Code improvements.

This commit is contained in:
MobiusDev
2016-04-24 16:30:15 +00:00
parent 8bd51aba1c
commit 2dd14bef9b
860 changed files with 8865 additions and 17041 deletions

View File

@@ -2886,10 +2886,9 @@ public final class Config
{
for (int regionY = L2World.TILE_Y_MIN; regionY <= L2World.TILE_Y_MAX; regionY++)
{
final String key = regionX + "_" + regionY;
if (geoData.containskey(regionX + "_" + regionY))
{
GEODATA_REGIONS.put(key, geoData.getBoolean(key, false));
GEODATA_REGIONS.put((regionX + "_" + regionY), geoData.getBoolean((regionX + "_" + regionY), false));
}
}
}
@@ -3167,11 +3166,7 @@ public final class Config
public boolean isAllowed(int job)
{
if ((_allowedClassChange == null) || !_allowedClassChange.containsKey(job))
{
return false;
}
return _allowedClassChange.get(job);
return (_allowedClassChange != null) && _allowedClassChange.containsKey(job) && _allowedClassChange.get(job);
}
public List<ItemHolder> getRewardItems(int job)
@@ -3267,8 +3262,7 @@ public final class Config
public void load()
{
GameServer.printSection("Network Configuration");
final File f = new File(IP_CONFIG_FILE);
if (f.exists())
if ((new File(IP_CONFIG_FILE)).exists())
{
LOGGER.log(Level.INFO, "Using existing ipconfig.xml.");
parseFile(new File(IP_CONFIG_FILE));
@@ -3391,20 +3385,12 @@ public final class Config
protected List<String> getSubnets()
{
if (_subnets.isEmpty())
{
return Arrays.asList("0.0.0.0/0");
}
return _subnets;
return _subnets.isEmpty() ? Arrays.asList("0.0.0.0/0") : _subnets;
}
protected List<String> getHosts()
{
if (_hosts.isEmpty())
{
return Arrays.asList("127.0.0.1");
}
return _hosts;
return _hosts.isEmpty() ? Arrays.asList("127.0.0.1") : _hosts;
}
}
}

View File

@@ -48,8 +48,7 @@ public final class ComplexBlock implements IBlock
private int _getCellHeight(int geoX, int geoY)
{
final short height = (short) (_getCellData(geoX, geoY) & 0x0FFF0);
return height >> 1;
return (short) (_getCellData(geoX, geoY) & 0x0FFF0) >> 1;
}
@Override

View File

@@ -52,8 +52,7 @@ public class JavaCompiler
public Map<String, byte[]> compile(String source, String fileName)
{
final PrintWriter err = new PrintWriter(System.err);
return compile(source, fileName, err, null, null);
return compile(source, fileName, new PrintWriter(System.err), null, null);
}
public Map<String, byte[]> compile(String fileName, String source, Writer err)

View File

@@ -89,8 +89,7 @@ public class JavaScriptEngine extends AbstractScriptEngine implements Compilable
{
final Map<String, byte[]> classBytesCopy = new HashMap<>();
classBytesCopy.putAll(_classBytes);
final MemoryClassLoader loader = new MemoryClassLoader(classBytesCopy, _classPath, JavaScriptEngine.getParentLoader(ctx));
_class = JavaScriptEngine.parseMain(loader, ctx);
_class = JavaScriptEngine.parseMain(new MemoryClassLoader(classBytesCopy, _classPath, JavaScriptEngine.getParentLoader(ctx)), ctx);
}
return JavaScriptEngine.evalClass(_class, ctx);
}
@@ -111,8 +110,7 @@ public class JavaScriptEngine extends AbstractScriptEngine implements Compilable
@Override
public Object eval(String str, ScriptContext ctx) throws ScriptException
{
final Class<?> clazz = parse(str, ctx);
return evalClass(clazz, ctx);
return evalClass(parse(str, ctx), ctx);
}
@Override
@@ -153,26 +151,17 @@ public class JavaScriptEngine extends AbstractScriptEngine implements Compilable
final String sourcePath = getSourcePath(ctx);
final String classPath = getClassPath(ctx);
Writer err = ctx.getErrorWriter();
if (err == null)
{
err = new StringWriter();
}
final Writer err = ctx.getErrorWriter() == null ? new StringWriter() : ctx.getErrorWriter();
final Map<String, byte[]> classBytes = compiler.compile(fileName, str, err, sourcePath, classPath);
if (classBytes == null)
{
if (err instanceof StringWriter)
{
throw new ScriptException(((StringWriter) err).toString());
}
throw new ScriptException("compilation failed");
throw err instanceof StringWriter ? new ScriptException(((StringWriter) err).toString()) : new ScriptException("compilation failed");
}
// create a ClassLoader to load classes from MemoryJavaFileManager
final MemoryClassLoader loader = new MemoryClassLoader(classBytes, classPath, getParentLoader(ctx));
return parseMain(loader, ctx);
return parseMain((new MemoryClassLoader(classBytes, classPath, getParentLoader(ctx))), ctx);
}
protected static Class<?> parseMain(MemoryClassLoader loader, ScriptContext ctx) throws ScriptException
@@ -218,11 +207,7 @@ public class JavaScriptEngine extends AbstractScriptEngine implements Compilable
// if class with "main" method, then
// return first class
final Iterator<Class<?>> itr = classes.iterator();
if (itr.hasNext())
{
return itr.next();
}
return null;
return itr.hasNext() ? itr.next() : null;
}
private JavaCompiledScript compile(String str, ScriptContext ctx) throws ScriptException
@@ -231,20 +216,11 @@ public class JavaScriptEngine extends AbstractScriptEngine implements Compilable
final String sourcePath = getSourcePath(ctx);
final String classPath = getClassPath(ctx);
Writer err = ctx.getErrorWriter();
if (err == null)
{
err = new StringWriter();
}
final Writer err = ctx.getErrorWriter() == null ? new StringWriter() : ctx.getErrorWriter();
final Map<String, byte[]> classBytes = compiler.compile(fileName, str, err, sourcePath, classPath);
if (classBytes == null)
{
if (err instanceof StringWriter)
{
throw new ScriptException(((StringWriter) err).toString());
}
throw new ScriptException("compilation failed");
throw err instanceof StringWriter ? new ScriptException(((StringWriter) err).toString()) : new ScriptException("compilation failed");
}
return new JavaCompiledScript(this, classBytes, classPath);
@@ -255,14 +231,9 @@ public class JavaScriptEngine extends AbstractScriptEngine implements Compilable
// find a public class with public static main method
for (Class<?> clazz : classes)
{
final int modifiers = clazz.getModifiers();
if (Modifier.isPublic(modifiers))
if (Modifier.isPublic(clazz.getModifiers()) && (findMainMethod(clazz) != null))
{
final Method mainMethod = findMainMethod(clazz);
if (mainMethod != null)
{
return clazz;
}
return clazz;
}
}
@@ -270,8 +241,7 @@ public class JavaScriptEngine extends AbstractScriptEngine implements Compilable
// has public static main method
for (Class<?> clazz : classes)
{
final Method mainMethod = findMainMethod(clazz);
if (mainMethod != null)
if (findMainMethod(clazz) != null)
{
return clazz;
}
@@ -326,11 +296,7 @@ public class JavaScriptEngine extends AbstractScriptEngine implements Compilable
private static String getFileName(ScriptContext ctx)
{
final int scope = ctx.getAttributesScope("javax.script.filename");
if (scope != -1)
{
return ctx.getAttribute("javax.script.filename", scope).toString();
}
return "$unnamed.java";
return scope != -1 ? ctx.getAttribute("javax.script.filename", scope).toString() : "$unnamed.java";
}
// for certain variables, we look for System properties. This is
@@ -359,14 +325,7 @@ public class JavaScriptEngine extends AbstractScriptEngine implements Compilable
private static String getSourcePath(ScriptContext ctx)
{
final int scope = ctx.getAttributesScope(SOURCEPATH);
if (scope != -1)
{
return ctx.getAttribute(SOURCEPATH).toString();
}
// look for "com.sun.script.java.sourcepath"
return System.getProperty(SYSPROP_PREFIX + SOURCEPATH);
return ctx.getAttributesScope(SOURCEPATH) != -1 ? ctx.getAttribute(SOURCEPATH).toString() : System.getProperty(SYSPROP_PREFIX + SOURCEPATH);
}
private static final String CLASSPATH = "classpath";
@@ -392,14 +351,7 @@ public class JavaScriptEngine extends AbstractScriptEngine implements Compilable
private static String getMainClassName(ScriptContext ctx)
{
final int scope = ctx.getAttributesScope(MAINCLASS);
if (scope != -1)
{
return ctx.getAttribute(MAINCLASS).toString();
}
// look for "com.sun.script.java.mainClass"
return System.getProperty("com.sun.script.java.mainClass");
return ctx.getAttributesScope(MAINCLASS) != -1 ? ctx.getAttribute(MAINCLASS).toString() : System.getProperty("com.sun.script.java.mainClass");
}
private static final String PARENTLOADER = "parentLoader";
@@ -456,13 +408,10 @@ public class JavaScriptEngine extends AbstractScriptEngine implements Compilable
mainMethod.setAccessible(true);
}
// get "command line" args for the main method
final String args[] = getArguments(ctx);
// call main method
mainMethod.invoke(null, new Object[]
{
args
getArguments(ctx)
});
}
@@ -495,5 +444,4 @@ public class JavaScriptEngine extends AbstractScriptEngine implements Compilable
}
return buf.toString();
}
}

View File

@@ -114,8 +114,7 @@ public final class MemoryJavaFileManager extends EclipseFileManager
public void close() throws IOException
{
out.close();
final ByteArrayOutputStream bos = (ByteArrayOutputStream) out;
classBytes.put(name, bos.toByteArray());
classBytes.put(name, ((ByteArrayOutputStream) out).toByteArray());
}
};
}

View File

@@ -161,23 +161,20 @@ public class MMOConnection<T extends MMOClient<?>>
final int remaining = temp.remaining();
_primaryWriteBuffer.flip();
final int limit = _primaryWriteBuffer.limit();
if (remaining >= _primaryWriteBuffer.remaining())
{
temp.put(_primaryWriteBuffer);
_selectorThread.recycleBuffer(_primaryWriteBuffer);
_primaryWriteBuffer = temp;
}
else
{
_primaryWriteBuffer.limit(remaining);
temp.put(_primaryWriteBuffer);
_primaryWriteBuffer.limit(limit);
_primaryWriteBuffer.limit(_primaryWriteBuffer.limit());
_primaryWriteBuffer.compact();
_secondaryWriteBuffer = _primaryWriteBuffer;
_primaryWriteBuffer = temp;
}
_primaryWriteBuffer = temp;
}
}

View File

@@ -285,79 +285,80 @@ public final class SelectorThread<T extends MMOClient<?>>extends Thread
private final void readPacket(SelectionKey key, MMOConnection<T> con)
{
if (!con.isClosed())
if (con.isClosed())
{
ByteBuffer buf;
if ((buf = con.getReadBuffer()) == null)
{
buf = READ_BUFFER;
}
return;
}
ByteBuffer buf;
if ((buf = con.getReadBuffer()) == null)
{
buf = READ_BUFFER;
}
// if we try to to do a read with no space in the buffer it will read 0 bytes going into infinite loop
if (buf.position() == buf.limit())
{
System.exit(0);
}
int result = -2;
try
{
result = con.read(buf);
}
catch (IOException e)
{
// error handling goes bellow
}
if (result > 0)
{
buf.flip();
// if we try to to do a read with no space in the buffer it will read 0 bytes going into infinite loop
if (buf.position() == buf.limit())
{
System.exit(0);
}
final T client = con.getClient();
int result = -2;
try
for (int i = 0; i < MAX_READ_PER_PASS; i++)
{
result = con.read(buf);
}
catch (IOException e)
{
// error handling goes bellow
}
if (result > 0)
{
buf.flip();
final T client = con.getClient();
for (int i = 0; i < MAX_READ_PER_PASS; i++)
if (!tryReadPacket(key, client, buf, con))
{
if (!tryReadPacket(key, client, buf, con))
{
return;
}
}
// only reachable if MAX_READ_PER_PASS has been reached
// check if there are some more bytes in buffer
// and allocate/compact to prevent content lose.
if (buf.remaining() > 0)
{
// did we use the READ_BUFFER ?
if (buf == READ_BUFFER)
{
// move the pending byte to the connections READ_BUFFER
allocateReadBuffer(con);
}
else
{
// move the first byte to the beginning :)
buf.compact();
}
return;
}
}
else
// only reachable if MAX_READ_PER_PASS has been reached
// check if there are some more bytes in buffer
// and allocate/compact to prevent content lose.
if (buf.remaining() > 0)
{
switch (result)
// did we use the READ_BUFFER ?
if (buf == READ_BUFFER)
{
case 0:
case -1:
{
closeConnectionImpl(key, con);
break;
}
case -2:
{
con.getClient().onForcedDisconnection();
closeConnectionImpl(key, con);
break;
}
// move the pending byte to the connections READ_BUFFER
allocateReadBuffer(con);
}
else
{
// move the first byte to the beginning :)
buf.compact();
}
}
}
else
{
switch (result)
{
case 0:
case -1:
{
closeConnectionImpl(key, con);
break;
}
case -2:
{
con.getClient().onForcedDisconnection();
closeConnectionImpl(key, con);
break;
}
}
}
@@ -406,38 +407,35 @@ public final class SelectorThread<T extends MMOClient<?>>extends Thread
buf.position(pos + dataPending);
}
// if we are done with this buffer
if (!buf.hasRemaining())
if (buf.hasRemaining())
{
if (buf != READ_BUFFER)
{
con.setReadBuffer(null);
recycleBuffer(buf);
}
else
{
READ_BUFFER.clear();
}
return false;
return true;
}
return true;
if (buf != READ_BUFFER)
{
con.setReadBuffer(null);
recycleBuffer(buf);
}
else
{
READ_BUFFER.clear();
}
return false;
}
// we don`t have enough bytes for the dataPacket so we need
// to read
// we don`t have enough bytes for the dataPacket so we need to read
key.interestOps(key.interestOps() | SelectionKey.OP_READ);
// move it`s position
buf.position(buf.position() - HEADER_SIZE);
// did we use the READ_BUFFER ?
if (buf == READ_BUFFER)
{
// move it`s position
buf.position(buf.position() - HEADER_SIZE);
// move the pending byte to the connections READ_BUFFER
allocateReadBuffer(con);
}
else
{
buf.position(buf.position() - HEADER_SIZE);
buf.compact();
}
return false;
@@ -453,31 +451,31 @@ public final class SelectorThread<T extends MMOClient<?>>extends Thread
private final void parseClientPacket(int pos, ByteBuffer buf, int dataSize, T client)
{
final boolean ret = client.decrypt(buf, dataSize);
if (ret && buf.hasRemaining())
if (!client.decrypt(buf, dataSize) || !buf.hasRemaining())
{
// apply limit
final int limit = buf.limit();
buf.limit(pos + dataSize);
final ReceivablePacket<T> cp = _packetHandler.handlePacket(buf, client);
if (cp != null)
{
cp._buf = buf;
cp._sbuf = STRING_BUFFER;
cp._client = client;
if (cp.read())
{
_executor.execute(cp);
}
cp._buf = null;
cp._sbuf = null;
}
buf.limit(limit);
return;
}
// apply limit
final int limit = buf.limit();
buf.limit(pos + dataSize);
final ReceivablePacket<T> cp = _packetHandler.handlePacket(buf, client);
if (cp != null)
{
cp._buf = buf;
cp._sbuf = STRING_BUFFER;
cp._client = client;
if (cp.read())
{
_executor.execute(cp);
}
cp._buf = null;
cp._sbuf = null;
}
buf.limit(limit);
}
private final void writeClosePacket(MMOConnection<T> con)
@@ -605,15 +603,12 @@ public final class SelectorThread<T extends MMOClient<?>>extends Thread
WRITE_BUFFER.flip();
if (DIRECT_WRITE_BUFFER.remaining() >= WRITE_BUFFER.limit())
{
DIRECT_WRITE_BUFFER.put(WRITE_BUFFER);
}
else
if (DIRECT_WRITE_BUFFER.remaining() < WRITE_BUFFER.limit())
{
con.createWriteBuffer(WRITE_BUFFER);
break;
}
DIRECT_WRITE_BUFFER.put(WRITE_BUFFER);
}
}
return hasPending;

View File

@@ -221,15 +221,7 @@ public class GeoData
*/
public boolean canSeeTarget(L2Object cha, L2Object target)
{
if (target == null)
{
return false;
}
if (target.isDoor())
{
return true;
}
return canSeeTarget(cha.getX(), cha.getY(), cha.getZ(), cha.getInstanceId(), target.getX(), target.getY(), target.getZ(), target.getInstanceId());
return (target != null) && (target.isDoor() || canSeeTarget(cha.getX(), cha.getY(), cha.getZ(), cha.getInstanceId(), target.getX(), target.getY(), target.getZ(), target.getInstanceId()));
}
/**
@@ -257,11 +249,7 @@ public class GeoData
*/
public boolean canSeeTarget(int x, int y, int z, int instanceId, int tx, int ty, int tz, int tInstanceId)
{
if ((instanceId != tInstanceId))
{
return false;
}
return canSeeTarget(x, y, z, instanceId, tx, ty, tz);
return (instanceId == tInstanceId) && canSeeTarget(x, y, z, instanceId, tx, ty, tz);
}
/**
@@ -277,15 +265,7 @@ public class GeoData
*/
public boolean canSeeTarget(int x, int y, int z, int instanceId, int tx, int ty, int tz)
{
if (DoorData.getInstance().checkIfDoorsBetween(x, y, z, tx, ty, tz, instanceId, true))
{
return false;
}
if (WallData.getInstance().checkIfWallsBetween(x, y, z, tx, ty, tz))
{
return false;
}
return canSeeTarget(x, y, z, tx, ty, tz);
return !DoorData.getInstance().checkIfDoorsBetween(x, y, z, tx, ty, tz, instanceId, true) && !WallData.getInstance().checkIfWallsBetween(x, y, z, tx, ty, tz) && canSeeTarget(x, y, z, tx, ty, tz);
}
private int getLosGeoZ(int prevX, int prevY, int prevGeoZ, int curX, int curY, int nswe)
@@ -294,12 +274,7 @@ public class GeoData
{
throw new RuntimeException("Multiple directions!");
}
if (checkNearestNsweAntiCornerCut(prevX, prevY, prevGeoZ, nswe))
{
return getNearestZ(curX, curY, prevGeoZ);
}
return getNextHigherZ(curX, curY, prevGeoZ);
return checkNearestNsweAntiCornerCut(prevX, prevY, prevGeoZ, nswe) ? getNearestZ(curX, curY, prevGeoZ) : getNextHigherZ(curX, curY, prevGeoZ);
}
/**
@@ -325,12 +300,7 @@ public class GeoData
// fastpath
if ((geoX == tGeoX) && (geoY == tGeoY))
{
if (hasGeoPos(tGeoX, tGeoY))
{
return z == tz;
}
return true;
return !hasGeoPos(tGeoX, tGeoY) || (z == tz);
}
if (tz > z)
@@ -382,16 +352,7 @@ public class GeoData
{
final int nswe = GeoUtils.computeNswe(prevX, prevY, curX, curY);
curGeoZ = getLosGeoZ(prevX, prevY, prevGeoZ, curX, curY, nswe);
int maxHeight;
if (ptIndex < ELEVATED_SEE_OVER_DISTANCE)
{
maxHeight = z + MAX_SEE_OVER_HEIGHT;
}
else
{
maxHeight = beeCurZ + MAX_SEE_OVER_HEIGHT;
}
final int maxHeight = ptIndex < ELEVATED_SEE_OVER_DISTANCE ? z + MAX_SEE_OVER_HEIGHT : beeCurZ + MAX_SEE_OVER_HEIGHT;
boolean canSeeThrough = false;
if (curGeoZ <= maxHeight)
{
@@ -471,11 +432,7 @@ public class GeoData
final int tGeoY = getGeoY(ty);
tz = getNearestZ(tGeoX, tGeoY, tz);
if (DoorData.getInstance().checkIfDoorsBetween(x, y, z, tx, ty, tz, instanceId, false))
{
return new Location(x, y, getHeight(x, y, z));
}
if (WallData.getInstance().checkIfWallsBetween(x, y, z, tx, ty, tz))
if (DoorData.getInstance().checkIfDoorsBetween(x, y, z, tx, ty, tz, instanceId, false) || WallData.getInstance().checkIfWallsBetween(x, y, z, tx, ty, tz))
{
return new Location(x, y, getHeight(x, y, z));
}
@@ -492,29 +449,16 @@ public class GeoData
final int curX = pointIter.x();
final int curY = pointIter.y();
final int curZ = getNearestZ(curX, curY, prevZ);
if (hasGeoPos(prevX, prevY))
if (hasGeoPos(prevX, prevY) && !checkNearestNsweAntiCornerCut(prevX, prevY, prevZ, GeoUtils.computeNswe(prevX, prevY, curX, curY)))
{
final int nswe = GeoUtils.computeNswe(prevX, prevY, curX, curY);
if (!checkNearestNsweAntiCornerCut(prevX, prevY, prevZ, nswe))
{
// can't move, return previous location
return new Location(getWorldX(prevX), getWorldY(prevY), prevZ);
}
// can't move, return previous location
return new Location(getWorldX(prevX), getWorldY(prevY), prevZ);
}
prevX = curX;
prevY = curY;
prevZ = curZ;
}
if (hasGeoPos(prevX, prevY) && (prevZ != tz))
{
// different floors, return start location
return new Location(x, y, z);
}
return new Location(tx, ty, tz);
return hasGeoPos(prevX, prevY) && (prevZ != tz) ? new Location(x, y, z) : new Location(tx, ty, tz);
}
/**
@@ -537,11 +481,7 @@ public class GeoData
final int tGeoY = getGeoY(toY);
toZ = getNearestZ(tGeoX, tGeoY, toZ);
if (DoorData.getInstance().checkIfDoorsBetween(fromX, fromY, fromZ, toX, toY, toZ, instanceId, false))
{
return false;
}
if (WallData.getInstance().checkIfWallsBetween(fromX, fromY, fromZ, toX, toY, toZ))
if (DoorData.getInstance().checkIfDoorsBetween(fromX, fromY, fromZ, toX, toY, toZ, instanceId, false) || WallData.getInstance().checkIfWallsBetween(fromX, fromY, fromZ, toX, toY, toZ))
{
return false;
}
@@ -558,28 +498,17 @@ public class GeoData
final int curX = pointIter.x();
final int curY = pointIter.y();
final int curZ = getNearestZ(curX, curY, prevZ);
if (hasGeoPos(prevX, prevY))
if (hasGeoPos(prevX, prevY) && !checkNearestNsweAntiCornerCut(prevX, prevY, prevZ, GeoUtils.computeNswe(prevX, prevY, curX, curY)))
{
final int nswe = GeoUtils.computeNswe(prevX, prevY, curX, curY);
if (!checkNearestNsweAntiCornerCut(prevX, prevY, prevZ, nswe))
{
return false;
}
}
prevX = curX;
prevY = curY;
prevZ = curZ;
}
if (hasGeoPos(prevX, prevY) && (prevZ != toZ))
{
// different floors
return false;
}
return true;
return (!hasGeoPos(prevX, prevY) || (prevZ == toZ));
}
public int traceTerrainZ(int x, int y, int z, int tx, int ty)
@@ -597,11 +526,7 @@ public class GeoData
while (pointIter.next())
{
final int curX = pointIter.x();
final int curY = pointIter.y();
final int curZ = getNearestZ(curX, curY, prevZ);
prevZ = curZ;
prevZ = getNearestZ(pointIter.x(), pointIter.y(), prevZ);
}
return prevZ;

View File

@@ -74,32 +74,24 @@ public final class ItemsAutoDestroy
}
}
}
else if (item.getItem().hasExImmediateEffect())
else if (item.getItem().hasExImmediateEffect() && ((curtime - item.getDropTime()) > Config.HERB_AUTO_DESTROY_TIME))
{
if ((curtime - item.getDropTime()) > Config.HERB_AUTO_DESTROY_TIME)
L2World.getInstance().removeVisibleObject(item, item.getWorldRegion());
L2World.getInstance().removeObject(item);
_items.remove(item.getObjectId());
if (Config.SAVE_DROPPED_ITEM)
{
L2World.getInstance().removeVisibleObject(item, item.getWorldRegion());
L2World.getInstance().removeObject(item);
_items.remove(item.getObjectId());
if (Config.SAVE_DROPPED_ITEM)
{
ItemsOnGroundManager.getInstance().removeObject(item);
}
ItemsOnGroundManager.getInstance().removeObject(item);
}
}
else
else if ((curtime - item.getDropTime()) > ((Config.AUTODESTROY_ITEM_AFTER == 0) ? 3600000 : Config.AUTODESTROY_ITEM_AFTER * 1000))
{
final long sleep = ((Config.AUTODESTROY_ITEM_AFTER == 0) ? 3600000 : Config.AUTODESTROY_ITEM_AFTER * 1000);
if ((curtime - item.getDropTime()) > sleep)
L2World.getInstance().removeVisibleObject(item, item.getWorldRegion());
L2World.getInstance().removeObject(item);
_items.remove(item.getObjectId());
if (Config.SAVE_DROPPED_ITEM)
{
L2World.getInstance().removeVisibleObject(item, item.getWorldRegion());
L2World.getInstance().removeObject(item);
_items.remove(item.getObjectId());
if (Config.SAVE_DROPPED_ITEM)
{
ItemsOnGroundManager.getInstance().removeObject(item);
}
ItemsOnGroundManager.getInstance().removeObject(item);
}
}
}

View File

@@ -203,8 +203,7 @@ public class LoginServerThread extends Thread
break;
}
final int packetType = incoming[0] & 0xff;
switch (packetType)
switch (incoming[0] & 0xff)
{
case 0x00:
{
@@ -220,10 +219,7 @@ public class LoginServerThread extends Thread
try
{
final KeyFactory kfac = KeyFactory.getInstance("RSA");
final BigInteger modulus = new BigInteger(init.getRSAKey());
final RSAPublicKeySpec kspec1 = new RSAPublicKeySpec(modulus, RSAKeyGenParameterSpec.F4);
publicKey = (RSAPublicKey) kfac.generatePublic(kspec1);
publicKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic((new RSAPublicKeySpec(new BigInteger(init.getRSAKey()), RSAKeyGenParameterSpec.F4)));
}
catch (GeneralSecurityException e)
{
@@ -252,35 +248,10 @@ public class LoginServerThread extends Thread
Config.saveHexid(serverID, hexToString(_hexID));
_log.info("Registered on login as Server " + serverID + " : " + _serverName);
final ServerStatus st = new ServerStatus();
if (Config.SERVER_LIST_BRACKET)
{
st.addAttribute(ServerStatus.SERVER_LIST_SQUARE_BRACKET, ServerStatus.ON);
}
else
{
st.addAttribute(ServerStatus.SERVER_LIST_SQUARE_BRACKET, ServerStatus.OFF);
}
st.addAttribute(ServerStatus.SERVER_LIST_SQUARE_BRACKET, Config.SERVER_LIST_BRACKET ? ServerStatus.ON : ServerStatus.OFF);
st.addAttribute(ServerStatus.SERVER_TYPE, Config.SERVER_LIST_TYPE);
if (Config.SERVER_GMONLY)
{
st.addAttribute(ServerStatus.SERVER_LIST_STATUS, ServerStatus.STATUS_GM_ONLY);
}
else
{
st.addAttribute(ServerStatus.SERVER_LIST_STATUS, ServerStatus.STATUS_AUTO);
}
if (Config.SERVER_LIST_AGE == 15)
{
st.addAttribute(ServerStatus.SERVER_AGE, ServerStatus.SERVER_AGE_15);
}
else if (Config.SERVER_LIST_AGE == 18)
{
st.addAttribute(ServerStatus.SERVER_AGE, ServerStatus.SERVER_AGE_18);
}
else
{
st.addAttribute(ServerStatus.SERVER_AGE, ServerStatus.SERVER_AGE_ALL);
}
st.addAttribute(ServerStatus.SERVER_LIST_STATUS, Config.SERVER_GMONLY ? ServerStatus.STATUS_GM_ONLY : ServerStatus.STATUS_AUTO);
st.addAttribute(ServerStatus.SERVER_AGE, Config.SERVER_LIST_AGE == 15 ? ServerStatus.SERVER_AGE_15 : Config.SERVER_LIST_AGE == 18 ? ServerStatus.SERVER_AGE_18 : ServerStatus.SERVER_AGE_ALL);
sendPacket(st);
if (L2World.getInstance().getAllPlayersCount() > 0)
{
@@ -559,17 +530,18 @@ public class LoginServerThread extends Thread
public void doKickPlayer(String account)
{
final L2GameClient client = _accountsInGameServer.get(account);
if (client != null)
if (client == null)
{
final LogRecord record = new LogRecord(Level.WARNING, "Kicked by login");
record.setParameters(new Object[]
{
client
});
_logAccounting.log(record);
client.setAditionalClosePacket(SystemMessage.getSystemMessage(SystemMessageId.YOU_ARE_LOGGED_IN_TO_TWO_PLACES_IF_YOU_SUSPECT_ACCOUNT_THEFT_WE_RECOMMEND_CHANGING_YOUR_PASSWORD_SCANNING_YOUR_COMPUTER_FOR_VIRUSES_AND_USING_AN_ANTI_VIRUS_SOFTWARE));
client.closeNow();
return;
}
final LogRecord record = new LogRecord(Level.WARNING, "Kicked by login");
record.setParameters(new Object[]
{
client
});
_logAccounting.log(record);
client.setAditionalClosePacket(SystemMessage.getSystemMessage(SystemMessageId.YOU_ARE_LOGGED_IN_TO_TWO_PLACES_IF_YOU_SUSPECT_ACCOUNT_THEFT_WE_RECOMMEND_CHANGING_YOUR_PASSWORD_SCANNING_YOUR_COMPUTER_FOR_VIRUSES_AND_USING_AN_ANTI_VIRUS_SOFTWARE));
client.closeNow();
}
/**

View File

@@ -16,7 +16,6 @@
*/
package com.l2jmobius.gameserver;
import java.lang.reflect.Constructor;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -69,8 +68,7 @@ public class MonsterRace
try
{
final L2NpcTemplate template = NpcData.getInstance().getTemplate(id + random);
final Constructor<?> constructor = Class.forName("com.l2jmobius.gameserver.model.actor.instance." + template.getType() + "Instance").getConstructors()[0];
_monsters[i] = (L2Npc) constructor.newInstance(template);
_monsters[i] = (L2Npc) Class.forName("com.l2jmobius.gameserver.model.actor.instance." + template.getType() + "Instance").getConstructors()[0].newInstance(template);
}
catch (Exception e)
{
@@ -91,14 +89,7 @@ public class MonsterRace
total = 0;
for (int j = 0; j < 20; j++)
{
if (j == 19)
{
_speeds[i][j] = 100;
}
else
{
_speeds[i][j] = Rnd.get(60) + 65;
}
_speeds[i][j] = j == 19 ? 100 : Rnd.get(60) + 65;
total += _speeds[i][j];
}
if (total >= _first[1])

View File

@@ -199,51 +199,20 @@ public class RecipeController
_skill = _player.getKnownSkill(_skillId);
_player.isInCraftMode(true);
if (_player.isAlikeDead())
if (_player.isAlikeDead() || _player.isProcessingTransaction() || (_recipeList.getRecipes().length == 0) || (_recipeList.getLevel() > _skillLevel))
{
_player.sendPacket(ActionFailed.STATIC_PACKET);
abort();
return;
}
if (_target.isAlikeDead())
if (_target.isAlikeDead() || _target.isProcessingTransaction())
{
_target.sendPacket(ActionFailed.STATIC_PACKET);
abort();
return;
}
if (_target.isProcessingTransaction())
{
_target.sendPacket(ActionFailed.STATIC_PACKET);
abort();
return;
}
if (_player.isProcessingTransaction())
{
_player.sendPacket(ActionFailed.STATIC_PACKET);
abort();
return;
}
// validate recipe list
if (_recipeList.getRecipes().length == 0)
{
_player.sendPacket(ActionFailed.STATIC_PACKET);
abort();
return;
}
// validate skill level
if (_recipeList.getLevel() > _skillLevel)
{
_player.sendPacket(ActionFailed.STATIC_PACKET);
abort();
return;
}
// check that customer can afford to pay for creation services
if (_player != _target)
{
@@ -388,51 +357,42 @@ public class RecipeController
}
// first take adena for manufacture
if ((_target != _player) && (_price > 0)) // customer must pay for services
if ((_target != _player) && (_price > 0) && (_target.transferItem("PayManufacture", _target.getInventory().getAdenaInstance().getObjectId(), _price, _player.getInventory(), _player) == null)) // customer must pay for services
{
// attempt to pay for item
final L2ItemInstance adenatransfer = _target.transferItem("PayManufacture", _target.getInventory().getAdenaInstance().getObjectId(), _price, _player.getInventory(), _player);
if (adenatransfer == null)
{
_target.sendPacket(SystemMessageId.YOU_DO_NOT_HAVE_ENOUGH_ADENA);
abort();
return;
}
_target.sendPacket(SystemMessageId.YOU_DO_NOT_HAVE_ENOUGH_ADENA);
abort();
return;
}
_items = listItems(true); // this line actually takes materials from inventory
if (_items == null)
if (_items != null)
{
// handle possible cheaters here
// (they click craft then try to get rid of items in order to get free craft)
}
else if (Rnd.get(100) < _recipeList.getSuccessRate())
{
rewardPlayer(); // and immediately puts created item in its place
updateMakeInfo(true);
}
else
{
if (_target != _player)
if (Rnd.get(100) < _recipeList.getSuccessRate())
{
SystemMessage msg = SystemMessage.getSystemMessage(SystemMessageId.YOU_FAILED_TO_CREATE_S2_FOR_C1_AT_THE_PRICE_OF_S3_ADENA);
msg.addString(_target.getName());
msg.addItemName(_recipeList.getItemId());
msg.addLong(_price);
_player.sendPacket(msg);
msg = SystemMessage.getSystemMessage(SystemMessageId.C1_HAS_FAILED_TO_CREATE_S2_AT_THE_PRICE_OF_S3_ADENA);
msg.addString(_player.getName());
msg.addItemName(_recipeList.getItemId());
msg.addLong(_price);
_target.sendPacket(msg);
rewardPlayer();
updateMakeInfo(true);
}
else
{
_target.sendPacket(SystemMessageId.YOU_FAILED_AT_MIXING_THE_ITEM);
if (_target != _player)
{
SystemMessage msg = SystemMessage.getSystemMessage(SystemMessageId.YOU_FAILED_TO_CREATE_S2_FOR_C1_AT_THE_PRICE_OF_S3_ADENA);
msg.addString(_target.getName());
msg.addItemName(_recipeList.getItemId());
msg.addLong(_price);
_player.sendPacket(msg);
msg = SystemMessage.getSystemMessage(SystemMessageId.C1_HAS_FAILED_TO_CREATE_S2_AT_THE_PRICE_OF_S3_ADENA);
msg.addString(_player.getName());
msg.addItemName(_recipeList.getItemId());
msg.addLong(_price);
_target.sendPacket(msg);
}
else
{
_target.sendPacket(SystemMessageId.YOU_FAILED_AT_MIXING_THE_ITEM);
}
updateMakeInfo(false);
}
updateMakeInfo(false);
}
// update load and mana bar of craft window
updateCurMp();
@@ -473,12 +433,7 @@ public class RecipeController
{
final TempItem item = _items.get(0);
int count = item.getQuantity();
if (count >= grabItems)
{
count = grabItems;
}
final int count = item.getQuantity() >= grabItems ? grabItems : item.getQuantity();
item.setQuantity(item.getQuantity() - count);
if (item.getQuantity() <= 0)
{
@@ -638,14 +593,13 @@ public class RecipeController
sm = SystemMessage.getSystemMessage(SystemMessageId.S2_S1_S_DISAPPEARED);
sm.addItemName(tmp.getItemId());
sm.addLong(tmp.getQuantity());
_target.sendPacket(sm);
}
else
{
sm = SystemMessage.getSystemMessage(SystemMessageId.S1_DISAPPEARED);
sm.addItemName(tmp.getItemId());
_target.sendPacket(sm);
}
_target.sendPacket(sm);
}
}
return materials;
@@ -666,18 +620,15 @@ public class RecipeController
final L2Item template = ItemTable.getInstance().getTemplate(itemId);
// check that the current recipe has a rare production or not
if ((rareProdId != -1) && ((rareProdId == itemId) || Config.CRAFT_MASTERWORK))
if ((rareProdId != -1) && ((rareProdId == itemId) || Config.CRAFT_MASTERWORK) && (Rnd.get(100) < _recipeList.getRarity()))
{
if (Rnd.get(100) < _recipeList.getRarity())
itemId = rareProdId;
itemCount = _recipeList.getRareCount();
final int craftMastery = (int) _player.calcStat(Stats.CRAFT_MASTERY, 0, null, null);
if ((craftMastery > 0) && (Rnd.get(10) < craftMastery))
{
itemId = rareProdId;
itemCount = _recipeList.getRareCount();
final int craftMastery = (int) _player.calcStat(Stats.CRAFT_MASTERY, 0, null, null);
if ((craftMastery > 0) && (Rnd.get(10) < craftMastery))
{
itemCount <<= 1;
}
itemCount <<= 1;
}
}
@@ -698,9 +649,6 @@ public class RecipeController
sm = SystemMessage.getSystemMessage(SystemMessageId.C1_CREATED_S2_AFTER_RECEIVING_S3_ADENA);
sm.addString(_player.getName());
sm.addItemName(itemId);
sm.addLong(_price);
_target.sendPacket(sm);
}
else
{
@@ -714,10 +662,10 @@ public class RecipeController
sm = SystemMessage.getSystemMessage(SystemMessageId.C1_CREATED_S3_S2_S_AT_THE_PRICE_OF_S4_ADENA);
sm.addString(_player.getName());
sm.addInt(itemCount);
sm.addItemName(itemId);
sm.addLong(_price);
_target.sendPacket(sm);
}
sm.addLong(_price);
sm.addItemName(itemId);
_target.sendPacket(sm);
}
if (itemCount > 1)
@@ -725,14 +673,13 @@ public class RecipeController
sm = SystemMessage.getSystemMessage(SystemMessageId.YOU_HAVE_EARNED_S2_S1_S);
sm.addItemName(itemId);
sm.addLong(itemCount);
_target.sendPacket(sm);
}
else
{
sm = SystemMessage.getSystemMessage(SystemMessageId.YOU_HAVE_EARNED_S1);
sm.addItemName(itemId);
_target.sendPacket(sm);
}
_target.sendPacket(sm);
if (Config.ALT_GAME_CREATION)
{

View File

@@ -84,14 +84,7 @@ public class Shutdown extends Thread
{
_log.warning("IP: " + IP + " issued shutdown command. " + MODE_TEXT[_shutdownMode] + " in " + seconds + " seconds!");
if (restart)
{
_shutdownMode = GM_RESTART;
}
else
{
_shutdownMode = GM_SHUTDOWN;
}
_shutdownMode = restart ? GM_RESTART : GM_SHUTDOWN;
if (_shutdownMode > 0)
{
@@ -167,14 +160,7 @@ public class Shutdown extends Thread
seconds = 0;
}
_secondsShut = seconds;
if (restart)
{
_shutdownMode = GM_RESTART;
}
else
{
_shutdownMode = GM_SHUTDOWN;
}
_shutdownMode = restart ? GM_RESTART : GM_SHUTDOWN;
}
/**
@@ -319,14 +305,7 @@ public class Shutdown extends Thread
*/
public void startShutdown(L2PcInstance activeChar, int seconds, boolean restart)
{
if (restart)
{
_shutdownMode = GM_RESTART;
}
else
{
_shutdownMode = GM_SHUTDOWN;
}
_shutdownMode = restart ? GM_RESTART : GM_SHUTDOWN;
_log.warning("GM: " + activeChar.getName() + "(" + activeChar.getObjectId() + ") issued shutdown command. " + MODE_TEXT[_shutdownMode] + " in " + seconds + " seconds!");

View File

@@ -580,13 +580,9 @@ public abstract class AbstractAI implements Ctrl
}
sendPacket = false;
}
else if (_actor.isOnGeodataPath())
else if (_actor.isOnGeodataPath() && (GameTimeController.getInstance().getGameTicks() < (_moveToPawnTimeout + 10)))
{
// minimum time to calculate new route is 2 seconds
if (GameTimeController.getInstance().getGameTicks() < (_moveToPawnTimeout + 10))
{
return;
}
return;
}
}
@@ -678,18 +674,20 @@ public abstract class AbstractAI implements Ctrl
_clientMovingToPawnOffset = 0;
if (_clientMoving || (loc != null))
if (!_clientMoving && (loc == null))
{
_clientMoving = false;
// Send a Server->Client packet StopMove to the actor and all L2PcInstance in its _knownPlayers
_actor.broadcastPacket(new StopMove(_actor));
if (loc != null)
{
// Send a Server->Client packet StopRotation to the actor and all L2PcInstance in its _knownPlayers
_actor.broadcastPacket(new StopRotation(_actor.getObjectId(), loc.getHeading(), 0));
}
return;
}
_clientMoving = false;
// Send a Server->Client packet StopMove to the actor and all L2PcInstance in its _knownPlayers
_actor.broadcastPacket(new StopMove(_actor));
if (loc != null)
{
// Send a Server->Client packet StopRotation to the actor and all L2PcInstance in its _knownPlayers
_actor.broadcastPacket(new StopRotation(_actor.getObjectId(), loc.getHeading(), 0));
}
}
@@ -814,20 +812,17 @@ public abstract class AbstractAI implements Ctrl
*/
public void describeStateToPlayer(L2PcInstance player)
{
if (getActor().isVisibleFor(player))
if (getActor().isVisibleFor(player) && _clientMoving)
{
if (_clientMoving)
if ((_clientMovingToPawnOffset != 0) && (_followTarget != null))
{
if ((_clientMovingToPawnOffset != 0) && (_followTarget != null))
{
// Send a Server->Client packet MoveToPawn to the actor and all L2PcInstance in its _knownPlayers
player.sendPacket(new MoveToPawn(_actor, _followTarget, _clientMovingToPawnOffset));
}
else
{
// Send a Server->Client packet CharMoveToLocation to the actor and all L2PcInstance in its _knownPlayers
player.sendPacket(new MoveToLocation(_actor));
}
// Send a Server->Client packet MoveToPawn to the actor and all L2PcInstance in its _knownPlayers
player.sendPacket(new MoveToPawn(_actor, _followTarget, _clientMovingToPawnOffset));
}
else
{
// Send a Server->Client packet CharMoveToLocation to the actor and all L2PcInstance in its _knownPlayers
player.sendPacket(new MoveToLocation(_actor));
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -36,17 +36,19 @@ public class L2BoatAI extends L2VehicleAI
@Override
protected void moveTo(int x, int y, int z)
{
if (!_actor.isMovementDisabled())
if (_actor.isMovementDisabled())
{
if (!_clientMoving)
{
_actor.broadcastPacket(new VehicleStarted(getActor(), 1));
}
_clientMoving = true;
_actor.moveToLocation(x, y, z, 0);
_actor.broadcastPacket(new VehicleDeparture(getActor()));
return;
}
if (!_clientMoving)
{
_actor.broadcastPacket(new VehicleStarted(getActor(), 1));
}
_clientMoving = true;
_actor.moveToLocation(x, y, z, 0);
_actor.broadcastPacket(new VehicleDeparture(getActor()));
}
@Override

View File

@@ -186,31 +186,32 @@ public class L2CharacterAI extends AbstractAI
protected void onIntentionActive()
{
// Check if the Intention is not already Active
if (getIntention() != AI_INTENTION_ACTIVE)
if (getIntention() == AI_INTENTION_ACTIVE)
{
// Set the AI Intention to AI_INTENTION_ACTIVE
changeIntention(AI_INTENTION_ACTIVE, null, null);
// Init cast and attack target
setCastTarget(null);
setAttackTarget(null);
// Stop the actor movement server side AND client side by sending Server->Client packet StopMove/StopRotation (broadcast)
clientStopMoving(null);
// Stop the actor auto-attack client side by sending Server->Client packet AutoAttackStop (broadcast)
clientStopAutoAttack();
// Also enable random animations for this L2Character if allowed
// This is only for mobs - town npcs are handled in their constructor
if (_actor instanceof L2Attackable)
{
((L2Npc) _actor).startRandomAnimationTimer();
}
// Launch the Think Event
onEvtThink();
return;
}
changeIntention(AI_INTENTION_ACTIVE, null, null);
// Init cast and attack target
setCastTarget(null);
setAttackTarget(null);
// Stop the actor movement server side AND client side by sending Server->Client packet StopMove/StopRotation (broadcast)
clientStopMoving(null);
// Stop the actor auto-attack client side by sending Server->Client packet AutoAttackStop (broadcast)
clientStopAutoAttack();
// Also enable random animations for this L2Character if allowed
// This is only for mobs - town npcs are handled in their constructor
if (_actor instanceof L2Attackable)
{
((L2Npc) _actor).startRandomAnimationTimer();
}
// Launch the Think Event
onEvtThink();
}
/**
@@ -245,20 +246,7 @@ public class L2CharacterAI extends AbstractAI
@Override
protected void onIntentionAttack(L2Character target)
{
if (target == null)
{
clientActionFailed();
return;
}
if (getIntention() == AI_INTENTION_REST)
{
// Cancel action client side by sending Server->Client packet ActionFailed to the L2PcInstance actor
clientActionFailed();
return;
}
if (_actor.isAllSkillsDisabled() || _actor.isCastingNow() || _actor.isAfraid())
if ((target == null) || (getIntention() == AI_INTENTION_REST) || _actor.isAllSkillsDisabled() || _actor.isCastingNow() || _actor.isAfraid())
{
// Cancel action client side by sending Server->Client packet ActionFailed to the L2PcInstance actor
clientActionFailed();
@@ -356,14 +344,7 @@ public class L2CharacterAI extends AbstractAI
@Override
protected void onIntentionMoveTo(Location loc)
{
if (getIntention() == AI_INTENTION_REST)
{
// Cancel action client side by sending Server->Client packet ActionFailed to the L2PcInstance actor
clientActionFailed();
return;
}
if (_actor.isAllSkillsDisabled() || _actor.isCastingNow())
if ((getIntention() == AI_INTENTION_REST) || _actor.isAllSkillsDisabled() || _actor.isCastingNow())
{
// Cancel action client side by sending Server->Client packet ActionFailed to the L2PcInstance actor
clientActionFailed();
@@ -395,36 +376,7 @@ public class L2CharacterAI extends AbstractAI
@Override
protected void onIntentionFollow(L2Character target)
{
if (getIntention() == AI_INTENTION_REST)
{
// Cancel action client side by sending Server->Client packet ActionFailed to the L2PcInstance actor
clientActionFailed();
return;
}
if (_actor.isAllSkillsDisabled() || _actor.isCastingNow())
{
// Cancel action client side by sending Server->Client packet ActionFailed to the L2PcInstance actor
clientActionFailed();
return;
}
if (_actor.isMovementDisabled())
{
// Cancel action client side by sending Server->Client packet ActionFailed to the L2PcInstance actor
clientActionFailed();
return;
}
// Dead actors can`t follow
if (_actor.isDead())
{
clientActionFailed();
return;
}
// do not follow yourself
if (_actor == target)
if ((getIntention() == AI_INTENTION_REST) || _actor.isAllSkillsDisabled() || _actor.isCastingNow() || _actor.isMovementDisabled() || _actor.isDead() || (_actor == target))
{
clientActionFailed();
return;
@@ -452,14 +404,7 @@ public class L2CharacterAI extends AbstractAI
@Override
protected void onIntentionPickUp(L2Object object)
{
if (getIntention() == AI_INTENTION_REST)
{
// Cancel action client side by sending Server->Client packet ActionFailed to the L2PcInstance actor
clientActionFailed();
return;
}
if (_actor.isAllSkillsDisabled() || _actor.isCastingNow())
if ((getIntention() == AI_INTENTION_REST) || _actor.isAllSkillsDisabled() || _actor.isCastingNow())
{
// Cancel action client side by sending Server->Client packet ActionFailed to the L2PcInstance actor
clientActionFailed();
@@ -479,7 +424,7 @@ public class L2CharacterAI extends AbstractAI
// Set the AI pick up target
setTarget(object);
if ((object.getX() == 0) && (object.getY() == 0)) // TODO: Find the drop&spawn bug
if ((object.getX() == 0) && (object.getY() == 0))
{
_log.warning("Object in coords 0,0 - using a temporary fix");
object.setXYZ(getActor().getX(), getActor().getY(), getActor().getZ() + 5);
@@ -502,14 +447,7 @@ public class L2CharacterAI extends AbstractAI
@Override
protected void onIntentionInteract(L2Object object)
{
if (getIntention() == AI_INTENTION_REST)
{
// Cancel action client side by sending Server->Client packet ActionFailed to the L2PcInstance actor
clientActionFailed();
return;
}
if (_actor.isAllSkillsDisabled() || _actor.isCastingNow())
if ((getIntention() == AI_INTENTION_REST) || _actor.isAllSkillsDisabled() || _actor.isCastingNow())
{
// Cancel action client side by sending Server->Client packet ActionFailed to the L2PcInstance actor
clientActionFailed();
@@ -519,17 +457,19 @@ public class L2CharacterAI extends AbstractAI
// Stop the actor auto-attack client side by sending Server->Client packet AutoAttackStop (broadcast)
clientStopAutoAttack();
if (getIntention() != AI_INTENTION_INTERACT)
if (getIntention() == AI_INTENTION_INTERACT)
{
// Set the Intention of this AbstractAI to AI_INTENTION_INTERACT
changeIntention(AI_INTENTION_INTERACT, object, null);
// Set the AI interact target
setTarget(object);
// Move the actor to Pawn server side AND client side by sending Server->Client packet MoveToPawn (broadcast)
moveToPawn(object, 60);
return;
}
// Set the Intention of this AbstractAI to AI_INTENTION_INTERACT
changeIntention(AI_INTENTION_INTERACT, object, null);
// Set the AI interact target
setTarget(object);
// Move the actor to Pawn server side AND client side by sending Server->Client packet MoveToPawn (broadcast)
moveToPawn(object, 60);
}
/**
@@ -856,22 +796,24 @@ public class L2CharacterAI extends AbstractAI
}
// Check if the targeted object was the actor
if (_actor == object)
if (_actor != object)
{
// Cancel AI target
setTarget(null);
setAttackTarget(null);
setCastTarget(null);
// Stop an AI Follow Task
stopFollow();
// Stop the actor movement server side AND client side by sending Server->Client packet StopMove/StopRotation (broadcast)
clientStopMoving(null);
// Set the Intention of this AbstractAI to AI_INTENTION_IDLE
changeIntention(AI_INTENTION_IDLE, null, null);
return;
}
// Cancel AI target
setTarget(null);
setAttackTarget(null);
setCastTarget(null);
// Stop an AI Follow Task
stopFollow();
// Stop the actor movement server side AND client side by sending Server->Client packet StopMove/StopRotation (broadcast)
clientStopMoving(null);
// Set the Intention of this AbstractAI to AI_INTENTION_IDLE
changeIntention(AI_INTENTION_IDLE, null, null);
}
/**
@@ -969,16 +911,7 @@ public class L2CharacterAI extends AbstractAI
}
// If pathfinding enabled the creature will go to the destination or it will go to the nearest obstacle.
final Location destination;
if (Config.PATHFINDING > 0)
{
destination = GeoData.getInstance().moveCheck(_actor.getX(), _actor.getY(), _actor.getZ(), posX, posY, posZ, _actor.getInstanceId());
}
else
{
destination = new Location(posX, posY, posZ);
}
setIntention(CtrlIntention.AI_INTENTION_MOVE_TO, destination);
setIntention(CtrlIntention.AI_INTENTION_MOVE_TO, (Config.PATHFINDING > 0 ? GeoData.getInstance().moveCheck(_actor.getX(), _actor.getY(), _actor.getZ(), posX, posY, posZ, _actor.getInstanceId()) : new Location(posX, posY, posZ)));
}
protected boolean maybeMoveToPosition(ILocational worldPosition, int offset)
@@ -1122,14 +1055,11 @@ public class L2CharacterAI extends AbstractAI
}
// while flying there is no move to cast
if ((_actor.getAI().getIntention() == CtrlIntention.AI_INTENTION_CAST) && (_actor instanceof L2PcInstance) && _actor.isTransformed())
if ((_actor.getAI().getIntention() == CtrlIntention.AI_INTENTION_CAST) && (_actor instanceof L2PcInstance) && _actor.isTransformed() && !_actor.getTransformation().isCombat())
{
if (!_actor.getTransformation().isCombat())
{
_actor.sendPacket(SystemMessageId.THE_DISTANCE_IS_TOO_FAR_AND_SO_THE_CASTING_HAS_BEEN_STOPPED);
_actor.sendPacket(ActionFailed.STATIC_PACKET);
return true;
}
_actor.sendPacket(SystemMessageId.THE_DISTANCE_IS_TOO_FAR_AND_SO_THE_CASTING_HAS_BEEN_STOPPED);
_actor.sendPacket(ActionFailed.STATIC_PACKET);
return true;
}
// If not running, set the L2Character movement type to run and send Server->Client packet ChangeMoveType to all others L2PcInstance
@@ -1220,29 +1150,17 @@ public class L2CharacterAI extends AbstractAI
*/
protected boolean checkTargetLost(L2Object target)
{
// check if player is fakedeath
if (target instanceof L2PcInstance)
if ((target instanceof L2PcInstance) && ((L2PcInstance) target).isFakeDeath())
{
final L2PcInstance target2 = (L2PcInstance) target; // convert object to chara
if (target2.isFakeDeath())
{
target2.stopFakeDeath(true);
return false;
}
((L2PcInstance) target).stopFakeDeath(true);
return false;
}
if (target == null)
if ((target != null) && ((_actor == null) || (_skill == null) || !_skill.isBad() || (_skill.getAffectRange() <= 0) || GeoData.getInstance().canSeeTarget(_actor, target)))
{
// Set the Intention of this AbstractAI to AI_INTENTION_ACTIVE
setIntention(AI_INTENTION_ACTIVE);
return true;
return false;
}
if ((_actor != null) && (_skill != null) && _skill.isBad() && (_skill.getAffectRange() > 0) && !GeoData.getInstance().canSeeTarget(_actor, target))
{
setIntention(AI_INTENTION_ACTIVE);
return true;
}
return false;
setIntention(AI_INTENTION_ACTIVE);
return true;
}
protected class SelfAnalysis
@@ -1498,22 +1416,8 @@ public class L2CharacterAI extends AbstractAI
isFighter = true;
}
}
if (target.getRunSpeed() < (_actor.getRunSpeed() - 3))
{
isSlower = true;
}
else
{
isSlower = false;
}
if ((target.getMDef(null, null) * 1.2) > _actor.getMAtk(null, null))
{
isMagicResistant = true;
}
else
{
isMagicResistant = false;
}
isSlower = target.getRunSpeed() < (_actor.getRunSpeed() - 3);
isMagicResistant = (target.getMDef(null, null) * 1.2) > _actor.getMAtk(null, null);
if (target.getBuffCount() < 4)
{
isCanceled = true;
@@ -1545,20 +1449,10 @@ public class L2CharacterAI extends AbstractAI
boolean cancast = true;
for (L2Character target : _actor.getKnownList().getKnownCharactersInRadius(sk.getAffectRange()))
{
if (!GeoData.getInstance().canSeeTarget(_actor, target))
if (!GeoData.getInstance().canSeeTarget(_actor, target) || ((target instanceof L2Attackable) && !((L2Npc) _actor).isChaos()))
{
continue;
}
if (target instanceof L2Attackable)
{
final L2Npc actors = ((L2Npc) _actor);
if (!actors.isChaos())
{
continue;
}
}
if (target.isAffectedBySkill(sk.getId()))
{
cancast = false;
@@ -1574,20 +1468,10 @@ public class L2CharacterAI extends AbstractAI
boolean cancast = true;
for (L2Character target : getAttackTarget().getKnownList().getKnownCharactersInRadius(sk.getAffectRange()))
{
if (!GeoData.getInstance().canSeeTarget(_actor, target) || (target == null))
if (!GeoData.getInstance().canSeeTarget(_actor, target) || (target == null) || ((target instanceof L2Attackable) && !((L2Npc) _actor).isChaos()))
{
continue;
}
if (target instanceof L2Attackable)
{
final L2Npc actors = ((L2Npc) _actor);
if (!actors.isChaos())
{
continue;
}
}
if (!target.getEffectList().isEmpty())
{
cancast = true;
@@ -1606,20 +1490,10 @@ public class L2CharacterAI extends AbstractAI
boolean cancast = false;
for (L2Character target : _actor.getKnownList().getKnownCharactersInRadius(sk.getAffectRange()))
{
if (!GeoData.getInstance().canSeeTarget(_actor, target))
if (!GeoData.getInstance().canSeeTarget(_actor, target) || ((target instanceof L2Attackable) && !((L2Npc) _actor).isChaos()))
{
continue;
}
if (target instanceof L2Attackable)
{
final L2Npc actors = ((L2Npc) _actor);
if (!actors.isChaos())
{
continue;
}
}
if (!target.getEffectList().isEmpty())
{
cancast = true;
@@ -1635,20 +1509,10 @@ public class L2CharacterAI extends AbstractAI
boolean cancast = true;
for (L2Character target : getAttackTarget().getKnownList().getKnownCharactersInRadius(sk.getAffectRange()))
{
if (!GeoData.getInstance().canSeeTarget(_actor, target))
if (!GeoData.getInstance().canSeeTarget(_actor, target) || ((target instanceof L2Attackable) && !((L2Npc) _actor).isChaos()))
{
continue;
}
if (target instanceof L2Attackable)
{
final L2Npc actors = ((L2Npc) _actor);
if (!actors.isChaos())
{
continue;
}
}
if (target.isAffectedBySkill(sk.getId()))
{
cancast = false;
@@ -1675,9 +1539,7 @@ public class L2CharacterAI extends AbstractAI
{
continue;
}
final L2Npc targets = ((L2Npc) target);
final L2Npc actors = ((L2Npc) _actor);
if (targets.isInMyClan(actors))
if (((L2Npc) target).isInMyClan(((L2Npc) _actor)))
{
count++;
if (target.isAffectedBySkill(sk.getId()))

View File

@@ -19,7 +19,6 @@ package com.l2jmobius.gameserver.ai;
import static com.l2jmobius.gameserver.ai.CtrlIntention.AI_INTENTION_ACTIVE;
import static com.l2jmobius.gameserver.ai.CtrlIntention.AI_INTENTION_ATTACK;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
@@ -67,16 +66,9 @@ public final class L2ControllableMobAI extends L2AttackableAI
protected void thinkFollow()
{
final L2Attackable me = (L2Attackable) _actor;
if (!Util.checkIfInRange(MobGroupTable.FOLLOW_RANGE, me, getForcedTarget(), true))
if (!Util.checkIfInRange(MobGroupTable.FOLLOW_RANGE, _actor, getForcedTarget(), true))
{
final int signX = (Rnd.nextInt(2) == 0) ? -1 : 1;
final int signY = (Rnd.nextInt(2) == 0) ? -1 : 1;
final int randX = Rnd.nextInt(MobGroupTable.FOLLOW_RANGE);
final int randY = Rnd.nextInt(MobGroupTable.FOLLOW_RANGE);
moveTo(getForcedTarget().getX() + (signX * randX), getForcedTarget().getY() + (signY * randY), getForcedTarget().getZ());
moveTo(getForcedTarget().getX() + (((Rnd.nextInt(2) == 0) ? -1 : 1) * Rnd.nextInt(MobGroupTable.FOLLOW_RANGE)), getForcedTarget().getY() + (((Rnd.nextInt(2) == 0) ? -1 : 1) * Rnd.nextInt(MobGroupTable.FOLLOW_RANGE)), getForcedTarget().getZ());
}
}
@@ -159,29 +151,29 @@ public final class L2ControllableMobAI extends L2AttackableAI
npc.setTarget(getAttackTarget());
if (!_actor.isMuted())
if (_actor.isMuted())
{
int max_range = 0;
// check distant skills
for (Skill sk : _actor.getAllSkills())
{
if (Util.checkIfInRange(sk.getCastRange(), _actor, getAttackTarget(), true) && !_actor.isSkillDisabled(sk) && (_actor.getCurrentMp() > _actor.getStat().getMpConsume(sk)))
{
_actor.doCast(sk);
return;
}
max_range = Math.max(max_range, sk.getCastRange());
}
if (!isNotMoving())
{
moveToPawn(getAttackTarget(), max_range);
}
return;
}
int max_range = 0;
// check distant skills
for (Skill sk : _actor.getAllSkills())
{
if (Util.checkIfInRange(sk.getCastRange(), _actor, getAttackTarget(), true) && !_actor.isSkillDisabled(sk) && (_actor.getCurrentMp() > _actor.getStat().getMpConsume(sk)))
{
_actor.doCast(sk);
return;
}
max_range = Math.max(max_range, sk.getCastRange());
}
if (!isNotMoving())
{
moveToPawn(getAttackTarget(), max_range);
}
}
protected void thinkAttackGroup()
@@ -284,10 +276,8 @@ public final class L2ControllableMobAI extends L2AttackableAI
if (getAttackTarget() != null)
{
// stop hating
final L2Attackable npc = (L2Attackable) _actor;
npc.stopHating(getAttackTarget());
((L2Attackable) _actor).stopHating(getAttackTarget());
}
setIntention(AI_INTENTION_ACTIVE);
}
else
@@ -295,21 +285,17 @@ public final class L2ControllableMobAI extends L2AttackableAI
// notify aggression
if (((L2Npc) _actor).getTemplate().getClans() != null)
{
final Collection<L2Object> objs = _actor.getKnownList().getKnownObjects().values();
for (L2Object obj : objs)
for (L2Object obj : _actor.getKnownList().getKnownObjects().values())
{
if (!(obj instanceof L2Npc))
{
continue;
}
final L2Npc npc = (L2Npc) obj;
if (!npc.isInMyClan((L2Npc) _actor))
{
continue;
}
if (_actor.isInsideRadius(npc, npc.getTemplate().getClanHelpRange(), false, true) && (Math.abs(getAttackTarget().getZ() - npc.getZ()) < 200))
{
npc.getAI().notifyEvent(CtrlEvent.EVT_AGGRESSION, getAttackTarget(), 1);
@@ -343,16 +329,7 @@ public final class L2ControllableMobAI extends L2AttackableAI
}
// Force mobs to attack anybody if confused.
L2Character hated;
if (_actor.isConfused())
{
hated = findNextRndTarget();
}
else
{
hated = getAttackTarget();
}
final L2Character hated = _actor.isConfused() ? findNextRndTarget() : getAttackTarget();
if (hated == null)
{
@@ -387,22 +364,15 @@ public final class L2ControllableMobAI extends L2AttackableAI
protected void thinkActive()
{
setAttackTarget(findNextRndTarget());
L2Character hated;
if (_actor.isConfused())
final L2Character hated = _actor.isConfused() ? findNextRndTarget() : getAttackTarget();
if (hated == null)
{
hated = findNextRndTarget();
}
else
{
hated = getAttackTarget();
return;
}
if (hated != null)
{
_actor.setRunning();
setIntention(CtrlIntention.AI_INTENTION_ATTACK, hated);
}
_actor.setRunning();
setIntention(CtrlIntention.AI_INTENTION_ATTACK, hated);
}
private boolean checkAutoAttackCondition(L2Character target)
@@ -436,14 +406,10 @@ public final class L2ControllableMobAI extends L2AttackableAI
return false;
}
// Check if the target is a L2Playable
if (target.isPlayable())
// Check if the target isn't in silent move mode
if (target.isPlayable() && ((L2Playable) target).isSilentMovingAffected())
{
// Check if the target isn't in silent move mode
if (((L2Playable) target).isSilentMovingAffected())
{
return false;
}
return false;
}
return me.isAggressive();
}
@@ -451,11 +417,7 @@ public final class L2ControllableMobAI extends L2AttackableAI
private L2Character findNextRndTarget()
{
final List<L2Character> potentialTarget = _actor.getKnownList().getKnownCharactersInRadius(getActiveChar().getAggroRange()).stream().filter(this::checkAutoAttackCondition).collect(Collectors.toList());
if (potentialTarget.isEmpty())
{
return null;
}
return potentialTarget.get(Rnd.nextInt(potentialTarget.size()));
return potentialTarget.isEmpty() ? null : potentialTarget.get(Rnd.nextInt(potentialTarget.size()));
}
private L2ControllableMobInstance findNextGroupTarget()

View File

@@ -173,5 +173,4 @@ public class L2DoorAI extends L2CharacterAI
}
}
}
}

View File

@@ -140,19 +140,9 @@ public class L2FortSiegeGuardAI extends L2CharacterAI implements Runnable
return false;
}
}
// Check if the target isn't invulnerable
if ((target != null) && target.isInvul())
if ((target != null) && target.isInvul() && ((target.isPlayer() && target.isGM()) || (target.isSummon() && ((L2Summon) target).getOwner().isGM())))
{
// However EffectInvincible requires to check GMs specially
if (target.isPlayer() && target.isGM())
{
return false;
}
if (target.isSummon() && ((L2Summon) target).getOwner().isGM())
{
return false;
}
return false;
}
// Get the owner if the target is a summon
@@ -164,18 +154,7 @@ public class L2FortSiegeGuardAI extends L2CharacterAI implements Runnable
target = owner;
}
}
// Check if the target is a L2PcInstance
if (target instanceof L2Playable)
{
// Check if the target isn't in silent move mode AND too far (>100)
if (((L2Playable) target).isSilentMovingAffected() && !_actor.isInsideRadius(target, 250, false, false))
{
return false;
}
}
// Los Check Here
return (_actor.isAutoAttackable(target) && GeoData.getInstance().canSeeTarget(_actor, target));
return (!(target instanceof L2Playable) || !((L2Playable) target).isSilentMovingAffected() || _actor.isInsideRadius(target, 250, false, false)) && _actor.isAutoAttackable(target) && GeoData.getInstance().canSeeTarget(_actor, target);
}
/**
@@ -198,17 +177,7 @@ public class L2FortSiegeGuardAI extends L2CharacterAI implements Runnable
// Check if actor is not dead
if (!_actor.isAlikeDead())
{
final L2Attackable npc = (L2Attackable) _actor;
// If its _knownPlayer isn't empty set the Intention to AI_INTENTION_ACTIVE
if (!npc.getKnownList().getKnownPlayers().isEmpty())
{
intention = AI_INTENTION_ACTIVE;
}
else
{
intention = AI_INTENTION_IDLE;
}
intention = ((L2Attackable) _actor).getKnownList().getKnownPlayers().isEmpty() ? AI_INTENTION_IDLE : AI_INTENTION_ACTIVE;
}
if (intention == AI_INTENTION_IDLE)
@@ -291,30 +260,14 @@ public class L2FortSiegeGuardAI extends L2CharacterAI implements Runnable
{
continue;
}
if (autoAttackCondition(target)) // check aggression
if (autoAttackCondition(target) && (npc.getHating(target) == 0)) // check aggression
{
// Get the hate level of the L2Attackable against this L2Character target contained in _aggroList
final int hating = npc.getHating(target);
// Add the attacker to the L2Attackable _aggroList with 0 damage and 1 hate
if (hating == 0)
{
npc.addDamageHate(target, 0, 1);
}
npc.addDamageHate(target, 0, 1);
}
}
// Chose a target from its aggroList
L2Character hated;
if (_actor.isConfused())
{
hated = getAttackTarget(); // Force mobs to attack anybody if confused
}
else
{
hated = npc.getMostHated();
// _mostHatedAnalysis.Update(hated);
}
final L2Character hated = _actor.isConfused() ? getAttackTarget() : npc.getMostHated();
// Order to the L2Attackable to attack the target
if (hated != null)
@@ -340,14 +293,7 @@ public class L2FortSiegeGuardAI extends L2CharacterAI implements Runnable
// Order to the L2SiegeGuardInstance to return to its home location because there's no target to attack
if (_actor.getWalkSpeed() >= 0)
{
if (_actor instanceof L2DefenderInstance)
{
((L2DefenderInstance) _actor).returnHome();
}
else
{
((L2FortCommanderInstance) _actor).returnHome();
}
(_actor instanceof L2DefenderInstance ? (L2DefenderInstance) _actor : (L2FortCommanderInstance) _actor).returnHome();
}
}
@@ -369,17 +315,10 @@ public class L2FortSiegeGuardAI extends L2CharacterAI implements Runnable
_log.warning(getClass().getSimpleName() + ": thinkAttack(); timeout=" + (_attackTimeout - GameTimeController.getInstance().getGameTicks()));
}
if (_attackTimeout < GameTimeController.getInstance().getGameTicks())
if ((_attackTimeout < GameTimeController.getInstance().getGameTicks()) && _actor.isRunning())
{
// Check if the actor is running
if (_actor.isRunning())
{
// Set the actor movement type to walk and send Server->Client packet ChangeMoveType to all others L2PcInstance
_actor.setWalking();
// Calculate a new attack timeout
_attackTimeout = MAX_ATTACK_TIMEOUT + GameTimeController.getInstance().getGameTicks();
}
_actor.setWalking();
_attackTimeout = MAX_ATTACK_TIMEOUT + GameTimeController.getInstance().getGameTicks();
}
final L2Character attackTarget = getAttackTarget();
@@ -389,8 +328,7 @@ public class L2FortSiegeGuardAI extends L2CharacterAI implements Runnable
// Stop hating this target after the attack timeout or if target is dead
if (attackTarget != null)
{
final L2Attackable npc = (L2Attackable) _actor;
npc.stopHating(attackTarget);
((L2Attackable) _actor).stopHating(attackTarget);
}
// Cancel target and timeout
@@ -412,16 +350,11 @@ public class L2FortSiegeGuardAI extends L2CharacterAI implements Runnable
{
final L2Character target = getAttackTarget();
// Call all L2Object of its Faction inside the Faction Range
if ((((L2Npc) _actor).getTemplate().getClans() == null) || (target == null))
if ((((L2Npc) _actor).getTemplate().getClans() == null) || (target == null) || target.isInvul())
{
return;
}
if (target.isInvul())
{
return; // speeding it up for siege guards
}
// Go through all L2Character that belong to its faction
// for (L2Character cha : _actor.getKnownList().getKnownCharactersInRadius(((L2NpcInstance) _actor).getFactionRange()+_actor.getTemplate().collisionRadius))
for (L2Character cha : _actor.getKnownList().getKnownCharactersInRadius(1000))
@@ -430,46 +363,32 @@ public class L2FortSiegeGuardAI extends L2CharacterAI implements Runnable
{
continue;
}
if (!(cha instanceof L2Npc))
{
if (_selfAnalysis.hasHealOrResurrect && (cha instanceof L2PcInstance) && ((L2Npc) _actor).getFort().getSiege().checkIsDefender(((L2PcInstance) cha).getClan()))
if (_selfAnalysis.hasHealOrResurrect && (cha instanceof L2PcInstance) && ((L2Npc) _actor).getFort().getSiege().checkIsDefender(((L2PcInstance) cha).getClan())//
&& !_actor.isAttackingDisabled() && (cha.getCurrentHp() < (cha.getMaxHp() * 0.6)) && (_actor.getCurrentHp() > (_actor.getMaxHp() / 2)) && (_actor.getCurrentMp() > (_actor.getMaxMp() / 2)) && cha.isInCombat())
{
// heal friends
if (!_actor.isAttackingDisabled() && (cha.getCurrentHp() < (cha.getMaxHp() * 0.6)) && (_actor.getCurrentHp() > (_actor.getMaxHp() / 2)) && (_actor.getCurrentMp() > (_actor.getMaxMp() / 2)) && cha.isInCombat())
for (Skill sk : _selfAnalysis.healSkills)
{
for (Skill sk : _selfAnalysis.healSkills)
if ((_actor.getCurrentMp() < sk.getMpConsume()) || _actor.isSkillDisabled(sk) || !Util.checkIfInRange(sk.getCastRange(), _actor, cha, true))
{
if (_actor.getCurrentMp() < sk.getMpConsume())
{
continue;
}
if (_actor.isSkillDisabled(sk))
{
continue;
}
if (!Util.checkIfInRange(sk.getCastRange(), _actor, cha, true))
{
continue;
}
final int chance = 5;
if (chance >= Rnd.get(100))
{
continue;
}
if (!GeoData.getInstance().canSeeTarget(_actor, cha))
{
break;
}
final L2Object OldTarget = _actor.getTarget();
_actor.setTarget(cha);
clientStopMoving(null);
_actor.doCast(sk);
_actor.setTarget(OldTarget);
return;
continue;
}
final int chance = 5;
if (chance >= Rnd.get(100))
{
continue;
}
if (!GeoData.getInstance().canSeeTarget(_actor, cha))
{
break;
}
final L2Object OldTarget = _actor.getTarget();
_actor.setTarget(cha);
clientStopMoving(null);
_actor.doCast(sk);
_actor.setTarget(OldTarget);
return;
}
}
continue;
@@ -484,11 +403,7 @@ public class L2FortSiegeGuardAI extends L2CharacterAI implements Runnable
if (npc.getAI() != null) // TODO: possibly check not needed
{
if (!npc.isDead() && (Math.abs(target.getZ() - npc.getZ()) < 600)
// && _actor.getAttackByList().contains(getAttackTarget())
&& ((npc.getAI()._intention == CtrlIntention.AI_INTENTION_IDLE) || (npc.getAI()._intention == CtrlIntention.AI_INTENTION_ACTIVE))
// limiting aggro for siege guards
&& target.isInsideRadius(npc, 1500, true, false) && GeoData.getInstance().canSeeTarget(npc, target))
if (!npc.isDead() && (Math.abs(target.getZ() - npc.getZ()) < 600) && ((npc.getAI()._intention == CtrlIntention.AI_INTENTION_IDLE) || (npc.getAI()._intention == CtrlIntention.AI_INTENTION_ACTIVE)) && target.isInsideRadius(npc, 1500, true, false) && GeoData.getInstance().canSeeTarget(npc, target))
{
// Notify the L2Object AI with EVT_AGGRESSION
npc.getAI().notifyEvent(CtrlEvent.EVT_AGGRESSION, getAttackTarget(), 1);
@@ -499,19 +414,10 @@ public class L2FortSiegeGuardAI extends L2CharacterAI implements Runnable
{
for (Skill sk : _selfAnalysis.healSkills)
{
if (_actor.getCurrentMp() < sk.getMpConsume())
if ((_actor.getCurrentMp() < sk.getMpConsume()) || _actor.isSkillDisabled(sk) || !Util.checkIfInRange(sk.getCastRange(), _actor, npc, true))
{
continue;
}
if (_actor.isSkillDisabled(sk))
{
continue;
}
if (!Util.checkIfInRange(sk.getCastRange(), _actor, npc, true))
{
continue;
}
final int chance = 4;
if (chance >= Rnd.get(100))
{
@@ -521,7 +427,6 @@ public class L2FortSiegeGuardAI extends L2CharacterAI implements Runnable
{
break;
}
final L2Object OldTarget = _actor.getTarget();
_actor.setTarget(npc);
clientStopMoving(null);
@@ -540,17 +445,8 @@ public class L2FortSiegeGuardAI extends L2CharacterAI implements Runnable
Collection<Skill> skills = null;
double dist_2 = 0;
int range = 0;
L2DefenderInstance sGuard;
if (_actor instanceof L2FortCommanderInstance)
{
sGuard = (L2FortCommanderInstance) _actor;
}
else
{
sGuard = (L2DefenderInstance) _actor;
}
final L2DefenderInstance sGuard = _actor instanceof L2FortCommanderInstance ? (L2FortCommanderInstance) _actor : (L2DefenderInstance) _actor;
L2Character attackTarget = getAttackTarget();
try
{
_actor.setTarget(attackTarget);
@@ -564,7 +460,6 @@ public class L2FortSiegeGuardAI extends L2CharacterAI implements Runnable
}
catch (NullPointerException e)
{
// _log.warning("AttackableAI: Attack target is NULL.");
_actor.setTarget(null);
setIntention(AI_INTENTION_IDLE, null, null);
return;
@@ -580,16 +475,6 @@ public class L2FortSiegeGuardAI extends L2CharacterAI implements Runnable
return;
}
if (!GeoData.getInstance().canSeeTarget(_actor, attackTarget))
{
// Siege guards differ from normal mobs currently:
// If target cannot seen, don't attack any more
sGuard.stopHating(attackTarget);
_actor.setTarget(null);
setIntention(AI_INTENTION_IDLE, null, null);
return;
}
// Check if the actor isn't muted and if it is far from target
if (!_actor.isMuted() && (dist_2 > (range * range)))
{
@@ -645,8 +530,7 @@ public class L2FortSiegeGuardAI extends L2CharacterAI implements Runnable
final double homeY = attackTarget.getY() - sGuard.getSpawn().getY();
// Check if the L2SiegeGuardInstance isn't too far from it's home location
if ((((dx * dx) + (dy * dy)) > 10000) && (((homeX * homeX) + (homeY * homeY)) > 3240000) // 1800 * 1800
&& (_actor.getKnownList().knowsObject(attackTarget)))
if ((((dx * dx) + (dy * dy)) > 10000) && (((homeX * homeX) + (homeY * homeY)) > 3240000) && (_actor.getKnownList().knowsObject(attackTarget)))
{
// Cancel the target
_actor.getKnownList().removeKnownObject(attackTarget);
@@ -658,7 +542,7 @@ public class L2FortSiegeGuardAI extends L2CharacterAI implements Runnable
{
// Temporary hack for preventing guards jumping off towers,
// before replacing this with effective geodata checks and AI modification
if ((dz * dz) < (170 * 170)) // normally 130 if guard z coordinates correct
if ((dz * dz) < (170 * 170))
{
if (_selfAnalysis.isMage)
{
@@ -668,112 +552,87 @@ public class L2FortSiegeGuardAI extends L2CharacterAI implements Runnable
{
return;
}
if (attackTarget.isMoving())
{
moveToPawn(attackTarget, range - 70);
}
else
{
moveToPawn(attackTarget, range);
}
moveToPawn(attackTarget, attackTarget.isMoving() ? range - 70 : range);
}
}
}
return;
}
// Else, if the actor is muted and far from target, just "move to pawn"
else if (_actor.isMuted() && (dist_2 > (range * range)))
else
{
// Temporary hack for preventing guards jumping off towers,
// before replacing this with effective geodata checks and AI modification
final double dz = _actor.getZ() - attackTarget.getZ();
if ((dz * dz) < (170 * 170)) // normally 130 if guard z coordinates correct
if (_actor.isMuted() && (dist_2 > (range * range)))
{
if (_selfAnalysis.isMage)
// Temporary hack for preventing guards jumping off towers,
// before replacing this with effective geodata checks and AI modification
final double dz = _actor.getZ() - attackTarget.getZ();
if ((dz * dz) < (170 * 170)) // normally 130 if guard z coordinates correct
{
range = _selfAnalysis.maxCastRange - 50;
}
if (_actor.getWalkSpeed() <= 0)
{
return;
}
if (attackTarget.isMoving())
{
moveToPawn(attackTarget, range - 70);
}
else
{
moveToPawn(attackTarget, range);
}
}
return;
}
// Else, if this is close enough to attack
else if (dist_2 <= (range * range))
{
// Force mobs to attack anybody if confused
L2Character hated = null;
if (_actor.isConfused())
{
hated = attackTarget;
}
else
{
hated = ((L2Attackable) _actor).getMostHated();
}
if (hated == null)
{
setIntention(AI_INTENTION_ACTIVE, null, null);
return;
}
if (hated != attackTarget)
{
attackTarget = hated;
}
_attackTimeout = MAX_ATTACK_TIMEOUT + GameTimeController.getInstance().getGameTicks();
// check for close combat skills && heal/buff skills
if (!_actor.isMuted() && (Rnd.nextInt(100) <= 5))
{
for (Skill sk : skills)
{
final int castRange = sk.getCastRange();
if (((castRange * castRange) >= dist_2) && !sk.isPassive() && (_actor.getCurrentMp() >= _actor.getStat().getMpConsume(sk)) && !_actor.isSkillDisabled(sk))
if (_selfAnalysis.isMage)
{
range = _selfAnalysis.maxCastRange - 50;
}
if (_actor.getWalkSpeed() <= 0)
{
final L2Object OldTarget = _actor.getTarget();
if ((sk.isContinuous() && !sk.isDebuff()) || (sk.hasEffectType(L2EffectType.HEAL)))
{
boolean useSkillSelf = true;
if ((sk.hasEffectType(L2EffectType.HEAL)) && (_actor.getCurrentHp() > (int) (_actor.getMaxHp() / 1.5)))
{
useSkillSelf = false;
break;
}
if ((sk.isContinuous() && !sk.isDebuff()) && _actor.isAffectedBySkill(sk.getId()))
{
useSkillSelf = false;
}
if (useSkillSelf)
{
_actor.setTarget(_actor);
}
}
clientStopMoving(null);
_actor.doCast(sk);
_actor.setTarget(OldTarget);
return;
}
moveToPawn(attackTarget, attackTarget.isMoving() ? range - 70 : range);
}
return;
}
if (dist_2 <= (range * range))
{
final L2Character hated = _actor.isConfused() ? attackTarget : ((L2Attackable) _actor).getMostHated();
if (hated == null)
{
setIntention(AI_INTENTION_ACTIVE, null, null);
return;
}
if (hated != attackTarget)
{
attackTarget = hated;
}
_attackTimeout = MAX_ATTACK_TIMEOUT + GameTimeController.getInstance().getGameTicks();
// check for close combat skills && heal/buff skills
if (!_actor.isMuted() && (Rnd.nextInt(100) <= 5))
{
for (Skill sk : skills)
{
final int castRange = sk.getCastRange();
if (((castRange * castRange) >= dist_2) && !sk.isPassive() && (_actor.getCurrentMp() >= _actor.getStat().getMpConsume(sk)) && !_actor.isSkillDisabled(sk))
{
final L2Object OldTarget = _actor.getTarget();
if ((sk.isContinuous() && !sk.isDebuff()) || (sk.hasEffectType(L2EffectType.HEAL)))
{
boolean useSkillSelf = true;
if ((sk.hasEffectType(L2EffectType.HEAL)) && (_actor.getCurrentHp() > (int) (_actor.getMaxHp() / 1.5)))
{
useSkillSelf = false;
break;
}
if ((sk.isContinuous() && !sk.isDebuff()) && _actor.isAffectedBySkill(sk.getId()))
{
useSkillSelf = false;
}
if (useSkillSelf)
{
_actor.setTarget(_actor);
}
}
clientStopMoving(null);
_actor.doCast(sk);
_actor.setTarget(OldTarget);
return;
}
}
}
// Finally, do the physical attack itself
_actor.doAttack(attackTarget);
}
// Finally, do the physical attack itself
_actor.doAttack(attackTarget);
}
}
@@ -900,15 +759,7 @@ public class L2FortSiegeGuardAI extends L2CharacterAI implements Runnable
_actor.setRunning();
}
L2DefenderInstance sGuard;
if (_actor instanceof L2FortCommanderInstance)
{
sGuard = (L2FortCommanderInstance) _actor;
}
else
{
sGuard = (L2DefenderInstance) _actor;
}
final L2DefenderInstance sGuard = _actor instanceof L2FortCommanderInstance ? (L2FortCommanderInstance) _actor : (L2DefenderInstance) _actor;
final double homeX = target.getX() - sGuard.getSpawn().getX();
final double homeY = target.getY() - sGuard.getSpawn().getY();

View File

@@ -116,5 +116,4 @@ public abstract class L2PlayableAI extends L2CharacterAI
}
super.onIntentionCast(skill, target);
}
}

View File

@@ -131,13 +131,11 @@ public class L2PlayerAI extends L2PlayableAI
if (getIntention() == AI_INTENTION_CAST)
{
// run interrupted or next intention
final IntentionCommand nextIntention = _nextIntention;
if (nextIntention != null)
if (_nextIntention != null)
{
if (nextIntention._crtlIntention != AI_INTENTION_CAST) // previous state shouldn't be casting
if (_nextIntention._crtlIntention != AI_INTENTION_CAST)
{
setIntention(nextIntention._crtlIntention, nextIntention._arg0, nextIntention._arg1);
setIntention(_nextIntention._crtlIntention, _nextIntention._arg0, _nextIntention._arg1);
}
else
{
@@ -155,16 +153,17 @@ public class L2PlayerAI extends L2PlayableAI
@Override
protected void onIntentionRest()
{
if (getIntention() != AI_INTENTION_REST)
if (getIntention() == AI_INTENTION_REST)
{
changeIntention(AI_INTENTION_REST, null, null);
setTarget(null);
if (getAttackTarget() != null)
{
setAttackTarget(null);
}
clientStopMoving(null);
return;
}
changeIntention(AI_INTENTION_REST, null, null);
setTarget(null);
if (getAttackTarget() != null)
{
setAttackTarget(null);
}
clientStopMoving(null);
}
@Override
@@ -293,11 +292,7 @@ public class L2PlayerAI extends L2PlayableAI
return;
}
final L2Object target = getTarget();
if (checkTargetLost(target))
{
return;
}
if (maybeMoveToPawn(target, 36))
if (checkTargetLost(target) || maybeMoveToPawn(target, 36))
{
return;
}
@@ -312,11 +307,7 @@ public class L2PlayerAI extends L2PlayableAI
return;
}
final L2Object target = getTarget();
if (checkTargetLost(target))
{
return;
}
if (maybeMoveToPawn(target, 36))
if (checkTargetLost(target) || maybeMoveToPawn(target, 36))
{
return;
}

View File

@@ -32,12 +32,13 @@ public class L2ShuttleAI extends L2VehicleAI
@Override
public void moveTo(int x, int y, int z)
{
if (!_actor.isMovementDisabled())
if (_actor.isMovementDisabled())
{
_clientMoving = true;
_actor.moveToLocation(x, y, z, 0);
_actor.broadcastPacket(new ExShuttleMove(getActor(), x, y, z));
return;
}
_clientMoving = true;
_actor.moveToLocation(x, y, z, 0);
_actor.broadcastPacket(new ExShuttleMove(getActor(), x, y, z));
}
@Override

View File

@@ -130,17 +130,9 @@ public class L2SiegeGuardAI extends L2CharacterAI implements Runnable
}
// Check if the target isn't invulnerable
if (target.isInvul())
if (target.isInvul() && ((target.isPlayer() && target.isGM()) || (target.isSummon() && ((L2Summon) target).getOwner().isGM())))
{
// However EffectInvincible requires to check GMs specially
if (target.isPlayer() && target.isGM())
{
return false;
}
if (target.isSummon() && ((L2Summon) target).getOwner().isGM())
{
return false;
}
return false;
}
// Get the owner if the target is a summon
@@ -153,15 +145,12 @@ public class L2SiegeGuardAI extends L2CharacterAI implements Runnable
}
}
// Check if the target is a L2PcInstance
if (target instanceof L2Playable)
// Check if the target isn't in silent move mode AND too far (>100)
if ((target instanceof L2Playable) && ((L2Playable) target).isSilentMovingAffected() && !_actor.isInsideRadius(target, 250, false, false))
{
// Check if the target isn't in silent move mode AND too far (>100)
if (((L2Playable) target).isSilentMovingAffected() && !_actor.isInsideRadius(target, 250, false, false))
{
return false;
}
return false;
}
// Los Check Here
return (_actor.isAutoAttackable(target) && GeoData.getInstance().canSeeTarget(_actor, target));
}
@@ -186,17 +175,7 @@ public class L2SiegeGuardAI extends L2CharacterAI implements Runnable
// Check if actor is not dead
if (!_actor.isAlikeDead())
{
final L2Attackable npc = (L2Attackable) _actor;
// If its _knownPlayer isn't empty set the Intention to AI_INTENTION_ACTIVE
if (!npc.getKnownList().getKnownPlayers().isEmpty())
{
intention = AI_INTENTION_ACTIVE;
}
else
{
intention = AI_INTENTION_IDLE;
}
intention = ((L2Attackable) _actor).getKnownList().getKnownPlayers().isEmpty() ? AI_INTENTION_IDLE : AI_INTENTION_ACTIVE;
}
if (intention == AI_INTENTION_IDLE)
@@ -279,30 +258,14 @@ public class L2SiegeGuardAI extends L2CharacterAI implements Runnable
{
continue;
}
if (autoAttackCondition(target)) // check aggression
if (autoAttackCondition(target) && (npc.getHating(target) == 0)) // check aggression
{
// Get the hate level of the L2Attackable against this L2Character target contained in _aggroList
final int hating = npc.getHating(target);
// Add the attacker to the L2Attackable _aggroList with 0 damage and 1 hate
if (hating == 0)
{
npc.addDamageHate(target, 0, 1);
}
npc.addDamageHate(target, 0, 1);
}
}
// Chose a target from its aggroList
L2Character hated;
if (_actor.isConfused())
{
hated = getAttackTarget(); // Force mobs to attack anybody if confused
}
else
{
hated = npc.getMostHated();
// _mostHatedAnalysis.Update(hated);
}
final L2Character hated = _actor.isConfused() ? getAttackTarget() : npc.getMostHated();
// Order to the L2Attackable to attack the target
if (hated != null)
@@ -347,17 +310,13 @@ public class L2SiegeGuardAI extends L2CharacterAI implements Runnable
_log.info(getClass().getSimpleName() + ": thinkAttack(); timeout=" + (_attackTimeout - GameTimeController.getInstance().getGameTicks()));
}
if (_attackTimeout < GameTimeController.getInstance().getGameTicks())
if ((_attackTimeout < GameTimeController.getInstance().getGameTicks()) && _actor.isRunning())
{
// Check if the actor is running
if (_actor.isRunning())
{
// Set the actor movement type to walk and send Server->Client packet ChangeMoveType to all others L2PcInstance
_actor.setWalking();
// Calculate a new attack timeout
_attackTimeout = MAX_ATTACK_TIMEOUT + GameTimeController.getInstance().getGameTicks();
}
// Set the actor movement type to walk and send Server->Client packet ChangeMoveType to all others L2PcInstance
_actor.setWalking();
// Calculate a new attack timeout
_attackTimeout = MAX_ATTACK_TIMEOUT + GameTimeController.getInstance().getGameTicks();
}
final L2Character attackTarget = getAttackTarget();
@@ -367,8 +326,7 @@ public class L2SiegeGuardAI extends L2CharacterAI implements Runnable
// Stop hating this target after the attack timeout or if target is dead
if (attackTarget != null)
{
final L2Attackable npc = (L2Attackable) _actor;
npc.stopHating(attackTarget);
((L2Attackable) _actor).stopHating(attackTarget);
}
// Cancel target and timeout
@@ -390,16 +348,11 @@ public class L2SiegeGuardAI extends L2CharacterAI implements Runnable
{
final L2Character target = getAttackTarget();
// Call all L2Object of its Faction inside the Faction Range
if ((((L2Npc) _actor).getTemplate().getClans() == null) || (target == null))
if ((((L2Npc) _actor).getTemplate().getClans() == null) || (target == null) || target.isInvul())
{
return;
}
if (target.isInvul())
{
return; // speeding it up for siege guards
}
// Go through all L2Character that belong to its faction
// for (L2Character cha : _actor.getKnownList().getKnownCharactersInRadius(((L2NpcInstance) _actor).getFactionRange()+_actor.getTemplate().collisionRadius))
for (L2Character cha : _actor.getKnownList().getKnownCharactersInRadius(1000))
@@ -408,46 +361,32 @@ public class L2SiegeGuardAI extends L2CharacterAI implements Runnable
{
continue;
}
if (!(cha instanceof L2Npc))
{
if (_selfAnalysis.hasHealOrResurrect && (cha instanceof L2PcInstance) && (((L2Npc) _actor).getCastle().getSiege().checkIsDefender(((L2PcInstance) cha).getClan())))
if (_selfAnalysis.hasHealOrResurrect && (cha instanceof L2PcInstance) && (((L2Npc) _actor).getCastle().getSiege().checkIsDefender(((L2PcInstance) cha).getClan()))//
&& !_actor.isAttackingDisabled() && (cha.getCurrentHp() < (cha.getMaxHp() * 0.6)) && (_actor.getCurrentHp() > (_actor.getMaxHp() / 2)) && (_actor.getCurrentMp() > (_actor.getMaxMp() / 2)) && cha.isInCombat())
{
// heal friends
if (!_actor.isAttackingDisabled() && (cha.getCurrentHp() < (cha.getMaxHp() * 0.6)) && (_actor.getCurrentHp() > (_actor.getMaxHp() / 2)) && (_actor.getCurrentMp() > (_actor.getMaxMp() / 2)) && cha.isInCombat())
for (Skill sk : _selfAnalysis.healSkills)
{
for (Skill sk : _selfAnalysis.healSkills)
if ((_actor.getCurrentMp() < sk.getMpConsume()) || _actor.isSkillDisabled(sk) || !Util.checkIfInRange(sk.getCastRange(), _actor, cha, true))
{
if (_actor.getCurrentMp() < sk.getMpConsume())
{
continue;
}
if (_actor.isSkillDisabled(sk))
{
continue;
}
if (!Util.checkIfInRange(sk.getCastRange(), _actor, cha, true))
{
continue;
}
final int chance = 5;
if (chance >= Rnd.get(100))
{
continue;
}
if (!GeoData.getInstance().canSeeTarget(_actor, cha))
{
break;
}
final L2Object OldTarget = _actor.getTarget();
_actor.setTarget(cha);
clientStopMoving(null);
_actor.doCast(sk);
_actor.setTarget(OldTarget);
return;
continue;
}
final int chance = 5;
if (chance >= Rnd.get(100))
{
continue;
}
if (!GeoData.getInstance().canSeeTarget(_actor, cha))
{
break;
}
final L2Object OldTarget = _actor.getTarget();
_actor.setTarget(cha);
clientStopMoving(null);
_actor.doCast(sk);
_actor.setTarget(OldTarget);
return;
}
}
continue;
@@ -462,11 +401,7 @@ public class L2SiegeGuardAI extends L2CharacterAI implements Runnable
if (npc.getAI() != null) // TODO: possibly check not needed
{
if (!npc.isDead() && (Math.abs(target.getZ() - npc.getZ()) < 600)
// && _actor.getAttackByList().contains(getAttackTarget())
&& ((npc.getAI()._intention == CtrlIntention.AI_INTENTION_IDLE) || (npc.getAI()._intention == CtrlIntention.AI_INTENTION_ACTIVE))
// limiting aggro for siege guards
&& target.isInsideRadius(npc, 1500, true, false) && GeoData.getInstance().canSeeTarget(npc, target))
if (!npc.isDead() && (Math.abs(target.getZ() - npc.getZ()) < 600) && ((npc.getAI()._intention == CtrlIntention.AI_INTENTION_IDLE) || (npc.getAI()._intention == CtrlIntention.AI_INTENTION_ACTIVE)) && target.isInsideRadius(npc, 1500, true, false) && GeoData.getInstance().canSeeTarget(npc, target))
{
// Notify the L2Object AI with EVT_AGGRESSION
npc.getAI().notifyEvent(CtrlEvent.EVT_AGGRESSION, getAttackTarget(), 1);
@@ -477,19 +412,10 @@ public class L2SiegeGuardAI extends L2CharacterAI implements Runnable
{
for (Skill sk : _selfAnalysis.healSkills)
{
if (_actor.getCurrentMp() < sk.getMpConsume())
if ((_actor.getCurrentMp() < sk.getMpConsume()) || _actor.isSkillDisabled(sk) || !Util.checkIfInRange(sk.getCastRange(), _actor, npc, true))
{
continue;
}
if (_actor.isSkillDisabled(sk))
{
continue;
}
if (!Util.checkIfInRange(sk.getCastRange(), _actor, npc, true))
{
continue;
}
final int chance = 4;
if (chance >= Rnd.get(100))
{
@@ -499,7 +425,6 @@ public class L2SiegeGuardAI extends L2CharacterAI implements Runnable
{
break;
}
final L2Object OldTarget = _actor.getTarget();
_actor.setTarget(npc);
clientStopMoving(null);
@@ -540,16 +465,13 @@ public class L2SiegeGuardAI extends L2CharacterAI implements Runnable
}
// never attack defenders
if (attackTarget instanceof L2PcInstance)
if ((attackTarget instanceof L2PcInstance) && (sGuard.getConquerableHall() == null) && sGuard.getCastle().getSiege().checkIsDefender(((L2PcInstance) attackTarget).getClan()))
{
if ((sGuard.getConquerableHall() == null) && sGuard.getCastle().getSiege().checkIsDefender(((L2PcInstance) attackTarget).getClan()))
{
// Cancel the target
sGuard.stopHating(attackTarget);
_actor.setTarget(null);
setIntention(AI_INTENTION_IDLE, null, null);
return;
}
// Cancel the target
sGuard.stopHating(attackTarget);
_actor.setTarget(null);
setIntention(AI_INTENTION_IDLE, null, null);
return;
}
if (!GeoData.getInstance().canSeeTarget(_actor, attackTarget))
@@ -640,110 +562,85 @@ public class L2SiegeGuardAI extends L2CharacterAI implements Runnable
{
range = _selfAnalysis.maxCastRange - 50;
}
if (attackTarget.isMoving())
{
moveToPawn(attackTarget, range - 70);
}
else
{
moveToPawn(attackTarget, range);
}
moveToPawn(attackTarget, attackTarget.isMoving() ? range - 70 : range);
}
}
}
return;
}
// Else, if the actor is muted and far from target, just "move to pawn"
else if (_actor.isMuted() && (dist_2 > (range * range)) && !_selfAnalysis.isHealer)
else
{
// Temporary hack for preventing guards jumping off towers,
// before replacing this with effective geodata checks and AI modification
final double dz = _actor.getZ() - attackTarget.getZ();
if ((dz * dz) < (170 * 170)) // normally 130 if guard z coordinates correct
if (_actor.isMuted() && (dist_2 > (range * range)) && !_selfAnalysis.isHealer)
{
if (_selfAnalysis.isMage)
// Temporary hack for preventing guards jumping off towers,
// before replacing this with effective geodata checks and AI modification
final double dz = _actor.getZ() - attackTarget.getZ();
if ((dz * dz) < (170 * 170)) // normally 130 if guard z coordinates correct
{
range = _selfAnalysis.maxCastRange - 50;
if (_selfAnalysis.isMage)
{
range = _selfAnalysis.maxCastRange - 50;
}
moveToPawn(attackTarget, attackTarget.isMoving() ? range - 70 : range);
}
if (attackTarget.isMoving())
{
moveToPawn(attackTarget, range - 70);
}
else
{
moveToPawn(attackTarget, range);
}
}
return;
}
// Else, if this is close enough to attack
else if (dist_2 <= (range * range))
{
// Force mobs to attack anybody if confused
L2Character hated = null;
if (_actor.isConfused())
{
hated = attackTarget;
}
else
{
hated = ((L2Attackable) _actor).getMostHated();
}
if (hated == null)
{
setIntention(AI_INTENTION_ACTIVE, null, null);
return;
}
if (hated != attackTarget)
if (dist_2 <= (range * range))
{
attackTarget = hated;
}
_attackTimeout = MAX_ATTACK_TIMEOUT + GameTimeController.getInstance().getGameTicks();
// check for close combat skills && heal/buff skills
if (!_actor.isMuted() && (Rnd.nextInt(100) <= 5))
{
for (Skill sk : skills)
final L2Character hated = _actor.isConfused() ? attackTarget : ((L2Attackable) _actor).getMostHated();
if (hated == null)
{
final int castRange = sk.getCastRange();
if (((castRange * castRange) >= dist_2) && !sk.isPassive() && (_actor.getCurrentMp() >= _actor.getStat().getMpConsume(sk)) && !_actor.isSkillDisabled(sk))
setIntention(AI_INTENTION_ACTIVE, null, null);
return;
}
if (hated != attackTarget)
{
attackTarget = hated;
}
_attackTimeout = MAX_ATTACK_TIMEOUT + GameTimeController.getInstance().getGameTicks();
// check for close combat skills && heal/buff skills
if (!_actor.isMuted() && (Rnd.nextInt(100) <= 5))
{
for (Skill sk : skills)
{
final L2Object OldTarget = _actor.getTarget();
if ((sk.isContinuous() && !sk.isDebuff()) || (sk.hasEffectType(L2EffectType.HEAL)))
{
boolean useSkillSelf = true;
if ((sk.hasEffectType(L2EffectType.HEAL)) && (_actor.getCurrentHp() > (int) (_actor.getMaxHp() / 1.5)))
{
useSkillSelf = false;
break;
}
if ((sk.isContinuous() && !sk.isDebuff()) && _actor.isAffectedBySkill(sk.getId()))
{
useSkillSelf = false;
}
if (useSkillSelf)
{
_actor.setTarget(_actor);
}
}
final int castRange = sk.getCastRange();
clientStopMoving(null);
_actor.doCast(sk);
_actor.setTarget(OldTarget);
return;
if (((castRange * castRange) >= dist_2) && !sk.isPassive() && (_actor.getCurrentMp() >= _actor.getStat().getMpConsume(sk)) && !_actor.isSkillDisabled(sk))
{
final L2Object OldTarget = _actor.getTarget();
if ((sk.isContinuous() && !sk.isDebuff()) || (sk.hasEffectType(L2EffectType.HEAL)))
{
boolean useSkillSelf = true;
if ((sk.hasEffectType(L2EffectType.HEAL)) && (_actor.getCurrentHp() > (int) (_actor.getMaxHp() / 1.5)))
{
useSkillSelf = false;
break;
}
if ((sk.isContinuous() && !sk.isDebuff()) && _actor.isAffectedBySkill(sk.getId()))
{
useSkillSelf = false;
}
if (useSkillSelf)
{
_actor.setTarget(_actor);
}
}
clientStopMoving(null);
_actor.doCast(sk);
_actor.setTarget(OldTarget);
return;
}
}
}
}
// Finally, do the physical attack itself
if (!_selfAnalysis.isHealer)
{
_actor.doAttack(attackTarget);
// Finally, do the physical attack itself
if (!_selfAnalysis.isHealer)
{
_actor.doAttack(attackTarget);
}
}
}
}

View File

@@ -70,10 +70,9 @@ public class L2SummonAI extends L2PlayableAI implements Runnable
@Override
protected void onIntentionActive()
{
final L2Summon summon = (L2Summon) _actor;
if (_startFollow)
{
setIntention(AI_INTENTION_FOLLOW, summon.getOwner());
setIntention(AI_INTENTION_FOLLOW, ((L2Summon) _actor).getOwner());
}
else
{
@@ -138,11 +137,7 @@ public class L2SummonAI extends L2PlayableAI implements Runnable
private void thinkPickUp()
{
if (checkTargetLost(getTarget()))
{
return;
}
if (maybeMoveToPawn(getTarget(), 36))
if (checkTargetLost(getTarget()) || maybeMoveToPawn(getTarget(), 36))
{
return;
}
@@ -152,11 +147,7 @@ public class L2SummonAI extends L2PlayableAI implements Runnable
private void thinkInteract()
{
if (checkTargetLost(getTarget()))
{
return;
}
if (maybeMoveToPawn(getTarget(), 36))
if (checkTargetLost(getTarget()) || maybeMoveToPawn(getTarget(), 36))
{
return;
}
@@ -245,23 +236,23 @@ public class L2SummonAI extends L2PlayableAI implements Runnable
@Override
public void run()
{
if (_startAvoid)
if (!_startAvoid)
{
_startAvoid = false;
if (!_clientMoving && !_actor.isDead() && !_actor.isMovementDisabled())
{
final int ownerX = ((L2Summon) _actor).getOwner().getX();
final int ownerY = ((L2Summon) _actor).getOwner().getY();
final double angle = Math.toRadians(Rnd.get(-90, 90)) + Math.atan2(ownerY - _actor.getY(), ownerX - _actor.getX());
final int targetX = ownerX + (int) (AVOID_RADIUS * Math.cos(angle));
final int targetY = ownerY + (int) (AVOID_RADIUS * Math.sin(angle));
if (GeoData.getInstance().canMove(_actor.getX(), _actor.getY(), _actor.getZ(), targetX, targetY, _actor.getZ(), _actor.getInstanceId()))
{
moveTo(targetX, targetY, _actor.getZ());
}
}
return;
}
_startAvoid = false;
if (_clientMoving || _actor.isDead() || _actor.isMovementDisabled())
{
return;
}
final int ownerX = ((L2Summon) _actor).getOwner().getX();
final int ownerY = ((L2Summon) _actor).getOwner().getY();
final double angle = Math.toRadians(Rnd.get(-90, 90)) + Math.atan2(ownerY - _actor.getY(), ownerX - _actor.getX());
final int targetX = ownerX + (int) (AVOID_RADIUS * Math.cos(angle));
final int targetY = ownerY + (int) (AVOID_RADIUS * Math.sin(angle));
if (GeoData.getInstance().canMove(_actor.getX(), _actor.getY(), _actor.getZ(), targetX, targetY, _actor.getZ(), _actor.getInstanceId()))
{
moveTo(targetX, targetY, _actor.getZ());
}
}

View File

@@ -111,11 +111,7 @@ public final class FighterAI implements Runnable
// Out of combat follow logic.
if (!_guard.isInCombat())
{
final int moveToLocX = _player.getLocation().getX() + Rnd.get((_followRange * -1), _followRange);
final int moveToLocY = _player.getLocation().getY() + Rnd.get((_followRange * -1), _followRange);
final int moveToLocZ = _player.getLocation().getZ();
final Location moveToLocation = new Location(moveToLocX, moveToLocY, moveToLocZ);
_guard.getAI().setIntention(CtrlIntention.AI_INTENTION_MOVE_TO, moveToLocation);
_guard.getAI().setIntention(CtrlIntention.AI_INTENTION_MOVE_TO, (new Location((_player.getLocation().getX() + Rnd.get((_followRange * -1), _followRange)), (_player.getLocation().getY() + Rnd.get((_followRange * -1), _followRange)), _player.getLocation().getZ())));
}
}
}

View File

@@ -119,11 +119,7 @@ public final class HealerAI implements Runnable
// Out of combat follow logic.
if (!_guard.isInCombat())
{
final int moveToLocX = _player.getLocation().getX() + Rnd.get((_followRange * -1), _followRange);
final int moveToLocY = _player.getLocation().getY() + Rnd.get((_followRange * -1), _followRange);
final int moveToLocZ = _player.getLocation().getZ();
final Location moveToLocation = new Location(moveToLocX, moveToLocY, moveToLocZ);
_guard.getAI().setIntention(CtrlIntention.AI_INTENTION_MOVE_TO, moveToLocation);
_guard.getAI().setIntention(CtrlIntention.AI_INTENTION_MOVE_TO, (new Location((_player.getLocation().getX() + Rnd.get((_followRange * -1), _followRange)), (_player.getLocation().getY() + Rnd.get((_followRange * -1), _followRange)), _player.getLocation().getZ())));
}
}
}

View File

@@ -178,18 +178,8 @@ public class HtmCache
private String getHtm(String path)
{
if ((path == null) || path.isEmpty())
{
return ""; // avoid possible NPE
}
String content = _cache.get(path);
// TODO: Check why some files do not get in cache on server startup.
if (content == null)
{
content = loadFile(new File(Config.DATAPACK_ROOT, path));
}
return content;
return (path == null) || path.isEmpty() ? "" : _cache.get(path) == null ? loadFile(new File(Config.DATAPACK_ROOT, path)) : _cache.get(path);
}
public boolean contains(String path)

View File

@@ -235,11 +235,12 @@ public final class Forum
public void vload()
{
if (!_loaded)
if (_loaded)
{
load();
getChildren();
_loaded = true;
return;
}
load();
getChildren();
_loaded = true;
}
}

View File

@@ -45,9 +45,7 @@ public class ForumsBBSManager extends BaseBBSManager
{
while (rs.next())
{
final int forumId = rs.getInt("forum_id");
final Forum f = new Forum(forumId, null);
addForum(f);
addForum((new Forum(rs.getInt("forum_id"), null)));
}
}
catch (Exception e)

View File

@@ -25,7 +25,6 @@ import java.util.concurrent.ConcurrentHashMap;
import com.l2jmobius.gameserver.communitybbs.BB.Forum;
import com.l2jmobius.gameserver.communitybbs.BB.Post;
import com.l2jmobius.gameserver.communitybbs.BB.Post.CPost;
import com.l2jmobius.gameserver.communitybbs.BB.Topic;
import com.l2jmobius.gameserver.handler.CommunityBoardHandler;
import com.l2jmobius.gameserver.model.actor.instance.L2PcInstance;
@@ -69,21 +68,8 @@ public class PostBBSManager extends BaseBBSManager
st.nextToken();
final int idf = Integer.parseInt(st.nextToken());
final int idp = Integer.parseInt(st.nextToken());
String index = null;
if (st.hasMoreTokens())
{
index = st.nextToken();
}
int ind = 0;
if (index == null)
{
ind = 1;
}
else
{
ind = Integer.parseInt(index);
}
final String index = st.hasMoreTokens() ? st.nextToken() : null;
final int ind = index == null ? 1 : Integer.parseInt(index);
showPost((TopicBBSManager.getInstance().getTopicByID(idp)), ForumsBBSManager.getInstance().getForumByID(idf), activeChar, ind);
}
else if (command.startsWith("_bbsposts;edit;"))
@@ -148,14 +134,7 @@ public class PostBBSManager extends BaseBBSManager
private void showMemoPost(Topic topic, L2PcInstance activeChar, Forum forum)
{
final Post p = getGPosttByTopic(topic);
final Locale locale = Locale.getDefault();
final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL, locale);
String mes = p.getCPost(0).postTxt.replace(">", "&gt;");
mes = mes.replace("<", "&lt;");
final String html = StringUtil.concat("<html><body><br><br><table border=0 width=610><tr><td width=10></td><td width=600 align=left><a action=\"bypass _bbshome\">HOME</a>&nbsp;>&nbsp;<a action=\"bypass _bbsmemo\">Memo Form</a></td></tr></table><img src=\"L2UI.squareblank\" width=\"1\" height=\"10\"><center><table border=0 cellspacing=0 cellpadding=0 bgcolor=333333><tr><td height=10></td></tr><tr><td fixWIDTH=55 align=right valign=top>&$413; : &nbsp;</td><td fixWIDTH=380 valign=top>", topic.getName(), "</td><td fixwidth=5></td><td fixwidth=50></td><td fixWIDTH=120></td></tr><tr><td height=10></td></tr><tr><td align=right><font color=\"AAAAAA\" >&$417; : &nbsp;</font></td><td><font color=\"AAAAAA\">", topic.getOwnerName() + "</font></td><td></td><td><font color=\"AAAAAA\">&$418; :</font></td><td><font color=\"AAAAAA\">", dateFormat.format(p.getCPost(0).postDate), "</font></td></tr><tr><td height=10></td></tr></table><br><table border=0 cellspacing=0 cellpadding=0><tr><td fixwidth=5></td><td FIXWIDTH=600 align=left>", mes, "</td><td fixqqwidth=5></td></tr></table><br><img src=\"L2UI.squareblank\" width=\"1\" height=\"5\"><img src=\"L2UI.squaregray\" width=\"610\" height=\"1\"><img src=\"L2UI.squareblank\" width=\"1\" height=\"5\"><table border=0 cellspacing=0 cellpadding=0 FIXWIDTH=610><tr><td width=50><button value=\"&$422;\" action=\"bypass _bbsmemo\" back=\"l2ui_ch3.smallbutton2_down\" width=65 height=20 fore=\"l2ui_ch3.smallbutton2\"></td><td width=560 align=right><table border=0 cellspacing=0><tr><td FIXWIDTH=300></td><td><button value = \"&$424;\" action=\"bypass _bbsposts;edit;", String.valueOf(forum.getID()), ";", String.valueOf(topic.getID()), ";0\" back=\"l2ui_ch3.smallbutton2_down\" width=65 height=20 fore=\"l2ui_ch3.smallbutton2\" ></td>&nbsp;<td><button value = \"&$425;\" action=\"bypass _bbstopics;del;", String.valueOf(forum.getID()), ";", String.valueOf(topic.getID()), "\" back=\"l2ui_ch3.smallbutton2_down\" width=65 height=20 fore=\"l2ui_ch3.smallbutton2\" ></td>&nbsp;<td><button value = \"&$421;\" action=\"bypass _bbstopics;crea;", String.valueOf(forum.getID()), "\" back=\"l2ui_ch3.smallbutton2_down\" width=65 height=20 fore=\"l2ui_ch3.smallbutton2\" ></td>&nbsp;</tr></table></td></tr></table><br><br><br></center></body></html>");
CommunityBoardHandler.separateAndSend(html, activeChar);
CommunityBoardHandler.separateAndSend(StringUtil.concat("<html><body><br><br><table border=0 width=610><tr><td width=10></td><td width=600 align=left><a action=\"bypass _bbshome\">HOME</a>&nbsp;>&nbsp;<a action=\"bypass _bbsmemo\">Memo Form</a></td></tr></table><img src=\"L2UI.squareblank\" width=\"1\" height=\"10\"><center><table border=0 cellspacing=0 cellpadding=0 bgcolor=333333><tr><td height=10></td></tr><tr><td fixWIDTH=55 align=right valign=top>&$413; : &nbsp;</td><td fixWIDTH=380 valign=top>", topic.getName(), "</td><td fixwidth=5></td><td fixwidth=50></td><td fixWIDTH=120></td></tr><tr><td height=10></td></tr><tr><td align=right><font color=\"AAAAAA\" >&$417; : &nbsp;</font></td><td><font color=\"AAAAAA\">", topic.getOwnerName() + "</font></td><td></td><td><font color=\"AAAAAA\">&$418; :</font></td><td><font color=\"AAAAAA\">", DateFormat.getDateInstance(DateFormat.FULL, Locale.getDefault()).format(p.getCPost(0).postDate), "</font></td></tr><tr><td height=10></td></tr></table><br><table border=0 cellspacing=0 cellpadding=0><tr><td fixwidth=5></td><td FIXWIDTH=600 align=left>", p.getCPost(0).postTxt.replace(">", "&gt;").replace("<", "&lt;"), "</td><td fixqqwidth=5></td></tr></table><br><img src=\"L2UI.squareblank\" width=\"1\" height=\"5\"><img src=\"L2UI.squaregray\" width=\"610\" height=\"1\"><img src=\"L2UI.squareblank\" width=\"1\" height=\"5\"><table border=0 cellspacing=0 cellpadding=0 FIXWIDTH=610><tr><td width=50><button value=\"&$422;\" action=\"bypass _bbsmemo\" back=\"l2ui_ch3.smallbutton2_down\" width=65 height=20 fore=\"l2ui_ch3.smallbutton2\"></td><td width=560 align=right><table border=0 cellspacing=0><tr><td FIXWIDTH=300></td><td><button value = \"&$424;\" action=\"bypass _bbsposts;edit;", String.valueOf(forum.getID()), ";", String.valueOf(topic.getID()), ";0\" back=\"l2ui_ch3.smallbutton2_down\" width=65 height=20 fore=\"l2ui_ch3.smallbutton2\" ></td>&nbsp;<td><button value = \"&$425;\" action=\"bypass _bbstopics;del;", String.valueOf(forum.getID()), ";", String.valueOf(topic.getID()), "\" back=\"l2ui_ch3.smallbutton2_down\" width=65 height=20 fore=\"l2ui_ch3.smallbutton2\" ></td>&nbsp;<td><button value = \"&$421;\" action=\"bypass _bbstopics;crea;", String.valueOf(forum.getID()), "\" back=\"l2ui_ch3.smallbutton2_down\" width=65 height=20 fore=\"l2ui_ch3.smallbutton2\" ></td>&nbsp;</tr></table></td></tr></table><br><br><br></center></body></html>"), activeChar);
}
@Override
@@ -183,8 +162,7 @@ public class PostBBSManager extends BaseBBSManager
final Post p = getGPosttByTopic(t);
if (p != null)
{
final CPost cp = p.getCPost(idp);
if (cp == null)
if (p.getCPost(idp) == null)
{
CommunityBoardHandler.separateAndSend("<html><body><br><br><center>the post: " + idp + " does not exist !</center><br><br></body></html>", activeChar);
}

View File

@@ -61,11 +61,7 @@ public class TopicBBSManager extends BaseBBSManager
public int getMaxID(Forum f)
{
final Integer i = _maxId.get(f);
if (i == null)
{
return 0;
}
return i;
return i == null ? 0 : i;
}
public Topic getTopicByID(int idf)
@@ -147,20 +143,8 @@ public class TopicBBSManager extends BaseBBSManager
st.nextToken();
st.nextToken();
final int idf = Integer.parseInt(st.nextToken());
String index = null;
if (st.hasMoreTokens())
{
index = st.nextToken();
}
int ind = 0;
if (index == null)
{
ind = 1;
}
else
{
ind = Integer.parseInt(index);
}
final String index = st.hasMoreTokens() ? st.nextToken() : null;
final int ind = index == null ? 1 : Integer.parseInt(index);
showTopics(ForumsBBSManager.getInstance().getForumByID(idf), activeChar, ind, idf);
}
else if (command.startsWith("_bbstopics;crea"))
@@ -261,12 +245,9 @@ public class TopicBBSManager extends BaseBBSManager
break;
}
final Topic t = forum.getTopic(j);
if (t != null)
if ((t != null) && (i++ >= (12 * (index - 1))))
{
if (i++ >= (12 * (index - 1)))
{
StringUtil.append(html, "<table border=0 cellspacing=0 cellpadding=5 WIDTH=610><tr><td FIXWIDTH=5></td><td FIXWIDTH=415><a action=\"bypass _bbsposts;read;", String.valueOf(forum.getID()), ";", String.valueOf(t.getID()), "\">", t.getName(), "</a></td><td FIXWIDTH=120 align=center></td><td FIXWIDTH=70 align=center>", dateFormat.format(new Date(t.getDate())), "</td></tr></table><img src=\"L2UI.Squaregray\" width=\"610\" height=\"1\">");
}
StringUtil.append(html, "<table border=0 cellspacing=0 cellpadding=5 WIDTH=610><tr><td FIXWIDTH=5></td><td FIXWIDTH=415><a action=\"bypass _bbsposts;read;", String.valueOf(forum.getID()), ";", String.valueOf(t.getID()), "\">", t.getName(), "</a></td><td FIXWIDTH=120 align=center></td><td FIXWIDTH=70 align=center>", dateFormat.format(new Date(t.getDate())), "</td></tr></table><img src=\"L2UI.Squaregray\" width=\"610\" height=\"1\">");
}
}
@@ -281,8 +262,7 @@ public class TopicBBSManager extends BaseBBSManager
StringUtil.append(html, "<td><button action=\"bypass _bbstopics;read;", String.valueOf(forum.getID()), ";", String.valueOf(index - 1), "\" back=\"l2ui_ch3.prev1_down\" fore=\"l2ui_ch3.prev1\" width=16 height=16 ></td>");
}
int nbp;
nbp = forum.getTopicSize() / 8;
int nbp = forum.getTopicSize() / 8;
if ((nbp * 8) != ClanTable.getInstance().getClanCount())
{
nbp++;

View File

@@ -52,21 +52,19 @@ public class CharNameTable
public final void addName(L2PcInstance player)
{
if (player != null)
if (player == null)
{
addName(player.getObjectId(), player.getName());
_accessLevels.put(player.getObjectId(), player.getAccessLevel().getLevel());
return;
}
addName(player.getObjectId(), player.getName());
_accessLevels.put(player.getObjectId(), player.getAccessLevel().getLevel());
}
private final void addName(int objectId, String name)
{
if (name != null)
if ((name != null) && !name.equals(_chars.get(objectId)))
{
if (!name.equals(_chars.get(objectId)))
{
_chars.put(objectId, name);
}
_chars.put(objectId, name);
}
}
@@ -117,14 +115,14 @@ public class CharNameTable
_log.log(Level.WARNING, getClass().getSimpleName() + ": Could not check existing char name: " + e.getMessage(), e);
}
if (id > 0)
if (id <= 0)
{
_chars.put(id, name);
_accessLevels.put(id, accessLevel);
return id;
return -1; // not found
}
return -1; // not found
_chars.put(id, name);
_accessLevels.put(id, accessLevel);
return id;
}
public final String getNameById(int id)
@@ -170,12 +168,7 @@ public class CharNameTable
public final int getAccessLevelById(int objectId)
{
if (getNameById(objectId) != null)
{
return _accessLevels.get(objectId);
}
return 0;
return getNameById(objectId) != null ? _accessLevels.get(objectId) : 0;
}
public synchronized boolean doesCharNameExist(String name)

View File

@@ -256,14 +256,7 @@ public class ClanTable
}
final L2ClanMember leaderMember = clan.getLeader();
if (leaderMember == null)
{
clan.getWarehouse().destroyAllItems("ClanRemove", null, null);
}
else
{
clan.getWarehouse().destroyAllItems("ClanRemove", clan.getLeader().getPlayerInstance(), null);
}
clan.getWarehouse().destroyAllItems("ClanRemove", leaderMember == null ? null : clan.getLeader().getPlayerInstance(), null);
for (L2ClanMember member : clan.getMembers())
{
@@ -324,13 +317,9 @@ public class ClanTable
if (fortId != 0)
{
final Fort fort = FortManager.getInstance().getFortById(fortId);
if (fort != null)
if ((fort != null) && (clan == fort.getOwnerClan()))
{
final L2Clan owner = fort.getOwnerClan();
if (clan == owner)
{
fort.removeOwner(true);
}
fort.removeOwner(true);
}
}
@@ -507,16 +496,13 @@ public class ClanTable
for (L2Clan clan : _clans.values())
{
final int allyId = clan.getAllyId();
if ((allyId != 0) && (clan.getId() != allyId))
if ((allyId != 0) && (clan.getId() != allyId) && !_clans.containsKey(allyId))
{
if (!_clans.containsKey(allyId))
{
clan.setAllyId(0);
clan.setAllyName(null);
clan.changeAllyCrest(0, true);
clan.updateClanInDB();
_log.info(getClass().getSimpleName() + ": Removed alliance from clan: " + clan);
}
clan.setAllyId(0);
clan.setAllyName(null);
clan.changeAllyCrest(0, true);
clan.updateClanInDB();
_log.info(getClass().getSimpleName() + ": Removed alliance from clan: " + clan);
}
}
}

View File

@@ -114,34 +114,25 @@ public final class CrestTable
for (L2Clan clan : ClanTable.getInstance().getClans())
{
if (clan.getCrestId() != 0)
if ((clan.getCrestId() != 0) && (getCrest(clan.getCrestId()) == null))
{
if (getCrest(clan.getCrestId()) == null)
{
LOGGER.info("Removing non-existent crest for clan " + clan.getName() + " [" + clan.getId() + "], crestId:" + clan.getCrestId());
clan.setCrestId(0);
clan.changeClanCrest(0);
}
LOGGER.info("Removing non-existent crest for clan " + clan.getName() + " [" + clan.getId() + "], crestId:" + clan.getCrestId());
clan.setCrestId(0);
clan.changeClanCrest(0);
}
if (clan.getCrestLargeId() != 0)
if ((clan.getCrestLargeId() != 0) && (getCrest(clan.getCrestLargeId()) == null))
{
if (getCrest(clan.getCrestLargeId()) == null)
{
LOGGER.info("Removing non-existent large crest for clan " + clan.getName() + " [" + clan.getId() + "], crestLargeId:" + clan.getCrestLargeId());
clan.setCrestLargeId(0);
clan.changeLargeCrest(0);
}
LOGGER.info("Removing non-existent large crest for clan " + clan.getName() + " [" + clan.getId() + "], crestLargeId:" + clan.getCrestLargeId());
clan.setCrestLargeId(0);
clan.changeLargeCrest(0);
}
if (clan.getAllyCrestId() != 0)
if ((clan.getAllyCrestId() != 0) && (getCrest(clan.getAllyCrestId()) == null))
{
if (getCrest(clan.getAllyCrestId()) == null)
{
LOGGER.info("Removing non-existent ally crest for clan " + clan.getName() + " [" + clan.getId() + "], allyCrestId:" + clan.getAllyCrestId());
clan.setAllyCrestId(0);
clan.changeAllyCrest(0, true);
}
LOGGER.info("Removing non-existent ally crest for clan " + clan.getName() + " [" + clan.getId() + "], allyCrestId:" + clan.getAllyCrestId());
clan.setAllyCrestId(0);
clan.changeAllyCrest(0, true);
}
}
}

View File

@@ -184,11 +184,7 @@ public class NpcBufferTable
public NpcBufferData getSkillInfo(int npcId, int buffGroup)
{
final NpcBufferSkills skills = _buffers.get(npcId);
if (skills != null)
{
return skills.getSkillGroupInfo(buffGroup);
}
return null;
return skills != null ? skills.getSkillGroupInfo(buffGroup) : null;
}
public static NpcBufferTable getInstance()

View File

@@ -45,11 +45,7 @@ public class SummonEffectsTable
private Map<Integer, Map<Integer, SummonEffect>> getServitorEffects(L2PcInstance owner)
{
final Map<Integer, Map<Integer, Map<Integer, SummonEffect>>> servitorMap = _servitorEffects.get(owner.getObjectId());
if (servitorMap == null)
{
return null;
}
return servitorMap.get(owner.getClassIndex());
return servitorMap == null ? null : servitorMap.get(owner.getClassIndex());
}
private Map<Integer, SummonEffect> getServitorEffects(L2PcInstance owner, int referenceSkill)

View File

@@ -110,12 +110,9 @@ public class SummonSkillsTable
}
break;
}
else if (temp.getMinLevel() <= cha.getLevel())
if ((temp.getMinLevel() <= cha.getLevel()) && (temp.getLevel() > lvl))
{
if (temp.getLevel() > lvl)
{
lvl = temp.getLevel();
}
lvl = temp.getLevel();
}
}
return lvl;

View File

@@ -68,38 +68,40 @@ public class TeleportLocationTable
LOGGER.log(Level.SEVERE, getClass().getSimpleName() + ": Error loading Teleport Table.", e);
}
if (Config.CUSTOM_TELEPORT_TABLE)
if (!Config.CUSTOM_TELEPORT_TABLE)
{
int _cTeleCount = _teleports.size();
try (Connection con = DatabaseFactory.getInstance().getConnection();
Statement s = con.createStatement();
ResultSet rs = s.executeQuery("SELECT id, loc_x, loc_y, loc_z, price, fornoble, itemId FROM custom_teleport"))
return;
}
int _cTeleCount = _teleports.size();
try (Connection con = DatabaseFactory.getInstance().getConnection();
Statement s = con.createStatement();
ResultSet rs = s.executeQuery("SELECT id, loc_x, loc_y, loc_z, price, fornoble, itemId FROM custom_teleport"))
{
L2TeleportLocation teleport;
while (rs.next())
{
L2TeleportLocation teleport;
while (rs.next())
{
teleport = new L2TeleportLocation();
teleport.setTeleId(rs.getInt("id"));
teleport.setLocX(rs.getInt("loc_x"));
teleport.setLocY(rs.getInt("loc_y"));
teleport.setLocZ(rs.getInt("loc_z"));
teleport.setPrice(rs.getInt("price"));
teleport.setIsForNoble(rs.getInt("fornoble") == 1);
teleport.setItemId(rs.getInt("itemId"));
_teleports.put(teleport.getTeleId(), teleport);
}
_cTeleCount = _teleports.size() - _cTeleCount;
if (_cTeleCount > 0)
{
LOGGER.info(getClass().getSimpleName() + ": Loaded " + _cTeleCount + " Custom Teleport Location Templates.");
}
teleport = new L2TeleportLocation();
teleport.setTeleId(rs.getInt("id"));
teleport.setLocX(rs.getInt("loc_x"));
teleport.setLocY(rs.getInt("loc_y"));
teleport.setLocZ(rs.getInt("loc_z"));
teleport.setPrice(rs.getInt("price"));
teleport.setIsForNoble(rs.getInt("fornoble") == 1);
teleport.setItemId(rs.getInt("itemId"));
_teleports.put(teleport.getTeleId(), teleport);
}
catch (Exception e)
_cTeleCount = _teleports.size() - _cTeleCount;
if (_cTeleCount > 0)
{
LOGGER.log(Level.WARNING, getClass().getSimpleName() + ": Error while creating custom teleport table " + e.getMessage(), e);
LOGGER.info(getClass().getSimpleName() + ": Loaded " + _cTeleCount + " Custom Teleport Location Templates.");
}
}
catch (Exception e)
{
LOGGER.log(Level.WARNING, getClass().getSimpleName() + ": Error while creating custom teleport table " + e.getMessage(), e);
}
}
/**

View File

@@ -60,10 +60,7 @@ public final class AbilityPointsData implements IXmlReader
if ("points".equalsIgnoreCase(d.getNodeName()))
{
final NamedNodeMap attrs = d.getAttributes();
final int from = parseInteger(attrs, "from");
final int to = parseInteger(attrs, "to");
final int costs = parseInteger(attrs, "costs");
_points.add(new RangeAbilityPointsHolder(from, to, costs));
_points.add(new RangeAbilityPointsHolder(parseInteger(attrs, "from"), parseInteger(attrs, "to"), parseInteger(attrs, "costs")));
}
}
}
@@ -86,18 +83,12 @@ public final class AbilityPointsData implements IXmlReader
{
points++; // for next point
final RangeAbilityPointsHolder holder = getHolder(points);
if (holder == null)
if (holder != null)
{
final RangeAbilityPointsHolder prevHolder = getHolder(points - 1);
if (prevHolder != null)
{
return prevHolder.getSP();
}
// No data found
return points >= 13 ? 1_000_000_000 : points >= 9 ? 750_000_000 : points >= 5 ? 500_000_000 : 250_000_000;
return holder.getSP();
}
return holder.getSP();
final RangeAbilityPointsHolder prevHolder = getHolder(points - 1);
return prevHolder != null ? prevHolder.getSP() : points >= 13 ? 1_000_000_000 : points >= 9 ? 750_000_000 : points >= 5 ? 500_000_000 : 250_000_000;
}
public static final AbilityPointsData getInstance()

View File

@@ -120,7 +120,7 @@ public final class AdminData implements IXmlReader
{
return _accessLevels.get(-1);
}
else if (!_accessLevels.containsKey(accessLevelNum))
if (!_accessLevels.containsKey(accessLevelNum))
{
_accessLevels.put(accessLevelNum, new L2AccessLevel());
}

View File

@@ -124,8 +124,7 @@ public final class BeautyShopData implements IXmlReader
att = attrs.item(i);
set.set(att.getNodeName(), att.getNodeValue());
}
final BeautyItem face = new BeautyItem(set);
beautyData.addFace(face);
beautyData.addFace((new BeautyItem(set)));
}
}
@@ -146,11 +145,7 @@ public final class BeautyShopData implements IXmlReader
public BeautyData getBeautyData(Race race, Sex sex)
{
if (_beautyList.containsKey(race))
{
return _beautyList.get(race).get(sex);
}
return null;
return _beautyList.containsKey(race) ? _beautyList.get(race).get(sex) : null;
}
public static BeautyShopData getInstance()

View File

@@ -153,8 +153,7 @@ public final class BuyListData implements IXmlReader
{
if ("npc".equalsIgnoreCase(npcs_node.getNodeName()))
{
final int npcId = Integer.parseInt(npcs_node.getTextContent());
buyList.addAllowedNpc(npcId);
buyList.addAllowedNpc(Integer.parseInt(npcs_node.getTextContent()));
}
}
}

View File

@@ -74,13 +74,7 @@ public final class CastleData implements IXmlReader
if ("npc".equals(npcNode.getNodeName()))
{
final NamedNodeMap np = npcNode.getAttributes();
final int npcId = parseInteger(np, "id");
final int x = parseInteger(np, "x");
final int y = parseInteger(np, "y");
final int z = parseInteger(np, "z");
final int heading = parseInteger(np, "heading");
spawns.add(new CastleSpawnHolder(npcId, side, x, y, z, heading));
spawns.add(new CastleSpawnHolder(parseInteger(np, "id"), side, parseInteger(np, "x"), parseInteger(np, "y"), parseInteger(np, "z"), parseInteger(np, "heading")));
}
}
}

View File

@@ -68,8 +68,7 @@ public final class ClassListData implements IXmlReader
attr = attrs.getNamedItem("name");
final String className = attr.getNodeValue();
attr = attrs.getNamedItem("parentClassId");
final ClassId parentClassId = (attr != null) ? ClassId.getClassId(parseInteger(attr)) : null;
_classData.put(classId, new ClassInfo(classId, className, parentClassId));
_classData.put(classId, new ClassInfo(classId, className, ((attr != null) ? ClassId.getClassId(parseInteger(attr)) : null)));
}
}
}

View File

@@ -131,8 +131,7 @@ public class DailyMissionData implements IXmlReader
}
else
{
final String[] s = att.getNodeValue().split(",");
for (String element : s)
for (String element : att.getNodeValue().split(","))
{
classesList.add(Integer.parseInt(element));
}
@@ -142,9 +141,7 @@ public class DailyMissionData implements IXmlReader
{
if ("reward".equalsIgnoreCase(c.getNodeName()))
{
final int itemId = Integer.parseInt(c.getAttributes().getNamedItem("item").getNodeValue());
final int itemCount = Integer.parseInt(c.getAttributes().getNamedItem("count").getNodeValue());
rewards.put(itemId, itemCount);
rewards.put(Integer.parseInt(c.getAttributes().getNamedItem("item").getNodeValue()), Integer.parseInt(c.getAttributes().getNamedItem("count").getNodeValue()));
}
}

View File

@@ -100,8 +100,7 @@ public class DoorData implements IXmlReader
pos = set.getString("node2").split(",");
posX = Integer.parseInt(pos[0]);
posY = Integer.parseInt(pos[1]);
int collisionRadius; // (max) radius for movement checks
collisionRadius = Math.min(Math.abs(nodeX - posX), Math.abs(nodeY - posY));
int collisionRadius = Math.min(Math.abs(nodeX - posX), Math.abs(nodeY - posY)); // (max) radius for movement checks
if (collisionRadius < 20)
{
collisionRadius = 20;

View File

@@ -17,7 +17,6 @@
package com.l2jmobius.gameserver.data.xml.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
@@ -85,75 +84,85 @@ public class EnchantItemBonusData implements IXmlReader
}
}
if (!_armorHPBonuses.isEmpty())
if (_armorHPBonuses.isEmpty())
{
final ItemTable it = ItemTable.getInstance();
// Armors
final Collection<Integer> armorIds = it.getAllArmorsId();
for (Integer itemId : armorIds)
return;
}
final ItemTable it = ItemTable.getInstance();
for (Integer itemId : it.getAllArmorsId())
{
final L2Item item = it.getTemplate(itemId);
if ((item != null) && (item.getCrystalType() != CrystalType.NONE))
{
final L2Item item = it.getTemplate(itemId);
if ((item != null) && (item.getCrystalType() != CrystalType.NONE))
switch (item.getBodyPart())
{
switch (item.getBodyPart())
case L2Item.SLOT_CHEST:
{
case L2Item.SLOT_CHEST:
if (item.getCrystalTypePlus() == CrystalType.R)
{
item.attach(new FuncTemplate(null, null, StatFunction.ENCHANTPATK.getName(), -1, Stats.POWER_ATTACK, 0));
item.attach(new FuncTemplate(null, null, StatFunction.ENCHANTMATK.getName(), -1, Stats.MAGIC_ATTACK, 0));
break;
}
item.attach(new FuncTemplate(null, null, StatFunction.ENCHANTHP.getName(), -1, Stats.MAX_HP, 0));
break;
case L2Item.SLOT_FEET:
if (item.getCrystalTypePlus() == CrystalType.R)
{
item.attach(new FuncTemplate(null, null, StatFunction.ENCHANTRUNSPD.getName(), -1, Stats.MOVE_SPEED, 0));
break;
}
item.attach(new FuncTemplate(null, null, StatFunction.ENCHANTHP.getName(), -1, Stats.MAX_HP, 0));
break;
case L2Item.SLOT_GLOVES:
if (item.getCrystalTypePlus() == CrystalType.R)
{
item.attach(new FuncTemplate(null, null, StatFunction.ENCHANTACCEVAS.getName(), -1, Stats.ACCURACY_COMBAT, 0));
item.attach(new FuncTemplate(null, null, StatFunction.ENCHANTACCEVAS.getName(), -1, Stats.ACCURACY_MAGIC, 0));
break;
}
item.attach(new FuncTemplate(null, null, StatFunction.ENCHANTHP.getName(), -1, Stats.MAX_HP, 0));
break;
case L2Item.SLOT_HEAD:
if (item.getCrystalTypePlus() == CrystalType.R)
{
item.attach(new FuncTemplate(null, null, StatFunction.ENCHANTACCEVAS.getName(), -1, Stats.EVASION_RATE, 0));
item.attach(new FuncTemplate(null, null, StatFunction.ENCHANTACCEVAS.getName(), -1, Stats.MAGIC_EVASION_RATE, 0));
break;
}
item.attach(new FuncTemplate(null, null, StatFunction.ENCHANTHP.getName(), -1, Stats.MAX_HP, 0));
break;
case L2Item.SLOT_LEGS:
if (item.getCrystalTypePlus() == CrystalType.R)
{
item.attach(new FuncTemplate(null, null, StatFunction.ENCHANTPMCRITRATE.getName(), -1, Stats.CRITICAL_RATE, 0));
item.attach(new FuncTemplate(null, null, StatFunction.ENCHANTPMCRITRATE.getName(), -1, Stats.MCRITICAL_RATE, 0));
break;
}
item.attach(new FuncTemplate(null, null, StatFunction.ENCHANTHP.getName(), -1, Stats.MAX_HP, 0));
break;
case L2Item.SLOT_BACK:
case L2Item.SLOT_FULL_ARMOR:
case L2Item.SLOT_UNDERWEAR:
case L2Item.SLOT_L_HAND:
case L2Item.SLOT_BELT:
if (item.getCrystalTypePlus() == CrystalType.R)
{
item.attach(new FuncTemplate(null, null, StatFunction.ENCHANTHP.getName(), -1, Stats.MAX_HP, 0));
item.attach(new FuncTemplate(null, null, StatFunction.ENCHANTPATK.getName(), -1, Stats.POWER_ATTACK, 0));
item.attach(new FuncTemplate(null, null, StatFunction.ENCHANTMATK.getName(), -1, Stats.MAGIC_ATTACK, 0));
break;
}
default:
item.attach(new FuncTemplate(null, null, StatFunction.ENCHANTHP.getName(), -1, Stats.MAX_HP, 0));
break;
}
case L2Item.SLOT_FEET:
{
if (item.getCrystalTypePlus() == CrystalType.R)
{
item.attach(new FuncTemplate(null, null, StatFunction.ENCHANTRUNSPD.getName(), -1, Stats.MOVE_SPEED, 0));
break;
}
item.attach(new FuncTemplate(null, null, StatFunction.ENCHANTHP.getName(), -1, Stats.MAX_HP, 0));
break;
}
case L2Item.SLOT_GLOVES:
{
if (item.getCrystalTypePlus() == CrystalType.R)
{
item.attach(new FuncTemplate(null, null, StatFunction.ENCHANTACCEVAS.getName(), -1, Stats.ACCURACY_COMBAT, 0));
item.attach(new FuncTemplate(null, null, StatFunction.ENCHANTACCEVAS.getName(), -1, Stats.ACCURACY_MAGIC, 0));
break;
}
item.attach(new FuncTemplate(null, null, StatFunction.ENCHANTHP.getName(), -1, Stats.MAX_HP, 0));
break;
}
case L2Item.SLOT_HEAD:
{
if (item.getCrystalTypePlus() == CrystalType.R)
{
item.attach(new FuncTemplate(null, null, StatFunction.ENCHANTACCEVAS.getName(), -1, Stats.EVASION_RATE, 0));
item.attach(new FuncTemplate(null, null, StatFunction.ENCHANTACCEVAS.getName(), -1, Stats.MAGIC_EVASION_RATE, 0));
break;
}
item.attach(new FuncTemplate(null, null, StatFunction.ENCHANTHP.getName(), -1, Stats.MAX_HP, 0));
break;
}
case L2Item.SLOT_LEGS:
{
if (item.getCrystalTypePlus() == CrystalType.R)
{
item.attach(new FuncTemplate(null, null, StatFunction.ENCHANTPMCRITRATE.getName(), -1, Stats.CRITICAL_RATE, 0));
item.attach(new FuncTemplate(null, null, StatFunction.ENCHANTPMCRITRATE.getName(), -1, Stats.MCRITICAL_RATE, 0));
break;
}
item.attach(new FuncTemplate(null, null, StatFunction.ENCHANTHP.getName(), -1, Stats.MAX_HP, 0));
break;
}
case L2Item.SLOT_BACK:
case L2Item.SLOT_FULL_ARMOR:
case L2Item.SLOT_UNDERWEAR:
case L2Item.SLOT_L_HAND:
case L2Item.SLOT_BELT:
{
item.attach(new FuncTemplate(null, null, StatFunction.ENCHANTHP.getName(), -1, Stats.MAX_HP, 0));
break;
}
default:
{
break;
}
}
}
@@ -172,15 +181,9 @@ public class EnchantItemBonusData implements IXmlReader
{
return 0;
}
double blessedArmorBonus = item.isBlessedItem() ? 1.5 : 1;
final double blessedArmorBonus = item.isBlessedItem() ? 1.5 : 1;
final int bonus = values.get(Math.min(item.getOlyEnchantLevel(), values.size()) - 1);
if (item.getItem().getBodyPart() == L2Item.SLOT_FULL_ARMOR)
{
return (int) (bonus * FULL_ARMOR_MODIFIER * blessedArmorBonus);
}
return bonus;
return item.getItem().getBodyPart() == L2Item.SLOT_FULL_ARMOR ? (int) (bonus * FULL_ARMOR_MODIFIER * blessedArmorBonus) : bonus;
}
/**

View File

@@ -96,11 +96,7 @@ public class EnchantItemOptionsData implements IXmlReader
*/
public EnchantOptions getOptions(int itemId, int enchantLevel)
{
if (!_data.containsKey(itemId) || !_data.get(itemId).containsKey(enchantLevel))
{
return null;
}
return _data.get(itemId).get(enchantLevel);
return !_data.containsKey(itemId) || !_data.get(itemId).containsKey(enchantLevel) ? null : _data.get(itemId).get(enchantLevel);
}
/**

View File

@@ -161,11 +161,7 @@ public class EnchantSkillGroupsData implements IXmlReader
{
// there is enchantment for this skill and we have the required level of it
final L2EnchantSkillLearn esl = getSkillEnchantmentBySkillId(skill.getId());
if ((esl != null) && (skill.getLevel() >= esl.getBaseLevel()))
{
return esl;
}
return null;
return (esl != null) && (skill.getLevel() >= esl.getBaseLevel()) ? esl : null;
}
/**

View File

@@ -102,11 +102,7 @@ public final class FishingMonstersData implements IXmlReader
*/
public L2FishingMonster getFishingMonsterById(int id)
{
if (_fishingMonstersData.containsKey(id))
{
return _fishingMonstersData.get(id);
}
return null;
return _fishingMonstersData.containsKey(id) ? _fishingMonstersData.get(id) : null;
}
/**

View File

@@ -130,9 +130,7 @@ public final class HennaData implements IXmlReader
{
if ("skill".equals(i.getNodeName()))
{
final int skillId = Integer.parseInt(i.getAttributes().getNamedItem("id").getNodeValue());
final int skillLevel = Integer.parseInt(i.getAttributes().getNamedItem("level").getNodeValue());
skills.add(new SkillHolder(skillId, skillLevel));
skills.add(new SkillHolder(Integer.parseInt(i.getAttributes().getNamedItem("id").getNodeValue()), Integer.parseInt(i.getAttributes().getNamedItem("level").getNodeValue())));
}
}
break;

View File

@@ -216,12 +216,7 @@ public final class InitialShortcutData implements IXmlReader
private Shortcut createShortcut(int pageId, Node b)
{
final NamedNodeMap attrs = b.getAttributes();
final int slotId = parseInteger(attrs, "slotId");
final ShortcutType shortcutType = parseEnum(attrs, ShortcutType.class, "shortcutType");
final int shortcutId = parseInteger(attrs, "shortcutId");
final int shortcutLevel = parseInteger(attrs, "shortcutLevel", 0);
final int characterType = parseInteger(attrs, "characterType", 0);
return new Shortcut(slotId, pageId, shortcutType, shortcutId, shortcutLevel, characterType);
return new Shortcut(parseInteger(attrs, "slotId"), pageId, parseEnum(attrs, ShortcutType.class, "shortcutType"), parseInteger(attrs, "shortcutId"), parseInteger(attrs, "shortcutLevel", 0), parseInteger(attrs, "characterType", 0));
}
/**

View File

@@ -65,10 +65,7 @@ public final class ItemCrystalizationData implements IXmlReader
if ("item".equalsIgnoreCase(c.getNodeName()))
{
final NamedNodeMap attrs = c.getAttributes();
final int itemId = parseInteger(attrs, "id");
final long itemCount = parseLong(attrs, "count");
final double itemChance = parseDouble(attrs, "chance");
data.addItem(new ItemChanceHolder(itemId, itemChance, itemCount));
data.addItem(new ItemChanceHolder(parseInteger(attrs, "id"), parseDouble(attrs, "chance"), parseLong(attrs, "count")));
}
}
_items.put(id, data);

View File

@@ -129,19 +129,15 @@ public final class MultisellData implements IXmlReader
{
if ("item".equalsIgnoreCase(d.getNodeName()))
{
final Entry e = parseEntry(d, entryId++, list);
list.getEntries().add(e);
list.getEntries().add(parseEntry(d, entryId++, list));
}
else if ("npcs".equalsIgnoreCase(d.getNodeName()))
{
for (Node b = d.getFirstChild(); b != null; b = b.getNextSibling())
{
if ("npc".equalsIgnoreCase(b.getNodeName()))
if ("npc".equalsIgnoreCase(b.getNodeName()) && Util.isDigit(b.getTextContent()))
{
if (Util.isDigit(b.getTextContent()))
{
list.allowNpc(Integer.parseInt(b.getTextContent()));
}
list.allowNpc(Integer.parseInt(b.getTextContent()));
}
}
}
@@ -281,12 +277,12 @@ public final class MultisellData implements IXmlReader
{
case PC_BANG_POINTS:
{
if (player.getPcBangPoints() < amount)
if (player.getPcBangPoints() >= amount)
{
player.sendPacket(SystemMessage.getSystemMessage(SystemMessageId.YOU_ARE_SHORT_OF_PC_POINTS));
break;
return true;
}
return true;
player.sendPacket(SystemMessage.getSystemMessage(SystemMessageId.YOU_ARE_SHORT_OF_PC_POINTS));
break;
}
case CLAN_REPUTATION:
{
@@ -300,12 +296,12 @@ public final class MultisellData implements IXmlReader
player.sendPacket(SystemMessageId.ONLY_THE_CLAN_LEADER_IS_ENABLED);
break;
}
if (player.getClan().getReputationScore() < amount)
if (player.getClan().getReputationScore() >= amount)
{
player.sendPacket(SystemMessageId.THE_CLAN_REPUTATION_IS_TOO_LOW);
break;
return true;
}
return true;
player.sendPacket(SystemMessageId.THE_CLAN_REPUTATION_IS_TOO_LOW);
break;
}
case FAME:
{
@@ -317,12 +313,12 @@ public final class MultisellData implements IXmlReader
}
case RAID_POINTS:
{
if (player.getRaidPoints() < amount)
if (player.getRaidPoints() >= amount)
{
player.sendPacket(SystemMessageId.NOT_ENOUGH_RAID_POINTS);
break;
return true;
}
return true;
player.sendPacket(SystemMessageId.NOT_ENOUGH_RAID_POINTS);
break;
}
}
return false;

View File

@@ -510,15 +510,7 @@ public class NpcData implements IXmlReader
parameters.putIfAbsent("Privates", _minionData._tempMinions.get(npcId));
}
if (parameters != null)
{
// Using unmodifiable map parameters of template are not meant to be changed at runtime.
template.setParameters(new StatsSet(Collections.unmodifiableMap(parameters)));
}
else
{
template.setParameters(StatsSet.EMPTY_STATSET);
}
template.setParameters(parameters != null ? new StatsSet(Collections.unmodifiableMap(parameters)) : StatsSet.EMPTY_STATSET);
if (skills != null)
{
@@ -645,12 +637,11 @@ public class NpcData implements IXmlReader
{
for (Node dropNode = dropListNode.getFirstChild(); dropNode != null; dropNode = dropNode.getNextSibling())
{
final NamedNodeMap attrs = dropNode.getAttributes();
switch (dropNode.getNodeName().toLowerCase())
{
case "group":
{
final GroupedGeneralDropItem dropItem = dropListScope.newGroupedDropItem(parseDouble(attrs, "chance"));
final GroupedGeneralDropItem dropItem = dropListScope.newGroupedDropItem(parseDouble(dropNode.getAttributes(), "chance"));
final List<IDropItem> groupedDropList = new ArrayList<>(2);
for (Node groupNode = dropNode.getFirstChild(); groupNode != null; groupNode = groupNode.getNextSibling())
{

View File

@@ -58,8 +58,7 @@ public final class PetDataTable implements IXmlReader
public void parseDocument(Document doc)
{
NamedNodeMap attrs;
final Node n = doc.getFirstChild();
for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling())
for (Node d = doc.getFirstChild().getFirstChild(); d != null; d = d.getNextSibling())
{
if (d.getNodeName().equals("pet"))
{
@@ -174,11 +173,7 @@ public final class PetDataTable implements IXmlReader
public L2PetLevelData getPetLevelData(int petId, int petLevel)
{
final L2PetData pd = getPetData(petId);
if (pd != null)
{
return pd.getPetLevelData(petLevel);
}
return null;
return pd != null ? pd.getPetLevelData(petLevel) : null;
}
/**

View File

@@ -71,12 +71,12 @@ public final class PlayerXpPercentLostData implements IXmlReader
public double getXpPercent(int level)
{
if (level > _maxlevel)
if (level <= _maxlevel)
{
LOGGER.warning("Require to high level inside PlayerXpPercentLostData (" + level + ")");
return _playerXpPercentLost[_maxlevel];
return _playerXpPercentLost[level];
}
return _playerXpPercentLost[level];
LOGGER.warning("Require to high level inside PlayerXpPercentLostData (" + level + ")");
return _playerXpPercentLost[_maxlevel];
}
/**

View File

@@ -51,15 +51,7 @@ public class PrimeShopData implements IXmlReader
{
_primeItems.clear();
parseDatapackFile("PrimeShop.xml");
if (_primeItems.size() > 0)
{
LOGGER.info(getClass().getSimpleName() + ": Loaded " + _primeItems.size() + " items");
}
else
{
LOGGER.info(getClass().getSimpleName() + ": System is disabled.");
}
LOGGER.info(_primeItems.size() > 0 ? getClass().getSimpleName() + ": Loaded " + _primeItems.size() + " items" : getClass().getSimpleName() + ": System is disabled.");
}
@Override

View File

@@ -161,9 +161,7 @@ public class RecipeData implements IXmlReader
}
else if ("ingredient".equalsIgnoreCase(c.getNodeName()))
{
final int ingId = Integer.parseInt(c.getAttributes().getNamedItem("id").getNodeValue());
final int ingCount = Integer.parseInt(c.getAttributes().getNamedItem("count").getNodeValue());
recipePartList.add(new L2RecipeInstance(ingId, ingCount));
recipePartList.add(new L2RecipeInstance(Integer.parseInt(c.getAttributes().getNamedItem("id").getNodeValue()), Integer.parseInt(c.getAttributes().getNamedItem("count").getNodeValue())));
}
else if ("production".equalsIgnoreCase(c.getNodeName()))
{

View File

@@ -49,11 +49,12 @@ public class SiegeScheduleData implements IXmlReader
_scheduleData.clear();
parseDatapackFile("../config/SiegeSchedule.xml");
LOGGER.log(Level.INFO, getClass().getSimpleName() + ": Loaded: " + _scheduleData.size() + " siege schedulers.");
if (_scheduleData.isEmpty())
if (!_scheduleData.isEmpty())
{
_scheduleData.add(new SiegeScheduleDate(new StatsSet()));
LOGGER.log(Level.INFO, getClass().getSimpleName() + ": Emergency Loaded: " + _scheduleData.size() + " default siege schedulers.");
return;
}
_scheduleData.add(new SiegeScheduleDate(new StatsSet()));
LOGGER.log(Level.INFO, getClass().getSimpleName() + ": Emergency Loaded: " + _scheduleData.size() + " default siege schedulers.");
}
@Override
@@ -76,12 +77,9 @@ public class SiegeScheduleData implements IXmlReader
final Node node = attrs.item(i);
final String key = node.getNodeName();
String val = node.getNodeValue();
if ("day".equals(key))
if ("day".equals(key) && !Util.isDigit(val))
{
if (!Util.isDigit(val))
{
val = Integer.toString(getValueForField(val));
}
val = Integer.toString(getValueForField(val));
}
set.set(key, val);
}
@@ -121,5 +119,4 @@ public class SiegeScheduleData implements IXmlReader
{
protected static final SiegeScheduleData _instance = new SiegeScheduleData();
}
}

View File

@@ -638,11 +638,7 @@ public final class SkillTreesData implements IXmlReader
continue;
}
final Skill oldSkill = player.getKnownSkill(skill.getSkillId());
if ((oldSkill != null) && (oldSkill.getLevel() == (skill.getSkillLevel() - 1)))
{
return true;
}
else if ((oldSkill == null) && (skill.getSkillLevel() == 1))
if (((oldSkill != null) && (oldSkill.getLevel() == (skill.getSkillLevel() - 1))) || ((oldSkill == null) && (skill.getSkillLevel() == 1)))
{
return true;
}
@@ -789,8 +785,7 @@ public final class SkillTreesData implements IXmlReader
{
for (L2SkillLearn s : learnable)
{
final Skill sk = SkillData.getInstance().getSkill(s.getSkillId(), s.getSkillLevel());
holder.addSkill(sk);
holder.addSkill(SkillData.getInstance().getSkill(s.getSkillId(), s.getSkillLevel()));
}
// Get new available skills, some skills depend of previous skills to be available.
@@ -908,9 +903,7 @@ public final class SkillTreesData implements IXmlReader
for (L2SkillLearn skill : revelationSkills.values())
{
final Skill oldSkill = player.getSkills().get(skill.getSkillId());
if (oldSkill == null)
if (player.getSkills().get(skill.getSkillId()) == null)
{
result.add(skill);
}
@@ -1398,11 +1391,7 @@ public final class SkillTreesData implements IXmlReader
*/
public L2SkillLearn getTransferSkill(int id, int lvl, ClassId classId)
{
if (_transferSkillTrees.get(classId) != null)
{
return _transferSkillTrees.get(classId).get(SkillData.getSkillHashCode(id, lvl));
}
return null;
return _transferSkillTrees.get(classId) != null ? _transferSkillTrees.get(classId).get(SkillData.getSkillHashCode(id, lvl)) : null;
}
/**
@@ -1497,12 +1486,9 @@ public final class SkillTreesData implements IXmlReader
{
for (L2SkillLearn s : skillTree.values())
{
if ((player.getLevel() < s.getGetLevel()) || (player.getDualClassLevel() < s.getDualClassLevel()))
if (((player.getLevel() < s.getGetLevel()) || (player.getDualClassLevel() < s.getDualClassLevel())) && ((minLevel == 0) || ((minLevel > s.getGetLevel()) && (minLevel > s.getDualClassLevel()))))
{
if ((minLevel == 0) || ((minLevel > s.getGetLevel()) && (minLevel > s.getDualClassLevel())))
{
minLevel = s.getGetLevel();
}
minLevel = s.getGetLevel();
}
}
}

View File

@@ -124,9 +124,7 @@ public final class TransformData implements IXmlReader
if ("skill".equals(s.getNodeName()))
{
attrs = s.getAttributes();
final int skillId = parseInteger(attrs, "id");
final int skillLevel = parseInteger(attrs, "level");
templateData.addSkill(new SkillHolder(skillId, skillLevel));
templateData.addSkill(new SkillHolder(parseInteger(attrs, "id"), parseInteger(attrs, "level")));
}
}
break;
@@ -155,10 +153,7 @@ public final class TransformData implements IXmlReader
if ("skill".equals(s.getNodeName()))
{
attrs = s.getAttributes();
final int skillId = parseInteger(attrs, "id");
final int skillLevel = parseInteger(attrs, "level");
final int minLevel = parseInteger(attrs, "minLevel");
templateData.addAdditionalSkill(new AdditionalSkillHolder(skillId, skillLevel, minLevel));
templateData.addAdditionalSkill(new AdditionalSkillHolder(parseInteger(attrs, "id"), parseInteger(attrs, "level"), parseInteger(attrs, "minLevel")));
}
}
break;
@@ -175,9 +170,7 @@ public final class TransformData implements IXmlReader
if ("item".equals(s.getNodeName()))
{
attrs = s.getAttributes();
final int itemId = parseInteger(attrs, "id");
final boolean allowed = parseBoolean(attrs, "allowed");
templateData.addAdditionalItem(new AdditionalItemHolder(itemId, allowed));
templateData.addAdditionalItem(new AdditionalItemHolder(parseInteger(attrs, "id"), parseBoolean(attrs, "allowed")));
}
}
break;

View File

@@ -321,170 +321,77 @@ public class AugmentationData
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
factory.setIgnoringComments(true);
final File aFile = new File(Config.DATAPACK_ROOT + "/stats/augmentation/retailchances.xml");
if (aFile.exists())
{
Document aDoc = null;
try
{
aDoc = factory.newDocumentBuilder().parse(aFile);
}
catch (Exception e)
{
e.printStackTrace();
return;
}
String aWeaponType = null;
int aStoneId = 0;
int aVariationId = 0;
int aCategoryChance = 0;
int aAugmentId = 0;
float aAugmentChance = 0;
for (Node l = aDoc.getFirstChild(); l != null; l = l.getNextSibling())
{
if (l.getNodeName().equals("list"))
{
NamedNodeMap aNodeAttributes = null;
for (Node n = l.getFirstChild(); n != null; n = n.getNextSibling())
{
if (n.getNodeName().equals("weapon"))
{
aNodeAttributes = n.getAttributes();
aWeaponType = aNodeAttributes.getNamedItem("type").getNodeValue();
for (Node c = n.getFirstChild(); c != null; c = c.getNextSibling())
{
if (c.getNodeName().equals("stone"))
{
aNodeAttributes = c.getAttributes();
aStoneId = Integer.parseInt(aNodeAttributes.getNamedItem("id").getNodeValue());
for (Node v = c.getFirstChild(); v != null; v = v.getNextSibling())
{
if (v.getNodeName().equals("variation"))
{
aNodeAttributes = v.getAttributes();
aVariationId = Integer.parseInt(aNodeAttributes.getNamedItem("id").getNodeValue());
for (Node j = v.getFirstChild(); j != null; j = j.getNextSibling())
{
if (j.getNodeName().equals("category"))
{
aNodeAttributes = j.getAttributes();
aCategoryChance = Integer.parseInt(aNodeAttributes.getNamedItem("probability").getNodeValue());
for (Node e = j.getFirstChild(); e != null; e = e.getNextSibling())
{
if (e.getNodeName().equals("augment"))
{
aNodeAttributes = e.getAttributes();
aAugmentId = Integer.parseInt(aNodeAttributes.getNamedItem("id").getNodeValue());
aAugmentChance = Float.parseFloat(aNodeAttributes.getNamedItem("chance").getNodeValue());
_augmentationChances.add(new AugmentationChance(aWeaponType, aStoneId, aVariationId, aCategoryChance, aAugmentId, aAugmentChance));
}
}
}
}
}
}
}
}
}
}
}
}
}
else
if (!aFile.exists())
{
LOGGER.log(Level.WARNING, getClass().getSimpleName() + ": ERROR The retailchances.xml data file is missing.");
return;
}
}
if (Config.RETAIL_LIKE_AUGMENTATION_ACCESSORY)
{
final DocumentBuilderFactory factory3 = DocumentBuilderFactory.newInstance();
factory3.setValidating(false);
factory3.setIgnoringComments(true);
final File aFile3 = new File(Config.DATAPACK_ROOT + "/stats/augmentation/retailchances_accessory.xml");
if (aFile3.exists())
Document aDoc = null;
try
{
Document aDoc = null;
try
aDoc = factory.newDocumentBuilder().parse(aFile);
}
catch (Exception e)
{
e.printStackTrace();
return;
}
String aWeaponType = null;
int aStoneId = 0;
int aVariationId = 0;
int aCategoryChance = 0;
int aAugmentId = 0;
float aAugmentChance = 0;
for (Node l = aDoc.getFirstChild(); l != null; l = l.getNextSibling())
{
if (l.getNodeName().equals("list"))
{
aDoc = factory3.newDocumentBuilder().parse(aFile3);
}
catch (Exception e)
{
e.printStackTrace();
return;
}
String aWeaponType = null;
int aStoneId = 0;
int aVariationId = 0;
int aCategoryChance = 0;
int aAugmentId = 0;
float aAugmentChance = 0;
for (Node l = aDoc.getFirstChild(); l != null; l = l.getNextSibling())
{
if (l.getNodeName().equals("list"))
NamedNodeMap aNodeAttributes = null;
for (Node n = l.getFirstChild(); n != null; n = n.getNextSibling())
{
NamedNodeMap aNodeAttributes = null;
for (Node n = l.getFirstChild(); n != null; n = n.getNextSibling())
if (n.getNodeName().equals("weapon"))
{
if (n.getNodeName().equals("weapon"))
aNodeAttributes = n.getAttributes();
aWeaponType = aNodeAttributes.getNamedItem("type").getNodeValue();
for (Node c = n.getFirstChild(); c != null; c = c.getNextSibling())
{
aNodeAttributes = n.getAttributes();
aWeaponType = aNodeAttributes.getNamedItem("type").getNodeValue();
for (Node c = n.getFirstChild(); c != null; c = c.getNextSibling())
if (c.getNodeName().equals("stone"))
{
if (c.getNodeName().equals("stone"))
aNodeAttributes = c.getAttributes();
aStoneId = Integer.parseInt(aNodeAttributes.getNamedItem("id").getNodeValue());
for (Node v = c.getFirstChild(); v != null; v = v.getNextSibling())
{
aNodeAttributes = c.getAttributes();
aStoneId = Integer.parseInt(aNodeAttributes.getNamedItem("id").getNodeValue());
for (Node v = c.getFirstChild(); v != null; v = v.getNextSibling())
if (v.getNodeName().equals("variation"))
{
if (v.getNodeName().equals("variation"))
aNodeAttributes = v.getAttributes();
aVariationId = Integer.parseInt(aNodeAttributes.getNamedItem("id").getNodeValue());
for (Node j = v.getFirstChild(); j != null; j = j.getNextSibling())
{
aNodeAttributes = v.getAttributes();
aVariationId = Integer.parseInt(aNodeAttributes.getNamedItem("id").getNodeValue());
for (Node j = v.getFirstChild(); j != null; j = j.getNextSibling())
if (j.getNodeName().equals("category"))
{
if (j.getNodeName().equals("category"))
aNodeAttributes = j.getAttributes();
aCategoryChance = Integer.parseInt(aNodeAttributes.getNamedItem("probability").getNodeValue());
for (Node e = j.getFirstChild(); e != null; e = e.getNextSibling())
{
aNodeAttributes = j.getAttributes();
aCategoryChance = Integer.parseInt(aNodeAttributes.getNamedItem("probability").getNodeValue());
for (Node e = j.getFirstChild(); e != null; e = e.getNextSibling())
if (e.getNodeName().equals("augment"))
{
if (e.getNodeName().equals("augment"))
{
aNodeAttributes = e.getAttributes();
aAugmentId = Integer.parseInt(aNodeAttributes.getNamedItem("id").getNodeValue());
aAugmentChance = Float.parseFloat(aNodeAttributes.getNamedItem("chance").getNodeValue());
_augmentationChancesAcc.add(new augmentationChanceAcc(aWeaponType, aStoneId, aVariationId, aCategoryChance, aAugmentId, aAugmentChance));
}
aNodeAttributes = e.getAttributes();
aAugmentId = Integer.parseInt(aNodeAttributes.getNamedItem("id").getNodeValue());
aAugmentChance = Float.parseFloat(aNodeAttributes.getNamedItem("chance").getNodeValue());
_augmentationChances.add(new AugmentationChance(aWeaponType, aStoneId, aVariationId, aCategoryChance, aAugmentId, aAugmentChance));
}
}
}
@@ -497,10 +404,94 @@ public class AugmentationData
}
}
}
else
}
if (!Config.RETAIL_LIKE_AUGMENTATION_ACCESSORY)
{
return;
}
final DocumentBuilderFactory factory3 = DocumentBuilderFactory.newInstance();
factory3.setValidating(false);
factory3.setIgnoringComments(true);
final File aFile3 = new File(Config.DATAPACK_ROOT + "/stats/augmentation/retailchances_accessory.xml");
if (!aFile3.exists())
{
LOGGER.log(Level.WARNING, getClass().getSimpleName() + ": ERROR The retailchances_accessory.xml data file is missing.");
return;
}
Document aDoc = null;
try
{
aDoc = factory3.newDocumentBuilder().parse(aFile3);
}
catch (Exception e)
{
e.printStackTrace();
return;
}
String aWeaponType = null;
int aStoneId = 0;
int aVariationId = 0;
int aCategoryChance = 0;
int aAugmentId = 0;
float aAugmentChance = 0;
for (Node l = aDoc.getFirstChild(); l != null; l = l.getNextSibling())
{
if (l.getNodeName().equals("list"))
{
LOGGER.log(Level.WARNING, getClass().getSimpleName() + ": ERROR The retailchances_accessory.xml data file is missing.");
return;
NamedNodeMap aNodeAttributes = null;
for (Node n = l.getFirstChild(); n != null; n = n.getNextSibling())
{
if (n.getNodeName().equals("weapon"))
{
aNodeAttributes = n.getAttributes();
aWeaponType = aNodeAttributes.getNamedItem("type").getNodeValue();
for (Node c = n.getFirstChild(); c != null; c = c.getNextSibling())
{
if (c.getNodeName().equals("stone"))
{
aNodeAttributes = c.getAttributes();
aStoneId = Integer.parseInt(aNodeAttributes.getNamedItem("id").getNodeValue());
for (Node v = c.getFirstChild(); v != null; v = v.getNextSibling())
{
if (v.getNodeName().equals("variation"))
{
aNodeAttributes = v.getAttributes();
aVariationId = Integer.parseInt(aNodeAttributes.getNamedItem("id").getNodeValue());
for (Node j = v.getFirstChild(); j != null; j = j.getNextSibling())
{
if (j.getNodeName().equals("category"))
{
aNodeAttributes = j.getAttributes();
aCategoryChance = Integer.parseInt(aNodeAttributes.getNamedItem("probability").getNodeValue());
for (Node e = j.getFirstChild(); e != null; e = e.getNextSibling())
{
if (e.getNodeName().equals("augment"))
{
aNodeAttributes = e.getAttributes();
aAugmentId = Integer.parseInt(aNodeAttributes.getNamedItem("id").getNodeValue());
aAugmentChance = Float.parseFloat(aNodeAttributes.getNamedItem("chance").getNodeValue());
_augmentationChancesAcc.add(new augmentationChanceAcc(aWeaponType, aStoneId, aVariationId, aCategoryChance, aAugmentId, aAugmentChance));
}
}
}
}
}
}
}
}
}
}
}
}
}

View File

@@ -29,7 +29,6 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
@@ -75,32 +74,33 @@ public final class BotReportTable
BotReportTable()
{
if (Config.BOTREPORT_ENABLE)
if (!Config.BOTREPORT_ENABLE)
{
_ipRegistry = new HashMap<>();
_charRegistry = new ConcurrentHashMap<>();
_reports = new ConcurrentHashMap<>();
_punishments = new ConcurrentHashMap<>();
try
{
final File punishments = new File("./config/BotReportPunishments.xml");
if (!punishments.exists())
{
throw new FileNotFoundException(punishments.getName());
}
final SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
parser.parse(punishments, new PunishmentsLoader());
}
catch (Exception e)
{
LOGGER.log(Level.WARNING, "BotReportTable: Could not load punishments from /config/BotReportPunishments.xml", e);
}
loadReportedCharData();
scheduleResetPointTask();
return;
}
_ipRegistry = new HashMap<>();
_charRegistry = new ConcurrentHashMap<>();
_reports = new ConcurrentHashMap<>();
_punishments = new ConcurrentHashMap<>();
try
{
final File punishments = new File("./config/BotReportPunishments.xml");
if (!punishments.exists())
{
throw new FileNotFoundException(punishments.getName());
}
SAXParserFactory.newInstance().newSAXParser().parse(punishments, new PunishmentsLoader());
}
catch (Exception e)
{
LOGGER.log(Level.WARNING, "BotReportTable: Could not load punishments from /config/BotReportPunishments.xml", e);
}
loadReportedCharData();
scheduleResetPointTask();
}
/**
@@ -186,12 +186,11 @@ public final class BotReportTable
for (Map.Entry<Integer, ReportedCharData> entrySet : _reports.entrySet())
{
final Map<Integer, Long> reportTable = entrySet.getValue()._reporters;
for (int reporterId : reportTable.keySet())
for (int reporterId : entrySet.getValue()._reporters.keySet())
{
ps.setInt(1, entrySet.getKey());
ps.setInt(2, reporterId);
ps.setLong(3, reportTable.get(reporterId));
ps.setLong(3, entrySet.getValue()._reporters.get(reporterId));
ps.execute();
}
}
@@ -360,17 +359,19 @@ public final class BotReportTable
*/
private void punishBot(L2PcInstance bot, PunishHolder ph)
{
if (ph != null)
if (ph == null)
{
ph._punish.applyEffects(bot, bot);
if (ph._systemMessageId > -1)
{
final SystemMessageId id = SystemMessageId.getSystemMessageId(ph._systemMessageId);
if (id != null)
{
bot.sendPacket(id);
}
}
return;
}
ph._punish.applyEffects(bot, bot);
if (ph._systemMessageId <= -1)
{
return;
}
final SystemMessageId id = SystemMessageId.getSystemMessageId(ph._systemMessageId);
if (id != null)
{
bot.sendPacket(id);
}
}
@@ -461,11 +462,7 @@ public final class BotReportTable
*/
private static boolean timeHasPassed(Map<Integer, Long> map, int objectId)
{
if (map.containsKey(objectId))
{
return (System.currentTimeMillis() - map.get(objectId)) > Config.BOTREPORT_REPORT_DELAY;
}
return true;
return !map.containsKey(objectId) || ((System.currentTimeMillis() - map.get(objectId)) > Config.BOTREPORT_REPORT_DELAY);
}
/**
@@ -562,32 +559,33 @@ public final class BotReportTable
@Override
public void startElement(String uri, String localName, String qName, Attributes attr)
{
if (qName.equals("punishment"))
if (!qName.equals("punishment"))
{
int reportCount = -1, skillId = -1, skillLevel = 1, sysMessage = -1;
try
return;
}
int reportCount = -1, skillId = -1, skillLevel = 1, sysMessage = -1;
try
{
reportCount = Integer.parseInt(attr.getValue("neededReportCount"));
skillId = Integer.parseInt(attr.getValue("skillId"));
final String level = attr.getValue("skillLevel");
final String systemMessageId = attr.getValue("sysMessageId");
if (level != null)
{
reportCount = Integer.parseInt(attr.getValue("neededReportCount"));
skillId = Integer.parseInt(attr.getValue("skillId"));
final String level = attr.getValue("skillLevel");
final String systemMessageId = attr.getValue("sysMessageId");
if (level != null)
{
skillLevel = Integer.parseInt(level);
}
if (systemMessageId != null)
{
sysMessage = Integer.parseInt(systemMessageId);
}
}
catch (Exception e)
{
e.printStackTrace();
skillLevel = Integer.parseInt(level);
}
addPunishment(reportCount, skillId, skillLevel, sysMessage);
if (systemMessageId != null)
{
sysMessage = Integer.parseInt(systemMessageId);
}
}
catch (Exception e)
{
e.printStackTrace();
}
addPunishment(reportCount, skillId, skillLevel, sysMessage);
}
}

View File

@@ -188,12 +188,7 @@ public class ItemTable
*/
public L2Item getTemplate(int id)
{
if ((id >= _allTemplates.length) || (id < 0))
{
return null;
}
return _allTemplates[id];
return (id >= _allTemplates.length) || (id < 0) ? null : _allTemplates[id];
}
/**
@@ -218,11 +213,9 @@ public class ItemTable
ScheduledFuture<?> itemLootShedule;
if ((reference instanceof L2Attackable) && ((L2Attackable) reference).isRaid()) // loot privilege for raids
{
final L2Attackable raid = (L2Attackable) reference;
// if in CommandChannel and was killing a World/RaidBoss
if ((raid.getFirstCommandChannelAttacked() != null) && !Config.AUTO_LOOT_RAIDS)
if ((((L2Attackable) reference).getFirstCommandChannelAttacked() != null) && !Config.AUTO_LOOT_RAIDS)
{
item.setOwnerId(raid.getFirstCommandChannelAttacked().getLeaderObjectId());
item.setOwnerId(((L2Attackable) reference).getFirstCommandChannelAttacked().getLeaderObjectId());
itemLootShedule = ThreadPoolManager.getInstance().scheduleGeneral(new ResetOwner(item), Config.LOOT_RAIDS_PRIVILEGE_INTERVAL);
item.setItemLootShedule(itemLootShedule);
}
@@ -249,40 +242,33 @@ public class ItemTable
item.setCount(count);
}
if (Config.LOG_ITEMS && !process.equals("Reset"))
if (Config.LOG_ITEMS && !process.equals("Reset") && (!Config.LOG_ITEMS_SMALL_LOG || (Config.LOG_ITEMS_SMALL_LOG && (item.isEquipable() || (item.getId() == ADENA_ID)))))
{
if (!Config.LOG_ITEMS_SMALL_LOG || (Config.LOG_ITEMS_SMALL_LOG && (item.isEquipable() || (item.getId() == ADENA_ID))))
final LogRecord record = new LogRecord(Level.INFO, "CREATE:" + process);
record.setLoggerName("item");
record.setParameters(new Object[]
{
final LogRecord record = new LogRecord(Level.INFO, "CREATE:" + process);
record.setLoggerName("item");
record.setParameters(new Object[]
{
item,
actor,
reference
});
LOGGER_ITEMS.log(record);
}
item,
actor,
reference
});
LOGGER_ITEMS.log(record);
}
if (actor != null)
if ((actor != null) && actor.isGM())
{
if (actor.isGM())
String referenceName = "no-reference";
if (reference instanceof L2Object)
{
String referenceName = "no-reference";
if (reference instanceof L2Object)
{
referenceName = (((L2Object) reference).getName() != null ? ((L2Object) reference).getName() : "no-name");
}
else if (reference instanceof String)
{
referenceName = (String) reference;
}
final String targetName = (actor.getTarget() != null ? actor.getTarget().getName() : "no-target");
if (Config.GMAUDIT)
{
GMAudit.auditGMAction(actor.getName() + " [" + actor.getObjectId() + "]", process + "(id: " + itemId + " count: " + count + " name: " + item.getItemName() + " objId: " + item.getObjectId() + ")", targetName, "L2Object referencing this action is: " + referenceName);
}
referenceName = (((L2Object) reference).getName() != null ? ((L2Object) reference).getName() : "no-name");
}
else if (reference instanceof String)
{
referenceName = (String) reference;
}
if (Config.GMAUDIT)
{
GMAudit.auditGMAction(actor.getName() + " [" + actor.getObjectId() + "]", process + "(id: " + itemId + " count: " + count + " name: " + item.getItemName() + " objId: " + item.getObjectId() + ")", (actor.getTarget() != null ? actor.getTarget().getName() : "no-target"), "L2Object referencing this action is: " + referenceName);
}
}
@@ -322,41 +308,34 @@ public class ItemTable
L2World.getInstance().removeObject(item);
IdFactory.getInstance().releaseId(item.getObjectId());
if (Config.LOG_ITEMS)
if (Config.LOG_ITEMS && (!Config.LOG_ITEMS_SMALL_LOG || (Config.LOG_ITEMS_SMALL_LOG && (item.isEquipable() || (item.getId() == ADENA_ID)))))
{
if (!Config.LOG_ITEMS_SMALL_LOG || (Config.LOG_ITEMS_SMALL_LOG && (item.isEquipable() || (item.getId() == ADENA_ID))))
final LogRecord record = new LogRecord(Level.INFO, "DELETE:" + process);
record.setLoggerName("item");
record.setParameters(new Object[]
{
final LogRecord record = new LogRecord(Level.INFO, "DELETE:" + process);
record.setLoggerName("item");
record.setParameters(new Object[]
{
item,
"PrevCount(" + old + ")",
actor,
reference
});
LOGGER_ITEMS.log(record);
}
item,
"PrevCount(" + old + ")",
actor,
reference
});
LOGGER_ITEMS.log(record);
}
if (actor != null)
if ((actor != null) && actor.isGM())
{
if (actor.isGM())
String referenceName = "no-reference";
if (reference instanceof L2Object)
{
String referenceName = "no-reference";
if (reference instanceof L2Object)
{
referenceName = (((L2Object) reference).getName() != null ? ((L2Object) reference).getName() : "no-name");
}
else if (reference instanceof String)
{
referenceName = (String) reference;
}
final String targetName = (actor.getTarget() != null ? actor.getTarget().getName() : "no-target");
if (Config.GMAUDIT)
{
GMAudit.auditGMAction(actor.getName() + " [" + actor.getObjectId() + "]", process + "(id: " + item.getId() + " count: " + item.getCount() + " itemObjId: " + item.getObjectId() + ")", targetName, "L2Object referencing this action is: " + referenceName);
}
referenceName = (((L2Object) reference).getName() != null ? ((L2Object) reference).getName() : "no-name");
}
else if (reference instanceof String)
{
referenceName = (String) reference;
}
if (Config.GMAUDIT)
{
GMAudit.auditGMAction(actor.getName() + " [" + actor.getObjectId() + "]", process + "(id: " + item.getId() + " count: " + item.getCount() + " itemObjId: " + item.getObjectId() + ")", (actor.getTarget() != null ? actor.getTarget().getName() : "no-target"), "L2Object referencing this action is: " + referenceName);
}
}

View File

@@ -77,84 +77,87 @@ public class MerchantPriceConfigTable implements InstanceListManager
factory.setValidating(false);
factory.setIgnoringComments(true);
final File file = new File(Config.DATAPACK_ROOT + "/" + MPCS_FILE);
if (file.exists())
if (!file.exists())
{
int defaultPriceConfigId;
final Document doc = factory.newDocumentBuilder().parse(file);
Node n = doc.getDocumentElement();
final Node dpcNode = n.getAttributes().getNamedItem("defaultPriceConfig");
if (dpcNode == null)
{
throw new IllegalStateException("merchantPriceConfig must define an 'defaultPriceConfig'");
}
defaultPriceConfigId = Integer.parseInt(dpcNode.getNodeValue());
MerchantPriceConfig mpc;
for (n = n.getFirstChild(); n != null; n = n.getNextSibling())
{
mpc = parseMerchantPriceConfig(n);
if (mpc != null)
{
_mpcs.put(mpc.getId(), mpc);
}
}
final MerchantPriceConfig defaultMpc = this.getMerchantPriceConfig(defaultPriceConfigId);
if (defaultMpc == null)
{
throw new IllegalStateException("'defaultPriceConfig' points to an non-loaded priceConfig");
}
_defaultMpc = defaultMpc;
return;
}
int defaultPriceConfigId;
final Document doc = factory.newDocumentBuilder().parse(file);
Node n = doc.getDocumentElement();
final Node dpcNode = n.getAttributes().getNamedItem("defaultPriceConfig");
if (dpcNode == null)
{
throw new IllegalStateException("merchantPriceConfig must define an 'defaultPriceConfig'");
}
defaultPriceConfigId = Integer.parseInt(dpcNode.getNodeValue());
MerchantPriceConfig mpc;
for (n = n.getFirstChild(); n != null; n = n.getNextSibling())
{
mpc = parseMerchantPriceConfig(n);
if (mpc != null)
{
_mpcs.put(mpc.getId(), mpc);
}
}
final MerchantPriceConfig defaultMpc = this.getMerchantPriceConfig(defaultPriceConfigId);
if (defaultMpc == null)
{
throw new IllegalStateException("'defaultPriceConfig' points to an non-loaded priceConfig");
}
_defaultMpc = defaultMpc;
}
private MerchantPriceConfig parseMerchantPriceConfig(Node n)
{
if (n.getNodeName().equals("priceConfig"))
if (!n.getNodeName().equals("priceConfig"))
{
final int id;
final int baseTax;
int castleId = -1;
int zoneId = -1;
final String name;
Node node = n.getAttributes().getNamedItem("id");
if (node == null)
{
throw new IllegalStateException("Must define the priceConfig 'id'");
}
id = Integer.parseInt(node.getNodeValue());
node = n.getAttributes().getNamedItem("name");
if (node == null)
{
throw new IllegalStateException("Must define the priceConfig 'name'");
}
name = node.getNodeValue();
node = n.getAttributes().getNamedItem("baseTax");
if (node == null)
{
throw new IllegalStateException("Must define the priceConfig 'baseTax'");
}
baseTax = Integer.parseInt(node.getNodeValue());
node = n.getAttributes().getNamedItem("castleId");
if (node != null)
{
castleId = Integer.parseInt(node.getNodeValue());
}
node = n.getAttributes().getNamedItem("zoneId");
if (node != null)
{
zoneId = Integer.parseInt(node.getNodeValue());
}
return new MerchantPriceConfig(id, name, baseTax, castleId, zoneId);
return null;
}
return null;
final int id;
final int baseTax;
int castleId = -1;
int zoneId = -1;
final String name;
Node node = n.getAttributes().getNamedItem("id");
if (node == null)
{
throw new IllegalStateException("Must define the priceConfig 'id'");
}
id = Integer.parseInt(node.getNodeValue());
node = n.getAttributes().getNamedItem("name");
if (node == null)
{
throw new IllegalStateException("Must define the priceConfig 'name'");
}
name = node.getNodeValue();
node = n.getAttributes().getNamedItem("baseTax");
if (node == null)
{
throw new IllegalStateException("Must define the priceConfig 'baseTax'");
}
baseTax = Integer.parseInt(node.getNodeValue());
node = n.getAttributes().getNamedItem("castleId");
if (node != null)
{
castleId = Integer.parseInt(node.getNodeValue());
}
node = n.getAttributes().getNamedItem("zoneId");
if (node != null)
{
zoneId = Integer.parseInt(node.getNodeValue());
}
return new MerchantPriceConfig(id, name, baseTax, castleId, zoneId);
}
@Override

View File

@@ -46,16 +46,17 @@ public class NpcPersonalAIData
*/
public void storeData(L2Spawn spawnDat, Map<String, Integer> data)
{
if ((data != null) && !data.isEmpty())
if ((data == null) || data.isEmpty())
{
// check for spawn name. Since spawn name is key for AI Data, generate random name, if spawn name isn't specified
if (spawnDat.getName() == null)
{
spawnDat.setName(Long.toString(Rnd.nextLong()));
}
_AIData.put(spawnDat.getName(), data);
return;
}
if (spawnDat.getName() == null)
{
spawnDat.setName(Long.toString(Rnd.nextLong()));
}
_AIData.put(spawnDat.getName(), data);
}
/**
@@ -88,34 +89,36 @@ public class NpcPersonalAIData
*/
public void initializeNpcParameters(L2Npc npc, L2Spawn spawn, String spawnName)
{
if (_AIData.containsKey(spawnName))
if (!_AIData.containsKey(spawnName))
{
final Map<String, Integer> map = _AIData.get(spawnName);
try
return;
}
final Map<String, Integer> map = _AIData.get(spawnName);
try
{
for (String key : map.keySet())
{
for (String key : map.keySet())
switch (key)
{
switch (key)
case "disableRandomAnimation":
{
case "disableRandomAnimation":
{
npc.setRandomAnimationEnabled((map.get(key) == 0));
break;
}
case "disableRandomWalk":
{
npc.setIsNoRndWalk((map.get(key) == 1));
spawn.setIsNoRndWalk((map.get(key) == 1));
break;
}
npc.setRandomAnimationEnabled((map.get(key) == 0));
break;
}
case "disableRandomWalk":
{
npc.setIsNoRndWalk((map.get(key) == 1));
spawn.setIsNoRndWalk((map.get(key) == 1));
break;
}
}
}
catch (Exception e)
{
// Do nothing
}
}
catch (Exception e)
{
// Do nothing
}
}

View File

@@ -78,8 +78,7 @@ public final class SkillData
}
// only non-enchanted skills
final int maxLvl = getMaxLevel(skillId);
if (skillLvl > maxLvl)
if (skillLvl > getMaxLevel(skillId))
{
_skillMaxLevel.put(skillId, skillLvl);
}

