Prohibit parameter assignments.

This commit is contained in:
MobiusDevelopment
2020-05-10 03:29:34 +00:00
parent 2d73110d15
commit 33bbf97afb
1756 changed files with 12542 additions and 10025 deletions
@@ -12,8 +12,11 @@ org.eclipse.jdt.core.codeComplete.staticFinalFieldSuffixes=
org.eclipse.jdt.core.compiler.annotation.inheritNullAnnotations=disabled org.eclipse.jdt.core.compiler.annotation.inheritNullAnnotations=disabled
org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore
org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull
org.eclipse.jdt.core.compiler.annotation.nonnull.secondary=
org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault
org.eclipse.jdt.core.compiler.annotation.nonnullbydefault.secondary=
org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable
org.eclipse.jdt.core.compiler.annotation.nullable.secondary=
org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate
@@ -24,6 +27,8 @@ org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.doc.comment.support=enabled org.eclipse.jdt.core.compiler.doc.comment.support=enabled
org.eclipse.jdt.core.compiler.problem.APILeak=warning
org.eclipse.jdt.core.compiler.problem.annotatedTypeArgumentToUnannotated=info
org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.autoboxing=ignore org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
@@ -75,12 +80,14 @@ org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning
org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning
org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore
org.eclipse.jdt.core.compiler.problem.nonnullParameterAnnotationDropped=warning org.eclipse.jdt.core.compiler.problem.nonnullParameterAnnotationDropped=warning
org.eclipse.jdt.core.compiler.problem.nonnullTypeVariableFromLegacyInvocation=warning
org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error
org.eclipse.jdt.core.compiler.problem.nullReference=warning org.eclipse.jdt.core.compiler.problem.nullReference=warning
org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error
org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=warning org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=warning
org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning
org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore org.eclipse.jdt.core.compiler.problem.parameterAssignment=warning
org.eclipse.jdt.core.compiler.problem.pessimisticNullAnalysisForFreeTypeVariables=warning
org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=warning org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=warning
org.eclipse.jdt.core.compiler.problem.potentialNullReference=warning org.eclipse.jdt.core.compiler.problem.potentialNullReference=warning
org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=ignore org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=ignore
@@ -96,17 +103,23 @@ org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled
org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning
org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled
org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled
org.eclipse.jdt.core.compiler.problem.suppressWarningsNotFullyAnalysed=info
org.eclipse.jdt.core.compiler.problem.syntacticNullAnalysisForFields=disabled org.eclipse.jdt.core.compiler.problem.syntacticNullAnalysisForFields=disabled
org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=warning org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=warning
org.eclipse.jdt.core.compiler.problem.terminalDeprecation=warning
org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning
org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled
org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning
org.eclipse.jdt.core.compiler.problem.unclosedCloseable=warning org.eclipse.jdt.core.compiler.problem.unclosedCloseable=warning
org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore
org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning
org.eclipse.jdt.core.compiler.problem.unlikelyCollectionMethodArgumentType=warning
org.eclipse.jdt.core.compiler.problem.unlikelyCollectionMethodArgumentTypeStrict=disabled
org.eclipse.jdt.core.compiler.problem.unlikelyEqualsArgumentType=info
org.eclipse.jdt.core.compiler.problem.unnecessaryElse=warning org.eclipse.jdt.core.compiler.problem.unnecessaryElse=warning
org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning
org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore
org.eclipse.jdt.core.compiler.problem.unstableAutoModuleName=warning
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=warning org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=warning
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=disabled org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=disabled
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=disabled org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=disabled
@@ -54,9 +54,9 @@ public class Wisp extends AbstractNpcAI
{ {
if (event.equals("DELETE_NPC")) if (event.equals("DELETE_NPC"))
{ {
params = new StatSet(); final StatSet statSet = new StatSet();
params.set("LOCATION_OBJECT", npc.getLocation()); statSet.set("LOCATION_OBJECT", npc.getLocation());
getTimers().addTimer("RESPAWN_WISP_" + npc.getObjectId(), params, getRandom(RESPAWN_MIN, RESPAWN_MAX), null, null); getTimers().addTimer("RESPAWN_WISP_" + npc.getObjectId(), statSet, getRandom(RESPAWN_MIN, RESPAWN_MAX), null, null);
npc.deleteMe(); npc.deleteMe();
} }
else else
@@ -106,11 +106,12 @@ public class DarkWaterDragon extends AbstractNpcAI
cancelQuestTimer("2", npc, null); cancelQuestTimer("2", npc, null);
cancelQuestTimer("3", npc, null); cancelQuestTimer("3", npc, null);
cancelQuestTimer("4", npc, null); cancelQuestTimer("4", npc, null);
MY_TRACKING_SET.remove(npc.getObjectId()); MY_TRACKING_SET.remove(npc.getObjectId());
player = ID_MAP.remove(npc.getObjectId()); final PlayerInstance removed = ID_MAP.remove(npc.getObjectId());
if (player != null) if (removed != null)
{ {
((Attackable) npc).doItemDrop(NpcData.getInstance().getTemplate(18485), player); ((Attackable) npc).doItemDrop(NpcData.getInstance().getTemplate(18485), removed);
} }
npc.deleteMe(); npc.deleteMe();
@@ -358,6 +358,7 @@ public class Beleth extends AbstractNpcAI
{ {
_minions.clear(); _minions.clear();
Npc spawn;
int a = 0; int a = 0;
for (int i = 0; i < 16; i++) for (int i = 0; i < 16; i++)
{ {
@@ -365,12 +366,12 @@ public class Beleth extends AbstractNpcAI
final int x = (int) ((650 * Math.cos(i * 0.39)) + 16323); final int x = (int) ((650 * Math.cos(i * 0.39)) + 16323);
final int y = (int) ((650 * Math.sin(i * 0.39)) + 213170); final int y = (int) ((650 * Math.sin(i * 0.39)) + 213170);
npc = addSpawn(FAKE_BELETH, new Location(x, y, -9357, 49152)); spawn = addSpawn(FAKE_BELETH, new Location(x, y, -9357, 49152));
_minions.add(npc); _minions.add(spawn);
if (a >= 2) if (a >= 2)
{ {
npc.setOverloaded(true); spawn.setOverloaded(true);
a = 0; a = 0;
} }
} }
@@ -381,33 +382,31 @@ public class Beleth extends AbstractNpcAI
{ {
xm[i] = (int) ((1700 * Math.cos((i * 1.57) + 0.78)) + 16323); xm[i] = (int) ((1700 * Math.cos((i * 1.57) + 0.78)) + 16323);
ym[i] = (int) ((1700 * Math.sin((i * 1.57) + 0.78)) + 213170); ym[i] = (int) ((1700 * Math.sin((i * 1.57) + 0.78)) + 213170);
npc = addSpawn(FAKE_BELETH, new Location(xm[i], ym[i], -9357, 49152)); spawn = addSpawn(FAKE_BELETH, new Location(xm[i], ym[i], -9357, 49152));
npc.setImmobilized(true); spawn.setImmobilized(true);
_minions.add(spawn);
_minions.add(npc);
} }
xm[4] = (xm[0] + xm[1]) / 2; xm[4] = (xm[0] + xm[1]) / 2;
ym[4] = (ym[0] + ym[1]) / 2; ym[4] = (ym[0] + ym[1]) / 2;
npc = addSpawn(FAKE_BELETH, new Location(xm[4], ym[4], -9357, 49152)); spawn = addSpawn(FAKE_BELETH, new Location(xm[4], ym[4], -9357, 49152));
npc.setImmobilized(true); spawn.setImmobilized(true);
_minions.add(npc); _minions.add(spawn);
xm[5] = (xm[1] + xm[2]) / 2; xm[5] = (xm[1] + xm[2]) / 2;
ym[5] = (ym[1] + ym[2]) / 2; ym[5] = (ym[1] + ym[2]) / 2;
npc = addSpawn(FAKE_BELETH, new Location(xm[5], ym[5], -9357, 49152)); spawn = addSpawn(FAKE_BELETH, new Location(xm[5], ym[5], -9357, 49152));
npc.setImmobilized(true); spawn.setImmobilized(true);
_minions.add(npc); _minions.add(spawn);
xm[6] = (xm[2] + xm[3]) / 2; xm[6] = (xm[2] + xm[3]) / 2;
ym[6] = (ym[2] + ym[3]) / 2; ym[6] = (ym[2] + ym[3]) / 2;
npc = addSpawn(FAKE_BELETH, new Location(xm[6], ym[6], -9357, 49152)); spawn = addSpawn(FAKE_BELETH, new Location(xm[6], ym[6], -9357, 49152));
npc.setImmobilized(true); spawn.setImmobilized(true);
_minions.add(npc); _minions.add(spawn);
xm[7] = (xm[3] + xm[0]) / 2; xm[7] = (xm[3] + xm[0]) / 2;
ym[7] = (ym[3] + ym[0]) / 2; ym[7] = (ym[3] + ym[0]) / 2;
npc = addSpawn(FAKE_BELETH, new Location(xm[7], ym[7], -9357, 49152)); spawn = addSpawn(FAKE_BELETH, new Location(xm[7], ym[7], -9357, 49152));
npc.setImmobilized(true); spawn.setImmobilized(true);
_minions.add(npc); _minions.add(spawn);
xm[8] = (xm[0] + xm[4]) / 2; xm[8] = (xm[0] + xm[4]) / 2;
ym[8] = (ym[0] + ym[4]) / 2; ym[8] = (ym[0] + ym[4]) / 2;
_minions.add(addSpawn(FAKE_BELETH, new Location(xm[8], ym[8], -9357, 49152))); _minions.add(addSpawn(FAKE_BELETH, new Location(xm[8], ym[8], -9357, 49152)));
@@ -92,23 +92,23 @@ public class KimerianCommon extends AbstractInstance
{ {
case "HELPER_TIME_ACTION": case "HELPER_TIME_ACTION":
{ {
player = npc.getVariables().getObject("PC_INSTANCE", PlayerInstance.class); final PlayerInstance pc = npc.getVariables().getObject("PC_INSTANCE", PlayerInstance.class);
if (player != null) if (pc != null)
{ {
final double distance = npc.calculateDistance2D(player); final double distance = npc.calculateDistance2D(pc);
if (distance > 1000) if (distance > 1000)
{ {
npc.teleToLocation(new Location(player.getX() + getRandom(-100, 100), player.getY() + getRandom(-100, 100), player.getZ() + 50)); npc.teleToLocation(new Location(pc.getX() + getRandom(-100, 100), pc.getY() + getRandom(-100, 100), pc.getZ() + 50));
} }
else if (!npc.isAttackingNow() && (distance > 250)) else if (!npc.isAttackingNow() && (distance > 250))
{ {
npc.setRunning(); npc.setRunning();
addMoveToDesire(npc, new Location(player.getX() + getRandom(-100, 100), player.getY() + getRandom(-100, 100), player.getZ() + 50), 23); addMoveToDesire(npc, new Location(pc.getX() + getRandom(-100, 100), pc.getY() + getRandom(-100, 100), pc.getZ() + 50), 23);
} }
else if (!npc.isInCombat() || !npc.isAttackingNow() || (npc.getTarget() == null)) else if (!npc.isInCombat() || !npc.isAttackingNow() || (npc.getTarget() == null))
{ {
final Creature monster = (Creature) player.getTarget(); final Creature monster = (Creature) pc.getTarget();
if ((monster != null) && monster.isMonster() && player.isInCombat()) if ((monster != null) && monster.isMonster() && pc.isInCombat())
{ {
addAttackDesire(npc, monster); addAttackDesire(npc, monster);
} }
@@ -44,6 +44,7 @@ public class BlackMarketeerOfMammon extends AbstractNpcAI
@Override @Override
public String onAdvEvent(String event, Npc npc, PlayerInstance player) public String onAdvEvent(String event, Npc npc, PlayerInstance player)
{ {
String htmltext = event;
if (event.equals("31092-01.html")) if (event.equals("31092-01.html"))
{ {
return event; return event;
@@ -51,7 +52,7 @@ public class BlackMarketeerOfMammon extends AbstractNpcAI
else if (event.startsWith("exchange")) else if (event.startsWith("exchange"))
{ {
final StringTokenizer st = new StringTokenizer(event, " "); final StringTokenizer st = new StringTokenizer(event, " ");
event = st.nextToken(); htmltext = st.nextToken();
if (!st.hasMoreElements()) if (!st.hasMoreElements())
{ {
return "31092-02.html"; return "31092-02.html";
@@ -78,7 +79,7 @@ public class BlackMarketeerOfMammon extends AbstractNpcAI
giveAdena(player, count, false); giveAdena(player, count, false);
return "31092-04.html"; return "31092-04.html";
} }
return super.onAdvEvent(event, npc, player); return super.onAdvEvent(htmltext, npc, player);
} }
public static void main(String[] args) public static void main(String[] args)
@@ -386,8 +386,9 @@ public class CastleCourtMagician extends AbstractNpcAI
return ((player.getClan() != null) && (player.getClanId() == npc.getCastle().getOwnerId())) ? "courtmagician.html" : "courtmagician-01.html"; return ((player.getClan() != null) && (player.getClanId() == npc.getCastle().getOwnerId())) ? "courtmagician.html" : "courtmagician-01.html";
} }
private void showClassSpecificMultisell(PlayerInstance player, Npc npc, int index) private void showClassSpecificMultisell(PlayerInstance player, Npc npc, int indexValue)
{ {
int index = indexValue;
for (CategoryType ct : AWAKENED_CT) for (CategoryType ct : AWAKENED_CT)
{ {
if (player.isInCategory(ct)) if (player.isInCategory(ct))
@@ -471,8 +471,9 @@ public class ClanHallManager extends AbstractNpcAI
World.getInstance().forEachVisibleObject(npc, PlayerInstance.class, player -> player.sendPacket(new AgitDecoInfo(clanHall))); World.getInstance().forEachVisibleObject(npc, PlayerInstance.class, player -> player.sendPacket(new AgitDecoInfo(clanHall)));
} }
private String getFunctionInfo(ResidenceFunction func, String htmltext, String name) private String getFunctionInfo(ResidenceFunction func, String htmltextValue, String name)
{ {
String htmltext = htmltextValue;
if (func != null) if (func != null)
{ {
htmltext = htmltext.replaceAll("%" + name + "recovery%", String.valueOf((int) func.getTemplate().getValue()) + "%"); htmltext = htmltext.replaceAll("%" + name + "recovery%", String.valueOf((int) func.getTemplate().getValue()) + "%");
@@ -235,7 +235,7 @@ public class ClassMaster extends AbstractNpcAI implements IXmlReader
} }
@Override @Override
public String onAdvEvent(String event, Npc npc, PlayerInstance player) public String onAdvEvent(String eventValue, Npc npc, PlayerInstance player)
{ {
if (!_isEnabled) if (!_isEnabled)
{ {
@@ -243,6 +243,7 @@ public class ClassMaster extends AbstractNpcAI implements IXmlReader
} }
String htmltext = null; String htmltext = null;
String event = eventValue;
final StringTokenizer st = new StringTokenizer(event); final StringTokenizer st = new StringTokenizer(event);
event = st.nextToken(); event = st.nextToken();
switch (event) switch (event)
@@ -89,11 +89,11 @@ public class HermuncusMinion extends AbstractNpcAI
} }
@Override @Override
public String onAdvEvent(String event, Npc npc, PlayerInstance player) public String onAdvEvent(String eventValue, Npc npc, PlayerInstance player)
{ {
String htmltext = null; String htmltext = null;
final StringTokenizer st = new StringTokenizer(event, " "); final StringTokenizer st = new StringTokenizer(eventValue, " ");
event = st.nextToken(); final String event = st.nextToken();
if (event.equals("teleportList")) if (event.equals("teleportList"))
{ {
if (!player.isInCategory(CategoryType.SIXTH_CLASS_GROUP)) if (!player.isInCategory(CategoryType.SIXTH_CLASS_GROUP))
@@ -61,8 +61,9 @@ public class AdminBuffs implements IAdminCommandHandler
private static final String FONT_RED2 = "</font>"; private static final String FONT_RED2 = "</font>";
@Override @Override
public boolean useAdminCommand(String command, PlayerInstance activeChar) public boolean useAdminCommand(String commandValue, PlayerInstance activeChar)
{ {
String command = commandValue;
if (command.startsWith("admin_buff")) if (command.startsWith("admin_buff"))
{ {
if ((activeChar.getTarget() == null) || !activeChar.getTarget().isCreature()) if ((activeChar.getTarget() == null) || !activeChar.getTarget().isCreature())
@@ -1079,8 +1079,9 @@ public class AdminEditChar implements IAdminCommandHandler
activeChar.sendPacket(html); activeChar.sendPacket(html);
} }
private void showCharacterInfo(PlayerInstance activeChar, PlayerInstance player) private void showCharacterInfo(PlayerInstance activeChar, PlayerInstance targetPlayer)
{ {
PlayerInstance player = targetPlayer;
if (player == null) if (player == null)
{ {
final WorldObject target = activeChar.getTarget(); final WorldObject target = activeChar.getTarget();
@@ -1181,7 +1182,7 @@ public class AdminEditChar implements IAdminCommandHandler
activeChar.sendPacket(adminReply); activeChar.sendPacket(adminReply);
} }
private void setTargetReputation(PlayerInstance activeChar, int newReputation) private void setTargetReputation(PlayerInstance activeChar, int value)
{ {
final WorldObject target = activeChar.getTarget(); final WorldObject target = activeChar.getTarget();
PlayerInstance player = null; PlayerInstance player = null;
@@ -1194,6 +1195,7 @@ public class AdminEditChar implements IAdminCommandHandler
return; return;
} }
int newReputation = value;
if (newReputation > Config.MAX_REPUTATION) if (newReputation > Config.MAX_REPUTATION)
{ {
newReputation = Config.MAX_REPUTATION; newReputation = Config.MAX_REPUTATION;
@@ -109,8 +109,9 @@ public class AdminEffects implements IAdminCommandHandler
}; };
@Override @Override
public boolean useAdminCommand(String command, PlayerInstance activeChar) public boolean useAdminCommand(String commandValue, PlayerInstance activeChar)
{ {
String command = commandValue;
final StringTokenizer st = new StringTokenizer(command); final StringTokenizer st = new StringTokenizer(command);
st.nextToken(); st.nextToken();
@@ -160,10 +160,10 @@ public class AdminFightCalculator implements IAdminCommandHandler
private void handleShow(String params, PlayerInstance activeChar) private void handleShow(String params, PlayerInstance activeChar)
{ {
params = params.trim(); String trimmedParams = params.trim();
Creature npc1 = null; Creature npc1 = null;
Creature npc2 = null; Creature npc2 = null;
if (params.isEmpty()) if (trimmedParams.isEmpty())
{ {
npc1 = activeChar; npc1 = activeChar;
npc2 = (Creature) activeChar.getTarget(); npc2 = (Creature) activeChar.getTarget();
@@ -177,7 +177,7 @@ public class AdminFightCalculator implements IAdminCommandHandler
{ {
int mid1 = 0; int mid1 = 0;
int mid2 = 0; int mid2 = 0;
final StringTokenizer st = new StringTokenizer(params); final StringTokenizer st = new StringTokenizer(trimmedParams);
mid1 = Integer.parseInt(st.nextToken()); mid1 = Integer.parseInt(st.nextToken());
mid2 = Integer.parseInt(st.nextToken()); mid2 = Integer.parseInt(st.nextToken());
npc1 = new MonsterInstance(NpcData.getInstance().getTemplate(mid1)); npc1 = new MonsterInstance(NpcData.getInstance().getTemplate(mid1));
@@ -291,7 +291,7 @@ public class AdminFightCalculator implements IAdminCommandHandler
final NpcHtmlMessage adminReply = new NpcHtmlMessage(0, 1); final NpcHtmlMessage adminReply = new NpcHtmlMessage(0, 1);
final StringBuilder replyMSG = new StringBuilder(1000); final StringBuilder replyMSG = new StringBuilder(1000);
replyMSG.append("<html><title>Selected mobs to fight</title><body><table>"); replyMSG.append("<html><title>Selected mobs to fight</title><body><table>");
if (params.isEmpty()) if (trimmedParams.isEmpty())
{ {
replyMSG.append("<tr><td width=140>Parameter</td><td width=70>me</td><td width=70>target</td></tr>"); replyMSG.append("<tr><td width=140>Parameter</td><td width=70>me</td><td width=70>target</td></tr>");
} }
@@ -321,7 +321,7 @@ public class AdminFightCalculator implements IAdminCommandHandler
replyMSG.append("</tr></table><center><br>"); replyMSG.append("</tr></table><center><br>");
if (params.isEmpty()) if (trimmedParams.isEmpty())
{ {
replyMSG.append("<button value=\"Retry\" action=\"bypass -h admin_fight_calculator_show\" width=100 height=15 back=\"L2UI_ct1.button_df\" fore=\"L2UI_ct1.button_df\">"); replyMSG.append("<button value=\"Retry\" action=\"bypass -h admin_fight_calculator_show\" width=100 height=15 back=\"L2UI_ct1.button_df\" fore=\"L2UI_ct1.button_df\">");
} }
@@ -334,7 +334,7 @@ public class AdminFightCalculator implements IAdminCommandHandler
adminReply.setHtml(replyMSG.toString()); adminReply.setHtml(replyMSG.toString());
activeChar.sendPacket(adminReply); activeChar.sendPacket(adminReply);
if (params.length() != 0) if (trimmedParams.length() != 0)
{ {
npc1.deleteMe(); npc1.deleteMe();
npc2.deleteMe(); npc2.deleteMe();
@@ -49,8 +49,9 @@ public class AdminFortSiege implements IAdminCommandHandler
}; };
@Override @Override
public boolean useAdminCommand(String command, PlayerInstance activeChar) public boolean useAdminCommand(String commandValue, PlayerInstance activeChar)
{ {
String command = commandValue;
final StringTokenizer st = new StringTokenizer(command, " "); final StringTokenizer st = new StringTokenizer(command, " ");
command = st.nextToken(); // Get actual command command = st.nextToken(); // Get actual command
@@ -37,9 +37,10 @@ public class AdminInstanceZone implements IAdminCommandHandler
}; };
@Override @Override
public boolean useAdminCommand(String command, PlayerInstance activeChar) public boolean useAdminCommand(String commandValue, PlayerInstance activeChar)
{ {
final String target = (activeChar.getTarget() != null) ? activeChar.getTarget().getName() : "no-target"; final String target = (activeChar.getTarget() != null) ? activeChar.getTarget().getName() : "no-target";
String command = commandValue;
GMAudit.auditGMAction(activeChar.getName(), command, target, ""); GMAudit.auditGMAction(activeChar.getName(), command, target, "");
if (command.startsWith("admin_instancezone_clear")) if (command.startsWith("admin_instancezone_clear"))
{ {
@@ -86,8 +86,9 @@ public class AdminSkill implements IAdminCommandHandler
private static Skill[] adminSkills; private static Skill[] adminSkills;
@Override @Override
public boolean useAdminCommand(String command, PlayerInstance activeChar) public boolean useAdminCommand(String commandValue, PlayerInstance activeChar)
{ {
String command = commandValue;
if (command.equals("admin_show_skills")) if (command.equals("admin_show_skills"))
{ {
showMainPage(activeChar); showMainPage(activeChar);
@@ -343,9 +344,9 @@ public class AdminSkill implements IAdminCommandHandler
/** /**
* TODO: Externalize HTML * TODO: Externalize HTML
* @param activeChar the active Game Master. * @param activeChar the active Game Master.
* @param page * @param pageValue
*/ */
private void removeSkillsPage(PlayerInstance activeChar, int page) private void removeSkillsPage(PlayerInstance activeChar, int pageValue)
{ {
final WorldObject target = activeChar.getTarget(); final WorldObject target = activeChar.getTarget();
if ((target == null) || !target.isPlayer()) if ((target == null) || !target.isPlayer())
@@ -363,6 +364,7 @@ public class AdminSkill implements IAdminCommandHandler
maxPages++; maxPages++;
} }
int page = pageValue;
if (page > maxPages) if (page > maxPages)
{ {
page = maxPages; page = maxPages;
@@ -501,7 +501,7 @@ public class AdminSpawn implements IAdminCommandHandler
} }
} }
private void spawnMonster(PlayerInstance activeChar, String monsterId, int respawnTime, int mobCount, boolean permanent) private void spawnMonster(PlayerInstance activeChar, String monsterIdValue, int respawnTime, int mobCount, boolean permanentValue)
{ {
WorldObject target = activeChar.getTarget(); WorldObject target = activeChar.getTarget();
if (target == null) if (target == null)
@@ -510,6 +510,7 @@ public class AdminSpawn implements IAdminCommandHandler
} }
final NpcTemplate template1; final NpcTemplate template1;
String monsterId = monsterIdValue;
if (monsterId.matches("[0-9]*")) if (monsterId.matches("[0-9]*"))
{ {
// First parameter was an ID number // First parameter was an ID number
@@ -536,6 +537,8 @@ public class AdminSpawn implements IAdminCommandHandler
spawn.setAmount(mobCount); spawn.setAmount(mobCount);
spawn.setHeading(activeChar.getHeading()); spawn.setHeading(activeChar.getHeading());
spawn.setRespawnDelay(respawnTime); spawn.setRespawnDelay(respawnTime);
boolean permanent = permanentValue;
if (activeChar.isInInstance()) if (activeChar.isInInstance())
{ {
spawn.setInstanceId(activeChar.getInstanceId()); spawn.setInstanceId(activeChar.getInstanceId());
@@ -343,7 +343,7 @@ public class NpcViewMod implements IBypassHandler
return sb.toString(); return sb.toString();
} }
private void sendNpcDropList(PlayerInstance player, Npc npc, DropType dropType, int page) private void sendNpcDropList(PlayerInstance player, Npc npc, DropType dropType, int pageValue)
{ {
final List<DropHolder> dropList = npc.getTemplate().getDropList(dropType); final List<DropHolder> dropList = npc.getTemplate().getDropList(dropType);
if (dropList == null) if (dropList == null)
@@ -368,6 +368,7 @@ public class NpcViewMod implements IBypassHandler
pagesSb.append("</tr></table>"); pagesSb.append("</tr></table>");
} }
int page = pageValue;
if (page >= pages) if (page >= pages)
{ {
page = pages - 1; page = pages - 1;
@@ -101,17 +101,18 @@ public class QuestLink implements IBypassHandler
.collect(Collectors.toSet()); .collect(Collectors.toSet());
//@formatter:on //@formatter:on
Collection<Quest> questList = quests;
if (Config.ORDER_QUEST_LIST_BY_QUESTID) if (Config.ORDER_QUEST_LIST_BY_QUESTID)
{ {
final Map<Integer, Quest> orderedQuests = new TreeMap<>(); // Use TreeMap to order quests final Map<Integer, Quest> orderedQuests = new TreeMap<>(); // Use TreeMap to order quests
for (Quest q : quests) for (Quest q : questList)
{ {
orderedQuests.put(q.getId(), q); orderedQuests.put(q.getId(), q);
} }
quests = orderedQuests.values(); questList = orderedQuests.values();
} }
for (Quest quest : quests) for (Quest quest : questList)
{ {
final QuestState qs = player.getQuestState(quest.getScriptName()); final QuestState qs = player.getQuestState(quest.getScriptName());
if ((qs == null) || qs.isCreated() || (qs.isCompleted() && qs.isNowAvailable())) if ((qs == null) || qs.isCreated() || (qs.isCompleted() && qs.isNowAvailable()))
@@ -43,7 +43,7 @@ public class ChatGeneral implements IChatHandler
}; };
@Override @Override
public void handleChat(ChatType type, PlayerInstance activeChar, String params, String text) public void handleChat(ChatType type, PlayerInstance activeChar, String paramsValue, String text)
{ {
boolean vcdUsed = false; boolean vcdUsed = false;
if (text.startsWith(".")) if (text.startsWith("."))
@@ -51,6 +51,7 @@ public class ChatGeneral implements IChatHandler
final StringTokenizer st = new StringTokenizer(text); final StringTokenizer st = new StringTokenizer(text);
final IVoicedCommandHandler vch; final IVoicedCommandHandler vch;
String command = ""; String command = "";
String params = paramsValue;
if (st.countTokens() > 1) if (st.countTokens() > 1)
{ {
command = st.nextToken().substring(1); command = st.nextToken().substring(1);
@@ -176,8 +176,9 @@ public class ClanBoard implements IWriteBoardHandler
} }
} }
private void clanList(PlayerInstance player, int index) private void clanList(PlayerInstance player, int indexValue)
{ {
int index = indexValue;
if (index < 1) if (index < 1)
{ {
index = 1; index = 1;
@@ -45,8 +45,9 @@ public class AddHate extends AbstractEffect
} }
@Override @Override
public void instant(Creature effector, Creature effected, Skill skill, ItemInstance item) public void instant(Creature creature, Creature effected, Skill skill, ItemInstance item)
{ {
Creature effector = creature;
if (_affectSummoner && (effector.getSummoner() != null)) if (_affectSummoner && (effector.getSummoner() != null))
{ {
effector = effector.getSummoner(); effector = effector.getSummoner();
@@ -98,11 +98,11 @@ public class Nursery extends AbstractInstance
{ {
if (gameTime == 0) if (gameTime == 0)
{ {
player = instance.getFirstPlayer(); final PlayerInstance firstPlayer = instance.getFirstPlayer();
if ((player != null) && hasQuestItems(player, SCORE_ITEM)) if ((firstPlayer != null) && hasQuestItems(firstPlayer, SCORE_ITEM))
{ {
final int itemCount = (int) getQuestItemsCount(player, SCORE_ITEM); final int itemCount = (int) getQuestItemsCount(firstPlayer, SCORE_ITEM);
takeItems(player, SCORE_ITEM, itemCount); takeItems(firstPlayer, SCORE_ITEM, itemCount);
npcVars.increaseInt("GAME_POINTS", 0, itemCount); npcVars.increaseInt("GAME_POINTS", 0, itemCount);
} }
instance.despawnGroup("GAME_MONSTERS"); instance.despawnGroup("GAME_MONSTERS");
@@ -198,45 +198,42 @@ public class Q00126_TheNameOfEvil2 extends Quest
case "DO_One": case "DO_One":
{ {
qs.set("DO", "1"); qs.set("DO", "1");
event = "32122-4d.html"; return "32122-4d.html";
break;
} }
case "MI_One": case "MI_One":
{ {
qs.set("MI", "1"); qs.set("MI", "1");
event = "32122-4f.html"; return "32122-4f.html";
break;
} }
case "FA_One": case "FA_One":
{ {
qs.set("FA", "1"); qs.set("FA", "1");
event = "32122-4h.html"; return "32122-4h.html";
break;
} }
case "SOL_One": case "SOL_One":
{ {
qs.set("SOL", "1"); qs.set("SOL", "1");
event = "32122-4j.html"; return "32122-4j.html";
break;
} }
case "FA2_One": case "FA2_One":
{ {
qs.set("FA2", "1"); qs.set("FA2", "1");
if (qs.isCond(14) && (qs.getInt("DO") > 0) && (qs.getInt("MI") > 0) && (qs.getInt("FA") > 0) && (qs.getInt("SOL") > 0) && (qs.getInt("FA2") > 0)) if (qs.isCond(14) && (qs.getInt("DO") > 0) && (qs.getInt("MI") > 0) && (qs.getInt("FA") > 0) && (qs.getInt("SOL") > 0) && (qs.getInt("FA2") > 0))
{ {
event = "32122-4n.html";
qs.setCond(15, true); qs.setCond(15, true);
} qs.unset("DO");
else qs.unset("MI");
{ qs.unset("FA");
event = "32122-4m.html"; qs.unset("SOL");
qs.unset("FA2");
return "32122-4n.html";
} }
qs.unset("DO"); qs.unset("DO");
qs.unset("MI"); qs.unset("MI");
qs.unset("FA"); qs.unset("FA");
qs.unset("SOL"); qs.unset("SOL");
qs.unset("FA2"); qs.unset("FA2");
break; return "32122-4m.html";
} }
case "32122-4m.html": case "32122-4m.html":
{ {
@@ -250,45 +247,42 @@ public class Q00126_TheNameOfEvil2 extends Quest
case "FA_Two": case "FA_Two":
{ {
qs.set("FA", "1"); qs.set("FA", "1");
event = "32122-5a.html"; return "32122-5a.html";
break;
} }
case "SOL_Two": case "SOL_Two":
{ {
qs.set("SOL", "1"); qs.set("SOL", "1");
event = "32122-5c.html"; return "32122-5c.html";
break;
} }
case "TI_Two": case "TI_Two":
{ {
qs.set("TI", "1"); qs.set("TI", "1");
event = "32122-5e.html"; return "32122-5e.html";
break;
} }
case "SOL2_Two": case "SOL2_Two":
{ {
qs.set("SOL2", "1"); qs.set("SOL2", "1");
event = "32122-5g.html"; return "32122-5g.html";
break;
} }
case "FA2_Two": case "FA2_Two":
{ {
qs.set("FA2", "1"); qs.set("FA2", "1");
if (qs.isCond(15) && (qs.getInt("FA") > 0) && (qs.getInt("SOL") > 0) && (qs.getInt("TI") > 0) && (qs.getInt("SOL2") > 0) && (qs.getInt("FA2") > 0)) if (qs.isCond(15) && (qs.getInt("FA") > 0) && (qs.getInt("SOL") > 0) && (qs.getInt("TI") > 0) && (qs.getInt("SOL2") > 0) && (qs.getInt("FA2") > 0))
{ {
event = "32122-5j.html";
qs.setCond(16, true); qs.setCond(16, true);
} qs.unset("FA");
else qs.unset("SOL");
{ qs.unset("TI");
event = "32122-5i.html"; qs.unset("SOL2");
qs.unset("FA2");
return "32122-5j.html";
} }
qs.unset("FA"); qs.unset("FA");
qs.unset("SOL"); qs.unset("SOL");
qs.unset("TI"); qs.unset("TI");
qs.unset("SOL2"); qs.unset("SOL2");
qs.unset("FA2"); qs.unset("FA2");
break; return "32122-5i.html";
} }
case "32122-5i.html": case "32122-5i.html":
{ {
@@ -302,45 +296,42 @@ public class Q00126_TheNameOfEvil2 extends Quest
case "SOL_Three": case "SOL_Three":
{ {
qs.set("SOL", "1"); qs.set("SOL", "1");
event = "32122-6a.html"; return "32122-6a.html";
break;
} }
case "FA_Three": case "FA_Three":
{ {
qs.set("FA", "1"); qs.set("FA", "1");
event = "32122-6c.html"; return "32122-6c.html";
break;
} }
case "MI_Three": case "MI_Three":
{ {
qs.set("MI", "1"); qs.set("MI", "1");
event = "32122-6e.html"; return "32122-6e.html";
break;
} }
case "FA2_Three": case "FA2_Three":
{ {
qs.set("FA2", "1"); qs.set("FA2", "1");
event = "32122-6g.html"; return "32122-6g.html";
break;
} }
case "MI2_Three": case "MI2_Three":
{ {
qs.set("MI2", "1"); qs.set("MI2", "1");
if (qs.isCond(16) && (qs.getInt("SOL") > 0) && (qs.getInt("FA") > 0) && (qs.getInt("MI") > 0) && (qs.getInt("FA2") > 0) && (qs.getInt("MI2") > 0)) if (qs.isCond(16) && (qs.getInt("SOL") > 0) && (qs.getInt("FA") > 0) && (qs.getInt("MI") > 0) && (qs.getInt("FA2") > 0) && (qs.getInt("MI2") > 0))
{ {
event = "32122-6j.html";
qs.setCond(17, true); qs.setCond(17, true);
} qs.unset("SOL");
else qs.unset("FA");
{ qs.unset("MI");
event = "32122-6i.html"; qs.unset("FA2");
qs.unset("MI2");
return "32122-6j.html";
} }
qs.unset("SOL"); qs.unset("SOL");
qs.unset("FA"); qs.unset("FA");
qs.unset("MI"); qs.unset("MI");
qs.unset("FA2"); qs.unset("FA2");
qs.unset("MI2"); qs.unset("MI2");
break; return "32122-6i.html";
} }
case "32122-6i.html": case "32122-6i.html":
{ {
@@ -310,30 +310,32 @@ public class Q00386_StolenDignity extends Quest
private String fillBoard(QuestState qs, String html) private String fillBoard(QuestState qs, String html)
{ {
String result = html;
for (int i0 = 0; i0 < 9; i0 += 1) for (int i0 = 0; i0 < 9; i0 += 1)
{ {
final int i1 = getNumberFromBingoBoard(qs, i0); final int i1 = getNumberFromBingoBoard(qs, i0);
if (isSelectedBingoNumber(qs, i1)) if (isSelectedBingoNumber(qs, i1))
{ {
html = html.replace("<?Cell" + (i0 + 1) + "?>", Integer.toString(i1)); result = result.replace("<?Cell" + (i0 + 1) + "?>", Integer.toString(i1));
} }
else else
{ {
html = html.replace("<?Cell" + (i0 + 1) + "?>", "?"); result = result.replace("<?Cell" + (i0 + 1) + "?>", "?");
} }
} }
return html; return result;
} }
private String colorBoard(QuestState qs, String html) private String colorBoard(QuestState qs, String html)
{ {
String result = html;
for (int i0 = 0; i0 < 9; i0 += 1) for (int i0 = 0; i0 < 9; i0 += 1)
{ {
final int i1 = getNumberFromBingoBoard(qs, i0); final int i1 = getNumberFromBingoBoard(qs, i0);
html = html.replace("<?FontColor" + (i0 + 1) + "?>", isSelectedBingoNumber(qs, i1) ? "ff0000" : "ffffff"); result = result.replace("<?FontColor" + (i0 + 1) + "?>", isSelectedBingoNumber(qs, i1) ? "ff0000" : "ffffff");
html = html.replace("<?Cell" + (i0 + 1) + "?>", Integer.toString(i1)); result = result.replace("<?Cell" + (i0 + 1) + "?>", Integer.toString(i1));
} }
return html; return result;
} }
private String beforeReward(PlayerInstance player, QuestState qs, int num) private String beforeReward(PlayerInstance player, QuestState qs, int num)
@@ -102,7 +102,7 @@ public class Q00500_BrothersBoundInChains extends Quest
} }
else else
{ {
event = "30981-05.html"; return "30981-05.html";
} }
break; break;
} }
@@ -123,13 +123,13 @@ public class Q00500_BrothersBoundInChains extends Quest
{ {
// If player delete QuestItems: Need check how it work on retail. // If player delete QuestItems: Need check how it work on retail.
qs.setCond(1); qs.setCond(1);
event = "30981-07.html"; return "30981-07.html";
} }
break; break;
} }
default: default:
{ {
event = getNoQuestMsg(player); return getNoQuestMsg(player);
} }
} }
@@ -189,12 +189,9 @@ public class Q00663_SeductiveWhispers extends Quest
// practice // practice
if (getQuestItemsCount(player, SPIRIT_BEAD) < 1) if (getQuestItemsCount(player, SPIRIT_BEAD) < 1)
{ {
event = "30846-13.html"; return "30846-13.html";
} }
else
{
takeItems(player, SPIRIT_BEAD, 1); takeItems(player, SPIRIT_BEAD, 1);
}
break; break;
} }
case "30846-22.html": case "30846-22.html":
@@ -207,8 +204,7 @@ public class Q00663_SeductiveWhispers extends Quest
{ {
playerCard = getRandomCard(); playerCard = getRandomCard();
} }
event = play(player, true, true); return play(player, true, true);
break;
} }
case "30846-23.html": case "30846-23.html":
{ {
@@ -221,19 +217,15 @@ public class Q00663_SeductiveWhispers extends Quest
{ {
npcCard = getRandomCard(); npcCard = getRandomCard();
} }
event = play(player, false, true); return play(player, false, true);
break;
} }
case "30846-15.html": case "30846-15.html":
{ {
if (getQuestItemsCount(player, SPIRIT_BEAD) < 50) if (getQuestItemsCount(player, SPIRIT_BEAD) < 50)
{ {
event = "30846-08.html"; return "30846-08.html";
} }
else
{
takeItems(player, SPIRIT_BEAD, 50); takeItems(player, SPIRIT_BEAD, 50);
}
break; break;
} }
case "30846-16.html": case "30846-16.html":
@@ -247,8 +239,7 @@ public class Q00663_SeductiveWhispers extends Quest
{ {
playerCard = getRandomCard(); playerCard = getRandomCard();
} }
event = play(player, true, false); return play(player, true, false);
break;
} }
case "30846-17.html": case "30846-17.html":
{ {
@@ -262,9 +253,7 @@ public class Q00663_SeductiveWhispers extends Quest
{ {
npcCard = getRandomCard(); npcCard = getRandomCard();
} }
return play(player, false, false);
event = play(player, false, false);
break;
} }
case "30846-20.html": case "30846-20.html":
{ {
@@ -484,6 +473,7 @@ public class Q00663_SeductiveWhispers extends Quest
{ {
SUN("Sun card"), SUN("Sun card"),
MOON("Moon card"); MOON("Moon card");
private String _name; private String _name;
Side(String name) Side(String name)
@@ -350,46 +350,46 @@ public class CommonUtil
/** /**
* Re-Maps a value from one range to another. * Re-Maps a value from one range to another.
* @param input * @param inputValue
* @param inputMin * @param inputMin
* @param inputMax * @param inputMax
* @param outputMin * @param outputMin
* @param outputMax * @param outputMax
* @return The mapped value * @return The mapped value
*/ */
public static int map(int input, int inputMin, int inputMax, int outputMin, int outputMax) public static int map(int inputValue, int inputMin, int inputMax, int outputMin, int outputMax)
{ {
input = constrain(input, inputMin, inputMax); final int input = constrain(inputValue, inputMin, inputMax);
return (((input - inputMin) * (outputMax - outputMin)) / (inputMax - inputMin)) + outputMin; return (((input - inputMin) * (outputMax - outputMin)) / (inputMax - inputMin)) + outputMin;
} }
/** /**
* Re-Maps a value from one range to another. * Re-Maps a value from one range to another.
* @param input * @param inputValue
* @param inputMin * @param inputMin
* @param inputMax * @param inputMax
* @param outputMin * @param outputMin
* @param outputMax * @param outputMax
* @return The mapped value * @return The mapped value
*/ */
public static long map(long input, long inputMin, long inputMax, long outputMin, long outputMax) public static long map(long inputValue, long inputMin, long inputMax, long outputMin, long outputMax)
{ {
input = constrain(input, inputMin, inputMax); final long input = constrain(inputValue, inputMin, inputMax);
return (((input - inputMin) * (outputMax - outputMin)) / (inputMax - inputMin)) + outputMin; return (((input - inputMin) * (outputMax - outputMin)) / (inputMax - inputMin)) + outputMin;
} }
/** /**
* Re-Maps a value from one range to another. * Re-Maps a value from one range to another.
* @param input * @param inputValue
* @param inputMin * @param inputMin
* @param inputMax * @param inputMax
* @param outputMin * @param outputMin
* @param outputMax * @param outputMax
* @return The mapped value * @return The mapped value
*/ */
public static double map(double input, double inputMin, double inputMax, double outputMin, double outputMax) public static double map(double inputValue, double inputMin, double inputMax, double outputMin, double outputMax)
{ {
input = constrain(input, inputMin, inputMax); final double input = constrain(inputValue, inputMin, inputMax);
return (((input - inputMin) * (outputMax - outputMin)) / (inputMax - inputMin)) + outputMin; return (((input - inputMin) * (outputMax - outputMin)) / (inputMax - inputMin)) + outputMin;
} }
@@ -59,12 +59,14 @@ public class HexUtils
/** /**
* Method to generate the hexadecimal character presentation of a byte * Method to generate the hexadecimal character presentation of a byte
* @param data byte to generate the hexadecimal character presentation from * @param data byte to generate the hexadecimal character presentation from
* @param dstHexChars the char array the hexadecimal character presentation should be copied to, if this is null, dstOffset is ignored and a new char array with 2 elements is created * @param dstHexCharsValue the char array the hexadecimal character presentation should be copied to, if this is null, dstOffset is ignored and a new char array with 2 elements is created
* @param dstOffset offset at which the hexadecimal character presentation is copied to dstHexChars * @param dstOffsetValue offset at which the hexadecimal character presentation is copied to dstHexChars
* @return the char array the hexadecimal character presentation was copied to * @return the char array the hexadecimal character presentation was copied to
*/ */
public static char[] b2HexChars(byte data, char[] dstHexChars, int dstOffset) public static char[] b2HexChars(byte data, char[] dstHexCharsValue, int dstOffsetValue)
{ {
char[] dstHexChars = dstHexCharsValue;
int dstOffset = dstOffsetValue;
if (dstHexChars == null) if (dstHexChars == null)
{ {
dstHexChars = new char[2]; dstHexChars = new char[2];
@@ -92,12 +94,14 @@ public class HexUtils
/** /**
* Method to generate the hexadecimal character presentation of an integer * Method to generate the hexadecimal character presentation of an integer
* @param data integer to generate the hexadecimal character presentation from * @param data integer to generate the hexadecimal character presentation from
* @param dstHexChars the char array the hexadecimal character presentation should be copied to, if this is null, dstOffset is ignored and a new char array with 8 elements is created * @param dstHexCharsValue the char array the hexadecimal character presentation should be copied to, if this is null, dstOffset is ignored and a new char array with 8 elements is created
* @param dstOffset offset at which the hexadecimal character presentation is copied to dstHexChars * @param dstOffsetValue offset at which the hexadecimal character presentation is copied to dstHexChars
* @return the char array the hexadecimal character presentation was copied to * @return the char array the hexadecimal character presentation was copied to
*/ */
public static char[] int2HexChars(int data, char[] dstHexChars, int dstOffset) public static char[] int2HexChars(int data, char[] dstHexCharsValue, int dstOffsetValue)
{ {
char[] dstHexChars = dstHexCharsValue;
int dstOffset = dstOffsetValue;
if (dstHexChars == null) if (dstHexChars == null)
{ {
dstHexChars = new char[8]; dstHexChars = new char[8];
@@ -108,6 +112,7 @@ public class HexUtils
b2HexChars((byte) ((data & 0x00FF0000) >> 16), dstHexChars, dstOffset + 2); b2HexChars((byte) ((data & 0x00FF0000) >> 16), dstHexChars, dstOffset + 2);
b2HexChars((byte) ((data & 0x0000FF00) >> 8), dstHexChars, dstOffset + 4); b2HexChars((byte) ((data & 0x0000FF00) >> 8), dstHexChars, dstOffset + 4);
b2HexChars((byte) (data & 0x000000FF), dstHexChars, dstOffset + 6); b2HexChars((byte) (data & 0x000000FF), dstHexChars, dstOffset + 6);
return dstHexChars; return dstHexChars;
} }
@@ -129,12 +134,14 @@ public class HexUtils
* @param data byte array to generate the hexadecimal character presentation from * @param data byte array to generate the hexadecimal character presentation from
* @param offset offset where to start in data array * @param offset offset where to start in data array
* @param len number of bytes to generate the hexadecimal character presentation from * @param len number of bytes to generate the hexadecimal character presentation from
* @param dstHexChars the char array the hexadecimal character presentation should be copied to, if this is null, dstOffset is ignored and a new char array with len*2 elements is created * @param dstHexCharsValue the char array the hexadecimal character presentation should be copied to, if this is null, dstOffset is ignored and a new char array with len*2 elements is created
* @param dstOffset offset at which the hexadecimal character presentation is copied to dstHexChars * @param dstOffsetValue offset at which the hexadecimal character presentation is copied to dstHexChars
* @return the char array the hexadecimal character presentation was copied to * @return the char array the hexadecimal character presentation was copied to
*/ */
public static char[] bArr2HexChars(byte[] data, int offset, int len, char[] dstHexChars, int dstOffset) public static char[] bArr2HexChars(byte[] data, int offset, int len, char[] dstHexCharsValue, int dstOffsetValue)
{ {
char[] dstHexChars = dstHexCharsValue;
int dstOffset = dstOffsetValue;
if (dstHexChars == null) if (dstHexChars == null)
{ {
dstHexChars = new char[len * 2]; dstHexChars = new char[len * 2];
@@ -157,8 +164,10 @@ public class HexUtils
return bArr2AsciiChars(data, offset, len, new char[len], 0); return bArr2AsciiChars(data, offset, len, new char[len], 0);
} }
public static char[] bArr2AsciiChars(byte[] data, int offset, int len, char[] dstAsciiChars, int dstOffset) public static char[] bArr2AsciiChars(byte[] data, int offset, int len, char[] dstAsciiCharsValue, int dstOffsetValue)
{ {
char[] dstAsciiChars = dstAsciiCharsValue;
int dstOffset = dstOffsetValue;
if (dstAsciiChars == null) if (dstAsciiChars == null)
{ {
dstAsciiChars = new char[len]; dstAsciiChars = new char[len];
@@ -1130,6 +1130,7 @@ public class BlowfishEngine
* @param xr * @param xr
* @param table * @param table
*/ */
@SuppressWarnings("all")
private void processTable(int xl, int xr, int[] table) private void processTable(int xl, int xr, int[] table)
{ {
final int size = table.length; final int size = table.length;
@@ -489,9 +489,9 @@ public class GameServer
INSTANCE = new GameServer(); INSTANCE = new GameServer();
} }
private void printSection(String s) private void printSection(String section)
{ {
s = "=[ " + s + " ]"; String s = "=[ " + section + " ]";
while (s.length() < 61) while (s.length() < 61)
{ {
s = "-" + s; s = "-" + s;
@@ -99,11 +99,7 @@ public class Shutdown extends Thread
*/ */
public Shutdown(int seconds, boolean restart) public Shutdown(int seconds, boolean restart)
{ {
if (seconds < 0) _secondsShut = Math.max(0, seconds);
{
seconds = 0;
}
_secondsShut = seconds;
_shutdownMode = restart ? GM_RESTART : GM_SHUTDOWN; _shutdownMode = restart ? GM_RESTART : GM_SHUTDOWN;
} }
@@ -423,13 +423,14 @@ public abstract class AbstractAI implements Ctrl
* Move the actor to Pawn server side AND client side by sending Server->Client packet MoveToPawn <i>(broadcast)</i>.<br> * Move the actor to Pawn server side AND client side by sending Server->Client packet MoveToPawn <i>(broadcast)</i>.<br>
* <font color=#FF0000><b><u>Caution</u>: Low level function, used by AI subclasses</b></font> * <font color=#FF0000><b><u>Caution</u>: Low level function, used by AI subclasses</b></font>
* @param pawn * @param pawn
* @param offset * @param offsetValue
*/ */
public void moveToPawn(WorldObject pawn, int offset) public void moveToPawn(WorldObject pawn, int offsetValue)
{ {
// Check if actor can move // Check if actor can move
if (!_actor.isMovementDisabled() && !_actor.isAttackingNow() && !_actor.isCastingNow()) if (!_actor.isMovementDisabled() && !_actor.isAttackingNow() && !_actor.isCastingNow())
{ {
int offset = offsetValue;
if (offset < 10) if (offset < 10)
{ {
offset = 10; offset = 10;
@@ -199,12 +199,13 @@ public class AttackableAI extends CreatureAI
/** /**
* Set the Intention of this CreatureAI and create an AI Task executed every 1s (call onEvtThink method) for this Attackable.<br> * Set the Intention of this CreatureAI and create an AI Task executed every 1s (call onEvtThink method) for this Attackable.<br>
* <font color=#FF0000><b><u>Caution</u>: If actor _knowPlayer isn't EMPTY, AI_INTENTION_IDLE will be change in AI_INTENTION_ACTIVE</b></font> * <font color=#FF0000><b><u>Caution</u>: If actor _knowPlayer isn't EMPTY, AI_INTENTION_IDLE will be change in AI_INTENTION_ACTIVE</b></font>
* @param intention The new Intention to set to the AI * @param newIntention The new Intention to set to the AI
* @param args The first parameter of the Intention * @param args The first parameter of the Intention
*/ */
@Override @Override
synchronized void changeIntention(CtrlIntention intention, Object... args) synchronized void changeIntention(CtrlIntention newIntention, Object... args)
{ {
CtrlIntention intention = newIntention;
if ((intention == AI_INTENTION_IDLE) || (intention == AI_INTENTION_ACTIVE)) if ((intention == AI_INTENTION_IDLE) || (intention == AI_INTENTION_ACTIVE))
{ {
// Check if actor is not dead // Check if actor is not dead
@@ -945,10 +945,10 @@ public class CreatureAI extends AbstractAI
* <li>PLayerAI, SummonAI</li> * <li>PLayerAI, SummonAI</li>
* </ul> * </ul>
* @param target The targeted WorldObject * @param target The targeted WorldObject
* @param offset The Interact area radius * @param offsetValue The Interact area radius
* @return True if a movement must be done * @return True if a movement must be done
*/ */
protected boolean maybeMoveToPawn(WorldObject target, int offset) protected boolean maybeMoveToPawn(WorldObject target, int offsetValue)
{ {
// Get the distance between the current position of the Creature and the target (x,y) // Get the distance between the current position of the Creature and the target (x,y)
if (target == null) if (target == null)
@@ -956,12 +956,12 @@ public class CreatureAI extends AbstractAI
LOGGER.warning("maybeMoveToPawn: target == NULL!"); LOGGER.warning("maybeMoveToPawn: target == NULL!");
return false; return false;
} }
if (offset < 0) if (offsetValue < 0)
{ {
return false; // skill radius -1 return false; // skill radius -1
} }
int offsetWithCollision = offset + _actor.getTemplate().getCollisionRadius(); int offsetWithCollision = offsetValue + _actor.getTemplate().getCollisionRadius();
if (target.isCreature()) if (target.isCreature())
{ {
offsetWithCollision += ((Creature) target).getTemplate().getCollisionRadius(); offsetWithCollision += ((Creature) target).getTemplate().getCollisionRadius();
@@ -1008,6 +1008,7 @@ public class CreatureAI extends AbstractAI
} }
stopFollow(); stopFollow();
int offset = offsetValue;
if (target.isCreature() && !target.isDoor()) if (target.isCreature() && !target.isDoor())
{ {
if (((Creature) target).isMoving()) if (((Creature) target).isMoving())
@@ -203,11 +203,12 @@ public class DoppelgangerAI extends CreatureAI
} }
@Override @Override
public void moveToPawn(WorldObject pawn, int offset) public void moveToPawn(WorldObject pawn, int offsetValue)
{ {
// Check if actor can move // Check if actor can move
if (!_actor.isMovementDisabled() && (_actor.getMoveSpeed() > 0)) if (!_actor.isMovementDisabled() && (_actor.getMoveSpeed() > 0))
{ {
int offset = offsetValue;
if (offset < 10) if (offset < 10)
{ {
offset = 10; offset = 10;
@@ -83,9 +83,9 @@ public class AbilityPointsData implements IXmlReader
return null; return null;
} }
public long getPrice(int points) public long getPrice(int value)
{ {
points++; // for next point final int points = value + 1; // for next point
final RangeAbilityPointsHolder holder = getHolder(points); final RangeAbilityPointsHolder holder = getHolder(points);
if (holder == null) if (holder == null)
{ {
@@ -96,7 +96,7 @@ public class AbilityPointsData implements IXmlReader
} }
// No data found // No data found
return points >= 13 ? 1_000_000_000 : points >= 9 ? 750_000_000 : points >= 5 ? 500_000_000 : 250_000_000; return points >= 13 ? 1000000000 : points >= 9 ? 750000000 : points >= 5 ? 500000000 : 250000000;
} }
return holder.getSP(); return holder.getSP();
} }
@@ -103,7 +103,7 @@ public class ExperienceData implements IXmlReader
{ {
if (level > Config.PLAYER_MAXIMUM_LEVEL) if (level > Config.PLAYER_MAXIMUM_LEVEL)
{ {
level = Config.PLAYER_MAXIMUM_LEVEL; return _expTable.get((int) Config.PLAYER_MAXIMUM_LEVEL);
} }
return _expTable.get(level); return _expTable.get(level);
} }
@@ -112,7 +112,7 @@ public class ExperienceData implements IXmlReader
{ {
if (level > Config.PLAYER_MAXIMUM_LEVEL) if (level > Config.PLAYER_MAXIMUM_LEVEL)
{ {
level = Config.PLAYER_MAXIMUM_LEVEL; return _traningRateTable.get((int) Config.PLAYER_MAXIMUM_LEVEL);
} }
return _traningRateTable.get(level); return _traningRateTable.get(level);
} }
@@ -109,14 +109,15 @@ public class ExtendDropData implements IXmlReader
StatSet statSet = null; StatSet statSet = null;
List<Object> list = null; List<Object> list = null;
Object text = null; Object text = null;
for (node = node.getFirstChild(); node != null; node = node.getNextSibling()) Node n = node;
for (n = n.getFirstChild(); n != null; n = n.getNextSibling())
{ {
final String nodeName = node.getNodeName(); final String nodeName = n.getNodeName();
switch (node.getNodeName()) switch (n.getNodeName())
{ {
case "#text": case "#text":
{ {
final String value = node.getNodeValue().trim(); final String value = n.getNodeValue().trim();
if (!value.isEmpty()) if (!value.isEmpty())
{ {
text = value; text = value;
@@ -130,7 +131,7 @@ public class ExtendDropData implements IXmlReader
list = new LinkedList<>(); list = new LinkedList<>();
} }
final Object value = parseValue(node); final Object value = parseValue(n);
if (value != null) if (value != null)
{ {
list.add(value); list.add(value);
@@ -139,7 +140,7 @@ public class ExtendDropData implements IXmlReader
} }
default: default:
{ {
final Object value = parseValue(node); final Object value = parseValue(n);
if (value != null) if (value != null)
{ {
if (statSet == null) if (statSet == null)
@@ -156,7 +157,7 @@ public class ExtendDropData implements IXmlReader
{ {
if (text != null) if (text != null)
{ {
throw new IllegalArgumentException("Text and list in same node are not allowed. Node[" + node + "]"); throw new IllegalArgumentException("Text and list in same node are not allowed. Node[" + n + "]");
} }
if (statSet != null) if (statSet != null)
{ {
@@ -171,7 +172,7 @@ public class ExtendDropData implements IXmlReader
{ {
if (list != null) if (list != null)
{ {
throw new IllegalArgumentException("Text and list in same node are not allowed. Node[" + node + "]"); throw new IllegalArgumentException("Text and list in same node are not allowed. Node[" + n + "]");
} }
if (statSet != null) if (statSet != null)
{ {
@@ -224,10 +224,10 @@ public class MultisellData implements IXmlReader
* @param player * @param player
* @param npc * @param npc
* @param inventoryOnly * @param inventoryOnly
* @param ingredientMultiplier * @param ingredientMultiplierValue
* @param productMultiplier * @param productMultiplierValue
*/ */
public void separateAndSend(int listId, PlayerInstance player, Npc npc, boolean inventoryOnly, double ingredientMultiplier, double productMultiplier) public void separateAndSend(int listId, PlayerInstance player, Npc npc, boolean inventoryOnly, double ingredientMultiplierValue, double productMultiplierValue)
{ {
final MultisellListHolder template = _multisells.get(listId); final MultisellListHolder template = _multisells.get(listId);
if (template == null) if (template == null)
@@ -250,9 +250,8 @@ public class MultisellData implements IXmlReader
} }
// Check if ingredient/product multipliers are set, if not, set them to the template value. // Check if ingredient/product multipliers are set, if not, set them to the template value.
ingredientMultiplier = (Double.isNaN(ingredientMultiplier) ? template.getIngredientMultiplier() : ingredientMultiplier); final double ingredientMultiplier = (Double.isNaN(ingredientMultiplierValue) ? template.getIngredientMultiplier() : ingredientMultiplierValue);
productMultiplier = (Double.isNaN(productMultiplier) ? template.getProductMultiplier() : productMultiplier); final double productMultiplier = (Double.isNaN(productMultiplierValue) ? template.getProductMultiplier() : productMultiplierValue);
final PreparedMultisellListHolder list = new PreparedMultisellListHolder(template, inventoryOnly, player.getInventory(), npc, ingredientMultiplier, productMultiplier); final PreparedMultisellListHolder list = new PreparedMultisellListHolder(template, inventoryOnly, player.getInventory(), npc, ingredientMultiplier, productMultiplier);
int index = 0; int index = 0;
do do
@@ -262,6 +261,7 @@ public class MultisellData implements IXmlReader
index += PAGE_SIZE; index += PAGE_SIZE;
} }
while (index < list.getEntries().size()); while (index < list.getEntries().size());
player.setMultiSell(list); player.setMultiSell(list);
} }
@@ -98,6 +98,7 @@ public class SendMessageLocalisationData implements IXmlReader
// Consider using proper SystemMessages where possible. // Consider using proper SystemMessages where possible.
String[] searchMessage; String[] searchMessage;
String[] replacementMessage; String[] replacementMessage;
String localisation = message;
boolean found; boolean found;
for (Entry<String[], String[]> entry : localisations.entrySet()) for (Entry<String[], String[]> entry : localisations.entrySet())
{ {
@@ -107,7 +108,7 @@ public class SendMessageLocalisationData implements IXmlReader
// Exact match. // Exact match.
if (searchMessage.length == 1) if (searchMessage.length == 1)
{ {
if (searchMessage[0].equals(message)) if (searchMessage[0].equals(localisation))
{ {
return replacementMessage[0]; return replacementMessage[0];
} }
@@ -117,7 +118,7 @@ public class SendMessageLocalisationData implements IXmlReader
found = true; found = true;
for (String part : searchMessage) for (String part : searchMessage)
{ {
if (!message.contains(part)) if (!localisation.contains(part))
{ {
found = false; found = false;
break; break;
@@ -127,12 +128,13 @@ public class SendMessageLocalisationData implements IXmlReader
{ {
for (int i = 0; i < searchMessage.length; i++) for (int i = 0; i < searchMessage.length; i++)
{ {
message = message.replace(searchMessage[i], replacementMessage[i]); localisation = localisation.replace(searchMessage[i], replacementMessage[i]);
} }
break; break;
} }
} }
} }
return localisation;
} }
} }
return message; return message;
@@ -446,7 +446,8 @@ public class SkillData implements IXmlReader
private NamedParamInfo parseNamedParamInfo(Node node, Map<String, Map<Integer, Map<Integer, Object>>> variableValues) private NamedParamInfo parseNamedParamInfo(Node node, Map<String, Map<Integer, Map<Integer, Object>>> variableValues)
{ {
final NamedNodeMap attributes = node.getAttributes(); Node n = node;
final NamedNodeMap attributes = n.getAttributes();
final String name = parseString(attributes, "name"); final String name = parseString(attributes, "name");
final Integer level = parseInteger(attributes, "level"); final Integer level = parseInteger(attributes, "level");
final Integer fromLevel = parseInteger(attributes, "fromLevel", level); final Integer fromLevel = parseInteger(attributes, "fromLevel", level);
@@ -455,11 +456,11 @@ public class SkillData implements IXmlReader
final Integer fromSubLevel = parseInteger(attributes, "fromSubLevel", subLevel); final Integer fromSubLevel = parseInteger(attributes, "fromSubLevel", subLevel);
final Integer toSubLevel = parseInteger(attributes, "toSubLevel", subLevel); final Integer toSubLevel = parseInteger(attributes, "toSubLevel", subLevel);
final Map<Integer, Map<Integer, StatSet>> info = new HashMap<>(); final Map<Integer, Map<Integer, StatSet>> info = new HashMap<>();
for (node = node.getFirstChild(); node != null; node = node.getNextSibling()) for (n = n.getFirstChild(); n != null; n = n.getNextSibling())
{ {
if (!node.getNodeName().equals("#text")) if (!n.getNodeName().equals("#text"))
{ {
parseInfo(node, variableValues, info); parseInfo(n, variableValues, info);
} }
} }
return new NamedParamInfo(name, fromLevel, toLevel, fromSubLevel, toSubLevel, info); return new NamedParamInfo(name, fromLevel, toLevel, fromSubLevel, toSubLevel, info);
@@ -491,23 +492,24 @@ public class SkillData implements IXmlReader
private Map<Integer, Map<Integer, Object>> parseValues(Node node) private Map<Integer, Map<Integer, Object>> parseValues(Node node)
{ {
Node n = node;
final Map<Integer, Map<Integer, Object>> values = new HashMap<>(); final Map<Integer, Map<Integer, Object>> values = new HashMap<>();
Object parsedValue = parseValue(node, true, false, Collections.emptyMap()); Object parsedValue = parseValue(n, true, false, Collections.emptyMap());
if (parsedValue != null) if (parsedValue != null)
{ {
values.computeIfAbsent(-1, k -> new HashMap<>()).put(-1, parsedValue); values.computeIfAbsent(-1, k -> new HashMap<>()).put(-1, parsedValue);
} }
else else
{ {
for (node = node.getFirstChild(); node != null; node = node.getNextSibling()) for (n = n.getFirstChild(); n != null; n = n.getNextSibling())
{ {
if (node.getNodeName().equalsIgnoreCase("value")) if (n.getNodeName().equalsIgnoreCase("value"))
{ {
final NamedNodeMap attributes = node.getAttributes(); final NamedNodeMap attributes = n.getAttributes();
final Integer level = parseInteger(attributes, "level"); final Integer level = parseInteger(attributes, "level");
if (level != null) if (level != null)
{ {
parsedValue = parseValue(node, false, false, Collections.emptyMap()); parsedValue = parseValue(n, false, false, Collections.emptyMap());
if (parsedValue != null) if (parsedValue != null)
{ {
final Integer subLevel = parseInteger(attributes, "subLevel", -1); final Integer subLevel = parseInteger(attributes, "subLevel", -1);
@@ -533,7 +535,7 @@ public class SkillData implements IXmlReader
{ {
variables.put("base", Double.parseDouble(String.valueOf(base))); variables.put("base", Double.parseDouble(String.valueOf(base)));
} }
parsedValue = parseValue(node, false, false, variables); parsedValue = parseValue(n, false, false, variables);
if (parsedValue != null) if (parsedValue != null)
{ {
subValues.put(j, parsedValue); subValues.put(j, parsedValue);
@@ -549,22 +551,23 @@ public class SkillData implements IXmlReader
Object parseValue(Node node, boolean blockValue, boolean parseAttributes, Map<String, Double> variables) Object parseValue(Node node, boolean blockValue, boolean parseAttributes, Map<String, Double> variables)
{ {
Node n = node;
StatSet statSet = null; StatSet statSet = null;
List<Object> list = null; List<Object> list = null;
Object text = null; Object text = null;
if (parseAttributes && (!node.getNodeName().equals("value") || !blockValue) && (node.getAttributes().getLength() > 0)) if (parseAttributes && (!n.getNodeName().equals("value") || !blockValue) && (n.getAttributes().getLength() > 0))
{ {
statSet = new StatSet(); statSet = new StatSet();
parseAttributes(node.getAttributes(), "", statSet, variables); parseAttributes(n.getAttributes(), "", statSet, variables);
} }
for (node = node.getFirstChild(); node != null; node = node.getNextSibling()) for (n = n.getFirstChild(); n != null; n = n.getNextSibling())
{ {
final String nodeName = node.getNodeName(); final String nodeName = n.getNodeName();
switch (node.getNodeName()) switch (n.getNodeName())
{ {
case "#text": case "#text":
{ {
final String value = node.getNodeValue().trim(); final String value = n.getNodeValue().trim();
if (!value.isEmpty()) if (!value.isEmpty())
{ {
text = parseNodeValue(value, variables); text = parseNodeValue(value, variables);
@@ -578,7 +581,7 @@ public class SkillData implements IXmlReader
list = new LinkedList<>(); list = new LinkedList<>();
} }
final Object value = parseValue(node, false, true, variables); final Object value = parseValue(n, false, true, variables);
if (value != null) if (value != null)
{ {
list.add(value); list.add(value);
@@ -595,7 +598,7 @@ public class SkillData implements IXmlReader
} }
default: default:
{ {
final Object value = parseValue(node, false, true, variables); final Object value = parseValue(n, false, true, variables);
if (value != null) if (value != null)
{ {
if (statSet == null) if (statSet == null)
@@ -612,7 +615,7 @@ public class SkillData implements IXmlReader
{ {
if (text != null) if (text != null)
{ {
throw new IllegalArgumentException("Text and list in same node are not allowed. Node[" + node + "]"); throw new IllegalArgumentException("Text and list in same node are not allowed. Node[" + n + "]");
} }
if (statSet != null) if (statSet != null)
{ {
@@ -627,7 +630,7 @@ public class SkillData implements IXmlReader
{ {
if (list != null) if (list != null)
{ {
throw new IllegalArgumentException("Text and list in same node are not allowed. Node[" + node + "]"); throw new IllegalArgumentException("Text and list in same node are not allowed. Node[" + n + "]");
} }
if (statSet != null) if (statSet != null)
{ {
@@ -444,10 +444,11 @@ public class SkillTreeData implements IXmlReader
final Map<Long, SkillLearn> skillTree = new HashMap<>(); final Map<Long, SkillLearn> skillTree = new HashMap<>();
// Add all skills that belong to all classes. // Add all skills that belong to all classes.
skillTree.putAll(_commonSkillTree); skillTree.putAll(_commonSkillTree);
while ((classId != null) && (_classSkillTrees.get(classId) != null)) ClassId currentClassId = classId;
while ((currentClassId != null) && (_classSkillTrees.get(currentClassId) != null))
{ {
skillTree.putAll(_classSkillTrees.get(classId)); skillTree.putAll(_classSkillTrees.get(currentClassId));
classId = _parentClassMap.get(classId); currentClassId = _parentClassMap.get(currentClassId);
} }
return skillTree; return skillTree;
} }
@@ -194,14 +194,15 @@ public abstract class DocumentBase
_tables.put(name, table); _tables.put(name, table);
} }
protected void parseTemplate(Node n, Object template) protected void parseTemplate(Node node, Object template)
{ {
Condition condition = null; Condition condition = null;
n = n.getFirstChild(); Node n = node.getFirstChild();
if (n == null) if (n == null)
{ {
return; return;
} }
if ("cond".equalsIgnoreCase(n.getNodeName())) if ("cond".equalsIgnoreCase(n.getNodeName()))
{ {
condition = parseCondition(n.getFirstChild(), template); condition = parseCondition(n.getFirstChild(), template);
@@ -275,8 +276,9 @@ public abstract class DocumentBase
} }
} }
protected Condition parseCondition(Node n, Object template) protected Condition parseCondition(Node node, Object template)
{ {
Node n = node;
while ((n != null) && (n.getNodeType() != Node.ELEMENT_NODE)) while ((n != null) && (n.getNodeType() != Node.ELEMENT_NODE))
{ {
n = n.getNextSibling(); n = n.getNextSibling();
@@ -324,12 +326,14 @@ public abstract class DocumentBase
} }
} }
} }
return condition; return condition;
} }
protected Condition parseLogicAnd(Node n, Object template) protected Condition parseLogicAnd(Node node, Object template)
{ {
final ConditionLogicAnd cond = new ConditionLogicAnd(); final ConditionLogicAnd cond = new ConditionLogicAnd();
Node n = node;
for (n = n.getFirstChild(); n != null; n = n.getNextSibling()) for (n = n.getFirstChild(); n != null; n = n.getNextSibling())
{ {
if (n.getNodeType() == Node.ELEMENT_NODE) if (n.getNodeType() == Node.ELEMENT_NODE)
@@ -344,9 +348,10 @@ public abstract class DocumentBase
return cond; return cond;
} }
protected Condition parseLogicOr(Node n, Object template) protected Condition parseLogicOr(Node node, Object template)
{ {
final ConditionLogicOr cond = new ConditionLogicOr(); final ConditionLogicOr cond = new ConditionLogicOr();
Node n = node;
for (n = n.getFirstChild(); n != null; n = n.getNextSibling()) for (n = n.getFirstChild(); n != null; n = n.getNextSibling())
{ {
if (n.getNodeType() == Node.ELEMENT_NODE) if (n.getNodeType() == Node.ELEMENT_NODE)
@@ -361,8 +366,9 @@ public abstract class DocumentBase
return cond; return cond;
} }
protected Condition parseLogicNot(Node n, Object template) protected Condition parseLogicNot(Node node, Object template)
{ {
Node n = node;
for (n = n.getFirstChild(); n != null; n = n.getNextSibling()) for (n = n.getFirstChild(); n != null; n = n.getNextSibling())
{ {
if (n.getNodeType() == Node.ELEMENT_NODE) if (n.getNodeType() == Node.ELEMENT_NODE)
@@ -102,8 +102,9 @@ public class DocumentItem extends DocumentBase implements IXmlReader
} }
} }
protected void parseItem(Node n) throws InvocationTargetException protected void parseItem(Node node) throws InvocationTargetException
{ {
Node n = node;
final int itemId = Integer.parseInt(n.getAttributes().getNamedItem("id").getNodeValue()); final int itemId = Integer.parseInt(n.getAttributes().getNamedItem("id").getNodeValue());
final String className = n.getAttributes().getNamedItem("type").getNodeValue(); final String className = n.getAttributes().getNamedItem("type").getNodeValue();
final String itemName = n.getAttributes().getNamedItem("name").getNodeValue(); final String itemName = n.getAttributes().getNamedItem("name").getNodeValue();
@@ -494,19 +494,26 @@ public class GeoEngine
/** /**
* Simple check for origin to target visibility. * Simple check for origin to target visibility.
* @param gox : origin X geodata coordinate * @param goxValue : origin X geodata coordinate
* @param goy : origin Y geodata coordinate * @param goyValue : origin Y geodata coordinate
* @param goz : origin Z geodata coordinate * @param gozValue : origin Z geodata coordinate
* @param oheight : origin height (if instance of {@link Character}) * @param oheight : origin height (if instance of {@link Character})
* @param gtx : target X geodata coordinate * @param gtxValue : target X geodata coordinate
* @param gty : target Y geodata coordinate * @param gtyValue : target Y geodata coordinate
* @param gtz : target Z geodata coordinate * @param gtzValue : target Z geodata coordinate
* @param theight : target height (if instance of {@link Character}) * @param theight : target height (if instance of {@link Character})
* @param instance * @param instance
* @return {@code boolean} : True, when target can be seen. * @return {@code boolean} : True, when target can be seen.
*/ */
private final boolean checkSee(int gox, int goy, int goz, double oheight, int gtx, int gty, int gtz, double theight, Instance instance) private final boolean checkSee(int goxValue, int goyValue, int gozValue, double oheight, int gtxValue, int gtyValue, int gtzValue, double theight, Instance instance)
{ {
int goz = gozValue;
int gtz = gtzValue;
int gox = goxValue;
int goy = goyValue;
int gtx = gtxValue;
int gty = gtyValue;
// get line of sight Z coordinates // get line of sight Z coordinates
double losoz = goz + ((oheight * Config.PART_OF_CHARACTER_HEIGHT) / 100); double losoz = goz + ((oheight * Config.PART_OF_CHARACTER_HEIGHT) / 100);
double lostz = gtz + ((theight * Config.PART_OF_CHARACTER_HEIGHT) / 100); double lostz = gtz + ((theight * Config.PART_OF_CHARACTER_HEIGHT) / 100);
@@ -167,10 +167,10 @@ final class GeoEnginePathfinding extends GeoEngine
/** /**
* Create list of node locations as result of calculated buffer node tree. * Create list of node locations as result of calculated buffer node tree.
* @param target : the entry point * @param node : the entry point
* @return List<NodeLoc> : list of node location * @return List<NodeLoc> : list of node location
*/ */
private static List<Location> constructPath(Node target) private static List<Location> constructPath(Node node)
{ {
// create empty list // create empty list
final LinkedList<Location> list = new LinkedList<>(); final LinkedList<Location> list = new LinkedList<>();
@@ -180,6 +180,7 @@ final class GeoEnginePathfinding extends GeoEngine
int dy = 0; int dy = 0;
// get target parent // get target parent
Node target = node;
Node parent = target.getParent(); Node parent = target.getParent();
// while parent exists // while parent exists
@@ -50,8 +50,9 @@ public class BypassHandler implements IHandler<IBypassHandler, String>
} }
@Override @Override
public IBypassHandler getHandler(String command) public IBypassHandler getHandler(String commandValue)
{ {
String command = commandValue;
if (command.contains(" ")) if (command.contains(" "))
{ {
command = command.substring(0, command.indexOf(' ')); command = command.substring(0, command.indexOf(' '));
@@ -62,12 +62,13 @@ public class CastleManager implements InstanceListManager
return findNearestCastle(obj, Long.MAX_VALUE); return findNearestCastle(obj, Long.MAX_VALUE);
} }
public Castle findNearestCastle(WorldObject obj, long maxDistance) public Castle findNearestCastle(WorldObject obj, long maxDistanceValue)
{ {
Castle nearestCastle = getCastle(obj); Castle nearestCastle = getCastle(obj);
if (nearestCastle == null) if (nearestCastle == null)
{ {
double distance; double distance;
long maxDistance = maxDistanceValue;
for (Castle castle : _castles.values()) for (Castle castle : _castles.values())
{ {
distance = castle.getDistance(obj); distance = castle.getDistance(obj);
@@ -330,9 +330,9 @@ public class ClanEntryManager
return false; return false;
} }
public List<PledgeWaitingInfo> getSortedWaitingList(int levelMin, int levelMax, int role, int sortBy, boolean descending) public List<PledgeWaitingInfo> getSortedWaitingList(int levelMin, int levelMax, int role, int sortByValue, boolean descending)
{ {
sortBy = CommonUtil.constrain(sortBy, 1, PLAYER_COMPARATOR.size() - 1); final int sortBy = CommonUtil.constrain(sortByValue, 1, PLAYER_COMPARATOR.size() - 1);
// TODO: Handle Role // TODO: Handle Role
//@formatter:off //@formatter:off
@@ -373,9 +373,10 @@ public class ClanEntryManager
return _clanList.values().stream().collect(Collectors.toList()); return _clanList.values().stream().collect(Collectors.toList());
} }
public List<PledgeRecruitInfo> getSortedClanList(int clanLevel, int karma, int sortBy, boolean descending) public List<PledgeRecruitInfo> getSortedClanList(int clanLevel, int karma, int sortByValue, boolean descending)
{ {
sortBy = CommonUtil.constrain(sortBy, 1, CLAN_COMPARATOR.size() - 1); final int sortBy = CommonUtil.constrain(sortByValue, 1, CLAN_COMPARATOR.size() - 1);
//@formatter:off //@formatter:off
return _clanList.values().stream() return _clanList.values().stream()
.filter((p -> (((clanLevel < 0) && (karma >= 0) && (karma != p.getKarma())) || ((clanLevel >= 0) && (karma < 0) && (clanLevel != (p.getClan() != null ? p.getClanLevel() : 0))) || ((clanLevel >= 0) && (karma >= 0) && ((clanLevel != (p.getClan() != null ? p.getClanLevel() : 0)) || (karma != p.getKarma())))))) .filter((p -> (((clanLevel < 0) && (karma >= 0) && (karma != p.getKarma())) || ((clanLevel >= 0) && (karma < 0) && (clanLevel != (p.getClan() != null ? p.getClanLevel() : 0))) || ((clanLevel >= 0) && (karma >= 0) && ((clanLevel != (p.getClan() != null ? p.getClanLevel() : 0)) || (karma != p.getKarma()))))))
@@ -42,11 +42,12 @@ public class FortManager implements InstanceListManager
return findNearestFort(obj, Long.MAX_VALUE); return findNearestFort(obj, Long.MAX_VALUE);
} }
public Fort findNearestFort(WorldObject obj, long maxDistance) public Fort findNearestFort(WorldObject obj, long maxDistanceValue)
{ {
Fort nearestFort = getFort(obj); Fort nearestFort = getFort(obj);
if (nearestFort == null) if (nearestFort == null)
{ {
long maxDistance = maxDistanceValue;
for (Fort fort : _forts.values()) for (Fort fort : _forts.values())
{ {
final double distance = fort.getDistance(obj); final double distance = fort.getDistance(obj);
@@ -826,17 +826,17 @@ public class Party extends AbstractPlayerGroup
* <li>Get the PlayerInstance owner of the ServitorInstance (if necessary)</li> * <li>Get the PlayerInstance owner of the ServitorInstance (if necessary)</li>
* <li>Calculate the Experience and SP reward distribution rate</li> * <li>Calculate the Experience and SP reward distribution rate</li>
* <li>Add Experience and SP to the PlayerInstance</li><br> * <li>Add Experience and SP to the PlayerInstance</li><br>
* @param xpReward The Experience reward to distribute * @param xpRewardValue The Experience reward to distribute
* @param spReward The SP reward to distribute * @param spRewardValue The SP reward to distribute
* @param rewardedMembers The list of PlayerInstance to reward * @param rewardedMembers The list of PlayerInstance to reward
* @param topLvl * @param topLvl
* @param target * @param target
*/ */
public void distributeXpAndSp(double xpReward, double spReward, List<PlayerInstance> rewardedMembers, int topLvl, Attackable target) public void distributeXpAndSp(double xpRewardValue, double spRewardValue, List<PlayerInstance> rewardedMembers, int topLvl, Attackable target)
{ {
final List<PlayerInstance> validMembers = getValidMembers(rewardedMembers, topLvl); final List<PlayerInstance> validMembers = getValidMembers(rewardedMembers, topLvl);
xpReward *= getExpBonus(validMembers.size(), target.getInstanceWorld()); double xpReward = xpRewardValue * getExpBonus(validMembers.size(), target.getInstanceWorld());
spReward *= getSpBonus(validMembers.size(), target.getInstanceWorld()); double spReward = spRewardValue * getSpBonus(validMembers.size(), target.getInstanceWorld());
int sqLevelSum = 0; int sqLevelSum = 0;
for (PlayerInstance member : validMembers) for (PlayerInstance member : validMembers)
{ {
@@ -892,10 +892,10 @@ public class Party extends AbstractPlayerGroup
} }
} }
private double calculateExpSpPartyCutoff(PlayerInstance player, int topLvl, double addExp, double addSp, boolean vit) private double calculateExpSpPartyCutoff(PlayerInstance player, int topLvl, double addExpValue, double addSpValue, boolean vit)
{ {
addExp *= Config.EXP_AMOUNT_MULTIPLIERS.getOrDefault(player.getClassId(), 1f); final double addExp = addExpValue * Config.EXP_AMOUNT_MULTIPLIERS.getOrDefault(player.getClassId(), 1f);
addSp *= Config.SP_AMOUNT_MULTIPLIERS.getOrDefault(player.getClassId(), 1f); final double addSp = addSpValue * Config.SP_AMOUNT_MULTIPLIERS.getOrDefault(player.getClassId(), 1f);
double xp = addExp; double xp = addExp;
double sp = addSp; double sp = addSp;
if (Config.PARTY_XP_CUTOFF_METHOD.equalsIgnoreCase("highfive")) if (Config.PARTY_XP_CUTOFF_METHOD.equalsIgnoreCase("highfive"))
@@ -48,7 +48,7 @@ public class Petition
public Petition(PlayerInstance petitioner, String petitionText, int petitionType) public Petition(PlayerInstance petitioner, String petitionText, int petitionType)
{ {
_id = IdFactory.getNextId(); _id = IdFactory.getNextId();
_type = PetitionType.values()[--petitionType]; _type = PetitionType.values()[petitionType - 1];
_content = petitionText; _content = petitionText;
_petitioner = petitioner; _petitioner = petitioner;
} }
@@ -187,25 +187,28 @@ public abstract class WorldObject extends ListenersContainer implements IIdentif
{ {
synchronized (this) synchronized (this)
{ {
if (x > World.MAP_MAX_X) int spawnX = x;
if (spawnX > World.MAP_MAX_X)
{ {
x = World.MAP_MAX_X - 5000; spawnX = World.MAP_MAX_X - 5000;
} }
if (x < World.MAP_MIN_X) if (spawnX < World.MAP_MIN_X)
{ {
x = World.MAP_MIN_X + 5000; spawnX = World.MAP_MIN_X + 5000;
} }
if (y > World.MAP_MAX_Y)
int spawnY = y;
if (spawnY > World.MAP_MAX_Y)
{ {
y = World.MAP_MAX_Y - 5000; spawnY = World.MAP_MAX_Y - 5000;
} }
if (y < World.MAP_MIN_Y) if (spawnY < World.MAP_MIN_Y)
{ {
y = World.MAP_MIN_Y + 5000; spawnY = World.MAP_MIN_Y + 5000;
} }
// Set the x,y,z position of the WorldObject. If flagged with _isSpawned, setXYZ will automatically update world region, so avoid that. // Set the x,y,z position of the WorldObject. If flagged with _isSpawned, setXYZ will automatically update world region, so avoid that.
setXYZ(x, y, z); setXYZ(spawnX, spawnY, z);
} }
// Spawn and update its _worldregion // Spawn and update its _worldregion
@@ -502,24 +505,27 @@ public abstract class WorldObject extends ListenersContainer implements IIdentif
public void setXYZInvisible(int x, int y, int z) public void setXYZInvisible(int x, int y, int z)
{ {
if (x > World.MAP_MAX_X) int correctX = x;
if (correctX > World.MAP_MAX_X)
{ {
x = World.MAP_MAX_X - 5000; correctX = World.MAP_MAX_X - 5000;
} }
if (x < World.MAP_MIN_X) if (correctX < World.MAP_MIN_X)
{ {
x = World.MAP_MIN_X + 5000; correctX = World.MAP_MIN_X + 5000;
}
if (y > World.MAP_MAX_Y)
{
y = World.MAP_MAX_Y - 5000;
}
if (y < World.MAP_MIN_Y)
{
y = World.MAP_MIN_Y + 5000;
} }
setXYZ(x, y, z); int correctY = y;
if (correctY > World.MAP_MAX_Y)
{
correctY = World.MAP_MAX_Y - 5000;
}
if (correctY < World.MAP_MIN_Y)
{
correctY = World.MAP_MIN_Y + 5000;
}
setXYZ(correctX, correctY, z);
setSpawned(false); setSpawned(false);
} }
@@ -683,12 +683,13 @@ public class Attackable extends Npc
/** /**
* Add damage and hate to the attacker AggroInfo of the Attackable _aggroList. * Add damage and hate to the attacker AggroInfo of the Attackable _aggroList.
* @param attacker The Creature that gave damages to this Attackable * @param creature The Creature that gave damages to this Attackable
* @param damage The number of damages given by the attacker Creature * @param damage The number of damages given by the attacker Creature
* @param aggro The hate (=damage) given by the attacker Creature * @param aggroValue The hate (=damage) given by the attacker Creature
*/ */
public void addDamageHate(Creature attacker, int damage, int aggro) public void addDamageHate(Creature creature, int damage, int aggroValue)
{ {
Creature attacker = creature;
if ((attacker == null) || (attacker == this)) if ((attacker == null) || (attacker == this))
{ {
return; return;
@@ -715,6 +716,7 @@ public class Attackable extends Npc
// traps does not cause aggro // traps does not cause aggro
// making this hack because not possible to determine if damage made by trap // making this hack because not possible to determine if damage made by trap
// so just check for triggered trap here // so just check for triggered trap here
int aggro = aggroValue;
if ((targetPlayer == null) || (targetPlayer.getTrap() == null) || !targetPlayer.getTrap().isTriggered()) if ((targetPlayer == null) || (targetPlayer.getTrap() == null) || !targetPlayer.getTrap().isTriggered())
{ {
ai.addHate(aggro); ai.addHate(aggro);
@@ -762,8 +764,7 @@ public class Attackable extends Npc
ai.addHate(amount); ai.addHate(amount);
} }
amount = getHating(mostHated); if (getHating(mostHated) >= 0)
if (amount >= 0)
{ {
((AttackableAI) getAI()).setGlobalAggro(-25); ((AttackableAI) getAI()).setGlobalAggro(-25);
clearAggroList(); clearAggroList();
@@ -728,14 +728,20 @@ public abstract class Creature extends WorldObject implements ISkillsHolder, IDe
* <li>Send a Server->Client packet TeleportToLocationt to the Creature AND to all PlayerInstance in its _KnownPlayers</li> * <li>Send a Server->Client packet TeleportToLocationt to the Creature AND to all PlayerInstance in its _KnownPlayers</li>
* <li>Modify the position of the pet if necessary</li> * <li>Modify the position of the pet if necessary</li>
* </ul> * </ul>
* @param x * @param xValue
* @param y * @param yValue
* @param z * @param zValue
* @param heading * @param headingValue
* @param instance * @param instanceValue
*/ */
public void teleToLocation(int x, int y, int z, int heading, Instance instance) public void teleToLocation(int xValue, int yValue, int zValue, int headingValue, Instance instanceValue)
{ {
int x = xValue;
int y = yValue;
int z = zValue;
int heading = headingValue;
Instance instance = instanceValue;
final LocationReturn term = EventDispatcher.getInstance().notifyEvent(new OnCreatureTeleport(this, x, y, z, heading, instance), this, LocationReturn.class); final LocationReturn term = EventDispatcher.getInstance().notifyEvent(new OnCreatureTeleport(this, x, y, z, heading, instance), this, LocationReturn.class);
if (term != null) if (term != null)
{ {
@@ -838,8 +844,10 @@ public abstract class Creature extends WorldObject implements ISkillsHolder, IDe
teleToLocation(x, y, z, heading, randomOffset, getInstanceWorld()); teleToLocation(x, y, z, heading, randomOffset, getInstanceWorld());
} }
public void teleToLocation(int x, int y, int z, int heading, int randomOffset, Instance instance) public void teleToLocation(int xValue, int yValue, int z, int heading, int randomOffset, Instance instance)
{ {
int x = xValue;
int y = yValue;
if (Config.OFFSET_ON_TELEPORT_ENABLED && (randomOffset > 0)) if (Config.OFFSET_ON_TELEPORT_ENABLED && (randomOffset > 0))
{ {
x += Rnd.get(-randomOffset, randomOffset); x += Rnd.get(-randomOffset, randomOffset);
@@ -1092,7 +1100,7 @@ public abstract class Creature extends WorldObject implements ISkillsHolder, IDe
case TWOHANDCROSSBOW: case TWOHANDCROSSBOW:
{ {
crossbow = true; crossbow = true;
// fallthough // fallthrough
} }
case BOW: case BOW:
{ {
@@ -1247,11 +1255,12 @@ public abstract class Creature extends WorldObject implements ISkillsHolder, IDe
return attack; return attack;
} }
private Hit generateHit(Creature target, Weapon weapon, boolean shotConsumed, boolean halfDamage) private Hit generateHit(Creature target, Weapon weapon, boolean shotConsumedValue, boolean halfDamage)
{ {
int damage = 0; int damage = 0;
byte shld = 0; byte shld = 0;
boolean crit = false; boolean crit = false;
boolean shotConsumed = shotConsumedValue;
final boolean miss = Formulas.calcHitMiss(this, target); final boolean miss = Formulas.calcHitMiss(this, target);
if (!shotConsumed) if (!shotConsumed)
{ {
@@ -3152,9 +3161,9 @@ public abstract class Creature extends WorldObject implements ISkillsHolder, IDe
{ {
if ((object != null) && !object.isSpawned()) if ((object != null) && !object.isSpawned())
{ {
object = null; _target = null;
return;
} }
_target = object; _target = object;
} }
@@ -3205,12 +3214,12 @@ public abstract class Creature extends WorldObject implements ISkillsHolder, IDe
* <li>AI : onIntentionMoveTo(Location), onIntentionPickUp(WorldObject), onIntentionInteract(WorldObject)</li> * <li>AI : onIntentionMoveTo(Location), onIntentionPickUp(WorldObject), onIntentionInteract(WorldObject)</li>
* <li>FollowTask</li> * <li>FollowTask</li>
* </ul> * </ul>
* @param x The X position of the destination * @param xValue The X position of the destination
* @param y The Y position of the destination * @param yValue The Y position of the destination
* @param z The Y position of the destination * @param zValue The Y position of the destination
* @param offset The size of the interaction area of the Creature targeted * @param offsetValue The size of the interaction area of the Creature targeted
*/ */
public void moveToLocation(int x, int y, int z, int offset) public void moveToLocation(int xValue, int yValue, int zValue, int offsetValue)
{ {
// Get the Move Speed of the Creature // Get the Move Speed of the Creature
final double speed = _stat.getMoveSpeed(); final double speed = _stat.getMoveSpeed();
@@ -3219,6 +3228,11 @@ public abstract class Creature extends WorldObject implements ISkillsHolder, IDe
return; return;
} }
int x = xValue;
int y = yValue;
int z = zValue;
int offset = offsetValue;
// Get current position of the Creature // Get current position of the Creature
final int curX = getX(); final int curX = getX();
final int curY = getY(); final int curY = getY();
@@ -3996,13 +4010,14 @@ public abstract class Creature extends WorldObject implements ISkillsHolder, IDe
* <ul> * <ul>
* <li>PlayerInstance : Save update in the character_skills table of the database</li> * <li>PlayerInstance : Save update in the character_skills table of the database</li>
* </ul> * </ul>
* @param newSkill The Skill to add to the Creature * @param skill The Skill to add to the Creature
* @return The Skill replaced or null if just added a new Skill * @return The Skill replaced or null if just added a new Skill
*/ */
@Override @Override
public Skill addSkill(Skill newSkill) public Skill addSkill(Skill skill)
{ {
Skill oldSkill = null; Skill oldSkill = null;
Skill newSkill = skill;
if (newSkill != null) if (newSkill != null)
{ {
// Mobius: Keep sublevel on skill level increase. // Mobius: Keep sublevel on skill level increase.
@@ -4364,7 +4379,7 @@ public abstract class Creature extends WorldObject implements ISkillsHolder, IDe
_status.addStatusListener(object); _status.addStatusListener(object);
} }
public void doAttack(double damage, Creature target, Skill skill, boolean isDOT, boolean directlyToHp, boolean critical, boolean reflect) public void doAttack(double damageValue, Creature target, Skill skill, boolean isDOT, boolean directlyToHp, boolean critical, boolean reflect)
{ {
// Check if fake players should aggro each other. // Check if fake players should aggro each other.
if (isFakePlayer() && !Config.FAKE_PLAYER_AGGRO_FPC && target.isFakePlayer()) if (isFakePlayer() && !Config.FAKE_PLAYER_AGGRO_FPC && target.isFakePlayer())
@@ -4382,6 +4397,7 @@ public abstract class Creature extends WorldObject implements ISkillsHolder, IDe
getAI().clientStartAutoAttack(); getAI().clientStartAutoAttack();
// ImmobileDamageBonus and ImmobileDamageResist effect bonuses. // ImmobileDamageBonus and ImmobileDamageResist effect bonuses.
double damage = damageValue;
if (target.isImmobilized()) if (target.isImmobilized())
{ {
damage *= _stat.getValue(Stat.IMMOBILE_DAMAGE_BONUS, 1); damage *= _stat.getValue(Stat.IMMOBILE_DAMAGE_BONUS, 1);
@@ -4481,20 +4497,22 @@ public abstract class Creature extends WorldObject implements ISkillsHolder, IDe
} }
} }
public void reduceCurrentHp(double value, Creature attacker, Skill skill) public void reduceCurrentHp(double amount, Creature attacker, Skill skill)
{ {
reduceCurrentHp(value, attacker, skill, false, false, false, false); reduceCurrentHp(amount, attacker, skill, false, false, false, false);
} }
public void reduceCurrentHp(double value, Creature attacker, Skill skill, boolean isDOT, boolean directlyToHp, boolean critical, boolean reflect) public void reduceCurrentHp(double amountValue, Creature attacker, Skill skill, boolean isDOT, boolean directlyToHp, boolean critical, boolean reflect)
{ {
double amount = amountValue;
// Notify of this attack only if there is an attacking creature. // Notify of this attack only if there is an attacking creature.
if (attacker != null) if (attacker != null)
{ {
EventDispatcher.getInstance().notifyEventAsync(new OnCreatureDamageDealt(attacker, this, value, skill, critical, isDOT, reflect), attacker); EventDispatcher.getInstance().notifyEventAsync(new OnCreatureDamageDealt(attacker, this, amount, skill, critical, isDOT, reflect), attacker);
} }
final DamageReturn term = EventDispatcher.getInstance().notifyEvent(new OnCreatureDamageReceived(attacker, this, value, skill, critical, isDOT, reflect), this, DamageReturn.class); final DamageReturn term = EventDispatcher.getInstance().notifyEvent(new OnCreatureDamageReceived(attacker, this, amount, skill, critical, isDOT, reflect), this, DamageReturn.class);
if (term != null) if (term != null)
{ {
if (term.terminate()) if (term.terminate())
@@ -4503,14 +4521,14 @@ public abstract class Creature extends WorldObject implements ISkillsHolder, IDe
} }
else if (term.override()) else if (term.override())
{ {
value = term.getDamage(); amount = term.getDamage();
} }
} }
final double damageCap = _stat.getValue(Stat.DAMAGE_LIMIT); final double damageCap = _stat.getValue(Stat.DAMAGE_LIMIT);
if (damageCap > 0) if (damageCap > 0)
{ {
value = Math.min(value, damageCap); amount = Math.min(amount, damageCap);
} }
// Calculate PvP/PvE damage received. It is a post-attack stat. // Calculate PvP/PvE damage received. It is a post-attack stat.
@@ -4518,36 +4536,36 @@ public abstract class Creature extends WorldObject implements ISkillsHolder, IDe
{ {
if (attacker.isPlayable()) if (attacker.isPlayable())
{ {
value *= (100 + Math.max(_stat.getValue(Stat.PVP_DAMAGE_TAKEN), -80)) / 100; amount *= (100 + Math.max(_stat.getValue(Stat.PVP_DAMAGE_TAKEN), -80)) / 100;
} }
else else
{ {
value *= (100 + Math.max(_stat.getValue(Stat.PVE_DAMAGE_TAKEN), -80)) / 100; amount *= (100 + Math.max(_stat.getValue(Stat.PVE_DAMAGE_TAKEN), -80)) / 100;
} }
} }
if (Config.CHAMPION_ENABLE && isChampion() && (Config.CHAMPION_HP != 0)) if (Config.CHAMPION_ENABLE && isChampion() && (Config.CHAMPION_HP != 0))
{ {
_status.reduceHp(value / Config.CHAMPION_HP, attacker, (skill == null) || !skill.isToggle(), isDOT, false); _status.reduceHp(amount / Config.CHAMPION_HP, attacker, (skill == null) || !skill.isToggle(), isDOT, false);
} }
else if (isPlayer()) else if (isPlayer())
{ {
getActingPlayer().getStatus().reduceHp(value, attacker, (skill == null) || !skill.isToggle(), isDOT, false, directlyToHp); getActingPlayer().getStatus().reduceHp(amount, attacker, (skill == null) || !skill.isToggle(), isDOT, false, directlyToHp);
} }
else else
{ {
_status.reduceHp(value, attacker, (skill == null) || !skill.isToggle(), isDOT, false); _status.reduceHp(amount, attacker, (skill == null) || !skill.isToggle(), isDOT, false);
} }
if (attacker != null) if (attacker != null)
{ {
attacker.sendDamageMessage(this, skill, (int) value, critical, false); attacker.sendDamageMessage(this, skill, (int) amount, critical, false);
} }
} }
public void reduceCurrentMp(double i) public void reduceCurrentMp(double amount)
{ {
_status.reduceMp(i); _status.reduceMp(amount);
} }
@Override @Override
@@ -5051,8 +5069,9 @@ public abstract class Creature extends WorldObject implements ISkillsHolder, IDe
} }
@SafeVarargs @SafeVarargs
public final List<SkillCaster> getSkillCasters(Predicate<SkillCaster> filter, Predicate<SkillCaster>... filters) public final List<SkillCaster> getSkillCasters(Predicate<SkillCaster> filterValue, Predicate<SkillCaster>... filters)
{ {
Predicate<SkillCaster> filter = filterValue;
for (Predicate<SkillCaster> additionalFilter : filters) for (Predicate<SkillCaster> additionalFilter : filters)
{ {
filter = filter.and(additionalFilter); filter = filter.and(additionalFilter);
@@ -5061,8 +5080,9 @@ public abstract class Creature extends WorldObject implements ISkillsHolder, IDe
} }
@SafeVarargs @SafeVarargs
public final SkillCaster getSkillCaster(Predicate<SkillCaster> filter, Predicate<SkillCaster>... filters) public final SkillCaster getSkillCaster(Predicate<SkillCaster> filterValue, Predicate<SkillCaster>... filters)
{ {
Predicate<SkillCaster> filter = filterValue;
for (Predicate<SkillCaster> additionalFilter : filters) for (Predicate<SkillCaster> additionalFilter : filters)
{ {
filter = filter.and(additionalFilter); filter = filter.and(additionalFilter);
@@ -107,8 +107,9 @@ public class FortCommanderInstance extends DefenderInstance
} }
@Override @Override
public void addDamage(Creature attacker, int damage, Skill skill) public void addDamage(Creature creature, int damage, Skill skill)
{ {
Creature attacker = creature;
final Spawn spawn = getSpawn(); final Spawn spawn = getSpawn();
if ((spawn != null) && canTalk()) if ((spawn != null) && canTalk())
{ {
@@ -149,13 +149,14 @@ public class GuardInstance extends Attackable
* @param player The PlayerInstance that start an action on the GuardInstance * @param player The PlayerInstance that start an action on the GuardInstance
*/ */
@Override @Override
public void onAction(PlayerInstance player, boolean interact) public void onAction(PlayerInstance player, boolean interactValue)
{ {
if (!canTarget(player)) if (!canTarget(player))
{ {
return; return;
} }
boolean interact = interactValue;
if (Config.FACTION_SYSTEM_ENABLED && Config.FACTION_GUARDS_ENABLED && ((player.isGood() && getTemplate().isClan(Config.FACTION_EVIL_TEAM_NAME)) || (player.isEvil() && getTemplate().isClan(Config.FACTION_GOOD_TEAM_NAME)))) if (Config.FACTION_SYSTEM_ENABLED && Config.FACTION_GUARDS_ENABLED && ((player.isGood() && getTemplate().isClan(Config.FACTION_EVIL_TEAM_NAME)) || (player.isEvil() && getTemplate().isClan(Config.FACTION_GOOD_TEAM_NAME))))
{ {
interact = false; interact = false;
@@ -213,6 +214,7 @@ public class GuardInstance extends Attackable
} }
} }
} }
// Send a Server->Client ActionFailed to the PlayerInstance in order to avoid that the client wait another packet // Send a Server->Client ActionFailed to the PlayerInstance in order to avoid that the client wait another packet
player.sendPacket(ActionFailed.STATIC_PACKET); player.sendPacket(ActionFailed.STATIC_PACKET);
} }
@@ -799,9 +799,9 @@ public class PetInstance extends Summon
} }
} }
public void dropItemHere(ItemInstance dropit, boolean protect) public void dropItemHere(ItemInstance item, boolean protect)
{ {
dropit = _inventory.dropItem("Drop", dropit.getObjectId(), dropit.getCount(), getOwner(), this); final ItemInstance dropit = _inventory.dropItem("Drop", item.getObjectId(), item.getCount(), getOwner(), this);
if (dropit != null) if (dropit != null)
{ {
if (protect) if (protect)
@@ -2003,13 +2003,15 @@ public class PlayerInstance extends Playable
/** /**
* Set the reputation of the PlayerInstance and send a Server->Client packet StatusUpdate (broadcast). * Set the reputation of the PlayerInstance and send a Server->Client packet StatusUpdate (broadcast).
* @param reputation * @param value
*/ */
@Override @Override
public void setReputation(int reputation) public void setReputation(int value)
{ {
// Notify to scripts. // Notify to scripts.
EventDispatcher.getInstance().notifyEventAsync(new OnPlayerReputationChanged(this, getReputation(), reputation), this); EventDispatcher.getInstance().notifyEventAsync(new OnPlayerReputationChanged(this, getReputation(), value), this);
int reputation = value;
if (reputation > Config.MAX_REPUTATION) // Max count of positive reputation if (reputation > Config.MAX_REPUTATION) // Max count of positive reputation
{ {
reputation = Config.MAX_REPUTATION; reputation = Config.MAX_REPUTATION;
@@ -2691,12 +2693,7 @@ public class PlayerInstance extends Playable
*/ */
public void setExp(long exp) public void setExp(long exp)
{ {
if (exp < 0) getStat().setExp(Math.max(0, exp));
{
exp = 0;
}
getStat().setExp(exp);
} }
/** /**
@@ -2749,12 +2746,7 @@ public class PlayerInstance extends Playable
*/ */
public void setSp(long sp) public void setSp(long sp)
{ {
if (sp < 0) super.getStat().setSp(Math.max(0, sp));
{
sp = 0;
}
super.getStat().setSp(sp);
} }
/** /**
@@ -3426,8 +3418,8 @@ public class PlayerInstance extends Playable
*/ */
public boolean destroyItem(String process, ItemInstance item, long count, WorldObject reference, boolean sendMessage) public boolean destroyItem(String process, ItemInstance item, long count, WorldObject reference, boolean sendMessage)
{ {
item = _inventory.destroyItem(process, item, count, this, reference); final ItemInstance destoyedItem = _inventory.destroyItem(process, item, count, this, reference);
if (item == null) if (destoyedItem == null)
{ {
if (sendMessage) if (sendMessage)
{ {
@@ -3440,7 +3432,7 @@ public class PlayerInstance extends Playable
if (!Config.FORCE_INVENTORY_UPDATE) if (!Config.FORCE_INVENTORY_UPDATE)
{ {
final InventoryUpdate playerIU = new InventoryUpdate(); final InventoryUpdate playerIU = new InventoryUpdate();
playerIU.addItem(item); playerIU.addItem(destoyedItem);
sendInventoryUpdate(playerIU); sendInventoryUpdate(playerIU);
} }
else else
@@ -3454,14 +3446,14 @@ public class PlayerInstance extends Playable
if (count > 1) if (count > 1)
{ {
final SystemMessage sm = new SystemMessage(SystemMessageId.S2_S1_S_DISAPPEARED); final SystemMessage sm = new SystemMessage(SystemMessageId.S2_S1_S_DISAPPEARED);
sm.addItemName(item); sm.addItemName(destoyedItem);
sm.addLong(count); sm.addLong(count);
sendPacket(sm); sendPacket(sm);
} }
else else
{ {
final SystemMessage sm = new SystemMessage(SystemMessageId.S1_DISAPPEARED); final SystemMessage sm = new SystemMessage(SystemMessageId.S1_DISAPPEARED);
sm.addItemName(item); sm.addItemName(destoyedItem);
sendPacket(sm); sendPacket(sm);
} }
} }
@@ -3712,8 +3704,8 @@ public class PlayerInstance extends Playable
*/ */
public boolean dropItem(String process, ItemInstance item, WorldObject reference, boolean sendMessage, boolean protectItem) public boolean dropItem(String process, ItemInstance item, WorldObject reference, boolean sendMessage, boolean protectItem)
{ {
item = _inventory.dropItem(process, item, this, reference); final ItemInstance droppedItem = _inventory.dropItem(process, item, this, reference);
if (item == null) if (droppedItem == null)
{ {
if (sendMessage) if (sendMessage)
{ {
@@ -3722,33 +3714,33 @@ public class PlayerInstance extends Playable
return false; return false;
} }
item.dropMe(this, (getX() + Rnd.get(50)) - 25, (getY() + Rnd.get(50)) - 25, getZ() + 20); droppedItem.dropMe(this, (getX() + Rnd.get(50)) - 25, (getY() + Rnd.get(50)) - 25, getZ() + 20);
if ((Config.AUTODESTROY_ITEM_AFTER > 0) && Config.DESTROY_DROPPED_PLAYER_ITEM && !Config.LIST_PROTECTED_ITEMS.contains(item.getId()) && ((item.isEquipable() && Config.DESTROY_EQUIPABLE_PLAYER_ITEM) || !item.isEquipable())) if ((Config.AUTODESTROY_ITEM_AFTER > 0) && Config.DESTROY_DROPPED_PLAYER_ITEM && !Config.LIST_PROTECTED_ITEMS.contains(droppedItem.getId()) && ((droppedItem.isEquipable() && Config.DESTROY_EQUIPABLE_PLAYER_ITEM) || !droppedItem.isEquipable()))
{ {
ItemsAutoDestroy.getInstance().addItem(item); ItemsAutoDestroy.getInstance().addItem(droppedItem);
} }
// protection against auto destroy dropped item // protection against auto destroy dropped item
if (Config.DESTROY_DROPPED_PLAYER_ITEM) if (Config.DESTROY_DROPPED_PLAYER_ITEM)
{ {
item.setProtected(item.isEquipable() && (!item.isEquipable() || !Config.DESTROY_EQUIPABLE_PLAYER_ITEM)); droppedItem.setProtected(droppedItem.isEquipable() && (!droppedItem.isEquipable() || !Config.DESTROY_EQUIPABLE_PLAYER_ITEM));
} }
else else
{ {
item.setProtected(true); droppedItem.setProtected(true);
} }
// retail drop protection // retail drop protection
if (protectItem) if (protectItem)
{ {
item.getDropProtection().protect(this); droppedItem.getDropProtection().protect(this);
} }
// Send inventory update packet // Send inventory update packet
if (!Config.FORCE_INVENTORY_UPDATE) if (!Config.FORCE_INVENTORY_UPDATE)
{ {
final InventoryUpdate playerIU = new InventoryUpdate(); final InventoryUpdate playerIU = new InventoryUpdate();
playerIU.addItem(item); playerIU.addItem(droppedItem);
sendInventoryUpdate(playerIU); sendInventoryUpdate(playerIU);
} }
else else
@@ -3760,7 +3752,7 @@ public class PlayerInstance extends Playable
if (sendMessage) if (sendMessage)
{ {
final SystemMessage sm = new SystemMessage(SystemMessageId.YOU_HAVE_DROPPED_S1); final SystemMessage sm = new SystemMessage(SystemMessageId.YOU_HAVE_DROPPED_S1);
sm.addItemName(item); sm.addItemName(droppedItem);
sendPacket(sm); sendPacket(sm);
} }
@@ -4626,11 +4618,12 @@ public class PlayerInstance extends Playable
* <li>Add the PlayerInstance to the _statusListener of the new target if it's a Creature</li> * <li>Add the PlayerInstance to the _statusListener of the new target if it's a Creature</li>
* <li>Target the new WorldObject (add the target to the PlayerInstance _target, _knownObject and PlayerInstance to _KnownObject of the WorldObject)</li> * <li>Target the new WorldObject (add the target to the PlayerInstance _target, _knownObject and PlayerInstance to _KnownObject of the WorldObject)</li>
* </ul> * </ul>
* @param newTarget The WorldObject to target * @param worldObject The WorldObject to target
*/ */
@Override @Override
public void setTarget(WorldObject newTarget) public void setTarget(WorldObject worldObject)
{ {
WorldObject newTarget = worldObject;
if (newTarget != null) if (newTarget != null)
{ {
final boolean isInParty = (newTarget.isPlayer() && isInParty() && _party.containsPlayer(newTarget.getActingPlayer())); final boolean isInParty = (newTarget.isPlayer() && isInParty() && _party.containsPlayer(newTarget.getActingPlayer()));
@@ -8270,32 +8263,34 @@ public class PlayerInstance extends Playable
@Override @Override
public boolean useMagic(Skill skill, ItemInstance item, boolean forceUse, boolean dontMove) public boolean useMagic(Skill skill, ItemInstance item, boolean forceUse, boolean dontMove)
{ {
Skill usedSkill = skill;
// Passive skills cannot be used. // Passive skills cannot be used.
if (skill.isPassive()) if (usedSkill.isPassive())
{ {
sendPacket(ActionFailed.STATIC_PACKET); sendPacket(ActionFailed.STATIC_PACKET);
return false; return false;
} }
// If Alternate rule Karma punishment is set to true, forbid skill Return to player with Karma // If Alternate rule Karma punishment is set to true, forbid skill Return to player with Karma
if (!Config.ALT_GAME_KARMA_PLAYER_CAN_TELEPORT && (getReputation() < 0) && skill.hasEffectType(EffectType.TELEPORT)) if (!Config.ALT_GAME_KARMA_PLAYER_CAN_TELEPORT && (getReputation() < 0) && usedSkill.hasEffectType(EffectType.TELEPORT))
{ {
sendPacket(ActionFailed.STATIC_PACKET); sendPacket(ActionFailed.STATIC_PACKET);
return false; return false;
} }
// players mounted on pets cannot use any toggle skills // players mounted on pets cannot use any toggle skills
if (skill.isToggle() && isMounted()) if (usedSkill.isToggle() && isMounted())
{ {
sendPacket(ActionFailed.STATIC_PACKET); sendPacket(ActionFailed.STATIC_PACKET);
return false; return false;
} }
// Support for wizard skills with stances (Fire, Water, Wind, Earth) // Support for wizard skills with stances (Fire, Water, Wind, Earth)
final Skill attachedSkill = skill.getAttachedSkill(this); final Skill attachedSkill = usedSkill.getAttachedSkill(this);
if (attachedSkill != null) if (attachedSkill != null)
{ {
skill = attachedSkill; usedSkill = attachedSkill;
} }
// Alter skills // Alter skills
@@ -8308,7 +8303,7 @@ public class PlayerInstance extends Playable
// ************************************* Check Player State ******************************************* // ************************************* Check Player State *******************************************
// Abnormal effects(ex : Stun, Sleep...) are checked in Creature useMagic() // Abnormal effects(ex : Stun, Sleep...) are checked in Creature useMagic()
if (!skill.canCastWhileDisabled() && (isControlBlocked() || hasBlockActions())) if (!usedSkill.canCastWhileDisabled() && (isControlBlocked() || hasBlockActions()))
{ {
sendPacket(ActionFailed.STATIC_PACKET); sendPacket(ActionFailed.STATIC_PACKET);
return false; return false;
@@ -8322,7 +8317,7 @@ public class PlayerInstance extends Playable
} }
// Check if fishing and trying to use non-fishing skills. // Check if fishing and trying to use non-fishing skills.
if (isFishing() && !skill.hasEffectType(EffectType.FISHING, EffectType.FISHING_START)) if (isFishing() && !usedSkill.hasEffectType(EffectType.FISHING, EffectType.FISHING_START))
{ {
sendPacket(SystemMessageId.ONLY_FISHING_SKILLS_MAY_BE_USED_AT_THIS_TIME); sendPacket(SystemMessageId.ONLY_FISHING_SKILLS_MAY_BE_USED_AT_THIS_TIME);
return false; return false;
@@ -8335,32 +8330,32 @@ public class PlayerInstance extends Playable
return false; return false;
} }
if (isSkillDisabled(skill)) if (isSkillDisabled(usedSkill))
{ {
final SystemMessage sm; final SystemMessage sm;
if (hasSkillReuse(skill.getReuseHashCode())) if (hasSkillReuse(usedSkill.getReuseHashCode()))
{ {
final int remainingTime = (int) (getSkillRemainingReuseTime(skill.getReuseHashCode()) / 1000); final int remainingTime = (int) (getSkillRemainingReuseTime(usedSkill.getReuseHashCode()) / 1000);
final int hours = remainingTime / 3600; final int hours = remainingTime / 3600;
final int minutes = (remainingTime % 3600) / 60; final int minutes = (remainingTime % 3600) / 60;
final int seconds = (remainingTime % 60); final int seconds = (remainingTime % 60);
if (hours > 0) if (hours > 0)
{ {
sm = new SystemMessage(SystemMessageId.THERE_ARE_S2_HOUR_S_S3_MINUTE_S_AND_S4_SECOND_S_REMAINING_IN_S1_S_RE_USE_TIME); sm = new SystemMessage(SystemMessageId.THERE_ARE_S2_HOUR_S_S3_MINUTE_S_AND_S4_SECOND_S_REMAINING_IN_S1_S_RE_USE_TIME);
sm.addSkillName(skill); sm.addSkillName(usedSkill);
sm.addInt(hours); sm.addInt(hours);
sm.addInt(minutes); sm.addInt(minutes);
} }
else if (minutes > 0) else if (minutes > 0)
{ {
sm = new SystemMessage(SystemMessageId.THERE_ARE_S2_MINUTE_S_S3_SECOND_S_REMAINING_IN_S1_S_RE_USE_TIME); sm = new SystemMessage(SystemMessageId.THERE_ARE_S2_MINUTE_S_S3_SECOND_S_REMAINING_IN_S1_S_RE_USE_TIME);
sm.addSkillName(skill); sm.addSkillName(usedSkill);
sm.addInt(minutes); sm.addInt(minutes);
} }
else else
{ {
sm = new SystemMessage(SystemMessageId.THERE_ARE_S2_SECOND_S_REMAINING_IN_S1_S_RE_USE_TIME); sm = new SystemMessage(SystemMessageId.THERE_ARE_S2_SECOND_S_REMAINING_IN_S1_S_RE_USE_TIME);
sm.addSkillName(skill); sm.addSkillName(usedSkill);
} }
sm.addInt(seconds); sm.addInt(seconds);
@@ -8368,7 +8363,7 @@ public class PlayerInstance extends Playable
else else
{ {
sm = new SystemMessage(SystemMessageId.S1_IS_NOT_AVAILABLE_AT_THIS_TIME_BEING_PREPARED_FOR_REUSE); sm = new SystemMessage(SystemMessageId.S1_IS_NOT_AVAILABLE_AT_THIS_TIME_BEING_PREPARED_FOR_REUSE);
sm.addSkillName(skill); sm.addSkillName(usedSkill);
} }
sendPacket(sm); sendPacket(sm);
@@ -8384,20 +8379,20 @@ public class PlayerInstance extends Playable
} }
// Check if the skill type is toggle and disable it, unless the toggle is necessary to be on. // Check if the skill type is toggle and disable it, unless the toggle is necessary to be on.
if (skill.isToggle()) if (usedSkill.isToggle())
{ {
if (isAffectedBySkill(skill.getId())) if (isAffectedBySkill(usedSkill.getId()))
{ {
if (!skill.isNecessaryToggle()) if (!usedSkill.isNecessaryToggle())
{ {
stopSkillEffects(true, skill.getId()); stopSkillEffects(true, usedSkill.getId());
} }
sendPacket(ActionFailed.STATIC_PACKET); sendPacket(ActionFailed.STATIC_PACKET);
return false; return false;
} }
else if (skill.getToggleGroupId() > 0) else if (usedSkill.getToggleGroupId() > 0)
{ {
getEffectList().stopAllTogglesOfGroup(skill.getToggleGroupId()); getEffectList().stopAllTogglesOfGroup(usedSkill.getToggleGroupId());
} }
} }
@@ -8411,9 +8406,9 @@ public class PlayerInstance extends Playable
// ************************************* Check Target ******************************************* // ************************************* Check Target *******************************************
// Create and set a WorldObject containing the target of the skill // Create and set a WorldObject containing the target of the skill
final WorldObject target = skill.getTarget(this, forceUse, dontMove, true); final WorldObject target = usedSkill.getTarget(this, forceUse, dontMove, true);
final Location worldPosition = _currentSkillWorldPosition; final Location worldPosition = _currentSkillWorldPosition;
if ((skill.getTargetType() == TargetType.GROUND) && (worldPosition == null)) if ((usedSkill.getTargetType() == TargetType.GROUND) && (worldPosition == null))
{ {
sendPacket(ActionFailed.STATIC_PACKET); sendPacket(ActionFailed.STATIC_PACKET);
return false; return false;
@@ -8427,27 +8422,27 @@ public class PlayerInstance extends Playable
} }
// Check if all casting conditions are completed // Check if all casting conditions are completed
if (!skill.checkCondition(this, target)) if (!usedSkill.checkCondition(this, target))
{ {
sendPacket(ActionFailed.STATIC_PACKET); sendPacket(ActionFailed.STATIC_PACKET);
// Upon failed conditions, next action is called. // Upon failed conditions, next action is called.
if ((skill.getNextAction() != NextActionType.NONE) && (target != this) && target.isAutoAttackable(this) && ((getAI().getNextIntention() == null) || (getAI().getNextIntention().getCtrlIntention() != CtrlIntention.AI_INTENTION_MOVE_TO))) if ((usedSkill.getNextAction() != NextActionType.NONE) && (target != this) && target.isAutoAttackable(this) && ((getAI().getNextIntention() == null) || (getAI().getNextIntention().getCtrlIntention() != CtrlIntention.AI_INTENTION_MOVE_TO)))
{ {
if (skill.getNextAction() == NextActionType.ATTACK) if (usedSkill.getNextAction() == NextActionType.ATTACK)
{ {
getAI().setIntention(CtrlIntention.AI_INTENTION_ATTACK, target); getAI().setIntention(CtrlIntention.AI_INTENTION_ATTACK, target);
} }
else if (skill.getNextAction() == NextActionType.CAST) else if (usedSkill.getNextAction() == NextActionType.CAST)
{ {
getAI().setIntention(CtrlIntention.AI_INTENTION_CAST, skill, target, item, false, false); getAI().setIntention(CtrlIntention.AI_INTENTION_CAST, usedSkill, target, item, false, false);
} }
} }
return false; return false;
} }
final boolean doubleCast = isAffected(EffectFlag.DOUBLE_CAST) && skill.canDoubleCast(); final boolean doubleCast = isAffected(EffectFlag.DOUBLE_CAST) && usedSkill.canDoubleCast();
// If a skill is currently being used, queue this one if this is not the same // If a skill is currently being used, queue this one if this is not the same
// In case of double casting, check if both slots are occupied, then queue skill. // In case of double casting, check if both slots are occupied, then queue skill.
@@ -8457,7 +8452,7 @@ public class PlayerInstance extends Playable
if (item == null) if (item == null)
{ {
// Create a new SkillDat object and queue it in the player _queuedSkill // Create a new SkillDat object and queue it in the player _queuedSkill
setQueuedSkill(skill, item, forceUse, dontMove); setQueuedSkill(usedSkill, item, forceUse, dontMove);
} }
sendPacket(ActionFailed.STATIC_PACKET); sendPacket(ActionFailed.STATIC_PACKET);
return false; return false;
@@ -8469,7 +8464,7 @@ public class PlayerInstance extends Playable
} }
// Notify the AI with AI_INTENTION_CAST and target // Notify the AI with AI_INTENTION_CAST and target
getAI().setIntention(CtrlIntention.AI_INTENTION_CAST, skill, target, item, forceUse, dontMove); getAI().setIntention(CtrlIntention.AI_INTENTION_CAST, usedSkill, target, item, forceUse, dontMove);
return true; return true;
} }
@@ -40,19 +40,20 @@ public class PlayableStat extends CreatureStat
super(player); super(player);
} }
public boolean addExp(long value) public boolean addExp(long amount)
{ {
final TerminateReturn term = EventDispatcher.getInstance().notifyEvent(new OnPlayableExpChanged(getActiveChar(), getExp(), getExp() + value), getActiveChar(), TerminateReturn.class); final TerminateReturn term = EventDispatcher.getInstance().notifyEvent(new OnPlayableExpChanged(getActiveChar(), getExp(), getExp() + amount), getActiveChar(), TerminateReturn.class);
if ((term != null) && term.terminate()) if ((term != null) && term.terminate())
{ {
return false; return false;
} }
if (((getExp() + value) < 0) || ((value > 0) && (getExp() == (getExpForLevel(getMaxLevel()) - 1)))) if (((getExp() + amount) < 0) || ((amount > 0) && (getExp() == (getExpForLevel(getMaxLevel()) - 1))))
{ {
return true; return true;
} }
long value = amount;
if ((getExp() + value) >= getExpForLevel(getMaxLevel())) if ((getExp() + value) >= getExpForLevel(getMaxLevel()))
{ {
value = getExpForLevel(getMaxLevel()) - 1 - getExp(); value = getExpForLevel(getMaxLevel()) - 1 - getExp();
@@ -95,8 +96,9 @@ public class PlayableStat extends CreatureStat
return true; return true;
} }
public boolean removeExp(long value) public boolean removeExp(long amount)
{ {
long value = amount;
if (((getExp() - value) < getExpForLevel(getLevel())) && (!Config.PLAYER_DELEVEL || (Config.PLAYER_DELEVEL && (getLevel() <= Config.DELEVEL_MINIMUM)))) if (((getExp() - value) < getExpForLevel(getLevel())) && (!Config.PLAYER_DELEVEL || (Config.PLAYER_DELEVEL && (getLevel() <= Config.DELEVEL_MINIMUM))))
{ {
value = getExp() - getExpForLevel(getLevel()); value = getExp() - getExpForLevel(getLevel());
@@ -146,8 +148,9 @@ public class PlayableStat extends CreatureStat
return expRemoved || spRemoved; return expRemoved || spRemoved;
} }
public boolean addLevel(byte value) public boolean addLevel(byte amount)
{ {
byte value = amount;
if ((getLevel() + value) > (getMaxLevel() - 1)) if ((getLevel() + value) > (getMaxLevel() - 1))
{ {
if (getLevel() < (getMaxLevel() - 1)) if (getLevel() < (getMaxLevel() - 1))
@@ -186,19 +189,21 @@ public class PlayableStat extends CreatureStat
return true; return true;
} }
public boolean addSp(long value) public boolean addSp(long amount)
{ {
if (value < 0) if (amount < 0)
{ {
LOGGER.warning("wrong usage"); LOGGER.warning("wrong usage");
return false; return false;
} }
final long currentSp = getSp(); final long currentSp = getSp();
if (currentSp >= Config.MAX_SP) if (currentSp >= Config.MAX_SP)
{ {
return false; return false;
} }
long value = amount;
if (currentSp > (Config.MAX_SP - value)) if (currentSp > (Config.MAX_SP - value))
{ {
value = Config.MAX_SP - currentSp; value = Config.MAX_SP - currentSp;
@@ -208,14 +213,15 @@ public class PlayableStat extends CreatureStat
return true; return true;
} }
public boolean removeSp(long value) public boolean removeSp(long amount)
{ {
final long currentSp = getSp(); final long currentSp = getSp();
if (currentSp < value) if (currentSp < amount)
{ {
value = currentSp; setSp(getSp() - currentSp);
return true;
} }
setSp(getSp() - value); setSp(getSp() - amount);
return true; return true;
} }
@@ -97,7 +97,7 @@ public class PlayerStat extends PlayableStat
return true; return true;
} }
public void addExpAndSp(double addToExp, double addToSp, boolean useBonuses) public void addExpAndSp(double addToExpValue, double addToSpValue, boolean useBonuses)
{ {
final PlayerInstance player = getActiveChar(); final PlayerInstance player = getActiveChar();
@@ -107,6 +107,9 @@ public class PlayerStat extends PlayableStat
return; return;
} }
double addToExp = addToExpValue;
double addToSp = addToSpValue;
// Premium rates // Premium rates
if (player.hasPremiumStatus()) if (player.hasPremiumStatus())
{ {
@@ -410,18 +413,19 @@ public class PlayerStat extends PlayableStat
@Override @Override
public void setLevel(byte value) public void setLevel(byte value)
{ {
if (value > (ExperienceData.getInstance().getMaxLevel() - 1)) byte level = value;
if (level > (ExperienceData.getInstance().getMaxLevel() - 1))
{ {
value = (byte) (ExperienceData.getInstance().getMaxLevel() - 1); level = (byte) (ExperienceData.getInstance().getMaxLevel() - 1);
} }
if (getActiveChar().isSubClassActive()) if (getActiveChar().isSubClassActive())
{ {
getActiveChar().getSubClasses().get(getActiveChar().getClassIndex()).setLevel(value); getActiveChar().getSubClasses().get(getActiveChar().getClassIndex()).setLevel(level);
} }
else else
{ {
super.setLevel(value); super.setLevel(level);
} }
} }
@@ -488,9 +492,9 @@ public class PlayerStat extends PlayableStat
/* /*
* Set current vitality points to this value if quiet = true - does not send system messages * Set current vitality points to this value if quiet = true - does not send system messages
*/ */
public void setVitalityPoints(int points, boolean quiet) public void setVitalityPoints(int value, boolean quiet)
{ {
points = Math.min(Math.max(points, MIN_VITALITY_POINTS), MAX_VITALITY_POINTS); final int points = Math.min(Math.max(value, MIN_VITALITY_POINTS), MAX_VITALITY_POINTS);
if (points == getVitalityPoints()) if (points == getVitalityPoints())
{ {
return; return;
@@ -531,13 +535,14 @@ public class PlayerStat extends PlayableStat
} }
} }
public synchronized void updateVitalityPoints(int points, boolean useRates, boolean quiet) public synchronized void updateVitalityPoints(int value, boolean useRates, boolean quiet)
{ {
if ((points == 0) || !Config.ENABLE_VITALITY) if ((value == 0) || !Config.ENABLE_VITALITY)
{ {
return; return;
} }
int points = value;
if (useRates) if (useRates)
{ {
if (getActiveChar().isLucky()) if (getActiveChar().isLucky())
@@ -123,7 +123,8 @@ public class PlayerStatus extends PlayableStatus
} }
} }
int fullValue = (int) value; double amount = value;
int fullValue = (int) amount;
int tDmg = 0; int tDmg = 0;
int mpDam = 0; int mpDam = 0;
if ((attacker != null) && (attacker != getActiveChar())) if ((attacker != null) && (attacker != getActiveChar()))
@@ -159,27 +160,27 @@ public class PlayerStatus extends PlayableStatus
final Summon summon = getActiveChar().getFirstServitor(); final Summon summon = getActiveChar().getFirstServitor();
if ((summon != null) && Util.checkIfInRange(1000, getActiveChar(), summon, true)) if ((summon != null) && Util.checkIfInRange(1000, getActiveChar(), summon, true))
{ {
tDmg = ((int) value * (int) getActiveChar().getStat().getValue(Stat.TRANSFER_DAMAGE_SUMMON_PERCENT, 0)) / 100; tDmg = ((int) amount * (int) getActiveChar().getStat().getValue(Stat.TRANSFER_DAMAGE_SUMMON_PERCENT, 0)) / 100;
// Only transfer dmg up to current HP, it should not be killed // Only transfer dmg up to current HP, it should not be killed
tDmg = Math.min((int) summon.getCurrentHp() - 1, tDmg); tDmg = Math.min((int) summon.getCurrentHp() - 1, tDmg);
if (tDmg > 0) if (tDmg > 0)
{ {
summon.reduceCurrentHp(tDmg, attacker, null); summon.reduceCurrentHp(tDmg, attacker, null);
value -= tDmg; amount -= tDmg;
fullValue = (int) value; // reduce the announced value here as player will get a message about summon damage fullValue = (int) amount; // reduce the announced value here as player will get a message about summon damage
} }
} }
mpDam = ((int) value * (int) getActiveChar().getStat().getValue(Stat.MANA_SHIELD_PERCENT, 0)) / 100; mpDam = ((int) amount * (int) getActiveChar().getStat().getValue(Stat.MANA_SHIELD_PERCENT, 0)) / 100;
if (mpDam > 0) if (mpDam > 0)
{ {
mpDam = (int) (value - mpDam); mpDam = (int) (amount - mpDam);
if (mpDam > getActiveChar().getCurrentMp()) if (mpDam > getActiveChar().getCurrentMp())
{ {
getActiveChar().sendPacket(SystemMessageId.MP_BECAME_0_AND_THE_ARCANE_SHIELD_IS_DISAPPEARING); getActiveChar().sendPacket(SystemMessageId.MP_BECAME_0_AND_THE_ARCANE_SHIELD_IS_DISAPPEARING);
getActiveChar().stopSkillEffects(true, 1556); getActiveChar().stopSkillEffects(true, 1556);
value = mpDam - getActiveChar().getCurrentMp(); amount = mpDam - getActiveChar().getCurrentMp();
getActiveChar().setCurrentMp(0); getActiveChar().setCurrentMp(0);
} }
else else
@@ -196,7 +197,7 @@ public class PlayerStatus extends PlayableStatus
if ((caster != null) && (getActiveChar().getParty() != null) && Util.checkIfInRange(1000, getActiveChar(), caster, true) && !caster.isDead() && (getActiveChar() != caster) && getActiveChar().getParty().getMembers().contains(caster)) if ((caster != null) && (getActiveChar().getParty() != null) && Util.checkIfInRange(1000, getActiveChar(), caster, true) && !caster.isDead() && (getActiveChar() != caster) && getActiveChar().getParty().getMembers().contains(caster))
{ {
int transferDmg = 0; int transferDmg = 0;
transferDmg = ((int) value * (int) getActiveChar().getStat().getValue(Stat.TRANSFER_DAMAGE_TO_PLAYER, 0)) / 100; transferDmg = ((int) amount * (int) getActiveChar().getStat().getValue(Stat.TRANSFER_DAMAGE_TO_PLAYER, 0)) / 100;
transferDmg = Math.min((int) caster.getCurrentHp() - 1, transferDmg); transferDmg = Math.min((int) caster.getCurrentHp() - 1, transferDmg);
if (transferDmg > 0) if (transferDmg > 0)
{ {
@@ -225,22 +226,22 @@ public class PlayerStatus extends PlayableStatus
if (membersInRange > 0) if (membersInRange > 0)
{ {
caster.reduceCurrentHp(transferDmg / membersInRange, attacker, null); caster.reduceCurrentHp(transferDmg / membersInRange, attacker, null);
value -= transferDmg; amount -= transferDmg;
fullValue = (int) value; fullValue = (int) amount;
} }
} }
} }
if (!ignoreCP && (attacker.isPlayable() || attacker.isFakePlayer())) if (!ignoreCP && (attacker.isPlayable() || attacker.isFakePlayer()))
{ {
if (_currentCp >= value) if (_currentCp >= amount)
{ {
setCurrentCp(_currentCp - value); // Set Cp to diff of Cp vs value setCurrentCp(_currentCp - amount); // Set Cp to diff of Cp vs value
value = 0; // No need to subtract anything from Hp amount = 0; // No need to subtract anything from Hp
} }
else else
{ {
value -= _currentCp; // Get diff from value vs Cp; will apply diff to Hp amount -= _currentCp; // Get diff from value vs Cp; will apply diff to Hp
setCurrentCp(0, false); // Set Cp to 0 setCurrentCp(0, false); // Set Cp to 0
} }
} }
@@ -277,9 +278,9 @@ public class PlayerStatus extends PlayableStatus
} }
} }
if (value > 0) if (amount > 0)
{ {
double newHp = Math.max(getCurrentHp() - value, getActiveChar().isUndying() ? 1 : 0); double newHp = Math.max(getCurrentHp() - amount, getActiveChar().isUndying() ? 1 : 0);
if (newHp <= 0) if (newHp <= 0)
{ {
if (getActiveChar().isInDuel()) if (getActiveChar().isInDuel())
@@ -339,7 +340,7 @@ public class PlayerStatus extends PlayableStatus
} }
@Override @Override
public void setCurrentCp(double newCp, boolean broadcastPacket) public void setCurrentCp(double value, boolean broadcastPacket)
{ {
// Get the Max CP of the Creature // Get the Max CP of the Creature
final int currentCp = (int) _currentCp; final int currentCp = (int) _currentCp;
@@ -352,11 +353,7 @@ public class PlayerStatus extends PlayableStatus
return; return;
} }
if (newCp < 0) final double newCp = Math.max(0, value);
{
newCp = 0;
}
if (newCp >= maxCp) if (newCp >= maxCp)
{ {
// Set the RegenActive flag to false // Set the RegenActive flag to false
@@ -37,9 +37,8 @@ public class SiegeFlagStatus extends NpcStatus
{ {
if (getActiveChar().isAdvancedHeadquarter()) if (getActiveChar().isAdvancedHeadquarter())
{ {
value /= 2.; super.reduceHp(value / 2, attacker, awake, isDOT, isHpConsumption);
} }
super.reduceHp(value, attacker, awake, isDOT, isHpConsumption); super.reduceHp(value, attacker, awake, isDOT, isHpConsumption);
} }
@@ -37,7 +37,7 @@ public class SummonStatus extends PlayableStatus
} }
@Override @Override
public void reduceHp(double value, Creature attacker, boolean awake, boolean isDOT, boolean isHPConsumption) public void reduceHp(double amount, Creature attacker, boolean awake, boolean isDOT, boolean isHPConsumption)
{ {
if ((attacker == null) || getActiveChar().isDead()) if ((attacker == null) || getActiveChar().isDead())
{ {
@@ -50,6 +50,7 @@ public class SummonStatus extends PlayableStatus
attackerPlayer.setDuelState(Duel.DUELSTATE_INTERRUPTED); attackerPlayer.setDuelState(Duel.DUELSTATE_INTERRUPTED);
} }
double value = amount;
final PlayerInstance caster = getActiveChar().getTransferingDamageTo(); final PlayerInstance caster = getActiveChar().getTransferingDamageTo();
if (getActiveChar().getOwner().getParty() != null) if (getActiveChar().getOwner().getParty() != null)
{ {
@@ -110,6 +111,7 @@ public class SummonStatus extends PlayableStatus
value -= transferDmg; value -= transferDmg;
} }
} }
super.reduceHp(value, attacker, awake, isDOT, isHPConsumption); super.reduceHp(value, attacker, awake, isDOT, isHPConsumption);
} }
@@ -950,13 +950,13 @@ public class NpcTemplate extends CreatureTemplate implements IIdentifiable
return _collisionHeightGrown; return _collisionHeightGrown;
} }
public static boolean isAssignableTo(Class<?> sub, Class<?> clazz) public static boolean isAssignableTo(Class<?> subValue, Class<?> clazz)
{ {
// If clazz represents an interface // If clazz represents an interface
if (clazz.isInterface()) if (clazz.isInterface())
{ {
// check if obj implements the clazz interface // check if obj implements the clazz interface
for (Class<?> interface1 : sub.getInterfaces()) for (Class<?> interface1 : subValue.getInterfaces())
{ {
if (clazz.getName().equals(interface1.getName())) if (clazz.getName().equals(interface1.getName()))
{ {
@@ -966,13 +966,13 @@ public class NpcTemplate extends CreatureTemplate implements IIdentifiable
} }
else else
{ {
Class<?> sub = subValue;
do do
{ {
if (sub.getName().equals(clazz.getName())) if (sub.getName().equals(clazz.getName()))
{ {
return true; return true;
} }
sub = sub.getSuperclass(); sub = sub.getSuperclass();
} }
while (sub != null); while (sub != null);
@@ -98,9 +98,9 @@ public class SubClass
{ {
if (!_dualClass && (expValue > (ExperienceData.getInstance().getExpForLevel(MAX_LEVEL + 1) - 1))) if (!_dualClass && (expValue > (ExperienceData.getInstance().getExpForLevel(MAX_LEVEL + 1) - 1)))
{ {
expValue = ExperienceData.getInstance().getExpForLevel(MAX_LEVEL + 1) - 1; _exp = ExperienceData.getInstance().getExpForLevel(MAX_LEVEL + 1) - 1;
return;
} }
_exp = expValue; _exp = expValue;
} }
@@ -128,13 +128,14 @@ public class SubClass
{ {
if (!_dualClass && (levelValue > MAX_LEVEL)) if (!_dualClass && (levelValue > MAX_LEVEL))
{ {
levelValue = MAX_LEVEL; _level = MAX_LEVEL;
return;
} }
else if (levelValue < Config.BASE_SUBCLASS_LEVEL) else if (levelValue < Config.BASE_SUBCLASS_LEVEL)
{ {
levelValue = Config.BASE_SUBCLASS_LEVEL; _level = Config.BASE_SUBCLASS_LEVEL;
return;
} }
_level = levelValue; _level = levelValue;
} }
} }
@@ -1163,8 +1163,9 @@ public class Clan implements IIdentifiable, INamable
} }
} }
private void storeNotice(String notice, boolean enabled) private void storeNotice(String noticeValue, boolean enabled)
{ {
String notice = noticeValue;
if (notice == null) if (notice == null)
{ {
notice = ""; notice = "";
@@ -1832,10 +1833,10 @@ public class Clan implements IIdentifiable, INamable
return _subPledges.values().toArray(new SubPledge[_subPledges.values().size()]); return _subPledges.values().toArray(new SubPledge[_subPledges.values().size()]);
} }
public SubPledge createSubPledge(PlayerInstance player, int pledgeType, int leaderId, String subPledgeName) public SubPledge createSubPledge(PlayerInstance player, int pledgeTypeValue, int leaderId, String subPledgeName)
{ {
SubPledge subPledge = null; SubPledge subPledge = null;
pledgeType = getAvailablePledgeTypes(pledgeType); final int pledgeType = getAvailablePledgeTypes(pledgeTypeValue);
if (pledgeType == 0) if (pledgeType == 0)
{ {
if (pledgeType == SUBUNIT_ACADEMY) if (pledgeType == SUBUNIT_ACADEMY)
@@ -1912,8 +1913,7 @@ public class Clan implements IIdentifiable, INamable
} }
case SUBUNIT_ROYAL1: case SUBUNIT_ROYAL1:
{ {
pledgeType = getAvailablePledgeTypes(SUBUNIT_ROYAL2); return getAvailablePledgeTypes(SUBUNIT_ROYAL2);
break;
} }
case SUBUNIT_ROYAL2: case SUBUNIT_ROYAL2:
{ {
@@ -1921,18 +1921,15 @@ public class Clan implements IIdentifiable, INamable
} }
case SUBUNIT_KNIGHT1: case SUBUNIT_KNIGHT1:
{ {
pledgeType = getAvailablePledgeTypes(SUBUNIT_KNIGHT2); return getAvailablePledgeTypes(SUBUNIT_KNIGHT2);
break;
} }
case SUBUNIT_KNIGHT2: case SUBUNIT_KNIGHT2:
{ {
pledgeType = getAvailablePledgeTypes(SUBUNIT_KNIGHT3); return getAvailablePledgeTypes(SUBUNIT_KNIGHT3);
break;
} }
case SUBUNIT_KNIGHT3: case SUBUNIT_KNIGHT3:
{ {
pledgeType = getAvailablePledgeTypes(SUBUNIT_KNIGHT4); return getAvailablePledgeTypes(SUBUNIT_KNIGHT4);
break;
} }
case SUBUNIT_KNIGHT4: case SUBUNIT_KNIGHT4:
{ {
@@ -206,8 +206,9 @@ public class CubicInstance
} }
} }
private void tryToUseSkill(WorldObject target, CubicSkill cubicSkill) private void tryToUseSkill(WorldObject worldObject, CubicSkill cubicSkill)
{ {
WorldObject target = worldObject;
final Skill skill = cubicSkill.getSkill(); final Skill skill = cubicSkill.getSkill();
if ((_template.getTargetType() != CubicTargetType.MASTER) && !((_template.getTargetType() == CubicTargetType.BY_SKILL) && (cubicSkill.getTargetType() == CubicTargetType.MASTER))) if ((_template.getTargetType() != CubicTargetType.MASTER) && !((_template.getTargetType() == CubicTargetType.BY_SKILL) && (cubicSkill.getTargetType() == CubicTargetType.MASTER)))
{ {
@@ -281,9 +281,9 @@ public class Castle extends AbstractResidence
// This method add to the treasury // This method add to the treasury
/** /**
* Add amount to castle instance's treasury (warehouse). * Add amount to castle instance's treasury (warehouse).
* @param amount * @param amountValue
*/ */
public void addToTreasury(long amount) public void addToTreasury(long amountValue)
{ {
// check if owned // check if owned
if (_ownerId <= 0) if (_ownerId <= 0)
@@ -291,6 +291,7 @@ public class Castle extends AbstractResidence
return; return;
} }
long amount = amountValue;
switch (getName().toLowerCase()) switch (getName().toLowerCase())
{ {
case "schuttgart": case "schuttgart":
@@ -327,21 +328,23 @@ public class Castle extends AbstractResidence
break; break;
} }
} }
addToTreasuryNoTax(amount); addToTreasuryNoTax(amount);
} }
/** /**
* Add amount to castle instance's treasury (warehouse), no tax paying. * Add amount to castle instance's treasury (warehouse), no tax paying.
* @param amount * @param amountValue
* @return * @return
*/ */
public boolean addToTreasuryNoTax(long amount) public boolean addToTreasuryNoTax(long amountValue)
{ {
if (_ownerId <= 0) if (_ownerId <= 0)
{ {
return false; return false;
} }
long amount = amountValue;
if (amount < 0) if (amount < 0)
{ {
amount *= -1; amount *= -1;
@@ -371,6 +374,7 @@ public class Castle extends AbstractResidence
{ {
LOGGER.log(Level.WARNING, e.getMessage(), e); LOGGER.log(Level.WARNING, e.getMessage(), e);
} }
return true; return true;
} }
@@ -187,10 +187,10 @@ public class Hero
} }
} }
private String calcFightTime(long fightTime) private String calcFightTime(long fightTimeValue)
{ {
final String format = String.format("%%0%dd", 2); final String format = String.format("%%0%dd", 2);
fightTime /= 1000; final long fightTime = fightTimeValue / 1000;
return String.format(format, (fightTime % 3600) / 60) + ":" + String.format(format, fightTime % 60); return String.format(format, (fightTime % 3600) / 60) + ":" + String.format(format, fightTime % 60);
} }
@@ -2187,9 +2187,9 @@ public abstract class AbstractScript extends ManagedScript implements IEventTime
* Add a temporary spawn of the specified NPC. * Add a temporary spawn of the specified NPC.
* @param summoner the NPC that requires this spawn * @param summoner the NPC that requires this spawn
* @param npcId the ID of the NPC to spawn * @param npcId the ID of the NPC to spawn
* @param x the X coordinate of the spawn location * @param xValue the X coordinate of the spawn location
* @param y the Y coordinate of the spawn location * @param yValue the Y coordinate of the spawn location
* @param z the Z coordinate (height) of the spawn location * @param zValue the Z coordinate (height) of the spawn location
* @param heading the heading of the NPC * @param heading the heading of the NPC
* @param randomOffset if {@code true}, adds +/- 50~100 to X/Y coordinates of the spawn location * @param randomOffset if {@code true}, adds +/- 50~100 to X/Y coordinates of the spawn location
* @param despawnDelay time in milliseconds till the NPC is despawned (0 - only despawned on server shutdown) * @param despawnDelay time in milliseconds till the NPC is despawned (0 - only despawned on server shutdown)
@@ -2200,17 +2200,19 @@ public abstract class AbstractScript extends ManagedScript implements IEventTime
* @see #addSpawn(int, int, int, int, int, boolean, long) * @see #addSpawn(int, int, int, int, int, boolean, long)
* @see #addSpawn(int, int, int, int, int, boolean, long, boolean) * @see #addSpawn(int, int, int, int, int, boolean, long, boolean)
*/ */
public static Npc addSpawn(Npc summoner, int npcId, int x, int y, int z, int heading, boolean randomOffset, long despawnDelay, boolean isSummonSpawn, int instance) public static Npc addSpawn(Npc summoner, int npcId, int xValue, int yValue, int zValue, int heading, boolean randomOffset, long despawnDelay, boolean isSummonSpawn, int instance)
{ {
try try
{ {
final Spawn spawn = new Spawn(npcId); final Spawn spawn = new Spawn(npcId);
if ((x == 0) && (y == 0)) if ((xValue == 0) && (yValue == 0))
{ {
LOGGER.severe("addSpawn(): invalid spawn coordinates for NPC #" + npcId + "!"); LOGGER.severe("addSpawn(): invalid spawn coordinates for NPC #" + npcId + "!");
return null; return null;
} }
int x = xValue;
int y = yValue;
if (randomOffset) if (randomOffset)
{ {
int offset = Rnd.get(50, 100); int offset = Rnd.get(50, 100);
@@ -2229,7 +2231,7 @@ public abstract class AbstractScript extends ManagedScript implements IEventTime
spawn.setInstanceId(instance); spawn.setInstanceId(instance);
spawn.setHeading(heading); spawn.setHeading(heading);
spawn.setXYZ(x, y, z); spawn.setXYZ(x, y, zValue);
spawn.stopRespawn(); spawn.stopRespawn();
final Npc npc = spawn.doSpawn(isSummonSpawn); final Npc npc = spawn.doSpawn(isSummonSpawn);
@@ -2581,16 +2583,16 @@ public abstract class AbstractScript extends ManagedScript implements IEventTime
* Give a reward to player using multipliers. * Give a reward to player using multipliers.
* @param player the player to whom to give the item * @param player the player to whom to give the item
* @param itemId the ID of the item to give * @param itemId the ID of the item to give
* @param count the amount of items to give * @param countValue the amount of items to give
*/ */
public static void rewardItems(PlayerInstance player, int itemId, long count) public static void rewardItems(PlayerInstance player, int itemId, long countValue)
{ {
if (player.isSimulatingTalking()) if (player.isSimulatingTalking())
{ {
return; return;
} }
if (count <= 0) if (countValue <= 0)
{ {
return; return;
} }
@@ -2601,6 +2603,7 @@ public abstract class AbstractScript extends ManagedScript implements IEventTime
return; return;
} }
long count = countValue;
try try
{ {
if (itemId == Inventory.ADENA_ID) if (itemId == Inventory.ADENA_ID)
@@ -2871,29 +2874,29 @@ public abstract class AbstractScript extends ManagedScript implements IEventTime
return true; return true;
} }
minAmount *= Config.RATE_QUEST_DROP; long minAmountWithBonus = (long) (minAmount * Config.RATE_QUEST_DROP);
maxAmount *= Config.RATE_QUEST_DROP; long maxAmountWithBonus = (long) (maxAmount * Config.RATE_QUEST_DROP);
dropChance *= Config.RATE_QUEST_DROP; // TODO separate configs for rate and amount long dropChanceWithBonus = (long) (dropChance * Config.RATE_QUEST_DROP); // TODO separate configs for rate and amount
if ((npc != null) && Config.CHAMPION_ENABLE && npc.isChampion()) if ((npc != null) && Config.CHAMPION_ENABLE && npc.isChampion())
{ {
if ((itemId == Inventory.ADENA_ID) || (itemId == Inventory.ANCIENT_ADENA_ID)) if ((itemId == Inventory.ADENA_ID) || (itemId == Inventory.ANCIENT_ADENA_ID))
{ {
dropChance *= Config.CHAMPION_ADENAS_REWARDS_CHANCE; dropChanceWithBonus *= Config.CHAMPION_ADENAS_REWARDS_CHANCE;
minAmount *= Config.CHAMPION_ADENAS_REWARDS_AMOUNT; minAmountWithBonus *= Config.CHAMPION_ADENAS_REWARDS_AMOUNT;
maxAmount *= Config.CHAMPION_ADENAS_REWARDS_AMOUNT; maxAmountWithBonus *= Config.CHAMPION_ADENAS_REWARDS_AMOUNT;
} }
else else
{ {
dropChance *= Config.CHAMPION_REWARDS_CHANCE; dropChanceWithBonus *= Config.CHAMPION_REWARDS_CHANCE;
minAmount *= Config.CHAMPION_REWARDS_AMOUNT; minAmountWithBonus *= Config.CHAMPION_REWARDS_AMOUNT;
maxAmount *= Config.CHAMPION_REWARDS_AMOUNT; maxAmountWithBonus *= Config.CHAMPION_REWARDS_AMOUNT;
} }
} }
long amountToGive = (minAmount == maxAmount) ? minAmount : Rnd.get(minAmount, maxAmount); long amountToGive = (minAmountWithBonus == maxAmountWithBonus) ? minAmountWithBonus : Rnd.get(minAmountWithBonus, maxAmountWithBonus);
final double random = Rnd.nextDouble(); final double random = Rnd.nextDouble();
// Inventory slot check (almost useless for non-stacking items) // Inventory slot check (almost useless for non-stacking items)
if ((dropChance >= random) && (amountToGive > 0) && player.getInventory().validateCapacityByItemId(itemId)) if ((dropChanceWithBonus >= random) && (amountToGive > 0) && player.getInventory().validateCapacityByItemId(itemId))
{ {
if ((limit > 0) && ((currentCount + amountToGive) > limit)) if ((limit > 0) && ((currentCount + amountToGive) > limit))
{ {
@@ -2931,10 +2934,10 @@ public abstract class AbstractScript extends ManagedScript implements IEventTime
* Take an amount of a specified item from player's inventory. * Take an amount of a specified item from player's inventory.
* @param player the player whose item to take * @param player the player whose item to take
* @param itemId the ID of the item to take * @param itemId the ID of the item to take
* @param amount the amount to take * @param amountValue the amount to take
* @return {@code true} if any items were taken, {@code false} otherwise * @return {@code true} if any items were taken, {@code false} otherwise
*/ */
public static boolean takeItems(PlayerInstance player, int itemId, long amount) public static boolean takeItems(PlayerInstance player, int itemId, long amountValue)
{ {
if (player.isSimulatingTalking()) if (player.isSimulatingTalking())
{ {
@@ -2949,7 +2952,8 @@ public abstract class AbstractScript extends ManagedScript implements IEventTime
} }
// Tests on count value in order not to have negative value // Tests on count value in order not to have negative value
if ((amount < 0) || (amount > item.getCount())) long amount = amountValue;
if ((amountValue < 0) || (amountValue > item.getCount()))
{ {
amount = item.getCount(); amount = item.getCount();
} }
@@ -2966,6 +2970,7 @@ public abstract class AbstractScript extends ManagedScript implements IEventTime
player.sendInventoryUpdate(iu); player.sendInventoryUpdate(iu);
player.broadcastUserInfo(); player.broadcastUserInfo();
} }
return player.destroyItemByItemId("Quest", itemId, amount, player, true); return player.destroyItemByItemId("Quest", itemId, amount, player, true);
} }
@@ -212,11 +212,12 @@ public class EventDispatcher
* @param listeners * @param listeners
* @param event * @param event
* @param returnBackClass * @param returnBackClass
* @param callback * @param callbackValue
* @return * @return
*/ */
private <T extends AbstractEventReturn> T notifyToListeners(Queue<AbstractEventListener> listeners, IBaseEvent event, Class<T> returnBackClass, T callback) private <T extends AbstractEventReturn> T notifyToListeners(Queue<AbstractEventListener> listeners, IBaseEvent event, Class<T> returnBackClass, T callbackValue)
{ {
T callback = callbackValue;
for (AbstractEventListener listener : listeners) for (AbstractEventListener listener : listeners)
{ {
try try
@@ -286,7 +286,7 @@ public class Fishing
} }
} }
private void reelIn(FishingEndReason reason, boolean consumeBait) private void reelIn(FishingEndReason reasonValue, boolean consumeBait)
{ {
if (!_isFishing) if (!_isFishing)
{ {
@@ -295,6 +295,7 @@ public class Fishing
cancelTasks(); cancelTasks();
FishingEndReason reason = reasonValue;
try try
{ {
final ItemInstance bait = _player.getInventory().getPaperdollItem(Inventory.PAPERDOLL_LHAND); final ItemInstance bait = _player.getInventory().getPaperdollItem(Inventory.PAPERDOLL_LHAND);
@@ -457,11 +457,12 @@ public class Instance implements IIdentifiable, INamable
/** /**
* @param groupName * @param groupName
* @param filter * @param filterValue
* @return {@code Stream<Npc>} of NPCs that is part of a group and matches filter specified * @return {@code Stream<Npc>} of NPCs that is part of a group and matches filter specified
*/ */
public Stream<Npc> getStreamOfGroup(String groupName, Predicate<Npc> filter) public Stream<Npc> getStreamOfGroup(String groupName, Predicate<Npc> filterValue)
{ {
Predicate<Npc> filter = filterValue;
if (filter == null) if (filter == null)
{ {
filter = Objects::nonNull; filter = Objects::nonNull;
@@ -69,8 +69,9 @@ public class AuctionDateGenerator
return calcDestTime(_calendar.getTimeInMillis(), date, TimeUnit.MILLISECONDS.convert(_interval, TimeUnit.DAYS)); return calcDestTime(_calendar.getTimeInMillis(), date, TimeUnit.MILLISECONDS.convert(_interval, TimeUnit.DAYS));
} }
private long calcDestTime(long time, long date, long add) private long calcDestTime(long timeValue, long date, long add)
{ {
long time = timeValue;
if (time < date) if (time < date)
{ {
time += ((date - time) / add) * add; time += ((date - time) / add) * add;
@@ -77,13 +77,14 @@ public abstract class ItemContainer
} }
/** /**
* @param filter * @param filterValue
* @param filters * @param filters
* @return the quantity of items in the inventory * @return the quantity of items in the inventory
*/ */
@SafeVarargs @SafeVarargs
public final int getSize(Predicate<ItemInstance> filter, Predicate<ItemInstance>... filters) public final int getSize(Predicate<ItemInstance> filterValue, Predicate<ItemInstance>... filters)
{ {
Predicate<ItemInstance> filter = filterValue;
for (Predicate<ItemInstance> additionalFilter : filters) for (Predicate<ItemInstance> additionalFilter : filters)
{ {
filter = filter.and(additionalFilter); filter = filter.and(additionalFilter);
@@ -102,13 +103,14 @@ public abstract class ItemContainer
/** /**
* Gets the items in inventory filtered by filter. * Gets the items in inventory filtered by filter.
* @param filter the filter * @param filterValue the filter
* @param filters multiple filters * @param filters multiple filters
* @return the filtered items in inventory * @return the filtered items in inventory
*/ */
@SafeVarargs @SafeVarargs
public final Collection<ItemInstance> getItems(Predicate<ItemInstance> filter, Predicate<ItemInstance>... filters) public final Collection<ItemInstance> getItems(Predicate<ItemInstance> filterValue, Predicate<ItemInstance>... filters)
{ {
Predicate<ItemInstance> filter = filterValue;
for (Predicate<ItemInstance> additionalFilter : filters) for (Predicate<ItemInstance> additionalFilter : filters)
{ {
filter = filter.and(additionalFilter); filter = filter.and(additionalFilter);
@@ -196,32 +198,33 @@ public abstract class ItemContainer
*/ */
public ItemInstance addItem(String process, ItemInstance item, PlayerInstance actor, Object reference) public ItemInstance addItem(String process, ItemInstance item, PlayerInstance actor, Object reference)
{ {
final ItemInstance olditem = getItemByItemId(item.getId()); ItemInstance newItem = item;
final ItemInstance olditem = getItemByItemId(newItem.getId());
// If stackable item is found in inventory just add to current quantity // If stackable item is found in inventory just add to current quantity
if ((olditem != null) && olditem.isStackable()) if ((olditem != null) && olditem.isStackable())
{ {
final long count = item.getCount(); final long count = newItem.getCount();
olditem.changeCount(process, count, actor, reference); olditem.changeCount(process, count, actor, reference);
olditem.setLastChange(ItemInstance.MODIFIED); olditem.setLastChange(ItemInstance.MODIFIED);
// And destroys the item // And destroys the item
ItemTable.getInstance().destroyItem(process, item, actor, reference); ItemTable.getInstance().destroyItem(process, newItem, actor, reference);
item.updateDatabase(); newItem.updateDatabase();
item = olditem; newItem = olditem;
} }
else // If item hasn't be found in inventory, create new one else // If item hasn't be found in inventory, create new one
{ {
item.setOwnerId(process, getOwnerId(), actor, reference); newItem.setOwnerId(process, getOwnerId(), actor, reference);
item.setItemLocation(getBaseLocation()); newItem.setItemLocation(getBaseLocation());
item.setLastChange((ItemInstance.ADDED)); newItem.setLastChange((ItemInstance.ADDED));
// Add item in inventory // Add item in inventory
addItem(item); addItem(newItem);
} }
refreshWeight(); refreshWeight();
return item; return newItem;
} }
/** /**
@@ -278,13 +281,13 @@ public abstract class ItemContainer
* Transfers item to another inventory * Transfers item to another inventory
* @param process string Identifier of process triggering this action * @param process string Identifier of process triggering this action
* @param objectId Item Identifier of the item to be transfered * @param objectId Item Identifier of the item to be transfered
* @param count Quantity of items to be transfered * @param countValue Quantity of items to be transfered
* @param target the item container where the item will be moved. * @param target the item container where the item will be moved.
* @param actor Player requesting the item transfer * @param actor Player requesting the item transfer
* @param reference Object Object referencing current action like NPC selling item or previous item in transformation * @param reference Object Object referencing current action like NPC selling item or previous item in transformation
* @return ItemInstance corresponding to the new item or the updated item in inventory * @return ItemInstance corresponding to the new item or the updated item in inventory
*/ */
public ItemInstance transferItem(String process, int objectId, long count, ItemContainer target, PlayerInstance actor, Object reference) public ItemInstance transferItem(String process, int objectId, long countValue, ItemContainer target, PlayerInstance actor, Object reference)
{ {
if (target == null) if (target == null)
{ {
@@ -307,6 +310,7 @@ public abstract class ItemContainer
} }
// Check if requested quantity is available // Check if requested quantity is available
long count = countValue;
if (count > sourceitem.getCount()) if (count > sourceitem.getCount())
{ {
count = sourceitem.getCount(); count = sourceitem.getCount();
@@ -379,20 +379,20 @@ public class PlayerInventory extends Inventory
@Override @Override
public ItemInstance addItem(String process, ItemInstance item, PlayerInstance actor, Object reference) public ItemInstance addItem(String process, ItemInstance item, PlayerInstance actor, Object reference)
{ {
item = super.addItem(process, item, actor, reference); final ItemInstance addedItem = super.addItem(process, item, actor, reference);
if (item != null) if (addedItem != null)
{ {
if ((item.getId() == ADENA_ID) && !item.equals(_adena)) if ((addedItem.getId() == ADENA_ID) && !addedItem.equals(_adena))
{ {
_adena = item; _adena = addedItem;
} }
else if ((item.getId() == ANCIENT_ADENA_ID) && !item.equals(_ancientAdena)) else if ((addedItem.getId() == ANCIENT_ADENA_ID) && !addedItem.equals(_ancientAdena))
{ {
_ancientAdena = item; _ancientAdena = addedItem;
} }
else if ((item.getId() == BEAUTY_TICKET_ID) && !item.equals(_beautyTickets)) else if ((addedItem.getId() == BEAUTY_TICKET_ID) && !addedItem.equals(_beautyTickets))
{ {
_beautyTickets = item; _beautyTickets = addedItem;
} }
if (actor != null) if (actor != null)
@@ -401,7 +401,7 @@ public class PlayerInventory extends Inventory
if (!Config.FORCE_INVENTORY_UPDATE) if (!Config.FORCE_INVENTORY_UPDATE)
{ {
final InventoryUpdate playerIU = new InventoryUpdate(); final InventoryUpdate playerIU = new InventoryUpdate();
playerIU.addItem(item); playerIU.addItem(addedItem);
actor.sendInventoryUpdate(playerIU); actor.sendInventoryUpdate(playerIU);
} }
else else
@@ -410,11 +410,10 @@ public class PlayerInventory extends Inventory
} }
// Notify to scripts // Notify to scripts
EventDispatcher.getInstance().notifyEventAsync(new OnPlayerItemAdd(actor, item), actor, item.getItem()); EventDispatcher.getInstance().notifyEventAsync(new OnPlayerItemAdd(actor, addedItem), actor, addedItem.getItem());
} }
} }
return addedItem;
return item;
} }
/** /**
@@ -498,6 +497,7 @@ public class PlayerInventory extends Inventory
public ItemInstance transferItem(String process, int objectId, long count, ItemContainer target, PlayerInstance actor, Object reference) public ItemInstance transferItem(String process, int objectId, long count, ItemContainer target, PlayerInstance actor, Object reference)
{ {
final ItemInstance item = super.transferItem(process, objectId, count, target, actor, reference); final ItemInstance item = super.transferItem(process, objectId, count, target, actor, reference);
if ((_adena != null) && ((_adena.getCount() <= 0) || (_adena.getOwnerId() != getOwnerId()))) if ((_adena != null) && ((_adena.getCount() <= 0) || (_adena.getOwnerId() != getOwnerId())))
{ {
_adena = null; _adena = null;
@@ -510,18 +510,19 @@ public class PlayerInventory extends Inventory
// Notify to scripts // Notify to scripts
EventDispatcher.getInstance().notifyEventAsync(new OnPlayerItemTransfer(actor, item, target), item.getItem()); EventDispatcher.getInstance().notifyEventAsync(new OnPlayerItemTransfer(actor, item, target), item.getItem());
return item; return item;
} }
@Override @Override
public ItemInstance detachItem(String process, ItemInstance item, long count, ItemLocation newLocation, PlayerInstance actor, Object reference) public ItemInstance detachItem(String process, ItemInstance item, long count, ItemLocation newLocation, PlayerInstance actor, Object reference)
{ {
item = super.detachItem(process, item, count, newLocation, actor, reference); final ItemInstance detachedItem = super.detachItem(process, item, count, newLocation, actor, reference);
if ((item != null) && (actor != null)) if ((detachedItem != null) && (actor != null))
{ {
actor.sendItemList(false); actor.sendItemList(false);
} }
return item; return detachedItem;
} }
/** /**
@@ -549,7 +550,8 @@ public class PlayerInventory extends Inventory
@Override @Override
public ItemInstance destroyItem(String process, ItemInstance item, long count, PlayerInstance actor, Object reference) public ItemInstance destroyItem(String process, ItemInstance item, long count, PlayerInstance actor, Object reference)
{ {
item = super.destroyItem(process, item, count, actor, reference); final ItemInstance destroyedItem = super.destroyItem(process, item, count, actor, reference);
if ((_adena != null) && (_adena.getCount() <= 0)) if ((_adena != null) && (_adena.getCount() <= 0))
{ {
_adena = null; _adena = null;
@@ -561,11 +563,12 @@ public class PlayerInventory extends Inventory
} }
// Notify to scripts // Notify to scripts
if (item != null) if (destroyedItem != null)
{ {
EventDispatcher.getInstance().notifyEventAsync(new OnPlayerItemDestroy(actor, item), item.getItem()); EventDispatcher.getInstance().notifyEventAsync(new OnPlayerItemDestroy(actor, destroyedItem), destroyedItem.getItem());
} }
return item;
return destroyedItem;
} }
/** /**
@@ -611,7 +614,8 @@ public class PlayerInventory extends Inventory
@Override @Override
public ItemInstance dropItem(String process, ItemInstance item, PlayerInstance actor, Object reference) public ItemInstance dropItem(String process, ItemInstance item, PlayerInstance actor, Object reference)
{ {
item = super.dropItem(process, item, actor, reference); final ItemInstance droppedItem = super.dropItem(process, item, actor, reference);
if ((_adena != null) && ((_adena.getCount() <= 0) || (_adena.getOwnerId() != getOwnerId()))) if ((_adena != null) && ((_adena.getCount() <= 0) || (_adena.getOwnerId() != getOwnerId())))
{ {
_adena = null; _adena = null;
@@ -623,11 +627,12 @@ public class PlayerInventory extends Inventory
} }
// Notify to scripts // Notify to scripts
if (item != null) if (droppedItem != null)
{ {
EventDispatcher.getInstance().notifyEventAsync(new OnPlayerItemDrop(actor, item, item.getLocation()), item.getItem()); EventDispatcher.getInstance().notifyEventAsync(new OnPlayerItemDrop(actor, droppedItem, droppedItem.getLocation()), droppedItem.getItem());
} }
return item;
return droppedItem;
} }
/** /**
@@ -643,6 +648,7 @@ public class PlayerInventory extends Inventory
public ItemInstance dropItem(String process, int objectId, long count, PlayerInstance actor, Object reference) public ItemInstance dropItem(String process, int objectId, long count, PlayerInstance actor, Object reference)
{ {
final ItemInstance item = super.dropItem(process, objectId, count, actor, reference); final ItemInstance item = super.dropItem(process, objectId, count, actor, reference);
if ((_adena != null) && ((_adena.getCount() <= 0) || (_adena.getOwnerId() != getOwnerId()))) if ((_adena != null) && ((_adena.getCount() <= 0) || (_adena.getOwnerId() != getOwnerId())))
{ {
_adena = null; _adena = null;
@@ -195,7 +195,8 @@ public class QuestState
if (value == null) if (value == null)
{ {
value = ""; _vars.put(var, "");
return;
} }
_vars.put(var, value); _vars.put(var, value);
@@ -222,9 +223,9 @@ public class QuestState
* If the key doesn't exist, the couple is added/created in the database</li> * If the key doesn't exist, the couple is added/created in the database</li>
* <ul> * <ul>
* @param var String indicating the name of the variable for quest * @param var String indicating the name of the variable for quest
* @param value String indicating the value of the variable for quest * @param val String indicating the value of the variable for quest
*/ */
public void set(String var, String value) public void set(String var, String val)
{ {
if (_simulated) if (_simulated)
{ {
@@ -236,6 +237,7 @@ public class QuestState
_vars = new HashMap<>(); _vars = new HashMap<>();
} }
String value = val;
if (value == null) if (value == null)
{ {
value = ""; value = "";
@@ -110,6 +110,7 @@ public class SkillCaster implements Runnable
_skill = skill; _skill = skill;
_item = item; _item = item;
_castingType = castingType; _castingType = castingType;
calcSkillTiming(caster, skill); calcSkillTiming(caster, skill);
} }
@@ -132,7 +133,7 @@ public class SkillCaster implements Runnable
/** /**
* Checks if the caster can cast the specified skill on the given target with the selected parameters. * Checks if the caster can cast the specified skill on the given target with the selected parameters.
* @param caster the creature trying to cast * @param caster the creature trying to cast
* @param target the selected target for cast * @param worldObject the selected target for cast
* @param skill the skill being cast * @param skill the skill being cast
* @param item the reference item which requests the skill cast * @param item the reference item which requests the skill cast
* @param castingType the type of casting * @param castingType the type of casting
@@ -141,7 +142,7 @@ public class SkillCaster implements Runnable
* @param castTime custom cast time in milliseconds or -1 for default. * @param castTime custom cast time in milliseconds or -1 for default.
* @return {@code SkillCaster} object containing casting data if casting has started or {@code null} if casting was not started. * @return {@code SkillCaster} object containing casting data if casting has started or {@code null} if casting was not started.
*/ */
public static SkillCaster castSkill(Creature caster, WorldObject target, Skill skill, ItemInstance item, SkillCastingType castingType, boolean ctrlPressed, boolean shiftPressed, int castTime) public static SkillCaster castSkill(Creature caster, WorldObject worldObject, Skill skill, ItemInstance item, SkillCastingType castingType, boolean ctrlPressed, boolean shiftPressed, int castTime)
{ {
if ((caster == null) || (skill == null) || (castingType == null)) if ((caster == null) || (skill == null) || (castingType == null))
{ {
@@ -154,7 +155,7 @@ public class SkillCaster implements Runnable
} }
// Check true aiming target of the skill. // Check true aiming target of the skill.
target = skill.getTarget(caster, target, ctrlPressed, shiftPressed, false); final WorldObject target = skill.getTarget(caster, worldObject, ctrlPressed, shiftPressed, false);
if (target == null) if (target == null)
{ {
return null; return null;
@@ -230,6 +231,7 @@ public class SkillCaster implements Runnable
{ {
final Creature caster = _caster.get(); final Creature caster = _caster.get();
final WorldObject target = _target.get(); final WorldObject target = _target.get();
if ((caster == null) || (target == null)) if ((caster == null) || (target == null))
{ {
return false; return false;
@@ -400,6 +402,7 @@ public class SkillCaster implements Runnable
{ {
final Creature caster = _caster.get(); final Creature caster = _caster.get();
final WorldObject target = _target.get(); final WorldObject target = _target.get();
if ((caster == null) || (target == null)) if ((caster == null) || (target == null))
{ {
return false; return false;
@@ -435,6 +438,7 @@ public class SkillCaster implements Runnable
{ {
final Creature caster = _caster.get(); final Creature caster = _caster.get();
final WorldObject target = _target.get(); final WorldObject target = _target.get();
if ((caster == null) || (target == null)) if ((caster == null) || (target == null))
{ {
return false; return false;
@@ -519,6 +523,7 @@ public class SkillCaster implements Runnable
// On each repeat recharge shots before cast. // On each repeat recharge shots before cast.
caster.rechargeShots(_skill.useSoulShot(), _skill.useSpiritShot(), false); caster.rechargeShots(_skill.useSoulShot(), _skill.useSpiritShot(), false);
return true; return true;
} }
@@ -603,6 +608,7 @@ public class SkillCaster implements Runnable
{ {
// Update pvpflag. // Update pvpflag.
player.updatePvPStatus((Creature) obj); player.updatePvPStatus((Creature) obj);
if (obj.isSummon()) if (obj.isSummon())
{ {
((Summon) obj).updateAndBroadcastStatus(1); ((Summon) obj).updateAndBroadcastStatus(1);
@@ -803,19 +809,21 @@ public class SkillCaster implements Runnable
creature.disableSkill(skill, skill.getReuseDelay()); creature.disableSkill(skill, skill.getReuseDelay());
} }
WorldObject currentTarget = target;
if (!ignoreTargetType) if (!ignoreTargetType)
{ {
final WorldObject objTarget = skill.getTarget(creature, false, false, false); final WorldObject objTarget = skill.getTarget(creature, false, false, false);
if ((objTarget != null) && objTarget.isCreature()) if ((objTarget != null) && objTarget.isCreature())
{ {
target = objTarget; currentTarget = objTarget;
} }
} }
final WorldObject[] targets = skill.getTargetsAffected(creature, target).toArray(new WorldObject[0]); final WorldObject[] targets = skill.getTargetsAffected(creature, currentTarget).toArray(new WorldObject[0]);
if (!skill.isNotBroadcastable()) if (!skill.isNotBroadcastable())
{ {
creature.broadcastPacket(new MagicSkillUse(creature, target, skill.getDisplayId(), skill.getLevel(), 0, 0)); creature.broadcastPacket(new MagicSkillUse(creature, currentTarget, skill.getDisplayId(), skill.getLevel(), 0, 0));
} }
// Launch the magic skill and calculate its effects // Launch the magic skill and calculate its effects
@@ -204,14 +204,16 @@ public class Formulas
/** /**
* Returns true in case of critical hit * Returns true in case of critical hit
* @param rate * @param rateValue
* @param skill * @param skill
* @param creature * @param creature
* @param target * @param target
* @return * @return
*/ */
public static boolean calcCrit(double rate, Creature creature, Creature target, Skill skill) public static boolean calcCrit(double rateValue, Creature creature, Creature target, Skill skill)
{ {
double rate = rateValue;
if (skill != null) if (skill != null)
{ {
// Magic Critical Rate. // Magic Critical Rate.
@@ -1238,7 +1240,7 @@ public class Formulas
final double karmaLooseMul = KarmaData.getInstance().getMultiplier(player.getLevel()); final double karmaLooseMul = KarmaData.getInstance().getMultiplier(player.getLevel());
if (finalExp > 0) // Received exp if (finalExp > 0) // Received exp
{ {
finalExp /= Config.RATE_KARMA_LOST; return (int) ((Math.abs(finalExp / Config.RATE_KARMA_LOST) / karmaLooseMul) / 30);
} }
return (int) ((Math.abs(finalExp) / karmaLooseMul) / 30); return (int) ((Math.abs(finalExp) / karmaLooseMul) / 30);
} }
@@ -325,16 +325,16 @@ public enum Stat
public static Stat valueOfXml(String name) public static Stat valueOfXml(String name)
{ {
name = name.intern(); String internName = name.intern();
for (Stat s : values()) for (Stat s : values())
{ {
if (s.getValue().equals(name)) if (s.getValue().equals(internName))
{ {
return s; return s;
} }
} }
throw new NoSuchElementException("Unknown name '" + name + "' for enum " + Stat.class.getSimpleName()); throw new NoSuchElementException("Unknown name '" + internName + "' for enum " + Stat.class.getSimpleName());
} }
/** /**
@@ -81,7 +81,8 @@ public abstract class AbstractHtmlPacket implements IClientOutgoingPacket
if (!html.contains("<html") && !html.startsWith("..\\L2")) if (!html.contains("<html") && !html.startsWith("..\\L2"))
{ {
html = "<html><body>" + html + "</body></html>"; _html = "<html><body>" + html + "</body></html>";
return;
} }
_html = html; _html = html;
@@ -46,9 +46,9 @@ public class MagicSkillLaunched implements IClientOutgoingPacket
_castingType = castingType; _castingType = castingType;
if (targets == null) if (targets == null)
{ {
targets = Collections.singletonList(creature); _targets = Collections.singletonList(creature);
return;
} }
_targets = targets; _targets = targets;
} }
@@ -150,16 +150,17 @@ public class ScriptEngineManager implements IXmlReader
} }
} }
public void executeScript(Path sourceFile) throws Exception public void executeScript(Path sourceFiles) throws Exception
{ {
if (!sourceFile.isAbsolute()) Path path = sourceFiles;
if (!path.isAbsolute())
{ {
sourceFile = SCRIPT_FOLDER.resolve(sourceFile); path = SCRIPT_FOLDER.resolve(path);
} }
sourceFile = sourceFile.toAbsolutePath(); path = path.toAbsolutePath();
final Entry<Path, Throwable> error = _javaExecutionContext.executeScript(sourceFile); final Entry<Path, Throwable> error = _javaExecutionContext.executeScript(path);
if (error != null) if (error != null)
{ {
throw new Exception("ScriptEngine: " + error.getKey() + " failed execution!", error.getValue()); throw new Exception("ScriptEngine: " + error.getKey() + " failed execution!", error.getValue());
@@ -103,19 +103,20 @@ final class ScriptingFileManager implements StandardJavaFileManager
return _wrapped.getJavaFileForOutput(location, className, kind, sibling); return _wrapped.getJavaFileForOutput(location, className, kind, sibling);
} }
if (className.contains("/")) String javaName = className;
if (javaName.contains("/"))
{ {
className = className.replace('/', '.'); javaName = javaName.replace('/', '.');
} }
ScriptingOutputFileObject fileObject; ScriptingOutputFileObject fileObject;
if (sibling != null) if (sibling != null)
{ {
fileObject = new ScriptingOutputFileObject(Paths.get(sibling.getName()), className, className.substring(className.lastIndexOf('.') + 1)); fileObject = new ScriptingOutputFileObject(Paths.get(sibling.getName()), javaName, javaName.substring(javaName.lastIndexOf('.') + 1));
} }
else else
{ {
fileObject = new ScriptingOutputFileObject(null, className, className.substring(className.lastIndexOf('.') + 1)); fileObject = new ScriptingOutputFileObject(null, javaName, javaName.substring(javaName.lastIndexOf('.') + 1));
} }
_classOutputs.add(fileObject); _classOutputs.add(fileObject);
@@ -100,7 +100,7 @@ public class SecondaryPasswordAuth
} }
} }
public boolean savePassword(String password) public boolean savePassword(String value)
{ {
if (passwordExist()) if (passwordExist())
{ {
@@ -109,14 +109,13 @@ public class SecondaryPasswordAuth
return false; return false;
} }
if (!validatePassword(password)) if (!validatePassword(value))
{ {
_activeClient.sendPacket(new Ex2ndPasswordAck(0, Ex2ndPasswordAck.WRONG_PATTERN)); _activeClient.sendPacket(new Ex2ndPasswordAck(0, Ex2ndPasswordAck.WRONG_PATTERN));
return false; return false;
} }
password = cryptPassword(password); final String password = cryptPassword(value);
try (Connection con = DatabaseFactory.getConnection(); try (Connection con = DatabaseFactory.getConnection();
PreparedStatement statement = con.prepareStatement(INSERT_PASSWORD)) PreparedStatement statement = con.prepareStatement(INSERT_PASSWORD))
{ {
@@ -173,12 +172,11 @@ public class SecondaryPasswordAuth
return false; return false;
} }
newPassword = cryptPassword(newPassword); final String password = cryptPassword(newPassword);
try (Connection con = DatabaseFactory.getConnection(); try (Connection con = DatabaseFactory.getConnection();
PreparedStatement statement = con.prepareStatement(UPDATE_PASSWORD)) PreparedStatement statement = con.prepareStatement(UPDATE_PASSWORD))
{ {
statement.setString(1, newPassword); statement.setString(1, password);
statement.setString(2, _activeClient.getAccountName()); statement.setString(2, _activeClient.getAccountName());
statement.setString(3, VAR_PWD); statement.setString(3, VAR_PWD);
statement.execute(); statement.execute();
@@ -189,14 +187,14 @@ public class SecondaryPasswordAuth
return false; return false;
} }
_password = newPassword; _password = password;
_authed = false; _authed = false;
return true; return true;
} }
public boolean checkPassword(String password, boolean skipAuth) public boolean checkPassword(String value, boolean skipAuth)
{ {
password = cryptPassword(password); final String password = cryptPassword(value);
if (!password.equals(_password)) if (!password.equals(_password))
{ {
_wrongAttempts++; _wrongAttempts++;
@@ -62,10 +62,11 @@ public class AttackStanceTaskManager
/** /**
* Removes the attack stance task. * Removes the attack stance task.
* @param actor the actor * @param creature the actor
*/ */
public void removeAttackStanceTask(Creature actor) public void removeAttackStanceTask(Creature creature)
{ {
Creature actor = creature;
if (actor != null) if (actor != null)
{ {
if (actor.isSummon()) if (actor.isSummon())
@@ -78,11 +79,12 @@ public class AttackStanceTaskManager
/** /**
* Checks for attack stance task. * Checks for attack stance task.
* @param actor the actor * @param creature the actor
* @return {@code true} if the character has an attack stance task, {@code false} otherwise * @return {@code true} if the character has an attack stance task, {@code false} otherwise
*/ */
public boolean hasAttackStanceTask(Creature actor) public boolean hasAttackStanceTask(Creature creature)
{ {
Creature actor = creature;
if (actor != null) if (actor != null)
{ {
if (actor.isSummon()) if (actor.isSummon())
@@ -136,13 +136,14 @@ public class SystemPanel extends JPanel
static String getDurationBreakdown(long millis) static String getDurationBreakdown(long millis)
{ {
final long days = TimeUnit.MILLISECONDS.toDays(millis); long remaining = millis;
millis -= TimeUnit.DAYS.toMillis(days); final long days = TimeUnit.MILLISECONDS.toDays(remaining);
final long hours = TimeUnit.MILLISECONDS.toHours(millis); remaining -= TimeUnit.DAYS.toMillis(days);
millis -= TimeUnit.HOURS.toMillis(hours); final long hours = TimeUnit.MILLISECONDS.toHours(remaining);
final long minutes = TimeUnit.MILLISECONDS.toMinutes(millis); remaining -= TimeUnit.HOURS.toMillis(hours);
millis -= TimeUnit.MINUTES.toMillis(minutes); final long minutes = TimeUnit.MILLISECONDS.toMinutes(remaining);
final long seconds = TimeUnit.MILLISECONDS.toSeconds(millis); remaining -= TimeUnit.MINUTES.toMillis(minutes);
final long seconds = TimeUnit.MILLISECONDS.toSeconds(remaining);
return (days + "d " + hours + "h " + minutes + "m " + seconds + "s"); return (days + "d " + hours + "h " + minutes + "m " + seconds + "s");
} }
} }
@@ -121,10 +121,11 @@ public class Broadcast
* <font color=#FF0000><b><u>Caution</u>: This method DOESN'T SEND Server->Client packet to this Creature (to do this use method toSelfAndKnownPlayers)</b></font> * <font color=#FF0000><b><u>Caution</u>: This method DOESN'T SEND Server->Client packet to this Creature (to do this use method toSelfAndKnownPlayers)</b></font>
* @param creature * @param creature
* @param mov * @param mov
* @param radius * @param radiusValue
*/ */
public static void toKnownPlayersInRadius(Creature creature, IClientOutgoingPacket mov, int radius) public static void toKnownPlayersInRadius(Creature creature, IClientOutgoingPacket mov, int radiusValue)
{ {
int radius = radiusValue;
if (radius < 0) if (radius < 0)
{ {
radius = 1500; radius = 1500;
@@ -154,8 +155,9 @@ public class Broadcast
} }
// To improve performance we are comparing values of radius^2 instead of calculating sqrt all the time // To improve performance we are comparing values of radius^2 instead of calculating sqrt all the time
public static void toSelfAndKnownPlayersInRadius(Creature creature, IClientOutgoingPacket mov, int radius) public static void toSelfAndKnownPlayersInRadius(Creature creature, IClientOutgoingPacket mov, int radiusValue)
{ {
int radius = radiusValue;
if (radius < 0) if (radius < 0)
{ {
radius = 600; radius = 600;
@@ -145,7 +145,7 @@ public class HtmlUtil
/** /**
* Gets the HTML representation of a gauge. * Gets the HTML representation of a gauge.
* @param width the width * @param width the width
* @param current the current value * @param currentValue the current value
* @param max the max value * @param max the max value
* @param displayAsPercentage if {@code true} the text in middle will be displayed as percent else it will be displayed as "current / max" * @param displayAsPercentage if {@code true} the text in middle will be displayed as percent else it will be displayed as "current / max"
* @param backgroundImage the background image * @param backgroundImage the background image
@@ -154,9 +154,9 @@ public class HtmlUtil
* @param top the top adjustment * @param top the top adjustment
* @return the HTML * @return the HTML
*/ */
private static String getGauge(int width, long current, long max, boolean displayAsPercentage, String backgroundImage, String image, long imageHeight, long top) private static String getGauge(int width, long currentValue, long max, boolean displayAsPercentage, String backgroundImage, String image, long imageHeight, long top)
{ {
current = Math.min(current, max); final long current = Math.min(currentValue, max);
final StringBuilder sb = new StringBuilder(); final StringBuilder sb = new StringBuilder();
sb.append("<table width="); sb.append("<table width=");
sb.append(width); sb.append(width);
@@ -51,13 +51,14 @@ public class Locator
/** /**
* Find the directory or jar a given resource has been loaded from. * Find the directory or jar a given resource has been loaded from.
* @param c the classloader to be consulted for the source. * @param classLoader the classloader to be consulted for the source.
* @param resource the resource whose location is required. * @param resource the resource whose location is required.
* @return the file with the resource source or null if we cannot determine the location. * @return the file with the resource source or null if we cannot determine the location.
* @since Ant 1.6 * @since Ant 1.6
*/ */
public static File getResourceSource(ClassLoader c, String resource) public static File getResourceSource(ClassLoader classLoader, String resource)
{ {
ClassLoader c = classLoader;
if (c == null) if (c == null)
{ {
c = Locator.class.getClassLoader(); c = Locator.class.getClassLoader();
@@ -98,12 +99,13 @@ public class Locator
* <p> * <p>
* Swallows '%' that are not followed by two characters, doesn't deal with non-ASCII characters. * Swallows '%' that are not followed by two characters, doesn't deal with non-ASCII characters.
* </p> * </p>
* @param uri the URI designating a file in the local filesystem. * @param uriValue the URI designating a file in the local filesystem.
* @return the local file system path for the file. * @return the local file system path for the file.
* @since Ant 1.6 * @since Ant 1.6
*/ */
public static String fromURI(String uri) public static String fromURI(String uriValue)
{ {
String uri = uriValue;
URL url = null; URL url = null;
try try
{ {
@@ -113,10 +115,12 @@ public class Locator
{ {
// Ignore malformed exception // Ignore malformed exception
} }
if ((url == null) || !("file".equals(url.getProtocol()))) if ((url == null) || !("file".equals(url.getProtocol())))
{ {
throw new IllegalArgumentException("Can only handle valid file: URIs"); throw new IllegalArgumentException("Can only handle valid file: URIs");
} }
final StringBuilder buf = new StringBuilder(url.getHost()); final StringBuilder buf = new StringBuilder(url.getHost());
if (buf.length() > 0) if (buf.length() > 0)
{ {
@@ -125,13 +129,12 @@ public class Locator
final String file = url.getFile(); final String file = url.getFile();
final int queryPos = file.indexOf('?'); final int queryPos = file.indexOf('?');
buf.append((queryPos < 0) ? file : file.substring(0, queryPos)); buf.append((queryPos < 0) ? file : file.substring(0, queryPos));
uri = buf.toString().replace('/', File.separatorChar); uri = buf.toString().replace('/', File.separatorChar);
if ((File.pathSeparatorChar == ';') && uri.startsWith("\\") && (uri.length() > 2) && Character.isLetter(uri.charAt(1)) && (uri.lastIndexOf(':') > -1)) if ((File.pathSeparatorChar == ';') && uri.startsWith("\\") && (uri.length() > 2) && Character.isLetter(uri.charAt(1)) && (uri.lastIndexOf(':') > -1))
{ {
uri = uri.substring(1); uri = uri.substring(1);
} }
return decodeUri(uri); return decodeUri(uri);
} }
@@ -71,7 +71,7 @@ public class TimeAmountInterpreter
* Please keep in mind, that this method is primarily designed to be used with heap text builders. Therefore, if the given text builder throws an {@link IOException}, this exception will be wrapped in a {@link RuntimeException} and returned to the caller as an unchecked exception. * Please keep in mind, that this method is primarily designed to be used with heap text builders. Therefore, if the given text builder throws an {@link IOException}, this exception will be wrapped in a {@link RuntimeException} and returned to the caller as an unchecked exception.
* @param <T> * @param <T>
* @param textBuilder a character sequence builder * @param textBuilder a character sequence builder
* @param timeAmount amount of time to be written * @param amount amount of time to be written
* @param timeUnit unit of the given amount * @param timeUnit unit of the given amount
* @param minConsolidationUnit smallest unit to be included within the description * @param minConsolidationUnit smallest unit to be included within the description
* @param maxConsolidationUnit largest unit to be included within the description * @param maxConsolidationUnit largest unit to be included within the description
@@ -79,10 +79,11 @@ public class TimeAmountInterpreter
* @return {@code textBuilder} * @return {@code textBuilder}
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private static <T extends Appendable & CharSequence> T appendConsolidated(T textBuilder, long timeAmount, TimeUnit timeUnit, TimeUnit minConsolidationUnit, TimeUnit maxConsolidationUnit, String noTimeUsedIndicator) private static <T extends Appendable & CharSequence> T appendConsolidated(T textBuilder, long amount, TimeUnit timeUnit, TimeUnit minConsolidationUnit, TimeUnit maxConsolidationUnit, String noTimeUsedIndicator)
{ {
try try
{ {
long timeAmount = amount;
if (timeAmount < 1) if (timeAmount < 1)
{ {
return (T) textBuilder.append(noTimeUsedIndicator); return (T) textBuilder.append(noTimeUsedIndicator);
@@ -117,6 +118,7 @@ public class TimeAmountInterpreter
{ {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
return textBuilder; return textBuilder;
} }
} }
@@ -642,8 +642,7 @@ public class Util
*/ */
public static int map(int input, int inputMin, int inputMax, int outputMin, int outputMax) public static int map(int input, int inputMin, int inputMax, int outputMin, int outputMax)
{ {
input = constrain(input, inputMin, inputMax); return (((constrain(input, inputMin, inputMax) - inputMin) * (outputMax - outputMin)) / (inputMax - inputMin)) + outputMin;
return (((input - inputMin) * (outputMax - outputMin)) / (inputMax - inputMin)) + outputMin;
} }
/** /**
@@ -657,8 +656,7 @@ public class Util
*/ */
public static long map(long input, long inputMin, long inputMax, long outputMin, long outputMax) public static long map(long input, long inputMin, long inputMax, long outputMin, long outputMax)
{ {
input = constrain(input, inputMin, inputMax); return (((constrain(input, inputMin, inputMax) - inputMin) * (outputMax - outputMin)) / (inputMax - inputMin)) + outputMin;
return (((input - inputMin) * (outputMax - outputMin)) / (inputMax - inputMin)) + outputMin;
} }
/** /**
@@ -672,8 +670,7 @@ public class Util
*/ */
public static double map(double input, double inputMin, double inputMax, double outputMin, double outputMax) public static double map(double input, double inputMin, double inputMax, double outputMin, double outputMax)
{ {
input = constrain(input, inputMin, inputMax); return (((constrain(input, inputMin, inputMax) - inputMin) * (outputMax - outputMin)) / (inputMax - inputMin)) + outputMin;
return (((input - inputMin) * (outputMax - outputMin)) / (inputMax - inputMin)) + outputMin;
} }
/** /**
@@ -272,16 +272,17 @@ public class CronParser
/** /**
* Parses a crontab-like line. * Parses a crontab-like line.
* @param table The table on which the parsed task will be stored, by side-effect. * @param table The table on which the parsed task will be stored, by side-effect.
* @param line The crontab-like line. * @param lineValue The crontab-like line.
* @throws Exception The supplied line doesn't represent a valid task line. * @throws Exception The supplied line doesn't represent a valid task line.
*/ */
public static void parseLine(TaskTable table, String line) throws Exception public static void parseLine(TaskTable table, String lineValue) throws Exception
{ {
line = line.trim(); String line = lineValue.trim();
if ((line.isEmpty()) || (line.charAt(0) == '#')) if ((line.isEmpty()) || (line.charAt(0) == '#'))
{ {
return; return;
} }
// Detecting the pattern. // Detecting the pattern.
int size = line.length(); int size = line.length();
String pattern = null; String pattern = null;
@@ -298,8 +299,10 @@ public class CronParser
{ {
throw new Exception("Invalid cron line: " + line); throw new Exception("Invalid cron line: " + line);
} }
line = line.substring(pattern.length()); line = line.substring(pattern.length());
size = line.length(); size = line.length();
// Splitting the line // Splitting the line
final ArrayList<String> splitted = new ArrayList<>(); final ArrayList<String> splitted = new ArrayList<>();
StringBuilder current = null; StringBuilder current = null;
@@ -351,6 +354,7 @@ public class CronParser
} }
} }
} }
if ((current != null) && (current.length() > 0)) if ((current != null) && (current.length() > 0))
{ {
String str = current.toString(); String str = current.toString();
@@ -361,6 +365,7 @@ public class CronParser
splitted.add(str); splitted.add(str);
current = null; current = null;
} }
// Analyzing // Analyzing
size = splitted.size(); size = splitted.size();
int status = 0; int status = 0;
@@ -377,6 +382,7 @@ public class CronParser
for (int i = 0; i < size; i++) for (int i = 0; i < size; i++)
{ {
final String tk = splitted.get(i); final String tk = splitted.get(i);
// Check the local status. // Check the local status.
if (status == 0) if (status == 0)
{ {
@@ -424,8 +430,10 @@ public class CronParser
} }
} }
} }
// Task preparing. // Task preparing.
Task task; Task task;
// Command evaluation. // Command evaluation.
if (command == null) if (command == null)
{ {
@@ -471,6 +479,7 @@ public class CronParser
{ {
cmdarray[i + 1] = argsList.get(i); cmdarray[i + 1] = argsList.get(i);
} }
// Environments. // Environments.
String[] envs = null; String[] envs = null;
size = envsList.size(); size = envsList.size();
@@ -482,6 +491,7 @@ public class CronParser
envs[i] = envsList.get(i); envs[i] = envsList.get(i);
} }
} }
// Working directory. // Working directory.
File dir = null; File dir = null;
if (dirString != null) if (dirString != null)
@@ -492,8 +502,10 @@ public class CronParser
throw new Exception("Invalid cron working directory parameter at line: " + line, new FileNotFoundException(dirString + " doesn't exist or it is not a directory")); throw new Exception("Invalid cron working directory parameter at line: " + line, new FileNotFoundException(dirString + " doesn't exist or it is not a directory"));
} }
} }
// Builds the task. // Builds the task.
final ProcessTask process = new ProcessTask(cmdarray, envs, dir); final ProcessTask process = new ProcessTask(cmdarray, envs, dir);
// Channels. // Channels.
if (stdinFile != null) if (stdinFile != null)
{ {
@@ -509,6 +521,7 @@ public class CronParser
} }
task = process; task = process;
} }
// End. // End.
table.add(new SchedulingPattern(pattern), task); table.add(new SchedulingPattern(pattern), task);
} }
@@ -145,7 +145,9 @@ public class LoginServer
lnr.lines() lnr.lines()
.map(String::trim) .map(String::trim)
.filter(l -> !l.isEmpty() && (l.charAt(0) != '#')) .filter(l -> !l.isEmpty() && (l.charAt(0) != '#'))
.forEach(line -> { .forEach(lineValue ->
{
String line = lineValue;
String[] parts = line.split("#", 2); // address[ duration][ # comments] String[] parts = line.split("#", 2); // address[ duration][ # comments]
line = parts[0]; line = parts[0];
parts = line.split("\\s+"); // durations might be aligned via multiple spaces parts = line.split("\\s+"); // durations might be aligned via multiple spaces
@@ -100,16 +100,17 @@ public class DBInstallerConsole implements DBOutputInterface
*/ */
public DBInstallerConsole(String defDatabase, String dir, String host, String port, String user, String pass, String database, String mode) throws Exception public DBInstallerConsole(String defDatabase, String dir, String host, String port, String user, String pass, String database, String mode) throws Exception
{ {
if ((database == null) || database.isEmpty()) String currentDatabase = database;
if ((currentDatabase == null) || currentDatabase.isEmpty())
{ {
database = defDatabase; currentDatabase = defDatabase;
} }
final MySqlConnect connector = new MySqlConnect(host, port, user, pass, database, true); final MySqlConnect connector = new MySqlConnect(host, port, user, pass, currentDatabase, true);
_con = connector.getConnection(); _con = connector.getConnection();
if ((mode != null) && ("c".equalsIgnoreCase(mode) || "u".equalsIgnoreCase(mode))) if ((mode != null) && ("c".equalsIgnoreCase(mode) || "u".equalsIgnoreCase(mode)))
{ {
final RunTasks rt = new RunTasks(this, database, dir); final RunTasks rt = new RunTasks(this, currentDatabase, dir);
rt.run(); rt.run();
} }
} }
@@ -274,11 +274,13 @@ public class GeoDataConverter
* @param x : Geodata X coordinate. * @param x : Geodata X coordinate.
* @param y : Geodata Y coordinate. * @param y : Geodata Y coordinate.
* @param z : Geodata Z coordinate. * @param z : Geodata Z coordinate.
* @param nswe : NSWE flag to be updated. * @param nsweValue : NSWE flag to be updated.
* @return byte : Updated NSWE flag. * @return byte : Updated NSWE flag.
*/ */
private static byte updateNsweBelow(int x, int y, short z, byte nswe) private static byte updateNsweBelow(int x, int y, short z, byte nsweValue)
{ {
byte nswe = nsweValue;
// calculate virtual layer height // calculate virtual layer height
final short height = (short) (z + GeoStructure.CELL_IGNORE_HEIGHT); final short height = (short) (z + GeoStructure.CELL_IGNORE_HEIGHT);
@@ -303,12 +303,13 @@ public abstract class BaseGameServerRegister
/** /**
* Show the error. * Show the error.
* @param msg the msg * @param message the msg
* @param t the t * @param t the t
*/ */
public void showError(String msg, Throwable t) public void showError(String message, Throwable t)
{ {
String title; String title;
String msg = message;
if (_bundle != null) if (_bundle != null)
{ {
title = _bundle.getString("error"); title = _bundle.getString("error");

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