Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.awt.Color;
- @ScriptManifest(authors = "Equinox_", keywords = { "Runecrafting", "Graahk",
- "Nature", "Karamja" }, name = "EquinoxGraahkCrafter", version = 1.4, description = "Nature Runecrafter with Graahks, pouches and more!")
- /**
- * @author Equinox_
- */
- public class EquinoxGraahkCrafter extends Script implements MessageListener,
- PaintListener, MouseMotionListener, MouseListener {
- // Variables
- final String baseURL = "http://equinox-scripts.web44.net/scripts/natcrafter";
- public final static int NATURE_RUNE_ID = 561;
- public final static int COSMIC_RUNE_ID = 564;
- public final static int ASTRAL_RUNE_ID = 9075;
- public static final int AIR_STAFF_ID = 1405;
- public final static int PURE_ESS_ID = 7936;
- public final static int NATURE_PORTAL_ID = 2460;
- public final static int NATURE_ALTER_ID = 2486;
- public final static int AIR_RUNE_ID = 556;
- public final static int SPIRIT_GRAAHK_POUCH_ID = 12810;
- public final static int OBELISK_OBJ_ID = 29938;
- public final static int KINSHIP_TELEPORT_ANIM = 13652;
- public final static int[] GRAAHK_TELEPORT_ANIM = { 8939, 8941 };
- public final static int NPC_CONTACT_ANIM = 4413;
- public final static int BANKER_ID = 9710;
- public final static int CRAFT_RUNE_ANIM = 791;
- public final static int DUELING_TELEPORT_ANIM = 9603;
- public final static String getChargeCountAsString(String s) {
- s = s.trim().toLowerCase();
- if (s != null && s.contains("(") && s.contains(")"))
- return s.substring(s.indexOf("(") + 1, s.indexOf(")"));
- return "0";
- }
- public final static int getChargeCount(String s) {
- try {
- return Integer.valueOf(getChargeCountAsString(s));
- } catch (Exception e) {
- return 0;
- }
- }
- public final static RSTile[][] DAEMONHEIM_MESH = {
- { new RSTile(3453, 3897), new RSTile(3447, 3897) },
- { new RSTile(3448, 3702), new RSTile(3451, 3702) },
- { new RSTile(3451, 3707), new RSTile(3448, 3707) },
- { new RSTile(3448, 3711), new RSTile(3451, 3711) },
- { new RSTile(3451, 3716), new RSTile(3448, 3716) },
- { new RSTile(3448, 3719), new RSTile(3449, 3719),
- new RSTile(3449, 3718) } };
- public final static RSTile[][] KARAMJA_MESH = {
- { new RSTile(2793, 3009), new RSTile(2793, 3009) },
- { new RSTile(2798, 3009), new RSTile(2796, 3008) },
- { new RSTile(2808, 3007), new RSTile(2809, 3013) },
- { new RSTile(2815, 3013), new RSTile(2815, 3007) },
- { new RSTile(2822, 3008), new RSTile(2823, 3013) },
- { new RSTile(2829, 3016), new RSTile(2834, 3009) },
- { new RSTile(2838, 3017), new RSTile(2831, 3021) },
- { new RSTile(2837, 3028), new RSTile(2842, 3025) },
- { new RSTile(2847, 3025), new RSTile(2847, 3030) },
- { new RSTile(2852, 3030), new RSTile(2852, 3025) },
- { new RSTile(2855, 3027), new RSTile(2856, 3031) },
- { new RSTile(2861, 3029), new RSTile(2859, 3024) },
- { new RSTile(2864, 3017), new RSTile(2864, 3023) },
- { new RSTile(2869, 3021), new RSTile(2866, 3021),
- new RSTile(2866, 3017), new RSTile(2869, 3017) } };
- public final static int POUCH_TRIES = 20;
- // Pouch IDs
- public static class Pouch {
- public final static int SMALL = 5509;
- public final static int MEDIUM = 5510;
- public final static int MEDIUM_DEGRADED = 5511;
- public final static int LARGE = 5512;
- public final static int LARGE_DEGRADED = 5513;
- public final static int GIANT = 5514;
- public final static int GIANT_DEGRADED = 5515;
- public final static int[] ALL = { SMALL, MEDIUM, MEDIUM_DEGRADED,
- LARGE, LARGE_DEGRADED, GIANT, GIANT_DEGRADED };
- public final static int[] ALL_REPAIRED = { SMALL, MEDIUM, LARGE, GIANT };
- public final static int[] ALL_DEGRADED = { MEDIUM_DEGRADED,
- LARGE_DEGRADED, GIANT_DEGRADED };
- public final static int[] ALL_DEGRADEABLE = { MEDIUM, MEDIUM_DEGRADED,
- LARGE, LARGE_DEGRADED, GIANT, GIANT_DEGRADED };
- }
- public static String serverMsg = "";
- public HashMap<PouchType, PouchState> pouches = new HashMap<PouchType, PouchState>();
- State currentState = State.LOST;
- public MeshPath karamjaMeshPath;
- public MeshPath daemonheimMeshPath;
- public PaintInterface Paint;
- public NPCContact npcContact = new NPCContact();
- public List<String> errorLog = new ArrayList<String>();
- public ModelMouse modelMouse;
- public int ringCharges = -1;
- public OptionsClass Options = new OptionsClass();
- public CameraControl camera;
- public static class OptionsClass {
- public Range mouseSpeed = new Range(4, 6);
- public pouchRepairOption pouchRepair = pouchRepairOption.ONE;
- public boolean hasAirStaff = true;
- public Range summoningRecharge = new Range(20, 25);
- public PouchCheckSystem pouchCheckSystem = PouchCheckSystem.SERVER_MSG;
- public Range walkingDistance = new Range(4, 6);
- public boolean save1ChargeRings = true;
- public TeleportSystem teleportSystem = TeleportSystem.DAEMONHEIM;
- /**
- * Teleport system
- *
- * @author Equinox
- */
- enum TeleportSystem {
- CASTLE_WARS, DAEMONHEIM
- }
- /**
- * When to repair pouches
- *
- * @author Equinox_
- *
- */
- public enum pouchRepairOption {
- ONE, TWO, ALL, NEVER
- }
- /**
- * How to determine a pouch's state
- *
- * @author Equinox_
- *
- */
- public enum PouchCheckSystem {
- SERVER_MSG, INVENTORY_STATUS
- }
- }
- /**
- * Possible states in the process of nature runecrafting
- *
- * @author Equinox_
- *
- */
- public enum State {
- TRAVERSE_DAEMONHEIM, BANK_WITHDRAW_GRAAHK, SUMMON_GRAAHK, DISMISS_WRONG_FAMILIAR, BANK_WITHDRAW_ESS, BANK_DEPOSIT_STUFF, FILL_POUCH, NPC_CONTACT, TELE_TO_KARAMJA, TRAVERSE_KARAMJA, CHARGE_SUMMONING, ENTER_PORTAL, CRAFT_ESSENCE, EMPTY_POUCH, TELE_TO_BANK, REMOVE_RING, EQUIP_RING, NEAR_BANK, LOST, WITHDRAW_RING
- }
- /**
- * Possible states of pouches, Empty or Full
- *
- * @author Equinox_
- *
- */
- public enum PouchState {
- Empty, Full
- }
- /**
- * Different pouches and their possible IDs
- *
- * @author Equinox_
- *
- */
- public enum PouchType {
- Small(Pouch.SMALL), Medium(Pouch.MEDIUM, Pouch.MEDIUM_DEGRADED), Large(
- Pouch.LARGE, Pouch.LARGE_DEGRADED), Giant(Pouch.GIANT,
- Pouch.GIANT_DEGRADED);
- public int[] ids;
- private PouchType(int... ids) {
- this.ids = ids;
- }
- }
- RSArea NATURE_ALTER = new RSArea(2390, 4835, 2410, 4850);
- RSArea KARAMJA_TRAVEL = new RSArea(2784, 2998, 2872, 3040);
- RSArea DAEMONHEIM_TRAVEL = new RSArea(3435, 3680, 3456, 3726);
- /**
- * Gets the current state
- *
- * @return State the current state
- * @throws Exception
- * so we can pipe errors back to the recorder
- */
- public State getState() throws Exception {
- if (objects.getNearest(OBELISK_OBJ_ID) != null
- && summoning.getSummoningPoints() <= Options.summoningRecharge
- .randomNormalDistribution())
- if (calc.tileOnMap(objects.getNearest(OBELISK_OBJ_ID).getLocation()))
- return State.CHARGE_SUMMONING;
- if (objects.getNearest(NATURE_PORTAL_ID) != null)
- if (calc.tileOnMap(objects.getNearest(NATURE_PORTAL_ID)
- .getLocation()))
- return State.ENTER_PORTAL;
- if (objects.getNearest(NATURE_ALTER_ID) != null)
- if (calc.tileOnMap(objects.getNearest(NATURE_ALTER_ID)
- .getLocation()))
- if ((inventory.isFull() || !pouches
- .containsValue(PouchState.Full))
- && inventory.contains(PURE_ESS_ID))
- return State.CRAFT_ESSENCE;
- else if (pouches.containsValue(PouchState.Full))
- return State.EMPTY_POUCH;
- else if (!pouches.containsValue(PouchState.Full)
- && !inventory.contains(PURE_ESS_ID))
- return State.TELE_TO_BANK;
- // Banking
- if (npcs.getNearest(Bank.BANKERS) != null
- || objects.getNearest(Bank.BANK_CHESTS) != null) {
- if ((npcs.getNearest(Bank.BANKERS) != null && npcs.getNearest(
- Bank.BANKERS).isOnScreen())
- || (objects.getNearest(Bank.BANK_CHESTS) != null && objects
- .getNearest(Bank.BANK_CHESTS).isOnScreen())) {
- // Familiar
- if (summoning.isFamiliarSummoned()) {
- if (summoning.getFamiliar() != null)
- if (!summoning.getFamiliar().getName().toLowerCase()
- .contains("graahk"))
- return State.DISMISS_WRONG_FAMILIAR;
- } else if (!inventory.contains(SPIRIT_GRAAHK_POUCH_ID))
- return State.BANK_WITHDRAW_GRAAHK;
- else
- return State.SUMMON_GRAAHK;
- // Pouch Repair
- if (shouldRepairPouches())
- return State.NPC_CONTACT;
- if (ringCharges <= (Options.save1ChargeRings ? 1 : 0)
- && Options.teleportSystem
- .equals(OptionsClass.TeleportSystem.CASTLE_WARS)) {
- if (Options.save1ChargeRings) {
- boolean hasChargedRing = false;
- for (int i = 2; i <= 8; i++)
- if (inventory.getItemID("Ring of Dueling (" + i
- + ")") >= 0) {
- hasChargedRing = true;
- break;
- }
- for (int i = 2; i <= 8; i++)
- if (inventory.getItemID("Ring of Dueling (" + i
- + ")") == -1
- && inventory
- .getItemID("Ring of Dueling (1)") >= 0
- && !hasChargedRing)
- return State.WITHDRAW_RING;
- else if (inventory.getItemID("Ring of Dueling ("
- + i + ")") >= 0
- && inventory
- .getItemID("Ring of Dueling (1)") == -1)
- return State.EQUIP_RING;
- if (inventory.getItemID("Ring of Dueling (1)") == -1)
- return State.REMOVE_RING;
- if (inventory.getItemID("Ring of Dueling (1)") >= 0)
- return State.BANK_DEPOSIT_STUFF;
- } else {
- boolean hasChargedRing = false;
- for (int i = 2; i <= 8; i++)
- if (inventory.getItemID("Ring of Dueling (" + i
- + ")") >= 0) {
- hasChargedRing = true;
- break;
- }
- for (int i = 2; i <= 8; i++)
- if (inventory.getItemID("Ring of Dueling (" + i
- + ")") == -1
- && !hasChargedRing)
- return State.WITHDRAW_RING;
- else if (inventory.getItemID("Ring of Dueling ("
- + i + ")") >= 0)
- return State.EQUIP_RING;
- }
- }
- if (inventory.getCount(Pouch.ALL)
- + inventory.getCount(PURE_ESS_ID) != inventory
- .getCount())
- return State.BANK_DEPOSIT_STUFF;
- if (inventory.contains(PURE_ESS_ID)
- && pouches.containsValue(PouchState.Empty))
- return State.FILL_POUCH;
- if (!inventory.isFull())
- return State.BANK_WITHDRAW_ESS;
- } else {
- return State.NEAR_BANK;
- }
- }
- if (KARAMJA_TRAVEL.contains(getMyPlayer().getLocation()))
- return State.TRAVERSE_KARAMJA;
- if (inventory.isFull() && inventory.contains(PURE_ESS_ID))
- return State.TELE_TO_KARAMJA;
- if (DAEMONHEIM_TRAVEL.contains(getMyPlayer().getLocation()))
- return State.TRAVERSE_DAEMONHEIM;
- return State.LOST;
- }
- /**
- * Internal use only. When the client receives a message this method is
- * invoked, saving the message for later use.
- */
- public void messageReceived(MessageEvent msg) {
- if (msg.getID() == MessageEvent.MESSAGE_ACTION
- || msg.getID() == MessageEvent.MESSAGE_SERVER) {
- serverMsg = msg.getMessage().toLowerCase();
- }
- }
- /**
- * Teleports to Karamja using the summoning bubble to interact with a
- * summoned graahk
- *
- * @throws Exception
- * to pipe the Exception back to the logger
- */
- public void teleportToKaramja() throws Exception {
- daemonheimMeshPath.clearPath();
- if (summoning.doAction("Interact")) {
- for (byte b = 0; b < 15; b++)
- if (interfaces.getComponent(228, 3) != null
- && interfaces.getComponent(228, 3).isValid())
- break;
- else
- sleep(100, 125);
- if (interfaces.getComponent(228, 3).doClick()) {
- sleep(1000, 1250);
- for (byte b = 0; b < 15
- && players.getMyPlayer().getAnimation() == GRAAHK_TELEPORT_ANIM[0]; b++)
- sleep(125, 175);
- return;
- }
- }
- }
- /**
- * Teleports to Daemonheim using an equipped ring of kinship
- *
- * @throws Exception
- * to pipe the Exception back to the logger
- */
- public void teleportToDaemonheim() throws Exception {
- if (getMyPlayer().getAnimation() != KINSHIP_TELEPORT_ANIM)
- for (byte b = 0; b < 5; b++)
- if (equipment.getItem(Equipment.RING) != null) {
- RSComponent comp = equipment.getItem(Equipment.RING)
- .getComponent();
- Point pt = comp.getCenter();
- pt.translate(random(-2, 3), random(-2, 3));
- mouse.click(pt, false);
- sleep(500, 750);
- if (menu.doAction("Teleport")) {
- for (byte b2 = 0; b2 < 25; b2++)
- if (getMyPlayer().getAnimation() != KINSHIP_TELEPORT_ANIM)
- sleep(100, 115);
- else {
- Paint.runsMade++;
- return;
- }
- }
- } else {
- log.severe("Somehow we are missing a ring :(");
- stopScript(true);
- }
- }
- /**
- * Teleports to Castlewars using an equipped ring of dueling
- *
- * @throws Exception
- * to pipe the Exception back to the logger
- */
- public void teleportToCastleWars() throws Exception {
- if (getMyPlayer().getAnimation() != DUELING_TELEPORT_ANIM)
- for (byte b = 0; b < 5; b++)
- if (equipment.getItem(Equipment.RING) != null) {
- RSComponent comp = equipment.getItem(Equipment.RING)
- .getComponent();
- Point pt = comp.getCenter();
- pt.translate(random(-2, 3), random(-2, 3));
- mouse.click(pt, false);
- sleep(500, 750);
- if (menu.doAction("Castle-wars")) {
- for (byte b2 = 0; b2 < 25; b2++)
- if (getMyPlayer().getAnimation() != DUELING_TELEPORT_ANIM)
- sleep(100, 115);
- else {
- Paint.runsMade++;
- return;
- }
- }
- } else {
- log.severe("Somehow we are missing a ring :(");
- stopScript(true);
- }
- }
- /**
- * Determines if pouches need repairing by using the method defined in the
- * Options class
- *
- * @return boolean should repair pouches
- */
- public boolean shouldRepairPouches() {
- int degradeable = inventory.getCount(Pouch.ALL_DEGRADEABLE);
- int degraded = inventory.getCount(Pouch.ALL_DEGRADED);
- switch (Options.pouchRepair) {
- case ONE:
- return degraded > 0;
- case TWO:
- return degraded > 1 || degradeable < 2;
- case ALL:
- return degradeable == degraded;
- case NEVER:
- return false;
- default:
- return degraded > 1 || degradeable < 2;
- }
- }
- /**
- * Tries to open the bank
- *
- * @return boolean did bank open
- */
- public boolean openBank() {
- if (npcs.getNearest(BANKER_ID) != null) {
- if (bank.isOpen())
- return true;
- bank.open();
- sleep(100, 250);
- }
- return false;
- }
- /**
- * Deposit all non necessary items.
- */
- public void deposit_non_necessities() {
- if (!openBank())
- return;
- if (inventory.getCount(Pouch.ALL) > 0)
- bank.depositAllExcept(Pouch.ALL);
- else
- bank.depositAll();
- }
- /**
- * Tries to open the bank if the bank is not open, then tries to withdraw
- * the item
- *
- * @param id
- * the item to withdraw
- * @param amount
- * the amount to withdraw, 0 for all
- * @return boolean successfully withdraw
- */
- public boolean withdrawItem(int id, int amount) {
- if (!openBank())
- return false;
- boolean returns = bank.withdraw(id, amount);
- sleep(500, 750);
- return returns;
- }
- /**
- * Withdraws pure essence
- *
- * @return boolean did withdraw item
- */
- public boolean withdrawEss() {
- return withdrawItem(PURE_ESS_ID, 0);
- }
- /**
- * Gets the count of items by the provided id(s) in both the bank and
- * inventory. Includes stack sizes
- *
- * @param id
- * item ids to search
- * @return int number of items in bank and inventory
- */
- public int getCountBankInv(int... id) {
- int count = 0;
- if (bank.isOpen())
- count += bank.getCount(id);
- count += inventory.getCount(true, id);
- return count;
- }
- /**
- * Gets the loaded area or the world
- *
- * @return RSArea the local area
- */
- public RSArea getLocalArea() {
- RSTile base = game.getMapBase();
- int plane = game.getPlane();
- int[][] flags = walking.getCollisionFlags(plane);
- return new RSArea(base, new RSTile(base.getX() + flags.length - 1,
- base.getY() + flags.length - 1), plane);
- }
- /**
- * Checks if the given tile is loaded
- *
- * @param t
- * the RSTile to check
- * @return boolean is loaded
- */
- public boolean isLocal(RSTile t) {
- RSArea local = getLocalArea();
- if (local != null)
- return local.contains(t);
- return false;
- }
- /**
- * Empties pouches using the method set in the Options class
- */
- public void emptyPouches() {
- for (PouchType pType : pouches.keySet()) {
- if (inventory.isFull())
- break;
- if (inventory.containsOneOf(pType.ids)) {
- if (pouches.get(pType).equals(PouchState.Full)) {
- RSItem item = inventory.getItem(pType.ids);
- if (item != null) {
- int invCount = inventory.getCount();
- if (item.doAction("Empty"))
- switch (Options.pouchCheckSystem) {
- case SERVER_MSG:
- for (int i = 0; i < POUCH_TRIES; i++) {
- if (serverMsg != null)
- if (serverMsg
- .contains("pouch has no ess")
- || serverMsg
- .contains("are no essences in your pouch")) {
- pouches.put(pType, PouchState.Empty);
- serverMsg = "";
- sleep(100, 150);
- break;
- }
- sleep(100, 150);
- }
- break;
- case INVENTORY_STATUS:
- for (int i = 1; i <= POUCH_TRIES; i++)
- if (inventory.getCount() == invCount
- && i != POUCH_TRIES)
- sleep(100, 150);
- else {
- if (!inventory.isFull())
- pouches.put(pType, PouchState.Empty);
- break;
- }
- break;
- }
- }
- }
- } else {
- pouches.remove(pType);
- }
- }
- }
- /**
- * Fills pouches using the method set in the Options class
- */
- public void fillPouches() {
- for (PouchType pType : pouches.keySet()) {
- if (!inventory.contains(PURE_ESS_ID))
- break;
- if (inventory.containsOneOf(pType.ids)) {
- if (pouches.get(pType).equals(PouchState.Empty)) {
- RSItem item = inventory.getItem(pType.ids);
- if (item != null) {
- int invCount = inventory.getCount();
- if (item.doAction("Fill"))
- switch (Options.pouchCheckSystem) {
- case SERVER_MSG:
- for (int i = 0; i < POUCH_TRIES; i++) {
- if (serverMsg != null)
- if (serverMsg.contains("pouch is ful")) {
- pouches.put(pType, PouchState.Full);
- serverMsg = "";
- break;
- }
- sleep(80, 120);
- }
- break;
- case INVENTORY_STATUS:
- for (int i = 1; i <= POUCH_TRIES; i++)
- if (inventory.getCount() == invCount
- && i != POUCH_TRIES)
- sleep(100, 150);
- else {
- if (inventory.contains(PURE_ESS_ID))
- pouches.put(pType, PouchState.Full);
- break;
- }
- break;
- }
- }
- }
- } else {
- pouches.remove(pType);
- }
- }
- }
- /**
- * Rechecks pouches with the inventory's current contents. If a pouch in the
- * list no longer exists it removes it, if there's a pouch in the inventory
- * not in the list it adds it as an empty pouch
- */
- public void updatePouches() {
- for (PouchType pouch : PouchType.values())
- if (inventory.containsOneOf(pouch.ids)) {
- if (!pouches.containsKey(pouch))
- pouches.put(pouch, PouchState.Empty);
- } else if (pouches.containsKey(pouch))
- pouches.remove(pouch);
- }
- public boolean onStart() {
- camera = new CameraControl(super.camera, calc, this);
- karamjaMeshPath = new MeshPath(walking, calc, players, KARAMJA_MESH,
- Options.walkingDistance);
- daemonheimMeshPath = new MeshPath(walking, calc, players,
- DAEMONHEIM_MESH, Options.walkingDistance);
- modelMouse = new ModelMouse(tiles, calc, mouse, menu,
- Options.mouseSpeed);
- // Set up the pouches:
- updatePouches();
- mouse.setSpeed(Options.mouseSpeed.randomLinearDistribution());
- RSItem wep = equipment.getItem(Equipment.WEAPON);
- if (wep != null)
- Options.hasAirStaff = (wep.getName().toLowerCase()
- .contains("staff") && wep.getName().toLowerCase()
- .contains("air"));
- RSItem ring = equipment.getItem(Equipment.RING);
- if (ring == null
- || ring.getName() == null
- || !ring.getName().toLowerCase().contains("ring")
- || !(ring.getName().toLowerCase().contains("kinship") || ring
- .getName().toLowerCase().contains("dueling"))) {
- log.severe("You must be weilding a ring of kinship or a ring of dueling");
- return false;
- }
- Options.teleportSystem = OptionsClass.TeleportSystem.DAEMONHEIM;
- if (ring.getName().toLowerCase().contains("dueling")
- && !ring.getName().toLowerCase().contains("(")) {
- Options.teleportSystem = OptionsClass.TeleportSystem.CASTLE_WARS;
- log.severe("Your ring of dueling must be charged!");
- return false;
- }
- RSItem tiara = equipment.getItem(Equipment.HELMET);
- if (tiara == null || !tiara.getName().toLowerCase().contains("nature")) {
- log.severe("You must have a Nature Tiara equipped!");
- return false;
- }
- Paint = new PaintInterface(this, log, Skills.RUNECRAFTING);
- new DataLoader(this);
- // optimal alt
- camera.setPitch(random(0, 10));
- log.info("Script initiation successful!");
- log.info("--Setup--");
- log.info("Air staff: " + (Options.hasAirStaff ? "Yes" : "No"));
- log.info("Walking range: " + Options.walkingDistance.toString());
- log.info("Summoning recharge: " + Options.summoningRecharge.toString());
- log.info("Pouch method: "
- + PaintFormatter.properCaseAll(Options.pouchCheckSystem.name()
- .replaceAll("_", " ")));
- log.info("Pouch repair system: "
- + PaintFormatter.properCaseAll(Options.pouchRepair.name()
- .replaceAll("_", " ")));
- log.info("Teleport System: "
- + PaintFormatter.properCaseAll(Options.teleportSystem.name()
- .replaceAll("_", " ")));
- if (Options.teleportSystem
- .equals(OptionsClass.TeleportSystem.CASTLE_WARS))
- log.info("Save 1 Charge Rings: "
- + (Options.save1ChargeRings ? "Yes" : "No"));
- return true;
- }
- public int loop() {
- mouse.setSpeed(Options.mouseSpeed.randomLinearDistribution());
- if (!camera.isRunning())
- camera.start();
- try {
- currentState = getState();
- switch (currentState) {
- case NEAR_BANK:
- RSNPC banker = npcs.getNearest(Bank.BANKERS);
- RSObject chest = objects.getNearest(Bank.BANK_CHESTS);
- if (banker != null) {
- if (!banker.isOnScreen()) {
- RSTile loc = banker.getLocation();
- if (calc.tileOnMap(loc)) {
- walking.walkTileMM(loc);
- for (byte b = 0; b < 22; b++)
- if (banker.isOnScreen()) {
- sleep(500);
- break;
- } else
- sleep(100, 115);
- }
- }
- } else if (chest != null) {
- if (!chest.isOnScreen()) {
- RSTile loc = chest.getLocation();
- if (calc.tileOnMap(loc)) {
- walking.walkTileMM(loc);
- for (byte b = 0; b < 22; b++)
- if (chest.isOnScreen()) {
- sleep(500);
- break;
- } else
- sleep(100, 115);
- }
- }
- }
- break;
- case BANK_DEPOSIT_STUFF:
- this.deposit_non_necessities();
- break;
- case BANK_WITHDRAW_ESS:
- this.withdrawEss();
- break;
- case BANK_WITHDRAW_GRAAHK:
- if (openBank())
- for (byte b = 0; b < 5 && inventory.contains(PURE_ESS_ID); b++) {
- bank.deposit(PURE_ESS_ID, 1);
- sleep(450, 750);
- }
- withdrawItem(SPIRIT_GRAAHK_POUCH_ID, 1);
- break;
- case SUMMON_GRAAHK:
- RSItem p = inventory.getItem(SPIRIT_GRAAHK_POUCH_ID);
- if (p != null) {
- for (byte b = 0; b < 10 && bank.isOpen(); b++) {
- bank.close();
- sleep(500, 750);
- }
- if (summoning.getSummoningPoints() <= 0) {
- log.severe("Out of summoning points :'(");
- stopScript(true);
- } else if (!bank.isOpen())
- p.doAction("Summon");
- }
- break;
- case CHARGE_SUMMONING:
- RSObject obby = objects.getNearest(OBELISK_OBJ_ID);
- if (calc.tileOnMap(obby.getLocation())) {
- if (calc.distanceTo(obby) > 5)
- walking.walkTileMM(obby.getLocation());
- camera.turnTo(obby);
- sleep(125, 175);
- modelMouse.doClick(obby);
- sleep(250, 500);
- }
- break;
- case CRAFT_ESSENCE:
- RSObject alter = objects.getNearest(NATURE_ALTER_ID);
- if (!alter.isOnScreen() && !getMyPlayer().isMoving())
- walking.walkTileMM(alter.getArea().getNearestTile(
- getMyPlayer().getLocation()));
- int invBefore = inventory.getCount(PURE_ESS_ID);
- int natsBefore = inventory.getCount(true, NATURE_RUNE_ID);
- if (!alter.isOnScreen())
- camera.turnTo(alter);
- modelMouse.doClick(alter);
- for (byte b = 0; b < 25
- && (getMyPlayer().getAnimation() == CRAFT_RUNE_ANIM || getMyPlayer()
- .isMoving()); b++)
- sleep(100, 125);
- if ((inventory.getCount(PURE_ESS_ID) != invBefore && natsBefore != inventory
- .getCount(true, NATURE_RUNE_ID))) {
- Paint.essUsed += invBefore
- - inventory.getCount(PURE_ESS_ID);
- Paint.runesMade += inventory.getCount(true, NATURE_RUNE_ID)
- - natsBefore;
- }
- break;
- case DISMISS_WRONG_FAMILIAR:
- this.summoning.doDismiss();
- sleep(500, 600);
- break;
- case EMPTY_POUCH:
- emptyPouches();
- break;
- case ENTER_PORTAL:
- RSObject obj = objects.getNearest(NATURE_PORTAL_ID);
- if (obj != null) {
- if (!obj.isOnScreen()) {
- walking.walkTileMM(obj.getArea().getNearestTile(
- getMyPlayer().getLocation()));
- camera.turnTo(obj);
- }
- sleep(750);
- if (obj.isOnScreen()) {
- modelMouse.doClick(obj);
- for (byte b = 0; b < 10
- && objects.getNearest(NATURE_ALTER_ID) == null; b++)
- sleep(80, 120);
- karamjaMeshPath.clearPath();
- }
- }
- break;
- case FILL_POUCH:
- fillPouches();
- break;
- case NPC_CONTACT:
- npcContact.main();
- break;
- case TELE_TO_BANK:
- if (Options.teleportSystem
- .equals(OptionsClass.TeleportSystem.DAEMONHEIM))
- this.teleportToDaemonheim();
- else
- this.teleportToCastleWars();
- break;
- case TELE_TO_KARAMJA:
- this.teleportToKaramja();
- break;
- case TRAVERSE_DAEMONHEIM:
- if (!daemonheimMeshPath.hasPath())
- daemonheimMeshPath.findPath(MeshPath.MeshPathType.FULL);
- daemonheimMeshPath.traverse();
- break;
- case TRAVERSE_KARAMJA:
- if (!karamjaMeshPath.hasPath())
- karamjaMeshPath
- .findPath(MeshPath.MeshPathType.WEIGHT_CENTER);
- karamjaMeshPath.traverse();
- break;
- case REMOVE_RING:
- if (bank.isOpen()
- || (interfaces.get(Bank.INTERFACE_EQUIPMENT) != null && interfaces
- .get(Bank.INTERFACE_EQUIPMENT).isValid())) {
- /*
- * if (bank.getEquipmentItems().length == 0)
- * bank.openEquipment(); for (byte b = 0; b < 25 &&
- * bank.getEquipmentItems().length == 0; b++) sleep(100,
- * 125); RSItem ring =
- * bank.getEquipmentItem(bank.getEquipmentItemID("Ring"));
- * if (ring!=null) ring.doAction("Remove");
- */
- bank.close();
- sleep(1000, 1100);
- }
- if (equipment.getItem(Equipment.RING) != null)
- equipment.getItem(Equipment.RING).doAction("Remove");
- break;
- case WITHDRAW_RING:
- openBank();
- boolean withdrawn = false;
- for (byte b = 2; b <= 8; b++)
- if (bank.getItemID("Ring of Dueling (" + b + ")") >= 0)
- if (withdrawItem(
- bank.getItemID("Ring of Dueling (" + b + ")"),
- 1)) {
- withdrawn = true;
- break;
- }
- if (!withdrawn) {
- log.severe("Out of rings!");
- stopScript(false);
- }
- break;
- case EQUIP_RING:
- for (byte b = 2; b <= 8; b++) {
- RSItem inv = inventory.getItem(inventory
- .getItemID("Ring of Dueling( " + b + ")"));
- if (inv != null)
- if (inv.doAction("Equip"))
- break;
- }
- break;
- }
- } catch (Exception e) {
- logError(e);
- }
- if (walking.getEnergy() > 50 && !walking.isRunEnabled())
- walking.setRun(true);
- return random(100, 125);
- }
- public void onFinish() {
- env.saveScreenshot(true);
- if (Paint != null)
- saveProggie();
- }
- /**
- * Saves a progress report to the Screenshots directory
- */
- public void saveProggie() {
- Paint.paintMenu.saveProggie(
- GlobalConfiguration.Paths.getScreenshotsDirectory(),
- getClass().getAnnotation(ScriptManifest.class).name()
- + "_"
- + PaintFormatter.getFormattedTime(
- System.currentTimeMillis() - Paint.startTime,
- "-", true), log);
- }
- /**
- * Logs an exception to the Logger and to the error cache
- *
- * @param e
- * as the Exception to log
- */
- public void logError(Exception e) {
- String s = e.getMessage();
- log.severe(s);
- for (StackTraceElement ele : e.getStackTrace()) {
- s += "\n" + ele.toString();
- log.severe(ele.toString());
- }
- errorLog.add(s);
- }
- public void onRepaint(Graphics g1) {
- Graphics2D g = (Graphics2D) g1;
- try {
- // MeshPaths
- karamjaMeshPath.paintAll(g);
- daemonheimMeshPath.paintAll(g);
- // Mouse Crosshair
- paintPouches(g);
- // main paint:
- if (Paint != null)
- Paint.render(g);
- } catch (NullPointerException e) {
- logError(e);
- }
- }
- /**
- * Paints the pouches loaded into the list using red for empty and green for
- * full. Only paints if inventory is visible.
- *
- * @param g
- * as Graphics
- */
- public void paintPouches(Graphics g) {
- // Loop through pouches
- for (PouchType pouch : pouches.keySet()) {
- if (game.getCurrentTab() == Game.TAB_INVENTORY) {
- RSItem item = inventory.getItem(pouch.ids);
- if (item != null) {
- if (pouches.get(pouch).equals(PouchState.Empty))
- g.setColor(new Color(1f, 0f, 0f, 0.5f));
- else
- g.setColor(new Color(0f, 1f, 0f, 0.5f));
- RSComponent c = item.getComponent();
- g.fillRect(c.getAbsoluteX(), c.getAbsoluteY(),
- c.getWidth(), c.getHeight());
- // Decay:
- for (int id : Pouch.ALL_DEGRADED)
- if (item.getID() == id) {
- g.setColor(Color.WHITE);
- g.setFont(Paint.style.FONT.deriveFont(4));
- g.drawString("Degraded", c.getAbsoluteX(),
- c.getAbsoluteY() + c.getHeight());
- break;
- }
- }
- }
- }
- }
- // Mouse Motion
- public void mouseDragged(MouseEvent arg0) {
- Paint.mouseLoc = arg0.getPoint();
- }
- public void mouseMoved(MouseEvent arg0) {
- Paint.mouseLoc = arg0.getPoint();
- }
- public void mouseClicked(MouseEvent arg0) {
- Paint.fireMouseEvent(arg0);
- }
- public void mouseEntered(MouseEvent arg0) {
- }
- public void mouseExited(MouseEvent arg0) {
- }
- public void mousePressed(MouseEvent arg0) {
- }
- public void mouseReleased(MouseEvent arg0) {
- }
- /**
- * A class used to represent the paint interface for this script
- *
- * @author Equinox_
- *
- */
- public class PaintInterface {
- // Constant
- public final int[] SKILL_INTERFACES = { Skills.INTERFACE_ATTACK,
- Skills.INTERFACE_DEFENSE, Skills.INTERFACE_STRENGTH,
- Skills.INTERFACE_CONSTITUTION, Skills.INTERFACE_RANGE,
- Skills.INTERFACE_PRAYER, Skills.INTERFACE_MAGIC,
- Skills.INTERFACE_COOKING, Skills.INTERFACE_WOODCUTTING,
- Skills.INTERFACE_FLETCHING, Skills.INTERFACE_FISHING,
- Skills.INTERFACE_FIREMAKING, Skills.INTERFACE_CRAFTING,
- Skills.INTERFACE_SMITHING, Skills.INTERFACE_MINING,
- Skills.INTERFACE_HERBLORE, Skills.INTERFACE_AGILITY,
- Skills.INTERFACE_THIEVING, Skills.INTERFACE_SLAYER,
- Skills.INTERFACE_FARMING, Skills.INTERFACE_RUNECRAFTING,
- Skills.INTERFACE_HUNTER, Skills.INTERFACE_CONSTRUCTION,
- Skills.INTERFACE_SUMMONING, Skills.INTERFACE_DUNGEONEERING };
- // Mouse
- public DrawMouse drawMouse = new DrawMouse();
- // Start data
- public int[] startExp = {};
- public long startTime = 0;
- public int[] startLevel = {};
- // Goal data
- public int[] goalExp;
- public int[] goalLevel;
- // Usage data
- public int runsMade = 0;
- public int runesMade = 0;
- public int essUsed = 0;
- public int graahksUsed = 0;
- // Prices
- public int essPrice;
- public FontRenderContext frc = new FontRenderContext(
- new AffineTransform(), false, false);
- public PaintStyle style = new PaintStyle();
- public Point mouseLoc = new Point(0, 0);
- final EquinoxGraahkCrafter crafter;
- final Logger log;
- int[] SkillIDs = { -1 };
- public PaintMenu paintMenu;
- public int graahkPrice;
- public int natPrice;
- /**
- * Constructs a PaintInterface using the provided parent and logger
- * object
- *
- * @param crafter
- * the parent crafter
- * @param log
- * the Logger object
- */
- public PaintInterface(EquinoxGraahkCrafter crafter, Logger log) {
- this(crafter, log, -1);
- }
- public PaintInterface(EquinoxGraahkCrafter crafter, Logger log,
- int... SkillIDs) {
- this.crafter = crafter;
- this.log = log;
- this.SkillIDs = SkillIDs;
- startTime = System.currentTimeMillis();
- startExp = new int[Skills.SKILL_NAMES.length];
- startLevel = new int[Skills.SKILL_NAMES.length];
- goalExp = new int[Skills.SKILL_NAMES.length];
- goalLevel = new int[Skills.SKILL_NAMES.length];
- for (int skill = 0; skill < Skills.SKILL_NAMES.length; skill++) {
- startExp[skill] = -1;
- startLevel[skill] = -1;
- goalExp[skill] = -1;
- goalLevel[skill] = -1;
- }
- init(SkillIDs);
- }
- public void init(int... skillsToAdd) {
- paintMenu = new PaintMenu(style, Anchor.DOWN_RIGHT);
- paintMenu.setFlowType(FlowType.HORIZONTAL);
- paintMenu.addMouseListener(new MenuMouseListener() {
- public void MouseAction(MouseEvent e) {
- if (e.getID() == MouseEvent.MOUSE_CLICKED)
- paintMenu.toggleShowAll();
- }
- });
- for (int SkillID : skillsToAdd) {
- if (SkillID >= 0 && SkillID < Skills.SKILL_NAMES.length) {
- startExp[SkillID] = skills.getCurrentExp(SkillID);
- log.info("Current "
- + PaintFormatter
- .properCaseAll(Skills.SKILL_NAMES[SkillID])
- + " EXP: " + startExp[SkillID]);
- startLevel[SkillID] = skills.getRealLevel(SkillID);
- if (startLevel[SkillID] > (SkillID == Skills.DUNGEONEERING ? 120
- : 99))
- startLevel[SkillID] = SkillID == Skills.DUNGEONEERING ? 120
- : 99;
- log.info("Current "
- + PaintFormatter
- .properCaseAll(Skills.SKILL_NAMES[SkillID])
- + " Level: " + startLevel[SkillID]);
- setUpGoal(SkillID);
- paintMenu.add(new PaintMenuSkillProgressBar(SkillID,
- skills, startExp[SkillID], paintMenu));
- if (goalExp[SkillID] > skills.getCurrentExp(SkillID))
- paintMenu.add(new PaintMenuSkillProgressBar(paintMenu,
- SkillID, goalExp[SkillID], skills,
- startExp[SkillID]));
- }
- }
- PaintMenuButton natures = new PaintMenuButton(paintMenu, "natures",
- "natrune", new GetPopup() {
- public PaintMenuPopUp getPopUp() {
- long millis = System.currentTimeMillis()
- - crafter.Paint.startTime;
- if (millis <= 0)
- millis = 1;
- String runesPerEssence = "Runes per Ess: "
- + ((essUsed > 0) ? (new DecimalFormat(
- "#.##").format(((double) runesMade)
- / ((double) essUsed)))
- : "No essence used");
- long natsPerHour = ((runesMade * 3600000l) / millis);
- long profit = (runesMade * natPrice)
- - (essUsed * essPrice)
- - (graahksUsed - graahkPrice);
- String[] lines = new String[9];
- lines[0] = "Essence Used: "
- + PaintFormatter.getFormattedMoney(essUsed);
- lines[1] = "Graahks Used: "
- + PaintFormatter
- .getFormattedMoney(graahksUsed);
- lines[2] = "Runes Crafted: "
- + PaintFormatter
- .getFormattedMoney(runesMade);
- lines[3] = "Runes/Hour: "
- + PaintFormatter
- .getFormattedMoney(natsPerHour);
- lines[4] = "Profit: "
- + PaintFormatter.getFormattedMoney(profit)
- + " gp";
- lines[5] = "Profit per hour: "
- + PaintFormatter
- .getFormattedMoney((profit * 3600000)
- / millis) + " gp";
- lines[6] = runesPerEssence;
- lines[7] = "Runs made: " + runsMade;
- lines[8] = "Runes per run: "
- + (runsMade > 0 ? (int) (runesMade / runsMade)
- : "No runs made");
- return new PaintMenuPopUp(lines, "runes");
- }
- public String getName() {
- return "runes";
- }
- });
- paintMenu.add(natures);
- PaintMenuButton home = new PaintMenuButton(paintMenu, "home",
- "homeicon", new GetPopup() {
- public PaintMenuPopUp getPopUp() {
- long millis = System.currentTimeMillis()
- - crafter.Paint.startTime;
- if (millis <= 0)
- millis = 1;
- String[] lines = new String[5];
- lines[0] = crafter.getClass()
- .getAnnotation(ScriptManifest.class).name();
- lines[1] = "By: "
- + PaintFormatter
- .formatList(crafter
- .getClass()
- .getAnnotation(
- ScriptManifest.class)
- .authors());
- lines[2] = "Version "
- + crafter
- .getClass()
- .getAnnotation(ScriptManifest.class)
- .version();
- lines[3] = "Runtime: "
- + PaintFormatter.getFormattedTime(millis)
- + "\n";
- lines[4] = PaintFormatter
- .properCaseAll(crafter.currentState.name()
- .replace("_", " "));
- if (crafter.currentState.equals(State.NPC_CONTACT))
- lines[4] += " - "
- + PaintFormatter
- .properCaseAll(npcContact.currentState
- .name().replace("_",
- " "));
- return new PaintMenuPopUp(lines, "home");
- }
- public String getName() {
- return "home";
- }
- });
- paintMenu.add(home);
- PaintMenuButton tools = new PaintMenuButton(paintMenu, "tools",
- "toolsicon", new GetPopup() {
- public PaintMenuPopUp getPopUp() {
- String[] lines = new String[2];
- lines[0] = "Save proggie";
- lines[1] = "Reload data";
- PaintMenuPopUp popUp = new PaintMenuPopUp(lines,
- "tools");
- popUp.addLineListener(new LineListener() {
- public void fireEvent(MouseEvent e, String line) {
- line = line.toLowerCase().trim();
- if (e.getID() == MouseEvent.MOUSE_CLICKED) {
- if (line.contains("save proggie"))
- crafter.saveProggie();
- else if (line.contains("reload data"))
- new DataLoader(crafter);
- else if (line.contains("set flow")) {
- if (line.contains("horizontal"))
- paintMenu
- .setFlowType(FlowType.HORIZONTAL);
- else
- paintMenu
- .setFlowType(FlowType.VERTICAL);
- } else if (line
- .contains("set vertical")) {
- if (line.contains("top")) {
- if (paintMenu.anchor.name()
- .contains("LEFT"))
- paintMenu.anchor = Anchor.UP_LEFT;
- else
- paintMenu.anchor = Anchor.UP_RIGHT;
- } else {
- if (paintMenu.anchor.name()
- .contains("LEFT"))
- paintMenu.anchor = Anchor.DOWN_LEFT;
- else
- paintMenu.anchor = Anchor.DOWN_RIGHT;
- }
- paintMenu.compile();
- } else if (line
- .contains("set horizontal")) {
- if (line.contains("left")) {
- if (paintMenu.anchor.name()
- .contains("UP"))
- paintMenu.anchor = Anchor.UP_LEFT;
- else
- paintMenu.anchor = Anchor.DOWN_LEFT;
- } else {
- if (paintMenu.anchor.name()
- .contains("UP"))
- paintMenu.anchor = Anchor.UP_RIGHT;
- else
- paintMenu.anchor = Anchor.DOWN_RIGHT;
- }
- }
- if (line.contains("set"))
- paintMenu.compile();
- }
- }
- public boolean hasAction(String line) {
- line = line.toLowerCase().trim();
- String[] lines = new String[2];
- lines[0] = "Save proggie";
- lines[1] = "Reload data";
- for (String s : lines)
- if (s.equalsIgnoreCase(line))
- return true;
- return false;
- }
- });
- return popUp;
- }
- public String getName() {
- return "tools";
- }
- });
- paintMenu.add(tools);
- paintMenu.compile();
- }
- /**
- * Gets the current Goal for the setSkill, or sets all goal variables to
- * -1 if there is no goal
- */
- public void setUpGoal(int skillid) {
- try {
- for (byte b = 0; b < 10; b++)
- if (game.getCurrentTab() != Game.TAB_STATS) {
- game.openTab(Game.TAB_STATS);
- sleep(1000);
- } else
- break;
- RSInterface stats = interfaces.get(320);
- if (stats != null && stats.isValid()) {
- RSComponent skill = stats
- .getComponent(SKILL_INTERFACES[skillid]);
- if (skill != null && skill.isValid()
- && skill.getArea() != null) {
- mouse.move((int) skill.getArea().getCenterX(),
- (int) skill.getArea().getCenterY());
- sleep(500, 750);
- // Now we see what the popup is doing
- RSComponent pop = stats.getComponent(202);
- if (pop != null && pop.isValid()) {
- RSComponent def = pop.getComponent(5);
- if (def != null && def.isValid()) {
- if (def.getText().trim()
- .equalsIgnoreCase("Target XP:")) {
- RSComponent goalXP = pop.getComponent(6);
- if (goalXP != null && goalXP.isValid()) {
- goalExp[skillid] = Integer
- .valueOf(goalXP.getText()
- .replace(",", "")
- .trim());
- goalLevel[skillid] = -1;
- }
- } else {
- // Proceed
- RSComponent currExp = pop.getComponent(4);
- RSComponent goalRemainder = pop
- .getComponent(12);
- RSComponent goalLvl = pop.getComponent(10);
- if (currExp != null && currExp.isValid()
- && goalRemainder != null
- && goalRemainder.isValid()
- && goalLvl != null
- && goalLvl.isValid()) {
- goalExp[skillid] = Integer
- .valueOf(currExp.getText()
- .replace(",", "")
- .trim())
- + Integer.valueOf(goalRemainder
- .getText()
- .replace(",", "")
- .trim());
- goalLevel[skillid] = Integer
- .valueOf(goalLvl.getText()
- .replace(",", "")
- .trim());
- }
- }
- log.info("Target level for "
- + Skills.SKILL_NAMES[skillid]
- + ": "
- + (goalLevel[skillid] > 0 ? goalLevel[skillid]
- : "None"));
- log.info("Target exp for "
- + Skills.SKILL_NAMES[skillid]
- + ": "
- + (goalExp[skillid] > 0 ? goalExp[skillid]
- : "None"));
- return;
- }
- }
- }
- }
- } catch (Exception e) {
- }
- goalExp[skillid] = -1;
- goalLevel[skillid] = -1;
- }
- /**
- * Renders the current paint to the given graphics context.
- *
- * @param g
- * as the Graphics2D object to render to
- */
- public void render(Graphics2D g) {
- paintMenu.render(g, mouseLoc);
- drawMouse.onRepaint(g);
- }
- /**
- * Fires a MouseEvent in the paintMenu
- *
- * @param e
- * MouseEvent
- */
- public void fireMouseEvent(MouseEvent e) {
- if (paintMenu.getBoundsFull().contains(e.getPoint()))
- paintMenu.fireMouseEvent(e);
- }
- public class DrawMouse {
- private MouseTrailing mouseTrailing = new MouseTrailing();
- private ArrayList<MouseInfo> clicks = new ArrayList<MouseInfo>();
- private long clickLifeTime = 1500;
- public void onRepaint(final Graphics render) {
- if (mouse != null) {
- Point Location = mouse.getLocation();
- if (mouse.isPressed()) {
- boolean found = false;
- for (MouseInfo click : clicks)
- if (click.getLocation().equals(Location)) {
- click.updateTime(System.currentTimeMillis());
- found = true;
- break;
- }
- if (!found)
- clicks.add(new MouseInfo(
- System.currentTimeMillis(), Location));
- }
- mouseTrailing.draw((Graphics2D) render, Color.WHITE);
- render.setColor(Color.GREEN);
- render.drawLine(Location.x - 5, Location.y, Location.x + 5,
- Location.y);
- render.drawLine(Location.x, Location.y - 5, Location.x,
- Location.y + 5);
- for (MouseInfo click : clicks) {
- float i = ((float) (click.getTime() + clickLifeTime - System
- .currentTimeMillis()) / (float) clickLifeTime) + 0.25f;
- if (i > 0) {
- render.setColor(new Color(1f, 0f, 0f, i > 1 ? 1f
- : i));
- render.drawLine(click.getLocation().x - 5,
- click.getLocation().y,
- click.getLocation().x + 5,
- click.getLocation().y);
- render.drawLine(click.getLocation().x,
- click.getLocation().y - 5,
- click.getLocation().x,
- click.getLocation().y + 5);
- } else if (System.currentTimeMillis() - click.getTime() >= clickLifeTime)
- clicks.remove(click);
- }
- }
- }
- public class MouseTrailing {
- private int LifeTime = 1500;
- private ArrayList<MouseInfo> locations = new ArrayList<MouseInfo>();
- private void addLocation() {
- Point m = mouse.getLocation();
- MouseInfo mInfo = new MouseInfo(System.currentTimeMillis(),
- m);
- if (!locations.contains(mInfo))
- locations.add(mInfo);
- }
- public void draw(Graphics2D g, Color c) {
- addLocation();
- for (int t = 1; t < locations.size(); t++) {
- MouseInfo p1 = locations.get(t);
- MouseInfo p2 = locations.get(t - 1);
- float i = (float) (p1.getTime() + LifeTime - System
- .currentTimeMillis()) / (float) LifeTime;
- i = i > 1 ? 1f : i;
- if (i > 0) {
- g.setColor(new Color(c.getRed() / 255f, c
- .getGreen() / 255f, c.getBlue() / 255f, (c
- .getAlpha() / 255f) * i));
- g.drawLine(p1.getLocation().x, p1.getLocation().y,
- p2.getLocation().x, p2.getLocation().y);
- }
- }
- if (locations.size() > 0
- && System.currentTimeMillis() > locations.get(0)
- .getTime() + LifeTime)
- locations.remove(0);
- }
- }
- private class MouseInfo {
- private long time;
- private Point location;
- public MouseInfo(long time, Point loc) {
- this.time = time;
- this.location = loc;
- }
- public long getTime() {
- return time;
- }
- public Point getLocation() {
- return location;
- }
- public void updateTime(long newTime) {
- this.time = newTime;
- }
- public boolean equals(Object m) {
- if (!(m instanceof MouseInfo))
- return false;
- MouseInfo cast = (MouseInfo) m;
- return (cast.getLocation().equals(location));
- }
- }
- }
- }
- /**
- * The different states the NPC contact process can be in
- *
- * @author Equinox_
- *
- */
- enum npcContactState {
- CAST, SCROLL, SELECT, WAIT, CONTINUE, MENU, WITHDRAW_ASTRAL, WITHDRAW_COSMIC, WITHDRAW_AIR, OUT_OF_RUNES
- }
- /**
- * A class to contact people using NPC contact
- *
- * @author Equinox_
- *
- */
- class NPCContact {
- public npcContactState currentState = npcContactState.WAIT;
- private final int MAIN_FRAME = 88;
- private final int SCROLL_BAR = 20;
- private final int SCROLL_BAR_DOWN = 0;
- private final int VISIBLE_NPCS_CONTAINER = 21;
- private final int NPCS_CONTAINER = 22;
- private final int NPC_CONTACT_ANIM = 4413;
- private final int NPC_TO_SELECT = 14;
- private final String[] MENU_ITEM = { "repair", "pouch" };
- /**
- * Gets the current npcContactState
- *
- * @return the current npcContactState
- */
- private npcContactState getState() {
- if (interfaces.get(MAIN_FRAME).isValid()) {
- if (interfaces.get(MAIN_FRAME).getComponent(NPCS_CONTAINER)
- .isValid()) {
- Point npcPoint = interfaces.get(MAIN_FRAME)
- .getComponent(NPCS_CONTAINER)
- .getComponent(NPC_TO_SELECT).getCenter();
- Rectangle visible = interfaces.get(MAIN_FRAME)
- .getComponent(VISIBLE_NPCS_CONTAINER).getArea();
- if (!visible.contains(npcPoint))
- return npcContactState.SCROLL;
- else
- return npcContactState.SELECT;
- }
- }
- if (interfaces.canContinue())
- return npcContactState.CONTINUE;
- if (getComponent(MENU_ITEM) != null)
- return npcContactState.MENU;
- if (!interfaces.canContinue()
- && getMyPlayer().getAnimation() != NPC_CONTACT_ANIM
- && getComponent(MENU_ITEM) == null
- && getComponent("lease wai") == null) {
- if (!inventory.contains(ASTRAL_RUNE_ID))
- return npcContactState.WITHDRAW_ASTRAL;
- if (!inventory.contains(COSMIC_RUNE_ID))
- return npcContactState.WITHDRAW_COSMIC;
- if (inventory.getCount(true, AIR_RUNE_ID) < 2
- && !Options.hasAirStaff)
- return npcContactState.WITHDRAW_AIR;
- return npcContactState.CAST;
- }
- return npcContactState.WAIT;
- }
- /**
- * Finds a RSComponent with the specified string
- *
- * @param s
- * The String to search
- * @return RSComponent with string, otherwise null
- */
- private RSComponent getComponent(String... s) {
- RSInterface[] valid = interfaces.getAll();
- for (RSInterface iface : valid) {
- if (iface.getIndex() != 137) {
- int len = iface.getChildCount();
- for (int i = 0; i < len; i++) {
- RSComponent child = iface.getComponent(i);
- boolean b = (child.isValid()
- && child.getAbsoluteX() > 10 && child
- .getAbsoluteY() > 300);
- for (String sub : s)
- if (!child.getText().toLowerCase()
- .contains(sub.toLowerCase()))
- b = false;
- if (b)
- return child;
- }
- }
- }
- return null;
- }
- /**
- * Checks if the inventory or bank contains the specified item
- *
- * @param id
- * the item id
- * @return <tt>true</tt> if the bank or inventory contains the item,
- * otherwise, <tt>false</tt>
- */
- boolean invBank(int id) {
- return bank.getCount(id) > 0 || inventory.containsOneOf(id);
- }
- /**
- * Gets the count of a specified item in the inventory and bank
- *
- * @param int itemId
- * @return the item count
- */
- int invBankCount(int id) {
- return bank.getCount(id) + inventory.getCount(true, id);
- }
- /**
- * The main loop. Call this to do the next action for the contact
- * process.
- */
- public void main() {
- switch (currentState = getState()) {
- case WITHDRAW_ASTRAL:
- withdrawItem(ASTRAL_RUNE_ID, 1);
- if (!invBank(ASTRAL_RUNE_ID))
- removePouches();
- sleep(500, 650);
- break;
- case WITHDRAW_COSMIC:
- withdrawItem(COSMIC_RUNE_ID, 1);
- if (!invBank(COSMIC_RUNE_ID))
- removePouches();
- sleep(500, 650);
- break;
- case WITHDRAW_AIR:
- if (!inventory.contains(AIR_RUNE_ID))
- withdrawItem(AIR_RUNE_ID, 1);
- withdrawItem(AIR_RUNE_ID, 1);
- if (invBankCount(AIR_RUNE_ID) < 2)
- removePouches();
- sleep(500, 650);
- break;
- case CAST:
- for (byte b = 0; b < 10 && bank.isOpen(); b++) {
- bank.close();
- sleep(500, 750);
- }
- if (!bank.isOpen() && game.getCurrentTab() != Game.TAB_MAGIC)
- game.openTab(Game.TAB_MAGIC);
- sleep(500, 1250);
- magic.castSpell(Magic.SPELL_NPC_CONTACT);
- sleep(750, 1250);
- break;
- case SCROLL:
- // Scroll
- RSComponent bar = interfaces.get(MAIN_FRAME)
- .getComponent(SCROLL_BAR).getComponent(SCROLL_BAR_DOWN);
- Point p = bar.getCenter();
- p.y = bar.getAbsoluteY() + bar.getHeight() - 5;
- mouse.click(p, true);
- sleep(750, 1250);
- break;
- case SELECT:
- interfaces.get(MAIN_FRAME).getComponent(NPCS_CONTAINER)
- .getComponent(NPC_TO_SELECT).doClick();
- sleep(750, 1250);
- break;
- case WAIT:
- sleep(500, 600);
- break;
- case CONTINUE:
- if (interfaces.canContinue())
- interfaces.clickContinue();
- sleep(500, 650);
- break;
- case MENU:
- if (getComponent(MENU_ITEM) != null)
- getComponent(MENU_ITEM).doClick();
- break;
- }
- sleep(900, 1200);
- }
- public void removePouches() {
- if (!openBank())
- return;
- // not enough runes, bank pouches:
- for (int id : Pouch.ALL_DEGRADED)
- if (inventory.contains(id)) {
- bank.deposit(id, 1);
- sleep(500, 600);
- }
- updatePouches();
- }
- }
- /**
- * Loads script data as the actual script runs. Useful for images that are
- * non-essential.
- *
- * @author Equinox_
- *
- */
- public static class DataLoader extends Thread {
- EquinoxGraahkCrafter crafter;
- public DataLoader(EquinoxGraahkCrafter crafter) {
- super("Data Loader");
- this.crafter = crafter;
- this.start();
- }
- // Item Info
- public void checkGE() {
- long before = System.currentTimeMillis();
- GEItem item = crafter.getGE().lookup(PURE_ESS_ID);
- if (item != null) {
- crafter.Paint.essPrice = getItemPrice(item);
- crafter.log("Price of " + item.getName() + ": "
- + getItemPrice(item));
- crafter.log("Loaded essence information in "
- + PaintFormatter.getFormattedTime(System
- .currentTimeMillis() - before));
- }
- before = System.currentTimeMillis();
- item = crafter.getGE().lookup(NATURE_RUNE_ID);
- if (item != null) {
- crafter.Paint.natPrice = getItemPrice(item);
- crafter.log("Price of " + item.getName() + ": "
- + getItemPrice(item));
- crafter.log("Loaded rune information in "
- + PaintFormatter.getFormattedTime(System
- .currentTimeMillis() - before));
- }
- before = System.currentTimeMillis();
- item = crafter.getGE().lookup(SPIRIT_GRAAHK_POUCH_ID);
- if (item != null) {
- crafter.Paint.graahkPrice = getItemPrice(item);
- crafter.log("Price of " + item.getName() + ": "
- + getItemPrice(item));
- crafter.log("Loaded graahk information in "
- + PaintFormatter.getFormattedTime(System
- .currentTimeMillis() - before));
- }
- }
- public void run() {
- if (crafter.Paint != null) {
- checkGE();
- try {
- if (JOptionPane.NO_OPTION == JOptionPane.showConfirmDialog(
- null, "Would you like to load some images?",
- "Equinox_ Data Loader", JOptionPane.YES_NO_OPTION))
- throw new Exception();
- long before = System.currentTimeMillis();
- int width = (int) (30 - (crafter.Paint.style.roundCorner));
- int height = (int) (30 - (crafter.Paint.style.roundCorner));
- int hints = Image.SCALE_FAST;
- crafter.Paint.paintMenu.putImage(
- "overallSkill",
- ImageIO.read(
- new URL(crafter.baseURL
- + "/images/overallSkill.png"))
- .getScaledInstance(width, height, hints));
- crafter.log("Loaded overall skill image in "
- + PaintFormatter.getFormattedTime(System
- .currentTimeMillis() - before));
- before = System.currentTimeMillis();
- crafter.Paint.paintMenu.putImage(
- "homeIcon",
- ImageIO.read(
- new URL(crafter.baseURL
- + "/images/houseIcon.png"))
- .getScaledInstance(width, height, hints));
- crafter.log("Loaded home image in "
- + PaintFormatter.getFormattedTime(System
- .currentTimeMillis() - before));
- before = System.currentTimeMillis();
- crafter.Paint.paintMenu.putImage(
- "natrune",
- ImageIO.read(
- new URL(crafter.baseURL
- + "/images/natRune.png"))
- .getScaledInstance(width, height, hints));
- crafter.log("Loaded nature image in "
- + PaintFormatter.getFormattedTime(System
- .currentTimeMillis() - before));
- before = System.currentTimeMillis();
- crafter.Paint.paintMenu.putImage(
- "tools",
- ImageIO.read(
- new URL(crafter.baseURL
- + "/images/tools.png"))
- .getScaledInstance(width, height, hints));
- crafter.log("Loaded tools icon in "
- + PaintFormatter.getFormattedTime(System
- .currentTimeMillis() - before));
- } catch (Exception e) {
- crafter.log("Failed to load images");
- }
- } else {
- crafter.log("Paint not initialized - didn't load data.");
- }
- }
- }
- /**
- * A class for reporting errors to the host. Threaded so the confirm dialog
- * doesn't freeze the script.
- *
- * @author Equinox_
- *
- */
- public static class ErrorReporter extends Thread {
- EquinoxGraahkCrafter crafter;
- String report = "";
- public ErrorReporter(EquinoxGraahkCrafter crafter) {
- super("Error reporter");
- this.crafter = crafter;
- this.start();
- }
- public void run() {
- if (JOptionPane.NO_OPTION == JOptionPane
- .showConfirmDialog(
- null,
- "Would you like to submit an error report to http://equinox_scripts.web44.net?",
- "Equinox_ Error Reporter",
- JOptionPane.YES_NO_OPTION))
- return;
- crafter.log("Submitting error report...");
- if (crafter.errorLog.size() <= 0) {
- crafter.log("No errors to report!");
- return;
- }
- for (String s : crafter.errorLog)
- report += s + "\n--------------------";
- try {
- URL url = new URL(crafter.baseURL + "/logError.php?errors="
- + report);
- url.openConnection().getContentLength();
- crafter.errorLog.clear();
- crafter.log("Sucessfully submitted error report.");
- } catch (Exception e) {
- crafter.log("Failed to sumbit error report!");
- }
- }
- }
- /**
- * Gets the grandExchange singleton for reference by other classes
- *
- * @return GrandExchange reference
- */
- public GrandExchange getGE() {
- return grandExchange;
- }
- /**
- * Gets the item price based on class. Works with all versions of
- * grandExchange.class
- *
- * @param item
- * the GEItem to get the price from
- * @return int the price
- *
- * @author Equinox_
- */
- public static int getItemPrice(GEItem item) {
- for (Method m : item.getClass().getMethods())
- if (m.getName().equals("getGuidePrice")
- || m.getName().equals("getMinPrice"))
- try {
- return (Integer) (m.invoke(item));
- } catch (Exception e) {
- }
- return 0;
- }
- //Equinox Script Includes:
- /**
- * Used for anchoring the menu bar
- *
- * @author Equinox_
- *
- */
- public enum Anchor {
- UP_LEFT, UP_RIGHT, DOWN_RIGHT, DOWN_LEFT
- }
- /**
- * Threaded camera control, so the bot won't pause to turn the camera.
- *
- * @author Equinox_
- *
- */
- public static class CameraControl extends Thread {
- private final Calculations calc;
- private final Camera camera;
- private int cameraAngle = 0;
- private int cameraPitch = 0;
- private int movingRandomly = 0;
- private final Script parent;
- private final Range yawVariance = new Range(15,20);
- private final Range pitchVariance = new Range(5,10);
- public CameraControl(Camera camera, Calculations calc, Script parent) {
- super("Equinox Camera Control");
- cameraAngle = camera.getAngle();
- cameraPitch = camera.getPitch();
- movingRandomly = 0;
- this.calc = calc;
- this.camera = camera;
- this.parent = parent;
- }
- /**
- * Returns the current compass orientation in degrees, with North at 0,
- * increasing counter-clockwise to 360.
- *
- * @return The current camera angle in degrees.
- */
- public int getAngle() {
- // the client uses fixed point radians 0 - 2^14
- // degrees = yaw * 360 / 2^14 = yaw / 45.5111...
- return camera.getAngle();
- }
- /**
- * Returns the angle between the current camera angle and the given angle in
- * degrees.
- *
- * @param degrees
- * The target angle.
- * @return The angle between the who angles in degrees.
- */
- public int getAngleTo(int degrees) {
- int ca = getAngle();
- if (ca < degrees) {
- ca += 360;
- }
- int da = ca - degrees;
- if (da > 180) {
- da -= 360;
- }
- return da;
- }
- /**
- * Returns the camera angle at which the camera would be facing a certain
- * character.
- *
- * @param n
- * the RSCharacter
- * @return The angle
- */
- public int getCharacterAngle(RSCharacter n) {
- return getTileAngle(n.getLocation());
- }
- /**
- * Returns the camera angle at which the camera would be facing a certain
- * object.
- *
- * @param o
- * The RSObject
- * @return The angle
- */
- public int getObjectAngle(RSObject o) {
- return getTileAngle(o.getLocation());
- }
- /**
- * Returns the current percentage of the maximum pitch of the camera in an
- * open area.
- *
- * @return The current camera altitude percentage.
- */
- public int getPitch() {
- return camera.getPitch();
- }
- /**
- * Returns the camera angle at which the camera would be facing a certain
- * tile.
- *
- * @param t
- * The target tile
- * @return The angle in degrees
- */
- public int getTileAngle(RSTile t) {
- int a = (calc.angleToTile(t) - 90) % 360;
- return a < 0 ? a + 360 : a;
- }
- /**
- * Returns the current x position of the camera.
- *
- * @return The x position.
- */
- public int getX() {
- return camera.getX();
- }
- /**
- * Returns the current y position of the camera.
- *
- * @return The y position.
- */
- public int getY() {
- return camera.getY();
- }
- /**
- * Returns the current z position of the camera.
- *
- * @return The z position.
- */
- public int getZ() {
- return camera.getZ();
- }
- /**
- * Moves the camera in a random direction for a given time.
- *
- * @param timeOut
- * The maximum time in milliseconds to move the camera for.
- */
- public void moveRandomly(int timeOut) {
- movingRandomly = timeOut;
- }
- /**
- * Get a random number in between min and max
- *
- * @return random int between inclusive minimum and exclusive maximum
- */
- public int random(int MIN, int MAX) {
- return (int) (Math.random() * (Math.max(MAX, MIN) - Math.min(MAX, MIN)))
- + Math.min(MAX, MIN);
- }
- public boolean isRunning() {
- return this.isAlive();
- }
- public void run() {
- parent.log("Started camera control!");
- while (parent.isRunning()) {
- if (parent.isActive()) {
- if (movingRandomly > 0) {
- camera.moveRandomly(movingRandomly);
- movingRandomly = 0;
- } else {
- if (Math.abs(camera.getAngleTo(cameraAngle))>yawVariance.randomLinearDistribution())
- camera.setAngle(cameraAngle);
- if (Math.abs(camera.getPitch() - cameraPitch)>pitchVariance.randomLinearDistribution())
- camera.setPitch(cameraPitch);
- }
- }
- }
- parent.log("Camera control stopped!");
- }
- /**
- * Rotates the camera to a specific angle in the closest direction.
- *
- * @param degrees
- * The angle to rotate to.
- */
- public void setAngle(int degrees) {
- cameraAngle = degrees;
- }
- /**
- * Rotates the camera to the specified cardinal direction.
- *
- * @param direction
- * The char direction to turn the map. char options are w,s,e,n
- * and defaults to north if character is unrecognized.
- */
- public void setCompass(char direction) {
- switch (direction) {
- case 'n':
- setAngle(359);
- break;
- case 'w':
- setAngle(89);
- break;
- case 's':
- setAngle(179);
- break;
- case 'e':
- setAngle(269);
- break;
- default:
- setAngle(359);
- break;
- }
- }
- /**
- * Uses the compass component to set the camera to face north.
- * @deprecated Uses the mouse. Frowned on here.
- */
- public void setNorth() {
- camera.setNorth();
- }
- /**
- * Sets the altitude to max or minimum.
- *
- * @param up
- * True to go up. False to go down.
- * @return <tt>true</tt> if the altitude was changed.
- */
- public void setPitch(boolean up) {
- if (up) {
- setPitch(100);
- } else {
- setPitch(0);
- }
- }
- /**
- * Set the camera to a certain percentage of the maximum pitch. Don't rely
- * on the return value too much - it should return whether the camera was
- * successfully set, but it isn't very accurate near the very extremes of
- * the height.
- * <p/>
- * <p/>
- * This also depends on the maximum camera angle in a region, as it changes
- * depending on situation and surroundings. So in some areas, 68% might be
- * the maximum altitude. This method will do the best it can to switch the
- * camera altitude to what you want, but if it hits the maximum or stops
- * moving for any reason, it will return.
- * <p/>
- * <p/>
- * <p/>
- * Mess around a little to find the altitude percentage you like. In later
- * versions, there will be easier-to-work-with methods regarding altitude.
- *
- * @param percent
- * The percentage of the maximum pitch to set the camera to.
- * @return true if the camera was successfully moved; otherwise false.
- */
- public void setPitch(int percent) {
- cameraPitch = percent;
- }
- /**
- * Turns to a RSCharacter (RSNPC or RSPlayer).
- *
- * @param c
- * The RSCharacter to turn to.
- */
- public void turnTo(final RSCharacter c) {
- int angle = getCharacterAngle(c);
- setAngle(angle);
- }
- /**
- * Turns to within a few degrees of an RSCharacter (RSNPC or RSPlayer).
- *
- * @param c
- * The RSCharacter to turn to.
- * @param dev
- * The maximum difference in the angle.
- */
- public void turnTo(final RSCharacter c, final int dev) {
- int angle = getCharacterAngle(c);
- angle = random(angle - dev, angle + dev + 1);
- setAngle(angle);
- }
- /**
- * Turns to an RSObject.
- *
- * @param o
- * The RSObject to turn to.
- */
- public void turnTo(final RSObject o) {
- int angle = getObjectAngle(o);
- setAngle(angle);
- }
- /**
- * Turns to within a few degrees of an RSObject.
- *
- * @param o
- * The RSObject to turn to.
- * @param dev
- * The maximum difference in the turn angle.
- */
- public void turnTo(final RSObject o, final int dev) {
- int angle = getObjectAngle(o);
- angle = random(angle - dev, angle + dev + 1);
- setAngle(angle);
- }
- /**
- * Turns to a specific RSTile.
- *
- * @param tile
- * Tile to turn to.
- */
- public void turnTo(final RSTile tile) {
- int angle = getTileAngle(tile);
- setAngle(angle);
- }
- /**
- * Turns within a few degrees to a specific RSTile.
- *
- * @param tile
- * Tile to turn to.
- * @param dev
- * Maximum deviation from the angle to the tile.
- */
- public void turnTo(final RSTile tile, final int dev) {
- int angle = getTileAngle(tile);
- angle = random(angle - dev, angle + dev + 1);
- setAngle(angle);
- }
- /**
- * Turns to an RSCharacter (RSNPC or RSPlayer).
- *
- * @deprecated
- * @param c
- * The RSCharacter to turn to.
- */
- public void turnToCharacter(RSCharacter c) {
- int angle = getCharacterAngle(c);
- setAngle(angle);
- }
- /**
- * Turns to within a few degrees of an RSCharacter (RSNPC or RSPlayer).
- *
- * @deprecated
- * @param c
- * The RSCharacter to turn to.
- * @param dev
- * The maximum difference in the angle.
- */
- public void turnToCharacter(RSCharacter c, int dev) {
- int angle = getCharacterAngle(c);
- angle = random(angle - dev, angle + dev + 1);
- setAngle(angle);
- }
- /**
- * Turns to an RSObject
- *
- * @deprecated
- * @param o
- * The RSObject to turn to.
- */
- public void turnToObject(RSObject o) {
- int angle = getObjectAngle(o);
- setAngle(angle);
- }
- /**
- * Turns to within a few degrees of an RSObject.
- *
- * @deprecated
- * @param o
- * The RSObject to turn to.
- * @param dev
- * The maximum difference in the turn angle.
- */
- public void turnToObject(RSObject o, int dev) {
- int angle = getObjectAngle(o);
- angle = random(angle - dev, angle + dev + 1);
- setAngle(angle);
- }
- /**
- * Turns to a specific RSTile.
- *
- * @deprecated
- * @param tile
- * Tile to turn to.
- */
- public void turnToTile(RSTile tile) {
- int angle = getTileAngle(tile);
- setAngle(angle);
- }
- /**
- * Turns within a few degrees to a specific RSTile.
- *
- * @deprecated
- * @param tile
- * Tile to turn to.
- * @param dev
- * Maximum deviation from the angle to the tile.
- */
- public void turnToTile(RSTile tile, int dev) {
- int angle = getTileAngle(tile);
- angle = random(angle - dev, angle + dev + 1);
- setAngle(angle);
- }
- }
- /**
- * Used for specifing the way a menu is layed out.
- *
- * @author Equinox_
- *
- */
- public enum FlowType {
- VERTICAL, HORIZONTAL
- }/**
- * Class representing the method for getting the current percentile for a
- * progress bar
- *
- * @author Equinox_
- *
- */
- public static abstract class GetPercent {
- public abstract double getPercent();
- }
- /**
- * Represents a class containing the method for getting the popup
- *
- * @author Equinox_
- *
- */
- public static abstract class GetPopup {
- public abstract PaintMenuPopUp getPopUp();
- public abstract String getName();
- }
- /**
- * A class for representing the validation of a PaintMenu component
- *
- * @author Equinox_
- *
- */
- public static abstract class IsValid {
- public abstract boolean isValid();
- }
- /**
- * Class representing the LineListeners in popups
- *
- * @author Equinox_
- *
- */
- public static abstract class LineListener {
- public abstract void fireEvent(MouseEvent e, String line);
- public abstract boolean hasAction(String line);
- }
- /**
- * Represents a modified MouseListener used in MenuEvents
- *
- * @author Equinox_
- *
- */
- public static abstract class MenuMouseListener {
- public abstract void MouseAction(MouseEvent e);
- }
- /**
- * A class that will take a specified mesh, generate a path through it, then
- * round the path off with Bezier curves.
- *
- * @author Equinox_
- *
- */
- public static class MeshPath {
- public static final Color BLOCK_PATH_COLOR = new Color(0f, 1f, 0f, 1f);
- public static final Color MESH_BORDER = new Color(0.75f, 0.75f, 0.75f,
- 0.75f);
- public static final Color MESH_FILL = new Color(0.5f, 0.5f, 0.5f, 0.75f);
- public static final Color SMOOTH_PATH_COLOR = new Color(0f, 0f, 1f, 1f);
- private List<RSTile> blockPath = new ArrayList<RSTile>();
- private final Calculations calc;
- private boolean end;
- private List<RSTile[]> mesh = new ArrayList<RSTile[]>();
- private final Players players;
- private List<RSTile> smoothPath = new ArrayList<RSTile>();
- private final Walking walking;
- private final Range walkingDistance;
- /**
- * Creates a mesh path with the provided walking methods, calculation
- * methods, player methods, and walking range.
- *
- * @param walking
- * @param calc
- * @param players
- */
- public MeshPath(Walking walking, Calculations calc, Players players) {
- this(walking, calc, players, new Range(7, 9));
- }
- /**
- * Creates a mesh path with the provided walking methods, calculation
- * methods, player methods, and walking range.
- *
- * @param walking
- * @param calc
- * @param players
- * @param walkingDistance
- */
- public MeshPath(Walking walking, Calculations calc, Players players,
- Range walkingDistance) {
- this.walking = walking;
- this.calc = calc;
- this.players = players;
- this.walkingDistance = walkingDistance;
- }
- /**
- * Creates a mesh path with the provided walking methods, calculation
- * methods, player methods, and mesh.
- *
- * @param walking
- * @param calc
- * @param players
- * @param mesh
- */
- public MeshPath(Walking walking, Calculations calc, Players players,
- RSTile[][] mesh) {
- this(walking, calc, players);
- setMesh(mesh);
- }
- /**
- * Creates a mesh path with the provided walking methods, calculation
- * methods, player methods, walking range, and mesh.
- *
- * @param walking
- * @param calc
- * @param players
- * @param walkingDistance
- * @param mesh
- */
- public MeshPath(Walking walking, Calculations calc, Players players,
- RSTile[][] mesh, Range walkingDistance) {
- this(walking, calc, players, walkingDistance);
- setMesh(mesh);
- }
- /**
- * Adds a line to the mesh with the given tiles
- *
- * @param tiles
- * the RSTiles making up the line
- */
- public void addLine(RSTile... tiles) {
- if (mesh.size() == 0) {
- mesh.add(tiles);
- return;
- }
- RSTile first = tiles[0];
- RSTile last = tiles[tiles.length - 1];
- RSTile[] oLine = mesh.get(mesh.size() - 1);
- RSTile oFirst = oLine[0];
- RSTile oLast = oLine[oLine.length - 1];
- double straight = calc.distanceBetween(first, oFirst)
- + calc.distanceBetween(last, oLast);
- double crossed = calc.distanceBetween(first, oLast)
- + calc.distanceBetween(last, oFirst);
- if (straight > crossed) {
- mesh.add(tiles);
- return;
- } else {
- RSTile[] reversed = new RSTile[tiles.length];
- for (int i = 0; i < tiles.length; i++)
- reversed[i] = tiles[tiles.length - 1 - i];
- mesh.add(reversed);
- return;
- }
- }
- /**
- * Adds all the lines of a specified mesh to the current mesh.
- *
- * @param mesh
- * as RSTile[][]
- */
- public void addMesh(RSTile[][] mesh) {
- for (RSTile[] line : mesh)
- addLine(line);
- }
- /**
- * Clears the current path and all refined versions of it.
- */
- public void clearPath() {
- blockPath.clear();
- smoothPath.clear();
- }
- /**
- * Finds a path between the beginning and end of the mesh using the
- * WEIGHT_CENTER placement type, then sets the current path to the found
- * path
- */
- public void findPath() {
- findPath(MeshPathType.WEIGHT_CENTER);
- }
- /**
- * Finds a path between the beginning and end of the mesh using the provided
- * placement type, then sets the current path to the found path
- *
- * @param placement
- * as MeshPathType
- */
- public void findPath(MeshPathType placement) {
- findPath(placement, 0, mesh.size() - 1);
- }
- /**
- * Finds a path between the start index and the end index using the provided
- * placement type, then sets the current path to the found path
- *
- * @param placement
- * as MeshPathType
- * @param start
- * index
- * @param end
- * index
- */
- public void findPath(MeshPathType placement, int start, int end) {
- blockPath.clear();
- for (int i = start; i <= end; i++)
- blockPath.add(getTileOnLine(placement, mesh.get(i)));
- smoothPath = smoothPath(blockPath);
- }
- /**
- * Gets the end tile of this path.
- *
- * @return The end <code>RSTile</code>.
- */
- public RSTile getEnd() {
- if (smoothPath.size() > 0)
- return smoothPath.get(smoothPath.size() - 1);
- else
- return null;
- }
- /**
- * Gets the next immediately available vertex in this path.
- *
- * @return The next walkable <code>RSTile</code>.
- */
- public RSTile getNext() {
- if (smoothPath.size() > 0)
- for (int i = smoothPath.size() - 1; i >= 0; i--)
- if (calc.tileOnMap(smoothPath.get(i)))
- return smoothPath.get(i);
- return null;
- }
- /**
- * Gets the start tile of this path.
- *
- * @return The start <code>RSTile</code>.
- */
- public RSTile getStart() {
- if (smoothPath.size() > 0)
- return smoothPath.get(0);
- else
- return null;
- }
- /**
- * Gets the nearest tile in the mesh to the provided RSTile
- *
- * @param tile
- * the RSTile to use
- * @return RSTile tile in mesh
- */
- public RSTile getTileInMesh(RSTile tile) {
- if (inMesh(tile))
- return tile;
- double bestDist = Double.MAX_VALUE;
- RSTile nearest = null;
- if (mesh.size() > 1) {
- for (int i = 1; i < mesh.size(); i++) {
- RSTile[] lineA = mesh.get(i - 1);
- RSTile[] lineB = mesh.get(i);
- if (lineA != null)
- for (RSTile t : lineA) {
- double dist = calc.distanceBetween(t, tile);
- if (dist < bestDist) {
- nearest = new RSTile(t.getX(), t.getY());
- bestDist = Double.valueOf(dist);
- }
- }
- if (lineB != null)
- for (RSTile t : lineB) {
- double dist = calc.distanceBetween(t, tile);
- if (dist < bestDist) {
- nearest = new RSTile(t.getX(), t.getY());
- bestDist = Double.valueOf(dist);
- }
- }
- }
- }
- return nearest;
- }
- /**
- * Gets a tile on the provided line using the provided method
- *
- * @param placement
- * as MeshPathType
- * @param line
- * as RSTile...
- * @return RSTile tile on line
- */
- public RSTile getTileOnLine(MeshPathType placement, RSTile... line) {
- List<RSTile> tiles = getTilesOnLines(line);
- int index = 0;
- switch (placement) {
- case ALL_CENTER:
- index = new Range((int) (tiles.size() * .25d),
- (int) (tiles.size() * 0.75d)).randomLinearDistribution();
- break;
- case FULL:
- index = new Range(0, tiles.size()).randomLinearDistribution();
- break;
- case WEIGHT_CENTER:
- index = new Range(0, tiles.size()).randomNormalDistribution();
- break;
- }
- if (index < 0)
- index = 0;
- if (index >= tiles.size())
- index = tiles.size() - 1;
- if (tiles.size() > 0)
- return tiles.get(index);
- else
- return null;
- }
- /**
- * Gets a tile on the provided line using the ALL_CENTER method
- *
- * @param line
- * as RSTile...
- * @return RSTile tile on line
- */
- public RSTile getTileOnLine(RSTile... line) {
- return getTileOnLine(MeshPathType.WEIGHT_CENTER, line);
- }
- /**
- * Returns an array containing all of the vertices in this path.
- *
- * @return an array containing all of the vertices in this path.
- */
- public RSTile[] getTilePath() {
- RSTile[] tiles = new RSTile[smoothPath.size()];
- for (int i = 0; i < tiles.length; i++)
- tiles[i] = new RSTile(smoothPath.get(i).getX(), smoothPath.get(i)
- .getY());
- return tiles;
- }
- public List<RSTile> getTilesOnLine(RSTile a, RSTile b) {
- List<RSTile> sublineTiles = new ArrayList<RSTile>();
- int deltaX = b.getX() - a.getX();
- int deltaY = b.getY() - a.getY();
- double dist = calc.distanceBetween(a, b);
- if (dist == 0)
- dist = 1;
- double eX = deltaX / dist, eY = deltaY / dist;
- for (int i = 0; i <= dist; i++)
- sublineTiles.add(new RSTile(a.getX() + (int) (eX * i), a.getY()
- + (int) (eY * i)));
- return sublineTiles;
- }
- /**
- * Gets all the tiles on the provided line
- *
- * @param line
- * as RSTile...
- * @return List<RSTile> tiles on line
- */
- public List<RSTile> getTilesOnLines(RSTile... line) {
- List<RSTile> sublineTiles = new ArrayList<RSTile>();
- if (line.length == 1)
- sublineTiles.add(line[0]);
- else
- for (int i = 1; i < line.length; i++) {
- RSTile a = line[i - 1];
- RSTile b = line[i];
- sublineTiles.addAll(getTilesOnLine(a, b));
- }
- return sublineTiles;
- }
- /**
- * Checks if we have a path
- *
- * @return boolean has path
- */
- public boolean hasPath() {
- return smoothPath.size() > 0;
- }
- /**
- * Checks to see if the provided RSTile is inside the mesh
- *
- * @param tile
- * the RSTile to check
- * @return boolean is in mesh
- */
- public boolean inMesh(RSTile tile) {
- if (mesh.size() > 1) {
- for (int i = 1; i < mesh.size(); i++) {
- RSTile[] lineA = mesh.get(i - 1);
- RSTile[] lineB = mesh.get(i);
- Polygon poly = new Polygon();
- if (lineA != null)
- for (RSTile t : lineA)
- poly.addPoint(t.getX(), t.getY());
- if (lineB != null)
- for (RSTile t : lineB)
- poly.addPoint(t.getX(), t.getY());
- if (poly.npoints >= 2)
- if (poly.contains(new Point(tile.getX(), tile.getY())))
- return true;
- }
- }
- return false;
- }
- /**
- * Checks whether or not this path can be traversed by the player. This will
- * be the case provided that the player near to one of its vertices, but not
- * already standing on the end vertex.
- *
- * @return <tt>true</tt> if the player can walk along this path; otherwise
- * <tt>false</tt>.
- */
- public boolean isValid() {
- return smoothPath.size() > 0 && getNext() != null
- && !players.getMyPlayer().getLocation().equals(getEnd());
- }
- /**
- * Gets the number of lines in the mesh
- *
- * @return int size
- */
- public int meshSize() {
- return mesh.size();
- }
- /**
- * Paints the mesh, and all versions of the current path to the minimap
- * using the provided graphics object
- *
- * @param g
- * as Graphics2D
- */
- public void paintAll(Graphics2D g) {
- paintMesh(g);
- paintBlockPath(g);
- paintSmoothPath(g);
- }
- /**
- * Paints the current un-smoothed path to the minimap using the provided
- * graphics object
- *
- * @param g
- * as Graphics2D
- */
- public void paintBlockPath(Graphics2D g) {
- if (blockPath.size() > 1) {
- g.setColor(BLOCK_PATH_COLOR);
- Point a = null;
- for (RSTile t : blockPath) {
- Point b = calc.tileToMinimap(t);
- if (b.x > 0 && b.y > 0)
- g.fillOval(b.x - 2, b.y - 2, 5, 5);
- if (a != null && a.x > 0 && a.y > 0 && b.x > 0 && b.y > 0)
- g.drawLine(a.x, a.y, b.x, b.y);
- a = b;
- }
- }
- }
- /**
- * Paints the mesh to the provided graphics context in the minimap
- *
- * @param g
- * as Graphics2D
- */
- public void paintMesh(Graphics2D g) {
- if (mesh.size() > 1) {
- Point[] oldLine = null;
- for (int i = 0; i < mesh.size(); i++) {
- RSTile[] lineB = mesh.get(i);
- Point[] thisLine = new Point[lineB.length];
- Polygon poly = new Polygon();
- boolean onMap = true;
- for (int tile = 0; tile < thisLine.length; tile++) {
- Point p = calc.tileToMinimap(lineB[tile]);
- thisLine[tile] = p;
- poly.addPoint(p.x, p.y);
- if (p.x == -1 || p.y == -1)
- onMap = false;
- }
- if (oldLine != null) {
- for (Point p : oldLine) {
- poly.addPoint(p.x, p.y);
- if (p.x == -1 || p.y == -1)
- onMap = false;
- }
- if (poly.npoints >= 2 && onMap) {
- g.setColor(MESH_BORDER);
- g.draw(poly);
- g.setColor(MESH_FILL);
- g.fill(poly);
- }
- }
- oldLine = thisLine;
- }
- }
- }
- /**
- * Paints the smoothed version of the current path to the minimap using the
- * provided graphics object
- *
- * @param g
- * as Graphics2D
- */
- public void paintSmoothPath(Graphics2D g) {
- if (smoothPath.size() > 1) {
- g.setColor(SMOOTH_PATH_COLOR);
- Point a = null;
- for (RSTile t : smoothPath) {
- Point b = calc.tileToMinimap(t);
- if (b.x > 0 && b.y > 0)
- g.fillOval(b.x - 2, b.y - 2, 5, 5);
- if (a != null && a.x > 0 && a.y > 0 && b.x > 0 && b.y > 0)
- g.drawLine(a.x, a.y, b.x, b.y);
- a = b;
- }
- }
- }
- /**
- * Reverses this path.
- *
- * @return This path.
- */
- public MeshPath reverse() {
- MeshPath m = new MeshPath(walking, calc, players);
- for (int i = mesh.size() - 1; i >= 0; i--) {
- m.addLine(blockPath.get(i));
- }
- return m;
- }
- /**
- * Sets the current mesh to the provided mesh
- *
- * @param mesh
- * as RSTile[][]
- */
- public void setMesh(RSTile[][] mesh) {
- this.mesh.clear();
- addMesh(mesh);
- }
- /**
- * Smoothes the provided List of RSTiles using Bezier curves. Will return a
- * path with 4 times as many vertices
- *
- * @param path
- * as List
- * @return List<RSTile> smoothed path
- */
- public List<RSTile> smoothPath(List<RSTile> path) {
- List<RSTile> smoothed = new ArrayList<RSTile>();
- if (path.size() >= 3) {
- for (int i = 0; i < path.size(); i++) {
- if (i + 2 < path.size()) {
- RSTile tile1 = path.get(i);
- RSTile tile2 = path.get(i + 1);
- RSTile tile3 = path.get(i + 2);
- if (i == 0)
- smoothed.add(tile1);
- double x2, y2;
- double t = 0.5d;
- // use Berstein polynomials
- x2 = (tile1.getX() + t
- * (-tile1.getX() * 3 + t
- * (3 * tile1.getX() - tile1.getX() * t)))
- + t
- * (3 * tile2.getX() + t
- * (-6 * tile2.getX() + tile2.getX() * 3 * t))
- + t
- * t
- * (tile2.getX() * 3 - tile2.getX() * 3 * t)
- + tile3.getX() * t * t * t;
- y2 = (tile1.getY() + t
- * (-tile1.getY() * 3 + t
- * (3 * tile1.getY() - tile1.getY() * t)))
- + t
- * (3 * tile2.getY() + t
- * (-6 * tile2.getY() + tile2.getY() * 3 * t))
- + t
- * t
- * (tile2.getY() * 3 - tile2.getY() * 3 * t)
- + tile3.getY() * t * t * t;
- smoothed.add(getTileInMesh(new RSTile((int) x2, (int) y2)));
- } else {
- // Just add the vert.
- smoothed.add(path.get(i));
- }
- }
- }
- return smoothed;
- }
- /**
- * Returns a string representation of this Mesh Path.
- *
- * @return String
- */
- public String toString() {
- return "{ Line count: " + mesh.size() + ", Path size: "
- + (hasPath() ? smoothPath.size() : "No path") + " }";
- }
- /**
- * Takes a step along this path if appropriate. Specifies only
- * TraversalOption.SPACE_ACTIONS.
- *
- * @return <tt>true</tt> if this path is currently valid for the player;
- * otherwise <tt>false</tt>.
- * @see #traverse(EnumSet)
- */
- public boolean traverse() {
- return this.traverse(EnumSet.of(TraversalOption.HANDLE_RUN,
- TraversalOption.SPACE_ACTIONS));
- }
- /**
- * Takes a step along this path if appropriate. If the path cannot be
- * traversed due to the player being too far from its vertices or already at
- * the end vertex, <tt>false</tt> will be returned. In all other cases,
- * <tt>true</tt> will be returned, but an action will not necessarily be
- * performed (based on the given options).
- *
- * @param options
- * Walking style options.
- * @return <tt>true</tt> if this path is currently valid for the player;
- * otherwise <tt>false</tt>.
- */
- public boolean traverse(EnumSet<TraversalOption> options) {
- RSTile next = getNext();
- if (next == null) {
- return false;
- }
- if (next.equals(getEnd())) {
- if (calc.distanceTo(next) <= 1
- || (end && players.getMyPlayer().isMoving())
- || next.equals(walking.getDestination())) {
- return false;
- }
- end = true;
- } else {
- end = false;
- }
- if (options.contains(TraversalOption.HANDLE_RUN)
- && !walking.isRunEnabled() && walking.getEnergy() > 50) {
- walking.setRun(true);
- }
- if (options.contains(TraversalOption.SPACE_ACTIONS)) {
- RSTile dest = walking.getDestination();
- if (dest != null
- && players.getMyPlayer().isMoving()
- && calc.distanceTo(dest) > 5
- && calc.distanceBetween(next, dest) < walkingDistance
- .randomLinearDistribution()) {
- return true;
- }
- }
- return walking.walkTileMM(next, 0, 0);
- }
- /**
- * Gets the nearest tile on the path by distance alone
- * @return RSTile
- */
- public RSTile getNearest() {
- int len = Integer.MAX_VALUE;
- RSTile best = null;
- if (hasPath())
- for (RSTile t : smoothPath)
- if (calc.distanceTo(t) < len) {
- best = t;
- len = calc.distanceTo(t);
- }
- return best;
- }
- /**
- * Gets the nearest tile on the path by the length of a path to it.
- * @return RSTile
- */
- public RSTile getNearestByPath() {
- int len = Integer.MAX_VALUE;
- RSTile best = null;
- if (hasPath())
- for (RSTile t : smoothPath) {
- int pLen = calc.pathLengthTo(t, false);
- if (pLen < len && pLen >= 0) {
- best = t;
- len = pLen;
- }
- }
- return best;
- }
- /**
- * Gets the nearest index on the path to the given tile
- * @param t RSTile
- * @return int
- */
- public int getNearestIndexTo(RSTile t) {
- int len = Integer.MAX_VALUE;
- int bestIndex = -1;
- if (hasPath())
- for (int i = 0; i < smoothPath.size(); i++)
- if (calc.distanceBetween(t, smoothPath.get(i)) < len) {
- bestIndex = i;
- len = calc.distanceTo(t);
- }
- return bestIndex;
- }
- /**
- * Use this enum to define the type of path <br />
- * ALL_Center: All points are near the middle of the lines <br />
- * Full: Points can be anywhere on the line<br />
- * WEIGHT_CENTER: Weighted to center, possibility of being on sides, but
- * lower
- *
- * @author Equinox_
- *
- */
- public enum MeshPathType {
- ALL_CENTER, FULL, WEIGHT_CENTER
- }
- }
- /**
- * A class for clicking on objects via their model. Uses normally distributed
- * points inside bounding ellipses
- *
- * @author Equinox_
- *
- */
- public static class ModelMouse {
- // Sin & Cos Tables
- static Map<Integer, Double> cosTable;
- static Map<Integer, Double> sinTable;
- final Calculations calc;
- final Menu menu;
- final Mouse mouse;
- final Range mouseSpeed;
- final Tiles tiles;
- /**
- * Begin to cache sine and cosine values
- */
- public static void cacheTrig() {
- sinTable = new HashMap<Integer, Double>();
- cosTable = new HashMap<Integer, Double>();
- }
- /**
- * Gets the distance between two points.
- *
- * @see Point.distance(x1, y1, x2, y2)
- * @param a
- * @param b
- * @return double
- */
- public static double distanceBetween(Point a, Point b) {
- return Point.distance(a.x, a.y, b.x, b.y);
- }
- /**
- * Gets the absolute center of the array of points via it's bounding box.
- *
- * @param points
- * @return Point
- */
- public static Point getAbsoluteCenter(Point[] points) {
- Rectangle rect = getBoundingBox(points);
- return new Point((int) rect.getCenterX(), (int) rect.getCenterY());
- }
- /**
- * Gets the bounding box of the provided point array
- *
- * @param points
- * @return Rectangle
- */
- public static Rectangle getBoundingBox(Point[] points) {
- int min_x = Integer.MAX_VALUE;
- int min_y = Integer.MAX_VALUE;
- int max_x = Integer.MIN_VALUE;
- int max_y = Integer.MIN_VALUE;
- if (points != null) {
- for (Point pt : points) {
- if (pt.x < min_x)
- min_x = pt.x;
- if (pt.x > max_x)
- max_x = pt.x;
- if (pt.y < min_y)
- min_y = pt.y;
- if (pt.y > max_y)
- max_y = pt.y;
- }
- return new Rectangle(min_x, min_y, max_x - min_x, max_y - min_y);
- }
- return null;
- }
- /**
- * Gets an approximate bounding ellipse for the specified point array. (May
- * not contain all points)
- *
- * @param points
- * @return Ellipse2D
- */
- public static Ellipse2D getBoundingEllipse(Point[] points) {
- Rectangle bound = getBoundingBox(points);
- return new Ellipse2D.Double(bound.x, bound.y, bound.width, bound.height);
- }
- /**
- * Gets the cosine of the given degrees, from the cache table if possible
- *
- * @param degrees
- * @return double
- */
- public static double getCos(int degrees) {
- if (cosTable != null && cosTable.containsKey(degrees))
- return cosTable.get(degrees);
- else {
- double cosVal = Math.cos(degrees);
- if (cosTable != null)
- cosTable.put(degrees, cosVal);
- return cosVal;
- }
- }
- /**
- * Gets a random point on the provided ellipse, calculating a random angle
- * between 0 and 360
- *
- * @see getPointOnEllipse(Ellipse2D ellipse, int degrees)
- * @see randomLinearDistribution(int MIN, int MAX)
- * @param ellipse
- * @return Point
- */
- public static Point getPointOnEllipse(Ellipse2D ellipse) {
- return getPointOnEllipse(ellipse,
- (int) randomLinearDistribution(0, 360));
- }
- /**
- * Gets a random point on the provided ellipse, on a ray originating from
- * the center and the provided angle, using a normally distributed length
- * between 0 and the ellipse's radius at the provided angle
- *
- * @see getPointOnEllipse(Ellipse2D ellipse, int degrees, double
- * distFromCenter)
- * @see randomNormalDistribution(int MIN, int MAX)
- * @param ellipse
- * @param degrees
- * @return Point
- */
- public static Point getPointOnEllipse(Ellipse2D ellipse, int degrees) {
- return getPointOnEllipse(ellipse, degrees,
- randomNormalDistribution(0, getRadiusAt(ellipse, degrees)));
- }
- /**
- * Gets a random point on the provided ellipse, on a ray originating from
- * the center and the provided angle, at the provided distance from the
- * center.
- *
- * @param ellipse
- * @param degrees
- * @param distFromCenter
- * @return Point
- */
- public static Point getPointOnEllipse(Ellipse2D ellipse, int degrees,
- double distFromCenter) {
- while (degrees >= 360)
- degrees -= 360;
- while (degrees < 0)
- degrees += 360;
- double sinVal = getSin(degrees), cosVal = getCos(degrees);
- return new Point(
- (int) (ellipse.getCenterX() + Math.round(distFromCenter
- * cosVal)),
- (int) (ellipse.getCenterY() + Math.round(distFromCenter
- * sinVal)));
- }
- /**
- * Gets a random point on the model.
- *
- * @see getPointOnPolygon(Polygon p)
- * @see getPolygonOnModel(RSModel m)
- * @param model
- * @return Point
- */
- public static Point getPointOnModel(RSModel model) {
- if (model != null)
- return getPointOnPolygon(getPolygonOnModel(model));
- return null;
- }
- /**
- * Gets a random point on the provided polygon using a bounding ellipse.
- *
- * @see getPointOnEllipse(Ellipse2D ellipse)
- * @see getPoints(Polygon p)
- * @see getBoundingEllipse(Point[] points)
- * @param p
- * @return Point
- */
- public static Point getPointOnPolygon(Polygon p) {
- Point result = null;
- Ellipse2D boundingEllipse = getBoundingEllipse(getPoints(p));
- for (byte b = 0; b < 100 && (result == null || !p.contains(result)); b++)
- result = getPointOnEllipse(boundingEllipse);
- if (result != null)
- return result;
- else
- return new Point((int) p.getBounds().getCenterX(), (int) p
- .getBounds().getCenterY());
- }
- /**
- * Gets all the points on the provided polygon.
- *
- * @param p
- * @return Point[]
- */
- public static Point[] getPoints(Polygon p) {
- Point[] result = new Point[p.npoints];
- for (int pIdx = 0; pIdx < p.npoints; pIdx++)
- result[pIdx] = new Point(p.xpoints[pIdx], p.ypoints[pIdx]);
- return result;
- }
- /**
- * Gets the nearest polygon to the base point from the array of polygons
- *
- * @param polygons
- * @param base
- * @return Polygon
- */
- public static Polygon getPolygonNearestTo(Polygon[] polygons, Point base) {
- double bDist = Double.MAX_VALUE;
- Polygon bPoly = null;
- for (Polygon tri : polygons) {
- double dist = Point.distance(tri.getBounds().getCenterX(), tri
- .getBounds().getCenterY(), base.x, base.y);
- if (dist < bDist) {
- bDist = dist;
- bPoly = tri;
- }
- }
- return bPoly;
- }
- /**
- * Gets a random polygon on the model by first calculating its bounding
- * ellipse, finding a point on that ellipse using a normal distribution
- * method, then getting the nearest polygon on the model to that point
- *
- * @param m
- * @return Polygon
- */
- public static Polygon getPolygonOnModel(RSModel m) {
- if (m != null && m.getTriangles() != null)
- return getPolygonNearestTo(m.getTriangles(),
- getPointOnEllipse(getBoundingEllipse(m.getPoints())));
- return null;
- }
- /**
- * Gets the radius of the ellipse and the given angle.
- *
- * @param ellipse
- * @param degrees
- * @return double
- */
- public static double getRadiusAt(Ellipse2D ellipse, int degrees) {
- while (degrees >= 360)
- degrees -= 360;
- while (degrees < 0)
- degrees += 360;
- if (degrees > 180)
- degrees = 360 - degrees;
- if (degrees > 90)
- degrees = 180 - degrees;
- double weightX = degrees / 90d, weightY = Math.abs(1 - weightX);
- return (weightX * (ellipse.getWidth() / 2d) + weightY
- * (ellipse.getHeight() / 2d));
- }
- /**
- * Gets the sine of the given degrees, from the cache table if possible
- *
- * @param degrees
- * @return double
- */
- public static double getSin(int degrees) {
- if (sinTable != null && sinTable.containsKey(degrees))
- return sinTable.get(degrees);
- else {
- double sinVal = Math.sin(degrees);
- if (sinTable != null)
- sinTable.put(degrees, sinVal);
- return sinVal;
- }
- }
- /**
- * Returns a linearly distributed pseudorandom integer.
- *
- * @return Random integer min <= n < max.
- */
- public static double randomLinearDistribution(double min, double max) {
- return Math.min(min, max) + new Random().nextDouble()
- * Math.abs(max - min);
- }
- /**
- * Returns a normally distributed pseudorandom integer about a mean centered
- * between min and max with a calculated standard deviation.
- *
- * @return Random integer min <= n < max from the normal distribution
- * described by the parameters.
- */
- public static double randomNormalDistribution(double MIN, double MAX) {
- double mean = MIN + (MAX - MIN) / 2d;
- double rand;
- double sd = (MAX - MIN) / 3d;
- do {
- rand = (new Random().nextGaussian() * sd + mean);
- } while (rand < MIN || rand >= MAX);
- return rand;
- }
- /**
- * Clear cache of sine and cosine values and no longer cache them
- */
- public static void unCacheTrig() {
- sinTable = null;
- cosTable = null;
- }
- static {
- cacheTrig();
- }
- /**
- * Creates a model mouse instance with the given Tile methods, Calculation
- * methods, Mouse methods, Menu methods, and mouse speed Range
- *
- * @param tiles
- * @param calc
- * @param mouse
- * @param menu
- * @param mouseSpeed
- * @see Range
- * @see Tiles
- * @see Calculations
- * @see Mouse
- * @see Menu
- */
- public ModelMouse(Tiles tiles, Calculations calc, Mouse mouse, Menu menu,
- Range mouseSpeed) {
- this.mouse = mouse;
- this.menu = menu;
- this.mouseSpeed = mouseSpeed;
- this.calc = calc;
- this.tiles = tiles;
- }
- // Characters
- /**
- * Performs the specified action on the character.
- *
- * @param character
- * RSCharacter
- * @param action
- * the menu item to search and click
- * @return returns true if clicked, false if character does not contain the
- * desired action
- */
- public boolean doAction(RSCharacter character, String action) {
- RSModel model = character.getModel();
- if (model != null) {
- return doAction(model, action);
- }
- return tiles.doAction(character.getLocation(), action);
- }
- // Ground Items
- /**
- * Performs the specified action on the Ground Item.
- *
- * @param groundItem
- * RSGroundItem
- * @param action
- * the menu item to search and click
- * @return returns true if clicked, false if groundItem does not contain the
- * desired action
- */
- public boolean doAction(RSGroundItem groundItem, String action) {
- RSModel model = groundItem.getModel();
- if (model != null) {
- return doAction(model, action);
- }
- return tiles.doAction(groundItem.getLocation(), action);
- }
- // Models
- /**
- * Clicks the RSModel and clicks the menu action
- *
- * @param model
- * The RSModel
- * @param action
- * the action to be clicked in the menu
- * @return true if clicked, false if failed.
- */
- public boolean doAction(RSModel model, String action) {
- if (model != null && model.getPointOnScreen() != null) {
- Point modelPoint = getPointOnModel(model);
- if (modelPoint != null) {
- mouse.setSpeed(mouseSpeed.randomLinearDistribution());
- mouse.move(modelPoint);
- return menu.doAction(action);
- }
- }
- return false;
- }
- // Objects
- /**
- * Performs the specified action on the object.
- *
- * @param object
- * RSObject
- * @param action
- * the menu item to search and click
- * @return returns true if clicked, false if object does not contain the
- * desired action
- */
- public boolean doAction(RSObject object, String action) {
- RSModel model = object.getModel();
- if (model != null) {
- return doAction(model, action);
- }
- return tiles.doAction(object.getLocation(), action);
- }
- /**
- * Left-clicks the character.
- *
- * @param character
- * The RSCharacter
- * @return <tt>true</tt> if clicked.
- */
- public boolean doClick(RSCharacter character) {
- return doClick(character, true);
- }
- /**
- * Clicks the character.
- *
- * @param character
- * The RSCharacter
- * @param left
- * <tt>true</tt> to left-click; <tt>false</tt> to right-click.
- * @return <tt>true</tt> if clicked.
- */
- public boolean doClick(RSCharacter character, boolean leftClick) {
- RSModel model = character.getModel();
- if (model != null) {
- return doClick(model, leftClick);
- } else {
- Point p = calc.tileToScreen(character.getLocation());
- if (calc.pointOnScreen(p)) {
- mouse.move(p);
- if (calc.pointOnScreen(p)) {
- mouse.click(leftClick);
- return true;
- } else {
- p = calc.tileToScreen(character.getLocation());
- if (calc.pointOnScreen(p)) {
- mouse.move(p);
- mouse.click(leftClick);
- return true;
- }
- }
- }
- return false;
- }
- }
- /**
- * Left-clicks the Ground Item.
- *
- * @param groundItem
- * The RSGroundItem
- * @return <tt>true</tt> if clicked.
- */
- public boolean doClick(RSGroundItem groundItem) {
- return doClick(groundItem, true);
- }
- /**
- * Clicks the Ground Item.
- *
- * @param groundItem
- * The RSGroundItem
- * @param left
- * <tt>true</tt> to left-click; <tt>false</tt> to right-click.
- * @return <tt>true</tt> if clicked.
- */
- public boolean doClick(RSGroundItem groundItem, boolean leftClick) {
- RSModel model = groundItem.getModel();
- if (model != null) {
- return doClick(model, leftClick);
- } else {
- Point p = calc.tileToScreen(groundItem.getLocation());
- if (calc.pointOnScreen(p)) {
- mouse.move(p);
- if (calc.pointOnScreen(p)) {
- mouse.click(leftClick);
- return true;
- } else {
- p = calc.tileToScreen(groundItem.getLocation());
- if (calc.pointOnScreen(p)) {
- mouse.move(p);
- mouse.click(leftClick);
- return true;
- }
- }
- }
- return false;
- }
- }
- /**
- * Left clicks the RSModel.
- *
- * @param model
- * the RSModel
- * @return true if clicked.
- */
- public boolean doClick(RSModel model) {
- return doClick(model, true);
- }
- /**
- * Clicks the RSModel.
- *
- * @param model
- * the RSModel
- * @param leftClick
- * if true it left clicks.
- * @return true if clicked.
- */
- public boolean doClick(RSModel model, boolean leftClick) {
- if (model != null && model.getPointOnScreen() != null) {
- Point modelPoint = getPointOnModel(model);
- if (modelPoint != null) {
- mouse.setSpeed(mouseSpeed.randomLinearDistribution());
- mouse.move(modelPoint);
- mouse.click(leftClick);
- return true;
- }
- }
- return false;
- }
- /**
- * Left-clicks the object.
- *
- * @param object
- * The RSObject
- * @return <tt>true</tt> if clicked.
- */
- public boolean doClick(RSObject object) {
- return doClick(object, true);
- }
- /**
- * Clicks the object.
- *
- * @param object
- * The RSObject
- * @param left
- * <tt>true</tt> to left-click; <tt>false</tt> to right-click.
- * @return <tt>true</tt> if clicked.
- */
- public boolean doClick(RSObject object, boolean leftClick) {
- RSModel model = object.getModel();
- if (model != null) {
- return doClick(model, leftClick);
- } else {
- Point p = calc.tileToScreen(object.getLocation());
- if (calc.pointOnScreen(p)) {
- mouse.move(p);
- if (calc.pointOnScreen(p)) {
- mouse.click(leftClick);
- return true;
- } else {
- p = calc.tileToScreen(object.getLocation());
- if (calc.pointOnScreen(p)) {
- mouse.move(p);
- mouse.click(leftClick);
- return true;
- }
- }
- }
- return false;
- }
- }
- /**
- * Moves the mouse over the character.
- *
- * @param character
- * The RSCharacter
- * @return <tt>true</tt> if the mouse was moved.
- */
- public boolean doHover(RSCharacter character) {
- RSModel model = character.getModel();
- if (model != null) {
- return doHover(model);
- } else {
- Point p = calc.tileToScreen(character.getLocation());
- if (calc.pointOnScreen(p)) {
- mouse.move(p);
- return true;
- }
- }
- return false;
- }
- /**
- * Moves the mouse over the Ground Item.
- *
- * @param groundItem
- * The RSGroundItem
- * @return <tt>true</tt> if the mouse was moved.
- */
- public boolean doHover(RSGroundItem groundItem) {
- RSModel model = groundItem.getModel();
- if (model != null) {
- return doHover(model);
- } else {
- Point p = calc.tileToScreen(groundItem.getLocation());
- if (calc.pointOnScreen(p)) {
- mouse.move(p);
- return true;
- }
- }
- return false;
- }
- /**
- * Moves the mouse onto the RSModel.
- *
- * @param model
- * The RSModel
- */
- public boolean doHover(RSModel model) {
- if (model != null && model.getPointOnScreen() != null) {
- Point modelPoint = getPointOnModel(model);
- if (modelPoint != null) {
- mouse.setSpeed(mouseSpeed.randomLinearDistribution());
- mouse.move(modelPoint);
- return true;
- }
- }
- return false;
- }
- /**
- * Moves the mouse over the object.
- *
- * @param object
- * The RSObject
- * @return <tt>true</tt> if the mouse was moved.
- */
- public boolean doHover(RSObject object) {
- RSModel model = object.getModel();
- if (model != null) {
- return doHover(model);
- } else {
- Point p = calc.tileToScreen(object.getLocation());
- if (calc.pointOnScreen(p)) {
- mouse.move(p);
- return true;
- }
- }
- return false;
- }
- }
- /**
- * Used to format data into more conventional formats
- *
- * @author Equinox_
- *
- */
- public static class PaintFormatter {
- /**
- * Converts an array of strings into one string, using commas and 'and' <br>
- * <br>
- * Examples: <br>
- * {"option1"} returns "option1"<br>
- * {"option1","option2"} returns "option1 and option2"<br>
- * {"op1","op2","op3"} returns "op1, op2, and op3"<br>
- * <br>
- *
- * @param list
- * The array of strings making up the list.
- * @return The properly formatted string
- */
- public static String formatList(String[] list) {
- String s = "";
- if (list != null)
- if (list.length == 2) {
- s = list[0] + " and " + list[1];
- } else if (list.length > 2) {
- for (int i = 0; i < list.length - 1; i++)
- s += list[i] + ", ";
- s += "and " + list[list.length - 1];
- } else if (list.length == 1)
- s = list[0];
- return s;
- }
- /**
- * Formats a specified amount into thousands, millions or billions, then
- * adds the proper suffix
- *
- * @param money
- * the amount of money
- * @return the formatted string
- */
- public static String getFormattedMoney(long money) {
- /*
- * String suffix = ""; int t = 1; if (money >= 10000) { t *= 1000;
- * suffix = "K"; } if (money / t > 10000) { t *= 1000; suffix = "M"; }
- * if (money / t > 10000) { t *= 1000; suffix = "B"; } return
- * String.valueOf((money / t)) + suffix;
- */
- return new DecimalFormat("###,###,###,###,###,###").format(money);
- }
- /**
- * Converts the milliseconds to DD:HH:MM:SS with the days optional.
- *
- * @param timeMillis
- * the number of milliseconds
- * @return the properly formatted time as a String
- */
- public static String getFormattedTime(final long timeMillis) {
- return getFormattedTime(timeMillis, ":", false);
- }
- /**
- * Formats time to DD:HH:MM:SS:MSMS with days and millis optional
- *
- * @param timeMillis
- * long milliseconds of time
- * @param sep
- * String seperation character
- * @param millisInc
- * boolean include milliseconds
- * @return
- */
- public static String getFormattedTime(final long timeMillis, String sep,
- boolean millisInc) {
- long millis = timeMillis;
- final long days = millis / (24 * 1000 * 60 * 60);
- millis -= days * (24 * 1000 * 60 * 60);
- final long hours = millis / (1000 * 60 * 60);
- millis -= hours * 1000 * 60 * 60;
- final long minutes = millis / (1000 * 60);
- millis -= minutes * 1000 * 60;
- final long _seconds = millis / 1000;
- millis -= _seconds * 1000;
- String dayString = String.valueOf(days);
- String hoursString = String.valueOf(hours);
- String minutesString = String.valueOf(minutes);
- String secondsString = String.valueOf(_seconds);
- if (hours < 10) {
- hoursString = 0 + hoursString;
- }
- if (minutes < 10) {
- minutesString = 0 + minutesString;
- }
- if (_seconds < 10) {
- secondsString = 0 + secondsString;
- }
- String s = "";
- if (days > 0)
- s = dayString + sep;
- s += hoursString + sep + minutesString + sep + secondsString;
- if (millisInc)
- s += sep + String.valueOf(millis);
- return s;
- }
- /**
- * Converts the first letter of every word to uppercase, and the rest
- * lowercase.
- *
- * @param s
- * The input String
- * @return the properly formatted string
- */
- public static String properCaseAll(String s) {
- String[] words = s.split(" ");
- String result = "";
- for (int i = 0; i < words.length; i++) {
- String f = words[i].substring(0, 1).toUpperCase();
- words[i] = f + words[i].substring(1).toLowerCase();
- result += " " + words[i];
- }
- return result.substring(1);
- }
- /**
- * Capitalizes the first letter of every sentence, with every other letter
- * lowercase.
- *
- * @param s
- * The input string
- * @return The properly formatted String
- */
- public static String properCaseFirst(String s) {
- String[] sentences = new String[] { s };
- if (s.contains("."))
- sentences = s.split(".");
- String result = "";
- for (int i = 0; i < sentences.length; i++) {
- String f = sentences[i].substring(0, 1).toUpperCase();
- sentences[i] = f + sentences[i].substring(1).toLowerCase();
- result += " " + sentences[i];
- }
- return result.substring(1);
- }
- }
- /**
- * Represents a PaintMenu
- *
- * @author Equinox_
- *
- */
- public static class PaintMenu {
- // Images
- public Map<String, Image> icons = new HashMap<String, Image>();
- public void putImage(String name, Image img) {
- icons.put(name.toLowerCase(), img);
- }
- public Image getImage(String name) {
- if (icons.containsKey(name.toLowerCase()))
- return icons.get(name.toLowerCase());
- return null;
- }
- public long startTime;
- // End Images
- final int padding = 1;
- Point location;
- PaintStyle style;
- List<PaintMenuItem> components = new ArrayList<PaintMenuItem>();
- boolean[] validCache;
- public Anchor anchor = Anchor.UP_RIGHT;
- boolean showAllPopups;
- PaintMenuPopUp visiblePopup = null;
- public Point mouseLoc = new Point(-1, -1);
- List<MenuMouseListener> mouseListeners;
- LineListener defaultLineListener;
- private FlowType flowType = FlowType.HORIZONTAL;
- public Rectangle bounds = new Rectangle(4,4,512,334);
- public FontRenderContext frc = new FontRenderContext(new AffineTransform(),
- false, false);
- int absX, absY, width, height;
- /**
- * Constructs a PaintMenu using the provided PaintInterface, Location,
- * Anchor, and the GameScreen as the bounds
- *
- * @param parent
- * PaintInterface
- * @param location
- * Point
- * @param anchor
- * Anchor
- */
- public PaintMenu(PaintStyle paintStyle, Anchor anchor) {
- this.style = paintStyle;
- this.location = getLocation();
- this.anchor = anchor;
- startTime = System.currentTimeMillis();
- }
- public Point getLocation() {
- Point loc = bounds.getLocation();
- if (anchor.name().contains("DOWN"))
- loc.y += bounds.getHeight();
- if (anchor.name().contains("RIGHT"))
- loc.x += bounds.getWidth();
- return loc;
- }
- /**
- * Sets the FlowType and recompiles the menu
- *
- * @param flowType
- * FlowType
- */
- public void setFlowType(FlowType flowType) {
- this.flowType = flowType;
- this.compile();
- }
- /**
- * Gets the FlowType
- *
- * @return FlowType
- */
- public FlowType getFlowType() {
- return flowType;
- }
- /**
- * Toggles the showAllPopups state
- * */
- public void toggleShowAll() {
- showAllPopups = !showAllPopups;
- }
- /**
- * Constructs a PaintMenu using the provided parent and location, assuming
- * Anchor.UP_LEFT
- *
- * @param parent
- * PaintInterface
- * @param location
- * Point
- */
- public PaintMenu(PaintStyle style) {
- this(style, Anchor.UP_LEFT);
- }
- /**
- * Adds the specified PaintMenu item
- *
- * @param i
- * MenuItem
- */
- public void add(PaintMenuItem i) {
- i.setIndex(components.size());
- components.add(i);
- compile();
- validCache = new boolean[components.size()];
- }
- /**
- * Compiles this menu
- */
- public void compile() {
- location = getLocation();
- absX = getAbsX();
- absY = getAbsY();
- width = getWidth();
- height = getHeight();
- for (int i = 0; i < components.size(); i++)
- if (components.get(i).isValid())
- components.get(i).compile();
- absX = getAbsX();
- absY = getAbsY();
- width = getWidth();
- height = getHeight();
- }
- /**
- * Gets position x based on the menu's anchor
- *
- * @return int
- */
- public int getAbsX() {
- if (anchor.name().contains("LEFT"))
- return location.x;
- else
- return location.x - getWidth();
- }
- /**
- * Gets position y based on the menu's anchor
- *
- * @return int
- */
- public int getAbsY() {
- if (anchor.name().contains("UP"))
- return location.y;
- else
- return location.y - getHeight();
- }
- /**
- * Gets the maximum width of this PaintMenu using the menu's FlowType
- *
- * @return int
- */
- public int getWidth() {
- if (flowType.equals(FlowType.HORIZONTAL)) {
- int width = padding * components.size();
- for (PaintMenuItem m : components)
- if (m.bounds != null && m.isValid())
- width += m.bounds.width;
- return width + padding;
- } else {
- int max = Integer.MIN_VALUE;
- for (PaintMenuItem m : components)
- if (m.bounds != null && m.isValid())
- if (max < m.bounds.width)
- max = (int) m.bounds.width;
- return max + (2 * padding);
- }
- }
- /**
- * Gets the maximum height of this PaintMenu based of FlowType
- *
- * @return int
- */
- public int getHeight() {
- if (flowType.equals(FlowType.HORIZONTAL)) {
- int max = Integer.MIN_VALUE;
- for (PaintMenuItem m : components)
- if (m.bounds != null && m.isValid())
- if (max < m.bounds.height)
- max = (int) m.bounds.height;
- return max + (2 * padding);
- } else {
- int height = 0;
- for (PaintMenuItem m : components)
- if (m.bounds != null && m.isValid())
- height += m.bounds.height + padding;
- return height + padding;
- }
- }
- /**
- * Gets the current bounds of this menu's components, excluding popups, with
- * rounded corners if specified
- *
- * @param rounded
- * boolean
- * @return RoundRectangle2D.Float
- */
- public RoundRectangle2D.Float getArea(boolean rounded) {
- float round = rounded ? style.roundCorner + 1 : 0;
- return new RoundRectangle2D.Float(absX, absY, width, height, round,
- round);
- }
- /**
- * Gets the bounds of the PaintMenu and the popups.
- *
- * @return Rectangle
- */
- public Rectangle getBoundsFull() {
- RoundRectangle2D r1 = getArea(false);
- RoundRectangle2D r2 = visiblePopup != null ? visiblePopup.bkg
- : getArea(false);
- int x = (int) Math.min(r1.getX(), r2.getX());
- int y = (int) Math.min(r1.getY(), r2.getY());
- int width = (int) Math.max(r1.getX() + r1.getWidth(),
- r2.getX() + r2.getWidth())
- - x;
- int height = (int) Math.max(r1.getX() + r1.getHeight(),
- r2.getX() + r2.getHeight())
- - y;
- return new Rectangle(x, y, width, height);
- }
- /**
- * Renders the PaintMenu to the specified Graphics object using the provided
- * mouse location for any popups
- *
- * @param g
- * Graphics2D
- * @param mouseLoc
- * Point
- */
- public void render(Graphics2D g, Point mouseLoc) {
- boolean compile = false;
- if (validCache == null || components.size() != validCache.length) {
- validCache = new boolean[components.size()];
- compile = true;
- }
- for (int i = 0; i < components.size(); i++) {
- Boolean valid = components.get(i).isValid();
- if (!valid.equals(validCache[i]))
- compile = true;
- validCache[i] = valid;
- }
- if (compile)
- compile();
- g.setColor(style.bgColor);
- g.fill(getArea(true));
- PaintMenuPopUp overPopup = null;
- if (showAllPopups)
- overPopup = getAllPopups(true, "tools");
- for (PaintMenuItem m : components) {
- if (m.isValid()) {
- m.render(g);
- if (overPopup == null
- && m.getMenuBounds().contains(mouseLoc)
- || (m.getPopup.getName().equalsIgnoreCase(
- visiblePopup != null ? visiblePopup.name : "") && rectangleContainsApprox(
- visiblePopup.bkg, mouseLoc))) {
- overPopup = m.getPopUp();
- }
- }
- }
- if (overPopup != null)
- overPopup.render(g);
- visiblePopup = overPopup;
- }
- /**
- * Check if the specified point is within 1 point of the Rectangle
- *
- * @param r
- * RoundRectangle2D
- * @param p
- * Point
- * @return boolean contains
- */
- public boolean rectangleContainsApprox(RoundRectangle2D r, Point p) {
- for (int oX = -1; oX <= 1; oX++)
- for (int oY = -1; oY <= 1; oY++)
- if (r.contains(new Point(p.x + oX, p.y + oY)))
- return true;
- return false;
- }
- /**
- * Gets all popups in frontToBack or backToFront order and excluding
- * specified names
- *
- * @param rightToLeft
- * boolean
- * @param excludeItems
- * String...
- * @return MenuPopUp
- */
- public PaintMenuPopUp getAllPopups(boolean backToFront,
- String... excludeItems) {
- Map<String, String> lines = new HashMap<String, String>();
- if (components.size() > 0)
- if (backToFront)
- outer: for (int i = components.size() - 1; i >= 0; i--) {
- if (!components.get(i).isValid())
- continue outer;
- for (String subS : excludeItems)
- if (components.get(i).name.equalsIgnoreCase(subS))
- continue outer;
- if (components.get(i).isValid()) {
- PaintMenuPopUp sub = components.get(i).getPopUp();
- if (sub != null)
- for (String line : sub.lines)
- lines.put(getLineTag(line).toLowerCase(), line);
- }
- }
- else
- outer: for (int i = 0; i < components.size(); i++) {
- for (String subS : excludeItems)
- if (components.get(i).name.equalsIgnoreCase(subS))
- continue outer;
- PaintMenuPopUp sub = components.get(i).getPopUp();
- if (sub != null)
- for (String line : sub.lines)
- lines.put(getLineTag(line).toLowerCase(), line);
- }
- String[] array = new String[lines.size()];
- PaintMenuPopUp p = new PaintMenuPopUp(lines.values().toArray(array),
- "allpopups");
- p.setParent(components.get(components.size() - 1));
- return p;
- }
- /**
- * Gets the data tag of a line
- *
- * @param line
- * the line String
- * @return the tag
- */
- public String getLineTag(String line) {
- if (line.contains(":"))
- return line.split(":")[0];
- else
- return line;
- }
- /**
- * Gets a proggie as a BufferedImage
- *
- * @return BufferedImage proggie
- */
- public BufferedImage getProggie() {
- String[] lines = getAllPopups(true, "tools").lines;
- Color color = style.FONT_COLOR;
- Font font = style.FONT;
- float line_height = font.getLineMetrics(lines[0], frc).getHeight();
- int width = 0;
- for (String line : lines)
- if (font.getStringBounds(line, frc).getWidth() > width)
- width = (int) font.getStringBounds(line, frc).getWidth();
- int height = (int) (lines.length * line_height);
- width += style.roundCorner + 2;
- height += style.roundCorner + 2;
- RoundRectangle2D.Float bkg = new RoundRectangle2D.Float(0, 0, width,
- height, style.roundCorner > 0 ? style.roundCorner + 1 : 0,
- style.roundCorner > 0 ? style.roundCorner + 1 : 0);
- RoundRectangle2D.Float fg = new RoundRectangle2D.Float(
- (float) bkg.getX() + 1, (float) bkg.getY() + 1, width - 2,
- height - 2, style.roundCorner, style.roundCorner);
- Rectangle txtBounds = new Rectangle(
- (int) (fg.getX() + (style.roundCorner / 2)),
- (int) (fg.getY() + (style.roundCorner / 2)), (int) (width
- - style.roundCorner - 2), (int) (height
- - style.roundCorner - 2));
- BufferedImage bImg = new BufferedImage(width, height,
- BufferedImage.TYPE_INT_ARGB);
- Graphics2D g = (Graphics2D) bImg.getGraphics();
- g.setColor(style.bgColor);
- g.fill(bkg);
- g.setColor(style.fgColor);
- g.fill(fg);
- g.setFont(font);
- g.setColor(color);
- for (int i = 0; i < lines.length; i++)
- g.drawString(lines[i], txtBounds.x, ((i + 1) * (line_height))
- + txtBounds.y);
- return bImg;
- }
- /**
- * Saves a progress report to the specified dir, proggie name (without
- * extension), and logger.
- *
- * @param dir
- * @param proggieName
- * @param log
- */
- public void saveProggie(String dirPath, String proggieName, Logger log) {
- File dir = new File(dirPath);
- try {
- if (!(dir.isDirectory() || dir.mkdirs()))
- throw new Exception("Error ceating screenshots directory!");
- File proggie = getFile(dir, proggieName, ".png");
- ImageIO.write(this.getProggie(), "png", proggie);
- log.info("Saved proggie!");
- log.info(proggie.getAbsolutePath());
- return;
- } catch (Exception e) {
- log.severe("Failed to save proggie: " + e.getMessage());
- }
- }
- /**
- * Gets a file for writing to in the specified dir as File, and name & ext.
- * Appending (copy number) to the name if needed.
- *
- * @param dir
- * @param name
- * @param ext
- * @return
- */
- public File getFile(File dir, String name, String ext) {
- try {
- int copy = 0;
- while (new File(dir, name + (copy > 0 ? ("(" + copy + ")") : "")
- + ext).exists())
- copy++;
- return new File(dir, name + (copy > 0 ? ("(" + copy + ")") : "")
- + ext);
- } catch (Exception e) {
- return new File(dir, name + ext);
- }
- }
- /**
- * Adds the specified mouse listener
- *
- * @param listen
- * MouseListen
- */
- public void addMouseListener(MenuMouseListener listen) {
- if (mouseListeners == null)
- mouseListeners = new ArrayList<MenuMouseListener>();
- mouseListeners.add(listen);
- }
- /**
- * Sets the default line listener
- *
- * @param listen
- * LineListener
- */
- public void setDefaultLineListener(LineListener listen) {
- defaultLineListener = listen;
- }
- /**
- * Fires the MouseEvent in all containing children and this
- *
- * @param e
- * MouseEvent
- */
- public void fireMouseEvent(MouseEvent e) {
- if (getArea(true).contains(e.getPoint()))
- if (mouseListeners != null)
- for (MenuMouseListener m : mouseListeners)
- m.MouseAction(e);
- for (PaintMenuItem m : components)
- if (m.bounds != null)
- if (m.bounds.contains(e.getPoint()))
- m.fireMouseEvent(e);
- if (visiblePopup != null)
- visiblePopup.fireMouseEvent(e);
- }
- }
- /**
- * A class representing a mouse over button on the parent menu
- *
- * @author Equinox_
- *
- */
- public static class PaintMenuButton extends PaintMenuItem {
- final static int width = 30;
- final static int height = 30;
- String imageIcon;
- /**
- * Constructs a button using the specified name, parent, imageIcon, getPopup
- * method, and validation method.
- *
- * @param name
- * String
- * @param parent
- * Menu
- * @param imageIcon
- * String
- * @param getPopUp
- * GetPopup
- * @param validation
- * IsValid
- */
- public PaintMenuButton(PaintMenu parent, String name, String imageIcon, GetPopup getPopUp,
- IsValid validation) {
- super(parent, name, getPopUp, width, height, validation);
- this.imageIcon = imageIcon.toLowerCase();
- }
- /**
- * Constructs a button using the specified name, parent, imageIcon, and
- * validation method.
- *
- * @param name
- * String
- * @param parent
- * Menu
- * @param imageIcon
- * String
- * @param validation
- * IsValid
- */
- public PaintMenuButton(PaintMenu parent, String name, String imageIcon, IsValid validation) {
- this(parent, name, imageIcon, null, validation);
- }
- /**
- * Constructs a button using the specified name, parent, and validation
- * method.
- *
- * @param name
- * String
- * @param parent
- * Menu
- * @param validation
- * IsValid
- */
- public PaintMenuButton(PaintMenu parent, String name, IsValid validation) {
- this(parent, name, "", null, validation);
- }
- /**
- * Constructs a button using the specified name, parent, imageIcon, and
- * getPopup method.
- *
- * @param name
- * String
- * @param parent
- * Menu
- * @param imageIcon
- * String
- * @param getPopUp
- * GetPopup
- */
- public PaintMenuButton(PaintMenu parent, String name, String imageIcon, GetPopup getPopUp) {
- super(parent, name, getPopUp, width, height, new IsValid() {
- public boolean isValid() {
- return true;
- }
- });
- this.imageIcon = imageIcon.toLowerCase();
- }
- /**
- * Constructs a button using the specified name, parent, and imageIcon.
- *
- * @param name
- * String
- * @param parent
- * Menu
- * @param imageIcon
- * String
- */
- public PaintMenuButton(PaintMenu parent, String name, String imageIcon) {
- this(parent, name, imageIcon, null, new IsValid() {
- public boolean isValid() {
- return true;
- }
- });
- }
- /**
- * Constructs a button using the specified name and parent.
- *
- * @param name
- * String
- * @param parent
- * Menu
- */
- public PaintMenuButton(PaintMenu parent, String name) {
- this(parent, name, "", null, new IsValid() {
- public boolean isValid() {
- return true;
- }
- });
- }
- /**
- * Renders this MenuButton to the given Graphics2D context
- */
- public void render(Graphics2D g) {
- // Compiling
- if (parent.icons.containsKey(imageIcon))
- if (parent.icons.get(imageIcon) != null)
- if (!parent.icons.containsKey("Button-" + imageIcon)) {
- // Scale the image
- int width = (int) (bounds.width - (parent.style.roundCorner));
- int height = (int) (bounds.height - (parent.style.roundCorner));
- int hints = Image.SCALE_FAST;
- parent.icons.put(
- "Button-" + imageIcon,
- parent.icons.get(imageIcon).getScaledInstance(
- width, height, hints));
- }
- g.setColor(parent.style.fgColor);
- g.fill(bounds);
- if (parent.icons.containsKey("Button-" + imageIcon))
- if (parent.icons.get("Button-" + imageIcon) != null)
- g.drawImage(parent.icons.get("Button-" + imageIcon),
- (int) (bounds.x + (parent.style.roundCorner / 2)),
- (int) (bounds.y + (parent.style.roundCorner / 2)), null);
- }
- boolean isValid() {
- return true;
- }
- }
- /**
- * An abstract class representing PaintMenuItems
- *
- * @author Equinox_
- *
- */
- public static abstract class PaintMenuItem {
- final GetPopup getPopup;
- public PaintMenu parent = null;
- RoundRectangle2D.Float bounds;
- int index;
- final int width;
- final int height;
- List<MenuMouseListener> mouseListeners;
- final String name;
- IsValid validation;
- /**
- * Constructs a PaintMenuItem with the given name, parent, getPopup method,
- * width, height, and validation method.
- *
- * @param parent
- * @param name
- * String
- * @param parent
- * Menu
- * @param getPopup
- * GetPopup
- * @param width
- * int
- * @param height
- * int
- * @param validation
- * IsValid
- */
- public PaintMenuItem(PaintMenu parent, String name, GetPopup getPopup,
- int width, int height, IsValid validation) {
- this.name = name;
- this.height = height;
- this.width = width;
- this.getPopup = getPopup;
- this.parent = parent;
- this.bounds = new RoundRectangle2D.Float(0, 0, width, height,
- parent.style.roundCorner, parent.style.roundCorner);
- this.validation = validation;
- }
- /**
- * Constructs a PaintMenuItem with the given name, parent, width, height,
- * and validation method.
- *
- * @param parent
- * @param name
- * String
- * @param parent
- * Menu
- * @param width
- * int
- * @param height
- * int
- * @param validation
- * IsValid
- */
- public PaintMenuItem(PaintMenu parent, String name, int width, int height,
- IsValid validation) {
- this(parent, name, null, width, height, validation);
- }
- /**
- * sets this item's index
- *
- * @param idx
- * int
- */
- public void setIndex(int idx) {
- this.index = idx;
- }
- /**
- * renders this item to the given Graphics2D
- *
- * @param g
- * Graphics2D
- */
- abstract void render(Graphics2D g);
- /**
- * Checks if this item is valid.
- *
- * @return boolean isValid
- */
- boolean isValid() {
- return validation.isValid();
- }
- /**
- * Compiles this item
- */
- public void compile() {
- if (parent != null) {
- this.bounds = new RoundRectangle2D.Float(0, 0, width, height,
- parent.style.roundCorner, parent.style.roundCorner);
- bounds.x = getX();
- bounds.y = getY();
- }
- }
- /**
- * Gets the offset from upper left of parent depending on parent's FlowType
- *
- * @return int offsetX
- */
- public int getOffX() {
- if (parent.getFlowType().equals(FlowType.HORIZONTAL)) {
- int x = 1;
- for (int i = 0; i < index; i++)
- if (parent.components.get(i).isValid())
- x += 1 + parent.components.get(i).bounds.width;
- return x;
- }
- if (parent.getWidth() > bounds.width)
- return (int) (parent.getWidth() / 2 - bounds.width / 2);
- return 1;
- }
- /**
- * Gets the bounds of this item in the menu, including extra space.
- *
- * @return Rectangle PaintMenu bounds
- */
- public Rectangle getMenuBounds() {
- if (parent.getFlowType().equals(FlowType.VERTICAL))
- return new Rectangle(parent.absX, (int) bounds.y, parent.width,
- (int) bounds.height);
- else
- return new Rectangle((int) bounds.x, parent.absY,
- (int) bounds.width, parent.height);
- }
- /**
- * Gets the offset from upper left of parent depending on parent's FlowType
- *
- * @return int offsetX
- */
- public int getOffY() {
- if (parent.getFlowType().equals(FlowType.VERTICAL)) {
- int y = 1;
- for (int i = 0; i < index; i++)
- if (parent.components.get(i).isValid())
- y += 1 + parent.components.get(i).bounds.height;
- return y;
- }
- if (parent.getHeight() > bounds.height)
- return (int) (parent.getHeight() / 2 - bounds.height / 2);
- return 1;
- }
- /**
- * Gets the absolute x
- *
- * @return int absolute x
- */
- public int getX() {
- int x = getOffX() + parent.absX;
- return x;
- }
- /**
- * Gets the absolute y
- *
- * @return int absolute y
- */
- public int getY() {
- int y = getOffY() + parent.absY;
- return y;
- }
- /**
- * Gets this item's popup
- *
- * @return MenuPopUp
- */
- public PaintMenuPopUp getPopUp() {
- if (getPopup != null) {
- PaintMenuPopUp m = getPopup.getPopUp();
- m.setParent(this);
- if (parent.defaultLineListener != null)
- m.addLineListener(parent.defaultLineListener);
- return m;
- }
- return null;
- }
- /**
- * Adds a mouselistener
- *
- * @param listen
- * MouseListen
- */
- public void addMouseListener(MenuMouseListener listen) {
- if (mouseListeners == null)
- mouseListeners = new ArrayList<MenuMouseListener>();
- mouseListeners.add(listen);
- }
- /**
- * Sends the mouse event to all of this item's listeners
- *
- * @param e
- * MouseEvent
- */
- public void fireMouseEvent(MouseEvent e) {
- if (mouseListeners != null && mouseListeners.size() > 0)
- for (MenuMouseListener m : mouseListeners)
- m.MouseAction(e);
- }
- }
- /**
- * A class representing the popups in the paint interface
- *
- * @author Equinox_
- *
- */
- public static class PaintMenuPopUp {
- private Font font;
- private Color color;
- private PaintStyle style;
- RoundRectangle2D bkg;
- public RoundRectangle2D fg;
- public Rectangle txtBounds;
- public final String name;
- public String[] lines;
- PaintMenuItem parent;
- int width;
- int height;
- List<LineListener> lineListeners;
- /**
- * Creates a popup using the provided array of strings making up the lines
- * and name
- *
- * @param lines
- * as String[]
- * @param name
- * as String
- */
- public PaintMenuPopUp(String[] lines, String name) {
- this.name = name;
- this.lines = lines;
- }
- /**
- * Set this popup's parent and compiles locations
- *
- * @param parent
- * MenuItem
- */
- public void setParent(PaintMenuItem parent) {
- this.parent = parent;
- this.style = parent.parent.style;
- // Calc dimensions
- color = name.equals("tools") ? style.TOOLS_FONT_COLOR
- : style.FONT_COLOR;
- font = name.equals("tools") ? style.TOOLS_FONT : style.FONT;
- float line_height = font.getLineMetrics(lines[0], parent.parent.frc).getHeight();
- width = 0;
- for (String line : lines)
- if (font.getStringBounds(line, parent.parent.frc).getWidth() > width)
- width = (int) font.getStringBounds(line, parent.parent.frc).getWidth();
- height = (int) (lines.length * line_height);
- width += style.roundCorner + 2;
- height += style.roundCorner + 2;
- int halfPadding = (parent.parent.padding / 2);
- int x = 0;
- int y = 0;
- if (parent.parent.getFlowType().equals(FlowType.HORIZONTAL)) {
- if (parent.bounds.y - height - parent.parent.padding > 0) {
- // Above
- x = (int) (parent.bounds.x - width + parent.bounds.width + halfPadding);
- if (x < 0)
- x = (int) (parent.bounds.x - halfPadding);
- y = (int) (parent.parent.absY - height);
- } else {
- // Below
- x = (int) (parent.bounds.x - halfPadding);
- if (x + width > parent.parent.bounds.width)
- x = (int) (parent.bounds.x - halfPadding - width);
- y = (int) (parent.parent.absY + parent.parent.getHeight());
- }
- } else {
- // Vertical
- if (parent.parent.absX - width > 0) {
- // Left
- x = (int) (parent.parent.absX - width);
- if (parent.bounds.y - height + halfPadding
- + parent.bounds.height > 0)
- y = (int) (parent.bounds.y - height + halfPadding + parent.bounds.height);
- else
- y = (int) (parent.bounds.y - halfPadding);
- } else {
- // Right
- x = (int) (parent.parent.absX + parent.parent.getWidth());
- if (parent.bounds.y - height + halfPadding
- + parent.bounds.height > 0)
- y = (int) (parent.bounds.y - height + halfPadding + parent.bounds.height);
- else
- y = (int) (parent.bounds.y - halfPadding);
- }
- }
- bkg = new RoundRectangle2D.Float(x, y, width, height,
- style.roundCorner > 0 ? style.roundCorner + 1 : 0,
- style.roundCorner > 0 ? style.roundCorner + 1 : 0);
- fg = new RoundRectangle2D.Float((float) bkg.getX() + 1,
- (float) bkg.getY() + 1, width - 2, height - 2,
- style.roundCorner, style.roundCorner);
- txtBounds = new Rectangle((int) (fg.getX() + (style.roundCorner / 2)),
- (int) (fg.getY() + (style.roundCorner / 2)), (int) (width
- - style.roundCorner - 2), (int) (height
- - style.roundCorner - 2));
- }
- /**
- * Paints this popup to using the provided Graphics2D in relation to it's
- * parent PaintInterface
- *
- * @param g
- * as Graphics2D
- */
- public void render(Graphics2D g) {
- g.setColor(style.bgColor);
- g.fill(bkg);
- g.setColor(style.fgColor);
- g.fill(fg);
- float line_height = (txtBounds.height - 4) / lines.length;
- g.setFont(font);
- g.setColor(color);
- for (int i = 0; i < lines.length; i++) {
- if (new Rectangle(txtBounds.x,
- (int) ((i * (line_height)) + txtBounds.y), txtBounds.width,
- (int) line_height).contains(parent.parent.mouseLoc)
- && hasAction(lines[i])) {
- g.setColor(style.highlightColor);
- g.fill(new Rectangle(txtBounds.x,
- (int) ((i * (line_height)) + 2 + txtBounds.y),
- txtBounds.width, (int) line_height));
- }
- g.setColor(color);
- g.drawString(lines[i], txtBounds.x, ((i + 1) * (line_height))
- + txtBounds.y);
- }
- }
- boolean hasAction(String line) {
- if (lineListeners != null)
- for (LineListener l : lineListeners)
- if (l.hasAction(line))
- return true;
- return false;
- }
- /**
- * Adds the specified line listener
- *
- * @param l
- * LineListener
- */
- public void addLineListener(LineListener l) {
- if (lineListeners == null)
- lineListeners = new ArrayList<LineListener>();
- this.lineListeners.add(l);
- }
- /**
- * fires the specified mouse event using this popup's line listeners
- *
- * @param e
- * MouseEvent
- */
- public void fireMouseEvent(MouseEvent e) {
- if (!bkg.contains(e.getPoint()) || lineListeners == null
- || lineListeners.size() == 0)
- return;
- int line_height = (txtBounds.height - 4) / lines.length;
- for (int i = 0; i < lines.length; i++) {
- Rectangle stringRect = new Rectangle(txtBounds.x,
- (i * (line_height)) + txtBounds.y, txtBounds.width,
- line_height);
- if (stringRect.contains(e.getPoint())) {
- for (LineListener lineListener : lineListeners)
- lineListener.fireEvent(e, lines[i]);
- return;
- }
- }
- }
- }
- /**
- * A class representing a progress bar in a menu
- *
- * @author Equinox_
- *
- */
- public static class PaintMenuProgressBar extends PaintMenuItem {
- final static int width = 150;
- final static int height = 30;
- final GetPercent getPercent;
- RoundRectangle2D.Double percent;
- Point textLoc;
- String prefix;
- /**
- * Constructs a MenuProgress bar using the specified name, parent,
- * getPercent method, text prefix, getPopup method, and validation method.
- *
- * @param name
- * String
- * @param parent
- * Menu
- * @param getPercent
- * GetPercent
- * @param prefix
- * String
- * @param getPopup
- * GetPopup
- * @param validation
- * IsValid
- */
- public PaintMenuProgressBar(PaintMenu parent, String name,
- GetPercent getPercent, String prefix, GetPopup getPopup,
- IsValid validation) {
- super(parent, name, getPopup, width, height, validation);
- this.getPercent = getPercent;
- this.prefix = prefix;
- percent = new RoundRectangle2D.Double(bounds.x, bounds.y, 0,
- bounds.height, bounds.arcwidth, bounds.archeight);
- compile();
- }
- /**
- * Renders this progress bar to the given Graphics context
- */
- public void render(Graphics2D g) {
- percent.width = (width / 100d) * getPercent.getPercent();
- g.setColor(parent.style.progressBarBG);
- g.fill(bounds);
- g.setColor(parent.style.progressBarFG);
- g.fill(percent);
- String perct = new DecimalFormat("00.00").format(getPercent
- .getPercent());
- if (perct.length() < 2)
- perct = "0" + perct;
- g.setFont(parent.style.FONT);
- g.setColor(parent.style.FONT_COLOR);
- g.drawString(prefix + ": " + perct + "%", textLoc.x, textLoc.y);
- }
- /**
- * Compiles this progress bar
- */
- public void compile() {
- super.compile();
- percent = new RoundRectangle2D.Double(bounds.x, bounds.y, 0,
- bounds.height, bounds.arcwidth, bounds.archeight);
- textLoc = new Point();
- textLoc.x = (int) bounds.getCenterX();
- textLoc.y = (int) bounds.getCenterY();
- textLoc.y += parent.style.FONT.getLineMetrics(prefix + ": 00.00%",
- parent.frc).getHeight() / 2f;
- textLoc.x -= parent.style.FONT.getStringBounds(prefix + ": 00.00%",
- parent.frc).getWidth() / 2f;
- }
- }
- public static class PaintMenuSkillProgressBar extends PaintMenuProgressBar {
- /**
- * Constructs a Skill Based Progress Bar based on a Next-Level status
- *
- * @param parent
- * Menu
- * @param SkillID
- * int
- * @param skills
- * Skills
- */
- public PaintMenuSkillProgressBar(final int SkillID,
- final Skills skills, final int startExp, final PaintMenu parent) {
- super(parent, "nextlvl" + Skills.SKILL_NAMES[SkillID],
- new GetPercent() {
- public double getPercent() {
- final int lvl = skills.getRealLevel(SkillID);
- if (lvl >= (SkillID == Skills.DUNGEONEERING ? 120 : 99))
- return 100;
- final double xpTotal = Skills.XP_TABLE[lvl + 1]
- - Skills.XP_TABLE[lvl];
- if (xpTotal == 0)
- return 100;
- final double xpDone = skills.getCurrentExp(SkillID)
- - Skills.XP_TABLE[lvl];
- double result = xpDone / xpTotal;
- if (result > 1)
- result = 1;
- if (result < 0)
- result = 1;
- return (result * 100d);
- }
- }, PaintFormatter.properCaseAll(Skills.SKILL_NAMES[SkillID])
- + " NL", new GetPopup() {
- public PaintMenuPopUp getPopUp() {
- long millis = Math.abs(System.currentTimeMillis()
- - parent.startTime);
- if (millis <= 0)
- millis = 1;
- long expGained = skills.getCurrentExp(SkillID)
- - startExp;
- long expPerHour = (expGained * 3600000l) / millis;
- String TTL = "No Exp Gained";
- if (expPerHour > 0)
- TTL = PaintFormatter
- .getFormattedTime((long) (((float) skills
- .getExpToNextLevel(SkillID))
- / ((float) expPerHour) * 3600000f));
- String skillName = PaintFormatter
- .properCaseAll(Skills.SKILL_NAMES[SkillID]);
- String[] lines = new String[4];
- lines[0] = skillName + " Exp gained: "
- + PaintFormatter.getFormattedMoney(expGained);
- lines[1] = skillName + " Exp per Hour: "
- + PaintFormatter.getFormattedMoney(expPerHour);
- lines[2] = skillName
- + " Exp 'till level: "
- + PaintFormatter.getFormattedMoney(skills
- .getExpToNextLevel(SkillID));
- lines[3] = "Time 'till " + skillName + " level: " + TTL;
- return new PaintMenuPopUp(lines, Skills.SKILL_NAMES[SkillID]
- + "nextlevel");
- }
- public String getName() {
- return Skills.SKILL_NAMES[SkillID] + "nextlevel";
- }
- }, new IsValid() {
- public boolean isValid() {
- final int lvl = skills.getRealLevel(SkillID);
- if (lvl >= (SkillID == Skills.DUNGEONEERING ? 120 : 99))
- return false;
- return skills.getCurrentExp(SkillID) > startExp;
- }
- });
- }
- /**
- * Constructs a Skill Based Progress Bar based on a set goal experience
- *
- * @param parent
- * Menu
- * @param SkillID
- * int
- * @param GoalEXP
- * int
- * @param skills
- * Skills
- */
- public PaintMenuSkillProgressBar(final PaintMenu parent, final int SkillID,
- final int GoalEXP, final Skills skills, final int startExp) {
- super(parent, "goalbar" + Skills.SKILL_NAMES[SkillID],
- new GetPercent() {
- public double getPercent() {
- double expTillGoalStart = GoalEXP - startExp;
- double expGained = skills.getCurrentExp(SkillID)
- - startExp;
- double result = expGained / expTillGoalStart;
- if (result > 1)
- result = 1;
- if (result < 0)
- result = 0;
- return (result * 100d);
- }
- }, PaintFormatter.properCaseAll(Skills.SKILL_NAMES[SkillID])
- + " Goal", new GetPopup() {
- public PaintMenuPopUp getPopUp() {
- long millis = Math.abs(System.currentTimeMillis()
- - parent.startTime);
- if (millis <= 0)
- millis = 1;
- long expGained = skills.getCurrentExp(SkillID)
- - startExp;
- long expPerHour = (expGained * 3600000l) / millis;
- int expTillGoal = (int) (GoalEXP - skills
- .getCurrentExp(SkillID));
- String TTG = "";
- int TTGunf = (int) ((expPerHour > 0) ? (((float) expTillGoal)
- / ((float) expPerHour) * 3600000f)
- : 0);
- if (TTGunf != 0)
- TTG = PaintFormatter.getFormattedTime(TTGunf);
- else
- TTG = "No exp gained";
- String[] lines = new String[6];
- String skillName = PaintFormatter
- .properCaseAll(Skills.SKILL_NAMES[SkillID]);
- lines[0] = skillName + " Goal Level: "
- + Skills.getLevelAt(GoalEXP);
- lines[1] = skillName + " Goal Exp: "
- + PaintFormatter.getFormattedMoney(GoalEXP);
- lines[2] = skillName + " Exp gained: "
- + PaintFormatter.getFormattedMoney(expGained);
- lines[3] = skillName + " Exp per Hour: "
- + PaintFormatter.getFormattedMoney(expPerHour);
- lines[4] = "Exp 'till " + skillName + " goal: "
- + PaintFormatter.getFormattedMoney(expTillGoal);
- lines[5] = "Time 'till " + skillName + " goal: " + TTG;
- return new PaintMenuPopUp(lines, Skills.SKILL_NAMES[SkillID]
- + "goalpopup");
- }
- public String getName() {
- return Skills.SKILL_NAMES[SkillID] + "goalpopup";
- }
- }, new IsValid() {
- public boolean isValid() {
- return skills.getCurrentExp(SkillID) > startExp;
- }
- });
- }
- }
- /**
- * Used to style the paint
- *
- * @author Equinox_
- *
- */
- public static class PaintStyle {
- public final Color FONT_COLOR = Color.BLACK;
- public final Font FONT = new Font("Arial", 1, 10)
- .deriveFont(Font.PLAIN);
- public final Font TOOLS_FONT = new Font("Arial", 1, 14)
- .deriveFont(Font.PLAIN);
- public final Color TOOLS_FONT_COLOR = Color.BLACK;
- public final float roundCorner = 7.5f;
- public final Color progressBarFG = new Color(0f, 1f, 0f, 1f);
- public final Color progressBarBG = new Color(.5f, .5f, .5f, 1f);
- public final Color bgColor = new Color(0f, 0f, 0f, 0.75f);
- final Color fgColor = new Color(.5f, .5f, .5f, 1f);
- final Color highlightColor = new Color(1f, 0f, 0f, 0.075f);
- }
- /**
- * A range class for randomized items
- *
- * @author Equinox_
- *
- */
- public static class Range {
- public int MAX;
- public int MIN;
- public Range() {
- MAX = 1;
- MIN = -1;
- }
- /**
- *
- * @param min
- * The inclusive lower bound
- * @param max
- * The inclusive upper bound
- */
- public Range(int min, int max) {
- MAX = Math.max(min, max) + 1;
- MIN = Math.min(min, max);
- }
- /**
- * Returns a linearly distributed pseudorandom integer.
- *
- * @return Random integer min <= n < max.
- */
- public int randomLinearDistribution() {
- return MIN + (MAX == MIN ? 0 : new Random().nextInt(MAX - MIN));
- }
- /**
- * Returns a normally distributed pseudorandom integer about a mean centered
- * between min and max with a calculated standard deviation.
- *
- * @return Random integer min <= n < max from the normal distribution
- * described by the parameters.
- */
- public int randomNormalDistribution() {
- int mean = MIN + (MAX - MIN) / 2;
- int rand;
- int sd = (MAX - MIN) / 3;
- do {
- rand = (int) (new Random().nextGaussian() * sd + mean);
- } while (rand < MIN || rand >= MAX);
- return rand;
- }
- /**
- * Returns a normally distributed pseudorandom integer about a mean centered
- * between min and max with a provided standard deviation.
- *
- * @param sd
- * The standard deviation. A higher value will increase the
- * probability of numbers further from the mean being returned.
- * @return Random integer min <= n < max from the normal distribution
- * described by the parameters.
- */
- public int randomNormalDistribution(int sd) {
- int mean = MIN + (MAX - MIN) / 2;
- int rand;
- do {
- rand = (int) (new Random().nextGaussian() * sd + mean);
- } while (rand < MIN || rand >= MAX);
- return rand;
- }
- public String toString() {
- return MIN + "-" + MAX;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment