Merge pull request #256 from sdburns1998/Cleanup

Cleanup
This commit is contained in:
Tyler Bochard
2019-05-15 22:39:36 -04:00
committed by GitHub
102 changed files with 5261 additions and 4477 deletions

View File

@@ -64,7 +64,7 @@ public class AntiDragOverlay extends Overlay
final net.runelite.api.Point mouseCanvasPosition = client.getMouseCanvasPosition(); final net.runelite.api.Point mouseCanvasPosition = client.getMouseCanvasPosition();
final Point mousePosition = new Point(mouseCanvasPosition.getX() - RADIUS, mouseCanvasPosition.getY() - RADIUS); final Point mousePosition = new Point(mouseCanvasPosition.getX() - RADIUS, mouseCanvasPosition.getY() - RADIUS);
final Rectangle bounds = new Rectangle(mousePosition.x, mousePosition.y, 2 * RADIUS, 2 * RADIUS); final Rectangle bounds = new Rectangle(mousePosition.x, mousePosition.y, 2 * RADIUS, 2 * RADIUS);
g.fillOval(bounds.x, bounds.y, bounds.height, bounds.width); g.fillOval(bounds.x, bounds.y, bounds.width, bounds.height);
return bounds.getSize(); return bounds.getSize();
} }

View File

@@ -30,14 +30,14 @@ package net.runelite.client.plugins.aoewarnings;
import java.time.Instant; import java.time.Instant;
import net.runelite.api.coords.LocalPoint; import net.runelite.api.coords.LocalPoint;
public class AoeProjectile class AoeProjectile
{ {
private final Instant startTime; private final Instant startTime;
private final LocalPoint targetPoint; private final LocalPoint targetPoint;
private final AoeProjectileInfo aoeProjectileInfo; private final AoeProjectileInfo aoeProjectileInfo;
private final int projectileLifetime; private final int projectileLifetime;
public AoeProjectile(Instant startTime, LocalPoint targetPoint, AoeProjectileInfo aoeProjectileInfo, int projectileLifetime) AoeProjectile(Instant startTime, LocalPoint targetPoint, AoeProjectileInfo aoeProjectileInfo, int projectileLifetime)
{ {
this.startTime = startTime; this.startTime = startTime;
this.targetPoint = targetPoint; this.targetPoint = targetPoint;
@@ -45,22 +45,22 @@ public class AoeProjectile
this.projectileLifetime = projectileLifetime; this.projectileLifetime = projectileLifetime;
} }
public Instant getStartTime() Instant getStartTime()
{ {
return startTime; return startTime;
} }
public LocalPoint getTargetPoint() LocalPoint getTargetPoint()
{ {
return targetPoint; return targetPoint;
} }
public AoeProjectileInfo getAoeProjectileInfo() AoeProjectileInfo getAoeProjectileInfo()
{ {
return aoeProjectileInfo; return aoeProjectileInfo;
} }
public int getProjectileLifetime() int getProjectileLifetime()
{ {
return projectileLifetime; return projectileLifetime;
} }

View File

@@ -33,22 +33,12 @@ import net.runelite.client.config.ConfigItem;
@ConfigGroup("aoe") @ConfigGroup("aoe")
public interface AoeWarningConfig extends Config public interface AoeWarningConfig extends Config
{ {
@ConfigItem(
keyName = "enabled",
name = "AoE Warnings Enabled",
description = "Configures whether or not AoE Projectile Warnings plugin is displayed",
position = 1
)
default boolean enabled()
{
return true;
}
@ConfigItem( @ConfigItem(
keyName = "outline", keyName = "outline",
name = "Display Outline", name = "Display Outline",
description = "Configures whether or not AoE Projectile Warnings have an outline", description = "Configures whether or not AoE Projectile Warnings have an outline",
position = 2 position = 1
) )
default boolean isOutlineEnabled() default boolean isOutlineEnabled()
{ {
@@ -59,7 +49,7 @@ public interface AoeWarningConfig extends Config
keyName = "fade", keyName = "fade",
name = "Fade Warnings", name = "Fade Warnings",
description = "Configures whether or not AoE Projectile Warnings fade over time", description = "Configures whether or not AoE Projectile Warnings fade over time",
position = 3 position = 2
) )
default boolean isFadeEnabled() default boolean isFadeEnabled()
{ {
@@ -70,7 +60,7 @@ public interface AoeWarningConfig extends Config
keyName = "lizardmanaoe", keyName = "lizardmanaoe",
name = "Lizardman Shamans", name = "Lizardman Shamans",
description = "Configures whether or not AoE Projectile Warnings for Lizardman Shamans is displayed", description = "Configures whether or not AoE Projectile Warnings for Lizardman Shamans is displayed",
position = 4 position = 3
) )
default boolean isShamansEnabled() default boolean isShamansEnabled()
{ {
@@ -92,7 +82,7 @@ public interface AoeWarningConfig extends Config
keyName = "icedemon", keyName = "icedemon",
name = "Ice Demon", name = "Ice Demon",
description = "Configures whether or not AoE Projectile Warnings for Ice Demon is displayed", description = "Configures whether or not AoE Projectile Warnings for Ice Demon is displayed",
position = 4 position = 5
) )
default boolean isIceDemonEnabled() default boolean isIceDemonEnabled()
{ {
@@ -103,7 +93,7 @@ public interface AoeWarningConfig extends Config
keyName = "vasa", keyName = "vasa",
name = "Vasa", name = "Vasa",
description = "Configures whether or not AoE Projectile Warnings for Vasa is displayed", description = "Configures whether or not AoE Projectile Warnings for Vasa is displayed",
position = 4 position = 6
) )
default boolean isVasaEnabled() default boolean isVasaEnabled()
{ {
@@ -114,7 +104,7 @@ public interface AoeWarningConfig extends Config
keyName = "tekton", keyName = "tekton",
name = "Tekton", name = "Tekton",
description = "Configures whether or not AoE Projectile Warnings for Tekton is displayed", description = "Configures whether or not AoE Projectile Warnings for Tekton is displayed",
position = 4 position = 7
) )
default boolean isTektonEnabled() default boolean isTektonEnabled()
{ {
@@ -125,7 +115,7 @@ public interface AoeWarningConfig extends Config
keyName = "vorkath", keyName = "vorkath",
name = "Vorkath", name = "Vorkath",
description = "Configures whether or not AoE Projectile Warnings for Vorkath are displayed", description = "Configures whether or not AoE Projectile Warnings for Vorkath are displayed",
position = 4 position = 7
) )
default boolean isVorkathEnabled() default boolean isVorkathEnabled()
{ {
@@ -136,7 +126,7 @@ public interface AoeWarningConfig extends Config
keyName = "galvek", keyName = "galvek",
name = "Galvek", name = "Galvek",
description = "Configures whether or not AoE Projectile Warnings for Galvek are displayed", description = "Configures whether or not AoE Projectile Warnings for Galvek are displayed",
position = 4 position = 8
) )
default boolean isGalvekEnabled() default boolean isGalvekEnabled()
{ {
@@ -147,7 +137,7 @@ public interface AoeWarningConfig extends Config
keyName = "gargboss", keyName = "gargboss",
name = "Gargoyle Boss", name = "Gargoyle Boss",
description = "Configs whether or not AoE Projectile Warnings for Dawn/Dusk are displayed", description = "Configs whether or not AoE Projectile Warnings for Dawn/Dusk are displayed",
position = 4 position = 9
) )
default boolean isGargBossEnabled() default boolean isGargBossEnabled()
{ {
@@ -158,7 +148,7 @@ public interface AoeWarningConfig extends Config
keyName = "vetion", keyName = "vetion",
name = "Vet'ion", name = "Vet'ion",
description = "Configures whether or not AoE Projectile Warnings for Vet'ion are displayed", description = "Configures whether or not AoE Projectile Warnings for Vet'ion are displayed",
position = 4 position = 10
) )
default boolean isVetionEnabled() default boolean isVetionEnabled()
{ {
@@ -169,7 +159,7 @@ public interface AoeWarningConfig extends Config
keyName = "chaosfanatic", keyName = "chaosfanatic",
name = "Chaos Fanatic", name = "Chaos Fanatic",
description = "Configures whether or not AoE Projectile Warnings for Chaos Fanatic are displayed", description = "Configures whether or not AoE Projectile Warnings for Chaos Fanatic are displayed",
position = 4 position = 11
) )
default boolean isChaosFanaticEnabled() default boolean isChaosFanaticEnabled()
{ {
@@ -180,7 +170,7 @@ public interface AoeWarningConfig extends Config
keyName = "olm", keyName = "olm",
name = "Olm", name = "Olm",
description = "Configures whether or not AoE Projectile Warnings for The Great Olm are displayed", description = "Configures whether or not AoE Projectile Warnings for The Great Olm are displayed",
position = 4 position = 12
) )
default boolean isOlmEnabled() default boolean isOlmEnabled()
{ {
@@ -191,7 +181,7 @@ public interface AoeWarningConfig extends Config
keyName = "bombDisplay", keyName = "bombDisplay",
name = "Olm Bombs", name = "Olm Bombs",
description = "Display a timer and colour-coded AoE for Olm's crystal-phase bombs.", description = "Display a timer and colour-coded AoE for Olm's crystal-phase bombs.",
position = 4 position = 13
) )
default boolean bombDisplay() default boolean bombDisplay()
{ {
@@ -202,7 +192,7 @@ public interface AoeWarningConfig extends Config
keyName = "corp", keyName = "corp",
name = "Corporeal Beast", name = "Corporeal Beast",
description = "Configures whether or not AoE Projectile Warnings for the Corporeal Beast are displayed", description = "Configures whether or not AoE Projectile Warnings for the Corporeal Beast are displayed",
position = 4 position = 14
) )
default boolean isCorpEnabled() default boolean isCorpEnabled()
{ {
@@ -213,7 +203,7 @@ public interface AoeWarningConfig extends Config
keyName = "wintertodt", keyName = "wintertodt",
name = "Wintertodt Snow Fall", name = "Wintertodt Snow Fall",
description = "Configures whether or not AOE Projectile Warnings for the Wintertodt snow fall are displayed", description = "Configures whether or not AOE Projectile Warnings for the Wintertodt snow fall are displayed",
position = 4 position = 15
) )
default boolean isWintertodtEnabled() default boolean isWintertodtEnabled()
{ {
@@ -224,7 +214,7 @@ public interface AoeWarningConfig extends Config
keyName = "isXarpusEnabled", keyName = "isXarpusEnabled",
name = "Xarpus", name = "Xarpus",
description = "Configures whether or not AOE Projectile Warnings for Xarpus are displayed", description = "Configures whether or not AOE Projectile Warnings for Xarpus are displayed",
position = 4 position = 16
) )
default boolean isXarpusEnabled() default boolean isXarpusEnabled()
{ {
@@ -235,7 +225,7 @@ public interface AoeWarningConfig extends Config
keyName = "lightning", keyName = "lightning",
name = "Olm Lightning Trails", name = "Olm Lightning Trails",
description = "Show Lightning Trails", description = "Show Lightning Trails",
position = 4 position = 17
) )
default boolean LightningTrail() default boolean LightningTrail()
{ {
@@ -246,27 +236,28 @@ public interface AoeWarningConfig extends Config
keyName = "addyDrags", keyName = "addyDrags",
name = "Addy Drags", name = "Addy Drags",
description = "Show Bad Areas", description = "Show Bad Areas",
position = 4 position = 18
) )
default boolean addyDrags() default boolean addyDrags()
{ {
return true; return true;
} }
@ConfigItem( @ConfigItem(
keyName = "drake", keyName = "drake", name = "Drakes Breath",
name = "Drakes Breath", description = "Configures if Drakes Breath tile markers are displayed",
description = "Configures if Drakes Breath tile markers are displayed" position = 19
) )
default boolean isDrakeEnabled() default boolean isDrakeEnabled()
{ {
return true; return true;
} }
@ConfigItem( @ConfigItem(
keyName = "cerbFire", keyName = "cerbFire",
name = "Cerberus Fire", name = "Cerberus Fire",
description = "Configures if Cerberus fire tile markers are displayed" description = "Configures if Cerberus fire tile markers are displayed",
position = 20
) )
default boolean isCerbFireEnabled() default boolean isCerbFireEnabled()
{ {
@@ -276,7 +267,8 @@ public interface AoeWarningConfig extends Config
@ConfigItem( @ConfigItem(
keyName = "delay", keyName = "delay",
name = "Fade delay", name = "Fade delay",
description = "Configures the amount of time in milliseconds that the warning lingers for after the projectile has touched the ground" description = "Configures the amount of time in milliseconds that the warning lingers for after the projectile has touched the ground",
position = 21
) )
default int delay() default int delay()
{ {

View File

@@ -69,10 +69,6 @@ public class AoeWarningOverlay extends Overlay
@Override @Override
public Dimension render(Graphics2D graphics) public Dimension render(Graphics2D graphics)
{ {
if (!config.enabled())
{
return null;
}
for (WorldPoint point : plugin.getLightningTrail()) for (WorldPoint point : plugin.getLightningTrail())
{ {
drawTile(graphics, point, new Color(0,150,200), 2, 150, 50); drawTile(graphics, point, new Color(0,150,200), 2, 150, 50);

View File

@@ -52,7 +52,6 @@ import net.runelite.api.events.GameObjectSpawned;
import net.runelite.api.events.GameStateChanged; import net.runelite.api.events.GameStateChanged;
import net.runelite.api.events.GameTick; import net.runelite.api.events.GameTick;
import net.runelite.api.events.ProjectileMoved; import net.runelite.api.events.ProjectileMoved;
import net.runelite.client.Notifier;
import net.runelite.client.config.ConfigManager; import net.runelite.client.config.ConfigManager;
import net.runelite.client.eventbus.Subscribe; import net.runelite.client.eventbus.Subscribe;
import net.runelite.client.plugins.Plugin; import net.runelite.client.plugins.Plugin;
@@ -74,23 +73,28 @@ public class AoeWarningPlugin extends Plugin
@Getter @Getter
private final Map<WorldPoint, CrystalBomb> bombs = new HashMap<>(); private final Map<WorldPoint, CrystalBomb> bombs = new HashMap<>();
private final Map<Projectile, AoeProjectile> projectiles = new HashMap<>(); private final Map<Projectile, AoeProjectile> projectiles = new HashMap<>();
@Inject @Inject
public AoeWarningConfig config; public AoeWarningConfig config;
@Inject @Inject
private OverlayManager overlayManager; private OverlayManager overlayManager;
@Inject @Inject
private AoeWarningOverlay coreOverlay; private AoeWarningOverlay coreOverlay;
@Inject @Inject
private BombOverlay bombOverlay; private BombOverlay bombOverlay;
@Inject @Inject
private Client client; private Client client;
@Inject
private Notifier notifier;
@Getter(AccessLevel.PACKAGE) @Getter(AccessLevel.PACKAGE)
private List<WorldPoint> LightningTrail = new ArrayList<>(); private List<WorldPoint> LightningTrail = new ArrayList<>();
@Getter(AccessLevel.PACKAGE) @Getter(AccessLevel.PACKAGE)
private List<WorldPoint> AcidTrail = new ArrayList<>(); private List<WorldPoint> AcidTrail = new ArrayList<>();
@Getter(AccessLevel.PACKAGE) @Getter(AccessLevel.PACKAGE)
private List<WorldPoint> CrystalSpike = new ArrayList<>(); private List<WorldPoint> CrystalSpike = new ArrayList<>();
@@ -100,7 +104,7 @@ public class AoeWarningPlugin extends Plugin
return configManager.getConfig(AoeWarningConfig.class); return configManager.getConfig(AoeWarningConfig.class);
} }
public Map<Projectile, AoeProjectile> getProjectiles() Map<Projectile, AoeProjectile> getProjectiles()
{ {
return projectiles; return projectiles;
} }
@@ -207,11 +211,8 @@ public class AoeWarningPlugin extends Plugin
} }
} }
Iterator<Map.Entry<WorldPoint, CrystalBomb>> it = bombs.entrySet().iterator(); for (Map.Entry<WorldPoint, CrystalBomb> entry : bombs.entrySet())
while (it.hasNext())
{ {
Map.Entry<WorldPoint, CrystalBomb> entry = it.next();
CrystalBomb bomb = entry.getValue(); CrystalBomb bomb = entry.getValue();
bomb.bombClockUpdate(); bomb.bombClockUpdate();
//bombClockUpdate smooths the shown timer; not using this results in 1.2 --> .6 vs. 1.2 --> 1.1, etc. //bombClockUpdate smooths the shown timer; not using this results in 1.2 --> .6 vs. 1.2 --> 1.1, etc.

View File

@@ -24,6 +24,18 @@
*/ */
package net.runelite.client.plugins.aoewarnings; package net.runelite.client.plugins.aoewarnings;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.time.Instant;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import javax.inject.Inject;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import net.runelite.api.Client; import net.runelite.api.Client;
import net.runelite.api.Perspective; import net.runelite.api.Perspective;
@@ -31,20 +43,11 @@ import net.runelite.api.Player;
import net.runelite.api.Point; import net.runelite.api.Point;
import net.runelite.api.coords.LocalPoint; import net.runelite.api.coords.LocalPoint;
import net.runelite.api.coords.WorldPoint; import net.runelite.api.coords.WorldPoint;
import net.runelite.client.plugins.aoewarnings.CrystalBomb; import net.runelite.client.ui.overlay.Overlay;
import net.runelite.client.ui.overlay.*; import net.runelite.client.ui.overlay.OverlayLayer;
import javax.inject.Inject; import net.runelite.client.ui.overlay.OverlayPosition;
import java.awt.Graphics2D; import net.runelite.client.ui.overlay.OverlayPriority;
import java.awt.Dimension; import net.runelite.client.ui.overlay.OverlayUtil;
import java.awt.Color;
import java.awt.Polygon;
import java.awt.BasicStroke;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.time.Instant;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
@Slf4j @Slf4j
public class BombOverlay extends Overlay public class BombOverlay extends Overlay

View File

@@ -24,14 +24,14 @@
*/ */
package net.runelite.client.plugins.aoewarnings; package net.runelite.client.plugins.aoewarnings;
import java.time.Instant;
import lombok.Getter; import lombok.Getter;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import net.runelite.api.GameObject; import net.runelite.api.GameObject;
import net.runelite.api.coords.WorldPoint; import net.runelite.api.coords.WorldPoint;
import java.time.Instant;
@Slf4j @Slf4j
public class CrystalBomb class CrystalBomb
{ {
@Getter @Getter
private Instant plantedOn; private Instant plantedOn;
@@ -49,7 +49,7 @@ public class CrystalBomb
@Getter @Getter
private WorldPoint worldLocation; private WorldPoint worldLocation;
public CrystalBomb(GameObject gameObject, int startTick) CrystalBomb(GameObject gameObject, int startTick)
{ {
this.plantedOn = Instant.now(); this.plantedOn = Instant.now();
this.objectId = gameObject.getId(); this.objectId = gameObject.getId();
@@ -57,7 +57,7 @@ public class CrystalBomb
this.tickStarted = startTick; this.tickStarted = startTick;
} }
public void bombClockUpdate() void bombClockUpdate()
{ {
lastClockUpdate = Instant.now(); lastClockUpdate = Instant.now();
} }

View File

@@ -38,85 +38,115 @@ public interface BarbarianAssaultConfig extends Config
description = "Show time to next call change", description = "Show time to next call change",
position = 0 position = 0
) )
default boolean showTimer() { return true; } default boolean showTimer()
{
return true;
}
@ConfigItem( @ConfigItem(
keyName = "waveTimes", keyName = "waveTimes",
name = "Show wave and game duration", name = "Show wave and game duration",
description = "Displays wave and game duration", description = "Displays wave and game duration",
position = 1 position = 1
)
default boolean waveTimes() { return true; }
@ConfigItem(
keyName = "showEggCountMessage",
name = "Show count of eggs collected as collector.",
description = "Display egg count as collector after each wave",
position = 2
)
default boolean showEggCount() { return false; }
@ConfigItem(
keyName = "showEggCountOverlay",
name = "Overlay of eggs counted",
description = "Display current egg count as collector",
position = 3
)
default boolean showEggCountOverlay() { return false; }
@ConfigItem(
keyName = "showHpCountMessage",
name = "Show count of Hp healed as healer.",
description = "Display healed count as healer after each wave",
position = 4
)
default boolean showHpCount() { return false; }
@ConfigItem(
keyName = "showHpCountOverlay",
name = "Overlay of Hp counted",
description = "Display current healed count as healer",
position = 5
) )
default boolean showHpCountOverlay() { return false; } default boolean waveTimes()
{
return true;
}
@ConfigItem( @ConfigItem(
keyName = "highlightCollectorEggs", keyName = "showEggCountMessage",
name = "Highlight collector eggs", name = "Show count of eggs collected as collector.",
description = "Highlight called egg colors", description = "Display egg count as collector after each wave",
position = 6 position = 2
) )
default boolean highlightCollectorEggs() { return false; } default boolean showEggCount()
{
return false;
}
@ConfigItem( @ConfigItem(
keyName = "showTotalRewards", keyName = "showEggCountOverlay",
name = "Summarize total reward points", name = "Overlay of eggs counted",
description = "Displays total eggs/healed hp and missed attacks/lost runners", description = "Display current egg count as collector",
position = 7 position = 3
) )
default boolean showTotalRewards(){ return false; }; default boolean showEggCountOverlay()
{
return false;
}
@ConfigItem( @ConfigItem(
keyName = "showSummaryOfPoints", keyName = "showHpCountMessage",
name = "Display summary of advanced points", name = "Show count of Hp healed as healer.",
description = "Gives summary of advanced points breakdown in chat log", description = "Display healed count as healer after each wave",
position = 8 position = 4
)
default boolean showSummaryOfPoints() { return false; };
@ConfigItem(
keyName = "wrongPoisonFoodTextColor",
name = "Change healer wrong poison pack color",
description = "Change healer wrong poison pack color",
position = 9
) )
default Color wrongPoisonFoodTextColor() { return Color.BLACK;} default boolean showHpCount()
{
return false;
}
@ConfigItem( @ConfigItem(
keyName = "highlightItems", keyName = "showHpCountOverlay",
name = "Highlight called poison/bait", name = "Overlay of Hp counted",
description = "Highlights the poison or bait that was called by your teammate", description = "Display current healed count as healer",
position = 10 position = 5
)
default boolean showHpCountOverlay()
{
return false;
}
@ConfigItem(
keyName = "highlightCollectorEggs",
name = "Highlight collector eggs",
description = "Highlight called egg colors",
position = 6
)
default boolean highlightCollectorEggs()
{
return false;
}
@ConfigItem(
keyName = "showTotalRewards",
name = "Summarize total reward points",
description = "Displays total eggs/healed hp and missed attacks/lost runners",
position = 7
)
default boolean showTotalRewards()
{
return false;
}
@ConfigItem(
keyName = "showSummaryOfPoints",
name = "Display summary of advanced points",
description = "Gives summary of advanced points breakdown in chat log",
position = 8
)
default boolean showSummaryOfPoints()
{
return false;
}
@ConfigItem(
keyName = "wrongPoisonFoodTextColor",
name = "Change healer wrong poison pack color",
description = "Change healer wrong poison pack color",
position = 9
)
default Color wrongPoisonFoodTextColor()
{
return Color.BLACK;
}
@ConfigItem(
keyName = "highlightItems",
name = "Highlight called poison/bait",
description = "Highlights the poison or bait that was called by your teammate",
position = 10
) )
default boolean highlightItems() default boolean highlightItems()
{ {
@@ -124,10 +154,10 @@ public interface BarbarianAssaultConfig extends Config
} }
@ConfigItem( @ConfigItem(
keyName = "highlightColor", keyName = "highlightColor",
name = "Highlight color", name = "Highlight color",
description = "Configures the color to highlight the called poison/bait", description = "Configures the color to highlight the called poison/bait",
position = 11 position = 11
) )
default Color highlightColor() default Color highlightColor()
{ {

View File

@@ -31,8 +31,8 @@ import java.awt.Graphics2D;
import java.awt.Polygon; import java.awt.Polygon;
import java.awt.Rectangle; import java.awt.Rectangle;
import java.awt.Stroke; import java.awt.Stroke;
import java.util.Map;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.util.Map;
import javax.inject.Inject; import javax.inject.Inject;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
@@ -60,9 +60,9 @@ import net.runelite.client.util.ImageUtil;
class BarbarianAssaultOverlay extends Overlay class BarbarianAssaultOverlay extends Overlay
{ {
private static final int MAX_EGG_DISTANCE = 2500; private static final int MAX_EGG_DISTANCE = 2500;
private final int HEALTH_BAR_HEIGHT = 20; private final int HEALTH_BAR_HEIGHT = 20;
private final Color HEALTH_BAR_COLOR = new Color(225, 35, 0, 125); private final Color HEALTH_BAR_COLOR = new Color(225, 35, 0, 125);
private static final Color BACKGROUND = new Color(0, 0, 0, 150); private static final Color BACKGROUND = new Color(0, 0, 0, 150);
private static final int OFFSET_Z = 20; private static final int OFFSET_Z = 20;
private final Client client; private final Client client;
@@ -124,13 +124,15 @@ class BarbarianAssaultOverlay extends Overlay
graphics.drawImage(plugin.getClockImage(), spriteBounds.x, spriteBounds.y, null); graphics.drawImage(plugin.getClockImage(), spriteBounds.x, spriteBounds.y, null);
} }
if (role == Role.COLLECTOR && config.highlightCollectorEggs()) { if (role == Role.COLLECTOR && config.highlightCollectorEggs())
{
String heardCall = plugin.getCollectorHeardCall(); String heardCall = plugin.getCollectorHeardCall();
Color highlightColor = BarbarianAssaultPlugin.getEggColor(heardCall); Color highlightColor = BarbarianAssaultPlugin.getEggColor(heardCall);
Map<WorldPoint, Integer> calledEggMap = plugin.getCalledEggMap(); Map<WorldPoint, Integer> calledEggMap = plugin.getCalledEggMap();
Map<WorldPoint, Integer> yellowEggMap = plugin.getYellowEggs(); Map<WorldPoint, Integer> yellowEggMap = plugin.getYellowEggs();
if (calledEggMap != null) { if (calledEggMap != null)
{
renderEggLocations(graphics, calledEggMap, highlightColor); renderEggLocations(graphics, calledEggMap, highlightColor);
} }
@@ -139,10 +141,12 @@ class BarbarianAssaultOverlay extends Overlay
} }
Widget inventory = client.getWidget(WidgetInfo.INVENTORY); Widget inventory = client.getWidget(WidgetInfo.INVENTORY);
if (config.highlightItems() && inventory != null && !inventory.isHidden() && ((role == Role.DEFENDER || role == Role.HEALER))) { if (config.highlightItems() && inventory != null && !inventory.isHidden() && ((role == Role.DEFENDER || role == Role.HEALER)))
{
int listenItemId = plugin.getListenItemId(role.getListen()); int listenItemId = plugin.getListenItemId(role.getListen());
if (listenItemId != -1) { if (listenItemId != -1)
{
Color color = config.highlightColor(); Color color = config.highlightColor();
BufferedImage highlight = ImageUtil.fillImage(itemManager.getImage(listenItemId), new Color(color.getRed(), color.getGreen(), color.getBlue(), 150)); BufferedImage highlight = ImageUtil.fillImage(itemManager.getImage(listenItemId), new Color(color.getRed(), color.getGreen(), color.getBlue(), 150));
@@ -156,47 +160,47 @@ class BarbarianAssaultOverlay extends Overlay
} }
} }
if (role == Role.HEALER) if (role == Role.HEALER)
{ {
for (HealerTeam teammate : HealerTeam.values()) for (HealerTeam teammate : HealerTeam.values())
{ {
Widget widget = client.getWidget(teammate.getTeammate()); Widget widget = client.getWidget(teammate.getTeammate());
if (widget == null) if (widget == null)
{ {
continue; continue;
} }
String[] teammateHealth = widget.getText().split(" / "); String[] teammateHealth = widget.getText().split(" / ");
final int curHealth = Integer.parseInt(teammateHealth[0]); final int curHealth = Integer.parseInt(teammateHealth[0]);
final int maxHealth = Integer.parseInt(teammateHealth[1]); final int maxHealth = Integer.parseInt(teammateHealth[1]);
int width = teammate.getWidth(); int width = teammate.getWidth();
final int filledWidth = getBarWidth(maxHealth, curHealth, width); final int filledWidth = getBarWidth(maxHealth, curHealth, width);
int offsetX = teammate.getOffset().getX(); int offsetX = teammate.getOffset().getX();
int offsetY = teammate.getOffset().getY(); int offsetY = teammate.getOffset().getY();
int x = widget.getCanvasLocation().getX() - offsetX; int x = widget.getCanvasLocation().getX() - offsetX;
int y = widget.getCanvasLocation().getY() - offsetY; int y = widget.getCanvasLocation().getY() - offsetY;
graphics.setColor(HEALTH_BAR_COLOR); graphics.setColor(HEALTH_BAR_COLOR);
graphics.fillRect(x, y, filledWidth, HEALTH_BAR_HEIGHT); graphics.fillRect(x, y, filledWidth, HEALTH_BAR_HEIGHT);
} }
} }
return null; return null;
} }
private static int getBarWidth(int base, int current, int size) private static int getBarWidth(int base, int current, int size)
{ {
final double ratio = (double) current / base; final double ratio = (double) current / base;
if (ratio >= 1) if (ratio >= 1)
{ {
return size; return size;
} }
return (int) Math.round(ratio * size); return (int) Math.round(ratio * size);
} }
private void renderEggLocations(Graphics2D graphics, Map<WorldPoint, Integer> eggMap, Color color) private void renderEggLocations(Graphics2D graphics, Map<WorldPoint, Integer> eggMap, Color color)
{ {

View File

@@ -29,27 +29,35 @@ import com.google.inject.Provides;
import java.awt.Color; import java.awt.Color;
import java.awt.Font; import java.awt.Font;
import java.awt.Image; import java.awt.Image;
import java.util.*; import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.inject.Inject; import javax.inject.Inject;
import lombok.AccessLevel; import lombok.AccessLevel;
import lombok.Getter; import lombok.Getter;
import net.runelite.api.*; import lombok.extern.slf4j.Slf4j;
import net.runelite.api.coords.WorldPoint;
import net.runelite.api.events.*;
import net.runelite.api.kit.KitType;
import net.runelite.api.ChatMessageType; import net.runelite.api.ChatMessageType;
import net.runelite.api.Client; import net.runelite.api.Client;
import net.runelite.api.EquipmentInventorySlot; import net.runelite.api.EquipmentInventorySlot;
import net.runelite.api.GameState;
import net.runelite.api.InventoryID; import net.runelite.api.InventoryID;
import net.runelite.api.Item; import net.runelite.api.Item;
import net.runelite.api.GameState;
import net.runelite.api.ItemID; import net.runelite.api.ItemID;
import net.runelite.api.MenuEntry;
import net.runelite.api.MessageNode;
import net.runelite.api.Player;
import net.runelite.api.Tile;
import net.runelite.api.Varbits; import net.runelite.api.Varbits;
import net.runelite.api.coords.WorldPoint;
import net.runelite.api.events.ChatMessage; import net.runelite.api.events.ChatMessage;
import net.runelite.api.events.GameStateChanged;
import net.runelite.api.events.ItemContainerChanged; import net.runelite.api.events.ItemContainerChanged;
import net.runelite.api.events.ItemDespawned;
import net.runelite.api.events.ItemSpawned;
import net.runelite.api.events.MenuEntryAdded;
import net.runelite.api.events.VarbitChanged; import net.runelite.api.events.VarbitChanged;
import net.runelite.api.events.WidgetLoaded; import net.runelite.api.events.WidgetLoaded;
import net.runelite.api.events.GameStateChanged; import net.runelite.api.kit.KitType;
import net.runelite.api.widgets.Widget; import net.runelite.api.widgets.Widget;
import net.runelite.api.widgets.WidgetID; import net.runelite.api.widgets.WidgetID;
import net.runelite.api.widgets.WidgetInfo; import net.runelite.api.widgets.WidgetInfo;
@@ -67,16 +75,15 @@ import net.runelite.client.ui.overlay.OverlayManager;
import net.runelite.client.util.ColorUtil; import net.runelite.client.util.ColorUtil;
import net.runelite.client.util.ImageUtil; import net.runelite.client.util.ImageUtil;
import net.runelite.client.util.Text; import net.runelite.client.util.Text;
import lombok.extern.slf4j.Slf4j;
@Slf4j @Slf4j
@PluginDescriptor( @PluginDescriptor(
name = "Barbarian Assault+", name = "Barbarian Assault+",
description = "Custom barbarian assault plugin, use along with BA Tools", description = "Custom barbarian assault plugin, use along with BA Tools",
tags = {"minigame", "overlay", "timer"}, tags = {"minigame", "overlay", "timer"},
type = PluginType.PVM // don't remove this, added this because our barbarian assault plugin is big time modified type = PluginType.PVM // don't remove this, added this because our barbarian assault plugin is big time modified
) )
public class BarbarianAssaultPlugin extends Plugin public class BarbarianAssaultPlugin extends Plugin
{ {
@@ -86,19 +93,24 @@ public class BarbarianAssaultPlugin extends Plugin
@Getter @Getter
private int collectedEggCount = 0; private int collectedEggCount = 0;
@Getter @Getter
private int positiveEggCount = 0; private int positiveEggCount = 0;
@Getter @Getter
private int wrongEggs = 0; private int wrongEggs = 0;
@Getter @Getter
private int HpHealed = 0; private int HpHealed = 0;
@Getter @Getter
private int totalCollectedEggCount = 0; private int totalCollectedEggCount = 0;
@Getter @Getter
private int totalHpHealed = 0; private int totalHpHealed = 0;
private boolean hasAnnounced; private boolean hasAnnounced;
private Font font; private Font font;
private final Image clockImage = ImageUtil.getResourceStreamFromClass(getClass(), "clock.png"); private final Image clockImage = ImageUtil.getResourceStreamFromClass(getClass(), "clock.png");
private int inGameBit = 0; private int inGameBit = 0;
private String currentWave = START_WAVE; private String currentWave = START_WAVE;
@@ -116,7 +128,6 @@ public class BarbarianAssaultPlugin extends Plugin
@Getter(AccessLevel.PACKAGE) @Getter(AccessLevel.PACKAGE)
private final HashMap<WorldPoint, Integer> yellowEggs = new HashMap<>(); private final HashMap<WorldPoint, Integer> yellowEggs = new HashMap<>();
@Inject @Inject
@Getter @Getter
private Client client; private Client client;
@@ -133,45 +144,20 @@ public class BarbarianAssaultPlugin extends Plugin
@Inject @Inject
private BarbarianAssaultOverlay overlay; private BarbarianAssaultOverlay overlay;
private final ImmutableList<WidgetInfo> WIDGETS = ImmutableList.of( @Provides
WidgetInfo.BA_FAILED_ATTACKER_ATTACKS,
WidgetInfo.BA_RUNNERS_PASSED,
WidgetInfo.BA_EGGS_COLLECTED,
WidgetInfo.BA_HITPOINTS_REPLENISHED,
WidgetInfo.BA_WRONG_POISON_PACKS,
WidgetInfo.BA_HONOUR_POINTS_REWARD
);
private final ImmutableList<WidgetInfo> POINTSWIDGETS = ImmutableList.of(
//base
WidgetInfo.BA_BASE_POINTS,
//att
WidgetInfo.BA_FAILED_ATTACKER_ATTACKS_POINTS,
WidgetInfo.BA_RANGERS_KILLED,
WidgetInfo.BA_FIGHTERS_KILLED,
//def
WidgetInfo.BA_RUNNERS_PASSED_POINTS,
WidgetInfo.BA_RUNNERS_KILLED,
//coll
WidgetInfo.BA_EGGS_COLLECTED_POINTS,
//heal
WidgetInfo.BA_HEALERS_KILLED,
WidgetInfo.BA_HITPOINTS_REPLENISHED_POINTS,
WidgetInfo.BA_WRONG_POISON_PACKS_POINTS
);
@Provides
BarbarianAssaultConfig provideConfig(ConfigManager configManager) BarbarianAssaultConfig provideConfig(ConfigManager configManager)
{ {
return configManager.getConfig(BarbarianAssaultConfig.class); return configManager.getConfig(BarbarianAssaultConfig.class);
} }
private Game game; private Game game;
private Wave wave;
@Override @Override
protected void startUp() throws Exception protected void startUp() throws Exception
{ {
overlayManager.add(overlay); overlayManager.add(overlay);
font = FontManager.getRunescapeFont() font = FontManager.getRunescapeFont()
.deriveFont(Font.BOLD, 24); .deriveFont(Font.BOLD, 24);
} }
@Override @Override
@@ -202,12 +188,14 @@ public class BarbarianAssaultPlugin extends Plugin
{ {
if (event.getGroupId() == WidgetID.BA_REWARD_GROUP_ID) if (event.getGroupId() == WidgetID.BA_REWARD_GROUP_ID)
{ {
wave = new Wave(client); Wave wave = new Wave(client);
Widget rewardWidget = client.getWidget(WidgetInfo.BA_REWARD_TEXT); Widget rewardWidget = client.getWidget(WidgetInfo.BA_REWARD_TEXT);
if (rewardWidget != null && rewardWidget.getText().contains(ENDGAME_REWARD_NEEDLE_TEXT) && gameTime != null) if (rewardWidget != null && rewardWidget.getText().contains(ENDGAME_REWARD_NEEDLE_TEXT) && gameTime != null)
{ {
if (config.waveTimes()) if (config.waveTimes())
{
announceTime("Game finished, duration: ", gameTime.getTime(false)); announceTime("Game finished, duration: ", gameTime.getTime(false));
}
if (config.showTotalRewards()) if (config.showTotalRewards())
{ {
announceSomething(game.getGameSummary()); announceSomething(game.getGameSummary());
@@ -215,7 +203,7 @@ public class BarbarianAssaultPlugin extends Plugin
} }
Widget pointsWidget = client.getWidget(WidgetInfo.BA_RUNNERS_PASSED); Widget pointsWidget = client.getWidget(WidgetInfo.BA_RUNNERS_PASSED);
if (!rewardWidget.getText().contains(ENDGAME_REWARD_NEEDLE_TEXT) && pointsWidget != null if (!rewardWidget.getText().contains(ENDGAME_REWARD_NEEDLE_TEXT) && pointsWidget != null
&& config.showSummaryOfPoints() && !hasAnnounced && client.getVar(Varbits.IN_GAME_BA) == 0) && config.showSummaryOfPoints() && !hasAnnounced && client.getVar(Varbits.IN_GAME_BA) == 0)
{ {
wave.setWaveAmounts(); wave.setWaveAmounts();
wave.setWavePoints(); wave.setWavePoints();
@@ -249,13 +237,15 @@ public class BarbarianAssaultPlugin extends Plugin
{ {
hasAnnounced = true; hasAnnounced = true;
} }
if (!chatMessage.getType().equals(ChatMessageType.GAMEMESSAGE)) if (!chatMessage.getType().equals(ChatMessageType.GAMEMESSAGE))
{ {
return; return;
} }
int inGame = client.getVar(Varbits.IN_GAME_BA); int inGame = client.getVar(Varbits.IN_GAME_BA);
if (inGameBit != inGame) if (inGameBit != inGame)
{
return; return;
}
final String message = chatMessage.getMessage().toLowerCase(); final String message = chatMessage.getMessage().toLowerCase();
final MessageNode messageNode = chatMessage.getMessageNode(); final MessageNode messageNode = chatMessage.getMessageNode();
final String nodeValue = Text.removeTags(messageNode.getValue()); final String nodeValue = Text.removeTags(messageNode.getValue());
@@ -368,13 +358,14 @@ public class BarbarianAssaultPlugin extends Plugin
inGameBit = inGame; inGameBit = inGame;
} }
@Subscribe @Subscribe
public void onItemSpawned(ItemSpawned itemSpawned) public void onItemSpawned(ItemSpawned itemSpawned)
{ {
int itemId = itemSpawned.getItem().getId(); int itemId = itemSpawned.getItem().getId();
WorldPoint worldPoint = itemSpawned.getTile().getWorldLocation(); WorldPoint worldPoint = itemSpawned.getTile().getWorldLocation();
HashMap<WorldPoint, Integer> eggMap = getEggMap(itemId); HashMap<WorldPoint, Integer> eggMap = getEggMap(itemId);
if (eggMap != null) if (eggMap != null)
{ {
Integer existingQuantity = eggMap.putIfAbsent(worldPoint, 1); Integer existingQuantity = eggMap.putIfAbsent(worldPoint, 1);
if (existingQuantity != null) if (existingQuantity != null)
@@ -470,9 +461,9 @@ public class BarbarianAssaultPlugin extends Plugin
private void announceSomething(final ChatMessageBuilder chatMessage) private void announceSomething(final ChatMessageBuilder chatMessage)
{ {
chatMessageManager.queue(QueuedMessage.builder() chatMessageManager.queue(QueuedMessage.builder()
.type(ChatMessageType.CONSOLE) .type(ChatMessageType.CONSOLE)
.runeLiteFormattedMessage(chatMessage.build()) .runeLiteFormattedMessage(chatMessage.build())
.build()); .build());
} }
String getCollectorHeardCall() String getCollectorHeardCall()
@@ -570,26 +561,22 @@ public class BarbarianAssaultPlugin extends Plugin
private void announceTime(String preText, String time) private void announceTime(String preText, String time)
{ {
final String chatMessage = new ChatMessageBuilder() final String chatMessage = new ChatMessageBuilder()
.append(ChatColorType.NORMAL) .append(ChatColorType.NORMAL)
.append(preText) .append(preText)
.append(ChatColorType.HIGHLIGHT) .append(ChatColorType.HIGHLIGHT)
.append(time) .append(time)
.build(); .build();
chatMessageManager.queue(QueuedMessage.builder() chatMessageManager.queue(QueuedMessage.builder()
.type(ChatMessageType.CONSOLE) .type(ChatMessageType.CONSOLE)
.runeLiteFormattedMessage(chatMessage) .runeLiteFormattedMessage(chatMessage)
.build()); .build());
} }
private boolean isEgg(int itemID) private boolean isEgg(int itemID)
{ {
if (itemID == ItemID.RED_EGG || itemID == ItemID.GREEN_EGG return itemID == ItemID.RED_EGG || itemID == ItemID.GREEN_EGG
|| itemID == ItemID.BLUE_EGG || itemID == ItemID.YELLOW_EGG) || itemID == ItemID.BLUE_EGG || itemID == ItemID.YELLOW_EGG;
{
return true;
}
return false;
} }
private boolean isUnderPlayer(Tile tile) private boolean isUnderPlayer(Tile tile)
@@ -616,12 +603,12 @@ public class BarbarianAssaultPlugin extends Plugin
return font; return font;
} }
public Image getClockImage() Image getClockImage()
{ {
return clockImage; return clockImage;
} }
public int getListenItemId(WidgetInfo listenInfo) int getListenItemId(WidgetInfo listenInfo)
{ {
Widget listenWidget = client.getWidget(listenInfo); Widget listenWidget = client.getWidget(listenInfo);

View File

@@ -24,120 +24,124 @@
*/ */
package net.runelite.client.plugins.barbarianassault; package net.runelite.client.plugins.barbarianassault;
import java.awt.Color;
import java.util.ArrayList;
import lombok.Getter; import lombok.Getter;
import net.runelite.api.Client; import net.runelite.api.Client;
import net.runelite.api.events.ChatMessage; import net.runelite.api.events.ChatMessage;
import net.runelite.client.chat.ChatColorType;
import net.runelite.client.chat.ChatMessageBuilder; import net.runelite.client.chat.ChatMessageBuilder;
import net.runelite.client.eventbus.Subscribe; import net.runelite.client.eventbus.Subscribe;
import java.awt.*;
import java.util.ArrayList;
@Getter @Getter
public class Game public class Game
{ {
private Client client; private Client client;
private String currentWave; private String currentWave;
private ArrayList<Wave> waves = new ArrayList<>(); private ArrayList<Wave> waves = new ArrayList<>();
private String[] totalDescriptions = { private String[] totalDescriptions = {
"A: ", "A: ",
"; D: ", "; D: ",
"; C: ", "; C: ",
"; Vial: ", "; Vial: ",
"; H packs: ", "; H packs: ",
"; Total: "}; "; Total: "};
private String[] otherPointsDescriptions = { private String[] otherPointsDescriptions = {
" A: ", " A: ",
"; D: ", "; D: ",
"; C: ", "; C: ",
"; H: " "; H: "
}; };
private int[] totalPoints = new int[6]; private int[] totalPoints = new int[6];
private int[] totalAmounts = new int[6]; private int[] totalAmounts = new int[6];
private int[] otherRolesPoints = new int[4]; private int[] otherRolesPoints = new int[4];
Game(Client client) Game(Client client)
{ {
this.client = client; this.client = client;
} }
Game(Client client, ArrayList<Wave> waves)
{ Game(Client client, ArrayList<Wave> waves)
this.client = client; {
this.waves = waves; this.client = client;
} this.waves = waves;
@Subscribe }
public void onChatMessage(ChatMessage chatMessage)
{ @Subscribe
if (chatMessage.getMessage().startsWith("---- Wave:")) public void onChatMessage(ChatMessage chatMessage)
{ {
String[] tempMessage = chatMessage.getMessage().split(" "); if (chatMessage.getMessage().startsWith("---- Wave:"))
currentWave = tempMessage[2]; {
String[] temp = currentWave.split(" "); String[] tempMessage = chatMessage.getMessage().split(" ");
} currentWave = tempMessage[2];
if (currentWave.equals("1")) String[] temp = currentWave.split(" ");
{ }
waves = null; if (currentWave.equals("1"))
totalPoints = new int[6]; {
totalAmounts = new int[6]; waves = null;
} totalPoints = new int[6];
} totalAmounts = new int[6];
ChatMessageBuilder getGameSummary() }
{ }
int[] amountsList;
int[] pointsList; ChatMessageBuilder getGameSummary()
int[] otherRolesPointsList; {
ChatMessageBuilder message = new ChatMessageBuilder(); int[] amountsList;
message.append("Round points: "); int[] pointsList;
for (Wave w : waves) int[] otherRolesPointsList;
{ ChatMessageBuilder message = new ChatMessageBuilder();
amountsList = w.getWaveAmounts(); message.append("Round points: ");
pointsList = w.getWavePoints(); for (Wave w : waves)
otherRolesPointsList = w.getOtherRolesPointsList(); {
for (int j = 0; j < totalAmounts.length; j++) { amountsList = w.getWaveAmounts();
totalAmounts[j] += amountsList[j]; pointsList = w.getWavePoints();
} otherRolesPointsList = w.getOtherRolesPointsList();
for (int k = 0; k < totalPoints.length; k++) { for (int j = 0; j < totalAmounts.length; j++)
totalPoints[k] += pointsList[k]; {
} totalAmounts[j] += amountsList[j];
for (int z = 0; z < otherRolesPoints.length; z++) { }
otherRolesPoints[z] += otherRolesPointsList[z]; for (int k = 0; k < totalPoints.length; k++)
} {
} totalPoints[k] += pointsList[k];
for (int i = 0; i < otherRolesPoints.length; i++) }
{ for (int z = 0; z < otherRolesPoints.length; z++)
otherRolesPoints[i] += 80; {
} otherRolesPoints[z] += otherRolesPointsList[z];
totalAmounts[5] += 80; }
for (int i = 0; i < totalDescriptions.length; i++) }
{ for (int i = 0; i < otherRolesPoints.length; i++)
if (i != 4) {
{ otherRolesPoints[i] += 80;
message.append(totalDescriptions[i]); }
message.append(String.valueOf(totalAmounts[i])); totalAmounts[5] += 80;
message.append("("); for (int i = 0; i < totalDescriptions.length; i++)
if (totalPoints[i] < 0) {
{ if (i != 4)
message.append(Color.RED, String.valueOf(totalPoints[i])); {
} message.append(totalDescriptions[i]);
else if (totalPoints[i] > 0) message.append(String.valueOf(totalAmounts[i]));
{ message.append("(");
message.append(Color.BLUE, String.valueOf(totalPoints[i])); if (totalPoints[i] < 0)
} {
else message.append(Color.RED, String.valueOf(totalPoints[i]));
{ }
message.append(String.valueOf(totalPoints[i])); else if (totalPoints[i] > 0)
} {
message.append(")"); message.append(Color.BLUE, String.valueOf(totalPoints[i]));
} }
} else
message.append(System.getProperty("line.separator")); {
message.append("All roles points this game: "); message.append(String.valueOf(totalPoints[i]));
for(int i = 0; i < otherPointsDescriptions.length; i++) }
{ message.append(")");
message.append(otherPointsDescriptions[i]); }
message.append(String.valueOf(otherRolesPoints[i])); }
} message.append(System.getProperty("line.separator"));
return message; message.append("All roles points this game: ");
} for (int i = 0; i < otherPointsDescriptions.length; i++)
{
message.append(otherPointsDescriptions[i]);
message.append(String.valueOf(otherRolesPoints[i]));
}
return message;
}
} }

View File

@@ -36,10 +36,13 @@ enum Role
@Getter @Getter
private final WidgetInfo listen; private final WidgetInfo listen;
@Getter @Getter
private final WidgetInfo call; private final WidgetInfo call;
@Getter @Getter
private final WidgetInfo roleText; private final WidgetInfo roleText;
@Getter @Getter
private final WidgetInfo roleSprite; private final WidgetInfo roleSprite;

View File

@@ -34,17 +34,22 @@ import net.runelite.api.Constants;
class Round class Round
{ {
private final Instant roundStartTime; private final Instant roundStartTime;
@Getter @Getter
private final Role roundRole; private final Role roundRole;
@Getter @Getter
@Setter @Setter
private boolean runnersKilled; private boolean runnersKilled;
@Getter @Getter
@Setter @Setter
private boolean rangersKilled; private boolean rangersKilled;
@Getter @Getter
@Setter @Setter
private boolean healersKilled; private boolean healersKilled;
@Getter @Getter
@Setter @Setter
private boolean fightersKilled; private boolean fightersKilled;
@@ -56,12 +61,7 @@ class Round
this.roundStartTime = Instant.now().plusMillis(2 * Constants.GAME_TICK_LENGTH); this.roundStartTime = Instant.now().plusMillis(2 * Constants.GAME_TICK_LENGTH);
} }
public long getRoundTime() long getTimeToChange()
{
return Duration.between(roundStartTime, Instant.now()).getSeconds();
}
public long getTimeToChange()
{ {
return 30 + (Duration.between(Instant.now(), roundStartTime).getSeconds() % 30); return 30 + (Duration.between(Instant.now(), roundStartTime).getSeconds() % 30);
} }

View File

@@ -25,193 +25,186 @@
package net.runelite.client.plugins.barbarianassault; package net.runelite.client.plugins.barbarianassault;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import java.awt.Color;
import lombok.Getter; import lombok.Getter;
import net.runelite.api.Client; import net.runelite.api.Client;
import net.runelite.api.widgets.Widget; import net.runelite.api.widgets.Widget;
import net.runelite.api.widgets.WidgetInfo; import net.runelite.api.widgets.WidgetInfo;
import net.runelite.client.chat.ChatMessageBuilder; import net.runelite.client.chat.ChatMessageBuilder;
import net.runelite.client.chat.ChatMessageManager;
import javax.inject.Inject;
import java.awt.*;
@Getter @Getter
class Wave class Wave
{ {
private Client client; private Client client;
private final ImmutableList<WidgetInfo> WIDGETS = ImmutableList.of( private final ImmutableList<WidgetInfo> WIDGETS = ImmutableList.of(
WidgetInfo.BA_FAILED_ATTACKER_ATTACKS, WidgetInfo.BA_FAILED_ATTACKER_ATTACKS,
WidgetInfo.BA_RUNNERS_PASSED, WidgetInfo.BA_RUNNERS_PASSED,
WidgetInfo.BA_EGGS_COLLECTED, WidgetInfo.BA_EGGS_COLLECTED,
WidgetInfo.BA_HITPOINTS_REPLENISHED, WidgetInfo.BA_HITPOINTS_REPLENISHED,
WidgetInfo.BA_WRONG_POISON_PACKS, WidgetInfo.BA_WRONG_POISON_PACKS,
WidgetInfo.BA_HONOUR_POINTS_REWARD WidgetInfo.BA_HONOUR_POINTS_REWARD
); );
private final ImmutableList<WidgetInfo> POINTSWIDGETS = ImmutableList.of( private final ImmutableList<WidgetInfo> POINTSWIDGETS = ImmutableList.of(
//base //base
WidgetInfo.BA_BASE_POINTS, WidgetInfo.BA_BASE_POINTS,
//att //att
WidgetInfo.BA_FAILED_ATTACKER_ATTACKS_POINTS, WidgetInfo.BA_FAILED_ATTACKER_ATTACKS_POINTS,
WidgetInfo.BA_RANGERS_KILLED, WidgetInfo.BA_RANGERS_KILLED,
WidgetInfo.BA_FIGHTERS_KILLED, WidgetInfo.BA_FIGHTERS_KILLED,
//def //def
WidgetInfo.BA_RUNNERS_PASSED_POINTS, WidgetInfo.BA_RUNNERS_PASSED_POINTS,
WidgetInfo.BA_RUNNERS_KILLED, WidgetInfo.BA_RUNNERS_KILLED,
//coll //coll
WidgetInfo.BA_EGGS_COLLECTED_POINTS, WidgetInfo.BA_EGGS_COLLECTED_POINTS,
//heal //heal
WidgetInfo.BA_HEALERS_KILLED, WidgetInfo.BA_HEALERS_KILLED,
WidgetInfo.BA_HITPOINTS_REPLENISHED_POINTS, WidgetInfo.BA_HITPOINTS_REPLENISHED_POINTS,
WidgetInfo.BA_WRONG_POISON_PACKS_POINTS WidgetInfo.BA_WRONG_POISON_PACKS_POINTS
); );
private int[] waveAmounts = new int[6]; private int[] waveAmounts = new int[6];
private int[] allPointsList = new int[10]; private int[] allPointsList = new int[10];
private int[] wavePoints = new int[6]; private int[] wavePoints = new int[6];
private int[] otherRolesPointsList = new int[4]; private int[] otherRolesPointsList = new int[4];
private String[] descriptions = { private String[] descriptions = {
" A: ", " A: ",
"; D: ", "; D: ",
"; C: ", "; C: ",
"; Vial: ", "; Vial: ",
"; H packs: ", "; H packs: ",
"; Total: "}; "; Total: "};
private String[] otherPointsDescriptions = { private String[] otherPointsDescriptions = {
" A: ", " A: ",
" D: ", " D: ",
" C: ", " C: ",
" H: " " H: "
}; };
Wave(Client client)
{
this.client = client;
}
void setWaveAmounts(int[] amounts)
{
for (int i = 0; i < amounts.length; i++)
{
waveAmounts[i] = amounts[i];
}
}
void setWavePoints(int[] points, int[] otherRolesPoints) Wave(Client client)
{ {
for (int i = 0; i < points.length; i++) this.client = client;
{ }
wavePoints[i] = points[i];
} void setWaveAmounts(int[] amounts)
for (int i = 0; i < otherRolesPoints.length; i++) {
{ System.arraycopy(amounts, 0, waveAmounts, 0, amounts.length);
otherRolesPointsList[i] = otherRolesPoints[i]; }
}
} void setWavePoints(int[] points, int[] otherRolesPoints)
void setWaveAmounts() {
{ System.arraycopy(points, 0, wavePoints, 0, points.length);
for (int i = 0; i < WIDGETS.size(); i++) System.arraycopy(otherRolesPoints, 0, otherRolesPointsList, 0, otherRolesPoints.length);
{ }
Widget w = client.getWidget(WIDGETS.get(i));
if (w != null) void setWaveAmounts()
{ {
waveAmounts[i] = Integer.parseInt(w.getText()); for (int i = 0; i < WIDGETS.size(); i++)
} {
} Widget w = client.getWidget(WIDGETS.get(i));
} if (w != null)
void setWavePoints() {
{ waveAmounts[i] = Integer.parseInt(w.getText());
for (int i = 0; i < POINTSWIDGETS.size(); i++) }
{ }
Widget w = client.getWidget(POINTSWIDGETS.get(i)); }
allPointsList[i] = Integer.parseInt(w.getText());
switch (i) void setWavePoints()
{ {
case 1: for (int i = 0; i < POINTSWIDGETS.size(); i++)
wavePoints[0] += allPointsList[i]; {
break; Widget w = client.getWidget(POINTSWIDGETS.get(i));
case 4: allPointsList[i] = Integer.parseInt(w.getText());
wavePoints[1] += allPointsList[i]; switch (i)
break; {
case 6: case 1:
wavePoints[2] += allPointsList[i]; wavePoints[0] += allPointsList[i];
break; break;
case 8: case 4:
case 9: wavePoints[1] += allPointsList[i];
wavePoints[3] += allPointsList[i]; break;
break; case 6:
default: wavePoints[2] += allPointsList[i];
break; break;
} case 8:
} case 9:
wavePoints[5] = 0; wavePoints[3] += allPointsList[i];
for (int i = 0; i < wavePoints.length-1; i++) break;
{ default:
wavePoints[5] += wavePoints[i]; break;
} }
for (int i = 0; i < POINTSWIDGETS.size(); i++) }
{ wavePoints[5] = 0;
Widget w = client.getWidget(POINTSWIDGETS.get(i)); for (int i = 0; i < wavePoints.length - 1; i++)
switch (i) {
{ wavePoints[5] += wavePoints[i];
case 0: }
otherRolesPointsList[0] += Integer.parseInt(w.getText()); for (int i = 0; i < POINTSWIDGETS.size(); i++)
otherRolesPointsList[1] += Integer.parseInt(w.getText()); {
otherRolesPointsList[2] += Integer.parseInt(w.getText()); Widget w = client.getWidget(POINTSWIDGETS.get(i));
otherRolesPointsList[3] += Integer.parseInt(w.getText()); switch (i)
break; {
case 1: case 0:
case 2: otherRolesPointsList[0] += Integer.parseInt(w.getText());
case 3: otherRolesPointsList[1] += Integer.parseInt(w.getText());
otherRolesPointsList[0] += Integer.parseInt(w.getText()); otherRolesPointsList[2] += Integer.parseInt(w.getText());
break; otherRolesPointsList[3] += Integer.parseInt(w.getText());
case 4: break;
case 5: case 1:
otherRolesPointsList[1] += Integer.parseInt(w.getText()); case 2:
break; case 3:
case 6: otherRolesPointsList[0] += Integer.parseInt(w.getText());
otherRolesPointsList[2] += Integer.parseInt(w.getText()); break;
break; case 4:
case 7: case 5:
case 8: otherRolesPointsList[1] += Integer.parseInt(w.getText());
case 9: break;
otherRolesPointsList[3] += Integer.parseInt(w.getText()); case 6:
break; otherRolesPointsList[2] += Integer.parseInt(w.getText());
default: break;
break; case 7:
} case 8:
} case 9:
} otherRolesPointsList[3] += Integer.parseInt(w.getText());
ChatMessageBuilder getWaveSummary() break;
{ default:
ChatMessageBuilder message = new ChatMessageBuilder(); break;
message.append("Wave points:"); }
for(int i = 0; i < descriptions.length; i++) }
{ }
if (i != 4)
{ ChatMessageBuilder getWaveSummary()
message.append(descriptions[i]); {
message.append(String.valueOf(waveAmounts[i])); ChatMessageBuilder message = new ChatMessageBuilder();
message.append("("); message.append("Wave points:");
if (wavePoints[i] < 0) for (int i = 0; i < descriptions.length; i++)
{ {
message.append(Color.RED, String.valueOf(wavePoints[i])); if (i != 4)
} {
else if (wavePoints[i] > 0) message.append(descriptions[i]);
{ message.append(String.valueOf(waveAmounts[i]));
message.append(Color.BLUE, String.valueOf(wavePoints[i])); message.append("(");
} if (wavePoints[i] < 0)
else {
{ message.append(Color.RED, String.valueOf(wavePoints[i]));
message.append(String.valueOf(wavePoints[i])); }
} else if (wavePoints[i] > 0)
message.append(")"); {
} message.append(Color.BLUE, String.valueOf(wavePoints[i]));
} }
message.append(System.getProperty("line.separator")); else
message.append("All roles points this wave: "); {
for(int i = 0; i < otherPointsDescriptions.length; i++) message.append(String.valueOf(wavePoints[i]));
{ }
message.append(otherPointsDescriptions[i]); message.append(")");
message.append(String.valueOf(otherRolesPointsList[i])); }
} }
return message; message.append(System.getProperty("line.separator"));
} message.append("All roles points this wave: ");
for (int i = 0; i < otherPointsDescriptions.length; i++)
{
message.append(otherPointsDescriptions[i]);
message.append(String.valueOf(otherRolesPointsList[i]));
}
return message;
}
} }

View File

@@ -32,9 +32,9 @@ import net.runelite.client.config.ConfigItem;
public interface BAToolsConfig extends Config public interface BAToolsConfig extends Config
{ {
@ConfigItem( @ConfigItem(
keyName = "defTimer", keyName = "defTimer",
name = "Defender Tick Timer", name = "Defender Tick Timer",
description = "Shows the current cycle tick of runners." description = "Shows the current cycle tick of runners."
) )
default boolean defTimer() default boolean defTimer()
{ {
@@ -42,9 +42,9 @@ public interface BAToolsConfig extends Config
} }
@ConfigItem( @ConfigItem(
keyName = "calls", keyName = "calls",
name = "Remove Incorrect Calls", name = "Remove Incorrect Calls",
description = "Remove incorrect calls." description = "Remove incorrect calls."
) )
default boolean calls() default boolean calls()
{ {
@@ -52,9 +52,9 @@ public interface BAToolsConfig extends Config
} }
@ConfigItem( @ConfigItem(
keyName = "swapLadder", keyName = "swapLadder",
name = "Swap ladder option", name = "Swap ladder option",
description = "Swap Climb-down with Quick-start in the wave lobbies" description = "Swap Climb-down with Quick-start in the wave lobbies"
) )
default boolean swapLadder() default boolean swapLadder()
{ {
@@ -62,9 +62,9 @@ public interface BAToolsConfig extends Config
} }
@ConfigItem( @ConfigItem(
keyName = "healerCodes", keyName = "healerCodes",
name = "Healer Codes", name = "Healer Codes",
description = "Overlay to show healer codes" description = "Overlay to show healer codes"
) )
default boolean healerCodes() default boolean healerCodes()
{ {
@@ -72,9 +72,9 @@ public interface BAToolsConfig extends Config
} }
@ConfigItem( @ConfigItem(
keyName = "healerMenuOption", keyName = "healerMenuOption",
name = "Healer menu options", name = "Healer menu options",
description = "asd" description = "asd"
) )
default boolean healerMenuOption() default boolean healerMenuOption()
{ {
@@ -82,9 +82,9 @@ public interface BAToolsConfig extends Config
} }
@ConfigItem( @ConfigItem(
keyName = "antiDrag", keyName = "antiDrag",
name = "Anti Drag", name = "Anti Drag",
description = "asd" description = "asd"
) )
default boolean antiDrag() default boolean antiDrag()
{ {
@@ -92,9 +92,9 @@ public interface BAToolsConfig extends Config
} }
@ConfigItem( @ConfigItem(
keyName = "antiDragDelay", keyName = "antiDragDelay",
name = "Anti Drag Delay", name = "Anti Drag Delay",
description = "asd" description = "asd"
) )
default int antiDragDelay() default int antiDragDelay()
{ {
@@ -102,9 +102,9 @@ public interface BAToolsConfig extends Config
} }
@ConfigItem( @ConfigItem(
keyName = "eggBoi", keyName = "eggBoi",
name = "Collector helper", name = "Collector helper",
description = "asd" description = "asd"
) )
default boolean eggBoi() default boolean eggBoi()
{ {
@@ -112,9 +112,9 @@ public interface BAToolsConfig extends Config
} }
@ConfigItem( @ConfigItem(
keyName = "osHelp", keyName = "osHelp",
name = "Shift OS", name = "Shift OS",
description = "asd" description = "asd"
) )
default boolean osHelp() default boolean osHelp()
{ {
@@ -122,9 +122,9 @@ public interface BAToolsConfig extends Config
} }
@ConfigItem( @ConfigItem(
keyName = "prayerMetronome", keyName = "prayerMetronome",
name = "Prayer Metronome", name = "Prayer Metronome",
description = "asd" description = "asd"
) )
default boolean prayerMetronome() default boolean prayerMetronome()
{ {
@@ -132,9 +132,9 @@ public interface BAToolsConfig extends Config
} }
@ConfigItem( @ConfigItem(
keyName = "prayerMetronomeVolume", keyName = "prayerMetronomeVolume",
name = "Prayer Metronome Volume", name = "Prayer Metronome Volume",
description = "asd" description = "asd"
) )
default int prayerMetronomeVolume() default int prayerMetronomeVolume()
{ {
@@ -142,9 +142,9 @@ public interface BAToolsConfig extends Config
} }
@ConfigItem( @ConfigItem(
keyName = "attackStyles", keyName = "attackStyles",
name = "Attack Styles", name = "Attack Styles",
description = "Hide attack styles depending on weapon." description = "Hide attack styles depending on weapon."
) )
default boolean attackStyles() default boolean attackStyles()
{ {
@@ -152,24 +152,33 @@ public interface BAToolsConfig extends Config
} }
@ConfigItem( @ConfigItem(
keyName = "removeBA", keyName = "removeBA",
name = "*Barbarian Assault Helper*", name = "*Barbarian Assault Helper*",
description = "Remove unnecessary menu options in Barbarian Assault depending on role<br>Examples: Remove attack options when not attacker<br>Remove take options when not collector" description = "Remove unnecessary menu options in Barbarian Assault depending on role<br>Examples: Remove attack options when not attacker<br>Remove take options when not collector"
) )
default boolean removeBA() { return true; } default boolean removeBA()
{
return true;
}
@ConfigItem( @ConfigItem(
keyName = "removeWrongEggs", keyName = "removeWrongEggs",
name = "Remove wrong eggs - *Barbarian Assault Helper*", name = "Remove wrong eggs - *Barbarian Assault Helper*",
description = "Remove unnecessary menu options in Barbarian Assault depending on role<br>Examples: Remove attack options when not attacker<br>Remove take options when not collector" description = "Remove unnecessary menu options in Barbarian Assault depending on role<br>Examples: Remove attack options when not attacker<br>Remove take options when not collector"
) )
default boolean removeWrongEggs() { return false; } default boolean removeWrongEggs()
{
return false;
}
@ConfigItem( @ConfigItem(
keyName = "removeWrongHealFood", keyName = "removeWrongHealFood",
name = "Remove wrong Heal Food - *Barbarian Assault Helper*", name = "Remove wrong Heal Food - *Barbarian Assault Helper*",
description = "Remove unnecessary menu options in Barbarian Assault depending on role<br>Examples: Remove attack options when not attacker<br>Remove take options when not collector" description = "Remove unnecessary menu options in Barbarian Assault depending on role<br>Examples: Remove attack options when not attacker<br>Remove take options when not collector"
) )
default boolean removeHealWrongFood() { return false; } default boolean removeHealWrongFood()
{
return false;
}
} }

View File

@@ -27,16 +27,17 @@ package net.runelite.client.plugins.batools;
import java.awt.Color; import java.awt.Color;
import java.awt.Dimension; import java.awt.Dimension;
import java.awt.Graphics2D; import java.awt.Graphics2D;
import net.runelite.api.NPCComposition;
import javax.inject.Inject;
import net.runelite.api.Client;
import net.runelite.client.ui.overlay.OverlayUtil;
import net.runelite.client.ui.overlay.Overlay;
import java.time.Duration; import java.time.Duration;
import java.time.Instant; import java.time.Instant;
import javax.inject.Inject;
import lombok.extern.slf4j.Slf4j;
import net.runelite.api.Client;
import net.runelite.api.NPCComposition;
import net.runelite.client.ui.overlay.Overlay;
import net.runelite.client.ui.overlay.OverlayLayer; import net.runelite.client.ui.overlay.OverlayLayer;
import net.runelite.client.ui.overlay.OverlayPosition; import net.runelite.client.ui.overlay.OverlayPosition;
import lombok.extern.slf4j.Slf4j; import net.runelite.client.ui.overlay.OverlayUtil;
@Slf4j @Slf4j
public class BAToolsOverlay extends Overlay public class BAToolsOverlay extends Overlay
@@ -52,16 +53,14 @@ public class BAToolsOverlay extends Overlay
private static final Color GRAY = new Color(158, 158, 158); private static final Color GRAY = new Color(158, 158, 158);
private final BAToolsConfig config; private final BAToolsConfig config;
private Client client;
private BAToolsPlugin plugin; private BAToolsPlugin plugin;
@Inject @Inject
public BAToolsOverlay(Client client, BAToolsPlugin plugin, BAToolsConfig config) public BAToolsOverlay(BAToolsPlugin plugin, BAToolsConfig config)
{ {
setPosition(OverlayPosition.DYNAMIC); setPosition(OverlayPosition.DYNAMIC);
setLayer(OverlayLayer.ABOVE_SCENE); setLayer(OverlayLayer.ABOVE_SCENE);
this.config = config; this.config = config;
this.client = client;
this.plugin = plugin; this.plugin = plugin;
} }
@@ -69,37 +68,24 @@ public class BAToolsOverlay extends Overlay
@Override @Override
public Dimension render(Graphics2D graphics) public Dimension render(Graphics2D graphics)
{ {
if(!config.healerCodes()) if (!config.healerCodes())
{ {
return null; return null;
} }
for (Healer healer : plugin.getHealers().values()) for (Healer healer : plugin.getHealers().values())
{ {
NPCComposition composition = healer.getNpc().getComposition(); Color color;
Color color = composition.getCombatLevel() > 1 ? YELLOW : ORANGE; int timeLeft = healer.getLastFoodTime() - (int) Duration.between(plugin.getWave_start(), Instant.now()).getSeconds();
if (composition.getConfigs() != null)
{
NPCComposition transformedComposition = composition.transform();
if (transformedComposition == null)
{
color = GRAY;
}
else
{
composition = transformedComposition;
}
}
int timeLeft = healer.getLastFoodTime() - (int)Duration.between(plugin.getWave_start(), Instant.now()).getSeconds();
timeLeft = timeLeft < 1 ? 0 : timeLeft; timeLeft = timeLeft < 1 ? 0 : timeLeft;
if(healer.getFoodRemaining() > 1) if (healer.getFoodRemaining() > 1)
{ {
color = GREEN; color = GREEN;
} }
else if(healer.getFoodRemaining() == 1) else if (healer.getFoodRemaining() == 1)
{ {
if(timeLeft > 0) if (timeLeft > 0)
{ {
color = RED; color = RED;
} }
@@ -118,7 +104,6 @@ public class BAToolsOverlay extends Overlay
timeLeft); timeLeft);
OverlayUtil.renderActorOverlay(graphics, healer.getNpc(), text, color); OverlayUtil.renderActorOverlay(graphics, healer.getNpc(), text, color);
} }
return null; return null;

View File

@@ -24,18 +24,16 @@
*/ */
package net.runelite.client.plugins.batools; package net.runelite.client.plugins.batools;
import net.runelite.api.Item;
import net.runelite.api.Prayer;
import net.runelite.api.SoundEffectID;
import net.runelite.api.Tile;
import net.runelite.api.kit.KitType;
import net.runelite.client.eventbus.Subscribe;
import com.google.inject.Provides; import com.google.inject.Provides;
import java.awt.event.KeyEvent; import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.time.Duration; import java.time.Duration;
import java.time.Instant; import java.time.Instant;
import java.util.*; import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject; import javax.inject.Inject;
import lombok.Getter; import lombok.Getter;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@@ -47,6 +45,8 @@ import net.runelite.api.ItemID;
import net.runelite.api.MenuEntry; import net.runelite.api.MenuEntry;
import net.runelite.api.NPC; import net.runelite.api.NPC;
import net.runelite.api.NpcID; import net.runelite.api.NpcID;
import net.runelite.api.Prayer;
import net.runelite.api.SoundEffectID;
import net.runelite.api.Varbits; import net.runelite.api.Varbits;
import net.runelite.api.coords.WorldPoint; import net.runelite.api.coords.WorldPoint;
import net.runelite.api.events.ChatMessage; import net.runelite.api.events.ChatMessage;
@@ -65,6 +65,7 @@ import net.runelite.api.widgets.WidgetID;
import net.runelite.api.widgets.WidgetInfo; import net.runelite.api.widgets.WidgetInfo;
import net.runelite.client.chat.ChatMessageManager; import net.runelite.client.chat.ChatMessageManager;
import net.runelite.client.config.ConfigManager; import net.runelite.client.config.ConfigManager;
import net.runelite.client.eventbus.Subscribe;
import net.runelite.client.game.ItemManager; import net.runelite.client.game.ItemManager;
import net.runelite.client.input.KeyListener; import net.runelite.client.input.KeyListener;
import net.runelite.client.input.KeyManager; import net.runelite.client.input.KeyManager;
@@ -79,16 +80,16 @@ import org.apache.commons.lang3.ArrayUtils;
@Slf4j @Slf4j
@PluginDescriptor( @PluginDescriptor(
name = "BA Tools", name = "BA Tools",
description = "Custom tools for Barbarian Assault", description = "Custom tools for Barbarian Assault",
tags = {"minigame", "overlay", "timer"}, tags = {"minigame", "overlay", "timer"},
type = PluginType.PVM type = PluginType.PVM
) )
public class BAToolsPlugin extends Plugin implements KeyListener public class BAToolsPlugin extends Plugin implements KeyListener
{ {
int inGameBit = 0; private int inGameBit = 0;
int tickNum; private int tickNum;
int pastCall = 0; private int pastCall = 0;
private int currentWave = 1; private int currentWave = 1;
private static final int BA_WAVE_NUM_INDEX = 2; private static final int BA_WAVE_NUM_INDEX = 2;
private final List<MenuEntry> entries = new ArrayList<>(); private final List<MenuEntry> entries = new ArrayList<>();
@@ -101,12 +102,6 @@ public class BAToolsPlugin extends Plugin implements KeyListener
@Inject @Inject
private Client client; private Client client;
@Inject
private ConfigManager configManager;
@Inject
private ChatMessageManager chatMessageManager;
@Inject @Inject
private OverlayManager overlayManager; private OverlayManager overlayManager;
@@ -166,16 +161,12 @@ public class BAToolsPlugin extends Plugin implements KeyListener
@Subscribe @Subscribe
public void onWidgetLoaded(WidgetLoaded event) public void onWidgetLoaded(WidgetLoaded event)
{ {
switch (event.getGroupId()) if (event.getGroupId() == WidgetID.BA_REWARD_GROUP_ID)
{ {
case WidgetID.BA_REWARD_GROUP_ID: Widget rewardWidget = client.getWidget(WidgetInfo.BA_REWARD_TEXT);
if (rewardWidget != null && rewardWidget.getText().contains("<br>5"))
{ {
Widget rewardWidget = client.getWidget(WidgetInfo.BA_REWARD_TEXT); tickNum = 0;
if (rewardWidget != null && rewardWidget.getText().contains("<br>5"))
{
tickNum = 0;
}
} }
} }
} }
@@ -211,38 +202,37 @@ public class BAToolsPlugin extends Plugin implements KeyListener
counter.setCount(tickNum); counter.setCount(tickNum);
if (config.defTimer()) if (config.defTimer())
{ {
//log.info("" + tickNum++);
tickNum++; tickNum++;
} }
} }
Widget weapon = client.getWidget(593, 1); Widget weapon = client.getWidget(593, 1);
if(config.attackStyles() if (config.attackStyles()
&& weapon!=null && weapon != null
&& inGameBit == 1 && inGameBit == 1
&& weapon.getText().contains("Crystal halberd") || weapon.getText().contains("Dragon claws") && weapon.getText().contains("Crystal halberd") || weapon.getText().contains("Dragon claws")
&& client.getWidget(WidgetInfo.BA_ATK_LISTEN_TEXT)!=null) && client.getWidget(WidgetInfo.BA_ATK_LISTEN_TEXT) != null)
{ {
String style = client.getWidget(WidgetInfo.BA_ATK_LISTEN_TEXT).getText(); String style = client.getWidget(WidgetInfo.BA_ATK_LISTEN_TEXT).getText();
if(style.contains("Defensive")) if (style.contains("Defensive"))
{ {
client.getWidget(WidgetInfo.COMBAT_STYLE_ONE).setHidden(true); client.getWidget(WidgetInfo.COMBAT_STYLE_ONE).setHidden(true);
client.getWidget(WidgetInfo.COMBAT_STYLE_TWO).setHidden(true); client.getWidget(WidgetInfo.COMBAT_STYLE_TWO).setHidden(true);
client.getWidget(WidgetInfo.COMBAT_STYLE_THREE).setHidden(true); client.getWidget(WidgetInfo.COMBAT_STYLE_THREE).setHidden(true);
client.getWidget(WidgetInfo.COMBAT_STYLE_FOUR).setHidden(false); client.getWidget(WidgetInfo.COMBAT_STYLE_FOUR).setHidden(false);
} }
else if(style.contains("Aggressive")) else if (style.contains("Aggressive"))
{ {
client.getWidget(WidgetInfo.COMBAT_STYLE_ONE).setHidden(true); client.getWidget(WidgetInfo.COMBAT_STYLE_ONE).setHidden(true);
client.getWidget(WidgetInfo.COMBAT_STYLE_TWO).setHidden(false); client.getWidget(WidgetInfo.COMBAT_STYLE_TWO).setHidden(false);
client.getWidget(WidgetInfo.COMBAT_STYLE_THREE).setHidden(true); client.getWidget(WidgetInfo.COMBAT_STYLE_THREE).setHidden(true);
client.getWidget(WidgetInfo.COMBAT_STYLE_FOUR).setHidden(true); client.getWidget(WidgetInfo.COMBAT_STYLE_FOUR).setHidden(true);
} }
else if(style.contains("Controlled")) else if (style.contains("Controlled"))
{ {
if(weapon.getText().contains("Crystal halberd")) if (weapon.getText().contains("Crystal halberd"))
{ {
client.getWidget(WidgetInfo.COMBAT_STYLE_ONE).setHidden(false); client.getWidget(WidgetInfo.COMBAT_STYLE_ONE).setHidden(false);
client.getWidget(WidgetInfo.COMBAT_STYLE_THREE).setHidden(true); client.getWidget(WidgetInfo.COMBAT_STYLE_THREE).setHidden(true);
@@ -255,7 +245,7 @@ public class BAToolsPlugin extends Plugin implements KeyListener
client.getWidget(WidgetInfo.COMBAT_STYLE_TWO).setHidden(true); client.getWidget(WidgetInfo.COMBAT_STYLE_TWO).setHidden(true);
client.getWidget(WidgetInfo.COMBAT_STYLE_FOUR).setHidden(true); client.getWidget(WidgetInfo.COMBAT_STYLE_FOUR).setHidden(true);
} }
else if(style.contains("Accurate") && weapon.getText().contains("Dragon claws")) else if (style.contains("Accurate") && weapon.getText().contains("Dragon claws"))
{ {
client.getWidget(WidgetInfo.COMBAT_STYLE_ONE).setHidden(false); client.getWidget(WidgetInfo.COMBAT_STYLE_ONE).setHidden(false);
client.getWidget(WidgetInfo.COMBAT_STYLE_TWO).setHidden(true); client.getWidget(WidgetInfo.COMBAT_STYLE_TWO).setHidden(true);
@@ -279,9 +269,9 @@ public class BAToolsPlugin extends Plugin implements KeyListener
client.getWidget(WidgetInfo.COMBAT_STYLE_FOUR).setHidden(false); client.getWidget(WidgetInfo.COMBAT_STYLE_FOUR).setHidden(false);
} }
if(config.prayerMetronome() && isAnyPrayerActive()) if (config.prayerMetronome() && isAnyPrayerActive())
{ {
for(int i = 0; i < config.prayerMetronomeVolume(); i++) for (int i = 0; i < config.prayerMetronomeVolume(); i++)
{ {
client.playSoundEffect(SoundEffectID.GE_INCREMENT_PLOP); client.playSoundEffect(SoundEffectID.GE_INCREMENT_PLOP);
} }
@@ -335,7 +325,7 @@ public class BAToolsPlugin extends Plugin implements KeyListener
public void onChatMessage(ChatMessage event) public void onChatMessage(ChatMessage event)
{ {
if (event.getType() == ChatMessageType.GAMEMESSAGE if (event.getType() == ChatMessageType.GAMEMESSAGE
&& event.getMessage().startsWith("---- Wave:")) && event.getMessage().startsWith("---- Wave:"))
{ {
String[] message = event.getMessage().split(" "); String[] message = event.getMessage().split(" ");
currentWave = Integer.parseInt(message[BA_WAVE_NUM_INDEX]); currentWave = Integer.parseInt(message[BA_WAVE_NUM_INDEX]);
@@ -355,7 +345,6 @@ public class BAToolsPlugin extends Plugin implements KeyListener
{ {
int spawnNumber = healers.size(); int spawnNumber = healers.size();
healers.put(npc, new Healer(npc, spawnNumber, currentWave)); healers.put(npc, new Healer(npc, spawnNumber, currentWave));
//log.info("spawn number: " + spawnNumber + " on wave " + currentWave);
} }
} }
} }
@@ -393,24 +382,24 @@ public class BAToolsPlugin extends Plugin implements KeyListener
{ {
Actor opponent = event.getTarget(); Actor opponent = event.getTarget();
if (opponent != null && opponent instanceof NPC && isNpcHealer(((NPC) opponent).getId()) && event.getSource() != client.getLocalPlayer()) if (opponent instanceof NPC && isNpcHealer(((NPC) opponent).getId()) && event.getSource() != client.getLocalPlayer())
{ {
lastInteracted = opponent; lastInteracted = opponent;
} }
} }
public static boolean isNpcHealer(int npcId) private static boolean isNpcHealer(int npcId)
{ {
return npcId == NpcID.PENANCE_HEALER || return npcId == NpcID.PENANCE_HEALER ||
npcId == NpcID.PENANCE_HEALER_5766 || npcId == NpcID.PENANCE_HEALER_5766 ||
npcId == NpcID.PENANCE_HEALER_5767 || npcId == NpcID.PENANCE_HEALER_5767 ||
npcId == NpcID.PENANCE_HEALER_5768 || npcId == NpcID.PENANCE_HEALER_5768 ||
npcId == NpcID.PENANCE_HEALER_5769 || npcId == NpcID.PENANCE_HEALER_5769 ||
npcId == NpcID.PENANCE_HEALER_5770 || npcId == NpcID.PENANCE_HEALER_5770 ||
npcId == NpcID.PENANCE_HEALER_5771 || npcId == NpcID.PENANCE_HEALER_5771 ||
npcId == NpcID.PENANCE_HEALER_5772 || npcId == NpcID.PENANCE_HEALER_5772 ||
npcId == NpcID.PENANCE_HEALER_5773 || npcId == NpcID.PENANCE_HEALER_5773 ||
npcId == NpcID.PENANCE_HEALER_5774; npcId == NpcID.PENANCE_HEALER_5774;
} }
@Subscribe @Subscribe
@@ -440,7 +429,7 @@ public class BAToolsPlugin extends Plugin implements KeyListener
if (correctCall != null) //&& callWidget.getTextColor()==16316664) if (correctCall != null) //&& callWidget.getTextColor()==16316664)
{ {
entries.add(correctCall); entries.add(correctCall);
client.setMenuEntries(entries.toArray(new MenuEntry[entries.size()])); client.setMenuEntries(entries.toArray(new MenuEntry[0]));
} }
} }
@@ -453,24 +442,31 @@ public class BAToolsPlugin extends Plugin implements KeyListener
{ {
swap(client, "quick-start", option, target, true); swap(client, "quick-start", option, target, true);
} }
else if(config.removeBA() && client.getVar(Varbits.IN_GAME_BA) == 1 && !option.contains("tell-"))//if in barbarian assault and menu isnt from a horn else if (config.removeBA() && client.getVar(Varbits.IN_GAME_BA) == 1 && !option.contains("tell-"))//if in barbarian assault and menu isnt from a horn
{ {
if(itemId == ItemID.LOGS && !target.contains("healing vial")) if (itemId == ItemID.LOGS && !target.contains("healing vial"))
{ {
if(client.getWidget(WidgetInfo.BA_DEF_ROLE_TEXT) == null) if (client.getWidget(WidgetInfo.BA_DEF_ROLE_TEXT) == null)
{
remove(new String[]{"take", "light"}, target, true); remove(new String[]{"take", "light"}, target, true);
}
else//remove "Light" option (and "Take" option if not defender). else//remove "Light" option (and "Take" option if not defender).
{
remove("light", target, true); remove("light", target, true);
}
} }
else if(option.equals("use")) else if (option.equals("use"))
{ {
if (config.removeHealWrongFood()) { if (config.removeHealWrongFood())
{
Widget healer = client.getWidget(WidgetInfo.BA_HEAL_LISTEN_TEXT); Widget healer = client.getWidget(WidgetInfo.BA_HEAL_LISTEN_TEXT);
if (healer != null) { if (healer != null)
{
String item = target.split("-")[0].trim(); String item = target.split("-")[0].trim();
List<String> poison = Arrays.asList("poisoned tofu", "poisoned meat", "poisoned worms"); List<String> poison = Arrays.asList("poisoned tofu", "poisoned meat", "poisoned worms");
List<String> vials = Arrays.asList("healing vial", "healing vial(1)", "healing vial(2)", "healing vial(3)", "healing vial(4)");//"healing vial(4)" List<String> vials = Arrays.asList("healing vial", "healing vial(1)", "healing vial(2)", "healing vial(3)", "healing vial(4)");//"healing vial(4)"
if (poison.contains(item)) {//if item is a poison item if (poison.contains(item))
{//if item is a poison item
int calledPoison = 0; int calledPoison = 0;
switch (healer.getText())//choose which poison to hide the use/destroy option for switch (healer.getText())//choose which poison to hide the use/destroy option for
{ {
@@ -491,10 +487,13 @@ public class BAToolsPlugin extends Plugin implements KeyListener
{ {
remove(new String[]{"use", "destroy", "examine"}, target, true);//remove options remove(new String[]{"use", "destroy", "examine"}, target, true);//remove options
} }
} else if (!target.contains("penance healer")) { }
else if (!target.contains("penance healer"))
{
remove(option, target, true); remove(option, target, true);
} }
} else if (vials.contains(item))//if item is the healer's healing vial }
else if (vials.contains(item))//if item is the healer's healing vial
{ {
if (!target.equals(item))//if target is not the vial itself if (!target.equals(item))//if target is not the vial itself
@@ -509,26 +508,26 @@ public class BAToolsPlugin extends Plugin implements KeyListener
} }
} }
} }
else if(option.equals("attack") && client.getWidget(WidgetInfo.BA_ATK_ROLE_TEXT) == null && !target.equals("queen spawn"))//if not attacker else if (option.equals("attack") && client.getWidget(WidgetInfo.BA_ATK_ROLE_TEXT) == null && !target.equals("queen spawn"))//if not attacker
{//remove attack option from everything but queen spawns {//remove attack option from everything but queen spawns
remove(option, target, true); remove(option, target, true);
} }
else if((option.equals("fix") || (option.equals("block") && target.equals("penance cave"))) && client.getWidget(WidgetInfo.BA_DEF_ROLE_TEXT) == null)//if not defender else if ((option.equals("fix") || (option.equals("block") && target.equals("penance cave"))) && client.getWidget(WidgetInfo.BA_DEF_ROLE_TEXT) == null)//if not defender
{//the check for option requires checking target as well because defensive attack style option is also called "block". {//the check for option requires checking target as well because defensive attack style option is also called "block".
remove(option, target, true); remove(option, target, true);
} }
else if((option.equals("load")) && client.getWidget(WidgetInfo.BA_COLL_ROLE_TEXT) == null)//if not collector, remove hopper options else if ((option.equals("load")) && client.getWidget(WidgetInfo.BA_COLL_ROLE_TEXT) == null)//if not collector, remove hopper options
{ {
remove(new String[]{option, "look-in"}, target, true); remove(new String[]{option, "look-in"}, target, true);
} }
else if(config.removeWrongEggs() && option.equals("take")) else if (config.removeWrongEggs() && option.equals("take"))
{ {
Widget eggToColl = client.getWidget(WidgetInfo.BA_COLL_LISTEN_TEXT); Widget eggToColl = client.getWidget(WidgetInfo.BA_COLL_LISTEN_TEXT);
if(eggToColl != null)//if we're a collector if (eggToColl != null)//if we're a collector
{ {
List<Integer> eggsToHide = new ArrayList<>(); List<Integer> eggsToHide = new ArrayList<>();
eggsToHide.add(ItemID.HAMMER); eggsToHide.add(ItemID.HAMMER);
switch(eggToColl.getText())//choose which eggs to hide take option for switch (eggToColl.getText())//choose which eggs to hide take option for
{ {
case "Red eggs": case "Red eggs":
eggsToHide.add(ItemID.BLUE_EGG); eggsToHide.add(ItemID.BLUE_EGG);
@@ -543,7 +542,7 @@ public class BAToolsPlugin extends Plugin implements KeyListener
eggsToHide.add(ItemID.BLUE_EGG); eggsToHide.add(ItemID.BLUE_EGG);
break; break;
} }
if(eggsToHide.contains(itemId)) if (eggsToHide.contains(itemId))
{ {
remove(option, target, true);//hide wrong eggs remove(option, target, true);//hide wrong eggs
} }
@@ -551,7 +550,7 @@ public class BAToolsPlugin extends Plugin implements KeyListener
else else
{ {
List<Integer> defenderItems = Arrays.asList(ItemID.HAMMER, ItemID.TOFU, ItemID.CRACKERS, ItemID.WORMS);//logs are handled separately due to hiding "light" option too. List<Integer> defenderItems = Arrays.asList(ItemID.HAMMER, ItemID.TOFU, ItemID.CRACKERS, ItemID.WORMS);//logs are handled separately due to hiding "light" option too.
if(client.getWidget(WidgetInfo.BA_DEF_ROLE_TEXT) == null || !defenderItems.contains(itemId))//if not defender, or item is not a defenderItem if (client.getWidget(WidgetInfo.BA_DEF_ROLE_TEXT) == null || !defenderItems.contains(itemId))//if not defender, or item is not a defenderItem
{ {
remove(option, target, true);//hide everything except hammer/logs and bait if Defender remove(option, target, true);//hide everything except hammer/logs and bait if Defender
} }
@@ -587,7 +586,7 @@ public class BAToolsPlugin extends Plugin implements KeyListener
if (client.getWidget(WidgetInfo.BA_COLL_LISTEN_TEXT) != null && inGameBit == 1 && config.eggBoi() && event.getTarget().endsWith("egg") && shiftDown) if (client.getWidget(WidgetInfo.BA_COLL_LISTEN_TEXT) != null && inGameBit == 1 && config.eggBoi() && event.getTarget().endsWith("egg") && shiftDown)
{ {
String[] currentCall = client.getWidget(WidgetInfo.BA_COLL_LISTEN_TEXT).getText().split(" "); String[] currentCall = client.getWidget(WidgetInfo.BA_COLL_LISTEN_TEXT).getText().split(" ");
//log.info("1 " + currentCall[0]);
MenuEntry[] menuEntries = client.getMenuEntries(); MenuEntry[] menuEntries = client.getMenuEntries();
MenuEntry correctEgg = null; MenuEntry correctEgg = null;
entries.clear(); entries.clear();
@@ -607,7 +606,7 @@ public class BAToolsPlugin extends Plugin implements KeyListener
{ {
entries.add(correctEgg); entries.add(correctEgg);
} }
client.setMenuEntries(entries.toArray(new MenuEntry[entries.size()])); client.setMenuEntries(entries.toArray(new MenuEntry[0]));
} }
if (client.getWidget(WidgetInfo.BA_HEAL_LISTEN_TEXT) != null && inGameBit == 1 && config.osHelp() && event.getTarget().equals("<col=ffff>Healer item machine") && shiftDown) if (client.getWidget(WidgetInfo.BA_HEAL_LISTEN_TEXT) != null && inGameBit == 1 && config.osHelp() && event.getTarget().equals("<col=ffff>Healer item machine") && shiftDown)
@@ -651,8 +650,8 @@ public class BAToolsPlugin extends Plugin implements KeyListener
String target = event.getMenuTarget(); String target = event.getMenuTarget();
if ((currentCall.equals("Pois. Worms") && (target.contains("Poisoned worms") && target.contains("->") && target.contains("Penance Healer"))) if ((currentCall.equals("Pois. Worms") && (target.contains("Poisoned worms") && target.contains("->") && target.contains("Penance Healer")))
|| (currentCall.equals("Pois. Meat") && (target.contains("Poisoned meat") && target.contains("->") && target.contains("Penance Healer"))) || (currentCall.equals("Pois. Meat") && (target.contains("Poisoned meat") && target.contains("->") && target.contains("Penance Healer")))
|| (currentCall.equals("Pois. Tofu") && (target.contains("Poisoned tofu") && target.contains("->") && target.contains("Penance Healer")))) || (currentCall.equals("Pois. Tofu") && (target.contains("Poisoned tofu") && target.contains("->") && target.contains("Penance Healer"))))
{ {
foodPressed.put(event.getId(), Instant.now()); foodPressed.put(event.getId(), Instant.now());
} }
@@ -702,7 +701,7 @@ public class BAToolsPlugin extends Plugin implements KeyListener
{ {
MenuEntry[] entries = client.getMenuEntries(); MenuEntry[] entries = client.getMenuEntries();
int idx = searchIndex(entries, option, target, strict); int idx = searchIndex(entries, option, target, strict);
if(idx >= 0 && entries[idx] != null) if (idx >= 0 && entries[idx] != null)
{ {
entries = ArrayUtils.removeElement(entries, entries[idx]); entries = ArrayUtils.removeElement(entries, entries[idx]);
client.setMenuEntries(entries); client.setMenuEntries(entries);
@@ -712,11 +711,13 @@ public class BAToolsPlugin extends Plugin implements KeyListener
private void remove(String[] options, String target, boolean strict) private void remove(String[] options, String target, boolean strict)
{ {
MenuEntry[] entries = client.getMenuEntries(); MenuEntry[] entries = client.getMenuEntries();
for(int i = 0; i < options.length; i++) for (String option : options)
{ {
int idx = searchIndex(entries, options[i], target, strict); int idx = searchIndex(entries, option, target, strict);
if(idx >= 0 && entries[idx] != null) if (idx >= 0 && entries[idx] != null)
{
entries = ArrayUtils.removeElement(entries, entries[idx]); entries = ArrayUtils.removeElement(entries, entries[idx]);
}
} }
client.setMenuEntries(entries); client.setMenuEntries(entries);
@@ -776,9 +777,9 @@ public class BAToolsPlugin extends Plugin implements KeyListener
// world point of the tile marker // world point of the tile marker
WorldPoint worldPoint = new WorldPoint( WorldPoint worldPoint = new WorldPoint(
((regionId >>> 8) << 6) + regionX, ((regionId >>> 8) << 6) + regionX,
((regionId & 0xff) << 6) + regionY, ((regionId & 0xff) << 6) + regionY,
z z
); );
int[][][] instanceTemplateChunks = client.getInstanceTemplateChunks(); int[][][] instanceTemplateChunks = client.getInstanceTemplateChunks();
@@ -791,11 +792,11 @@ public class BAToolsPlugin extends Plugin implements KeyListener
int templateChunkY = (chunkData >> 3 & 0x7FF) * CHUNK_SIZE; int templateChunkY = (chunkData >> 3 & 0x7FF) * CHUNK_SIZE;
int templateChunkX = (chunkData >> 14 & 0x3FF) * CHUNK_SIZE; int templateChunkX = (chunkData >> 14 & 0x3FF) * CHUNK_SIZE;
if (worldPoint.getX() >= templateChunkX && worldPoint.getX() < templateChunkX + CHUNK_SIZE if (worldPoint.getX() >= templateChunkX && worldPoint.getX() < templateChunkX + CHUNK_SIZE
&& worldPoint.getY() >= templateChunkY && worldPoint.getY() < templateChunkY + CHUNK_SIZE) && worldPoint.getY() >= templateChunkY && worldPoint.getY() < templateChunkY + CHUNK_SIZE)
{ {
WorldPoint p = new WorldPoint(client.getBaseX() + x * CHUNK_SIZE + (worldPoint.getX() & (CHUNK_SIZE - 1)), WorldPoint p = new WorldPoint(client.getBaseX() + x * CHUNK_SIZE + (worldPoint.getX() & (CHUNK_SIZE - 1)),
client.getBaseY() + y * CHUNK_SIZE + (worldPoint.getY() & (CHUNK_SIZE - 1)), client.getBaseY() + y * CHUNK_SIZE + (worldPoint.getY() & (CHUNK_SIZE - 1)),
worldPoint.getPlane()); worldPoint.getPlane());
p = rotate(p, rotation); p = rotate(p, rotation);
if (p.distanceTo(npc.getWorldLocation()) < 5) if (p.distanceTo(npc.getWorldLocation()) < 5)
{ {

View File

@@ -29,9 +29,9 @@ import net.runelite.client.ui.overlay.infobox.Counter;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
public class CycleCounter extends Counter class CycleCounter extends Counter
{ {
public CycleCounter(BufferedImage img, Plugin plugin, int tick) CycleCounter(BufferedImage img, Plugin plugin, int tick)
{ {
super(img, plugin, tick); super(img, plugin, tick);
} }

View File

@@ -32,7 +32,7 @@ import net.runelite.api.NPC;
import net.runelite.api.Actor; import net.runelite.api.Actor;
public class Healer class Healer
{ {
@Getter @Getter
@@ -62,9 +62,7 @@ public class Healer
@Setter @Setter
private int secondCallFood; private int secondCallFood;
Healer(NPC npc, int spawnNumber, int wave)
public Healer(NPC npc, int spawnNumber, int wave)
{ {
this.npc = npc; this.npc = npc;
this.wave = wave; this.wave = wave;
@@ -102,7 +100,4 @@ public class Healer
default: return null; default: return null;
} }
} }
} }

View File

@@ -25,9 +25,15 @@
package net.runelite.client.plugins.blackjack; package net.runelite.client.plugins.blackjack;
import com.google.inject.Binder; import com.google.inject.Binder;
import javax.inject.Inject;
import javax.inject.Singleton;
import lombok.Getter; import lombok.Getter;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import net.runelite.api.*; import net.runelite.api.ChatMessageType;
import net.runelite.api.Client;
import net.runelite.api.MenuEntry;
import net.runelite.api.Quest;
import net.runelite.api.QuestState;
import net.runelite.api.events.ChatMessage; import net.runelite.api.events.ChatMessage;
import net.runelite.api.events.GameTick; import net.runelite.api.events.GameTick;
import net.runelite.api.events.MenuEntryAdded; import net.runelite.api.events.MenuEntryAdded;
@@ -36,9 +42,6 @@ import net.runelite.client.plugins.Plugin;
import net.runelite.client.plugins.PluginDescriptor; import net.runelite.client.plugins.PluginDescriptor;
import net.runelite.client.plugins.PluginType; import net.runelite.client.plugins.PluginType;
import javax.inject.Inject;
import javax.inject.Singleton;
/** /**
* Authors gazivodag longstreet * Authors gazivodag longstreet
*/ */
@@ -127,6 +130,4 @@ public class BlackjackPlugin extends Plugin {
client.setMenuEntries(newEntries); client.setMenuEntries(newEntries);
} }
} }
} }

View File

@@ -31,10 +31,10 @@ public interface ClanManModeConfig extends Config
} }
@ConfigItem( @ConfigItem(
position = 2, position = 2,
keyName = "highlightattacked", keyName = "highlightattacked",
name = "Highlight clan targets", name = "Highlight clan targets",
description = "Highlights people being attacked by your clan" description = "Highlights people being attacked by your clan"
) )
default boolean highlightAttacked() default boolean highlightAttacked()
{ {
@@ -42,10 +42,10 @@ public interface ClanManModeConfig extends Config
} }
@ConfigItem( @ConfigItem(
position = 3, position = 3,
keyName = "attackedcolor", keyName = "attackedcolor",
name = "Clan target color", name = "Clan target color",
description = "Color of players being attacked by clan" description = "Color of players being attacked by clan"
) )
default Color getClanAttackableColor() default Color getClanAttackableColor()
{ {
@@ -86,10 +86,10 @@ public interface ClanManModeConfig extends Config
} }
@ConfigItem( @ConfigItem(
position = 7, position = 7,
keyName = "showtargets", keyName = "showtargets",
name = "Highlight My Attackers", name = "Highlight My Attackers",
description = "Shows players interacting with you" description = "Shows players interacting with you"
) )
default boolean showAttackers() default boolean showAttackers()
{ {
@@ -97,10 +97,10 @@ public interface ClanManModeConfig extends Config
} }
@ConfigItem( @ConfigItem(
position = 8, position = 8,
keyName = "attackcolor", keyName = "attackcolor",
name = "Attacker Color", name = "Attacker Color",
description = "Color of attackers" description = "Color of attackers"
) )
default Color getAttackerColor() default Color getAttackerColor()
{ {
@@ -108,58 +108,76 @@ public interface ClanManModeConfig extends Config
} }
@ConfigItem( @ConfigItem(
position = 9, position = 9,
keyName = "showbold", keyName = "showbold",
name = "Bold names of clan targets", name = "Bold names of clan targets",
description = "Turns names of clan targets bold" description = "Turns names of clan targets bold"
) )
default boolean ShowBold() { return false; } default boolean ShowBold()
{
return false;
}
@ConfigItem( @ConfigItem(
position = 10, position = 10,
keyName = "hideafter", keyName = "hideafter",
name = "Hide attackable targets after login", name = "Hide attackable targets after login",
description = "Automatically disables attackable player highlighting after login" description = "Automatically disables attackable player highlighting after login"
) )
default boolean hideAttackable() { return false; } default boolean hideAttackable()
{
return false;
}
@ConfigItem( @ConfigItem(
position = 11, position = 11,
keyName = "hidetime", keyName = "hidetime",
name = "Ticks to hide", name = "Ticks to hide",
description = "How many ticks after you are logged in that attackbles are hidden (1 tick = 0.6 seconds)" description = "How many ticks after you are logged in that attackbles are hidden (1 tick = 0.6 seconds)"
) )
default int hideTime() { return 5; } default int hideTime()
{
return 5;
}
@ConfigItem( @ConfigItem(
position = 12, position = 12,
keyName = "mycblvl", keyName = "mycblvl",
name = "Calc targets on my own combat level", name = "Calc targets on my own combat level",
description = "Calculates potential targets based off your own combat lvl instead of clans" description = "Calculates potential targets based off your own combat lvl instead of clans"
) )
default boolean CalcSelfCB() { return false; } default boolean CalcSelfCB()
{
return false;
}
@ConfigItem( @ConfigItem(
position = 13, position = 13,
keyName = "hideatkopt", keyName = "hideatkopt",
name = "Hide attack option for clan members", name = "Hide attack option for clan members",
description = "Disables attack option for clan members" description = "Disables attack option for clan members"
) )
default boolean hideAtkOpt() { return false; } default boolean hideAtkOpt()
{
return false;
}
@ConfigItem( @ConfigItem(
position = 14, position = 14,
keyName = "showclanmembers", keyName = "showclanmembers",
name = "Persistent Clan Members", name = "Persistent Clan Members",
description = "Will highlight clan members even when not in clan chat" description = "Will highlight clan members even when not in clan chat"
) )
default boolean PersistentClan() { return false; } default boolean PersistentClan()
{
return false;
}
@ConfigItem( @ConfigItem(
position = 15, position = 15,
keyName = "clancolor", keyName = "clancolor",
name = "Clan Member Color", name = "Clan Member Color",
description = "Color of clan members" description = "Color of clan members"
) )
default Color getClanMemberColor() default Color getClanMemberColor()
{ {

View File

@@ -3,10 +3,8 @@ package net.runelite.client.plugins.clanmanmode;
import java.awt.Color; import java.awt.Color;
import java.awt.Dimension; import java.awt.Dimension;
import java.awt.Graphics2D; import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
import net.runelite.api.ClanMemberRank;
import net.runelite.api.Player; import net.runelite.api.Player;
import net.runelite.api.Point; import net.runelite.api.Point;
import net.runelite.client.game.ClanManager; import net.runelite.client.game.ClanManager;
@@ -21,15 +19,12 @@ public class ClanManModeOverlay extends Overlay
{ {
private final ClanManModeService ClanManModeService; private final ClanManModeService ClanManModeService;
private final ClanManModeConfig config; private final ClanManModeConfig config;
private final ClanManager clanManager;
@Inject @Inject
private ClanManModeOverlay(ClanManModeConfig config, ClanManModeService ClanManModeService, private ClanManModeOverlay(ClanManModeConfig config, ClanManModeService ClanManModeService)
ClanManager clanManager)
{ {
this.config = config; this.config = config;
this.ClanManModeService = ClanManModeService; this.ClanManModeService = ClanManModeService;
this.clanManager = clanManager;
setPosition(OverlayPosition.DYNAMIC); setPosition(OverlayPosition.DYNAMIC);
setPriority(OverlayPriority.MED); setPriority(OverlayPriority.MED);
} }

View File

@@ -1,6 +1,5 @@
package net.runelite.client.plugins.clanmanmode; package net.runelite.client.plugins.clanmanmode;
import net.runelite.client.eventbus.Subscribe;
import com.google.inject.Provides; import com.google.inject.Provides;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
@@ -8,12 +7,17 @@ import java.util.Map;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import javax.inject.Inject; import javax.inject.Inject;
import net.runelite.api.*; import net.runelite.api.Client;
import net.runelite.api.GameState;
import net.runelite.api.MenuEntry;
import net.runelite.api.Player;
import net.runelite.api.Varbits;
import net.runelite.api.coords.WorldPoint; import net.runelite.api.coords.WorldPoint;
import net.runelite.api.events.GameStateChanged; import net.runelite.api.events.GameStateChanged;
import net.runelite.api.events.GameTick; import net.runelite.api.events.GameTick;
import net.runelite.api.events.MenuEntryAdded; import net.runelite.api.events.MenuEntryAdded;
import net.runelite.client.config.ConfigManager; import net.runelite.client.config.ConfigManager;
import net.runelite.client.eventbus.Subscribe;
import net.runelite.client.game.ClanManager; import net.runelite.client.game.ClanManager;
import net.runelite.client.plugins.Plugin; import net.runelite.client.plugins.Plugin;
import net.runelite.client.plugins.PluginDescriptor; import net.runelite.client.plugins.PluginDescriptor;
@@ -26,7 +30,8 @@ import org.apache.commons.lang3.ArrayUtils;
name = "Clan Man Mode", name = "Clan Man Mode",
description = "Assists in clan PVP scenarios", description = "Assists in clan PVP scenarios",
tags = {"highlight", "minimap", "overlay", "players"}, tags = {"highlight", "minimap", "overlay", "players"},
type = PluginType.PVP type = PluginType.PVP,
enabledByDefault = false
) )
public class ClanManModePlugin extends Plugin public class ClanManModePlugin extends Plugin
{ {
@@ -123,8 +128,8 @@ public class ClanManModePlugin extends Plugin
if (option.equals("attack")) { if (option.equals("attack")) {
final Pattern ppattern = Pattern.compile("<col=ffffff>(.+?)<col="); final Pattern ppattern = Pattern.compile("<col=ffffff>(.+?)<col=");
final Matcher pmatch = ppattern.matcher(event.getTarget()); final Matcher pmatch = ppattern.matcher(event.getTarget());
pmatch.find();
if (pmatch.matches()) { if (pmatch.find() && pmatch.matches()) {
if (pmatch.group(1) != null) { if (pmatch.group(1) != null) {
if (clan.containsKey(pmatch.group(1).replace(" ", " "))) { if (clan.containsKey(pmatch.group(1).replace(" ", " "))) {
MenuEntry[] entries = client.getMenuEntries(); MenuEntry[] entries = client.getMenuEntries();

View File

@@ -6,7 +6,6 @@ import java.util.Map;
import java.util.function.BiConsumer; import java.util.function.BiConsumer;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
import net.runelite.api.Actor; import net.runelite.api.Actor;
import net.runelite.api.Client; import net.runelite.api.Client;
import net.runelite.api.NPC; import net.runelite.api.NPC;
@@ -28,7 +27,7 @@ public class ClanManModeService
this.plugin = plugin; this.plugin = plugin;
} }
Map<String, String> interactors = new HashMap<>(); private Map<String, String> interactors = new HashMap<>();
public void forEachPlayer(final BiConsumer<Player, Color> consumer) public void forEachPlayer(final BiConsumer<Player, Color> consumer)
{ {
@@ -102,7 +101,7 @@ public class ClanManModeService
if (config.highlightAttacked()) { if (config.highlightAttacked()) {
if (interactors.containsKey(player.getName())) { if (interactors.containsKey(player.getName())) {
String attackername = interactors.get(player.getName()); String attackername = interactors.get(player.getName());
Boolean found = false; boolean found = false;
for (Player attacker : client.getPlayers()) { for (Player attacker : client.getPlayers()) {
if (attacker == null || attacker.getName() == null) { if (attacker == null || attacker.getName() == null) {
continue; continue;

View File

@@ -1,5 +1,7 @@
package net.runelite.client.plugins.climbupclimbdown; package net.runelite.client.plugins.climbupclimbdown;
import javax.inject.Inject;
import javax.inject.Singleton;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@@ -12,18 +14,16 @@ import net.runelite.client.plugins.Plugin;
import net.runelite.client.plugins.PluginDescriptor; import net.runelite.client.plugins.PluginDescriptor;
import net.runelite.client.plugins.PluginType; import net.runelite.client.plugins.PluginType;
import javax.inject.Inject;
import javax.inject.Singleton;
@PluginDescriptor( @PluginDescriptor(
name = "Climb Up Climb Down", name = "Climb Up Climb Down",
description = "Hold Shift to Climb up, Ctrl to Climb down", description = "Hold Shift to Climb up, Ctrl to Climb down",
tags = {"climb", "stairs", "ladder", "swap", "key", "input"}, tags = {"climb", "stairs", "ladder", "swap", "key", "input"},
type = PluginType.UTILITY type = PluginType.UTILITY
) )
@Slf4j @Slf4j
@Singleton @Singleton
public class ClimbPlugin extends Plugin { public class ClimbPlugin extends Plugin
{
@Inject @Inject
Client client; Client client;
@@ -37,32 +37,45 @@ public class ClimbPlugin extends Plugin {
@Getter @Getter
@Setter @Setter
private boolean isHoldingShift; private boolean isHoldingShift;
@Getter @Getter
@Setter @Setter
private boolean isHoldingCtrl; private boolean isHoldingCtrl;
@Override @Override
protected void startUp() throws Exception { protected void startUp() throws Exception
{
enableCustomization(); enableCustomization();
} }
@Override @Override
protected void shutDown() throws Exception { protected void shutDown() throws Exception
{
disableCustomization(); disableCustomization();
} }
@Subscribe @Subscribe
public void onMenuEntryAdded(MenuEntryAdded menuEntryAdded) { public void onMenuEntryAdded(MenuEntryAdded menuEntryAdded)
try { {
if (menuEntryAdded.getOption().equalsIgnoreCase("climb")) { try
if (isHoldingCtrl ^ isHoldingShift) { {
if (menuEntryAdded.getOption().equalsIgnoreCase("climb"))
{
if (isHoldingCtrl ^ isHoldingShift)
{
if (isHoldingShift) if (isHoldingShift)
{
stripExceptFor("climb-up"); stripExceptFor("climb-up");
}
if (isHoldingCtrl) if (isHoldingCtrl)
{
stripExceptFor("climb-down"); stripExceptFor("climb-down");
}
} }
} }
} catch (Exception e) { }
catch (Exception e)
{
log.error("Uh oh!", e); log.error("Uh oh!", e);
} }
} }
@@ -78,16 +91,21 @@ public class ClimbPlugin extends Plugin {
keyManager.unregisterKeyListener(inputListener); keyManager.unregisterKeyListener(inputListener);
} }
private void stripExceptFor(String option) { private void stripExceptFor(String option)
{
MenuEntry[] newEntries = new MenuEntry[1]; MenuEntry[] newEntries = new MenuEntry[1];
for (MenuEntry entry : client.getMenuEntries()) for (MenuEntry entry : client.getMenuEntries())
{
if (entry.getOption().equalsIgnoreCase(option)) if (entry.getOption().equalsIgnoreCase(option))
{
newEntries[0] = entry; newEntries[0] = entry;
}
}
if (newEntries[0] != null) if (newEntries[0] != null)
{
client.setMenuEntries(newEntries); client.setMenuEntries(newEntries);
}
} }
} }

View File

@@ -1,48 +1,60 @@
package net.runelite.client.plugins.climbupclimbdown; package net.runelite.client.plugins.climbupclimbdown;
import java.awt.event.KeyEvent;
import javax.inject.Inject;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import net.runelite.api.Client;
import net.runelite.client.input.KeyListener; import net.runelite.client.input.KeyListener;
import javax.inject.Inject;
import java.awt.event.KeyEvent;
@Slf4j @Slf4j
public class ShiftCtrlInputListener implements KeyListener { public class ShiftCtrlInputListener implements KeyListener
{
@Inject
Client client;
@Inject @Inject
ClimbPlugin plugin; ClimbPlugin plugin;
@Override @Override
public void keyTyped(KeyEvent e) { public void keyTyped(KeyEvent e)
{
} }
@Override @Override
public void keyPressed(KeyEvent e) { public void keyPressed(KeyEvent e)
switch (e.getKeyCode()) { {
switch (e.getKeyCode())
{
case KeyEvent.VK_SHIFT: case KeyEvent.VK_SHIFT:
if (plugin.isHoldingShift()) return; if (plugin.isHoldingShift())
{
return;
}
plugin.setHoldingShift(true); plugin.setHoldingShift(true);
break; break;
case KeyEvent.VK_CONTROL: case KeyEvent.VK_CONTROL:
if (plugin.isHoldingCtrl()) return; if (plugin.isHoldingCtrl())
{
return;
}
plugin.setHoldingCtrl(true); plugin.setHoldingCtrl(true);
break; break;
} }
} }
@Override @Override
public void keyReleased(KeyEvent e) { public void keyReleased(KeyEvent e)
switch (e.getKeyCode()) { {
switch (e.getKeyCode())
{
case KeyEvent.VK_SHIFT: case KeyEvent.VK_SHIFT:
if (!plugin.isHoldingShift()) return; if (!plugin.isHoldingShift())
{
return;
}
plugin.setHoldingShift(false); plugin.setHoldingShift(false);
break; break;
case KeyEvent.VK_CONTROL: case KeyEvent.VK_CONTROL:
if (!plugin.isHoldingCtrl()) return; if (!plugin.isHoldingCtrl())
{
return;
}
plugin.setHoldingCtrl(false); plugin.setHoldingCtrl(false);
break; break;
} }

View File

@@ -206,82 +206,75 @@ public class ConfigPanel extends PluginPanel
List<PluginListItem> externalPlugins = new ArrayList<>(); List<PluginListItem> externalPlugins = new ArrayList<>();
// populate pluginList with all external Plugins // populate pluginList with all external Plugins
pluginManager.getPlugins().stream() pluginManager.getPlugins().stream()
.filter(plugin -> plugin.getClass().getAnnotation(PluginDescriptor.class).type()==PluginType.EXTERNAL) .filter(plugin -> plugin.getClass().getAnnotation(PluginDescriptor.class).type().equals(PluginType.EXTERNAL))
.forEach(plugin -> .forEach(plugin ->
{ {
final PluginDescriptor descriptor = plugin.getClass().getAnnotation(PluginDescriptor.class); final PluginDescriptor descriptor = plugin.getClass().getAnnotation(PluginDescriptor.class);
final Config config = pluginManager.getPluginConfigProxy(plugin); final Config config = pluginManager.getPluginConfigProxy(plugin);
final ConfigDescriptor configDescriptor = config == null ? null : configManager.getConfigDescriptor(config); final ConfigDescriptor configDescriptor = config == null ? null : configManager.getConfigDescriptor(config);
final PluginListItem listItem = new PluginListItem(this, configManager, plugin, descriptor, config, configDescriptor); final PluginListItem listItem = new PluginListItem(this, configManager, plugin, descriptor, config, configDescriptor);
System.out.println("Started "+listItem.getName()); listItem.setPinned(pinnedPlugins.contains(listItem.getName()));
listItem.setPinned(pinnedPlugins.contains(listItem.getName())); externalPlugins.add(listItem);
externalPlugins.add(listItem); });
});
externalPlugins.sort(Comparator.comparing(PluginListItem::getName)); externalPlugins.sort(Comparator.comparing(PluginListItem::getName));
for (PluginListItem plugin : externalPlugins) pluginList.addAll(externalPlugins);
pluginList.add(plugin);
List<PluginListItem> pvmPlugins = new ArrayList<>(); List<PluginListItem> pvmPlugins = new ArrayList<>();
// populate pluginList with all PVM Plugins
pluginManager.getPlugins().stream()
.filter(plugin -> plugin.getClass().getAnnotation(PluginDescriptor.class).type().equals(PluginType.PVM))
.forEach(plugin ->
{
final PluginDescriptor descriptor = plugin.getClass().getAnnotation(PluginDescriptor.class);
final Config config = pluginManager.getPluginConfigProxy(plugin);
final ConfigDescriptor configDescriptor = config == null ? null : configManager.getConfigDescriptor(config);
final PluginListItem listItem = new PluginListItem(this, configManager, plugin, descriptor, config, configDescriptor); // populate pluginList with all non-hidden plugins
System.out.println("Started "+listItem.getName()); pluginManager.getPlugins().stream()
listItem.setPinned(pinnedPlugins.contains(listItem.getName())); .filter(plugin -> plugin.getClass().getAnnotation(PluginDescriptor.class).type().equals(PluginType.PVM))
pvmPlugins.add(listItem); .forEach(plugin ->
}); {
final PluginDescriptor descriptor = plugin.getClass().getAnnotation(PluginDescriptor.class);
final Config config = pluginManager.getPluginConfigProxy(plugin);
final ConfigDescriptor configDescriptor = config == null ? null : configManager.getConfigDescriptor(config);
final PluginListItem listItem = new PluginListItem(this, configManager, plugin, descriptor, config, configDescriptor);
listItem.setPinned(pinnedPlugins.contains(listItem.getName()));
pvmPlugins.add(listItem);
});
pvmPlugins.sort(Comparator.comparing(PluginListItem::getName)); pvmPlugins.sort(Comparator.comparing(PluginListItem::getName));
for (PluginListItem plugin : pvmPlugins) pluginList.addAll(pvmPlugins);
pluginList.add(plugin);
List<PluginListItem> pvpPlugins = new ArrayList<>(); List<PluginListItem> pvpPlugins = new ArrayList<>();
// populate pluginList with all PVP Plugins // populate pluginList with all PVP Plugins
pluginManager.getPlugins().stream() pluginManager.getPlugins().stream()
.filter(plugin -> plugin.getClass().getAnnotation(PluginDescriptor.class).type().equals(PluginType.PVP)) .filter(plugin -> plugin.getClass().getAnnotation(PluginDescriptor.class).type().equals(PluginType.PVP))
.forEach(plugin -> .forEach(plugin ->
{ {
final PluginDescriptor descriptor = plugin.getClass().getAnnotation(PluginDescriptor.class); final PluginDescriptor descriptor = plugin.getClass().getAnnotation(PluginDescriptor.class);
final Config config = pluginManager.getPluginConfigProxy(plugin); final Config config = pluginManager.getPluginConfigProxy(plugin);
final ConfigDescriptor configDescriptor = config == null ? null : configManager.getConfigDescriptor(config); final ConfigDescriptor configDescriptor = config == null ? null : configManager.getConfigDescriptor(config);
final PluginListItem listItem = new PluginListItem(this, configManager, plugin, descriptor, config, configDescriptor); final PluginListItem listItem = new PluginListItem(this, configManager, plugin, descriptor, config, configDescriptor);
System.out.println("Started "+listItem.getName()); listItem.setPinned(pinnedPlugins.contains(listItem.getName()));
listItem.setPinned(pinnedPlugins.contains(listItem.getName())); pvpPlugins.add(listItem);
pvpPlugins.add(listItem); });
});
pvpPlugins.sort(Comparator.comparing(PluginListItem::getName)); pvpPlugins.sort(Comparator.comparing(PluginListItem::getName));
for (PluginListItem plugin : pvpPlugins) pluginList.addAll(pvpPlugins);
pluginList.add(plugin);
List<PluginListItem> utilPlugins = new ArrayList<>(); List<PluginListItem> utilPlugins = new ArrayList<>();
// populate pluginList with all utility Plugins // populate pluginList with all PVP Plugins
pluginManager.getPlugins().stream() pluginManager.getPlugins().stream()
.filter(plugin -> plugin.getClass().getAnnotation(PluginDescriptor.class).type().equals(PluginType.UTILITY)) .filter(plugin -> plugin.getClass().getAnnotation(PluginDescriptor.class).type().equals(PluginType.UTILITY))
.forEach(plugin -> .forEach(plugin ->
{ {
final PluginDescriptor descriptor = plugin.getClass().getAnnotation(PluginDescriptor.class); final PluginDescriptor descriptor = plugin.getClass().getAnnotation(PluginDescriptor.class);
final Config config = pluginManager.getPluginConfigProxy(plugin); final Config config = pluginManager.getPluginConfigProxy(plugin);
final ConfigDescriptor configDescriptor = config == null ? null : configManager.getConfigDescriptor(config); final ConfigDescriptor configDescriptor = config == null ? null : configManager.getConfigDescriptor(config);
final PluginListItem listItem = new PluginListItem(this, configManager, plugin, descriptor, config, configDescriptor); final PluginListItem listItem = new PluginListItem(this, configManager, plugin, descriptor, config, configDescriptor);
System.out.println("Started "+listItem.getName()); listItem.setPinned(pinnedPlugins.contains(listItem.getName()));
listItem.setPinned(pinnedPlugins.contains(listItem.getName())); utilPlugins.add(listItem);
utilPlugins.add(listItem); });
});
utilPlugins.sort(Comparator.comparing(PluginListItem::getName)); utilPlugins.sort(Comparator.comparing(PluginListItem::getName));
for (PluginListItem plugin : utilPlugins) pluginList.addAll(utilPlugins);
pluginList.add(plugin);
// populate pluginList with all vanilla RL plugins // populate pluginList with all vanilla RL plugins
List<PluginListItem> vanillaPlugins = new ArrayList<>(); List<PluginListItem> vanillaPlugins = new ArrayList<>();
@@ -312,22 +305,20 @@ public class ConfigPanel extends PluginPanel
vanillaPlugins.add(chatColor); vanillaPlugins.add(chatColor);
vanillaPlugins.sort(Comparator.comparing(PluginListItem::getName)); vanillaPlugins.sort(Comparator.comparing(PluginListItem::getName));
for (PluginListItem plugin : vanillaPlugins) pluginList.addAll(vanillaPlugins);
pluginList.add(plugin);
// Add plugin sorter to bottom // Add plugin sorter to bottom
pluginManager.getPlugins().stream() pluginManager.getPlugins().stream()
.filter(plugin -> plugin.getClass().getAnnotation(PluginDescriptor.class).type().equals(PluginType.PLUGIN_ORGANIZER)) .filter(plugin -> plugin.getClass().getAnnotation(PluginDescriptor.class).type().equals(PluginType.PLUGIN_ORGANIZER))
.forEach(plugin -> .forEach(plugin ->
{ {
final PluginDescriptor descriptor = plugin.getClass().getAnnotation(PluginDescriptor.class); final PluginDescriptor descriptor = plugin.getClass().getAnnotation(PluginDescriptor.class);
final Config config = pluginManager.getPluginConfigProxy(plugin); final Config config = pluginManager.getPluginConfigProxy(plugin);
final ConfigDescriptor configDescriptor = config == null ? null : configManager.getConfigDescriptor(config); final ConfigDescriptor configDescriptor = config == null ? null : configManager.getConfigDescriptor(config);
final PluginListItem listItem = new PluginListItem(this, configManager, plugin, descriptor, config, configDescriptor); final PluginListItem listItem = new PluginListItem(this, configManager, plugin, descriptor, config, configDescriptor);
System.out.println("Started "+listItem.getName()); pluginList.add(listItem);
pluginList.add(listItem); });
});
} }
void refreshPluginList() void refreshPluginList()

View File

@@ -24,41 +24,43 @@
*/ */
package net.runelite.client.plugins.equipmentinspector; package net.runelite.client.plugins.equipmentinspector;
import java.awt.Color;
import net.runelite.client.config.Config; import net.runelite.client.config.Config;
import net.runelite.client.config.ConfigGroup; import net.runelite.client.config.ConfigGroup;
import net.runelite.client.config.ConfigItem; import net.runelite.client.config.ConfigItem;
import net.runelite.client.plugins.grounditems.config.ItemHighlightMode;
import net.runelite.client.plugins.grounditems.config.MenuHighlightMode;
import net.runelite.client.plugins.grounditems.config.PriceDisplayMode;
@ConfigGroup("grounditems") @ConfigGroup("grounditems")
public interface EquipmentInspectorConfig extends Config public interface EquipmentInspectorConfig extends Config
{ {
@ConfigItem( @ConfigItem(
keyName = "ShowValue", keyName = "ShowValue",
name = "Show the total value of the items", name = "Show the total value of the items",
description = "shows the total value of the items", description = "shows the total value of the items",
position = 1 position = 1
) )
default boolean ShowValue() default boolean ShowValue()
{ {
return true; return true;
} }
@ConfigItem(
keyName = "protecteditems", @ConfigItem(
name = "# of protected items", keyName = "protecteditems",
description = "Limit 4", name = "# of protected items",
position = 2 description = "Limit 4",
) position = 2
default int protecteditems() )
{ return 1; } default int protecteditems()
@ConfigItem( {
keyName = "ExactValue", return 1;
name = "Show exact value", }
description = "shows the excact gp value",
position = 3 @ConfigItem(
) keyName = "ExactValue",
default boolean ExactValue() name = "Show exact value",
{ return false; } description = "shows the excact gp value",
position = 3
)
default boolean ExactValue()
{
return false;
}
} }

View File

@@ -24,6 +24,21 @@
*/ */
package net.runelite.client.plugins.equipmentinspector; package net.runelite.client.plugins.equipmentinspector;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.util.HashMap;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.swing.BorderFactory;
import javax.swing.GroupLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import net.runelite.api.ItemComposition; import net.runelite.api.ItemComposition;
import net.runelite.api.kit.KitType; import net.runelite.api.kit.KitType;
@@ -32,15 +47,6 @@ import net.runelite.client.game.ItemManager;
import net.runelite.client.ui.ColorScheme; import net.runelite.client.ui.ColorScheme;
import net.runelite.client.ui.PluginPanel; import net.runelite.client.ui.PluginPanel;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.swing.*;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.util.HashMap;
import java.util.Map;
@Slf4j @Slf4j
@Singleton @Singleton
public class EquipmentInspectorPanel extends PluginPanel public class EquipmentInspectorPanel extends PluginPanel
@@ -71,27 +77,27 @@ public class EquipmentInspectorPanel extends PluginPanel
header = new JPanel(); header = new JPanel();
header.setLayout(new BorderLayout()); header.setLayout(new BorderLayout());
header.setBorder(new CompoundBorder( header.setBorder(new CompoundBorder(
BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(58, 58, 58)), BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(58, 58, 58)),
BorderFactory.createEmptyBorder(0, 0, 10, 0))); BorderFactory.createEmptyBorder(0, 0, 10, 0)));
nameLabel = new JLabel(NO_PLAYER_SELECTED); nameLabel = new JLabel(NO_PLAYER_SELECTED);
nameLabel.setForeground(Color.WHITE); nameLabel.setForeground(Color.WHITE);
header.add(nameLabel, BorderLayout.CENTER); header.add(nameLabel, BorderLayout.CENTER);
layout.setHorizontalGroup(layout.createParallelGroup() layout.setHorizontalGroup(layout.createParallelGroup()
.addComponent(equipmentPanels) .addComponent(equipmentPanels)
.addComponent(header) .addComponent(header)
); );
layout.setVerticalGroup(layout.createSequentialGroup() layout.setVerticalGroup(layout.createSequentialGroup()
.addComponent(header) .addComponent(header)
.addGap(10) .addGap(10)
.addComponent(equipmentPanels) .addComponent(equipmentPanels)
); );
update(new HashMap<>(), ""); update(new HashMap<>(), "");
} }
public void update(Map<KitType, ItemComposition> playerEquipment, String playerName) public void update(Map<KitType, ItemComposition> playerEquipment, String playerName)
{ {
if (playerName.isEmpty() || playerName == null) if (playerName.isEmpty())
{ {
nameLabel.setText(NO_PLAYER_SELECTED); nameLabel.setText(NO_PLAYER_SELECTED);
} }
@@ -100,18 +106,18 @@ public class EquipmentInspectorPanel extends PluginPanel
nameLabel.setText("Player: " + playerName); nameLabel.setText("Player: " + playerName);
} }
SwingUtilities.invokeLater(() -> SwingUtilities.invokeLater(() ->
{
equipmentPanels.removeAll();
playerEquipment.forEach((kitType, itemComposition) ->
{ {
equipmentPanels.removeAll(); AsyncBufferedImage itemImage = itemManager.getImage(itemComposition.getId());
playerEquipment.forEach((kitType, itemComposition) -> equipmentPanels.add(new ItemPanel(itemComposition, kitType, itemImage), c);
{ c.gridy++;
AsyncBufferedImage itemImage = itemManager.getImage(itemComposition.getId());
equipmentPanels.add(new ItemPanel(itemComposition, kitType, itemImage), c);
c.gridy++;
}); });
header.revalidate(); header.revalidate();
header.repaint(); header.repaint();
} }
); );
} }
} }

View File

@@ -26,6 +26,18 @@ package net.runelite.client.plugins.equipmentinspector;
import com.google.inject.Provides; import com.google.inject.Provides;
import java.awt.image.BufferedImage;
import java.lang.reflect.InvocationTargetException;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ScheduledExecutorService;
import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.swing.SwingUtilities;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import net.runelite.api.ChatMessageType; import net.runelite.api.ChatMessageType;
import net.runelite.api.Client; import net.runelite.api.Client;
@@ -49,208 +61,226 @@ import net.runelite.client.ui.NavigationButton;
import net.runelite.client.util.ImageUtil; import net.runelite.client.util.ImageUtil;
import net.runelite.client.util.Text; import net.runelite.client.util.Text;
import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.swing.*;
import java.awt.image.BufferedImage;
import java.lang.reflect.InvocationTargetException;
import java.text.NumberFormat;
import java.util.*;
import java.util.concurrent.ScheduledExecutorService;
@PluginDescriptor( @PluginDescriptor(
name = "Equipment Inspector", name = "Equipment Inspector",
enabledByDefault = false, enabledByDefault = false,
type = PluginType.PVP type = PluginType.PVP
) )
@Slf4j @Slf4j
public class EquipmentInspectorPlugin extends Plugin { public class EquipmentInspectorPlugin extends Plugin
{
private static final String INSPECT_EQUIPMENT = "Gear";
private static final String INSPECT_EQUIPMENT = "Gear"; @Inject
private static final String KICK_OPTION = "Kick"; @Nullable
private Client client;
@Inject @Inject
@Nullable private ItemManager itemManager;
private Client client;
@Inject @Inject
private ItemManager itemManager; private EquipmentInspectorConfig config;
@Inject @Inject
private EquipmentInspectorConfig config; private ChatMessageManager chatMessageManager;
@Inject
private MenuManager menuManager;
@Inject @Inject
private ChatMessageManager chatMessageManager; private ScheduledExecutorService executor;
@Inject
private MenuManager menuManager;
@Inject @Inject
private ScheduledExecutorService executor; private ClientToolbar pluginToolbar;
private NavigationButton navButton;
private EquipmentInspectorPanel equipmentInspectorPanel;
private int TotalPrice = 0;
private int Prot1 = 0;
private int Prot2 = 0;
private int Prot3 = 0;
private int Prot4 = 0;
@Inject @Provides
private ClientToolbar pluginToolbar; EquipmentInspectorConfig provideConfig(ConfigManager configManager)
private NavigationButton navButton; {
private EquipmentInspectorPanel equipmentInspectorPanel; return configManager.getConfig(EquipmentInspectorConfig.class);
private int TotalPrice = 0; }
private int Prot1 = 0;
private int Prot2 = 0;
private int Prot3 = 0;
private int Prot4 = 0;
@Provides @Override
EquipmentInspectorConfig provideConfig(ConfigManager configManager) { protected void startUp() throws Exception
return configManager.getConfig(EquipmentInspectorConfig.class); {
}
@Override equipmentInspectorPanel = injector.getInstance(EquipmentInspectorPanel.class);
protected void startUp() throws Exception { if (client != null)
{
menuManager.addPlayerMenuItem(INSPECT_EQUIPMENT);
}
equipmentInspectorPanel = injector.getInstance(EquipmentInspectorPanel.class); final BufferedImage icon = ImageUtil.getResourceStreamFromClass(this.getClass(), "normal.png");
if (client != null) {
menuManager.addPlayerMenuItem(INSPECT_EQUIPMENT);
}
//synchronized (ImageIO.class) navButton = NavigationButton.builder()
//{ .tooltip("Equipment Inspector")
final BufferedImage icon = ImageUtil.getResourceStreamFromClass(this.getClass(), "normal.png"); .icon(icon)
//} .priority(5)
.panel(equipmentInspectorPanel)
navButton = NavigationButton.builder() .build();
.tooltip("Equipment Inspector")
.icon(icon)
.priority(5)
.panel(equipmentInspectorPanel)
.build();
pluginToolbar.addNavigation(navButton); pluginToolbar.addNavigation(navButton);
} }
@Override @Override
protected void shutDown() throws Exception { protected void shutDown() throws Exception
{
menuManager.removePlayerMenuItem(INSPECT_EQUIPMENT); menuManager.removePlayerMenuItem(INSPECT_EQUIPMENT);
} }
@Subscribe @Subscribe
public void onPlayerMenuOptionClicked(PlayerMenuOptionClicked event) { public void onPlayerMenuOptionClicked(PlayerMenuOptionClicked event)
if (event.getMenuOption().equals(INSPECT_EQUIPMENT)) { {
if (event.getMenuOption().equals(INSPECT_EQUIPMENT))
{
executor.execute(() -> executor.execute(() ->
{ {
try { try
SwingUtilities.invokeAndWait(() -> {
{ SwingUtilities.invokeAndWait(() ->
if (!navButton.isSelected()) { {
navButton.getOnSelect().run(); if (!navButton.isSelected())
} {
}); navButton.getOnSelect().run();
} catch (InterruptedException | InvocationTargetException e) { }
});
}
catch (InterruptedException | InvocationTargetException e)
{
throw new RuntimeException(e); throw new RuntimeException(e);
} }
String playerName = Text.removeTags(event.getMenuTarget()); String playerName = Text.removeTags(event.getMenuTarget());
// The player menu uses a non-breaking space in the player name, we need to replace this to compare // The player menu uses a non-breaking space in the player name, we need to replace this to compare
// against the playerName in the player cache. // against the playerName in the player cache.
String finalPlayerName = playerName.replace('\u00A0', ' '); String finalPlayerName = playerName.replace('\u00A0', ' ');
System.out.println(finalPlayerName); System.out.println(finalPlayerName);
List<Player> players = client.getPlayers(); List<Player> players = client.getPlayers();
Optional<Player> targetPlayer = players.stream() Optional<Player> targetPlayer = players.stream()
.filter(Objects::nonNull) .filter(Objects::nonNull)
.filter(p -> p.getName().equals(finalPlayerName)).findFirst(); .filter(p -> p.getName().equals(finalPlayerName)).findFirst();
if (targetPlayer.isPresent()) { if (targetPlayer.isPresent())
TotalPrice = 0; {
Prot1 = 0; TotalPrice = 0;
Prot2 = 0; Prot1 = 0;
Prot3 = 0; Prot2 = 0;
Prot4 = 0; Prot3 = 0;
Player p = targetPlayer.get(); Prot4 = 0;
Map<KitType, ItemComposition> playerEquipment = new HashMap<>(); Player p = targetPlayer.get();
Map<KitType, ItemComposition> playerEquipment = new HashMap<>();
for (KitType kitType : KitType.values()) { for (KitType kitType : KitType.values())
if (kitType == KitType.RING) continue; //prevents the equipment inspector from breaking {
if (kitType == KitType.AMMUNITION) continue; if (kitType == KitType.RING)
{
continue; //prevents the equipment inspector from breaking
}
if (kitType == KitType.AMMUNITION)
{
continue;
}
int itemId = p.getPlayerComposition().getEquipmentId(kitType); int itemId = p.getPlayerComposition().getEquipmentId(kitType);
if (itemId != -1) { if (itemId != -1)
ItemComposition itemComposition = client.getItemDefinition(itemId); {
playerEquipment.put(kitType, itemComposition); ItemComposition itemComposition = client.getItemDefinition(itemId);
int ItemPrice = itemManager.getItemPrice(itemId); playerEquipment.put(kitType, itemComposition);
TotalPrice += ItemPrice; int ItemPrice = itemManager.getItemPrice(itemId);
if (ItemPrice > Prot1) { TotalPrice += ItemPrice;
Prot4 = Prot3; if (ItemPrice > Prot1)
Prot3 = Prot2; {
Prot2 = Prot1; Prot4 = Prot3;
Prot3 = Prot2;
Prot2 = Prot1;
Prot1 = ItemPrice; Prot1 = ItemPrice;
} else if (ItemPrice > Prot2) { }
Prot4 = Prot3; else if (ItemPrice > Prot2)
Prot3 = Prot2; {
Prot2 = ItemPrice; Prot4 = Prot3;
} else if (ItemPrice > Prot3) { Prot3 = Prot2;
Prot4 = Prot3; Prot2 = ItemPrice;
Prot3 = ItemPrice; }
} else if (ItemPrice > Prot4) { else if (ItemPrice > Prot3)
Prot4 = ItemPrice; {
} Prot4 = Prot3;
} Prot3 = ItemPrice;
} }
int IgnoredItems = config.protecteditems(); else if (ItemPrice > Prot4)
if (IgnoredItems != 0 && IgnoredItems != 1 && IgnoredItems != 2 && IgnoredItems != 3) { {
IgnoredItems = 4; Prot4 = ItemPrice;
}
}
}
int IgnoredItems = config.protecteditems();
if (IgnoredItems != 0 && IgnoredItems != 1 && IgnoredItems != 2 && IgnoredItems != 3)
{
IgnoredItems = 4;
} }
if (config.ShowValue()) { if (config.ShowValue())
switch (IgnoredItems) { {
case 1: switch (IgnoredItems)
TotalPrice = TotalPrice - Prot1; {
break; case 1:
case 2: TotalPrice = TotalPrice - Prot1;
TotalPrice = TotalPrice - Prot1; break;
TotalPrice = TotalPrice - Prot2; case 2:
TotalPrice = TotalPrice - Prot1;
TotalPrice = TotalPrice - Prot2;
break; break;
case 3: case 3:
TotalPrice = TotalPrice - Prot1; TotalPrice = TotalPrice - Prot1;
TotalPrice = TotalPrice - Prot2; TotalPrice = TotalPrice - Prot2;
TotalPrice = TotalPrice - Prot3; TotalPrice = TotalPrice - Prot3;
break; break;
case 4: case 4:
TotalPrice = TotalPrice - Prot1; TotalPrice = TotalPrice - Prot1;
TotalPrice = TotalPrice - Prot2; TotalPrice = TotalPrice - Prot2;
TotalPrice = TotalPrice - Prot3; TotalPrice = TotalPrice - Prot3;
TotalPrice = TotalPrice - Prot4; TotalPrice = TotalPrice - Prot4;
break; break;
} }
String StringPrice = ""; String StringPrice = "";
if (!config.ExactValue()) { if (!config.ExactValue())
TotalPrice = TotalPrice / 1000; {
StringPrice = NumberFormat.getIntegerInstance().format(TotalPrice); TotalPrice = TotalPrice / 1000;
StringPrice = StringPrice + 'K'; StringPrice = NumberFormat.getIntegerInstance().format(TotalPrice);
} StringPrice = StringPrice + 'K';
if (config.ExactValue()) { }
StringPrice = NumberFormat.getIntegerInstance().format(TotalPrice); if (config.ExactValue())
} {
chatMessageManager.queue(QueuedMessage.builder() StringPrice = NumberFormat.getIntegerInstance().format(TotalPrice);
.type(ChatMessageType.FRIENDSCHATNOTIFICATION) }
.runeLiteFormattedMessage(new ChatMessageBuilder() chatMessageManager.queue(QueuedMessage.builder()
.append(ChatColorType.HIGHLIGHT) .type(ChatMessageType.FRIENDSCHATNOTIFICATION)
.append("Risked Value: ") .runeLiteFormattedMessage(new ChatMessageBuilder()
.append(ChatColorType.NORMAL) .append(ChatColorType.HIGHLIGHT)
.append(StringPrice) .append("Risked Value: ")
.build()) .append(ChatColorType.NORMAL)
.build()); .append(StringPrice)
} .build())
equipmentInspectorPanel.update(playerEquipment, playerName); .build());
}
equipmentInspectorPanel.update(playerEquipment, playerName);
} }
}); });
} }
} }
} }

View File

@@ -24,6 +24,10 @@
*/ */
package net.runelite.client.plugins.equipmentinspector; package net.runelite.client.plugins.equipmentinspector;
import javax.swing.GroupLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import net.runelite.api.ItemComposition; import net.runelite.api.ItemComposition;
import net.runelite.api.kit.KitType; import net.runelite.api.kit.KitType;
import net.runelite.client.game.AsyncBufferedImage; import net.runelite.client.game.AsyncBufferedImage;
@@ -31,12 +35,8 @@ import net.runelite.client.ui.ColorScheme;
import net.runelite.client.ui.FontManager; import net.runelite.client.ui.FontManager;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
class ItemPanel extends JPanel class ItemPanel extends JPanel
{ {
ItemPanel(ItemComposition item, KitType kitType, AsyncBufferedImage icon) ItemPanel(ItemComposition item, KitType kitType, AsyncBufferedImage icon)
{ {

View File

@@ -61,8 +61,7 @@ import org.apache.commons.lang3.ArrayUtils;
name = "Fight Cave", name = "Fight Cave",
description = "Displays current and upcoming wave monsters in the Fight Caves", description = "Displays current and upcoming wave monsters in the Fight Caves",
tags = {"bosses", "combat", "minigame", "overlay", "pve", "pvm", "jad", "fire", "cape", "wave"}, tags = {"bosses", "combat", "minigame", "overlay", "pve", "pvm", "jad", "fire", "cape", "wave"},
type = PluginType.PVM, type = PluginType.PVM
enabledByDefault = false
) )
public class FightCavePlugin extends Plugin public class FightCavePlugin extends Plugin

View File

@@ -29,180 +29,198 @@ import net.runelite.client.config.ConfigGroup;
import net.runelite.client.config.ConfigItem; import net.runelite.client.config.ConfigItem;
@ConfigGroup("flexo") @ConfigGroup("flexo")
public interface FlexoConfig extends Config { public interface FlexoConfig extends Config
{
@ConfigItem( @ConfigItem(
position = 0, position = 0,
keyName = "overlayEnabled", keyName = "overlayEnabled",
name = "Overlay Enabled", name = "Overlay Enabled",
description = "Shows clicking area and points etc." description = "Shows clicking area and points etc."
) )
default boolean overlayEnabled() { default boolean overlayEnabled()
return true; {
} return true;
}
@ConfigItem( @ConfigItem(
position = 1, position = 1,
keyName = "minDelayAmount", keyName = "minDelayAmount",
name = "Min Delay", name = "Min Delay",
description = "Minimum delay that is applied to every action at the end (ms)" description = "Minimum delay that is applied to every action at the end (ms)"
) )
default int minDelayAmt() { default int minDelayAmt()
return 45; {
} return 45;
}
@ConfigItem( @ConfigItem(
position = 2, position = 2,
keyName = "reactionTime", keyName = "reactionTime",
name = "Reaction Time", name = "Reaction Time",
description = "The base time between actions (ms)" description = "The base time between actions (ms)"
) )
default int getReactionTimeVariation() { default int getReactionTimeVariation()
return 80; {
} return 80;
}
@ConfigItem( @ConfigItem(
position = 3, position = 3,
keyName = "mouseDragSpeed", keyName = "mouseDragSpeed",
name = "Mouse drag speed", name = "Mouse drag speed",
description = "The speed at which steps are executed. Keep at 49? cuz jagex mouse recorder?" description = "The speed at which steps are executed. Keep at 49? cuz jagex mouse recorder?"
) )
default int getMouseDragSpeed() { default int getMouseDragSpeed()
return 49; {
} return 49;
}
@ConfigItem( @ConfigItem(
position = 4, position = 4,
keyName = "overshoots", keyName = "overshoots",
name = "Overshoots", name = "Overshoots",
description = "Higher number = more overshoots" description = "Higher number = more overshoots"
) )
default int getOvershoots() { default int getOvershoots()
return 4; {
} return 4;
}
@ConfigItem( @ConfigItem(
position = 5, position = 5,
keyName = "variatingFlow", keyName = "variatingFlow",
name = "Flow - Variating", name = "Flow - Variating",
description = "" description = ""
) )
default boolean getVariatingFlow() { default boolean getVariatingFlow()
return true; {
} return true;
}
@ConfigItem( @ConfigItem(
position = 6, position = 6,
keyName = "slowStartupFlow", keyName = "slowStartupFlow",
name = "Flow - Slow startup", name = "Flow - Slow startup",
description = "" description = ""
) )
default boolean getSlowStartupFlow() { default boolean getSlowStartupFlow()
return true; {
} return true;
}
@ConfigItem( @ConfigItem(
position = 7, position = 7,
keyName = "slowStartup2Flow", keyName = "slowStartup2Flow",
name = "Flow - Slow startup 2", name = "Flow - Slow startup 2",
description = "" description = ""
) )
default boolean getSlowStartup2Flow() { default boolean getSlowStartup2Flow()
return true; {
} return true;
}
@ConfigItem( @ConfigItem(
position = 8, position = 8,
keyName = "jaggedFlow", keyName = "jaggedFlow",
name = "Flow - Jagged", name = "Flow - Jagged",
description = "" description = ""
) )
default boolean getJaggedFlow() { default boolean getJaggedFlow()
return true; {
} return true;
}
@ConfigItem( @ConfigItem(
position = 9, position = 9,
keyName = "interruptedFlow", keyName = "interruptedFlow",
name = "Flow - Interrupted", name = "Flow - Interrupted",
description = "" description = ""
) )
default boolean getInterruptedFlow() { default boolean getInterruptedFlow()
return false; {
} return false;
}
@ConfigItem( @ConfigItem(
position = 10, position = 10,
keyName = "interruptedFlow2", keyName = "interruptedFlow2",
name = "Flow - Interrupted 2", name = "Flow - Interrupted 2",
description = "" description = ""
) )
default boolean getInterruptedFlow2() { default boolean getInterruptedFlow2()
return false; {
} return false;
}
@ConfigItem( @ConfigItem(
position = 11, position = 11,
keyName = "stoppingFlow", keyName = "stoppingFlow",
name = "Flow - Stopping", name = "Flow - Stopping",
description = "" description = ""
) )
default boolean getStoppingFlow() { default boolean getStoppingFlow()
return false; {
} return false;
}
@ConfigItem( @ConfigItem(
position = 12, position = 12,
keyName = "deviationSlopeDivider", keyName = "deviationSlopeDivider",
name = "Deviation slope divider", name = "Deviation slope divider",
description = "" description = ""
) )
default int getDeviationSlope() { default int getDeviationSlope()
return 10; {
} return 10;
}
@ConfigItem( @ConfigItem(
position = 13, position = 13,
keyName = "noisinessDivider", keyName = "noisinessDivider",
name = "Noisiness divider", name = "Noisiness divider",
description = "" description = ""
) )
default String getNoisinessDivider() { default String getNoisinessDivider()
return "2.0D"; {
} return "2.0D";
}
@ConfigItem( @ConfigItem(
position = 14, position = 14,
keyName = "debugNPCs", keyName = "debugNPCs",
name = "Debug NPCs", name = "Debug NPCs",
description = "Draws clickArea and clickPoints across all visible npcs" description = "Draws clickArea and clickPoints across all visible npcs"
) )
default boolean getDebugNPCs() { default boolean getDebugNPCs()
return false; {
} return false;
}
@ConfigItem( @ConfigItem(
position = 15, position = 15,
keyName = "debugPlayers", keyName = "debugPlayers",
name = "Debug Players", name = "Debug Players",
description = "Draws clickArea and clickPoints across all visible players" description = "Draws clickArea and clickPoints across all visible players"
) )
default boolean getDebugPlayers() { default boolean getDebugPlayers()
return false; {
} return false;
}
@ConfigItem( @ConfigItem(
position = 16, position = 16,
keyName = "debugGroundItems", keyName = "debugGroundItems",
name = "Debug Ground Items", name = "Debug Ground Items",
description = "Draws clickArea and clickPoints across all visible ground items" description = "Draws clickArea and clickPoints across all visible ground items"
) )
default boolean getDebugGroundItems() { default boolean getDebugGroundItems()
return false; {
} return false;
}
} }

View File

@@ -27,66 +27,74 @@
package net.runelite.client.plugins.flexo; package net.runelite.client.plugins.flexo;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.geom.Line2D;
import java.util.ArrayList;
import javax.annotation.Nullable;
import javax.inject.Inject;
import net.runelite.api.Client; import net.runelite.api.Client;
import net.runelite.client.ui.overlay.Overlay; import net.runelite.client.ui.overlay.Overlay;
import net.runelite.client.ui.overlay.OverlayLayer; import net.runelite.client.ui.overlay.OverlayLayer;
import net.runelite.client.ui.overlay.OverlayPosition; import net.runelite.client.ui.overlay.OverlayPosition;
import javax.annotation.Nullable; public class FlexoOverlay extends Overlay
import javax.inject.Inject; {
import java.awt.*; private static Rectangle clickArea;
import java.awt.geom.Line2D;
import java.util.ArrayList;
public class FlexoOverlay extends Overlay { ArrayList<Rectangle> clickAreas = new ArrayList<>();
ArrayList<Point> clickPoints = new ArrayList<>();
public static Rectangle clickArea; @Inject
public ArrayList<Rectangle> clickAreas = new ArrayList<>(); private FlexoConfig config;
public ArrayList<Point> clickPoints = new ArrayList<>();
@Inject @Inject
private Client client; public FlexoOverlay(FlexoConfig config)
{
@Inject setPosition(OverlayPosition.DYNAMIC);
private FlexoPlugin plugin; setLayer(OverlayLayer.ABOVE_WIDGETS);
this.config = config;
@Inject }
private FlexoConfig config;
@Inject
public FlexoOverlay(@Nullable Client client, FlexoPlugin plugin, FlexoConfig config) {
setPosition(OverlayPosition.DYNAMIC);
setLayer(OverlayLayer.ABOVE_WIDGETS);
this.client = client;
this.plugin = plugin;
this.config = config;
}
@Override @Override
public Dimension render(Graphics2D graphics) { public Dimension render(Graphics2D graphics)
if (config.getDebugNPCs() || config.getDebugGroundItems() || config.getDebugPlayers()) { {
if (clickArea!=null) if (config.getDebugNPCs() || config.getDebugGroundItems() || config.getDebugPlayers())
graphics.draw(clickArea); {
if (clickAreas!=null) { if (clickArea != null)
for (Rectangle clickArea : clickAreas) { {
if (clickArea!=null) graphics.draw(clickArea);
graphics.draw(clickArea); }
} if (clickAreas != null)
} {
if (clickPoints!=null) { for (Rectangle clickArea : clickAreas)
for (Point p : clickPoints) { {
if (p!=null) { if (clickArea != null)
graphics.setColor(Color.MAGENTA); {
graphics.draw(new Line2D.Double(p.x, p.y, p.x, p.y)); graphics.draw(clickArea);
graphics.draw(new Line2D.Double(p.x-1, p.y-1, p.x-1, p.y-1)); }
graphics.draw(new Line2D.Double(p.x+1, p.y+1, p.x+1, p.y+1)); }
graphics.draw(new Line2D.Double(p.x-1, p.y+1, p.x-1, p.y+1)); }
graphics.draw(new Line2D.Double(p.x+1, p.y-1, p.x+1, p.y-1)); if (clickPoints != null)
} {
} for (Point p : clickPoints)
} {
} if (p != null)
return null; {
} graphics.setColor(Color.MAGENTA);
graphics.draw(new Line2D.Double(p.x, p.y, p.x, p.y));
graphics.draw(new Line2D.Double(p.x - 1, p.y - 1, p.x - 1, p.y - 1));
graphics.draw(new Line2D.Double(p.x + 1, p.y + 1, p.x + 1, p.y + 1));
graphics.draw(new Line2D.Double(p.x - 1, p.y + 1, p.x - 1, p.y + 1));
graphics.draw(new Line2D.Double(p.x + 1, p.y - 1, p.x + 1, p.y - 1));
}
}
}
}
return null;
}
} }

View File

@@ -35,6 +35,11 @@ import com.github.joonasvali.naturalmouse.support.Flow;
import com.github.joonasvali.naturalmouse.support.SinusoidalDeviationProvider; import com.github.joonasvali.naturalmouse.support.SinusoidalDeviationProvider;
import com.github.joonasvali.naturalmouse.util.FlowTemplates; import com.github.joonasvali.naturalmouse.util.FlowTemplates;
import com.google.inject.Provides; import com.google.inject.Provides;
import java.awt.AWTException;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import net.runelite.api.Client; import net.runelite.api.Client;
import net.runelite.api.NPC; import net.runelite.api.NPC;
import net.runelite.api.Perspective; import net.runelite.api.Perspective;
@@ -42,7 +47,6 @@ import net.runelite.api.Player;
import net.runelite.api.coords.LocalPoint; import net.runelite.api.coords.LocalPoint;
import net.runelite.api.events.BeforeRender; import net.runelite.api.events.BeforeRender;
import net.runelite.api.events.ConfigChanged; import net.runelite.api.events.ConfigChanged;
import net.runelite.api.events.GameTick;
import net.runelite.client.config.ConfigManager; import net.runelite.client.config.ConfigManager;
import net.runelite.client.eventbus.Subscribe; import net.runelite.client.eventbus.Subscribe;
import net.runelite.client.flexo.Flexo; import net.runelite.client.flexo.Flexo;
@@ -56,178 +60,227 @@ import net.runelite.client.plugins.stretchedmode.StretchedModeConfig;
import net.runelite.client.ui.ClientUI; import net.runelite.client.ui.ClientUI;
import net.runelite.client.ui.overlay.OverlayManager; import net.runelite.client.ui.overlay.OverlayManager;
import javax.inject.Inject;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
@PluginDescriptor( @PluginDescriptor(
name = "Flexo Config", name = "Flexo Config",
description = "Customizes the flexo api", description = "Customizes the flexo api",
tags = {"flexo", "null"}, tags = {"flexo", "null"},
type = PluginType.UTILITY type = PluginType.UTILITY
) )
public class FlexoPlugin extends Plugin { public class FlexoPlugin extends Plugin
{
private Flexo flexo;
private Flexo flexo; {
try
{
flexo = new Flexo();
}
catch (AWTException e)
{
e.printStackTrace();
}
}
{ @Inject
try { private Client client;
flexo = new Flexo();
} catch (AWTException e) {
e.printStackTrace();
}
}
@Inject @Inject
private Client client; private ClientUI clientUI;
@Inject @Inject
private ClientUI clientUI; private ConfigManager configManager;
@Inject @Inject
private ConfigManager configManager; private OverlayManager overlayManager;
@Inject @Inject
private OverlayManager overlayManager; private FlexoOverlay overlay;
@Inject @Provides
private FlexoOverlay overlay; FlexoConfig getConfig(ConfigManager configManager)
{
return configManager.getConfig(FlexoConfig.class);
}
@Provides @Subscribe
FlexoConfig getConfig(ConfigManager configManager) { private void onConfigChanged(ConfigChanged event)
return configManager.getConfig(FlexoConfig.class); {
} if (event.getKey().compareTo("overlayEnabled") == 0)
{
@Subscribe if (getConfig(configManager).overlayEnabled())
private void onConfigChanged(ConfigChanged event) { {
if (event.getKey().compareTo("overlayEnabled")==0) { overlayManager.add(overlay);
if (getConfig(configManager).overlayEnabled()) { }
overlayManager.add(overlay); else
} else { {
overlayManager.remove(overlay); overlayManager.remove(overlay);
} }
} }
updateMouseMotionFactory(); updateMouseMotionFactory();
} }
@Subscribe @Subscribe
public void onBeforeRender(BeforeRender event) { public void onBeforeRender(BeforeRender event)
if (Flexo.client==null) {
Flexo.client = client; if (Flexo.client == null)
if (Flexo.clientUI==null) {
Flexo.clientUI = clientUI; Flexo.client = client;
overlay.clickAreas = new ArrayList<>(); }
overlay.clickPoints = new ArrayList<>(); if (Flexo.clientUI == null)
if (getConfig(configManager).getDebugNPCs()) { {
Flexo.isStretched = client.isStretchedEnabled(); Flexo.clientUI = clientUI;
Flexo.scale = configManager.getConfig(StretchedModeConfig.class).scalingFactor(); }
if (flexo != null) overlay.clickAreas = new ArrayList<>();
for (NPC npc : client.getNpcs()) { overlay.clickPoints = new ArrayList<>();
if (npc != null) if (getConfig(configManager).getDebugNPCs())
if (npc.getConvexHull() != null) { {
Rectangle r = FlexoMouse.getClickArea(npc.getConvexHull().getBounds()); Flexo.isStretched = client.isStretchedEnabled();
overlay.clickAreas.add(r); Flexo.scale = configManager.getConfig(StretchedModeConfig.class).scalingFactor();
java.awt.Point p = FlexoMouse.getClickPoint(r); if (flexo != null)
overlay.clickPoints.add(p); {
} for (NPC npc : client.getNpcs())
} {
} if (npc != null)
{
if (npc.getConvexHull() != null)
{
Rectangle r = FlexoMouse.getClickArea(npc.getConvexHull().getBounds());
overlay.clickAreas.add(r);
java.awt.Point p = FlexoMouse.getClickPoint(r);
overlay.clickPoints.add(p);
}
}
}
}
}
if (getConfig(configManager).getDebugPlayers()) { if (getConfig(configManager).getDebugPlayers())
Flexo.isStretched = client.isStretchedEnabled(); {
Flexo.scale = configManager.getConfig(StretchedModeConfig.class).scalingFactor(); Flexo.isStretched = client.isStretchedEnabled();
if (flexo != null) Flexo.scale = configManager.getConfig(StretchedModeConfig.class).scalingFactor();
for (Player player : client.getPlayers()) { if (flexo != null)
if (player != null) {
if (player.getConvexHull() != null) { for (Player player : client.getPlayers())
Rectangle r = FlexoMouse.getClickArea(player.getConvexHull().getBounds()); {
overlay.clickAreas.add(r); if (player != null)
java.awt.Point p = FlexoMouse.getClickPoint(r); {
overlay.clickPoints.add(p); if (player.getConvexHull() != null)
} {
} Rectangle r = FlexoMouse.getClickArea(player.getConvexHull().getBounds());
} overlay.clickAreas.add(r);
java.awt.Point p = FlexoMouse.getClickPoint(r);
overlay.clickPoints.add(p);
}
}
}
}
}
//Could still use some improvement // Could still use some improvement
if (getConfig(configManager).getDebugGroundItems()) { if (getConfig(configManager).getDebugGroundItems())
Flexo.isStretched = client.isStretchedEnabled(); {
Flexo.scale = configManager.getConfig(StretchedModeConfig.class).scalingFactor(); Flexo.isStretched = client.isStretchedEnabled();
if (flexo != null) Flexo.scale = configManager.getConfig(StretchedModeConfig.class).scalingFactor();
if (GroundItemsPlugin.getCollectedGroundItems()!=null)
for (GroundItem gi : GroundItemsPlugin.getCollectedGroundItems().values()) {
if (gi != null)
if (Perspective.getCanvasTilePoly(client, LocalPoint.fromWorld(client, gi.getLocation()))!=null) {
Rectangle r1 = FlexoMouse.getClickArea(Perspective.getCanvasTilePoly(client, LocalPoint.fromWorld(client, gi.getLocation())).getBounds());
Rectangle r2 = FlexoMouse.getClickArea(r1);
Rectangle r3 = FlexoMouse.getClickArea(r2);
overlay.clickAreas.add(r3);
java.awt.Point p = FlexoMouse.getClickPoint(r3);
overlay.clickPoints.add(p);
}
}
}
}
@Subscribe if (flexo != null)
public void onGameTick(GameTick event) { {
if (GroundItemsPlugin.getCollectedGroundItems() != null)
{
for (GroundItem gi : GroundItemsPlugin.getCollectedGroundItems().values())
{
if (gi != null)
{
LocalPoint lp = LocalPoint.fromWorld(client, gi.getLocation());
if (lp != null)
{
if (Perspective.getCanvasTilePoly(client, lp) != null)
{
Rectangle r1 = FlexoMouse.getClickArea(Perspective.getCanvasTilePoly(client, lp).getBounds());
Rectangle r2 = FlexoMouse.getClickArea(r1);
Rectangle r3 = FlexoMouse.getClickArea(r2);
overlay.clickAreas.add(r3);
java.awt.Point p = FlexoMouse.getClickPoint(r3);
overlay.clickPoints.add(p);
}
}
}
}
}
}
}
}
} private void updateMouseMotionFactory()
{
Flexo.minDelay = getConfig(configManager).minDelayAmt();
MouseMotionFactory factory = new MouseMotionFactory();
// TODO:Add Options for various flows to allow more personalization
List<Flow> flows = new ArrayList<>();
private void updateMouseMotionFactory() { // Always add random
Flexo.minDelay = getConfig(configManager).minDelayAmt(); flows.add(new Flow(FlowTemplates.random()));
MouseMotionFactory factory = new MouseMotionFactory();
//TODO:Add Options for various flows to allow more personalization
List<Flow> flows = new ArrayList<>();
//Always add random if (getConfig(configManager).getVariatingFlow())
flows.add(new Flow(FlowTemplates.random())); {
flows.add(new Flow(FlowTemplates.variatingFlow()));
}
if (getConfig(configManager).getVariatingFlow()) if (getConfig(configManager).getSlowStartupFlow())
flows.add(new Flow(FlowTemplates.variatingFlow())); {
flows.add(new Flow(FlowTemplates.slowStartupFlow()));
}
if (getConfig(configManager).getSlowStartupFlow()) if (getConfig(configManager).getSlowStartup2Flow())
flows.add(new Flow(FlowTemplates.slowStartupFlow())); {
flows.add(new Flow(FlowTemplates.slowStartup2Flow()));
}
if (getConfig(configManager).getSlowStartup2Flow()) if (getConfig(configManager).getJaggedFlow())
flows.add(new Flow(FlowTemplates.slowStartup2Flow())); {
flows.add(new Flow(FlowTemplates.jaggedFlow()));
}
if (getConfig(configManager).getJaggedFlow()) if (getConfig(configManager).getInterruptedFlow())
flows.add(new Flow(FlowTemplates.jaggedFlow())); {
flows.add(new Flow(FlowTemplates.interruptedFlow()));
}
if (getConfig(configManager).getInterruptedFlow()) if (getConfig(configManager).getInterruptedFlow2())
flows.add(new Flow(FlowTemplates.interruptedFlow())); {
flows.add(new Flow(FlowTemplates.interruptedFlow2()));
}
if (getConfig(configManager).getInterruptedFlow2()) if (getConfig(configManager).getStoppingFlow())
flows.add(new Flow(FlowTemplates.interruptedFlow2())); {
flows.add(new Flow(FlowTemplates.stoppingFlow()));
}
if (getConfig(configManager).getStoppingFlow()) DefaultSpeedManager manager = new DefaultSpeedManager(flows);
flows.add(new Flow(FlowTemplates.stoppingFlow())); //TODO:Add options for custom Deviation Provider and Noise Provider
factory.setDeviationProvider(new SinusoidalDeviationProvider(getConfig(configManager).getDeviationSlope()));
factory.setNoiseProvider(new DefaultNoiseProvider(Double.valueOf(getConfig(configManager).getNoisinessDivider())));
factory.getNature().setReactionTimeVariationMs(getConfig(configManager).getReactionTimeVariation());
manager.setMouseMovementBaseTimeMs(getConfig(configManager).getMouseDragSpeed());
DefaultSpeedManager manager = new DefaultSpeedManager(flows); DefaultOvershootManager overshootManager = (DefaultOvershootManager) factory.getOvershootManager();
//TODO:Add options for custom Deviation Provider and Noise Provider overshootManager.setOvershoots(getConfig(configManager).getOvershoots());
factory.setDeviationProvider(new SinusoidalDeviationProvider(getConfig(configManager).getDeviationSlope()));
factory.setNoiseProvider(new DefaultNoiseProvider(Double.valueOf(getConfig(configManager).getNoisinessDivider())));
factory.getNature().setReactionTimeVariationMs(getConfig(configManager).getReactionTimeVariation());
manager.setMouseMovementBaseTimeMs(getConfig(configManager).getMouseDragSpeed());
DefaultOvershootManager overshootManager = (DefaultOvershootManager) factory.getOvershootManager(); factory.setSpeedManager(manager);
overshootManager.setOvershoots(getConfig(configManager).getOvershoots()); Flexo.currentMouseMotionFactory = factory;
}
factory.setSpeedManager(manager); @Override
Flexo.currentMouseMotionFactory = factory; protected void startUp() throws Exception
} {
Flexo.isStretched = client.isStretchedEnabled();
overlayManager.add(overlay);
updateMouseMotionFactory();
}
@Override @Override
protected void startUp() throws Exception { protected void shutDown() throws Exception
Flexo.isStretched = client.isStretchedEnabled(); {
overlayManager.add(overlay); overlayManager.remove(overlay);
updateMouseMotionFactory(); }
}
@Override
protected void shutDown() throws Exception {
overlayManager.remove(overlay);
}
} }

View File

@@ -32,75 +32,75 @@ import net.runelite.client.config.ConfigItem;
@ConfigGroup("flinching") @ConfigGroup("flinching")
public interface FlinchingConfig extends Config public interface FlinchingConfig extends Config
{ {
@ConfigItem( @ConfigItem(
position = 0, position = 0,
keyName = "hexColorFlinch", keyName = "hexColorFlinch",
name = "Overlay Color", name = "Overlay Color",
description = "Color of flinching timer overlay" description = "Color of flinching timer overlay"
) )
default Color getFlinchOverlayColor() default Color getFlinchOverlayColor()
{ {
return Color.CYAN; return Color.CYAN;
} }
@ConfigItem( @ConfigItem(
position = 1, position = 1,
keyName = "flinchOverlaySize", keyName = "flinchOverlaySize",
name = "Overlay Diameter", name = "Overlay Diameter",
description = "Flinch overlay timer diameter" description = "Flinch overlay timer diameter"
) )
default int getFlinchOverlaySize() default int getFlinchOverlaySize()
{ {
return 30; return 30;
} }
@ConfigItem( @ConfigItem(
position = 2, position = 2,
keyName = "flinchDelay", keyName = "flinchDelay",
name = "Flinch Timer Delay", name = "Flinch Timer Delay",
description = "Shows the appropriate time to attack while flinching milliseconds" description = "Shows the appropriate time to attack while flinching milliseconds"
) )
default int getFlinchDelay() default int getFlinchDelay()
{ {
return 5400; return 5400;
} }
@ConfigItem( @ConfigItem(
position = 3, position = 3,
keyName = "flinchOnHitReceivedDelay", keyName = "flinchOnHitReceivedDelay",
name = "Flinch Hit Received Delay", name = "Flinch Hit Received Delay",
description = "Slightly longer delay after being attacked milliseconds" description = "Slightly longer delay after being attacked milliseconds"
) )
default int getFlinchAttackedDelay() default int getFlinchAttackedDelay()
{ {
return 6600; return 6600;
} }
@ConfigItem( @ConfigItem(
position = 4, position = 4,
keyName = "flinchResetOnHit", keyName = "flinchResetOnHit",
name = "Reset on Hit", name = "Reset on Hit",
description = "Timer resets after every attack from your character" description = "Timer resets after every attack from your character"
) )
default boolean getFlinchResetOnHit() default boolean getFlinchResetOnHit()
{ {
return true; return true;
} }
@ConfigItem( @ConfigItem(
position = 5, position = 5,
keyName = "flinchResetOnHitReceived", keyName = "flinchResetOnHitReceived",
name = "Reset on Hit Received", name = "Reset on Hit Received",
description = "Timer resets when your character gets attacked" description = "Timer resets when your character gets attacked"
) )
default boolean getFlinchResetOnHitReceived() default boolean getFlinchResetOnHitReceived()
{ {
return true; return true;
} }
} }

View File

@@ -43,74 +43,74 @@ import net.runelite.client.ui.overlay.components.ProgressPieComponent;
public class FlinchingOverlay extends Overlay public class FlinchingOverlay extends Overlay
{ {
private final Client client; private final Client client;
private final FlinchingPlugin plugin; private final FlinchingPlugin plugin;
private final FlinchingConfig config; private final FlinchingConfig config;
private Color color; private Color color;
private Color borderColor; private Color borderColor;
private int overlaySize = 25; private int overlaySize;
@Inject @Inject
FlinchingOverlay(Client client, FlinchingPlugin plugin, FlinchingConfig config) FlinchingOverlay(Client client, FlinchingPlugin plugin, FlinchingConfig config)
{ {
setPosition(OverlayPosition.DYNAMIC); setPosition(OverlayPosition.DYNAMIC);
setLayer(OverlayLayer.ABOVE_SCENE); setLayer(OverlayLayer.ABOVE_SCENE);
this.plugin = plugin; this.plugin = plugin;
this.config = config; this.config = config;
this.client = client; this.client = client;
overlaySize = this.config.getFlinchOverlaySize(); overlaySize = this.config.getFlinchOverlaySize();
} }
@Override @Override
public Dimension render(Graphics2D graphics) public Dimension render(Graphics2D graphics)
{ {
drawOverlays(graphics); drawOverlays(graphics);
return null; return null;
} }
public void updateConfig() public void updateConfig()
{ {
borderColor = config.getFlinchOverlayColor(); borderColor = config.getFlinchOverlayColor();
color = new Color(borderColor.getRed(), borderColor.getGreen(), borderColor.getBlue(), 100); color = new Color(borderColor.getRed(), borderColor.getGreen(), borderColor.getBlue(), 100);
overlaySize = config.getFlinchOverlaySize(); overlaySize = config.getFlinchOverlaySize();
} }
private void drawOverlays(Graphics2D graphics) private void drawOverlays(Graphics2D graphics)
{ {
for (Map.Entry<Integer, FlinchingTarget> entry : plugin.GetTargets().entrySet()) for (Map.Entry<Integer, FlinchingTarget> entry : plugin.GetTargets().entrySet())
{ {
FlinchingTarget target = entry.getValue(); FlinchingTarget target = entry.getValue();
drawFlinchTimer(graphics, target.worldLocation, target.GetRemainingTimePercent()); drawFlinchTimer(graphics, target.worldLocation, target.GetRemainingTimePercent());
} }
} }
private void drawFlinchTimer(Graphics2D graphics, WorldPoint targetLocation, double fillAmount) private void drawFlinchTimer(Graphics2D graphics, WorldPoint targetLocation, double fillAmount)
{ {
if (targetLocation.getPlane() != client.getPlane()) if (targetLocation.getPlane() != client.getPlane())
{ {
return; return;
} }
LocalPoint localLoc = LocalPoint.fromWorld(client, targetLocation); LocalPoint localLoc = LocalPoint.fromWorld(client, targetLocation);
if (localLoc == null) if (localLoc == null)
{ {
return; return;
} }
Point loc = Perspective.localToCanvas(client, localLoc, client.getPlane()); Point loc = Perspective.localToCanvas(client, localLoc, client.getPlane());
ProgressPieComponent pie = new ProgressPieComponent(); ProgressPieComponent pie = new ProgressPieComponent();
pie.setDiameter(overlaySize); pie.setDiameter(overlaySize);
pie.setFill(color); pie.setFill(color);
pie.setBorderColor(borderColor); pie.setBorderColor(borderColor);
pie.setPosition(loc); pie.setPosition(loc);
pie.setProgress(fillAmount); pie.setProgress(fillAmount);
pie.render(graphics); pie.render(graphics);
} }
} }

View File

@@ -24,262 +24,258 @@
*/ */
package net.runelite.client.plugins.flinching; package net.runelite.client.plugins.flinching;
import net.runelite.client.eventbus.Subscribe; import com.google.inject.Provides;
import net.runelite.api.Client;
import net.runelite.api.Player;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
import javax.inject.Inject;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import net.runelite.api.Actor;
import net.runelite.api.Client;
import net.runelite.api.GameState;
import net.runelite.api.NPC;
import net.runelite.api.Player;
import net.runelite.api.events.ConfigChanged;
import net.runelite.api.events.GameStateChanged;
import net.runelite.api.events.GameTick; import net.runelite.api.events.GameTick;
import net.runelite.api.events.HitsplatApplied;
import net.runelite.api.events.NpcDespawned;
import net.runelite.client.config.ConfigManager;
import net.runelite.client.eventbus.Subscribe;
import net.runelite.client.plugins.Plugin; import net.runelite.client.plugins.Plugin;
import net.runelite.client.plugins.PluginDescriptor; import net.runelite.client.plugins.PluginDescriptor;
import net.runelite.client.plugins.PluginType; import net.runelite.client.plugins.PluginType;
import net.runelite.client.ui.overlay.OverlayManager; import net.runelite.client.ui.overlay.OverlayManager;
import javax.inject.Inject;
import net.runelite.api.Actor;
import net.runelite.api.NPC;
import net.runelite.api.GameState;
import net.runelite.api.events.GameStateChanged;
import net.runelite.api.events.NpcDespawned;
import net.runelite.client.config.ConfigManager;
import net.runelite.api.events.ConfigChanged;
import net.runelite.api.events.HitsplatApplied;
import com.google.inject.Provides;
@Slf4j @Slf4j
@PluginDescriptor( @PluginDescriptor(
name = "Flinching Timer", name = "Flinching Timer",
description = "Time your attacks while flinching", description = "Time your attacks while flinching",
tags = {"overlay", "flinching", "timers", "combat"}, tags = {"overlay", "flinching", "timers", "combat"},
enabledByDefault = false, enabledByDefault = false,
type = PluginType.PVM type = PluginType.PVM
) )
public class FlinchingPlugin extends Plugin public class FlinchingPlugin extends Plugin
{ {
@Inject @Inject
private Client client; private Client client;
@Inject @Inject
private OverlayManager overlayManager; private OverlayManager overlayManager;
@Inject @Inject
private FlinchingConfig config; private FlinchingConfig config;
@Inject @Inject
private FlinchingOverlay overlay; private FlinchingOverlay overlay;
private int currentWorld = -1; private int currentWorld = -1;
private int currentInteractingId = -1; private int currentInteractingId = -1;
private final Map<Integer, FlinchingTarget> flinchingTargets = new HashMap<Integer, FlinchingTarget>(); private final Map<Integer, FlinchingTarget> flinchingTargets = new HashMap<>();
private boolean resetOnHit = true; private boolean resetOnHit = true;
private boolean resetOnHitReceived = true; private boolean resetOnHitReceived = true;
@Provides @Provides
FlinchingConfig provideConfig(ConfigManager configManager) FlinchingConfig provideConfig(ConfigManager configManager)
{ {
return configManager.getConfig(FlinchingConfig.class); return configManager.getConfig(FlinchingConfig.class);
} }
@Override @Override
protected void startUp() protected void startUp()
{ {
overlayManager.add(overlay); overlayManager.add(overlay);
overlay.updateConfig(); overlay.updateConfig();
resetOnHit = config.getFlinchResetOnHit(); resetOnHit = config.getFlinchResetOnHit();
resetOnHitReceived = config.getFlinchResetOnHitReceived(); resetOnHitReceived = config.getFlinchResetOnHitReceived();
ClearTargets(); ClearTargets();
} }
@Override @Override
protected void shutDown() protected void shutDown()
{ {
ClearTargets(); ClearTargets();
} }
@Subscribe @Subscribe
public void onConfigChanged(ConfigChanged event) public void onConfigChanged(ConfigChanged event)
{ {
if (event.getGroup().equals("flinching")) if (event.getGroup().equals("flinching"))
{ {
overlay.updateConfig(); overlay.updateConfig();
resetOnHit = config.getFlinchResetOnHit(); resetOnHit = config.getFlinchResetOnHit();
resetOnHitReceived = config.getFlinchResetOnHitReceived(); resetOnHitReceived = config.getFlinchResetOnHitReceived();
Iterator<Map.Entry<Integer, FlinchingTarget>> it = flinchingTargets.entrySet().iterator(); for (Map.Entry<Integer, FlinchingTarget> integerFlinchingTargetEntry : flinchingTargets.entrySet())
while (it.hasNext()) {
{ FlinchingTarget target = integerFlinchingTargetEntry.getValue();
FlinchingTarget target = it.next().getValue(); if (target != null)
if(target != null) {
{ target.SetDelayTime(config.getFlinchDelay(), config.getFlinchAttackedDelay());
target.SetDelayTime(config.getFlinchDelay(), config.getFlinchAttackedDelay()); }
} }
} }
} }
}
@Subscribe @Subscribe
public void onGameStateChanged(GameStateChanged event) public void onGameStateChanged(GameStateChanged event)
{ {
if (event.getGameState() == GameState.LOGGED_IN) if (event.getGameState() == GameState.LOGGED_IN)
{ {
if (currentWorld == -1) if (currentWorld == -1)
{ {
currentWorld = client.getWorld(); currentWorld = client.getWorld();
} }
else if (currentWorld != client.getWorld()) else if (currentWorld != client.getWorld())
{ {
ClearTargets(); ClearTargets();
} }
} }
} }
private void ClearTargets() private void ClearTargets()
{ {
Iterator<Map.Entry<Integer, FlinchingTarget>> it = flinchingTargets.entrySet().iterator(); Iterator<Map.Entry<Integer, FlinchingTarget>> it = flinchingTargets.entrySet().iterator();
while (it.hasNext()) while (it.hasNext())
{ {
it.remove(); it.remove();
} }
} }
@Subscribe @Subscribe
private void onGameTick(GameTick tick) private void onGameTick(GameTick tick)
{ {
if (client.getGameState() != GameState.LOGGED_IN) if (client.getGameState() == GameState.LOGGED_IN)
{ {
return;
}
} TickTargets();
else checkInteracting();
{ }
TickTargets();
checkInteracting();
}
}
@Subscribe @Subscribe
public void onHitsplatApplied(HitsplatApplied hitsplatApplied) public void onHitsplatApplied(HitsplatApplied hitsplatApplied)
{ {
Actor actor = hitsplatApplied.getActor(); Actor actor = hitsplatApplied.getActor();
if (actor instanceof NPC) if (actor instanceof NPC)
{ {
NPC hitTarget = (NPC) actor; NPC hitTarget = (NPC) actor;
int hitId = hitTarget.getId(); int hitId = hitTarget.getId();
if(hitId == currentInteractingId) if (hitId == currentInteractingId)
{ {
if (!flinchingTargets.containsKey(hitId)) if (!flinchingTargets.containsKey(hitId))
{ {
TargetGained(hitTarget); TargetGained(hitTarget);
} }
else else
{ {
FlinchingTarget currentTarget = flinchingTargets.get(hitId); FlinchingTarget currentTarget = flinchingTargets.get(hitId);
if(currentTarget != null) if (currentTarget != null)
{ {
if(resetOnHit) if (resetOnHit)
{ {
currentTarget.TargetHit(); currentTarget.TargetHit();
} }
} }
} }
} }
} }
else if(resetOnHitReceived && actor == client.getLocalPlayer()) else if (resetOnHitReceived && actor == client.getLocalPlayer())
{ {
PlayerHit(); PlayerHit();
} }
} }
private void checkInteracting() private void checkInteracting()
{ {
Player localPlayer = client.getLocalPlayer(); Player localPlayer = client.getLocalPlayer();
Actor interacting = localPlayer.getInteracting(); Actor interacting = localPlayer.getInteracting();
if (interacting instanceof NPC) if (interacting instanceof NPC)
{ {
NPC newTarget = (NPC) interacting; NPC newTarget = (NPC) interacting;
currentInteractingId = newTarget.getId(); currentInteractingId = newTarget.getId();
if(newTarget.getHealth() <= 0 || newTarget.isDead()) if (newTarget.getHealth() <= 0 || newTarget.isDead())
{ {
if (flinchingTargets.containsKey(currentInteractingId)) if (flinchingTargets.containsKey(currentInteractingId))
{ {
flinchingTargets.remove(currentInteractingId); flinchingTargets.remove(currentInteractingId);
currentInteractingId = -1; currentInteractingId = -1;
} }
} }
} }
} }
private void TickTargets() private void TickTargets()
{ {
Iterator<Map.Entry<Integer, FlinchingTarget>> it = flinchingTargets.entrySet().iterator(); Iterator<Map.Entry<Integer, FlinchingTarget>> it = flinchingTargets.entrySet().iterator();
while (it.hasNext()) while (it.hasNext())
{ {
FlinchingTarget target = it.next().getValue(); FlinchingTarget target = it.next().getValue();
if(target != null) if (target != null)
{ {
target.Tick(); target.Tick();
if(target.isActive == false) if (!target.isActive)
{ {
it.remove(); it.remove();
} }
} }
else else
{ {
it.remove(); it.remove();
} }
} }
} }
@Subscribe @Subscribe
public void onNpcDespawned(NpcDespawned npcDespawned) public void onNpcDespawned(NpcDespawned npcDespawned)
{ {
NPC actor = npcDespawned.getNpc(); NPC actor = npcDespawned.getNpc();
int actorId = actor.getId(); int actorId = actor.getId();
if (actor.isDead() && flinchingTargets.containsKey(actorId)) if (actor.isDead() && flinchingTargets.containsKey(actorId))
{ {
TargetLost(actorId); TargetLost(actorId);
} }
} }
private void TargetLost(int targetId) private void TargetLost(int targetId)
{ {
flinchingTargets.remove(targetId); flinchingTargets.remove(targetId);
} }
private void TargetGained(NPC _newTarget) private void TargetGained(NPC _newTarget)
{ {
FlinchingTarget newTarget = new FlinchingTarget(_newTarget); FlinchingTarget newTarget = new FlinchingTarget(_newTarget);
newTarget.SetDelayTime(config.getFlinchDelay(), config.getFlinchAttackedDelay()); newTarget.SetDelayTime(config.getFlinchDelay(), config.getFlinchAttackedDelay());
flinchingTargets.put(_newTarget.getId(), newTarget); flinchingTargets.put(_newTarget.getId(), newTarget);
} }
public void PlayerHit() private void PlayerHit()
{ {
Iterator<Map.Entry<Integer, FlinchingTarget>> it = flinchingTargets.entrySet().iterator(); for (Map.Entry<Integer, FlinchingTarget> integerFlinchingTargetEntry : flinchingTargets.entrySet())
while (it.hasNext()) {
{ FlinchingTarget target = integerFlinchingTargetEntry.getValue();
FlinchingTarget target = it.next().getValue(); if (target != null)
if(target != null) {
{ target.PlayerHit();
target.PlayerHit(); }
} }
} }
}
public Map<Integer, FlinchingTarget> GetTargets() Map<Integer, FlinchingTarget> GetTargets()
{ {
return(flinchingTargets); return (flinchingTargets);
} }
} }

View File

@@ -32,113 +32,113 @@ import net.runelite.api.coords.WorldPoint;
public class FlinchingTarget public class FlinchingTarget
{ {
private int currentDisplayLength = 5400; private int currentDisplayLength = 5400;
private boolean usingHitDelay = false; private boolean usingHitDelay = false;
private int displayLength = 5400; private int displayLength = 5400;
private int displayHitReceivedLength = 6600; private int displayHitReceivedLength = 6600;
private Instant lastAttacked; private Instant lastAttacked;
public boolean isActive = false; public boolean isActive;
@Getter @Getter
private int objectId; private int objectId;
private NPC targetObject; private NPC targetObject;
@Getter @Getter
public WorldPoint worldLocation; public WorldPoint worldLocation;
public FlinchingTarget(NPC target) FlinchingTarget(NPC target)
{ {
isActive = true; isActive = true;
this.targetObject = target; this.targetObject = target;
this.lastAttacked = Instant.now(); this.lastAttacked = Instant.now();
this.objectId = target.getId(); this.objectId = target.getId();
this.worldLocation = target.getWorldLocation(); this.worldLocation = target.getWorldLocation();
} }
public void TargetHit() void TargetHit()
{ {
boolean shouldHit = true; boolean shouldHit = true;
if(usingHitDelay) if (usingHitDelay)
{ {
if(GetRemainingTime() > displayLength) if (GetRemainingTime() > displayLength)
{ {
shouldHit = false; shouldHit = false;
} }
} }
if(shouldHit) if (shouldHit)
{ {
lastAttacked = Instant.now(); lastAttacked = Instant.now();
usingHitDelay = false; usingHitDelay = false;
currentDisplayLength = displayLength; currentDisplayLength = displayLength;
} }
} }
public double GetRemainingTimePercent() double GetRemainingTimePercent()
{ {
double remainingTime = GetRemainingTime(); double remainingTime = GetRemainingTime();
double timePercent = remainingTime / currentDisplayLength; double timePercent = remainingTime / currentDisplayLength;
if(timePercent < 0) if (timePercent < 0)
{ {
timePercent = 0; timePercent = 0;
} }
else if(timePercent > 1) else if (timePercent > 1)
{ {
timePercent = 1; timePercent = 1;
} }
return(timePercent); return (timePercent);
} }
private double GetRemainingTime() private double GetRemainingTime()
{ {
Duration duration = Duration.between(lastAttacked, Instant.now()); Duration duration = Duration.between(lastAttacked, Instant.now());
return( (currentDisplayLength - ((double)duration.toMillis()))); return ((currentDisplayLength - ((double) duration.toMillis())));
} }
public void Tick() void Tick()
{ {
if(targetObject == null) if (targetObject == null)
{ {
isActive = false; isActive = false;
} }
else else
{ {
worldLocation = targetObject.getWorldLocation(); worldLocation = targetObject.getWorldLocation();
double remainingTime = GetRemainingTime(); double remainingTime = GetRemainingTime();
if(remainingTime <= 0) if (remainingTime <= 0)
{ {
isActive = false; isActive = false;
} }
} }
} }
public void SetDelayTime(int delayTime, int delayHitReceivedTime) void SetDelayTime(int delayTime, int delayHitReceivedTime)
{ {
displayLength = delayTime; displayLength = delayTime;
displayHitReceivedLength = delayHitReceivedTime; displayHitReceivedLength = delayHitReceivedTime;
if(usingHitDelay) if (usingHitDelay)
{ {
currentDisplayLength = displayHitReceivedLength; currentDisplayLength = displayHitReceivedLength;
} }
else else
{ {
currentDisplayLength = displayLength; currentDisplayLength = displayLength;
} }
} }
public void PlayerHit() void PlayerHit()
{ {
usingHitDelay = true; usingHitDelay = true;
currentDisplayLength = displayHitReceivedLength; currentDisplayLength = displayHitReceivedLength;
lastAttacked = Instant.now(); lastAttacked = Instant.now();
} }
} }

View File

@@ -29,37 +29,39 @@ import net.runelite.client.config.ConfigGroup;
import net.runelite.client.config.ConfigItem; import net.runelite.client.config.ConfigItem;
@ConfigGroup("hydra") @ConfigGroup("hydra")
public interface HydraConfig extends Config { public interface HydraConfig extends Config
@ConfigItem( {
position = 0,
keyName = "hydraenable",
name = "Enable Hydra (194 cb) Helper",
description = "Configures whether or not to enable Hydra Helper. (For use on regular hydra's only, will not work with Alchemical Hydra)."
)
default boolean EnableHydra() { return true; }
@ConfigItem( @ConfigItem(
position = 1, position = 1,
keyName = "textindicators", keyName = "textindicators",
name = "Text Indicator", name = "Text Indicator",
description = "Configures if text indicator is shown above hydra's or not." description = "Configures if text indicator is shown above hydra's or not."
) )
default boolean TextIndicator() { return true; } default boolean TextIndicator()
{
return true;
}
@ConfigItem( @ConfigItem(
position = 2, position = 2,
keyName = "countersize", keyName = "countersize",
name = "Bold indicator", name = "Bold indicator",
description = "Configures if text indicator is bold or not." description = "Configures if text indicator is bold or not."
) )
default boolean BoldText() { return false; } default boolean BoldText()
{
return false;
}
@ConfigItem( @ConfigItem(
position = 3, position = 3,
keyName = "prayerhelper", keyName = "prayerhelper",
name = "Prayer Helper", name = "Prayer Helper",
description = "Configures if prayer helper is shown or not." description = "Configures if prayer helper is shown or not."
) )
default boolean PrayerHelper() { return true; } default boolean PrayerHelper()
{
return true;
}
} }

View File

@@ -24,53 +24,53 @@
*/ */
package net.runelite.client.plugins.hydra; package net.runelite.client.plugins.hydra;
import java.awt.*; import java.awt.Dimension;
import java.awt.image.BufferedImage; import java.awt.Graphics2D;
import javax.inject.Inject; import javax.inject.Inject;
import net.runelite.client.ui.overlay.Overlay;
import net.runelite.api.*; import net.runelite.client.ui.overlay.OverlayPosition;
import net.runelite.api.Point; import net.runelite.client.ui.overlay.OverlayPriority;
import net.runelite.client.game.SpriteManager;
import net.runelite.client.ui.overlay.*;
import net.runelite.client.ui.overlay.components.ComponentConstants;
import net.runelite.client.ui.overlay.components.ImageComponent;
import net.runelite.client.ui.overlay.components.LineComponent; import net.runelite.client.ui.overlay.components.LineComponent;
import net.runelite.client.ui.overlay.components.PanelComponent; import net.runelite.client.ui.overlay.components.PanelComponent;
import static net.runelite.api.MenuAction.RUNELITE_OVERLAY_CONFIG; public class HydraIndicatorOverlay extends Overlay
import static net.runelite.client.ui.overlay.OverlayManager.OPTION_CONFIGURE; {
private final HydraConfig config;
private final HydraPlugin plugin;
public class HydraIndicatorOverlay extends Overlay { private final PanelComponent panelComponent = new PanelComponent();
private final HydraConfig config;
private final HydraPlugin plugin;
private final PanelComponent panelComponent = new PanelComponent(); @Inject
private HydraIndicatorOverlay(HydraConfig config, HydraPlugin plugin)
{
this.config = config;
this.plugin = plugin;
setPosition(OverlayPosition.BOTTOM_RIGHT);
setPriority(OverlayPriority.MED);
panelComponent.setPreferredSize(new Dimension(14, 0));
}
@Inject @Override
private HydraIndicatorOverlay(HydraConfig config, HydraPlugin plugin) { public Dimension render(Graphics2D graphics)
this.config = config; {
this.plugin = plugin; if (!config.PrayerHelper())
setPosition(OverlayPosition.BOTTOM_RIGHT); {
setPriority(OverlayPriority.MED); return null;
panelComponent.setPreferredSize(new Dimension(14, 0)); }
}
@Override if (plugin.Hydra != null)
public Dimension render(Graphics2D graphics) { {
if (!config.PrayerHelper()) { if (plugin.hydras.containsKey(plugin.Hydra.getIndex()))
return null; {
} int val = plugin.hydras.get(plugin.Hydra.getIndex());
if (val != 0)
if (plugin.Hydra != null) { {
if (plugin.hydras.containsKey(plugin.Hydra.getIndex())) { panelComponent.getChildren().clear();
int val = plugin.hydras.get(plugin.Hydra.getIndex()); panelComponent.getChildren().add(LineComponent.builder().right(Integer.toString(val)).build());
if (val != 0) { return panelComponent.render(graphics);
panelComponent.getChildren().clear(); }
panelComponent.getChildren().add(LineComponent.builder().right(Integer.toString(val)).build()); }
return panelComponent.render(graphics); }
} return null;
} }
}
return null;
}
} }

View File

@@ -24,16 +24,23 @@
*/ */
package net.runelite.client.plugins.hydra; package net.runelite.client.plugins.hydra;
import java.awt.*; import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import javax.inject.Inject; import javax.inject.Inject;
import net.runelite.api.Client;
import net.runelite.api.*; import net.runelite.api.NPC;
import net.runelite.api.Point; import net.runelite.api.Point;
import net.runelite.client.ui.FontManager; import net.runelite.client.ui.FontManager;
import net.runelite.client.ui.overlay.*; import net.runelite.client.ui.overlay.Overlay;
import net.runelite.client.ui.overlay.OverlayLayer;
import net.runelite.client.ui.overlay.OverlayPosition;
import net.runelite.client.ui.overlay.OverlayPriority;
import net.runelite.client.ui.overlay.OverlayUtil;
import net.runelite.client.ui.overlay.components.PanelComponent; import net.runelite.client.ui.overlay.components.PanelComponent;
public class HydraOverlay extends Overlay { public class HydraOverlay extends Overlay
{
private final HydraConfig config; private final HydraConfig config;
private final HydraPlugin plugin; private final HydraPlugin plugin;
private final PanelComponent panelComponent = new PanelComponent(); private final PanelComponent panelComponent = new PanelComponent();
@@ -43,7 +50,8 @@ public class HydraOverlay extends Overlay {
private Client client; private Client client;
@Inject @Inject
private HydraOverlay(HydraConfig config, HydraPlugin plugin) { private HydraOverlay(HydraConfig config, HydraPlugin plugin)
{
this.config = config; this.config = config;
this.plugin = plugin; this.plugin = plugin;
setLayer(OverlayLayer.ABOVE_SCENE); setLayer(OverlayLayer.ABOVE_SCENE);
@@ -53,41 +61,60 @@ public class HydraOverlay extends Overlay {
} }
@Override @Override
public Dimension render(Graphics2D graphics) { public Dimension render(Graphics2D graphics)
if (!config.TextIndicator()) { {
if (!config.TextIndicator())
{
return null; return null;
} }
for (NPC hydra : client.getNpcs()) { for (NPC hydra : client.getNpcs())
if (hydra == null || hydra.getName() == null) { {
if (hydra == null || hydra.getName() == null)
{
continue; continue;
} }
if (hydra.getName().equalsIgnoreCase("Hydra")) { if (hydra.getName().equalsIgnoreCase("Hydra"))
if (plugin.hydras.containsKey(hydra.getIndex())) { {
if (plugin.hydras.containsKey(hydra.getIndex()))
{
int val = plugin.hydras.get(hydra.getIndex()); int val = plugin.hydras.get(hydra.getIndex());
if (val != 0) { if (val != 0)
if (config.BoldText()) { {
if (config.BoldText())
{
graphics.setFont(FontManager.getRunescapeBoldFont()); graphics.setFont(FontManager.getRunescapeBoldFont());
} }
if (plugin.hydraattacks.containsKey(hydra.getIndex())) { if (plugin.hydraattacks.containsKey(hydra.getIndex()))
{
int attack = plugin.hydraattacks.get(hydra.getIndex()); int attack = plugin.hydraattacks.get(hydra.getIndex());
if (attack == 8261) { if (attack == 8261)
if (val == 3) { {
if (val == 3)
{
OverlayUtil.renderTextLocation(graphics, hydra.getCanvasTextLocation(graphics, "MAGE", hydra.getLogicalHeight() + 100), "MAGE", Color.BLUE); OverlayUtil.renderTextLocation(graphics, hydra.getCanvasTextLocation(graphics, "MAGE", hydra.getLogicalHeight() + 100), "MAGE", Color.BLUE);
} else { }
else
{
OverlayUtil.renderTextLocation(graphics, hydra.getCanvasTextLocation(graphics, "RANGE", hydra.getLogicalHeight() + 100), "RANGE", Color.GREEN); OverlayUtil.renderTextLocation(graphics, hydra.getCanvasTextLocation(graphics, "RANGE", hydra.getLogicalHeight() + 100), "RANGE", Color.GREEN);
} }
} else if (attack == 8262) { }
if (val == 3) { else if (attack == 8262)
{
if (val == 3)
{
OverlayUtil.renderTextLocation(graphics, hydra.getCanvasTextLocation(graphics, "RANGE", hydra.getLogicalHeight() + 100), "RANGE", Color.GREEN); OverlayUtil.renderTextLocation(graphics, hydra.getCanvasTextLocation(graphics, "RANGE", hydra.getLogicalHeight() + 100), "RANGE", Color.GREEN);
} else { }
else
{
OverlayUtil.renderTextLocation(graphics, hydra.getCanvasTextLocation(graphics, "MAGE", hydra.getLogicalHeight() + 100), "MAGE", Color.BLUE); OverlayUtil.renderTextLocation(graphics, hydra.getCanvasTextLocation(graphics, "MAGE", hydra.getLogicalHeight() + 100), "MAGE", Color.BLUE);
} }
} }
} }
Point runelitepleaseexplainwhyineedtocheckthisfornullinsteadoftheentirehydravariablethisshitcostmelikeanhourofmylifeandiblameyouadam = hydra.getCanvasTextLocation(graphics, Integer.toString(val), hydra.getLogicalHeight() + 40); Point hydraPoint = hydra.getCanvasTextLocation(graphics, Integer.toString(val), hydra.getLogicalHeight() + 40);
if (runelitepleaseexplainwhyineedtocheckthisfornullinsteadoftheentirehydravariablethisshitcostmelikeanhourofmylifeandiblameyouadam != null) { if (hydraPoint != null)
OverlayUtil.renderTextLocation(graphics, runelitepleaseexplainwhyineedtocheckthisfornullinsteadoftheentirehydravariablethisshitcostmelikeanhourofmylifeandiblameyouadam, Integer.toString(val), Color.WHITE); {
OverlayUtil.renderTextLocation(graphics, hydraPoint, Integer.toString(val), Color.WHITE);
} }
} }
} }

View File

@@ -24,21 +24,24 @@
*/ */
package net.runelite.client.plugins.hydra; package net.runelite.client.plugins.hydra;
import net.runelite.api.events.*;
import net.runelite.client.eventbus.Subscribe;
import com.google.inject.Provides; import com.google.inject.Provides;
import java.util.HashMap;
import java.util.Map;
import javax.inject.Inject; import javax.inject.Inject;
import net.runelite.api.*; import net.runelite.api.Actor;
import net.runelite.api.Client;
import net.runelite.api.NPC;
import net.runelite.api.events.AnimationChanged;
import net.runelite.api.events.NpcDespawned;
import net.runelite.api.events.NpcSpawned;
import net.runelite.client.config.ConfigManager; import net.runelite.client.config.ConfigManager;
import net.runelite.client.eventbus.Subscribe;
import net.runelite.client.game.SpriteManager; import net.runelite.client.game.SpriteManager;
import net.runelite.client.plugins.Plugin; import net.runelite.client.plugins.Plugin;
import net.runelite.client.plugins.PluginDescriptor; import net.runelite.client.plugins.PluginDescriptor;
import net.runelite.client.plugins.PluginType; import net.runelite.client.plugins.PluginType;
import net.runelite.client.ui.overlay.OverlayManager; import net.runelite.client.ui.overlay.OverlayManager;
import java.util.HashMap;
import java.util.Map;
@PluginDescriptor( @PluginDescriptor(
name = "Hydra Helper", name = "Hydra Helper",
description = "Hydra Helper", description = "Hydra Helper",
@@ -65,11 +68,9 @@ public class HydraPlugin extends Plugin
@Inject @Inject
private Client client; private Client client;
@Inject
private SpriteManager spriteManager;
@Provides @Provides
HydraConfig provideConfig(ConfigManager configManager) { HydraConfig provideConfig(ConfigManager configManager)
{
return configManager.getConfig(HydraConfig.class); return configManager.getConfig(HydraConfig.class);
} }
@@ -78,14 +79,16 @@ public class HydraPlugin extends Plugin
NPC Hydra; NPC Hydra;
@Override @Override
protected void startUp() throws Exception { protected void startUp() throws Exception
{
overlayManager.add(HydraOverlay); overlayManager.add(HydraOverlay);
overlayManager.add(HydraPrayOverlay); overlayManager.add(HydraPrayOverlay);
overlayManager.add(HydraIndicatorOverlay); overlayManager.add(HydraIndicatorOverlay);
} }
@Override @Override
protected void shutDown() throws Exception { protected void shutDown() throws Exception
{
overlayManager.remove(HydraOverlay); overlayManager.remove(HydraOverlay);
overlayManager.remove(HydraPrayOverlay); overlayManager.remove(HydraPrayOverlay);
overlayManager.remove(HydraIndicatorOverlay); overlayManager.remove(HydraIndicatorOverlay);
@@ -94,14 +97,15 @@ public class HydraPlugin extends Plugin
} }
@Subscribe @Subscribe
public void onNpcSpawned(NpcSpawned event) { public void onNpcSpawned(NpcSpawned event)
if (!config.EnableHydra()) { {
return;
}
NPC hydra = event.getNpc(); NPC hydra = event.getNpc();
if (hydra.getCombatLevel() != 0 && hydra.getName() != null) { if (hydra.getCombatLevel() != 0 && hydra.getName() != null)
if (hydra.getName().equalsIgnoreCase("Hydra")) { {
if (!hydras.containsKey(hydra.getIndex())) { if (hydra.getName().equalsIgnoreCase("Hydra"))
{
if (!hydras.containsKey(hydra.getIndex()))
{
hydras.put(hydra.getIndex(), 3); hydras.put(hydra.getIndex(), 3);
} }
} }
@@ -109,56 +113,71 @@ public class HydraPlugin extends Plugin
} }
@Subscribe @Subscribe
public void onNpcDespawned(NpcDespawned event) { public void onNpcDespawned(NpcDespawned event)
if (!config.EnableHydra()) { {
return;
}
NPC hydra = event.getNpc(); NPC hydra = event.getNpc();
if (hydra.getCombatLevel() != 0 && hydra.getName() != null) { if (hydra.getCombatLevel() != 0 && hydra.getName() != null)
if (hydra.getName().equalsIgnoreCase("Hydra")) { {
if (hydras.containsKey(hydra.getIndex())) { if (hydra.getName().equalsIgnoreCase("Hydra"))
hydras.remove(hydra.getIndex()); {
} hydras.remove(hydra.getIndex());
if (hydraattacks.containsKey(hydra.getIndex())) { hydraattacks.remove(hydra.getIndex());
hydraattacks.remove(hydra.getIndex());
}
} }
} }
} }
@Subscribe @Subscribe
public void onAnimationChanged(AnimationChanged event) { public void onAnimationChanged(AnimationChanged event)
{
Actor monster = event.getActor(); Actor monster = event.getActor();
Actor local = client.getLocalPlayer(); Actor local = client.getLocalPlayer();
if (monster instanceof NPC) { if (monster instanceof NPC)
{
NPC hydra = (NPC) monster; NPC hydra = (NPC) monster;
if (hydra.getCombatLevel() != 0 && hydra.getName() != null) { if (hydra.getCombatLevel() != 0 && hydra.getName() != null)
if (hydra.getName().equalsIgnoreCase("Hydra")) { {
if (hydras.containsKey(hydra.getIndex())) { if (hydra.getName().equalsIgnoreCase("Hydra"))
if (hydra.getAnimation() == 8261 || hydra.getAnimation() == 8262) { {
if (hydra.getInteracting().equals(local)) { if (hydras.containsKey(hydra.getIndex()))
{
if (hydra.getAnimation() == 8261 || hydra.getAnimation() == 8262)
{
if (hydra.getInteracting().equals(local))
{
Hydra = hydra; Hydra = hydra;
} }
if (hydraattacks.containsKey(hydra.getIndex())) { if (hydraattacks.containsKey(hydra.getIndex()))
{
int lastattack = hydraattacks.get(hydra.getIndex()); int lastattack = hydraattacks.get(hydra.getIndex());
hydraattacks.replace(hydra.getIndex(), hydra.getAnimation()); hydraattacks.replace(hydra.getIndex(), hydra.getAnimation());
if (lastattack != hydra.getAnimation()) { if (lastattack != hydra.getAnimation())
{
hydras.replace(hydra.getIndex(), 2); hydras.replace(hydra.getIndex(), 2);
} else { }
else
{
int currval = hydras.get(hydra.getIndex()); int currval = hydras.get(hydra.getIndex());
if (currval == 1) { if (currval == 1)
{
hydras.replace(hydra.getIndex(), 3); hydras.replace(hydra.getIndex(), 3);
} else { }
else
{
hydras.replace(hydra.getIndex(), currval - 1); hydras.replace(hydra.getIndex(), currval - 1);
} }
} }
} else { }
else
{
hydraattacks.put(hydra.getIndex(), hydra.getAnimation()); hydraattacks.put(hydra.getIndex(), hydra.getAnimation());
int currval = hydras.get(hydra.getIndex()); int currval = hydras.get(hydra.getIndex());
if (currval == 1) { if (currval == 1)
{
hydras.replace(hydra.getIndex(), 3); hydras.replace(hydra.getIndex(), 3);
} else { }
else
{
hydras.replace(hydra.getIndex(), currval - 1); hydras.replace(hydra.getIndex(), currval - 1);
} }
} }

View File

@@ -24,101 +24,122 @@
*/ */
package net.runelite.client.plugins.hydra; package net.runelite.client.plugins.hydra;
import java.awt.*; import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import javax.inject.Inject; import javax.inject.Inject;
import net.runelite.api.Client;
import net.runelite.api.*; import net.runelite.api.Prayer;
import net.runelite.api.Point; import net.runelite.api.SpriteID;
import net.runelite.client.game.SpriteManager; import net.runelite.client.game.SpriteManager;
import net.runelite.client.ui.overlay.*; import net.runelite.client.ui.overlay.Overlay;
import net.runelite.client.ui.overlay.OverlayPosition;
import net.runelite.client.ui.overlay.OverlayPriority;
import net.runelite.client.ui.overlay.components.ComponentConstants; import net.runelite.client.ui.overlay.components.ComponentConstants;
import net.runelite.client.ui.overlay.components.ImageComponent; import net.runelite.client.ui.overlay.components.ImageComponent;
import net.runelite.client.ui.overlay.components.PanelComponent; import net.runelite.client.ui.overlay.components.PanelComponent;
public class HydraPrayOverlay extends Overlay { public class HydraPrayOverlay extends Overlay
private final HydraConfig config; {
private final HydraPlugin plugin; private final HydraConfig config;
private final HydraPlugin plugin;
private static final Color NOT_ACTIVATED_BACKGROUND_COLOR = new Color(150, 0, 0, 150); private static final Color NOT_ACTIVATED_BACKGROUND_COLOR = new Color(150, 0, 0, 150);
private final SpriteManager spriteManager; private final SpriteManager spriteManager;
private final PanelComponent imagePanelComponent = new PanelComponent(); private final PanelComponent imagePanelComponent = new PanelComponent();
@Inject @Inject
private Client client; private Client client;
@Inject @Inject
private HydraPrayOverlay(HydraConfig config, HydraPlugin plugin, SpriteManager spriteManager) { private HydraPrayOverlay(HydraConfig config, HydraPlugin plugin, SpriteManager spriteManager)
this.config = config; {
this.plugin = plugin; this.config = config;
setPosition(OverlayPosition.BOTTOM_RIGHT); this.plugin = plugin;
setPriority(OverlayPriority.HIGH); setPosition(OverlayPosition.BOTTOM_RIGHT);
this.spriteManager = spriteManager; setPriority(OverlayPriority.HIGH);
} this.spriteManager = spriteManager;
}
@Override @Override
public Dimension render(Graphics2D graphics) { public Dimension render(Graphics2D graphics)
if (!config.PrayerHelper()) { {
return null; if (!config.PrayerHelper())
} {
return null;
}
if (plugin.Hydra != null) { if (plugin.Hydra != null)
if (plugin.hydras.containsKey(plugin.Hydra.getIndex())) { {
int val = plugin.hydras.get(plugin.Hydra.getIndex()); if (plugin.hydras.containsKey(plugin.Hydra.getIndex()))
if (val != 0) { {
if (plugin.hydraattacks.containsKey(plugin.Hydra.getIndex())) { int val = plugin.hydras.get(plugin.Hydra.getIndex());
int attack = plugin.hydraattacks.get(plugin.Hydra.getIndex()); if (val != 0)
if (attack == 8261) { {
if (val == 3) { if (plugin.hydraattacks.containsKey(plugin.Hydra.getIndex()))
final BufferedImage prayerImage = spriteManager.getSprite(SpriteID.PRAYER_PROTECT_FROM_MAGIC, 0); {
int attack = plugin.hydraattacks.get(plugin.Hydra.getIndex());
if (attack == 8261)
{
if (val == 3)
{
final BufferedImage prayerImage = spriteManager.getSprite(SpriteID.PRAYER_PROTECT_FROM_MAGIC, 0);
imagePanelComponent.getChildren().clear(); imagePanelComponent.getChildren().clear();
imagePanelComponent.getChildren().add(new ImageComponent(prayerImage)); imagePanelComponent.getChildren().add(new ImageComponent(prayerImage));
imagePanelComponent.setBackgroundColor(client.isPrayerActive(Prayer.PROTECT_FROM_MAGIC) imagePanelComponent.setBackgroundColor(client.isPrayerActive(Prayer.PROTECT_FROM_MAGIC)
? ComponentConstants.STANDARD_BACKGROUND_COLOR ? ComponentConstants.STANDARD_BACKGROUND_COLOR
: NOT_ACTIVATED_BACKGROUND_COLOR); : NOT_ACTIVATED_BACKGROUND_COLOR);
return imagePanelComponent.render(graphics); return imagePanelComponent.render(graphics);
} else { }
final BufferedImage prayerImage = spriteManager.getSprite(SpriteID.PRAYER_PROTECT_FROM_MISSILES, 0); else
{
final BufferedImage prayerImage = spriteManager.getSprite(SpriteID.PRAYER_PROTECT_FROM_MISSILES, 0);
imagePanelComponent.getChildren().clear(); imagePanelComponent.getChildren().clear();
imagePanelComponent.getChildren().add(new ImageComponent(prayerImage)); imagePanelComponent.getChildren().add(new ImageComponent(prayerImage));
imagePanelComponent.setBackgroundColor(client.isPrayerActive(Prayer.PROTECT_FROM_MISSILES) imagePanelComponent.setBackgroundColor(client.isPrayerActive(Prayer.PROTECT_FROM_MISSILES)
? ComponentConstants.STANDARD_BACKGROUND_COLOR ? ComponentConstants.STANDARD_BACKGROUND_COLOR
: NOT_ACTIVATED_BACKGROUND_COLOR); : NOT_ACTIVATED_BACKGROUND_COLOR);
return imagePanelComponent.render(graphics); return imagePanelComponent.render(graphics);
} }
} else if (attack == 8262) { }
if (val == 3) { else if (attack == 8262)
final BufferedImage prayerImage = spriteManager.getSprite(SpriteID.PRAYER_PROTECT_FROM_MISSILES, 0); {
if (val == 3)
{
final BufferedImage prayerImage = spriteManager.getSprite(SpriteID.PRAYER_PROTECT_FROM_MISSILES, 0);
imagePanelComponent.getChildren().clear(); imagePanelComponent.getChildren().clear();
imagePanelComponent.getChildren().add(new ImageComponent(prayerImage)); imagePanelComponent.getChildren().add(new ImageComponent(prayerImage));
imagePanelComponent.setBackgroundColor(client.isPrayerActive(Prayer.PROTECT_FROM_MISSILES) imagePanelComponent.setBackgroundColor(client.isPrayerActive(Prayer.PROTECT_FROM_MISSILES)
? ComponentConstants.STANDARD_BACKGROUND_COLOR ? ComponentConstants.STANDARD_BACKGROUND_COLOR
: NOT_ACTIVATED_BACKGROUND_COLOR); : NOT_ACTIVATED_BACKGROUND_COLOR);
return imagePanelComponent.render(graphics); return imagePanelComponent.render(graphics);
} else { }
final BufferedImage prayerImage = spriteManager.getSprite(SpriteID.PRAYER_PROTECT_FROM_MAGIC, 0); else
{
final BufferedImage prayerImage = spriteManager.getSprite(SpriteID.PRAYER_PROTECT_FROM_MAGIC, 0);
imagePanelComponent.getChildren().clear(); imagePanelComponent.getChildren().clear();
imagePanelComponent.getChildren().add(new ImageComponent(prayerImage)); imagePanelComponent.getChildren().add(new ImageComponent(prayerImage));
imagePanelComponent.setBackgroundColor(client.isPrayerActive(Prayer.PROTECT_FROM_MAGIC) imagePanelComponent.setBackgroundColor(client.isPrayerActive(Prayer.PROTECT_FROM_MAGIC)
? ComponentConstants.STANDARD_BACKGROUND_COLOR ? ComponentConstants.STANDARD_BACKGROUND_COLOR
: NOT_ACTIVATED_BACKGROUND_COLOR); : NOT_ACTIVATED_BACKGROUND_COLOR);
return imagePanelComponent.render(graphics); return imagePanelComponent.render(graphics);
} }
} }
} }
} }
} }
} }
return null; return null;
} }
} }

View File

@@ -31,30 +31,47 @@ import net.runelite.client.config.ConfigItem;
@ConfigGroup("learntoclick") @ConfigGroup("learntoclick")
public interface LearnToClickConfig extends Config public interface LearnToClickConfig extends Config
{ {
@ConfigItem(
@ConfigItem(position = 1, keyName = "blockCompass", name = "Compass", description = "Prevents the camera from moving when you misclick on the compass") position = 1,
keyName = "blockCompass",
name = "Compass",
description = "Prevents the camera from moving when you misclick on the compass"
)
default boolean shouldBlockCompass() default boolean shouldBlockCompass()
{ {
return false; return false;
} }
@ConfigItem(position = 2, keyName = "rightClickMap", name = "World Map", description = "Prevents the world map from opening on left click without disabling it entirely") @ConfigItem(
position = 2,
keyName = "rightClickMap",
name = "World Map",
description = "Prevents the world map from opening on left click without disabling it entirely"
)
default boolean shouldRightClickMap() default boolean shouldRightClickMap()
{ {
return false; return false;
} }
@ConfigItem(position = 3, keyName = "rightClickXp", name = "Xp Drops Toggle", description = "Prevents toggling xp drops on left click without disabling the toggle function entirely") @ConfigItem(
position = 3,
keyName = "rightClickXp",
name = "Xp Drops Toggle",
description = "Prevents toggling xp drops on left click without disabling the toggle function entirely"
)
default boolean shouldRightClickXp() default boolean shouldRightClickXp()
{ {
return false; return false;
} }
@ConfigItem(position = 4, keyName = "rightClickRetaliate", name = "Auto Retaliate", description = "Prevents toggling auto retaliate on left click without disabling the toggle function entirely") @ConfigItem(
position = 4,
keyName = "rightClickRetaliate",
name = "Auto Retaliate",
description = "Prevents toggling auto retaliate on left click without disabling the toggle function entirely"
)
default boolean shouldRightClickRetaliate() default boolean shouldRightClickRetaliate()
{ {
return false; return false;
} }
} }

View File

@@ -38,7 +38,6 @@ public class LearnToClickPlugin extends Plugin
@Inject @Inject
private LearnToClickConfig config; private LearnToClickConfig config;
private boolean forceRightClickFlag; private boolean forceRightClickFlag;
private MenuEntry[] entries;
@Inject @Inject
private Client client; private Client client;
@@ -86,7 +85,7 @@ public class LearnToClickPlugin extends Plugin
{ {
forceRightClickFlag = true; forceRightClickFlag = true;
} }
entries = client.getMenuEntries(); MenuEntry[] entries = client.getMenuEntries();
if (config.shouldBlockCompass()) if (config.shouldBlockCompass())
{ {
for (int i = entries.length - 1; i >= 0; i--) for (int i = entries.length - 1; i >= 0; i--)

View File

@@ -5,7 +5,6 @@ import java.awt.Dimension;
import java.awt.Graphics2D; import java.awt.Graphics2D;
import java.awt.Polygon; import java.awt.Polygon;
import java.text.DecimalFormat; import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map; import java.util.Map;
import javax.inject.Inject; import javax.inject.Inject;
import net.runelite.api.Client; import net.runelite.api.Client;
@@ -21,16 +20,12 @@ import net.runelite.client.ui.overlay.OverlayUtil;
public class LootAssistOverlay extends Overlay public class LootAssistOverlay extends Overlay
{ {
private LootAssistPlugin plugin;
private Client client; private Client client;
private DecimalFormat d = new DecimalFormat("##.#"); private DecimalFormat d = new DecimalFormat("##.#");
@Inject @Inject
public LootAssistOverlay(Client client, LootAssistPlugin plugin) public LootAssistOverlay(Client client)
{ {
this.plugin = plugin;
this.client = client; this.client = client;
setLayer(OverlayLayer.ABOVE_SCENE); setLayer(OverlayLayer.ABOVE_SCENE);
setPosition(OverlayPosition.DYNAMIC); setPosition(OverlayPosition.DYNAMIC);
@@ -48,9 +43,7 @@ public class LootAssistOverlay extends Overlay
int y; int y;
try try
{ {
x = LocalPoint.fromWorld(client, pile.getLocation()).getSceneX(); x = LocalPoint.fromWorld(client, pile.getLocation()).getSceneX();
y = LocalPoint.fromWorld(client, pile.getLocation()).getSceneY(); y = LocalPoint.fromWorld(client, pile.getLocation()).getSceneY();
} }
catch (NullPointerException e) catch (NullPointerException e)
@@ -73,32 +66,32 @@ public class LootAssistOverlay extends Overlay
{ {
String nameOverlay = pile.getPlayerName(); String nameOverlay = pile.getPlayerName();
String timeOverlay = d.format((pile.getTimeAppearing() - System.currentTimeMillis()) / 1000f); String timeOverlay = d.format((pile.getTimeAppearing() - System.currentTimeMillis()) / 1000f);
final Polygon poly = Perspective.getCanvasTilePoly(client, final Polygon poly = Perspective.getCanvasTilePoly(client,
client.getScene().getTiles()[client.getPlane()][x][y].getLocalLocation()); client.getScene().getTiles()[client.getPlane()][x][y].getLocalLocation());
if (poly != null) if (poly != null)
{ {
Point textLoc = Perspective.getCanvasTextLocation(client, graphics, Point textLoc = Perspective.getCanvasTextLocation(client, graphics,
LocalPoint.fromWorld(client, pile.getLocation()), LocalPoint.fromWorld(client, pile.getLocation()),
nameOverlay, graphics.getFontMetrics().getHeight() * 7); nameOverlay, graphics.getFontMetrics().getHeight() * 7);
Point timeLoc = Perspective.getCanvasTextLocation(client, graphics, Point timeLoc = Perspective.getCanvasTextLocation(client, graphics,
LocalPoint.fromWorld(client, pile.getLocation()), LocalPoint.fromWorld(client, pile.getLocation()),
timeOverlay, graphics.getFontMetrics().getHeight()); timeOverlay, graphics.getFontMetrics().getHeight());
OverlayUtil.renderPolygon(graphics, poly, Color.WHITE); OverlayUtil.renderPolygon(graphics, poly, Color.WHITE);
if (timeRemaining < 5) if (timeRemaining < 5)
{ {
OverlayUtil.renderTextLocation(graphics, timeLoc, timeOverlay, Color.RED); OverlayUtil.renderTextLocation(graphics, timeLoc, timeOverlay, Color.RED);
OverlayUtil.renderTextLocation(graphics, textLoc, nameOverlay, Color.RED); OverlayUtil.renderTextLocation(graphics, textLoc, nameOverlay, Color.RED);
} }
if (timeRemaining < 2) if (timeRemaining < 2)
{ {
client.setHintArrow(WorldPoint.fromLocal(client, client.setHintArrow(WorldPoint.fromLocal(client,
LocalPoint.fromWorld(client, pile.getLocation()))); LocalPoint.fromWorld(client, pile.getLocation())));
} }
else else
{ {
OverlayUtil.renderTextLocation(graphics, timeLoc, timeOverlay, Color.WHITE); OverlayUtil.renderTextLocation(graphics, timeLoc, timeOverlay, Color.WHITE);
OverlayUtil.renderTextLocation(graphics, textLoc, nameOverlay, Color.WHITE); OverlayUtil.renderTextLocation(graphics, textLoc, nameOverlay, Color.WHITE);
} }
} }

View File

@@ -2,13 +2,11 @@ package net.runelite.client.plugins.lootassist;
import com.google.inject.Provides; import com.google.inject.Provides;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.inject.Inject; import javax.inject.Inject;
import net.runelite.api.Actor; import net.runelite.api.Actor;
import net.runelite.api.AnimationID; import net.runelite.api.AnimationID;
import net.runelite.api.Client; import net.runelite.api.Client;
import net.runelite.api.Player; import net.runelite.api.Player;
import net.runelite.api.coords.LocalPoint;
import net.runelite.api.coords.WorldPoint; import net.runelite.api.coords.WorldPoint;
import net.runelite.api.events.AnimationChanged; import net.runelite.api.events.AnimationChanged;
import net.runelite.api.events.GameStateChanged; import net.runelite.api.events.GameStateChanged;
@@ -28,21 +26,13 @@ import net.runelite.client.ui.overlay.OverlayManager;
) )
public class LootAssistPlugin extends Plugin public class LootAssistPlugin extends Plugin
{ {
@Inject
private Client client;
@Inject @Inject
OverlayManager overlayManager; OverlayManager overlayManager;
@Inject @Inject
LootAssistOverlay lootAssistOverlay; LootAssistOverlay lootAssistOverlay;
@Inject static ConcurrentHashMap<WorldPoint, LootPile> lootPiles = new ConcurrentHashMap<>();
private LootAssitConfig config;
public static ConcurrentHashMap<WorldPoint, LootPile> lootPiles = new ConcurrentHashMap<>();
@Provides @Provides
LootAssitConfig getConfig(ConfigManager configManager) LootAssitConfig getConfig(ConfigManager configManager)

View File

@@ -5,24 +5,28 @@ import lombok.Setter;
import net.runelite.api.coords.LocalPoint; import net.runelite.api.coords.LocalPoint;
import net.runelite.api.coords.WorldPoint; import net.runelite.api.coords.WorldPoint;
public class LootPile class LootPile
{ {
private static final long TIME_UNTIL_VISIBLE = 60000; private static final long TIME_UNTIL_VISIBLE = 60000;
private final long timeCreated;
@Getter @Getter
private final long timeAppearing; private final long timeAppearing;
@Getter @Getter
private final WorldPoint location; private final WorldPoint location;
@Getter @Getter
private final String playerName; private final String playerName;
@Getter @Setter
@Getter
@Setter
private boolean beingRendered = false; private boolean beingRendered = false;
public LootPile(WorldPoint location, String playerName) LootPile(WorldPoint location, String playerName)
{ {
this.timeCreated = System.currentTimeMillis(); long timeCreated = System.currentTimeMillis();
this.location = location; this.location = location;
this.playerName = playerName; this.playerName = playerName;
this.timeAppearing = this.timeCreated + TIME_UNTIL_VISIBLE; this.timeAppearing = timeCreated + TIME_UNTIL_VISIBLE;
} }
} }

View File

@@ -74,20 +74,26 @@ class LootingBagViewerOverlay extends Overlay
{ {
if(client.getItemContainer(InventoryID.LOOTING_BAG) != null) { if(client.getItemContainer(InventoryID.LOOTING_BAG) != null) {
itemContainer = client.getItemContainer(InventoryID.LOOTING_BAG); itemContainer = client.getItemContainer(InventoryID.LOOTING_BAG);
items = itemContainer.getItems(); if (itemContainer != null)
{
items = itemContainer.getItems();
}
} }
return null; return null;
} }
else if(itemContainer != null && client.getItemContainer(InventoryID.LOOTING_BAG) != null) else if(items != null && client.getItemContainer(InventoryID.LOOTING_BAG) != null)
{ {
itemContainer = client.getItemContainer(InventoryID.LOOTING_BAG); itemContainer = client.getItemContainer(InventoryID.LOOTING_BAG);
Item[] tempItems = itemContainer.getItems(); if (itemContainer != null)
for(int i = 0; i < items.length; i++)
{ {
if(!items[i].equals(tempItems[i])) Item[] tempItems = itemContainer.getItems();
for (int i = 0; i < items.length; i++)
{ {
items = tempItems; if (!items[i].equals(tempItems[i]))
{
items = tempItems;
}
} }
} }
} }

View File

@@ -31,24 +31,51 @@ import net.runelite.client.config.ConfigItem;
@ConfigGroup("menumodifier") @ConfigGroup("menumodifier")
public interface MenuModifierConfig extends Config public interface MenuModifierConfig extends Config
{ {
@ConfigItem(position = 0, keyName = "hideCancel", name = "Hide Cancel", description = "Hides the 'cancel' option from the right click menu") @ConfigItem(
default boolean hideCancel() { return true; } position = 0,
keyName = "hideExamine",
@ConfigItem(position = 1, keyName = "hideExamine", name = "Hide Examine", description = "Hides the 'examine' option from the right click menu") name = "Hide Examine",
description = "Hides the 'examine' option from the right click menu"
)
default boolean hideExamine() { return true; } default boolean hideExamine() { return true; }
@ConfigItem(position = 2, keyName = "hideTradeWith", name = "Hide Trade With", description = "Hides the 'trade with' option from the right click menu") @ConfigItem(
position = 1,
keyName = "hideTradeWith",
name = "Hide Trade With",
description = "Hides the 'trade with' option from the right click menu"
)
default boolean hideTradeWith() { return true; } default boolean hideTradeWith() { return true; }
@ConfigItem(position = 3, keyName = "hideReport", name = "Hide Report", description = "Hides the 'report' option from the right click menu") @ConfigItem(
position = 2,
keyName = "hideReport",
name = "Hide Report",
description = "Hides the 'report' option from the right click menu"
)
default boolean hideReport() { return true; } default boolean hideReport() { return true; }
@ConfigItem(position = 4, keyName = "hideLookup", name = "Hide Lookup", description = "Hides the 'lookup' option from the right click menu") @ConfigItem(
position = 3,
keyName = "hideLookup",
name = "Hide Lookup",
description = "Hides the 'lookup' option from the right click menu"
)
default boolean hideLookup() { return true; } default boolean hideLookup() { return true; }
@ConfigItem(position = 4, keyName = "hideNet", name = "Hide Net", description = "Hides the 'net' option from the right click menu") @ConfigItem(
position = 4,
keyName = "hideNet",
name = "Hide Net",
description = "Hides the 'net' option from the right click menu"
)
default boolean hideNet() { return true; } default boolean hideNet() { return true; }
@ConfigItem(position = 4, keyName = "hideBait", name = "Hide Bait", description = "Hides the 'Bait' option from the right click menu") @ConfigItem(
position = 5,
keyName = "hideBait",
name = "Hide Bait",
description = "Hides the 'Bait' option from the right click menu"
)
default boolean hideBait() { return true; } default boolean hideBait() { return true; }
} }

View File

@@ -24,40 +24,39 @@
*/ */
package net.runelite.client.plugins.menumodifier; package net.runelite.client.plugins.menumodifier;
import java.awt.event.KeyEvent;
import javax.inject.Inject;
import net.runelite.client.input.KeyListener; import net.runelite.client.input.KeyListener;
import net.runelite.client.input.MouseAdapter; import net.runelite.client.input.MouseAdapter;
import javax.inject.Inject;
import java.awt.event.KeyEvent;
public class MenuModifierInputListener extends MouseAdapter implements KeyListener public class MenuModifierInputListener extends MouseAdapter implements KeyListener
{ {
private static final int HOTKEY = KeyEvent.VK_CONTROL; private static final int HOTKEY = KeyEvent.VK_CONTROL;
@Override @Override
public void keyTyped(KeyEvent e) public void keyTyped(KeyEvent e)
{ {
} }
@Inject @Inject
private MenuModifierPlugin plugin; private MenuModifierPlugin plugin;
@Override @Override
public void keyPressed(KeyEvent e) public void keyPressed(KeyEvent e)
{ {
if (e.getKeyCode() == HOTKEY) if (e.getKeyCode() == HOTKEY)
{ {
plugin.setHotKeyPressed(true); plugin.setHotKeyPressed(true);
} }
} }
@Override @Override
public void keyReleased(KeyEvent e) public void keyReleased(KeyEvent e)
{ {
if (e.getKeyCode() == HOTKEY) if (e.getKeyCode() == HOTKEY)
{ {
plugin.setHotKeyPressed(false); plugin.setHotKeyPressed(false);
} }
} }
} }

View File

@@ -24,18 +24,19 @@
*/ */
package net.runelite.client.plugins.menumodifier; package net.runelite.client.plugins.menumodifier;
import net.runelite.api.events.MenuOpened;
import net.runelite.client.eventbus.Subscribe;
import com.google.inject.Provides; import com.google.inject.Provides;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import lombok.AccessLevel; import lombok.AccessLevel;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import net.runelite.api.Client; import net.runelite.api.Client;
import net.runelite.api.MenuEntry; import net.runelite.api.MenuEntry;
import net.runelite.api.Player; import net.runelite.api.Player;
import net.runelite.api.events.GameTick; import net.runelite.api.events.MenuOpened;
import net.runelite.api.events.MenuEntryAdded;
import net.runelite.client.config.ConfigManager; import net.runelite.client.config.ConfigManager;
import net.runelite.client.eventbus.Subscribe;
import net.runelite.client.input.KeyManager; import net.runelite.client.input.KeyManager;
import net.runelite.client.plugins.Plugin; import net.runelite.client.plugins.Plugin;
import net.runelite.client.plugins.PluginDescriptor; import net.runelite.client.plugins.PluginDescriptor;
@@ -43,158 +44,174 @@ import net.runelite.client.plugins.PluginType;
import net.runelite.client.util.MiscUtils; import net.runelite.client.util.MiscUtils;
import net.runelite.client.util.Text; import net.runelite.client.util.Text;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
@PluginDescriptor( @PluginDescriptor(
name = "Menu Modifier", name = "Menu Modifier",
description = "Changes right click menu for players", description = "Changes right click menu for players",
tags = { "menu", "modifier", "right", "click", "pk", "bogla" }, tags = {"menu", "modifier", "right", "click", "pk", "bogla"},
enabledByDefault = false, enabledByDefault = false,
type = PluginType.UTILITY type = PluginType.UTILITY
) )
public class MenuModifierPlugin extends Plugin public class MenuModifierPlugin extends Plugin
{ {
@Inject @Inject
private Client client; private Client client;
@Inject @Inject
private MenuModifierConfig config; private MenuModifierConfig config;
@Inject @Inject
private MenuModifierInputListener inputListener; private MenuModifierInputListener inputListener;
@Inject @Inject
private KeyManager keyManager; private KeyManager keyManager;
@Provides @Provides
MenuModifierConfig provideConfig(ConfigManager configManager) MenuModifierConfig provideConfig(ConfigManager configManager)
{ {
return configManager.getConfig(MenuModifierConfig.class); return configManager.getConfig(MenuModifierConfig.class);
} }
@Override @Override
protected void startUp() throws Exception protected void startUp() throws Exception
{ {
keyManager.registerKeyListener(inputListener); keyManager.registerKeyListener(inputListener);
} }
@Override @Override
protected void shutDown() throws Exception protected void shutDown() throws Exception
{ {
keyManager.unregisterKeyListener(inputListener); keyManager.unregisterKeyListener(inputListener);
} }
@Getter(AccessLevel.PACKAGE) @Getter(AccessLevel.PACKAGE)
@Setter(AccessLevel.PACKAGE) @Setter(AccessLevel.PACKAGE)
private boolean hotKeyPressed; private boolean hotKeyPressed;
@Subscribe @Subscribe
public void onMenuOpened(MenuOpened event) public void onMenuOpened(MenuOpened event)
{ {
Player localPlayer = client.getLocalPlayer(); Player localPlayer = client.getLocalPlayer();
if (localPlayer == null) if (localPlayer == null)
return; {
return;
}
if (!(MiscUtils.getWildernessLevelFrom(client, localPlayer.getWorldLocation()) >= 0)) if (!(MiscUtils.getWildernessLevelFrom(client, localPlayer.getWorldLocation()) >= 0))
return; {
return;
}
if (hotKeyPressed) if (hotKeyPressed)
return; {
return;
}
List<MenuEntry> menu_entries = new ArrayList<MenuEntry>(); List<MenuEntry> menu_entries = new ArrayList<>();
for (MenuEntry entry : event.getMenuEntries()) for (MenuEntry entry : event.getMenuEntries())
{ {
String option = Text.removeTags(entry.getOption()).toLowerCase(); String option = Text.removeTags(entry.getOption()).toLowerCase();
if (option.contains("trade with") && config.hideTradeWith()) if (option.contains("trade with") && config.hideTradeWith())
continue; {
continue;
}
if (option.contains("lookup") && config.hideLookup()) if (option.contains("lookup") && config.hideLookup())
continue; {
continue;
}
if (option.contains("report") && config.hideReport()) if (option.contains("report") && config.hideReport())
continue; {
continue;
}
if (option.contains("examine") && config.hideExamine()) if (option.contains("examine") && config.hideExamine())
continue; {
continue;
}
if (option.contains("net") && config.hideNet()) if (option.contains("net") && config.hideNet())
{
continue; continue;
}
if (option.contains("bait") && config.hideBait()) if (option.contains("bait") && config.hideBait())
{
continue; continue;
}
int identifier = entry.getIdentifier(); int identifier = entry.getIdentifier();
Player[] players = client.getCachedPlayers(); Player[] players = client.getCachedPlayers();
Player player = null; Player player = null;
if (identifier >= 0 && identifier < players.length) if (identifier >= 0 && identifier < players.length)
player = players[identifier]; {
player = players[identifier];
}
if (player == null) if (player == null)
{ {
menu_entries.add(entry); menu_entries.add(entry);
continue; continue;
} }
if ((option.contains("attack") || option.contains("cast")) && (player.isFriend() || player.isClanMember())) if ((option.contains("attack") || option.contains("cast")) && (player.isFriend() || player.isClanMember()))
continue; {
continue;
}
menu_entries.add(entry); menu_entries.add(entry);
} }
MenuEntry[] updated_menu_entries = new MenuEntry[menu_entries.size()]; MenuEntry[] updated_menu_entries = new MenuEntry[menu_entries.size()];
updated_menu_entries = menu_entries.toArray(updated_menu_entries); updated_menu_entries = menu_entries.toArray(updated_menu_entries);
client.setMenuEntries(updated_menu_entries); client.setMenuEntries(updated_menu_entries);
} }
/*@Subscribe /*@Subscribe
public void onMenuEntryAdded(MenuEntryAdded menuEntryAdded) public void onMenuEntryAdded(MenuEntryAdded menuEntryAdded)
{ {
if (true) if (true)
return; return;
if (!inWilderness) if (!inWilderness)
return; return;
if (hotKeyPressed) if (hotKeyPressed)
return; return;
String option = Text.removeTags(menuEntryAdded.getOption()).toLowerCase(); String option = Text.removeTags(menuEntryAdded.getOption()).toLowerCase();
if ((option.contains("trade with") && config.hideTradeWith()) if ((option.contains("trade with") && config.hideTradeWith())
|| (option.contains("lookup") && config.hideLookup()) || (option.contains("lookup") && config.hideLookup())
|| (option.contains("report") && config.hideReport()) || (option.contains("report") && config.hideReport())
|| (option.contains("examine") && config.hideExamine()) || (option.contains("examine") && config.hideExamine())
|| (option.contains("cancel") && config.hideCancel())) || (option.contains("cancel") && config.hideCancel()))
{ {
int identifier = menuEntryAdded.getIdentifier(); int identifier = menuEntryAdded.getIdentifier();
Player[] players = client.getCachedPlayers(); Player[] players = client.getCachedPlayers();
Player player = null; Player player = null;
if (identifier >= 0 && identifier < players.length) if (identifier >= 0 && identifier < players.length)
player = players[identifier]; player = players[identifier];
if (player == null) if (player == null)
return; return;
//allow trading with friends/clanmates //allow trading with friends/clanmates
if (option.contains("trade with") && (player.isFriend() || player.isClanMember())) if (option.contains("trade with") && (player.isFriend() || player.isClanMember()))
return; return;
MenuEntry[] menuEntries = client.getMenuEntries(); MenuEntry[] menuEntries = client.getMenuEntries();
if (menuEntries.length > 0) if (menuEntries.length > 0)
client.setMenuEntries(Arrays.copyOf(menuEntries, menuEntries.length - 1)); client.setMenuEntries(Arrays.copyOf(menuEntries, menuEntries.length - 1));
} }
}*/ }*/
} }

View File

@@ -24,72 +24,69 @@
*/ */
package net.runelite.client.plugins.pluginsorter; package net.runelite.client.plugins.pluginsorter;
import java.awt.Color;
import net.runelite.client.config.Config; import net.runelite.client.config.Config;
import net.runelite.client.config.ConfigGroup; import net.runelite.client.config.ConfigGroup;
import net.runelite.client.config.ConfigItem; import net.runelite.client.config.ConfigItem;
import java.awt.*;
@ConfigGroup("pluginsorter") @ConfigGroup("pluginsorter")
public interface PluginSorterConfig extends Config { public interface PluginSorterConfig extends Config
{
boolean pluginsHidden = false;
Color rlDefault = new Color(250, 155, 23); @ConfigItem(
position = 0,
keyName = "hidePlugins",
name = "Hide Plugins",
description = "Hides all 3rd party plugins if checked"
)
default boolean hidePlugins()
{
return pluginsHidden;
}
boolean pluginsHidden = false; @ConfigItem(
position = 1,
keyName = "externalColor",
name = "External color",
description = "Configure the color of external plugins"
)
default Color externalColor()
{
return Color.MAGENTA;
}
@ConfigItem( @ConfigItem(
position = 0, position = 2,
keyName = "hidePlugins", keyName = "pvmColor",
name = "Hide Plugins", name = "PVM color",
description = "Hides all 3rd party plugins if checked" description = "Configure the color of PVM related plugins"
) )
default boolean hidePlugins() default Color pvmColor()
{ {
return pluginsHidden; return Color.GREEN;
} }
@ConfigItem( @ConfigItem(
position = 1, position = 3,
keyName = "externalColor", keyName = "pvpColor",
name = "External color", name = "PVP color",
description = "Configure the color of external plugins" description = "Configure the color of PVP related plugins"
) )
default Color externalColor() default Color pvpColor()
{ {
return Color.MAGENTA; return Color.RED;
} }
@ConfigItem( @ConfigItem(
position = 2, position = 4,
keyName = "pvmColor", keyName = "utilityColor",
name = "PVM color", name = "Utility color",
description = "Configure the color of PVM related plugins" description = "Configure the color of utility related plugins"
) )
default Color pvmColor() default Color utilityColor()
{ {
return Color.GREEN; return Color.CYAN;
} }
@ConfigItem(
position = 3,
keyName = "pvpColor",
name = "PVP color",
description = "Configure the color of PVP related plugins"
)
default Color pvpColor()
{
return Color.RED;
}
@ConfigItem(
position = 4,
keyName = "utilityColor",
name = "Utility color",
description = "Configure the color of utility related plugins"
)
default Color utilityColor()
{
return Color.CYAN;
}
} }

View File

@@ -25,10 +25,14 @@
package net.runelite.client.plugins.pluginsorter; package net.runelite.client.plugins.pluginsorter;
import com.google.inject.Provides; import com.google.inject.Provides;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.inject.Inject;
import net.runelite.api.GameState; import net.runelite.api.GameState;
import net.runelite.api.events.ConfigChanged; import net.runelite.api.events.ConfigChanged;
import net.runelite.api.events.GameStateChanged; import net.runelite.api.events.GameStateChanged;
import net.runelite.client.config.ConfigItemDescriptor;
import net.runelite.client.config.ConfigManager; import net.runelite.client.config.ConfigManager;
import net.runelite.client.eventbus.Subscribe; import net.runelite.client.eventbus.Subscribe;
import net.runelite.client.plugins.Plugin; import net.runelite.client.plugins.Plugin;
@@ -37,70 +41,76 @@ import net.runelite.client.plugins.PluginType;
import net.runelite.client.plugins.config.ConfigPanel; import net.runelite.client.plugins.config.ConfigPanel;
import net.runelite.client.plugins.config.PluginListItem; import net.runelite.client.plugins.config.PluginListItem;
import javax.inject.Inject;
import java.awt.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@PluginDescriptor( @PluginDescriptor(
name = "Plugin Organizer", name = "Plugin Organizer",
description = "Hides and colors 3rd party plugins for better control", description = "Hides and colors 3rd party plugins for better control",
tags = {"plugins","organizer"}, tags = {"plugins", "organizer"},
type = PluginType.PLUGIN_ORGANIZER type = PluginType.PLUGIN_ORGANIZER
) )
public class PluginSorterPlugin extends Plugin { public class PluginSorterPlugin extends Plugin
{
//Cache the hidden plugins
private static List<PluginListItem> removedPlugins = new ArrayList<>();
//Cache the hidden plugins @Inject
public static List<PluginListItem> removedPlugins = new ArrayList<>(); private PluginSorterConfig config;
@Inject @Provides
private PluginSorterConfig config; PluginSorterConfig provideConfig(ConfigManager configManager)
{
return configManager.getConfig(PluginSorterConfig.class);
}
@Provides @Override
PluginSorterConfig provideConfig(ConfigManager configManager) protected void startUp() throws Exception
{ {
return configManager.getConfig(PluginSorterConfig.class); updateColors();
} }
@Override @Override
protected void startUp() throws Exception protected void shutDown() throws Exception
{ {
updateColors();
}
@Override }
protected void shutDown() throws Exception
{
} @Subscribe
public void onGameStateChanged(GameStateChanged gameStateChanged)
{
if (gameStateChanged.getGameState() == GameState.LOGIN_SCREEN)
{
if (config.hidePlugins())
{
hidePlugins();
}
updateColors();
}
}
@Subscribe @Subscribe
public void onGameStateChanged (GameStateChanged gameStateChanged) public void onConfigChanged(ConfigChanged configChanged)
{ {
if (gameStateChanged.getGameState()== GameState.LOGIN_SCREEN) { if (configChanged.getKey().equals("hidePlugins"))
if (config.hidePlugins()) {
hidePlugins(); if (config.hidePlugins())
updateColors(); {
} hidePlugins();
} }
else
{
showPlugins();
}
}
updateColors();
}
@Subscribe private void updateColors()
public void onConfigChanged(ConfigChanged configChanged) { {
if (configChanged.getKey().equals("hidePlugins")) { for (PluginListItem pli : ConfigPanel.pluginList)
if (config.hidePlugins()) { {
hidePlugins(); if (pli.getPlugin() != null)
} else { {
showPlugins(); switch (pli.getPlugin().getClass().getAnnotation(PluginDescriptor.class).type())
} {
}
updateColors();
}
public void updateColors() {
for (PluginListItem pli : ConfigPanel.pluginList) {
if (pli.getPlugin()!=null) {
switch (pli.getPlugin().getClass().getAnnotation(PluginDescriptor.class).type()) {
case EXTERNAL: case EXTERNAL:
pli.nameLabel.setForeground(config.externalColor()); pli.nameLabel.setForeground(config.externalColor());
break; break;
@@ -117,15 +127,18 @@ public class PluginSorterPlugin extends Plugin {
pli.nameLabel.setForeground(Color.WHITE); pli.nameLabel.setForeground(Color.WHITE);
break; break;
} }
} }
} }
} }
public void hidePlugins() { private void hidePlugins()
Iterator<PluginListItem> iter = ConfigPanel.pluginList.iterator(); {
while (iter.hasNext()) { Iterator<PluginListItem> iter = ConfigPanel.pluginList.iterator();
PluginListItem pli = iter.next(); while (iter.hasNext())
if (pli.getPlugin() != null) { {
PluginListItem pli = iter.next();
if (pli.getPlugin() != null)
{
switch (pli.getPlugin().getClass().getAnnotation(PluginDescriptor.class).type()) switch (pli.getPlugin().getClass().getAnnotation(PluginDescriptor.class).type())
{ {
case PVM: case PVM:
@@ -139,14 +152,15 @@ public class PluginSorterPlugin extends Plugin {
default: default:
break; break;
} }
} }
} }
} }
public void showPlugins() { private void showPlugins()
List<PluginListItem> tempList = new ArrayList<>(); {
List<PluginListItem> tempList = new ArrayList<>();
tempList.addAll(removedPlugins); tempList.addAll(removedPlugins);
tempList.addAll(ConfigPanel.pluginList); tempList.addAll(ConfigPanel.pluginList);
ConfigPanel.pluginList = tempList; ConfigPanel.pluginList = tempList;
} }
} }

View File

@@ -31,26 +31,34 @@ import net.runelite.api.Player;
* When they attacked me * When they attacked me
* And (in milliseconds) when to expire the overlay around them * And (in milliseconds) when to expire the overlay around them
*/ */
public class PlayerContainer { public class PlayerContainer
{
private Player player; private Player player;
private long whenTheyAttackedMe; private long whenTheyAttackedMe;
private int millisToExpireHighlight; private int millisToExpireHighlight;
public PlayerContainer(Player player, long whenTheyAttackedMe, int millisToExpireHighlight) { PlayerContainer(Player player, long whenTheyAttackedMe, int millisToExpireHighlight)
{
this.player = player; this.player = player;
this.whenTheyAttackedMe = whenTheyAttackedMe; this.whenTheyAttackedMe = whenTheyAttackedMe;
this.millisToExpireHighlight = millisToExpireHighlight; this.millisToExpireHighlight = millisToExpireHighlight;
} }
//getters //getters
public Player getPlayer() { public Player getPlayer()
{
return player; return player;
} }
public long getWhenTheyAttackedMe() {
long getWhenTheyAttackedMe()
{
return whenTheyAttackedMe; return whenTheyAttackedMe;
} }
public int getMillisToExpireHighlight() { return millisToExpireHighlight; };
int getMillisToExpireHighlight()
{
return millisToExpireHighlight;
}
} }

View File

@@ -24,160 +24,209 @@
package net.runelite.client.plugins.prayagainstplayer; package net.runelite.client.plugins.prayagainstplayer;
import java.awt.Color;
import net.runelite.client.config.Config; import net.runelite.client.config.Config;
import net.runelite.client.config.ConfigGroup; import net.runelite.client.config.ConfigGroup;
import net.runelite.client.config.ConfigItem; import net.runelite.client.config.ConfigItem;
import java.awt.*;
@ConfigGroup("prayagainstplayer") @ConfigGroup("prayagainstplayer")
public interface PrayAgainstPlayerConfig extends Config { public interface PrayAgainstPlayerConfig extends Config
{
@ConfigItem( @ConfigItem(
position = 0, position = 0,
keyName = "attackerPlayerColor", keyName = "attackerPlayerColor",
name = "Attacker color", name = "Attacker color",
description = "This is the color that will be used to highlight attackers." description = "This is the color that will be used to highlight attackers."
) )
default Color attackerPlayerColor() { return new Color(0xFF0006); } default Color attackerPlayerColor()
{
return new Color(0xFF0006);
}
@ConfigItem( @ConfigItem(
position = 1, position = 1,
keyName = "potentialPlayerColor", keyName = "potentialPlayerColor",
name = "Potential Attacker color", name = "Potential Attacker color",
description = "This is the color that will be used to highlight potential attackers." description = "This is the color that will be used to highlight potential attackers."
) )
default Color potentialPlayerColor() { return new Color(0xFFFF00); } default Color potentialPlayerColor()
{
//// return new Color(0xFFFF00);
@ConfigItem( }
position = 2,
keyName = "attackerTargetTimeout",
name = "Attacker Timeout",
description = "Seconds until attacker is no longer highlighted."
)
default int attackerTargetTimeout() { return 10; }
@ConfigItem( @ConfigItem(
position = 3, position = 2,
keyName = "potentialTargetTimeout", keyName = "attackerTargetTimeout",
name = "Potential Attacker Timeout", name = "Attacker Timeout",
description = "Seconds until potential attacker is no longer highlighted." description = "Seconds until attacker is no longer highlighted."
) )
default int potentialTargetTimeout() { return 10; } default int attackerTargetTimeout()
{
return 10;
}
@ConfigItem( @ConfigItem(
position = 4, position = 3,
keyName = "newSpawnTimeout", keyName = "potentialTargetTimeout",
name = "New Player Timeout", name = "Potential Attacker Timeout",
description = "Seconds until logged in/spawned player is no longer highlighted." description = "Seconds until potential attacker is no longer highlighted."
) )
default int newSpawnTimeout() { return 5; } default int potentialTargetTimeout()
//// {
return 10;
//// }
@ConfigItem(
position = 5,
keyName = "ignoreFriends",
name = "Ignore Friends",
description = "This lets you decide whether you want friends to be highlighted by this plugin."
)
default boolean ignoreFriends() { return true; }
@ConfigItem( @ConfigItem(
position = 6, position = 4,
keyName = "ignoreClanMates", keyName = "newSpawnTimeout",
name = "Ignore Clan Mates", name = "New Player Timeout",
description = "This lets you decide whether you want clan mates to be highlighted by this plugin." description = "Seconds until logged in/spawned player is no longer highlighted."
) )
default boolean ignoreClanMates() { return true; } default int newSpawnTimeout()
//// {
return 5;
}
@ConfigItem( @ConfigItem(
position = 7, position = 5,
keyName = "markNewPlayer", keyName = "ignoreFriends",
name = "Mark new player as potential attacker", name = "Ignore Friends",
description = "Marks someone that logged in or teleported as a potential attacker for your safety\nDO NOT RUN THIS IN WORLD 1-2 GRAND EXCHANGE!" description = "This lets you decide whether you want friends to be highlighted by this plugin."
) )
default boolean markNewPlayer() { return false; } default boolean ignoreFriends()
{
return true;
}
@ConfigItem( @ConfigItem(
position = 8, position = 6,
keyName = "drawTargetPrayAgainst", keyName = "ignoreClanMates",
name = "Draw what to pray on attacker", name = "Ignore Clan Mates",
description = "Tells you what to pray from what weapon the attacker is holding" description = "This lets you decide whether you want clan mates to be highlighted by this plugin."
) )
default boolean drawTargetPrayAgainst() { return true; } default boolean ignoreClanMates()
{
return true;
}
@ConfigItem( @ConfigItem(
position = 9, position = 7,
keyName = "drawPotentialTargetPrayAgainst", keyName = "markNewPlayer",
name = "Draw what to pray on potential attacker", name = "Mark new player as potential attacker",
description = "Tells you what to pray from what weapon the potential attacker is holding" description = "Marks someone that logged in or teleported as a potential attacker for your safety\nDO NOT RUN THIS IN WORLD 1-2 GRAND EXCHANGE!"
) )
default boolean drawPotentialTargetPrayAgainst() { return true; } default boolean markNewPlayer()
{
return false;
}
@ConfigItem( @ConfigItem(
position = 10, position = 8,
keyName = "drawTargetPrayAgainstPrayerTab", keyName = "drawTargetPrayAgainst",
name = "Draw what to pray from prayer tab", name = "Draw what to pray on attacker",
description = "Tells you what to pray from what weapon the attacker is holding from the prayer tab" description = "Tells you what to pray from what weapon the attacker is holding"
) )
default boolean drawTargetPrayAgainstPrayerTab() { return false; } default boolean drawTargetPrayAgainst()
{
return true;
}
@ConfigItem( @ConfigItem(
position = 11, position = 9,
keyName = "drawTargetsName", keyName = "drawPotentialTargetPrayAgainst",
name = "Draw name on attacker", name = "Draw what to pray on potential attacker",
description = "Configures whether or not the attacker\'s name should be shown" description = "Tells you what to pray from what weapon the potential attacker is holding"
) )
default boolean drawTargetsName() { return true; } default boolean drawPotentialTargetPrayAgainst()
{
return true;
}
@ConfigItem( @ConfigItem(
position = 12, position = 10,
keyName = "drawPotentialTargetsName", keyName = "drawTargetPrayAgainstPrayerTab",
name = "Draw name on potential attacker", name = "Draw what to pray from prayer tab",
description = "Configures whether or not the potential attacker\'s name should be shown" description = "Tells you what to pray from what weapon the attacker is holding from the prayer tab"
) )
default boolean drawPotentialTargetsName() { return true; } default boolean drawTargetPrayAgainstPrayerTab()
{
return false;
}
@ConfigItem( @ConfigItem(
position = 13, position = 11,
keyName = "drawTargetHighlight", keyName = "drawTargetsName",
name = "Draw highlight around attacker", name = "Draw name on attacker",
description = "Configures whether or not the attacker should be highlighted" description = "Configures whether or not the attacker\'s name should be shown"
) )
default boolean drawTargetHighlight() { return true; } default boolean drawTargetsName()
{
return true;
}
@ConfigItem( @ConfigItem(
position = 14, position = 12,
keyName = "drawPotentialTargetHighlight", keyName = "drawPotentialTargetsName",
name = "Draw highlight around potential attacker", name = "Draw name on potential attacker",
description = "Configures whether or not the potential attacker should be highlighted" description = "Configures whether or not the potential attacker\'s name should be shown"
) )
default boolean drawPotentialTargetHighlight() { return true; } default boolean drawPotentialTargetsName()
{
return true;
}
@ConfigItem( @ConfigItem(
position = 15, position = 13,
keyName = "drawTargetTile", keyName = "drawTargetHighlight",
name = "Draw tile under attacker", name = "Draw highlight around attacker",
description = "Configures whether or not the attacker\'s tile be highlighted" description = "Configures whether or not the attacker should be highlighted"
) )
default boolean drawTargetTile() { return false; } default boolean drawTargetHighlight()
{
return true;
}
@ConfigItem( @ConfigItem(
position = 16, position = 14,
keyName = "drawPotentialTargetTile", keyName = "drawPotentialTargetHighlight",
name = "Draw tile under potential attacker", name = "Draw highlight around potential attacker",
description = "Configures whether or not the potential attacker\'s tile be highlighted" description = "Configures whether or not the potential attacker should be highlighted"
) )
default boolean drawPotentialTargetTile() { return false; } default boolean drawPotentialTargetHighlight()
{
return true;
}
@ConfigItem( @ConfigItem(
position = 17, position = 15,
keyName = "drawUnknownWeapons", keyName = "drawTargetTile",
name = "Draw unknown weapons", name = "Draw tile under attacker",
description = "Configures whether or not the unknown weapons should be shown when a player equips one" description = "Configures whether or not the attacker\'s tile be highlighted"
) )
default boolean drawUnknownWeapons() { return false; } default boolean drawTargetTile()
{
return false;
}
@ConfigItem(
position = 16,
keyName = "drawPotentialTargetTile",
name = "Draw tile under potential attacker",
description = "Configures whether or not the potential attacker\'s tile be highlighted"
)
default boolean drawPotentialTargetTile()
{
return false;
}
@ConfigItem(
position = 17,
keyName = "drawUnknownWeapons",
name = "Draw unknown weapons",
description = "Configures whether or not the unknown weapons should be shown when a player equips one"
)
default boolean drawUnknownWeapons()
{
return false;
}
} }

View File

@@ -24,27 +24,35 @@
package net.runelite.client.plugins.prayagainstplayer; package net.runelite.client.plugins.prayagainstplayer;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.image.BufferedImage;
import java.util.ConcurrentModificationException;
import javax.inject.Inject;
import net.runelite.api.Client; import net.runelite.api.Client;
import net.runelite.api.ItemComposition; import net.runelite.api.ItemComposition;
import net.runelite.api.Player; import net.runelite.api.Player;
import net.runelite.api.kit.KitType;
import net.runelite.client.ui.overlay.*;
import net.runelite.client.util.Text;
import net.runelite.api.Point; import net.runelite.api.Point;
import net.runelite.api.kit.KitType;
import net.runelite.client.ui.overlay.Overlay;
import net.runelite.client.ui.overlay.OverlayLayer;
import net.runelite.client.ui.overlay.OverlayPosition;
import net.runelite.client.ui.overlay.OverlayPriority;
import net.runelite.client.ui.overlay.OverlayUtil;
import net.runelite.client.util.Text;
import javax.inject.Inject; class PrayAgainstPlayerOverlay extends Overlay
import java.awt.*; {
import java.awt.image.BufferedImage;
import java.util.ConcurrentModificationException;
class PrayAgainstPlayerOverlay extends Overlay {
private final PrayAgainstPlayerPlugin plugin; private final PrayAgainstPlayerPlugin plugin;
private final PrayAgainstPlayerConfig config; private final PrayAgainstPlayerConfig config;
private final Client client; private final Client client;
@Inject @Inject
private PrayAgainstPlayerOverlay(PrayAgainstPlayerPlugin plugin, PrayAgainstPlayerConfig config, Client client) { private PrayAgainstPlayerOverlay(PrayAgainstPlayerPlugin plugin, PrayAgainstPlayerConfig config, Client client)
{
super(plugin); super(plugin);
this.plugin = plugin; this.plugin = plugin;
this.config = config; this.config = config;
@@ -57,73 +65,127 @@ class PrayAgainstPlayerOverlay extends Overlay {
@Override @Override
public Dimension render(Graphics2D graphics) { public Dimension render(Graphics2D graphics)
{
renderPotentialPlayers(graphics); renderPotentialPlayers(graphics);
renderAttackingPlayers(graphics); renderAttackingPlayers(graphics);
return null; return null;
} }
private void renderPotentialPlayers(Graphics2D graphics) { private void renderPotentialPlayers(Graphics2D graphics)
if (plugin.getPotentialPlayersAttackingMe() == null || !plugin.getPotentialPlayersAttackingMe().isEmpty()) { {
try { if (plugin.getPotentialPlayersAttackingMe() == null || !plugin.getPotentialPlayersAttackingMe().isEmpty())
for (PlayerContainer container : plugin.getPotentialPlayersAttackingMe()) { {
if ((System.currentTimeMillis() > (container.getWhenTheyAttackedMe() + container.getMillisToExpireHighlight())) && (container.getPlayer().getInteracting() != client.getLocalPlayer())) { try
plugin.removePlayerFromPotentialContainer(container); {
if (plugin.getPotentialPlayersAttackingMe() != null)
{
for (PlayerContainer container : plugin.getPotentialPlayersAttackingMe())
{
if ((System.currentTimeMillis() > (container.getWhenTheyAttackedMe() + container.getMillisToExpireHighlight())) && (container.getPlayer().getInteracting() != client.getLocalPlayer()))
{
plugin.removePlayerFromPotentialContainer(container);
}
if (config.drawPotentialTargetsName())
{
renderNameAboveHead(graphics, container.getPlayer(), config.potentialPlayerColor());
}
if (config.drawPotentialTargetHighlight())
{
renderHighlightedPlayer(graphics, container.getPlayer(), config.potentialPlayerColor());
}
if (config.drawPotentialTargetTile())
{
renderTileUnderPlayer(graphics, container.getPlayer(), config.potentialPlayerColor());
}
if (config.drawPotentialTargetPrayAgainst())
{
renderPrayAgainstOnPlayer(graphics, container.getPlayer(), config.potentialPlayerColor());
}
} }
if (config.drawPotentialTargetsName()) renderNameAboveHead(graphics, container.getPlayer(), config.potentialPlayerColor());
if (config.drawPotentialTargetHighlight()) renderHighlightedPlayer(graphics, container.getPlayer(), config.potentialPlayerColor());
if (config.drawPotentialTargetTile()) renderTileUnderPlayer(graphics, container.getPlayer(), config.potentialPlayerColor());
if (config.drawPotentialTargetPrayAgainst()) renderPrayAgainstOnPlayer(graphics, container.getPlayer(), config.potentialPlayerColor());
} }
} catch (ConcurrentModificationException e) { }
catch (ConcurrentModificationException ignored)
{
} }
} }
} }
private void renderAttackingPlayers(Graphics2D graphics) { private void renderAttackingPlayers(Graphics2D graphics)
if (plugin.getPlayersAttackingMe() == null || !plugin.getPlayersAttackingMe().isEmpty()) { {
try { if (plugin.getPlayersAttackingMe() == null || !plugin.getPlayersAttackingMe().isEmpty())
for (PlayerContainer container : plugin.getPlayersAttackingMe()) { {
if ((System.currentTimeMillis() > (container.getWhenTheyAttackedMe() + container.getMillisToExpireHighlight())) && (container.getPlayer().getInteracting() != client.getLocalPlayer())) { try
plugin.removePlayerFromAttackerContainer(container); {
} if (plugin.getPlayersAttackingMe() != null)
{
for (PlayerContainer container : plugin.getPlayersAttackingMe())
{
if ((System.currentTimeMillis() > (container.getWhenTheyAttackedMe() + container.getMillisToExpireHighlight())) && (container.getPlayer().getInteracting() != client.getLocalPlayer()))
{
plugin.removePlayerFromAttackerContainer(container);
}
if (config.drawTargetsName()) renderNameAboveHead(graphics, container.getPlayer(), config.attackerPlayerColor()); if (config.drawTargetsName())
if (config.drawTargetHighlight()) renderHighlightedPlayer(graphics, container.getPlayer(), config.attackerPlayerColor()); {
if (config.drawTargetTile()) renderTileUnderPlayer(graphics, container.getPlayer(), config.attackerPlayerColor()); renderNameAboveHead(graphics, container.getPlayer(), config.attackerPlayerColor());
if (config.drawTargetPrayAgainst()) renderPrayAgainstOnPlayer(graphics, container.getPlayer(), config.attackerPlayerColor()); }
if (config.drawTargetHighlight())
{
renderHighlightedPlayer(graphics, container.getPlayer(), config.attackerPlayerColor());
}
if (config.drawTargetTile())
{
renderTileUnderPlayer(graphics, container.getPlayer(), config.attackerPlayerColor());
}
if (config.drawTargetPrayAgainst())
{
renderPrayAgainstOnPlayer(graphics, container.getPlayer(), config.attackerPlayerColor());
}
}
} }
} catch (ConcurrentModificationException e) { }
catch (ConcurrentModificationException ignored)
{
} }
} }
} }
private void renderNameAboveHead(Graphics2D graphics, Player player, Color color) { private void renderNameAboveHead(Graphics2D graphics, Player player, Color color)
{
final String name = Text.sanitize(player.getName()); final String name = Text.sanitize(player.getName());
final int offset = player.getLogicalHeight() + 40; final int offset = player.getLogicalHeight() + 40;
Point textLocation = player.getCanvasTextLocation(graphics, name, offset); Point textLocation = player.getCanvasTextLocation(graphics, name, offset);
if (textLocation != null) { if (textLocation != null)
{
OverlayUtil.renderTextLocation(graphics, textLocation, name, color); OverlayUtil.renderTextLocation(graphics, textLocation, name, color);
} }
} }
private void renderHighlightedPlayer(Graphics2D graphics, Player player, Color color) { private void renderHighlightedPlayer(Graphics2D graphics, Player player, Color color)
try { {
try
{
OverlayUtil.renderPolygon(graphics, player.getConvexHull(), color); OverlayUtil.renderPolygon(graphics, player.getConvexHull(), color);
} catch (NullPointerException e) { }
catch (NullPointerException ignored)
{
} }
} }
private void renderTileUnderPlayer(Graphics2D graphics, Player player, Color color) { private void renderTileUnderPlayer(Graphics2D graphics, Player player, Color color)
{
Polygon poly = player.getCanvasTilePoly(); Polygon poly = player.getCanvasTilePoly();
OverlayUtil.renderPolygon(graphics, poly, color); OverlayUtil.renderPolygon(graphics, poly, color);
} }
private void renderPrayAgainstOnPlayer(Graphics2D graphics, Player player, Color color) { private void renderPrayAgainstOnPlayer(Graphics2D graphics, Player player, Color color)
{
final int offset = (player.getLogicalHeight() / 2) + 75; final int offset = (player.getLogicalHeight() / 2) + 75;
BufferedImage icon; BufferedImage icon;
switch (WeaponType.checkWeaponOnPlayer(client, player)) { switch (WeaponType.checkWeaponOnPlayer(client, player))
{
case WEAPON_MELEE: case WEAPON_MELEE:
icon = plugin.getProtectionIcon(WeaponType.WEAPON_MELEE); icon = plugin.getProtectionIcon(WeaponType.WEAPON_MELEE);
break; break;
@@ -137,12 +199,17 @@ class PrayAgainstPlayerOverlay extends Overlay {
icon = null; icon = null;
break; break;
} }
try { try
if (icon != null) { {
if (icon != null)
{
Point point = player.getCanvasImageLocation(icon, offset); Point point = player.getCanvasImageLocation(icon, offset);
OverlayUtil.renderImageLocation(graphics, point, icon); OverlayUtil.renderImageLocation(graphics, point, icon);
} else { }
if (config.drawUnknownWeapons()) { else
{
if (config.drawUnknownWeapons())
{
int itemId = player.getPlayerComposition().getEquipmentId(KitType.WEAPON); int itemId = player.getPlayerComposition().getEquipmentId(KitType.WEAPON);
ItemComposition itemComposition = client.getItemDefinition(itemId); ItemComposition itemComposition = client.getItemDefinition(itemId);
@@ -151,7 +218,9 @@ class PrayAgainstPlayerOverlay extends Overlay {
OverlayUtil.renderTextLocation(graphics, point, str, color); OverlayUtil.renderTextLocation(graphics, point, str, color);
} }
} }
} catch (Exception e) { }
catch (Exception ignored)
{
} }
} }

View File

@@ -24,24 +24,33 @@
package net.runelite.client.plugins.prayagainstplayer; package net.runelite.client.plugins.prayagainstplayer;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.Rectangle;
import java.util.ConcurrentModificationException;
import javax.inject.Inject;
import net.runelite.api.Client; import net.runelite.api.Client;
import net.runelite.api.Player; import net.runelite.api.Player;
import net.runelite.api.widgets.Widget; import net.runelite.api.widgets.Widget;
import net.runelite.api.widgets.WidgetInfo; import net.runelite.api.widgets.WidgetInfo;
import net.runelite.client.ui.overlay.*; import net.runelite.client.ui.overlay.Overlay;
import net.runelite.client.ui.overlay.OverlayLayer;
import net.runelite.client.ui.overlay.OverlayPosition;
import net.runelite.client.ui.overlay.OverlayPriority;
import net.runelite.client.ui.overlay.OverlayUtil;
import javax.inject.Inject; class PrayAgainstPlayerOverlayPrayerTab extends Overlay
import java.awt.*; {
import java.util.ConcurrentModificationException;
class PrayAgainstPlayerOverlayPrayerTab extends Overlay {
private final PrayAgainstPlayerPlugin plugin; private final PrayAgainstPlayerPlugin plugin;
private final PrayAgainstPlayerConfig config; private final PrayAgainstPlayerConfig config;
private final Client client; private final Client client;
@Inject @Inject
private PrayAgainstPlayerOverlayPrayerTab (PrayAgainstPlayerPlugin plugin, PrayAgainstPlayerConfig config, Client client) { private PrayAgainstPlayerOverlayPrayerTab(PrayAgainstPlayerPlugin plugin, PrayAgainstPlayerConfig config, Client client)
{
super(plugin); super(plugin);
this.plugin = plugin; this.plugin = plugin;
this.config = config; this.config = config;
@@ -54,30 +63,46 @@ class PrayAgainstPlayerOverlayPrayerTab extends Overlay {
@Override @Override
public Dimension render(Graphics2D graphics) { public Dimension render(Graphics2D graphics)
if (plugin.getPlayersAttackingMe() == null || !plugin.getPlayersAttackingMe().isEmpty()) { {
try { if (plugin.getPlayersAttackingMe() == null || !plugin.getPlayersAttackingMe().isEmpty())
for (PlayerContainer container : plugin.getPlayersAttackingMe()) { {
if (plugin.getPlayersAttackingMe() != null && plugin.getPlayersAttackingMe().size() > 0) { try
//no reason to show you what prayers to pray in your prayer tab if multiple people are attacking you {
if ((plugin.getPlayersAttackingMe().size() == 1) && (config.drawTargetPrayAgainstPrayerTab())) { if (plugin.getPlayersAttackingMe() != null)
renderPrayerToClick(graphics, container.getPlayer()); {
for (PlayerContainer container : plugin.getPlayersAttackingMe())
{
if (plugin.getPlayersAttackingMe() != null && plugin.getPlayersAttackingMe().size() > 0)
{
// no reason to show you what prayers to pray in your prayer tab if multiple people are attacking you
if ((plugin.getPlayersAttackingMe().size() == 1) && (config.drawTargetPrayAgainstPrayerTab()))
{
renderPrayerToClick(graphics, container.getPlayer());
}
} }
} }
} }
} catch (ConcurrentModificationException e) { }
catch (ConcurrentModificationException ignored)
{
} }
} }
return null; return null;
} }
private void renderPrayerToClick(Graphics2D graphics, Player player) { private void renderPrayerToClick(Graphics2D graphics, Player player)
{
Widget PROTECT_FROM_MAGIC = client.getWidget(WidgetInfo.PRAYER_PROTECT_FROM_MAGIC); Widget PROTECT_FROM_MAGIC = client.getWidget(WidgetInfo.PRAYER_PROTECT_FROM_MAGIC);
Widget PROTECT_FROM_RANGED = client.getWidget(WidgetInfo.PRAYER_PROTECT_FROM_MISSILES); Widget PROTECT_FROM_RANGED = client.getWidget(WidgetInfo.PRAYER_PROTECT_FROM_MISSILES);
Widget PROTECT_FROM_MELEE = client.getWidget(WidgetInfo.PRAYER_PROTECT_FROM_MELEE); Widget PROTECT_FROM_MELEE = client.getWidget(WidgetInfo.PRAYER_PROTECT_FROM_MELEE);
Color color = Color.RED; Color color = Color.RED;
if (PROTECT_FROM_MELEE.isHidden()) return; if (PROTECT_FROM_MELEE.isHidden())
switch (WeaponType.checkWeaponOnPlayer(client, player)) { {
return;
}
switch (WeaponType.checkWeaponOnPlayer(client, player))
{
case WEAPON_MAGIC: case WEAPON_MAGIC:
OverlayUtil.renderPolygon(graphics, rectangleToPolygon(PROTECT_FROM_MAGIC.getBounds()), color); OverlayUtil.renderPolygon(graphics, rectangleToPolygon(PROTECT_FROM_MAGIC.getBounds()), color);
break; break;
@@ -92,9 +117,11 @@ class PrayAgainstPlayerOverlayPrayerTab extends Overlay {
} }
} }
private static Polygon rectangleToPolygon(Rectangle rect) { private static Polygon rectangleToPolygon(Rectangle rect)
{
int[] xpoints = {rect.x, rect.x + rect.width, rect.x + rect.width, rect.x}; int[] xpoints = {rect.x, rect.x + rect.width, rect.x + rect.width, rect.x};
int[] ypoints = {rect.y, rect.y, rect.y + rect.height, rect.y + rect.height}; int[] ypoints = {rect.y, rect.y, rect.y + rect.height, rect.y + rect.height};
return new Polygon(xpoints, ypoints, 4); return new Polygon(xpoints, ypoints, 4);
} }

View File

@@ -25,8 +25,27 @@
package net.runelite.client.plugins.prayagainstplayer; package net.runelite.client.plugins.prayagainstplayer;
import com.google.inject.Provides; import com.google.inject.Provides;
import net.runelite.api.*; import java.awt.Color;
import net.runelite.api.events.*; import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.DataBufferByte;
import java.awt.image.IndexColorModel;
import java.awt.image.WritableRaster;
import java.util.ArrayList;
import java.util.Arrays;
import javax.inject.Inject;
import net.runelite.api.AnimationID;
import net.runelite.api.Client;
import net.runelite.api.GameState;
import net.runelite.api.IndexedSprite;
import net.runelite.api.Player;
import net.runelite.api.SpriteID;
import net.runelite.api.events.AnimationChanged;
import net.runelite.api.events.GameStateChanged;
import net.runelite.api.events.InteractingChanged;
import net.runelite.api.events.PlayerDespawned;
import net.runelite.api.events.PlayerSpawned;
import net.runelite.client.config.ConfigManager; import net.runelite.client.config.ConfigManager;
import net.runelite.client.eventbus.Subscribe; import net.runelite.client.eventbus.Subscribe;
import net.runelite.client.game.SpriteManager; import net.runelite.client.game.SpriteManager;
@@ -36,33 +55,29 @@ import net.runelite.client.plugins.PluginType;
import net.runelite.client.ui.overlay.OverlayManager; import net.runelite.client.ui.overlay.OverlayManager;
import net.runelite.client.util.ImageUtil; import net.runelite.client.util.ImageUtil;
import javax.inject.Inject;
import java.awt.*;
import java.awt.image.*;
import java.util.ArrayList;
import java.util.Arrays;
@PluginDescriptor( @PluginDescriptor(
name = "Pray Against Player", name = "Pray Against Player",
description = "Use plugin in PvP situations for best results!!", description = "Use plugin in PvP situations for best results!!",
tags = {"highlight", "pvp", "overlay", "players"}, tags = {"highlight", "pvp", "overlay", "players"},
type = PluginType.PVP type = PluginType.PVP,
enabledByDefault = false
) )
/** /**
* I am fully aware that there is plenty of overhead and is a MESS! * I am fully aware that there is plenty of overhead and is a MESS!
* If you'd like to contribute please do! * If you'd like to contribute please do!
*/ */
public class PrayAgainstPlayerPlugin extends Plugin { public class PrayAgainstPlayerPlugin extends Plugin
{
private static final int[] PROTECTION_ICONS = { private static final int[] PROTECTION_ICONS = {
SpriteID.PRAYER_PROTECT_FROM_MISSILES, SpriteID.PRAYER_PROTECT_FROM_MISSILES,
SpriteID.PRAYER_PROTECT_FROM_MELEE, SpriteID.PRAYER_PROTECT_FROM_MELEE,
SpriteID.PRAYER_PROTECT_FROM_MAGIC SpriteID.PRAYER_PROTECT_FROM_MAGIC
}; };
private static final Dimension PROTECTION_ICON_DIMENSION = new Dimension(33, 33); private static final Dimension PROTECTION_ICON_DIMENSION = new Dimension(33, 33);
private static final Color PROTECTION_ICON_OUTLINE_COLOR = new Color(33, 33, 33); private static final Color PROTECTION_ICON_OUTLINE_COLOR = new Color(33, 33, 33);
public final BufferedImage[] ProtectionIcons = new BufferedImage[PROTECTION_ICONS.length]; private final BufferedImage[] ProtectionIcons = new BufferedImage[PROTECTION_ICONS.length];
private ArrayList<PlayerContainer> potentialPlayersAttackingMe; private ArrayList<PlayerContainer> potentialPlayersAttackingMe;
private ArrayList<PlayerContainer> playersAttackingMe; private ArrayList<PlayerContainer> playersAttackingMe;
@@ -86,19 +101,23 @@ public class PrayAgainstPlayerPlugin extends Plugin {
private PrayAgainstPlayerConfig config; private PrayAgainstPlayerConfig config;
@Provides @Provides
PrayAgainstPlayerConfig provideConfig(ConfigManager configManager) { PrayAgainstPlayerConfig provideConfig(ConfigManager configManager)
{
return configManager.getConfig(PrayAgainstPlayerConfig.class); return configManager.getConfig(PrayAgainstPlayerConfig.class);
} }
@Subscribe @Subscribe
public void onGameStateChanged(GameStateChanged gameStateChanged) { public void onGameStateChanged(GameStateChanged gameStateChanged)
if (gameStateChanged.getGameState() == GameState.LOGGED_IN) { {
if (gameStateChanged.getGameState() == GameState.LOGGED_IN)
{
loadProtectionIcons(); loadProtectionIcons();
} }
} }
@Override @Override
protected void startUp() { protected void startUp()
{
potentialPlayersAttackingMe = new ArrayList<>(); potentialPlayersAttackingMe = new ArrayList<>();
playersAttackingMe = new ArrayList<>(); playersAttackingMe = new ArrayList<>();
overlayManager.add(overlay); overlayManager.add(overlay);
@@ -106,31 +125,44 @@ public class PrayAgainstPlayerPlugin extends Plugin {
} }
@Override @Override
protected void shutDown() throws Exception { protected void shutDown() throws Exception
{
overlayManager.remove(overlay); overlayManager.remove(overlay);
overlayManager.remove(overlayPrayerTab); overlayManager.remove(overlayPrayerTab);
} }
@Subscribe @Subscribe
protected void onAnimationChanged(AnimationChanged animationChanged) { protected void onAnimationChanged(AnimationChanged animationChanged)
if ((animationChanged.getActor() instanceof Player) && (animationChanged.getActor().getInteracting() instanceof Player) && (animationChanged.getActor().getInteracting() == client.getLocalPlayer())) { {
if ((animationChanged.getActor() instanceof Player) && (animationChanged.getActor().getInteracting() instanceof Player) && (animationChanged.getActor().getInteracting() == client.getLocalPlayer()))
{
Player sourcePlayer = (Player) animationChanged.getActor(); Player sourcePlayer = (Player) animationChanged.getActor();
//is the client is a friend/clan and the config is set to ignore friends/clan dont add them to list // is the client is a friend/clan and the config is set to ignore friends/clan dont add them to list
if (client.isFriended(sourcePlayer.getName(), true) && config.ignoreFriends()) return; if (client.isFriended(sourcePlayer.getName(), true) && config.ignoreFriends())
if (client.isClanMember(sourcePlayer.getName()) && config.ignoreClanMates()) return; {
return;
}
if (client.isClanMember(sourcePlayer.getName()) && config.ignoreClanMates())
{
return;
}
if ((sourcePlayer.getAnimation() != -1) && (!isBlockAnimation(sourcePlayer.getAnimation()))) { if ((sourcePlayer.getAnimation() != -1) && (!isBlockAnimation(sourcePlayer.getAnimation())))
//if attacker attacks again, reset his timer so overlay doesn't go away {
if (findPlayerInAttackerList(sourcePlayer) != null) { // if attacker attacks again, reset his timer so overlay doesn't go away
if (findPlayerInAttackerList(sourcePlayer) != null)
{
resetPlayerFromAttackerContainerTimer(findPlayerInAttackerList(sourcePlayer)); resetPlayerFromAttackerContainerTimer(findPlayerInAttackerList(sourcePlayer));
} }
//if he attacks and he was in the potential attackers list, remove him // if he attacks and he was in the potential attackers list, remove him
if (!potentialPlayersAttackingMe.isEmpty() && potentialPlayersAttackingMe.contains(findPlayerInPotentialList(sourcePlayer))) { if (!potentialPlayersAttackingMe.isEmpty() && potentialPlayersAttackingMe.contains(findPlayerInPotentialList(sourcePlayer)))
{
removePlayerFromPotentialContainer(findPlayerInPotentialList(sourcePlayer)); removePlayerFromPotentialContainer(findPlayerInPotentialList(sourcePlayer));
} }
//if he's not in the attackers list, add him // if he's not in the attackers list, add him
if (findPlayerInAttackerList(sourcePlayer) == null) { if (findPlayerInAttackerList(sourcePlayer) == null)
{
PlayerContainer container = new PlayerContainer(sourcePlayer, System.currentTimeMillis(), (config.attackerTargetTimeout() * 1000)); PlayerContainer container = new PlayerContainer(sourcePlayer, System.currentTimeMillis(), (config.attackerTargetTimeout() * 1000));
playersAttackingMe.add(container); playersAttackingMe.add(container);
} }
@@ -139,16 +171,25 @@ public class PrayAgainstPlayerPlugin extends Plugin {
} }
@Subscribe @Subscribe
protected void onInteractingChanged(InteractingChanged interactingChanged) { protected void onInteractingChanged(InteractingChanged interactingChanged)
//if someone interacts with you, add them to the potential attackers list {
if ((interactingChanged.getSource() instanceof Player) && (interactingChanged.getTarget() instanceof Player)) { // if someone interacts with you, add them to the potential attackers list
if ((interactingChanged.getSource() instanceof Player) && (interactingChanged.getTarget() instanceof Player))
{
Player sourcePlayer = (Player) interactingChanged.getSource(); Player sourcePlayer = (Player) interactingChanged.getSource();
Player targetPlayer = (Player) interactingChanged.getTarget(); Player targetPlayer = (Player) interactingChanged.getTarget();
if ((targetPlayer == client.getLocalPlayer()) && (findPlayerInPotentialList(sourcePlayer) == null)) { //we're being interacted with if ((targetPlayer == client.getLocalPlayer()) && (findPlayerInPotentialList(sourcePlayer) == null))
{ //we're being interacted with
//is the client is a friend/clan and the config is set to ignore friends/clan dont add them to list // is the client is a friend/clan and the config is set to ignore friends/clan dont add them to list
if (client.isFriended(sourcePlayer.getName(), true) && config.ignoreFriends()) return; if (client.isFriended(sourcePlayer.getName(), true) && config.ignoreFriends())
if (client.isClanMember(sourcePlayer.getName()) && config.ignoreClanMates()) return; {
return;
}
if (client.isClanMember(sourcePlayer.getName()) && config.ignoreClanMates())
{
return;
}
PlayerContainer container = new PlayerContainer(sourcePlayer, System.currentTimeMillis(), (config.potentialTargetTimeout() * 1000)); PlayerContainer container = new PlayerContainer(sourcePlayer, System.currentTimeMillis(), (config.potentialTargetTimeout() * 1000));
potentialPlayersAttackingMe.add(container); potentialPlayersAttackingMe.add(container);
@@ -157,53 +198,71 @@ public class PrayAgainstPlayerPlugin extends Plugin {
} }
@Subscribe @Subscribe
protected void onPlayerDespawned(PlayerDespawned playerDespawned) { protected void onPlayerDespawned(PlayerDespawned playerDespawned)
{
PlayerContainer container = findPlayerInAttackerList(playerDespawned.getPlayer()); PlayerContainer container = findPlayerInAttackerList(playerDespawned.getPlayer());
PlayerContainer container2 = findPlayerInPotentialList(playerDespawned.getPlayer()); PlayerContainer container2 = findPlayerInPotentialList(playerDespawned.getPlayer());
if (container != null) { if (container != null)
{
playersAttackingMe.remove(container); playersAttackingMe.remove(container);
} }
if (container2 != null) { if (container2 != null)
{
potentialPlayersAttackingMe.remove(container2); potentialPlayersAttackingMe.remove(container2);
} }
} }
@Subscribe @Subscribe
protected void onPlayerSpawned(PlayerSpawned playerSpawned) { protected void onPlayerSpawned(PlayerSpawned playerSpawned)
if (config.markNewPlayer()) { {
if (config.markNewPlayer())
{
Player p = playerSpawned.getPlayer(); Player p = playerSpawned.getPlayer();
if (client.isFriended(p.getName(), true) && config.ignoreFriends()) return; if (client.isFriended(p.getName(), true) && config.ignoreFriends())
if (client.isClanMember(p.getName()) && config.ignoreClanMates()) return; {
return;
}
if (client.isClanMember(p.getName()) && config.ignoreClanMates())
{
return;
}
PlayerContainer container = findPlayerInPotentialList(p); PlayerContainer container = findPlayerInPotentialList(p);
if (container == null) { if (container == null)
{
container = new PlayerContainer(p, System.currentTimeMillis(), (config.newSpawnTimeout() * 1000)); container = new PlayerContainer(p, System.currentTimeMillis(), (config.newSpawnTimeout() * 1000));
potentialPlayersAttackingMe.add(container); potentialPlayersAttackingMe.add(container);
} }
} }
} }
PlayerContainer findPlayerInAttackerList(Player player) { private PlayerContainer findPlayerInAttackerList(Player player)
if (playersAttackingMe.isEmpty()) { {
if (playersAttackingMe.isEmpty())
{
return null; return null;
} }
for (int i = 0 ; i < playersAttackingMe.size() ; i++) { for (PlayerContainer container : playersAttackingMe)
PlayerContainer container = playersAttackingMe.get(i); {
if (container.getPlayer() == player) { if (container.getPlayer() == player)
{
return container; return container;
} }
} }
return null; return null;
} }
PlayerContainer findPlayerInPotentialList(Player player) { private PlayerContainer findPlayerInPotentialList(Player player)
if (potentialPlayersAttackingMe.isEmpty()) { {
if (potentialPlayersAttackingMe.isEmpty())
{
return null; return null;
} }
for (int i = 0 ; i < potentialPlayersAttackingMe.size() ; i++) { for (PlayerContainer container : potentialPlayersAttackingMe)
PlayerContainer container = potentialPlayersAttackingMe.get(i); {
if (container.getPlayer() == player) { if (container.getPlayer() == player)
{
return container; return container;
} }
} }
@@ -212,29 +271,36 @@ public class PrayAgainstPlayerPlugin extends Plugin {
/** /**
* Resets player timer in case he attacks again, so his highlight doesn't go away so easily * Resets player timer in case he attacks again, so his highlight doesn't go away so easily
*
* @param container * @param container
*/ */
public void resetPlayerFromAttackerContainerTimer(PlayerContainer container) { private void resetPlayerFromAttackerContainerTimer(PlayerContainer container)
{
removePlayerFromAttackerContainer(container); removePlayerFromAttackerContainer(container);
PlayerContainer newContainer = new PlayerContainer(container.getPlayer(), System.currentTimeMillis(), (config.attackerTargetTimeout() * 1000)); PlayerContainer newContainer = new PlayerContainer(container.getPlayer(), System.currentTimeMillis(), (config.attackerTargetTimeout() * 1000));
playersAttackingMe.add(newContainer); playersAttackingMe.add(newContainer);
} }
void removePlayerFromPotentialContainer(PlayerContainer container)
public void removePlayerFromPotentialContainer(PlayerContainer container) { {
if ((potentialPlayersAttackingMe != null) && (!potentialPlayersAttackingMe.isEmpty()) && (potentialPlayersAttackingMe.contains(container))) { if ((potentialPlayersAttackingMe != null) && (!potentialPlayersAttackingMe.isEmpty()))
{
potentialPlayersAttackingMe.remove(container); potentialPlayersAttackingMe.remove(container);
} }
} }
public void removePlayerFromAttackerContainer(PlayerContainer container) { void removePlayerFromAttackerContainer(PlayerContainer container)
if ((playersAttackingMe != null) && (!playersAttackingMe.isEmpty()) && (playersAttackingMe.contains(container))) { {
if ((playersAttackingMe != null) && (!playersAttackingMe.isEmpty()))
{
playersAttackingMe.remove(container); playersAttackingMe.remove(container);
} }
} }
private boolean isBlockAnimation(int anim) { private boolean isBlockAnimation(int anim)
switch (anim) { {
switch (anim)
{
case AnimationID.BLOCK_DEFENDER: case AnimationID.BLOCK_DEFENDER:
case AnimationID.BLOCK_NO_SHIELD: case AnimationID.BLOCK_NO_SHIELD:
case AnimationID.BLOCK_SHIELD: case AnimationID.BLOCK_SHIELD:
@@ -246,49 +312,34 @@ public class PrayAgainstPlayerPlugin extends Plugin {
} }
} }
public ArrayList<PlayerContainer> getPotentialPlayersAttackingMe() { return potentialPlayersAttackingMe; } ArrayList<PlayerContainer> getPotentialPlayersAttackingMe()
public ArrayList<PlayerContainer> getPlayersAttackingMe() { return playersAttackingMe; } {
return potentialPlayersAttackingMe;
}
ArrayList<PlayerContainer> getPlayersAttackingMe()
{
return playersAttackingMe;
}
//All of the methods below are from the Zulrah plugin!!! Credits to it's respective owner //All of the methods below are from the Zulrah plugin!!! Credits to it's respective owner
private void loadProtectionIcons() { private void loadProtectionIcons()
final IndexedSprite[] protectionIcons = {}; {
final IndexedSprite[] newProtectionIcons = Arrays.copyOf(protectionIcons, PROTECTION_ICONS.length);
int curPosition = 0; int curPosition = 0;
for (int i = 0; i < PROTECTION_ICONS.length; i++, curPosition++) for (int i = 0; i < PROTECTION_ICONS.length; i++, curPosition++)
{ {
final int resource = PROTECTION_ICONS[i]; final int resource = PROTECTION_ICONS[i];
ProtectionIcons[i] = rgbaToIndexedBufferedImage(ProtectionIconFromSprite(spriteManager.getSprite(resource, 0))); ProtectionIcons[i] = rgbaToIndexedBufferedImage(ProtectionIconFromSprite(spriteManager.getSprite(resource, 0)));
newProtectionIcons[curPosition] = createIndexedSprite(client, ProtectionIcons[i]);
} }
} }
private static IndexedSprite createIndexedSprite(final Client client, final BufferedImage bufferedImage) { private static BufferedImage rgbaToIndexedBufferedImage(final BufferedImage sourceBufferedImage)
final IndexColorModel indexedCM = (IndexColorModel) bufferedImage.getColorModel(); {
final int width = bufferedImage.getWidth();
final int height = bufferedImage.getHeight();
final byte[] pixels = ((DataBufferByte) bufferedImage.getRaster().getDataBuffer()).getData();
final int[] palette = new int[indexedCM.getMapSize()];
indexedCM.getRGBs(palette);
final IndexedSprite newIndexedSprite = client.createIndexedSprite();
newIndexedSprite.setPixels(pixels);
newIndexedSprite.setPalette(palette);
newIndexedSprite.setWidth(width);
newIndexedSprite.setHeight(height);
newIndexedSprite.setOriginalWidth(width);
newIndexedSprite.setOriginalHeight(height);
newIndexedSprite.setOffsetX(0);
newIndexedSprite.setOffsetY(0);
return newIndexedSprite;
}
private static BufferedImage rgbaToIndexedBufferedImage(final BufferedImage sourceBufferedImage) {
final BufferedImage indexedImage = new BufferedImage( final BufferedImage indexedImage = new BufferedImage(
sourceBufferedImage.getWidth(), sourceBufferedImage.getWidth(),
sourceBufferedImage.getHeight(), sourceBufferedImage.getHeight(),
BufferedImage.TYPE_BYTE_INDEXED); BufferedImage.TYPE_BYTE_INDEXED);
final ColorModel cm = indexedImage.getColorModel(); final ColorModel cm = indexedImage.getColorModel();
final IndexColorModel icm = (IndexColorModel) cm; final IndexColorModel icm = (IndexColorModel) cm;
@@ -309,13 +360,16 @@ public class PrayAgainstPlayerPlugin extends Plugin {
return resultIndexedImage; return resultIndexedImage;
} }
private static BufferedImage ProtectionIconFromSprite(final BufferedImage freezeSprite) { private static BufferedImage ProtectionIconFromSprite(final BufferedImage freezeSprite)
{
final BufferedImage freezeCanvas = ImageUtil.resizeCanvas(freezeSprite, PROTECTION_ICON_DIMENSION.width, PROTECTION_ICON_DIMENSION.height); final BufferedImage freezeCanvas = ImageUtil.resizeCanvas(freezeSprite, PROTECTION_ICON_DIMENSION.width, PROTECTION_ICON_DIMENSION.height);
return ImageUtil.outlineImage(freezeCanvas, PROTECTION_ICON_OUTLINE_COLOR); return ImageUtil.outlineImage(freezeCanvas, PROTECTION_ICON_OUTLINE_COLOR);
} }
BufferedImage getProtectionIcon(WeaponType weaponType) { BufferedImage getProtectionIcon(WeaponType weaponType)
switch (weaponType) { {
switch (weaponType)
{
case WEAPON_RANGED: case WEAPON_RANGED:
return ProtectionIcons[0]; return ProtectionIcons[0];
case WEAPON_MELEE: case WEAPON_MELEE:

View File

@@ -23,24 +23,25 @@ import net.runelite.client.config.ConfigItem;
@ConfigGroup("prayeralert") @ConfigGroup("prayeralert")
public interface PrayerAlertConfig extends Config public interface PrayerAlertConfig extends Config
{ {
@ConfigItem( @ConfigItem(
position = 1, position = 1,
keyName = "alwaysShowAlert", keyName = "alwaysShowAlert",
name = "Always show prayer alert", name = "Always show prayer alert",
description = "Show the alert, even without prayer restore in inventory" description = "Show the alert, even without prayer restore in inventory"
) )
default boolean alwaysShowAlert() default boolean alwaysShowAlert()
{ {
return false; return false;
} }
@ConfigItem(
position = 2, @ConfigItem(
keyName = "oldRenderMode", position = 2,
name = "Render using old method", keyName = "oldRenderMode",
description = "Render the prayer alert using the old method" name = "Render using old method",
) description = "Render the prayer alert using the old method"
default boolean oldRenderMode() )
{ default boolean oldRenderMode()
return false; {
} return false;
}
} }

View File

@@ -16,10 +16,16 @@
package net.runelite.client.plugins.prayeralert; package net.runelite.client.plugins.prayeralert;
import java.awt.*; import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics2D;
import javax.inject.Inject; import javax.inject.Inject;
import net.runelite.api.Client;
import net.runelite.api.*; import net.runelite.api.InventoryID;
import net.runelite.api.Item;
import net.runelite.api.ItemContainer;
import net.runelite.api.ItemID;
import net.runelite.client.game.ItemManager; import net.runelite.client.game.ItemManager;
import net.runelite.client.plugins.itemstats.stats.Stat; import net.runelite.client.plugins.itemstats.stats.Stat;
import net.runelite.client.plugins.itemstats.stats.Stats; import net.runelite.client.plugins.itemstats.stats.Stats;
@@ -33,157 +39,169 @@ import net.runelite.client.ui.overlay.components.TitleComponent;
class PrayerAlertOverlay extends Overlay class PrayerAlertOverlay extends Overlay
{ {
private final Client client; private final Client client;
private final PrayerAlertConfig config; private final PrayerAlertConfig config;
private final PanelComponent panelComponent = new PanelComponent(); private final PanelComponent panelComponent = new PanelComponent();
private final ItemManager itemManager; private final ItemManager itemManager;
private final Stat prayer = Stats.PRAYER; private final Stat prayer = Stats.PRAYER;
@Inject @Inject
private PrayerAlertOverlay(Client client, PrayerAlertConfig config, ItemManager itemManager) private PrayerAlertOverlay(Client client, PrayerAlertConfig config, ItemManager itemManager)
{ {
setPosition(OverlayPosition.TOP_RIGHT); setPosition(OverlayPosition.TOP_RIGHT);
setLayer(OverlayLayer.ABOVE_WIDGETS); setLayer(OverlayLayer.ABOVE_WIDGETS);
this.client = client; this.client = client;
this.config = config; this.config = config;
this.itemManager = itemManager; this.itemManager = itemManager;
} }
@Override @Override
public Dimension render(Graphics2D graphics) public Dimension render(Graphics2D graphics)
{ {
panelComponent.getChildren().clear(); panelComponent.getChildren().clear();
int prayerLevel = getPrayerLevel(); int prayerLevel = getPrayerLevel();
int prayerPoints = getPrayerPoints(); int prayerPoints = getPrayerPoints();
if (config.oldRenderMode()){ if (config.oldRenderMode())
if (config.alwaysShowAlert()){ {
boolean drink = drinkPrayerPotion(prayerLevel, prayerPoints); if (config.alwaysShowAlert())
if (drink) { {
oldPrayerRestorePanel(graphics); boolean drink = drinkPrayerPotion(prayerLevel, prayerPoints);
} if (drink)
} {
else { oldPrayerRestorePanel(graphics);
boolean drink = drinkPrayerPotion(prayerLevel, prayerPoints); }
boolean hasPrayerPotion = checkInventoryForPotion(); }
if (drink && hasPrayerPotion) { else
oldPrayerRestorePanel(graphics); {
} boolean drink = drinkPrayerPotion(prayerLevel, prayerPoints);
} boolean hasPrayerPotion = checkInventoryForPotion();
} if (drink && hasPrayerPotion)
else{ {
if (config.alwaysShowAlert()){ oldPrayerRestorePanel(graphics);
boolean drink = drinkPrayerPotion(prayerLevel, prayerPoints); }
if (drink) { }
prayerRestorePanel(panelComponent, graphics); }
} else
} {
else { if (config.alwaysShowAlert())
boolean drink = drinkPrayerPotion(prayerLevel, prayerPoints); {
boolean hasPrayerPotion = checkInventoryForPotion(); boolean drink = drinkPrayerPotion(prayerLevel, prayerPoints);
if (drink && hasPrayerPotion) { if (drink)
prayerRestorePanel(panelComponent, graphics); {
} prayerRestorePanel(panelComponent, graphics);
} }
} }
return panelComponent.render(graphics); else
} {
boolean drink = drinkPrayerPotion(prayerLevel, prayerPoints);
boolean hasPrayerPotion = checkInventoryForPotion();
if (drink && hasPrayerPotion)
{
prayerRestorePanel(panelComponent, graphics);
}
}
}
return panelComponent.render(graphics);
}
private int getPrayerLevel() private int getPrayerLevel()
{ {
return prayer.getMaximum(client); return prayer.getMaximum(client);
} }
private int getPrayerPoints() private int getPrayerPoints()
{ {
return prayer.getValue(client); return prayer.getValue(client);
} }
private boolean drinkPrayerPotion(int prayerLevel, int prayerPoints) private boolean drinkPrayerPotion(int prayerLevel, int prayerPoints)
{ {
boolean drink = false; boolean drink = false;
int prayerPotionRestoreValue = 7; int prayerPotionRestoreValue = 7;
double quarterOfPrayerLevel = (0.25) * (double) prayerLevel; double quarterOfPrayerLevel = (0.25) * (double) prayerLevel;
prayerPotionRestoreValue = prayerPotionRestoreValue + (int) quarterOfPrayerLevel; prayerPotionRestoreValue = prayerPotionRestoreValue + (int) quarterOfPrayerLevel;
if (prayerPoints < (prayerLevel - prayerPotionRestoreValue)) if (prayerPoints < (prayerLevel - prayerPotionRestoreValue))
{ {
drink = true; drink = true;
} }
return drink; return drink;
} }
private boolean checkInventoryForPotion() private boolean checkInventoryForPotion()
{ {
ItemContainer inventory = client.getItemContainer(InventoryID.INVENTORY); ItemContainer inventory = client.getItemContainer(InventoryID.INVENTORY);
Item[] inventoryItems; Item[] inventoryItems;
boolean hasPrayerPotion = false; boolean hasPrayerPotion = false;
int[] potionID = {ItemID.PRAYER_POTION1, ItemID.PRAYER_POTION2, ItemID.PRAYER_POTION3, ItemID.PRAYER_POTION4, ItemID.PRAYER_POTION1_20396, ItemID.PRAYER_POTION2_20395, int[] potionID = {ItemID.PRAYER_POTION1, ItemID.PRAYER_POTION2, ItemID.PRAYER_POTION3, ItemID.PRAYER_POTION4, ItemID.PRAYER_POTION1_20396, ItemID.PRAYER_POTION2_20395,
ItemID.PRAYER_POTION3_20394, ItemID.PRAYER_POTION4_20393, ItemID.PRAYER_MIX1, ItemID.PRAYER_MIX2, ItemID.SUPER_RESTORE1, ItemID.SUPER_RESTORE2, ItemID.PRAYER_POTION3_20394, ItemID.PRAYER_POTION4_20393, ItemID.PRAYER_MIX1, ItemID.PRAYER_MIX2, ItemID.SUPER_RESTORE1, ItemID.SUPER_RESTORE2,
ItemID.SUPER_RESTORE3, ItemID.SUPER_RESTORE4, ItemID.SUPER_RESTORE_MIX1, ItemID.SUPER_RESTORE_MIX2}; ItemID.SUPER_RESTORE3, ItemID.SUPER_RESTORE4, ItemID.SUPER_RESTORE_MIX1, ItemID.SUPER_RESTORE_MIX2};
if (inventory != null) if (inventory != null)
{ {
inventoryItems = inventory.getItems(); inventoryItems = inventory.getItems();
for (Item item : inventoryItems) for (Item item : inventoryItems)
{ {
for (int prayerPotionId : potionID) for (int prayerPotionId : potionID)
{ {
if (item.getId() == prayerPotionId) if (item.getId() == prayerPotionId)
{ {
hasPrayerPotion = true; hasPrayerPotion = true;
} }
} }
} }
} }
return hasPrayerPotion; return hasPrayerPotion;
} }
private void prayerRestorePanel(PanelComponent panelComponent, Graphics2D graphics){ private void prayerRestorePanel(PanelComponent panelComponent, Graphics2D graphics)
panelComponent.getChildren().add(new ImageComponent(itemManager.getImage(ItemID.PRAYER_POTION4))); {
panelComponent.getChildren().add(TitleComponent.builder() panelComponent.getChildren().add(new ImageComponent(itemManager.getImage(ItemID.PRAYER_POTION4)));
.text("Drink") panelComponent.getChildren().add(TitleComponent.builder()
.color(Color.RED) .text("Drink")
.build()); .color(Color.RED)
panelComponent.setPreferredSize(new Dimension( .build());
graphics.getFontMetrics().stringWidth("Drink") + 12,0)); panelComponent.setPreferredSize(new Dimension(
} graphics.getFontMetrics().stringWidth("Drink") + 12, 0));
}
private void oldPrayerRestorePanel(Graphics2D graphics){ private void oldPrayerRestorePanel(Graphics2D graphics)
graphics.translate(-100, 15); {
graphics.setColor(new Color(0.2f, 0.2f, 0.2f, 0.5f)); graphics.translate(-100, 15);
graphics.fillRect(0, 0, 100, 45); graphics.setColor(new Color(0.2f, 0.2f, 0.2f, 0.5f));
graphics.fillRect(0, 0, 100, 45);
graphics.drawImage(itemManager.getImage(ItemID.PRAYER_POTION4), null, 14, 7); graphics.drawImage(itemManager.getImage(ItemID.PRAYER_POTION4), null, 14, 7);
Font dropShadow1 = FontManager.getRunescapeFont(); Font dropShadow1 = FontManager.getRunescapeFont();
dropShadow1 = dropShadow1.deriveFont(Font.PLAIN); dropShadow1 = dropShadow1.deriveFont(Font.PLAIN);
graphics.setFont(dropShadow1); graphics.setFont(dropShadow1);
graphics.setColor(new Color(0f, 0f, 0f, 0.6f)); graphics.setColor(new Color(0f, 0f, 0f, 0.6f));
graphics.drawString("Drink", 56, 20); graphics.drawString("Drink", 56, 20);
Font drinkFont1 = FontManager.getRunescapeFont(); Font drinkFont1 = FontManager.getRunescapeFont();
drinkFont1 = drinkFont1.deriveFont(Font.PLAIN); drinkFont1 = drinkFont1.deriveFont(Font.PLAIN);
graphics.setFont(drinkFont1); graphics.setFont(drinkFont1);
graphics.setColor(new Color(1.0f, 0.03529412f, 0.0f)); graphics.setColor(new Color(1.0f, 0.03529412f, 0.0f));
graphics.translate(-0.8, -0.8); graphics.translate(-0.8, -0.8);
graphics.drawString("Drink", 56, 20); graphics.drawString("Drink", 56, 20);
Font dropShadow2 = FontManager.getRunescapeFont(); Font dropShadow2 = FontManager.getRunescapeFont();
dropShadow2 = dropShadow2.deriveFont(Font.PLAIN); dropShadow2 = dropShadow2.deriveFont(Font.PLAIN);
graphics.setFont(dropShadow2); graphics.setFont(dropShadow2);
graphics.setColor(new Color(0f, 0f, 0f, 0.6f)); graphics.setColor(new Color(0f, 0f, 0f, 0.6f));
graphics.drawString("Potion", 53, 40); graphics.drawString("Potion", 53, 40);
Font drinkFont2 = FontManager.getRunescapeFont(); Font drinkFont2 = FontManager.getRunescapeFont();
drinkFont2 = drinkFont2.deriveFont(Font.PLAIN); drinkFont2 = drinkFont2.deriveFont(Font.PLAIN);
graphics.setFont(drinkFont2); graphics.setFont(drinkFont2);
graphics.setColor(new Color(1.0f, 0.03529412f, 0.0f)); graphics.setColor(new Color(1.0f, 0.03529412f, 0.0f));
graphics.translate(-0.8, -0.8); graphics.translate(-0.8, -0.8);
graphics.drawString("Potion", 53, 40); graphics.drawString("Potion", 53, 40);
} }
} }

View File

@@ -18,45 +18,42 @@ package net.runelite.client.plugins.prayeralert;
import com.google.inject.Provides; import com.google.inject.Provides;
import javax.inject.Inject; import javax.inject.Inject;
import net.runelite.client.config.ConfigManager;
import net.runelite.client.plugins.Plugin; import net.runelite.client.plugins.Plugin;
import net.runelite.client.plugins.PluginDescriptor; import net.runelite.client.plugins.PluginDescriptor;
import net.runelite.client.config.ConfigManager;
import net.runelite.client.plugins.PluginType; import net.runelite.client.plugins.PluginType;
import net.runelite.client.ui.overlay.OverlayManager; import net.runelite.client.ui.overlay.OverlayManager;
@PluginDescriptor( @PluginDescriptor(
name = "Prayer Alerter", name = "Prayer Alerter",
description = "Alert the player when prayer is low", description = "Alert the player when prayer is low",
tags = {"prayer", "overlay"}, tags = {"prayer", "overlay"},
type = PluginType.UTILITY, type = PluginType.UTILITY,
enabledByDefault = false enabledByDefault = false
) )
public class PrayerAlertPlugin extends Plugin public class PrayerAlertPlugin extends Plugin
{ {
@Inject @Inject
private OverlayManager overlayManager; private OverlayManager overlayManager;
@Inject @Inject
private PrayerAlertOverlay overlay; private PrayerAlertOverlay overlay;
@Inject @Provides
private PrayerAlertConfig config; PrayerAlertConfig provideConfig(ConfigManager configManager)
{
return configManager.getConfig(PrayerAlertConfig.class);
}
@Provides @Override
PrayerAlertConfig provideConfig(ConfigManager configManager) protected void startUp() throws Exception
{ {
return configManager.getConfig(PrayerAlertConfig.class); overlayManager.add(overlay);
} }
@Override @Override
protected void startUp() throws Exception protected void shutDown() throws Exception
{ {
overlayManager.add(overlay); overlayManager.remove(overlay);
} }
@Override
protected void shutDown() throws Exception
{
overlayManager.remove(overlay);
}
} }

View File

@@ -59,12 +59,10 @@ class ProfilePanel extends JPanel
} }
private final String loginText; private final String loginText;
private final ProfilesPanel parent;
private String password = null; private String password = null;
ProfilePanel(final Client client, String data, ProfilesConfig config, ProfilesPanel parent) ProfilePanel(final Client client, String data, ProfilesConfig config, ProfilesPanel parent)
{ {
this.parent = parent;
String[] parts = data.split(":"); String[] parts = data.split(":");
this.loginText = parts[1]; this.loginText = parts[1];
if (parts.length == 3) if (parts.length == 3)

View File

@@ -31,8 +31,6 @@ import net.runelite.client.config.ConfigItem;
@ConfigGroup("profiles") @ConfigGroup("profiles")
public interface ProfilesConfig extends Config public interface ProfilesConfig extends Config
{ {
@ConfigItem( @ConfigItem(
keyName = "profilesData", keyName = "profilesData",
name = "", name = "",
@@ -52,10 +50,10 @@ public interface ProfilesConfig extends Config
void profilesData(String str); void profilesData(String str);
@ConfigItem( @ConfigItem(
keyName = "salt", keyName = "salt",
name = "", name = "",
description = "", description = "",
hidden = true hidden = true
) )
default String salt() default String salt()
{ {
@@ -63,9 +61,9 @@ public interface ProfilesConfig extends Config
} }
@ConfigItem( @ConfigItem(
keyName = "salt", keyName = "salt",
name = "", name = "",
description = "" description = ""
) )
void salt(String key); void salt(String key);

View File

@@ -51,9 +51,14 @@ import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec; import javax.crypto.spec.SecretKeySpec;
import javax.inject.Inject; import javax.inject.Inject;
import javax.swing.*; import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder; import javax.swing.border.EmptyBorder;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import net.runelite.api.Client; import net.runelite.api.Client;
import net.runelite.client.ui.ColorScheme; import net.runelite.client.ui.ColorScheme;
@@ -71,7 +76,7 @@ class ProfilesPanel extends PluginPanel
private static final String PASSWORD_LABEL = "Account Password"; private static final String PASSWORD_LABEL = "Account Password";
private static final String HELP = "To add and load accounts, first enter a password into the Encryption Password " + private static final String HELP = "To add and load accounts, first enter a password into the Encryption Password " +
"field then press Load Accounts. You can now add as many accounts as you would like. The next time you restart" + "field then press Load Accounts. You can now add as many accounts as you would like. The next time you restart" +
" Runelite, enter your encryption password and click load accounts to see the accounts you entered"; "Runelite, enter your encryption password and click load accounts to see the accounts you entered";
private static final Dimension PREFERRED_SIZE = new Dimension(PluginPanel.PANEL_WIDTH - 20, 30); private static final Dimension PREFERRED_SIZE = new Dimension(PluginPanel.PANEL_WIDTH - 20, 30);
private static final Dimension HELP_PREFERRED_SIZE = new Dimension(PluginPanel.PANEL_WIDTH - 20, 130); private static final Dimension HELP_PREFERRED_SIZE = new Dimension(PluginPanel.PANEL_WIDTH - 20, 130);
@@ -81,12 +86,10 @@ class ProfilesPanel extends PluginPanel
private static ProfilesConfig profilesConfig; private static ProfilesConfig profilesConfig;
private final JPasswordField txtDecryptPassword = new JPasswordField(UNLOCK_PASSWORD); private final JPasswordField txtDecryptPassword = new JPasswordField(UNLOCK_PASSWORD);
private final JButton btnLoadAccounts = new JButton(LOAD_ACCOUNTS);
private final JTextField txtAccountLabel = new JTextField(ACCOUNT_LABEL); private final JTextField txtAccountLabel = new JTextField(ACCOUNT_LABEL);
private final JPasswordField txtAccountLogin = new JPasswordField(ACCOUNT_USERNAME); private final JPasswordField txtAccountLogin = new JPasswordField(ACCOUNT_USERNAME);
private final JPasswordField txtPasswordLogin = new JPasswordField(PASSWORD_LABEL); private final JPasswordField txtPasswordLogin = new JPasswordField(PASSWORD_LABEL);
private final JPanel profilesPanel = new JPanel(); private final JPanel profilesPanel = new JPanel();
private final JPanel helpPanel = new JPanel(new BorderLayout());
private GridBagConstraints c; private GridBagConstraints c;
@Inject @Inject
@@ -108,18 +111,18 @@ class ProfilesPanel extends PluginPanel
c.weighty = 0; c.weighty = 0;
c.insets = new Insets(0, 0, 4, 0); c.insets = new Insets(0, 0, 4, 0);
JPanel helpPanel = new JPanel(new BorderLayout());
helpPanel.setBackground(ColorScheme.DARKER_GRAY_COLOR); helpPanel.setBackground(ColorScheme.DARKER_GRAY_COLOR);
JLabel helpLabel = new JLabel("<html> <p>" + HELP + "</p></html>"); JLabel helpLabel = new JLabel("<html> <p>" + HELP + "</p></html>");
helpLabel.setFont(FontManager.getRunescapeSmallFont()); helpLabel.setFont(FontManager.getRunescapeSmallFont());
helpPanel.setPreferredSize(HELP_PREFERRED_SIZE); helpPanel.setPreferredSize(HELP_PREFERRED_SIZE);
//helpPanel.setSize(MINIMUM_SIZE); // helpPanel.setSize(MINIMUM_SIZE);
helpPanel.add(helpLabel, BorderLayout.NORTH); helpPanel.add(helpLabel, BorderLayout.NORTH);
add(helpPanel); add(helpPanel);
c.gridy = c.gridy + 3; c.gridy = c.gridy + 3;
c.gridy++; c.gridy++;
txtDecryptPassword.setEchoChar((char) 0); txtDecryptPassword.setEchoChar((char) 0);
txtDecryptPassword.setPreferredSize(PREFERRED_SIZE); txtDecryptPassword.setPreferredSize(PREFERRED_SIZE);
txtDecryptPassword.setForeground(ColorScheme.MEDIUM_GRAY_COLOR); txtDecryptPassword.setForeground(ColorScheme.MEDIUM_GRAY_COLOR);
@@ -154,6 +157,7 @@ class ProfilesPanel extends PluginPanel
add(txtDecryptPassword, c); add(txtDecryptPassword, c);
c.gridy++; c.gridy++;
JButton btnLoadAccounts = new JButton(LOAD_ACCOUNTS);
btnLoadAccounts.setPreferredSize(PREFERRED_SIZE); btnLoadAccounts.setPreferredSize(PREFERRED_SIZE);
btnLoadAccounts.setBackground(ColorScheme.DARKER_GRAY_COLOR); btnLoadAccounts.setBackground(ColorScheme.DARKER_GRAY_COLOR);
btnLoadAccounts.setMinimumSize(MINIMUM_SIZE); btnLoadAccounts.setMinimumSize(MINIMUM_SIZE);
@@ -333,7 +337,7 @@ class ProfilesPanel extends PluginPanel
try try
{ {
if(!addProfile(data)) if (!addProfile(data))
{ {
return; return;
} }
@@ -410,10 +414,10 @@ class ProfilesPanel extends PluginPanel
c.gridy = 0; c.gridy = 0;
c.insets = new Insets(0, 0, 5, 0); c.insets = new Insets(0, 0, 5, 0);
//addAccounts(config.profilesData()); // addAccounts(config.profilesData());
} }
void redrawProfiles() throws InvalidKeySpecException, NoSuchAlgorithmException private void redrawProfiles() throws InvalidKeySpecException, NoSuchAlgorithmException
{ {
profilesPanel.removeAll(); profilesPanel.removeAll();
c.gridy = 0; c.gridy = 0;
@@ -433,9 +437,9 @@ class ProfilesPanel extends PluginPanel
repaint(); repaint();
} }
void addAccounts(String data) private void addAccounts(String data)
{ {
//log.info("Data: " + data); // log.info("Data: " + data);
data = data.trim(); data = data.trim();
if (!data.contains(":")) if (!data.contains(":"))
{ {
@@ -444,38 +448,38 @@ class ProfilesPanel extends PluginPanel
Arrays.stream(data.split("\\n")).forEach(this::addAccount); Arrays.stream(data.split("\\n")).forEach(this::addAccount);
} }
boolean addProfile(String data) throws InvalidKeySpecException, NoSuchAlgorithmException private boolean addProfile(String data) throws InvalidKeySpecException, NoSuchAlgorithmException
{ {
return setProfileData( return setProfileData(
getProfileData() + data + "\n"); getProfileData() + data + "\n");
} }
void removeProfile(String data) throws InvalidKeySpecException, NoSuchAlgorithmException void removeProfile(String data) throws InvalidKeySpecException, NoSuchAlgorithmException
{ {
setProfileData( setProfileData(
getProfileData().replaceAll(data + "\\n", "")); getProfileData().replaceAll(data + "\\n", ""));
revalidate(); revalidate();
repaint(); repaint();
} }
void setSalt(byte[] bytes) private void setSalt(byte[] bytes)
{ {
profilesConfig.salt(base64Encode(bytes)); profilesConfig.salt(base64Encode(bytes));
} }
byte[] getSalt() private byte[] getSalt()
{ {
if(profilesConfig.salt().length() == 0) if (profilesConfig.salt().length() == 0)
{ {
return new byte[0]; return new byte[0];
} }
return base64Decode(profilesConfig.salt()); return base64Decode(profilesConfig.salt());
} }
SecretKey getAesKey() throws NoSuchAlgorithmException, InvalidKeySpecException private SecretKey getAesKey() throws NoSuchAlgorithmException, InvalidKeySpecException
{ {
if(getSalt().length == 0) if (getSalt().length == 0)
{ {
byte[] b = new byte[16]; byte[] b = new byte[16];
SecureRandom.getInstanceStrong().nextBytes(b); SecureRandom.getInstanceStrong().nextBytes(b);
@@ -483,16 +487,15 @@ class ProfilesPanel extends PluginPanel
} }
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec spec = new PBEKeySpec(txtDecryptPassword.getPassword(), getSalt(), iterations, 128); KeySpec spec = new PBEKeySpec(txtDecryptPassword.getPassword(), getSalt(), iterations, 128);
SecretKey key = factory.generateSecret(spec); return factory.generateSecret(spec);
return key;
} }
String getProfileData() throws InvalidKeySpecException, NoSuchAlgorithmException private String getProfileData() throws InvalidKeySpecException, NoSuchAlgorithmException
{ {
String tmp = profilesConfig.profilesData(); String tmp = profilesConfig.profilesData();
if(tmp.startsWith("¬")) if (tmp.startsWith("¬"))
{ {
if(txtDecryptPassword.getPassword().length == 0 || String.valueOf(txtDecryptPassword.getPassword()).equals(UNLOCK_PASSWORD)) if (txtDecryptPassword.getPassword().length == 0 || String.valueOf(txtDecryptPassword.getPassword()).equals(UNLOCK_PASSWORD))
{ {
showErrorMessage("Unable to load data", "Please enter a password!"); showErrorMessage("Unable to load data", "Please enter a password!");
return tmp; return tmp;
@@ -503,27 +506,29 @@ class ProfilesPanel extends PluginPanel
return tmp; return tmp;
} }
boolean setProfileData(String data) throws InvalidKeySpecException, NoSuchAlgorithmException private boolean setProfileData(String data) throws InvalidKeySpecException, NoSuchAlgorithmException
{ {
if(txtDecryptPassword.getPassword().length == 0 || String.valueOf(txtDecryptPassword.getPassword()).equals(UNLOCK_PASSWORD)) if (txtDecryptPassword.getPassword().length == 0 || String.valueOf(txtDecryptPassword.getPassword()).equals(UNLOCK_PASSWORD))
{ {
showErrorMessage("Unable to save data", "Please enter a password!"); showErrorMessage("Unable to save data", "Please enter a password!");
return false; return false;
} }
byte[] enc = encryptText(data, getAesKey()); byte[] enc = encryptText(data, getAesKey());
if(enc.length == 0) if (enc.length == 0)
{
return false; return false;
String s = "¬"+base64Encode(enc); }
String s = "¬" + base64Encode(enc);
profilesConfig.profilesData(s); profilesConfig.profilesData(s);
return true; return true;
} }
public byte[] base64Decode(String data) private byte[] base64Decode(String data)
{ {
return Base64.getDecoder().decode(data); return Base64.getDecoder().decode(data);
} }
public String base64Encode(byte[] data) private String base64Encode(byte[] data)
{ {
return Base64.getEncoder().encodeToString(data); return Base64.getEncoder().encodeToString(data);
} }
@@ -534,7 +539,7 @@ class ProfilesPanel extends PluginPanel
* @param text text to encrypt * @param text text to encrypt
* @return encrypted string * @return encrypted string
*/ */
public static byte[] encryptText(String text, SecretKey aesKey) private static byte[] encryptText(String text, SecretKey aesKey)
{ {
try try
{ {
@@ -550,7 +555,7 @@ class ProfilesPanel extends PluginPanel
return new byte[0]; return new byte[0];
} }
public static String decryptText(byte[] enc, SecretKey aesKey) private static String decryptText(byte[] enc, SecretKey aesKey)
{ {
try try
{ {
@@ -566,12 +571,12 @@ class ProfilesPanel extends PluginPanel
return ""; return "";
} }
public static void showErrorMessage(String title, String text) private static void showErrorMessage(String title, String text)
{ {
SwingUtilities.invokeLater(() -> JOptionPane.showMessageDialog(null, SwingUtilities.invokeLater(() -> JOptionPane.showMessageDialog(null,
text, text,
title, title,
JOptionPane.ERROR_MESSAGE)); JOptionPane.ERROR_MESSAGE));
} }
} }

View File

@@ -25,19 +25,9 @@
package net.runelite.client.plugins.profiles; package net.runelite.client.plugins.profiles;
import com.google.inject.Provides; import com.google.inject.Provides;
import java.security.InvalidKeyException; import java.awt.image.BufferedImage;
import java.security.Key; import javax.inject.Inject;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Logger;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import net.runelite.api.Client;
import net.runelite.api.GameState;
import net.runelite.api.events.ConfigChanged; import net.runelite.api.events.ConfigChanged;
import net.runelite.api.events.GameStateChanged;
import net.runelite.client.config.ConfigManager; import net.runelite.client.config.ConfigManager;
import net.runelite.client.eventbus.Subscribe; import net.runelite.client.eventbus.Subscribe;
import net.runelite.client.plugins.Plugin; import net.runelite.client.plugins.Plugin;
@@ -46,8 +36,6 @@ import net.runelite.client.plugins.PluginType;
import net.runelite.client.ui.ClientToolbar; import net.runelite.client.ui.ClientToolbar;
import net.runelite.client.ui.NavigationButton; import net.runelite.client.ui.NavigationButton;
import net.runelite.client.util.ImageUtil; import net.runelite.client.util.ImageUtil;
import javax.inject.Inject;
import java.awt.image.BufferedImage;
@PluginDescriptor( @PluginDescriptor(
name = "Account Switcher", name = "Account Switcher",
@@ -60,13 +48,6 @@ public class ProfilesPlugin extends Plugin
@Inject @Inject
private ClientToolbar clientToolbar; private ClientToolbar clientToolbar;
@Inject
private Client client;
@Inject
private ProfilesConfig config;
private ProfilesPanel panel; private ProfilesPanel panel;
private NavigationButton navButton; private NavigationButton navButton;
@@ -92,7 +73,6 @@ public class ProfilesPlugin extends Plugin
.build(); .build();
clientToolbar.addNavigation(navButton); clientToolbar.addNavigation(navButton);
} }
@Override @Override

View File

@@ -9,20 +9,26 @@
package net.runelite.client.plugins.pvptools; package net.runelite.client.plugins.pvptools;
import net.runelite.api.Client; import java.awt.BorderLayout;
import net.runelite.client.ui.FontManager; import java.awt.Font;
import java.awt.Toolkit;
import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionListener; import java.awt.event.ActionListener;
import java.util.List; import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import net.runelite.api.Client;
import net.runelite.client.ui.FontManager;
public class CurrentPlayersJFrame extends JFrame public class CurrentPlayersJFrame extends JFrame
{ {
public JList currentPlayersJList; public JList<Object> currentPlayersJList;
CurrentPlayersJFrame(Client client, PvpToolsPlugin pvpToolsPlugin, List<String> list) CurrentPlayersJFrame(Client client, PvpToolsPlugin pvpToolsPlugin, List<String> list)
{ {
@@ -35,7 +41,7 @@ public class CurrentPlayersJFrame extends JFrame
JButton refreshJButton = new JButton("Refresh"); JButton refreshJButton = new JButton("Refresh");
refreshJButton.addActionListener(pvpToolsPlugin.currentPlayersActionListener); refreshJButton.addActionListener(pvpToolsPlugin.currentPlayersActionListener);
JButton copyJButton = new JButton("Copy List"); JButton copyJButton = new JButton("Copy List");
currentPlayersJList = new JList(list.toArray()); currentPlayersJList = new JList<>(list.toArray());
ActionListener copyButtonActionListener = e -> ActionListener copyButtonActionListener = e ->
{ {
StringSelection stringSelection; StringSelection stringSelection;

View File

@@ -10,28 +10,25 @@
package net.runelite.client.plugins.pvptools; package net.runelite.client.plugins.pvptools;
import java.awt.BorderLayout; import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Font; import java.awt.Font;
import java.awt.Toolkit; import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionListener; import java.awt.event.ActionListener;
import java.util.List; import java.util.List;
import java.util.Vector;
import javax.swing.JButton; import javax.swing.JButton;
import javax.swing.JFrame; import javax.swing.JFrame;
import javax.swing.JLabel; import javax.swing.JLabel;
import javax.swing.JList; import javax.swing.JList;
import javax.swing.JPanel; import javax.swing.JPanel;
import javax.swing.JScrollPane; import javax.swing.JScrollPane;
import net.runelite.api.ClanMember;
import net.runelite.api.Client; import net.runelite.api.Client;
import net.runelite.client.ui.FontManager; import net.runelite.client.ui.FontManager;
public class MissingPlayersJFrame extends JFrame public class MissingPlayersJFrame extends JFrame
{ {
public JList missingPlayersJList; public JList<Object> missingPlayersJList;
MissingPlayersJFrame(Client client, PvpToolsPlugin pvpToolsPlugin, List<String> list) MissingPlayersJFrame(Client client, PvpToolsPlugin pvpToolsPlugin, List<String> list)
{ {
@@ -44,7 +41,7 @@ public class MissingPlayersJFrame extends JFrame
JButton refreshJButton = new JButton("Refresh"); JButton refreshJButton = new JButton("Refresh");
refreshJButton.addActionListener(pvpToolsPlugin.playersButtonActionListener); refreshJButton.addActionListener(pvpToolsPlugin.playersButtonActionListener);
JButton copyJButton = new JButton("Copy List"); JButton copyJButton = new JButton("Copy List");
missingPlayersJList = new JList(list.toArray()); missingPlayersJList = new JList<>(list.toArray());
ActionListener copyButtonActionListener = e -> ActionListener copyButtonActionListener = e ->
{ {
StringSelection stringSelection; StringSelection stringSelection;

View File

@@ -9,8 +9,6 @@
package net.runelite.client.plugins.pvptools; package net.runelite.client.plugins.pvptools;
import java.awt.Color;
import java.security.Key;
import net.runelite.client.config.Config; import net.runelite.client.config.Config;
import net.runelite.client.config.ConfigGroup; import net.runelite.client.config.ConfigGroup;
import net.runelite.client.config.ConfigItem; import net.runelite.client.config.ConfigItem;
@@ -33,8 +31,7 @@ public interface PvpToolsConfig extends Config
@ConfigItem( @ConfigItem(
keyName = "countOverHeads", keyName = "countOverHeads",
name = "Count Enemy Overheads", name = "Count Enemy Overheads",
description = "Counts the number of each protection prayer attackable targets not in your CC are currently" + description = "Counts the number of each protection prayer attackable targets not in your CC are currently using",
" using",
position = 4 position = 4
) )
default boolean countOverHeads() default boolean countOverHeads()
@@ -100,11 +97,11 @@ public interface PvpToolsConfig extends Config
} }
@ConfigItem( @ConfigItem(
keyName = "levelRangeAttackOptions", keyName = "levelRangeAttackOptions",
name = "Moves Other Attack Options", name = "Moves Other Attack Options",
description = "Moves the attack option for people that are outside your level range", description = "Moves the attack option for people that are outside your level range",
position = 10, position = 10,
group = "Right-Click Attack Options" group = "Right-Click Attack Options"
) )
default boolean levelRangeAttackOptions() default boolean levelRangeAttackOptions()
{ {
@@ -125,18 +122,19 @@ public interface PvpToolsConfig extends Config
@ConfigItem( @ConfigItem(
keyName = "missingPlayers", keyName = "missingPlayers",
name = "Missing CC Players", name = "Missing CC Players",
description = "Adds a button to the PvP Tools panel that opens a window showing which CC members are not at" + description = "Adds a button to the PvP Tools panel that opens a window showing which CC members are not at the current players location",
" the current players location",
position = 15 position = 15
) )
default boolean missingPlayersEnabled() { return true; } default boolean missingPlayersEnabled()
{
return true;
}
@ConfigItem( @ConfigItem(
keyName = "currentPlayers", keyName = "currentPlayers",
name = "Current CC Players", name = "Current CC Players",
description = "Adds a button to the PvP Tools panel that opens a window showing which CC members currently at" + description = "Adds a button to the PvP Tools panel that opens a window showing which CC members currently at the players location",
" the players location", position = 16
position = 16
) )
default boolean currentPlayersEnabled() default boolean currentPlayersEnabled()
{ {

View File

@@ -9,14 +9,13 @@
package net.runelite.client.plugins.pvptools; package net.runelite.client.plugins.pvptools;
import java.awt.*; import java.awt.BasicStroke;
import java.util.ArrayList; import java.awt.Color;
import java.util.Arrays; import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Polygon;
import javax.inject.Inject; import javax.inject.Inject;
import net.runelite.api.Actor;
import net.runelite.api.Client; import net.runelite.api.Client;
import net.runelite.api.Player;
import net.runelite.api.Point; import net.runelite.api.Point;
import net.runelite.client.ui.FontManager; import net.runelite.client.ui.FontManager;
import net.runelite.client.ui.overlay.Overlay; import net.runelite.client.ui.overlay.Overlay;
@@ -40,7 +39,7 @@ public class PvpToolsOverlay extends Overlay
setLayer(OverlayLayer.ABOVE_WIDGETS); setLayer(OverlayLayer.ABOVE_WIDGETS);
setPriority(OverlayPriority.HIGH); setPriority(OverlayPriority.HIGH);
setPosition(OverlayPosition.DYNAMIC); setPosition(OverlayPosition.DYNAMIC);
} }
@Override @Override

View File

@@ -33,21 +33,18 @@ public class PvpToolsPanel extends PluginPanel
private final JLabel loggedLabel = new JLabel(); private final JLabel loggedLabel = new JLabel();
private final JRichTextPane emailLabel = new JRichTextPane(); private final JRichTextPane emailLabel = new JRichTextPane();
public JLabel numCC = new JLabel(); JLabel numCC = new JLabel();
public JLabel numOther = new JLabel(); JLabel numOther = new JLabel();
public JLabel numMageJLabel = new JLabel(" "); JLabel numMageJLabel = new JLabel(" ");
public JLabel numRangeJLabel = new JLabel(" "); JLabel numRangeJLabel = new JLabel(" ");
public JLabel numMeleeJLabel = new JLabel(" "); JLabel numMeleeJLabel = new JLabel(" ");
public JLabel totalRiskLabel = new JLabel(" "); JLabel totalRiskLabel = new JLabel(" ");
public JLabel riskProtectingItem = new JLabel(" "); JLabel riskProtectingItem = new JLabel(" ");
public JLabel biggestItemLabel = new JLabel("Protected Item: "); JLabel biggestItemLabel = new JLabel("Protected Item: ");
public JButton missingPlayers = new JButton("Show missing CC members"); JButton missingPlayers = new JButton("Show missing CC members");
public JButton currentPlayers = new JButton("Show current CC members"); JButton currentPlayers = new JButton("Show current CC members");
public JLabel numBrews = new JLabel(); private JLabel numBrews = new JLabel();
@Inject
private JPanel pvpToolsPanel = new JPanel(new GridLayout(11, 1));
private JPanel missingPlayersPanel = new JPanel(); private JPanel missingPlayersPanel = new JPanel();
private JPanel currentPlayersPanel = new JPanel();
public static String htmlLabel(String key, String value) public static String htmlLabel(String key, String value)
@@ -62,7 +59,6 @@ public class PvpToolsPanel extends PluginPanel
setBorder(new EmptyBorder(10, 10, 10, 10)); setBorder(new EmptyBorder(10, 10, 10, 10));
JPanel versionPanel = new JPanel(); JPanel versionPanel = new JPanel();
versionPanel.setBackground(ColorScheme.DARKER_GRAY_COLOR); versionPanel.setBackground(ColorScheme.DARKER_GRAY_COLOR);
versionPanel.setBorder(new EmptyBorder(10, 10, 10, 10)); versionPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
@@ -136,7 +132,7 @@ public class PvpToolsPanel extends PluginPanel
} }
public void disablePlayerCount() void disablePlayerCount()
{ {
this.numOther.setText("Disabled"); this.numOther.setText("Disabled");
this.numCC.setText("Disabled"); this.numCC.setText("Disabled");
@@ -144,7 +140,7 @@ public class PvpToolsPanel extends PluginPanel
this.numOther.repaint(); this.numOther.repaint();
} }
public void disablePrayerCount() void disablePrayerCount()
{ {
this.numMageJLabel.setText("disabled"); this.numMageJLabel.setText("disabled");
this.numRangeJLabel.setText("disabled"); this.numRangeJLabel.setText("disabled");
@@ -154,7 +150,7 @@ public class PvpToolsPanel extends PluginPanel
this.numMeleeJLabel.repaint(); this.numMeleeJLabel.repaint();
} }
public void disableRiskCalculator() void disableRiskCalculator()
{ {
this.totalRiskLabel.setText("disabled"); this.totalRiskLabel.setText("disabled");
this.riskProtectingItem.setText("disabled"); this.riskProtectingItem.setText("disabled");

View File

@@ -20,7 +20,6 @@ import java.util.NavigableMap;
import java.util.Objects; import java.util.Objects;
import java.util.TreeMap; import java.util.TreeMap;
import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ScheduledExecutorService;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import javax.inject.Inject; import javax.inject.Inject;
import lombok.AccessLevel; import lombok.AccessLevel;
@@ -45,13 +44,11 @@ import net.runelite.api.events.PlayerSpawned;
import net.runelite.client.config.ConfigManager; import net.runelite.client.config.ConfigManager;
import net.runelite.client.eventbus.Subscribe; import net.runelite.client.eventbus.Subscribe;
import net.runelite.client.game.AsyncBufferedImage; import net.runelite.client.game.AsyncBufferedImage;
import net.runelite.client.game.ClanManager;
import net.runelite.client.game.ItemManager; import net.runelite.client.game.ItemManager;
import net.runelite.client.input.KeyManager; import net.runelite.client.input.KeyManager;
import net.runelite.client.plugins.Plugin; import net.runelite.client.plugins.Plugin;
import net.runelite.client.plugins.PluginDescriptor; import net.runelite.client.plugins.PluginDescriptor;
import net.runelite.client.plugins.PluginType; import net.runelite.client.plugins.PluginType;
import net.runelite.client.plugins.PluginManager;
import net.runelite.client.plugins.clanchat.ClanChatPlugin; import net.runelite.client.plugins.clanchat.ClanChatPlugin;
import static net.runelite.client.plugins.pvptools.PvpToolsPanel.htmlLabel; import static net.runelite.client.plugins.pvptools.PvpToolsPanel.htmlLabel;
import net.runelite.client.ui.ClientToolbar; import net.runelite.client.ui.ClientToolbar;
@@ -74,25 +71,30 @@ public class PvpToolsPlugin extends Plugin
{ {
@Inject @Inject
PvpToolsOverlay pvpToolsOverlay; PvpToolsOverlay pvpToolsOverlay;
boolean fallinHelperEnabled = false; boolean fallinHelperEnabled = false;
private PvpToolsPanel panel; private PvpToolsPanel panel;
private MissingPlayersJFrame missingPlayersJFrame; private MissingPlayersJFrame missingPlayersJFrame;
private CurrentPlayersJFrame currentPlayersJFrame; private CurrentPlayersJFrame currentPlayersJFrame;
private NavigationButton navButton; private NavigationButton navButton;
@Getter(AccessLevel.PACKAGE) @Getter(AccessLevel.PACKAGE)
@Setter(AccessLevel.PACKAGE) @Setter(AccessLevel.PACKAGE)
private boolean attackHotKeyPressed; private boolean attackHotKeyPressed;
@Getter(AccessLevel.PACKAGE) @Getter(AccessLevel.PACKAGE)
@Setter(AccessLevel.PACKAGE) @Setter(AccessLevel.PACKAGE)
private boolean hideAll; private boolean hideAll;
@Inject
private ScheduledExecutorService executorService;
@Inject @Inject
private OverlayManager overlayManager; private OverlayManager overlayManager;
@Inject @Inject
private Client client; private Client client;
@Inject @Inject
private ItemManager itemManager; private ItemManager itemManager;
private PvpToolsPlugin uhPvpToolsPlugin = this; private PvpToolsPlugin uhPvpToolsPlugin = this;
/** /**
@@ -144,15 +146,6 @@ public class PvpToolsPlugin extends Plugin
@Inject @Inject
private PvpToolsConfig config; private PvpToolsConfig config;
@Inject
private PluginManager pluginManager;
@Inject
private ClanManager clanManager;
private ClanChatPlugin clanChatPlugin;
/** /**
* The HotKeyListener for the hot key assigned in the config that triggers the Fall In Helper feature * The HotKeyListener for the hot key assigned in the config that triggers the Fall In Helper feature
*/ */
@@ -174,23 +167,11 @@ public class PvpToolsPlugin extends Plugin
private int[] overheadCount = new int[]{0, 0, 0}; private int[] overheadCount = new int[]{0, 0, 0};
private Comparator<Item> itemPriceComparator = new Comparator<Item>() private List<String> getMissingMembers()
{
@Override
public int compare(Item o1, Item o2)
{
return (itemManager.getItemPrice(itemManager.getItemComposition(o1.getId()).getPrice())
- itemManager.getItemPrice(itemManager.getItemComposition(o2.getId()).getPrice()));
}
};
private String mtarget;
public List getMissingMembers()
{ {
CopyOnWriteArrayList<Player> ccMembers = ClanChatPlugin.getClanMembers(); CopyOnWriteArrayList<Player> ccMembers = ClanChatPlugin.getClanMembers();
ArrayList missingMembers = new ArrayList(); ArrayList<String> missingMembers = new ArrayList<>();
for (ClanMember clanMember:client.getClanMembers()) for (ClanMember clanMember : client.getClanMembers())
{ {
if (!Objects.isNull(clanMember)) if (!Objects.isNull(clanMember))
{ {
@@ -206,16 +187,13 @@ public class PvpToolsPlugin extends Plugin
} }
return missingMembers; return missingMembers;
//Arrays.stream(Arrays.stream(client.getClanMembers()).filter(Objects::nonNull).map(ClanMember::getUsername)
//.toArray()).collect(Collectors.toList());
} }
public List getCurrentMembers() private List<String> getCurrentMembers()
{ {
CopyOnWriteArrayList<Player> ccMembers = ClanChatPlugin.getClanMembers(); CopyOnWriteArrayList<Player> ccMembers = ClanChatPlugin.getClanMembers();
ArrayList currentMembers = new ArrayList(); ArrayList<String> currentMembers = new ArrayList<>();
for (ClanMember clanMember:client.getClanMembers()) for (ClanMember clanMember : client.getClanMembers())
{ {
if (!Objects.isNull(clanMember)) if (!Objects.isNull(clanMember))
{ {
@@ -231,13 +209,9 @@ public class PvpToolsPlugin extends Plugin
} }
return currentMembers; return currentMembers;
//Arrays.stream(Arrays.stream(client.getClanMembers()).filter(Objects::nonNull).map(ClanMember::getUsername)
//.toArray()).collect(Collectors.toList());
} }
@Provides @Provides
PvpToolsConfig config(ConfigManager configManager) PvpToolsConfig config(ConfigManager configManager)
{ {
@@ -247,7 +221,6 @@ public class PvpToolsPlugin extends Plugin
@Override @Override
protected void startUp() throws Exception protected void startUp() throws Exception
{ {
overlayManager.add(pvpToolsOverlay); overlayManager.add(pvpToolsOverlay);
keyManager.registerKeyListener(fallinHotkeyListener); keyManager.registerKeyListener(fallinHotkeyListener);
@@ -399,65 +372,47 @@ public class PvpToolsPlugin extends Plugin
@Subscribe @Subscribe
public void onMenuEntryAdded(MenuEntryAdded menuEntryAdded) public void onMenuEntryAdded(MenuEntryAdded menuEntryAdded)
{ {
if (config.attackOptionsFriend() || config.attackOptionsClan() || config.levelRangeAttackOptions()) if (config.attackOptionsFriend() || config.attackOptionsClan() || config.levelRangeAttackOptions())
{
if (client.getGameState() != GameState.LOGGED_IN)
{ {
if (client.getGameState() != GameState.LOGGED_IN) return;
}
Player[] players = client.getCachedPlayers();
Player player = null;
int identifier = menuEntryAdded.getIdentifier();
if (identifier >= 0 && identifier < players.length)
{
player = players[identifier];
}
if (player == null)
{
return;
}
if (attackHotKeyPressed && config.attackOptionsClan() || config.attackOptionsFriend() ||
config.levelRangeAttackOptions())
{
if (config.attackOptionsFriend() && player.isFriend())
{ {
return; moveEntry();
} }
Player[] players = client.getCachedPlayers(); if (config.attackOptionsClan() && player.isClanMember())
Player player = null;
int identifier = menuEntryAdded.getIdentifier();
if (identifier >= 0 && identifier < players.length)
{ {
player = players[identifier]; moveEntry();
} }
if (player == null) if (config.levelRangeAttackOptions() && !PvPUtil.isAttackable(client, player))
{ {
return; moveEntry();
}
final String option = Text.removeTags(menuEntryAdded.getOption()).toLowerCase();
final String mtarget = Text.removeTags(menuEntryAdded.getTarget()).toLowerCase();
if (attackHotKeyPressed && config.attackOptionsClan() || config.attackOptionsFriend() ||
config.levelRangeAttackOptions())
{
if (config.attackOptionsFriend() && player.isFriend())
{
moveEntry(mtarget);
}
if (config.attackOptionsClan() && player.isClanMember())
{
moveEntry(mtarget);
}
if (config.levelRangeAttackOptions() && !PvPUtil.isAttackable(client, player))
{
moveEntry(mtarget);
}
} }
} }
}
} }
private void moveEntry(String mtarget) private void moveEntry()
{ {
this.mtarget = mtarget;
MenuEntry[] menuEntries = client.getMenuEntries(); MenuEntry[] menuEntries = client.getMenuEntries();
MenuEntry lastEntry = menuEntries[menuEntries.length - 1]; MenuEntry lastEntry = menuEntries[menuEntries.length - 1];
// strip out existing <col...
String target = lastEntry.getTarget();
int idx = target.indexOf('>');
if (idx != -1)
{
target = target.substring(idx + 1);
}
/*System.out.println("Contents : " + lastEntry.getTarget());
System.out.println("Contents : " + lastEntry.getIdentifier());
System.out.println("Contents : " + lastEntry.getOption());
System.out.println("length : " + menuEntries.length);*/
if (menuEntries[menuEntries.length - 1] != null)
{
//System.out.println(menuEntries.length + ": " + menuEntries[menuEntries.length-1]);
}
if (lastEntry.getOption().contains("attack".toLowerCase())) if (lastEntry.getOption().contains("attack".toLowerCase()))
{ {
ArrayUtils.shift(menuEntries, 1); ArrayUtils.shift(menuEntries, 1);
@@ -468,10 +423,8 @@ public class PvpToolsPlugin extends Plugin
if (lastEntry.getOption().equals("Attack")) if (lastEntry.getOption().equals("Attack"))
{ {
ArrayUtils.shift(menuEntries, 1); ArrayUtils.shift(menuEntries, 1);
//menuEntries = ArrayUtils.sremove(menuEntries, menuEntries.length - 1);
//menuEntrySwapperPlugin.swap("attack", option, mtarget, false);
} }
client.setMenuEntries(menuEntries); client.setMenuEntries(menuEntries);
} }

View File

@@ -33,13 +33,16 @@ import net.runelite.client.config.ConfigItem;
@ConfigGroup("runeliteplus") @ConfigGroup("runeliteplus")
public interface RuneLitePlusConfig extends Config public interface RuneLitePlusConfig extends Config
{ {
@ConfigItem( @ConfigItem(
position = 0, position = 0,
keyName = "customPresence", keyName = "customPresence",
name = "RL+ Presence", name = "RL+ Presence",
description = "Represent RL+ with a custom icon and discord presence." description = "Represent RL+ with a custom icon and discord presence."
) )
default boolean customPresence() { return false; } default boolean customPresence()
{
return false;
}
@ConfigItem( @ConfigItem(
keyName = "enableOpacity", keyName = "enableOpacity",

View File

@@ -28,6 +28,7 @@ package net.runelite.client.plugins.runeliteplus;
import com.google.inject.Provides; import com.google.inject.Provides;
import javax.inject.Inject;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import net.runelite.api.events.ConfigChanged; import net.runelite.api.events.ConfigChanged;
import net.runelite.client.RuneLiteProperties; import net.runelite.client.RuneLiteProperties;
@@ -39,8 +40,6 @@ import net.runelite.client.plugins.PluginDescriptor;
import net.runelite.client.plugins.PluginType; import net.runelite.client.plugins.PluginType;
import net.runelite.client.ui.ClientUI; import net.runelite.client.ui.ClientUI;
import javax.inject.Inject;
@PluginDescriptor( @PluginDescriptor(
loadWhenOutdated = true, // prevent users from disabling loadWhenOutdated = true, // prevent users from disabling
hidden = true, // prevent users from disabling hidden = true, // prevent users from disabling
@@ -67,7 +66,7 @@ public class RuneLitePlusPlugin extends Plugin
@Provides @Provides
RuneLitePlusConfig getConfig(ConfigManager configManager) RuneLitePlusConfig getConfig(ConfigManager configManager)
{ {
return configManager.getConfig(RuneLitePlusConfig.class); return configManager.getConfig(RuneLitePlusConfig.class);
} }
@@ -75,16 +74,20 @@ public class RuneLitePlusPlugin extends Plugin
@Override @Override
protected void startUp() throws Exception protected void startUp() throws Exception
{ {
if (getConfig(configManager).customPresence()) { if (getConfig(configManager).customPresence())
{
ClientUI.currentPresenceName = ("RuneLitePlus"); ClientUI.currentPresenceName = ("RuneLitePlus");
ClientUI.frame.setTitle(ClientUI.currentPresenceName); ClientUI.frame.setTitle(ClientUI.currentPresenceName);
} }
if (config.customPresence()) { if (config.customPresence())
{
RuneLiteProperties.discordAppID = rlPlusDiscordApp; RuneLiteProperties.discordAppID = rlPlusDiscordApp;
discordService.close(); discordService.close();
discordService.init(); discordService.init();
} else { }
else
{
RuneLiteProperties.discordAppID = rlDiscordApp; RuneLiteProperties.discordAppID = rlDiscordApp;
discordService.close(); discordService.close();
discordService.init(); discordService.init();
@@ -92,21 +95,29 @@ public class RuneLitePlusPlugin extends Plugin
} }
@Subscribe @Subscribe
protected void onConfigChanged(ConfigChanged event) { protected void onConfigChanged(ConfigChanged event)
if (event.getKey().equals("customPresence")) { {
if (config.customPresence()) { if (event.getKey().equals("customPresence"))
{
if (config.customPresence())
{
ClientUI.currentPresenceName = ("RuneLitePlus"); ClientUI.currentPresenceName = ("RuneLitePlus");
ClientUI.frame.setTitle(ClientUI.currentPresenceName); ClientUI.frame.setTitle(ClientUI.currentPresenceName);
} else { }
else
{
ClientUI.currentPresenceName = ("RuneLite"); ClientUI.currentPresenceName = ("RuneLite");
ClientUI.frame.setTitle(ClientUI.currentPresenceName); ClientUI.frame.setTitle(ClientUI.currentPresenceName);
} }
if (config.customPresence()) { if (config.customPresence())
{
RuneLiteProperties.discordAppID = rlPlusDiscordApp; RuneLiteProperties.discordAppID = rlPlusDiscordApp;
discordService.close(); discordService.close();
discordService.init(); discordService.init();
} else { }
else
{
RuneLiteProperties.discordAppID = rlDiscordApp; RuneLiteProperties.discordAppID = rlDiscordApp;
discordService.close(); discordService.close();
discordService.init(); discordService.init();

View File

@@ -44,7 +44,7 @@ public class SafeSpotOverlay extends Overlay
{ {
if (safeSpotPlugin.isSafeSpotsRenderable()) if (safeSpotPlugin.isSafeSpotsRenderable())
{ {
if(safeSpotPlugin.getSafeSpotList() != null) if (safeSpotPlugin.getSafeSpotList() != null)
{ {
if (safeSpotPlugin.getSafeSpotList().size() > 0) if (safeSpotPlugin.getSafeSpotList().size() > 0)
{ {

View File

@@ -40,16 +40,18 @@ import net.runelite.client.ui.overlay.OverlayManager;
) )
public class SafeSpotPlugin extends Plugin public class SafeSpotPlugin extends Plugin
{ {
@Inject @Inject
private Client client; private Client client;
@Inject @Inject
OverlayManager overlayManager; OverlayManager overlayManager;
@Inject @Inject
private SafeSpotConfig config; private SafeSpotConfig config;
@Getter @Getter
private ArrayList<Tile> safeSpotList; private ArrayList<Tile> safeSpotList;
@Getter @Getter
private boolean safeSpotsRenderable = false; private boolean safeSpotsRenderable = false;
@@ -132,7 +134,8 @@ public class SafeSpotPlugin extends Plugin
/** /**
* The ArrayList of 1-way safe spots * The ArrayList of 1-way safe spots
* @param actor - The Actor that the tiles are a safe spot against *
* @param actor - The Actor that the tiles are a safe spot against
* @param worldPoints - Worldpoints in the current scene * @param worldPoints - Worldpoints in the current scene
* @return an ArrayList of Tiles where current player can attack actor but actor cannot attack local player * @return an ArrayList of Tiles where current player can attack actor but actor cannot attack local player
*/ */
@@ -140,7 +143,7 @@ public class SafeSpotPlugin extends Plugin
{ {
ArrayList<Tile> safeSpotList = new ArrayList<>(); ArrayList<Tile> safeSpotList = new ArrayList<>();
Tile[][][] tiles = client.getScene().getTiles(); Tile[][][] tiles = client.getScene().getTiles();
for (WorldPoint w:worldPoints) for (WorldPoint w : worldPoints)
{ {
LocalPoint toPoint = LocalPoint.fromWorld(client, w); LocalPoint toPoint = LocalPoint.fromWorld(client, w);
Tile fromTile = tiles[client.getPlane()][actor.getLocalLocation().getSceneX()] Tile fromTile = tiles[client.getPlane()][actor.getLocalLocation().getSceneX()]
@@ -151,11 +154,11 @@ public class SafeSpotPlugin extends Plugin
int bit = client.getCollisionMaps()[plane].getFlags()[toPoint.getSceneX()][toPoint.getSceneY()]; int bit = client.getCollisionMaps()[plane].getFlags()[toPoint.getSceneX()][toPoint.getSceneY()];
if (toTile.hasLineOfSightTo(fromTile) && !fromTile.hasLineOfSightTo(toTile)) if (toTile.hasLineOfSightTo(fromTile) && !fromTile.hasLineOfSightTo(toTile))
{ {
if (!((bit & CollisionDataFlag.BLOCK_MOVEMENT_OBJECT ) == CollisionDataFlag.BLOCK_MOVEMENT_OBJECT || if (!((bit & CollisionDataFlag.BLOCK_MOVEMENT_OBJECT) == CollisionDataFlag.BLOCK_MOVEMENT_OBJECT ||
(bit & CollisionDataFlag.BLOCK_MOVEMENT_FLOOR_DECORATION ) (bit & CollisionDataFlag.BLOCK_MOVEMENT_FLOOR_DECORATION)
== CollisionDataFlag.BLOCK_MOVEMENT_FLOOR_DECORATION || == CollisionDataFlag.BLOCK_MOVEMENT_FLOOR_DECORATION ||
(bit & CollisionDataFlag.BLOCK_MOVEMENT_FLOOR ) == CollisionDataFlag.BLOCK_MOVEMENT_FLOOR || (bit & CollisionDataFlag.BLOCK_MOVEMENT_FLOOR) == CollisionDataFlag.BLOCK_MOVEMENT_FLOOR ||
(bit & CollisionDataFlag.BLOCK_MOVEMENT_FULL ) == CollisionDataFlag.BLOCK_MOVEMENT_FULL)) (bit & CollisionDataFlag.BLOCK_MOVEMENT_FULL) == CollisionDataFlag.BLOCK_MOVEMENT_FULL))
{ {
safeSpotList.add(toTile); safeSpotList.add(toTile);
} }

View File

@@ -80,7 +80,8 @@ import net.runelite.client.plugins.PluginDescriptor;
name = "Slayermusiq1 Guides", name = "Slayermusiq1 Guides",
description = "Adds a right-click option to go to Slayermusiq1's guides from the quest tab", description = "Adds a right-click option to go to Slayermusiq1's guides from the quest tab",
tags = {"quest", "guide", "slayermusiq"}, tags = {"quest", "guide", "slayermusiq"},
type = PluginType.UTILITY type = PluginType.UTILITY,
enabledByDefault = false
) )
@Slf4j @Slf4j
public class SlayermusiqPlugin extends Plugin public class SlayermusiqPlugin extends Plugin

View File

@@ -1,77 +1,82 @@
package net.runelite.client.plugins.tickcounter; package net.runelite.client.plugins.tickcounter;
import java.awt.Color;
import net.runelite.client.config.Alpha; import net.runelite.client.config.Alpha;
import net.runelite.client.config.Config; import net.runelite.client.config.Config;
import net.runelite.client.config.ConfigGroup; import net.runelite.client.config.ConfigGroup;
import net.runelite.client.config.ConfigItem; import net.runelite.client.config.ConfigItem;
import java.awt.*;
@ConfigGroup("tickcounter") @ConfigGroup("tickcounter")
public interface TickCounterConfig extends Config { public interface TickCounterConfig extends Config
@ConfigItem( {
keyName = "resetInstance", @ConfigItem(
name = "Reset on new instances", keyName = "resetInstance",
description = "", name = "Reset on new instances",
position = 1 description = "",
) position = 1
default boolean instance() )
{ default boolean instance()
return true; {
} return true;
@Alpha }
@ConfigItem(
keyName = "selfColor", @Alpha
name = "Your color", @ConfigItem(
description = "", keyName = "selfColor",
position = 4 name = "Your color",
) description = "",
default Color selfColor() position = 4
{ )
return Color.green; default Color selfColor()
} {
@Alpha return Color.green;
@ConfigItem( }
keyName = "totalColor",
name = "Total color", @Alpha
description = "", @ConfigItem(
position = 6 keyName = "totalColor",
) name = "Total color",
default Color totalColor() description = "",
{ position = 6
return Color.RED; )
} default Color totalColor()
@Alpha {
@ConfigItem( return Color.RED;
keyName = "otherColor", }
name = "Other players color",
description = "", @Alpha
position = 5 @ConfigItem(
) keyName = "otherColor",
default Color otherColor() name = "Other players color",
{ description = "",
return Color.white; position = 5
} )
@Alpha default Color otherColor()
@ConfigItem( {
keyName = "bgColor", return Color.white;
name = "Background color", }
description = "",
position = 3 @Alpha
) @ConfigItem(
default Color bgColor() keyName = "bgColor",
{ name = "Background color",
return new Color(70, 61, 50, 156); description = "",
} position = 3
@Alpha )
@ConfigItem( default Color bgColor()
keyName = "titleColor", {
name = "Title color", return new Color(70, 61, 50, 156);
description = "", }
position = 2
) @Alpha
default Color titleColor() @ConfigItem(
{ keyName = "titleColor",
return Color.white; name = "Title color",
} description = "",
position = 2
)
default Color titleColor()
{
return Color.white;
}
} }

View File

@@ -1,15 +1,12 @@
package net.runelite.client.plugins.tickcounter; package net.runelite.client.plugins.tickcounter;
import java.awt.Color;
import java.awt.Dimension; import java.awt.Dimension;
import java.awt.Graphics2D; import java.awt.Graphics2D;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Comparator; import java.util.Comparator;
import java.util.List; import java.util.List;
import java.util.Map.Entry; import java.util.Map.Entry;
import javax.inject.Inject; import javax.inject.Inject;
import net.runelite.api.Client; import net.runelite.api.Client;
import net.runelite.client.ui.overlay.Overlay; import net.runelite.client.ui.overlay.Overlay;
import net.runelite.client.ui.overlay.OverlayPosition; import net.runelite.client.ui.overlay.OverlayPosition;
@@ -18,7 +15,8 @@ import net.runelite.client.ui.overlay.components.LineComponent;
import net.runelite.client.ui.overlay.components.PanelComponent; import net.runelite.client.ui.overlay.components.PanelComponent;
import net.runelite.client.ui.overlay.components.TitleComponent; import net.runelite.client.ui.overlay.components.TitleComponent;
public class TickCounterOverlay extends Overlay { public class TickCounterOverlay extends Overlay
{
private TickCounterPlugin plugin; private TickCounterPlugin plugin;
private TickCounterConfig config; private TickCounterConfig config;
@@ -26,7 +24,8 @@ public class TickCounterOverlay extends Overlay {
private PanelComponent panelComponent = new PanelComponent(); private PanelComponent panelComponent = new PanelComponent();
@Inject @Inject
public TickCounterOverlay(TickCounterPlugin plugin,Client client,TickCounterConfig config) { public TickCounterOverlay(TickCounterPlugin plugin, Client client, TickCounterConfig config)
{
super(plugin); super(plugin);
setPosition(OverlayPosition.DYNAMIC); setPosition(OverlayPosition.DYNAMIC);
setPosition(OverlayPosition.DETACHED); setPosition(OverlayPosition.DETACHED);
@@ -37,27 +36,31 @@ public class TickCounterOverlay extends Overlay {
} }
@Override @Override
public Dimension render(Graphics2D g) { public Dimension render(Graphics2D g)
{
List<LayoutableRenderableEntity> elems = panelComponent.getChildren(); List<LayoutableRenderableEntity> elems = panelComponent.getChildren();
elems.clear(); elems.clear();
panelComponent.setBackgroundColor(config.bgColor()); panelComponent.setBackgroundColor(config.bgColor());
elems.add(TitleComponent.builder().text("Combat counter").color(config.titleColor()).build()); elems.add(TitleComponent.builder().text("Combat counter").color(config.titleColor()).build());
List<Entry<String, Integer>> list = new ArrayList<>(plugin.activity.entrySet()); List<Entry<String, Integer>> list = new ArrayList<>(plugin.activity.entrySet());
list.sort(new Comparator<Entry<String, Integer>>() { list.sort((o1, o2) -> {
@Override int value = -Integer.compare(o1.getValue(), o2.getValue());
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) { if (value == 0)
int value = -Integer.compare(o1.getValue(), o2.getValue()); {
if (value == 0) value = o1.getKey().compareTo(o2.getKey());
value = o1.getKey().compareTo(o2.getKey());
return value;
} }
return value;
}); });
int total = 0; int total = 0;
for (Entry<String, Integer> e : list) { for (Entry<String, Integer> e : list)
{
total += e.getValue(); total += e.getValue();
if(e.getKey().equals(client.getLocalPlayer().getName())){ if (e.getKey().equals(client.getLocalPlayer().getName()))
{
elems.add(LineComponent.builder().leftColor(config.selfColor()).rightColor(config.selfColor()).left(e.getKey()).right(e.getValue().toString()).build()); elems.add(LineComponent.builder().leftColor(config.selfColor()).rightColor(config.selfColor()).left(e.getKey()).right(e.getValue().toString()).build());
}else{ }
else
{
elems.add(LineComponent.builder().left(e.getKey()).right(e.getValue().toString()).leftColor(config.otherColor()).rightColor(config.otherColor()).build()); elems.add(LineComponent.builder().left(e.getKey()).right(e.getValue().toString()).leftColor(config.otherColor()).rightColor(config.otherColor()).build());
} }

View File

@@ -1,13 +1,11 @@
package net.runelite.client.plugins.tickcounter; package net.runelite.client.plugins.tickcounter;
import com.google.inject.Provides;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import javax.inject.Inject; import javax.inject.Inject;
import com.google.inject.Provides;
import net.runelite.api.Actor; import net.runelite.api.Actor;
import net.runelite.api.Client; import net.runelite.api.Client;
import net.runelite.api.Player; import net.runelite.api.Player;
@@ -23,53 +21,66 @@ import net.runelite.client.plugins.PluginType;
import net.runelite.client.ui.overlay.OverlayManager; import net.runelite.client.ui.overlay.OverlayManager;
@PluginDescriptor(name = "Tick Counter", @PluginDescriptor(name = "Tick Counter",
description = "Counts combat activity for nearby players", description = "Counts combat activity for nearby players",
enabledByDefault = false, enabledByDefault = false,
type = PluginType.PVP type = PluginType.PVP
) )
public class TickCounterPlugin extends Plugin { public class TickCounterPlugin extends Plugin
{
@Inject @Inject
private OverlayManager overlayManager; private OverlayManager overlayManager;
@Inject @Inject
private TickCounterConfig config; private TickCounterConfig config;
@Inject @Inject
private Client client; private Client client;
@Provides @Provides
TickCounterConfig provideConfig(ConfigManager configManager) TickCounterConfig provideConfig(ConfigManager configManager)
{ {
return configManager.getConfig(TickCounterConfig.class); return configManager.getConfig(TickCounterConfig.class);
} }
@Inject @Inject
private TickCounterOverlay overlay; private TickCounterOverlay overlay;
Map<String, Integer> activity = new HashMap<>(); Map<String, Integer> activity = new HashMap<>();
private List<Player> blowpiping = new ArrayList<>(); private List<Player> blowpiping = new ArrayList<>();
boolean instanced = false; private boolean instanced = false;
boolean prevInstance = false; private boolean prevInstance = false;
@Override @Override
protected void startUp() throws Exception { protected void startUp() throws Exception
{
overlayManager.add(overlay); overlayManager.add(overlay);
} }
@Override @Override
protected void shutDown() throws Exception { protected void shutDown() throws Exception
{
overlayManager.remove(overlay); overlayManager.remove(overlay);
activity.clear(); activity.clear();
} }
@Subscribe @Subscribe
public void onAnimationChanged(AnimationChanged e) { public void onAnimationChanged(AnimationChanged e)
{
if (!(e.getActor() instanceof Player)) if (!(e.getActor() instanceof Player))
{
return; return;
}
Player p = (Player) e.getActor(); Player p = (Player) e.getActor();
int weapon = -1; int weapon = -1;
if (p.getPlayerComposition() != null) if (p.getPlayerComposition() != null)
{
weapon = p.getPlayerComposition().getEquipmentId(KitType.WEAPON); weapon = p.getPlayerComposition().getEquipmentId(KitType.WEAPON);
}
int delta = 0; int delta = 0;
switch (p.getAnimation()) { switch (p.getAnimation())
{
case 7617: // rune knife case 7617: // rune knife
case 8194: // dragon knife case 8194: // dragon knife
case 8291: // dragon knife spec case 8291: // dragon knife spec
@@ -89,9 +100,13 @@ public class TickCounterPlugin extends Plugin {
break; break;
case 426: // bow shoot case 426: // bow shoot
if (weapon == 20997) // twisted bow if (weapon == 20997) // twisted bow
{
delta = 5; delta = 5;
}
else // shortbow else // shortbow
{
delta = 3; delta = 3;
}
break; break;
case 376: // dds poke case 376: // dds poke
case 377: // dds slash case 377: // dds slash
@@ -119,7 +134,8 @@ public class TickCounterPlugin extends Plugin {
delta = 4; delta = 4;
break; break;
case 393: // staff bash case 393: // staff bash
if (weapon == 13652) { // claw scratch if (weapon == 13652)
{ // claw scratch
delta = 4; delta = 4;
break; break;
} }
@@ -135,9 +151,13 @@ public class TickCounterPlugin extends Plugin {
break; break;
case 401: case 401:
if (weapon == 13576) // dwh bop if (weapon == 13576) // dwh bop
{
delta = 6; delta = 6;
}
else // used by pickaxe and axe else // used by pickaxe and axe
{
delta = 5; delta = 5;
}
break; break;
case 1378: case 1378:
case 7045: case 7045:
@@ -158,37 +178,47 @@ public class TickCounterPlugin extends Plugin {
case 1203: // chally spec case 1203: // chally spec
delta = 7; delta = 7;
break; break;
case -1: case -1:
blowpiping.remove(p); blowpiping.remove(p);
break; break;
} }
if (delta > 0) { if (delta > 0)
{
String name = p.getName(); String name = p.getName();
this.activity.put(name, this.activity.getOrDefault(name, 0) + delta); this.activity.put(name, this.activity.getOrDefault(name, 0) + delta);
} }
} }
@Subscribe @Subscribe
public void onClientTick(ClientTick e) { public void onClientTick(ClientTick e)
{
/* /*
* Hack for blowpipe since the AnimationChanged event doesn't fire when using a * Hack for blowpipe since the AnimationChanged event doesn't fire when using a
* blowpipe because of its speed. If blowpipe animation restarts, then add 2 * blowpipe because of its speed. If blowpipe animation restarts, then add 2
*/ */
for (Player p : blowpiping) { for (Player p : blowpiping)
{
Actor rsp = p; Actor rsp = p;
if (rsp.getActionFrame() == 0 && rsp.getActionFrameCycle() == 1) { if (rsp.getActionFrame() == 0 && rsp.getActionFrameCycle() == 1)
{
String name = p.getName(); String name = p.getName();
int activity = this.activity.getOrDefault(name, 0).intValue(); int activity = this.activity.getOrDefault(name, 0);
this.activity.put(name, activity + 2); this.activity.put(name, activity + 2);
} }
} }
} }
@Subscribe @Subscribe
public void onGameTick(GameTick tick){ public void onGameTick(GameTick tick)
if(!config.instance())return; {
if (!config.instance())
{
return;
}
prevInstance = instanced; prevInstance = instanced;
instanced = client.isInInstancedRegion(); instanced = client.isInInstancedRegion();
if(!prevInstance && instanced){ if (!prevInstance && instanced)
{
activity.clear(); activity.clear();
} }
} }

View File

@@ -1,44 +0,0 @@
/*
* Copyright (c) 2019, Frosty Fridge <https://github.com/frostyfridge>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.runelite.client.plugins.vetion;
import net.runelite.client.config.Config;
import net.runelite.client.config.ConfigGroup;
import net.runelite.client.config.ConfigItem;
@ConfigGroup("vetion")
public interface VetionConfig extends Config
{
@ConfigItem(
keyName = "earthquakeTimerActive",
name = "Vet'ion Earthquake Timer",
description = "Configures whether or not a timer is shown to track the cooldown of Vet'ion's earthquake attack",
position = 0
)
default boolean eartquakeTimerActive()
{
return true;
}
}

View File

@@ -24,6 +24,12 @@
*/ */
package net.runelite.client.plugins.vetion; package net.runelite.client.plugins.vetion;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.time.Duration;
import java.time.Instant;
import javax.inject.Inject;
import net.runelite.api.Client; import net.runelite.api.Client;
import net.runelite.api.Perspective; import net.runelite.api.Perspective;
import net.runelite.api.Point; import net.runelite.api.Point;
@@ -33,61 +39,57 @@ import net.runelite.client.ui.overlay.OverlayLayer;
import net.runelite.client.ui.overlay.OverlayPosition; import net.runelite.client.ui.overlay.OverlayPosition;
import net.runelite.client.ui.overlay.components.ProgressPieComponent; import net.runelite.client.ui.overlay.components.ProgressPieComponent;
import javax.inject.Inject; public class VetionOverlay extends Overlay
import java.awt.*; {
import java.time.Duration;
import java.time.Instant;
public class VetionOverlay extends Overlay{ private static final Color RED_ALPHA = new Color(Color.RED.getRed(), Color.RED.getGreen(), Color.RED.getBlue(), 100);
private static final Duration MAX_TIME = Duration.ofSeconds(9);
private final VetionPlugin plugin;
private Client client;
private static final Color RED_ALPHA = new Color(Color.RED.getRed(), Color.RED.getGreen(), Color.RED.getBlue(), 100); @Inject
private static final Duration MAX_TIME = Duration.ofSeconds(9); private VetionOverlay(Client client, VetionPlugin plugin)
private final VetionPlugin plugin; {
private Client client; this.plugin = plugin;
this.client = client;
setPosition(OverlayPosition.DYNAMIC);
setLayer(OverlayLayer.ABOVE_SCENE);
}
@Inject @Override
private VetionOverlay(Client client, VetionPlugin plugin) public Dimension render(Graphics2D graphics)
{ {
this.plugin = plugin; plugin.getVetions().forEach((actor, timer) ->
this.client = client; {
setPosition(OverlayPosition.DYNAMIC); LocalPoint localPos = actor.getLocalLocation();
setLayer(OverlayLayer.ABOVE_SCENE); if (localPos != null)
} {
Point position = Perspective.localToCanvas(client, localPos, client.getPlane(),
actor.getLogicalHeight() + 96);
if (position != null)
{
position = new Point(position.getX(), position.getY());
@Override final ProgressPieComponent progressPie = new ProgressPieComponent();
public Dimension render(Graphics2D graphics) progressPie.setDiameter(30);
{ progressPie.setFill(RED_ALPHA);
plugin.getVetions().forEach((actor, timer) -> progressPie.setBorderColor(Color.RED);
{ progressPie.setPosition(position);
LocalPoint localPos = actor.getLocalLocation();
if (localPos != null)
{
Point position = Perspective.localToCanvas(client, localPos, client.getPlane(),
actor.getLogicalHeight() + 96);
if (position != null)
{
position = new Point(position.getX(), position.getY());
final ProgressPieComponent progressPie = new ProgressPieComponent(); final Duration duration = Duration.between(timer, Instant.now());
progressPie.setDiameter(30); progressPie.setProgress(1 - (duration.compareTo(MAX_TIME) < 0
progressPie.setFill(RED_ALPHA); ? (double) duration.toMillis() / MAX_TIME.toMillis()
progressPie.setBorderColor(Color.RED); : 1));
progressPie.setPosition(position);
final Duration duration = Duration.between(timer, Instant.now()); progressPie.render(graphics);
progressPie.setProgress(1 - (duration.compareTo(MAX_TIME) < 0 if (1 - duration.compareTo(MAX_TIME) < 0)
? (double) duration.toMillis() / MAX_TIME.toMillis() {
: 1)); plugin.getVetions().remove(actor);
}
}
}
});
progressPie.render(graphics); return null;
if (1 - duration.compareTo(MAX_TIME) < 0) }
{
plugin.getVetions().remove(actor);
}
}
}
});
return null;
}
} }

View File

@@ -25,8 +25,14 @@
package net.runelite.client.plugins.vetion; package net.runelite.client.plugins.vetion;
import com.google.inject.Provides; import com.google.inject.Provides;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import javax.inject.Inject;
import lombok.Getter; import lombok.Getter;
import net.runelite.api.*; import net.runelite.api.Actor;
import net.runelite.api.AnimationID;
import net.runelite.api.Client;
import net.runelite.api.events.AnimationChanged; import net.runelite.api.events.AnimationChanged;
import net.runelite.client.config.ConfigManager; import net.runelite.client.config.ConfigManager;
import net.runelite.client.eventbus.Subscribe; import net.runelite.client.eventbus.Subscribe;
@@ -35,63 +41,47 @@ import net.runelite.client.plugins.PluginDescriptor;
import net.runelite.client.plugins.PluginType; import net.runelite.client.plugins.PluginType;
import net.runelite.client.ui.overlay.OverlayManager; import net.runelite.client.ui.overlay.OverlayManager;
import javax.inject.Inject;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
@PluginDescriptor( @PluginDescriptor(
name = "Vetion Helper", name = "Vetion Helper",
description = "Tracks Vet'ion's special attacks", description = "Tracks Vet'ion's special attacks",
tags = {"bosses", "combat", "pve", "overlay"}, tags = {"bosses", "combat", "pve", "overlay"},
type = PluginType.PVM type = PluginType.PVM
) )
public class VetionPlugin extends Plugin { public class VetionPlugin extends Plugin
{
@Inject @Inject
private Client client; private OverlayManager overlayManager;
@Inject @Inject
private VetionConfig config; private VetionOverlay overlay;
@Inject @Getter
private OverlayManager overlayManager; private Map<Actor, Instant> vetions;
@Inject @Override
private VetionOverlay overlay; protected void startUp()
{
vetions = new HashMap<>();
overlayManager.add(overlay);
}
@Getter @Override
private Map<Actor, Instant> vetions; protected void shutDown()
{
@Provides overlayManager.remove(overlay);
VetionConfig getConfig(ConfigManager configManager) vetions = null;
{ }
return configManager.getConfig(VetionConfig.class);
}
@Override
protected void startUp()
{
vetions = new HashMap<>();
overlayManager.add(overlay);
}
@Override
protected void shutDown()
{
overlayManager.remove(overlay);
vetions = null;
}
@Subscribe @Subscribe
public void onAnimationChanged(AnimationChanged event) public void onAnimationChanged(AnimationChanged event)
{ {
if (config.eartquakeTimerActive() && event.getActor().getAnimation() == AnimationID.VETION_EARTHQUAKE) if (event.getActor().getAnimation() == AnimationID.VETION_EARTHQUAKE)
{ {
Actor vet = event.getActor(); Actor vet = event.getActor();
vetions.remove(vet, Instant.now()); vetions.remove(vet, Instant.now());
vetions.put(vet, Instant.now()); vetions.put(vet, Instant.now());
} }
} }
} }

View File

@@ -34,10 +34,10 @@ import net.runelite.client.config.ConfigItem;
public interface WarIndicatorConfig extends Config public interface WarIndicatorConfig extends Config
{ {
@ConfigItem( @ConfigItem(
position = 0, position = 0,
keyName = "highLightCallers", keyName = "highLightCallers",
name = "Highlight Callers", name = "Highlight Callers",
description = "Highlight listed caller(s)" description = "Highlight listed caller(s)"
) )
default boolean highLightCallers() default boolean highLightCallers()
{ {
@@ -45,10 +45,10 @@ public interface WarIndicatorConfig extends Config
} }
@ConfigItem( @ConfigItem(
position = 1, position = 1,
keyName = "callerColor", keyName = "callerColor",
name = "Caller(s) Color", name = "Caller(s) Color",
description = "Color to highlight caller's name" description = "Color to highlight caller's name"
) )
default Color getCallerColor() default Color getCallerColor()
{ {
@@ -56,10 +56,10 @@ public interface WarIndicatorConfig extends Config
} }
@ConfigItem( @ConfigItem(
position = 2, position = 2,
keyName = "callerMinimap", keyName = "callerMinimap",
name = "Callers on Minimap", name = "Callers on Minimap",
description = "Show your caller(s) on the minimap" description = "Show your caller(s) on the minimap"
) )
default boolean callerMinimap() default boolean callerMinimap()
{ {
@@ -68,10 +68,10 @@ public interface WarIndicatorConfig extends Config
@ConfigItem( @ConfigItem(
position = 3, position = 3,
keyName = "callerTile", keyName = "callerTile",
name = "Show Caller's Tile", name = "Show Caller's Tile",
description = "Show the tile your target is standing on" description = "Show the tile your target is standing on"
) )
default boolean callerTile() default boolean callerTile()
{ {
@@ -79,10 +79,10 @@ public interface WarIndicatorConfig extends Config
} }
@ConfigItem( @ConfigItem(
position = 4, position = 4,
keyName = "activeCallers", keyName = "activeCallers",
name = "Callers", name = "Callers",
description = "Adds a user to your caller list. Format: (caller), (caller)" description = "Adds a user to your caller list. Format: (caller), (caller)"
) )
default String getActiveCallers() default String getActiveCallers()
{ {
@@ -90,19 +90,19 @@ public interface WarIndicatorConfig extends Config
} }
@ConfigItem( @ConfigItem(
position = 5, position = 5,
keyName = "activeCallers", keyName = "activeCallers",
name = "", name = "",
description = "" description = ""
) )
void setActiveCallers(String key); void setActiveCallers(String key);
@ConfigItem( @ConfigItem(
position = 6, position = 6,
keyName = "highlightSnipes", keyName = "highlightSnipes",
name = "Highlight Targets", name = "Highlight Targets",
description = "Highlight listed target(s)" description = "Highlight listed target(s)"
) )
default boolean highlightSnipes() default boolean highlightSnipes()
{ {
@@ -110,10 +110,10 @@ public interface WarIndicatorConfig extends Config
} }
@ConfigItem( @ConfigItem(
position = 7, position = 7,
keyName = "snipeColor", keyName = "snipeColor",
name = "Target(s) Color", name = "Target(s) Color",
description = "Color to highlight target name" description = "Color to highlight target name"
) )
default Color getSnipeColor() default Color getSnipeColor()
{ {
@@ -121,10 +121,10 @@ public interface WarIndicatorConfig extends Config
} }
@ConfigItem( @ConfigItem(
position = 8, position = 8,
keyName = "snipeMinimap", keyName = "snipeMinimap",
name = "Targets on Minimap", name = "Targets on Minimap",
description = "Show your target on the minimap" description = "Show your target on the minimap"
) )
default boolean snipeMinimap() default boolean snipeMinimap()
{ {
@@ -132,10 +132,10 @@ public interface WarIndicatorConfig extends Config
} }
@ConfigItem( @ConfigItem(
position = 9, position = 9,
keyName = "snipeTile", keyName = "snipeTile",
name = "Show Target's Tile", name = "Show Target's Tile",
description = "Show the tile your target is standing on" description = "Show the tile your target is standing on"
) )
default boolean snipeTile() default boolean snipeTile()
{ {
@@ -143,10 +143,10 @@ public interface WarIndicatorConfig extends Config
} }
@ConfigItem( @ConfigItem(
position = 10, position = 10,
keyName = "targetedSnipes", keyName = "targetedSnipes",
name = "Targets", name = "Targets",
description = "Adds a user to your snipe list. Format: (target), (target)" description = "Adds a user to your snipe list. Format: (target), (target)"
) )
default String getTargetedSnipes() default String getTargetedSnipes()
{ {
@@ -154,11 +154,10 @@ public interface WarIndicatorConfig extends Config
} }
@ConfigItem( @ConfigItem(
position = 11, position = 11,
keyName = "targetedSnipes", keyName = "targetedSnipes",
name = "", name = "",
description = "" description = ""
) )
void setTargetedSnipe(String key); void setTargetedSnipe(String key);
} }

View File

@@ -30,7 +30,6 @@ import java.awt.Graphics2D;
import java.awt.Polygon; import java.awt.Polygon;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.apache.commons.lang3.ArrayUtils;
import net.runelite.api.Player; import net.runelite.api.Player;
import net.runelite.api.Point; import net.runelite.api.Point;
import net.runelite.client.ui.overlay.Overlay; import net.runelite.client.ui.overlay.Overlay;
@@ -38,6 +37,7 @@ import net.runelite.client.ui.overlay.OverlayLayer;
import net.runelite.client.ui.overlay.OverlayPosition; import net.runelite.client.ui.overlay.OverlayPosition;
import net.runelite.client.ui.overlay.OverlayPriority; import net.runelite.client.ui.overlay.OverlayPriority;
import net.runelite.client.ui.overlay.OverlayUtil; import net.runelite.client.ui.overlay.OverlayUtil;
import org.apache.commons.lang3.ArrayUtils;
@Singleton @Singleton
public class WarIndicatorOverlay extends Overlay public class WarIndicatorOverlay extends Overlay

View File

@@ -24,43 +24,28 @@
*/ */
package net.runelite.client.plugins.warindicators; package net.runelite.client.plugins.warindicators;
import com.google.common.collect.Sets;
import com.google.common.eventbus.Subscribe;
import com.google.inject.Provides; import com.google.inject.Provides;
import java.awt.Color; import java.awt.Color;
import java.util.Collection;
import javax.inject.Inject; import javax.inject.Inject;
import net.runelite.client.plugins.PluginType;
import org.apache.commons.lang3.ArrayUtils;
import net.runelite.api.Client; import net.runelite.api.Client;
import static net.runelite.api.MenuAction.FOLLOW; import static net.runelite.api.MenuAction.*;
import static net.runelite.api.MenuAction.ITEM_USE_ON_PLAYER;
import static net.runelite.api.MenuAction.PLAYER_EIGTH_OPTION;
import static net.runelite.api.MenuAction.PLAYER_FIFTH_OPTION;
import static net.runelite.api.MenuAction.PLAYER_FIRST_OPTION;
import static net.runelite.api.MenuAction.PLAYER_FOURTH_OPTION;
import static net.runelite.api.MenuAction.PLAYER_SECOND_OPTION;
import static net.runelite.api.MenuAction.PLAYER_SEVENTH_OPTION;
import static net.runelite.api.MenuAction.PLAYER_SIXTH_OPTION;
import static net.runelite.api.MenuAction.PLAYER_THIRD_OPTION;
import static net.runelite.api.MenuAction.SPELL_CAST_ON_PLAYER;
import static net.runelite.api.MenuAction.TRADE;
import net.runelite.api.MenuEntry; import net.runelite.api.MenuEntry;
import net.runelite.api.Player; import net.runelite.api.Player;
import net.runelite.api.events.MenuEntryAdded; import net.runelite.api.events.MenuEntryAdded;
import net.runelite.client.config.ConfigManager; import net.runelite.client.config.ConfigManager;
import net.runelite.client.eventbus.Subscribe;
import net.runelite.client.plugins.Plugin; import net.runelite.client.plugins.Plugin;
import net.runelite.client.plugins.PluginDescriptor; import net.runelite.client.plugins.PluginDescriptor;
import net.runelite.client.ui.overlay.Overlay; import net.runelite.client.plugins.PluginType;
import net.runelite.client.ui.overlay.OverlayManager; import net.runelite.client.ui.overlay.OverlayManager;
import org.apache.commons.lang3.ArrayUtils;
@PluginDescriptor( @PluginDescriptor(
name = "War calling indicators", name = "War calling indicators",
description = "War War War.", description = "War War War.",
tags = {"skill", "total", "max", "PVP"}, tags = {"skill", "total", "max", "PVP"},
type = PluginType.PVP, type = PluginType.PVP,
enabledByDefault = false enabledByDefault = false
) )
public class WarIndicatorPlugin extends Plugin public class WarIndicatorPlugin extends Plugin
{ {
@@ -85,31 +70,31 @@ public class WarIndicatorPlugin extends Plugin
return configManager.getConfig(WarIndicatorConfig.class); return configManager.getConfig(WarIndicatorConfig.class);
} }
@Override @Override
protected void startUp() throws Exception protected void startUp() throws Exception
{ {
overlayManager.add(warIndicatorOverlay); overlayManager.add(warIndicatorOverlay);
overlayManager.add(warIndicatorMiniMapOverlay); overlayManager.add(warIndicatorMiniMapOverlay);
} }
@Override @Override
protected void shutDown() throws Exception protected void shutDown() throws Exception
{ {
overlayManager.remove(warIndicatorOverlay); overlayManager.remove(warIndicatorOverlay);
overlayManager.remove(warIndicatorMiniMapOverlay); overlayManager.remove(warIndicatorMiniMapOverlay);
} }
@Subscribe @Subscribe
public void onMenuEntryAdd(MenuEntryAdded menuEntryAdded) public void onMenuEntryAdded(MenuEntryAdded onMenuEntryAdded)
{ {
int type = menuEntryAdded.getType(); int type = onMenuEntryAdded.getType();
if (type >= 2000) if (type >= 2000)
{ {
type -= 2000; type -= 2000;
} }
int identifier = menuEntryAdded.getIdentifier(); int identifier = onMenuEntryAdded.getIdentifier();
if (type == FOLLOW.getId() || type == TRADE.getId() if (type == FOLLOW.getId() || type == TRADE.getId()
|| type == SPELL_CAST_ON_PLAYER.getId() || type == SPELL_CAST_ON_PLAYER.getId()
|| type == ITEM_USE_ON_PLAYER.getId() || type == ITEM_USE_ON_PLAYER.getId()

View File

@@ -24,12 +24,12 @@
*/ */
package net.runelite.client.plugins.warindicators; package net.runelite.client.plugins.warindicators;
import net.runelite.api.Client; import java.awt.Color;
import net.runelite.api.Player; import java.util.function.BiConsumer;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
import java.awt.*; import net.runelite.api.Client;
import java.util.function.BiConsumer; import net.runelite.api.Player;
@Singleton @Singleton
public class WarIndicatorService public class WarIndicatorService
@@ -62,14 +62,9 @@ public class WarIndicatorService
String[] targets = config.getTargetedSnipes().split(", "); String[] targets = config.getTargetedSnipes().split(", ");
if (targets == null) for (String target : targets)
{ {
return; if (player.getName().equalsIgnoreCase(target))
}
for (int i = 0; i < targets.length; i++)
{
if (player.getName().equalsIgnoreCase(targets[i]))
{ {
consumer.accept(player, config.getSnipeColor()); consumer.accept(player, config.getSnipeColor());
} }
@@ -88,14 +83,9 @@ public class WarIndicatorService
String[] callers = config.getActiveCallers().split(", "); String[] callers = config.getActiveCallers().split(", ");
if (callers == null) for (String caller : callers)
{ {
return; if (player.getName().equalsIgnoreCase(caller))
}
for (int i = 0; i < callers.length; i++)
{
if (player.getName().equalsIgnoreCase(callers[i]))
{ {
consumer.accept(player, config.getCallerColor()); consumer.accept(player, config.getCallerColor());
} }

View File

@@ -43,7 +43,8 @@ import org.apache.commons.lang3.ObjectUtils;
name = "Whale Watchers", name = "Whale Watchers",
description = "A Plugin to save help whales in the wild", description = "A Plugin to save help whales in the wild",
tags = {"whale watchers", "whale", "protect item", "warning", "pklite"}, tags = {"whale watchers", "whale", "protect item", "warning", "pklite"},
type = PluginType.PVP type = PluginType.PVP,
enabledByDefault = false
) )
public class WhaleWatchersPlugin extends Plugin public class WhaleWatchersPlugin extends Plugin
{ {

View File

@@ -28,14 +28,13 @@ public class WildernessLocationsOverlay extends Overlay
private WildernessLocationsConfig wildyConfig; private WildernessLocationsConfig wildyConfig;
@Inject @Inject
public WildernessLocationsOverlay(Client client, WildernessLocationsPlugin plugin) public WildernessLocationsOverlay(WildernessLocationsPlugin plugin)
{ {
this.plugin = plugin; this.plugin = plugin;
setLayer(OverlayLayer.ABOVE_WIDGETS); setLayer(OverlayLayer.ABOVE_WIDGETS);
setPriority(OverlayPriority.HIGH); setPriority(OverlayPriority.HIGH);
setPosition(OverlayPosition.BOTTOM_RIGHT); setPosition(OverlayPosition.BOTTOM_RIGHT);
textComponent = new TextComponent(); textComponent = new TextComponent();
} }
@Override @Override

View File

@@ -10,13 +10,12 @@
package net.runelite.client.plugins.wildernesslocations; package net.runelite.client.plugins.wildernesslocations;
import com.google.inject.Provides;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import javax.inject.Inject; import javax.inject.Inject;
import com.google.inject.Provides;
import lombok.Getter; import lombok.Getter;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import net.runelite.api.Client; import net.runelite.api.Client;
@@ -34,7 +33,6 @@ import net.runelite.client.eventbus.Subscribe;
import net.runelite.client.input.KeyManager; import net.runelite.client.input.KeyManager;
import net.runelite.client.plugins.Plugin; import net.runelite.client.plugins.Plugin;
import net.runelite.client.plugins.PluginDescriptor; import net.runelite.client.plugins.PluginDescriptor;
import net.runelite.client.plugins.PluginManager;
import net.runelite.client.plugins.PluginType; import net.runelite.client.plugins.PluginType;
import net.runelite.client.ui.overlay.OverlayManager; import net.runelite.client.ui.overlay.OverlayManager;
import net.runelite.client.util.HotkeyListener; import net.runelite.client.util.HotkeyListener;
@@ -42,10 +40,11 @@ import net.runelite.client.util.WildernessLocation;
@Slf4j @Slf4j
@PluginDescriptor( @PluginDescriptor(
name = "Wild Locations", name = "Wild Locations",
description = "Indicates the players current location in the wild", description = "Indicates the players current location in the wild",
tags = {"Wildy", "Wilderness Location", "location", "loc", "pvp", "pklite"}, tags = {"Wildy", "Wilderness Location", "location", "loc", "pvp", "pklite"},
type = PluginType.PVP type = PluginType.PVP,
enabledByDefault = false
) )
public class WildernessLocationsPlugin extends Plugin public class WildernessLocationsPlugin extends Plugin
{ {
@@ -57,7 +56,7 @@ public class WildernessLocationsPlugin extends Plugin
OverlayManager overlayManager; OverlayManager overlayManager;
@Inject @Inject
private WildernessLocationsOverlay overlay = new WildernessLocationsOverlay(this.client, this); private WildernessLocationsOverlay overlay = new WildernessLocationsOverlay(this);
@Getter @Getter
private boolean renderLocation; private boolean renderLocation;
@@ -76,7 +75,6 @@ public class WildernessLocationsPlugin extends Plugin
private String oldChat = ""; private String oldChat = "";
private int currentCooldown = 0; private int currentCooldown = 0;
private final int COOLDOWN_TICKS = 30;
private WorldPoint worldPoint = null; private WorldPoint worldPoint = null;
private final HashMap<WorldArea, String> wildLocs = getLocationMap(); private final HashMap<WorldArea, String> wildLocs = getLocationMap();
@@ -154,7 +152,7 @@ public class WildernessLocationsPlugin extends Plugin
} }
} }
if (client.getLocalPlayer().getWorldLocation().getY() > if (client.getLocalPlayer().getWorldLocation().getY() >
(Objects.requireNonNull(closestArea).toWorldPoint().getY() + closestArea.getHeight())) (Objects.requireNonNull(closestArea).toWorldPoint().getY() + closestArea.getHeight()))
{ {
s = s + "N"; s = s + "N";
} }
@@ -167,7 +165,7 @@ public class WildernessLocationsPlugin extends Plugin
s = s + "W"; s = s + "W";
} }
if (client.getLocalPlayer().getWorldLocation().getX() > if (client.getLocalPlayer().getWorldLocation().getX() >
(closestArea.toWorldPoint().getX() + closestArea.getWidth())) (closestArea.toWorldPoint().getX() + closestArea.getWidth()))
{ {
s = s + "E"; s = s + "E";
} }
@@ -184,7 +182,7 @@ public class WildernessLocationsPlugin extends Plugin
{ {
HashMap<WorldArea, String> hashMap = new HashMap<>(); HashMap<WorldArea, String> hashMap = new HashMap<>();
Arrays.stream(WildernessLocation.values()).forEach(wildernessLocation -> Arrays.stream(WildernessLocation.values()).forEach(wildernessLocation ->
hashMap.put(wildernessLocation.getWorldArea(), wildernessLocation.getName())); hashMap.put(wildernessLocation.getWorldArea(), wildernessLocation.getName()));
return hashMap; return hashMap;
} }
@@ -234,6 +232,6 @@ public class WildernessLocationsPlugin extends Plugin
return; return;
} }
sendMessage("/World: " + client.getWorld() + " Location: " + location); sendMessage("/World: " + client.getWorld() + " Location: " + location);
currentCooldown = COOLDOWN_TICKS; currentCooldown = 30;
} }
} }

View File

@@ -33,17 +33,6 @@ import net.runelite.client.config.ConfigItem;
@ConfigGroup("zulrah") @ConfigGroup("zulrah")
public interface ZulrahConfig extends Config public interface ZulrahConfig extends Config
{ {
@ConfigItem(
position = 0,
keyName = "zulrahenable",
name = "Enable Zulrah Helper",
description = "Configures whether or not to enable Zulrah Helper."
)
default boolean EnableZulrah()
{
return true;
}
@ConfigItem( @ConfigItem(
position = 1, position = 1,
keyName = "zulrahprayenable", keyName = "zulrahprayenable",

View File

@@ -230,11 +230,6 @@ public class ZulrahPlugin extends Plugin
@Subscribe @Subscribe
public void onGameTick(GameTick event) public void onGameTick(GameTick event)
{ {
if (!config.EnableZulrah())
{
return;
}
if (phase4 && phases.size() == 11) if (phase4 && phases.size() == 11)
{ {
jadphase = 1; jadphase = 1;

View File

@@ -48,11 +48,7 @@ import java.lang.reflect.Field;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.net.URL; import java.net.URL;
import java.net.URLClassLoader; import java.net.URLClassLoader;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@@ -62,20 +58,18 @@ import java.util.jar.JarInputStream;
import java.util.jar.JarOutputStream; import java.util.jar.JarOutputStream;
import java.util.jar.Manifest; import java.util.jar.Manifest;
import java.util.logging.Logger; import java.util.logging.Logger;
import javassist.ClassPool;
import javassist.NotFoundException;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Named; import javax.inject.Named;
import javax.inject.Singleton; import javax.inject.Singleton;
import javassist.ClassPool;
import javassist.NotFoundException;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import net.runelite.client.RuneLite;
import static net.runelite.client.rs.ClientUpdateCheckMode.AUTO; import static net.runelite.client.rs.ClientUpdateCheckMode.AUTO;
import static net.runelite.client.rs.ClientUpdateCheckMode.NONE; import static net.runelite.client.rs.ClientUpdateCheckMode.NONE;
import static net.runelite.client.rs.ClientUpdateCheckMode.VANILLA; import static net.runelite.client.rs.ClientUpdateCheckMode.VANILLA;
import net.runelite.client.RuneLite;
import net.runelite.client.rs.bytecode.ByteCodeUtils;
import net.runelite.client.rs.bytecode.ByteCodePatcher; import net.runelite.client.rs.bytecode.ByteCodePatcher;
import net.runelite.client.rs.bytecode.ByteCodeUtils;
import net.runelite.client.rs.bytecode.Hooks; import net.runelite.client.rs.bytecode.Hooks;
import net.runelite.http.api.RuneLiteAPI; import net.runelite.http.api.RuneLiteAPI;
import okhttp3.Request; import okhttp3.Request;
@@ -87,10 +81,9 @@ import org.xeustechnologies.jcl.JarClassLoader;
@Singleton @Singleton
public class ClientLoader public class ClientLoader
{ {
public static File hooksFile = new File(RuneLite.RUNELITE_DIR+"/hooks-"+ RuneLiteAPI.getVersion() +"-.json"); public static File hooksFile = new File(RuneLite.RUNELITE_DIR + "/hooks-" + RuneLiteAPI.getVersion() + "-.json");
private final ClientConfigLoader clientConfigLoader; private final ClientConfigLoader clientConfigLoader;
private ClientUpdateCheckMode updateCheckMode; private ClientUpdateCheckMode updateCheckMode;
private JarOutputStream target;
private static String[] preotectedStuffs; private static String[] preotectedStuffs;
private static int stepCount; private static int stepCount;
@@ -114,14 +107,13 @@ public class ClientLoader
{ {
File injectedClientFile = ByteCodeUtils.injectedClientFile; File injectedClientFile = ByteCodeUtils.injectedClientFile;
File hijackedClientFile = ByteCodeUtils.hijackedClientFile; File hijackedClientFile = ByteCodeUtils.hijackedClientFile;
Manifest manifest = new Manifest(); Manifest manifest = new Manifest();
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
target = new JarOutputStream(new FileOutputStream(injectedClientFile), manifest); JarOutputStream target = new JarOutputStream(new FileOutputStream(injectedClientFile), manifest);
RSConfig config = clientConfigLoader.fetch(); RSConfig config = clientConfigLoader.fetch();
Map<String, byte[]> zipFile = new HashMap<>(); Map<String, byte[]> zipFile = new HashMap<>();
{ {
Certificate[] jagexCertificateChain = getJagexCertificateChain();
String codebase = config.getCodeBase(); String codebase = config.getCodeBase();
String initialJar = config.getInitialJar(); String initialJar = config.getInitialJar();
URL url = new URL(codebase + initialJar); URL url = new URL(codebase + initialJar);
@@ -133,7 +125,7 @@ public class ClientLoader
{ {
JarInputStream jis; JarInputStream jis;
jis = new JarInputStream(response.body().byteStream()); jis = new JarInputStream(response.body().byteStream());
byte[] tmp = new byte[4096]; byte[] tmp = new byte[4096];
ByteArrayOutputStream buffer = new ByteArrayOutputStream(756 * 1024); ByteArrayOutputStream buffer = new ByteArrayOutputStream(756 * 1024);
@@ -161,118 +153,132 @@ public class ClientLoader
} }
} }
if (updateCheckMode == AUTO) if (updateCheckMode == AUTO)
{
Map<String, String> hashes;
try (InputStream is = ClientLoader.class.getResourceAsStream("/patch/hashes.json"))
{ {
Map<String, String> hashes; hashes = new Gson().fromJson(new InputStreamReader(is), new TypeToken<HashMap<String, String>>()
try (InputStream is = ClientLoader.class.getResourceAsStream("/patch/hashes.json"))
{ {
hashes = new Gson().fromJson(new InputStreamReader(is), new TypeToken<HashMap<String, String>>() }.getType());
{ }
}.getType());
for (Map.Entry<String, String> file : hashes.entrySet())
{
byte[] bytes = zipFile.get(file.getKey());
String ourHash = null;
if (bytes != null)
{
ourHash = Hashing.sha512().hashBytes(bytes).toString();
} }
for (Map.Entry<String, String> file : hashes.entrySet()) if (!file.getValue().equals(ourHash))
{ {
byte[] bytes = zipFile.get(file.getKey()); if (hijackedClientFile.exists())
String ourHash = null;
if (bytes != null)
{ {
ourHash = Hashing.sha512().hashBytes(bytes).toString(); Logger.getAnonymousLogger().warning("[RuneLitePlus] Hash checking / Client patching skipped due to hijacked client.");
updateCheckMode = VANILLA;
break;
} }
else
if (!file.getValue().equals(ourHash))
{ {
if (hijackedClientFile.exists()) { log.info("{} had a hash mismatch; falling back to vanilla. {} != {}", file.getKey(), file.getValue(), ourHash);
Logger.getAnonymousLogger().warning("[RuneLitePlus] Hash checking / Client patching skipped due to hijacked client."); log.info("Client is outdated!");
updateCheckMode = VANILLA; updateCheckMode = VANILLA;
break; break;
} else {
log.info("{} had a hash mismatch; falling back to vanilla. {} != {}", file.getKey(), file.getValue(), ourHash);
log.info("Client is outdated!");
updateCheckMode = VANILLA;
break;
}
} }
} }
} }
}
if (updateCheckMode == AUTO) if (updateCheckMode == AUTO)
{
ByteArrayOutputStream patchOs = new ByteArrayOutputStream(756 * 1024);
int patchCount = 0;
for (Map.Entry<String, byte[]> file : zipFile.entrySet())
{ {
ByteArrayOutputStream patchOs = new ByteArrayOutputStream(756 * 1024); byte[] bytes;
int patchCount = 0; try (InputStream is = ClientLoader.class.getResourceAsStream("/patch/" + file.getKey() + ".bs"))
for (Map.Entry<String, byte[]> file : zipFile.entrySet())
{ {
byte[] bytes; if (is == null)
try (InputStream is = ClientLoader.class.getResourceAsStream("/patch/" + file.getKey() + ".bs"))
{ {
if (is == null) continue;
{
continue;
}
bytes = ByteStreams.toByteArray(is);
} }
patchOs.reset(); bytes = ByteStreams.toByteArray(is);
Patch.patch(file.getValue(), bytes, patchOs);
file.setValue(patchOs.toByteArray());
++patchCount;
if (!file.getKey().startsWith("META")) {
add(file.getValue(), file.getKey(), target);
}
} }
if (target!=null)
target.close();
log.info("Patched {} classes", patchCount); patchOs.reset();
Patch.patch(file.getValue(), bytes, patchOs);
file.setValue(patchOs.toByteArray());
++patchCount;
if (!file.getKey().startsWith("META"))
{
add(file.getValue(), file.getKey(), target);
}
} }
if (hooksFile.exists()) { target.close();
ByteCodePatcher.classPool = new ClassPool(true);
ByteCodePatcher.classPool.appendClassPath(RuneLite.RUNELITE_DIR+"/injectedClient-"+ RuneLiteAPI.getVersion() +"-.jar");
Gson gson = new Gson();
Hooks hooks = gson.fromJson(new BufferedReader(new FileReader(hooksFile)), Hooks.class);
if (hooks.clientInstance.equals("")|| log.info("Patched {} classes", patchCount);
hooks.projectileClass.equals("") || }
hooks.actorClass.equals("") || if (hooksFile.exists())
hooks.playerClass.equals("")) { {
System.out.println("[RuneLitePlus] Bad hooks, re-scraping."); ByteCodePatcher.classPool = new ClassPool(true);
stepCount = getStepCount(ByteCodeUtils.injectedClientFile.getPath()); ByteCodePatcher.classPool.appendClassPath(RuneLite.RUNELITE_DIR + "/injectedClient-" + RuneLiteAPI.getVersion() + "-.jar");
ByteCodePatcher.clientInstance = initHookScrape(ByteCodeUtils.injectedClientFile.getPath()); Gson gson = new Gson();
ByteCodePatcher.findHooks(injectedClientFile.getPath()); Hooks hooks = gson.fromJson(new BufferedReader(new FileReader(hooksFile)), Hooks.class);
} else {
ByteCodePatcher.clientInstance = hooks.clientInstance;
ByteCodePatcher.applyHooks(ByteCodeUtils.injectedClientFile, hooks);
System.out.println("[RuneLitePlus] Loaded hooks");
}
} else { if (hooks.clientInstance.equals("") ||
System.out.println("[RuneLitePlus] Hooks file not found, scraping hooks."); hooks.clientClass.equals("") ||
hooks.projectileClass.equals("") ||
hooks.actorClass.equals("") ||
hooks.playerClass.equals(""))
{
log.info("[RuneLitePlus] Bad hooks, re-scraping.");
stepCount = getStepCount(ByteCodeUtils.injectedClientFile.getPath()); stepCount = getStepCount(ByteCodeUtils.injectedClientFile.getPath());
ByteCodePatcher.clientInstance = initHookScrape(ByteCodeUtils.injectedClientFile.getPath()); ByteCodePatcher.clientInstance = initHookScrape(ByteCodeUtils.injectedClientFile.getPath());
ByteCodePatcher.hooks.protectedStuff = preotectedStuffs;
ByteCodePatcher.findHooks(injectedClientFile.getPath()); ByteCodePatcher.findHooks(injectedClientFile.getPath());
} }
else
{
ByteCodePatcher.clientInstance = hooks.clientInstance;
ByteCodePatcher.applyHooks(ByteCodeUtils.injectedClientFile, hooks);
log.info("[RuneLitePlus] Loaded hooks");
}
}
else
{
log.info("[RuneLitePlus] Hooks file not found, scraping hooks.");
stepCount = getStepCount(ByteCodeUtils.injectedClientFile.getPath());
ByteCodePatcher.clientInstance = initHookScrape(ByteCodeUtils.injectedClientFile.getPath());
ByteCodePatcher.hooks.protectedStuff = preotectedStuffs;
ByteCodePatcher.findHooks(injectedClientFile.getPath());
}
Map<String, byte[]> zipFile2 = new HashMap<>(); Map<String, byte[]> zipFile2 = new HashMap<>();
JarInputStream jis = new JarInputStream(new FileInputStream(hijackedClientFile)); JarInputStream jis = new JarInputStream(new FileInputStream(hijackedClientFile));
byte[] tmp = new byte[4096]; byte[] tmp = new byte[4096];
ByteArrayOutputStream buffer = new ByteArrayOutputStream(756 * 1024); ByteArrayOutputStream buffer = new ByteArrayOutputStream(756 * 1024);
for (; ; ) { for (; ; )
{
JarEntry metadata = jis.getNextJarEntry(); JarEntry metadata = jis.getNextJarEntry();
if (metadata == null) { if (metadata == null)
{
break; break;
} }
buffer.reset(); buffer.reset();
for (; ; ) { for (; ; )
{
int n = jis.read(tmp); int n = jis.read(tmp);
if (n <= -1) { if (n <= -1)
{
break; break;
} }
buffer.write(tmp, 0, n); buffer.write(tmp, 0, n);
@@ -306,7 +312,7 @@ public class ClientLoader
return rs; return rs;
} }
catch (IOException | ClassNotFoundException | InstantiationException | IllegalAccessException catch (IOException | ClassNotFoundException | InstantiationException | IllegalAccessException
| CompressorException | InvalidHeaderException | CertificateException | SecurityException e) | CompressorException | InvalidHeaderException | SecurityException e)
{ {
if (e instanceof ClassNotFoundException) if (e instanceof ClassNotFoundException)
{ {
@@ -317,142 +323,175 @@ public class ClientLoader
log.error("Error loading RS!", e); log.error("Error loading RS!", e);
return null; return null;
} catch (NotFoundException e) { }
catch (NotFoundException e)
{
e.printStackTrace(); e.printStackTrace();
} }
return null; return null;
} }
private void add(byte[] bytes, String entryName ,JarOutputStream target) throws IOException { private void add(byte[] bytes, String entryName, JarOutputStream target) throws IOException
BufferedInputStream in = null;
try {
JarEntry entry = new JarEntry(entryName);
target.putNextEntry(entry);
target.write(bytes);
target.closeEntry();
} finally {
if (in != null)
in.close();
}
}
private static Certificate[] getJagexCertificateChain() throws CertificateException
{ {
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); JarEntry entry = new JarEntry(entryName);
Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(ClientLoader.class.getResourceAsStream("jagex.crt")); target.putNextEntry(entry);
return certificates.toArray(new Certificate[certificates.size()]); target.write(bytes);
target.closeEntry();
} }
public static int getStepCount(String jarFile) { private static int getStepCount(String jarFile)
{
int stepCount = 0; int stepCount = 0;
JarClassLoader jcl = new JarClassLoader(); JarClassLoader jcl = new JarClassLoader();
try { try
{
ClassPool classPool = new ClassPool(true); ClassPool classPool = new ClassPool(true);
classPool.appendClassPath(RuneLite.RUNELITE_DIR+"/injectedClient-"+ RuneLiteAPI.getVersion() +"-.jar"); classPool.appendClassPath(RuneLite.RUNELITE_DIR + "/injectedClient-" + RuneLiteAPI.getVersion() + "-.jar");
} catch (NotFoundException e) { }
catch (NotFoundException e)
{
e.printStackTrace(); e.printStackTrace();
} }
try { try
{
jcl.add(new FileInputStream(jarFile)); jcl.add(new FileInputStream(jarFile));
try (JarInputStream in = new JarInputStream(new BufferedInputStream(new FileInputStream(jarFile)))) { try (JarInputStream in = new JarInputStream(new BufferedInputStream(new FileInputStream(jarFile))))
{
JarEntry entry; JarEntry entry;
while ((entry = in.getNextJarEntry()) != null) { while ((entry = in.getNextJarEntry()) != null)
if (entry.getName().endsWith(".class")) { {
if (entry.getName().endsWith(".class"))
{
stepCount++; stepCount++;
} }
} }
} }
} catch (Exception e) { }
catch (Exception e)
{
e.printStackTrace(); e.printStackTrace();
} }
return stepCount; return stepCount;
} }
public static String initHookScrape(String jarFile) { private static String initHookScrape(String jarFile)
{
int currentStep = 0; int currentStep = 0;
RuneLite.splashScreen.setMessage("Analyzing injected client"); RuneLite.splashScreen.setMessage("Analyzing injected client");
List protectedStuff = new ArrayList<String>(); List<String> protectedStuff = new ArrayList<>();
String clientInstance = ""; String clientInstance = "";
JarClassLoader jcl = new JarClassLoader(); JarClassLoader jcl = new JarClassLoader();
try { try
ClassPool classPool = new ClassPool(true); {
classPool.appendClassPath(RuneLite.RUNELITE_DIR+"/injectedClient-"+ RuneLiteAPI.getVersion() +"-.jar"); ClassPool classPool = new ClassPool(true);
} catch (NotFoundException e) { classPool.appendClassPath(RuneLite.RUNELITE_DIR + "/injectedClient-" + RuneLiteAPI.getVersion() + "-.jar");
e.printStackTrace(); }
} catch (NotFoundException e)
{
e.printStackTrace();
}
try { try
jcl.add(new FileInputStream(jarFile)); {
try (JarInputStream in = new JarInputStream(new BufferedInputStream(new FileInputStream(jarFile)))) { jcl.add(new FileInputStream(jarFile));
JarEntry entry; try (JarInputStream in = new JarInputStream(new BufferedInputStream(new FileInputStream(jarFile))))
while ((entry = in.getNextJarEntry()) != null) { {
if (entry.getName().endsWith(".class")) { JarEntry entry;
File temp = new File(jarFile); while ((entry = in.getNextJarEntry()) != null)
ClassLoader cl = ClassLoader.getSystemClassLoader(); {
try { if (entry.getName().endsWith(".class"))
URLClassLoader child = new URLClassLoader( {
new URL[] {temp.toURI().toURL()}, File temp = new File(jarFile);
cl ClassLoader cl = ClassLoader.getSystemClassLoader();
); try
try { {
Class classToLoad = Class.forName(entry.getName().replace(".class", ""), false, child); URLClassLoader child = new URLClassLoader(
RuneLite.splashScreen.setSubMessage(entry.getName()); new URL[]{temp.toURI().toURL()},
currentStep++; cl
RuneLite.splashScreen.setProgress(currentStep, stepCount); );
JarClassLoader jcl2 = new JarClassLoader(); try
try { {
jcl2.add(new FileInputStream(ByteCodeUtils.injectedClientFile)); Class classToLoad = Class.forName(entry.getName().replace(".class", ""), false, child);
Field[] fields = classToLoad.getDeclaredFields(); RuneLite.splashScreen.setSubMessage(entry.getName());
Method[] methods = classToLoad.getDeclaredMethods(); currentStep++;
for (Field f : fields) { RuneLite.splashScreen.setProgress(currentStep, stepCount);
try { JarClassLoader jcl2 = new JarClassLoader();
if (f.getName().contains("$")) { try
System.out.println(classToLoad.getName()+"."+f.getName()); {
protectedStuff.add(classToLoad.getName()+"."+f.getName()); jcl2.add(new FileInputStream(ByteCodeUtils.injectedClientFile));
Field[] fields = classToLoad.getDeclaredFields();
Method[] methods = classToLoad.getDeclaredMethods();
for (Field f : fields)
{
try
{
if (f.getName().contains("$"))
{
log.info(classToLoad.getName() + "." + f.getName());
protectedStuff.add(classToLoad.getName() + "." + f.getName());
} }
if (f.getType().getName()=="client") { if (f.getType().getName().equals("client"))
ByteCodePatcher.hooks.clientInstance = classToLoad.getName()+"."+f.getName(); {
clientInstance = classToLoad.getName()+"."+f.getName(); ByteCodePatcher.hooks.clientInstance = classToLoad.getName() + "." + f.getName();
} clientInstance = classToLoad.getName() + "." + f.getName();
} catch (Exception e) { }
e.printStackTrace(); }
} catch (Exception e)
} {
for (Method m : methods) { e.printStackTrace();
RuneLite.splashScreen.setSubMessage("Checked "+m.getName());
if (m.getName().contains("$")) {
protectedStuff.add(classToLoad.getName()+"."+m.getName());
} }
} }
RuneLite.splashScreen.setProgress(currentStep, stepCount); for (Method m : methods)
} catch (FileNotFoundException e) { {
e.printStackTrace(); RuneLite.splashScreen.setSubMessage("Checked " + m.getName());
} if (m.getName().contains("$"))
} catch (Exception e) { {
e.printStackTrace(); protectedStuff.add(classToLoad.getName() + "." + m.getName());
} }
}
RuneLite.splashScreen.setProgress(currentStep, stepCount);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
catch (Exception e)
{
e.printStackTrace();
}
RuneLite.splashScreen.setProgress(2, 5); RuneLite.splashScreen.setProgress(2, 5);
} catch (Exception e) { }
e.printStackTrace(); catch (Exception e)
System.out.println("Class not found: "+entry.getName()); {
} e.printStackTrace();
} log.info("Class not found: " + entry.getName());
} }
} }
} catch (Exception e) { }
e.printStackTrace(); }
} }
int i = 0; catch (Exception e)
for (Object o : protectedStuff) { {
e.printStackTrace();
}
int i = 0;
for (String ignored : protectedStuff)
{
i++; i++;
} }
preotectedStuffs = new String[i];
i = 0; preotectedStuffs = new String[i];
for (Object o : protectedStuff) { i = 0;
preotectedStuffs[i] = (String) o;
for (String o : protectedStuff)
{
preotectedStuffs[i] = o;
i++; i++;
} }
return clientInstance;
} return clientInstance;
}
} }

View File

@@ -2,20 +2,6 @@ package net.runelite.client.rs.bytecode;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.NotFoundException;
import net.runelite.client.RuneLite;
import net.runelite.client.rs.ClientLoader;
import net.runelite.client.rs.bytecode.transformers.ActorTransform;
import net.runelite.client.rs.bytecode.transformers.ClientTransform;
import net.runelite.client.rs.bytecode.transformers.ErrorTransform;
import net.runelite.client.rs.bytecode.transformers.PlayerTransform;
import net.runelite.client.rs.bytecode.transformers.ProjectileTransform;
import net.runelite.http.api.RuneLiteAPI;
import org.xeustechnologies.jcl.JarClassLoader;
import javax.swing.*;
import java.io.BufferedInputStream; import java.io.BufferedInputStream;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
@@ -29,200 +15,284 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.jar.JarEntry; import java.util.jar.JarEntry;
import java.util.jar.JarInputStream; import java.util.jar.JarInputStream;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.NotFoundException;
import lombok.extern.slf4j.Slf4j;
import net.runelite.client.RuneLite;
import net.runelite.client.rs.ClientLoader;
import net.runelite.client.rs.bytecode.transformers.ActorTransform;
import net.runelite.client.rs.bytecode.transformers.ClientTransform;
import net.runelite.client.rs.bytecode.transformers.ErrorTransform;
import net.runelite.client.rs.bytecode.transformers.PlayerTransform;
import net.runelite.client.rs.bytecode.transformers.ProjectileTransform;
import net.runelite.http.api.RuneLiteAPI;
import org.xeustechnologies.jcl.JarClassLoader;
public class ByteCodePatcher { @Slf4j
public class ByteCodePatcher
{
public static List<CtClass> modifiedClasses = new ArrayList<>(); public static List<CtClass> modifiedClasses = new ArrayList<>();
public static Hooks hooks = new Hooks(); public static Hooks hooks = new Hooks();
public static String clientInstance; public static String clientInstance;
public static JarClassLoader jcl = new JarClassLoader(); private static JarClassLoader jcl = new JarClassLoader();
public static ClassPool classPool = null; public static ClassPool classPool = null;
public static ClassLoader cl = ClassLoader.getSystemClassLoader(); private static ClassLoader cl = ClassLoader.getSystemClassLoader();
public static int classCount = 0; private static int classCount = 0;
public static void applyHooks(File jf, Hooks hooks) { public static void applyHooks(File jf, Hooks hooks)
{
RuneLite.splashScreen.setProgress(0, 5); RuneLite.splashScreen.setProgress(0, 5);
RuneLite.splashScreen.setMessage("Applying cached bytecode patches..."); RuneLite.splashScreen.setMessage("Applying cached bytecode patches...");
try { try
{
URLClassLoader child = new URLClassLoader( URLClassLoader child = new URLClassLoader(
new URL[] {jf.toURI().toURL()}, new URL[]{jf.toURI().toURL()},
cl cl
); );
try { try
{
RuneLite.splashScreen.setSubMessage("Transforming Client");
Class clientClass = Class.forName(hooks.clientClass, false, child);
transformClient(clientClass);
RuneLite.splashScreen.setProgress(1, 5);
RuneLite.splashScreen.setSubMessage("Transforming Actor"); RuneLite.splashScreen.setSubMessage("Transforming Actor");
Class actorClass = Class.forName(hooks.actorClass, false, child); Class actorClass = Class.forName(hooks.actorClass, false, child);
transformActor(actorClass); transformActor(actorClass);
RuneLite.splashScreen.setProgress(1, 5); RuneLite.splashScreen.setProgress(2, 5);
RuneLite.splashScreen.setSubMessage("Transforming Projectile"); RuneLite.splashScreen.setSubMessage("Transforming Projectile");
Class projectileClass = Class.forName(hooks.projectileClass, false, child); Class projectileClass = Class.forName(hooks.projectileClass, false, child);
transformProjectile(projectileClass); transformProjectile(projectileClass);
RuneLite.splashScreen.setProgress(2, 5); RuneLite.splashScreen.setProgress(3, 5);
RuneLite.splashScreen.setSubMessage("Transforming Player"); RuneLite.splashScreen.setSubMessage("Transforming Player");
Class playerClass = Class.forName(hooks.playerClass, false, child); Class playerClass = Class.forName(hooks.playerClass, false, child);
transformPlayer(playerClass); transformPlayer(playerClass);
RuneLite.splashScreen.setProgress(3, 5);
RuneLite.splashScreen.setSubMessage("Transforming Client");
Class clientClass = Class.forName("client", false, child);
transformClient(clientClass);
RuneLite.splashScreen.setProgress(4, 5); RuneLite.splashScreen.setProgress(4, 5);
//Odds and ends // Odds and ends
RuneLite.splashScreen.setSubMessage("Transforming Error method"); RuneLite.splashScreen.setSubMessage("Transforming Error method");
ErrorTransform et = new ErrorTransform(); transformStackTrace();
et.modify(null);
RuneLite.splashScreen.setProgress(5, 5); RuneLite.splashScreen.setProgress(5, 5);
RuneLite.splashScreen.setSubMessage(""); RuneLite.splashScreen.setSubMessage("");
ByteCodeUtils.updateHijackedJar(); ByteCodeUtils.updateHijackedJar();
} catch (Exception e) { }
e.printStackTrace(); catch (Exception e)
{
// e.printStackTrace();
} }
} catch (Exception e) { }
e.printStackTrace(); catch (Exception e)
{
// e.printStackTrace();
} }
} }
public static void findHooks(String jf) { public static void findHooks(String jf)
{
RuneLite.splashScreen.setMessage("Hijacking Classes"); RuneLite.splashScreen.setMessage("Hijacking Classes");
try { try
{
classPool = new ClassPool(true); classPool = new ClassPool(true);
classPool.appendClassPath(RuneLite.RUNELITE_DIR+"/injectedClient-"+ RuneLiteAPI.getVersion() +"-.jar"); classPool.appendClassPath(RuneLite.RUNELITE_DIR + "/injectedClient-" + RuneLiteAPI.getVersion() + "-.jar");
} catch (NotFoundException e) { }
catch (NotFoundException e)
{
e.printStackTrace(); e.printStackTrace();
} }
try { try
{
jcl.add(new FileInputStream(jf)); jcl.add(new FileInputStream(jf));
try (JarInputStream in = new JarInputStream(new BufferedInputStream(new FileInputStream(jf)))) { try (JarInputStream in = new JarInputStream(new BufferedInputStream(new FileInputStream(jf))))
{
JarEntry entry; JarEntry entry;
while ((entry = in.getNextJarEntry()) != null) { while ((entry = in.getNextJarEntry()) != null)
if (entry.getName().endsWith(".class")) { {
if (entry.getName().endsWith(".class"))
{
classCount++; classCount++;
} }
} }
} }
int i = 0; int i = 0;
jcl.add(new FileInputStream(jf)); jcl.add(new FileInputStream(jf));
try (JarInputStream in = new JarInputStream(new BufferedInputStream(new FileInputStream(jf)))) { try (JarInputStream in = new JarInputStream(new BufferedInputStream(new FileInputStream(jf))))
{
JarEntry entry; JarEntry entry;
while ((entry = in.getNextJarEntry()) != null) { while ((entry = in.getNextJarEntry()) != null)
if (entry.getName().endsWith(".class")) { {
if (entry.getName().endsWith(".class"))
{
RuneLite.splashScreen.setProgress(i, classCount); RuneLite.splashScreen.setProgress(i, classCount);
RuneLite.splashScreen.setSubMessage("Checking "+entry.getName()); RuneLite.splashScreen.setSubMessage("Checking " + entry.getName());
checkClasses(new File(jf), entry); checkClasses(new File(jf), entry);
i++; i++;
} }
} }
} }
} catch (Exception e) { }
catch (Exception e)
{
e.printStackTrace(); e.printStackTrace();
} }
Gson gson = new GsonBuilder().setPrettyPrinting().create(); Gson gson = new GsonBuilder().setPrettyPrinting().create();
try { try
{
Writer writer = new FileWriter(ClientLoader.hooksFile); Writer writer = new FileWriter(ClientLoader.hooksFile);
gson.toJson(hooks, writer); gson.toJson(hooks, writer);
writer.flush(); writer.flush();
writer.close(); writer.close();
} catch (IOException e) { }
catch (IOException e)
{
e.printStackTrace(); e.printStackTrace();
} }
ByteCodeUtils.updateHijackedJar(); ByteCodeUtils.updateHijackedJar();
} }
public static void checkClasses(File jf, JarEntry entry) { private static void checkClasses(File jf, JarEntry entry)
try { {
try
{
URLClassLoader child = new URLClassLoader( URLClassLoader child = new URLClassLoader(
new URL[] {jf.toURI().toURL()}, new URL[]{jf.toURI().toURL()},
cl cl
); );
try { try
{
Class classToLoad = Class.forName(entry.getName().replace(".class", ""), false, child); Class classToLoad = Class.forName(entry.getName().replace(".class", ""), false, child);
checkClient(classToLoad);
checkActor(classToLoad); checkActor(classToLoad);
checkProjectile(classToLoad); checkProjectile(classToLoad);
checkPlayer(classToLoad); checkPlayer(classToLoad);
} catch (Exception e) { }
e.printStackTrace(); catch (Exception e)
{
// e.printStackTrace();
} }
} catch (Exception e) { }
e.printStackTrace(); catch (Exception e)
System.out.println("Class not found: "+entry.getName()); {
// e.printStackTrace();
// System.out.println("Class not found: "+entry.getName());
} }
} }
public static void checkActor(Class current) { private static void checkClient(Class current)
try { {
Method method = current.getDeclaredMethod("setCombatInfo", new Class[] { int.class, int.class, int.class, int.class, int.class, int.class }); try
if (method!=null) { {
Method method = current.getDeclaredMethod("getProjectiles");
if (method != null)
{
hooks.clientClass = current.getName();
log.info("[RuneLitePlus] Transforming Client at class: " + current.getName());
ClientTransform ct = new ClientTransform();
ct.modify(current);
}
}
catch (NoSuchMethodException | NoClassDefFoundError e)
{
// e.printStackTrace();
}
}
private static void transformClient(Class client)
{
log.info("[RuneLitePlus] Transforming Client at class: " + client.getName());
ClientTransform ct = new ClientTransform();
ct.modify(client);
}
private static void checkActor(Class current)
{
try
{
Method method = current.getDeclaredMethod("setCombatInfo", new Class[]{int.class, int.class, int.class, int.class, int.class, int.class});
if (method != null)
{
hooks.actorClass = current.getName(); hooks.actorClass = current.getName();
System.out.println("[RuneLitePlus] Transforming Actor at class: "+current.getName()); log.info("[RuneLitePlus] Transforming Actor at class: " + current.getName());
ActorTransform at = new ActorTransform(); ActorTransform at = new ActorTransform();
at.modify(current); at.modify(current);
} }
} catch (NoSuchMethodException e) { }
//e.printStackTrace(); catch (NoSuchMethodException | NoClassDefFoundError e)
} catch (NoClassDefFoundError e) { {
//e.printStackTrace(); // e.printStackTrace();
} }
} }
public static void transformActor(Class actor) { private static void transformActor(Class actor)
System.out.println("[RuneLitePlus] Transforming Actor at class: "+actor.getName()); {
log.info("[RuneLitePlus] Transforming Actor at class: " + actor.getName());
ActorTransform at = new ActorTransform(); ActorTransform at = new ActorTransform();
at.modify(actor); at.modify(actor);
} }
public static void checkProjectile(Class current) { private static void checkProjectile(Class current)
try { {
Method method = current.getDeclaredMethod("projectileMoved", new Class[] { int.class, int.class, int.class, int.class}); try
if (method!=null) { {
Method method = current.getDeclaredMethod("projectileMoved", new Class[]{int.class, int.class, int.class, int.class});
if (method != null)
{
hooks.projectileClass = current.getName(); hooks.projectileClass = current.getName();
System.out.println("[RuneLitePlus] Transforming Projectile at class: "+current.getName()); log.info("[RuneLitePlus] Transforming Projectile at class: " + current.getName());
ProjectileTransform pt = new ProjectileTransform(); ProjectileTransform pt = new ProjectileTransform();
pt.modify(current); pt.modify(current);
} }
} catch (NoSuchMethodException e) { }
//e.printStackTrace(); catch (NoSuchMethodException | NoClassDefFoundError e)
} catch (NoClassDefFoundError e) { {
//e.printStackTrace(); // e.printStackTrace();
} }
} }
public static void transformProjectile(Class projectile) { private static void transformProjectile(Class projectile)
System.out.println("[RuneLitePlus] Transforming Projectile at class: "+projectile.getName()); {
log.info("[RuneLitePlus] Transforming Projectile at class: " + projectile.getName());
ProjectileTransform pt = new ProjectileTransform(); ProjectileTransform pt = new ProjectileTransform();
pt.modify(projectile); pt.modify(projectile);
} }
public static void checkPlayer(Class current) { private static void checkPlayer(Class current)
try { {
try
{
Method method = current.getDeclaredMethod("getSkullIcon"); Method method = current.getDeclaredMethod("getSkullIcon");
if (method!=null) { if (method != null)
{
hooks.playerClass = current.getName(); hooks.playerClass = current.getName();
System.out.println("[RuneLitePlus] Transforming Player at class: "+current.getName()); log.info("[RuneLitePlus] Transforming Player at class: " + current.getName());
PlayerTransform pt = new PlayerTransform(); PlayerTransform pt = new PlayerTransform();
pt.modify(current); pt.modify(current);
} }
} catch (NoSuchMethodException e) { }
//e.printStackTrace(); catch (NoSuchMethodException | NoClassDefFoundError e)
} catch (NoClassDefFoundError e) { {
//e.printStackTrace(); // e.printStackTrace();
} }
} }
public static void transformPlayer(Class player) { private static void transformPlayer(Class player)
System.out.println("[RuneLitePlus] Transforming Player at class: "+player.getName()); {
log.info("[RuneLitePlus] Transforming Player at class: " + player.getName());
PlayerTransform pt = new PlayerTransform(); PlayerTransform pt = new PlayerTransform();
pt.modify(player); pt.modify(player);
} }
public static void transformClient(Class clazz) { private static void transformStackTrace()
System.out.println("[RuneLitePlus] Transforming Client"); {
ClientTransform bt = new ClientTransform(); log.info("[RuneLitePlus] Transforming Stack Trace");
bt.modify(clazz); ErrorTransform et = new ErrorTransform();
et.modify(null);
} }
} }

View File

@@ -1,9 +1,5 @@
package net.runelite.client.rs.bytecode; package net.runelite.client.rs.bytecode;
import javassist.CtClass;
import net.runelite.client.RuneLite;
import net.runelite.http.api.RuneLiteAPI;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;
@@ -19,99 +15,127 @@ import java.util.jar.JarOutputStream;
import java.util.jar.Manifest; import java.util.jar.Manifest;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipFile; import java.util.zip.ZipFile;
import javassist.CtClass;
import net.runelite.client.RuneLite;
import net.runelite.http.api.RuneLiteAPI;
public class ByteCodeUtils { public class ByteCodeUtils
//TODO: Write method to delete old revision injected clients. {
public static File injectedClientFile = new File(RuneLite.RUNELITE_DIR+"/injectedClient-"+ RuneLiteAPI.getVersion() +"-.jar"); //TODO: Write method to delete old revision injected clients.
public static File hijackedClientFile = new File(RuneLite.RUNELITE_DIR+"/hijackedClient-"+ RuneLiteAPI.getVersion() +"-.jar"); public static File injectedClientFile = new File(RuneLite.RUNELITE_DIR + "/injectedClient-" + RuneLiteAPI.getVersion() + "-.jar");
public static File hijackedClientFile = new File(RuneLite.RUNELITE_DIR + "/hijackedClient-" + RuneLiteAPI.getVersion() + "-.jar");
public static JarOutputStream target; public static JarOutputStream target;
public static void updateHijackedJar() { static void updateHijackedJar()
Manifest manifest = new Manifest(); {
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); Manifest manifest = new Manifest();
try { manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
target = new JarOutputStream(new FileOutputStream(hijackedClientFile), manifest); try
} catch (IOException e) { {
e.printStackTrace(); target = new JarOutputStream(new FileOutputStream(hijackedClientFile), manifest);
} }
try { catch (IOException e)
List<String> classesToSkip = new ArrayList<>(); {
for (CtClass ct : ByteCodePatcher.modifiedClasses) { e.printStackTrace();
classesToSkip.add(ct.getName()); }
} try
{
JarFile original = new JarFile(injectedClientFile);
Enumeration<JarEntry> entries = original.entries();
while (entries.hasMoreElements())
{
JarEntry entry = entries.nextElement();
boolean skip = false;
for (CtClass ct : ByteCodePatcher.modifiedClasses)
{
if ((ct.getName() + ".class").equals(entry.getName()))
{
skip = true;
}
}
if (!skip)
{
add(entry);
}
}
JarFile original = new JarFile(injectedClientFile); for (CtClass ct : ByteCodePatcher.modifiedClasses)
Enumeration<JarEntry> entries = original.entries(); {
while (entries.hasMoreElements()) { add(ct);
JarEntry entry = entries.nextElement(); }
boolean skip = false;
for (CtClass ct : ByteCodePatcher.modifiedClasses) {
if ((ct.getName()+".class").equals(entry.getName())) {
skip = true;
}
}
if (!skip)
add(entry);
}
for (CtClass ct : ByteCodePatcher.modifiedClasses) { target.close();
add(ct); }
} catch (Exception e)
{
e.printStackTrace();
}
}
target.close(); private static void add(CtClass ct)
} catch (Exception e) { {
e.printStackTrace(); try
} {
} JarEntry newEntry = new JarEntry(ct.getName() + ".class");
target.putNextEntry(newEntry);
target.write(ct.toBytecode());
target.closeEntry();
}
catch (Exception e)
{
e.printStackTrace();
}
}
private static void add(CtClass ct) { private static void add(JarEntry entry) throws IOException
try { {
JarEntry newEntry = new JarEntry(ct.getName()+".class"); try
target.putNextEntry(newEntry); {
target.write(ct.toBytecode()); if (!entry.getName().startsWith("META") && !entry.getName().equals(""))
target.closeEntry(); {
} catch (Exception e) { target.putNextEntry(entry);
e.printStackTrace(); target.write(getBytesFromZipFile(entry.getName()));
} target.closeEntry();
} }
}
catch (Exception e)
{
e.printStackTrace();
}
}
private static void add(JarEntry entry) throws IOException { private static byte[] getBytesFromZipFile(String entryName)
try { {
if (!entry.getName().startsWith("META")&&!entry.getName().equals("")) { ZipFile zipFile;
target.putNextEntry(entry); try
target.write(getBytesFromZipFile(entry.getName())); {
target.closeEntry(); zipFile = new ZipFile(injectedClientFile);
} Enumeration<? extends ZipEntry> entries = zipFile.entries();
} catch (Exception e) {
e.printStackTrace();
}
}
public static byte[] getBytesFromZipFile(String entryName) { while (entries.hasMoreElements())
ZipFile zipFile; {
try { ZipEntry entry = entries.nextElement();
zipFile = new ZipFile(injectedClientFile); if (entry.getName().equals(entryName))
Enumeration<? extends ZipEntry> entries = zipFile.entries(); {
InputStream stream = zipFile.getInputStream(entry);
while(entries.hasMoreElements()){ ByteArrayOutputStream buffer = new ByteArrayOutputStream();
ZipEntry entry = entries.nextElement(); int nRead;
if (entry.getName().equals(entryName)) { byte[] data = new byte[1024];
InputStream stream = zipFile.getInputStream(entry); while ((nRead = stream.read(data, 0, data.length)) != -1)
{
ByteArrayOutputStream buffer = new ByteArrayOutputStream(); buffer.write(data, 0, nRead);
int nRead; }
byte[] data = new byte[1024]; buffer.flush();
while ((nRead = stream.read(data, 0, data.length)) != -1) { return buffer.toByteArray();
buffer.write(data, 0, nRead); }
} }
buffer.flush(); }
return buffer.toByteArray(); catch (IOException e)
} {
} e.printStackTrace();
} catch (IOException e) { }
e.printStackTrace(); return null;
} }
return null;
}
} }

View File

@@ -7,6 +7,7 @@ public class Hooks {
public String projectileClass = ""; public String projectileClass = "";
public String playerClass = ""; public String playerClass = "";
public String[] protectedStuff; public String[] protectedStuff;
public String clientClass = "";
public Hooks() { public Hooks() {
} }

View File

@@ -5,66 +5,102 @@ import javassist.CtClass;
import javassist.CtMethod; import javassist.CtMethod;
import javassist.CtNewMethod; import javassist.CtNewMethod;
import javassist.NotFoundException; import javassist.NotFoundException;
import lombok.extern.slf4j.Slf4j;
import net.runelite.client.rs.bytecode.ByteCodePatcher; import net.runelite.client.rs.bytecode.ByteCodePatcher;
public class ActorTransform implements Transform { @Slf4j
private CtClass ct; public class ActorTransform implements Transform
{
private CtClass ct;
@Override @Override
public void modify(Class actor) { public void modify(Class actor)
try {
ct = ByteCodePatcher.classPool.get(actor.getName());
transformGetAnimation();
transformAnimationChanged();
transformGraphicChanged();
ByteCodePatcher.modifiedClasses.add(ct);
} catch (CannotCompileException | NotFoundException e) {
e.printStackTrace();
}
}
private void transformGetAnimation() throws CannotCompileException, NotFoundException
{ {
CtMethod protectedAnimation = ct.getDeclaredMethod("1protect$getRsAnimation"); try
ct.removeMethod(protectedAnimation); {
ct = ByteCodePatcher.classPool.get(actor.getName());
protectedAnimation.setName("getRsAnimation"); transformGetAnimation();
ct.addMethod(protectedAnimation); transformAnimationChanged();
transformGraphicChanged();
CtMethod getAnimation = ct.getDeclaredMethod("getAnimation"); ByteCodePatcher.modifiedClasses.add(ct);
ct.removeMethod(getAnimation); }
catch (CannotCompileException | NotFoundException e)
{
e.printStackTrace();
}
}
getAnimation = CtNewMethod.make("public int getAnimation() { return this.getRsAnimation(); }",ct); private void transformGetAnimation() throws CannotCompileException, NotFoundException
ct.addMethod(getAnimation);
}
private void transformAnimationChanged() throws CannotCompileException, NotFoundException
{ {
CtMethod getAnimationChanged = ct.getDeclaredMethod("animationChanged", new CtClass[]{CtClass.intType}); CtMethod protectedAnimation = ct.getDeclaredMethod("1protect$getRsAnimation");
ct.removeMethod(getAnimationChanged); ct.removeMethod(protectedAnimation);
getAnimationChanged = CtNewMethod.make( protectedAnimation.setName("getRsAnimation");
"public void animationChanged(int n) { " + ct.addMethod(protectedAnimation);
"net.runelite.api.events.AnimationChanged animationChanged = new net.runelite.api.events.AnimationChanged();" +
"animationChanged.setActor((net.runelite.api.Actor)this);" +
ByteCodePatcher.clientInstance + ".getCallbacks().post((java.lang.Object)animationChanged); }", ct);
ct.addMethod(getAnimationChanged);
}
private void transformGraphicChanged() throws CannotCompileException, NotFoundException CtMethod getAnimation = ct.getDeclaredMethod("getAnimation");
ct.removeMethod(getAnimation);
getAnimation = CtNewMethod.make(
"public int getAnimation()" +
"{" +
" return this.getRsAnimation();" +
"}", ct);
ct.addMethod(getAnimation);
log.info(
"[RuneLitePlus] transformed {} ({}) at class: {}",
this.getClass().getSimpleName(),
new Object(){}.getClass().getEnclosingMethod().getName(),
ct.getName()
);
}
private void transformAnimationChanged() throws CannotCompileException, NotFoundException
{
CtMethod getAnimationChanged = ct.getDeclaredMethod("animationChanged", new CtClass[]{CtClass.intType});
ct.removeMethod(getAnimationChanged);
getAnimationChanged = CtNewMethod.make(
"public void animationChanged(int n)" +
"{" +
" net.runelite.api.events.AnimationChanged animationChanged = new net.runelite.api.events.AnimationChanged();" +
" animationChanged.setActor((net.runelite.api.Actor) this);" +
ByteCodePatcher.clientInstance + ".getCallbacks().post((java.lang.Object)animationChanged);" +
"}", ct);
ct.addMethod(getAnimationChanged);
log.info(
"[RuneLitePlus] transformed {} ({}) at class: {}",
this.getClass().getSimpleName(),
new Object(){}.getClass().getEnclosingMethod().getName(),
ct.getName()
);
}
private void transformGraphicChanged() throws CannotCompileException, NotFoundException
{ {
CtMethod graphicChanged = ct.getDeclaredMethod("graphicChanged", new CtClass[]{CtClass.intType}); CtMethod graphicChanged = ct.getDeclaredMethod("graphicChanged", new CtClass[]{CtClass.intType});
ct.removeMethod(graphicChanged); ct.removeMethod(graphicChanged);
graphicChanged = CtNewMethod.make( graphicChanged = CtNewMethod.make(
"public void graphicChanged(int paramInt){" + "public void graphicChanged(int paramInt)" +
"net.runelite.api.events.GraphicChanged localGraphicChanged = new net.runelite.api.events.GraphicChanged();" + "{" +
"localGraphicChanged.setActor(this);" + " net.runelite.api.events.GraphicChanged localGraphicChanged = new net.runelite.api.events.GraphicChanged();" +
ByteCodePatcher.clientInstance+".getCallbacks().post(localGraphicChanged);}",ct); " localGraphicChanged.setActor(this);" +
ByteCodePatcher.clientInstance + ".getCallbacks().post(localGraphicChanged);" +
"}", ct);
ct.addMethod(graphicChanged); ct.addMethod(graphicChanged);
}
log.info(
"[RuneLitePlus] transformed {} ({}) at class: {}",
this.getClass().getSimpleName(),
new Object(){}.getClass().getEnclosingMethod().getName(),
ct.getName()
);
}
} }

View File

@@ -8,15 +8,20 @@ import javassist.NotFoundException;
import javassist.bytecode.AnnotationsAttribute; import javassist.bytecode.AnnotationsAttribute;
import javassist.bytecode.ClassFile; import javassist.bytecode.ClassFile;
import javassist.bytecode.ConstPool; import javassist.bytecode.ConstPool;
import lombok.extern.slf4j.Slf4j;
import net.runelite.client.rs.bytecode.ByteCodePatcher; import net.runelite.client.rs.bytecode.ByteCodePatcher;
public class ClientTransform implements Transform { @Slf4j
public class ClientTransform implements Transform
{
private CtClass ct; private CtClass ct;
@Override @Override
public void modify(Class clazz) { public void modify(Class clazz)
try { {
try
{
ct = ByteCodePatcher.classPool.get(clazz.getName()); ct = ByteCodePatcher.classPool.get(clazz.getName());
transformProtectedGetMenuOptions(); transformProtectedGetMenuOptions();
@@ -28,15 +33,17 @@ public class ClientTransform implements Transform {
transformGetMenuEntries(); transformGetMenuEntries();
transformSetMenuEntries(); transformSetMenuEntries();
transformOnMenuOptionsChanged(); transformOnMenuOptionsChanged();
transformGetProjectiles(); transformGetProjectiles();
transformGetCollisionMaps(); transformGetCollisionMaps();
transformDraw2010Menu(); transformDraw2010Menu();
transformRenderSelf(); transformRenderSelf();
transformboundingBoxCheck(); transformboundingBoxCheck();
transformcheckClickBox(); transformcheckClickBox();
ByteCodePatcher.modifiedClasses.add(ct); ByteCodePatcher.modifiedClasses.add(ct);
} catch (Exception e) { }
catch (Exception e)
{
e.printStackTrace(); e.printStackTrace();
} }
} }
@@ -50,40 +57,53 @@ public class ClientTransform implements Transform {
protectedGetMenuOptions.setName("getMenuOptions"); protectedGetMenuOptions.setName("getMenuOptions");
ct.addMethod(protectedGetMenuOptions); ct.addMethod(protectedGetMenuOptions);
log.info(
"[RuneLitePlus] transformed {} ({}) at class: {}",
this.getClass().getSimpleName(),
new Object(){}.getClass().getEnclosingMethod().getName(),
ct.getName()
);
} }
private void transformGetProjectiles() throws CannotCompileException, NotFoundException private void transformGetProjectiles() throws CannotCompileException, NotFoundException
{ {
CtMethod getProjectiles; CtMethod getProjectiles;
CtMethod getProjectilesDeque = ct.getDeclaredMethod("1protect$getProjectilesDeque"); CtMethod getProjectilesDeque = ct.getDeclaredMethod("1protect$getProjectilesDeque");
ct.removeMethod(getProjectilesDeque); ct.removeMethod(getProjectilesDeque);
getProjectilesDeque.setName("getProjectilesDeque"); getProjectilesDeque.setName("getProjectilesDeque");
ct.addMethod(getProjectilesDeque); ct.addMethod(getProjectilesDeque);
getProjectiles = ct.getDeclaredMethod("getProjectiles"); getProjectiles = ct.getDeclaredMethod("getProjectiles");
ct.removeMethod(getProjectiles); ct.removeMethod(getProjectiles);
getProjectiles = CtNewMethod.make( getProjectiles = CtNewMethod.make(
"public java.util.List getProjectiles() { " + "public java.util.List getProjectiles() { " +
"java.util.ArrayList localArrayList = new java.util.ArrayList();" + "java.util.ArrayList localArrayList = new java.util.ArrayList();" +
"net.runelite.rs.api.RSDeque localRSDeque = getProjectilesDeque();" + "net.runelite.rs.api.RSDeque localRSDeque = getProjectilesDeque();" +
"net.runelite.rs.api.RSNode localRSNode = localRSDeque.getHead();" + "net.runelite.rs.api.RSNode localRSNode = localRSDeque.getHead();" +
"for (net.runelite.api.Node localNode = localRSNode.getNext(); localNode != localRSNode; localNode = localNode.getNext()) {" + "for (net.runelite.api.Node localNode = localRSNode.getNext(); localNode != localRSNode; localNode = localNode.getNext()) {" +
"net.runelite.api.Projectile localProjectile = (net.runelite.api.Projectile)localNode;" + "net.runelite.api.Projectile localProjectile = (net.runelite.api.Projectile)localNode;" +
"localArrayList.add(localProjectile); }" + "localArrayList.add(localProjectile); }" +
"return localArrayList; }", ct); "return localArrayList; }", ct);
ct.addMethod(getProjectiles); ct.addMethod(getProjectiles);
ClassFile classFile = ct.getClassFile(); ClassFile classFile = ct.getClassFile();
ConstPool constPool = classFile.getConstPool(); ConstPool constPool = classFile.getConstPool();
AnnotationsAttribute attr = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag); AnnotationsAttribute attr = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
javassist.bytecode.annotation.Annotation annotation = new javassist.bytecode.annotation.Annotation("Override", constPool); javassist.bytecode.annotation.Annotation annotation = new javassist.bytecode.annotation.Annotation("Override", constPool);
attr.setAnnotation(annotation); attr.setAnnotation(annotation);
getProjectiles.getMethodInfo().addAttribute(attr); getProjectiles.getMethodInfo().addAttribute(attr);
System.out.println("Added override annotation for getprojectiles");
} log.info(
"[RuneLitePlus] transformed {} ({}) at class: {}",
this.getClass().getSimpleName(),
new Object(){}.getClass().getEnclosingMethod().getName(),
ct.getName()
);
}
private void transformProtectedGetMenuTargets() throws CannotCompileException, NotFoundException private void transformProtectedGetMenuTargets() throws CannotCompileException, NotFoundException
{ {
@@ -94,24 +114,38 @@ public class ClientTransform implements Transform {
protectedGetMenuTargets.setName("getMenuTargets"); protectedGetMenuTargets.setName("getMenuTargets");
ct.addMethod(protectedGetMenuTargets); ct.addMethod(protectedGetMenuTargets);
log.info(
"[RuneLitePlus] transformed {} ({}) at class: {}",
this.getClass().getSimpleName(),
new Object(){}.getClass().getEnclosingMethod().getName(),
ct.getName()
);
} }
private void transformGetCollisionMaps() throws CannotCompileException, NotFoundException private void transformGetCollisionMaps() throws CannotCompileException, NotFoundException
{ {
CtMethod getCollisionMaps; CtMethod getCollisionMaps;
CtMethod protectedMaps = ct.getDeclaredMethod("1protect$getRsCollisionMaps"); CtMethod protectedMaps = ct.getDeclaredMethod("1protect$getRsCollisionMaps");
ct.removeMethod(protectedMaps); ct.removeMethod(protectedMaps);
protectedMaps.setName("getRsCollisionMaps"); protectedMaps.setName("getRsCollisionMaps");
ct.addMethod(protectedMaps); ct.addMethod(protectedMaps);
getCollisionMaps = ct.getDeclaredMethod("getCollisionMaps"); getCollisionMaps = ct.getDeclaredMethod("getCollisionMaps");
ct.removeMethod(getCollisionMaps); ct.removeMethod(getCollisionMaps);
getCollisionMaps = CtMethod.make("public net.runelite.rs.api.RSCollisionData[] getCollisionMaps() { return getRsCollisionMaps(); }", ct); getCollisionMaps = CtMethod.make("public net.runelite.rs.api.RSCollisionData[] getCollisionMaps() { return getRsCollisionMaps(); }", ct);
ct.addMethod(getCollisionMaps); ct.addMethod(getCollisionMaps);
}
log.info(
"[RuneLitePlus] transformed {} ({}) at class: {}",
this.getClass().getSimpleName(),
new Object(){}.getClass().getEnclosingMethod().getName(),
ct.getName()
);
}
private void transformProtectedGetMenuIdentifiers() throws CannotCompileException, NotFoundException private void transformProtectedGetMenuIdentifiers() throws CannotCompileException, NotFoundException
{ {
@@ -122,6 +156,13 @@ public class ClientTransform implements Transform {
protectedGetMenuIdentifiers.setName("getMenuIdentifiers"); protectedGetMenuIdentifiers.setName("getMenuIdentifiers");
ct.addMethod(protectedGetMenuIdentifiers); ct.addMethod(protectedGetMenuIdentifiers);
log.info(
"[RuneLitePlus] transformed {} ({}) at class: {}",
this.getClass().getSimpleName(),
new Object(){}.getClass().getEnclosingMethod().getName(),
ct.getName()
);
} }
private void transformProtectedGetMenuTypes() throws CannotCompileException, NotFoundException private void transformProtectedGetMenuTypes() throws CannotCompileException, NotFoundException
@@ -130,12 +171,19 @@ public class ClientTransform implements Transform {
protectedGetMenuTypes = ct.getDeclaredMethod("1protect$getMenuTypes"); protectedGetMenuTypes = ct.getDeclaredMethod("1protect$getMenuTypes");
// Don't remove as this is referenced elsewhere in client // Don't remove as this is referenced elsewhere in client
//ct.removeMethod(protectedGetMenuTypes); // ct.removeMethod(protectedGetMenuTypes);
CtMethod newProtectedGetMenuTypes = CtNewMethod.copy(protectedGetMenuTypes, ct, null); CtMethod newProtectedGetMenuTypes = CtNewMethod.copy(protectedGetMenuTypes, ct, null);
newProtectedGetMenuTypes.setName("getMenuTypes"); newProtectedGetMenuTypes.setName("getMenuTypes");
ct.addMethod(newProtectedGetMenuTypes); ct.addMethod(newProtectedGetMenuTypes);
log.info(
"[RuneLitePlus] transformed {} ({}) at class: {}",
this.getClass().getSimpleName(),
new Object(){}.getClass().getEnclosingMethod().getName(),
ct.getName()
);
} }
private void transformProtectedGetMenuActionParams0() throws CannotCompileException, NotFoundException private void transformProtectedGetMenuActionParams0() throws CannotCompileException, NotFoundException
@@ -147,6 +195,13 @@ public class ClientTransform implements Transform {
protectedGetMenuActionParams0.setName("getMenuActionParams0"); protectedGetMenuActionParams0.setName("getMenuActionParams0");
ct.addMethod(protectedGetMenuActionParams0); ct.addMethod(protectedGetMenuActionParams0);
log.info(
"[RuneLitePlus] transformed {} ({}) at class: {}",
this.getClass().getSimpleName(),
new Object(){}.getClass().getEnclosingMethod().getName(),
ct.getName()
);
} }
private void transformProtectedGetMenuActionParams1() throws CannotCompileException, NotFoundException private void transformProtectedGetMenuActionParams1() throws CannotCompileException, NotFoundException
@@ -157,6 +212,13 @@ public class ClientTransform implements Transform {
ct.removeMethod(protectedGetMenuActionParams1); ct.removeMethod(protectedGetMenuActionParams1);
protectedGetMenuActionParams1.setName("getMenuActionParams1"); protectedGetMenuActionParams1.setName("getMenuActionParams1");
ct.addMethod(protectedGetMenuActionParams1); ct.addMethod(protectedGetMenuActionParams1);
log.info(
"[RuneLitePlus] transformed {} ({}) at class: {}",
this.getClass().getSimpleName(),
new Object(){}.getClass().getEnclosingMethod().getName(),
ct.getName()
);
} }
private void transformGetMenuEntries() throws CannotCompileException, NotFoundException private void transformGetMenuEntries() throws CannotCompileException, NotFoundException
@@ -167,71 +229,86 @@ public class ClientTransform implements Transform {
ct.removeMethod(getMenuEntries); ct.removeMethod(getMenuEntries);
getMenuEntries = CtMethod.make( getMenuEntries = CtMethod.make(
"public net.runelite.api.MenuEntry[] getMenuEntries() {" + "public net.runelite.api.MenuEntry[] getMenuEntries()" +
"int n2 = this.getMenuOptionCount();"+ "{" +
"String[] arrstring = this.getMenuOptions();"+ " int n2 = this.getMenuOptionCount();" +
"String[] arrstring2 = this.getMenuTargets();"+ " String[] arrstring = this.getMenuOptions();" +
"int[] arrn = this.getMenuIdentifiers();"+ " String[] arrstring2 = this.getMenuTargets();" +
"int[] arrn2 = this.getMenuTypes();"+ " int[] arrn = this.getMenuIdentifiers();" +
"int[] arrn3 = this.getMenuActionParams0();"+ " int[] arrn2 = this.getMenuTypes();" +
"int[] arrn4 = this.getMenuActionParams1();"+ " int[] arrn3 = this.getMenuActionParams0();" +
"boolean[] arrbl = this.getMenuForceLeftClick();"+ " int[] arrn4 = this.getMenuActionParams1();" +
"net.runelite.api.MenuEntry[] arrmenuEntry = new net.runelite.api.MenuEntry[n2];"+ " boolean[] arrbl = this.getMenuForceLeftClick();" +
"int n3 = 0;"+ " net.runelite.api.MenuEntry[] arrmenuEntry = new net.runelite.api.MenuEntry[n2];" +
"while (n3 < n2) {"+ " int n3 = 0;" +
"net.runelite.api.MenuEntry menuEntry = arrmenuEntry[n3] = new net.runelite.api.MenuEntry();"+ " while (n3 < n2) " +
"menuEntry.setOption(arrstring[n3]);"+ " {" +
"menuEntry.setTarget(arrstring2[n3]);"+ " net.runelite.api.MenuEntry menuEntry = arrmenuEntry[n3] = new net.runelite.api.MenuEntry();" +
"menuEntry.setIdentifier(arrn[n3]);"+ " menuEntry.setOption(arrstring[n3]);" +
"menuEntry.setType(arrn2[n3]);"+ " menuEntry.setTarget(arrstring2[n3]);" +
"menuEntry.setParam0(arrn3[n3]);"+ " menuEntry.setIdentifier(arrn[n3]);" +
"menuEntry.setParam1(arrn4[n3]);"+ " menuEntry.setType(arrn2[n3]);" +
"menuEntry.setForceLeftClick(arrbl[n3]);"+ " menuEntry.setParam0(arrn3[n3]);" +
"++n3; }"+ " menuEntry.setParam1(arrn4[n3]);" +
"return arrmenuEntry; }", ct); " menuEntry.setForceLeftClick(arrbl[n3]);" +
" ++n3;" +
" }" +
" return arrmenuEntry;" +
"}", ct);
ct.addMethod(getMenuEntries); ct.addMethod(getMenuEntries);
log.info(
"[RuneLitePlus] transformed {} ({}) at class: {}",
this.getClass().getSimpleName(),
new Object(){}.getClass().getEnclosingMethod().getName(),
ct.getName()
);
} }
private void transformSetMenuEntries() throws CannotCompileException, NotFoundException { private void transformSetMenuEntries() throws CannotCompileException, NotFoundException
{
CtMethod setMenuEntries; CtMethod setMenuEntries;
setMenuEntries = ct.getDeclaredMethod("setMenuEntries"); setMenuEntries = ct.getDeclaredMethod("setMenuEntries");
ct.removeMethod(setMenuEntries); ct.removeMethod(setMenuEntries);
setMenuEntries = CtNewMethod.make( setMenuEntries = CtNewMethod.make(
"public void setMenuEntries(net.runelite.api.MenuEntry[] arrmenuEntry) {" + "public void setMenuEntries(net.runelite.api.MenuEntry[] arrmenuEntry)" +
"int n2 = 0;" + "{" +
"String[] arrstring = this.getMenuOptions();" + " int n2 = 0;" +
"String[] arrstring2 = this.getMenuTargets();" + " String[] arrstring = this.getMenuOptions();" +
"int[] arrn = this.getMenuIdentifiers();" + " String[] arrstring2 = this.getMenuTargets();" +
"int[] arrn2 = this.getMenuTypes();" + " int[] arrn = this.getMenuIdentifiers();" +
"int[] arrn3 = this.getMenuActionParams0();" + " int[] arrn2 = this.getMenuTypes();" +
"int[] arrn4 = this.getMenuActionParams1();" + " int[] arrn3 = this.getMenuActionParams0();" +
"boolean[] arrbl = getMenuForceLeftClick();" + " int[] arrn4 = this.getMenuActionParams1();" +
"net.runelite.api.MenuEntry[] arrmenuEntry2 = arrmenuEntry;" + " boolean[] arrbl = getMenuForceLeftClick();" +
"int n3 = arrmenuEntry2.length;" + " net.runelite.api.MenuEntry[] arrmenuEntry2 = arrmenuEntry;" +
"int n4 = 0;" + " int n3 = arrmenuEntry2.length;" +
"do {" + " int n4 = 0;" +
"String string;" + " do" +
"if (n4 >= n3) {" + " {" +
"this.setMenuOptionCount(n2);" + " String string;" +
"oldMenuEntryCount = n2;" + " if (n4 >= n3)" +
"return;" + " {" +
"}" + " this.setMenuOptionCount(n2);" +
"net.runelite.api.MenuEntry menuEntry = arrmenuEntry2[n4];" + " oldMenuEntryCount = n2;" +
"int n5 = menuEntry.getType();" + " return;" +
"arrstring[n2] = menuEntry.getOption();" + " }" +
"arrstring2[n2] = menuEntry.getTarget();" + " net.runelite.api.MenuEntry menuEntry = arrmenuEntry2[n4];" +
"arrn[n2] = menuEntry.getIdentifier();" + " int n5 = menuEntry.getType();" +
"arrn2[n2] = n5;" + " arrstring[n2] = menuEntry.getOption();" +
"arrn3[n2] = menuEntry.getParam0();" + " arrstring2[n2] = menuEntry.getTarget();" +
"arrn4[n2] = menuEntry.getParam1();" + " arrn[n2] = menuEntry.getIdentifier();" +
"arrbl[n2] = menuEntry.isForceLeftClick();" + " arrn2[n2] = n5;" +
"++n2;" + " arrn3[n2] = menuEntry.getParam0();" +
"++n4;" + " arrn4[n2] = menuEntry.getParam1();" +
"} while (true);" + " arrbl[n2] = menuEntry.isForceLeftClick();" +
"}" " ++n2;" +
, ct); " ++n4;" +
ct.addMethod(setMenuEntries); " } while (true);" +
"}"
, ct);
ct.addMethod(setMenuEntries);
} }
private void transformOnMenuOptionsChanged() throws CannotCompileException, NotFoundException private void transformOnMenuOptionsChanged() throws CannotCompileException, NotFoundException
@@ -242,23 +319,31 @@ public class ClientTransform implements Transform {
ct.removeMethod(onMenuOptionsChanged); ct.removeMethod(onMenuOptionsChanged);
onMenuOptionsChanged = CtMethod.make( onMenuOptionsChanged = CtMethod.make(
"public static void onMenuOptionsChanged(int n2) {"+ "public static void onMenuOptionsChanged(int n2)" +
"int n3;" + "{" +
"int n4 = oldMenuEntryCount;"+ " int n3;" +
"oldMenuEntryCount = n3 = "+ByteCodePatcher.clientInstance+".getMenuOptionCount();"+ " int n4 = oldMenuEntryCount;" +
"if (n3 != n4 + 1) return;"+ " oldMenuEntryCount = n3 = " + ByteCodePatcher.clientInstance + ".getMenuOptionCount();" +
"net.runelite.api.events.MenuEntryAdded menuEntryAdded = new net.runelite.api.events.MenuEntryAdded("+ " if (n3 != n4 + 1) return;" +
ByteCodePatcher.clientInstance+".getMenuOptions()[n3 - 1],"+ " net.runelite.api.events.MenuEntryAdded menuEntryAdded = new net.runelite.api.events.MenuEntryAdded(" +
ByteCodePatcher.clientInstance+".getMenuTargets()[n3 - 1],"+ ByteCodePatcher.clientInstance + ".getMenuOptions()[n3 - 1]," +
ByteCodePatcher.clientInstance+".getMenuTypes()[n3 - 1],"+ ByteCodePatcher.clientInstance + ".getMenuTargets()[n3 - 1]," +
ByteCodePatcher.clientInstance+".getMenuIdentifiers()[n3 - 1],"+ ByteCodePatcher.clientInstance + ".getMenuTypes()[n3 - 1]," +
ByteCodePatcher.clientInstance+".getMenuActionParams0()[n3 - 1],"+ ByteCodePatcher.clientInstance + ".getMenuIdentifiers()[n3 - 1]," +
ByteCodePatcher.clientInstance+".getMenuActionParams1()[n3 - 1]);"+ ByteCodePatcher.clientInstance + ".getMenuActionParams0()[n3 - 1]," +
ByteCodePatcher.clientInstance+".getCallbacks().post((Object)menuEntryAdded);"+ ByteCodePatcher.clientInstance + ".getMenuActionParams1()[n3 - 1]);" +
ByteCodePatcher.clientInstance + ".getCallbacks().post((Object)menuEntryAdded);" +
"}" "}"
, ct); , ct);
ct.addMethod(onMenuOptionsChanged); ct.addMethod(onMenuOptionsChanged);
log.info(
"[RuneLitePlus] transformed {} ({}) at class: {}",
this.getClass().getSimpleName(),
new Object(){}.getClass().getEnclosingMethod().getName(),
ct.getName()
);
} }
private void transformRenderSelf() throws CannotCompileException private void transformRenderSelf() throws CannotCompileException
@@ -275,6 +360,13 @@ public class ClientTransform implements Transform {
renderSelf.getMethodInfo().addAttribute(attr); renderSelf.getMethodInfo().addAttribute(attr);
ct.addMethod(renderSelf); ct.addMethod(renderSelf);
log.info(
"[RuneLitePlus] transformed {} ({}) at class: {}",
this.getClass().getSimpleName(),
new Object(){}.getClass().getEnclosingMethod().getName(),
ct.getName()
);
} }
private void transformDraw2010Menu() throws CannotCompileException, NotFoundException private void transformDraw2010Menu() throws CannotCompileException, NotFoundException
@@ -285,51 +377,64 @@ public class ClientTransform implements Transform {
ct.removeMethod(draw2010Menu); ct.removeMethod(draw2010Menu);
draw2010Menu = CtNewMethod.make( draw2010Menu = CtNewMethod.make(
"public void draw2010Menu() {" + "public void draw2010Menu()" +
"int n2 = this.getMenuX();" + "{" +
"int n3 = this.getMenuY();" + " int n2 = this.getMenuX();" +
"int n4 = this.getMenuWidth();" + " int n3 = this.getMenuY();" +
"int n5 = this.getMenuHeight();" + " int n4 = this.getMenuWidth();" +
"this.RasterizerDrawHorizontalLine(n2 + 2, n3, n4 - 4, 7170651);" + " int n5 = this.getMenuHeight();" +
"this.RasterizerDrawHorizontalLine(n2 + 2, n3 + n5 - 1, n4 - 4, 7170651);" + " this.RasterizerDrawHorizontalLine(n2 + 2, n3, n4 - 4, 7170651);" +
"this.RasterizerDrawVerticalLine(n2, n3 + 2, n5 - 4, 7170651);" + " this.RasterizerDrawHorizontalLine(n2 + 2, n3 + n5 - 1, n4 - 4, 7170651);" +
"this.RasterizerDrawVerticalLine(n2 + n4 - 1, n3 + 2, n5 - 4, 7170651);" + " this.RasterizerDrawVerticalLine(n2, n3 + 2, n5 - 4, 7170651);" +
"this.RasterizerDrawRectangle(n2 + 1, n3 + 5, n4 - 2, n5 - 6, 2827810);" + " this.RasterizerDrawVerticalLine(n2 + n4 - 1, n3 + 2, n5 - 4, 7170651);" +
"this.RasterizerDrawHorizontalLine(n2 + 1, n3 + 17, n4 - 2, 2827810);" + " this.RasterizerDrawRectangle(n2 + 1, n3 + 5, n4 - 2, n5 - 6, 2827810);" +
"this.RasterizerDrawCircle(n2 + 2, n3 + n5 - 3, 0, 2827810);" + " this.RasterizerDrawHorizontalLine(n2 + 1, n3 + 17, n4 - 2, 2827810);" +
"this.RasterizerDrawCircle(n2 + n4 - 3, n3 + n5 - 3, 0, 2827810);" + " this.RasterizerDrawCircle(n2 + 2, n3 + n5 - 3, 0, 2827810);" +
"this.RasterizerDrawGradient(n2 + 2, n3 + 1, n4 - 4, 16, 3288610, 592388);" + " this.RasterizerDrawCircle(n2 + n4 - 3, n3 + n5 - 3, 0, 2827810);" +
"this.RasterizerFillRectangle(n2 + 1, n3 + 1, 2, 4, 2827810);" + " this.RasterizerDrawGradient(n2 + 2, n3 + 1, n4 - 4, 16, 3288610, 592388);" +
"this.RasterizerFillRectangle(n2 + n4 - 3, n3 + 1, 2, 4, 2827810);" + " this.RasterizerFillRectangle(n2 + 1, n3 + 1, 2, 4, 2827810);" +
"this.RasterizerDrawHorizontalLine(n2 + 2, n3 + 18, n4 - 4, 5392957);" + " this.RasterizerFillRectangle(n2 + n4 - 3, n3 + 1, 2, 4, 2827810);" +
"this.RasterizerDrawHorizontalLine(n2 + 3, n3 + n5 - 3, n4 - 6, 5392957);" + " this.RasterizerDrawHorizontalLine(n2 + 2, n3 + 18, n4 - 4, 5392957);" +
"this.RasterizerDrawVerticalLine(n2 + 2, n3 + 18, n5 - 21, 5392957);" + " this.RasterizerDrawHorizontalLine(n2 + 3, n3 + n5 - 3, n4 - 6, 5392957);" +
"this.RasterizerDrawVerticalLine(n2 + n4 - 3, n3 + 18, n5 - 21, 5392957);" + " this.RasterizerDrawVerticalLine(n2 + 2, n3 + 18, n5 - 21, 5392957);" +
"this.RasterizerFillRectangle(n2 + 3, n3 + 19, n4 - 6, n5 - 22, 2828060);" + " this.RasterizerDrawVerticalLine(n2 + n4 - 3, n3 + 18, n5 - 21, 5392957);" +
"this.RasterizerDrawCircle(n2 + 1, n3 + 1, 0, 7170651);" + " this.RasterizerFillRectangle(n2 + 3, n3 + 19, n4 - 6, n5 - 22, 2828060);" +
"this.RasterizerDrawCircle(n2 + n4 - 2, n3 + 1, 0, 7170651);" + " this.RasterizerDrawCircle(n2 + 1, n3 + 1, 0, 7170651);" +
"this.RasterizerDrawCircle(n2 + 1, n3 + n5 - 2, 0, 7170651);" + " this.RasterizerDrawCircle(n2 + n4 - 2, n3 + 1, 0, 7170651);" +
"this.RasterizerDrawCircle(n2 + n4 - 2, n3 + n5 - 2, 0, 7170651);" + " this.RasterizerDrawCircle(n2 + 1, n3 + n5 - 2, 0, 7170651);" +
"net.runelite.rs.api.RSFont rSFont = this.getFontBold12();" + " this.RasterizerDrawCircle(n2 + n4 - 2, n3 + n5 - 2, 0, 7170651);" +
"rSFont.drawTextLeftAligned(\"Choose Option\", n2 + 3, n3 + 14, 13023381, -1);" + " net.runelite.rs.api.RSFont rSFont = this.getFontBold12();" +
"int n6 = this.getMouseX();" + " rSFont.drawTextLeftAligned(\"Choose Option\", n2 + 3, n3 + 14, 13023381, -1);" +
"int n7 = this.getMouseY();" + " int n6 = this.getMouseX();" +
"int n8 = this.getMenuOptionCount();" + " int n7 = this.getMouseY();" +
"String[] arrstring = this.getMenuTargets();" + " int n8 = this.getMenuOptionCount();" +
"String[] arrstring2 = this.getMenuOptions();" + " String[] arrstring = this.getMenuTargets();" +
"for (int i = 0; i < n8; ++i) {" + " String[] arrstring2 = this.getMenuOptions();" +
"int n9 = n3 + (n8 - 1 - i) * 15 + 31;" + " for (int i = 0; i < n8; ++i)" +
"String string = arrstring2[i];" + " {" +
"if (!arrstring[i].isEmpty()) {" + " int n9 = n3 + (n8 - 1 - i) * 15 + 31;" +
"string = string + \" \" + arrstring[i];" + " String string = arrstring2[i];" +
"}" + " if (!arrstring[i].isEmpty())" +
"rSFont.drawTextLeftAligned(string, n2 + 3, n9, 13023381, -1);" + " {" +
"if (n6 <= n2 || n6 >= n4 + n2 || n7 <= n9 - 13 || n7 >= n9 + 3) continue;" + " string = string + \" \" + arrstring[i];" +
"this.RasterizerFillRectangleAlpha(n2 + 3, n9 - 12, n4 - 6, 15, 16777215, 80);" + " }" +
"}" + " rSFont.drawTextLeftAligned(string, n2 + 3, n9, 13023381, -1);" +
" if (n6 <= n2 || n6 >= n4 + n2 || n7 <= n9 - 13 || n7 >= n9 + 3)" +
" {" +
" continue;" +
" }" +
" this.RasterizerFillRectangleAlpha(n2 + 3, n9 - 12, n4 - 6, 15, 16777215, 80);" +
" }" +
"}" "}"
, ct); , ct);
ct.addMethod(draw2010Menu); ct.addMethod(draw2010Menu);
log.info(
"[RuneLitePlus] transformed {} ({}) at class: {}",
this.getClass().getSimpleName(),
new Object(){}.getClass().getEnclosingMethod().getName(),
ct.getName()
);
} }
//TODO: fix not being able to click far away objects towards top of screen only. //TODO: fix not being able to click far away objects towards top of screen only.
@@ -338,70 +443,86 @@ public class ClientTransform implements Transform {
CtMethod boundingboxCheck2; CtMethod boundingboxCheck2;
boundingboxCheck2 = CtMethod.make( boundingboxCheck2 = CtMethod.make(
"public boolean boundingboxCheck2(net.runelite.api.Model model, int n2, int n3, int n4) {" + "public boolean boundingboxCheck2(net.runelite.api.Model model, int n2, int n3, int n4)" +
"int n5 = "+ByteCodePatcher.clientInstance+".getCameraPitch();" + "{" +
"int n6 = "+ByteCodePatcher.clientInstance+".getCameraYaw();" + " int n5 = " + ByteCodePatcher.clientInstance + ".getCameraPitch();" +
"int n7 = net.runelite.api.Perspective.SINE[n5];" + " int n6 = " + ByteCodePatcher.clientInstance + ".getCameraYaw();" +
"int n8 = net.runelite.api.Perspective.COSINE[n5];" + " int n7 = net.runelite.api.Perspective.SINE[n5];" +
"int n9 = net.runelite.api.Perspective.SINE[n6];" + " int n8 = net.runelite.api.Perspective.COSINE[n5];" +
"int n10 = net.runelite.api.Perspective.COSINE[n6];" + " int n9 = net.runelite.api.Perspective.SINE[n6];" +
"int n11 = "+ByteCodePatcher.clientInstance+".getCenterX();" + " int n10 = net.runelite.api.Perspective.COSINE[n6];" +
"int n12 = "+ByteCodePatcher.clientInstance+".getCenterY();" + " int n11 = " + ByteCodePatcher.clientInstance + ".getCenterX();" +
"int n13 = "+ByteCodePatcher.clientInstance+".getViewportMouseX();" + " int n12 = " + ByteCodePatcher.clientInstance + ".getCenterY();" +
"int n14 = "+ByteCodePatcher.clientInstance+".getViewportMouseY();" + " int n13 = " + ByteCodePatcher.clientInstance + ".getViewportMouseX();" +
"int n15 = "+ByteCodePatcher.clientInstance+".get3dZoom();" + " int n14 = " + ByteCodePatcher.clientInstance + ".getViewportMouseY();" +
"int n16 = (n13 - n11) * 50 / n15;" + " int n15 = " + ByteCodePatcher.clientInstance + ".get3dZoom();" +
"int n17 = (n14 - n12) * 50 / n15;" + " int n16 = (n13 - n11) * 50 / n15;" +
"int n18 = (n13 - n11) * 10000 / n15;" + " int n17 = (n14 - n12) * 50 / n15;" +
"int n19 = (n14 - n12) * 10000 / n15;" + " int n18 = (n13 - n11) * 10000 / n15;" +
"int n20 = client.rl$rot1(n17, 50, n8, n7);" + " int n19 = (n14 - n12) * 10000 / n15;" +
"int n21 = client.rl$rot2(n17, 50, n8, n7);" + " int n20 = client.rl$rot1(n17, 50, n8, n7);" +
"n17 = n20;" + " int n21 = client.rl$rot2(n17, 50, n8, n7);" +
"n20 = client.rl$rot1(n19, 10000, n8, n7);" + " n17 = n20;" +
"int n22 = client.rl$rot2(n19, 10000, n8, n7);" + " n20 = client.rl$rot1(n19, 10000, n8, n7);" +
"n19 = n20;" + " int n22 = client.rl$rot2(n19, 10000, n8, n7);" +
"n20 = client.rl$rot3(n16, n21, n10, n9);" + " n19 = n20;" +
"n21 = client.rl$rot4(n16, n21, n10, n9);" + " n20 = client.rl$rot3(n16, n21, n10, n9);" +
"n16 = n20;" + " n21 = client.rl$rot4(n16, n21, n10, n9);" +
"n20 = client.rl$rot3(n18, n22, n10, n9);" + " n16 = n20;" +
"n22 = client.rl$rot4(n18, n22, n10, n9);" + " n20 = client.rl$rot3(n18, n22, n10, n9);" +
"int n23 = (n20 - n16) / 2;" + " n22 = client.rl$rot4(n18, n22, n10, n9);" +
"int n24 = (n19 - n17) / 2;" + " int n23 = (n20 - n16) / 2;" +
"int n25 = (n22 - n21) / 2;" + " int n24 = (n19 - n17) / 2;" +
"int n26 = Math.abs(n23);" + " int n25 = (n22 - n21) / 2;" +
"int n27 = Math.abs(n24);" + " int n26 = Math.abs(n23);" +
"int n28 = Math.abs(n25);" + " int n27 = Math.abs(n24);" +
"int n29 = n2 + model.getCenterX();" + " int n28 = Math.abs(n25);" +
"int n30 = n3 + model.getCenterY();" + " int n29 = n2 + model.getCenterX();" +
"int n31 = n4 + model.getCenterZ();" + " int n30 = n3 + model.getCenterY();" +
"int n32 = model.getExtremeX();" + " int n31 = n4 + model.getCenterZ();" +
"int n33 = model.getExtremeY();" + " int n32 = model.getExtremeX();" +
"int n34 = model.getExtremeZ();" + " int n33 = model.getExtremeY();" +
"int n35 = (n16 + n20) / 2;" + " int n34 = model.getExtremeZ();" +
"int n36 = (n17 + n19) / 2;" + " int n35 = (n16 + n20) / 2;" +
"int n37 = (n22 + n21) / 2;" + " int n36 = (n17 + n19) / 2;" +
"int n38 = n35 - n29;" + " int n37 = (n22 + n21) / 2;" +
"int n39 = n36 - n30;" + " int n38 = n35 - n29;" +
"int n40 = n37 - n31;" + " int n39 = n36 - n30;" +
"if (Math.abs(n38) > n32 + n26) {" + " int n40 = n37 - n31;" +
"return false;" + " if (Math.abs(n38) > n32 + n26)" +
"}" + " {" +
"if (Math.abs(n39) > n33 + n27) {" + " return false;" +
"return false;" + " }" +
"}" + " if (Math.abs(n39) > n33 + n27)" +
"if (Math.abs(n40) > n34 + n28) {" + " {" +
"return false;" + " return false;" +
"}" + " }" +
"if (Math.abs(n40 * n24 - n39 * n25) > n33 * n28 + n34 * n27) {" + " if (Math.abs(n40) > n34 + n28)" +
"return false;" + " {" +
"}" + " return false;" +
"if (Math.abs(n38 * n25 - n40 * n23) > n34 * n26 + n32 * n28) {" + " }" +
"return false;" + " if (Math.abs(n40 * n24 - n39 * n25) > n33 * n28 + n34 * n27)" +
"}" + " {" +
"if (Math.abs(n39 * n23 - n38 * n24) <= n33 * n26 + n32 * n27) return true;" + " return false;" +
"return false;" + " }" +
"}", ct); " if (Math.abs(n38 * n25 - n40 * n23) > n34 * n26 + n32 * n28)" +
" {" +
" return false;" +
" }" +
" if (Math.abs(n39 * n23 - n38 * n24) <= n33 * n26 + n32 * n27)" +
" {" +
" return true;" +
" }" +
" return false;" +
"}", ct);
ct.addMethod(boundingboxCheck2); ct.addMethod(boundingboxCheck2);
log.info(
"[RuneLitePlus] transformed {} ({}) at class: {}",
this.getClass().getSimpleName(),
new Object(){}.getClass().getEnclosingMethod().getName(),
ct.getName()
);
} }
private void transformcheckClickBox() throws CannotCompileException, NotFoundException private void transformcheckClickBox() throws CannotCompileException, NotFoundException
@@ -412,88 +533,110 @@ public class ClientTransform implements Transform {
ct.removeMethod(checkClickBox); ct.removeMethod(checkClickBox);
checkClickBox = CtMethod.make( checkClickBox = CtMethod.make(
"public void checkClickbox(net.runelite.api.Model model, int n2, int n3, int n4, int n5, int n6, int n7, int n8, int n9, long l2) {"+ "public void checkClickbox(net.runelite.api.Model model, int n2, int n3, int n4, int n5, int n6, int n7, int n8, int n9, long l2) {" +
"int n10;" + " int n10;" +
"int n11;" + " int n11;" +
"int n12;" + " int n12;" +
"int n13;" + " int n13;" +
"int n14;" + " int n14;" +
"net.runelite.rs.api.RSModel rSModel = (net.runelite.rs.api.RSModel)model;" + " net.runelite.rs.api.RSModel rSModel = (net.runelite.rs.api.RSModel)model;" +
"boolean bl2 = l2 != 0L && (int)(l2 >>> 16 & 1L) != 1;" + " boolean bl2 = l2 != 0L && (int)(l2 >>> 16 & 1L) != 1;" +
"boolean bl3 = "+ByteCodePatcher.clientInstance+".getViewportContainsMouse();" + " boolean bl3 = " + ByteCodePatcher.clientInstance + ".getViewportContainsMouse();" +
"if (!bl2) return;" + " if (!bl2)" +
"if (!bl3) return;" + " {" +
"boolean bl4 = this.boundingboxCheck2((net.runelite.api.Model)rSModel, n7, n8, n9);" + " return;" +
"if (!bl4) {" + " }" +
"return;" + " if (!bl3)" +
"}" + " {" +
"if (rSModel.isClickable()) {" + " return;" +
"this.addHashAtMouse(l2);" + " }" +
"return;" + " boolean bl4 = this.boundingboxCheck2((net.runelite.api.Model)rSModel, n7, n8, n9);" +
"}" + " if (!bl4)" +
"int n15 = rSModel.getVerticesCount();" + " {" +
"int n16 = rSModel.getTrianglesCount();" + " return;" +
"int[] arrn = rSModel.getVerticesX();" + " }" +
"int[] arrn2 = rSModel.getVerticesY();" + " if (rSModel.isClickable())" +
"int[] arrn3 = rSModel.getVerticesZ();" + " {" +
"int[] arrn4 = rSModel.getTrianglesX();" + " this.addHashAtMouse(l2);" +
"int[] arrn5 = rSModel.getTrianglesY();" + " return;" +
"int[] arrn6 = rSModel.getTrianglesZ();" + " }" +
"int[] arrn7 = rSModel.getFaceColors3();" + " int n15 = rSModel.getVerticesCount();" +
"int n17 = "+ByteCodePatcher.clientInstance+".get3dZoom();" + " int n16 = rSModel.getTrianglesCount();" +
"int n18 = "+ByteCodePatcher.clientInstance+".getCenterX();" + " int[] arrn = rSModel.getVerticesX();" +
"int n19 = "+ByteCodePatcher.clientInstance+".getCenterY();" + " int[] arrn2 = rSModel.getVerticesY();" +
"int n20 = 0;" + " int[] arrn3 = rSModel.getVerticesZ();" +
"int n21 = 0;" + " int[] arrn4 = rSModel.getTrianglesX();" +
"if (n2 != 0) {" + " int[] arrn5 = rSModel.getTrianglesY();" +
"n20 = net.runelite.api.Perspective.SINE[n2];" + " int[] arrn6 = rSModel.getTrianglesZ();" +
"n21 = net.runelite.api.Perspective.COSINE[n2];" + " int[] arrn7 = rSModel.getFaceColors3();" +
"}" + " int n17 = " + ByteCodePatcher.clientInstance + ".get3dZoom();" +
"for (n14 = 0; n14 < n15; ++n14) {" + " int n18 = " + ByteCodePatcher.clientInstance + ".getCenterX();" +
"n11 = arrn[n14];" + " int n19 = " + ByteCodePatcher.clientInstance + ".getCenterY();" +
"n13 = arrn2[n14];" + " int n20 = 0;" +
"n12 = arrn3[n14];" + " int n21 = 0;" +
"if (n2 != 0) {" + " if (n2 != 0)" +
"n10 = n12 * n20 + n11 * n21 >> 16;" + " {" +
"n12 = n12 * n21 - n11 * n20 >> 16;" + " n20 = net.runelite.api.Perspective.SINE[n2];" +
"n11 = n10;" + " n21 = net.runelite.api.Perspective.COSINE[n2];" +
"}" + " }" +
"n10 = (n12 += n9) * n5 + n6 * (n11 += n7) >> 16;" + " for (n14 = 0; n14 < n15; ++n14)" +
"n12 = n6 * n12 - n11 * n5 >> 16;" + " {" +
"n11 = n10;" + " n11 = arrn[n14];" +
"n10 = n4 * (n13 += n8) - n12 * n3 >> 16;" + " n13 = arrn2[n14];" +
"if ((n12 = n13 * n3 + n4 * n12 >> 16) >= 50) {" + " n12 = arrn3[n14];" +
"client.rl$modelViewportYs[n14] = n11 * n17 / n12 + n18;" + " if (n2 != 0)" +
"client.rl$modelViewportXs[n14] = n10 * n17 / n12 + n19;" + " {" +
"continue;" + " n10 = n12 * n20 + n11 * n21 >> 16;" +
"}" + " n12 = n12 * n21 - n11 * n20 >> 16;" +
"client.rl$modelViewportYs[n14] = -5000;" + " n11 = n10;" +
"}" + " }" +
"n14 = "+ByteCodePatcher.clientInstance+".getViewportMouseX();" + " n10 = (n12 += n9) * n5 + n6 * (n11 += n7) >> 16;" +
"n11 = "+ByteCodePatcher.clientInstance+".getViewportMouseY();" + " n12 = n6 * n12 - n11 * n5 >> 16;" +
"n13 = 0;" + " n11 = n10;" +
"while (n13 < n16) {" + " n10 = n4 * (n13 += n8) - n12 * n3 >> 16;" +
"if (arrn7[n13] != -2) {" + " if ((n12 = n13 * n3 + n4 * n12 >> 16) >= 50)" +
"int n22;" + " {" +
"boolean bl5;" + " client.rl$modelViewportYs[n14] = n11 * n17 / n12 + n18;" +
"int n23;" + " client.rl$modelViewportXs[n14] = n10 * n17 / n12 + n19;" +
"n12 = arrn4[n13];" + " continue;" +
"n10 = arrn5[n13];" + " }" +
"int n24 = arrn6[n13];" + " client.rl$modelViewportYs[n14] = -5000;" +
"int n25 = rl$modelViewportYs[n12];" + " }" +
"int n26 = rl$modelViewportYs[n10];" + " n14 = " + ByteCodePatcher.clientInstance + ".getViewportMouseX();" +
"int n27 = rl$modelViewportYs[n24];" + " n11 = " + ByteCodePatcher.clientInstance + ".getViewportMouseY();" +
"int n28 = rl$modelViewportXs[n12];" + " n13 = 0;" +
"int n29 = rl$modelViewportXs[n10];" + " while (n13 < n16)" +
"int n30 = rl$modelViewportXs[n24];" + " {" +
"if (n25 != -5000 && n26 != -5000 && n27 != -5000 && (bl5 = (n23 = (n22 = rSModel.isClickable() ? 20 : 5) + n11) < n28 && n23 < n29 && n23 < n30 ? false : ((n23 = n11 - n22) > n28 && n23 > n29 && n23 > n30 ? false : ((n23 = n22 + n14) < n25 && n23 < n26 && n23 < n27 ? false : (n23 = n14 - n22) <= n25 || n23 <= n26 || n23 <= n27)))) {" + " if (arrn7[n13] != -2)" +
"this.addHashAtMouse(l2);" + " {" +
"return;" + " int n22;" +
"}" + " boolean bl5;" +
"}" + " int n23;" +
"++n13;" + " n12 = arrn4[n13];" +
"}" + " n10 = arrn5[n13];" +
"}", ct); " int n24 = arrn6[n13];" +
ct.addMethod(checkClickBox); " int n25 = rl$modelViewportYs[n12];" +
" int n26 = rl$modelViewportYs[n10];" +
" int n27 = rl$modelViewportYs[n24];" +
" int n28 = rl$modelViewportXs[n12];" +
" int n29 = rl$modelViewportXs[n10];" +
" int n30 = rl$modelViewportXs[n24];" +
" if (n25 != -5000 && n26 != -5000 && n27 != -5000 && (bl5 = (n23 = (n22 = rSModel.isClickable() ? 20 : 5) + n11) < n28 && n23 < n29 && n23 < n30 ? false : ((n23 = n11 - n22) > n28 && n23 > n29 && n23 > n30 ? false : ((n23 = n22 + n14) < n25 && n23 < n26 && n23 < n27 ? false : (n23 = n14 - n22) <= n25 || n23 <= n26 || n23 <= n27))))" +
" {" +
" this.addHashAtMouse(l2);" +
" return;" +
" }" +
" }" +
" ++n13;" +
" }" +
"}", ct);
ct.addMethod(checkClickBox);
log.info(
"[RuneLitePlus] transformed {} ({}) at class: {}",
this.getClass().getSimpleName(),
new Object(){}.getClass().getEnclosingMethod().getName(),
ct.getName()
);
} }
} }

View File

@@ -4,40 +4,54 @@ import javassist.CannotCompileException;
import javassist.CtClass; import javassist.CtClass;
import javassist.CtMethod; import javassist.CtMethod;
import javassist.NotFoundException; import javassist.NotFoundException;
import lombok.extern.slf4j.Slf4j;
import net.runelite.client.rs.bytecode.ByteCodePatcher; import net.runelite.client.rs.bytecode.ByteCodePatcher;
//This prevents the client from sending stack traces to Jagex at all, even classes outside of runelite. @Slf4j
public class ErrorTransform implements Transform { // This prevents the client from sending stack traces to Jagex at all, even classes outside of runelite.
public class ErrorTransform implements Transform
{
private CtClass ct; private CtClass ct;
//Where Runelites error interceptor is located, not auto-scraped. // Where Runelites error interceptor is located, not auto-scraped.
private static final String ERROR_INSTANCE_CLASS = "dp"; private static final String ERROR_INSTANCE_CLASS = "dp";
private static final String ERROR_INSTANCE_METHOD = "a"; private static final String ERROR_INSTANCE_METHOD = "a";
//private static final String ERROR_WARNING = "Tried to send a warning"; // private static final String ERROR_WARNING = "Tried to send a warning";
@Override
public void modify(Class clazz) {
try {
System.out.println("[RuneLitePlus] Transforming error method at class: "+ERROR_INSTANCE_CLASS);
@Override
public void modify(Class clazz)
{
try
{
ct = ByteCodePatcher.classPool.get(ERROR_INSTANCE_CLASS); ct = ByteCodePatcher.classPool.get(ERROR_INSTANCE_CLASS);
transformError(); transformError();
ByteCodePatcher.modifiedClasses.add(ct); ByteCodePatcher.modifiedClasses.add(ct);
} catch (CannotCompileException | NotFoundException e) { }
e.printStackTrace(); catch (CannotCompileException | NotFoundException e)
} {
} e.printStackTrace();
}
}
private void transformError() throws CannotCompileException, NotFoundException private void transformError() throws CannotCompileException, NotFoundException
{ {
CtMethod error = ct.getDeclaredMethod(ERROR_INSTANCE_METHOD); CtMethod error = ct.getDeclaredMethod(ERROR_INSTANCE_METHOD);
ct.removeMethod(error); ct.removeMethod(error);
error = CtMethod.make( error = CtMethod.make(
"public static void a(String string, Throwable throwable, byte by) {"+ "public static void a(String string, Throwable throwable, byte by)" +
"throwable.printStackTrace();"+ "{" +
"System.out.println(\"[RuneLitePlus] Prevented preceeding stack trace from being sent to Jagex\");}", ct); " throwable.printStackTrace();" +
" System.out.println(\"[RuneLitePlus] Prevented preceeding stack trace from being sent to Jagex\");" +
"}", ct);
ct.addMethod(error); ct.addMethod(error);
log.info(
"[RuneLitePlus] transformed {} ({}) at class: {}",
this.getClass().getSimpleName(),
new Object(){}.getClass().getEnclosingMethod().getName(),
ct.getName()
);
} }
} }

Some files were not shown because too many files have changed in this diff Show More