View File

@@ -64,21 +64,23 @@ public final class SpawnTable implements IXmlReader
@Override
public void load()
{
if (!Config.ALT_DEV_NO_SPAWNS)
if (Config.ALT_DEV_NO_SPAWNS)
{
fillSpawnTable(false);
final int spawnCount = _spawnTable.size();
LOGGER.info(getClass().getSimpleName() + ": Loaded " + spawnCount + " npc spawns.");
if (Config.CUSTOM_SPAWNLIST_TABLE)
{
fillSpawnTable(true);
LOGGER.info(getClass().getSimpleName() + ": Loaded " + (_spawnTable.size() - spawnCount) + " custom npc spawns.");
}
// Load XML list
parseDatapackDirectory("spawnlist", false);
LOGGER.info(getClass().getSimpleName() + ": Loaded " + _xmlSpawnCount + " npc spawns from XML.");
return;
}
fillSpawnTable(false);
final int spawnCount = _spawnTable.size();
LOGGER.info(getClass().getSimpleName() + ": Loaded " + spawnCount + " npc spawns.");
if (Config.CUSTOM_SPAWNLIST_TABLE)
{
fillSpawnTable(true);
LOGGER.info(getClass().getSimpleName() + ": Loaded " + (_spawnTable.size() - spawnCount) + " custom npc spawns.");
}
// Load XML list
parseDatapackDirectory("spawnlist", false);
LOGGER.info(getClass().getSimpleName() + ": Loaded " + _xmlSpawnCount + " npc spawns from XML.");
}
/**
@@ -89,19 +91,13 @@ public final class SpawnTable implements IXmlReader
private boolean checkTemplate(int npcId)
{
final L2NpcTemplate npcTemplate = NpcData.getInstance().getTemplate(npcId);
if (npcTemplate == null)
if (npcTemplate != null)
{
LOGGER.warning(getClass().getSimpleName() + ": Data missing in NPC table for ID: " + npcId + ".");
return false;
return !npcTemplate.isType("L2SiegeGuard") && !npcTemplate.isType("L2RaidBoss") && (Config.ALLOW_CLASS_MASTERS || !npcTemplate.isType("L2ClassMaster"));
}
if (npcTemplate.isType("L2SiegeGuard") || npcTemplate.isType("L2RaidBoss") || (!Config.ALLOW_CLASS_MASTERS && npcTemplate.isType("L2ClassMaster")))
{
// Don't spawn
return false;
}
return true;
LOGGER.warning(getClass().getSimpleName() + ": Data missing in NPC table for ID: " + npcId + ".");
// Don't spawn
return false;
}
@Override
@@ -413,27 +409,28 @@ public final class SpawnTable implements IXmlReader
{
addSpawn(spawn);
if (storeInDb)
if (!storeInDb)
{
final String spawnTable = spawn.isCustom() && Config.CUSTOM_SPAWNLIST_TABLE ? "custom_spawnlist" : "spawnlist";
try (Connection con = DatabaseFactory.getInstance().getConnection();
PreparedStatement insert = con.prepareStatement("INSERT INTO " + spawnTable + "(count,npc_templateid,locx,locy,locz,heading,respawn_delay,respawn_random,loc_id) values(?,?,?,?,?,?,?,?,?)"))
{
insert.setInt(1, spawn.getAmount());
insert.setInt(2, spawn.getId());
insert.setInt(3, spawn.getX());
insert.setInt(4, spawn.getY());
insert.setInt(5, spawn.getZ());
insert.setInt(6, spawn.getHeading());
insert.setInt(7, spawn.getRespawnDelay() / 1000);
insert.setInt(8, spawn.getRespawnMaxDelay() - spawn.getRespawnMinDelay());
insert.setInt(9, spawn.getLocationId());
insert.execute();
}
catch (Exception e)
{
LOGGER.log(Level.WARNING, getClass().getSimpleName() + ": Could not store spawn in the DB:" + e.getMessage(), e);
}
return;
}
final String spawnTable = spawn.isCustom() && Config.CUSTOM_SPAWNLIST_TABLE ? "custom_spawnlist" : "spawnlist";
try (Connection con = DatabaseFactory.getInstance().getConnection();
PreparedStatement insert = con.prepareStatement("INSERT INTO " + spawnTable + "(count,npc_templateid,locx,locy,locz,heading,respawn_delay,respawn_random,loc_id) values(?,?,?,?,?,?,?,?,?)"))
{
insert.setInt(1, spawn.getAmount());
insert.setInt(2, spawn.getId());
insert.setInt(3, spawn.getX());
insert.setInt(4, spawn.getY());
insert.setInt(5, spawn.getZ());
insert.setInt(6, spawn.getHeading());
insert.setInt(7, spawn.getRespawnDelay() / 1000);
insert.setInt(8, spawn.getRespawnMaxDelay() - spawn.getRespawnMinDelay());
insert.setInt(9, spawn.getLocationId());
insert.execute();
}
catch (Exception e)
{
LOGGER.log(Level.WARNING, getClass().getSimpleName() + ": Could not store spawn in the DB:" + e.getMessage(), e);
}
}
@@ -485,16 +482,17 @@ public final class SpawnTable implements IXmlReader
private boolean removeSpawn(L2Spawn spawn)
{
final Set<L2Spawn> set = _spawnTable.get(spawn.getId());
if (set != null)
if (set == null)
{
final boolean removed = set.remove(spawn);
if (set.isEmpty())
{
_spawnTable.remove(spawn.getId());
}
return removed;
return false;
}
return false;
final boolean removed = set.remove(spawn);
if (set.isEmpty())
{
_spawnTable.remove(spawn.getId());
}
return removed;
}
/**

View File

@@ -216,8 +216,7 @@ public abstract class DocumentBase
else if ((condition != null) && (msgId != null))
{
condition.setMessageId(Integer.decode(getValue(msgId.getNodeValue(), null)));
final Node addName = n.getAttributes().getNamedItem("addName");
if ((addName != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
if ((n.getAttributes().getNamedItem("addName") != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
{
condition.addName();
}
@@ -270,16 +269,7 @@ public abstract class DocumentBase
}
final String valueString = n.getAttributes().getNamedItem("val").getNodeValue();
double value;
if (valueString.charAt(0) == '#')
{
value = Double.parseDouble(getTableValue(valueString));
}
else
{
value = Double.parseDouble(valueString);
}
final double value = valueString.charAt(0) == '#' ? Double.parseDouble(getTableValue(valueString)) : Double.parseDouble(valueString);
final Condition applayCond = parseCondition(n.getFirstChild(), template);
final FuncTemplate ft = new FuncTemplate(attachCond, applayCond, functionName, order, stat, value);
if (template instanceof L2Item)
@@ -675,8 +665,7 @@ public abstract class DocumentBase
final ArrayList<Integer> array = new ArrayList<>(st.countTokens());
while (st.hasMoreTokens())
{
final String item = st.nextToken().trim();
array.add(Integer.decode(getValue(item, template)));
array.add(Integer.decode(getValue(st.nextToken().trim(), template)));
}
cond = joinAnd(cond, new ConditionPlayerHasClanHall(array));
break;
@@ -751,8 +740,7 @@ public abstract class DocumentBase
final ArrayList<Integer> array = new ArrayList<>(st.countTokens());
while (st.hasMoreTokens())
{
final String item = st.nextToken().trim();
array.add(Integer.decode(getValue(item, template)));
array.add(Integer.decode(getValue(st.nextToken().trim(), template)));
}
cond = joinAnd(cond, new ConditionPlayerClassIdRestriction(array));
break;
@@ -774,8 +762,7 @@ public abstract class DocumentBase
final ArrayList<Integer> array = new ArrayList<>(st.countTokens());
while (st.hasMoreTokens())
{
final String item = st.nextToken().trim();
array.add(Integer.decode(getValue(item, template)));
array.add(Integer.decode(getValue(st.nextToken().trim(), template)));
}
cond = joinAnd(cond, new ConditionPlayerInstanceId(array));
break;
@@ -798,8 +785,7 @@ public abstract class DocumentBase
final ArrayList<Integer> array = new ArrayList<>(st.countTokens());
while (st.hasMoreTokens())
{
final String item = st.nextToken().trim();
array.add(Integer.decode(getValue(item, template)));
array.add(Integer.decode(getValue(st.nextToken().trim(), template)));
}
cond = joinAnd(cond, new ConditionPlayerHasPet(array));
break;
@@ -820,9 +806,7 @@ public abstract class DocumentBase
{
npcIds[index] = Integer.parseInt(getValue(ids[index], template));
}
final int radius = Integer.parseInt(st.nextToken());
final boolean val = Boolean.parseBoolean(st.nextToken());
cond = joinAnd(cond, new ConditionPlayerRangeFromNpc(npcIds, radius, val));
cond = joinAnd(cond, new ConditionPlayerRangeFromNpc(npcIds, Integer.parseInt(st.nextToken()), Boolean.parseBoolean(st.nextToken())));
}
break;
}
@@ -902,8 +886,7 @@ public abstract class DocumentBase
final List<Integer> array = new ArrayList<>(st.countTokens());
while (st.hasMoreTokens())
{
final String item = st.nextToken().trim();
array.add(Integer.decode(getValue(item, template)));
array.add(Integer.decode(getValue(st.nextToken().trim(), template)));
}
cond = joinAnd(cond, new ConditionPlayerInsideZoneId(array));
break;
@@ -1013,8 +996,7 @@ public abstract class DocumentBase
final List<Integer> array = new ArrayList<>(st.countTokens());
while (st.hasMoreTokens())
{
final String item = st.nextToken().trim();
array.add(Integer.decode(getValue(item, null)));
array.add(Integer.decode(getValue(st.nextToken().trim(), null)));
}
cond = joinAnd(cond, new ConditionTargetClassIdRestriction(array));
break;
@@ -1103,8 +1085,7 @@ public abstract class DocumentBase
final List<Integer> array = new ArrayList<>(st.countTokens());
while (st.hasMoreTokens())
{
final String item = st.nextToken().trim();
array.add(Integer.decode(getValue(item, null)));
array.add(Integer.decode(getValue(st.nextToken().trim(), null)));
}
cond = joinAnd(cond, new ConditionTargetNpcId(array));
break;
@@ -1222,11 +1203,7 @@ public abstract class DocumentBase
final StringTokenizer st = new StringTokenizer(a.getNodeValue(), ";");
final int id = Integer.parseInt(st.nextToken().trim());
final int slot = Integer.parseInt(st.nextToken().trim());
int enchant = 0;
if (st.hasMoreTokens())
{
enchant = Integer.parseInt(st.nextToken().trim());
}
final int enchant = st.hasMoreTokens() ? Integer.parseInt(st.nextToken().trim()) : 0;
cond = joinAnd(cond, new ConditionSlotItemId(slot, id, enchant));
break;
}
@@ -1255,18 +1232,15 @@ public abstract class DocumentBase
final Node a = attrs.item(i);
if ("skill".equalsIgnoreCase(a.getNodeName()))
{
final boolean val = Boolean.parseBoolean(a.getNodeValue());
cond = joinAnd(cond, new ConditionWithSkill(val));
cond = joinAnd(cond, new ConditionWithSkill(Boolean.parseBoolean(a.getNodeValue())));
}
if ("night".equalsIgnoreCase(a.getNodeName()))
{
final boolean val = Boolean.parseBoolean(a.getNodeValue());
cond = joinAnd(cond, new ConditionGameTime(CheckGameTime.NIGHT, val));
cond = joinAnd(cond, new ConditionGameTime(CheckGameTime.NIGHT, Boolean.parseBoolean(a.getNodeValue())));
}
if ("chance".equalsIgnoreCase(a.getNodeName()))
{
final int val = Integer.decode(getValue(a.getNodeValue(), null));
cond = joinAnd(cond, new ConditionGameChance(val));
cond = joinAnd(cond, new ConditionGameChance(Integer.decode(getValue(a.getNodeValue(), null))));
}
}
if (cond == null)
@@ -1298,14 +1272,7 @@ public abstract class DocumentBase
final String name = n.getAttributes().getNamedItem("name").getNodeValue().trim();
final String value = n.getAttributes().getNamedItem("val").getNodeValue().trim();
final char ch = value.isEmpty() ? ' ' : value.charAt(0);
if ((ch == '#') || (ch == '-') || Character.isDigit(ch))
{
set.set(name, String.valueOf(getValue(value, level)));
}
else
{
set.set(name, value);
}
set.set(name, (ch == '#') || (ch == '-') || Character.isDigit(ch) ? String.valueOf(getValue(value, level)) : value);
}
protected void setExtractableSkillData(StatsSet set, String value)

View File

@@ -17,7 +17,6 @@
package com.l2jmobius.gameserver.engines.items;
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
@@ -98,12 +97,7 @@ public final class DocumentItem extends DocumentBase
final int itemId = Integer.parseInt(n.getAttributes().getNamedItem("id").getNodeValue());
final String className = n.getAttributes().getNamedItem("type").getNodeValue();
final String itemName = n.getAttributes().getNamedItem("name").getNodeValue();
String additionalName = null;
if (n.getAttributes().getNamedItem("additionalName") != null)
{
additionalName = n.getAttributes().getNamedItem("additionalName").getNodeValue();
}
final String additionalName = n.getAttributes().getNamedItem("additionalName") != null ? n.getAttributes().getNamedItem("additionalName").getNodeValue() : null;
_currentItem.id = itemId;
_currentItem.name = itemName;
_currentItem.type = className;
@@ -149,8 +143,7 @@ public final class DocumentItem extends DocumentBase
else if ((condition != null) && (msgId != null))
{
condition.setMessageId(Integer.decode(getValue(msgId.getNodeValue(), null)));
final Node addName = n.getAttributes().getNamedItem("addName");
if ((addName != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
if ((n.getAttributes().getNamedItem("addName") != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
{
condition.addName();
}
@@ -170,8 +163,7 @@ public final class DocumentItem extends DocumentBase
}
try
{
final Constructor<?> c = Class.forName("com.l2jmobius.gameserver.model.items.L2" + _currentItem.type).getConstructor(StatsSet.class);
_currentItem.item = (L2Item) c.newInstance(_currentItem.set);
_currentItem.item = (L2Item) Class.forName("com.l2jmobius.gameserver.model.items.L2" + _currentItem.type).getConstructor(StatsSet.class).newInstance(_currentItem.set);
}
catch (Exception e)
{

View File

@@ -553,8 +553,7 @@ public class DocumentSkill extends DocumentBase
else if ((condition != null) && (msgId != null))
{
condition.setMessageId(Integer.decode(getValue(msgId.getNodeValue(), null)));
final Node addName = n.getAttributes().getNamedItem("addName");
if ((addName != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
if ((n.getAttributes().getNamedItem("addName") != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
{
condition.addName();
}
@@ -611,8 +610,7 @@ public class DocumentSkill extends DocumentBase
else if ((condition != null) && (msgId != null))
{
condition.setMessageId(Integer.decode(getValue(msgId.getNodeValue(), null)));
final Node addName = n.getAttributes().getNamedItem("addName");
if ((addName != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
if ((n.getAttributes().getNamedItem("addName") != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
{
condition.addName();
}
@@ -673,8 +671,7 @@ public class DocumentSkill extends DocumentBase
else if ((condition != null) && (msgId != null))
{
condition.setMessageId(Integer.decode(getValue(msgId.getNodeValue(), null)));
final Node addName = n.getAttributes().getNamedItem("addName");
if ((addName != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
if ((n.getAttributes().getNamedItem("addName") != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
{
condition.addName();
}
@@ -731,8 +728,7 @@ public class DocumentSkill extends DocumentBase
else if ((condition != null) && (msgId != null))
{
condition.setMessageId(Integer.decode(getValue(msgId.getNodeValue(), null)));
final Node addName = n.getAttributes().getNamedItem("addName");
if ((addName != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
if ((n.getAttributes().getNamedItem("addName") != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
{
condition.addName();
}
@@ -793,8 +789,7 @@ public class DocumentSkill extends DocumentBase
else if ((condition != null) && (msgId != null))
{
condition.setMessageId(Integer.decode(getValue(msgId.getNodeValue(), null)));
final Node addName = n.getAttributes().getNamedItem("addName");
if ((addName != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
if ((n.getAttributes().getNamedItem("addName") != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
{
condition.addName();
}
@@ -847,8 +842,7 @@ public class DocumentSkill extends DocumentBase
else if ((condition != null) && (msgId != null))
{
condition.setMessageId(Integer.decode(getValue(msgId.getNodeValue(), null)));
final Node addName = n.getAttributes().getNamedItem("addName");
if ((addName != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
if ((n.getAttributes().getNamedItem("addName") != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
{
condition.addName();
}
@@ -909,8 +903,7 @@ public class DocumentSkill extends DocumentBase
else if ((condition != null) && (msgId != null))
{
condition.setMessageId(Integer.decode(getValue(msgId.getNodeValue(), null)));
final Node addName = n.getAttributes().getNamedItem("addName");
if ((addName != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
if ((n.getAttributes().getNamedItem("addName") != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
{
condition.addName();
}
@@ -967,8 +960,7 @@ public class DocumentSkill extends DocumentBase
else if ((condition != null) && (msgId != null))
{
condition.setMessageId(Integer.decode(getValue(msgId.getNodeValue(), null)));
final Node addName = n.getAttributes().getNamedItem("addName");
if ((addName != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
if ((n.getAttributes().getNamedItem("addName") != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
{
condition.addName();
}
@@ -1029,8 +1021,7 @@ public class DocumentSkill extends DocumentBase
else if ((condition != null) && (msgId != null))
{
condition.setMessageId(Integer.decode(getValue(msgId.getNodeValue(), null)));
final Node addName = n.getAttributes().getNamedItem("addName");
if ((addName != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
if ((n.getAttributes().getNamedItem("addName") != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
{
condition.addName();
}
@@ -1087,8 +1078,7 @@ public class DocumentSkill extends DocumentBase
else if ((condition != null) && (msgId != null))
{
condition.setMessageId(Integer.decode(getValue(msgId.getNodeValue(), null)));
final Node addName = n.getAttributes().getNamedItem("addName");
if ((addName != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
if ((n.getAttributes().getNamedItem("addName") != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
{
condition.addName();
}
@@ -1149,8 +1139,7 @@ public class DocumentSkill extends DocumentBase
else if ((condition != null) && (msgId != null))
{
condition.setMessageId(Integer.decode(getValue(msgId.getNodeValue(), null)));
final Node addName = n.getAttributes().getNamedItem("addName");
if ((addName != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
if ((n.getAttributes().getNamedItem("addName") != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
{
condition.addName();
}
@@ -1207,8 +1196,7 @@ public class DocumentSkill extends DocumentBase
else if ((condition != null) && (msgId != null))
{
condition.setMessageId(Integer.decode(getValue(msgId.getNodeValue(), null)));
final Node addName = n.getAttributes().getNamedItem("addName");
if ((addName != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
if ((n.getAttributes().getNamedItem("addName") != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
{
condition.addName();
}
@@ -1269,8 +1257,7 @@ public class DocumentSkill extends DocumentBase
else if ((condition != null) && (msgId != null))
{
condition.setMessageId(Integer.decode(getValue(msgId.getNodeValue(), null)));
final Node addName = n.getAttributes().getNamedItem("addName");
if ((addName != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
if ((n.getAttributes().getNamedItem("addName") != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
{
condition.addName();
}
@@ -1327,8 +1314,7 @@ public class DocumentSkill extends DocumentBase
else if ((condition != null) && (msgId != null))
{
condition.setMessageId(Integer.decode(getValue(msgId.getNodeValue(), null)));
final Node addName = n.getAttributes().getNamedItem("addName");
if ((addName != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
if ((n.getAttributes().getNamedItem("addName") != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
{
condition.addName();
}
@@ -1389,8 +1375,7 @@ public class DocumentSkill extends DocumentBase
else if ((condition != null) && (msgId != null))
{
condition.setMessageId(Integer.decode(getValue(msgId.getNodeValue(), null)));
final Node addName = n.getAttributes().getNamedItem("addName");
if ((addName != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
if ((n.getAttributes().getNamedItem("addName") != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
{
condition.addName();
}
@@ -1447,8 +1432,7 @@ public class DocumentSkill extends DocumentBase
else if ((condition != null) && (msgId != null))
{
condition.setMessageId(Integer.decode(getValue(msgId.getNodeValue(), null)));
final Node addName = n.getAttributes().getNamedItem("addName");
if ((addName != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
if ((n.getAttributes().getNamedItem("addName") != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
{
condition.addName();
}
@@ -1509,8 +1493,7 @@ public class DocumentSkill extends DocumentBase
else if ((condition != null) && (msgId != null))
{
condition.setMessageId(Integer.decode(getValue(msgId.getNodeValue(), null)));
final Node addName = n.getAttributes().getNamedItem("addName");
if ((addName != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
if ((n.getAttributes().getNamedItem("addName") != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
{
condition.addName();
}
@@ -1567,8 +1550,7 @@ public class DocumentSkill extends DocumentBase
else if ((condition != null) && (msgId != null))
{
condition.setMessageId(Integer.decode(getValue(msgId.getNodeValue(), null)));
final Node addName = n.getAttributes().getNamedItem("addName");
if ((addName != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
if ((n.getAttributes().getNamedItem("addName") != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
{
condition.addName();
}
@@ -1629,8 +1611,7 @@ public class DocumentSkill extends DocumentBase
else if ((condition != null) && (msgId != null))
{
condition.setMessageId(Integer.decode(getValue(msgId.getNodeValue(), null)));
final Node addName = n.getAttributes().getNamedItem("addName");
if ((addName != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
if ((n.getAttributes().getNamedItem("addName") != null) && (Integer.decode(getValue(msgId.getNodeValue(), null)) > 0))
{
condition.addName();
}

View File

@@ -34,8 +34,7 @@ public class AdminCommandHandler implements IHandler<IAdminCommandHandler, Strin
@Override
public void registerHandler(IAdminCommandHandler handler)
{
final String[] ids = handler.getAdminCommandList();
for (String id : ids)
for (String id : handler.getAdminCommandList())
{
_datatable.put(id, handler);
}
@@ -44,8 +43,7 @@ public class AdminCommandHandler implements IHandler<IAdminCommandHandler, Strin
@Override
public synchronized void removeHandler(IAdminCommandHandler handler)
{
final String[] ids = handler.getAdminCommandList();
for (String id : ids)
for (String id : handler.getAdminCommandList())
{
_datatable.remove(id);
}
@@ -54,12 +52,7 @@ public class AdminCommandHandler implements IHandler<IAdminCommandHandler, Strin
@Override
public IAdminCommandHandler getHandler(String adminCommand)
{
String command = adminCommand;
if (adminCommand.contains(" "))
{
command = adminCommand.substring(0, adminCommand.indexOf(" "));
}
return _datatable.get(command);
return _datatable.get((adminCommand.contains(" ") ? adminCommand.substring(0, adminCommand.indexOf(" ")) : adminCommand));
}
@Override

View File

@@ -63,8 +63,7 @@ public final class EffectHandler implements IHandler<Class<? extends AbstractEff
{
try
{
final File file = new File(L2ScriptEngineManager.SCRIPT_FOLDER, "handlers/EffectMasterHandler.java");
L2ScriptEngineManager.getInstance().executeScript(file);
L2ScriptEngineManager.getInstance().executeScript((new File(L2ScriptEngineManager.SCRIPT_FOLDER, "handlers/EffectMasterHandler.java")));
}
catch (Exception e)
{

View File

@@ -34,8 +34,7 @@ public class UserCommandHandler implements IHandler<IUserCommandHandler, Integer
@Override
public void registerHandler(IUserCommandHandler handler)
{
final int[] ids = handler.getUserCommandList();
for (int id : ids)
for (int id : handler.getUserCommandList())
{
_datatable.put(id, handler);
}
@@ -44,8 +43,7 @@ public class UserCommandHandler implements IHandler<IUserCommandHandler, Integer
@Override
public synchronized void removeHandler(IUserCommandHandler handler)
{
final int[] ids = handler.getUserCommandList();
for (int id : ids)
for (int id : handler.getUserCommandList())
{
_datatable.remove(id);
}

View File

@@ -34,8 +34,7 @@ public class VoicedCommandHandler implements IHandler<IVoicedCommandHandler, Str
@Override
public void registerHandler(IVoicedCommandHandler handler)
{
final String[] ids = handler.getVoicedCommandList();
for (String id : ids)
for (String id : handler.getVoicedCommandList())
{
_datatable.put(id, handler);
}
@@ -44,8 +43,7 @@ public class VoicedCommandHandler implements IHandler<IVoicedCommandHandler, Str
@Override
public synchronized void removeHandler(IVoicedCommandHandler handler)
{
final String[] ids = handler.getVoicedCommandList();
for (String id : ids)
for (String id : handler.getVoicedCommandList())
{
_datatable.remove(id);
}
@@ -54,12 +52,7 @@ public class VoicedCommandHandler implements IHandler<IVoicedCommandHandler, Str
@Override
public IVoicedCommandHandler getHandler(String voicedCommand)
{
String command = voicedCommand;
if (voicedCommand.contains(" "))
{
command = voicedCommand.substring(0, voicedCommand.indexOf(" "));
}
return _datatable.get(command);
return _datatable.get((voicedCommand.contains(" ") ? voicedCommand.substring(0, voicedCommand.indexOf(" ")) : voicedCommand));
}
@Override

View File

@@ -110,22 +110,15 @@ public class BitSetIDFactory extends IdFactory
_freeIds.set(newID);
_freeIdCount.decrementAndGet();
int nextFree = _freeIds.nextClearBit(newID);
final int nextFree = _freeIds.nextClearBit(newID) < 0 ? _freeIds.nextClearBit(0) : _freeIds.nextClearBit(newID);
if (nextFree < 0)
{
nextFree = _freeIds.nextClearBit(0);
}
if (nextFree < 0)
{
if (_freeIds.size() < FREE_OBJECT_ID_SIZE)
{
increaseBitSetCapacity();
}
else
if (_freeIds.size() >= FREE_OBJECT_ID_SIZE)
{
throw new NullPointerException("Ran out of valid Id's.");
}
increaseBitSetCapacity();
}
_nextFreeId.set(nextFree);

View File

@@ -88,11 +88,7 @@ public class CompactionIDFactory extends IdFactory
}
}
int hole = id - _curOID;
if (hole > (N - idx))
{
hole = N - idx;
}
final int hole = (id - _curOID) > (N - idx) ? N - idx : id - _curOID;
for (int i = 1; i <= hole; i++)
{
id = tmp_obj_ids[N - i];

View File

@@ -101,11 +101,7 @@ public class StackIDFactory extends IdFactory
}
// int hole = id - _curOID;
int hole = id - _tempOID;
if (hole > (N - idx))
{
hole = N - idx;
}
final int hole = (id - _tempOID) > (N - idx) ? N - idx : id - _tempOID;
for (int i = 1; i <= hole; i++)
{
// log.info("Free ID added " + (_tempOID));

View File

@@ -137,14 +137,15 @@ public class AirShipManager
public void removeAirShip(L2AirShipInstance ship)
{
if (ship.getOwnerId() != 0)
if (ship.getOwnerId() == 0)
{
storeInDb(ship.getOwnerId());
final StatsSet info = _airShipsInfo.get(ship.getOwnerId());
if (info != null)
{
info.set("fuel", ship.getFuel());
}
return;
}
storeInDb(ship.getOwnerId());
final StatsSet info = _airShipsInfo.get(ship.getOwnerId());
if (info != null)
{
info.set("fuel", ship.getFuel());
}
}
@@ -155,40 +156,34 @@ public class AirShipManager
public void registerLicense(int ownerId)
{
if (!_airShipsInfo.containsKey(ownerId))
if (_airShipsInfo.containsKey(ownerId))
{
final StatsSet info = new StatsSet();
info.set("fuel", 600);
_airShipsInfo.put(ownerId, info);
try (Connection con = DatabaseFactory.getInstance().getConnection();
PreparedStatement ps = con.prepareStatement(ADD_DB))
{
ps.setInt(1, ownerId);
ps.setInt(2, info.getInt("fuel"));
ps.executeUpdate();
}
catch (SQLException e)
{
_log.log(Level.WARNING, getClass().getSimpleName() + ": Could not add new airship license: " + e.getMessage(), e);
}
catch (Exception e)
{
_log.log(Level.WARNING, getClass().getSimpleName() + ": Error while initializing: " + e.getMessage(), e);
}
return;
}
final StatsSet info = new StatsSet();
info.set("fuel", 600);
_airShipsInfo.put(ownerId, info);
try (Connection con = DatabaseFactory.getInstance().getConnection();
PreparedStatement ps = con.prepareStatement(ADD_DB))
{
ps.setInt(1, ownerId);
ps.setInt(2, info.getInt("fuel"));
ps.executeUpdate();
}
catch (SQLException e)
{
_log.log(Level.WARNING, getClass().getSimpleName() + ": Could not add new airship license: " + e.getMessage(), e);
}
catch (Exception e)
{
_log.log(Level.WARNING, getClass().getSimpleName() + ": Error while initializing: " + e.getMessage(), e);
}
}
public boolean hasAirShip(int ownerId)
{
final L2AirShipInstance ship = _airShips.get(ownerId);
if ((ship == null) || !(ship.isVisible() || ship.isTeleporting()))
{
return false;
}
return true;
return (ship != null) && (ship.isVisible() || ship.isTeleporting());
}
public void registerAirShipTeleportList(int dockId, int locationId, VehiclePathPoint[][] tp, int[] fuelConsumption)
@@ -227,33 +222,13 @@ public class AirShipManager
public VehiclePathPoint[] getTeleportDestination(int dockId, int index)
{
final AirShipTeleportList all = _teleports.get(dockId);
if (all == null)
{
return null;
}
if ((index < -1) || (index >= all.getRoute().length))
{
return null;
}
return all.getRoute()[index + 1];
return (all == null) || (index < -1) || (index >= all.getRoute().length) ? null : all.getRoute()[index + 1];
}
public int getFuelConsumption(int dockId, int index)
{
final AirShipTeleportList all = _teleports.get(dockId);
if (all == null)
{
return 0;
}
if ((index < -1) || (index >= all.getFuel().length))
{
return 0;
}
return all.getFuel()[index + 1];
return (all == null) || (index < -1) || (index >= all.getFuel().length) ? 0 : all.getFuel()[index + 1];
}
private void load()

View File

@@ -67,39 +67,24 @@ public final class AntiFeedManager
}
final L2PcInstance targetPlayer = target.getActingPlayer();
if (targetPlayer == null)
if ((targetPlayer == null) || ((Config.ANTIFEED_INTERVAL > 0) && _lastDeathTimes.containsKey(targetPlayer.getObjectId()) && ((System.currentTimeMillis() - _lastDeathTimes.get(targetPlayer.getObjectId())) < Config.ANTIFEED_INTERVAL)))
{
return false;
}
if ((Config.ANTIFEED_INTERVAL > 0) && _lastDeathTimes.containsKey(targetPlayer.getObjectId()))
if (!Config.ANTIFEED_DUALBOX || (attacker == null))
{
if ((System.currentTimeMillis() - _lastDeathTimes.get(targetPlayer.getObjectId())) < Config.ANTIFEED_INTERVAL)
{
return false;
}
return true;
}
if (Config.ANTIFEED_DUALBOX && (attacker != null))
final L2PcInstance attackerPlayer = attacker.getActingPlayer();
if (attackerPlayer == null)
{
final L2PcInstance attackerPlayer = attacker.getActingPlayer();
if (attackerPlayer == null)
{
return false;
}
final L2GameClient targetClient = targetPlayer.getClient();
final L2GameClient attackerClient = attackerPlayer.getClient();
if ((targetClient == null) || (attackerClient == null) || targetClient.isDetached() || attackerClient.isDetached())
{
// unable to check ip address
return !Config.ANTIFEED_DISCONNECTED_AS_DUALBOX;
}
return !targetClient.getConnectionAddress().equals(attackerClient.getConnectionAddress());
return false;
}
return true;
final L2GameClient targetClient = targetPlayer.getClient();
final L2GameClient attackerClient = attackerPlayer.getClient();
return (targetClient == null) || (attackerClient == null) || targetClient.isDetached() || attackerClient.isDetached() ? !Config.ANTIFEED_DISCONNECTED_AS_DUALBOX : !targetClient.getConnectionAddress().equals(attackerClient.getConnectionAddress());
}
/**
@@ -155,12 +140,12 @@ public final class AntiFeedManager
final AtomicInteger connectionCount = event.computeIfAbsent(addrHash, k -> new AtomicInteger());
if ((connectionCount.get() + 1) <= (max + Config.L2JMOD_DUALBOX_CHECK_WHITELIST.getOrDefault(addrHash, 0)))
if ((connectionCount.get() + 1) > (max + Config.L2JMOD_DUALBOX_CHECK_WHITELIST.getOrDefault(addrHash, 0)))
{
connectionCount.incrementAndGet();
return true;
return false;
}
return false;
connectionCount.incrementAndGet();
return true;
}
/**
@@ -258,12 +243,7 @@ public final class AntiFeedManager
}
final Integer addrHash = Integer.valueOf(client.getConnectionAddress().hashCode());
int limit = max;
if (Config.L2JMOD_DUALBOX_CHECK_WHITELIST.containsKey(addrHash))
{
limit += Config.L2JMOD_DUALBOX_CHECK_WHITELIST.get(addrHash);
}
return limit;
return Config.L2JMOD_DUALBOX_CHECK_WHITELIST.containsKey(addrHash) ? max + Config.L2JMOD_DUALBOX_CHECK_WHITELIST.get(addrHash) : max;
}
public static final AntiFeedManager getInstance()

View File

@@ -117,11 +117,7 @@ public final class CHSiegeManager
public final ClanHallSiegeEngine getSiege(L2Character character)
{
final SiegableHall hall = getNearbyClanHall(character);
if (hall == null)
{
return null;
}
return hall.getSiege();
return hall == null ? null : hall.getSiege();
}
public final void registerClan(L2Clan clan, SiegableHall hall, L2PcInstance player)

View File

@@ -200,12 +200,7 @@ public final class CastleManager implements InstanceListManager
public int getCircletByCastleId(int castleId)
{
if ((castleId > 0) && (castleId < 10))
{
return _castleCirclets[castleId];
}
return 0;
return (castleId > 0) && (castleId < 10) ? _castleCirclets[castleId] : 0;
}
// remove this castle's circlets from the clan
@@ -223,45 +218,48 @@ public final class CastleManager implements InstanceListManager
{
return;
}
final L2PcInstance player = member.getPlayerInstance();
final int circletId = getCircletByCastleId(castleId);
if (circletId != 0)
if (circletId == 0)
{
// online-player circlet removal
if (player != null)
return;
}
// online-player circlet removal
if (player != null)
{
try
{
try
final L2ItemInstance circlet = player.getInventory().getItemByItemId(circletId);
if (circlet != null)
{
final L2ItemInstance circlet = player.getInventory().getItemByItemId(circletId);
if (circlet != null)
if (circlet.isEquipped())
{
if (circlet.isEquipped())
{
player.getInventory().unEquipItemInSlot(circlet.getLocationSlot());
}
player.destroyItemByItemId("CastleCircletRemoval", circletId, 1, player, true);
player.getInventory().unEquipItemInSlot(circlet.getLocationSlot());
}
return;
}
catch (NullPointerException e)
{
// continue removing offline
player.destroyItemByItemId("CastleCircletRemoval", circletId, 1, player, true);
}
return;
}
// else offline-player circlet removal
try (Connection con = DatabaseFactory.getInstance().getConnection();
PreparedStatement ps = con.prepareStatement("DELETE FROM items WHERE owner_id = ? and item_id = ?"))
catch (NullPointerException e)
{
ps.setInt(1, member.getObjectId());
ps.setInt(2, circletId);
ps.execute();
}
catch (Exception e)
{
_log.log(Level.WARNING, "Failed to remove castle circlets offline for player " + member.getName() + ": " + e.getMessage(), e);
// continue removing offline
}
}
// else offline-player circlet removal
try (Connection con = DatabaseFactory.getInstance().getConnection();
PreparedStatement ps = con.prepareStatement("DELETE FROM items WHERE owner_id = ? and item_id = ?"))
{
ps.setInt(1, member.getObjectId());
ps.setInt(2, circletId);
ps.execute();
}
catch (Exception e)
{
_log.log(Level.WARNING, "Failed to remove castle circlets offline for player " + member.getName() + ": " + e.getMessage(), e);
}
}
@Override

View File

@@ -185,26 +185,25 @@ public class ClanEntryManager
public boolean addPlayerApplicationToClan(int clanId, PledgeApplicantInfo info)
{
if (!_playerLocked.containsKey(info.getPlayerId()))
if (_playerLocked.containsKey(info.getPlayerId()))
{
_applicantList.computeIfAbsent(clanId, k -> new ConcurrentHashMap<>()).put(info.getPlayerId(), info);
try (Connection con = DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement(INSERT_APPLICANT))
{
statement.setInt(1, info.getPlayerId());
statement.setInt(2, info.getRequestClanId());
statement.setInt(3, info.getKarma());
statement.setString(4, info.getMessage());
statement.executeUpdate();
}
catch (Exception e)
{
_log.log(Level.WARNING, e.getMessage(), e);
}
return true;
return false;
}
return false;
_applicantList.computeIfAbsent(clanId, k -> new ConcurrentHashMap<>()).put(info.getPlayerId(), info);
try (Connection con = DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement(INSERT_APPLICANT))
{
statement.setInt(1, info.getPlayerId());
statement.setInt(2, info.getRequestClanId());
statement.setInt(3, info.getKarma());
statement.setString(4, info.getMessage());
statement.executeUpdate();
}
catch (Exception e)
{
_log.log(Level.WARNING, e.getMessage(), e);
}
return true;
}
public OptionalInt getClanIdForPlayerApplication(int playerId)
@@ -214,109 +213,108 @@ public class ClanEntryManager
public boolean addToWaitingList(int playerId, PledgeWaitingInfo info)
{
if (!_playerLocked.containsKey(playerId))
if (_playerLocked.containsKey(playerId))
{
try (Connection con = DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement(INSERT_WAITING_LIST))
{
statement.setInt(1, info.getPlayerId());
statement.setInt(2, info.getKarma());
statement.executeUpdate();
}
catch (Exception e)
{
_log.log(Level.WARNING, e.getMessage(), e);
}
return _waitingList.put(playerId, info) != null;
return false;
}
return false;
try (Connection con = DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement(INSERT_WAITING_LIST))
{
statement.setInt(1, info.getPlayerId());
statement.setInt(2, info.getKarma());
statement.executeUpdate();
}
catch (Exception e)
{
_log.log(Level.WARNING, e.getMessage(), e);
}
return _waitingList.put(playerId, info) != null;
}
public boolean removeFromWaitingList(int playerId)
{
if (_waitingList.containsKey(playerId))
if (!_waitingList.containsKey(playerId))
{
try (Connection con = DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement(DELETE_WAITING_LIST))
{
statement.setInt(1, playerId);
statement.executeUpdate();
}
catch (Exception e)
{
_log.log(Level.WARNING, e.getMessage(), e);
}
_waitingList.remove(playerId);
lockPlayer(playerId);
return true;
return false;
}
return false;
try (Connection con = DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement(DELETE_WAITING_LIST))
{
statement.setInt(1, playerId);
statement.executeUpdate();
}
catch (Exception e)
{
_log.log(Level.WARNING, e.getMessage(), e);
}
_waitingList.remove(playerId);
lockPlayer(playerId);
return true;
}
public boolean addToClanList(int clanId, PledgeRecruitInfo info)
{
if (!_clanList.containsKey(clanId) && !_clanLocked.containsKey(clanId))
if (_clanList.containsKey(clanId) || _clanLocked.containsKey(clanId))
{
try (Connection con = DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement(INSERT_CLAN_RECRUIT))
{
statement.setInt(1, info.getClanId());
statement.setInt(2, info.getKarma());
statement.setString(3, info.getInformation());
statement.setString(4, info.getDetailedInformation());
statement.executeUpdate();
}
catch (Exception e)
{
_log.log(Level.WARNING, e.getMessage(), e);
}
return _clanList.put(clanId, info) != null;
return false;
}
return false;
try (Connection con = DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement(INSERT_CLAN_RECRUIT))
{
statement.setInt(1, info.getClanId());
statement.setInt(2, info.getKarma());
statement.setString(3, info.getInformation());
statement.setString(4, info.getDetailedInformation());
statement.executeUpdate();
}
catch (Exception e)
{
_log.log(Level.WARNING, e.getMessage(), e);
}
return _clanList.put(clanId, info) != null;
}
public boolean updateClanList(int clanId, PledgeRecruitInfo info)
{
if (_clanList.containsKey(clanId) && !_clanLocked.containsKey(clanId))
if (!_clanList.containsKey(clanId) || _clanLocked.containsKey(clanId))
{
try (Connection con = DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement(UPDATE_CLAN_RECRUIT))
{
statement.setInt(1, info.getKarma());
statement.setString(2, info.getInformation());
statement.setString(3, info.getDetailedInformation());
statement.setInt(4, info.getClanId());
statement.executeUpdate();
}
catch (Exception e)
{
_log.log(Level.WARNING, e.getMessage(), e);
}
return _clanList.replace(clanId, info) != null;
return false;
}
return false;
try (Connection con = DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement(UPDATE_CLAN_RECRUIT))
{
statement.setInt(1, info.getKarma());
statement.setString(2, info.getInformation());
statement.setString(3, info.getDetailedInformation());
statement.setInt(4, info.getClanId());
statement.executeUpdate();
}
catch (Exception e)
{
_log.log(Level.WARNING, e.getMessage(), e);
}
return _clanList.replace(clanId, info) != null;
}
public boolean removeFromClanList(int clanId)
{
if (_clanList.containsKey(clanId))
if (!_clanList.containsKey(clanId))
{
try (Connection con = DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement(DELETE_CLAN_RECRUIT))
{
statement.setInt(1, clanId);
statement.executeUpdate();
}
catch (Exception e)
{
_log.log(Level.WARNING, e.getMessage(), e);
}
_clanList.remove(clanId);
lockClan(clanId);
return true;
return false;
}
return false;
try (Connection con = DatabaseFactory.getInstance().getConnection();
PreparedStatement statement = con.prepareStatement(DELETE_CLAN_RECRUIT))
{
statement.setInt(1, clanId);
statement.executeUpdate();
}
catch (Exception e)
{
_log.log(Level.WARNING, e.getMessage(), e);
}
_clanList.remove(clanId);
lockClan(clanId);
return true;
}
public List<PledgeWaitingInfo> getSortedWaitingList(int levelMin, int levelMax, int role, int sortBy, boolean descending)

View File

@@ -117,11 +117,7 @@ public final class ClanHallAuctionManager
public final Auction getAuction(int auctionId)
{
final int index = getAuctionIndex(auctionId);
if (index >= 0)
{
return _auctions.get(index);
}
return null;
return index >= 0 ? _auctions.get(index) : null;
}
public final int getAuctionIndex(int auctionId)

View File

@@ -30,7 +30,6 @@ import com.l2jmobius.gameserver.data.sql.impl.ClanTable;
import com.l2jmobius.gameserver.model.L2Clan;
import com.l2jmobius.gameserver.model.L2Object;
import com.l2jmobius.gameserver.model.StatsSet;
import com.l2jmobius.gameserver.model.entity.Auction;
import com.l2jmobius.gameserver.model.entity.ClanHall;
import com.l2jmobius.gameserver.model.entity.clanhall.AuctionableHall;
import com.l2jmobius.gameserver.model.entity.clanhall.SiegableHall;
@@ -95,8 +94,7 @@ public final class ClanHallManager
}
_freeClanHall.put(id, ch);
final Auction auc = ClanHallAuctionManager.getInstance().getAuction(id);
if ((auc == null) && (lease > 0))
if ((ClanHallAuctionManager.getInstance().getAuction(id) == null) && (lease > 0))
{
ClanHallAuctionManager.getInstance().initNPC(id);
}
@@ -151,11 +149,7 @@ public final class ClanHallManager
*/
public final boolean isFree(int chId)
{
if (_freeClanHall.containsKey(chId))
{
return true;
}
return false;
return _freeClanHall.containsKey(chId);
}
/**

View File

@@ -430,8 +430,7 @@ public final class CommissionManager
{
if ((_commissionItems.remove(commissionItem.getCommissionId()) != null) && deleteItemFromDB(commissionItem.getCommissionId()))
{
final Message mail = new Message(commissionItem.getItemInstance().getOwnerId(), commissionItem.getItemInstance(), MailType.COMMISSION_ITEM_RETURNED);
MailManager.getInstance().sendMessage(mail);
MailManager.getInstance().sendMessage(new Message(commissionItem.getItemInstance().getOwnerId(), commissionItem.getItemInstance(), MailType.COMMISSION_ITEM_RETURNED));
}
}

View File

@@ -70,55 +70,51 @@ public final class CoupleManager
public final Couple getCouple(int coupleId)
{
final int index = getCoupleIndex(coupleId);
if (index >= 0)
{
return getCouples().get(index);
}
return null;
return index >= 0 ? getCouples().get(index) : null;
}
public void createCouple(L2PcInstance player1, L2PcInstance player2)
{
if ((player1 != null) && (player2 != null))
if ((player1 == null) || (player2 == null) || (player1.getPartnerId() != 0) || (player2.getPartnerId() != 0))
{
if ((player1.getPartnerId() == 0) && (player2.getPartnerId() == 0))
{
final int player1id = player1.getObjectId();
final int player2id = player2.getObjectId();
final Couple couple = new Couple(player1, player2);
getCouples().add(couple);
player1.setPartnerId(player2id);
player2.setPartnerId(player1id);
player1.setCoupleId(couple.getId());
player2.setCoupleId(couple.getId());
}
return;
}
final int player1id = player1.getObjectId();
final int player2id = player2.getObjectId();
final Couple couple = new Couple(player1, player2);
getCouples().add(couple);
player1.setPartnerId(player2id);
player2.setPartnerId(player1id);
player1.setCoupleId(couple.getId());
player2.setCoupleId(couple.getId());
}
public void deleteCouple(int coupleId)
{
final int index = getCoupleIndex(coupleId);
final Couple couple = getCouples().get(index);
if (couple != null)
if (couple == null)
{
final L2PcInstance player1 = L2World.getInstance().getPlayer(couple.getPlayer1Id());
final L2PcInstance player2 = L2World.getInstance().getPlayer(couple.getPlayer2Id());
if (player1 != null)
{
player1.setPartnerId(0);
player1.setMarried(false);
player1.setCoupleId(0);
}
if (player2 != null)
{
player2.setPartnerId(0);
player2.setMarried(false);
player2.setCoupleId(0);
}
couple.divorce();
getCouples().remove(index);
return;
}
final L2PcInstance player1 = L2World.getInstance().getPlayer(couple.getPlayer1Id());
final L2PcInstance player2 = L2World.getInstance().getPlayer(couple.getPlayer2Id());
if (player1 != null)
{
player1.setPartnerId(0);
player1.setMarried(false);
player1.setCoupleId(0);
}
if (player2 != null)
{
player2.setPartnerId(0);
player2.setMarried(false);
player2.setCoupleId(0);
}
couple.divorce();
getCouples().remove(index);
}
public final int getCoupleIndex(int coupleId)

View File

@@ -31,7 +31,6 @@ import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
@@ -101,9 +100,7 @@ public final class CursedWeaponsManager
return;
}
final Document doc = factory.newDocumentBuilder().parse(file);
for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling())
for (Node n = factory.newDocumentBuilder().parse(file).getFirstChild(); n != null; n = n.getNextSibling())
{
if ("list".equalsIgnoreCase(n.getNodeName()))
{
@@ -306,23 +303,17 @@ public final class CursedWeaponsManager
public void drop(int itemId, L2Character killer)
{
final CursedWeapon cw = _cursedWeapons.get(itemId);
cw.dropIt(killer);
_cursedWeapons.get(itemId).dropIt(killer);
}
public void increaseKills(int itemId)
{
final CursedWeapon cw = _cursedWeapons.get(itemId);
cw.increaseKills();
_cursedWeapons.get(itemId).increaseKills();
}
public int getLevel(int itemId)
{
final CursedWeapon cw = _cursedWeapons.get(itemId);
return cw.getLevel();
return _cursedWeapons.get(itemId).getLevel();
}
public static void announce(SystemMessage sm)

View File

@@ -169,14 +169,7 @@ public final class DayNightSpawnManager
{
try
{
if (GameTimeController.getInstance().isNight())
{
changeMode(1);
}
else
{
changeMode(0);
}
changeMode(GameTimeController.getInstance().isNight() ? 1 : 0);
}
catch (Exception e)
{

View File

@@ -112,8 +112,7 @@ public final class DuelManager
{
return;
}
final Duel duel = getDuel(player.getDuelId());
duel.doSurrender(player);
getDuel(player.getDuelId()).doSurrender(player);
}
/**

View File

@@ -52,8 +52,7 @@ public class FactionManager
{
while (rs.next())
{
final int id = rs.getInt(1);
_playerFactions.put(id, rs.getInt(2));
_playerFactions.put(rs.getInt(1), rs.getInt(2));
}
}
catch (SQLException e)
@@ -101,15 +100,7 @@ public class FactionManager
public final boolean isSameFaction(L2PcInstance player1, L2PcInstance player2)
{
// TODO: Maybe add support for multiple factions?
// if (getFactionByCharId(player1.getId()) == getFactionByCharId(player2.getId()))
// {
// return true;
// }
if ((player1.isGood() && player2.isGood()) || (player1.isEvil() && player2.isEvil()))
{
return true;
}
return false;
return (player1.isGood() && player2.isGood()) || (player1.isEvil() && player2.isEvil());
}
public static FactionManager getInstance()

View File

@@ -211,42 +211,22 @@ public class FishingChampionshipManager
public String getWinnerName(int par)
{
if (_winPlayersName.size() >= par)
{
return _winPlayersName.get(par - 1);
}
return "None";
return _winPlayersName.size() >= par ? _winPlayersName.get(par - 1) : "None";
}
public String getCurrentName(int par)
{
if (_playersName.size() >= par)
{
return _playersName.get(par - 1);
}
return "None";
return _playersName.size() >= par ? _playersName.get(par - 1) : "None";
}
public String getFishLength(int par)
{
if (_winFishLength.size() >= par)
{
return _winFishLength.get(par - 1);
}
return "0";
return _winFishLength.size() >= par ? _winFishLength.get(par - 1) : "0";
}
public String getCurrentFishLength(int par)
{
if (_fishLength.size() >= par)
{
return _fishLength.get(par - 1);
}
return "0";
return _fishLength.size() >= par ? _fishLength.get(par - 1) : "0";
}
public boolean isWinner(String playerName)
@@ -265,54 +245,51 @@ public class FishingChampionshipManager
{
for (Fisher fisher : _winPlayers)
{
if (fisher.getName().equalsIgnoreCase(pl.getName()))
if (fisher.getName().equalsIgnoreCase(pl.getName()) && (fisher.getRewardType() != 2))
{
if (fisher.getRewardType() != 2)
int rewardCnt = 0;
for (int x = 0; x < _winPlayersName.size(); x++)
{
int rewardCnt = 0;
for (int x = 0; x < _winPlayersName.size(); x++)
if (_winPlayersName.get(x).equalsIgnoreCase(pl.getName()))
{
if (_winPlayersName.get(x).equalsIgnoreCase(pl.getName()))
switch (x)
{
switch (x)
case 0:
{
case 0:
{
rewardCnt = Config.ALT_FISH_CHAMPIONSHIP_REWARD_1;
break;
}
case 1:
{
rewardCnt = Config.ALT_FISH_CHAMPIONSHIP_REWARD_2;
break;
}
case 2:
{
rewardCnt = Config.ALT_FISH_CHAMPIONSHIP_REWARD_3;
break;
}
case 3:
{
rewardCnt = Config.ALT_FISH_CHAMPIONSHIP_REWARD_4;
break;
}
case 4:
{
rewardCnt = Config.ALT_FISH_CHAMPIONSHIP_REWARD_5;
break;
}
rewardCnt = Config.ALT_FISH_CHAMPIONSHIP_REWARD_1;
break;
}
case 1:
{
rewardCnt = Config.ALT_FISH_CHAMPIONSHIP_REWARD_2;
break;
}
case 2:
{
rewardCnt = Config.ALT_FISH_CHAMPIONSHIP_REWARD_3;
break;
}
case 3:
{
rewardCnt = Config.ALT_FISH_CHAMPIONSHIP_REWARD_4;
break;
}
case 4:
{
rewardCnt = Config.ALT_FISH_CHAMPIONSHIP_REWARD_5;
break;
}
}
}
fisher.setRewardType(2);
if (rewardCnt > 0)
{
pl.addItem("fishing_reward", Config.ALT_FISH_CHAMPIONSHIP_REWARD_ITEM, rewardCnt, null, true);
final NpcHtmlMessage html = new NpcHtmlMessage();
html.setFile(pl.getHtmlPrefix(), "html/fisherman/championship/fish_event_reward001.htm");
pl.sendPacket(html);
}
}
fisher.setRewardType(2);
if (rewardCnt > 0)
{
pl.addItem("fishing_reward", Config.ALT_FISH_CHAMPIONSHIP_REWARD_ITEM, rewardCnt, null, true);
final NpcHtmlMessage html = new NpcHtmlMessage();
html.setFile(pl.getHtmlPrefix(), "html/fisherman/championship/fish_event_reward001.htm");
pl.sendPacket(html);
}
}
}

View File

@@ -154,13 +154,7 @@ public final class FortSiegeManager
try
{
final int x = Integer.parseInt(st.nextToken());
final int y = Integer.parseInt(st.nextToken());
final int z = Integer.parseInt(st.nextToken());
final int heading = Integer.parseInt(st.nextToken());
final int npc_id = Integer.parseInt(st.nextToken());
commanderSpawns.add(new FortSiegeSpawn(fort.getResidenceId(), x, y, z, heading, npc_id, i));
commanderSpawns.add(new FortSiegeSpawn(fort.getResidenceId(), Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()), i));
}
catch (Exception e)
{
@@ -181,12 +175,7 @@ public final class FortSiegeManager
try
{
final int x = Integer.parseInt(st.nextToken());
final int y = Integer.parseInt(st.nextToken());
final int z = Integer.parseInt(st.nextToken());
final int flag_id = Integer.parseInt(st.nextToken());
flagSpawns.add(new CombatFlag(fort.getResidenceId(), x, y, z, 0, flag_id));
flagSpawns.add(new CombatFlag(fort.getResidenceId(), Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()), 0, Integer.parseInt(st.nextToken())));
}
catch (Exception e)
{
@@ -308,30 +297,18 @@ public final class FortSiegeManager
// here check if is siege is in progress
// here check if is siege is attacker
final Fort fort = FortManager.getInstance().getFort(player);
if ((fort == null) || (fort.getResidenceId() <= 0))
if ((fort != null) && (fort.getResidenceId() > 0) && fort.getSiege().isInProgress() && (fort.getSiege().getAttackerClan(player.getClan()) != null))
{
player.sendPacket(sm);
return false;
return true;
}
else if (!fort.getSiege().isInProgress())
{
player.sendPacket(sm);
return false;
}
else if (fort.getSiege().getAttackerClan(player.getClan()) == null)
{
player.sendPacket(sm);
return false;
}
return true;
player.sendPacket(sm);
return false;
}
public void dropCombatFlag(L2PcInstance player, int fortId)
{
final Fort fort = FortManager.getInstance().getFortById(fortId);
final List<CombatFlag> fcf = _flagList.get(fort.getResidenceId());
for (CombatFlag cf : fcf)
for (CombatFlag cf : _flagList.get(fort.getResidenceId()))
{
if (cf.getPlayerObjectId() == player.getObjectId())
{

View File

@@ -433,8 +433,7 @@ public final class FourSepulchersManager
spawnDat.setHeading(rs.getInt("heading"));
spawnDat.setRespawnDelay(rs.getInt("respawn_delay"));
SpawnTable.getInstance().addNewSpawn(spawnDat, false);
final int keyNpcId = rs.getInt("key_npc_id");
_mysteriousBoxSpawns.put(keyNpcId, spawnDat);
_mysteriousBoxSpawns.put(rs.getInt("key_npc_id"), spawnDat);
}
}
LOG.info(getClass().getSimpleName() + ": loaded " + _mysteriousBoxSpawns.size() + " Mysterious-Box spawns.");
@@ -1046,10 +1045,6 @@ public final class FourSepulchersManager
mem.destroyItemByItemId("Quest", CHAPEL_KEY, hallsKey.getCount(), mem, true);
}
}
_challengers.put(npcId, player);
_hallInUse.put(npcId, true);
}
else
{
@@ -1062,17 +1057,14 @@ public final class FourSepulchersManager
{
player.addItem("Quest", USED_PASS, 1, player, true);
}
final L2ItemInstance hallsKey = player.getInventory().getItemByItemId(CHAPEL_KEY);
if (hallsKey != null)
{
player.destroyItemByItemId("Quest", CHAPEL_KEY, hallsKey.getCount(), player, true);
}
_challengers.put(npcId, player);
_hallInUse.put(npcId, true);
}
_hallInUse.put(npcId, true);
_challengers.put(npcId, player);
}
public void spawnMysteriousBox(int npcId)
@@ -1098,115 +1090,108 @@ public final class FourSepulchersManager
}
final List<L2SepulcherMonsterInstance> mobs = new CopyOnWriteArrayList<>();
final List<L2Spawn> monsterList;
if (Rnd.get(2) == 0)
final List<L2Spawn> monsterList = Rnd.get(2) == 0 ? _physicalMonsters.get(npcId) : _magicalMonsters.get(npcId);
if (monsterList == null)
{
monsterList = _physicalMonsters.get(npcId);
}
else
{
monsterList = _magicalMonsters.get(npcId);
return;
}
if (monsterList != null)
boolean spawnKeyBoxMob = false;
boolean spawnedKeyBoxMob = false;
for (L2Spawn spawnDat : monsterList)
{
boolean spawnKeyBoxMob = false;
boolean spawnedKeyBoxMob = false;
for (L2Spawn spawnDat : monsterList)
if (spawnedKeyBoxMob)
{
if (spawnedKeyBoxMob)
spawnKeyBoxMob = false;
}
else
{
switch (npcId)
{
spawnKeyBoxMob = false;
}
else
{
switch (npcId)
case 31469:
case 31474:
case 31479:
case 31484:
{
case 31469:
case 31474:
case 31479:
case 31484:
if (Rnd.get(48) == 0)
{
if (Rnd.get(48) == 0)
{
spawnKeyBoxMob = true;
}
break;
}
default:
{
spawnKeyBoxMob = false;
spawnKeyBoxMob = true;
}
break;
}
}
L2SepulcherMonsterInstance mob = null;
if (spawnKeyBoxMob)
{
try
default:
{
final L2Spawn keyBoxMobSpawn = new L2Spawn(18149);
keyBoxMobSpawn.setAmount(1);
keyBoxMobSpawn.setLocation(spawnDat.getLocation());
keyBoxMobSpawn.setRespawnDelay(3600);
SpawnTable.getInstance().addNewSpawn(keyBoxMobSpawn, false);
mob = (L2SepulcherMonsterInstance) keyBoxMobSpawn.doSpawn();
keyBoxMobSpawn.stopRespawn();
spawnKeyBoxMob = false;
}
catch (Exception e)
{
LOG.log(Level.WARNING, "FourSepulchersManager.SpawnMonster: Spawn could not be initialized: " + e.getMessage(), e);
}
spawnedKeyBoxMob = true;
}
else
{
mob = (L2SepulcherMonsterInstance) spawnDat.doSpawn();
spawnDat.stopRespawn();
}
if (mob != null)
{
mob.mysteriousBoxId = npcId;
switch (npcId)
{
case 31469:
case 31474:
case 31479:
case 31484:
case 31472:
case 31477:
case 31482:
case 31487:
{
mobs.add(mob);
}
}
_allMobs.add(mob);
}
}
switch (npcId)
L2SepulcherMonsterInstance mob = null;
if (spawnKeyBoxMob)
{
case 31469:
case 31474:
case 31479:
case 31484:
try
{
_viscountMobs.put(npcId, mobs);
break;
final L2Spawn keyBoxMobSpawn = new L2Spawn(18149);
keyBoxMobSpawn.setAmount(1);
keyBoxMobSpawn.setLocation(spawnDat.getLocation());
keyBoxMobSpawn.setRespawnDelay(3600);
SpawnTable.getInstance().addNewSpawn(keyBoxMobSpawn, false);
mob = (L2SepulcherMonsterInstance) keyBoxMobSpawn.doSpawn();
keyBoxMobSpawn.stopRespawn();
}
case 31472:
case 31477:
case 31482:
case 31487:
catch (Exception e)
{
_dukeMobs.put(npcId, mobs);
break;
LOG.log(Level.WARNING, "FourSepulchersManager.SpawnMonster: Spawn could not be initialized: " + e.getMessage(), e);
}
spawnedKeyBoxMob = true;
}
else
{
mob = (L2SepulcherMonsterInstance) spawnDat.doSpawn();
spawnDat.stopRespawn();
}
if (mob != null)
{
mob.mysteriousBoxId = npcId;
switch (npcId)
{
case 31469:
case 31474:
case 31479:
case 31484:
case 31472:
case 31477:
case 31482:
case 31487:
{
mobs.add(mob);
}
}
_allMobs.add(mob);
}
}
switch (npcId)
{
case 31469:
case 31474:
case 31479:
case 31484:
{
_viscountMobs.put(npcId, mobs);
break;
}
case 31472:
case 31477:
case 31482:
case 31487:
{
_dukeMobs.put(npcId, mobs);
break;
}
}
}
@@ -1293,32 +1278,29 @@ public final class FourSepulchersManager
public void spawnArchonOfHalisha(int npcId)
{
if (!isAttackTime())
{
return;
}
if (_archonSpawned.get(npcId))
if (!isAttackTime() || _archonSpawned.get(npcId))
{
return;
}
final List<L2Spawn> monsterList = _dukeFinalMobs.get(npcId);
if (monsterList != null)
if (monsterList == null)
{
for (L2Spawn spawnDat : monsterList)
{
final L2SepulcherMonsterInstance mob = (L2SepulcherMonsterInstance) spawnDat.doSpawn();
spawnDat.stopRespawn();
if (mob != null)
{
mob.mysteriousBoxId = npcId;
_allMobs.add(mob);
}
}
_archonSpawned.put(npcId, true);
return;
}
for (L2Spawn spawnDat : monsterList)
{
final L2SepulcherMonsterInstance mob = (L2SepulcherMonsterInstance) spawnDat.doSpawn();
spawnDat.stopRespawn();
if (mob != null)
{
mob.mysteriousBoxId = npcId;
_allMobs.add(mob);
}
}
_archonSpawned.put(npcId, true);
}
public void spawnEmperorsGraveNpc(int npcId)
@@ -1537,13 +1519,6 @@ public final class FourSepulchersManager
min = minuteSelect(min);
NpcStringId msg = NpcStringId.MINUTE_S_HAVE_PASSED;
if (min == 90)
{
msg = NpcStringId.GAME_OVER_THE_TELEPORT_WILL_APPEAR_MOMENTARILY;
}
for (L2Spawn temp : _managers)
{
if (temp == null)
@@ -1562,29 +1537,20 @@ public final class FourSepulchersManager
{
continue;
}
((L2SepulcherNpcInstance) temp.getLastSpawn()).sayInShout(msg);
((L2SepulcherNpcInstance) temp.getLastSpawn()).sayInShout((min == 90 ? NpcStringId.GAME_OVER_THE_TELEPORT_WILL_APPEAR_MOMENTARILY : NpcStringId.MINUTE_S_HAVE_PASSED));
}
}
else if (_inEntryTime)
{
final NpcStringId msg1 = NpcStringId.YOU_MAY_NOW_ENTER_THE_SEPULCHER;
final NpcStringId msg2 = NpcStringId.IF_YOU_PLACE_YOUR_HAND_ON_THE_STONE_STATUE_IN_FRONT_OF_EACH_SEPULCHER_YOU_WILL_BE_ABLE_TO_ENTER;
for (L2Spawn temp : _managers)
{
if (temp == null)
if ((temp == null) || !(temp.getLastSpawn() instanceof L2SepulcherNpcInstance))
{
LOG.warning(getClass().getSimpleName() + ": Something goes wrong in managerSay()...");
continue;
}
if (!(temp.getLastSpawn() instanceof L2SepulcherNpcInstance))
{
LOG.warning(getClass().getSimpleName() + ": Something goes wrong in managerSay()...");
continue;
}
((L2SepulcherNpcInstance) temp.getLastSpawn()).sayInShout(msg1);
((L2SepulcherNpcInstance) temp.getLastSpawn()).sayInShout(msg2);
((L2SepulcherNpcInstance) temp.getLastSpawn()).sayInShout(NpcStringId.YOU_MAY_NOW_ENTER_THE_SEPULCHER);
((L2SepulcherNpcInstance) temp.getLastSpawn()).sayInShout(NpcStringId.IF_YOU_PLACE_YOUR_HAND_ON_THE_STONE_STATUE_IN_FRONT_OF_EACH_SEPULCHER_YOU_WILL_BE_ABLE_TO_ENTER);
}
}
}

View File

@@ -144,23 +144,24 @@ public final class GraciaSeedsManager
public void increaseSoDTiatKilled()
{
if (_SoDState == 1)
if (_SoDState != 1)
{
_SoDTiatKilled++;
if (_SoDTiatKilled >= Config.SOD_TIAT_KILL_COUNT)
{
setSoDState(2, false);
}
saveData(SODTYPE);
final Quest esQuest = QuestManager.getInstance().getQuest(ENERGY_SEEDS);
if (esQuest == null)
{
_log.warning(getClass().getSimpleName() + ": missing EnergySeeds Quest!");
}
else
{
esQuest.notifyEvent("StartSoDAi", null, null);
}
return;
}
_SoDTiatKilled++;
if (_SoDTiatKilled >= Config.SOD_TIAT_KILL_COUNT)
{
setSoDState(2, false);
}
saveData(SODTYPE);
final Quest esQuest = QuestManager.getInstance().getQuest(ENERGY_SEEDS);
if (esQuest == null)
{
_log.warning(getClass().getSimpleName() + ": missing EnergySeeds Quest!");
}
else
{
esQuest.notifyEvent("StartSoDAi", null, null);
}
}

View File

@@ -133,9 +133,7 @@ public final class GrandBossManager implements IStorable
{
while (rs.next())
{
final int id = rs.getInt("player_id");
final int zoneId = rs.getInt("zone");
zones.get(zoneId).add(id);
zones.get(rs.getInt("zone")).add(rs.getInt("player_id"));
}
_log.info(getClass().getSimpleName() + ": Initialized " + _zones.size() + " Grand Boss Zones");
}

View File

@@ -225,7 +225,7 @@ public final class HandysBlockCheckerManager
final ArenaParticipantsHolder holder = _arenaPlayers[arenaId];
synchronized (holder)
{
final boolean isRed = team == 0 ? true : false;
final boolean isRed = team == 0;
holder.removePlayer(player, team);
holder.broadCastPacketToTeam(new ExCubeGameRemovePlayer(player, isRed));
@@ -255,29 +255,14 @@ public final class HandysBlockCheckerManager
synchronized (holder)
{
final boolean isFromRed = holder.getRedPlayers().contains(player);
if (isFromRed && (holder.getBlueTeamSize() == 6))
if ((isFromRed && (holder.getBlueTeamSize() == 6)) || (!isFromRed && (holder.getRedTeamSize() == 6)))
{
player.sendMessage("The team is full");
return;
}
else if (!isFromRed && (holder.getRedTeamSize() == 6))
{
player.sendMessage("The team is full");
return;
}
final int futureTeam = isFromRed ? 1 : 0;
holder.addPlayer(player, futureTeam);
if (isFromRed)
{
holder.removePlayer(player, 0);
}
else
{
holder.removePlayer(player, 1);
}
holder.removePlayer(player, isFromRed ? 0 : 1);
holder.broadCastPacketToTeam(new ExCubeGameChangeTeam(player, isFromRed));
}
}
@@ -298,11 +283,7 @@ public final class HandysBlockCheckerManager
*/
public boolean arenaIsBeingUsed(int arenaId)
{
if ((arenaId < 0) || (arenaId > 3))
{
return false;
}
return _arenaStatus.get(arenaId);
return (arenaId >= 0) && (arenaId <= 3) && _arenaStatus.get(arenaId);
}
/**
@@ -332,29 +313,29 @@ public final class HandysBlockCheckerManager
final int arena = player.getBlockCheckerArena();
final int team = getHolder(arena).getPlayerTeam(player);
HandysBlockCheckerManager.getInstance().removePlayer(player, arena, team);
if (player.getTeam() != Team.NONE)
if (player.getTeam() == Team.NONE)
{
player.stopAllEffects();
// Remove team aura
player.setTeam(Team.NONE);
// Remove the event items
final PcInventory inv = player.getInventory();
if (inv.getItemByItemId(13787) != null)
{
final long count = inv.getInventoryItemCount(13787, 0);
inv.destroyItemByItemId("Handys Block Checker", 13787, count, player, player);
}
if (inv.getItemByItemId(13788) != null)
{
final long count = inv.getInventoryItemCount(13788, 0);
inv.destroyItemByItemId("Handys Block Checker", 13788, count, player, player);
}
player.setInsideZone(ZoneId.PVP, false);
// Teleport Back
player.teleToLocation(-57478, -60367, -2370);
return;
}
player.stopAllEffects();
// Remove team aura
player.setTeam(Team.NONE);
// Remove the event items
final PcInventory inv = player.getInventory();
if (inv.getItemByItemId(13787) != null)
{
inv.destroyItemByItemId("Handys Block Checker", 13787, inv.getInventoryItemCount(13787, 0), player, player);
}
if (inv.getItemByItemId(13788) != null)
{
inv.destroyItemByItemId("Handys Block Checker", 13788, inv.getInventoryItemCount(13788, 0), player, player);
}
player.setInsideZone(ZoneId.PVP, false);
// Teleport Back
player.teleToLocation(-57478, -60367, -2370);
}
public void removePenalty(int objectId)

View File

@@ -102,8 +102,7 @@ public final class ItemAuctionManager
throw new Exception("Dublicated instanceId " + instanceId);
}
final ItemAuctionInstance instance = new ItemAuctionInstance(instanceId, _auctionIds, nb);
_managerInstances.put(instanceId, instance);
_managerInstances.put(instanceId, (new ItemAuctionInstance(instanceId, _auctionIds, nb)));
}
}
}

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