text " package com.rs.cache; import com.rs.cache.utils.CacheUtil; import com.rs.cache.utils.CompressionUtils; import com.rs.cache.utils.Constants; import com.rs.cache.utils.Whirlpool; import com.rs.lib.io.InputStream; import com.rs.lib.io.OutputStream; public class Archive { private int id; private int revision; private int compression; private byte[] data; private int[] keys; protected Archive(int id, byte[] archive, int[] keys) { this.id = id; this.keys = keys; decompress(archive); } public Archive(int id, int compression, int revision, byte[] data) { this.id = id; this.compression = compression; this.revision = revision; this.data = data; } public byte[] compress() { OutputStream stream = new OutputStream(); stream.writeByte(compression); byte[] compressedData; switch (compression) { case Constants.GZIP_COMPRESSION: compressedData = CompressionUtils.gzip(data); stream.writeInt(compressedData.length); stream.writeInt(data.length); break; case Constants.BZIP2_COMPRESSION: compressedData = CompressionUtils.bzip2(data); stream.writeInt(compressedData.length); stream.writeInt(data.length); break; default: compressedData = data; stream.writeInt(data.length); break; } stream.writeBytes(compressedData); if (keys != null && keys.length == 4) stream.encodeXTEA(keys, 5, stream.getOffset()); if (revision != -1) stream.writeShort(revision); return stream.toByteArray(); } private void decompress(byte[] archive) { try { InputStream stream = new InputStream(archive); compression = stream.readUnsignedByte(); int length = stream.readInt(); if (keys != null && keys.length == 4) stream.decodeXTEA(keys, 5, length + (compression == Constants.NO_COMPRESSION ? 5 : 9)); if (length < 0 || length > Constants.MAX_VALID_ARCHIVE_LENGTH) throw new RuntimeException(""INVALID ARCHIVE HEADER""); switch (compression) { case Constants.NO_COMPRESSION: data = new byte[length]; stream.readBytes(data, 0, length); revision = -1; if (stream.getRemaining() >= 2) { revision = stream.readShort(); } break; case Constants.BZIP2_COMPRESSION: case Constants.GZIP_COMPRESSION: int uncompressedLength = stream.readInt(); if (uncompressedLength <= 0 || uncompressedLength > 1000000000) { data = null; break; } byte[] compressed = new byte[length]; stream.readBytes(compressed, 0, length); data = (compression == Constants.BZIP2_COMPRESSION ? CompressionUtils.bunzip2(compressed) : CompressionUtils.gunzip(compressed)); if (data.length != uncompressedLength) { throw new Exception(""Length mismatch. [ "" + data.length + "", "" + uncompressedLength + "" ]""); } revision = -1; if (stream.getRemaining() >= 2) { revision = stream.readShort(); } break; } } catch (Exception e) { System.out.println(""Exception loading archive: "" + id); } } public Object[] editNoRevision(byte[] data, MainFile mainFile) { this.data = data; byte[] compressed = compress(); if (!mainFile.putArchiveData(id, compressed)) return null; return new Object[] { CacheUtil.getCrcChecksum(compressed, compressed.length), Whirlpool.getWhirlpool(compressed, 0, compressed.length) }; } public int getId() { return id; } public byte[] getData() { return data; } public int getDecompressedLength() { return data.length; } public int getRevision() { return revision; } public void setRevision(int revision) { this.revision = revision; } public int getCompression() { return compression; } public int[] getKeys() { return keys; } public void setKeys(int[] keys) { this.keys = keys; } }" " package com.rs.cache; import java.util.Arrays; public class ArchiveReference { private int nameHash; private byte[] whirpool; private int crc; private int revision; private FileReference[] files; private int[] validFileIds; private boolean needsFilesSort; private boolean updatedRevision; public void updateRevision() { if (updatedRevision) return; revision++; updatedRevision = true; } public int getNameHash() { return nameHash; } public void setNameHash(int nameHash) { this.nameHash = nameHash; } public byte[] getWhirpool() { return whirpool; } public void setWhirpool(byte[] whirpool) { this.whirpool = whirpool; } public int getCRC() { return crc; } public void setCrc(int crc) { this.crc = crc; } public int getRevision() { return revision; } public FileReference[] getFiles() { return files; } public void setFiles(FileReference[] files) { this.files = files; } public void setRevision(int revision) { this.revision = revision; } public int[] getValidFileIds() { return validFileIds; } public void setValidFileIds(int[] validFileIds) { this.validFileIds = validFileIds; } public boolean isNeedsFilesSort() { return needsFilesSort; } public void setNeedsFilesSort(boolean needsFilesSort) { this.needsFilesSort = needsFilesSort; } public void removeFileReference(int fileId) { int[] newValidFileIds = new int[validFileIds.length - 1]; int count = 0; for (int id : validFileIds) { if (id == fileId) continue; newValidFileIds[count++] = id; } validFileIds = newValidFileIds; files[fileId] = null; } public void addEmptyFileReference(int fileId) { needsFilesSort = true; int[] newValidFileIds = Arrays.copyOf(validFileIds, validFileIds.length + 1); newValidFileIds[newValidFileIds.length - 1] = fileId; validFileIds = newValidFileIds; if (files.length <= fileId) { FileReference[] newFiles = Arrays.copyOf(files, fileId + 1); newFiles[fileId] = new FileReference(); files = newFiles; } else files[fileId] = new FileReference(); } public void sortFiles() { Arrays.sort(validFileIds); needsFilesSort = false; } public void reset() { whirpool = null; updatedRevision = true; revision = 0; nameHash = 0; crc = 0; files = new FileReference[0]; validFileIds = new int[0]; needsFilesSort = false; } public void copyHeader(ArchiveReference fromReference) { setCrc(fromReference.getCRC()); setNameHash(fromReference.getNameHash()); setWhirpool(fromReference.getWhirpool()); int[] validFiles = fromReference.getValidFileIds(); setValidFileIds(Arrays.copyOf(validFiles, validFiles.length)); FileReference[] files = fromReference.getFiles(); setFiles(Arrays.copyOf(files, files.length)); } } " " package com.rs.cache; public enum ArchiveType { UNDERLAYS(1), SCT_2(2), IDENTIKIT(3), OVERLAYS(4), INVENTORIES(5), OBJECTS(6, 8), SCT_7(7), ENUMS(8, 8), NPCS(9, 7), ITEMS(10, 8), PARAMS(11), ANIMATIONS(12, 7), SPOT_ANIMS(13, 8), VARBITS(14, 10), VARC_STRING(15), VARS(16), SCT_17(17), SCT_18(18), VARC(19), SCT_20(20), SCT_21(21), SCT_22(22), SCT_23(23), SCT_24(24), //varn SCT_25(25), //varnBit STRUCTS(26), SCT_27(27), SCT_28(28), SKYBOX(29), SUN(30), LIGHT_INTENSITIES(31), BAS(32), CURSORS(33), MAP_SPRITES(34), QUESTS(35), MAP_AREAS(36), SCT_37(37), SCT_38(38), SCT_39(39), SCT_40(40), SCT_41(41), SCT_42(42), SCT_43(43), SCT_44(44), SCT_45(45), HITSPLATS(46), CLAN_VAR(47), SCT_48(48), SCT_49(49), SCT_50(50), SCT_51(51), SCT_53(53), CLAN_VAR_SETTINGS(54), SCT_70(70), HITBARS(72), SCT_73(73), SCT_74(74); private int id, fileIdBitShift; private ArchiveType(int id) { this(id, 0); } ArchiveType(int id, int fileIdBitShift) { this.id = id; this.fileIdBitShift = fileIdBitShift; } public int getId() { return id; } public int filesPerContainer() { return 1 << this.fileIdBitShift; } public int archiveId(int id) { return id >>> this.fileIdBitShift; } public int fileId(int id) { return id & (1 << this.fileIdBitShift) - 1; } } " " package com.rs.cache; import java.io.IOException; import com.rs.lib.util.Logger; public final class Cache { public static Store STORE; private Cache() { } public static void init(String path) throws IOException { Logger.info(Cache.class, ""init"", ""Loading cache at ""+path+""...""); STORE = new Store(path, false); } } " " package com.rs.cache; public class FileReference { private int nameHash; public int getNameHash() { return nameHash; } public void setNameHash(int nameHash) { this.nameHash = nameHash; } } " " package com.rs.cache; import com.rs.lib.io.InputStream; import com.rs.lib.io.OutputStream; import com.rs.lib.util.Utils; public final class Huffman { private int[] huffmanAlgorithm1; private byte[] huffmanAlgorithm2; private int[] huffmanAlgorithm3; public Huffman(Store store) { loadAlgorithmValues(store); } public int sendEncryptMessage(OutputStream stream, String message) { try { int startOffset = stream.getOffset(); byte[] messageData = Utils.getFormatedMessage(message); stream.writeSmart(messageData.length); stream.checkCapacityPosition(stream.getOffset() + message.length() * 2); stream.skip(encryptMessage(stream.getOffset(), messageData.length, stream.getBuffer(), 0, messageData)); return stream.getOffset() - startOffset; } catch (Throwable e) { return -1; } } public final String readEncryptedMessage(InputStream stream) { return readEncryptedMessage(32767, stream); } public final String readEncryptedMessage(int maxLength, InputStream stream) { try { int messageDataLength = stream.readUnsignedSmart(); if (messageDataLength > maxLength) messageDataLength = maxLength; byte[] messageData = new byte[messageDataLength]; stream.skip(decryptMessage(messageData, messageDataLength, stream.getBuffer(), stream.getOffset(), 0)); String message = Utils.getUnformatedMessage(messageDataLength, 0, messageData); return message; } catch (Throwable e) { return """"; } } public final void loadAlgorithmValues(Store store) { byte[] huffmanFile = store.getIndex(IndexType.HUFFMAN).getFile(store.getIndex(IndexType.HUFFMAN).getArchiveId(""huffman"")); int fileLength = huffmanFile.length; huffmanAlgorithm2 = huffmanFile; huffmanAlgorithm1 = new int[fileLength]; huffmanAlgorithm3 = new int[8]; int[] is = new int[33]; int i_4_ = 0; for (int i_5_ = 0; (fileLength ^ 0xffffffff) < (i_5_ ^ 0xffffffff); i_5_++) { int i_6_ = huffmanFile[i_5_]; if (i_6_ != 0) { int i_7_ = 1 << 32 - i_6_; int i_8_ = is[i_6_]; huffmanAlgorithm1[i_5_] = i_8_; int i_9_; if ((i_8_ & i_7_) == 0) { for (int i_10_ = -1 + i_6_; i_10_ >= 1; i_10_--) { int i_11_ = is[i_10_]; if (i_8_ != i_11_) break; int i_12_ = 1 << 32 + -i_10_; if ((i_12_ & i_11_ ^ 0xffffffff) != -1) { is[i_10_] = is[-1 + i_10_]; break; } is[i_10_] = (i_11_ | i_12_); } i_9_ = i_7_ | i_8_; } else i_9_ = is[i_6_ + -1]; is[i_6_] = i_9_; for (int i_13_ = 1 + i_6_; i_13_ <= 32; i_13_++) { if (i_8_ == is[i_13_]) is[i_13_] = i_9_; } int i_14_ = 0; for (int i_15_ = 0; (i_6_ ^ 0xffffffff) < (i_15_ ^ 0xffffffff); i_15_++) { int i_16_ = -2147483648 >>> i_15_; if ((i_8_ & i_16_ ^ 0xffffffff) == -1) i_14_++; else { if (huffmanAlgorithm3[i_14_] == 0) huffmanAlgorithm3[i_14_] = i_4_; i_14_ = huffmanAlgorithm3[i_14_]; } if ((huffmanAlgorithm3.length ^ 0xffffffff) >= (i_14_ ^ 0xffffffff)) { int[] is_17_ = new int[huffmanAlgorithm3.length * 2]; for (int i_18_ = 0; i_18_ < huffmanAlgorithm3.length; i_18_++) is_17_[i_18_] = huffmanAlgorithm3[i_18_]; huffmanAlgorithm3 = is_17_; } i_16_ >>>= 1; } huffmanAlgorithm3[i_14_] = i_5_ ^ 0xffffffff; if ((i_4_ ^ 0xffffffff) >= (i_14_ ^ 0xffffffff)) i_4_ = 1 + i_14_; } } } public final int decryptMessage(byte[] messageData, int messagedDataLength, byte[] streamBuffer, int streamOffset, int messageDataOffset) { if ((messagedDataLength ^ 0xffffffff) == -1) return 0; int i = 0; messagedDataLength += messageDataOffset; int i_1_ = streamOffset; for (;;) { byte i_2_ = streamBuffer[i_1_]; if ((i_2_ ^ 0xffffffff) <= -1) i++; else i = huffmanAlgorithm3[i]; int i_3_; if ((i_3_ = huffmanAlgorithm3[i]) < 0) { messageData[messageDataOffset++] = (byte) (i_3_ ^ 0xffffffff); if (messagedDataLength <= messageDataOffset) break; i = 0; } if ((i_2_ & 0x40 ^ 0xffffffff) == -1) i++; else i = huffmanAlgorithm3[i]; if (((i_3_ = huffmanAlgorithm3[i]) ^ 0xffffffff) > -1) { messageData[messageDataOffset++] = (byte) (i_3_ ^ 0xffffffff); if (messagedDataLength <= messageDataOffset) break; i = 0; } if ((0x20 & i_2_ ^ 0xffffffff) != -1) i = huffmanAlgorithm3[i]; else i++; if ((i_3_ = huffmanAlgorithm3[i]) < 0) { messageData[messageDataOffset++] = (byte) (i_3_ ^ 0xffffffff); if (messagedDataLength <= messageDataOffset) break; i = 0; } if ((0x10 & i_2_ ^ 0xffffffff) != -1) i = huffmanAlgorithm3[i]; else i++; if ((i_3_ = huffmanAlgorithm3[i]) < 0) { messageData[messageDataOffset++] = (byte) (i_3_ ^ 0xffffffff); if ((messageDataOffset ^ 0xffffffff) <= (messagedDataLength ^ 0xffffffff)) break; i = 0; } if ((i_2_ & 0x8) == 0) i++; else i = huffmanAlgorithm3[i]; if ((i_3_ = huffmanAlgorithm3[i]) < 0) { messageData[messageDataOffset++] = (byte) (i_3_ ^ 0xffffffff); if (messageDataOffset >= messagedDataLength) break; i = 0; } if ((0x4 & i_2_ ^ 0xffffffff) != -1) i = huffmanAlgorithm3[i]; else i++; if (((i_3_ = huffmanAlgorithm3[i]) ^ 0xffffffff) > -1) { messageData[messageDataOffset++] = (byte) (i_3_ ^ 0xffffffff); if (messageDataOffset >= messagedDataLength) break; i = 0; } if ((0x2 & i_2_) != 0) i = huffmanAlgorithm3[i]; else i++; if (((i_3_ = huffmanAlgorithm3[i]) ^ 0xffffffff) > -1) { messageData[messageDataOffset++] = (byte) (i_3_ ^ 0xffffffff); if (messagedDataLength <= messageDataOffset) break; i = 0; } if ((0x1 & i_2_ ^ 0xffffffff) != -1) i = huffmanAlgorithm3[i]; else i++; if ((i_3_ = huffmanAlgorithm3[i]) < 0) { messageData[messageDataOffset++] = (byte) (i_3_ ^ 0xffffffff); if ((messageDataOffset ^ 0xffffffff) <= (messagedDataLength ^ 0xffffffff)) break; i = 0; } i_1_++; } return -streamOffset + i_1_ - -1; } public final int encryptMessage(int streamOffset, int messageDataLength, byte[] streamBuffer, int messageDataOffset, byte[] messageData) { int i = 0; messageDataLength += messageDataOffset; int i_19_ = streamOffset << 309760323; for (/**/; messageDataOffset < messageDataLength; messageDataOffset++) { int i_20_ = 0xff & messageData[messageDataOffset]; int i_21_ = huffmanAlgorithm1[i_20_]; int i_22_ = huffmanAlgorithm2[i_20_]; if (i_22_ == 0) throw new RuntimeException(""No codeword for data value "" + i_20_); int i_23_ = i_19_ >> -976077821; int i_24_ = 0x7 & i_19_; i &= -i_24_ >> -1041773793; int i_25_ = (-1 + i_24_ - -i_22_ >> -2003626461) + i_23_; i_19_ += i_22_; i_24_ += 24; streamBuffer[i_23_] = (byte) (i = (i | (i_21_ >>> i_24_))); if (i_25_ > i_23_) { i_24_ -= 8; i_23_++; streamBuffer[i_23_] = (byte) (i = i_21_ >>> i_24_); if ((i_23_ ^ 0xffffffff) > (i_25_ ^ 0xffffffff)) { i_24_ -= 8; i_23_++; streamBuffer[i_23_] = (byte) (i = i_21_ >>> i_24_); if ((i_23_ ^ 0xffffffff) > (i_25_ ^ 0xffffffff)) { i_24_ -= 8; i_23_++; streamBuffer[i_23_] = (byte) (i = i_21_ >>> i_24_); if ((i_25_ ^ 0xffffffff) < (i_23_ ^ 0xffffffff)) { i_23_++; i_24_ -= 8; streamBuffer[i_23_] = (byte) (i = i_21_ << -i_24_); } } } } } return -streamOffset + (7 + i_19_ >> 1737794179); } } " " package com.rs.cache; import java.util.zip.CRC32; import com.rs.cache.utils.CacheUtil; import com.rs.cache.utils.Constants; import com.rs.cache.utils.Whirlpool; import com.rs.lib.io.InputStream; import com.rs.lib.io.OutputStream; public final class Index { private MainFile mainFile; private MainFile index255; private ReferenceTable table; private byte[][][] cachedFiles; private int crc; private byte[] whirlpool; protected Index(MainFile index255, MainFile mainFile) { this.mainFile = mainFile; this.index255 = index255; byte[] archiveData = index255.getArchiveData(getId()); if (archiveData == null) return; crc = CacheUtil.getCrcChecksum(archiveData, archiveData.length); whirlpool = Whirlpool.getWhirlpool(archiveData, 0, archiveData.length); Archive archive = new Archive(getId(), archiveData, null); table = new ReferenceTable(archive); resetCachedFiles(); } public void resetCachedFiles() { cachedFiles = new byte[getLastArchiveId() + 1][][]; } public int getLastFileId(int archiveId) { if (!archiveExists(archiveId)) return -1; return table.getArchives()[archiveId].getFiles().length - 1; } public int getLastArchiveId() { return table.getArchives().length - 1; } public int getValidArchivesCount() { return table.getValidArchiveIds().length; } public int getValidFilesCount(int archiveId) { if (!archiveExists(archiveId)) return -1; return table.getArchives()[archiveId].getValidFileIds().length; } public boolean archiveExists(int archiveId) { if (archiveId < 0) return false; ArchiveReference[] archives = table.getArchives(); return archives.length > archiveId && archives[archiveId] != null; } public boolean fileExists(int archiveId, int fileId) { if (!archiveExists(archiveId)) return false; FileReference[] files = table.getArchives()[archiveId].getFiles(); return files.length > fileId && files[fileId] != null; } public int getArchiveId(String name) { int nameHash = CacheUtil.getNameHash(name); ArchiveReference[] archives = table.getArchives(); int[] validArchiveIds = table.getValidArchiveIds(); for (int archiveId : validArchiveIds) { if (archives[archiveId].getNameHash() == nameHash) return archiveId; } return -1; } public int getFileId(int archiveId, String name) { if (!archiveExists(archiveId)) return -1; int nameHash = CacheUtil.getNameHash(name); FileReference[] files = table.getArchives()[archiveId].getFiles(); int[] validFileIds = table.getArchives()[archiveId].getValidFileIds(); for (int index = 0; index < validFileIds.length; index++) { int fileId = validFileIds[index]; if (files[fileId].getNameHash() == nameHash) return fileId; } return -1; } public byte[] getFile(int archiveId) { if (!archiveExists(archiveId)) return null; return getFile(archiveId, table.getArchives()[archiveId].getValidFileIds()[0]); } public byte[] getFile(int archiveId, int fileId) { return getFile(archiveId, fileId, null); } public byte[] getFile(int archiveId, int fileId, int[] keys) { try { if (!fileExists(archiveId, fileId)) { return null; } if (cachedFiles[archiveId] == null || cachedFiles[archiveId][fileId] == null) cacheArchiveFiles(archiveId, keys); byte[] file = cachedFiles[archiveId][fileId]; cachedFiles[archiveId][fileId] = null; return file; } catch (Throwable e) { e.printStackTrace(); return null; } } public boolean packIndex(Store originalStore) { return packIndex(originalStore, false); } public boolean packIndex(Store originalStore, boolean checkCRC) { try { return packIndex(getRef(), originalStore, checkCRC); } catch (Exception e) { } return packIndex(getRef(), originalStore, checkCRC); } public boolean packIndex(IndexType index, Store originalStore, boolean checkCRC) { try { Index originalIndex = originalStore.getIndex(index); for (int archiveId : originalIndex.table.getValidArchiveIds()) { if (checkCRC && archiveExists(archiveId) && originalIndex.table.getArchives()[archiveId].getCRC() == table.getArchives()[archiveId].getCRC()) continue; if (!putArchive(index, archiveId, originalStore, false, false)) return false; } if (!rewriteTable()) return false; resetCachedFiles(); return true; } catch (Exception e) { } return true; } public boolean putArchive(int archiveId, Store originalStore) { return putArchive(getRef(), archiveId, originalStore, true, true); } public boolean putArchive(int archiveId, Store originalStore, boolean rewriteTable, boolean resetCache) { return putArchive(getRef(), archiveId, originalStore, rewriteTable, resetCache); } public boolean putArchive(IndexType index, int archiveId, Store originalStore, boolean rewriteTable, boolean resetCache) { try { Index originalIndex = originalStore.getIndex(index); byte[] data = originalIndex.getMainFile().getArchiveData(archiveId); if (data == null) return false; if (!archiveExists(archiveId)) table.addEmptyArchiveReference(archiveId); ArchiveReference reference = table.getArchives()[archiveId]; reference.updateRevision(); ArchiveReference originalReference = originalIndex.table.getArchives()[archiveId]; reference.copyHeader(originalReference); int revision = reference.getRevision(); data[data.length - 2] = (byte) (revision >> 8); data[data.length - 1] = (byte) revision; if (!mainFile.putArchiveData(archiveId, data)) return false; if (rewriteTable && !rewriteTable()) return false; if (resetCache) resetCachedFiles(); return true; } catch (Exception e) { e.printStackTrace(); } return true; } public boolean putArchive(int archiveId, byte[] data) { return putFile(archiveId, 0, data); } public boolean putFile(int archiveId, int fileId, byte[] data) { return putFile(archiveId, fileId, Constants.GZIP_COMPRESSION, data, null, true, true, -1, -1); } public boolean removeFile(int archiveId, int fileId) { return removeFile(archiveId, fileId, Constants.GZIP_COMPRESSION, null); } public boolean removeFile(int archiveId, int fileId, int compression, int[] keys) { if (!fileExists(archiveId, fileId)) return false; cacheArchiveFiles(archiveId, keys); ArchiveReference reference = table.getArchives()[archiveId]; reference.removeFileReference(fileId); int filesCount = getValidFilesCount(archiveId); byte[] archiveData; if (filesCount == 1) archiveData = getFile(archiveId, reference.getValidFileIds()[0], keys); else { int[] filesSize = new int[filesCount]; OutputStream stream = new OutputStream(); for (int index = 0; index < filesCount; index++) { int id = reference.getValidFileIds()[index]; byte[] fileData = getFile(archiveId, id, keys); filesSize[index] = fileData.length; stream.writeBytes(fileData); } for (int index = 0; index < filesSize.length; index++) { int offset = filesSize[index]; if (index != 0) offset -= filesSize[index - 1]; stream.writeInt(offset); } stream.writeByte(1); // 1loop archiveData = new byte[stream.getOffset()]; stream.setOffset(0); stream.getBytes(archiveData, 0, archiveData.length); } reference.updateRevision(); Archive archive = new Archive(archiveId, compression, reference.getRevision(), archiveData); byte[] closedArchive = archive.compress(); CRC32 crc = new CRC32(); crc.update(closedArchive, 0, closedArchive.length - 2); reference.setCrc((int) crc.getValue()); reference.setWhirpool(Whirlpool.getWhirlpool(closedArchive, 0, closedArchive.length - 2)); if (!mainFile.putArchiveData(archiveId, closedArchive)) return false; if (!rewriteTable()) return false; resetCachedFiles(); return true; } public boolean putFile(int archiveId, int fileId, int compression, byte[] data, int[] keys, boolean rewriteTable, boolean resetCache, int archiveName, int fileName) { if (!archiveExists(archiveId)) { table.addEmptyArchiveReference(archiveId); resetCachedFiles(); cachedFiles[archiveId] = new byte[1][]; } else cacheArchiveFiles(archiveId, keys); ArchiveReference reference = table.getArchives()[archiveId]; if (!fileExists(archiveId, fileId)) reference.addEmptyFileReference(fileId); reference.sortFiles(); int filesCount = getValidFilesCount(archiveId); byte[] archiveData; if (filesCount == 1) archiveData = data; else { int[] filesSize = new int[filesCount]; OutputStream stream = new OutputStream(); for (int index = 0; index < filesCount; index++) { int id = reference.getValidFileIds()[index]; byte[] fileData; if (id == fileId) fileData = data; else fileData = getFile(archiveId, id, keys); filesSize[index] = fileData.length; stream.writeBytes(fileData); } for (int index = 0; index < filesCount; index++) { int offset = filesSize[index]; if (index != 0) offset -= filesSize[index - 1]; stream.writeInt(offset); } stream.writeByte(1); // 1loop archiveData = new byte[stream.getOffset()]; stream.setOffset(0); stream.getBytes(archiveData, 0, archiveData.length); } reference.updateRevision(); Archive archive = new Archive(archiveId, compression, reference.getRevision(), archiveData); byte[] closedArchive = archive.compress(); reference.setCrc(CacheUtil.getCrcChecksum(closedArchive, closedArchive.length - 2)); reference.setWhirpool(Whirlpool.getWhirlpool(closedArchive, 0, closedArchive.length - 2)); if (archiveName != -1) reference.setNameHash(archiveName); if (fileName != -1) reference.getFiles()[fileId].setNameHash(fileName); if (!mainFile.putArchiveData(archiveId, closedArchive)) return false; if (rewriteTable && !rewriteTable()) return false; if (resetCache) resetCachedFiles(); return true; } public boolean encryptArchive(int archiveId, int[] keys) { return encryptArchive(archiveId, null, keys, true, true); } public boolean encryptArchive(int archiveId, int[] oldKeys, int[] keys, boolean rewriteTable, boolean resetCache) { if (!archiveExists(archiveId)) return false; Archive archive = mainFile.getArchive(archiveId, oldKeys); if (archive == null) return false; ArchiveReference reference = table.getArchives()[archiveId]; if (reference.getRevision() != archive.getRevision()) throw new RuntimeException(""ERROR REVISION""); reference.updateRevision(); archive.setRevision(reference.getRevision()); archive.setKeys(keys); byte[] closedArchive = archive.compress(); reference.setCrc(CacheUtil.getCrcChecksum(closedArchive, closedArchive.length - 2)); reference.setWhirpool(Whirlpool.getWhirlpool(closedArchive, 0, closedArchive.length - 2)); if (!mainFile.putArchiveData(archiveId, closedArchive)) return false; if (rewriteTable && !rewriteTable()) return false; if (resetCache) resetCachedFiles(); return true; } public boolean rewriteTable() { table.updateRevision(); table.sortTable(); Object[] hashes = table.encodeHeader(index255); if (hashes == null) return false; crc = (int) hashes[0]; whirlpool = (byte[]) hashes[1]; return true; } public void setKeys(int[] keys) { table.setKeys(keys); } public int[] getKeys() { return table.getKeys(); } private void cacheArchiveFiles(int archiveId, int[] keys) { Archive archive = getArchive(archiveId, keys); int lastFileId = getLastFileId(archiveId); cachedFiles[archiveId] = new byte[lastFileId + 1][]; if (archive == null) return; byte[] data = archive.getData(); if (data == null) return; int filesCount = getValidFilesCount(archiveId); if (filesCount == 1) cachedFiles[archiveId][lastFileId] = data; else { int readPosition = data.length; int amtOfLoops = data[--readPosition] & 0xff; readPosition -= amtOfLoops * (filesCount * 4); InputStream stream = new InputStream(data); stream.setOffset(readPosition); int filesSize[] = new int[filesCount]; for (int loop = 0; loop < amtOfLoops; loop++) { int offset = 0; for (int i = 0; i < filesCount; i++) filesSize[i] += offset += stream.readInt(); } byte[][] filesData = new byte[filesCount][]; for (int i = 0; i < filesCount; i++) { filesData[i] = new byte[filesSize[i]]; filesSize[i] = 0; } stream.setOffset(readPosition); int sourceOffset = 0; for (int loop = 0; loop < amtOfLoops; loop++) { int dataRead = 0; for (int i = 0; i < filesCount; i++) { dataRead += stream.readInt(); System.arraycopy(data, sourceOffset, filesData[i], filesSize[i], dataRead); sourceOffset += dataRead; filesSize[i] += dataRead; } } int count = 0; for (int fileId : table.getArchives()[archiveId].getValidFileIds()) cachedFiles[archiveId][fileId] = filesData[count++]; } } public IndexType getRef() { return IndexType.values()[mainFile.getId()]; } public int getId() { return mainFile.getId(); } public ReferenceTable getTable() { return table; } public MainFile getMainFile() { return mainFile; } public Archive getArchive(int id) { return mainFile.getArchive(id, null); } public Archive getArchive(int id, int[] keys) { return mainFile.getArchive(id, keys); } public int getCRC() { return crc; } public byte[] getWhirlpool() { return whirlpool; } }" " package com.rs.cache; public enum IndexType { ANIMATION_FRAME_SETS(0), ANIMATION_FRAME_BASES(1), CONFIG(2), INTERFACES(3), SOUND_EFFECTS(4), MAPS(5), MUSIC(6), MODELS(7), SPRITES(8), MATERIALS(9), HUFFMAN(10), MUSIC2(11), CS2_SCRIPTS(12), FONT_METRICS(13), MIDI_INSTRUMENTS(14), SOUND_EFFECTS_MIDI(15), OBJECTS(16), ENUMS(17), NPCS(18), ITEMS(19), ANIMATIONS(20), SPOT_ANIMS(21), VARBITS(22), MAP_AREAS(23), QC_MESSAGES(24), QC_MENUS(25), TEXTURES(26), PARTICLES(27), DEFAULTS(28), BILLBOARDS(29), NATIVE_LIBRARIES(30), SHADERS(31), NORMAL_FONTS(32), GAME_TIPS(33), JAGEX_FONTS(34), CUTSCENES(35), VORBIS(36); private int id; private IndexType(int id) { this.id = id; } public int getId() { return id; } } " " package com.rs.cache; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; /* * Created by Alex(Dragonkk) * 23/10/11 */ public final class MainFile { private static final int IDX_BLOCK_LEN = 6; private static final int HEADER_LEN = 8; private static final int EXPANDED_HEADER_LEN = 10; private static final int BLOCK_LEN = 512; private static final int EXPANDED_BLOCK_LEN = 510; private static final int TOTAL_BLOCK_LEN = HEADER_LEN + BLOCK_LEN; private static final ByteBuffer tempBuffer = ByteBuffer.allocateDirect(TOTAL_BLOCK_LEN); private int id; private FileChannel index; private FileChannel data; protected MainFile(int id, RandomAccessFile data, RandomAccessFile index) throws IOException { this.id = id; this.data = data.getChannel(); this.index = index.getChannel(); } public Archive getArchive(int id) { return getArchive(id, null); } public Archive getArchive(int id, int[] keys) { byte[] data = getArchiveData(id); if (data == null) return null; return new Archive(id, data, keys); } public byte[] getArchiveData(int archiveId) { synchronized (data) { try { tempBuffer.position(0).limit(IDX_BLOCK_LEN); index.read(tempBuffer, archiveId * IDX_BLOCK_LEN); tempBuffer.flip(); int size = getMediumInt(tempBuffer); int block = getMediumInt(tempBuffer); if (size < 0) return null; if (block <= 0 || block > data.size() / TOTAL_BLOCK_LEN) { return null; } ByteBuffer fileBuffer = ByteBuffer.allocate(size); int remaining = size; int chunk = 0; int blockLen = archiveId <= 0xffff ? BLOCK_LEN : EXPANDED_BLOCK_LEN; int headerLen = archiveId <= 0xffff ? HEADER_LEN : EXPANDED_HEADER_LEN; while (remaining > 0) { if (block == 0) { System.out.println(archiveId + "", ""); return null; } int blockSize = remaining > blockLen ? blockLen : remaining; tempBuffer.position(0).limit(blockSize + headerLen); data.read(tempBuffer, block * TOTAL_BLOCK_LEN); tempBuffer.flip(); int currentFile, currentChunk, nextBlock, currentIndex; if (archiveId <= 65535) { currentFile = tempBuffer.getShort() & 0xffff; currentChunk = tempBuffer.getShort() & 0xffff; nextBlock = getMediumInt(tempBuffer); currentIndex = tempBuffer.get() & 0xff; } else { currentFile = tempBuffer.getInt(); currentChunk = tempBuffer.getShort() & 0xffff; nextBlock = getMediumInt(tempBuffer); currentIndex = tempBuffer.get() & 0xff; } if ((archiveId != currentFile && archiveId <= 65535) || chunk != currentChunk || id != currentIndex) { return null; } if (nextBlock < 0 || nextBlock > data.size() / TOTAL_BLOCK_LEN) { return null; } fileBuffer.put(tempBuffer); remaining -= blockSize; block = nextBlock; chunk++; } return (byte[]) fileBuffer.flip().array(); } catch (Exception ex) { return null; } } } private static int getMediumInt(ByteBuffer buffer) { return ((buffer.get() & 0xff) << 16) | ((buffer.get() & 0xff) << 8) | (buffer.get() & 0xff); } private static void putMediumInt(ByteBuffer buffer, int val) { buffer.put((byte) (val >> 16)); buffer.put((byte) (val >> 8)); buffer.put((byte) val); } public boolean putArchive(Archive archive) { return putArchiveData(archive.getId(), archive.getData()); } public boolean putArchiveData(int id, byte[] archive) { ByteBuffer buffer = ByteBuffer.wrap(archive); boolean done = putArchiveData(id, buffer, archive.length, false); if (!done) done = putArchiveData(id, buffer, archive.length, true); return done; } public boolean putArchiveData(int archiveId, ByteBuffer archive, int size, boolean exists) { synchronized (data) { try { int block; if (exists) { if (archiveId * IDX_BLOCK_LEN + IDX_BLOCK_LEN > index.size()) { return false; } tempBuffer.position(0).limit(IDX_BLOCK_LEN); index.read(tempBuffer, archiveId * IDX_BLOCK_LEN); tempBuffer.flip().position(3); block = getMediumInt(tempBuffer); if (block <= 0 || block > data.size() / TOTAL_BLOCK_LEN) { return false; } } else { block = (int) (data.size() + TOTAL_BLOCK_LEN - 1) / TOTAL_BLOCK_LEN; if (block == 0) { block = 1; } } tempBuffer.position(0); putMediumInt(tempBuffer, size); putMediumInt(tempBuffer, block); tempBuffer.flip(); index.write(tempBuffer, archiveId * IDX_BLOCK_LEN); int remaining = size; int chunk = 0; int blockLen = archiveId <= 0xffff ? BLOCK_LEN : EXPANDED_BLOCK_LEN; int headerLen = archiveId <= 0xffff ? HEADER_LEN : EXPANDED_HEADER_LEN; while (remaining > 0) { int nextBlock = 0; if (exists) { tempBuffer.position(0).limit(headerLen); data.read(tempBuffer, block * TOTAL_BLOCK_LEN); tempBuffer.flip(); int currentFile, currentChunk, currentIndex; if (archiveId <= 0xffff) { currentFile = tempBuffer.getShort() & 0xffff; currentChunk = tempBuffer.getShort() & 0xffff; nextBlock = getMediumInt(tempBuffer); currentIndex = tempBuffer.get() & 0xff; } else { currentFile = tempBuffer.getInt(); currentChunk = tempBuffer.getShort() & 0xffff; nextBlock = getMediumInt(tempBuffer); currentIndex = tempBuffer.get() & 0xff; } if ((archiveId != currentFile && archiveId <= 65535) || chunk != currentChunk || id != currentIndex) { return false; } if (nextBlock < 0 || nextBlock > data.size() / TOTAL_BLOCK_LEN) { return false; } } if (nextBlock == 0) { exists = false; nextBlock = (int) ((data.size() + TOTAL_BLOCK_LEN - 1) / TOTAL_BLOCK_LEN); if (nextBlock == 0) { nextBlock = 1; } if (nextBlock == block) { nextBlock++; } } if (remaining <= blockLen) { nextBlock = 0; } tempBuffer.position(0).limit(TOTAL_BLOCK_LEN); if (archiveId <= 0xffff) { tempBuffer.putShort((short) archiveId); tempBuffer.putShort((short) chunk); putMediumInt(tempBuffer, nextBlock); tempBuffer.put((byte) id); } else { tempBuffer.putInt(archiveId); tempBuffer.putShort((short) chunk); putMediumInt(tempBuffer, nextBlock); tempBuffer.put((byte) id); } int blockSize = remaining > blockLen ? blockLen : remaining; archive.limit(archive.position() + blockSize); tempBuffer.put(archive); tempBuffer.flip(); data.write(tempBuffer, block * TOTAL_BLOCK_LEN); remaining -= blockSize; block = nextBlock; chunk++; } return true; } catch (Exception ex) { return false; } } } public int getId() { return id; } public int getArchivesCount() throws IOException { synchronized (index) { return (int) (index.size() / 6); } } }" " package com.rs.cache; import java.util.Arrays; import com.rs.lib.io.InputStream; import com.rs.lib.io.OutputStream; public final class ReferenceTable { private Archive archive; private int revision; private boolean named; private boolean usesWhirpool; private ArchiveReference[] archives; private int[] validArchiveIds; // editing private boolean updatedRevision; private boolean needsArchivesSort; protected ReferenceTable(Archive archive) { this.archive = archive; decodeHeader(); } public void setKeys(int[] keys) { archive.setKeys(keys); } public int[] getKeys() { return archive.getKeys(); } public void sortArchives() { Arrays.sort(validArchiveIds); needsArchivesSort = false; } public void addEmptyArchiveReference(int archiveId) { needsArchivesSort = true; int[] newValidArchiveIds = Arrays.copyOf(validArchiveIds, validArchiveIds.length + 1); newValidArchiveIds[newValidArchiveIds.length - 1] = archiveId; validArchiveIds = newValidArchiveIds; ArchiveReference reference; if (archives.length <= archiveId) { ArchiveReference[] newArchives = Arrays.copyOf(archives, archiveId + 1); reference = newArchives[archiveId] = new ArchiveReference(); archives = newArchives; } else reference = archives[archiveId] = new ArchiveReference(); reference.reset(); } public void sortTable() { if (needsArchivesSort) sortArchives(); for (int index = 0; index < validArchiveIds.length; index++) { ArchiveReference archive = archives[validArchiveIds[index]]; if (archive.isNeedsFilesSort()) archive.sortFiles(); } } public Object[] encodeHeader(MainFile mainFile) { OutputStream stream = new OutputStream(); int protocol = getProtocol(); stream.writeByte(protocol); if (protocol >= 6) stream.writeInt(revision); stream.writeByte((named ? 0x1 : 0) | (usesWhirpool ? 0x2 : 0)); if (protocol >= 7) stream.writeBigSmart(validArchiveIds.length); else stream.writeShort(validArchiveIds.length); for (int index = 0; index < validArchiveIds.length; index++) { int offset = validArchiveIds[index]; if (index != 0) offset -= validArchiveIds[index - 1]; if (protocol >= 7) stream.writeBigSmart(offset); else stream.writeShort(offset); } if (named) for (int index = 0; index < validArchiveIds.length; index++) stream.writeInt(archives[validArchiveIds[index]].getNameHash()); for (int index = 0; index < validArchiveIds.length; index++) stream.writeInt(archives[validArchiveIds[index]].getCRC()); if (usesWhirpool) for (int index = 0; index < validArchiveIds.length; index++) stream.writeBytes(archives[validArchiveIds[index]].getWhirpool()); for (int index = 0; index < validArchiveIds.length; index++) stream.writeInt(archives[validArchiveIds[index]].getRevision()); for (int index = 0; index < validArchiveIds.length; index++) { int value = archives[validArchiveIds[index]].getValidFileIds().length; if (protocol >= 7) stream.writeBigSmart(value); else stream.writeShort(value); } for (int index = 0; index < validArchiveIds.length; index++) { ArchiveReference archive = archives[validArchiveIds[index]]; for (int index2 = 0; index2 < archive.getValidFileIds().length; index2++) { int offset = archive.getValidFileIds()[index2]; if (index2 != 0) offset -= archive.getValidFileIds()[index2 - 1]; if (protocol >= 7) stream.writeBigSmart(offset); else stream.writeShort(offset); } } if (named) { for (int index = 0; index < validArchiveIds.length; index++) { ArchiveReference archive = archives[validArchiveIds[index]]; for (int index2 = 0; index2 < archive.getValidFileIds().length; index2++) stream.writeInt(archive.getFiles()[archive.getValidFileIds()[index2]].getNameHash()); } } byte[] data = new byte[stream.getOffset()]; stream.setOffset(0); stream.getBytes(data, 0, data.length); return archive.editNoRevision(data, mainFile); } public int getProtocol() { if (archives.length > 65535) return 7; for (int index = 0; index < validArchiveIds.length; index++) { if (index > 0) if (validArchiveIds[index] - validArchiveIds[index - 1] > 65535) return 7; if (archives[validArchiveIds[index]].getValidFileIds().length > 65535) return 7; } return revision == 0 ? 5 : 6; } public void setRevision(int revision) { updatedRevision = true; this.revision = revision; } public void updateRevision() { if (updatedRevision) return; revision++; updatedRevision = true; } private void decodeHeader() { InputStream stream = new InputStream(archive.getData()); int protocol = stream.readUnsignedByte(); if (protocol < 5 || protocol > 7) throw new RuntimeException(""INVALID PROTOCOL""); if (protocol >= 6) revision = stream.readInt(); int hash = stream.readUnsignedByte(); named = (0x1 & hash) != 0; usesWhirpool = (0x2 & hash) != 0; int validArchivesCount = protocol >= 7 ? stream.readBigSmart() : stream.readUnsignedShort(); validArchiveIds = new int[validArchivesCount]; int lastArchiveId = 0; int biggestArchiveId = 0; for (int index = 0; index < validArchivesCount; index++) { int archiveId = lastArchiveId += protocol >= 7 ? stream.readBigSmart() : stream.readUnsignedShort(); if (archiveId > biggestArchiveId) biggestArchiveId = archiveId; validArchiveIds[index] = archiveId; } archives = new ArchiveReference[biggestArchiveId + 1]; for (int index = 0; index < validArchivesCount; index++) archives[validArchiveIds[index]] = new ArchiveReference(); if (named) for (int index = 0; index < validArchivesCount; index++) archives[validArchiveIds[index]].setNameHash(stream.readInt()); for (int index = 0; index < validArchivesCount; index++) archives[validArchiveIds[index]].setCrc(stream.readInt()); if (usesWhirpool) { for (int index = 0; index < validArchivesCount; index++) { byte[] whirpool = new byte[64]; stream.getBytes(whirpool, 0, 64); archives[validArchiveIds[index]].setWhirpool(whirpool); } } for (int index = 0; index < validArchivesCount; index++) archives[validArchiveIds[index]].setRevision(stream.readInt()); for (int index = 0; index < validArchivesCount; index++) archives[validArchiveIds[index]].setValidFileIds(new int[protocol >= 7 ? stream.readBigSmart() : stream.readUnsignedShort()]); for (int index = 0; index < validArchivesCount; index++) { int lastFileId = 0; int biggestFileId = 0; ArchiveReference archive = archives[validArchiveIds[index]]; for (int index2 = 0; index2 < archive.getValidFileIds().length; index2++) { int fileId = lastFileId += protocol >= 7 ? stream.readBigSmart() : stream.readUnsignedShort(); if (fileId > biggestFileId) biggestFileId = fileId; archive.getValidFileIds()[index2] = fileId; } archive.setFiles(new FileReference[biggestFileId + 1]); for (int index2 = 0; index2 < archive.getValidFileIds().length; index2++) archive.getFiles()[archive.getValidFileIds()[index2]] = new FileReference(); } if (named) { for (int index = 0; index < validArchivesCount; index++) { ArchiveReference archive = archives[validArchiveIds[index]]; for (int index2 = 0; index2 < archive.getValidFileIds().length; index2++) archive.getFiles()[archive.getValidFileIds()[index2]].setNameHash(stream.readInt()); } } } public int getRevision() { return revision; } public ArchiveReference[] getArchives() { return archives; } public int[] getValidArchiveIds() { return validArchiveIds; } public boolean isNamed() { return named; } public boolean usesWhirpool() { return usesWhirpool; } public int getCompression() { return archive.getCompression(); } }" " package com.rs.cache; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.math.BigInteger; import java.util.Arrays; import com.rs.cache.utils.CacheUtil; import com.rs.cache.utils.Whirlpool; import com.rs.lib.io.OutputStream; public final class Store { private Index[] indexes; private MainFile index255; private String path; private RandomAccessFile data; private Huffman huffman; public Store(String path, boolean newProtocol) throws IOException { this.path = path; data = new RandomAccessFile(path + ""main_file_cache.dat2"", ""rw""); index255 = new MainFile(255, data, new RandomAccessFile(path + ""main_file_cache.idx255"", ""rw"")); int idxsCount = index255.getArchivesCount(); indexes = new Index[idxsCount]; for (int id = 0; id < idxsCount; id++) { if (id == 47) continue; Index index = new Index(index255, new MainFile(id, data, new RandomAccessFile(path + ""main_file_cache.idx"" + id, ""rw""))); if (index.getTable() == null) continue; indexes[id] = index; } huffman = new Huffman(this); } public Store(String path) throws IOException { this(path, false); } public final byte[] getChecksumContainer(BigInteger rsaExp, BigInteger rsaMod) { byte[] checksumTable = getChecksumTable(rsaExp, rsaMod); OutputStream out = new OutputStream(); out.writeByte(255); out.writeInt(255); out.writeByte(0); out.writeInt(checksumTable.length); int offset = 10; for (int index = 0; index < checksumTable.length; index++) { if (offset == 512) { out.writeByte(255); offset = 1; } out.writeByte(checksumTable[index]); offset++; } return out.toByteArray(); } public final byte[] getChecksumTable(BigInteger rsaExp, BigInteger rsaMod) { OutputStream os = new OutputStream(); os.writeByte(indexes.length); for (int i = 0;i < indexes.length;i++) { os.writeInt(indexes[i].getCRC()); os.writeInt(indexes[i].getTable().getRevision()); os.writeBytes(indexes[i].getWhirlpool()); } byte[] archive = os.toByteArray(); OutputStream temp = new OutputStream(65); temp.writeByte(0); temp.writeBytes(Whirlpool.getWhirlpool(archive, 0, archive.length)); os.writeBytes(CacheUtil.cryptRSA(temp.toByteArray(), rsaExp, rsaMod)); return os.toByteArray(); } public Index getIndex(IndexType index) { return indexes[index.ordinal()]; } public Index[] getIndices() { return indexes; } public MainFile getIndex255() { return index255; } /* * returns index */ public int addIndex(boolean named, boolean usesWhirpool, int tableCompression) throws IOException { int id = indexes.length; Index[] newIndexes = Arrays.copyOf(indexes, indexes.length + 1); resetIndex(id, newIndexes, named, usesWhirpool, tableCompression); indexes = newIndexes; return id; } public void resetIndex(int id, boolean named, boolean usesWhirpool, int tableCompression) throws FileNotFoundException, IOException { resetIndex(id, indexes, named, usesWhirpool, tableCompression); } public void resetIndex(int id, Index[] indexes, boolean named, boolean usesWhirpool, int tableCompression) throws FileNotFoundException, IOException { OutputStream stream = new OutputStream(4); stream.writeByte(5); stream.writeByte((named ? 0x1 : 0) | (usesWhirpool ? 0x2 : 0)); stream.writeShort(0); byte[] archiveData = new byte[stream.getOffset()]; stream.setOffset(0); stream.getBytes(archiveData, 0, archiveData.length); Archive archive = new Archive(id, tableCompression, -1, archiveData); index255.putArchiveData(id, archive.compress()); indexes[id] = new Index(index255, new MainFile(id, data, new RandomAccessFile(path + ""main_file_cache.idx"" + id, ""rw""))); } public Huffman getHuffman() { return huffman; } } " " package com.rs.cache.loaders; import java.util.concurrent.ConcurrentHashMap; import com.rs.cache.ArchiveType; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.lib.io.InputStream; public final class MapSpriteDefinitions { private static final ConcurrentHashMap defs = new ConcurrentHashMap(); public boolean aBool7726 = false; public int anInt7727; public int spriteId; int[] anIntArray7730; public int id; public static final MapSpriteDefinitions getMapSpriteDefinitions(int id) { MapSpriteDefinitions script = defs.get(id); if (script != null)// open new txt document return script; byte[] data = Cache.STORE.getIndex(IndexType.CONFIG).getFile(ArchiveType.MAP_SPRITES.getId(), id); script = new MapSpriteDefinitions(); script.id = id; if (data != null) script.readValueLoop(new InputStream(data)); defs.put(id, script); return script; } private MapSpriteDefinitions() { } private void readValueLoop(InputStream stream) { for (;;) { int opcode = stream.readUnsignedByte(); if (opcode == 0) break; readValues(stream, opcode); } } private void readValues(InputStream stream, int i) { if (i == 1) spriteId = stream.readBigSmart(); else if (2 == i) anInt7727 = stream.read24BitInt(); else if (i == 3) aBool7726 = true; else if (4 == i) spriteId = -1; } } " " package com.rs.cache.loaders; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.concurrent.ConcurrentHashMap; import com.rs.cache.ArchiveType; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.lib.io.InputStream; import com.rs.lib.util.Utils; public final class AreaDefinitions { private static final ConcurrentHashMap defs = new ConcurrentHashMap(); public int anInt2715; public int[] anIntArray2717; public int anInt2718; public int spriteId = -1; public int anInt2720; public int anInt2721; public int anInt2722; public int anInt2726; public int anInt2727; public boolean aBool2728; public boolean aBool2729; public boolean aBool2730; public int anInt2731; public String aString2732; int anInt2733; int anInt2734; int anInt2735; int anInt2736; public int[] anIntArray2738; int anInt2739; public String[] options; int anInt2741; public boolean aBool2742; int anInt2743; public int anInt2744; int anInt2745; public int anInt2746; public int anInt2747; public int anInt2748; public int anInt2749; public int anInt2750; public String areaName; public int anInt2752; public int anInt2753; public byte[] aByteArray2754; int anInt2755; public int anInt2756; public int anInt2757 = -1; public HashMap clientScriptMap = new HashMap(); public int id; public static final AreaDefinitions getDefinitions(int id) { AreaDefinitions area = defs.get(id); if (area != null) return area; byte[] data = Cache.STORE.getIndex(IndexType.CONFIG).getFile(ArchiveType.MAP_AREAS.getId(), id); area = new AreaDefinitions(); area.id = id; if (data != null) area.readValueLoop(new InputStream(data)); defs.put(id, area); return area; } public static void dump() throws IOException { File file = new File(""worldMap.txt""); if (file.exists()) file.delete(); else file.createNewFile(); BufferedWriter writer = new BufferedWriter(new FileWriter(file));; writer.append(""//Version = 727\n""); writer.flush(); for (int i = 0;i < Cache.STORE.getIndex(IndexType.CONFIG).getLastFileId(ArchiveType.MAP_AREAS.getId())+1;i++) { AreaDefinitions defs = getDefinitions(i); writer.append(i+"" - ""+defs); writer.newLine(); writer.flush(); } writer.close(); } AreaDefinitions() { options = new String[5]; anInt2722 = 0; aBool2728 = true; aBool2729 = false; aBool2730 = true; aBool2742 = true; } private void readValueLoop(InputStream stream) { for (;;) { int opcode = stream.readUnsignedByte(); if (opcode == 0) break; readValues(stream, opcode); } } private void readValues(InputStream stream, int i) { if (1 == i) spriteId = stream.readBigSmart(); else if (2 == i) anInt2757 = stream.readBigSmart(); else if (i == 3) areaName = stream.readString(); else if (4 == i) anInt2720 = stream.read24BitInt(); else if (5 == i) anInt2721 = stream.read24BitInt(); else if (i == 6) anInt2722 = stream.readUnsignedByte(); else if (i == 7) { int i_3_ = stream.readUnsignedByte(); if ((i_3_ & 0x1) == 0) aBool2728 = false; if (2 == (i_3_ & 0x2)) aBool2729 = true; } else if (i == 8) aBool2730 = stream.readUnsignedByte() == 1; else if (i == 9) { anInt2736 = stream.readUnsignedShort(); if (anInt2736 == 65535) anInt2736 = -1; anInt2745 = stream.readUnsignedShort(); if (anInt2745 == 65535) anInt2745 = 1; anInt2734 = stream.readInt(); anInt2735 = stream.readInt(); } else if (i >= 10 && i <= 14) options[i - 10] = stream.readString(); else if (15 == i) { int i_4_ = stream.readUnsignedByte(); anIntArray2717 = new int[2 * i_4_]; for (int i_5_ = 0; i_5_ < i_4_ * 2; i_5_++) anIntArray2717[i_5_] = stream.readShort(); anInt2715 = stream.readInt(); int i_6_ = stream.readUnsignedByte(); anIntArray2738 = new int[i_6_]; for (int i_7_ = 0; i_7_ < anIntArray2738.length; i_7_++) anIntArray2738[i_7_] = stream.readInt(); aByteArray2754 = new byte[i_4_]; for (int i_8_ = 0; i_8_ < i_4_; i_8_++) aByteArray2754[i_8_] = (byte) stream.readByte(); } else if (i == 16) aBool2742 = false; else if (17 == i) aString2732 = stream.readString(); else if (i == 18) anInt2733 = stream.readBigSmart(); else if (19 == i) anInt2718 = stream.readUnsignedShort(); else if (20 == i) { anInt2755 = stream.readUnsignedShort(); if (65535 == anInt2755) anInt2755 = 1; anInt2741 = stream.readUnsignedShort(); if (anInt2741 == 65535) anInt2741 = 1; anInt2743 = stream.readInt(); anInt2739 = stream.readInt(); } else if (i == 21) anInt2727 = stream.readInt(); else if (22 == i) anInt2726 = stream.readInt(); else if (23 == i) { anInt2748 = stream.readUnsignedByte(); anInt2749 = stream.readUnsignedByte(); anInt2756 = stream.readUnsignedByte(); } else if (24 == i) { anInt2750 = stream.readShort(); anInt2752 = stream.readShort(); } else if (i == 249) { int i_19_ = stream.readUnsignedByte(); for (int i_21_ = 0; i_21_ < i_19_; i_21_++) { boolean bool = stream.readUnsignedByte() == 1; int i_22_ = stream.read24BitInt(); if (bool) clientScriptMap.put(i_22_, stream.readString()); else clientScriptMap.put(i_22_, stream.readInt()); } } } @Override public String toString() { StringBuilder result = new StringBuilder(); String newLine = System.getProperty(""line.separator""); result.append(this.getClass().getName()); result.append("" {""); result.append(newLine); // determine fields declared in this class only (no fields of // superclass) Field[] fields = this.getClass().getDeclaredFields(); // print field names paired with their values for (Field field : fields) { if (Modifier.isStatic(field.getModifiers())) continue; result.append("" ""); try { result.append(field.getType().getCanonicalName() + "" "" + field.getName() + "": ""); result.append(Utils.getFieldValue(this, field)); } catch (Throwable ex) { System.out.println(ex); } result.append(newLine); } result.append(""}""); return result.toString(); } } " " package com.rs.cache.loaders; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.concurrent.ConcurrentHashMap; import com.rs.cache.ArchiveType; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.lib.io.InputStream; import com.rs.lib.util.Utils; public class BASDefinitions { public int numStandAnimations; public int[] standAnimations; public int standAnimation = -1; public int standTurn1; public int standTurn2; public int walkAnimation; public int walkDir1; public int walkDir2; public int walkDir3; public int walkTurn1; public int walkTurn2; public int runningAnimation; public int runDir1; public int runDir2; public int runDir3; public int runTurn1; public int runTurn2; public int teleportingAnimation; public int teleDir1; public int teleDir2; public int teleDir3; public int teleTurn1; public int teleTurn2; public int anInt2790; public int[][] anIntArrayArray2791; public int anInt2798; public int[][] anIntArrayArray2802; public int anInt2804; public int[] anIntArray2811; public int anInt2813; public int[] anIntArray2814; public int anInt2815; public int anInt2816; public int[] anIntArray2818; public int anInt2820; public int anInt2823; public int anInt2824; public int anInt2825; public int anInt2826; public int anInt2827; public int anInt2829; public int anInt2786; public boolean aBool2787; private static final ConcurrentHashMap RENDER_ANIM_CACHE = new ConcurrentHashMap(); public static void main(String[] args) throws IOException { Cache.init(""../darkan-cache/""); int search = 772; for (int i = 0;i < Utils.getBASAnimDefSize();i++) { BASDefinitions def = BASDefinitions.getDefs(i); if (def.walkAnimation == search || def.runningAnimation == search || def.walkDir1 == search || def.walkDir2 == search || def.walkDir3 == search || def.standAnimation == search) System.out.println(i); } } public static final BASDefinitions getDefs(int emoteId) { BASDefinitions defs = RENDER_ANIM_CACHE.get(emoteId); if (defs != null) return defs; if (emoteId == -1) return null; byte[] data = Cache.STORE.getIndex(IndexType.CONFIG).getFile(ArchiveType.BAS.getId(), emoteId); defs = new BASDefinitions(); if (data != null) defs.readValueLoop(new InputStream(data)); RENDER_ANIM_CACHE.put(emoteId, defs); return defs; } @Override public String toString() { StringBuilder result = new StringBuilder(); String newLine = System.getProperty(""line.separator""); result.append(this.getClass().getName()); result.append("" {""); result.append(newLine); // determine fields declared in this class only (no fields of // superclass) Field[] fields = this.getClass().getDeclaredFields(); // print field names paired with their values for (Field field : fields) { if (Modifier.isStatic(field.getModifiers())) continue; result.append("" ""); try { result.append(field.getType().getCanonicalName() + "" "" + field.getName() + "": ""); result.append(Utils.getFieldValue(this, field)); } catch (Throwable ex) { System.out.println(ex); } result.append(newLine); } result.append(""}""); return result.toString(); } private void readValueLoop(InputStream stream) { for (;;) { int opcode = stream.readUnsignedByte(); if (opcode == 0) break; readValues(stream, opcode); } } private void readValues(InputStream stream, int opcode) { if (1 == opcode) { standAnimation = stream.readBigSmart(); walkAnimation = stream.readBigSmart(); } else if (2 == opcode) teleportingAnimation = stream.readBigSmart(); else if (opcode == 3) teleDir3 = stream.readBigSmart(); else if (opcode == 4) teleDir2 = stream.readBigSmart(); else if (5 == opcode) teleDir1 = stream.readBigSmart(); else if (opcode == 6) runningAnimation = stream.readBigSmart(); else if (opcode == 7) runDir3 = stream.readBigSmart(); else if (8 == opcode) runDir2 = stream.readBigSmart(); else if (opcode == 9) runDir1 = stream.readBigSmart(); else if (26 == opcode) { anInt2786 = ((short) (stream.readUnsignedByte() * 4)); anInt2829 = ((short) (stream.readUnsignedByte() * 4)); } else if (opcode == 27) { if (anIntArrayArray2802 == null) anIntArrayArray2802 = new int[15][]; int i_1_ = stream.readUnsignedByte(); anIntArrayArray2802[i_1_] = new int[6]; for (int i_2_ = 0; i_2_ < 6; i_2_++) anIntArrayArray2802[i_1_][i_2_] = stream.readShort(); } else if (opcode == 28) { int i_3_ = stream.readUnsignedByte(); anIntArray2811 = new int[i_3_]; for (int i_4_ = 0; i_4_ < i_3_; i_4_++) { anIntArray2811[i_4_] = stream.readUnsignedByte(); if (255 == anIntArray2811[i_4_]) anIntArray2811[i_4_] = -1; } } else if (29 == opcode) anInt2820 = stream.readUnsignedByte(); else if (30 == opcode) anInt2804 = stream.readUnsignedShort(); else if (opcode == 31) anInt2825 = stream.readUnsignedByte(); else if (32 == opcode) anInt2823 = stream.readUnsignedShort(); else if (33 == opcode) anInt2824 = stream.readShort(); else if (opcode == 34) anInt2816 = stream.readUnsignedByte(); else if (opcode == 35) anInt2815 = stream.readUnsignedShort(); else if (36 == opcode) anInt2827 = stream.readShort(); else if (37 == opcode) anInt2826 = stream.readUnsignedByte(); else if (38 == opcode) standTurn1 = stream.readBigSmart(); else if (opcode == 39) standTurn2 = stream.readBigSmart(); else if (opcode == 40) walkDir3 = stream.readBigSmart(); else if (41 == opcode) walkDir2 = stream.readBigSmart(); else if (42 == opcode) walkDir1 = stream.readBigSmart(); else if (opcode == 43) stream.readUnsignedShort(); else if (opcode == 44) stream.readUnsignedShort(); else if (45 == opcode) anInt2798 = stream.readUnsignedShort(); else if (46 == opcode) teleTurn1 = stream.readBigSmart(); else if (opcode == 47) teleTurn2 = stream.readBigSmart(); else if (opcode == 48) runTurn1 = stream.readBigSmart(); else if (49 == opcode) runTurn2 = stream.readBigSmart(); else if (opcode == 50) walkTurn1 = stream.readBigSmart(); else if (opcode == 51) walkTurn2 = stream.readBigSmart(); else if (52 == opcode) { int i_5_ = stream.readUnsignedByte(); anIntArray2814 = new int[i_5_]; standAnimations = new int[i_5_]; for (int i_6_ = 0; i_6_ < i_5_; i_6_++) { anIntArray2814[i_6_] = stream.readBigSmart(); int i_7_ = stream.readUnsignedByte(); standAnimations[i_6_] = i_7_; numStandAnimations += i_7_; } } else if (53 == opcode) aBool2787 = false; else if (opcode == 54) { anInt2813 = (stream.readUnsignedByte() << 6); anInt2790 = (stream.readUnsignedByte() << 6); } else if (opcode == 55) { if (anIntArray2818 == null) anIntArray2818 = new int[15]; int i_8_ = stream.readUnsignedByte(); anIntArray2818[i_8_] = stream.readUnsignedShort(); } else if (opcode == 56) { if (null == anIntArrayArray2791) anIntArrayArray2791 = new int[15][]; int i_9_ = stream.readUnsignedByte(); anIntArrayArray2791[i_9_] = new int[3]; for (int i_10_ = 0; i_10_ < 3; i_10_++) anIntArrayArray2791[i_9_][i_10_] = stream.readShort(); } } public BASDefinitions() { anIntArray2814 = null; standAnimations = null; numStandAnimations = 0; standTurn1 = -1; standTurn2 = -1; walkAnimation = -1; walkDir3 = -1; walkDir2 = -1; walkDir1 = -1; runningAnimation = -1; runDir3 = -1; runDir2 = -1; runDir1 = -1; teleportingAnimation = -1; teleDir3 = -1; teleDir2 = -1; teleDir1 = -1; teleTurn1 = -1; teleTurn2 = -1; runTurn1 = -1; runTurn2 = -1; walkTurn1 = -1; walkTurn2 = -1; anInt2786 = 0; anInt2829 = 0; anInt2813 = 0; anInt2790 = 0; anInt2820 = 0; anInt2804 = 0; anInt2825 = 0; anInt2823 = 0; anInt2824 = 0; anInt2816 = 0; anInt2815 = 0; anInt2827 = 0; anInt2826 = -1; anInt2798 = -1; aBool2787 = true; } } " " package com.rs.cache.loaders; public enum Bonus { STAB_ATT, //0 SLASH_ATT, //1 CRUSH_ATT, //2 MAGIC_ATT, //3 RANGE_ATT, //4 STAB_DEF, //5 SLASH_DEF, //6 CRUSH_DEF, //7 MAGIC_DEF, //8 RANGE_DEF, //9 SUMM_DEF, //10 ABSORB_MELEE, //11 ABSORB_MAGIC, //12 ABSORB_RANGE, //13 MELEE_STR, //14 RANGE_STR, //15 PRAYER, //16 MAGIC_STR //17 } " " package com.rs.cache.loaders; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import com.rs.cache.ArchiveType; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.cache.loaders.cs2.CS2Type; import com.rs.lib.io.InputStream; import com.rs.lib.util.Utils; public class ClanVarDefinitions { private static final HashMap CACHE = new HashMap<>(); public int id; public char aChar4832; public CS2Type type; public int baseVar = -1; public int startBit; public int endBit; public static void main(String[] args) throws IOException { Cache.init(""../cache/""); Set varbits = new HashSet<>(); for (int i = 0;i < Cache.STORE.getIndex(IndexType.CONFIG).getLastFileId(ArchiveType.CLAN_VAR.getId()) + 1;i++) { ClanVarDefinitions defs = getDefs(i); if (defs.baseVar != -1) varbits.add(defs.baseVar); } for (int i = 0;i < Cache.STORE.getIndex(IndexType.CONFIG).getLastFileId(ArchiveType.CLAN_VAR.getId()) + 1;i++) { ClanVarDefinitions defs = getDefs(i); if (varbits.contains(i)) continue; System.out.println(""/*""+i + ""\t"" + defs.type + ""\t"" + defs.getMaxSize() +""\t\t*/""); } } public static final ClanVarDefinitions getDefs(int id) { ClanVarDefinitions defs = CACHE.get(id); if (defs != null) return defs; byte[] data = Cache.STORE.getIndex(IndexType.CONFIG).getFile(ArchiveType.CLAN_VAR.getId(), id); defs = new ClanVarDefinitions(); defs.id = id; if (data != null) defs.readValueLoop(new InputStream(data)); CACHE.put(id, defs); return defs; } private void readValueLoop(InputStream stream) { for (;;) { int opcode = stream.readUnsignedByte(); if (opcode == 0) break; readValues(stream, opcode); } } private void readValues(InputStream stream, int opcode) { if (opcode == 1) { this.aChar4832 = Utils.cp1252ToChar((byte) stream.readByte()); this.type = CS2Type.forJagexDesc(this.aChar4832); } else if (opcode == 3) { this.baseVar = stream.readUnsignedShort(); this.startBit = stream.readUnsignedByte(); this.endBit = stream.readUnsignedByte(); } } @Override public String toString() { StringBuilder result = new StringBuilder(); String newLine = System.getProperty(""line.separator""); result.append(this.getClass().getName()); result.append("" {""); result.append(newLine); // determine fields declared in this class only (no fields of // superclass) Field[] fields = this.getClass().getDeclaredFields(); // print field names paired with their values for (Field field : fields) { if (Modifier.isStatic(field.getModifiers())) continue; result.append("" ""); try { result.append(field.getType().getCanonicalName() + "" "" + field.getName() + "": ""); result.append(Utils.getFieldValue(this, field)); } catch (Throwable ex) { System.out.println(ex); } result.append(newLine); } result.append(""}""); return result.toString(); } public long getMaxSize() { if (baseVar == -1) { if (type == CS2Type.INT) return Integer.MAX_VALUE; else if (type == CS2Type.LONG) return Long.MAX_VALUE; else return -1; } else { return 1 << (endBit - startBit); } } } " " package com.rs.cache.loaders; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import com.rs.cache.ArchiveType; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.cache.loaders.cs2.CS2Type; import com.rs.lib.io.InputStream; import com.rs.lib.util.Utils; public class ClanVarSettingsDefinitions { private static final HashMap CACHE = new HashMap<>(); public int id; public char aChar4832; public CS2Type type; public int baseVar = -1; public int startBit; public int endBit; public static void main(String[] args) throws IOException { Cache.init(""../cache/""); Set varbits = new HashSet<>(); for (int i = 0;i < Cache.STORE.getIndex(IndexType.CONFIG).getLastFileId(ArchiveType.CLAN_VAR_SETTINGS.getId()) + 1;i++) { ClanVarSettingsDefinitions defs = getDefs(i); if (defs.baseVar != -1) varbits.add(defs.baseVar); } for (int i = 0;i < Cache.STORE.getIndex(IndexType.CONFIG).getLastFileId(ArchiveType.CLAN_VAR_SETTINGS.getId()) + 1;i++) { ClanVarSettingsDefinitions defs = getDefs(i); if (varbits.contains(i)) continue; System.out.println(""/*""+i + ""\t"" + defs.type + ""\t"" + defs.getMaxSize() +""\t\t*/""); } } public static final ClanVarSettingsDefinitions getDefs(int id) { ClanVarSettingsDefinitions defs = CACHE.get(id); if (defs != null) return defs; byte[] data = Cache.STORE.getIndex(IndexType.CONFIG).getFile(ArchiveType.CLAN_VAR_SETTINGS.getId(), id); defs = new ClanVarSettingsDefinitions(); defs.id = id; if (data != null) defs.readValueLoop(new InputStream(data)); CACHE.put(id, defs); return defs; } private void readValueLoop(InputStream stream) { for (;;) { int opcode = stream.readUnsignedByte(); if (opcode == 0) break; readValues(stream, opcode); } } private void readValues(InputStream stream, int opcode) { if (opcode == 1) { this.aChar4832 = Utils.cp1252ToChar((byte) stream.readByte()); this.type = CS2Type.forJagexDesc(this.aChar4832); } else if (opcode == 2) { this.baseVar = stream.readUnsignedShort(); this.startBit = stream.readUnsignedByte(); this.endBit = stream.readUnsignedByte(); } } public long getMaxSize() { if (baseVar == -1) { if (type == CS2Type.INT) return Integer.MAX_VALUE; else if (type == CS2Type.LONG) return Long.MAX_VALUE; else return -1; } else { return 1 << (endBit - startBit); } } @Override public String toString() { StringBuilder result = new StringBuilder(); String newLine = System.getProperty(""line.separator""); result.append(this.getClass().getName()); result.append("" {""); result.append(newLine); // determine fields declared in this class only (no fields of // superclass) Field[] fields = this.getClass().getDeclaredFields(); // print field names paired with their values for (Field field : fields) { if (Modifier.isStatic(field.getModifiers())) continue; result.append("" ""); try { result.append(field.getType().getCanonicalName() + "" "" + field.getName() + "": ""); result.append(Utils.getFieldValue(this, field)); } catch (Throwable ex) { System.out.println(ex); } result.append(newLine); } result.append(""}""); return result.toString(); } } " " package com.rs.cache.loaders; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashMap; import com.rs.cache.ArchiveType; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.lib.io.InputStream; import com.rs.lib.util.Utils; public class CursorDefinitions { private static final HashMap CACHE = new HashMap<>(); public int id; int spriteId; public int anInt5002; public int anInt5000; public static final CursorDefinitions getDefs(int id) { CursorDefinitions defs = CACHE.get(id); if (defs != null) return defs; byte[] data = Cache.STORE.getIndex(IndexType.CONFIG).getFile(ArchiveType.CURSORS.getId(), id); defs = new CursorDefinitions(); defs.id = id; if (data != null) defs.readValueLoop(new InputStream(data)); CACHE.put(id, defs); return defs; } private void readValueLoop(InputStream stream) { for (;;) { int opcode = stream.readUnsignedByte(); if (opcode == 0) break; readValues(stream, opcode); } } private void readValues(InputStream stream, int opcode) { if (opcode == 1) { this.spriteId = stream.readBigSmart(); } else if (opcode == 2) { this.anInt5002 = stream.readUnsignedByte(); this.anInt5000 = stream.readUnsignedByte(); } } public SpriteDefinitions getSprite() { return SpriteDefinitions.getSprite(spriteId, 0); } @Override public String toString() { StringBuilder result = new StringBuilder(); String newLine = System.getProperty(""line.separator""); result.append(this.getClass().getName()); result.append("" {""); result.append(newLine); // determine fields declared in this class only (no fields of // superclass) Field[] fields = this.getClass().getDeclaredFields(); // print field names paired with their values for (Field field : fields) { if (Modifier.isStatic(field.getModifiers())) continue; result.append("" ""); try { result.append(field.getType().getCanonicalName() + "" "" + field.getName() + "": ""); result.append(Utils.getFieldValue(this, field)); } catch (Throwable ex) { System.out.println(ex); } result.append(newLine); } result.append(""}""); return result.toString(); } } " " package com.rs.cache.loaders; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashMap; import com.rs.lib.io.InputStream; import com.rs.lib.util.Utils; public class DefinitionsTemplate { private static final HashMap CACHE = new HashMap<>(); public int id; public static final DefinitionsTemplate getDefs(int id) { DefinitionsTemplate defs = CACHE.get(id); if (defs != null) return defs; //byte[] data = Cache.STORE.getIndex(IndexType.).getFile(FileType., id); byte[] data = new byte[5]; defs = new DefinitionsTemplate(); defs.id = id; if (data != null) defs.readValueLoop(new InputStream(data)); CACHE.put(id, defs); return defs; } private void readValueLoop(InputStream stream) { for (;;) { int opcode = stream.readUnsignedByte(); if (opcode == 0) break; readValues(stream, opcode); } } private void readValues(InputStream stream, int opcode) { } @Override public String toString() { StringBuilder result = new StringBuilder(); String newLine = System.getProperty(""line.separator""); result.append(this.getClass().getName()); result.append("" {""); result.append(newLine); // determine fields declared in this class only (no fields of // superclass) Field[] fields = this.getClass().getDeclaredFields(); // print field names paired with their values for (Field field : fields) { if (Modifier.isStatic(field.getModifiers())) continue; result.append("" ""); try { result.append(field.getType().getCanonicalName() + "" "" + field.getName() + "": ""); result.append(Utils.getFieldValue(this, field)); } catch (Throwable ex) { System.out.println(ex); } result.append(newLine); } result.append(""}""); return result.toString(); } } " " package com.rs.cache.loaders; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.concurrent.ConcurrentHashMap; import com.rs.cache.ArchiveType; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.cache.loaders.cs2.CS2Type; import com.rs.lib.Constants; import com.rs.lib.game.WorldTile; import com.rs.lib.io.InputStream; import com.rs.lib.util.Utils; public final class EnumDefinitions { public CS2Type keyType; public char keyTypeChar; public CS2Type valueType; public char valueTypeChar; private String defaultStringValue; private int defaultIntValue; private HashMap values; private static final ConcurrentHashMap ENUMS_CACHE = new ConcurrentHashMap(); public static void main(String[] args) throws IOException { File file = new File(""enums.txt""); if (file.exists()) file.delete(); else file.createNewFile(); BufferedWriter writer = new BufferedWriter(new FileWriter(file)); writer.append(""//Version = 727\n""); writer.flush(); for (int i = 0; i < 100000; i++) { EnumDefinitions map = getEnum(i); if (map == null || map.getValues() == null) continue; writer.append(i + "": "" + map.toString()); writer.newLine(); writer.flush(); System.out.println(i + "" - "" + map.getValues().toString()); } writer.close(); } public static final EnumDefinitions getEnum(int enumId) { EnumDefinitions script = ENUMS_CACHE.get(enumId); if (script != null) return script; byte[] data = Cache.STORE.getIndex(IndexType.ENUMS).getFile(ArchiveType.ENUMS.archiveId(enumId), ArchiveType.ENUMS.fileId(enumId)); script = new EnumDefinitions(); if (data != null) script.readValueLoop(new InputStream(data)); ENUMS_CACHE.put(enumId, script); return script; } public int getDefaultIntValue() { return defaultIntValue; } public String getDefaultStringValue() { return defaultStringValue; } public HashMap getValues() { return values; } public Object getValue(long key) { if (values == null) return null; return values.get(key); } public long getKeyForValue(Object value) { for (Long key : values.keySet()) { if (values.get(key).equals(value)) return key; } return -1; } public int getSize() { if (values == null) return 0; return values.size(); } public int getIntValue(long key) { if (values == null) return defaultIntValue; Object value = values.get(key); if (value == null || !(value instanceof Integer)) return defaultIntValue; return (Integer) value; } public int getKeyIndex(long key) { if (values == null) return -1; int i = 0; for (long k : values.keySet()) { if (k == key) return i; i++; } return -1; } public int getIntValueAtIndex(int i) { if (values == null) return -1; return (int) values.values().toArray()[i]; } public String getStringValue(long key) { if (values == null) return defaultStringValue; Object value = values.get(key); if (value == null || !(value instanceof String)) return defaultStringValue; return (String) value; } private void readValueLoop(InputStream stream) { for (;;) { int opcode = stream.readUnsignedByte(); if (opcode == 0) break; readValues(stream, opcode); } } private void readValues(InputStream stream, int opcode) { if (opcode == 1) { keyTypeChar = Utils.cp1252ToChar((byte) stream.readByte()); keyType = CS2Type.forJagexDesc(keyTypeChar); } else if (opcode == 2) { valueTypeChar = Utils.cp1252ToChar((byte) stream.readByte()); valueType = CS2Type.forJagexDesc(valueTypeChar); } else if (opcode == 3) defaultStringValue = stream.readString(); else if (opcode == 4) defaultIntValue = stream.readInt(); else if (opcode == 5 || opcode == 6 || opcode == 7 || opcode == 8) { int count = stream.readUnsignedShort(); int loop = opcode == 7 || opcode == 8 ? stream.readUnsignedShort() : count; if (values == null) values = new HashMap(Utils.getHashMapSize(count)); for (int i = 0; i < loop; i++) { int key = opcode == 7 || opcode == 8 ? stream.readUnsignedShort() : stream.readInt(); Object value = opcode == 5 || opcode == 7 ? stream.readString() : stream.readInt(); values.put((long) key, value); } } } private EnumDefinitions() { defaultStringValue = ""null""; } public Object keyToType(long l) { if (keyType == CS2Type.ICOMPONENT) { long interfaceId = l >> 16; long componentId = l - (interfaceId << 16); return ""IComponent(""+interfaceId+"", ""+componentId+"")""; } else if (keyType == CS2Type.LOCATION) { return WorldTile.of((int) l); } else if (keyType == CS2Type.SKILL) { int idx = (int) l; if (idx >= Constants.SKILL_NAME.length) return l; return idx+""(""+Constants.SKILL_NAME[((int) l)]+"")""; } else if (keyType == CS2Type.ITEM) { return l+""(""+ItemDefinitions.getDefs((int) l).getName()+"")""; } else if (keyType == CS2Type.NPCDEF) { return l+""(""+NPCDefinitions.getDefs((int) l).getName()+"")""; } else if (keyType == CS2Type.STRUCT) { return l + "": "" + StructDefinitions.getStruct((int) l); } return l; } public Object valToType(Object o) { if (valueType == CS2Type.ICOMPONENT) { if (o instanceof String) return o; long interfaceId = ((int) o) >> 16; long componentId = ((int) o) - (interfaceId << 16); return ""IComponent(""+interfaceId+"", ""+componentId+"")""; } else if (valueType == CS2Type.LOCATION) { if (o instanceof String) return o; return WorldTile.of(((int) o)); } else if (valueType == CS2Type.SKILL) { if (o instanceof String) return o; int idx = (int) o; if (idx >= Constants.SKILL_NAME.length) return o; return idx+""(""+Constants.SKILL_NAME[((int) o)]+"")""; } else if (valueType == CS2Type.ITEM) { if (o instanceof String) return o; return ((int) o)+"" (""+ItemDefinitions.getDefs(((int) o)).getName()+"")""; } else if (valueType == CS2Type.NPCDEF) { if (o instanceof String) return o; return ((int) o)+"" (""+NPCDefinitions.getDefs(((int) o)).getName()+"")""; } else if (valueType == CS2Type.STRUCT) { return o + "": "" + StructDefinitions.getStruct((int) o); } else if (valueType == CS2Type.ENUM) { return o + "": "" + getEnum((int) o); } return o; } @Override public String toString() { StringBuilder s = new StringBuilder(); if (getValues() == null) return ""null""; s.append(""<""+keyType+"", ""+valueType+""> - "" + getDefaultStringValue() + "" - "" + getDefaultIntValue() + "" { ""); s.append(""\r\n""); for (Long l : getValues().keySet()) { s.append(keyToType(l)); s.append("" = ""); s.append(valToType(getValues().get(l))); s.append(""\r\n""); } s.append(""} \r\n""); return s.toString(); } } " " package com.rs.cache.loaders; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashMap; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.lib.io.InputStream; import com.rs.lib.util.Utils; public class FontMetrics { private static final HashMap CACHE = new HashMap<>(); private static int p11Full, p12Full, b12Full; public int id; byte[] characters; public int anInt4975; public int anInt4978; public int anInt4979; byte[][] kerning; public static void main(String[] args) throws IOException { //Cache.init(); p11Full = Cache.STORE.getIndex(IndexType.NORMAL_FONTS).getArchiveId(""p11_full""); p12Full = Cache.STORE.getIndex(IndexType.NORMAL_FONTS).getArchiveId(""p12_full""); b12Full = Cache.STORE.getIndex(IndexType.NORMAL_FONTS).getArchiveId(""b12_full""); System.out.println(p11Full); System.out.println(p12Full); System.out.println(b12Full); System.out.println(get(p11Full)); System.out.println(get(p12Full)); System.out.println(get(b12Full)); // for (int i = 0;i < Cache.STORE.getIndex(IndexType.FONT_METRICS).getLastArchiveId()+1;i++) { // FontMetrics defs = get(i); // System.out.println(defs); // } } public static final FontMetrics get(int id) { FontMetrics defs = CACHE.get(id); if (defs != null) return defs; byte[] data = Cache.STORE.getIndex(IndexType.FONT_METRICS).getFile(id); defs = new FontMetrics(); defs.id = id; if (data != null) defs.decode(new InputStream(data)); CACHE.put(id, defs); return defs; } private void decode(InputStream stream) { int i_3 = stream.readUnsignedByte(); if (i_3 != 0) { throw new RuntimeException(""""); } else { boolean bool_4 = stream.readUnsignedByte() == 1; this.characters = new byte[256]; stream.readBytes(this.characters, 0, 256); if (bool_4) { int[] ints_5 = new int[256]; int[] ints_6 = new int[256]; int i_7; for (i_7 = 0; i_7 < 256; i_7++) { ints_5[i_7] = stream.readUnsignedByte(); } for (i_7 = 0; i_7 < 256; i_7++) { ints_6[i_7] = stream.readUnsignedByte(); } byte[][] bytes_12 = new byte[256][]; int i_10; for (int i_8 = 0; i_8 < 256; i_8++) { bytes_12[i_8] = new byte[ints_5[i_8]]; byte b_9 = 0; for (i_10 = 0; i_10 < bytes_12[i_8].length; i_10++) { b_9 += stream.readByte(); bytes_12[i_8][i_10] = b_9; } } byte[][] bytes_13 = new byte[256][]; int i_14; for (i_14 = 0; i_14 < 256; i_14++) { bytes_13[i_14] = new byte[ints_5[i_14]]; byte b_15 = 0; for (int i_11 = 0; i_11 < bytes_13[i_14].length; i_11++) { b_15 += stream.readByte(); bytes_13[i_14][i_11] = b_15; } } this.kerning = new byte[256][256]; for (i_14 = 0; i_14 < 256; i_14++) { if (i_14 != 32 && i_14 != 160) { for (i_10 = 0; i_10 < 256; i_10++) { if (i_10 != 32 && i_10 != 160) { this.kerning[i_14][i_10] = (byte) Utils.calculateKerning(bytes_12, bytes_13, ints_6, this.characters, ints_5, i_14, i_10); } } } } this.anInt4975 = ints_6[32] + ints_5[32]; } else { this.anInt4975 = stream.readUnsignedByte(); } stream.readUnsignedByte(); stream.readUnsignedByte(); this.anInt4978 = stream.readUnsignedByte(); this.anInt4979 = stream.readUnsignedByte(); } } @Override public String toString() { StringBuilder result = new StringBuilder(); String newLine = System.getProperty(""line.separator""); result.append(this.getClass().getName()); result.append("" {""); result.append(newLine); // determine fields declared in this class only (no fields of // superclass) Field[] fields = this.getClass().getDeclaredFields(); // print field names paired with their values for (Field field : fields) { if (Modifier.isStatic(field.getModifiers())) continue; result.append("" ""); try { result.append(field.getType().getCanonicalName() + "" "" + field.getName() + "": ""); result.append(Utils.getFieldValue(this, field)); } catch (Throwable ex) { System.out.println(ex); } result.append(newLine); } result.append(""}""); return result.toString(); } } " " package com.rs.cache.loaders; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashMap; import com.rs.cache.ArchiveType; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.lib.io.InputStream; import com.rs.lib.util.Utils; public class HitbarDefinitions { private static final HashMap CACHE = new HashMap<>(); public int id; public int anInt2446 = 255; public int anInt2440 = 255; public int anInt2439 = -1; public int anInt2443 = 70; int anInt2444 = -1; int anInt2445 = -1; int anInt2441 = -1; int anInt2447 = -1; public int anInt2442 = 1; public static void main(String[] args) throws IOException { //Cache.init(); for (int i = 0;i < Cache.STORE.getIndex(IndexType.CONFIG).getLastFileId(ArchiveType.HITBARS.getId())+1;i++) { HitbarDefinitions defs = getDefs(i); System.out.println(defs); } } public static final HitbarDefinitions getDefs(int id) { HitbarDefinitions defs = CACHE.get(id); if (defs != null) return defs; byte[] data = Cache.STORE.getIndex(IndexType.CONFIG).getFile(ArchiveType.HITBARS.getId(), id); defs = new HitbarDefinitions(); defs.id = id; if (data != null) defs.readValueLoop(new InputStream(data)); CACHE.put(id, defs); return defs; } private void readValueLoop(InputStream stream) { for (;;) { int opcode = stream.readUnsignedByte(); if (opcode == 0) break; readValues(stream, opcode); } } private void readValues(InputStream stream, int opcode) { if (opcode == 1) { stream.readUnsignedShort(); } else if (opcode == 2) { this.anInt2446 = stream.readUnsignedByte(); } else if (opcode == 3) { this.anInt2440 = stream.readUnsignedByte(); } else if (opcode == 4) { this.anInt2439 = 0; } else if (opcode == 5) { this.anInt2443 = stream.readUnsignedShort(); } else if (opcode == 6) { stream.readUnsignedByte(); } else if (opcode == 7) { this.anInt2444 = stream.readBigSmart(); } else if (opcode == 8) { this.anInt2445 = stream.readBigSmart(); } else if (opcode == 9) { this.anInt2441 = stream.readBigSmart(); } else if (opcode == 10) { this.anInt2447 = stream.readBigSmart(); } else if (opcode == 11) { this.anInt2439 = stream.readUnsignedShort(); } } @Override public String toString() { StringBuilder result = new StringBuilder(); String newLine = System.getProperty(""line.separator""); result.append(this.getClass().getName()); result.append("" {""); result.append(newLine); // determine fields declared in this class only (no fields of // superclass) Field[] fields = this.getClass().getDeclaredFields(); // print field names paired with their values for (Field field : fields) { if (Modifier.isStatic(field.getModifiers())) continue; result.append("" ""); try { result.append(field.getType().getCanonicalName() + "" "" + field.getName() + "": ""); result.append(Utils.getFieldValue(this, field)); } catch (Throwable ex) { System.out.println(ex); } result.append(newLine); } result.append(""}""); return result.toString(); } } " " package com.rs.cache.loaders; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashMap; import com.rs.cache.ArchiveType; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.lib.io.InputStream; import com.rs.lib.util.Utils; public class HitsplatDefinitions { private static final HashMap CACHE = new HashMap<>(); public int id; public int anInt2849 = -1; public int anInt2844 = 16777215; public boolean aBool2838 = false; int anInt2842 = -1; int anInt2851 = -1; int anInt2843 = -1; int anInt2845 = -1; public int anInt2846 = 0; String aString2840 = """"; public int anInt2841 = 70; public int anInt2833 = 0; public int anInt2847 = -1; public int anInt2839 = -1; public int anInt2832 = 0; public static void main(String[] args) throws IOException { //Cache.init(); for (int i = 0;i < Cache.STORE.getIndex(IndexType.CONFIG).getLastFileId(ArchiveType.HITSPLATS.getId())+1;i++) { HitsplatDefinitions defs = getDefs(i); System.out.println(defs); } } public static final HitsplatDefinitions getDefs(int id) { HitsplatDefinitions defs = CACHE.get(id); if (defs != null) return defs; byte[] data = Cache.STORE.getIndex(IndexType.CONFIG).getFile(ArchiveType.HITSPLATS.getId(), id); defs = new HitsplatDefinitions(); defs.id = id; if (data != null) defs.readValueLoop(new InputStream(data)); CACHE.put(id, defs); return defs; } private void readValueLoop(InputStream stream) { for (;;) { int opcode = stream.readUnsignedByte(); if (opcode == 0) break; readValues(stream, opcode); } } private void readValues(InputStream stream, int opcode) { if (opcode == 1) { this.anInt2849 = stream.readBigSmart(); } else if (opcode == 2) { this.anInt2844 = stream.read24BitUnsignedInteger(); this.aBool2838 = true; } else if (opcode == 3) { this.anInt2842 = stream.readBigSmart(); } else if (opcode == 4) { this.anInt2851 = stream.readBigSmart(); } else if (opcode == 5) { this.anInt2843 = stream.readBigSmart(); } else if (opcode == 6) { this.anInt2845 = stream.readBigSmart(); } else if (opcode == 7) { this.anInt2846 = stream.readShort(); } else if (opcode == 8) { //TODO check readGJString compare to readJagString this.aString2840 = stream.readGJString(); } else if (opcode == 9) { this.anInt2841 = stream.readUnsignedShort(); } else if (opcode == 10) { this.anInt2833 = stream.readShort(); } else if (opcode == 11) { this.anInt2847 = 0; } else if (opcode == 12) { this.anInt2839 = stream.readUnsignedByte(); } else if (opcode == 13) { this.anInt2832 = stream.readShort(); } else if (opcode == 14) { this.anInt2847 = stream.readUnsignedShort(); } } @Override public String toString() { StringBuilder result = new StringBuilder(); String newLine = System.getProperty(""line.separator""); result.append(this.getClass().getName()); result.append("" {""); result.append(newLine); // determine fields declared in this class only (no fields of // superclass) Field[] fields = this.getClass().getDeclaredFields(); // print field names paired with their values for (Field field : fields) { if (Modifier.isStatic(field.getModifiers())) continue; result.append("" ""); try { result.append(field.getType().getCanonicalName() + "" "" + field.getName() + "": ""); result.append(Utils.getFieldValue(this, field)); } catch (Throwable ex) { System.out.println(ex); } result.append(newLine); } result.append(""}""); return result.toString(); } } " " package com.rs.cache.loaders; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashMap; import com.rs.cache.ArchiveType; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.lib.io.InputStream; import com.rs.lib.util.Utils; public class IdentiKitDefinitions { private static final HashMap CACHE = new HashMap<>(); public int id; int[] modelIds; short[] originalColours; short[] replacementColours; short[] originalTextures; short[] replacementTextures; int[] headModels = new int[] { -1, -1, -1, -1, -1 }; public static final IdentiKitDefinitions getDefs(int id) { IdentiKitDefinitions defs = CACHE.get(id); if (defs != null) return defs; byte[] data = Cache.STORE.getIndex(IndexType.CONFIG).getFile(ArchiveType.IDENTIKIT.getId(), id); defs = new IdentiKitDefinitions(); defs.id = id; if (data != null) defs.readValueLoop(new InputStream(data)); CACHE.put(id, defs); return defs; } private void readValueLoop(InputStream stream) { for (;;) { int opcode = stream.readUnsignedByte(); if (opcode == 0) break; readValues(stream, opcode); } } private void readValues(InputStream buffer, int opcode) { if (opcode == 1) { buffer.readUnsignedByte(); } else if (opcode == 2) { int count = buffer.readUnsignedByte(); this.modelIds = new int[count]; for (int i_5 = 0; i_5 < count; i_5++) { this.modelIds[i_5] = buffer.readBigSmart(); } } else if (opcode == 40) { int count = buffer.readUnsignedByte(); this.originalColours = new short[count]; this.replacementColours = new short[count]; for (int i_5 = 0; i_5 < count; i_5++) { this.originalColours[i_5] = (short) buffer.readUnsignedShort(); this.replacementColours[i_5] = (short) buffer.readUnsignedShort(); } } else if (opcode == 41) { int count = buffer.readUnsignedByte(); this.originalTextures = new short[count]; this.replacementTextures = new short[count]; for (int i_5 = 0; i_5 < count; i_5++) { this.originalTextures[i_5] = (short) buffer.readUnsignedShort(); this.replacementTextures[i_5] = (short) buffer.readUnsignedShort(); } } else if (opcode >= 60 && opcode < 70) { this.headModels[opcode - 60] = buffer.readBigSmart(); } } @Override public String toString() { StringBuilder result = new StringBuilder(); String newLine = System.getProperty(""line.separator""); result.append(this.getClass().getName()); result.append("" {""); result.append(newLine); // determine fields declared in this class only (no fields of // superclass) Field[] fields = this.getClass().getDeclaredFields(); // print field names paired with their values for (Field field : fields) { if (Modifier.isStatic(field.getModifiers())) continue; result.append("" ""); try { result.append(field.getType().getCanonicalName() + "" "" + field.getName() + "": ""); result.append(Utils.getFieldValue(this, field)); } catch (Throwable ex) { System.out.println(ex); } result.append(newLine); } result.append(""}""); return result.toString(); } } " " package com.rs.cache.loaders; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.concurrent.ConcurrentHashMap; import com.rs.cache.ArchiveType; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.cache.Store; import com.rs.lib.io.InputStream; import com.rs.lib.io.OutputStream; import com.rs.lib.util.Utils; public final class InventoryDefinitions { public int id; public int maxSize = 0; public int contentSize = 0; public int[] ids; public int[] amounts; private static final ConcurrentHashMap maps = new ConcurrentHashMap(); public static void main(String... args) { //Cache.init(); for (int i = 0;i < Cache.STORE.getIndex(IndexType.CONFIG).getValidFilesCount(ArchiveType.INVENTORIES.getId());i++) { InventoryDefinitions defs = InventoryDefinitions.getContainer(i); String shop = (i+1000)+"" -1 false - Inventory ""+i+"" - ""; if (defs.ids == null) continue; for (int j = 0;j < defs.ids.length;j++) { shop += """" + defs.ids[j] + "" "" + defs.amounts[j] + "" ""; } System.out.println(shop); } } public InventoryDefinitions(int id) { this.id = id; byte[] data = Cache.STORE.getIndex(IndexType.CONFIG).getFile(ArchiveType.INVENTORIES.getId(), id); if (data != null) decode(new InputStream(data)); } public static boolean contains(int[] arr, int id) { for (int i = 0;i < arr.length;i++) { if (arr[i] == id) return true; } return false; } public static final InventoryDefinitions getContainer(int id) { InventoryDefinitions def = maps.get(id); if (def != null) return def; def = new InventoryDefinitions(id); maps.put(id, def); return def; } public void write(Store store) { store.getIndex(IndexType.CONFIG).putFile(ArchiveType.INVENTORIES.getId(), id, encode()); } private byte[] encode() { OutputStream stream = new OutputStream(); if (maxSize != 0) { stream.writeByte(2); stream.writeShort(maxSize); } if (contentSize != 0) { stream.writeByte(4); stream.writeByte(contentSize); for (int i = 0;i < contentSize;i++) { stream.writeShort(ids[i]); stream.writeShort(amounts[i]); } } stream.writeByte(0); return stream.toByteArray(); } private void decode(InputStream stream) { while(true) { int opcode = stream.readUnsignedByte(); if (opcode == 0) break; readValues(opcode, stream); } } private void readValues(int opcode, InputStream stream) { if (opcode == 2) { maxSize = stream.readUnsignedShort(); } else if (opcode == 4) { contentSize = stream.readUnsignedByte(); ids = new int[contentSize]; amounts = new int[contentSize]; for (int i = 0; i < contentSize; i++) { ids[i] = stream.readUnsignedShort(); amounts[i] = stream.readUnsignedShort(); } } } @Override public String toString() { StringBuilder result = new StringBuilder(); String newLine = System.getProperty(""line.separator""); result.append(this.getClass().getName()); result.append("" {""); result.append(newLine); // determine fields declared in this class only (no fields of // superclass) Field[] fields = this.getClass().getDeclaredFields(); // print field names paired with their values for (Field field : fields) { if (Modifier.isStatic(field.getModifiers())) continue; result.append("" ""); try { result.append(field.getType().getCanonicalName() + "" "" + field.getName() + "": ""); result.append(Utils.getFieldValue(this, field)); } catch (Throwable ex) { System.out.println(ex); } result.append(newLine); } result.append(""}""); return result.toString(); } } " " package com.rs.cache.loaders; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.HashMap; import java.lang.SuppressWarnings; import com.rs.cache.ArchiveType; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.cache.Store; import com.rs.lib.Constants; import com.rs.lib.io.InputStream; import com.rs.lib.io.OutputStream; import com.rs.lib.util.RSColor; import com.rs.lib.util.Utils; public final class ItemDefinitions { private static final HashMap ITEM_DEFINITIONS = new HashMap<>(); private static final HashMap EQUIP_IDS = new HashMap(); public int id; public boolean loaded; public int value = 1; public int modelId; public int modelZoom = 2000; public int modelRotationX = 0; public int modelRotationY = 0; public int modelRotationZ = 0; public int modelOffsetX = 0; public int modelOffsetY = 0; public int[] originalModelColors; public int[] modifiedModelColors; public byte[] spriteRecolorIndices; public int[] originalTextureIds; public int[] modifiedTextureIds; public String name = ""null""; public boolean membersOnly = false; public int wearPos = -1; public int wearPos2 = -1; public int wearPos3 = -1; public int maleEquip1 = -1; public int maleEquip2 = -1; public int maleEquip3 = -1; public int femaleEquip1 = -1; public int femaleEquip2 = -1; public int femaleEquip3 = -1; public int maleWearXOffset = 0; public int femaleWearXOffset = 0; public int maleWearYOffset = 0; public int femaleWearYOffset = 0; public int maleWearZOffset = 0; public int femaleWearZOffset = 0; public int maleHead1 = -1; public int maleHead2 = -1; public int femaleHead1 = -1; public int femaleHead2 = -1; public int teamId = 0; public String[] groundOptions; public int stackable = 0; public String[] inventoryOptions; public int multiStackSize = -1; public int tooltipColor; public boolean hasTooltipColor = false; private boolean grandExchange = false; public int unknownInt6 = 0; public int certId = -1; public int certTemplateId = -1; public int resizeX = 128; public int[] stackIds; public int[] stackAmounts; public int resizeY = 128; public int resizeZ = 128; public int ambient = 0; public int contrast = 0; public int lendId = -1; public int lendTemplateId = -1; public int unknownInt18 = -1; public int unknownInt19 = -1; public int unknownInt20 = -1; public int unknownInt21 = -1; public int customCursorOp1 = -1; public int customCursorId1 = -1; public int customCursorOp2 = -1; public int customCursorId2 = -1; public int[] quests; public int[] bonuses = new int[18]; public int pickSizeShift = 0; public int bindId = -1; public int bindTemplateId = -1; // extra added public boolean noted; public boolean lended; private HashMap params; private HashMap wieldRequirements; public static void main(String[] args) throws IOException { Cache.init(""../cache/""); for (int i = 0;i < Utils.getItemDefinitionsSize();i++) { ItemDefinitions def = ItemDefinitions.getDefs(i); if (!def.name.toLowerCase().contains(""key"")) continue; if (def.originalModelColors != null && def.originalModelColors.length > 0) System.out.println(i + "" - "" + def.name + "" - "" + Arrays.toString(def.originalModelColors) + "" - "" + Arrays.toString(def.modifiedModelColors)); } System.out.println(RSColor.RGB_to_HSL(255, 255, 255)); //6792 8867 } /** * 1 = thrown weapons? and cannonballs 2 = arrows 3 = bolts 4 = construction * materials 5 = flatpacks 6 = cooking items 7 = cosmetic items 8 = crafting * items 9 = summoning pouches 10 = junky farming produce 11 = fletching items * 12 = eatable items 13 = herblore secondaries and unf pots 14 = hunter * clothing/traps/bait 15 = hunter produce 16 = jewelry 17 = magic armour 18 = * staves 19 = low tier melee armour 20 = mid tier melee armour 21 = high tier * melee armour 22 = low level melee weapons 23 = mid tier melee weapons 24 = * high tier melee weapons 25 = smithables 26 = finished potions 27 = prayer * enhancing items 28 = prayer training items bones/ashes 29 = ranged armour 30 * = ranged weapons 31 = runecrafting training items 32 = teleport items 33 = * seeds 34 = summoning scrolls 35 = crafting misc items/tools 36 = woodcutting * produce */ public int getItemCategory() { if (params == null) return -1; Object protectedOnDeath = params.get(2195); if (protectedOnDeath != null && protectedOnDeath instanceof Integer) return (Integer) protectedOnDeath; return -1; } public int getIdk() { if (params == null) return -1; Object protectedOnDeath = params.get(1397); if (protectedOnDeath != null && protectedOnDeath instanceof Integer) return (Integer) protectedOnDeath; return -1; } public static void mapEquipIds() { int equipId = 0; for (int itemId = 0; itemId < Utils.getItemDefinitionsSize(); itemId++) { ItemDefinitions def = ItemDefinitions.getDefs(itemId); if (def.getMaleWornModelId1() >= 0 || def.getFemaleWornModelId1() >= 0) { EQUIP_IDS.put(itemId, equipId++); } } } public int getEquipId() { if (EQUIP_IDS.isEmpty()) mapEquipIds(); Integer equipId = EQUIP_IDS.get(id); return equipId == null ? -1 : equipId; } public static final ItemDefinitions getItemDefinitions(Store store, int itemId, boolean loadTemplates) { return new ItemDefinitions(store, itemId, loadTemplates); } public static final ItemDefinitions getItemDefinitions(Store store, int itemId) { return new ItemDefinitions(store, itemId, true); } public static final ItemDefinitions getDefs(int itemId) { return getItemDefinitions(itemId, true); } public static final ItemDefinitions getItemDefinitions(int itemId, boolean loadTemplates) { ItemDefinitions def = ITEM_DEFINITIONS.get(itemId); if (def == null) { def = new ItemDefinitions(itemId, loadTemplates); ITEM_DEFINITIONS.put(itemId, def); } return def; } public static final void clearItemsDefinitions() { ITEM_DEFINITIONS.clear(); } public ItemDefinitions(int id) { this(Cache.STORE, id, true); } public ItemDefinitions(int id, boolean loadTemplates) { this(Cache.STORE, id, loadTemplates); } public ItemDefinitions(Store store, int id, boolean loadTemplates) { this.id = id; setDefaultOptions(); loadItemDefinitions(store, loadTemplates); switch (id) { case 25629: this.name = ""Iron""; break; case 25630: this.name = ""Coal""; break; case 25631: this.name = ""Mithril""; break; case 25632: this.name = ""Adamantite""; break; case 25633: this.name = ""Runite""; break; default: break; } } @Override public String toString() { StringBuilder result = new StringBuilder(); String newLine = System.getProperty(""line.separator""); result.append(this.getClass().getName()); result.append("" {""); result.append(newLine); // determine fields declared in this class only (no fields of // superclass) Field[] fields = this.getClass().getDeclaredFields(); // print field names paired with their values for (Field field : fields) { if (Modifier.isStatic(field.getModifiers())) continue; result.append("" ""); try { result.append(field.getType().getCanonicalName() + "" "" + field.getName() + "": ""); result.append(Utils.getFieldValue(this, field)); } catch (Throwable ex) { System.out.println(ex); } result.append(newLine); } result.append(""}""); return result.toString(); } public boolean isLoaded() { return loaded; } private final void loadItemDefinitions(Store store, boolean loadTemplates) { byte[] data = store.getIndex(IndexType.ITEMS).getFile(ArchiveType.ITEMS.archiveId(id), ArchiveType.ITEMS.fileId(id)); if (data == null) { return; } readOpcodeValues(new InputStream(data)); if (loadTemplates) { if (certTemplateId != -1) toNote(); if (lendTemplateId != -1) toLend(); if (bindTemplateId != -1) toBind(); } parseBonuses(); loaded = true; } public static final int STAB_ATTACK = 0, SLASH_ATTACK = 1, CRUSH_ATTACK = 2, RANGE_ATTACK = 4, MAGIC_ATTACK = 3; public static final int STAB_DEF = 5, SLASH_DEF = 6, CRUSH_DEF = 7, RANGE_DEF = 9, MAGIC_DEF = 8, SUMMONING_DEF = 10; public static final int STRENGTH_BONUS = 14, RANGED_STR_BONUS = 15, MAGIC_DAMAGE = 17, PRAYER_BONUS = 16; public static final int ABSORVE_MELEE_BONUS = 11, ABSORVE_RANGE_BONUS = 13, ABSORVE_MAGE_BONUS = 12; public boolean faceMask() { if (id == 4168) return true; return getParamVal(625) == 1; } private void parseBonuses() { bonuses = new int[18]; bonuses[STAB_ATTACK] = getParamVal(0); bonuses[SLASH_ATTACK] = getParamVal(1); bonuses[CRUSH_ATTACK] = getParamVal(2); bonuses[MAGIC_ATTACK] = getParamVal(3); bonuses[RANGE_ATTACK] = getParamVal(4); bonuses[STAB_DEF] = getParamVal(5); bonuses[SLASH_DEF] = getParamVal(6); bonuses[CRUSH_DEF] = getParamVal(7); bonuses[MAGIC_DEF] = getParamVal(8); bonuses[RANGE_DEF] = getParamVal(9); bonuses[SUMMONING_DEF] = getParamVal(417); bonuses[PRAYER_BONUS] = getParamVal(11); bonuses[ABSORVE_MELEE_BONUS] = getParamVal(967); bonuses[ABSORVE_RANGE_BONUS] = getParamVal(968); bonuses[ABSORVE_MAGE_BONUS] = getParamVal(969); bonuses[STRENGTH_BONUS] = getParamVal(641) / 10; bonuses[RANGED_STR_BONUS] = getParamVal(643) / 10; bonuses[MAGIC_DAMAGE] = getParamVal(685); if (id == 25349) { for (int i = 0;i < bonuses.length;i++) { bonuses[i] = 10000; } } } public void setBonuses(int[] bonuses2) { if (bonuses2[STAB_ATTACK] != 0 || bonuses[STAB_ATTACK] != bonuses2[STAB_ATTACK]) params.put(0, bonuses2[STAB_ATTACK]); if (bonuses2[SLASH_ATTACK] != 0 || bonuses[SLASH_ATTACK] != bonuses2[SLASH_ATTACK]) params.put(1, bonuses2[SLASH_ATTACK]); if (bonuses2[CRUSH_ATTACK] != 0 || bonuses[CRUSH_ATTACK] != bonuses2[CRUSH_ATTACK]) params.put(2, bonuses2[CRUSH_ATTACK]); if (bonuses2[MAGIC_ATTACK] != 0 || bonuses[MAGIC_ATTACK] != bonuses2[MAGIC_ATTACK]) params.put(3, bonuses2[MAGIC_ATTACK]); if (bonuses2[RANGE_ATTACK] != 0 || bonuses[RANGE_ATTACK] != bonuses2[RANGE_ATTACK]) params.put(4, bonuses2[RANGE_ATTACK]); if (bonuses2[STAB_DEF] != 0 || bonuses[STAB_DEF] != bonuses2[STAB_DEF]) params.put(5, bonuses2[STAB_DEF]); if (bonuses2[SLASH_DEF] != 0 || bonuses[SLASH_DEF] != bonuses2[SLASH_DEF]) params.put(6, bonuses2[SLASH_DEF]); if (bonuses2[CRUSH_DEF] != 0 || bonuses[CRUSH_DEF] != bonuses2[CRUSH_DEF]) params.put(7, bonuses2[CRUSH_DEF]); if (bonuses2[MAGIC_DEF] != 0 || bonuses[MAGIC_DEF] != bonuses2[MAGIC_DEF]) params.put(8, bonuses2[MAGIC_DEF]); if (bonuses2[RANGE_DEF] != 0 || bonuses[RANGE_DEF] != bonuses2[RANGE_DEF]) params.put(9, bonuses2[RANGE_DEF]); if (bonuses2[SUMMONING_DEF] != 0 || bonuses[SUMMONING_DEF] != bonuses2[SUMMONING_DEF]) params.put(417, bonuses2[SUMMONING_DEF]); if (bonuses2[PRAYER_BONUS] != 0 || bonuses[PRAYER_BONUS] != bonuses2[PRAYER_BONUS]) params.put(11, bonuses2[PRAYER_BONUS]); if (bonuses2[ABSORVE_MELEE_BONUS] != 0 || bonuses[ABSORVE_MELEE_BONUS] != bonuses2[ABSORVE_MELEE_BONUS]) params.put(967, bonuses2[ABSORVE_MELEE_BONUS]); if (bonuses2[ABSORVE_RANGE_BONUS] != 0 || bonuses[ABSORVE_RANGE_BONUS] != bonuses2[ABSORVE_RANGE_BONUS]) params.put(968, bonuses2[ABSORVE_RANGE_BONUS]); if (bonuses2[ABSORVE_MAGE_BONUS] != 0 || bonuses[ABSORVE_MAGE_BONUS] != bonuses2[ABSORVE_MAGE_BONUS]) params.put(969, bonuses2[ABSORVE_MAGE_BONUS]); if (bonuses2[STRENGTH_BONUS] != 0 || bonuses[STRENGTH_BONUS] != bonuses2[STRENGTH_BONUS]) params.put(641, bonuses2[STRENGTH_BONUS] * 10); if (bonuses2[RANGED_STR_BONUS] != 0 || bonuses[RANGED_STR_BONUS] != bonuses2[RANGED_STR_BONUS]) params.put(643, bonuses2[RANGED_STR_BONUS] * 10); if (bonuses2[MAGIC_DAMAGE] != 0 || bonuses[MAGIC_DAMAGE] != bonuses2[MAGIC_DAMAGE]) params.put(685, bonuses2[MAGIC_DAMAGE]); } private void toNote() { // ItemDefinitions noteItem; //certTemplateId ItemDefinitions realItem = getDefs(certId); membersOnly = realItem.membersOnly; value = realItem.value; name = realItem.name; stackable = 1; noted = true; } private void toBind() { // ItemDefinitions lendItem; //lendTemplateId ItemDefinitions realItem = getDefs(bindId); originalModelColors = realItem.originalModelColors; maleEquip3 = realItem.maleEquip3; femaleEquip3 = realItem.femaleEquip3; teamId = realItem.teamId; value = 0; membersOnly = realItem.membersOnly; name = realItem.name; inventoryOptions = new String[5]; groundOptions = realItem.groundOptions; if (realItem.inventoryOptions != null) for (int optionIndex = 0; optionIndex < 4; optionIndex++) inventoryOptions[optionIndex] = realItem.inventoryOptions[optionIndex]; inventoryOptions[4] = ""Discard""; maleEquip1 = realItem.maleEquip1; maleEquip2 = realItem.maleEquip2; femaleEquip1 = realItem.femaleEquip1; femaleEquip2 = realItem.femaleEquip2; params = realItem.params; wearPos = realItem.wearPos; wearPos2 = realItem.wearPos2; } private void toLend() { // ItemDefinitions lendItem; //lendTemplateId ItemDefinitions realItem = getDefs(lendId); originalModelColors = realItem.originalModelColors; maleEquip3 = realItem.maleEquip3; femaleEquip3 = realItem.femaleEquip3; teamId = realItem.teamId; value = 0; membersOnly = realItem.membersOnly; name = realItem.name; inventoryOptions = new String[5]; groundOptions = realItem.groundOptions; if (realItem.inventoryOptions != null) for (int optionIndex = 0; optionIndex < 4; optionIndex++) inventoryOptions[optionIndex] = realItem.inventoryOptions[optionIndex]; inventoryOptions[4] = ""Discard""; maleEquip1 = realItem.maleEquip1; maleEquip2 = realItem.maleEquip2; femaleEquip1 = realItem.femaleEquip1; femaleEquip2 = realItem.femaleEquip2; params = realItem.params; wearPos = realItem.wearPos; wearPos2 = realItem.wearPos2; lended = true; } public boolean isDestroyItem() { if (inventoryOptions == null) return false; for (String option : inventoryOptions) { if (option == null) continue; if (option.equalsIgnoreCase(""destroy"")) return true; } return false; } public boolean canExchange() { if (isNoted() && certId != -1) return getDefs(certId).grandExchange; return grandExchange; } public int getStageOnDeath() { if (params == null) return 0; Object protectedOnDeath = params.get(1397); if (protectedOnDeath != null && protectedOnDeath instanceof Integer) return (Integer) protectedOnDeath; return 0; } public boolean containsOption(int i, String option) { if (inventoryOptions == null || inventoryOptions[i] == null || inventoryOptions.length <= i) return false; return inventoryOptions[i].equals(option); } public boolean containsOption(String option) { if (inventoryOptions == null) return false; for (String o : inventoryOptions) { if (o == null || !o.equals(option)) continue; return true; } return false; } public boolean isWearItem() { return wearPos != -1; } public boolean isWearItem(boolean male) { if (id == 4285) return true; if (wearPos < 12 && (male ? getMaleWornModelId1() == -1 : getFemaleWornModelId1() == -1)) return false; return wearPos != -1; } public boolean hasSpecialBar() { if (params == null) return false; Object specialBar = params.get(686); if (specialBar != null && specialBar instanceof Integer) return (Integer) specialBar == 1; return false; } public int getRenderAnimId() { if (params == null) return 1426; Object animId = params.get(644); if (animId != null && animId instanceof Integer) return (Integer) animId; return 1426; } public double getDungShopValueMultiplier() { if (params == null) return 1; Object value = params.get(1046); if (value != null && value instanceof Integer) return ((Integer) value).doubleValue() / 100; return 1; } public int getModelZoom() { return modelZoom; } public int getModelOffset1() { return modelOffsetX; } public int getModelOffset2() { return modelOffsetY; } public int getQuestId() { if (params == null) return -1; Object questId = params.get(861); if (questId != null && questId instanceof Integer) return (Integer) questId; return -1; } public int getWieldQuestReq() { switch(id) { case 19784: return 174; case 10887: return 120; default: return getParam(-1, 743); } } public int getParamVal(int id) { return getParam(0, id); } public int getParam(int defaultVal, int id) { if (params == null || params.get(id) == null) return defaultVal; return (int) params.get(id); } public HashMap getClientScriptData() { return params; } public HashMap getWearingSkillRequiriments() { if (params == null) return null; if (wieldRequirements == null) { HashMap skills = new HashMap(); for (int i = 0; i < 10; i++) { Integer skill = (Integer) params.get(749 + (i * 2)); if (skill != null) { Integer level = (Integer) params.get(750 + (i * 2)); if (level != null) skills.put(skill, level); } } Integer maxedSkill = (Integer) params.get(277); if (maxedSkill != null) skills.put(maxedSkill, getId() == 19709 ? 120 : 99); wieldRequirements = skills; switch(getId()) { case 8846: wieldRequirements.put(Constants.ATTACK, 5); wieldRequirements.put(Constants.DEFENSE, 5); break; case 8847: wieldRequirements.put(Constants.ATTACK, 10); wieldRequirements.put(Constants.DEFENSE, 10); break; case 8848: wieldRequirements.put(Constants.ATTACK, 20); wieldRequirements.put(Constants.DEFENSE, 20); break; case 8849: wieldRequirements.put(Constants.ATTACK, 30); wieldRequirements.put(Constants.DEFENSE, 30); break; case 8850: wieldRequirements.put(Constants.ATTACK, 40); wieldRequirements.put(Constants.DEFENSE, 40); break; case 20072: wieldRequirements.put(Constants.ATTACK, 60); wieldRequirements.put(Constants.DEFENSE, 60); break; case 10498: wieldRequirements.put(Constants.RANGE, 30); break; case 10499: wieldRequirements.put(Constants.RANGE, 50); break; case 20068: wieldRequirements.put(Constants.RANGE, 50); break; case 22358: case 22359: case 22360: case 22361: wieldRequirements.put(Constants.ATTACK, 80); break; case 22362: case 22363: case 22364: case 22365: wieldRequirements.put(Constants.RANGE, 80); break; case 22366: case 22367: case 22368: case 22369: wieldRequirements.put(Constants.MAGIC, 80); break; case 21371: case 21372: case 21373: case 21374: case 21375: wieldRequirements.put(Constants.ATTACK, 85); wieldRequirements.put(Constants.SLAYER, 80); break; case 10887: wieldRequirements.put(Constants.ATTACK, 60); wieldRequirements.put(Constants.STRENGTH, 40); break; case 7459: wieldRequirements.put(Constants.DEFENSE, 13); break; case 7460: wieldRequirements.put(Constants.DEFENSE, 34); break; case 7461: wieldRequirements.put(Constants.DEFENSE, 41); break; case 7462: wieldRequirements.put(Constants.DEFENSE, 41); wieldRequirements.put(Constants.COOKING, 64); wieldRequirements.put(Constants.AGILITY, 48); wieldRequirements.put(Constants.MINING, 44); wieldRequirements.put(Constants.FISHING, 47); wieldRequirements.put(Constants.THIEVING, 53); wieldRequirements.put(Constants.HERBLORE, 19); wieldRequirements.put(Constants.MAGIC, 50); wieldRequirements.put(Constants.SMITHING, 34); wieldRequirements.put(Constants.FIREMAKING, 50); wieldRequirements.put(Constants.RANGE, 40); break; } } return wieldRequirements; } private void setDefaultOptions() { groundOptions = new String[] { null, null, ""take"", null, null }; inventoryOptions = new String[] { null, null, null, null, ""drop"" }; } public boolean write(Store store) { return store.getIndex(IndexType.ITEMS).putFile(ArchiveType.ITEMS.archiveId(id), ArchiveType.ITEMS.fileId(id), encode()); } private final byte[] encode() { OutputStream stream = new OutputStream(); stream.writeByte(1); stream.writeBigSmart(modelId); if (!name.equals(""null"")) { stream.writeByte(2); stream.writeString(name); } if (modelZoom != 2000) { stream.writeByte(4); stream.writeShort(modelZoom); } if (modelRotationX != 0) { stream.writeByte(5); stream.writeShort(modelRotationX); } if (modelRotationY != 0) { stream.writeByte(6); stream.writeShort(modelRotationY); } if (modelOffsetX != 0) { stream.writeByte(7); int value = modelOffsetX >>= 0; if (value < 0) value += 65536; stream.writeShort(value); } if (modelOffsetY != 0) { stream.writeByte(8); int value = modelOffsetY >>= 0; if (value < 0) value += 65536; stream.writeShort(value); } if (stackable == 1) { stream.writeByte(11); } if (value != 1) { stream.writeByte(12); stream.writeInt(value); } if (wearPos != -1) { stream.writeByte(13); stream.writeByte(wearPos); } if (wearPos2 != -1) { stream.writeByte(14); stream.writeByte(wearPos2); } if (membersOnly) { stream.writeByte(16); } if (multiStackSize != -1) { stream.writeByte(18); stream.writeShort(multiStackSize); } if (maleEquip1 != -1) { stream.writeByte(23); stream.writeBigSmart(maleEquip1); } if (maleEquip2 != -1) { stream.writeByte(24); stream.writeBigSmart(maleEquip2); } if (femaleEquip1 != -1) { stream.writeByte(25); stream.writeBigSmart(femaleEquip1); } if (femaleEquip2 != -1) { stream.writeByte(26); stream.writeBigSmart(femaleEquip2); } if (wearPos3 != -1) { stream.writeByte(27); stream.writeByte(wearPos3); } String[] DEFAULTGROUND = new String[] { null, null, ""take"", null, null }; for (int i = 0;i < groundOptions.length;i++) { if (groundOptions[i] != null && !groundOptions[i].equals(DEFAULTGROUND[i])) { stream.writeByte(30+i); stream.writeString(groundOptions[i]); } } String[] DEFAULTINV = new String[] { null, null, null, null, ""drop"" }; for (int i = 0;i < inventoryOptions.length;i++) { if (inventoryOptions[i] != null && !inventoryOptions[i].equals(DEFAULTINV[i])) { stream.writeByte(35+i); stream.writeString(inventoryOptions[i]); } } if (originalModelColors != null && modifiedModelColors != null) { stream.writeByte(40); stream.writeByte(originalModelColors.length); for (int i = 0; i < originalModelColors.length; i++) { stream.writeShort(originalModelColors[i]); stream.writeShort(modifiedModelColors[i]); } } if (originalTextureIds != null && modifiedTextureIds != null) { stream.writeByte(41); stream.writeByte(originalTextureIds.length); for (int i = 0; i < originalTextureIds.length; i++) { stream.writeShort(originalTextureIds[i]); stream.writeShort(modifiedTextureIds[i]); } } if (spriteRecolorIndices != null) { stream.writeByte(42); stream.writeByte(spriteRecolorIndices.length); for (int i = 0; i < spriteRecolorIndices.length; i++) stream.writeByte(spriteRecolorIndices[i]); } if (tooltipColor != 0 && hasTooltipColor) { stream.writeByte(43); stream.writeInt(tooltipColor); } if (grandExchange) { stream.writeByte(65); } if (maleEquip3 != -1) { stream.writeByte(78); stream.writeBigSmart(maleEquip3); } if (femaleEquip3 != -1) { stream.writeByte(79); stream.writeBigSmart(femaleEquip3); } if (maleHead1 != -1) { stream.writeByte(90); stream.writeBigSmart(maleHead1); } if (femaleHead1 != -1) { stream.writeByte(91); stream.writeBigSmart(femaleHead1); } if (maleHead2 != -1) { stream.writeByte(92); stream.writeBigSmart(maleHead2); } if (femaleHead2 != -1) { stream.writeByte(93); stream.writeBigSmart(femaleHead2); } if (modelRotationZ != 0) { stream.writeByte(95); stream.writeShort(modelRotationZ); } if (unknownInt6 != 0) { stream.writeByte(96); stream.writeByte(unknownInt6); } if (certId != -1) { stream.writeByte(97); stream.writeShort(certId); } if (certTemplateId != -1) { stream.writeByte(98); stream.writeShort(certTemplateId); } if (stackIds != null && stackAmounts != null) { for (int i = 0; i < stackIds.length; i++) { if (stackIds[i] == 0 && stackAmounts[i] == 0) continue; stream.writeByte(100 + i); stream.writeShort(stackIds[i]); stream.writeShort(stackAmounts[i]); } } if (resizeX != 128) { stream.writeByte(110); stream.writeShort(resizeX); } if (resizeY != 128) { stream.writeByte(111); stream.writeShort(resizeY); } if (resizeZ != 128) { stream.writeByte(112); stream.writeShort(resizeZ); } if (ambient != 0) { stream.writeByte(113); stream.writeByte(ambient); } if (contrast != 0) { stream.writeByte(114); stream.writeByte(contrast / 5); } if (teamId != 0) { stream.writeByte(115); stream.writeByte(teamId); } if (lendId != -1) { stream.writeByte(121); stream.writeShort(lendId); } if (lendTemplateId != -1) { stream.writeByte(122); stream.writeShort(lendTemplateId); } if (maleWearXOffset != 0 || maleWearYOffset != 0 || maleWearZOffset != 0) { stream.writeByte(125); stream.writeByte(maleWearXOffset >> 2); stream.writeByte(maleWearYOffset >> 2); stream.writeByte(maleWearZOffset >> 2); } if (femaleWearXOffset != 0 || femaleWearYOffset != 0 || femaleWearZOffset != 0) { stream.writeByte(126); stream.writeByte(femaleWearXOffset >> 2); stream.writeByte(femaleWearYOffset >> 2); stream.writeByte(femaleWearZOffset >> 2); } if (unknownInt18 != -1 || unknownInt19 != -1) { stream.writeByte(127); stream.writeByte(unknownInt18); stream.writeShort(unknownInt19); } if (unknownInt20 != -1 || unknownInt21 != -1) { stream.writeByte(128); stream.writeByte(unknownInt20); stream.writeShort(unknownInt21); } if (customCursorOp1 != -1 || customCursorId1 != -1) { stream.writeByte(129); stream.writeByte(customCursorOp1); stream.writeShort(customCursorId1); } if (customCursorOp2 != -1 || customCursorId2 != -1) { stream.writeByte(130); stream.writeByte(customCursorOp2); stream.writeShort(customCursorId2); } if (quests != null) { stream.writeByte(132); stream.writeByte(quests.length); for (int index = 0; index < quests.length; index++) stream.writeShort(quests[index]); } if (pickSizeShift != 0) { stream.writeByte(134); stream.writeByte(pickSizeShift); } if (bindId != -1) { stream.writeByte(139); stream.writeShort(bindId); } if (bindTemplateId != -1) { stream.writeByte(140); stream.writeShort(bindTemplateId); } if (params != null) { stream.writeByte(249); stream.writeByte(params.size()); for (int key : params.keySet()) { Object value = params.get(key); stream.writeByte(value instanceof String ? 1 : 0); stream.write24BitInt(key); if (value instanceof String) { stream.writeString((String) value); } else { stream.writeInt((Integer) value); } } } stream.writeByte(0); byte[] data = new byte[stream.getOffset()]; stream.setOffset(0); stream.getBytes(data, 0, data.length); return data; } @SuppressWarnings(""unused"") private final void readValues(InputStream stream, int opcode) { if (opcode == 1) modelId = stream.readBigSmart(); else if (opcode == 2) name = stream.readString(); else if (opcode == 4) modelZoom = stream.readUnsignedShort(); else if (opcode == 5) modelRotationX = stream.readUnsignedShort(); else if (opcode == 6) modelRotationY = stream.readUnsignedShort(); else if (opcode == 7) { modelOffsetX = stream.readUnsignedShort(); if (modelOffsetX > 32767) modelOffsetX -= 65536; modelOffsetX <<= 0; } else if (opcode == 8) { modelOffsetY = stream.readUnsignedShort(); if (modelOffsetY > 32767) modelOffsetY -= 65536; modelOffsetY <<= 0; } else if (opcode == 11) stackable = 1; else if (opcode == 12) { value = stream.readInt(); } else if (opcode == 13) { wearPos = stream.readUnsignedByte(); } else if (opcode == 14) { wearPos2 = stream.readUnsignedByte(); } else if (opcode == 16) membersOnly = true; else if (opcode == 18) { multiStackSize = stream.readUnsignedShort(); } else if (opcode == 23) maleEquip1 = stream.readBigSmart(); else if (opcode == 24) maleEquip2 = stream.readBigSmart(); else if (opcode == 25) femaleEquip1 = stream.readBigSmart(); else if (opcode == 26) femaleEquip2 = stream.readBigSmart(); else if (opcode == 27) wearPos3 = stream.readUnsignedByte(); else if (opcode >= 30 && opcode < 35) groundOptions[opcode - 30] = stream.readString(); else if (opcode >= 35 && opcode < 40) inventoryOptions[opcode - 35] = stream.readString(); else if (opcode == 40) { int length = stream.readUnsignedByte(); originalModelColors = new int[length]; modifiedModelColors = new int[length]; for (int index = 0; index < length; index++) { originalModelColors[index] = stream.readUnsignedShort(); modifiedModelColors[index] = stream.readUnsignedShort(); } } else if (opcode == 41) { int length = stream.readUnsignedByte(); originalTextureIds = new int[length]; modifiedTextureIds = new int[length]; for (int index = 0; index < length; index++) { originalTextureIds[index] = (short) stream.readUnsignedShort(); modifiedTextureIds[index] = (short) stream.readUnsignedShort(); } } else if (opcode == 42) { int length = stream.readUnsignedByte(); spriteRecolorIndices = new byte[length]; for (int index = 0; index < length; index++) spriteRecolorIndices[index] = (byte) stream.readByte(); } else if (opcode == 43) { this.tooltipColor = stream.readInt(); this.hasTooltipColor = true; } else if (opcode == 44) { /*int i_7_ = */stream.readUnsignedShort(); // int i_8_ = 0; // for (int i_9_ = i_7_; i_9_ > 0; i_9_ >>= 1) // i_8_++; // aByteArray6974 = new byte[i_8_]; // byte i_10_ = 0; // for (int i_11_ = 0; i_11_ < i_8_; i_11_++) { // if ((i_7_ & 1 << i_11_) > 0) { // aByteArray6974[i_11_] = i_10_; // i_10_++; // } else // aByteArray6974[i_11_] = (byte) -1; // } } else if (45 == opcode) { /*int i_12_ = */stream.readUnsignedShort(); // int i_13_ = 0; // for (int i_14_ = i_12_; i_14_ > 0; i_14_ >>= 1) // i_13_++; // aByteArray6975 = new byte[i_13_]; // byte i_15_ = 0; // for (int i_16_ = 0; i_16_ < i_13_; i_16_++) { // if ((i_12_ & 1 << i_16_) > 0) { // aByteArray6975[i_16_] = i_15_; // i_15_++; // } else // aByteArray6975[i_16_] = (byte) -1; // } } else if (opcode == 65) grandExchange = true; else if (opcode == 78) maleEquip3 = stream.readBigSmart(); else if (opcode == 79) femaleEquip3 = stream.readBigSmart(); else if (opcode == 90) maleHead1 = stream.readBigSmart(); else if (opcode == 91) femaleHead1 = stream.readBigSmart(); else if (opcode == 92) maleHead2 = stream.readBigSmart(); else if (opcode == 93) femaleHead2 = stream.readBigSmart(); else if (opcode == 94) // new stream.readUnsignedShort(); else if (opcode == 95) modelRotationZ = stream.readUnsignedShort(); else if (opcode == 96) unknownInt6 = stream.readUnsignedByte(); else if (opcode == 97) certId = stream.readUnsignedShort(); else if (opcode == 98) certTemplateId = stream.readUnsignedShort(); else if (opcode >= 100 && opcode < 110) { if (stackIds == null) { stackIds = new int[10]; stackAmounts = new int[10]; } stackIds[opcode - 100] = stream.readUnsignedShort(); stackAmounts[opcode - 100] = stream.readUnsignedShort(); } else if (opcode == 110) resizeX = stream.readUnsignedShort(); else if (opcode == 111) resizeY = stream.readUnsignedShort(); else if (opcode == 112) resizeZ = stream.readUnsignedShort(); else if (opcode == 113) ambient = stream.readByte(); else if (opcode == 114) contrast = stream.readByte() * 5; else if (opcode == 115) teamId = stream.readUnsignedByte(); else if (opcode == 121) lendId = stream.readUnsignedShort(); else if (opcode == 122) lendTemplateId = stream.readUnsignedShort(); else if (opcode == 125) { this.maleWearXOffset = stream.readByte() << 2; this.maleWearYOffset = stream.readByte() << 2; this.maleWearZOffset = stream.readByte() << 2; } else if (opcode == 126) { this.femaleWearXOffset = stream.readByte() << 2; this.femaleWearYOffset = stream.readByte() << 2; this.femaleWearZOffset = stream.readByte() << 2; } else if (opcode == 127) { unknownInt18 = stream.readUnsignedByte(); unknownInt19 = stream.readUnsignedShort(); } else if (opcode == 128) { unknownInt20 = stream.readUnsignedByte(); unknownInt21 = stream.readUnsignedShort(); } else if (opcode == 129) { customCursorOp1 = stream.readUnsignedByte(); customCursorId1 = stream.readUnsignedShort(); } else if (opcode == 130) { customCursorOp2 = stream.readUnsignedByte(); customCursorId2 = stream.readUnsignedShort(); } else if (opcode == 132) { int length = stream.readUnsignedByte(); quests = new int[length]; for (int index = 0; index < length; index++) quests[index] = stream.readUnsignedShort(); } else if (opcode == 134) { this.pickSizeShift = stream.readUnsignedByte(); } else if (opcode == 139) { bindId = stream.readUnsignedShort(); } else if (opcode == 140) { bindTemplateId = stream.readUnsignedShort(); } else if (opcode >= 142 && opcode < 147) { // if (null == ((Class518) this).anIntArray6988) { // ((Class518) this).anIntArray6988 = new int[6]; // Arrays.fill(((Class518) this).anIntArray6988, -1); // } /*anIntArray6988[opcode - 142] = */stream.readUnsignedShort(); } else if (opcode >= 150 && opcode < 155) { // if (null == ((Class518) this).anIntArray6986) { // ((Class518) this).anIntArray6986 = new int[5]; // Arrays.fill(((Class518) this).anIntArray6986, -1); // } /*anIntArray6986[opcode - 150] = */stream.readUnsignedShort(); } else if (opcode == 157) { } else if (161 == opcode) {// new int anInt7904 = stream.readUnsignedShort(); } else if (162 == opcode) {// new int anInt7923 = stream.readUnsignedShort(); } else if (163 == opcode) {// new int anInt7939 = stream.readUnsignedShort(); } else if (164 == opcode) {// new coinshare shard String aString7902 = stream.readString(); } else if (165 == opcode) {// new stackable = 2; } else if (opcode == 249) { int length = stream.readUnsignedByte(); if (params == null) params = new HashMap(length); for (int index = 0; index < length; index++) { boolean stringInstance = stream.readUnsignedByte() == 1; int key = stream.read24BitInt(); Object value = stringInstance ? stream.readString() : stream.readInt(); params.put(key, value); } } else { System.err.println(""MISSING OPCODE "" + opcode + "" FOR ITEM "" + getId()); throw new RuntimeException(""MISSING OPCODE "" + opcode + "" FOR ITEM "" + getId()); } } private final void readOpcodeValues(InputStream stream) { while (true) { int opcode = stream.readUnsignedByte(); if (opcode == 0) break; readValues(stream, opcode); } } public boolean containsEquipmentOption(int optionId, String option) { if (params == null) return false; Object wearingOption = params.get(528 + optionId); if (wearingOption != null && wearingOption instanceof String) return wearingOption.equals(option); return false; } public String getEquipmentOption(int optionId) { if (params == null) return ""null""; Object wearingOption = params.get(optionId == 4 ? 1211 : (528 + optionId)); if (wearingOption != null && wearingOption instanceof String) return (String) wearingOption; return ""null""; } public String getInventoryOption(int optionId) { switch(id) { case 6099: case 6100: case 6101: case 6102: if (optionId == 2) return ""Temple""; break; case 19760: case 13561: case 13562: if (optionId == 0) return inventoryOptions[1]; else if (optionId == 1) return inventoryOptions[0]; break; } if (inventoryOptions == null) return ""null""; if (optionId >= inventoryOptions.length) return ""null""; if (inventoryOptions[optionId] == null) return ""null""; return inventoryOptions[optionId]; } public String getName() { return name; } public int getFemaleWornModelId1() { return femaleEquip1; } public int getFemaleWornModelId2() { return femaleEquip2; } public int getMaleWornModelId1() { return maleEquip1; } public int getMaleWornModelId2() { return maleEquip2; } public boolean isOverSized() { return modelZoom > 5000; } public boolean isLended() { return lended; } public boolean isMembersOnly() { return membersOnly; } public boolean isStackable() { return stackable == 1; } public boolean isNoted() { return noted; } public int getLendId() { return lendId; } public int getCertId() { return certId; } public int getValue() { if (id == 18744 || id == 18745 || id == 18746 || id == 18747) return 5; if (id == 10551 || id == 10548 || id == 2952 || id == 2890 || id == 10499) return 1; return value; } public int getSellPrice() { return (int) (value / (10.0 / 3.0)); } public int getHighAlchPrice() { return (int) (value / (10.0 / 6.0)); } public int getId() { return id; } public int getEquipSlot() { return wearPos; } public boolean isEquipType(int type) { return wearPos3 == type || wearPos2 == type; } public boolean isBinded() { return (id >= 15775 && id <= 16272) || (id >= 19865 && id <= 19866); } public boolean isBindItem() { if (inventoryOptions == null) return false; for (String option : inventoryOptions) { if (option == null) continue; if (option.equalsIgnoreCase(""bind"")) return true; } return false; } public boolean containsInventoryOption(int i, String string) { if (inventoryOptions == null || i >= inventoryOptions.length || inventoryOptions[i] == null) return false; return inventoryOptions[i].equalsIgnoreCase(string); } public int[] getBonuses() { return bonuses; } }" " package com.rs.cache.loaders; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.lang.SuppressWarnings; import com.rs.lib.game.Item; public class LoyaltyRewardDefinitions { private static int NAME = 1930; private static int ITEM_ID = 1935; private static int ENUM = 1995; public enum Type { AURA, EFFECT, EMOTE, COSTUME, TITLE, RECOLOR } public enum Tab { AURAS(5182, 2229, 66, 1, Reward.ODDBALL, Reward.POISON_PURGE, Reward.FRIEND_IN_NEED, Reward.KNOCK_OUT, Reward.SHARPSHOOTER, Reward.RUNIC_ACCURACY, Reward.SUREFOOTED, Reward.REVERENCE, Reward.CALL_OF_THE_SEA, Reward.JACK_OF_TRADES, Reward.GREATER_POISON_PURGE, Reward.GREATER_RUNIC_ACCURACY, Reward.GREATER_SHARPSHOOTER, Reward.GREATER_CALL_OF_THE_SEA, Reward.GREATER_REVERENCE, Reward.GREATER_SUREFOOTED, Reward.LUMBERJACK, Reward.GREATER_LUMBERJACK, Reward.QUARRYMASTER, Reward.GREATER_QUARRYMASTER, Reward.FIVE_FINGER_DISCOUNT, Reward.GREATER_FIVE_FINGER_DISCOUNT, Reward.RESOURCEFUL, Reward.EQUILIBRIUM, Reward.INSPIRATION, Reward.VAMPYRISM, Reward.PENANCE, Reward.WISDOM, Reward.AEGIS, Reward.REGENERATION, Reward.DARK_MAGIC, Reward.BERSERKER, Reward.ANCESTOR_SPIRITS, Reward.GREENFINGERS, Reward.GREATER_GREENFINGERS, Reward.MASTER_GREENFINGERS, Reward.TRACKER, Reward.GREATER_TRACKER, Reward.MASTER_TRACKER, Reward.SALVATION, Reward.GREATER_SALVATION, Reward.MASTER_SALVATION, Reward.CORRUPTION, Reward.GREATER_CORRUPTION, Reward.MASTER_CORRUPTION, Reward.MASTER_FIVE_FINGER_DISCOUNT, Reward.MASTER_QUARRYMASTER, Reward.MASTER_LUMBERJACK, Reward.MASTER_POISON_PURGE, Reward.MASTER_RUNIC_ACCURACY, Reward.MASTER_SHARPSHOOTER, Reward.MASTER_CALL_OF_THE_SEA, Reward.MASTER_REVERENCE, Reward.MASTER_KNOCK_OUT, Reward.SUPREME_SALVATION, Reward.SUPREME_CORRUPTION, Reward.HARMONY, Reward.GREATER_HARMONY, Reward.MASTER_HARMONY, Reward.SUPREME_HARMONY, Reward.INVIGORATE, Reward.GREATER_INVIGORATE, Reward.MASTER_INVIGORATE, Reward.SUPREME_INVIGORATE, Reward.SUPREME_FIVE_FINGER_DISCOUNT, Reward.SUPREME_QUARRYMASTER, Reward.SUPREME_LUMBERJACK, Reward.SUPREME_POISON_PURGE, Reward.SUPREME_RUNIC_ACCURACY, Reward.SUPREME_SHARPSHOOTER, Reward.SUPREME_CALL_OF_THE_SEA, Reward.SUPREME_REVERENCE, Reward.SUPREME_TRACKER, Reward.SUPREME_GREENFINGERS), EFFECTS(5724, 2540, 67, 9, Reward.INFERNAL_GAZE, Reward.SERENE_GAZE, Reward.VERNAL_GAZE, Reward.NOCTURNAL_GAZE, Reward.MYSTICAL_GAZE, Reward.BLAZING_GAZE, Reward.ABYSSAL_GAZE, Reward.DIVINE_GAZE), EMOTES(3875, 2230, 68, 2, Reward.CAT_FIGHT, Reward.TALK_TO_THE_HAND, Reward.SHAKE_HANDS, Reward.HIGH_FIVE, Reward.FACE_PALM, Reward.SURRENDER, Reward.LEVITATE, Reward.MUSCLE_MAN_POSE, Reward.ROFL, Reward.BREATHE_FIRE, Reward.STORM, Reward.SNOW, Reward.HEAD_IN_THE_SAND, Reward.HULA_HOOP, Reward.DISAPPEAR, Reward.GHOST, Reward.BRING_IT, Reward.PALM_FIST, Reward.EVIL_LAUGH, Reward.GOLF_CLAP, Reward.LOLCANO, Reward.INFERNAL_POWER, Reward.DIVINE_POWER, Reward.YOURE_DEAD, Reward.SCREAM, Reward.TORNADO, Reward.ROFLCOPTER, Reward.NATURES_MIGHT, Reward.INNER_POWER, Reward.WEREWOLF_TRANSFORMATION), COSTUMES(5189, 2231, 69, 3, Reward.DERVISH_OUTFIT, Reward.EASTERN_OUTFIT, Reward.SAXON_OUTFIT, Reward.SAMBA_OUTFIT, Reward.THEATRICAL_OUTFIT, Reward.PHARAOH_OUTFIT, Reward.CHANGSHAN_OUTFIT, Reward.SILKEN_OUTFIT, Reward.COLONISTS_OUTFIT, Reward.AZTEC_OUTFIT, Reward.HIGHLANDER_OUTFIT, Reward.MUSKETEER_OUTFIT, Reward.ELVEN_OUTFIT, Reward.WEREWOLF_COSTUME), TITLES(5184, 2232, 70, 4, Reward.SIR, Reward.LORD, Reward.DUDERINO, Reward.LIONHEART, Reward.HELLRAISER, Reward.CRUSADER, Reward.DESPERADO, Reward.BARON, Reward.COUNT, Reward.OVERLORD, Reward.BANDITO, Reward.DUKE, Reward.KING, Reward.BIG_CHEESE, Reward.BIGWIG, Reward.WUNDERKIND, Reward.EMPEROR, Reward.PRINCE, Reward.WITCH_KING, Reward.ARCHON, Reward.JUSTICIAR, Reward.THE_AWESOME, Reward.THE_MAGNIFICENT, Reward.THE_UNDEFEATED, Reward.THE_STRANGE, Reward.THE_DIVINE, Reward.THE_FALLEN, Reward.THE_WARRIOR, Reward.ATHLETE), RECOLOR(5183, 2232, 71, 5, Reward.PET_ROCK, Reward.ROBIN_HOOD_HAT, Reward.STAFF_OF_LIGHT, Reward.GNOME_SCARF, Reward.LUNAR_EQUIPMENT, Reward.FULL_SLAYER_HELMET, Reward.RANGER_BOOTS, Reward.RING_OF_STONE, Reward.ANCIENT_STAFF, Reward.MAGES_BOOK, Reward.TOP_HAT); private int csMapId; public int unlockConfig; private int favoriteComponent; private int buyComponent; public int configId; private Reward[] rewards; private static HashMap map = new HashMap<>(); static { for (Tab t : Tab.values()) { map.put(t.buyComponent, t); map.put(t.favoriteComponent, t); } } public static Tab forId(int componentId) { return map.get(componentId); } private Tab(int reqScript, int unlockConfig, int buyComponent, int configId, Reward... rewards) { this.csMapId = reqScript; this.unlockConfig = unlockConfig; this.buyComponent = buyComponent; this.favoriteComponent = buyComponent-6; this.configId = configId; this.rewards = rewards; } public int getBuyComponent() { return buyComponent; } public int getFavoriteComponent() { return favoriteComponent; } public boolean isBuyComponent(int component) { return buyComponent == component; } public boolean isFavoriteComponent(int component) { return favoriteComponent == component; } public Reward getReward(int slot) { if (slot >= rewards.length) return null; return rewards[slot]; } public int getCSMapId(boolean male) { if (this == Tab.COSTUMES) { return male ? 5189 : 5188; } return csMapId; } public Reward[] getRewards() { return rewards; } } public enum Reward { /* * AURAS */ ODDBALL(Type.AURA, 0x0, -1, 20957, 2000), POISON_PURGE(Type.AURA, 0x1, -1, 20958, 2750), FRIEND_IN_NEED(Type.AURA, 0x2, -1, 20963, 3500), KNOCK_OUT(Type.AURA, 0x3, -1, 20961, 3500), SHARPSHOOTER(Type.AURA, 0x4, -1, 20967, 4250), RUNIC_ACCURACY(Type.AURA, 0x5, -1, 20962, 4250), SUREFOOTED(Type.AURA, 0x6, -1, 20964, 5000), REVERENCE(Type.AURA, 0x7, -1, 20965, 5000), CALL_OF_THE_SEA(Type.AURA, 0x8, -1, 20966, 5000), JACK_OF_TRADES(Type.AURA, 0x9, -1, 20959, 15000), GREATER_POISON_PURGE(Type.AURA, 0xA, 20958, 22268, 12250), GREATER_RUNIC_ACCURACY(Type.AURA, 0xB, 20962, 22270, 16750), GREATER_SHARPSHOOTER(Type.AURA, 0xC, 20967, 22272, 16750), GREATER_CALL_OF_THE_SEA(Type.AURA, 0xD, 20966, 22274, 14000), GREATER_REVERENCE(Type.AURA, 0xE, 20965, 22276, 16000), GREATER_SUREFOOTED(Type.AURA, 0xF, 20964, 22278, 12000), LUMBERJACK(Type.AURA, 0x10, -1, 22280, 5000), GREATER_LUMBERJACK(Type.AURA, 0x11, 22280, 22282, 14000), QUARRYMASTER(Type.AURA, 0x12, -1, 22284, 5000), GREATER_QUARRYMASTER(Type.AURA, 0x13, 22284, 22286, 14000), FIVE_FINGER_DISCOUNT(Type.AURA, 0x14, -1, 22288, 5000), GREATER_FIVE_FINGER_DISCOUNT(Type.AURA, 0x15, 22288, 22290, 14000), RESOURCEFUL(Type.AURA, 0x16, -1, 22292, 23000), EQUILIBRIUM(Type.AURA, 0x17, -1, 22294, 23000), INSPIRATION(Type.AURA, 0x18, -1, 22296, 23000), VAMPYRISM(Type.AURA, 0x19, -1, 22298, 23000), PENANCE(Type.AURA, 0x1A, -1, 22300, 23000), WISDOM(Type.AURA, 0x1B, -1, 22302, 40000), AEGIS(Type.AURA, 0x1C, -1, 22889, 84000), REGENERATION(Type.AURA, 0x1D, -1, 22893, 45000), DARK_MAGIC(Type.AURA, 0x1E, -1, 22891, 42500), BERSERKER(Type.AURA, 0x1F, -1, 22897, 50000), ANCESTOR_SPIRITS(Type.AURA, 0x20, -1, 22895, 50000), GREENFINGERS(Type.AURA, 0x21, -1, 22883, 5000), GREATER_GREENFINGERS(Type.AURA, 0x22, 22883, 22885, 16000), MASTER_GREENFINGERS(Type.AURA, 0x23, 22885, 22887, 29000), TRACKER(Type.AURA, 0x24, -1, 22927, 5000), GREATER_TRACKER(Type.AURA, 0x25, 22927, 22929, 16000), MASTER_TRACKER(Type.AURA, 0x26, 22929, 22931, 29000), SALVATION(Type.AURA, 0x27, -1, 22899, 5000), GREATER_SALVATION(Type.AURA, 0x28, 22899, 22901, 12000), MASTER_SALVATION(Type.AURA, 0x29, 22901, 22903, 30500), CORRUPTION(Type.AURA, 0x2A, -1, 22905, 5000), GREATER_CORRUPTION(Type.AURA, 0x2B, 22905, 22907, 12000), MASTER_CORRUPTION(Type.AURA, 0x2C, 22907, 22909, 30500), MASTER_FIVE_FINGER_DISCOUNT(Type.AURA, 0x2D, 22290, 22911, 33500), MASTER_QUARRYMASTER(Type.AURA, 0x2E, 22286, 22913, 33500), MASTER_LUMBERJACK(Type.AURA, 0x2F, 22282, 22915, 33500), MASTER_POISON_PURGE(Type.AURA, 0x30, 22268, 22917, 32500), MASTER_RUNIC_ACCURACY(Type.AURA, 0x31, 22270, 22919, 29000), MASTER_SHARPSHOOTER(Type.AURA, 0x32, 22272, 22921, 29000), MASTER_CALL_OF_THE_SEA(Type.AURA, 0x33, 22274, 22923, 33500), MASTER_REVERENCE(Type.AURA, 0x34, 22276, 22925, 36500), MASTER_KNOCK_OUT(Type.AURA, 0x35, 20961, 22933, 50000), SUPREME_SALVATION(Type.AURA, 0x36, 22903, 23876, 63500), SUPREME_CORRUPTION(Type.AURA, 0x37, 22909, 23874, 63500), HARMONY(Type.AURA, 0x38, -1, 23848, 5000), GREATER_HARMONY(Type.AURA, 0x39, 23848, 23850, 12000), MASTER_HARMONY(Type.AURA, 0x3A, 23850, 23852, 30500), SUPREME_HARMONY(Type.AURA, 0x3B, 23852, 23854, 63500), INVIGORATE(Type.AURA, 0x3C, -1, 23840, 5000), GREATER_INVIGORATE(Type.AURA, 0x3D, 23840, 23842, 16000), MASTER_INVIGORATE(Type.AURA, 0x3E, 23842, 23844, 36500), SUPREME_INVIGORATE(Type.AURA, 0x3F, 23844, 23846, 57500), SUPREME_FIVE_FINGER_DISCOUNT(Type.AURA, 0x40, 22911, 23856, 58500), SUPREME_QUARRYMASTER(Type.AURA, 0x41, 22913, 23858, 58500), SUPREME_LUMBERJACK(Type.AURA, 0x42, 22915, 23860, 58500), SUPREME_POISON_PURGE(Type.AURA, 0x43, 22917, 23862, 51500), SUPREME_RUNIC_ACCURACY(Type.AURA, 0x44, 22919, 23864, 57000), SUPREME_SHARPSHOOTER(Type.AURA, 0x45, 22921, 23866, 57000), SUPREME_CALL_OF_THE_SEA(Type.AURA, 0x46, 22923, 23868, 58500), SUPREME_REVERENCE(Type.AURA, 0x47, 22925, 23870, 57500), SUPREME_TRACKER(Type.AURA, 0x48, 22931, 23872, 61000), SUPREME_GREENFINGERS(Type.AURA, 0x49, 22887, 23878, 61000), /* * Gazes */ INFERNAL_GAZE(Type.EFFECT, 0x0, -1, 23880, 18000), SERENE_GAZE(Type.EFFECT, 0x1, -1, 23882, 18000), VERNAL_GAZE(Type.EFFECT, 0x2, -1, 23884, 18000), NOCTURNAL_GAZE(Type.EFFECT, 0x3, -1, 23886, 18000), MYSTICAL_GAZE(Type.EFFECT, 0x4, -1, 23888, 18000), BLAZING_GAZE(Type.EFFECT, 0x5, -1, 23890, 18000), ABYSSAL_GAZE(Type.EFFECT, 0x6, -1, 23892, 18000), DIVINE_GAZE(Type.EFFECT, 0x7, -1, 23894, 18000), /* * EMOTES */ CAT_FIGHT(Type.EMOTE, 0x0, -1, 21314, 500), TALK_TO_THE_HAND(Type.EMOTE, 0x1, -1, 21306, 750), SHAKE_HANDS(Type.EMOTE, 0x2, -1, 21300, 750), HIGH_FIVE(Type.EMOTE, 0x3, -1, 21302, 750), FACE_PALM(Type.EMOTE, 0x4, -1, 21312, 750), SURRENDER(Type.EMOTE, 0x5, -1, 21320, 750), LEVITATE(Type.EMOTE, 0x6, -1, 21304, 1000), MUSCLE_MAN_POSE(Type.EMOTE, 0x7, -1, 21298, 1000), ROFL(Type.EMOTE, 0x8, -1, 21316, 1000), BREATHE_FIRE(Type.EMOTE, 0x9, -1, 21318, 1000), STORM(Type.EMOTE, 0xA, -1, 21308, 4000), SNOW(Type.EMOTE, 0xB, -1, 21310, 4000), HEAD_IN_THE_SAND(Type.EMOTE, 0xC, -1, 21874, 6000), HULA_HOOP(Type.EMOTE, 0xD, -1, 21876, 4000), DISAPPEAR(Type.EMOTE, 0xE, -1, 21878, 12000), GHOST(Type.EMOTE, 0xF, -1, 21880, 12000), BRING_IT(Type.EMOTE, 0x10, -1, 21882, 1000), PALM_FIST(Type.EMOTE, 0x11, -1, 21884, 750), EVIL_LAUGH(Type.EMOTE, 0x12, -1, 22512, 1000), GOLF_CLAP(Type.EMOTE, 0x13, -1, 22514, 750), LOLCANO(Type.EMOTE, 0x14, -1, 22516, 6000), INFERNAL_POWER(Type.EMOTE, 0x15, -1, 22518, 12000), DIVINE_POWER(Type.EMOTE, 0x16, -1, 22520, 12000), YOURE_DEAD(Type.EMOTE, 0x17, -1, 22522, 1000), SCREAM(Type.EMOTE, 0x18, -1, 22524, 6000), TORNADO(Type.EMOTE, 0x19, -1, 22526, 12000), ROFLCOPTER(Type.EMOTE, 0x1A, -1, 23832, 6000), NATURES_MIGHT(Type.EMOTE, 0x1B, -1, 23834, 12000), INNER_POWER(Type.EMOTE, 0x1C, -1, 23836, 6000), WEREWOLF_TRANSFORMATION(Type.EMOTE, 0x1D, -1, 23838, 12000), /* * COSTUMES */ DERVISH_OUTFIT(Type.COSTUME, 0x0, -1, new Item[][] { //male new Item[] { new Item(20970, 2), new Item(20980, 2), new Item(20990, 2), new Item(21000, 2) }, //female new Item[] { new Item(21010, 2), new Item(21020, 2), new Item(21030, 2), new Item(21040, 2) }, }, 1000), EASTERN_OUTFIT(Type.COSTUME, 0x1, -1, new Item[][] { //male new Item[] { new Item(21050), new Item(21052, 2), new Item(21062, 2), new Item(21072) }, //female new Item[] { new Item(21074), new Item(21076, 2), new Item(21086, 2), new Item(21096, 2) }, }, 1000), SAXON_OUTFIT(Type.COSTUME, 0x2, -1, new Item[][] { //male new Item[] { new Item(21106, 2), new Item(21116, 2), new Item(21126, 2), new Item(21136, 2) }, //female new Item[] { new Item(21146, 2), new Item(21156, 2), new Item(21166, 2), new Item(21176) }, }, 1000), SAMBA_OUTFIT(Type.COSTUME, 0x3, -1, new Item[][] { //male new Item[] { new Item(21178, 2), new Item(21188, 2), new Item(21198, 2), new Item(21208, 2) }, //female new Item[] { new Item(21218, 2), new Item(21228, 2), new Item(21238, 2), new Item(21248) }, }, 1000), THEATRICAL_OUTFIT(Type.COSTUME, 0x4, -1, new Item[][] { //male new Item[] { new Item(21887, 2), new Item(21897, 2), new Item(21907, 2), new Item(21917, 2) }, //female new Item[] { new Item(21927, 2), new Item(21937, 2), new Item(21947, 2), new Item(21957, 2) }, }, 2000), PHARAOH_OUTFIT(Type.COSTUME, 0x5, -1, new Item[][] { //male new Item[] { new Item(21967, 2), new Item(21977, 2), new Item(21987, 2), new Item(21997, 2) }, //female new Item[] { new Item(22007, 2), new Item(22017, 2), new Item(22027, 2), new Item(22037, 2) }, }, 2000), CHANGSHAN_OUTFIT(Type.COSTUME, 0x6, -1, new Item[][] { //male new Item[] { new Item(22047, 2), new Item(22057, 2), new Item(22067, 2), new Item(22077, 2) }, //female new Item[] { new Item(22087, 2), new Item(22097, 2), new Item(22107, 2), new Item(22117, 2) }, }, 2000), SILKEN_OUTFIT(Type.COSTUME, 0x7, -1, new Item[][] { //male new Item[] { new Item(22127, 2), new Item(22137, 2), new Item(22147, 2), new Item(22157, 2) }, //female new Item[] { new Item(22167, 2), new Item(22177, 2), new Item(22187, 2), new Item(22197, 2) }, }, 2000), COLONISTS_OUTFIT(Type.COSTUME, 0x8, -1, new Item[][] { //male new Item[] { new Item(22568, 2), new Item(22578, 2), new Item(22588, 2), new Item(22598, 2) }, //female new Item[] { new Item(22608, 2), new Item(22618, 2), new Item(22628, 2), new Item(22638) }, //TODO cancer shoes.. }, 4000), AZTEC_OUTFIT(Type.COSTUME, 0x9, -1, new Item[][] { //male new Item[] { new Item(22723, 2), new Item(22733, 2), new Item(22743, 2), new Item(22753, 2) }, //female new Item[] { new Item(22763, 2), new Item(22773, 2), new Item(22783, 2), new Item(22793, 2) }, }, 4000), HIGHLANDER_OUTFIT(Type.COSTUME, 0xA, -1, new Item[][] { //male new Item[] { new Item(22643, 2), new Item(22653, 2), new Item(22663, 2), new Item(22673, 2) }, //female new Item[] { new Item(22683, 2), new Item(22693, 2), new Item(22703, 2), new Item(22713, 2) }, }, 4000), MUSKETEER_OUTFIT(Type.COSTUME, 0xB, -1, new Item[][] { //male new Item[] { new Item(22803, 2), new Item(22813, 2), new Item(22823, 2), new Item(22833, 2) }, //female new Item[] { new Item(22843, 2), new Item(22853, 2), new Item(22863, 2), new Item(22873, 2) }, }, 4000), ELVEN_OUTFIT(Type.COSTUME, 0xC, -1, new Item[][] { //male new Item[] { new Item(23912, 2), new Item(23922, 2), new Item(23932, 2), new Item(23942, 2) }, //female new Item[] { new Item(23952, 2), new Item(23962, 2), new Item(23972, 2), new Item(23982, 2) }, }, 8000), WEREWOLF_COSTUME(Type.COSTUME, 0xD, -1, new Item[][] { //male new Item[] { new Item(23992, 2), new Item(24002, 2), new Item(24012, 2), new Item(24022, 2), new Item(24032, 2) }, //female new Item[] { new Item(24042, 2), new Item(24052, 2), new Item(24062, 2), new Item(24072, 2), new Item(24082, 2) }, }, 8000), /* * TITLES */ SIR(Type.TITLE, 0x0, -1, 5, 1000), LORD(Type.TITLE, 0x1, -1, 6, 1000), DUDERINO(Type.TITLE, 0x2, -1, 7, 4000), LIONHEART(Type.TITLE, 0x3, -1, 8, 4000), HELLRAISER(Type.TITLE, 0x4, -1, 9, 8000), CRUSADER(Type.TITLE, 0x5, -1, 10, 8000), DESPERADO(Type.TITLE, 0x6, -1, 11, 10000), BARON(Type.TITLE, 0x7, -1, 12, 10000), COUNT(Type.TITLE, 0x8, -1, 13, 15000), OVERLORD(Type.TITLE, 0x9, -1, 14, 15000), BANDITO(Type.TITLE, 0xA, -1, 15, 20000), DUKE(Type.TITLE, 0xB, -1, 16, 20000), KING(Type.TITLE, 0xC, -1, 17, 25000), BIG_CHEESE(Type.TITLE, 0xD, -1, 18, 25000), BIGWIG(Type.TITLE, 0xE, -1, 19, 25000), WUNDERKIND(Type.TITLE, 0xF, -1, 20, 50000), EMPEROR(Type.TITLE, 0x10, -1, 26, 30000), PRINCE(Type.TITLE, 0x11, -1, 27, 15000), WITCH_KING(Type.TITLE, 0x12, -1, 28, 50000), ARCHON(Type.TITLE, 0x13, -1, 29, 25000), JUSTICIAR(Type.TITLE, 0x14, -1, 30, 20000), THE_AWESOME(Type.TITLE, 0x15, -1, 31, 50000), THE_MAGNIFICENT(Type.TITLE, 0x16, -1, 32, 50000), THE_UNDEFEATED(Type.TITLE, 0x17, -1, 33, 50000), THE_STRANGE(Type.TITLE, 0x18, -1, 34, 50000), THE_DIVINE(Type.TITLE, 0x19, -1, 35, 50000), THE_FALLEN(Type.TITLE, 0x1A, -1, 36, 50000), THE_WARRIOR(Type.TITLE, 0x1B, -1, 37, 50000), ATHLETE(Type.TITLE, 0x1C, -1, 71, 5000), /* * RECOLORS */ PET_ROCK(Type.RECOLOR, 0x10, -1, 3695, 1000), ROBIN_HOOD_HAT(Type.RECOLOR, 0x11, -1, 2581, 1000), STAFF_OF_LIGHT(Type.RECOLOR, 0x12, -1, 15486, 2000), GNOME_SCARF(Type.RECOLOR, 0x13, -1, 9470, 2000), LUNAR_EQUIPMENT(Type.RECOLOR, 0x14, -1, 9096, 2000), FULL_SLAYER_HELMET(Type.RECOLOR, 0x15, -1, 15492, 4000), RANGER_BOOTS(Type.RECOLOR, 0x16, -1, 2577, 4000), RING_OF_STONE(Type.RECOLOR, 0x17, -1, 6583, 4000), ANCIENT_STAFF(Type.RECOLOR, 0x18, -1, 4675, 6000), MAGES_BOOK(Type.RECOLOR, 0x19, -1, 6889, 6000), TOP_HAT(Type.RECOLOR, 0x1A, -1, 13101, 6000); private Type type; private int bit; private int preReq; private Item[][] items; private int price; private static HashMap ITEMID_MAP = new HashMap(); private static HashMap PREREQ_MAP = new HashMap(); static { for (Reward r : Reward.values()) { ITEMID_MAP.put(r.items[0][0].getId(), r); PREREQ_MAP.put(r.preReq, r); } } public static Reward forId(int itemId) { return ITEMID_MAP.get(itemId); } public static Reward forPreReq(int itemId) { return PREREQ_MAP.get(itemId); } private Reward(Type type, int bit, int preReq, Item[][] items, int price) { this.type = type; this.bit = bit; this.preReq = preReq; this.items = items; this.price = price; } private Reward(Type type, int bit, int preReq, int itemId, int price) { this(type, bit, preReq, new Item[][] { { new Item(itemId) } }, price); } public Reward getLowestTier() { Reward reward = this; while(reward.getPreReq() != -1) reward = Reward.forId(reward.preReq); return reward; } public Type getType() { return type; } public int getBit() { return bit; } public int getPreReq() { return preReq; } public Item getItem() { return items[0][0]; } public Item[] getItems() { return items[0]; } public Item[] getItems(int type) { return items[type]; } public int getPrice() { return price; } } public static void main(String[] args) throws IOException { //Cache.init(); dump(); } @SuppressWarnings(""unused"") private static void dump() { for (Tab t : Tab.values()) { if (t != Tab.COSTUMES) continue; int bit = 0; int index = 0; String nameArr = """"; EnumDefinitions tab = EnumDefinitions.getEnum(t.csMapId); //System.out.println(""Tab parsed: "" + t.name()); for (int i = 0;i < tab.getSize();i++) { StructDefinitions reward = StructDefinitions.getStruct(tab.getIntValue(i)); if (reward != null) { int bitVal = (bit + (t == Tab.RECOLOR ? 16 : 0)); String name = reward.getStringValue(NAME).trim().toUpperCase().replaceAll("" "", ""_""); int itemId = reward.getIntValue(ITEM_ID); if (reward.getStringValue(ENUM).contains(""_female"")) name += ""_F""; if (reward.getStringValue(ENUM).contains(""_male"")) name += ""_M""; int num = 1; if (reward.getIntValue(1950) != 0) { num = 5; } else if (reward.getIntValue(1949) != 0) { num = 4; } else if (reward.getIntValue(1948) != 0) { num = 3; } else if (reward.getIntValue(1947) != 0) { num = 2; } else if (reward.getIntValue(1946) != 0) { num = 1; } int preReq = -1; if (reward.getIntValue(1989) != 0 && reward.getIntValue(1989) < itemId && preReq < itemId) { preReq = reward.getIntValue(1989); } if (reward.getIntValue(1990) != 0 && reward.getIntValue(1990) < itemId && preReq < itemId) { preReq = reward.getIntValue(1990); } if (reward.getIntValue(1991) != 0 && reward.getIntValue(1991) < itemId && preReq < itemId) { preReq = reward.getIntValue(1991); } String[] colors = new String[num]; for (int j = 0;j < num;j++) { if (reward.getIntValue(1946+j) != 0) { colors[j] = StructDefinitions.getStruct(reward.getIntValue(1946+j)).getStringValue(1994); } } nameArr += ""Reward.""+name + (i == tab.getSize()-1 ? """" : "", ""); //System.out.println(name+""(0x""+Integer.toHexString(bitVal).toUpperCase()+"", ""+preReq+"", ""+itemId+"", ""+num+"", ""+reward.getIntValue(PRICE)+""),""); System.out.println(reward.getValues()); System.out.println(Arrays.toString(colors)); // if (i == tab.getSize()-1) { // System.out.println(nameArr); // } index++; bit++; } } } } } " " package com.rs.cache.loaders; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import com.rs.cache.ArchiveType; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.cache.Store; import com.rs.cache.loaders.animations.AnimationDefinitions; import com.rs.lib.game.VarManager; import com.rs.lib.io.InputStream; import com.rs.lib.io.OutputStream; import com.rs.lib.util.Utils; public final class NPCDefinitions { private static final ConcurrentHashMap MAP = new ConcurrentHashMap(); public int id; public HashMap parameters; public int anInt4856; public String[] options = new String[5]; public String[] membersOptions = new String[5]; public int[] modelIds; public byte aByte4916 = -1; private String name = ""null""; public int size = 1; public int basId = -1; byte aByte4871 = 0; public int anInt4873 = -1; public int anInt4861 = -1; public int anInt4875 = -1; public int anInt4854 = -1; public int attackOpCursor = -1; public boolean drawMapdot = true; public int combatLevel = -1; int resizeX = 128; int resizeY = 128; public boolean aBool4904 = false; public boolean aBool4890 = false; public boolean aBool4884 = false; int ambient = 0; int contrast = 0; public int headIcons = -1; public int armyIcon = -1; public int rotation = 32; public int varpBit = -1; public int varp = -1; public boolean visible = true; public boolean isClickable = true; public boolean animateIdle = true; public short aShort4874 = 0; public short aShort4897 = 0; public byte aByte4883 = -96; public byte aByte4899 = -16; public byte walkMask = 0; public int walkingAnimation = -1; public int rotate180Animation = -1; public int rotate90RightAnimation = -1; public int rotate90LeftAnimation = -1; public int specialByte = 0; public int anInt4908 = 0; public int anInt4909 = 255; public int height = -1; public int mapIcon = -1; public int anInt4917 = -1; public int anInt4911 = 256; public int anInt4919 = 256; public int anInt4913 = 0; public boolean aBool4920 = true; short[] originalColors; public short[] modifiedColors; short[] originalTextures; public short[] modifiedTextures; byte[] recolourPalette; public int[] headModels; public int[] transformTo; int[][] modelTranslation; private int[] bonuses; private int[] strBonuses; byte aByte4868; byte aByte4869; byte aByte4905; public int[] quests; public boolean aBool4872; public MovementType movementType; public int respawnDirection = 4; private boolean usesCrawlWalkBAS; public static void main(String[] args) throws IOException { Cache.init(""../cache/""); System.out.println(NPCDefinitions.getDefs(5092).basId); // File file = new File(""npcModifiedColorsTextures.txt""); // if (file.exists()) // file.delete(); // else // file.createNewFile(); // BufferedWriter writer = new BufferedWriter(new FileWriter(file)); // writer.append(""//Version = 727\n""); // writer.flush(); // for (int i = 0;i < Utils.getNPCDefinitionsSize();i++) { // NPCDefinitions defs = getDefs(i); // if (defs.modifiedColors != null || defs.modifiedTextures != null) { // writer.append(i + "": "" + defs.getName()); // writer.newLine(); // writer.append(""Models:"" + Arrays.toString(defs.modelIds)); // writer.newLine(); // writer.append(""Colors: "" + Arrays.toString(defs.modifiedColors)); // writer.newLine(); // writer.append(""Textures: "" + Arrays.toString(defs.modifiedTextures)); // writer.newLine(); // writer.flush(); // } // } // writer.close(); } public boolean transformsTo(int id) { if (this.transformTo == null) return false; for (int to : transformTo) { if (to == id) return true; } return false; } @Override public String toString() { StringBuilder result = new StringBuilder(); String newLine = System.getProperty(""line.separator""); result.append(this.getClass().getName()); result.append("" {""); result.append(newLine); // determine fields declared in this class only (no fields of // superclass) Field[] fields = this.getClass().getDeclaredFields(); // print field names paired with their values for (Field field : fields) { if (Modifier.isStatic(field.getModifiers())) continue; result.append("" ""); try { result.append(field.getType().getCanonicalName() + "" "" + field.getName() + "": ""); result.append(Utils.getFieldValue(this, field)); } catch (Throwable ex) { System.out.println(ex); } result.append(newLine); } result.append(""}""); return result.toString(); } public static final NPCDefinitions getDefs(int id) { NPCDefinitions def = MAP.get(id); if (def == null) { def = new NPCDefinitions(id); def.setEmptyModelIds(); byte[] data = Cache.STORE.getIndex(IndexType.NPCS).getFile(ArchiveType.NPCS.archiveId(id), ArchiveType.NPCS.fileId(id)); if (data == null) { // System.out.println(""Failed loading NPC "" + id + "".""); } else def.readValueLoop(new InputStream(data)); if (def.basId != -1) { BASDefinitions render = BASDefinitions.getDefs(def.basId); if (render != null && render.walkAnimation == -1 && render.teleportingAnimation != -1) def.usesCrawlWalkBAS = true; } def.bonuses = new int[10]; def.bonuses[0] = def.getStabAtt(); def.bonuses[1] = def.getSlashAtt(); def.bonuses[2] = def.getCrushAtt(); def.bonuses[3] = def.getMagicAtt(); def.bonuses[4] = def.getRangeAtt(); def.bonuses[5] = def.getStabDef(); def.bonuses[6] = def.getSlashDef(); def.bonuses[7] = def.getCrushDef(); def.bonuses[8] = def.getMagicDef(); def.bonuses[9] = def.getRangeDef(); def.strBonuses = new int[3]; def.strBonuses[0] = def.getMeleeStr(); def.strBonuses[1] = def.getRangeStr(); def.strBonuses[2] = def.getMagicStr(); MAP.put(id, def); } return def; } public void setEmptyModelIds() { if (modelIds == null) modelIds = new int[0]; } private void readValueLoop(InputStream stream) { while (true) { int opcode = stream.readUnsignedByte(); if (opcode == 0) break; readValues(stream, opcode); } } public int getId() { return id; } public List getCompatibleAnimations() { HashSet animsWithSkeleton = new HashSet(); if (basId != -1) { if (BASDefinitions.getDefs(basId).standAnimation != -1) { if (AnimationDefinitions.getDefs(BASDefinitions.getDefs(basId).standAnimation).frameSetIds != null) { int skeleton = AnimationDefinitions.getDefs(BASDefinitions.getDefs(basId).standAnimation).frameSetIds[0]; for (int i = 0; i < Utils.getAnimationDefinitionsSize(); i++) { AnimationDefinitions check = AnimationDefinitions.getDefs(i); if (check == null) continue; if (check.frameSetIds == null || check.frameSetIds[0] == -1) continue; if (check.frameSetIds[0] == skeleton) animsWithSkeleton.add(i); } } } } List list = new ArrayList<>(animsWithSkeleton); Collections.sort(list); return list; } private void readValues(InputStream stream, int opcode) { if (opcode == 1) { int i_4 = stream.readUnsignedByte(); this.modelIds = new int[i_4]; for (int i_5 = 0; i_5 < i_4; i_5++) { this.modelIds[i_5] = stream.readBigSmart(); } } else if (opcode == 2) { this.name = stream.readString(); } else if (opcode == 12) { this.size = stream.readUnsignedByte(); } else if (opcode >= 30 && opcode < 35) { this.options[opcode - 30] = stream.readString(); } else if (opcode == 40) { int i_4 = stream.readUnsignedByte(); this.originalColors = new short[i_4]; this.modifiedColors = new short[i_4]; for (int i_5 = 0; i_5 < i_4; i_5++) { this.originalColors[i_5] = (short) stream.readUnsignedShort(); this.modifiedColors[i_5] = (short) stream.readUnsignedShort(); } } else if (opcode == 41) { int i_4 = stream.readUnsignedByte(); this.originalTextures = new short[i_4]; this.modifiedTextures = new short[i_4]; for (int i_5 = 0; i_5 < i_4; i_5++) { this.originalTextures[i_5] = (short) stream.readUnsignedShort(); this.modifiedTextures[i_5] = (short) stream.readUnsignedShort(); } } else if (opcode == 42) { int i_4 = stream.readUnsignedByte(); this.recolourPalette = new byte[i_4]; for (int i_5 = 0; i_5 < i_4; i_5++) { this.recolourPalette[i_5] = (byte) stream.readByte(); } } else if (opcode == 60) { int i_4 = stream.readUnsignedByte(); this.headModels = new int[i_4]; for (int i_5 = 0; i_5 < i_4; i_5++) { this.headModels[i_5] = stream.readBigSmart(); } } else if (opcode == 93) { this.drawMapdot = false; } else if (opcode == 95) { this.combatLevel = stream.readUnsignedShort(); } else if (opcode == 97) { this.resizeX = stream.readUnsignedShort(); } else if (opcode == 98) { this.resizeY = stream.readUnsignedShort(); } else if (opcode == 99) { this.aBool4904 = true; } else if (opcode == 100) { this.ambient = stream.readByte(); } else if (opcode == 101) { this.contrast = stream.readByte(); } else if (opcode == 102) { this.headIcons = stream.readUnsignedShort(); } else if (opcode == 103) { this.rotation = stream.readUnsignedShort(); } else if (opcode == 106 || opcode == 118) { this.varpBit = stream.readUnsignedShort(); if (this.varpBit == 65535) { this.varpBit = -1; } this.varp = stream.readUnsignedShort(); if (this.varp == 65535) { this.varp = -1; } int defaultId = -1; if (opcode == 118) { defaultId = stream.readUnsignedShort(); if (defaultId == 65535) { defaultId = -1; } } int size = stream.readUnsignedByte(); this.transformTo = new int[size + 2]; for (int i = 0; i <= size; i++) { this.transformTo[i] = stream.readUnsignedShort(); if (this.transformTo[i] == 65535) { this.transformTo[i] = -1; } } this.transformTo[size + 1] = defaultId; } else if (opcode == 107) { this.visible = false; } else if (opcode == 109) { this.isClickable = false; } else if (opcode == 111) { this.animateIdle = false; } else if (opcode == 113) { this.aShort4874 = (short) stream.readUnsignedShort(); this.aShort4897 = (short) stream.readUnsignedShort(); } else if (opcode == 114) { this.aByte4883 = (byte) stream.readByte(); this.aByte4899 = (byte) stream.readByte(); } else if (opcode == 119) { this.walkMask = (byte) stream.readByte(); } else if (opcode == 121) { this.modelTranslation = new int[this.modelIds.length][]; int i_4 = stream.readUnsignedByte(); for (int i_5 = 0; i_5 < i_4; i_5++) { int i_6 = stream.readUnsignedByte(); int[] translations = this.modelTranslation[i_6] = new int[3]; translations[0] = stream.readByte(); translations[1] = stream.readByte(); translations[2] = stream.readByte(); } } else if (opcode == 123) { this.height = stream.readUnsignedShort(); } else if (opcode == 125) { this.respawnDirection = stream.readByte(); } else if (opcode == 127) { this.basId = stream.readUnsignedShort(); } else if (opcode == 128) { this.movementType = MovementType.forId(stream.readUnsignedByte()); } else if (opcode == 134) { this.walkingAnimation = stream.readUnsignedShort(); if (this.walkingAnimation == 65535) { this.walkingAnimation = -1; } this.rotate180Animation = stream.readUnsignedShort(); if (this.rotate180Animation == 65535) { this.rotate180Animation = -1; } this.rotate90RightAnimation = stream.readUnsignedShort(); if (this.rotate90RightAnimation == 65535) { this.rotate90RightAnimation = -1; } this.rotate90LeftAnimation = stream.readUnsignedShort(); if (this.rotate90LeftAnimation == 65535) { this.rotate90LeftAnimation = -1; } this.specialByte = stream.readUnsignedByte(); } else if (opcode == 135) { this.anInt4875 = stream.readUnsignedByte(); this.anInt4873 = stream.readUnsignedShort(); } else if (opcode == 136) { this.anInt4854 = stream.readUnsignedByte(); this.anInt4861 = stream.readUnsignedShort(); } else if (opcode == 137) { this.attackOpCursor = stream.readUnsignedShort(); } else if (opcode == 138) { this.armyIcon = stream.readBigSmart(); } else if (opcode == 140) { this.anInt4909 = stream.readUnsignedByte(); } else if (opcode == 141) { this.aBool4884 = true; } else if (opcode == 142) { this.mapIcon = stream.readUnsignedShort(); } else if (opcode == 143) { this.aBool4890 = true; } else if (opcode >= 150 && opcode < 155) { this.membersOptions[opcode - 150] = stream.readString(); } else if (opcode == 155) { this.aByte4868 = (byte) stream.readByte(); this.aByte4869 = (byte) stream.readByte(); this.aByte4905 = (byte) stream.readByte(); this.aByte4871 = (byte) stream.readByte(); } else if (opcode == 158) { this.aByte4916 = 1; } else if (opcode == 159) { this.aByte4916 = 0; } else if (opcode == 160) { int i_4 = stream.readUnsignedByte(); this.quests = new int[i_4]; for (int i_5 = 0; i_5 < i_4; i_5++) { this.quests[i_5] = stream.readUnsignedShort(); } } else if (opcode == 162) { this.aBool4872 = true; } else if (opcode == 163) { this.anInt4917 = stream.readUnsignedByte(); } else if (opcode == 164) { this.anInt4911 = stream.readUnsignedShort(); this.anInt4919 = stream.readUnsignedShort(); } else if (opcode == 165) { this.anInt4913 = stream.readUnsignedByte(); } else if (opcode == 168) { this.anInt4908 = stream.readUnsignedByte(); } else if (opcode == 169) { this.aBool4920 = false; } else if (opcode == 249) { int length = stream.readUnsignedByte(); if (parameters == null) parameters = new HashMap(length); for (int i_60_ = 0; i_60_ < length; i_60_++) { boolean bool = stream.readUnsignedByte() == 1; int i_61_ = stream.read24BitInt(); if (!bool) parameters.put(i_61_, stream.readInt()); else parameters.put(i_61_, stream.readString()); } } } public boolean write(Store store) { return store.getIndex(IndexType.NPCS).putFile(ArchiveType.NPCS.archiveId(id), ArchiveType.NPCS.fileId(id), encode()); } private final byte[] encode() { OutputStream stream = new OutputStream(); if (modelIds != null && modelIds.length > 0) { stream.writeByte(1); stream.writeByte(modelIds.length); for (int i = 0;i < modelIds.length;i++) stream.writeBigSmart(modelIds[i]); } if (!name.equals(""null"")) { stream.writeByte(2); stream.writeString(name); } if (size != 1) { stream.writeByte(12); stream.writeByte(size); } for (int i = 0;i < 5;i++) { if (options[i] != null) { stream.writeByte(30+i); stream.writeString(options[i]); } } if (originalColors != null && modifiedColors != null) { stream.writeByte(40); stream.writeByte(originalColors.length); for (int i = 0; i < originalColors.length; i++) { stream.writeShort(originalColors[i]); stream.writeShort(modifiedColors[i]); } } if (originalTextures != null && modifiedTextures != null) { stream.writeByte(41); stream.writeByte(originalTextures.length); for (int i = 0; i < originalTextures.length; i++) { stream.writeShort(originalTextures[i]); stream.writeShort(modifiedTextures[i]); } } if (recolourPalette != null) { stream.writeByte(42); stream.writeByte(recolourPalette.length); for (int i = 0; i < recolourPalette.length; i++) stream.writeByte(recolourPalette[i]); } if (headModels != null && headModels.length > 0) { stream.writeByte(60); stream.writeByte(headModels.length); for (int i = 0;i < headModels.length;i++) stream.writeBigSmart(headModels[i]); } if (!drawMapdot) { stream.writeByte(93); } if (combatLevel != -1) { stream.writeByte(95); stream.writeShort(combatLevel); } if (resizeX != 128) { stream.writeByte(97); stream.writeShort(resizeX); } if (resizeY != 128) { stream.writeByte(98); stream.writeShort(resizeY); } if (aBool4904) { stream.writeByte(99); } if (ambient != 0) { stream.writeByte(100); stream.writeByte(ambient); } if (contrast != 0) { stream.writeByte(101); stream.writeByte(contrast); } if (headIcons != 0) { stream.writeByte(102); stream.writeShort(headIcons); } if (rotation != 32) { stream.writeByte(103); stream.writeShort(rotation); } if (transformTo != null) { //TODO write this properly } if (!visible) { stream.writeByte(107); } if (!isClickable) { stream.writeByte(109); } if (!animateIdle) { stream.writeByte(111); } if (aShort4874 != 0 || aShort4897 != 0) { stream.writeByte(113); stream.writeShort(aShort4874); stream.writeShort(aShort4897); } if (aByte4883 != -96 || aByte4899 != -16) { stream.writeByte(114); stream.writeShort(aByte4883); stream.writeShort(aByte4899); } if (walkMask != 0) { stream.writeByte(119); stream.writeByte(walkMask); } if (modelTranslation != null) { stream.writeByte(121); int translationCount = 0; for (int i = 0;i < modelTranslation.length;i++) { if (modelTranslation[i] != null) translationCount++; } stream.writeByte(translationCount); for (int i = 0;i < modelTranslation.length;i++) { if (modelTranslation[i] != null) { stream.writeByte(i); stream.writeByte(modelTranslation[i][0]); stream.writeByte(modelTranslation[i][1]); stream.writeByte(modelTranslation[i][2]); } } } if (height != -1) { stream.writeByte(123); stream.writeShort(height); } if (respawnDirection != 4) { stream.writeByte(125); stream.writeByte(respawnDirection); } if (basId != -1) { stream.writeByte(127); stream.writeShort(basId); } if (movementType != null) { stream.writeByte(128); stream.writeByte(movementType.id); } if (walkingAnimation != -1 || rotate180Animation != -1 || rotate90RightAnimation != -1 || rotate90LeftAnimation != -1 || specialByte != 0) { stream.writeByte(134); stream.writeShort(walkingAnimation); stream.writeShort(rotate180Animation); stream.writeShort(rotate90RightAnimation); stream.writeShort(rotate90LeftAnimation); stream.writeByte(specialByte); } if (anInt4875 != -1 || anInt4873 != -1) { stream.writeByte(135); stream.writeByte(anInt4875); stream.writeShort(anInt4873); } if (anInt4854 != -1 || anInt4861 != -1) { stream.writeByte(136); stream.writeByte(anInt4854); stream.writeShort(anInt4861); } if (attackOpCursor != -1) { stream.writeByte(137); stream.writeShort(attackOpCursor); } if (armyIcon != -1) { stream.writeByte(138); stream.writeBigSmart(armyIcon); } if (anInt4909 != 255) { stream.writeByte(140); stream.writeByte(anInt4909); } if (aBool4884) { stream.writeByte(141); } if (mapIcon != -1) { stream.writeByte(142); stream.writeShort(mapIcon); } if (aBool4890) { stream.writeByte(143); } for (int i = 0;i < 5;i++) { if (membersOptions[i] != null) { stream.writeByte(150+i); stream.writeString(membersOptions[i]); } } if (aByte4868 != 0 || aByte4869 != 0 || aByte4905 != 0 || aByte4871 != 0) { stream.writeByte(155); stream.writeByte(aByte4868); stream.writeByte(aByte4869); stream.writeByte(aByte4905); stream.writeByte(aByte4871); } if (aByte4916 != -1 && aByte4916 == 1) { stream.writeByte(158); } if (aByte4916 != -1 && aByte4916 == 0) { stream.writeByte(159); } if (quests != null && quests.length > 0) { stream.writeByte(160); stream.writeByte(quests.length); for (int i = 0;i < quests.length;i++) { stream.writeShort(quests[i]); } } if (aBool4872) { stream.writeByte(162); } if (anInt4917 != -1) { stream.writeByte(163); stream.writeByte(anInt4917); } if (anInt4911 != 256 || anInt4919 != 256) { stream.writeByte(164); stream.writeShort(anInt4911); stream.writeShort(anInt4919); } if (anInt4913 != 0) { stream.writeByte(165); stream.writeByte(anInt4913); } if (anInt4908 != 0) { stream.writeByte(168); stream.writeByte(anInt4908); } if (!aBool4920) { stream.writeByte(169); } if (parameters != null) { stream.writeByte(249); stream.writeByte(parameters.size()); for (int key : parameters.keySet()) { Object value = parameters.get(key); stream.writeByte(value instanceof String ? 1 : 0); stream.write24BitInt(key); if (value instanceof String) { stream.writeString((String) value); } else { stream.writeInt((Integer) value); } } } stream.writeByte(0); byte[] data = new byte[stream.getOffset()]; stream.setOffset(0); stream.getBytes(data, 0, data.length); return data; } public int getIdForPlayer(VarManager vars) { if (transformTo == null || transformTo.length == 0) return id; if (vars == null) { int varIdx = transformTo[transformTo.length - 1]; return varIdx; } int index = -1; if (varpBit != -1) { index = vars.getVarBit(varpBit); } else if (varp != -1) { index = vars.getVar(varp); } if (index >= 0 && index < transformTo.length - 1 && transformTo[index] != -1) { return transformTo[index]; } else { int varIdx = transformTo[transformTo.length - 1]; return varIdx; } } public static final void clearNPCDefinitions() { MAP.clear(); } public enum MovementType { STATIONARY(-1), HALF_WALK(0), WALKING(1), RUNNING(2); public int id; private MovementType(int id) { this.id = id; } public static MovementType forId(int id) { for (MovementType type : MovementType.values()) { if (type.id == id) return type; } return null; } } public NPCDefinitions(int id) { this.id = id; } public int getStabAtt() { return getBonus(0); } public int getSlashAtt() { return getBonus(1); } public int getCrushAtt() { return getBonus(2); } public int getMagicAtt() { return getBonus(3); } public int getRangeAtt() { return getBonus(4); } public int getStabDef() { return getBonus(5); } public int getSlashDef() { return getBonus(6); } public int getCrushDef() { return getBonus(7); } public int getMagicDef() { return getBonus(8); } public int getRangeDef() { return getBonus(9); } public int getMagicStr() { return getBonus(965) / 10; } public int getMeleeStr() { return getBonus(641) / 10; } public int getRangeStr() { return getBonus(643) / 10; } public int getAttackDelay() { int speed = getBonus(14); return speed <= 0 ? 4 : speed; } public int getBoBSlots() { return getCSValue(379); } public int getSummoningReq() { return getCSValue(394); } public int getSummoningDurationMins() { return getCSValue(424); } public boolean isBeastOfBurden() { return getCSValue(1323) == 1; } public int getCSValue(int key) { if (parameters == null) return -1; if (parameters.get(key) == null || !(parameters.get(id) instanceof Integer)) return -1; return (Integer) parameters.get(key); } public int getBonus(int id) { if (parameters == null) return 0; if (parameters.get(id) == null || !(parameters.get(id) instanceof Integer)) return 0; int bonus = (Integer) parameters.get(id); return bonus; } public int getBonus(Bonus bonus) { return switch(bonus) { case CRUSH_ATT -> getCrushAtt(); case CRUSH_DEF -> getCrushDef(); case MAGIC_ATT -> getMagicAtt(); case MAGIC_DEF -> getMagicDef(); case MAGIC_STR -> getMagicStr(); case MELEE_STR -> getMeleeStr(); case RANGE_ATT -> getRangeAtt(); case RANGE_DEF -> getRangeDef(); case RANGE_STR -> getRangeStr(); case SLASH_ATT -> getSlashAtt(); case SLASH_DEF -> getSlashDef(); case STAB_ATT -> getStabAtt(); case STAB_DEF -> getStabDef(); default -> 0; }; } public boolean isDungNPC() { return (id >= 9724 && id <= 11229) || (id >= 11708 && id <= 12187) || (id >= 12436 && id <= 13090) || hasOption(""mark""); } public boolean hasOption(String op) { for (String option : options) { if (option != null && option.equalsIgnoreCase(op)) return true; } for (String option : membersOptions) { if (option != null && option.equalsIgnoreCase(op)) return true; } return false; } public String getOption(int op) { if (options == null && membersOptions == null) return ""null""; if (op >= options.length) return ""null""; if (options[op] != null) return options[op]; if (membersOptions[op] != null) return membersOptions[op]; return ""null""; } public boolean hasAttackOption() { for (String option : options) { if (option != null && (option.equalsIgnoreCase(""attack"") || option.equalsIgnoreCase(""destroy""))) return true; } for (String option : membersOptions) { if (option != null && (option.equalsIgnoreCase(""attack"") || option.equalsIgnoreCase(""destroy""))) return true; } return false; } public Object getParam(int is) { if (parameters == null) return null; return parameters.get(id); } public String getConfigInfoString() { String finalString = """"; String transforms = ""\r\n""; boolean found = false; for (int npcId = 0;npcId < Utils.getNPCDefinitionsSize();npcId++) { NPCDefinitions defs = getDefs(npcId); if (defs.transformTo == null) continue; for (int i = 0;i < defs.transformTo.length;i++) { if (defs.transformTo[i] == id) { found = true; transforms += ""["" + npcId + ""(""+defs.getName()+"")"" +"":""; if (defs.varp != -1) transforms += (""v""+defs.varp+""=""+i); if (defs.varpBit != -1) transforms += (""vb""+defs.varpBit+""=""+i); transforms += ""], \r\n""; } } } if (found) { finalString += "" - transformed into by: "" + transforms; transforms = """"; } found = false; if (transformTo != null) { found = true; for (int i = 0;i < transformTo.length;i++) { if (transformTo[i] != -1) transforms += ""["" + i + "": "" + transformTo[i] +"" (""+getDefs(transformTo[i]).name+"")""; else transforms += ""[""+i+"": INVISIBLE""; transforms += ""], \r\n""; } } if (found) { finalString += "" - transforms into with ""; if (varp != -1) finalString += (""v""+varp) + "":""; if (varpBit != -1) finalString += (""vb""+varpBit) + "":""; finalString += transforms; transforms = """"; } return finalString; } public String getName() { return getName(null); } public String getName(VarManager vars) { int realId = getIdForPlayer(vars); if (realId == id) return name; if (realId == -1) return ""null""; return getDefs(realId).name; } public static NPCDefinitions getDefs(int id, VarManager vars) { NPCDefinitions defs = getDefs(getDefs(id).getIdForPlayer(vars)); if (defs == null) return getDefs(id); return defs; } private static String[] UNDEAD = new String[] { ""zombie"", ""skeleton"", ""banshee"", ""ankou"", ""undead"", ""ghast"", ""ghost"", ""crawling hand"", ""skogre"", ""zogre"", ""mummy"", ""revenant"", ""shade"" }; public boolean isUndead() { for(String s : UNDEAD) { if(getName() != null && getName().toLowerCase().contains(s)) return true; } return false; } public boolean crawlWalkRender() { return usesCrawlWalkBAS; } public int[] getBonuses() { return bonuses.clone(); } public int[] getStrBonuses() { return strBonuses.clone(); } } " " package com.rs.cache.loaders; import java.io.IOException; import java.lang.reflect.Field; import java.lang.SuppressWarnings; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.concurrent.ConcurrentHashMap; import com.rs.cache.ArchiveType; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.lib.game.VarManager; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.util.Utils; @SuppressWarnings(""unused"") public class ObjectDefinitions { private static final ConcurrentHashMap objectDefinitions = new ConcurrentHashMap(); public int anInt5633; public byte aByte5634; public int offsetY; public ObjectType[] types; public int[][] modelIds; private String name = ""null""; public int scaleY; public short[] modifiedColors; public byte[] aByteArray5641; public byte aByte5642; public short[] modifiedTextures; public byte aByte5644; public short[] originalColors; public byte aByte5646; public String[] options = new String[5]; public int sizeX; public int sizeY; public int[] transformTo; public int interactable; public int ambientSoundId; public int anInt5654; public boolean delayShading; public int occludes; public boolean castsShadow; public int anInt5658; public int[] animations; public boolean members; public int decorDisplacement; public int varp; public int contrast; public boolean blocks; public int anInt5665; public int anInt5666; public int anInt5667; public int mapIcon; public int anInt5670; public boolean adjustMapSceneRotation; public int mapSpriteRotation; public boolean flipMapSprite; public boolean inverted; public int[] animProbs; public int scaleX; public int clipType; public int scaleZ; public int offsetX; public short[] originalTextures; public int offsetZ; public int anInt5682; public int anInt5683; public int anInt5684; public boolean obstructsGround; public boolean ignoreAltClip; public int supportsItems; public int[] soundEffectsTimed; public int mapSpriteId; public int varpBit; public static short[] aShortArray5691 = new short[256]; public int ambient; public int ambientSoundHearDistance; public int anInt5694; public int ambientSoundVolume; public boolean midiSound; public byte groundContoured; public int anInt5698; public boolean aBool5699; public boolean midiSoundEffectsTimed; public boolean hidden; public boolean aBool5702; public boolean aBool5703; public int anInt5704; public int anInt5705; public boolean hasAnimation; public int[] anIntArray5707; public int anInt5708; public int anInt5709; public int anInt5710; public boolean aBool5711; public HashMap parameters; public int id; public int accessBlockFlag; public static void main(String[] args) throws IOException { Cache.init(""../cache/""); ObjectDefinitions defs = getDefs(40953); System.out.println(defs); // for (int i = 0;i < Utils.getObjectDefinitionsSize();i++) { // ObjectDefinitions def = getDefs(i); // if (def.getName().contains(""Potter"") && def.getName().toLowerCase().contains(""oven"")) { // System.out.println(def.getName()); // } // } // // for (int i = 0;i < defs.toObjectIds.length;i++) { // ObjectDefinitions toDef = getObjectDefinitions(defs.toObjectIds[i]); // System.out.println(i+""-""+toDef.getName()); // } // for (int i = 0;i < Utils.getObjectDefinitionsSize();i++) { // ObjectDefinitions defs = getObjectDefinitions(i); // if (defs.configFileId == 8405) // System.out.println(defs); // } // ProductInfo[] infos = new ProductInfo[] { ProductInfo.Hammerstone, ProductInfo.Asgarnian, ProductInfo.Yanillian, ProductInfo.Krandorian, ProductInfo.Wildblood, ProductInfo.Barley, ProductInfo.Jute }; // // int prodIdx = 0; // for (ProductInfo info : infos) { // int count = 0; // int startIdx = 0; // for (int i = 0;i < 64;i++) { // ObjectDefinitions toDef = getObjectDefinitions(defs.toObjectIds[i]); // if (toDef != null && toDef.getName().contains(info.name())) { // if (startIdx == 0) // startIdx = i; // count++; // } // } // System.out.println(prodIdx + ""(""+info.name() + "") "" + (count-info.maxStage) + ""-"" + startIdx); // // prodIdx++; // } } @Override public String toString() { StringBuilder result = new StringBuilder(); String newLine = System.getProperty(""line.separator""); result.append(this.getClass().getName()); result.append("" {""); result.append(newLine); // determine fields declared in this class only (no fields of // superclass) Field[] fields = this.getClass().getDeclaredFields(); // print field names paired with their values for (Field field : fields) { if (Modifier.isStatic(field.getModifiers())) continue; result.append("" ""); try { result.append(field.getType().getCanonicalName() + "" "" + field.getName() + "": ""); result.append(Utils.getFieldValue(this, field)); } catch (Throwable ex) { System.out.println(ex); } result.append(newLine); } result.append(""}""); return result.toString(); } public int[] getModels(ObjectType type) { for (int i = 0;i < types.length;i++) { if (types[i] == type) return modelIds[i]; } return new int[] {0}; } public String getFirstOption() { if (options == null || options.length < 1 || options[0] == null) return """"; return options[0]; } public String getSecondOption() { if (options == null || options.length < 2 || options[1] == null) return """"; return options[1]; } public String getOption(int option) { if (options == null || options.length < option || option == 0 || options[option - 1] == null) return """"; return options[option - 1]; } public String getOption(ClientPacket option) { int op = -1; switch(option) { case OBJECT_OP1 -> op = 0; case OBJECT_OP2 -> op = 1; case OBJECT_OP3 -> op = 2; case OBJECT_OP4 -> op = 3; case OBJECT_OP5 -> op = 4; default -> throw new IllegalArgumentException(""Unexpected value: "" + option); } if (options == null || op < 0 || options.length < op || options[op] == null) return """"; return options[op]; } public String getThirdOption() { if (options == null || options.length < 3 || options[2] == null) return """"; return options[2]; } public boolean containsOption(int i, String option) { if (options == null || options[i] == null || options.length <= i) return false; return options[i].equals(option); } public boolean containsOptionIgnoreCase(String string) { if (options == null) return false; for (String option : options) { if (option == null) continue; if (option.toLowerCase().contains(string.toLowerCase())) return true; } return false; } public boolean containsOption(String o) { if (options == null) return false; for (String option : options) { if (option == null) continue; if (option.equalsIgnoreCase(o)) return true; } return false; } public boolean containsOption(int i) { if (options == null || options[i] == null || options.length <= i) return false; return !options[i].equals(""null""); } private void readValues(InputStream stream, int opcode) { if (opcode == 1) { int i_4_ = stream.readUnsignedByte(); types = new ObjectType[i_4_]; modelIds = new int[i_4_][]; for (int i_5_ = 0; i_5_ < i_4_; i_5_++) { types[i_5_] = ObjectType.forId(stream.readByte()); int i_6_ = stream.readUnsignedByte(); modelIds[i_5_] = new int[i_6_]; for (int i_7_ = 0; i_7_ < i_6_; i_7_++) modelIds[i_5_][i_7_] = stream.readBigSmart(); } } else if (opcode == 2) name = stream.readString(); else if (opcode == 14) sizeX = stream.readUnsignedByte(); else if (15 == opcode) sizeY = stream.readUnsignedByte(); else if (17 == opcode) { clipType = 0; blocks = false; } else if (18 == opcode) blocks = false; else if (opcode == 19) interactable = stream.readUnsignedByte(); else if (21 == opcode) groundContoured = (byte) 1; else if (22 == opcode) delayShading = true; else if (opcode == 23) occludes = 1; else if (opcode == 24) { int i_8_ = stream.readBigSmart(); if (i_8_ != -1) animations = new int[] { i_8_ }; } else if (opcode == 27) clipType = 1; else if (opcode == 28) decorDisplacement = (stream.readUnsignedByte() << 2); else if (opcode == 29) ambient = stream.readByte(); else if (39 == opcode) contrast = stream.readByte(); else if (opcode >= 30 && opcode < 35) options[opcode - 30] = stream.readString(); else if (40 == opcode) { int i_9_ = stream.readUnsignedByte(); originalColors = new short[i_9_]; modifiedColors = new short[i_9_]; for (int i_10_ = 0; i_10_ < i_9_; i_10_++) { originalColors[i_10_] = (short) stream.readUnsignedShort(); modifiedColors[i_10_] = (short) stream.readUnsignedShort(); } } else if (opcode == 41) { int i_11_ = stream.readUnsignedByte(); originalTextures = new short[i_11_]; modifiedTextures = new short[i_11_]; for (int i_12_ = 0; i_12_ < i_11_; i_12_++) { originalTextures[i_12_] = (short) stream.readUnsignedShort(); modifiedTextures[i_12_] = (short) stream.readUnsignedShort(); } } else if (opcode == 42) { int i_13_ = stream.readUnsignedByte(); aByteArray5641 = new byte[i_13_]; for (int i_14_ = 0; i_14_ < i_13_; i_14_++) aByteArray5641[i_14_] = (byte) stream.readByte(); } else if (opcode == 62) inverted = true; else if (opcode == 64) castsShadow = false; else if (65 == opcode) scaleX = stream.readUnsignedShort(); else if (opcode == 66) scaleY = stream.readUnsignedShort(); else if (67 == opcode) scaleZ = stream.readUnsignedShort(); else if (opcode == 69) accessBlockFlag = stream.readUnsignedByte(); else if (70 == opcode) offsetX = (stream.readShort() << 2); else if (opcode == 71) offsetY = (stream.readShort() << 2); else if (opcode == 72) offsetZ = (stream.readShort() << 2); else if (73 == opcode) obstructsGround = true; else if (opcode == 74) ignoreAltClip = true; else if (opcode == 75) supportsItems = stream.readUnsignedByte(); else if (77 == opcode || 92 == opcode) { varpBit = stream.readUnsignedShort(); if (65535 == varpBit) varpBit = -1; varp = stream.readUnsignedShort(); if (varp == 65535) varp = -1; int objectId = -1; if (opcode == 92) objectId = stream.readBigSmart(); int transforms = stream.readUnsignedByte(); transformTo = new int[transforms + 2]; for (int i = 0; i <= transforms; i++) transformTo[i] = stream.readBigSmart(); transformTo[1 + transforms] = objectId; } else if (78 == opcode) { ambientSoundId = stream.readUnsignedShort(); ambientSoundHearDistance = stream.readUnsignedByte(); } else if (79 == opcode) { anInt5667 = stream.readUnsignedShort(); anInt5698 = stream.readUnsignedShort(); ambientSoundHearDistance = stream.readUnsignedByte(); int i_18_ = stream.readUnsignedByte(); soundEffectsTimed = new int[i_18_]; for (int i_19_ = 0; i_19_ < i_18_; i_19_++) soundEffectsTimed[i_19_] = stream.readUnsignedShort(); } else if (81 == opcode) { groundContoured = (byte) 2; anInt5654 = stream.readUnsignedByte() * 256; } else if (opcode == 82) hidden = true; else if (88 == opcode) aBool5703 = false; else if (opcode == 89) aBool5702 = false; else if (91 == opcode) members = true; else if (93 == opcode) { groundContoured = (byte) 3; anInt5654 = stream.readUnsignedShort(); } else if (opcode == 94) groundContoured = (byte) 4; else if (95 == opcode) { groundContoured = (byte) 5; anInt5654 = stream.readShort(); } else if (97 == opcode) adjustMapSceneRotation = true; else if (98 == opcode) hasAnimation = true; else if (99 == opcode) { anInt5705 = stream.readUnsignedByte(); anInt5665 = stream.readUnsignedShort(); } else if (opcode == 100) { anInt5670 = stream.readUnsignedByte(); anInt5666 = stream.readUnsignedShort(); } else if (101 == opcode) mapSpriteRotation = stream.readUnsignedByte(); else if (opcode == 102) mapSpriteId = stream.readUnsignedShort(); else if (opcode == 103) occludes = 0; else if (104 == opcode) ambientSoundVolume = stream.readUnsignedByte(); else if (opcode == 105) flipMapSprite = true; else if (106 == opcode) { int i_20_ = stream.readUnsignedByte(); int i_21_ = 0; animations = new int[i_20_]; animProbs = new int[i_20_]; for (int i_22_ = 0; i_22_ < i_20_; i_22_++) { animations[i_22_] = stream.readBigSmart(); i_21_ += animProbs[i_22_] = stream.readUnsignedByte(); } for (int i_23_ = 0; i_23_ < i_20_; i_23_++) animProbs[i_23_] = animProbs[i_23_] * 65535 / i_21_; } else if (opcode == 107) mapIcon = stream.readUnsignedShort(); else if (opcode >= 150 && opcode < 155) { options[opcode - 150] = stream.readString(); // if (!((ObjectDefinitionsLoader) loader).showOptions) // aStringArray5647[opcode - 150] = null; } else if (160 == opcode) { int i_24_ = stream.readUnsignedByte(); anIntArray5707 = new int[i_24_]; for (int i_25_ = 0; i_25_ < i_24_; i_25_++) anIntArray5707[i_25_] = stream.readUnsignedShort(); } else if (162 == opcode) { groundContoured = (byte) 3; anInt5654 = stream.readInt(); } else if (163 == opcode) { aByte5644 = (byte) stream.readByte(); aByte5642 = (byte) stream.readByte(); aByte5646 = (byte) stream.readByte(); aByte5634 = (byte) stream.readByte(); } else if (164 == opcode) anInt5682 = stream.readShort(); else if (165 == opcode) anInt5683 = stream.readShort(); else if (166 == opcode) anInt5710 = stream.readShort(); else if (167 == opcode) anInt5704 = stream.readUnsignedShort(); else if (168 == opcode) midiSound = true; else if (169 == opcode) midiSoundEffectsTimed = true; else if (opcode == 170) anInt5684 = stream.readUnsignedSmart(); else if (opcode == 171) anInt5658 = stream.readUnsignedSmart(); else if (opcode == 173) { anInt5708 = stream.readUnsignedShort(); anInt5709 = stream.readUnsignedShort(); } else if (177 == opcode) aBool5699 = true; else if (178 == opcode) anInt5694 = stream.readUnsignedByte(); else if (189 == opcode) aBool5711 = true; else if (249 == opcode) { int length = stream.readUnsignedByte(); if (parameters == null) parameters = new HashMap(length); for (int i_60_ = 0; i_60_ < length; i_60_++) { boolean bool = stream.readUnsignedByte() == 1; int i_61_ = stream.read24BitInt(); if (!bool) parameters.put(i_61_, stream.readInt()); else parameters.put(i_61_, stream.readString()); } } } public int getIdForPlayer(VarManager vars) { if (transformTo == null || transformTo.length == 0) return id; if (vars == null) { int varIdx = transformTo[transformTo.length - 1]; return varIdx; } int index = -1; if (varpBit != -1) { index = vars.getVarBit(varpBit); } else if (varp != -1) { index = vars.getVar(varp); } if (index >= 0 && index < transformTo.length - 1 && transformTo[index] != -1) { return transformTo[index]; } else { int varIdx = transformTo[transformTo.length - 1]; return varIdx; } } public String getConfigInfoString() { String finalString = """"; String transforms = ""\r\n""; boolean found = false; for (int objectId = 0;objectId < Utils.getObjectDefinitionsSize();objectId++) { ObjectDefinitions defs = getDefs(objectId); if (defs.transformTo == null) continue; for (int i = 0;i < defs.transformTo.length;i++) { if (defs.transformTo[i] == id) { found = true; transforms += ""["" + objectId + ""(""+defs.getName()+"")"" +"":""; if (defs.varp != -1) transforms += (""v""+defs.varp+""=""+i); if (defs.varpBit != -1) transforms += (""vb""+defs.varpBit+""=""+i); transforms += ""], \r\n""; } } } if (found) { finalString += "" - transformed into by: "" + transforms; transforms = """"; } found = false; if (transformTo != null) { found = true; for (int i = 0;i < transformTo.length;i++) { if (transformTo[i] != -1) transforms += ""["" + i + "": "" + transformTo[i] +"" (""+getDefs(transformTo[i]).name+"")""; else transforms += ""[""+i+"": INVISIBLE""; transforms += ""], \r\n""; } } if (found) { finalString += "" - transforms into with ""; if (varp != -1) finalString += (""v""+varp) + "":""; if (varpBit != -1) finalString += (""vb""+varpBit) + "":""; finalString += transforms; transforms = """"; } return finalString; } private void skipReadModelIds(InputStream stream) { int length = stream.readUnsignedByte(); for (int index = 0; index < length; index++) { stream.skip(1); int length2 = stream.readUnsignedByte(); for (int i = 0; i < length2; i++) stream.readBigSmart(); } } private void readValueLoop(InputStream stream) { for (;;) { int opcode = stream.readUnsignedByte(); if (opcode == 0) { break; } readValues(stream, opcode); } } private ObjectDefinitions() { aByte5634 = (byte) 0; sizeX = 1; sizeY = 1; clipType = 2; blocks = true; interactable = -1; groundContoured = (byte) 0; anInt5654 = -1; delayShading = false; occludes = -1; anInt5684 = 960; anInt5658 = 0; animations = null; animProbs = null; decorDisplacement = 64; ambient = 0; contrast = 0; anInt5665 = -1; anInt5666 = -1; anInt5705 = -1; anInt5670 = -1; mapIcon = -1; mapSpriteId = -1; adjustMapSceneRotation = false; mapSpriteRotation = 0; flipMapSprite = false; inverted = false; castsShadow = true; scaleX = 128; scaleY = 128; scaleZ = 128; offsetX = 0; offsetY = 0; offsetZ = 0; anInt5682 = 0; anInt5683 = 0; anInt5710 = 0; obstructsGround = false; ignoreAltClip = false; supportsItems = -1; anInt5704 = 0; varpBit = -1; varp = -1; ambientSoundId = -1; ambientSoundHearDistance = 0; anInt5694 = 0; ambientSoundVolume = -1; midiSound = false; anInt5667 = 0; anInt5698 = 0; midiSoundEffectsTimed = false; aBool5702 = true; hidden = false; aBool5703 = true; members = false; hasAnimation = false; anInt5708 = -1; anInt5709 = 0; accessBlockFlag = 0; aBool5699 = false; aBool5711 = false; name = ""null""; } public static ObjectDefinitions getDefs(int id) { ObjectDefinitions def = objectDefinitions.get(id); if (def == null) { def = new ObjectDefinitions(); def.id = id; byte[] data = Cache.STORE.getIndex(IndexType.OBJECTS).getFile(ArchiveType.OBJECTS.archiveId(id), ArchiveType.OBJECTS.fileId(id)); if (data != null) def.readValueLoop(new InputStream(data)); def.method7966(); // if (def.ignoreAltClip) { // def.clipType = 0; // def.blocks = false; // } /* * DUNGEONEERING DOORS?.. */ switch (id) { case 50342: case 50343: case 50344: case 53948: case 55762: case 50350: case 50351: case 50352: case 53950: case 55764: def.ignoreAltClip = false; def.blocks = true; def.clipType = 1; break; } objectDefinitions.put(id, def); } return def; } void method7966() { if (interactable == -1) { interactable = 0; if (null != types && types.length == 1 && (types[0] == ObjectType.SCENERY_INTERACT)) interactable = 1; for (int i_30_ = 0; i_30_ < 5; i_30_++) { if (options[i_30_] != null) { interactable = 1; break; } } } if (supportsItems == -1) supportsItems = (0 != clipType ? 1 : 0); if (animations != null || hasAnimation || transformTo != null) aBool5699 = true; } public static ObjectDefinitions getDefs(int id, VarManager player) { ObjectDefinitions defs = getDefs(getDefs(id).getIdForPlayer(player)); if (defs == null) return getDefs(id); return defs; } public String getName() { return getName(null); } public String getName(VarManager player) { int realId = getIdForPlayer(player); if (realId == id) return name; if (realId == -1) return ""null""; return getDefs(realId).name; } public ObjectDefinitions getRealDefs() { return getDefs(getIdForPlayer(null)); } public int getClipType() { return clipType; } public boolean blocks() { return blocks; } public boolean isClipped() { return clipType != 0; } public int getSizeX() { return sizeX; } public int getSizeY() { return sizeY; } public int getAccessBlockFlag() { return accessBlockFlag; } public static void clearObjectDefinitions() { objectDefinitions.clear(); } public ObjectType getType(int i) { if (types != null && i < types.length) return types[i]; return ObjectType.SCENERY_INTERACT; } public int getSlot() { return getType(0).slot; } } " " package com.rs.cache.loaders; import java.util.HashMap; import java.util.Map; public enum ObjectType { WALL_STRAIGHT(0, 0), WALL_DIAGONAL_CORNER(1, 0), WALL_WHOLE_CORNER(2, 0), WALL_STRAIGHT_CORNER(3, 0), STRAIGHT_INSIDE_WALL_DEC(4, 1), STRAIGHT_OUSIDE_WALL_DEC(5, 1), DIAGONAL_OUTSIDE_WALL_DEC(6, 1), DIAGONAL_INSIDE_WALL_DEC(7, 1), DIAGONAL_INWALL_DEC(8, 1), WALL_INTERACT(9, 2), SCENERY_INTERACT(10, 2), GROUND_INTERACT(11, 2), STRAIGHT_SLOPE_ROOF(12, 2), DIAGONAL_SLOPE_ROOF(13, 2), DIAGONAL_SLOPE_CONNECT_ROOF(14, 2), STRAIGHT_SLOPE_CORNER_CONNECT_ROOF(15, 2), STRAIGHT_SLOPE_CORNER_ROOF(16, 2), STRAIGHT_FLAT_ROOF(17, 2), STRAIGHT_BOTTOM_EDGE_ROOF(18, 2), DIAGONAL_BOTTOM_EDGE_CONNECT_ROOF(19, 2), STRAIGHT_BOTTOM_EDGE_CONNECT_ROOF(20, 2), STRAIGHT_BOTTOM_EDGE_CONNECT_CORNER_ROOF(21, 2), GROUND_DECORATION(22, 3); private static Map MAP = new HashMap<>(); static { for (ObjectType t : ObjectType.values()) MAP.put(t.id, t); } public static ObjectType forId(int type) { return MAP.get(type); } public final int id; public final int slot; ObjectType(int type, int slot) { this.id = type; this.slot = slot; } public boolean isWall() { return id >= ObjectType.WALL_STRAIGHT.id && id <= ObjectType.WALL_STRAIGHT_CORNER.id || id == ObjectType.WALL_INTERACT.id; } }" " package com.rs.cache.loaders; import java.util.concurrent.ConcurrentHashMap; import com.rs.cache.ArchiveType; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.lib.io.InputStream; public final class OverlayDefinitions { private static final ConcurrentHashMap defs = new ConcurrentHashMap(); public int anInt6318; int anInt6319; public int primaryRgb; public int texture = -1; public int anInt6322; public int secondaryRgb; public int anInt6325; public int anInt6326; public boolean aBool6327; public int anInt6328; public int anInt6329; public int anInt6330; public boolean aBool6331; public int anInt6332; public boolean hideUnderlay = true; public int id; public static final OverlayDefinitions getOverlayDefinitions(int id) { OverlayDefinitions script = defs.get(id); if (script != null)// open new txt document return script; byte[] data = Cache.STORE.getIndex(IndexType.CONFIG).getFile(ArchiveType.OVERLAYS.getId(), id); script = new OverlayDefinitions(); script.id = id; if (data != null) script.readValueLoop(new InputStream(data)); defs.put(id, script); return script; } // public int getRGB() { // int rgb = 0; // if (hideUnderlay) { // rgb = primaryRgb; // } // if (secondaryRgb > -1) { // rgb = secondaryRgb; // } // if (texture != -1) { // rgb = TextureDefinitions.getDefinitions(texture & 0xFF).unk4; // } // if (rgb == 0 || rgb == -1 || rgb == 16711935) { // rgb = 0; // } // return rgb; // } public int getOverlayRGB() { int col = primaryRgb == -1 || primaryRgb == 16711935 || primaryRgb == 0 ? secondaryRgb : primaryRgb; if (col == 0 || col == -1 || col == 16711935) { col = 0; } if (col == 0 && texture != -1) { col = TextureDefinitions.getDefinitions(texture & 0xFF).color; } return col; } public int getShapeRGB() { int col = primaryRgb == -1 || primaryRgb == 16711935 || primaryRgb == 0 ? secondaryRgb : primaryRgb; if (col == 0 || col == -1 || col == 16711935) { col = 0; } return col; } OverlayDefinitions() { secondaryRgb = -1; anInt6322 = -1; aBool6331 = true; anInt6326 = -1; aBool6327 = false; anInt6328 = -1; anInt6329 = -1; anInt6330 = -1; anInt6318 = -1; anInt6325 = -1; } private void readValueLoop(InputStream stream) { for (;;) { int opcode = stream.readUnsignedByte(); if (opcode == 0) break; readValues(stream, opcode); } } static int method2632(int i) { if (i == 16711935) return -1; return method11651(i); } public static int method11651(int i) { double d = (double) (i >> 16 & 0xff) / 256.0; double d_13_ = (double) (i >> 8 & 0xff) / 256.0; double d_14_ = (double) (i & 0xff) / 256.0; double d_15_ = d; if (d_13_ < d_15_) d_15_ = d_13_; if (d_14_ < d_15_) d_15_ = d_14_; double d_16_ = d; if (d_13_ > d_16_) d_16_ = d_13_; if (d_14_ > d_16_) d_16_ = d_14_; double d_17_ = 0.0; double d_18_ = 0.0; double d_19_ = (d_16_ + d_15_) / 2.0; if (d_15_ != d_16_) { if (d_19_ < 0.5) d_18_ = (d_16_ - d_15_) / (d_15_ + d_16_); if (d_19_ >= 0.5) d_18_ = (d_16_ - d_15_) / (2.0 - d_16_ - d_15_); if (d == d_16_) d_17_ = (d_13_ - d_14_) / (d_16_ - d_15_); else if (d_16_ == d_13_) d_17_ = 2.0 + (d_14_ - d) / (d_16_ - d_15_); else if (d_16_ == d_14_) d_17_ = 4.0 + (d - d_13_) / (d_16_ - d_15_); } d_17_ /= 6.0; int i_20_ = (int) (d_17_ * 256.0); int i_21_ = (int) (d_18_ * 256.0); int i_22_ = (int) (d_19_ * 256.0); if (i_21_ < 0) i_21_ = 0; else if (i_21_ > 255) i_21_ = 255; if (i_22_ < 0) i_22_ = 0; else if (i_22_ > 255) i_22_ = 255; if (i_22_ > 243) i_21_ >>= 4; else if (i_22_ > 217) i_21_ >>= 3; else if (i_22_ > 192) i_21_ >>= 2; else if (i_22_ > 179) i_21_ >>= 1; return ((i_22_ >> 1) + (((i_20_ & 0xff) >> 2 << 10) + (i_21_ >> 5 << 7))); } private void readValues(InputStream stream, int i) { if (1 == i) primaryRgb = stream.read24BitInt(); //rgb = method2632(stream.read24BitInt()); else if (i == 2) texture = stream.readUnsignedByte(); else if (3 == i) { texture = stream.readUnsignedShort(); if (65535 == texture) texture = -1; } else if (i == 5) hideUnderlay = false; else if (i == 7) secondaryRgb = stream.read24BitInt();/* * method2632(stream.read24BitInt( ), -398738558); */ else if (8 != i) { if (i == 9) anInt6322 = ((stream.readUnsignedShort() << 2)); else if (i == 10) aBool6331 = false; else if (i == 11) anInt6326 = stream.readUnsignedByte(); else if (i == 12) aBool6327 = true; else if (i == 13) anInt6328 = stream.read24BitInt(); else if (14 == i) anInt6329 = (stream.readUnsignedByte() << 2); else if (16 == i) anInt6330 = stream.readUnsignedByte(); else if (i == 20) anInt6318 = stream.readUnsignedShort(); else if (i == 21) anInt6332 = stream.readUnsignedByte(); else if (i == 22) anInt6325 = stream.readUnsignedShort(); } } } " " package com.rs.cache.loaders; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.concurrent.ConcurrentHashMap; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.cache.Store; import com.rs.lib.io.InputStream; import com.rs.lib.io.OutputStream; import com.rs.lib.util.Utils; public class ParticleProducerDefinitions { private static final ConcurrentHashMap PARTICLE_DEFS = new ConcurrentHashMap(); public int id; public int[] anIntArray562; public short minimumAngleH; public short maximumAngleH; public short minimumAngleV; public short maximumAngleV; public int minimumSpeed; public int maximumSpeed; public int anInt542 = 0; public int anInt569; public int maximumSize; public int minimumSize; public int minimumStartColor; public int maximumStartColor; public int minimumLifetime; public int maximumLifetime; public int minimumParticleRate; public int maximumParticleRate; public int[] anIntArray559; public int[] anIntArray561; public int anInt591 = -2; public int anInt600 = -2; public int anInt557 = 0; public int textureId = -1; public int anInt573 = -1; public int fadeColor; public boolean activeFirst = true; public int anInt537 = -1; public int lifetime = -1; public int minimumSetting = 0; public int colorFading = 100; public boolean periodic = true; public int alphaFading = 100; public int endSpeed = -1; public int speedChange = 100; public boolean uniformColorVariance = true; public int[] anIntArray582; public boolean aBool572 = true; public int endSize = -1; public int sizeChange = 100; public boolean aBool574 = false; public boolean aBool534 = true; public boolean aBool576 = false; public boolean aBool541 = true; public boolean opcode5 = false; public boolean opcode31 = false; /* * Initialized variables */ public boolean aBool578 = false; public int anInt565; public int anInt566; public int anInt581; public int anInt551; public int anInt599; public int anInt584; public int anInt585; public int anInt586; public int anInt587; public int anInt588; public int anInt575; public int anInt590; public int colorFadeStart; public int alphaFadeStart; public int fadeRedStep; public int fadeGreenStep; public int fadeBlueStep; public int startSpeedChange; public int fadeAlphaStep; public int speedStep; public int startSizeChange; public int sizeChangeStep; private int opcode2; private int opcode29; public static void main(String[] args) throws IOException { //Cache.init(); // for (int i = 0;i < Cache.STORE.getIndex(IndexType.PARTICLES).getLastFileId(0);i++) { // ParticleProducerDefinitions defs = getDefs(i); // System.out.println(defs); // } System.out.println(getDefs(729)); } public static final ParticleProducerDefinitions getDefs(int id) { ParticleProducerDefinitions defs = PARTICLE_DEFS.get(id); if (defs != null) return defs; byte[] data = Cache.STORE.getIndex(IndexType.PARTICLES).getFile(0, id); defs = new ParticleProducerDefinitions(); defs.id = id; if (data != null) defs.readValueLoop(new InputStream(data), false); //defs.init(); PARTICLE_DEFS.put(id, defs); return defs; } public void decode(byte[] data, boolean rs3) { readValueLoop(new InputStream(data), rs3); } private void readValueLoop(InputStream stream, boolean rs3) { for (;;) { int opcode = stream.readUnsignedByte(); if (opcode == 0) break; readValues(stream, opcode, rs3); } } private void readValues(InputStream buffer, int opcode, boolean rs3) { if (opcode == 1) { this.minimumAngleH = (short) buffer.readUnsignedShort(); this.maximumAngleH = (short) buffer.readUnsignedShort(); this.minimumAngleV = (short) buffer.readUnsignedShort(); this.maximumAngleV = (short) buffer.readUnsignedShort(); } else if (opcode == 2) { this.opcode2 = buffer.readUnsignedByte(); } else if (opcode == 3) { this.minimumSpeed = buffer.readInt(); this.maximumSpeed = buffer.readInt(); } else if (opcode == 4) { this.anInt542 = buffer.readUnsignedByte(); this.anInt569 = buffer.readByte(); } else if (opcode == 5) { this.opcode5 = true; this.minimumSize = this.maximumSize = buffer.readUnsignedShort(); } else if (opcode == 6) { this.minimumStartColor = buffer.readInt(); this.maximumStartColor = buffer.readInt(); } else if (opcode == 7) { this.minimumLifetime = buffer.readUnsignedShort(); this.maximumLifetime = buffer.readUnsignedShort(); } else if (opcode == 8) { this.minimumParticleRate = buffer.readUnsignedShort(); this.maximumParticleRate = buffer.readUnsignedShort(); } else { int i_5; int count; if (opcode == 9) { count = buffer.readUnsignedByte(); this.anIntArray559 = new int[count]; for (i_5 = 0; i_5 < count; i_5++) { this.anIntArray559[i_5] = buffer.readUnsignedShort(); } } else if (opcode == 10) { count = buffer.readUnsignedByte(); this.anIntArray561 = new int[count]; for (i_5 = 0; i_5 < count; i_5++) { this.anIntArray561[i_5] = buffer.readUnsignedShort(); } } else if (opcode == 12) { this.anInt591 = buffer.readByte(); } else if (opcode == 13) { this.anInt600 = buffer.readByte(); } else if (opcode == 14) { this.anInt557 = buffer.readUnsignedShort(); } else if (opcode == 15) { this.textureId = buffer.readUnsignedShort(); } else if (opcode == 16) { this.activeFirst = buffer.readUnsignedByte() == 1; this.anInt537 = buffer.readUnsignedShort(); this.lifetime = buffer.readUnsignedShort(); this.periodic = buffer.readUnsignedByte() == 1; } else if (opcode == 17) { this.anInt573 = buffer.readUnsignedShort(); } else if (opcode == 18) { this.fadeColor = buffer.readInt(); } else if (opcode == 19) { this.minimumSetting = buffer.readUnsignedByte(); } else if (opcode == 20) { this.colorFading = buffer.readUnsignedByte(); } else if (opcode == 21) { this.alphaFading = buffer.readUnsignedByte(); } else if (opcode == 22) { this.endSpeed = buffer.readInt(); } else if (opcode == 23) { this.speedChange = buffer.readUnsignedByte(); } else if (opcode == 24) { this.uniformColorVariance = false; } else if (opcode == 25) { count = buffer.readUnsignedByte(); this.anIntArray582 = new int[count]; for (i_5 = 0; i_5 < count; i_5++) { this.anIntArray582[i_5] = buffer.readUnsignedShort(); } } else if (opcode == 26) { this.aBool572 = false; } else if (opcode == 27) { this.endSize = buffer.readUnsignedShort(); } else if (opcode == 28) { this.sizeChange = buffer.readUnsignedByte(); } else if (opcode == 29) { if (rs3) { if (buffer.readUnsignedByte() == 0) { buffer.readShort(); } else { buffer.readShort(); buffer.readShort() ; } } else this.opcode29 = buffer.readShort(); } else if (opcode == 30) { this.aBool574 = true; } else if (opcode == 31) { this.opcode31 = true; this.minimumSize = buffer.readUnsignedShort(); this.maximumSize = buffer.readUnsignedShort(); } else if (opcode == 32) { this.aBool534 = false; } else if (opcode == 33) { this.aBool576 = true; } else if (opcode == 34) { this.aBool541 = false; } else if (opcode == 35) { if (buffer.readUnsignedByte() == 0) { buffer.readShort(); } else { buffer.readShort(); buffer.readShort(); buffer.readUnsignedByte(); } } } } public byte[] encode() { OutputStream stream = new OutputStream(); if (minimumAngleH != 0 || maximumAngleH != 0 || minimumAngleV != 0 || maximumAngleV != 0) { stream.writeByte(1); stream.writeShort(minimumAngleH); stream.writeShort(maximumAngleH); stream.writeShort(minimumAngleV); stream.writeShort(maximumAngleV); } if (opcode2 != 0) { stream.writeByte(2); stream.writeByte(opcode2); } if (minimumSpeed != 0 || maximumSpeed != 0) { stream.writeByte(3); stream.writeInt(minimumSpeed); stream.writeInt(maximumSpeed); } if (anInt542 != 0 || anInt569 != 0) { stream.writeByte(4); stream.writeByte(anInt542); stream.writeByte(anInt569); } if (opcode5) { stream.writeByte(5); stream.writeShort(minimumSize); } if (minimumStartColor != 0 || maximumStartColor != 0) { stream.writeByte(6); stream.writeInt(minimumStartColor); stream.writeInt(maximumStartColor); } if (minimumLifetime != 0 || maximumLifetime != 0) { stream.writeByte(7); stream.writeShort(minimumLifetime); stream.writeShort(maximumLifetime); } if (minimumParticleRate != 0 || maximumParticleRate != 0) { stream.writeByte(8); stream.writeShort(minimumParticleRate); stream.writeShort(maximumParticleRate); } if (anIntArray559 != null) { stream.writeByte(9); stream.writeByte(anIntArray559.length); for (int i = 0;i < anIntArray559.length;i++) { stream.writeShort(anIntArray559[i]); } } if (anIntArray561 != null) { stream.writeByte(10); stream.writeByte(anIntArray561.length); for (int i = 0;i < anIntArray561.length;i++) { stream.writeShort(anIntArray561[i]); } } if (anInt591 != -2) { stream.writeByte(12); stream.writeByte(anInt591); } if (anInt600 != -2) { stream.writeByte(13); stream.writeByte(anInt600); } if (anInt557 != 0) { stream.writeByte(14); stream.writeShort(anInt557); } if (textureId != -1) { stream.writeByte(15); stream.writeShort(textureId); } if (!activeFirst || anInt537 != -1 || lifetime != -1 || !periodic) { stream.writeByte(16); stream.writeBoolean(activeFirst); stream.writeShort(anInt537); stream.writeShort(lifetime); stream.writeBoolean(periodic); } if (anInt573 != -1) { stream.writeByte(17); stream.writeShort(anInt573); } if (fadeColor != 0) { stream.writeByte(18); stream.writeInt(fadeColor); } if (minimumSetting != 0) { stream.writeByte(19); stream.writeByte(minimumSetting); } if (colorFading != 100) { stream.writeByte(20); stream.writeByte(colorFading); } if (alphaFading != 100) { stream.writeByte(21); stream.writeByte(alphaFading); } if (endSpeed != -1) { stream.writeByte(22); stream.writeInt(endSpeed); } if (speedChange != 100) { stream.writeByte(23); stream.writeByte(speedChange); } if (!uniformColorVariance) { stream.writeByte(24); } if (anIntArray582 != null) { stream.writeByte(25); stream.writeByte(anIntArray582.length); for (int i = 0;i < anIntArray582.length;i++) { stream.writeShort(anIntArray582[i]); } } if (!aBool572) { stream.writeByte(26); } if (endSize != -1) { stream.writeByte(27); stream.writeShort(endSize); } if (sizeChange != 100) { stream.writeByte(28); stream.writeByte(sizeChange); } if (opcode29 != 0) { stream.writeByte(29); stream.writeShort(opcode29); } if (aBool574) { stream.writeByte(30); } if (opcode31) { stream.writeByte(31); stream.writeShort(minimumSize); stream.writeShort(maximumSize); } if (!aBool534) { stream.writeByte(32); } if (aBool576) { stream.writeByte(33); } if (!aBool541) { stream.writeByte(34); } stream.writeByte(0); return stream.toByteArray(); } public boolean write(Store store) { return store.getIndex(IndexType.PARTICLES).putFile(0, id, encode()); } void init() { if (this.anInt591 > -2 || this.anInt600 > -2) { this.aBool578 = true; } this.anInt565 = this.minimumStartColor >> 16 & 0xff; this.anInt566 = this.maximumStartColor >> 16 & 0xff; this.anInt581 = this.anInt566 - this.anInt565; this.anInt551 = this.minimumStartColor >> 8 & 0xff; this.anInt599 = this.maximumStartColor >> 8 & 0xff; this.anInt584 = this.anInt599 - this.anInt551; this.anInt585 = this.minimumStartColor & 0xff; this.anInt586 = this.maximumStartColor & 0xff; this.anInt587 = this.anInt586 - this.anInt585; this.anInt588 = this.minimumStartColor >> 24 & 0xff; this.anInt575 = this.maximumStartColor >> 24 & 0xff; this.anInt590 = this.anInt575 - this.anInt588; if (this.fadeColor != 0) { this.colorFadeStart = this.colorFading * this.maximumLifetime / 100; this.alphaFadeStart = this.alphaFading * this.maximumLifetime / 100; if (this.colorFadeStart == 0) { this.colorFadeStart = 1; } this.fadeRedStep = ((this.fadeColor >> 16 & 0xff) - (this.anInt581 / 2 + this.anInt565) << 8) / this.colorFadeStart; this.fadeGreenStep = ((this.fadeColor >> 8 & 0xff) - (this.anInt584 / 2 + this.anInt551) << 8) / this.colorFadeStart; this.fadeBlueStep = ((this.fadeColor & 0xff) - (this.anInt587 / 2 + this.anInt585) << 8) / this.colorFadeStart; if (this.alphaFadeStart == 0) { this.alphaFadeStart = 1; } this.fadeAlphaStep = ((this.fadeColor >> 24 & 0xff) - (this.anInt590 / 2 + this.anInt588) << 8) / this.alphaFadeStart; this.fadeRedStep += this.fadeRedStep > 0 ? -4 : 4; this.fadeGreenStep += this.fadeGreenStep > 0 ? -4 : 4; this.fadeBlueStep += this.fadeBlueStep > 0 ? -4 : 4; this.fadeAlphaStep += this.fadeAlphaStep > 0 ? -4 : 4; } if (this.endSpeed != -1) { this.startSpeedChange = this.maximumLifetime * this.speedChange / 100; if (this.startSpeedChange == 0) { this.startSpeedChange = 1; } this.speedStep = (this.endSpeed - ((this.maximumSpeed - this.minimumSpeed) / 2 + this.minimumSpeed)) / this.startSpeedChange; } if (this.endSize != -1) { this.startSizeChange = this.sizeChange * this.maximumLifetime / 100; if (this.startSizeChange == 0) { this.startSizeChange = 1; } this.sizeChangeStep = (this.endSize - ((this.maximumSize - this.minimumSize) / 2 + this.minimumSize)) / this.startSizeChange; } } @Override public String toString() { StringBuilder result = new StringBuilder(); String newLine = System.getProperty(""line.separator""); result.append(this.getClass().getName()); result.append("" {""); result.append(newLine); // determine fields declared in this class only (no fields of // superclass) Field[] fields = this.getClass().getDeclaredFields(); // print field names paired with their values for (Field field : fields) { if (Modifier.isStatic(field.getModifiers())) continue; result.append("" ""); try { result.append(field.getType().getCanonicalName() + "" "" + field.getName() + "": ""); result.append(Utils.getFieldValue(this, field)); } catch (Throwable ex) { System.out.println(ex); } result.append(newLine); } result.append(""}""); return result.toString(); } } " " package com.rs.cache.loaders; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashMap; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.lib.io.InputStream; import com.rs.lib.util.Utils; public class QCCategoryDefinitions { private static final HashMap CACHE = new HashMap<>(); public int id; public String name; public int[] subCategories; public char[] subCategoryHotkeys; public int[] messages; public char[] messageHotkeys; public static final QCCategoryDefinitions getDefs(int id) { QCCategoryDefinitions defs = CACHE.get(id); if (defs != null) return defs; byte[] data = Cache.STORE.getIndex(IndexType.QC_MENUS).getFile(0, id); defs = new QCCategoryDefinitions(); defs.id = id; if (data != null) defs.readValueLoop(new InputStream(data)); CACHE.put(id, defs); return defs; } private void readValueLoop(InputStream stream) { for (;;) { int opcode = stream.readUnsignedByte(); if (opcode == 0) break; readValues(stream, opcode); } method15213(); } void method15213() { int i_2; if (this.messages != null) { for (i_2 = 0; i_2 < this.messages.length; i_2++) { this.messages[i_2] |= 0x8000; } } if (this.subCategories != null) { for (i_2 = 0; i_2 < this.subCategories.length; i_2++) { this.subCategories[i_2] |= 0x8000; } } } private void readValues(InputStream buffer, int opcode) { if (opcode == 1) { this.name = buffer.readString(); } else if (opcode == 2) { int count = buffer.readUnsignedByte(); this.subCategories = new int[count]; this.subCategoryHotkeys = new char[count]; for (int i_5 = 0; i_5 < count; i_5++) { this.subCategories[i_5] = buffer.readUnsignedShort(); byte b_6 = (byte) buffer.readByte(); this.subCategoryHotkeys[i_5] = b_6 == 0 ? 0 : Utils.cp1252ToChar(b_6); } } else if (opcode == 3) { int i_4 = buffer.readUnsignedByte(); this.messages = new int[i_4]; this.messageHotkeys = new char[i_4]; for (int i_5 = 0; i_5 < i_4; i_5++) { this.messages[i_5] = buffer.readUnsignedShort(); byte b_6 = (byte) buffer.readByte(); this.messageHotkeys[i_5] = b_6 == 0 ? 0 : Utils.cp1252ToChar(b_6); } } else if (opcode == 4) { return; } } @Override public String toString() { StringBuilder result = new StringBuilder(); String newLine = System.getProperty(""line.separator""); result.append(this.getClass().getName()); result.append("" {""); result.append(newLine); // determine fields declared in this class only (no fields of // superclass) Field[] fields = this.getClass().getDeclaredFields(); // print field names paired with their values for (Field field : fields) { if (Modifier.isStatic(field.getModifiers())) continue; result.append("" ""); try { result.append(field.getType().getCanonicalName() + "" "" + field.getName() + "": ""); result.append(Utils.getFieldValue(this, field)); } catch (Throwable ex) { System.out.println(ex); } result.append(newLine); } result.append(""}""); return result.toString(); } } " " package com.rs.cache.loaders; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashMap; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.lib.io.InputStream; import com.rs.lib.util.Utils; public class QCMesDefinitions { private static final HashMap CACHE = new HashMap<>(); public int id; public String[] message; public int[] responses; public QCValueType[] types; public int[][] configs; public boolean searchable = true; public static void main(String[] args) throws IOException { //Cache.init(); for (int i = 0;i < Cache.STORE.getIndex(IndexType.QC_MESSAGES).getLastFileId(1)+1;i++) { QCMesDefinitions defs = getDefs(i); if (defs == null) continue; // for (String str : defs.message) { // if (str.contains(""My current Slayer assignment is"")) // System.out.println(defs); // } if (defs.types == null) continue; for (QCValueType type : defs.types) { if (type == QCValueType.TOSTRING_SHARED) System.out.println(defs); } } // QCMesDefinitions defs = getDefs(1108); // System.out.println(defs); } public static final QCMesDefinitions getDefs(int id) { QCMesDefinitions defs = CACHE.get(id); if (defs != null) return defs; byte[] data = Cache.STORE.getIndex(IndexType.QC_MESSAGES).getFile(1, id); defs = new QCMesDefinitions(); defs.id = id; if (data != null) defs.readValueLoop(new InputStream(data)); CACHE.put(id, defs); return defs; } private void readValueLoop(InputStream stream) { for (;;) { int opcode = stream.readUnsignedByte(); if (opcode == 0) break; readValues(stream, opcode); } } private void readValues(InputStream buffer, int opcode) { if (opcode == 1) { this.message = Utils.splitByChar(buffer.readString(), '<'); } else if (opcode == 2) { int i_4 = buffer.readUnsignedByte(); this.responses = new int[i_4]; for (int i_5 = 0; i_5 < i_4; i_5++) { this.responses[i_5] = buffer.readUnsignedShort(); } } else if (opcode == 3) { int count = buffer.readUnsignedByte(); this.types = new QCValueType[count]; this.configs = new int[count][]; for (int i = 0; i < count; i++) { int typeId = buffer.readUnsignedShort(); QCValueType type = QCValueType.get(typeId); if (type != null) { this.types[i] = type; this.configs[i] = new int[type.paramCount]; for (int config = 0; config < type.paramCount; config++) { this.configs[i][config] = buffer.readUnsignedShort(); } } } } else if (opcode == 4) { this.searchable = false; } } public enum QCValueType { LISTDIALOG(0, 2, 2, 1), OBJDIALOG(1, 2, 2, 0), COUNTDIALOG(2, 4, 4, 0), STAT_BASE(4, 1, 1, 1), ENUM_STRING(6, 0, 4, 2), ENUM_STRING_CLAN(7, 0, 1, 1), TOSTRING_VARP(8, 0, 4, 1), TOSTRING_VARBIT(9, 0, 4, 1), OBJTRADEDIALOG(10, 2, 2, 0), ENUM_STRING_STATBASE(11, 0, 1, 2), ACC_GETCOUNT_WORLD(12, 0, 1, 0), ACC_GETMEANCOMBATLEVEL(13, 0, 1, 0), TOSTRING_SHARED(14, 0, 4, 1), ACTIVECOMBATLEVEL(15, 0, 1, 0); private static HashMap MAP = new HashMap<>(); static { for (QCValueType type : QCValueType.values()) { MAP.put(type.id, type); } } public int id, clientSize, serverSize, paramCount; private QCValueType(int id, int clientSize, int serverSize, int paramCount) { this.id = id; this.clientSize = clientSize; this.serverSize = serverSize; this.paramCount = paramCount; } public static QCValueType get(int id) { return MAP.get(id); } } public String getFilledQuickchat(InputStream stream) { StringBuilder builder = new StringBuilder(80); if (this.types != null) { for (int i = 0; i < this.types.length; i++) { builder.append(this.message[i]); builder.append(getFilledValue(this.types[i], this.configs[i], stream.readSized(this.types[i].serverSize))); } } builder.append(this.message[this.message.length - 1]); return builder.toString(); } public String getFilledValue(QCValueType type, int[] configs, long data) { if (type == QCValueType.LISTDIALOG) { EnumDefinitions enumDef = EnumDefinitions.getEnum(configs[0]); return enumDef.getStringValue((int) data); } else if (type != QCValueType.OBJDIALOG && type != QCValueType.OBJTRADEDIALOG) { return type != QCValueType.ENUM_STRING && type != QCValueType.ENUM_STRING_CLAN && type != QCValueType.ENUM_STRING_STATBASE ? null : EnumDefinitions.getEnum(configs[0]).getStringValue((int) data); } else { return ItemDefinitions.getDefs((int) data).name; } } @Override public String toString() { StringBuilder result = new StringBuilder(); String newLine = System.getProperty(""line.separator""); result.append(this.getClass().getName()); result.append("" {""); result.append(newLine); // determine fields declared in this class only (no fields of // superclass) Field[] fields = this.getClass().getDeclaredFields(); // print field names paired with their values for (Field field : fields) { if (Modifier.isStatic(field.getModifiers())) continue; result.append("" ""); try { result.append(field.getType().getCanonicalName() + "" "" + field.getName() + "": ""); result.append(Utils.getFieldValue(this, field)); } catch (Throwable ex) { System.out.println(ex); } result.append(newLine); } result.append(""}""); return result.toString(); } } " " package com.rs.cache.loaders; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashMap; import com.rs.cache.ArchiveType; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.lib.io.InputStream; import com.rs.lib.util.Utils; public class SkyboxDefinitions { private static final HashMap CACHE = new HashMap<>(); public int id; int anInt2653 = -1; int anInt2654 = -1; SkyboxRelatedEnum aClass204_2656; int anInt2657; int[] anIntArray2655; public static void main(String[] args) throws IOException { //Cache.init(); for (int i = 0;i < Cache.STORE.getIndex(IndexType.CONFIG).getLastFileId(ArchiveType.SKYBOX.getId())+1;i++) { SkyboxDefinitions defs = getDefs(i); System.out.println(defs); } } public static final SkyboxDefinitions getDefs(int id) { SkyboxDefinitions defs = CACHE.get(id); if (defs != null) return defs; byte[] data = Cache.STORE.getIndex(IndexType.CONFIG).getFile(ArchiveType.SKYBOX.getId(), id); defs = new SkyboxDefinitions(); defs.id = id; if (data != null) defs.readValueLoop(new InputStream(data)); CACHE.put(id, defs); return defs; } private void readValueLoop(InputStream stream) { for (;;) { int opcode = stream.readUnsignedByte(); if (opcode == 0) break; readValues(stream, opcode); } } private void readValues(InputStream buffer, int opcode) { if (opcode == 1) { this.anInt2653 = buffer.readUnsignedShort(); } else if (opcode == 2) { this.anIntArray2655 = new int[buffer.readUnsignedByte()]; for (int i_4 = 0; i_4 < this.anIntArray2655.length; i_4++) { this.anIntArray2655[i_4] = buffer.readUnsignedShort(); } } else if (opcode == 3) { this.anInt2654 = buffer.readUnsignedByte(); } else if (opcode == 4) { this.aClass204_2656 = SkyboxRelatedEnum.values()[buffer.readUnsignedByte()]; } else if (opcode == 5) { this.anInt2657 = buffer.readBigSmart(); } } public enum SkyboxRelatedEnum { TYPE0, TYPE1 } @Override public String toString() { StringBuilder result = new StringBuilder(); String newLine = System.getProperty(""line.separator""); result.append(this.getClass().getName()); result.append("" {""); result.append(newLine); // determine fields declared in this class only (no fields of // superclass) Field[] fields = this.getClass().getDeclaredFields(); // print field names paired with their values for (Field field : fields) { if (Modifier.isStatic(field.getModifiers())) continue; result.append("" ""); try { result.append(field.getType().getCanonicalName() + "" "" + field.getName() + "": ""); result.append(Utils.getFieldValue(this, field)); } catch (Throwable ex) { System.out.println(ex); } result.append(newLine); } result.append(""}""); return result.toString(); } } " " package com.rs.cache.loaders; import java.util.concurrent.ConcurrentHashMap; import com.rs.cache.ArchiveType; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.lib.io.InputStream; public class SpotAnimDefinitions { public boolean aBool6968; public int anInt6969; public int defaultModel; public int anInt6971; public short[] aShortArray6972; public short[] aShortArray6974; public short[] aShortArray6975; public int anInt6976; public int animationId = -1; public int anInt6978; public int anInt6979; public int anInt6980; public int anInt6981; public byte aByte6982; public short[] aShortArray6983; public int id; private static final ConcurrentHashMap SPOT_ANIM_DEFS = new ConcurrentHashMap(); public static final SpotAnimDefinitions getDefs(int spotId) { SpotAnimDefinitions defs = SPOT_ANIM_DEFS.get(spotId); if (defs != null) return defs; byte[] data = Cache.STORE.getIndex(IndexType.SPOT_ANIMS).getFile(ArchiveType.SPOT_ANIMS.archiveId(spotId), ArchiveType.SPOT_ANIMS.fileId(spotId)); defs = new SpotAnimDefinitions(); defs.id = spotId; if (data != null) defs.readValueLoop(new InputStream(data)); SPOT_ANIM_DEFS.put(spotId, defs); return defs; } private void readValueLoop(InputStream stream) { for (;;) { int opcode = stream.readUnsignedByte(); if (opcode == 0) break; readValues(stream, opcode); } } public void readValues(InputStream stream, int i) { if (i == 1) defaultModel = stream.readBigSmart(); else if (2 == i) animationId = stream.readBigSmart(); else if (i == 4) anInt6976 = stream.readUnsignedShort(); else if (5 == i) anInt6971 = stream.readUnsignedShort(); else if (6 == i) anInt6978 = stream.readUnsignedShort(); else if (i == 7) anInt6979 = stream.readUnsignedByte(); else if (i == 8) anInt6981 = stream.readUnsignedByte(); else if (i == 9) { aByte6982 = (byte) 3; anInt6980 = 8224; } else if (i == 10) aBool6968 = true; else if (i == 11) aByte6982 = (byte) 1; else if (12 == i) aByte6982 = (byte) 4; else if (i == 13) aByte6982 = (byte) 5; else if (i == 14) { aByte6982 = (byte) 2; anInt6980 = stream.readUnsignedByte(); } else if (15 == i) { aByte6982 = (byte) 3; anInt6980 = stream.readUnsignedShort(); } else if (16 == i) { aByte6982 = (byte) 3; anInt6980 = stream.readInt(); } else if (40 == i) { int i_3_ = stream.readUnsignedByte(); aShortArray6972 = new short[i_3_]; aShortArray6983 = new short[i_3_]; for (int i_4_ = 0; i_4_ < i_3_; i_4_++) { aShortArray6972[i_4_] = (short) stream.readUnsignedShort(); aShortArray6983[i_4_] = (short) stream.readUnsignedShort(); } } else if (41 == i) { int i_5_ = stream.readUnsignedByte(); aShortArray6974 = new short[i_5_]; aShortArray6975 = new short[i_5_]; for (int i_6_ = 0; i_6_ < i_5_; i_6_++) { aShortArray6974[i_6_] = (short) stream.readUnsignedShort(); aShortArray6975[i_6_] = (short) stream.readUnsignedShort(); } } } public SpotAnimDefinitions() { anInt6976 = 128; anInt6971 = 128; anInt6978 = 0; anInt6979 = 0; anInt6981 = 0; aBool6968 = false; aByte6982 = (byte) 0; anInt6980 = -1; } } " " package com.rs.cache.loaders; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.Arrays; import com.rs.cache.IndexType; import com.rs.cache.Store; import com.rs.lib.io.InputStream; import com.rs.lib.io.OutputStream; public final class SpriteContainer { static final int MAX_RGB = 255; static final int MAX_NODES = 266817; static final int MAX_TREE_DEPTH = 8; // these are precomputed in advance static int SQUARES[]; static int SHIFT[]; static { SQUARES = new int[MAX_RGB + MAX_RGB + 1]; for (int i= -MAX_RGB; i <= MAX_RGB; i++) { SQUARES[i + MAX_RGB] = i * i; } SHIFT = new int[MAX_TREE_DEPTH + 1]; for (int i = 0; i < MAX_TREE_DEPTH + 1; ++i) { SHIFT[i] = 1 << (15 - i); } } private ArrayList images; public int[] pallete; private int[][] pixelsIndexes; private byte[][] alpha; private boolean[] usesAlpha; private int biggestWidth; private int biggestHeight; private int archive; private boolean loaded; public SpriteContainer(BufferedImage... images) { this.images = new ArrayList(); this.images.addAll(Arrays.asList(images)); } public SpriteContainer(Store cache, int archiveId, int fileId) { this(cache, IndexType.SPRITES, archiveId, fileId); } public SpriteContainer(Store cache, IndexType idx, int archiveId, int fileId) { this.archive = archiveId; } public boolean decodeImage(byte[] data) { try { if (data != null) { InputStream stream = new InputStream(data); stream.setOffset(data.length - 2); int count = stream.readUnsignedShort(); this.images = new ArrayList(); this.pixelsIndexes = new int[count][]; this.alpha = new byte[count][]; this.usesAlpha = new boolean[count]; int[] imagesMinX = new int[count]; int[] imagesMinY = new int[count]; int[] imagesWidth = new int[count]; int[] imagesHeight = new int[count]; stream.setOffset(data.length - 7 - count * 8); this.setBiggestWidth(stream.readShort()); this.setBiggestHeight(stream.readShort()); int palleteLength = (stream.readUnsignedByte() & 255) + 1; int index; for (index = 0; index < count; ++index) { imagesMinX[index] = stream.readUnsignedShort(); } for (index = 0; index < count; ++index) { imagesMinY[index] = stream.readUnsignedShort(); } for (index = 0; index < count; ++index) { imagesWidth[index] = stream.readUnsignedShort(); } for (index = 0; index < count; ++index) { imagesHeight[index] = stream.readUnsignedShort(); } stream.setOffset(data.length - 7 - count * 8 - (palleteLength - 1) * 3); this.pallete = new int[palleteLength]; for (index = 1; index < palleteLength; ++index) { this.pallete[index] = stream.read24BitInt(); if (this.pallete[index] == 0) { this.pallete[index] = 1; } } stream.setOffset(0); for (index = 0; index < count; ++index) { int pixelsIndexesLength = imagesWidth[index] * imagesHeight[index]; this.pixelsIndexes[index] = new int[pixelsIndexesLength]; this.alpha[index] = new byte[pixelsIndexesLength]; int maskData = stream.readUnsignedByte(); int i_31_; if ((maskData & 2) == 0) { int var201; if ((maskData & 1) == 0) { for (var201 = 0; var201 < pixelsIndexesLength; ++var201) { this.pixelsIndexes[index][var201] = (byte) stream.readByte(); } } else { for (var201 = 0; var201 < imagesWidth[index]; ++var201) { for (i_31_ = 0; i_31_ < imagesHeight[index]; ++i_31_) { this.pixelsIndexes[index][var201 + i_31_ * imagesWidth[index]] = (byte) stream .readByte(); } } } } else { this.usesAlpha[index] = true; boolean var20 = false; if ((maskData & 1) == 0) { for (i_31_ = 0; i_31_ < pixelsIndexesLength; ++i_31_) { this.pixelsIndexes[index][i_31_] = (byte) stream.readByte(); } for (i_31_ = 0; i_31_ < pixelsIndexesLength; ++i_31_) { byte var21 = this.alpha[index][i_31_] = (byte) stream.readByte(); var20 |= var21 != -1; } } else { int var211; for (i_31_ = 0; i_31_ < imagesWidth[index]; ++i_31_) { for (var211 = 0; var211 < imagesHeight[index]; ++var211) { this.pixelsIndexes[index][i_31_ + var211 * imagesWidth[index]] = stream.readByte(); } } for (i_31_ = 0; i_31_ < imagesWidth[index]; ++i_31_) { for (var211 = 0; var211 < imagesHeight[index]; ++var211) { byte i_33_ = this.alpha[index][i_31_ + var211 * imagesWidth[index]] = (byte) stream .readByte(); var20 |= i_33_ != -1; } } } if (!var20) { this.alpha[index] = null; } } this.images.add(getBufferedImage(imagesWidth[index], imagesHeight[index], this.pixelsIndexes[index], this.alpha[index], this.usesAlpha[index])); } } this.loaded = true; return true; } catch (Throwable e) { e.printStackTrace(); } return false; } public boolean decodeImage(Store cache, IndexType idx, int archiveId, int fileId) { return decodeImage(cache.getIndex(idx).getFile(archiveId, fileId)); } public BufferedImage getBufferedImage(int width, int height, int[] pixelsIndexes, byte[] extraPixels, boolean useExtraPixels) { if (width > 0 && height > 0) { BufferedImage image = new BufferedImage(width, height, 6); int[] rgbArray = new int[width * height]; int i = 0; int i_43_ = 0; int i_46_; int i_47_; if (useExtraPixels && extraPixels != null) { for (i_46_ = 0; i_46_ < height; ++i_46_) { for (i_47_ = 0; i_47_ < width; ++i_47_) { rgbArray[i_43_++] = extraPixels[i] << 24 | this.pallete[pixelsIndexes[i] & 255]; ++i; } } } else { for (i_46_ = 0; i_46_ < height; ++i_46_) { for (i_47_ = 0; i_47_ < width; ++i_47_) { int i_48_ = this.pallete[pixelsIndexes[i++] & 255]; rgbArray[i_43_++] = i_48_ != 0 ? -16777216 | i_48_ : 0; } } } image.setRGB(0, 0, width, height, rgbArray, 0, width); image.flush(); return image; } else { return null; } } public byte[] encode() { this.biggestHeight = 0; this.biggestWidth = 0; if (this.pallete == null) { this.generatePallete(); } OutputStream stream = new OutputStream(); int container; int len$; int i$; for (container = 0; container < this.images.size(); ++container) { len$ = 0; if (this.usesAlpha[container]) { len$ |= 2; } stream.writeByte(len$); for (i$ = 0; i$ < this.pixelsIndexes[container].length; ++i$) { stream.writeByte(this.pixelsIndexes[container][i$]); } if (this.usesAlpha[container]) { for (i$ = 0; i$ < this.alpha[container].length; ++i$) { stream.writeByte(this.alpha[container][i$]); } } } for (container = 0; container < this.pallete.length; ++container) { stream.write24BitInt(this.pallete[container]); } if (this.biggestWidth == 0 && this.biggestHeight == 0) { BufferedImage[] var7 = this.images.toArray(new BufferedImage[this.images.size()]); len$ = var7.length; for (i$ = 0; i$ < len$; ++i$) { BufferedImage image = var7[i$]; if (image.getWidth() > this.biggestWidth) { this.biggestWidth = image.getWidth(); } if (image.getHeight() > this.biggestHeight) { this.biggestHeight = image.getHeight(); } } } stream.writeShort(this.biggestWidth); stream.writeShort(this.biggestHeight); stream.writeByte(this.pallete.length - 1); for (container = 0; container < this.images.size(); ++container) { stream.writeShort(this.images.get(container).getMinX()); } for (container = 0; container < this.images.size(); ++container) { stream.writeShort(this.images.get(container).getMinY()); } for (container = 0; container < this.images.size(); ++container) { stream.writeShort(this.images.get(container).getWidth()); } for (container = 0; container < this.images.size(); ++container) { stream.writeShort(this.images.get(container).getHeight()); } stream.writeShort(this.images.size()); return stream.toByteArray(); } public int getPalleteIndex(int rgb) { if (this.pallete == null) { this.pallete = new int[1]; } for (int pallete = 0; pallete < this.pallete.length; ++pallete) { if (this.pallete[pallete] == rgb) { return pallete; } } if (this.pallete.length == 256) { System.out.println(""Pallete to big, please reduce images quality.""); return 0; } else { int[] newPallete = new int[this.pallete.length + 1]; System.arraycopy(this.pallete, 0, newPallete, 0, this.pallete.length); newPallete[this.pallete.length] = rgb; this.pallete = newPallete; return this.pallete.length - 1; } } public int addImage(BufferedImage image) { this.images.add(image); this.pallete = null; this.pixelsIndexes = null; this.alpha = null; this.usesAlpha = null; return this.images.size(); } public int removeImage(int index) { this.images.remove(index); this.pallete = null; this.pixelsIndexes = null; this.alpha = null; this.usesAlpha = null; return this.images.size(); } public void replaceImage(BufferedImage image, int index) { this.images.remove(index); this.images.add(index, image); this.pallete = null; this.pixelsIndexes = null; this.alpha = null; this.usesAlpha = null; } public void generatePallete() { this.pixelsIndexes = new int[this.images.size()][]; this.alpha = new byte[this.images.size()][]; this.usesAlpha = new boolean[this.images.size()]; for (int index = 0; index < this.images.size(); ++index) { BufferedImage image = this.images.get(index); int[] rgbArray = new int[image.getWidth() * image.getHeight()]; image.getRGB(0, 0, image.getWidth(), image.getHeight(), rgbArray, 0, image.getWidth()); this.pixelsIndexes[index] = new int[image.getWidth() * image.getHeight()]; this.alpha[index] = new byte[image.getWidth() * image.getHeight()]; for (int pixel = 0; pixel < this.pixelsIndexes[index].length; ++pixel) { int rgb = rgbArray[pixel]; int medintrgb = this.convertToMediumInt(rgb); int i = this.getPalleteIndex(medintrgb); this.pixelsIndexes[index][pixel] = i; if (rgb >> 24 != 0) { this.alpha[index][pixel] = (byte) (rgb >> 24); this.usesAlpha[index] = true; } } } } public int convertToMediumInt(int rgb) { OutputStream out = new OutputStream(4); out.writeInt(rgb); InputStream stream = new InputStream(out.getBuffer()); stream.setOffset(1); rgb = stream.read24BitInt(); return rgb; } public ArrayList getImages() { return images; } public int getBiggestWidth() { return this.biggestWidth; } public void setBiggestWidth(int biggestWidth) { this.biggestWidth = biggestWidth; } public int getBiggestHeight() { return this.biggestHeight; } public void setBiggestHeight(int biggestHeight) { this.biggestHeight = biggestHeight; } public boolean isLoaded() { return loaded; } @Override public String toString() { return ""Sprite - "" + archive; } } " " package com.rs.cache.loaders; import java.awt.Color; import java.awt.image.BufferedImage; import java.awt.image.RGBImageFilter; import java.util.ArrayList; import java.util.Arrays; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.cache.Store; import com.rs.lib.io.InputStream; import com.rs.lib.io.OutputStream; public final class SpriteDefinitions { private BufferedImage[] images; private int pallete[]; private int pixelsIndexes[][]; private byte alpha[][]; private boolean[] usesAlpha; private int biggestWidth; private int biggestHeight; public SpriteDefinitions(BufferedImage... images) { this.images = images; } public static SpriteDefinitions getSprite(int spriteId, int fileId) { return new SpriteDefinitions(Cache.STORE, spriteId, fileId); } public SpriteDefinitions(Store cache, int archiveId, int fileId) { decodeArchive(cache, archiveId, fileId); } public void decodeArchive(Store cache, int archiveId, int fileId) { byte[] data = cache.getIndex(IndexType.SPRITES).getFile(archiveId, fileId); if (data == null) return; InputStream stream = new InputStream(data); stream.setOffset(data.length - 2); int count = stream.readUnsignedShort(); images = new BufferedImage[count]; pixelsIndexes = new int[images.length][]; alpha = new byte[images.length][]; usesAlpha = new boolean[images.length]; int[] imagesMinX = new int[images.length]; int[] imagesMinY = new int[images.length]; int[] imagesWidth = new int[images.length]; int[] imagesHeight = new int[images.length]; stream.setOffset(data.length - 7 - images.length * 8); setBiggestWidth(stream.readShort()); // biggestWidth setBiggestHeight(stream.readShort()); // biggestHeight int palleteLength = (stream.readUnsignedByte() & 0xff) + 1; // 1 + up to // 255. for (int index = 0; index < images.length; index++) imagesMinX[index] = stream.readUnsignedShort(); for (int index = 0; index < images.length; index++) imagesMinY[index] = stream.readUnsignedShort(); for (int index = 0; index < images.length; index++) imagesWidth[index] = stream.readUnsignedShort(); for (int index = 0; index < images.length; index++) imagesHeight[index] = stream.readUnsignedShort(); stream.setOffset(data.length - 7 - images.length * 8 - (palleteLength - 1) * 3); pallete = new int[palleteLength]; for (int index = 1; index < palleteLength; index++) { pallete[index] = stream.read24BitInt(); if (pallete[index] == 0) pallete[index] = 1; } stream.setOffset(0); for (int i_20_ = 0; i_20_ < images.length; i_20_++) { int pixelsIndexesLength = imagesWidth[i_20_] * imagesHeight[i_20_]; pixelsIndexes[i_20_] = new int[pixelsIndexesLength]; alpha[i_20_] = new byte[pixelsIndexesLength]; int maskData = stream.readUnsignedByte(); if ((maskData & 0x2) == 0) { if ((maskData & 0x1) == 0) { for (int index = 0; index < pixelsIndexesLength; index++) { pixelsIndexes[i_20_][index] = (byte) stream.readByte(); } } else { for (int i_24_ = 0; i_24_ < imagesWidth[i_20_]; i_24_++) { for (int i_25_ = 0; i_25_ < imagesHeight[i_20_]; i_25_++) { pixelsIndexes[i_20_][i_24_ + i_25_ * imagesWidth[i_20_]] = (byte) stream.readByte(); } } } } else { usesAlpha[i_20_] = true; boolean bool = false; if ((maskData & 0x1) == 0) { for (int index = 0; index < pixelsIndexesLength; index++) { pixelsIndexes[i_20_][index] = (byte) stream.readByte(); } for (int i_27_ = 0; i_27_ < pixelsIndexesLength; i_27_++) { byte i_28_ = (alpha[i_20_][i_27_] = (byte) stream.readByte()); bool = bool | i_28_ != -1; } } else { for (int i_29_ = 0; i_29_ < imagesWidth[i_20_]; i_29_++) { for (int i_30_ = 0; i_30_ < imagesHeight[i_20_]; i_30_++) { pixelsIndexes[i_20_][i_29_ + i_30_ * imagesWidth[i_20_]] = stream.readByte(); } } for (int i_31_ = 0; i_31_ < imagesWidth[i_20_]; i_31_++) { for (int i_32_ = 0; i_32_ < imagesHeight[i_20_]; i_32_++) { byte i_33_ = (alpha[i_20_][i_31_ + i_32_ * imagesWidth[i_20_]] = (byte) stream.readByte()); bool = bool | i_33_ != -1; } } } if (!bool) alpha[i_20_] = null; } images[i_20_] = getBufferedImage(imagesWidth[i_20_], imagesHeight[i_20_], pixelsIndexes[i_20_], alpha[i_20_], usesAlpha[i_20_]); } } public BufferedImage getBufferedImage(int width, int height, int[] pixelsIndexes, byte[] extraPixels, boolean useExtraPixels) { if (width <= 0 || height <= 0) return null; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR); int[] rgbArray = new int[width * height]; int i = 0; int i_43_ = 0; if (useExtraPixels && extraPixels != null) { for (int i_44_ = 0; i_44_ < height; i_44_++) { for (int i_45_ = 0; i_45_ < width; i_45_++) { rgbArray[i_43_++] = (extraPixels[i] << 24 | (pallete[pixelsIndexes[i] & 0xff])); i++; } } } else { for (int i_46_ = 0; i_46_ < height; i_46_++) { for (int i_47_ = 0; i_47_ < width; i_47_++) { int i_48_ = pallete[pixelsIndexes[i++] & 0xff]; rgbArray[i_43_++] = i_48_ != 0 ? ~0xffffff | i_48_ : 0; } } } image.setRGB(0, 0, width, height, rgbArray, 0, width); image.flush(); return image; } public byte[] encodeFile() { if (pallete == null) // if not generated yet generatePallete(); OutputStream stream = new OutputStream(); // sets pallete indexes and int size bytes for (int imageId = 0; imageId < images.length; imageId++) { int pixelsMask = 0; if (usesAlpha[imageId]) pixelsMask |= 0x2; // pixelsMask |= 0x1; //sets read all rgbarray indexes 1by1 stream.writeByte(pixelsMask); for (int index = 0; index < pixelsIndexes[imageId].length; index++) stream.writeByte(pixelsIndexes[imageId][index]); if (usesAlpha[imageId]) for (int index = 0; index < alpha[imageId].length; index++) stream.writeByte(alpha[imageId][index]); } // sets up to 255colors pallete, index0 is black for (int index = 1; index < pallete.length; index++) stream.write24BitInt(pallete[index]); // extra inform if (biggestWidth == 0 && biggestHeight == 0) { for (BufferedImage image : images) { if (image.getWidth() > biggestWidth) biggestWidth = image.getWidth(); if (image.getHeight() > biggestHeight) biggestHeight = image.getHeight(); } } stream.writeShort(biggestWidth); // probably used for textures stream.writeShort(biggestHeight);// probably used for textures stream.writeByte(pallete.length - 1); // sets pallete size, -1 cuz of // black index for (int imageId = 0; imageId < images.length; imageId++) stream.writeShort(images[imageId].getMinX()); for (int imageId = 0; imageId < images.length; imageId++) stream.writeShort(images[imageId].getMinY()); for (int imageId = 0; imageId < images.length; imageId++) stream.writeShort(images[imageId].getWidth()); for (int imageId = 0; imageId < images.length; imageId++) stream.writeShort(images[imageId].getHeight()); stream.writeShort(images.length); // amt of images // generates fixed byte data array byte[] container = new byte[stream.getOffset()]; stream.setOffset(0); stream.getBytes(container, 0, container.length); return container; } public int getPalleteIndex(int rgb) { if (pallete == null) // index 0 is 0 pallete = new int[] { 0 }; for (int index = 0; index < pallete.length; index++) { if (pallete[index] == rgb) return index; } if (pallete.length == 256) { System.out.println(""Pallete to big, please reduce images quality.""); return 0; } int[] newpallete = new int[pallete.length + 1]; System.arraycopy(pallete, 0, newpallete, 0, pallete.length); newpallete[pallete.length] = rgb; pallete = newpallete; return pallete.length - 1; } public int addImage(BufferedImage image) { BufferedImage[] newImages = Arrays.copyOf(images, images.length + 1); newImages[images.length] = image; images = newImages; pallete = null; pixelsIndexes = null; alpha = null; usesAlpha = null; return images.length - 1; } public void replaceImage(BufferedImage image, int index) { images[index] = image; pallete = null; pixelsIndexes = null; alpha = null; usesAlpha = null; } public void generatePallete() { pixelsIndexes = new int[images.length][]; alpha = new byte[images.length][]; usesAlpha = new boolean[images.length]; for (int index = 0; index < images.length; index++) { BufferedImage image = filter(images[index]); int[] rgbArray = new int[image.getWidth() * image.getHeight()]; image.getRGB(0, 0, image.getWidth(), image.getHeight(), rgbArray, 0, image.getWidth()); pixelsIndexes[index] = new int[image.getWidth() * image.getHeight()]; alpha[index] = new byte[image.getWidth() * image.getHeight()]; for (int pixel = 0; pixel < pixelsIndexes[index].length; pixel++) { int rgb = rgbArray[pixel]; Color c = new Color(rgb, true); int medintrgb = new Color(c.getRed(), c.getGreen(), c.getBlue()).getRGB(); int i = getPalleteIndex(medintrgb); pixelsIndexes[index][pixel] = i; if (c.getAlpha() != 0) { alpha[index][pixel] = (byte) c.getAlpha(); usesAlpha[index] = true; } } } } public BufferedImage[] getImages() { return images; } public int getBiggestWidth() { return biggestWidth; } public void setBiggestWidth(int biggestWidth) { this.biggestWidth = biggestWidth; } public int getBiggestHeight() { return biggestHeight; } public void setBiggestHeight(int biggestHeight) { this.biggestHeight = biggestHeight; } public static BufferedImage filter(BufferedImage image) { DetailFilter filter = new DetailFilter(); while (!filter.done()) { for (int x = 0; x < image.getWidth(); x++) { for (int y = 0; y < image.getHeight(); y++) { int rgb = filter.filterRGB(x, y, image.getRGB(x, y)); image.setRGB(x, y, rgb); } } } return image; } private static class DetailFilter extends RGBImageFilter { public static int START_DIFF = 1; private int diffB, diffG, diffR; private ArrayList colours; public boolean done() { if (colours == null) { colours = new ArrayList(); diffB = diffG = diffR = START_DIFF; return false; } int increase = colours.size() > 1000 ? 5 : 1; if (increase == 0) increase = 1; // System.out.println(diffR+"", ""+diffG+"", ""+diffB+"", // ""+colours.size()+"", ""+increase); if (colours.size() <= 256) return true; colours.clear(); if (diffR <= diffB) diffR += increase; else if (diffG <= diffB) diffG += increase; else if (diffB <= diffR) diffB += increase; return false; } @Override public int filterRGB(int x, int y, int rgb) { Color c = new Color(rgb, true); rgb = c.getRGB(); int blue = (int) (c.getBlue() / diffB * diffB); int green = (int) (c.getGreen() / diffG * diffG); int red = (int) (c.getRed() / diffR * diffR); int alpha = c.getAlpha(); rgb = new Color(red, green, blue).getRGB(); if (!colours.contains(rgb)) { // System.out.println(colours.size() +"", ""+rgb+"", ""+red+"", // ""+green+"", ""+blue+"", ""+alpha); colours.add(rgb); } rgb = new Color(red, green, blue, alpha).getRGB(); return rgb; } } } " " package com.rs.cache.loaders; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.concurrent.ConcurrentHashMap; import com.rs.cache.ArchiveType; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.cache.loaders.cs2.CS2ParamDefs; import com.rs.cache.loaders.cs2.CS2Type; import com.rs.lib.Constants; import com.rs.lib.game.WorldTile; import com.rs.lib.io.InputStream; public final class StructDefinitions { private HashMap values; private static final ConcurrentHashMap maps = new ConcurrentHashMap(); public static void main(String[] args) throws IOException { //Cache.init(); File file = new File(""structs.txt""); if (file.exists()) file.delete(); else file.createNewFile(); BufferedWriter writer = new BufferedWriter(new FileWriter(file)); writer.append(""//Version = 727\n""); writer.flush(); for (int i = 0; i < 100000; i++) { StructDefinitions map = getStruct(i); if (map == null || map.getValues() == null) continue; writer.append(i + "" - "" + map); writer.newLine(); writer.flush(); System.out.println(i + "" - "" + map.getValues().toString()); } writer.close(); } public static final StructDefinitions getStruct(int structId) { StructDefinitions script = maps.get(structId); if (script != null) return script; byte[] data = Cache.STORE.getIndex(IndexType.CONFIG).getFile(ArchiveType.STRUCTS.getId(), structId); script = new StructDefinitions(); if (data != null) script.readValueLoop(new InputStream(data)); maps.put(structId, script); return script; } public HashMap getValues() { return values; } public Object getValue(long key) { if (values == null) return null; return values.get(key); } public long getKeyForValue(Object value) { for (Long key : values.keySet()) { if (values.get(key).equals(value)) return key; } return -1; } public int getSize() { if (values == null) return 0; return values.size(); } public int getIntValue(long key) { if (values == null) return 0; Object value = values.get(key); if (value == null || !(value instanceof Integer)) return 0; return (Integer) value; } public int getIntValue(long key, int defaultVal) { if (values == null) return defaultVal; Object value = values.get(key); if (value == null || !(value instanceof Integer)) return defaultVal; return (Integer) value; } public String getStringValue(long key) { if (values == null) return """"; Object value = values.get(key); if (value == null || !(value instanceof String)) return """"; return (String) value; } private void readValueLoop(InputStream stream) { for (;;) { int opcode = stream.readUnsignedByte(); if (opcode == 0) break; readValues(stream, opcode); } } private void readValues(InputStream stream, int opcode) { if (opcode == 249) { int length = stream.readUnsignedByte(); if (values == null) values = new HashMap(length); for (int index = 0; index < length; index++) { boolean stringInstance = stream.readUnsignedByte() == 1; int key = stream.read24BitInt(); Object value = stringInstance ? stream.readString() : stream.readInt(); values.put((long) key, value); } } } public Object valToType(long id, Object o) { if (CS2ParamDefs.getParams((int) id).type == CS2Type.ICOMPONENT) { if (o instanceof String) return o; long interfaceId = ((int) o) >> 16; long componentId = ((int) o) - (interfaceId << 16); return ""IComponent(""+interfaceId+"", ""+componentId+"")""; } else if (CS2ParamDefs.getParams((int) id).type == CS2Type.LOCATION) { if (o instanceof String) return o; return WorldTile.of(((int) o)); } else if (CS2ParamDefs.getParams((int) id).type == CS2Type.SKILL) { if (o instanceof String) return o; int idx = (int) o; if (idx >= Constants.SKILL_NAME.length) return o; return idx+""(""+Constants.SKILL_NAME[((int) o)]+"")""; } else if (CS2ParamDefs.getParams((int) id).type == CS2Type.ITEM) { if (o instanceof String) return o; return ((int) o)+"" (""+ItemDefinitions.getDefs(((int) o)).getName()+"")""; } else if (CS2ParamDefs.getParams((int) id).type == CS2Type.NPCDEF) { if (o instanceof String) return o; return ((int) o)+"" (""+NPCDefinitions.getDefs(((int) o)).getName()+"")""; } else if (CS2ParamDefs.getParams((int) id).type == CS2Type.STRUCT) { return o + "": "" + StructDefinitions.getStruct((int) o).getValues(); } return o; } @Override public String toString() { if (getValues() == null) return ""null""; StringBuilder s = new StringBuilder(); s.append(""{""); for (Long l : getValues().keySet()) { s.append(""\n\t""); s.append(l + "" (""+CS2ParamDefs.getParams(l.intValue()).type+"")""); s.append("" = ""); s.append(valToType(l, getValues().get(l)) + "", ""); } s.append(""\n}""); return s.toString(); } private StructDefinitions() { } } " " package com.rs.cache.loaders; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashMap; import com.rs.cache.ArchiveType; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.lib.io.InputStream; import com.rs.lib.util.Utils; public class SunDefinitions { private static final HashMap CACHE = new HashMap<>(); public int id; public int anInt396 = 8; public boolean aBool400; public int anInt401; public int anInt397; public int anInt399; public int anInt395; public int anInt402; public int anInt404 = 16777215; public int anInt403; public int anInt398; public int anInt405; public static final SunDefinitions getDefs(int id) { SunDefinitions defs = CACHE.get(id); if (defs != null) return defs; byte[] data = Cache.STORE.getIndex(IndexType.CONFIG).getFile(ArchiveType.SUN.getId(), id); defs = new SunDefinitions(); defs.id = id; if (data != null) defs.readValueLoop(new InputStream(data)); CACHE.put(id, defs); return defs; } private void readValueLoop(InputStream stream) { for (;;) { int opcode = stream.readUnsignedByte(); if (opcode == 0) break; readValues(stream, opcode); } } private void readValues(InputStream stream, int opcode) { if (opcode == 1) { this.anInt396 = stream.readUnsignedShort(); } else if (opcode == 2) { this.aBool400 = true; } else if (opcode == 3) { this.anInt401 = stream.readShort(); this.anInt397 = stream.readShort(); this.anInt399 = stream.readShort(); } else if (opcode == 4) { this.anInt395 = stream.readUnsignedByte(); } else if (opcode == 5) { this.anInt402 = stream.readBigSmart(); } else if (opcode == 6) { this.anInt404 = stream.read24BitUnsignedInteger(); } else if (opcode == 7) { this.anInt403 = stream.readShort(); this.anInt398 = stream.readShort(); this.anInt405 = stream.readShort(); } } @Override public String toString() { StringBuilder result = new StringBuilder(); String newLine = System.getProperty(""line.separator""); result.append(this.getClass().getName()); result.append("" {""); result.append(newLine); // determine fields declared in this class only (no fields of // superclass) Field[] fields = this.getClass().getDeclaredFields(); // print field names paired with their values for (Field field : fields) { if (Modifier.isStatic(field.getModifiers())) continue; result.append("" ""); try { result.append(field.getType().getCanonicalName() + "" "" + field.getName() + "": ""); result.append(Utils.getFieldValue(this, field)); } catch (Throwable ex) { System.out.println(ex); } result.append(newLine); } result.append(""}""); return result.toString(); } } " " package com.rs.cache.loaders; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashMap; import java.lang.SuppressWarnings; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.lib.io.InputStream; import com.rs.lib.io.OutputStream; import com.rs.lib.util.Utils; public class TextureDefinitions { private static HashMap TEXTURE_DEFINITIONS = new HashMap<>(); public int id; public boolean isGroundMesh; public boolean isHalfSize; public boolean skipTriangles; public int brightness; public int shadowFactor; public int effectId; public int effectParam1; public int color; public int textureSpeedU; public int textureSpeedV; public boolean aBoolean527; public boolean isBrickTile; public int useMipmaps; public boolean repeatS; public boolean repeatT; public boolean hdr; public int combineMode; public int effectParam2; public int blendType; private TextureDefinitions(int id) { this.id = id; } public static void main(String[] args) throws IOException { //Cache.init(); parseTextureDefs(); for (TextureDefinitions defs : TEXTURE_DEFINITIONS.values()) { System.out.println(defs); } } public static boolean exists(int id) { if (TEXTURE_DEFINITIONS.isEmpty()) parseTextureDefs(); return TEXTURE_DEFINITIONS.containsKey(id); } public static void parseTextureDefs() { TEXTURE_DEFINITIONS.clear(); byte[] data = Cache.STORE.getIndex(IndexType.TEXTURES).getFile(0, 0); InputStream stream = new InputStream(data); int len = stream.readUnsignedShort(); for (int i = 0;i < len;i++) { if (stream.readUnsignedByte() == 1) TEXTURE_DEFINITIONS.put(i, new TextureDefinitions(i)); } for (int i = 0;i < len;i++) { if (getDefinitions(i) != null) getDefinitions(i).isGroundMesh = stream.readUnsignedByte() == 0; } for (int i = 0;i < len;i++) { if (getDefinitions(i) != null) getDefinitions(i).isHalfSize = stream.readUnsignedByte() == 1; } for (int i = 0;i < len;i++) { if (getDefinitions(i) != null) getDefinitions(i).skipTriangles = stream.readUnsignedByte() == 1; } for (int i = 0;i < len;i++) { if (getDefinitions(i) != null) getDefinitions(i).brightness = stream.readByte(); } for (int i = 0;i < len;i++) { if (getDefinitions(i) != null) getDefinitions(i).shadowFactor = stream.readByte(); } for (int i = 0;i < len;i++) { if (getDefinitions(i) != null) getDefinitions(i).effectId = stream.readByte(); } for (int i = 0;i < len;i++) { if (getDefinitions(i) != null) getDefinitions(i).effectParam1 = stream.readByte(); } for (int i = 0;i < len;i++) { if (getDefinitions(i) != null) getDefinitions(i).color = stream.readUnsignedShort(); } for (int i = 0;i < len;i++) { if (getDefinitions(i) != null) getDefinitions(i).textureSpeedU = stream.readByte(); } for (int i = 0;i < len;i++) { if (getDefinitions(i) != null) getDefinitions(i).textureSpeedV = stream.readByte(); } for (int i = 0;i < len;i++) { if (getDefinitions(i) != null) getDefinitions(i).aBoolean527 = stream.readUnsignedByte() == 1; } for (int i = 0;i < len;i++) { if (getDefinitions(i) != null) getDefinitions(i).isBrickTile = stream.readUnsignedByte() == 1; } for (int i = 0;i < len;i++) { if (getDefinitions(i) != null) getDefinitions(i).useMipmaps = stream.readByte(); } for (int i = 0;i < len;i++) { if (getDefinitions(i) != null) getDefinitions(i).repeatS = stream.readUnsignedByte() == 1; } for (int i = 0;i < len;i++) { if (getDefinitions(i) != null) getDefinitions(i).repeatT = stream.readUnsignedByte() == 1; } for (int i = 0;i < len;i++) { if (getDefinitions(i) != null) getDefinitions(i).hdr = stream.readUnsignedByte() == 1; } for (int i = 0;i < len;i++) { if (getDefinitions(i) != null) getDefinitions(i).combineMode = stream.readUnsignedByte(); } for (int i = 0;i < len;i++) { if (getDefinitions(i) != null) getDefinitions(i).effectParam2 = stream.readInt(); } for (int i = 0;i < len;i++) { if (getDefinitions(i) != null) getDefinitions(i).blendType = stream.readUnsignedByte(); } } public static byte[] encode() { OutputStream stream = new OutputStream(); int lastId = getHighestId()+1; stream.writeShort(lastId); for (int i = 0; i < lastId; i++) { stream.writeBoolean(getDefinitions(i) != null); } for (int i = 0; i < lastId; i++) { if (getDefinitions(i) != null) stream.writeBoolean(!getDefinitions(i).isGroundMesh); } for (int i = 0; i < lastId; i++) { if (getDefinitions(i) != null) stream.writeBoolean(getDefinitions(i).isHalfSize); } for (int i = 0; i < lastId; i++) { if (getDefinitions(i) != null) stream.writeBoolean(getDefinitions(i).skipTriangles); } for (int i = 0; i < lastId; i++) { if (getDefinitions(i) != null) stream.writeByte(getDefinitions(i).brightness); } for (int i = 0; i < lastId; i++) { if (getDefinitions(i) != null) stream.writeByte(getDefinitions(i).shadowFactor); } for (int i = 0; i < lastId; i++) { if (getDefinitions(i) != null) stream.writeByte(getDefinitions(i).effectId); } for (int i = 0; i < lastId; i++) { if (getDefinitions(i) != null) stream.writeByte(getDefinitions(i).effectParam1); } for (int i = 0; i < lastId; i++) { if (getDefinitions(i) != null) stream.writeShort(getDefinitions(i).color); } for (int i = 0; i < lastId; i++) { if (getDefinitions(i) != null) stream.writeByte(getDefinitions(i).textureSpeedU); } for (int i = 0; i < lastId; i++) { if (getDefinitions(i) != null) stream.writeByte(getDefinitions(i).textureSpeedV); } for (int i = 0; i < lastId; i++) { if (getDefinitions(i) != null) stream.writeBoolean(getDefinitions(i).aBoolean527); } for (int i = 0; i < lastId; i++) { if (getDefinitions(i) != null) stream.writeBoolean(getDefinitions(i).isBrickTile); } for (int i = 0; i < lastId; i++) { if (getDefinitions(i) != null) stream.writeByte(getDefinitions(i).useMipmaps); } for (int i = 0; i < lastId; i++) { if (getDefinitions(i) != null) stream.writeBoolean(getDefinitions(i).repeatS); } for (int i = 0; i < lastId; i++) { if (getDefinitions(i) != null) stream.writeBoolean(getDefinitions(i).repeatT); } for (int i = 0; i < lastId; i++) { if (getDefinitions(i) != null) stream.writeBoolean(getDefinitions(i).hdr); } for (int i = 0; i < lastId; i++) { if (getDefinitions(i) != null) stream.writeByte(getDefinitions(i).combineMode); } for (int i = 0; i < lastId; i++) { if (getDefinitions(i) != null) stream.writeInt(getDefinitions(i).effectParam2); } for (int i = 0; i < lastId; i++) { if (getDefinitions(i) != null) stream.writeByte(getDefinitions(i).blendType); } return stream.toByteArray(); } public static int getHighestId() { if (TEXTURE_DEFINITIONS.isEmpty()) parseTextureDefs(); int highest = 0; for (TextureDefinitions i : TEXTURE_DEFINITIONS.values()) if (i.id > highest) highest = i.id; return highest; } public static TextureDefinitions getDefinitions(int id) { if (TEXTURE_DEFINITIONS.isEmpty()) parseTextureDefs(); return TEXTURE_DEFINITIONS.get(id); } public static TextureDefinitions getRS3(int id, byte[] stream) { if (TEXTURE_DEFINITIONS.isEmpty()) parseTextureDefs(); TextureDefinitions defs = new TextureDefinitions(id); defs.decodeRS3(new InputStream(stream)); return defs; } public static void addDef(TextureDefinitions defs) { if (TEXTURE_DEFINITIONS.isEmpty()) parseTextureDefs(); TEXTURE_DEFINITIONS.put(defs.id, defs); } public static boolean encodeAndReplace() { if (TEXTURE_DEFINITIONS.isEmpty()) parseTextureDefs(); return Cache.STORE.getIndex(IndexType.TEXTURES).putFile(0, 0, encode()); } @SuppressWarnings(""unused"") private void decodeRS3(InputStream buffer) { buffer.readUnsignedByte(); int flag = buffer.readInt(); if ((flag & 0x1) != 0) { buffer.readUnsignedShort(); buffer.readUnsignedByte(); } if ((flag & 0x1000) != 0) { for (int i = 0;i < 6;i++) { buffer.readShort(); buffer.readUnsignedByte(); } } if ((flag & 0x2) != 0) { buffer.readUnsignedShort(); buffer.readUnsignedByte(); } if ((flag & 0x4) != 0) { buffer.readUnsignedShort(); buffer.readUnsignedByte(); } if ((flag & 0x8) != 0) { buffer.readUnsignedShort(); } if ((flag & 0x10) != 0) { buffer.readUnsignedShort(); buffer.readUnsignedByte(); } if ((flag & 0x20) != 0) { buffer.readUnsignedShort(); buffer.readUnsignedByte(); } if ((flag & 0x40) != 0) { buffer.readUnsignedShort(); buffer.readUnsignedByte(); } if ((flag & 0x80) != 0) { buffer.readUnsignedShort(); buffer.readUnsignedByte(); } if ((flag & 0x100) != 0) { buffer.readUnsignedShort(); buffer.readUnsignedByte(); } if ((flag & 0x200) != 0) { buffer.readUnsignedShort(); buffer.readUnsignedByte(); } if ((flag & 0x400) != 0) { buffer.readUnsignedShort(); buffer.readUnsignedByte(); } if ((flag & 0x800) != 0) { buffer.readUnsignedShort(); buffer.readUnsignedByte(); } int wrappingFlag = (byte) buffer.readUnsignedByte(); repeatS = (byte) (wrappingFlag & 0x7) != 0; repeatT = (byte) (wrappingFlag >> 3 & 0x7) != 0; int settings = buffer.readInt(); if ((settings & 0x10) != 0) { buffer.readFloat(); buffer.readFloat(); } if (0 != (settings & 0x20)) buffer.readInt(); if ((settings & 0x40) != 0) buffer.readInt(); if ((settings & 0x80) != 0) buffer.readInt(); if (0 != (settings & 0x100)) buffer.readInt(); if (0 != (settings & 0x200)) buffer.readInt(); hdr = buffer.readUnsignedByte() == 1; buffer.readUnsignedByte(); buffer.readUnsignedByte(); blendType = buffer.readByte(); if(blendType == 1) { int blendMode = buffer.readByte(); } int speedFlag = buffer.readUnsignedByte(); if (0 != (speedFlag & 0x1)) { textureSpeedU = (byte) buffer.readUnsignedByte(); } if (0 != (speedFlag & 0x2)) { textureSpeedV = (byte) buffer.readUnsignedByte(); } if (0 != (speedFlag & 0x4)) { buffer.readUnsignedByte(); } if (0 != (speedFlag & 0x8)) { buffer.readUnsignedByte(); } if (buffer.readUnsignedByte() == 1) { effectId = (byte) buffer.readUnsignedByte(); effectParam1 = (byte) buffer.readUnsignedByte(); effectParam2 = buffer.readInt(); combineMode = buffer.readUnsignedByte(); buffer.readUnsignedByte(); useMipmaps = (byte) buffer.readUnsignedByte(); skipTriangles = buffer.readUnsignedByte() == 1; isGroundMesh = buffer.readUnsignedByte() == 1; brightness = (byte) buffer.readUnsignedByte(); shadowFactor = (byte) buffer.readUnsignedByte(); color = (short) buffer.readUnsignedShort(); } } @Override public String toString() { StringBuilder result = new StringBuilder(); String newLine = System.getProperty(""line.separator""); result.append(this.getClass().getName()); result.append("" {""); result.append(newLine); // determine fields declared in this class only (no fields of // superclass) Field[] fields = this.getClass().getDeclaredFields(); // print field names paired with their values for (Field field : fields) { if (Modifier.isStatic(field.getModifiers())) continue; result.append("" ""); try { result.append(field.getType().getCanonicalName() + "" "" + field.getName() + "": ""); result.append(Utils.getFieldValue(this, field)); } catch (Throwable ex) { System.out.println(ex); } result.append(newLine); } result.append(""}""); return result.toString(); } } " " package com.rs.cache.loaders; import java.awt.Color; import java.util.concurrent.ConcurrentHashMap; import java.lang.SuppressWarnings; import com.rs.cache.ArchiveType; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.lib.io.InputStream; public final class UnderlayDefinitions { private static final ConcurrentHashMap defs = new ConcurrentHashMap(); public int r; public int b; public int anInt6003; public boolean aBool6004; public boolean aBool6005; public int rgb = 0; public int g; public int a; public int texture; public int id; public int hue; public int saturation; public int lumiance; public int blendHue; public int blendHueMultiplier; public int hsl16; public static final UnderlayDefinitions getUnderlayDefinitions(int id) { UnderlayDefinitions def = defs.get(id); if (def != null)// open new txt document return def; byte[] data = Cache.STORE.getIndex(IndexType.CONFIG).getFile(ArchiveType.UNDERLAYS.getId(), id); def = new UnderlayDefinitions(); def.id = id; if (data != null) def.readValueLoop(new InputStream(data)); defs.put(id, def); return def; } private UnderlayDefinitions() { anInt6003 = -1; texture = -1; aBool6004 = true; aBool6005 = true; } private void readValueLoop(InputStream stream) { for (;;) { int opcode = stream.readUnsignedByte(); if (opcode == 0) break; readValues(stream, opcode); } } @SuppressWarnings(""unused"") private void rgbToHsl(int rgb) { double r = (rgb >> 16 & 0xff) / 256.0; double g = (rgb >> 8 & 0xff) / 256.0; double b = (rgb & 0xff) / 256.0; double min = r; if (g < min) { min = g; } if (b < min) { min = b; } double max = r; if (g > max) { max = g; } if (b > max) { max = b; } double h = 0.0; double s = 0.0; double l = (min + max) / 2.0; if (min != max) { if (l < 0.5) { s = (max - min) / (max + min); } if (l >= 0.5) { s = (max - min) / (2.0 - max - min); } if (r == max) { h = (g - b) / (max - min); } else if (g == max) { h = 2.0 + (b - r) / (max - min); } else if (b == max) { h = 4.0 + (r - g) / (max - min); } } h /= 6.0; hue = (int) (h * 256.0); saturation = (int) (s * 256.0); lumiance = (int) (l * 256.0); if (saturation < 0) { saturation = 0; } else if (saturation > 255) { saturation = 255; } if (lumiance < 0) { lumiance = 0; } else if (lumiance > 255) { lumiance = 255; } if (l > 0.5) { blendHueMultiplier = (int) ((1.0 - l) * s * 512.0); } else { blendHueMultiplier = (int) (l * s * 512.0); } if (blendHueMultiplier < 1) { blendHueMultiplier = 1; } blendHue = (int) (h * blendHueMultiplier); hsl16 = hsl24to16(hue, saturation, lumiance); } public static Color toRGB(float h, float s, float l, float alpha) { if (s < 0.0f || s > 100.0f) { String message = ""Color parameter outside of expected range - Saturation""; throw new IllegalArgumentException(message); } if (l < 0.0f || l > 100.0f) { String message = ""Color parameter outside of expected range - Luminance""; throw new IllegalArgumentException(message); } if (alpha < 0.0f || alpha > 1.0f) { String message = ""Color parameter outside of expected range - Alpha""; throw new IllegalArgumentException(message); } // Formula needs all values between 0 - 1. h = h % 360.0f; h /= 360f; s /= 100f; l /= 100f; float q = 0; if (l < 0.5) q = l * (1 + s); else q = (l + s) - (s * l); float p = 2 * l - q; float r = Math.max(0, hueToRGB(p, q, h + (1.0f / 3.0f))); float g = Math.max(0, hueToRGB(p, q, h)); float b = Math.max(0, hueToRGB(p, q, h - (1.0f / 3.0f))); r = Math.min(r, 1.0f); g = Math.min(g, 1.0f); b = Math.min(b, 1.0f); return new Color(r, g, b, alpha); } private static float hueToRGB(float p, float q, float h) { if (h < 0) h += 1; if (h > 1) h -= 1; if (6 * h < 1) { return p + ((q - p) * 6 * h); } if (2 * h < 1) { return q; } if (3 * h < 2) { return p + ((q - p) * 6 * ((2.0f / 3.0f) - h)); } return p; } private final static int hsl24to16(int h, int s, int l) { if (l > 179) { s /= 2; } if (l > 192) { s /= 2; } if (l > 217) { s /= 2; } if (l > 243) { s /= 2; } return (h / 4 << 10) + (s / 32 << 7) + l / 2; } private void readValues(InputStream stream, int i) { if (1 == i) { rgb = stream.read24BitInt(); //rgbToHsl(rgb); r = (rgb >> 16 & 0xff); g = (rgb >> 8 & 0xff); b = (rgb & 0xff); } else if (i == 2) { texture = stream.readUnsignedShort(); if (65535 == texture) texture = -1; } else if (3 == i) anInt6003 = (stream.readUnsignedShort() << 2); else if (i == 4) aBool6004 = false; else if (i == 5) aBool6005 = false; } } " " package com.rs.cache.loaders; import java.io.IOException; import java.util.concurrent.ConcurrentHashMap; import com.rs.cache.ArchiveType; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.lib.io.InputStream; public final class VarBitDefinitions { private static final ConcurrentHashMap varpbitDefs = new ConcurrentHashMap(); public int id; public int baseVar; public int startBit; public int endBit; public static final void main(String[] args) throws IOException { Cache.init(""../cache/""); //System.out.println(getDefs(8065).baseVar); for (int i = 0; i < Cache.STORE.getIndex(IndexType.VARBITS).getLastArchiveId() * 0x3ff; i++) { VarBitDefinitions cd = getDefs(i); if (cd.baseVar == 448) System.out.println(cd.id + "": "" + cd.startBit + ""->"" + cd.endBit + "" on varp "" + cd.baseVar); } } public static final VarBitDefinitions getDefs(int id) { VarBitDefinitions script = varpbitDefs.get(id); if (script != null)// open new txt document return script; byte[] data = Cache.STORE.getIndex(IndexType.VARBITS).getFile(ArchiveType.VARBITS.archiveId(id), ArchiveType.VARBITS.fileId(id)); script = new VarBitDefinitions(); script.id = id; if (data != null) script.readValueLoop(new InputStream(data)); varpbitDefs.put(id, script); return script; } private void readValueLoop(InputStream stream) { for (;;) { int opcode = stream.readUnsignedByte(); if (opcode == 0) break; readValues(stream, opcode); } } private void readValues(InputStream stream, int opcode) { if (opcode == 1) { baseVar = stream.readUnsignedShort(); startBit = stream.readUnsignedByte(); endBit = stream.readUnsignedByte(); } } private VarBitDefinitions() { } }" " package com.rs.cache.loaders; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashMap; import com.rs.cache.ArchiveType; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.lib.io.InputStream; import com.rs.lib.util.Utils; public class VarcDefinitions { private static final HashMap CACHE = new HashMap<>(); public int id; public int anInt4983 = 1; public char aChar4984; public static final VarcDefinitions getDefs(int id) { VarcDefinitions defs = CACHE.get(id); if (defs != null) return defs; byte[] data = Cache.STORE.getIndex(IndexType.CONFIG).getFile(ArchiveType.VARC.getId(), id); defs = new VarcDefinitions(); defs.id = id; if (data != null) defs.readValueLoop(new InputStream(data)); CACHE.put(id, defs); return defs; } private void readValueLoop(InputStream stream) { for (;;) { int opcode = stream.readUnsignedByte(); if (opcode == 0) break; readValues(stream, opcode); } } private void readValues(InputStream stream, int opcode) { if (opcode == 1) { this.aChar4984 = Utils.cp1252ToChar((byte) stream.readByte()); } else if (opcode == 2) { this.anInt4983 = 0; } } @Override public String toString() { StringBuilder result = new StringBuilder(); String newLine = System.getProperty(""line.separator""); result.append(this.getClass().getName()); result.append("" {""); result.append(newLine); // determine fields declared in this class only (no fields of // superclass) Field[] fields = this.getClass().getDeclaredFields(); // print field names paired with their values for (Field field : fields) { if (Modifier.isStatic(field.getModifiers())) continue; result.append("" ""); try { result.append(field.getType().getCanonicalName() + "" "" + field.getName() + "": ""); result.append(Utils.getFieldValue(this, field)); } catch (Throwable ex) { System.out.println(ex); } result.append(newLine); } result.append(""}""); return result.toString(); } } " " package com.rs.cache.loaders; import java.io.IOException; import java.util.concurrent.ConcurrentHashMap; import com.rs.cache.ArchiveType; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.lib.io.InputStream; import com.rs.lib.util.Utils; public final class VarDefinitions { private static final ConcurrentHashMap VAR_DEFS = new ConcurrentHashMap(); public int id; public char paramType; public int defaultValue = 0; public static final void main(String[] args) throws IOException { //Cache.init(); System.out.println(""Num vars: "" + Cache.STORE.getIndex(IndexType.CONFIG).getLastFileId(ArchiveType.VARS.getId())); for (int i = 0; i < Cache.STORE.getIndex(IndexType.CONFIG).getLastFileId(ArchiveType.VARS.getId())+1; i++) { VarDefinitions cd = getDefs(i); System.out.println(i + "" - "" + cd.paramType + "" "" + cd.defaultValue); } } public static final VarDefinitions getDefs(int id) { VarDefinitions script = VAR_DEFS.get(id); if (script != null) return script; byte[] data = Cache.STORE.getIndex(IndexType.CONFIG).getFile(ArchiveType.VARS.getId(), id); script = new VarDefinitions(); script.id = id; if (data != null) script.readValueLoop(new InputStream(data)); VAR_DEFS.put(id, script); return script; } private void readValueLoop(InputStream stream) { for (;;) { int opcode = stream.readUnsignedByte(); if (opcode == 0) break; readValues(stream, opcode); } } private void readValues(InputStream stream, int opcode) { if (opcode == 1) { paramType = Utils.cp1252ToChar((byte) stream.readByte()); } else if (opcode == 5) { defaultValue = stream.readUnsignedShort(); } } private VarDefinitions() { } } " " package com.rs.cache.loaders.animations; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import com.rs.cache.ArchiveType; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.lib.io.InputStream; import com.rs.lib.util.Utils; public class AnimationDefinitions { public int id; public int replayMode; public int[] interfaceFrames; public int[] frameDurations; public int[][] soundSettings; public int loopDelay = -1; public boolean[] aBoolArray5915; public int priority = -1; public int leftHandItem = 65535; public int rightHandItem = 65535; public int[] anIntArray5919; public int animatingPrecedence; public int walkingPrecedence; public int[] frameHashes; public int[] frameSetIds; public int[] anIntArray5923; public boolean aBool5923; public boolean tweened; public int[] soundDurations; public int[] anIntArray5927; public boolean vorbisSound; public int maxLoops = 1; public int[][] soundFlags; private AnimationFrameSet[] frameSets; public HashMap clientScriptMap = new HashMap(); private static final ConcurrentHashMap animDefs = new ConcurrentHashMap(); private static final HashMap itemAnims = new HashMap(); public static void main(String[] args) throws IOException { Cache.init(""../cache/""); int[] itemIds = { 1351, 1349, 1353, 1361, 1355, 1357, 1359, 6739, 13661 }; Map> mapping = new HashMap<>(); for (int i = 0;i < Utils.getAnimationDefinitionsSize();i++) { AnimationDefinitions def = AnimationDefinitions.getDefs(i); for (int itemId : itemIds) { if (def.rightHandItem == itemId || def.leftHandItem == itemId) { Map sets = mapping.get(itemId); if (sets == null) sets = new HashMap<>(); int hash = Arrays.hashCode(def.frameHashes); sets.put(hash, def.id); mapping.put(itemId, sets); } } } // AnimationDefinitions def = AnimationDefinitions.getDefs(12322); // System.out.println(def); } public static void init() { for (int i = 0; i < Utils.getAnimationDefinitionsSize(); i++) { AnimationDefinitions defs = getDefs(i); if (defs == null) continue; if (defs.leftHandItem != -1 && defs.leftHandItem != 65535) { itemAnims.put(defs.leftHandItem, i); } if (defs.rightHandItem != -1 && defs.rightHandItem != 65535) { itemAnims.put(defs.rightHandItem, i); } } } public AnimationFrameSet[] getFrameSets() { if (frameSets == null) { frameSets = new AnimationFrameSet[frameSetIds.length]; if (frameSetIds != null) { for (int i = 0;i < frameSetIds.length;i++) { frameSets[i] = AnimationFrameSet.getFrameSet(frameSetIds[i]); } } } return frameSets; } public static int getAnimationWithItem(int itemId) { if (itemAnims.get(itemId) != null) return itemAnims.get(itemId); return -1; } @Override public String toString() { StringBuilder result = new StringBuilder(); String newLine = System.getProperty(""line.separator""); result.append(this.getClass().getName()); result.append("" {""); result.append(newLine); // determine fields declared in this class only (no fields of // superclass) Field[] fields = this.getClass().getDeclaredFields(); // print field names paired with their values for (Field field : fields) { if (Modifier.isStatic(field.getModifiers())) continue; result.append("" ""); try { result.append(field.getType().getCanonicalName() + "" "" + field.getName() + "": ""); result.append(Utils.getFieldValue(this, field)); } catch (Throwable ex) { System.out.println(ex); } result.append(newLine); } result.append(""}""); return result.toString(); } public static final AnimationDefinitions getDefs(int emoteId) { try { AnimationDefinitions defs = animDefs.get(emoteId); if (defs != null) return defs; byte[] data = Cache.STORE.getIndex(IndexType.ANIMATIONS).getFile(ArchiveType.ANIMATIONS.archiveId(emoteId), ArchiveType.ANIMATIONS.fileId(emoteId)); defs = new AnimationDefinitions(); if (data != null) defs.readValueLoop(new InputStream(data)); defs.method11143(); defs.id = emoteId; animDefs.put(emoteId, defs); return defs; } catch (Throwable t) { return null; } } private void readValueLoop(InputStream stream) { for (;;) { int opcode = stream.readUnsignedByte(); if (opcode == 0) break; readValues(stream, opcode); } } public int getEmoteTime() { if (frameDurations == null) return 0; int ms = 0; for (int i : frameDurations) ms += i * 20; return ms; } public int getEmoteGameTicks() { return getEmoteTime() / 600; } private void readValues(InputStream stream, int opcode) { if (1 == opcode) { int frameCount = stream.readUnsignedShort(); frameDurations = new int[frameCount]; for (int i = 0; i < frameCount; i++) frameDurations[i] = stream.readUnsignedShort(); frameHashes = new int[frameCount]; frameSetIds = new int[frameCount]; for (int i = 0; i < frameCount; i++) { frameHashes[i] = stream.readUnsignedShort(); } for (int i = 0; i < frameCount; i++) frameHashes[i] += (stream.readUnsignedShort() << 16); for (int i = 0; i < frameCount; i++) { frameSetIds[i] = frameHashes[i] >>> 16; } } else if (opcode == 2) loopDelay = stream.readUnsignedShort(); else if (3 == opcode) { aBoolArray5915 = new boolean[256]; int i_7_ = stream.readUnsignedByte(); for (int i_8_ = 0; i_8_ < i_7_; i_8_++) aBoolArray5915[stream.readUnsignedByte()] = true; } else if (5 == opcode) priority = stream.readUnsignedByte(); else if (6 == opcode) leftHandItem = stream.readUnsignedShort(); else if (opcode == 7) rightHandItem = stream.readUnsignedShort(); else if (8 == opcode) maxLoops = stream.readUnsignedByte(); else if (9 == opcode) animatingPrecedence = stream.readUnsignedByte(); else if (10 == opcode) walkingPrecedence = stream.readUnsignedByte(); else if (opcode == 11) replayMode = stream.readUnsignedByte(); else if (opcode == 12) { int i_9_ = stream.readUnsignedByte(); interfaceFrames = new int[i_9_]; for (int i_10_ = 0; i_10_ < i_9_; i_10_++) interfaceFrames[i_10_] = stream.readUnsignedShort(); for (int i_11_ = 0; i_11_ < i_9_; i_11_++) interfaceFrames[i_11_] = (stream.readUnsignedShort() << 16) + interfaceFrames[i_11_]; } else if (13 == opcode) { int i_12_ = stream.readUnsignedShort(); soundSettings = new int[i_12_][]; soundFlags = new int[i_12_][]; for (int i_13_ = 0; i_13_ < i_12_; i_13_++) { int i_14_ = stream.readUnsignedByte(); if (i_14_ > 0) { soundSettings[i_13_] = new int[i_14_]; soundSettings[i_13_][0] = stream.read24BitInt(); soundFlags[i_13_] = new int[3]; soundFlags[i_13_][0] = soundSettings[i_13_][0] >> 8; soundFlags[i_13_][1] = soundSettings[i_13_][0] >> 5 & 0x7; soundFlags[i_13_][2] = soundSettings[i_13_][0] & 0x1f; for (int i_15_ = 1; i_15_ < i_14_; i_15_++) soundSettings[i_13_][i_15_] = stream.readUnsignedShort(); } } } else if (opcode == 14) aBool5923 = true; else if (opcode == 15) tweened = true; else if (opcode != 16) { if (18 == opcode) vorbisSound = true; else if (19 == opcode) { if (soundDurations == null) { soundDurations = new int[soundSettings.length]; for (int i_16_ = 0; i_16_ < soundSettings.length; i_16_++) soundDurations[i_16_] = 255; } soundDurations[stream.readUnsignedByte()] = stream.readUnsignedByte(); } else if (opcode == 20) { if (null == anIntArray5927 || null == anIntArray5919) { anIntArray5927 = new int[soundSettings.length]; anIntArray5919 = new int[soundSettings.length]; for (int i_17_ = 0; i_17_ < soundSettings.length; i_17_++) { anIntArray5927[i_17_] = 256; anIntArray5919[i_17_] = 256; } } int i_18_ = stream.readUnsignedByte(); anIntArray5927[i_18_] = stream.readUnsignedShort(); anIntArray5919[i_18_] = stream.readUnsignedShort(); } else if (249 == opcode) { int i_19_ = stream.readUnsignedByte(); for (int i_21_ = 0; i_21_ < i_19_; i_21_++) { boolean bool = stream.readUnsignedByte() == 1; int i_22_ = stream.read24BitInt(); if (bool) clientScriptMap.put(i_22_, stream.readString()); else clientScriptMap.put(i_22_, stream.readInt()); } } } } public Set getUsedSynthSoundIds() { Set set = new HashSet<>(); if (this.vorbisSound || this.soundFlags == null || this.soundFlags.length <= 0) return set; for (int i = 0;i < soundFlags.length;i++) { if (soundFlags[i] == null) continue; set.add(soundFlags[i][0]); } return set; } void method11143() { if (animatingPrecedence == -1) { if (aBoolArray5915 != null) animatingPrecedence = 2; else animatingPrecedence = 0; } if (walkingPrecedence == -1) { if (null != aBoolArray5915) walkingPrecedence = 2; else walkingPrecedence = 0; } } } " " package com.rs.cache.loaders.animations; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import com.rs.lib.io.InputStream; import com.rs.lib.util.Utils; public class AnimationFrame { public static short[] indicesBuffer = new short[500]; public static short[] bufferX = new short[500]; public static short[] bufferY = new short[500]; public static short[] bufferZ = new short[500]; public static short[] skipped = new short[500]; public static byte[] flagsBuffer = new byte[500]; public boolean modifiesColor; public int transformationCount = 0; public short[] transformationX; public short[] transformationY; public short[] transformationZ; public short[] skippedReferences; public byte[] transformationFlags; public boolean modifiesAlpha = false; public short[] transformationIndices; public boolean aBool988; public int frameBaseId; public AnimationFrameBase frameBase; public static AnimationFrame getFrame(byte[] frameData, AnimationFrameBase frameBase) { AnimationFrame frame = new AnimationFrame(); frame.frameBase = frameBase; frame.frameBaseId = frameBase.id; frame.readFrameData(frameData); return frame; } private void readFrameData(byte[] data) { try { InputStream attribBuffer = new InputStream(data); InputStream transformationBuffer = new InputStream(data); attribBuffer.readUnsignedByte(); attribBuffer.skip(2); int count = attribBuffer.readUnsignedByte(); int used = 0; int last = -1; int lastUsed = -1; transformationBuffer.setOffset(attribBuffer.getOffset() + count); for (int i = 0; i < count; i++) { int type = frameBase.transformationTypes[i]; if (type == 0) last = i; int attribute = attribBuffer.readUnsignedByte(); if (attribute > 0) { if (type == 0) lastUsed = i; indicesBuffer[used] = (short) i; short value = 0; if (type == 3 || type == 10) value = (short) 128; if ((attribute & 0x1) != 0) bufferX[used] = (short) transformationBuffer.readSignedSmart(); else bufferX[used] = value; if ((attribute & 0x2) != 0) bufferY[used] = (short) transformationBuffer.readSignedSmart(); else bufferY[used] = value; if ((attribute & 0x4) != 0) bufferZ[used] = (short) transformationBuffer.readSignedSmart(); else bufferZ[used] = value; flagsBuffer[used] = (byte) (attribute >>> 3 & 0x3); if (type == 2 || type == 9) { bufferX[used] = (short) (bufferX[used] << 2 & 0x3fff); bufferY[used] = (short) (bufferY[used] << 2 & 0x3fff); bufferZ[used] = (short) (bufferZ[used] << 2 & 0x3fff); } skipped[used] = -1; if (type == 1 || type == 2 || type == 3) { if (last > lastUsed) { skipped[used] = (short) last; lastUsed = last; } } else if (type == 5) modifiesAlpha = true; else if (type == 7) modifiesColor = true; else if (type == 9 || type == 10 || type == 8) aBool988 = true; used++; } } if (transformationBuffer.getOffset() != data.length) throw new RuntimeException(); transformationCount = used; transformationIndices = new short[used]; transformationX = new short[used]; transformationY = new short[used]; transformationZ = new short[used]; skippedReferences = new short[used]; transformationFlags = new byte[used]; for (int i = 0; i < used; i++) { transformationIndices[i] = indicesBuffer[i]; transformationX[i] = bufferX[i]; transformationY[i] = bufferY[i]; transformationZ[i] = bufferZ[i]; skippedReferences[i] = skipped[i]; transformationFlags[i] = flagsBuffer[i]; } } catch (Exception exception_13) { this.transformationCount = 0; this.modifiesAlpha = false; this.modifiesColor = false; } } @Override public String toString() { StringBuilder result = new StringBuilder(); String newLine = System.getProperty(""line.separator""); result.append(this.getClass().getName()); result.append("" {""); result.append(newLine); // determine fields declared in this class only (no fields of // superclass) Field[] fields = this.getClass().getDeclaredFields(); // print field names paired with their values for (Field field : fields) { if (Modifier.isStatic(field.getModifiers())) continue; result.append("" ""); try { result.append(field.getType().getCanonicalName() + "" "" + field.getName() + "": ""); result.append(Utils.getFieldValue(this, field)); } catch (Throwable ex) { System.out.println(ex); } result.append(newLine); } result.append(""}""); return result.toString(); } } " " package com.rs.cache.loaders.animations; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.concurrent.ConcurrentHashMap; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.lib.io.InputStream; import com.rs.lib.util.Utils; public class AnimationFrameBase { private static final ConcurrentHashMap FRAME_BASES = new ConcurrentHashMap(); public int id; public int[][] labels; public int[] anIntArray7561; public int[] transformationTypes; public boolean[] aBoolArray7563; public int count; public AnimationFrameBase(int id) { this.id = id; } public static AnimationFrameBase getFrame(int frameBaseId) { if (FRAME_BASES.get(frameBaseId) != null) return FRAME_BASES.get(frameBaseId); byte[] frameBaseData = Cache.STORE.getIndex(IndexType.ANIMATION_FRAME_BASES).getFile(frameBaseId, 0); if (frameBaseData == null) { return null; } AnimationFrameBase defs = new AnimationFrameBase(frameBaseId); defs.decode(new InputStream(frameBaseData)); FRAME_BASES.put(frameBaseId, defs); return defs; } public void decode(InputStream buffer) { count = buffer.readUnsignedByte(); transformationTypes = new int[count]; labels = new int[count][]; aBoolArray7563 = new boolean[count]; anIntArray7561 = new int[count]; for (int i_0_ = 0; i_0_ < count; i_0_++) { transformationTypes[i_0_] = buffer.readUnsignedByte(); if (transformationTypes[i_0_] == 6) transformationTypes[i_0_] = 2; } for (int i_1_ = 0; i_1_ < count; i_1_++) aBoolArray7563[i_1_] = buffer.readUnsignedByte() == 1; for (int i_2_ = 0; i_2_ < count; i_2_++) anIntArray7561[i_2_] = buffer.readUnsignedShort(); for (int i_3_ = 0; i_3_ < count; i_3_++) labels[i_3_] = new int[buffer.readUnsignedByte()]; for (int i_4_ = 0; i_4_ < count; i_4_++) { for (int i_5_ = 0; (i_5_ < labels[i_4_].length); i_5_++) labels[i_4_][i_5_] = buffer.readUnsignedByte(); } } @Override public String toString() { StringBuilder result = new StringBuilder(); String newLine = System.getProperty(""line.separator""); result.append(this.getClass().getName()); result.append("" {""); result.append(newLine); // determine fields declared in this class only (no fields of // superclass) Field[] fields = this.getClass().getDeclaredFields(); // print field names paired with their values for (Field field : fields) { if (Modifier.isStatic(field.getModifiers())) continue; result.append("" ""); try { result.append(field.getType().getCanonicalName() + "" "" + field.getName() + "": ""); result.append(Utils.getFieldValue(this, field)); } catch (Throwable ex) { System.out.println(ex); } result.append(newLine); } result.append(""}""); return result.toString(); } } " " package com.rs.cache.loaders.animations; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.concurrent.ConcurrentHashMap; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.lib.io.InputStream; import com.rs.lib.util.Utils; public class AnimationFrameSet { private static final ConcurrentHashMap FRAME_COLLECTIONS = new ConcurrentHashMap(); public int id; private AnimationFrame[] frames; public AnimationFrame[] getFrames() { return frames; } public static AnimationFrameSet getFrameSet(int id) { if (FRAME_COLLECTIONS.get(id) != null) return FRAME_COLLECTIONS.get(id); if (id > Cache.STORE.getIndex(IndexType.ANIMATION_FRAME_SETS).getTable().getArchives().length) return null; int[] files = Cache.STORE.getIndex(IndexType.ANIMATION_FRAME_SETS).getTable().getArchives()[id].getValidFileIds(); if (files == null) { System.out.println(""Null files: "" + id); return null; } AnimationFrameSet defs = new AnimationFrameSet(); defs.id = id; byte[][] frameData = new byte[files.length][]; for (int i = 0;i < files.length;i++) frameData[i] = Cache.STORE.getIndex(IndexType.ANIMATION_FRAME_SETS).getFile(id, files[i]); defs.frames = new AnimationFrame[frameData.length]; for (int i = 0;i < frameData.length;i++) { InputStream stream = new InputStream(frameData[i]); stream.setOffset(1); int frameBaseId = stream.readUnsignedShort(); defs.frames[i] = AnimationFrame.getFrame(frameData[i], AnimationFrameBase.getFrame(frameBaseId)); } FRAME_COLLECTIONS.put(id, defs); return defs; } @Override public String toString() { StringBuilder result = new StringBuilder(); String newLine = System.getProperty(""line.separator""); result.append(this.getClass().getName()); result.append("" {""); result.append(newLine); // determine fields declared in this class only (no fields of // superclass) Field[] fields = this.getClass().getDeclaredFields(); // print field names paired with their values for (Field field : fields) { if (Modifier.isStatic(field.getModifiers())) continue; result.append("" ""); try { result.append(field.getType().getCanonicalName() + "" "" + field.getName() + "": ""); result.append(Utils.getFieldValue(this, field)); } catch (Throwable ex) { System.out.println(ex); } result.append(newLine); } result.append(""}""); return result.toString(); } } " " package com.rs.cache.loaders.cs2; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.lib.io.InputStream; public class CS2Definitions { private static HashMap scripts = new HashMap(); public static void main(String[] args) throws IOException { Cache.init(""../cache/""); int id = 4421; // for (int i = 0;i < Cache.STORE.getIndex(IndexType.CS2_SCRIPTS).getLastArchiveId();i++) { // CS2Script s = getScript(i); // if (s == null) // continue; // if (s.name != null) // System.out.println(s.name); // for (int x = 0;x < s.operations.length;x++) { // if (s.operations[x] == CS2Instruction.SOUND_SYNTH) { // System.out.println(i); // System.out.println(Arrays.toString(s.operations)); // id = i; // break; // } // if (s.operations[x] == CS2Instruction.SOUND_SYNTH_RATE) { // System.out.println(i); // System.out.println(Arrays.toString(s.operations)); // id = i; // break; // } // if (s.operations[x] == CS2Instruction.SOUND_SYNTH_VOLUME) { // System.out.println(i); // System.out.println(Arrays.toString(s.operations)); // id = i; // break; // } // // } // } CS2Script script = getScript(id); System.out.println(script); System.out.println(""script = CS2Definitions.getScript("" + script.id + "");""); System.out.println(Arrays.toString(script.arguments)); for (int i = 0;i < script.operations.length;i++) { System.out.println(""[""+i+""]: "" + script.getOpString(i)); } printCS2RenameProgress(); } public static boolean instructionUsed(CS2Instruction instr) { for (int i = 0;i <= Cache.STORE.getIndex(IndexType.CS2_SCRIPTS).getLastArchiveId();i++) { CS2Script s = getScript(i); if (s == null) continue; for (int x = 0;x < s.operations.length;x++) { if (s.operations[x] == instr) return true; } } return false; } public static void printCS2RenameProgress() { int total = CS2Instruction.values().length; Set used = new HashSet<>(); for (int i = 0;i < Cache.STORE.getIndex(IndexType.CS2_SCRIPTS).getLastArchiveId();i++) { CS2Script s = getScript(i); if (s == null) continue; for (int x = 0;x < s.operations.length;x++) { used.add(s.operations[x]); } } int identified = 0; int usedIdentified = 0; for (CS2Instruction instr : CS2Instruction.values()) { if (!instr.name().contains(""instr"")) { identified++; if (used.contains(instr)) usedIdentified++; } } System.out.println(""-CS2 Overall Instruction Progress-""); System.out.println(""Instruction count: "" + total); System.out.println(""Unidentified: "" + (total-identified)); System.out.println(""Identified: "" + identified + "" (""+Math.round(((double) identified / (double) total * 100.0))+""%)""); System.out.println(""-CS2 Used Instruction Progress-""); System.out.println(""Instruction count: "" + used.size()); System.out.println(""Unidentified: "" + (used.size()-usedIdentified)); System.out.println(""Identified: "" + usedIdentified + "" (""+Math.round(((double) usedIdentified / (double) used.size() * 100.0))+""%)""); } public static void verify() { int correct = 0; int scriptCount = 0; for (int i = 0;i < Cache.STORE.getIndex(IndexType.CS2_SCRIPTS).getLastArchiveId();i++) { CS2Script script = getScript(i); CS2Script reCoded = new CS2Script(new InputStream(script.encode())); if (script.equals(reCoded)) correct++; scriptCount++; } System.out.println(correct+""/""+scriptCount); } public static CS2Script getScript(int scriptId) { if (scripts.containsKey(scriptId)) { return scripts.get(scriptId); } if (Cache.STORE.getIndex(IndexType.CS2_SCRIPTS).archiveExists(scriptId)) { CS2Script script = new CS2Script(new InputStream(Cache.STORE.getIndex(IndexType.CS2_SCRIPTS).getArchive(scriptId).getData())); script.id = scriptId; scripts.put(scriptId, script); return script; } return null; } } " " package com.rs.cache.loaders.cs2; import java.util.HashMap; public enum CS2Instruction { PUSH_INT(79, true), LOAD_VARP(154, true), STORE_VARP(929, true), PUSH_STRING(57, true), GOTO(123, true), INT_NE(693, true), INT_EQ(933, true), INT_LT(566, true), INT_GT(939, true), GET_VARP_OLD(267, true), GET_VARPBIT_OLD(827, true), GET_VARN_OLD(229, true), GET_VARNBIT_OLD(526, true), RETURN(184), LOAD_VARPBIT(408, true), STORE_VARPBIT(371, true), INT_LE(670, true), INT_GE(319, true), LOAD_INT(500, true), STORE_INT(168, true), LOAD_STRING(799, true), STORE_STRING(356, true), MERGE_STRINGS(531, true), POP_INT(492), POP_STRING(354), CALL_CS2(902, true), LOAD_VARC(311, true), STORE_VARC(510, true), ARRAY_NEW(235, true), ARRAY_LOAD(859, true), ARRAY_STORE(116, true), LOAD_VARC_STRING(700, true), STORE_VARC_STRING(21, true), SWITCH(377, true), PUSH_LONG(633, true), POP_LONG(539, true), LOAD_LONG(473, true), STORE_LONG(987, true), LONG_NE(908, true), LONG_EQ(381, true), LONG_LT(597, true), LONG_GT(237, true), LONG_LE(465, true), LONG_GE(142, true), BRANCH_EQ1(195, true), BRANCH_EQ0(836, true), LOAD_CLAN_VAR(717, true), LOAD_CLAN_VARBIT(220, true), LOAD_CLAN_VAR_LONG(215, true), LOAD_CLAN_VAR_STRING(995, true), LOAD_CLAN_SETTING_VAR(73, true), LOAD_CLAN_SETTING_VARBIT(147, true), LOAD_CLAN_SETTING_VAR_LONG(83, true), LOAD_CLAN_SETTING_VAR_STRING(910, true), CC_CREATE(113), CC_DELETE(981), CC_DELETEALL(572), CC_SETCHILD_SLOT(677), CC_SETCHILD(333), IF_SENDTOFRONT(515), IF_SENDTOBACK(246), CC_SENDTOFRONT(993), CC_SENDTOBACK(584), IF_RESUME_PAUSEBUTTON(326), CC_RESUME_PAUSEBUTTON(502), BASE_IDKIT(613), BASE_COLOR(156), SET_GENDER(325), SET_ITEM(925), CC_SETPOSITION(847), CC_SETSIZE(140), CC_SETHIDE(112), CC_SETASPECT(341), CC_SETNOCLICKTHROUGH(787), CC_SETSCROLLPOS(126), CC_SETCOLOR(274), CC_SETFILL(402), CC_SETTRANS(320), CC_SETLINEWID(124), CC_SETGRAPHIC(415), CC_SET2DANGLE(196), CC_SETTILING(406), CC_SETMODEL(872), CC_SETMODELANGLE(528), CC_SETMODELANIM(32), CC_SETMODELORTHOG(363), CC_SETMODELTINT(911), CC_SETTEXT(972), CC_SETTEXTFONT(351), CC_SETTEXTALIGN(546), CC_SETTEXTSHADOW(103), CC_SETTEXTANTIMACRO(644), CC_SETOUTLINE(317), CC_SETGRAPHICSHADOW(751), CC_SETVFLIP(599), CC_SETHFLIP(185), CC_SETSCROLLSIZE(28), CC_SETALPHA(209), CC_SETMODELZOOM(159), CC_SETLINEDIRECTION(965), CC_SETMODELORIGIN(24), CC_SETMAXLINES(77), CC_SETPARAM_INT(497), CC_SETPARAM_STRING(639), instr6050(513), instr6051(100), CC_SETRECOL(589), CC_SETRETEX(579), CC_SETFONTMONO(476), CC_SETPARAM(606), CC_SETCLICKMASK(924), CC_SETITEM(13), CC_SETNPCHEAD(542), CC_SETPLAYERHEAD_SELF(186), CC_SETNPCMODEL(470), CC_SETPLAYERMODEL(133), CC_SETITEM_NONUM(412), instr6063(591), instr6064(314), instr6065(878), instr6066(173), instr6895(928), CC_SETPLAYERMODEL_SELF(443), CC_SETITEM_ALWAYSNUM(998), CC_SETITEM_WEARCOL_ALWAYSNUM(834), CC_SETOP(671), instr6676(68), instr6073(345), instr6443(764), instr6075(223), instr6076(275), instr6110(466), instr6179(611), instr6218(627), CC_SETOPCURSOR(176), instr6081(806), instr6737(659), instr6083(66), instr6258(749), instr6085(895), instr6086(67), instr6087(219), instr6088(813), instr5957(158), instr6450(374), instr6091(1), instr6092(665), instr6224(705), instr6094(892), instr6095(697), instr6556(957), instr6687(457), instr6499(392), instr6084(708), instr6346(207), instr6452(191), instr6899(886), instr6103(991), instr6765(615), instr6370(807), instr6106(695), instr6580(323), instr6437(59), instr6903(841), instr6099(883), instr6111(719), instr6112(490), instr6113(440), instr6492(652), instr6096(315), instr6116(70), instr6054(525), instr6782(916), instr6119(505), instr6120(544), instr6121(702), instr6552(797), instr6772(523), instr6124(545), instr6125(796), instr6344(747), instr6462(204), instr6128(626), instr6762(451), instr6130(494), instr6131(755), instr6132(979), instr6133(680), instr6134(829), instr6135(0), instr6901(491), instr6529(648), instr6670(555), instr6139(34), instr6005(97), instr6262(728), instr6928(449), instr6771(832), instr6144(723), instr6230(664), instr6566(160), instr6842(472), instr6148(137), instr6636(36), instr6150(3), instr6151(620), instr6585(467), instr6153(75), instr6154(125), instr6155(694), instr6662(707), instr6157(989), IF_SETPOSITION(937), IF_SETSIZE(982), IF_SETHIDE(590), IF_SETASPECT(434), IF_SETNOCLICKTHROUGH(668), IF_SETSCROLLPOS(825), IF_SETCOLOR(816), IF_SETFILL(918), IF_SETTRANS(763), IF_SETLINEWID(530), IF_SETGRAPHIC(529), IF_SET2DANGLE(205), IF_SETTILING(460), IF_SETMODEL(488), IF_SETMODELANGLE(605), IF_SETMODELANIM(690), instr6174(824), instr6369(82), IF_SETTEXT(724), IF_SETTEXTFONT(85), IF_SETTEXTALIGN(741), instr6170(689), instr6180(651), instr6181(344), instr6182(131), instr6183(503), instr6184(774), instr6185(628), instr6216(368), instr6187(527), instr6188(760), instr6377(862), instr6190(432), instr6191(369), instr6192(198), instr6193(479), instr6194(206), instr6195(194), instr6196(950), instr6197(316), IF_SETCLICKMASK(224), IF_SETITEM(388), IF_SETNPCHEAD(857), IF_SETPLAYERHEAD_SELF(783), instr6715(845), instr6864(547), instr6879(72), instr6205(203), instr6919(598), instr6207(518), instr6208(352), instr6209(744), instr6210(499), instr6129(552), instr6793(898), instr6213(255), instr6214(899), instr6215(495), instr5969(98), instr6217(413), instr6569(289), instr6219(583), instr6220(512), instr6221(896), instr6222(122), instr6223(790), instr6888(805), instr6136(222), instr6226(127), instr6477(739), instr6228(903), instr6229(786), HOOK_MOUSE_PRESS(881), instr6231(143), instr6232(382), HOOK_MOUSE_ENTER(968), HOOK_MOUSE_EXIT(600), instr6235(478), instr6527(770), instr6237(244), instr6342(300), instr6239(172), instr6240(926), instr5973(287), IF_SETONMOUSEOVER(753), IF_SETONMOUSELEAVE(809), instr6393(486), instr6376(758), instr6246(550), instr6247(683), instr6248(730), instr6708(76), instr6250(625), instr6251(416), instr6252(179), instr6253(532), instr6254(947), instr6255(630), instr6256(321), instr6257(189), instr6507(768), instr6259(508), instr6260(401), instr6261(111), instr6898(105), IF_CLEARSCRIPTHOOKS(64), IF_GETX(710), IF_GETY(170), IF_GETWIDTH(263), IF_GETHEIGHT(953), IF_GETHIDE(578), IF_GETLAYER(135), IF_GETPARENTLAYER(692), IF_GETCOLOR(798), IF_GETSCROLLX(932), IF_GETSCROLLY(428), IF_GETTEXT(748), instr6275(496), instr6276(978), instr6277(38), instr6292(461), instr6279(96), instr6280(436), instr6281(912), instr6544(721), instr6283(463), instr6284(169), instr6072(624), instr6159(864), instr6287(870), instr6288(997), instr6289(543), instr6290(808), instr6875(373), instr6805(888), instr6293(1000), instr6294(448), instr6295(331), instr6296(704), instr6297(164), instr6298(996), instr6299(197), instr6300(163), instr6391(52), instr6302(941), instr6303(588), instr6304(948), instr6646(999), instr6186(882), instr6307(167), instr6002(736), instr6309(250), MES(471), RESET_MYPLAYER_ANIMS(245), IF_CLOSE(574), RESUME_COUNTDIALOG(117), RESUME_NAMEDIALOG(216), RESUME_STRINGDIALOG(4), OPPLAYER(162), IF_DRAGPICKUP(18), CC_DRAGPICKUP(259), RESUME_ITEMDIALOG(304), IF_OPENSUBCLIENT(360), IF_CLOSESUBCLIENT(291), OPPLAYERT(637), MES_TYPED(913), SETUP_MESSAGEBOX(211), RESUME_HSLDIALOG(238), RESUME_CLANFORUMQFCDIALOG(101), SOUND_SYNTH(2), SOUND_SONG(855), SOUND_JINGLE(920), SOUND_SYNTH_VOLUME(784), SOUND_SONG_VOLUME(780), SOUND_JINGLE_VOLUME(145), SOUND_VORBIS_VOLUME(516), SOUND_SPEECH_VOLUME(959), SOUND_SYNTH_RATE(535), SOUND_VORBIS_RATE(395), CLIENTCLOCK(80), INV_GETITEM(180), INV_GETNUM(138), INV_TOTAL(485), INV_SIZE(157), INV_TOTALCAT(192), STAT(301), STAT_BASE(340), STAT_VISIBLE_XP(772), COORD(389), COORDX(93), COORDY(298), COORDZ(536), WORLD_MEMBERS(336), INVOTHER_GETITEM(612), INVOTHER_GETNUM(720), INVOTHER_TOTAL(771), STAFFMODLEVEL(727), GET_SYSTEM_UPDATE_TIMER(715), WORLD_ID(601), RUNENERGY_VISIBLE(944), RUNWEIGHT_VISIBLE(866), PLAYERMOD(81), PLAYERMODLEVEL(718), PLAYERMEMBER(262), COMLEVEL_ACTIVE(139), GENDER(657), WORLD_QUICKCHAT(427), CONTAINER_FREE_SPACE(20), CONTAINER_TOTAL_PARAM(696), CONTAINER_TOTAL_PARAM_STACK(524), WORLD_LANGUAGE(202), MOVECOORD(48), AFFILIATE(25), PROFILE_CPU(930), PLAYERDEMO(619), APPLET_HASFOCUS(781), FROMBILLING(655), GET_MOUSE_X(243), GET_MOUSE_Y(308), GET_ACTIVE_MINIMENU_ENTRY(115), GET_SECOND_MINIMENU_ENTRY(366), GET_MINIMENU_LENGTH(50), GET_CURRENTCURSOR(980), GET_SELFYANGLE(426), MAP_ISOWNER(214), GET_MOUSEBUTTONS(453), SELF_PLAYER_UID(554), GET_MINIMENU_TARGET(814), ENUM_STRING(820), ENUM(540), ENUM_HASOUTPUT(60), ENUM_HASOUTPUT_STRING(840), ENUM_GETOUTPUTCOUNT(533), ENUM_GETREVERSECOUNT(149), ENUM_GETREVERSECOUNT_STRING(438), ENUM_GETREVERSEINDEX(904), ENUM_GETREVERSEINDEX_STRING(86), EMAIL_VALIDATION_SUBMIT_CODE(364), EMAIL_VALIDATION_CHANGE_ADDRESS(121), EMAIL_VALIDATION_ADD_NEW_ADDRESS(511), FRIEND_COUNT(183), FRIEND_GETNAME(252), FRIEND_GETWORLD(51), FRIEND_GETRANK(732), FRIEND_GETWORLDFLAGS(562), FRIEND_SETRANK(647), FRIEND_ADD(609), FRIEND_DEL(914), IGNORE_ADD(177), IGNORE_DEL(871), FRIEND_TEST(879), FRIEND_GETWORLDNAME(767), FC_GETCHATDISPLAYNAME(765), FC_GETCHATCOUNT(1002), FC_GETCHATUSERNAME(699), FC_GETCHATUSERWORLD(587), FC_GETCHATUSERRANK(394), FC_GETCHATMINKICK(346), FC_KICKUSER(421), FC_GETCHATRANK(854), FC_JOINCHAT(293), FC_LEAVECHAT(682), IGNORE_COUNT(735), IGNORE_GETNAME(284), IGNORE_TEST(966), FC_ISSELF(802), FC_GETCHATOWNERNAME(338), FC_GETCHATUSERWORLDNAME(943), FRIEND_PLATFORM(880), FRIEND_GETSLOTFROMNAME(520), PLAYERCOUNTRY(667), IGNORE_ADD_TEMP(954), IGNORE_IS_TEMP(629), FC_GETCHATUSERNAME_UNFILTERED(580), IGNORE_GETNAME_UNFILTERED(37), FRIEND_IS_REFERRER(656), ACTIVECLANSETTINGS_FIND_LISTENED(833), ACTIVECLANSETTINGS_FIND_AFFINED(452), ACTIVECLANSETTINGS_GETCLANNAME(815), ACTIVECLANSETTINGS_GETALLOWUNAFFINED(843), ACTIVECLANSETTINGS_GETRANKTALK(91), ACTIVECLANSETTINGS_GETRANKKICK(894), ACTIVECLANSETTINGS_GETRANKLOOTSHARE(549), ACTIVECLANSETTINGS_GETCOINSHARE(200), ACTIVECLANSETTINGS_GETAFFINEDCOUNT(706), ACTIVECLANSETTINGS_GETAFFINEDDISPLAYNAME(541), ACTIVECLANSETTINGS_GETAFFINEDRANK(166), ACTIVECLANSETTINGS_GETBANNEDCOUNT(411), ACTIVECLANSETTINGS_GETBANNEDDISPLAYNAME(746), ACTIVECLANSETTINGS_GETAFFINEDEXTRAINFO(861), ACTIVECLANSETTINGS_GETCURRENTOWNER_SLOT(962), ACTIVECLANSETTINGS_GETREPLACEMENTOWNER_SLOT(7), ACTIVECLANSETTINGS_GETAFFINEDSLOT(557), ACTIVECLANSETTINGS_GETSORTEDAFFINEDSLOT(956), UNUSED_CLAN_OP(104), ACTIVECLANSETTINGS_GETAFFINEDJOINRUNEDAY(838), ACTIVECLANCHANNEL_FIND_LISTENED(884), ACTIVECLANCHANNEL_FIND_AFFINED(347), ACTIVECLANCHANNEL_GETCLANNAME(370), ACTIVECLANCHANNEL_GETRANKKICK(907), ACTIVECLANCHANNEL_GETRANKTALK(489), ACTIVECLANCHANNEL_GETUSERCOUNT(399), ACTIVECLANCHANNEL_GETUSERDISPLAYNAME(444), ACTIVECLANCHANNEL_GETUSERRANK(673), ACTIVECLANCHANNEL_GETUSERWORLD(23), ACTIVECLANCHANNEL_KICKUSER(350), ACTIVECLANCHANNEL_GETUSERSLOT(897), ACTIVECLANCHANNEL_GETSORTEDUSERSLOT(5), CLAN_VARS_ENABLED(559), STOCKMARKET_GETOFFERTYPE(414), STOCKMARKET_GETOFFERITEM(602), STOCKMARKET_GETOFFERPRICE(575), STOCKMARKET_GETOFFERCOUNT(27), STOCKMARKET_GETOFFERCOMPLETEDCOUNT(480), STOCKMARKET_GETOFFERCOMPLETEDGOLD(687), STOCKMARKET_ISOFFEREMPTY(650), STOCKMARKET_ISOFFERSTABLE(733), STOCKMARKET_ISOFFERFINISHED(984), STOCKMARKET_ISOFFERADDING(361), ADD(279), SUBTRACT(130), MULTIPLY(367), DIVIDE(56), RANDOM(675), RANDOM_INCLUSIVE(851), INTERPOLATE(190), ADD_PERCENT(890), SET_BIT(119), CLEAR_BIT(873), BIT_FLAGGED(278), MODULO(178), POW(645), POW_INVERSE(776), BIT_AND(199), BIT_OR(474), MIN(538), MAX(750), SCALE(277), RANDOM_SOUND_PITCH(729), HSVTORGB(586), BIT_NOT(534), APPEND_NUM(310), APPEND(286), APPEND_SIGNNUM(573), GET_COL_TAG(874), LOWERCASE(556), FROMDATE(618), TEXT_GENDER(709), TOSTRING(688), COMPARE(810), PARAHEIGHT(469), PARAWIDTH(43), TEXT_SWITCH(15), ESCAPE(49), APPEND_CHAR(701), CHAR_ISPRINTABLE(638), CHAR_ISALPHANUMERIC(150), CHAR_ISALPHA(801), CHAR_ISNUMERIC(934), STRING_LENGTH(247), SUBSTRING(108), REMOVETAGS(41), STRING_INDEXOF_CHAR(593), STRING_INDEXOF_STRING(844), CHAR_TOLOWERCASE(977), CHAR_TOUPPERCASE(153), TOSTRING_LOCALISED(280), STRINGWIDTH(459), FORMAT_DATETIME_FROM_MINUTES(339), CLANFORUMQFC_TOSTRING(454), ITEM_NAME(385), ITEM_OP(128), ITEM_IOP(949), ITEM_COST(89), ITEM_STACKABLE(905), ITEM_CERT(94), ITEM_UNCERT(313), ITEM_WEARPOS(22), ITEM_WEARPOS2(756), ITEM_WEARPOS3(384), ITEM_MEMBERS(822), ITEM_PARAM(120), OC_ICURSOR(45), ITEM_FIND(800), ITEM_FINDNEXT(623), OC_FINDRESTART(146), ITEM_MULTISTACKSIZE(249), ITEM_FIND_PARAMINT(754), ITEM_FIND_PARAMSTR(264), ITEM_MINIMENU_COLOUR_OVERRIDDEN(481), ITEM_MINIMENU_COLOUR(213), NPC_PARAM(425), OBJECT_PARAM(935), STRUCT_PARAM(594), ANIMATION_PARAM(404), BAS_GETANIM_READY(456), UNUSED_LOGIN_GLOBAL_BOOL(643), UNUSED_PACKET_SEND_STRING(990), UNUSED_PACKET_SET_GLOBAL_BYTE(777), CHAT_GETFILTER_PUBLIC(860), CHAT_SETFILTER(424), CHAT_SENDABUSEREPORT(257), instr6560(231), instr6739(681), instr6562(792), instr6563(118), instr6010(134), instr6211(743), instr6189(789), instr6624(622), instr6565(335), CHAT_PLAYERNAME(292), CHAT_GETFILTER_TRADE(839), instr6225(961), instr6572(482), instr6573(462), instr6574(309), instr6682(327), instr6249(272), instr6577(867), instr6578(927), instr6202(946), instr6030(988), instr6581(10), instr6425(604), instr6583(328), instr6584(958), instr6069(661), instr6586(187), instr6587(329), instr6588(909), instr6368(922), instr6590(713), instr6591(994), instr6592(208), instr6449(188), instr6594(795), instr6595(324), instr6596(109), instr6597(217), instr6598(349), instr6599(711), instr6613(830), instr6601(227), instr6602(285), instr6603(663), instr6233(290), instr6716(759), instr6606(334), instr6607(386), instr6608(731), instr6308(84), instr6610(397), instr6611(726), instr6612(16), instr6849(560), instr6614(405), instr6615(306), instr6616(788), instr6617(674), instr6090(441), instr6074(975), instr6620(923), instr6621(676), instr6439(410), instr6685(823), instr6638(228), instr6212(603), instr5966(260), instr6206(970), instr6628(641), instr6238(475), instr6630(969), instr6631(662), instr6632(288), instr6633(74), instr6634(901), instr6582(35), instr6671(775), instr6637(514), instr6818(210), instr6639(785), instr6488(175), instr6704(141), instr6404(596), instr6643(691), instr6644(297), instr6645(818), instr6406(617), instr6647(649), instr6648(577), instr6649(234), instr6650(567), instr6651(46), instr6652(595), instr6653(716), instr6654(951), instr6655(355), instr6656(318), instr6657(6), instr6658(431), instr6666(110), instr6660(65), instr6661(61), instr6866(565), instr6416(477), instr6410(672), GETCLIPBOARD(853), instr6780(964), instr6667(343), instr6668(359), CHECK_JAVA_VERSION(826), IS_GAMESCREEN_STATE(1004), instr6923(973), instr6672(400), instr6673(435), instr6451(521), instr6675(570), instr6162(99), instr6677(107), instr6678(940), instr6679(144), instr6456(493), instr6681(161), instr6663(893), instr6108(868), instr6684(483), instr6823(8), instr6686(155), instr6331(931), instr6627(722), instr6236(396), instr6013(365), instr6122(151), instr6692(831), instr6204(273), instr6694(171), SEND_VERIFY_EMAIL_PACKET(654), SEND_SIGNUP_FORM_PACKET(686), instr6697(362), instr6698(684), instr6699(1003), instr6700(9), instr6323(92), instr6702(742), instr6703(498), instr6774(551), instr6641(182), instr6305(422), instr6707(19), instr6623(242), instr6709(945), instr6710(447), instr6711(391), instr6712(569), instr6642(885), instr6714(666), instr6576(875), instr6101(44), instr6717(509), instr6718(869), instr6719(506), instr6720(917), instr6721(357), instr6722(849), instr6609(484), instr6724(372), instr6725(537), instr6726(71), instr6727(226), instr6860(270), DETAIL_LIGHTDETAIL_HIGH(281), DETAIL_WATERDETAIL_HIGH(232), instr6731(685), instr6674(269), DETAIL_STEREO(383), DETAIL_SOUNDVOL(358), DETAIL_MUSICVOL(276), DETAIL_BGSOUNDVOL(417), DETAIL_REMOVEROOFS_OPTION_OVERRIDE(992), DETAIL_PARTICLES(703), DETAIL_ANTIALIASING_DEFAULT(380), DETAIL_BUILDAREA(376), DETAIL_BLOOM(564), instr6742(181), instr6743(553), instr6744(464), instr6745(348), instr6922(261), instr6747(90), instr6748(218), instr6570(568), instr6750(632), instr6629(455), instr6752(817), instr6948(332), instr6754(848), instr6285(983), instr6756(268), instr6688(254), instr6489(585), instr6759(646), instr6785(390), instr6761(891), DETAILGET_WATERDETAIL_HIGH(487), instr6060(193), instr6938(782), instr6755(26), instr6766(828), instr6767(942), instr6768(919), instr5975(712), instr6770(458), instr6605(582), instr6640(752), instr6773(387), instr6925(794), instr5954(419), instr6600(725), instr6777(734), instr6778(804), instr6286(418), instr6400(30), instr6781(714), instr6301(971), instr6783(353), instr6784(42), instr6941(132), instr6786(240), instr6775(737), instr6097(423), instr6789(581), instr6790(607), instr6764(745), instr6792(47), instr6141(936), instr6486(403), instr5988(283), instr6365(55), instr6797(519), instr6798(636), instr6799(793), instr6800(877), instr6821(17), instr6802(256), instr6803(233), instr6227(212), instr6829(915), instr6806(239), instr6807(960), instr6808(296), instr6809(658), WORLDLIST_PINGWORLDS(678), instr6589(303), IF_DEBUG_GETOPENIFCOUNT(271), IF_DEBUG_GETOPENIFID(342), IF_DEBUG_GETNAME(738), IF_DEBUG_GETCOMCOUNT(136), IF_DEBUG_GETCOMNAME(40), IF_DEBUG_GETSERVERTRIGGERS(307), instr6386(429), instr6659(305), instr6794(653), instr6278(561), instr6890(294), instr6350(819), instr6824(251), instr6825(31), instr6826(778), instr6827(266), instr6828(906), instr6920(445), instr5955(437), MEC_TEXT(985), MEC_SPRITE(631), MEC_TEXTSIZE(757), MEC_CATEGORY(976), MEC_PARAM(230), USERDETAIL_QUICKCHAT(201), USERDETAIL_LOBBY_MEMBERSHIP(148), USERDETAIL_LOBBY_RECOVERYDAY(379), USERDETAIL_LOBBY_UNREADMESSAGES(241), USERDETAIL_LOBBY_LASTLOGINDAY(236), USERDETAIL_LOBBY_LASTLOGINADDRESS(78), USERDETAIL_LOBBY_EMAILSTATUS(54), USERDETAIL_LOBBY_CCEXPIRY(679), USERDETAIL_LOBBY_GRACEEXPIRY(522), USERDETAIL_LOBBY_DOBREQUESTED(769), USERDETAIL_DOB(407), USERDETAIL_LOBBY_MEMBERSSTATS(253), USERDETAIL_LOBBY_PLAYAGE(393), USERDETAIL_LOBBY_JCOINS_BALANCE(887), USERDETAIL_LOBBY_LOYALTY_ENABLED(265), USERDETAIL_LOBBY_LOYALTY_BALANCE(375), instr6852(1005), AUTOSETUP_SETHIGH(398), AUTOSETUP_SETMEDIUM(837), AUTOSETUP_SETLOW(225), AUTOSETUP_SETMIN(955), instr6857(312), instr6858(773), instr6859(952), instr6046(174), instr6861(88), instr6862(762), instr6863(548), instr6838(766), instr6680(507), instr6476(576), instr6867(106), instr6868(420), instr6869(337), instr6058(63), DETAILCANMOD_GROUNDDECOR(761), DETAILCANMOD_CHARSHADOWS(129), DETAILCANMOD_SPOTSHADOWS(640), DETAILCANMOD_WATERDETAIL(635), DETAILCANMOD_ANTIALIASING(621), DETAILCANMOD_PARTICLES(803), DETAILCANMOD_BUILDAREA(221), DETAILCANMOD_BLOOM(610), DETAILCANMOD_GROUNDBLENDING(504), DETAILCANMOD_TEXTURING(938), DETAILCANMOD_MAXSCREENSIZE(446), DETAILCANMOD_FOG(563), DETAILCANMOD_TOOLKIT_DEFAULT(258), DETAILCANMOD_TOOLKIT(850), DETAILCANMOD_SKYBOXES(821), DETAILCANSET_GROUNDDECOR(114), DETAILCANSET_CHARSHADOWS(1001), DETAILCANSET_SPOTSHADOWS(58), DETAILCANSET_WATERDETAIL(442), DETAILCANSET_ANTIALIASING(900), DETAILCANSET_PARTICLES(876), DETAILCANSET_BUILDAREA(571), DETAILCANSET_BLOOM(501), DETAILCANSET_GROUNDBLENDING(865), DETAILCANSET_TEXTURING(33), DETAILCANSET_MAXSCREENSIZE(921), DETAILCANSET_FOG(409), DETAILCANSET_TOOLKIT_DEFAULT(779), DETAILCANSET_RENDERER(616), DETAILCANSET_SKYBOXES(53), instr6388(430), instr6902(282), GET_ENTITY_SAY(378), GET_DISPLAYNAME_WITHEXTRAS(812), instr6905(740), instr6906(29), GET_NPC_NAME(660), instr6908(165), GET_ENTITY_SCREEN_POSITION(330), IF_GET_GAMESCREEN(811), instr6911(669), GET_NPC_STAT(248), IS_NPC_ACTIVE(634), IS_NPC_VISIBLE(322), IS_TARGETED_ENTITY(852), IF_DELETEALL(986), NPC_TYPE(974), GET_OBJECT_SCREEN_POSITION(439), GET_ITEM_SCREEN_POSITION(450), GET_OBJECT_OVERLAY_HEIGHT(433), GET_ITEM_OVERLAY_HEIGHT(295), GET_OBJECT_BOUNDING_BOX(69), GET_ITEM_BOUNDING_BOX(517), GET_ENTITY_BOUNDING_BOX(95), BUG_REPORT(558), ARRAY_SORT(87), QUEST_GETNAME(791), QUEST_GETSORTNAME(889), QUEST_TYPE(842), QUEST_GETDIFFICULTY(468), QUEST_GETMEMBERS(863), QUEST_POINTS(608), QUEST_QUESTREQ_COUNT(14), QUEST_QUESTREQ(642), QUEST_QUESTREQ_MET(856), QUEST_POINTSREQ(846), QUEST_POINTSREQ_MET(967), QUEST_STATREQ_COUNT(102), QUEST_STATREQ_STAT(614), QUEST_STATREQ_LEVEL(39), QUEST_STATREQ_MET(592), QUEST_VARPREQ_COUNT(698), QUEST_VARPREQ_DESC(302), QUEST_VARPREQ_MET(299), QUEST_VARBITREQ_COUNT(11), QUEST_VARBITREQ_DESC(835), QUEST_VARBITREQ_MET(858), QUEST_ALLREQMET(152), QUEST_STARTED(12), QUEST_FINISHED(963), QUEST_PARAM(62); private static final HashMap OPCODES = new HashMap<>(); static { for (CS2Instruction op : CS2Instruction.values()) { OPCODES.put(op.opcode, op); } } public final int opcode; public final boolean hasIntConstant; CS2Instruction(int opcode) { this(opcode, false); } CS2Instruction(int opcode, boolean hasIntConstant) { this.opcode = opcode; this.hasIntConstant = hasIntConstant; } public static CS2Instruction getByOpcode(int id) { return OPCODES.get(id); } public int getOpcode() { return opcode; } public boolean hasIntConstant() { return hasIntConstant; } } " " package com.rs.cache.loaders.cs2; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.concurrent.ConcurrentHashMap; import com.rs.cache.ArchiveType; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.lib.io.InputStream; import com.rs.lib.util.Utils; public final class CS2ParamDefs { public int id; public int defaultInt; public boolean autoDisable = true; public char charVal; public String defaultString; public CS2Type type; private static final ConcurrentHashMap maps = new ConcurrentHashMap(); public static void main(String[] args) throws IOException { //Cache.init(); File file = new File(""params.txt""); if (file.exists()) file.delete(); else file.createNewFile(); BufferedWriter writer = new BufferedWriter(new FileWriter(file)); writer.append(""//Version = 727\n""); writer.flush(); for (int i = 0; i < Cache.STORE.getIndex(IndexType.CONFIG).getValidFilesCount(ArchiveType.PARAMS.getId()); i++) { CS2ParamDefs param = getParams(i); if (param == null) continue; writer.append(i + "" - '""+param.charVal+""'->"" + param.type + "", ""+param.autoDisable+"" int: "" + param.defaultInt + "" str:\"""" + param.defaultString + ""\""""); writer.newLine(); writer.flush(); } writer.close(); } public static final CS2ParamDefs getParams(int paramId) { CS2ParamDefs param = maps.get(paramId); if (param != null) return param; byte[] data = Cache.STORE.getIndex(IndexType.CONFIG).getFile(ArchiveType.PARAMS.getId(), paramId); param = new CS2ParamDefs(); param.id = paramId; if (data != null) param.readValueLoop(new InputStream(data)); maps.put(paramId, param); return param; } private void readValueLoop(InputStream stream) { for (;;) { int opcode = stream.readUnsignedByte(); if (opcode == 0) break; readValues(stream, opcode); } } private void readValues(InputStream stream, int opcode) { if (opcode == 1) { charVal = Utils.cp1252ToChar((byte) stream.readByte()); type = CS2Type.forJagexDesc(charVal); } else if (opcode == 2) { defaultInt = stream.readInt(); } else if (opcode == 4) { autoDisable = false; } else if (opcode == 5) { defaultString = stream.readString(); } } @Override public String toString() { StringBuilder result = new StringBuilder(); String newLine = System.getProperty(""line.separator""); result.append(this.getClass().getName()); result.append("" {""); result.append(newLine); // determine fields declared in this class only (no fields of // superclass) Field[] fields = this.getClass().getDeclaredFields(); // print field names paired with their values for (Field field : fields) { if (Modifier.isStatic(field.getModifiers())) continue; result.append("" ""); try { result.append(field.getType().getCanonicalName() + "" "" + field.getName() + "": ""); result.append(Utils.getFieldValue(this, field)); } catch (Throwable ex) { System.out.println(ex); } result.append(newLine); } result.append(""}""); return result.toString(); } } " " package com.rs.cache.loaders.cs2; import java.lang.reflect.Field; import java.lang.SuppressWarnings; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.HashMap; import com.rs.cache.IndexType; import com.rs.cache.Store; import com.rs.lib.io.InputStream; import com.rs.lib.io.OutputStream; import com.rs.lib.util.Utils; public class CS2Script { public String[] stringOpValues; public String name; public CS2Instruction[] operations; public CS2Type[] arguments; public int[] operationOpcodes; public int[] intOpValues; public long[] longOpValues; public int longArgsCount; public int intLocalsCount; public int stringLocalsCount; public int intArgsCount; public int stringArgsCount; public int longLocalsCount; public HashMap[] switchMaps; public int id; public CS2Script(InputStream buffer) { int instructionLength = decodeHeader(buffer); int opCount = 0; while (buffer.getOffset() < instructionLength) { CS2Instruction op = getOpcode(buffer); decodeInstruction(buffer, opCount, op); opCount++; } postDecode(); } CS2Instruction getOpcode(InputStream buffer) { int opcode = buffer.readUnsignedShort(); if (opcode < 0 || opcode >= CS2Instruction.values().length) { throw new RuntimeException(""Invalid operation code: "" + opcode); } CS2Instruction op = CS2Instruction.getByOpcode(opcode); return op; } public Object getParam(int i) { CS2Instruction op = operations[i]; if (op == CS2Instruction.PUSH_LONG) { return longOpValues[i]; } if (op == CS2Instruction.PUSH_STRING) { return ""\""""+stringOpValues[i]+""\""""; } if (op.hasIntConstant()) { return intOpValues[i]; } return null; } @SuppressWarnings(""unchecked"") private int decodeHeader(InputStream buffer) { buffer.setOffset(buffer.getLength() - 2); int switchBlockSize = buffer.readUnsignedShort(); int instructionLength = buffer.getBuffer().length - 2 - switchBlockSize - 16; buffer.setOffset(instructionLength); int codeSize = buffer.readInt(); intLocalsCount = buffer.readUnsignedShort(); stringLocalsCount = buffer.readUnsignedShort(); longLocalsCount = buffer.readUnsignedShort(); intArgsCount = buffer.readUnsignedShort(); stringArgsCount = buffer.readUnsignedShort(); longArgsCount = buffer.readUnsignedShort(); int switchesCount = buffer.readUnsignedByte(); if (switchesCount > 0) { switchMaps = new HashMap[switchesCount]; for (int i = 0; i < switchesCount; i++) { int numCases = buffer.readUnsignedShort(); switchMaps[i] = new HashMap(numCases); while (numCases-- > 0) { switchMaps[i].put(buffer.readInt(), buffer.readInt()); } } } buffer.setOffset(0); name = buffer.readNullString(); operations = new CS2Instruction[codeSize]; operationOpcodes = new int[codeSize]; return instructionLength; } private void decodeInstruction(InputStream buffer, int opIndex, CS2Instruction operation) { int opLength = operations.length; if (operation == CS2Instruction.PUSH_STRING) { if (stringOpValues == null) stringOpValues = new String[opLength]; stringOpValues[opIndex] = buffer.readString(); } else if (CS2Instruction.PUSH_LONG == operation) { if (null == longOpValues) longOpValues = new long[opLength]; longOpValues[opIndex] = buffer.readLong(); } else { if (null == intOpValues) intOpValues = new int[opLength]; if (operation.hasIntConstant()) intOpValues[opIndex] = buffer.readInt(); else intOpValues[opIndex] = buffer.readUnsignedByte(); } operations[opIndex] = operation; operationOpcodes[opIndex] = operation.getOpcode(); } public void postDecode() { arguments = new CS2Type[intArgsCount + stringArgsCount + longArgsCount]; int write = 0; for (int i = 0; i < intArgsCount; i++) arguments[write++] = CS2Type.INT; for (int i = 0; i < stringArgsCount; i++) arguments[write++] = CS2Type.STRING; for (int i = 0; i < longArgsCount; i++) arguments[write++] = CS2Type.LONG; } public void write(Store store) { store.getIndex(IndexType.CS2_SCRIPTS).putArchive(id, encode()); } public byte[] encode() { OutputStream out = new OutputStream(); if (name == null) { out.writeByte(0); } else out.writeString(name); for (int i = 0; i < operations.length; i++) { CS2Instruction op = operations[i]; if(op == null) continue; out.writeShort(op.getOpcode()); if (op == CS2Instruction.PUSH_STRING) { out.writeString((String) stringOpValues[i]); } else if (CS2Instruction.PUSH_LONG == op) { out.writeLong(longOpValues[i]); } else { if (op.hasIntConstant()) { out.writeInt(intOpValues[i]); } else { out.writeByte(intOpValues[i]); } } } out.writeInt(operations.length); out.writeShort(intLocalsCount); out.writeShort(stringLocalsCount); out.writeShort(longLocalsCount); out.writeShort(intArgsCount); out.writeShort(stringArgsCount); out.writeShort(longArgsCount); OutputStream switchBlock = new OutputStream(); if (switchMaps == null) { switchBlock.writeByte(0); } else { switchBlock.writeByte(switchMaps.length); if (switchMaps.length > 0) { for (int i = 0; i < switchMaps.length; i++) { HashMap map = switchMaps[i]; switchBlock.writeShort(map.size()); for (int key : map.keySet()) { switchBlock.writeInt(key); switchBlock.writeInt(map.get(key)); } } } } byte[] switchBytes = switchBlock.toByteArray(); out.writeBytes(switchBytes); out.writeShort(switchBytes.length); return out.toByteArray(); } public String getIntBytes(int i) { return ((byte) (i >> 24))+"" ""+((byte) (i >> 16))+"" ""+((byte) (i >> 8))+"" ""+((byte) i); } public String getShortBytes(int i) { return ((byte) (i >> 8))+"" ""+((byte) i); } @Override public boolean equals(Object other) { if (!(other instanceof CS2Script)) return false; CS2Script script = (CS2Script) other; if (script.operationOpcodes != null) { if (this.operationOpcodes == null) { System.out.println(""Mismatching operation opcodes.""); return false; } if (!Arrays.equals(script.operationOpcodes, this.operationOpcodes)) { System.out.println(""Mismatching operation opcodes""); return false; } } if (script.intOpValues != null) { if (this.intOpValues == null) { System.out.println(""int op values null shouldn't be""); return false; } if (!Arrays.equals(script.intOpValues, this.intOpValues)) { System.out.println(""Mismatching int op values""); return false; } } if (script.longOpValues != null) { if (this.longOpValues == null) { System.out.println(""long op values null shouldn't be""); return false; } if (!Arrays.equals(script.longOpValues, this.longOpValues)) { System.out.println(""Mismatching long op values""); return false; } } if (script.stringOpValues != null) { if (this.stringOpValues == null) { System.out.println(""String op values null shouldn't be""); return false; } if (!Arrays.equals(script.stringOpValues, this.stringOpValues)) { System.out.println(""Mismatching string op values""); System.out.println(Arrays.toString(this.stringOpValues)); System.out.println(Arrays.toString(script.stringOpValues)); return false; } } if (script.switchMaps != null) { if (this.switchMaps == null) { System.out.println(""Switchmap null shouldn't be""); return false; } if (this.switchMaps.length != script.switchMaps.length) { System.out.println(""Mismatching switch map lengths""); return false; } for (int i = 0;i < this.switchMaps.length;i++) { HashMap map1 = this.switchMaps[i]; HashMap map2 = script.switchMaps[i]; for (int key : map1.keySet()) { if (map2.get(key).intValue() != map1.get(key).intValue()) { System.out.println(""Mismatching map keys: "" + map1.get(key) + "" - "" + map2.get(key)); return false; } } } } return true; } @Override public String toString() { StringBuilder result = new StringBuilder(); String newLine = System.getProperty(""line.separator""); result.append(this.getClass().getName()); result.append("" {""); result.append(newLine); // determine fields declared in this class only (no fields of // superclass) Field[] fields = this.getClass().getDeclaredFields(); // print field names paired with their values for (Field field : fields) { if (Modifier.isStatic(field.getModifiers())) continue; result.append("" ""); try { result.append(field.getType().getCanonicalName() + "" "" + field.getName() + "": ""); result.append(Utils.getFieldValue(this, field)); } catch (Throwable ex) { System.out.println(ex); } result.append(newLine); } result.append(""}""); return result.toString(); } public String getOpString(int i) { String str = ""CS2Instruction.""+operations[i] + "", //(""; if (intOpValues != null && (stringOpValues == null || stringOpValues[i] == null)) { str += intOpValues[i]; } if (longOpValues != null) { str += longOpValues[i]; } if (stringOpValues != null) { str += (stringOpValues[i] != null ? stringOpValues[i] : """"); } return str + "")""; } public void setInstruction(int index, CS2Instruction instr, int intParam) { operations[index] = instr; intOpValues[index] = intParam; } } " " package com.rs.cache.loaders.cs2; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.lang.SuppressWarnings; public class CS2Type { public static Map attrTypes = new HashMap<>(); private int intStackSize; private int stringStackSize; private int longStackSize; private String name; public char charDesc; private boolean structure; //BASE TYPES public static CS2Type VOID = new CS2Type(0, 0, 0, ""void"", '\0'); public static CS2Type BOOLEAN = new CS2Type(1, 0, 0, ""boolean"", '1'); public static CS2Type INT = new CS2Type(1, 0, 0, ""int"", 'i'); public static CS2Type FONTMETRICS = new CS2Type(1, 0, 0, ""FontMetrics"", 'f'); public static CS2Type SPRITE = new CS2Type(1, 0, 0, ""Sprite"", 'd'); public static CS2Type MODEL = new CS2Type(1, 0, 0, ""Model"", 'm'); public static CS2Type MIDI = new CS2Type(1, 0, 0, ""Midi"", 'M'); public static CS2Type ENUM = new CS2Type(1, 0, 0, ""Enum"", 'g'); public static CS2Type STRUCT = new CS2Type(1, 0, 0, ""Struct"", 'J'); public static CS2Type CHAR = new CS2Type(1, 0, 0, ""char"", 'z'); public static CS2Type CONTAINER = new CS2Type(1, 0, 0, ""Container"", 'v'); public static CS2Type STRING = new CS2Type(0, 1, 0, ""string"", 's'); public static CS2Type LONG = new CS2Type(0, 0, 1, ""long"", (char) 0xA7); public static CS2Type ICOMPONENT = new CS2Type(1, 0, 0, ""IComponent"", 'I'); public static CS2Type LOCATION = new CS2Type(1, 0, 0, ""Location"", 'c'); public static CS2Type ITEM = new CS2Type(1, 0, 0, ""Item"", 'o'); // public static CS2Type ITEM_NAMED = new CS2Type(1, 0, 0, ""Item"", 'O', false); public static CS2Type COLOR = new CS2Type(1, 0, 0, ""Color"", 'i'); //Not a real type, but helps us know where we need to convert int to hex notation public static CS2Type IDENTIKIT = new CS2Type(1, 0, 0, ""Identikit"", 'K'); public static CS2Type ANIM = new CS2Type(1, 0, 0, ""Animation"", 'A'); public static CS2Type MAPID = new CS2Type(1, 0, 0, ""Map"", '`'); public static CS2Type GRAPHIC = new CS2Type(1, 0, 0, ""SpotAnim"", 't'); public static CS2Type SKILL = new CS2Type(1, 0, 0, ""Skill"", 'S'); public static CS2Type NPCDEF = new CS2Type(1, 0, 0, ""NpcDef"", 'n'); public static CS2Type QCPHRASE = new CS2Type(1, 0, 0, ""QcPhrase"", 'e'); public static CS2Type CHATCAT = new CS2Type(1, 0, 0, ""QcCat"", 'k'); public static CS2Type TEXTURE = new CS2Type(1, 0, 0, ""Texture"", 'x'); public static CS2Type STANCE = new CS2Type(1, 0, 0, ""Stance"", (char) 0x20AC); public static CS2Type SPELL = new CS2Type(1, 0, 0, ""Spell"", '@'); //target cursor? public static CS2Type CATEGORY = new CS2Type(1, 0, 0, ""Category"", 'y'); public static CS2Type SOUNDEFFECT = new CS2Type(1, 0, 0, ""SoundEff"", (char) 0xAB); // public static CS2Type VARINT = new CS2Type(0, 0, 0, ""int..."", 'Y'); //'Trigger/varargs' public static CS2Type CALLBACK = new CS2Type(0, 0, 0, ""Callback"", '\0'); //not real type public static CS2Type UNKNOWN = new CS2Type(0, 0, 0, ""??"", '\0'); public static CS2Type[] TYPE_LIST = new CS2Type[]{VOID, CALLBACK, BOOLEAN, INT, FONTMETRICS, SPRITE, MODEL, MIDI, LOCATION, CHAR, STRING, LONG, UNKNOWN, ICOMPONENT, ITEM, COLOR, CONTAINER, ENUM, STRUCT, IDENTIKIT, ANIM, MAPID, GRAPHIC, SKILL, NPCDEF, QCPHRASE, CHATCAT, TEXTURE, STANCE, SPELL, CATEGORY, SOUNDEFFECT}; private static List cache = new ArrayList(); //TODO: Refactor this public CS2Type(int iss, int sss, int lss, String name, char c) { this.intStackSize = iss; this.stringStackSize = sss; this.longStackSize = lss; this.name = name; this.charDesc = c; this.structure = false; composite.add(this); } public List composite = new ArrayList<>(); private CS2Type(List struct) { for (CS2Type t : struct) { this.intStackSize += t.intStackSize; this.stringStackSize += t.stringStackSize; this.longStackSize += t.longStackSize; composite.addAll(t.composite); } structure = true; name = """"; cache.add(this); } public static CS2Type of(List typeList) { if (typeList.size() == 1) { return typeList.get(0); } find: for (CS2Type other : cache) { if (other.composite.size() != typeList.size()) { continue; } for (int i = 0; i < other.composite.size(); i++) { if (other.composite.get(i) != typeList.get(i)) { continue find; } } return other; } return new CS2Type(typeList); } public boolean isStructure() { return structure; } public String getName() { return name; } @Override public int hashCode() { int stackHash = structure ? (1 << 9) : 0; stackHash |= intStackSize & 0x7; stackHash |= (stringStackSize & 0x7) << 3; stackHash |= (longStackSize & 0x7) << 6; int nameHash = (name.length() & 0x7) | (name.length() << 3); for (int i = 0; i < name.length(); i++) { char c = name.charAt(i); if ((c & 0x1) != 0) nameHash += nameHash + (nameHash / c); else nameHash += nameHash - (nameHash * c); } return stackHash | (nameHash << 11); } public boolean equals(CS2Type other) { if (this.structure != other.structure) { return false; } if (this.composite.size() != other.composite.size()) { return false; } for (int i = 0; i < composite.size(); i++) { if (composite.get(i) != other.composite.get(i)) { return false; } } return true; } public boolean isCompatible(CS2Type other) { //TODO: Order should be same too, but only used for simple types? return other == CS2Type.UNKNOWN || (intStackSize == other.intStackSize && stringStackSize == other.stringStackSize && longStackSize == other.longStackSize); } public static CS2Type forDesc(String desc) { for (int i = 0; i < TYPE_LIST.length; i++) if (desc.equals(TYPE_LIST[i].toString())) return TYPE_LIST[i]; if (!desc.contains(""{"")) return null; String[] spl = desc.split(""\\{""); @SuppressWarnings(""unused"") String name = spl[0]; String stackDesc = spl[1].substring(0, spl[1].length() - 1); String[] stackSpl = stackDesc.split(""\\,""); List composite = new LinkedList<>(); for (String s : stackSpl) { composite.add(forDesc(s.trim())); } return CS2Type.of(composite); } public static CS2Type forJagexDesc(char desc) { switch (desc) { case '\0': return VOID; case 0xA7: return LONG; case 'i': return INT; case 'z': return CHAR; case 's': return STRING; case '1': return BOOLEAN; case 'o': case 'O': //One of these is actually NAMED_ITEM? return ITEM; case 'A': return ANIM; case 'S': return SKILL; case 't': return GRAPHIC; case 'c': return LOCATION; case 'n': return NPCDEF; case 'J': return STRUCT; case 'g': return ENUM; case 'f': return FONTMETRICS; case 'd': return SPRITE; case 'm': return MODEL; case 'M': return MIDI; case 'K': return IDENTIKIT; case 'v': return CONTAINER; case 'I': return ICOMPONENT; case 'e': return QCPHRASE; case 'k': return CHATCAT; case 0x20AC: return STANCE; case 'x': return TEXTURE; case '@': return SPELL; case '`': return MAPID; case 'y': return CATEGORY; case 0xAB: return SOUNDEFFECT; // case 'P': // return SYNTH; //'l' LOC (object) //More int based types... default: return INT; } } @Override public String toString() { if (structure) { StringBuilder s = new StringBuilder(); boolean first = true; for (CS2Type t : composite) { if (!first) { s.append("", ""); } first = false; s.append(t); } return s.toString(); } else { return this.name; } } } " " package com.rs.cache.loaders.cutscenes; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import com.rs.lib.game.WorldTile; import com.rs.lib.io.InputStream; import com.rs.lib.util.Utils; public class CutsceneArea { public WorldTile mapBase; public int regionId; public int width; public int length; public int anInt7481; public int anInt7480; public int anInt7483; public int anInt7486; CutsceneArea(InputStream buffer) { int position = buffer.readInt(); this.mapBase = WorldTile.of(position >>> 14 & 0x3fff, position & 0x3fff, position >>> 28); this.width = buffer.readUnsignedByte(); this.length = buffer.readUnsignedByte(); this.anInt7481 = buffer.readUnsignedByte(); this.anInt7480 = buffer.readUnsignedByte(); this.anInt7483 = buffer.readUnsignedByte(); this.anInt7486 = buffer.readUnsignedByte(); } @Override public String toString() { StringBuilder result = new StringBuilder(); String newLine = System.getProperty(""line.separator""); result.append(this.getClass().getName()); result.append("" {""); result.append(newLine); // determine fields declared in this class only (no fields of // superclass) Field[] fields = this.getClass().getDeclaredFields(); // print field names paired with their values for (Field field : fields) { if (Modifier.isStatic(field.getModifiers())) continue; result.append("" ""); try { result.append(field.getType().getCanonicalName() + "" "" + field.getName() + "": ""); result.append(Utils.getFieldValue(this, field)); } catch (Throwable ex) { System.out.println(ex); } result.append(newLine); } result.append(""}""); return result.toString(); } } " " package com.rs.cache.loaders.cutscenes; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import com.rs.lib.io.InputStream; import com.rs.lib.util.Utils; public class CutsceneCameraMovement { int[] anIntArray763; int[] anIntArray760; int[] anIntArray762; int[] anIntArray759; int[] anIntArray761; int[] anIntArray764; int[] anIntArray765; CutsceneCameraMovement(InputStream buffer) { int len = buffer.readUnsignedSmart(); this.anIntArray763 = new int[len]; this.anIntArray760 = new int[len]; this.anIntArray762 = new int[len]; this.anIntArray759 = new int[len]; this.anIntArray761 = new int[len]; this.anIntArray764 = new int[len]; this.anIntArray765 = new int[len]; for (int i = 0; i < len; i++) { this.anIntArray763[i] = buffer.readUnsignedShort() - 5120; this.anIntArray762[i] = buffer.readUnsignedShort() - 5120; this.anIntArray760[i] = buffer.readShort(); this.anIntArray761[i] = buffer.readUnsignedShort() - 5120; this.anIntArray765[i] = buffer.readUnsignedShort() - 5120; this.anIntArray764[i] = buffer.readShort(); this.anIntArray759[i] = buffer.readShort(); } } @Override public String toString() { StringBuilder result = new StringBuilder(); String newLine = System.getProperty(""line.separator""); result.append(this.getClass().getName()); result.append("" {""); result.append(newLine); // determine fields declared in this class only (no fields of // superclass) Field[] fields = this.getClass().getDeclaredFields(); // print field names paired with their values for (Field field : fields) { if (Modifier.isStatic(field.getModifiers())) continue; result.append("" ""); try { result.append(field.getType().getCanonicalName() + "" "" + field.getName() + "": ""); result.append(Utils.getFieldValue(this, field)); } catch (Throwable ex) { System.out.println(ex); } result.append(newLine); } result.append(""}""); return result.toString(); } } " " package com.rs.cache.loaders.cutscenes; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.lib.io.InputStream; import com.rs.lib.util.Utils; public class CutsceneDefinitions { private static final HashMap CACHE = new HashMap<>(); public int id; public int anInt825; public int anInt824; public List areas = new ArrayList<>(); public List camMovements = new ArrayList<>(); public List entities = new ArrayList<>(); public List objects = new ArrayList<>(); public List movements = new ArrayList<>(); public static final CutsceneDefinitions getDefs(int id) { CutsceneDefinitions defs = CACHE.get(id); if (defs != null) return defs; byte[] data = Cache.STORE.getIndex(IndexType.CUTSCENES).getFile(id); defs = new CutsceneDefinitions(); defs.id = id; if (data != null) defs.decode(new InputStream(data)); CACHE.put(id, defs); return defs; } public static boolean cutsceneExists(int dent) { byte[] data = Cache.STORE.getIndex(IndexType.CUTSCENES).getFile(dent); if(data != null) return true; return false; } private void decode(InputStream buffer) { readValues(buffer); int len = buffer.readUnsignedByte(); for (int i = 0; i < len; i++) areas.add(new CutsceneArea(buffer)); len = buffer.readUnsignedSmart(); for (int i = 0; i < len; i++) camMovements.add(new CutsceneCameraMovement(buffer)); len = buffer.readUnsignedSmart(); for (int i = 0; i < len; i++) entities.add(new CutsceneEntity(buffer, i)); len = buffer.readUnsignedSmart(); for (int i = 0; i < len; i++) objects.add(new CutsceneObject(buffer)); len = buffer.readUnsignedSmart(); for (int i = 0; i < len; i++) movements.add(new CutsceneEntityMovement(buffer)); buffer.skip(buffer.getRemaining()); //TODO decode the other like.. 26 diff cutscene actions lmao } private void readValues(InputStream stream) { while (true) { int i = stream.readUnsignedByte(); switch (i) { case 0: anInt825 = stream.readUnsignedShort(); anInt824 = stream.readUnsignedShort(); break; case 255: return; } } } @Override public String toString() { StringBuilder result = new StringBuilder(); String newLine = System.getProperty(""line.separator""); result.append(this.getClass().getName()); result.append("" {""); result.append(newLine); // determine fields declared in this class only (no fields of // superclass) Field[] fields = this.getClass().getDeclaredFields(); // print field names paired with their values for (Field field : fields) { if (Modifier.isStatic(field.getModifiers())) continue; result.append("" ""); try { result.append(field.getType().getCanonicalName() + "" "" + field.getName() + "": ""); result.append(Utils.getFieldValue(this, field)); } catch (Throwable ex) { System.out.println(ex); } result.append(newLine); } result.append(""}""); return result.toString(); } } " " package com.rs.cache.loaders.cutscenes; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import com.rs.lib.io.InputStream; import com.rs.lib.util.Utils; public class CutsceneEntity { public int index; public int id; public String str; CutsceneEntity(InputStream buffer, int index) { this.index = index; int type = buffer.readUnsignedByte(); switch (type) { case 0: this.id = buffer.readBigSmart(); break; case 1: this.id = -1; break; default: this.id = -1; } str = buffer.readString(); } @Override public String toString() { StringBuilder result = new StringBuilder(); String newLine = System.getProperty(""line.separator""); result.append(this.getClass().getName()); result.append("" {""); result.append(newLine); // determine fields declared in this class only (no fields of // superclass) Field[] fields = this.getClass().getDeclaredFields(); // print field names paired with their values for (Field field : fields) { if (Modifier.isStatic(field.getModifiers())) continue; result.append("" ""); try { result.append(field.getType().getCanonicalName() + "" "" + field.getName() + "": ""); result.append(Utils.getFieldValue(this, field)); } catch (Throwable ex) { System.out.println(ex); } result.append(newLine); } result.append(""}""); return result.toString(); } } " " package com.rs.cache.loaders.cutscenes; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import com.rs.lib.io.InputStream; import com.rs.lib.util.Utils; public class CutsceneEntityMovement { int[] movementTypes; int[] movementCoordinates; CutsceneEntityMovement(InputStream buffer) { int len = buffer.readUnsignedSmart(); this.movementTypes = new int[len]; this.movementCoordinates = new int[len]; for (int i = 0; i < len; i++) { this.movementTypes[i] = buffer.readUnsignedByte(); int x = buffer.readUnsignedShort(); int y = buffer.readUnsignedShort(); this.movementCoordinates[i] = y + (x << 16); } } @Override public String toString() { StringBuilder result = new StringBuilder(); String newLine = System.getProperty(""line.separator""); result.append(this.getClass().getName()); result.append("" {""); result.append(newLine); // determine fields declared in this class only (no fields of // superclass) Field[] fields = this.getClass().getDeclaredFields(); // print field names paired with their values for (Field field : fields) { if (Modifier.isStatic(field.getModifiers())) continue; result.append("" ""); try { result.append(field.getType().getCanonicalName() + "" "" + field.getName() + "": ""); result.append(Utils.getFieldValue(this, field)); } catch (Throwable ex) { System.out.println(ex); } result.append(newLine); } result.append(""}""); return result.toString(); } } " " package com.rs.cache.loaders.cutscenes; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import com.rs.lib.io.InputStream; import com.rs.lib.util.Utils; public class CutsceneObject { int objectId; int type; CutsceneObject(InputStream rsbytebuffer_1) { this.objectId = rsbytebuffer_1.readBigSmart(); this.type = rsbytebuffer_1.readUnsignedByte(); } @Override public String toString() { StringBuilder result = new StringBuilder(); String newLine = System.getProperty(""line.separator""); result.append(this.getClass().getName()); result.append("" {""); result.append(newLine); // determine fields declared in this class only (no fields of // superclass) Field[] fields = this.getClass().getDeclaredFields(); // print field names paired with their values for (Field field : fields) { if (Modifier.isStatic(field.getModifiers())) continue; result.append("" ""); try { result.append(field.getType().getCanonicalName() + "" "" + field.getName() + "": ""); result.append(Utils.getFieldValue(this, field)); } catch (Throwable ex) { System.out.println(ex); } result.append(newLine); } result.append(""}""); return result.toString(); } } " " package com.rs.cache.loaders.interfaces; public enum ComponentType { CONTAINER(0), TYPE_1(1), TYPE_2(2), FIGURE(3), TEXT(4), SPRITE(5), MODEL(6), TYPE_7(7), TYPE_8(8), LINE(9); public static ComponentType forId(int id) { for (ComponentType t : ComponentType.values()) { if (t.id == id) return t; } return null; } private int id; private ComponentType(int id) { this.id = id; } }" " package com.rs.cache.loaders.interfaces; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.lang.SuppressWarnings; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.lib.io.InputStream; import com.rs.lib.util.Utils; public class IComponentDefinitions { private static IComponentDefinitions[][] COMPONENT_DEFINITIONS; private static IFEvents DEFAULT_EVENTS = new IFEvents(0, -1); @SuppressWarnings(""rawtypes"") public Hashtable aHashTable4823; public ComponentType type; public String name; public int contentType = 0; public int basePositionX = 0; public int basePositionY = 0; public int baseWidth = 0; public int baseHeight = 0; public byte aspectWidthType = 0; public byte aspectHeightType = 0; public byte aspectXType = 0; public byte aspectYType = 0; public int parent = -1; public boolean hidden = false; public int scrollWidth = 0; public int scrollHeight = 0; public boolean noClickThrough = false; public int spriteId = -1; public int angle2d = 0; public ModelType modelType = ModelType.RAW_MODEL; public int modelId; public boolean tiling = false; public int fontId = -1; public String text = """"; public int color = 0; public boolean alpha = false; public int transparency = 0; public int borderThickness = 0; public int anInt1324 = 0; public int anInt1358 = 0; public int textHorizontalAli = 0; public int textVerticalAli = 0; public int lineWidth = 1; public boolean hasOrigin; public boolean monospaced = true; public boolean filled = false; public byte[][] aByteArrayArray1366; public byte[][] aByteArrayArray1367; public int[] anIntArray1395; public int[] anIntArray1267; public String useOnName = """"; public boolean vFlip; public boolean shadow = false; public boolean lineDirection = false; public String[] optionNames; public boolean usesOrthogonal = false; public int multiline = 0; public int[] opCursors; public boolean hFlip; public String opName; public boolean aBool1345 = false; public boolean aBool1424; public int anInt1380; public int anInt1381; public int anInt1382; public String useOptionString = """"; public int originX = 0; public int originY = 0; public int spritePitch = 0; public int spriteRoll = 0; public int spriteYaw = 0; public int spriteScale = 100; public boolean clickMask = true; public int originZ = 0; public int animation = -1; public int targetOverCursor = -1; public int mouseOverCursor = -1; public IFEvents events = DEFAULT_EVENTS; public int aspectWidth = 0; public int targetLeaveCursor = -1; public Object[] onLoadScript; public Object[] onMouseHoverScript; public Object[] onMouseLeaveScript; public Object[] anObjectArray1396; public Object[] anObjectArray1400; public Object[] anObjectArray1397; public Object[] mouseLeaveScript; public Object[] anObjectArray1387; public Object[] anObjectArray1409; public Object[] params; public int aspectHeight = 0; public Object[] anObjectArray1393; public Object[] popupScript; public Object[] anObjectArray1386; public Object[] anObjectArray1319; public Object[] anObjectArray1302; public Object[] anObjectArray1389; public Object[] anObjectArray1451; public Object[] anObjectArray1394; public Object[] anObjectArray1412; public Object[] anObjectArray1403; public Object[] anObjectArray1405; public int[] varps; public int[] mouseLeaveArrayParam; public int[] anIntArray1402; public int[] anIntArray1315; public int[] anIntArray1406; public Object[] anObjectArray1413; public Object[] anObjectArray1292; public Object[] anObjectArray1415; public Object[] anObjectArray1416; public Object[] anObjectArray1383; public Object[] anObjectArray1419; public Object[] anObjectArray1361; public Object[] anObjectArray1421; public Object[] anObjectArray1346; public Object[] anObjectArray1353; public Object[] anObjectArray1271; public boolean usesScripts; public int uid = -1; public int anInt1288 = -1; public int x = 0; public int y = 0; public int width = 0; public int height = 0; public int anInt1289 = 1; public int anInt1375 = 1; public int scrollX = 0; public int scrollY = 0; public int anInt1339 = -1; public int anInt1293 = 0; public int anInt1334 = 0; public int anInt1335 = 2; public int parentBase = -1; public int parentComponent = -1; public int interfaceId = -1; public int componentId = -1; public List children = new ArrayList<>(); public static boolean checkForScripts(int scriptId, Object[]... arrs) { for (Object[] arr : arrs) { if (arr == null) continue; for (int i = 0;i < arr.length;i++) try { if (arr[i] != null && (Integer) arr[i] == scriptId) return true; } catch (ClassCastException e) { } } return false; } public boolean usesScript(int scriptId) { if (checkForScripts(scriptId, onLoadScript, onMouseHoverScript, onMouseLeaveScript, anObjectArray1396, anObjectArray1400, anObjectArray1397, mouseLeaveScript, anObjectArray1387, anObjectArray1409, params, anObjectArray1393, popupScript, anObjectArray1386, anObjectArray1319, anObjectArray1302, anObjectArray1389, anObjectArray1451, anObjectArray1394, anObjectArray1412, anObjectArray1403, anObjectArray1405, anObjectArray1413, anObjectArray1292, anObjectArray1415, anObjectArray1416, anObjectArray1383, anObjectArray1419, anObjectArray1361, anObjectArray1421, anObjectArray1346, anObjectArray1353, anObjectArray1271)) return true; return false; } public static void main(String[] args) throws IOException { Cache.init(""../cache/""); COMPONENT_DEFINITIONS = new IComponentDefinitions[Utils.getInterfaceDefinitionsSize()][]; // int scriptId = 787; // // for (int id = 0;id < COMPONENT_DEFINITIONS.length;id++) { // IComponentDefinitions[] defs = getInterface(id); // for (int comp = 0;comp < defs.length;comp++) { // if (defs[comp].usesScript(scriptId)) // System.out.println(""Interface: "" + id + "", "" + comp); // } // } // System.out.println(Utils.toInterfaceHash(747, 9)); // System.out.println(Utils.interfaceIdFromHash(25428066) + "" - "" + Utils.componentIdFromHash(25428066)); // IComponentDefinitions[] defs = getInterface(477); //defs[604].children.clear(); //System.out.println(defs[483]); for (IComponentDefinitions def : defs) { def.children.clear(); System.out.println(def); } // System.out.println((31260698 >> 16) + "" - "" + (31260698 & 0xFFFF)); // System.out.println(defs[1]); // Set hasChildrenExisting = new HashSet<>(); // // for (IComponentDefinitions def : defs) { // if (def.parent != -1) // hasChildrenExisting.add(Utils.componentIdFromHash(def.parent)); // } // for (IComponentDefinitions def : defs) { // if (def.type == ComponentType.CONTAINER && !hasChildrenExisting.contains(def.componentId)) // System.out.println(def.componentId + "" - "" + def.type + "" - ["" + Utils.interfaceIdFromHash(def.parent) + "", "" + Utils.componentIdFromHash(def.parent) + ""]""); // } } @Override public String toString() { StringBuilder result = new StringBuilder(); String newLine = System.getProperty(""line.separator""); IComponentDefinitions def = new IComponentDefinitions(); result.append(this.getClass().getName()); result.append("" {""); result.append(newLine); Field[] fields = this.getClass().getDeclaredFields(); for (Field field : fields) { if (Modifier.isStatic(field.getModifiers())) continue; try { Object f1 = Utils.getFieldValue(this, field); Object f2 = Utils.getFieldValue(def, field); if (f1 == f2 || f1.equals(f2)) continue; result.append("" ""); result.append(field.getType().getCanonicalName() + "" "" + field.getName() + "": ""); result.append(Utils.getFieldValue(this, field)); } catch (Throwable ex) { System.out.println(ex); } result.append(newLine); } result.append(""}""); return result.toString(); } public static IComponentDefinitions getInterfaceComponent(int id, int component) { IComponentDefinitions[] inter = getInterface(id); if (inter == null || component >= inter.length) return null; return inter[component]; } public static IComponentDefinitions[] getInterface(int id) { if (COMPONENT_DEFINITIONS == null) COMPONENT_DEFINITIONS = new IComponentDefinitions[Utils.getInterfaceDefinitionsSize()][]; if (id >= COMPONENT_DEFINITIONS.length) return null; if (COMPONENT_DEFINITIONS[id] == null) { COMPONENT_DEFINITIONS[id] = new IComponentDefinitions[Utils.getInterfaceDefinitionsComponentsSize(id)]; Map uidMap = new HashMap<>(); for (int i = 0; i < COMPONENT_DEFINITIONS[id].length; i++) { byte[] data = Cache.STORE.getIndex(IndexType.INTERFACES).getFile(id, i); if (data != null) { IComponentDefinitions defs = COMPONENT_DEFINITIONS[id][i] = new IComponentDefinitions(); defs.uid = i + (id << 16); defs.interfaceId = id; defs.componentId = i; uidMap.put(defs.uid, defs); if (data[0] != -1) { throw new IllegalStateException(""if1""); } defs.decode(new InputStream(data)); } } for (int i = 0; i < COMPONENT_DEFINITIONS[id].length; i++) { IComponentDefinitions defs = COMPONENT_DEFINITIONS[id][i]; if (defs.parent != -1) uidMap.get(defs.parent).children.add(defs); } } return COMPONENT_DEFINITIONS[id]; } @SuppressWarnings({ ""unchecked"", ""rawtypes"" }) final void decode(InputStream stream) { int i_3 = stream.readUnsignedByte(); if (i_3 == 255) { i_3 = -1; } int typeId = stream.readUnsignedByte(); if ((typeId & 0x80) != 0) { typeId &= 0x7f; this.name = stream.readString(); } this.type = ComponentType.forId(typeId); this.contentType = stream.readUnsignedShort(); this.basePositionX = stream.readShort(); this.basePositionY = stream.readShort(); this.baseWidth = stream.readUnsignedShort(); this.baseHeight = stream.readUnsignedShort(); this.aspectWidthType = (byte) stream.readByte(); this.aspectHeightType = (byte) stream.readByte(); this.aspectXType = (byte) stream.readByte(); this.aspectYType = (byte) stream.readByte(); this.parent = stream.readUnsignedShort(); if (this.parent == 65535) { this.parent = -1; } else { this.parent += this.uid & ~0xffff; } if (parent != -1) { parentBase = parent >> 16; parentComponent = parent & 0xFFFF; } int i_4 = stream.readUnsignedByte(); this.hidden = (i_4 & 0x1) != 0; if (i_3 >= 0) { this.noClickThrough = (i_4 & 0x2) != 0; } if (this.type == ComponentType.CONTAINER) { this.scrollWidth = stream.readUnsignedShort(); this.scrollHeight = stream.readUnsignedShort(); if (i_3 < 0) { this.noClickThrough = stream.readUnsignedByte() == 1; } } if (this.type == ComponentType.SPRITE) { this.spriteId = stream.readInt(); this.angle2d = stream.readUnsignedShort(); int flag2 = stream.readUnsignedByte(); this.tiling = (flag2 & 0x1) != 0; this.alpha = (flag2 & 0x2) != 0; this.transparency = stream.readUnsignedByte(); this.borderThickness = stream.readUnsignedByte(); this.anInt1324 = stream.readInt(); this.vFlip = stream.readUnsignedByte() == 1; this.hFlip = stream.readUnsignedByte() == 1; this.color = stream.readInt(); if (i_3 >= 3) { this.clickMask = stream.readUnsignedByte() == 1; } } if (this.type == ComponentType.MODEL) { this.modelType = ModelType.RAW_MODEL; this.modelId = stream.readBigSmart(); int flag2 = stream.readUnsignedByte(); boolean bool_6 = (flag2 & 0x1) == 1; this.hasOrigin = (flag2 & 0x2) == 2; this.usesOrthogonal = (flag2 & 0x4) == 4; this.aBool1345 = (flag2 & 0x8) == 8; if (bool_6) { this.originX = stream.readShort(); this.originY = stream.readShort(); this.spritePitch = stream.readUnsignedShort(); this.spriteRoll = stream.readUnsignedShort(); this.spriteYaw = stream.readUnsignedShort(); this.spriteScale = stream.readUnsignedShort(); } else if (this.hasOrigin) { this.originX = stream.readShort(); this.originY = stream.readShort(); this.originZ = stream.readShort(); this.spritePitch = stream.readUnsignedShort(); this.spriteRoll = stream.readUnsignedShort(); this.spriteYaw = stream.readUnsignedShort(); this.spriteScale = stream.readShort(); } this.animation = stream.readBigSmart(); if (this.aspectWidthType != 0) { this.aspectWidth = stream.readUnsignedShort(); } if (this.aspectHeightType != 0) { this.aspectHeight = stream.readUnsignedShort(); } } if (this.type == ComponentType.TEXT) { this.fontId = stream.readBigSmart(); if (i_3 >= 2) { this.monospaced = stream.readUnsignedByte() == 1; } this.text = stream.readString(); if (this.text.toLowerCase().contains(""runescape"")) { this.text = this.text.replace(""runescape"", ""Darkan""); this.text = this.text.replace(""RuneScape"", ""Darkan""); this.text = this.text.replace(""Runescape"", ""Darkan""); } this.anInt1358 = stream.readUnsignedByte(); this.textHorizontalAli = stream.readUnsignedByte(); this.textVerticalAli = stream.readUnsignedByte(); this.shadow = stream.readUnsignedByte() == 1; this.color = stream.readInt(); this.transparency = stream.readUnsignedByte(); if (i_3 >= 0) { this.multiline = stream.readUnsignedByte(); } } if (this.type == ComponentType.FIGURE) { this.color = stream.readInt(); this.filled = stream.readUnsignedByte() == 1; this.transparency = stream.readUnsignedByte(); } if (this.type == ComponentType.LINE) { this.lineWidth = stream.readUnsignedByte(); this.color = stream.readInt(); this.lineDirection = stream.readUnsignedByte() == 1; } int optionMask = stream.read24BitUnsignedInteger(); int i_16 = stream.readUnsignedByte(); int i_7; if (i_16 != 0) { this.aByteArrayArray1366 = new byte[11][]; this.aByteArrayArray1367 = new byte[11][]; this.anIntArray1395 = new int[11]; for (this.anIntArray1267 = new int[11]; i_16 != 0; i_16 = stream.readUnsignedByte()) { i_7 = (i_16 >> 4) - 1; i_16 = i_16 << 8 | stream.readUnsignedByte(); i_16 &= 0xfff; if (i_16 == 4095) { i_16 = -1; } byte b_8 = (byte) stream.readByte(); if (b_8 != 0) { this.aBool1424 = true; } byte b_9 = (byte) stream.readByte(); this.anIntArray1395[i_7] = i_16; this.aByteArrayArray1366[i_7] = new byte[] { b_8 }; this.aByteArrayArray1367[i_7] = new byte[] { b_9 }; } } this.useOnName = stream.readString(); i_7 = stream.readUnsignedByte(); int i_17 = i_7 & 0xf; int i_18 = i_7 >> 4; int i_10; if (i_17 > 0) { this.optionNames = new String[i_17]; for (i_10 = 0; i_10 < i_17; i_10++) { this.optionNames[i_10] = stream.readString(); } } int i_11; if (i_18 > 0) { i_10 = stream.readUnsignedByte(); this.opCursors = new int[i_10 + 1]; for (i_11 = 0; i_11 < this.opCursors.length; i_11++) { this.opCursors[i_11] = -1; } this.opCursors[i_10] = stream.readUnsignedShort(); } if (i_18 > 1) { i_10 = stream.readUnsignedByte(); this.opCursors[i_10] = stream.readUnsignedShort(); } this.opName = stream.readString(); if (this.opName.equals("""")) { this.opName = null; } this.anInt1380 = stream.readUnsignedByte(); this.anInt1381 = stream.readUnsignedByte(); this.anInt1382 = stream.readUnsignedByte(); this.useOptionString = stream.readString(); i_10 = -1; if (IFEvents.getUseOptionFlags(optionMask) != 0) { i_10 = stream.readUnsignedShort(); if (i_10 == 65535) { i_10 = -1; } this.targetOverCursor = stream.readUnsignedShort(); if (this.targetOverCursor == 65535) { this.targetOverCursor = -1; } this.targetLeaveCursor = stream.readUnsignedShort(); if (this.targetLeaveCursor == 65535) { this.targetLeaveCursor = -1; } } if (i_3 >= 0) { this.mouseOverCursor = stream.readUnsignedShort(); if (this.mouseOverCursor == 65535) { this.mouseOverCursor = -1; } } this.events = new IFEvents(optionMask, i_10); if (i_3 >= 0) { if (this.aHashTable4823 == null) this.aHashTable4823 = new Hashtable(); i_11 = stream.readUnsignedByte(); int i_12; int i_13; int i_14; for (i_12 = 0; i_12 < i_11; i_12++) { i_13 = stream.read24BitUnsignedInteger(); i_14 = stream.readInt(); this.aHashTable4823.put(i_14, (long) i_13); } i_12 = stream.readUnsignedByte(); for (i_13 = 0; i_13 < i_12; i_13++) { i_14 = stream.read24BitUnsignedInteger(); String string_15 = stream.readGJString(); this.aHashTable4823.put(string_15, (long) i_14); } } this.onLoadScript = this.decodeScript(stream); this.onMouseHoverScript = this.decodeScript(stream); this.onMouseLeaveScript = this.decodeScript(stream); this.anObjectArray1396 = this.decodeScript(stream); this.anObjectArray1400 = this.decodeScript(stream); this.anObjectArray1397 = this.decodeScript(stream); this.mouseLeaveScript = this.decodeScript(stream); this.anObjectArray1387 = this.decodeScript(stream); this.anObjectArray1409 = this.decodeScript(stream); this.params = this.decodeScript(stream); if (i_3 >= 0) { this.anObjectArray1393 = this.decodeScript(stream); } this.popupScript = this.decodeScript(stream); this.anObjectArray1386 = this.decodeScript(stream); this.anObjectArray1319 = this.decodeScript(stream); this.anObjectArray1302 = this.decodeScript(stream); this.anObjectArray1389 = this.decodeScript(stream); this.anObjectArray1451 = this.decodeScript(stream); this.anObjectArray1394 = this.decodeScript(stream); this.anObjectArray1412 = this.decodeScript(stream); this.anObjectArray1403 = this.decodeScript(stream); this.anObjectArray1405 = this.decodeScript(stream); this.varps = this.method4150(stream); this.mouseLeaveArrayParam = this.method4150(stream); this.anIntArray1402 = this.method4150(stream); this.anIntArray1315 = this.method4150(stream); this.anIntArray1406 = this.method4150(stream); } private final Object[] decodeScript(InputStream buffer) { int i_29_ = buffer.readUnsignedByte(); if (0 == i_29_) return null; Object[] objects = new Object[i_29_]; for (int i_30_ = 0; i_30_ < i_29_; i_30_++) { int i_31_ = buffer.readUnsignedByte(); if (i_31_ == 0) objects[i_30_] = buffer.readInt(); else if (i_31_ == 1) objects[i_30_] = buffer.readString(); } usesScripts = true; return objects; } private final int[] method4150(InputStream buffer) { int i = buffer.readUnsignedByte(); if (i == 0) { return null; } int[] is = new int[i]; for (int i_60_ = 0; i_60_ < i; i_60_++) is[i_60_] = buffer.readInt(); return is; } final int method14502(int i) { return i >> 11 & 0x7f; } } " " package com.rs.cache.loaders.interfaces; import java.util.Arrays; public class IFEvents { public enum UseFlag { GROUND_ITEM(0x1), NPC(0x2), WORLD_OBJECT(0x4), PLAYER(0x8), SELF(0x10), ICOMPONENT(0x20), WORLD_TILE(0x40); private int flag; private UseFlag(int flag) { this.flag = flag; } public int getFlag() { return flag; } } private int interfaceId; private int componentId; private int fromSlot; private int toSlot; private int eventsHash; public IFEvents(int interfaceId, int componentId, int fromSlot, int toSlot, int eventsHash) { this.interfaceId = interfaceId; this.componentId = componentId; this.fromSlot = fromSlot; this.toSlot = toSlot; this.eventsHash = eventsHash; } public IFEvents(int settings, int interfaceId) { this.eventsHash = settings; this.interfaceId = interfaceId; } public IFEvents(int interfaceId, int componentId, int fromSlot, int toSlot) { this(interfaceId, componentId, fromSlot, toSlot, 0); } public boolean clickOptionEnabled(int i) { return 0 != (eventsHash >> 1 + i & 0x1); } public IFEvents enableRightClickOptions(int... ids) { Arrays.stream(ids).forEach((id) -> enableRightClickOption(id)); return this; } public IFEvents enableRightClickOption(int id) { if (id < 0 || id > 9) return null; eventsHash &= ~(0x1 << (id + 1)); eventsHash |= (0x1 << (id + 1)); return this; } public final boolean useOptionEnabled(UseFlag flag) { return ((eventsHash >> 11 & 0x7F) & flag.getFlag()) != 0; } public IFEvents enableUseOptions(UseFlag... flags) { Arrays.stream(flags).forEach(this::enableUseOption); return this; } public final int getUseOptionFlags() { return IFEvents.getUseOptionFlags(this.eventsHash); } static final int getUseOptionFlags(int settings) { return settings >> 11 & 0x7f; } public IFEvents enableUseOption(UseFlag flag) { int useOptions = eventsHash >> 11 & 0x7F; useOptions |= flag.flag; eventsHash &= ~(useOptions << 11); eventsHash |= (useOptions << 11); return this; } public boolean dragEnabled() { return (eventsHash >> 21 & 0x1) != 0; } public IFEvents enableDrag() { eventsHash &= ~(1 << 21); eventsHash |= (1 << 21); return this; } public boolean continueOptionEnabled() { return (eventsHash & 0x1) != 0; } public IFEvents enableContinueButton() { eventsHash |= 0x1; return this; } public boolean ignoresDepthFlags() { return 0 != (eventsHash >> 23 & 0x1); } public IFEvents enableDepthFlagIgnoring() { eventsHash &= ~(1 << 23); eventsHash |= (1 << 23); return this; } public boolean isTargetableByUse() { return 0 != (eventsHash >> 22 & 0x1); } public IFEvents enableUseTargetability() { eventsHash &= ~(1 << 22); eventsHash |= (1 << 22); return this; } public int getDepth() { return eventsHash >> 18 & 0x7; } public IFEvents setDepth(int depth) { if (depth < 0 || depth > 7) return null; eventsHash &= ~(0x7 << 18); eventsHash |= (depth << 18); return this; } public int getInterfaceId() { return interfaceId; } public int getComponentId() { return componentId; } public int getFromSlot() { return fromSlot; } public int getToSlot() { return toSlot; } public int getSettings() { return eventsHash; } @Override public boolean equals(Object other) { if (other instanceof IFEvents) return ((IFEvents) other).eventsHash == eventsHash; return false; } @Override public String toString() { String s = ""player.getPackets().setIFEvents(new IFEvents("" + interfaceId + "", "" + componentId + "", "" + fromSlot + "", "" + toSlot + "")""; String useFlags = """"; for (int i = 0;i < UseFlag.values().length;i++) { useFlags += useOptionEnabled(UseFlag.values()[i]) ? ""UseFlag."" + UseFlag.values()[i].name() + "","" : """"; } if (!useFlags.equals("""")) { s += "".enableUseOptions("" + useFlags.substring(0, useFlags.length()-1) + "")""; } String rightClicks = """"; for (int i = 0;i <= 9;i++) { rightClicks += clickOptionEnabled(i) ? """" + i + "","" : """"; } if (!rightClicks.equals("""")) { s += "".enableRightClickOptions("" + rightClicks.substring(0, rightClicks.length()-1) + "")""; } if (getDepth() != 0) { s += "".setDepth("" + getDepth() + "")""; } if (continueOptionEnabled()) { s += "".enableContinueButton()""; } if (dragEnabled()) { s += "".enableDrag()""; } if (ignoresDepthFlags()) { s += "".enableDepthFlagIgnoring()""; } if (isTargetableByUse()) { s += "".enableUseTargetability()""; } s += ""); //"" + eventsHash; return s; } }" " package com.rs.cache.loaders.interfaces; import java.awt.Component; import java.awt.Image; import java.awt.image.FilteredImageSource; import java.awt.image.ImageFilter; import java.awt.image.ImageProducer; import java.awt.image.ReplicateScaleFilter; import javax.swing.JComponent; import com.rs.cache.Store; public class Interface { public int id; public Store cache; public IComponentDefinitions[] components; public JComponent[] jcomponents; public Interface(int id, Store cache) { this(id, cache, true); } public Interface(int id, Store cache, boolean load) { this.id = id; this.cache = cache; if (load) components = IComponentDefinitions.getInterface(id); } public void draw(JComponent parent) { } public Image resizeImage(Image image, int width, int height, Component c) { ImageFilter replicate = new ReplicateScaleFilter(width, height); ImageProducer prod = new FilteredImageSource(image.getSource(), replicate); return c.createImage(prod); } } " " package com.rs.cache.loaders.interfaces; public enum ModelType { NONE(0), RAW_MODEL(1), NPC_HEAD(2), PLAYER_HEAD(3), ITEM(4), PLAYER_MODEL(5), NPC_MODEL(6), PLAYER_HEAD_IGNOREWORN(7), ITEM_CONTAINER_MALE(8), ITEM_CONTAINER_FEMALE(9); public static ModelType forId(int id) { for (ModelType t : ModelType.values()) { if (t.id == id) return t; } return null; } private int id; private ModelType(int id) { this.id = id; } public int getId() { return id; } } " " package com.rs.cache.loaders.map; public enum RegionSize { SIZE_104(104), SIZE_120(120), SIZE_136(136), SIZE_168(168), SIZE_72(72); public int size; RegionSize(int size) { this.size = size; } } " " package com.rs.cache.loaders.map; public class StaticElements { } " " package com.rs.cache.loaders.map; public class WorldMapArea { } " " package com.rs.cache.loaders.map; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.lib.io.InputStream; public class WorldMapDefinitions { private static Map CACHE = new HashMap<>(); public int anInt9542 = -1; public int anInt9539 = 12800; public int anInt9540; public int anInt9541 = 12800; public int anInt9535; public int id; public String staticElementsName; public String areaName; public int regionHash; public int anInt9538 = -1; public boolean aBool9543 = true; public RegionSize mapSize; public List areaRects = new ArrayList<>(); public WorldMapDefinitions(int fileId) { this.id = fileId; } public static void loadAreas() { int detailsArchive = Cache.STORE.getIndex(IndexType.MAP_AREAS).getArchiveId(""details""); int size = Cache.STORE.getIndex(IndexType.MAP_AREAS).getValidFilesCount(detailsArchive); for (int i = 0; i < size; i++) { byte[] data = Cache.STORE.getIndex(IndexType.MAP_AREAS).getFile(detailsArchive, i); if (data == null) continue; WorldMapDefinitions defs = new WorldMapDefinitions(i); defs.init(); CACHE.put(i, defs); } } public void decode(byte[] data) { InputStream stream = new InputStream(data); this.staticElementsName = stream.readString(); this.areaName = stream.readString(); this.regionHash = stream.readInt(); this.anInt9538 = stream.readInt(); this.aBool9543 = stream.readUnsignedByte() == 1; this.anInt9542 = stream.readUnsignedByte(); if (this.anInt9542 == 255) this.anInt9542 = 0; this.mapSize = RegionSize.values()[stream.readUnsignedByte()]; int size = stream.readUnsignedByte(); for (int i = 0; i < size; i++) { areaRects.add(new WorldMapRect(stream.readUnsignedByte(), stream.readUnsignedShort(), stream.readUnsignedShort(), stream.readUnsignedShort(), stream.readUnsignedShort(), stream.readUnsignedShort(), stream.readUnsignedShort(), stream.readUnsignedShort(), stream.readUnsignedShort())); } } public StaticElements getStaticElements() { // int staticElementsArchive = Cache.STORE.getIndex(IndexType.MAP_AREAS).getArchiveId(staticElementsName + ""_staticelements""); // if (archiveId == -1) { // return new StaticElements(0); // } else { // int[] fileIds = index_0.getValidFileIds(archiveId); // StaticElements elements = new StaticElements(fileIds.length); // int id = 0; // int fileIndex = 0; // while (true) { // while (id < elements.size) { // ByteBuf buffer = new ByteBuf(index_0.getFile(archiveId, fileIds[fileIndex++])); // int regionHash = buffer.readInt(); // int areaId = buffer.readUnsignedShort(); // int isMembers = buffer.readUnsignedByte(); // if (!members && isMembers == 1) { // --elements.size; // } else { // elements.regionHashes[id] = regionHash; // elements.areaIds[id] = areaId; // ++id; // } // } // return elements; // } // } return null; } public boolean method14775(int i_1, int i_2, int[] ints_3) { for (WorldMapRect rect : areaRects) { if (rect.method12409(i_1, i_2)) { rect.method12410(i_1, i_2, ints_3); return true; } } return false; } public boolean method14777(int i_1, int i_2, int[] ints_3) { for (WorldMapRect rect : areaRects) { if (rect.method12415(i_1, i_2)) { rect.method12414(i_1, i_2, ints_3); return true; } } return false; } public boolean method14778(int i_1, int i_2, int i_3, int[] ints_4) { for (WorldMapRect rect : areaRects) { if (rect.method12408(i_1, i_2, i_3)) { rect.method12414(i_2, i_3, ints_4); return true; } } return false; } public void init() { this.anInt9539 = 12800; this.anInt9540 = 0; this.anInt9541 = 12800; this.anInt9535 = 0; for (WorldMapRect rect : areaRects) { if (rect.bestBottomLeftX < anInt9539) this.anInt9539 = rect.bestBottomLeftX; if (rect.bestTopRightX > anInt9540) this.anInt9540 = rect.bestTopRightX; if (rect.bestBottomLeftY < anInt9541) this.anInt9541 = rect.bestBottomLeftY; if (rect.bestTopRightY > anInt9535) this.anInt9535 = rect.bestTopRightY; } } public boolean method14784(int i_1, int i_2) { for (WorldMapRect rect : areaRects) { if (rect.method12415(i_1, i_2)) { return true; } } return false; } } " " package com.rs.cache.loaders.map; public class WorldMapRect { public int plane; public int bottomLeftX; public int bottomLeftY; public int topRightX; public int topRightY; public int bestBottomLeftX; public int bestBottomLeftY; public int bestTopRightX; public int bestTopRightY; WorldMapRect(int plane, int bottomLeftX, int bottomLeftY, int topRightX, int topRightY, int bestBottomLeftX, int bestBottomLeftY, int bestTopRightX, int bestTopRightY) { this.plane = plane; this.bottomLeftX = bottomLeftX; this.bottomLeftY = bottomLeftY; this.topRightX = topRightX; this.topRightY = topRightY; this.bestBottomLeftX = bestBottomLeftX; this.bestBottomLeftY = bestBottomLeftY; this.bestTopRightX = bestTopRightX; this.bestTopRightY = bestTopRightY; } boolean method12408(int plane, int x, int y) { return this.plane == plane && x >= bottomLeftX && x <= topRightX && y >= bottomLeftY && y <= topRightY; } boolean method12409(int x, int y) { return x >= bestBottomLeftX && x <= bestTopRightX && y >= bestBottomLeftY && y <= bestTopRightY; } void method12410(int i_1, int i_2, int[] ints_3) { ints_3[0] = plane; ints_3[1] = bottomLeftX - bestBottomLeftX + i_1; ints_3[2] = bottomLeftY - bestBottomLeftY + i_2; } void method12414(int i_1, int i_2, int[] ints_3) { ints_3[0] = 0; ints_3[1] = bestBottomLeftX - bottomLeftX + i_1; ints_3[2] = bestBottomLeftY - bottomLeftY + i_2; } boolean method12415(int x, int y) { return x >= bottomLeftX && x <= topRightX && y >= bottomLeftY && y <= topRightY; } } " " package com.rs.cache.loaders.model; public class BillBoardConfig { public int type; public int face; public int priority; public int magnitude; BillBoardConfig(int type, int face, int priority, int magnitude) { this.type = type; this.face = face; this.priority = priority; this.magnitude = magnitude; } BillBoardConfig method1459(int face) { return new BillBoardConfig(this.type, face, this.priority, this.magnitude); } } " " package com.rs.cache.loaders.model; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.CompositeContext; import java.awt.Graphics2D; import java.awt.Transparency; import java.awt.image.BufferedImage; import java.awt.image.Raster; import java.util.Set; import com.google.common.collect.Sets; public class BufferedImageUtils { public static BufferedImage flipHoriz(BufferedImage image) { BufferedImage newImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics2D gg = newImage.createGraphics(); gg.drawImage(image, image.getHeight(), 0, -image.getWidth(), image.getHeight(), null); gg.dispose(); return newImage; } /** * Returns true if the provided image has partially transparent * areas (alpha channel). */ public static boolean hasPartialTransparency(BufferedImage image) { final Raster alphaRaster = image.getAlphaRaster(); if (image.getTransparency() != Transparency.TRANSLUCENT || alphaRaster == null) { return false; } int[] pixels = alphaRaster.getPixels(0, 0, alphaRaster.getWidth(), alphaRaster.getHeight(), (int[]) null); for (int i : pixels) { if (i != 0 && i != 255) { return true; } } return false; } /** * Returns true if the provided image has any kind of transparent * areas */ public static boolean hasTransparency(BufferedImage image) { final Raster alphaRaster = image.getAlphaRaster(); if (image.getTransparency() != Transparency.TRANSLUCENT || alphaRaster == null) { return false; } int[] pixels = alphaRaster.getPixels(0, 0, alphaRaster.getWidth(), alphaRaster.getHeight(), (int[]) null); for (int i : pixels) { if (i != 255) { return true; } } return false; } /** * Returns the number of distinct colors (excluding transparency) in the * image. */ public static int countDistictColors(BufferedImage image) { return getDistictColors(image).length; } /** * Returns the image's distinct colors in an RGB format, discarding * transparency information. */ public static int[] getDistictColors(BufferedImage image) { return getDistictColors(image, 0); } /** * Returns the image's distinct colors in an RGB format, discarding * transparency information. Adds padding empty slots at the * beginning of the returned array. */ public static int[] getDistictColors(BufferedImage image, int padding) { final int width = image.getWidth(); final int height = image.getHeight(); final Set colors = Sets.newHashSet(); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { final int pixel = image.getRGB(x, y); // Count only colors for which alpha is not fully transparent if ((pixel & 0xff000000) != 0x00000000) { colors.add(Integer.valueOf(pixel & 0x00ffffff)); } } } final int[] colorMap = new int[colors.size() + padding]; int index = padding; for (Integer color : colors) { colorMap[index++] = color; } return colorMap; } /** * Returns a two dimensional array of the image's RGB values, * including transparency. */ public static int[][] getRgb(BufferedImage image) { final int width = image.getWidth(); final int height = image.getHeight(); final int[][] rgb = new int[width][height]; for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { rgb[x][y] = image.getRGB(x, y); } } return rgb; } /** * Performs matting of the source image using * matteColor. Matting is rendering partial transparencies using * solid color as if the original image was put on top of a bitmap filled with * matteColor. */ public static BufferedImage matte(BufferedImage source, Color matteColor) { final int width = source.getWidth(); final int height = source.getHeight(); // A workaround for possibly different custom image types we can get: // draw a copy of the image final BufferedImage sourceConverted = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR); sourceConverted.getGraphics().drawImage(source, 0, 0, null); final BufferedImage matted = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR); final BufferedImage matte = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR); final int matteRgb = matteColor.getRGB(); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { matte.setRGB(x, y, matteRgb); } } CompositeContext context = AlphaComposite.DstOver.createContext(matte.getColorModel(), sourceConverted.getColorModel(), null); context.compose(matte.getRaster(), sourceConverted.getRaster(), matted.getRaster()); return matted; } /** * Draws image on the canvas placing the top left * corner of image at x / y offset from * the top left corner of canvas. */ public static void drawImage(BufferedImage image, BufferedImage canvas, int x, int y) { final int[] imgRGB = image.getRGB(0, 0, image.getWidth(), image.getHeight(), null, 0, image.getWidth()); canvas.setRGB(x, y, image.getWidth(), image.getHeight(), imgRGB, 0, image.getWidth()); } private BufferedImageUtils() { } } " " package com.rs.cache.loaders.model; import java.nio.ByteBuffer; public class ByteBufferUtils { public static int getSmart(ByteBuffer buffer) { int i_118_ = buffer.get(buffer.position()) & 0xff; if (i_118_ < 128) return buffer.get() & 0xFF; return (buffer.getShort() & 0xFFFF) - 32768; } public static int getSmart1(ByteBuffer buffer) { int i_118_ = buffer.get(buffer.position()) & 0xff; if (i_118_ < 128) return (buffer.get() & 0xFF) - 64; return (buffer.getShort() & 0xFFFF) - 49152; } public static int getSmart2(ByteBuffer buffer) { int i_118_ = buffer.get(buffer.position()) & 0xff; if (i_118_ < 128) return (buffer.get() & 0xFF) - 1; return (buffer.getShort() & 0xFFFF) - 32769; } public static int getMedium(ByteBuffer buffer) { return ((buffer.get() & 0xFF) << 16) | ((buffer.get() & 0xFF) << 8) | (buffer.get() & 0xFF); } } " " package com.rs.cache.loaders.model; import java.awt.Color; import java.awt.image.BufferedImage; import java.awt.image.DataBuffer; import java.awt.image.IndexColorModel; import java.awt.image.WritableRaster; public class ColorQuantizer { /** * Maximum number of colors in an indexed image, leaving one for transparency */ public static final int MAX_INDEXED_COLORS = 255; private ColorQuantizer() { // Prevent Instantiation } /** * Quantizes the image to {@link #MAX_INDEXED_COLORS} with white matte for areas * with partial transparency (full transparency will be preserved). * * @return {@link BufferedImage} with type * {@link BufferedImage#TYPE_BYTE_INDEXED} and quantized colors */ public static BufferedImage quantize(BufferedImage source) { return quantize(source, Color.WHITE); } /** * Quantizes the image to {@link #MAX_INDEXED_COLORS} with the provided matte * {@link Color} for areas with partial transparency (full transparency will be * preserved). * * @return {@link BufferedImage} with type * {@link BufferedImage#TYPE_BYTE_INDEXED} and quantized colors */ public static BufferedImage quantize(BufferedImage source, Color matteColor) { return quantize(source, matteColor, MAX_INDEXED_COLORS); } /** * Quantizes the image to the provided number of colors with the provided matte * {@link Color} for areas with partial transparency (full transparency will be * preserved). * * @return {@link BufferedImage} with type * {@link BufferedImage#TYPE_BYTE_INDEXED} and quantized colors */ public static BufferedImage quantize(BufferedImage source, Color matteColor, int maxColors) { final int width = source.getWidth(); final int height = source.getHeight(); // First put the matte color so that we have a sensible result // for images with full alpha transparencies final BufferedImage mattedSource = BufferedImageUtils.matte(source, matteColor); // Get two copies of RGB data (quantization will overwrite one) final int[][] bitmap = BufferedImageUtils.getRgb(mattedSource); // Quantize colors and shift palette by one for transparency color // We'll keep transparency color black for now. final int[] colors = Quantize.quantizeImage(bitmap, maxColors); final int[] colorsWithAlpha = new int[colors.length + 1]; System.arraycopy(colors, 0, colorsWithAlpha, 1, colors.length); colorsWithAlpha[0] = matteColor.getRGB(); final IndexColorModel colorModel = new IndexColorModel(8, colorsWithAlpha.length, colorsWithAlpha, 0, false, 0, DataBuffer.TYPE_BYTE); // Write the results to an indexed image, skipping the fully transparent bits final BufferedImage quantized = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_INDEXED, colorModel); final WritableRaster raster = quantized.getRaster(); final int[][] rgb = BufferedImageUtils.getRgb(source); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { final int value = (rgb[x][y] & 0xff000000) != 0x00000000 ? bitmap[x][y] + 1 : 0; raster.setPixel(x, y, new int[] { value }); } } return quantized; } /** * Reduces a direct color buffered image to an indexed color one without quality * loss. To make sure no quality loss will occur, check the results of the * {@link #getColorReductionInfo(BufferedImage)} method call. * * @throws IllegalArgumentException if the application of this method would * result in image quality loss */ public static BufferedImage reduce(BufferedImage source) { final int width = source.getWidth(); final int height = source.getHeight(); if (BufferedImageUtils.hasPartialTransparency(source)) { throw new IllegalArgumentException(""The source image cannot contain translucent areas""); } final int[] colorsWithAlpha = BufferedImageUtils.getDistictColors(source, 1); if (colorsWithAlpha.length - 1 > MAX_INDEXED_COLORS) { throw new IllegalArgumentException(""The source image cannot contain more than "" + MAX_INDEXED_COLORS + "" colors""); } final IndexColorModel colorModel = new IndexColorModel(8, colorsWithAlpha.length, colorsWithAlpha, 0, false, 0, DataBuffer.TYPE_BYTE); // Write the results to an indexed image, skipping the fully transparent bits final BufferedImage quantized = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_INDEXED, colorModel); final int[][] rgb = BufferedImageUtils.getRgb(source); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { if ((rgb[x][y] & 0xff000000) != 0x00000000) { quantized.setRGB(x, y, source.getRGB(x, y)); } } } return quantized; } /** * Returns a {@link ColorReductionInfo} for the provided image. */ public static ColorReductionInfo getColorReductionInfo(BufferedImage source) { return new ColorReductionInfo(BufferedImageUtils.hasPartialTransparency(source), BufferedImageUtils.countDistictColors(source)); } /** * Indicates how many distinct colors an image has, whether it has partial * trasparency (alpha channel). */ public static class ColorReductionInfo { /** Number of distint colors in the image */ public int distictColors; /** True if the image has partially transparent areas (alpha channel) */ public boolean hasPartialTransparency; public ColorReductionInfo(boolean hasPartialTransparency, int distictColors) { this.hasPartialTransparency = hasPartialTransparency; this.distictColors = distictColors; } /** * Returns true if the image can be saved in a 8-bit indexed color format with * 1-bit transparency without quality loss. */ public boolean canReduceWithoutQualityLoss() { return !hasPartialTransparency && distictColors <= MAX_INDEXED_COLORS; } } } " " package com.rs.cache.loaders.model; public class EmitterConfig { public int type; public int face; public int faceX; public int faceY; public int faceZ; public byte priority; EmitterConfig(int type, int face, int faceX, int faceY, int faceZ, byte priority) { this.type = type; this.face = face; this.faceX = faceX; this.faceY = faceY; this.faceZ = faceZ; this.priority = priority; } } " " package com.rs.cache.loaders.model; public class MagnetConfig { public int type; public int vertex; MagnetConfig(int type, int vertex) { this.type = type; this.vertex = vertex; } } " "package com.rs.cache.loaders.model; /** * (#)Quantize.java 0.90 9/19/00 Adam Doppelt * * An efficient color quantization algorithm, adapted from the C++ * implementation quantize.c in * ImageMagick. The pixels for an * image are placed into an oct tree. The oct tree is reduced in size, and the * pixels from the original image are reassigned to the nodes in the reduced * tree. *

* * Here is the copyright notice from ImageMagick: * *

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%  Permission is hereby granted, free of charge, to any person obtaining a    %
%  copy of this software and associated documentation files (""ImageMagick""),  %
%  to deal in ImageMagick without restriction, including without limitation   %
%  the rights to use, copy, modify, merge, publish, distribute, sublicense,   %
%  and/or sell copies of ImageMagick, and to permit persons to whom the       %
%  ImageMagick is furnished to do so, subject to the following conditions:    %
%                                                                             %
%  The above copyright notice and this permission notice shall be included in %
%  all copies or substantial portions of ImageMagick.                         %
%                                                                             %
%  The software is provided ""as is"", without warranty of any kind, express or %
%  implied, including but not limited to the warranties of merchantability,   %
%  fitness for a particular purpose and noninfringement.  In no event shall   %
%  E. I. du Pont de Nemours and Company be liable for any claim, damages or   %
%  other liability, whether in an action of contract, tort or otherwise,      %
%  arising from, out of or in connection with ImageMagick or the use or other %
%  dealings in ImageMagick.                                                   %
%                                                                             %
%  Except as contained in this notice, the name of the E. I. du Pont de       %
%  Nemours and Company shall not be used in advertising or otherwise to       %
%  promote the sale, use or other dealings in ImageMagick without prior       %
%  written authorization from the E. I. du Pont de Nemours and Company.       %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 * 
* * * @version 0.90 19 Sep 2000 * @author Adam Doppelt */ public class Quantize { /* * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% * %% % % % % % % % QQQ U U AAA N N TTTTT IIIII ZZZZZ EEEEE % % Q Q U U A A NN N * T I ZZ E % % Q Q U U AAAAA N N N T I ZZZ EEEEE % % Q QQ U U A A N NN T I ZZ E * % % QQQQ UUU A A N N T IIIII ZZZZZ EEEEE % % % % % % Reduce the Number of * Unique Colors in an Image % % % % % % Software Design % % John Cristy % % * July 1992 % % % % % % Copyright 1998 E. I. du Pont de Nemours and Company % % * % % Permission is hereby granted, free of charge, to any person obtaining a % * % copy of this software and associated documentation files (""ImageMagick""), % * % to deal in ImageMagick without restriction, including without limitation % * % the rights to use, copy, modify, merge, publish, distribute, sublicense, % * % and/or sell copies of ImageMagick, and to permit persons to whom the % % * ImageMagick is furnished to do so, subject to the following conditions: % % % * % The above copyright notice and this permission notice shall be included in * % % all copies or substantial portions of ImageMagick. % % % % The software * is provided ""as is"", without warranty of any kind, express or % % implied, * including but not limited to the warranties of merchantability, % % fitness * for a particular purpose and noninfringement. In no event shall % % E. I. du * Pont de Nemours and Company be liable for any claim, damages or % % other * liability, whether in an action of contract, tort or otherwise, % % arising * from, out of or in connection with ImageMagick or the use or other % % * dealings in ImageMagick. % % % % Except as contained in this notice, the name * of the E. I. du Pont de % % Nemours and Company shall not be used in * advertising or otherwise to % % promote the sale, use or other dealings in * ImageMagick without prior % % written authorization from the E. I. du Pont de * Nemours and Company. % % % * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% * %% % % Realism in computer graphics typically requires using 24 bits/pixel to * % generate an image. Yet many graphic display devices do not contain % the * amount of memory necessary to match the spatial and color % resolution of the * human eye. The QUANTIZE program takes a 24 bit % image and reduces the number * of colors so it can be displayed on % raster device with less bits per pixel. * In most instances, the % quantized image closely resembles the original * reference image. % % A reduction of colors in an image is also desirable for * image % transmission and real-time animation. % % Function Quantize takes a * standard RGB or monochrome images and quantizes % them down to some fixed * number of colors. % % For purposes of color allocation, an image is a set of * n pixels, where % each pixel is a point in RGB space. RGB space is a * 3-dimensional % vector space, and each pixel, pi, is defined by an ordered * triple of % red, green, and blue coordinates, (ri, gi, bi). % % Each primary * color component (red, green, or blue) represents an % intensity which varies * linearly from 0 to a maximum value, cmax, which % corresponds to full * saturation of that color. Color allocation is % defined over a domain * consisting of the cube in RGB space with % opposite vertices at (0,0,0) and * (cmax,cmax,cmax). QUANTIZE requires % cmax = 255. % % The algorithm maps this * domain onto a tree in which each node % represents a cube within that domain. * In the following discussion % these cubes are defined by the coordinate of * two opposite vertices: % The vertex nearest the origin in RGB space and the * vertex farthest % from the origin. % % The tree's root node represents the * the entire domain, (0,0,0) through % (cmax,cmax,cmax). Each lower level in * the tree is generated by % subdividing one node's cube into eight smaller * cubes of equal size. % This corresponds to bisecting the parent cube with * planes passing % through the midpoints of each edge. % % The basic algorithm * operates in three phases: Classification, % Reduction, and Assignment. * Classification builds a color % description tree for the image. Reduction * collapses the tree until % the number it represents, at most, the number of * colors desired in the % output image. Assignment defines the output image's * color map and % sets each pixel's color by reclassification in the reduced * tree. % Our goal is to minimize the numerical discrepancies between the * original % colors and quantized colors (quantization error). % % * Classification begins by initializing a color description tree of % * sufficient depth to represent each possible input color in a leaf. % However, * it is impractical to generate a fully-formed color % description tree in the * classification phase for realistic values of % cmax. If colors components in * the input image are quantized to k-bit % precision, so that cmax= 2k-1, the * tree would need k levels below the % root node to allow representing each * possible input color in a leaf. % This becomes prohibitive because the tree's * total number of nodes is % 1 + sum(i=1,k,8k). % % A complete tree would * require 19,173,961 nodes for k = 8, cmax = 255. % Therefore, to avoid * building a fully populated tree, QUANTIZE: (1) % Initializes data structures * for nodes only as they are needed; (2) % Chooses a maximum depth for the tree * as a function of the desired % number of colors in the output image * (currently log2(colormap size)). % % For each pixel in the input image, * classification scans downward from % the root of the color description tree. * At each level of the tree it % identifies the single node which represents a * cube in RGB space % containing the pixel's color. It updates the following * data for each % such node: % % n1: Number of pixels whose color is contained * in the RGB cube % which this node represents; % % n2: Number of pixels whose * color is not represented in a node at % lower depth in the tree; initially, * n2 = 0 for all nodes except % leaves of the tree. % % Sr, Sg, Sb: Sums of the * red, green, and blue component values for % all pixels not classified at a * lower depth. The combination of % these sums and n2 will ultimately * characterize the mean color of a % set of pixels represented by this node. % * % E: The distance squared in RGB space between each pixel contained % within * a node and the nodes' center. This represents the quantization % error for a * node. % % Reduction repeatedly prunes the tree until the number of nodes with * % n2 > 0 is less than or equal to the maximum number of colors allowed % in * the output image. On any given iteration over the tree, it selects % those * nodes whose E count is minimal for pruning and merges their % color * statistics upward. It uses a pruning threshold, Ep, to govern % node * selection as follows: % % Ep = 0 % while number of nodes with (n2 > 0) > * required maximum number of colors % prune all nodes such that E <= Ep % Set * Ep to minimum E in remaining nodes % % This has the effect of minimizing any * quantization error when merging % two nodes together. % % When a node to be * pruned has offspring, the pruning procedure invokes % itself recursively in * order to prune the tree from the leaves upward. % n2, Sr, Sg, and Sb in a * node being pruned are always added to the % corresponding data in that node's * parent. This retains the pruned % node's color characteristics for later * averaging. % % For each node, n2 pixels exist for which that node represents * the % smallest volume in RGB space containing those pixel's colors. When n2 % * > 0 the node will uniquely define a color in the output image. At the % * beginning of reduction, n2 = 0 for all nodes except a the leaves of % the * tree which represent colors present in the input image. % % The other pixel * count, n1, indicates the total number of colors % within the cubic volume * which the node represents. This includes n1 - % n2 pixels whose colors should * be defined by nodes at a lower level in % the tree. % % Assignment generates * the output image from the pruned tree. The % output image consists of two * parts: (1) A color map, which is an % array of color descriptions (RGB * triples) for each color present in % the output image; (2) A pixel array, * which represents each pixel as % an index into the color map array. % % * First, the assignment phase makes one pass over the pruned color % * description tree to establish the image's color map. For each node % with n2 * > 0, it divides Sr, Sg, and Sb by n2 . This produces the % mean color of all * pixels that classify no lower than this node. Each % of these colors becomes * an entry in the color map. % % Finally, the assignment phase reclassifies * each pixel in the pruned % tree to identify the deepest node containing the * pixel's color. The % pixel's value in the pixel array becomes the index of * this node's mean % color in the color map. % % With the permission of USC * Information Sciences Institute, 4676 Admiralty % Way, Marina del Rey, * California 90292, this code was adapted from module % ALCOLS written by Paul * Raveling. % % The names of ISI and USC are not used in advertising or * publicity % pertaining to distribution of the software without prior specific * % written permission from ISI. % */ static final boolean QUICK = false; static final int MAX_RGB = 255; static final int MAX_NODES = 266817; static final int MAX_TREE_DEPTH = 8; // these are precomputed in advance static int[] SQUARES; static int[] SHIFT; static { SQUARES = new int[MAX_RGB + MAX_RGB + 1]; for (int i = -MAX_RGB; i <= MAX_RGB; i++) { SQUARES[i + MAX_RGB] = i * i; } SHIFT = new int[MAX_TREE_DEPTH + 1]; for (int i = 0; i < MAX_TREE_DEPTH + 1; ++i) { SHIFT[i] = 1 << (15 - i); } } private Quantize() { // Prevent Instantiation } /** * Reduce the image to the given number of colors. The pixels are reduced in * place. * * @return The new color palette. */ public static int[] quantizeImage(int[][] pixels, int maxColors) { Cube cube = new Cube(pixels, maxColors); cube.classification(); cube.reduction(); cube.assignment(); return cube.colormap; } static class Cube { int[][] pixels; int maxColors; int[] colormap; Node root; int depth; // counter for the number of colors in the cube. this gets // recalculated often. int colors; // counter for the number of nodes in the tree int nodes; Cube(int[][] pixels, int maxColors) { this.pixels = pixels; this.maxColors = maxColors; int i = maxColors; // tree_depth = log max_colors // 4 for (depth = 1; i != 0; depth++) { i /= 4; } if (depth > 1) { --depth; } if (depth > MAX_TREE_DEPTH) { depth = MAX_TREE_DEPTH; } else if (depth < 2) { depth = 2; } root = new Node(this); } /** * Procedure Classification begins by initializing a color description tree of * sufficient depth to represent each possible input color in a leaf. However, * it is impractical to generate a fully-formed color description tree in the * classification phase for realistic values of cmax. If colors components in * the input image are quantized to k-bit precision, so that cmax= 2k-1, the * tree would need k levels below the root node to allow representing each * possible input color in a leaf. This becomes prohibitive because the tree's * total number of nodes is 1 + sum(i=1,k,8k). * * A complete tree would require 19,173,961 nodes for k = 8, cmax = 255. * Therefore, to avoid building a fully populated tree, QUANTIZE: (1) * Initializes data structures for nodes only as they are needed; (2) Chooses a * maximum depth for the tree as a function of the desired number of colors in * the output image (currently log2(colormap size)). * * For each pixel in the input image, classification scans downward from the * root of the color description tree. At each level of the tree it identifies * the single node which represents a cube in RGB space containing It updates * the following data for each such node: * * number_pixels : Number of pixels whose color is contained in the RGB cube * which this node represents; * * unique : Number of pixels whose color is not represented in a node at lower * depth in the tree; initially, n2 = 0 for all nodes except leaves of the tree. * * total_red/green/blue : Sums of the red, green, and blue component values for * all pixels not classified at a lower depth. The combination of these sums and * n2 will ultimately characterize the mean color of a set of pixels represented * by this node. */ void classification() { int[][] pixels = this.pixels; int width = pixels.length; int height = pixels[0].length; // convert to indexed color for (int x = width; x-- > 0;) { for (int y = height; y-- > 0;) { int pixel = pixels[x][y]; int red = (pixel >> 16) & 0xFF; int green = (pixel >> 8) & 0xFF; int blue = (pixel >> 0) & 0xFF; // a hard limit on the number of nodes in the tree if (nodes > MAX_NODES) { System.out.println(""pruning""); root.pruneLevel(); --depth; } // walk the tree to depth, increasing the // number_pixels count for each node Node node = root; for (int level = 1; level <= depth; ++level) { int id = (((red > node.midRed ? 1 : 0) << 0) | ((green > node.midGreen ? 1 : 0) << 1) | ((blue > node.midBlue ? 1 : 0) << 2)); if (node.child[id] == null) { new Node(node, id, level); } node = node.child[id]; node.numberPixels += SHIFT[level]; } ++node.unique; node.totalRed += red; node.totalGreen += green; node.totalBlue += blue; } } } /* * reduction repeatedly prunes the tree until the number of nodes with unique > * 0 is less than or equal to the maximum number of colors allowed in the output * image. * * When a node to be pruned has offspring, the pruning procedure invokes itself * recursively in order to prune the tree from the leaves upward. The statistics * of the node being pruned are always added to the corresponding data in that * node's parent. This retains the pruned node's color characteristics for later * averaging. */ void reduction() { int threshold = 1; while (colors > maxColors) { colors = 0; threshold = root.reduce(threshold, Integer.MAX_VALUE); } } /** * The result of a closest color search. */ static class Search { int distance; int colorNumber; } /* * Procedure assignment generates the output image from the pruned tree. The * output image consists of two parts: (1) A color map, which is an array of * color descriptions (RGB triples) for each color present in the output image; * (2) A pixel array, which represents each pixel as an index into the color map * array. * * First, the assignment phase makes one pass over the pruned color description * tree to establish the image's color map. For each node with n2 > 0, it * divides Sr, Sg, and Sb by n2. This produces the mean color of all pixels that * classify no lower than this node. Each of these colors becomes an entry in * the color map. * * Finally, the assignment phase reclassifies each pixel in the pruned tree to * identify the deepest node containing the pixel's color. The pixel's value in * the pixel array becomes the index of this node's mean color in the color map. */ void assignment() { colormap = new int[colors]; colors = 0; root.colormap(); int[][] pixels = this.pixels; int width = pixels.length; int height = pixels[0].length; Search search = new Search(); // convert to indexed color for (int x = width; x-- > 0;) { for (int y = height; y-- > 0;) { int pixel = pixels[x][y]; int red = (pixel >> 16) & 0xFF; int green = (pixel >> 8) & 0xFF; int blue = (pixel >> 0) & 0xFF; // walk the tree to find the cube containing that color Node node = root; for (;;) { int id = (((red > node.midRed ? 1 : 0) << 0) | ((green > node.midGreen ? 1 : 0) << 1) | ((blue > node.midBlue ? 1 : 0) << 2)); if (node.child[id] == null) { break; } node = node.child[id]; } if (QUICK) { // if QUICK is set, just use that // node. Strictly speaking, this isn't // necessarily best match. pixels[x][y] = node.colorNumber; } else { // Find the closest color. search.distance = Integer.MAX_VALUE; node.parent.closestColor(red, green, blue, search); pixels[x][y] = search.colorNumber; } } } } /** * A single Node in the tree. */ static class Node { Cube cube; // parent node Node parent; // child nodes Node[] child; int nchild; // our index within our parent int id; // our level within the tree int level; // our color midpoint int midRed; int midGreen; int midBlue; // the pixel count for this node and all children int numberPixels; // the pixel count for this node int unique; // the sum of all pixels contained in this node int totalRed; int totalGreen; int totalBlue; // used to build the colormap int colorNumber; Node(Cube cube) { this.cube = cube; this.parent = this; this.child = new Node[8]; this.id = 0; this.level = 0; this.numberPixels = Integer.MAX_VALUE; this.midRed = (MAX_RGB + 1) >> 1; this.midGreen = (MAX_RGB + 1) >> 1; this.midBlue = (MAX_RGB + 1) >> 1; } Node(Node parent, int id, int level) { this.cube = parent.cube; this.parent = parent; this.child = new Node[8]; this.id = id; this.level = level; // add to the cube ++cube.nodes; if (level == cube.depth) { ++cube.colors; } // add to the parent ++parent.nchild; parent.child[id] = this; // figure out our midpoint int bi = (1 << (MAX_TREE_DEPTH - level)) >> 1; midRed = parent.midRed + ((id & 1) > 0 ? bi : -bi); midGreen = parent.midGreen + ((id & 2) > 0 ? bi : -bi); midBlue = parent.midBlue + ((id & 4) > 0 ? bi : -bi); } /** * Remove this child node, and make sure our parent absorbs our pixel * statistics. */ void pruneChild() { --parent.nchild; parent.unique += unique; parent.totalRed += totalRed; parent.totalGreen += totalGreen; parent.totalBlue += totalBlue; parent.child[id] = null; --cube.nodes; cube = null; parent = null; } /** * Prune the lowest layer of the tree. */ void pruneLevel() { if (nchild != 0) { for (int i = 0; i < 8; i++) { if (child[i] != null) { child[i].pruneLevel(); } } } if (level == cube.depth) { pruneChild(); } } /** * Remove any nodes that have fewer than threshold pixels. Also, as long as * we're walking the tree: * * - figure out the color with the fewest pixels - recalculate the total number * of colors in the tree */ int reduce(int threshold, int nextThreshold) { if (nchild != 0) { for (int i = 0; i < 8; i++) { if (child[i] != null) { nextThreshold = child[i].reduce(threshold, nextThreshold); } } } if (numberPixels <= threshold) { pruneChild(); } else { if (unique != 0) { cube.colors++; } if (numberPixels < nextThreshold) { nextThreshold = numberPixels; } } return nextThreshold; } /* * colormap traverses the color cube tree and notes each colormap entry. A * colormap entry is any node in the color cube tree where the number of unique * colors is not zero. */ void colormap() { if (nchild != 0) { for (int i = 0; i < 8; i++) { if (child[i] != null) { child[i].colormap(); } } } if (unique != 0) { int r = ((totalRed + (unique >> 1)) / unique); int g = ((totalGreen + (unique >> 1)) / unique); int b = ((totalBlue + (unique >> 1)) / unique); cube.colormap[cube.colors] = (((0xFF) << 24) | ((r & 0xFF) << 16) | ((g & 0xFF) << 8) | ((b & 0xFF) << 0)); colorNumber = cube.colors++; } } /* * ClosestColor traverses the color cube tree at a particular node and * determines which colormap entry best represents the input color. */ void closestColor(int red, int green, int blue, Search search) { if (nchild != 0) { for (int i = 0; i < 8; i++) { if (child[i] != null) { child[i].closestColor(red, green, blue, search); } } } if (unique != 0) { int color = cube.colormap[colorNumber]; int distance = distance(color, red, green, blue); if (distance < search.distance) { search.distance = distance; search.colorNumber = colorNumber; } } } /** * Figure out the distance between this node and som color. */ static final int distance(int color, int r, int g, int b) { return (SQUARES[((color >> 16) & 0xFF) - r + MAX_RGB] + SQUARES[((color >> 8) & 0xFF) - g + MAX_RGB] + SQUARES[((color >> 0) & 0xFF) - b + MAX_RGB]); } public String toString() { StringBuilder buf = new StringBuilder(); if (parent == this) { buf.append(""root""); } else { buf.append(""node""); } buf.append(' '); buf.append(level); buf.append("" [""); buf.append(midRed); buf.append(','); buf.append(midGreen); buf.append(','); buf.append(midBlue); buf.append(']'); return new String(buf); } } } }" " package com.rs.cache.loaders.model; import java.awt.Color; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.IOException; import java.nio.ByteBuffer; import javax.imageio.ImageIO; import com.rs.cache.Store; public class RS3Tex { private int id; private byte[] data; private int[] pixels; private byte[] imageData; private BufferedImage image; public RS3Tex(int id) { this.id = id; } public void decode(Store cache, boolean quantize) { data = cache.getIndices()[43].getFile(id, 0); final byte format = (byte) (data[0] & 0xFF); try { switch (format) { case 1: byte[] tempPixels = new byte[data.length - 5]; System.arraycopy(data, 5, tempPixels, 0, data.length - 5); pixels = method2671(tempPixels, false, quantize); break; case 6: int[] var14 = null; int offset = 1; for (int i = 0; i < 6; ++i) { int someLength = (data[offset] & 255) << 24 | (data[1 + offset] & 255) << 16 | (data[offset + 2] & 255) << 8 | data[3 + offset] & 255; byte[] var11 = new byte[someLength]; System.arraycopy(data, offset + 4, var11, 0, someLength); int[] var12 = method2671(var11, false, quantize); if (i == 0) { var14 = new int[var12.length * 6]; } System.arraycopy(var12, 0, var14, var12.length * i, var12.length); offset += 4 + someLength; } pixels = var14; break; default: throw new IllegalStateException(""Unknown format="" + format); } } catch (Exception e) { e.printStackTrace(); } } private int[] method2671(byte[] imageData, boolean var2, boolean quantize) throws IOException { BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageData)); this.imageData = imageData; if (quantize) image = ColorQuantizer.quantize(image, Color.BLACK); this.image = BufferedImageUtils.flipHoriz(image); if (image == null) { return null; } else { int[] var5 = getRGB(image); if (var2) { for (int var6 = image.getHeight() - 1; var6 >= 0; --var6) { int var7 = var6 * image.getWidth(); for (int var8 = (var6 + 1) * image.getWidth(); var7 < var8; ++var7) { --var8; int var9 = var5[var7]; var5[var7] = var5[var8]; var5[var8] = var9; } } } return var5; } } private static int[] getRGB(BufferedImage bufferedimage) { if (bufferedimage.getType() == 10 || bufferedimage.getType() == 0) { int[] is = null; is = bufferedimage.getRaster().getPixels(0, 0, bufferedimage.getWidth(), bufferedimage.getHeight(), is); int[] is_6_ = (new int[bufferedimage.getWidth() * bufferedimage.getHeight()]); if (bufferedimage.getType() == 10) { for (int i_7_ = 0; i_7_ < is_6_.length; i_7_++) { is_6_[i_7_] = is[i_7_] + ((is[i_7_] << 16) + (is[i_7_] << 8)) + -16777216; } } else { for (int i_8_ = 0; i_8_ < is_6_.length; i_8_++) { int i_9_ = 2 * i_8_; is_6_[i_8_] = ((is[i_9_ + 1] << 24) + is[i_9_] + ((is[i_9_] << 16) + (is[i_9_] << 8))); } } return is_6_; } return bufferedimage.getRGB(0, 0, bufferedimage.getWidth(), bufferedimage.getHeight(), null, 0, bufferedimage.getWidth()); } public ByteBuffer toByteBuffer() { ByteBuffer buffer = ByteBuffer.allocateDirect(pixels.length * 4); for (int pixel : pixels) { buffer.put((byte) ((pixel >> 16) & 0xFF)); buffer.put((byte) ((pixel >> 8) & 0xFF)); buffer.put((byte) (pixel & 0xFF)); buffer.put((byte) (pixel >> 24)); } buffer.flip(); return buffer; } public int getId() { return id; } public byte[] getData() { return data; } public int[] getPixels() { return pixels; } public byte[] getImageData() { return imageData; } public BufferedImage getImage() { return image; } } " " package com.rs.cache.loaders.model; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.lang.SuppressWarnings; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.cache.Store; import com.rs.cache.loaders.ParticleProducerDefinitions; import com.rs.lib.io.InputStream; import com.rs.lib.io.OutputStream; import com.rs.lib.util.RSColor; import com.rs.lib.util.Utils; public class RSModel { public int id; public byte priority; public int version = 12; public int vertexCount = 0; public int faceCount; public int texturedFaceCount; public int maxVertexUsed = 0; public int textureUVCoordCount; public float[] textureCoordU; public float[] textureCoordV; public byte[] uvCoordVertexA; public byte[] uvCoordVertexB; public byte[] uvCoordVertexC; public byte[] facePriorities; public byte[] faceAlpha; public byte[] faceRenderTypes; public byte[] textureRenderTypes; public byte[] textureRotationY; public byte[] textureUVDirections; public int[] particleLifespanZ; public int[] textureScaleX; public int[] textureScaleY; public int[] textureScaleZ; public int[] texturePrimaryColor; public int[] textureSecondaryColor; public int[] faceBones; public int[] vertexX; public int[] vertexY; public int[] vertexZ; public int[] vertexBones; public int[] vertexUVOffset; public short[] faceTextureIndexes; public short[] textureTriangleX; public short[] textureTriangleY; public short[] textureTriangleZ; public short[] faceA; public short[] faceB; public short[] faceC; public short[] faceTextures; public short[] faceColors; public EmitterConfig[] emitterConfigs; public MagnetConfig[] magnetConfigs; public BillBoardConfig[] billBoardConfigs; public short[] aShortArray1980; public short[] aShortArray1981; public static void main(String[] args) throws IOException { Cache.init(""../cache/""); //RSMesh mesh = getMesh(NPCDefinitions.getNPCDefinitions(0).headModels[0]); // AnimationDefinitions defs = AnimationDefinitions.getDefs(7280); // RSModel mesh = getMesh(29132); // System.out.println(mesh.vertexBones.length); // System.out.println(AnimationFrameSet.getFrameSet(defs.getFrameSets()[0].id).getFrames()[0]); List meshes = new ArrayList<>(); int baseCol = RSColor.RGB_to_HSL(238, 213, 54); for (int i = 0;i < Cache.STORE.getIndex(IndexType.MODELS).getLastArchiveId();i++) { RSModel model = getMesh(i); if (model.getAvgColor() == 0) continue; if (model != null && Math.abs(baseCol-model.getAvgColor()) < 100 /*&& model.faceCount < 32*/) meshes.add(model); } meshes.sort((m1, m2) -> { //if ((m1.vertexCount + m1.faceCount) == (m2.vertexCount + m2.faceCount)) return Math.abs(m1.getAvgColor()-baseCol) - Math.abs(m2.getAvgColor()-baseCol); //return (m1.vertexCount + m1.faceCount + Math.abs(m1.getAvgColor()-baseCol)) / 2 - (m2.vertexCount + m2.faceCount + Math.abs(m2.getAvgColor()-baseCol)) / 2; }); int count = 0; for (RSModel model : meshes) { if (count++ > 100) break; System.out.println(model.id + "" - v"" + model.vertexCount + "" - f"" + model.faceCount + "" - "" + Math.abs(model.getAvgColor()-baseCol)); } } public short getAvgColor() { int total = 0; int count = 0; for (int i = 0;i < faceCount;i++) { if (faceColors[i] == Short.MAX_VALUE) continue; total += faceColors[i]; count++; } if (count == 0) return 0; return (short) (total / count); } RSModel(byte[] data, boolean rs3) { version = 12; priority = (byte) 0; vertexCount = 0; maxVertexUsed = 0; faceCount = 0; priority = (byte) 0; texturedFaceCount = 0; if (rs3) { decodeRS3(data); } else { if (data[data.length - 1] == -1 && data[data.length - 2] == -1) { this.decode663(data); } else { this.decode317(data); } } } public RSModel(byte[] data) { this(data, false); } final int getFaces(RSModel rsmesh_1, int i_2, short s_3) { int i_4 = rsmesh_1.vertexX[i_2]; int i_5 = rsmesh_1.vertexY[i_2]; int i_6 = rsmesh_1.vertexZ[i_2]; for (int i_7 = 0; i_7 < this.vertexCount; i_7++) { if (i_4 == this.vertexX[i_7] && i_5 == this.vertexY[i_7] && i_6 == this.vertexZ[i_7]) { this.aShortArray1980[i_7] |= s_3; return i_7; } } this.vertexX[this.vertexCount] = i_4; this.vertexY[this.vertexCount] = i_5; this.vertexZ[this.vertexCount] = i_6; this.aShortArray1980[this.vertexCount] = s_3; this.vertexBones[this.vertexCount] = rsmesh_1.vertexBones != null ? rsmesh_1.vertexBones[i_2] : -1; return this.vertexCount++; } void decodeRS3(byte[] is) { faceCount = 0; priority = (byte) 0; texturedFaceCount = 0; ByteBuffer[] buffers = new ByteBuffer[7]; for (int i = 0; i < buffers.length; i++) buffers[i] = ByteBuffer.wrap(is); int modelType = buffers[0].get() & 0xFF; if (modelType != 1) System.out.println(""Invalid model identifier: "" + modelType); else { buffers[0].get(); version = buffers[0].get() & 0xFF; buffers[0].position(is.length - 26); vertexCount = buffers[0].getShort() & 0xFFFF; faceCount = buffers[0].getShort() & 0xFFFF; texturedFaceCount = buffers[0].getShort() & 0xFFFF; int flags = buffers[0].get() & 0xFF; boolean hasFaceRenderTypes = (flags & 0x1) == 1; boolean hasParticleEffects = (flags & 0x2) == 2; boolean hasBillboards = (flags & 0x4) == 4; boolean hasExternalVertexBones = (flags & 0x10) == 16; boolean hasExternalFaceBones = (flags & 0x20) == 32; boolean hasExternalPriorities = (flags & 0x40) == 64; boolean hasTextureUV = (flags & 0x80) == 128; int modelPriority = buffers[0].get() & 0xFF; int hasFaceAlpha = buffers[0].get() & 0xFF; int hasFaceBones = buffers[0].get() & 0xFF; int hasFaceTextures = buffers[0].get() & 0xFF; int hasVertexBones = buffers[0].get() & 0xFF; int vertexXDataSize = buffers[0].getShort() & 0xFFFF; int vertexYDataSize = buffers[0].getShort() & 0xFFFF; int vertexZDataSize = buffers[0].getShort() & 0xFFFF; int faceDataSize = buffers[0].getShort() & 0xFFFF; int faceTextureIndexSize = buffers[0].getShort() & 0xFFFF; int vertexBoneDataSize = buffers[0].getShort() & 0xFFFF; int faceBoneDataSize = buffers[0].getShort() & 0xFFFF; if (!hasExternalVertexBones) { if (hasVertexBones == 1) vertexBoneDataSize = vertexCount; else vertexBoneDataSize = 0; } if (!hasExternalFaceBones) { if (hasFaceBones == 1) faceBoneDataSize = faceCount; else faceBoneDataSize = 0; } int simpleTexFaceCnt = 0; int complexTexFaceCnt = 0; int cubeTexFaceCnt = 0; if (texturedFaceCount > 0) { textureRenderTypes = new byte[texturedFaceCount]; buffers[0].position(3); for (int tri = 0; tri < texturedFaceCount; tri++) { byte renderType = textureRenderTypes[tri] = buffers[0].get(); if (renderType == 0) simpleTexFaceCnt++; if (renderType >= 1 && renderType <= 3) complexTexFaceCnt++; if (renderType == 2) cubeTexFaceCnt++; } } int accumulator = 3 + texturedFaceCount; int vertexReadFlagOffset = accumulator; accumulator += vertexCount; int face_render_info_offset = accumulator; if (hasFaceRenderTypes) accumulator += faceCount; int face_read_flag_offset = accumulator; accumulator += faceCount; int face_priority_offset = accumulator; if (modelPriority == 255) accumulator += faceCount; int face_bone_offset = accumulator; accumulator += faceBoneDataSize; int vertex_bone_offset = accumulator; accumulator += vertexBoneDataSize; int face_alpha_offset = accumulator; if (hasFaceAlpha == 1) accumulator += faceCount; int face_data_offset = accumulator; accumulator += faceDataSize; int face_texture_offset = accumulator; if (hasFaceTextures == 1) accumulator += faceCount * 2; int face_texture_index_offset = accumulator; accumulator += faceTextureIndexSize; int face_colour_offset = accumulator; accumulator += faceCount * 2; int vertex_x_data_offset = accumulator; accumulator += vertexXDataSize; int vertex_y_data_offset = accumulator; accumulator += vertexYDataSize; int vertex_z_data_offset = accumulator; accumulator += vertexZDataSize; int simple_tex_pmn_offset = accumulator; accumulator += simpleTexFaceCnt * 6; int complex_tex_pmn_offset = accumulator; accumulator += complexTexFaceCnt * 6; int tex_chunk_size = 6; if (version == 14) tex_chunk_size = 7; else if (version >= 15) tex_chunk_size = 9; int tex_scale_offset = accumulator; accumulator += complexTexFaceCnt * tex_chunk_size; int tex_rot_offset = accumulator; accumulator += complexTexFaceCnt; int tex_dir_offset = accumulator; accumulator += complexTexFaceCnt; int particleZLifespanAndTextureColorOffset = accumulator; accumulator += complexTexFaceCnt + cubeTexFaceCnt * 2; int extras_offset = accumulator; int face_uv_index_offset = is.length; int vertex_uv_offset = is.length; int tex_coord_u_offset = is.length; int tex_coord_v_offset = is.length; if (hasTextureUV) { ByteBuffer uvBuffer = ByteBuffer.wrap(is); uvBuffer.position(is.length - 26); uvBuffer.position(uvBuffer.position() - is[uvBuffer.position() - 1]); textureUVCoordCount = uvBuffer.getShort() & 0xFFFF; int extras_data_size = uvBuffer.getShort() & 0xFFFF; int uv_index_data_size = uvBuffer.getShort() & 0xFFFF; face_uv_index_offset = extras_offset + extras_data_size; vertex_uv_offset = face_uv_index_offset + uv_index_data_size; tex_coord_u_offset = vertex_uv_offset + vertexCount; tex_coord_v_offset = tex_coord_u_offset + textureUVCoordCount * 2; } vertexX = new int[vertexCount]; vertexY = new int[vertexCount]; vertexZ = new int[vertexCount]; faceA = new short[faceCount]; faceB = new short[faceCount]; faceC = new short[faceCount]; if (hasVertexBones == 1) vertexBones = new int[vertexCount]; if (hasFaceRenderTypes) faceRenderTypes = new byte[faceCount]; if (modelPriority == 255) facePriorities = new byte[faceCount]; else priority = (byte) modelPriority; if (hasFaceAlpha == 1) faceAlpha = new byte[faceCount]; if (hasFaceBones == 1) faceBones = new int[faceCount]; if (hasFaceTextures == 1) faceTextures = new short[faceCount]; if (hasFaceTextures == 1 && (texturedFaceCount > 0 || textureUVCoordCount > 0)) faceTextureIndexes = new short[faceCount]; faceColors = new short[faceCount]; if (texturedFaceCount > 0) { textureTriangleX = new short[texturedFaceCount]; textureTriangleY = new short[texturedFaceCount]; textureTriangleZ = new short[texturedFaceCount]; if (complexTexFaceCnt > 0) { textureScaleX = new int[complexTexFaceCnt]; textureScaleY = new int[complexTexFaceCnt]; textureScaleZ = new int[complexTexFaceCnt]; textureRotationY = new byte[complexTexFaceCnt]; textureUVDirections = new byte[complexTexFaceCnt]; particleLifespanZ = new int[complexTexFaceCnt]; } if (cubeTexFaceCnt > 0) { texturePrimaryColor = new int[cubeTexFaceCnt]; textureSecondaryColor = new int[cubeTexFaceCnt]; } } buffers[0].position(vertexReadFlagOffset); buffers[1].position(vertex_x_data_offset); buffers[2].position(vertex_y_data_offset); buffers[3].position(vertex_z_data_offset); buffers[4].position(vertex_bone_offset); int prevX = 0; int prevY = 0; int prevZ = 0; for (int point = 0; point < vertexCount; point++) { int component_flags = buffers[0].get() & 0xFF; int dx = 0; if ((component_flags & 0x1) != 0) dx = ByteBufferUtils.getSmart1(buffers[1]); int dy = 0; if ((component_flags & 0x2) != 0) dy = ByteBufferUtils.getSmart1(buffers[2]); int dz = 0; if ((component_flags & 0x4) != 0) dz = ByteBufferUtils.getSmart1(buffers[3]); vertexX[point] = prevX + dx; vertexY[point] = prevY + dy; vertexZ[point] = prevZ + dz; prevX = vertexX[point]; prevY = vertexY[point]; prevZ = vertexZ[point]; if (hasVertexBones == 1) { if (hasExternalVertexBones) vertexBones[point] = ByteBufferUtils.getSmart2(buffers[4]); else { vertexBones[point] = buffers[4].get() & 0xFF; if (vertexBones[point] == 255) vertexBones[point] = -1; } } } if (textureUVCoordCount > 0) { buffers[0].position(vertex_uv_offset); buffers[1].position(tex_coord_u_offset); buffers[2].position(tex_coord_v_offset); vertexUVOffset = new int[vertexCount]; int coord = 0; int size = 0; for (; coord < vertexCount; coord++) { vertexUVOffset[coord] = size; size += buffers[0].get() & 0xFF; } uvCoordVertexA = new byte[faceCount]; uvCoordVertexB = new byte[faceCount]; uvCoordVertexC = new byte[faceCount]; textureCoordU = new float[textureUVCoordCount]; textureCoordV = new float[textureUVCoordCount]; for (coord = 0; coord < textureUVCoordCount; coord++) { textureCoordU[coord] = (buffers[1].getShort() / 4096.0F); textureCoordV[coord] = (buffers[2].getShort() / 4096.0F); } } buffers[0].position(face_colour_offset); buffers[1].position(face_render_info_offset); buffers[2].position(face_priority_offset); buffers[3].position(face_alpha_offset); buffers[4].position(face_bone_offset); buffers[5].position(face_texture_offset); buffers[6].position(face_texture_index_offset); for (int tri = 0; tri < faceCount; tri++) { faceColors[tri] = (short) (buffers[0].getShort() & 0xFFFF); if (hasFaceRenderTypes) faceRenderTypes[tri] = buffers[1].get(); if (modelPriority == 255) facePriorities[tri] = buffers[2].get(); if (hasFaceAlpha == 1) faceAlpha[tri] = buffers[3].get(); if (hasFaceBones == 1) { if (hasExternalFaceBones) faceBones[tri] = ByteBufferUtils.getSmart2(buffers[4]); else { faceBones[tri] = buffers[4].get() & 0xFF; if (faceBones[tri] == 255) faceBones[tri] = -1; } } if (hasFaceTextures == 1) faceTextures[tri] = (short) ((buffers[5].getShort() & 0xFFFF) - 1); if (faceTextureIndexes != null) { if (faceTextures[tri] != -1) { if (version >= 16) faceTextureIndexes[tri] = (short) (ByteBufferUtils.getSmart(buffers[6]) - 1); else faceTextureIndexes[tri] = (short) ((buffers[6].get() & 0xFF) - 1); } else faceTextureIndexes[tri] = (short) -1; } } maxVertexUsed = -1; buffers[0].position(face_data_offset); buffers[1].position(face_read_flag_offset); buffers[2].position(face_uv_index_offset); calculateMaxDepthRS3(buffers[0], buffers[1], buffers[2]); buffers[0].position(simple_tex_pmn_offset); buffers[1].position(complex_tex_pmn_offset); buffers[2].position(tex_scale_offset); buffers[3].position(tex_rot_offset); buffers[4].position(tex_dir_offset); buffers[5].position(particleZLifespanAndTextureColorOffset); decodeTexturedTrianglesRS3(buffers[0], buffers[1], buffers[2], buffers[3], buffers[4], buffers[5]); buffers[0].position(extras_offset); if (hasParticleEffects) { int emitterCount = buffers[0].get() & 0xFF; if (emitterCount > 0) { emitterConfigs = new EmitterConfig[emitterCount]; for (int idx = 0; idx < emitterCount; idx++) { int type = buffers[0].getShort() & 0xFFFF; int face = buffers[0].getShort() & 0xFFFF; byte pri; if (modelPriority == 255) pri = facePriorities[face]; else pri = (byte) modelPriority; emitterConfigs[idx] = new EmitterConfig(type, face, faceA[face], faceB[face], faceC[face], pri); } } int magnetCount = buffers[0].get() & 0xFF; if (magnetCount > 0) { magnetConfigs = new MagnetConfig[magnetCount]; for (int face = 0; face < magnetCount; face++) { int skin = buffers[0].getShort() & 0xFFFF; int point = buffers[0].getShort() & 0xFFFF; magnetConfigs[face] = new MagnetConfig(skin, point); } } } if (hasBillboards) { int billBoardCount = buffers[0].get() & 0xFF; if (billBoardCount > 0) { billBoardConfigs = new BillBoardConfig[billBoardCount]; for (int vertex = 0; vertex < billBoardCount; vertex++) { int type = buffers[0].getShort() & 0xFFFF; int face = buffers[0].getShort() & 0xFFFF; int priority; if (hasExternalPriorities) priority = ByteBufferUtils.getSmart2(buffers[0]); else { priority = buffers[0].get() & 0xFF; if (priority == 255) priority = -1; } byte magnitude = buffers[0].get(); billBoardConfigs[vertex] = new BillBoardConfig(type, face, priority, magnitude); } } } } } void decode663(byte[] data) { InputStream first = new InputStream(data); InputStream second = new InputStream(data); InputStream third = new InputStream(data); InputStream fourth = new InputStream(data); InputStream fifth = new InputStream(data); InputStream sixth = new InputStream(data); InputStream seventh = new InputStream(data); first.offset = data.length - 23; this.vertexCount = first.readUnsignedShort(); this.faceCount = first.readUnsignedShort(); this.texturedFaceCount = first.readUnsignedByte(); int footerFlags = first.readUnsignedByte(); boolean hasFaceTypes = (footerFlags & 0x1) == 1; boolean hasParticleEffects = (footerFlags & 0x2) == 2; boolean hasBillboards = (footerFlags & 0x4) == 4; boolean hasVersion = (footerFlags & 0x8) == 8; if (hasVersion) { first.offset -= 7; this.version = first.readUnsignedByte(); first.offset += 6; } int modelPriority = first.readUnsignedByte(); int hasFaceAlpha = first.readUnsignedByte(); int hasFaceSkins = first.readUnsignedByte(); int hasFaceTextures = first.readUnsignedByte(); int hasVertexSkins = first.readUnsignedByte(); int modelVerticesX = first.readUnsignedShort(); int modelVerticesY = first.readUnsignedShort(); int modelVerticesZ = first.readUnsignedShort(); int faceIndices = first.readUnsignedShort(); int textureIndices = first.readUnsignedShort(); int simpleTextureFaceCount = 0; int complexTextureFaceCount = 0; int cubeTextureFaceCount = 0; if (this.texturedFaceCount > 0) { this.textureRenderTypes = new byte[this.texturedFaceCount]; first.offset = 0; for (int i = 0; i < this.texturedFaceCount; i++) { byte type = this.textureRenderTypes[i] = (byte) first.readByte(); if (type == 0) { ++simpleTextureFaceCount; } if (type >= 1 && type <= 3) { ++complexTextureFaceCount; } if (type == 2) { ++cubeTextureFaceCount; } } } int offset = this.texturedFaceCount; int vertexFlagsOffset = offset; //System.out.println(""1: "" + vertexFlagsOffset); offset += this.vertexCount; int faceTypesOffset = offset; //System.out.println(""2: "" + (faceTypesOffset - vertexFlagsOffset)); if (hasFaceTypes) { offset += this.faceCount; } int facesCompressTypeOffset = offset; //System.out.println(""3: "" + (facesCompressTypeOffset - faceTypesOffset)); offset += this.faceCount; int facePrioritiesOffset = offset; //System.out.println(""4: "" + (facePrioritiesOffset - facesCompressTypeOffset)); if (modelPriority == 255) { offset += this.faceCount; } int faceSkinsOffset = offset; //System.out.println(""5: "" + (faceSkinsOffset - facePrioritiesOffset)); if (hasFaceSkins == 1) { offset += this.faceCount; } int vertexSkinsOffset = offset; //System.out.println(""6: "" + (vertexSkinsOffset - faceSkinsOffset)); if (hasVertexSkins == 1) { offset += this.vertexCount; } int faceAlphasOffset = offset; //System.out.println(""7: "" + (faceAlphasOffset - vertexSkinsOffset)); if (hasFaceAlpha == 1) { offset += this.faceCount; } int faceIndicesOffset = offset; //System.out.println(""8: "" + (faceIndicesOffset - faceAlphasOffset)); offset += faceIndices; int faceMaterialsOffset = offset; //System.out.println(""9: "" + (faceMaterialsOffset - faceIndicesOffset)); if (hasFaceTextures == 1) { offset += this.faceCount * 2; } int faceTextureIndicesOffset = offset; //System.out.println(""10: "" + (faceTextureIndicesOffset - faceMaterialsOffset)); offset += textureIndices; int faceColorsOffset = offset; //System.out.println(""11: "" + (faceColorsOffset - faceTextureIndicesOffset)); offset += this.faceCount * 2; int vertexXOffsetOffset = offset; //System.out.println(""12: "" + (vertexXOffsetOffset - faceColorsOffset)); offset += modelVerticesX; int vertexYOffsetOffset = offset; //System.out.println(""13: "" + (vertexYOffsetOffset - vertexXOffsetOffset)); offset += modelVerticesY; int vertexZOffsetOffset = offset; //System.out.println(""14: "" + (vertexZOffsetOffset - vertexYOffsetOffset)); offset += modelVerticesZ; int simpleTexturesOffset = offset; //System.out.println(""15: "" + (simpleTexturesOffset - vertexZOffsetOffset)); offset += simpleTextureFaceCount * 6; int complexTexturesOffset = offset; //System.out.println(""16: "" + (complexTexturesOffset - simpleTexturesOffset)); offset += complexTextureFaceCount * 6; byte textureBytes = 6; if (this.version == 14) { textureBytes = 7; } else if (this.version >= 15) { textureBytes = 9; } int texturesScaleOffset = offset; //System.out.println(""17: "" + (texturesScaleOffset - complexTexturesOffset)); offset += complexTextureFaceCount * textureBytes; int texturesRotationOffset = offset; //System.out.println(""18: "" + (texturesRotationOffset - texturesScaleOffset)); offset += complexTextureFaceCount; int texturesDirectionOffset = offset; //System.out.println(""19: "" + (texturesDirectionOffset - texturesRotationOffset)); offset += complexTextureFaceCount; int texturesTranslationOffset = offset; //System.out.println(""20: "" + (texturesTranslationOffset - texturesDirectionOffset)); offset += complexTextureFaceCount + cubeTextureFaceCount * 2; this.vertexX = new int[this.vertexCount]; this.vertexY = new int[this.vertexCount]; this.vertexZ = new int[this.vertexCount]; this.faceA = new short[this.faceCount]; this.faceB = new short[this.faceCount]; this.faceC = new short[this.faceCount]; if (hasVertexSkins == 1) { this.vertexBones = new int[this.vertexCount]; } if (hasFaceTypes) { this.faceRenderTypes = new byte[this.faceCount]; } if (modelPriority == 255) { this.facePriorities = new byte[this.faceCount]; } else { this.priority = (byte) modelPriority; } if (hasFaceAlpha == 1) { this.faceAlpha = new byte[this.faceCount]; } if (hasFaceSkins == 1) { this.faceBones = new int[this.faceCount]; } if (hasFaceTextures == 1) { this.faceTextures = new short[this.faceCount]; } if (hasFaceTextures == 1 && this.texturedFaceCount > 0) { this.faceTextureIndexes = new short[this.faceCount]; } this.faceColors = new short[this.faceCount]; if (this.texturedFaceCount > 0) { this.textureTriangleX = new short[this.texturedFaceCount]; this.textureTriangleY = new short[this.texturedFaceCount]; this.textureTriangleZ = new short[this.texturedFaceCount]; if (complexTextureFaceCount > 0) { this.textureScaleX = new int[complexTextureFaceCount]; this.textureScaleY = new int[complexTextureFaceCount]; this.textureScaleZ = new int[complexTextureFaceCount]; this.textureRotationY = new byte[complexTextureFaceCount]; this.textureUVDirections = new byte[complexTextureFaceCount]; this.particleLifespanZ = new int[complexTextureFaceCount]; } if (cubeTextureFaceCount > 0) { this.texturePrimaryColor = new int[cubeTextureFaceCount]; this.textureSecondaryColor = new int[cubeTextureFaceCount]; } } first.offset = vertexFlagsOffset; second.offset = vertexXOffsetOffset; third.offset = vertexYOffsetOffset; fourth.offset = vertexZOffsetOffset; fifth.offset = vertexSkinsOffset; int baseX = 0; int baseY = 0; int baseZ = 0; for (int vertex = 0; vertex < this.vertexCount; vertex++) { int vertexFlags = first.readUnsignedByte(); int xOffset = 0; if ((vertexFlags & 0x1) != 0) { xOffset = second.readSignedSmart(); } int yOffset = 0; if ((vertexFlags & 0x2) != 0) { yOffset = third.readSignedSmart(); } int zOffset = 0; if ((vertexFlags & 0x4) != 0) { zOffset = fourth.readSignedSmart(); } this.vertexX[vertex] = baseX + xOffset; this.vertexY[vertex] = baseY + yOffset; this.vertexZ[vertex] = baseZ + zOffset; baseX = this.vertexX[vertex]; baseY = this.vertexY[vertex]; baseZ = this.vertexZ[vertex]; if (hasVertexSkins == 1) { this.vertexBones[vertex] = fifth.readUnsignedByte(); if (vertexBones[vertex] == 255) vertexBones[vertex] = -1; } } first.offset = faceColorsOffset; second.offset = faceTypesOffset; third.offset = facePrioritiesOffset; fourth.offset = faceAlphasOffset; fifth.offset = faceSkinsOffset; sixth.offset = faceMaterialsOffset; seventh.offset = faceTextureIndicesOffset; for (int face = 0; face < this.faceCount; face++) { this.faceColors[face] = (short) first.readUnsignedShort(); if (hasFaceTypes) { this.faceRenderTypes[face] = (byte) second.readByte(); } if (modelPriority == 255) { this.facePriorities[face] = (byte) third.readByte(); } if (hasFaceAlpha == 1) { this.faceAlpha[face] = (byte) fourth.readByte(); } if (hasFaceSkins == 1) { this.faceBones[face] = fifth.readUnsignedByte(); } if (hasFaceTextures == 1) { this.faceTextures[face] = (short) (sixth.readUnsignedShort() - 1); } if (this.faceTextureIndexes != null) { if (this.faceTextures[face] != -1) { this.faceTextureIndexes[face] = (byte) (seventh.readUnsignedByte() - 1); } else { this.faceTextureIndexes[face] = -1; } } } this.maxVertexUsed = -1; first.offset = faceIndicesOffset; second.offset = facesCompressTypeOffset; this.calculateMaxDepth(first, second); first.offset = simpleTexturesOffset; second.offset = complexTexturesOffset; third.offset = texturesScaleOffset; fourth.offset = texturesRotationOffset; fifth.offset = texturesDirectionOffset; sixth.offset = texturesTranslationOffset; this.decodeTexturedTriangles(first, second, third, fourth, fifth, sixth); first.offset = offset; if (hasParticleEffects) { int particleIdx = first.readUnsignedByte(); if (particleIdx > 0) { this.emitterConfigs = new EmitterConfig[particleIdx]; for (int i = 0; i < particleIdx; i++) { int particleId = first.readUnsignedShort(); int idx = first.readUnsignedShort(); byte pri; if (modelPriority == 255) { pri = this.facePriorities[idx]; } else { pri = (byte) modelPriority; } this.emitterConfigs[i] = new EmitterConfig(particleId, idx, this.faceA[idx], this.faceB[idx], this.faceC[idx], pri); } } int numEffectors = first.readUnsignedByte(); if (numEffectors > 0) { this.magnetConfigs = new MagnetConfig[numEffectors]; for (int i = 0; i < numEffectors; i++) { int effector = first.readUnsignedShort(); int vertex = first.readUnsignedShort(); this.magnetConfigs[i] = new MagnetConfig(effector, vertex); } } } if (hasBillboards) { int billboardIdx = first.readUnsignedByte(); if (billboardIdx > 0) { this.billBoardConfigs = new BillBoardConfig[billboardIdx]; for (int i = 0; i < billboardIdx; i++) { int id = first.readUnsignedShort(); int face = first.readUnsignedShort(); int skin = first.readUnsignedByte(); byte dist = (byte) first.readByte(); this.billBoardConfigs[i] = new BillBoardConfig(id, face, skin, dist); } } } } public byte[] encode() { /* create the master buffer */ OutputStream master = new OutputStream(); /* create the temporary buffers */ OutputStream face_mappings_buffer = new OutputStream(); OutputStream vertex_flags_buffer = new OutputStream(); OutputStream face_types_buffer = new OutputStream(); OutputStream face_index_types_buffer = new OutputStream(); OutputStream face_priorities_buffer = new OutputStream(); OutputStream face_skins_buffer = new OutputStream(); OutputStream vertex_skins_buffer = new OutputStream(); OutputStream face_alphas_buffer = new OutputStream(); OutputStream face_indices_buffer = new OutputStream(); OutputStream face_materials_buffer = new OutputStream(); OutputStream face_textures_buffer = new OutputStream(); OutputStream face_colors_buffer = new OutputStream(); OutputStream vertex_x_buffer = new OutputStream(); OutputStream vertex_y_buffer = new OutputStream(); OutputStream vertex_z_buffer = new OutputStream(); OutputStream simple_textures_buffer = new OutputStream(); OutputStream complex_textures_buffer = new OutputStream(); OutputStream texture_scale_buffer = new OutputStream(); OutputStream texture_rotation_buffer = new OutputStream(); OutputStream texture_direction_buffer = new OutputStream(); OutputStream texture_translation_buffer = new OutputStream(); OutputStream particle_effects_buffer = new OutputStream(); OutputStream footer_buffer = new OutputStream(); OutputStream[] buffers = new OutputStream[] { face_mappings_buffer, //1 vertex_flags_buffer, //2 face_types_buffer, //3 face_index_types_buffer, //4 face_priorities_buffer, //5 face_skins_buffer, //6 vertex_skins_buffer, //7 face_alphas_buffer, //8 face_indices_buffer, //9 face_materials_buffer, //10 face_textures_buffer, //11 face_colors_buffer, //12 vertex_x_buffer, //13 vertex_y_buffer, //14 vertex_z_buffer, //15 simple_textures_buffer, //16 complex_textures_buffer, //17 texture_scale_buffer, //18 texture_rotation_buffer, //19 texture_direction_buffer, //20 texture_translation_buffer, //21 particle_effects_buffer, //22 footer_buffer //23 }; /* serialize the face mapping types */ if (texturedFaceCount > 0) { for (int face = 0; face < texturedFaceCount; face++) { face_mappings_buffer.writeByte(textureRenderTypes[face]); } } /* create the vertices variables */ boolean hasVertexSkins = vertexBones != null; /* serialize the vertices */ int baseX = 0, baseY = 0, baseZ = 0; for (int vertex = 0; vertex < vertexCount; vertex++) { int x = vertexX[vertex]; int y = vertexY[vertex]; int z = vertexZ[vertex]; int xoff = x - baseX; int yoff = y - baseY; int zoff = z - baseZ; int flag = 0; if (xoff != 0) { vertex_x_buffer.writeUnsignedSmart(xoff); flag |= 0x1; } if (yoff != 0) { vertex_y_buffer.writeUnsignedSmart(yoff); flag |= 0x2; } if (zoff != 0) { vertex_z_buffer.writeUnsignedSmart(zoff); flag |= 0x4; } vertex_flags_buffer.writeByte(flag); vertexX[vertex] = baseX + xoff; vertexY[vertex] = baseY + yoff; vertexZ[vertex] = baseZ + zoff; baseX = vertexX[vertex]; baseY = vertexY[vertex]; baseZ = vertexZ[vertex]; if (hasVertexSkins) { vertex_skins_buffer.writeByte(vertexBones[vertex] == -1 ? 255 : vertexBones[vertex]); } } /* create the faces variables */ boolean hasFaceTypes = faceRenderTypes != null; boolean hasFacePriorities = facePriorities != null; boolean hasFaceAlpha = faceAlpha != null; boolean hasFaceSkins = faceBones != null; boolean hasFaceTextures = faceTextures != null; /* serialize the faces */ for (int face = 0; face < faceCount; face++) { face_colors_buffer.writeShort(faceColors[face]); if (hasFaceTypes) { face_types_buffer.writeByte(faceRenderTypes[face]); } if (hasFacePriorities) { face_priorities_buffer.writeByte(facePriorities[face]); } if (hasFaceAlpha) { face_alphas_buffer.writeByte(faceAlpha[face]); } if (hasFaceSkins) { face_skins_buffer.writeByte(faceBones[face]); } if (hasFaceTextures) { face_materials_buffer.writeShort(faceTextures[face] + 1); } if (faceTextures != null) { if (faceTextures[face] != -1) { face_textures_buffer.writeByte(faceTextureIndexes[face] + 1); } } } /* serialize the face indices */ encodeIndices(face_indices_buffer, face_index_types_buffer); /* serialize the texture mapping */ encodeMapping(simple_textures_buffer, complex_textures_buffer, texture_scale_buffer, texture_rotation_buffer, texture_direction_buffer, texture_translation_buffer); /* create the particle effects variables */ boolean hasParticleEffects = emitterConfigs != null || magnetConfigs != null; /* serialize the particle effects */ if (hasParticleEffects) { int numEmitters = emitterConfigs != null ? emitterConfigs.length : 0; particle_effects_buffer.writeByte(numEmitters); if (numEmitters > 0) { for (int index = 0; index < numEmitters; index++) { EmitterConfig triangle = emitterConfigs[index]; particle_effects_buffer.writeShort(triangle.type); particle_effects_buffer.writeShort(triangle.face); } } int numEffectors = magnetConfigs != null ? magnetConfigs.length : 0; particle_effects_buffer.writeByte(numEffectors); if (numEffectors > 0) { for (int index = 0; index < numEffectors; index++) { MagnetConfig vertex = magnetConfigs[index]; particle_effects_buffer.writeShort(vertex.type); particle_effects_buffer.writeShort(vertex.vertex); } } } /* create the billboards variables */ boolean hasBillboards = billBoardConfigs != null; /* serialize the billboards */ if (hasBillboards) { particle_effects_buffer.writeByte(billBoardConfigs.length); for (int index = 0; index < billBoardConfigs.length; index++) { BillBoardConfig billboard = billBoardConfigs[index]; particle_effects_buffer.writeShort(billboard.type); particle_effects_buffer.writeShort(billboard.face); particle_effects_buffer.writeByte(billboard.priority); particle_effects_buffer.writeByte(billboard.magnitude); } } /* create the footer data */ boolean hasVersion = version != 12; if (hasVersion) { footer_buffer.writeByte(version); } footer_buffer.writeShort(vertexCount); footer_buffer.writeShort(faceCount); footer_buffer.writeByte(texturedFaceCount); int flags = 0; if (hasFaceTypes) { flags |= 0x1; } if (hasParticleEffects) { flags |= 0x2; } if (hasBillboards) { flags |= 0x4; } if (hasVersion) { flags |= 0x8; } footer_buffer.writeByte(flags); footer_buffer.writeByte(hasFacePriorities ? -1 : priority); footer_buffer.writeBoolean(hasFaceAlpha); footer_buffer.writeBoolean(hasFaceSkins); footer_buffer.writeBoolean(hasFaceTextures); footer_buffer.writeBoolean(hasVertexSkins); footer_buffer.writeShort(vertex_x_buffer.getOffset()); footer_buffer.writeShort(vertex_y_buffer.getOffset()); footer_buffer.writeShort(vertex_z_buffer.getOffset()); footer_buffer.writeShort(face_indices_buffer.getOffset()); footer_buffer.writeShort(face_textures_buffer.getOffset()); for (int i = 0; i < buffers.length; i++) { OutputStream buffer = buffers[i]; //int before = master.getOffset(); master.writeBytes(buffer.toByteArray()); //System.out.println(""buffer: "" + (i+1) + "" size: "" + (master.getOffset() - before)); } master.writeByte(-1); master.writeByte(-1); return master.toByteArray(); } private void encodeMapping(OutputStream simple, OutputStream complex, OutputStream scale, OutputStream rotation, OutputStream direction, OutputStream translation) { for (int face = 0; face < texturedFaceCount; face++) { int type = textureRenderTypes[face] & 0xff; if (type == 0) { simple.writeShort(textureTriangleX[face]); simple.writeShort(textureTriangleY[face]); simple.writeShort(textureTriangleZ[face]); } else { int scaleX = textureScaleX[face]; int scaleY = textureScaleY[face]; int scaleZ = textureScaleZ[face]; if (type == 1) { complex.writeShort(textureTriangleX[face]); complex.writeShort(textureTriangleY[face]); complex.writeShort(textureTriangleZ[face]); if (version >= 15 || scaleX > 0xffff || scaleZ > 0xffff) { if (version < 15) { version = 15; } scale.write24BitInt(scaleX); scale.write24BitInt(scaleY); scale.write24BitInt(scaleZ); } else { scale.writeShort(scaleX); if (version < 14 && scaleY > 0xffff) { version = 14; } if (version < 14) { scale.writeShort(scaleY); } else { scale.write24BitInt(scaleY); } scale.writeShort(scaleZ); } rotation.writeByte(textureRotationY[face]); direction.writeByte(textureUVDirections[face]); translation.writeByte(particleLifespanZ[face]); } else if (type == 2) { complex.writeShort(textureTriangleX[face]); complex.writeShort(textureTriangleY[face]); complex.writeShort(textureTriangleZ[face]); if (version >= 15 || scaleX > 0xffff || scaleZ > 0xffff) { if (version < 15) { version = 15; } scale.write24BitInt(scaleX); scale.write24BitInt(scaleY); scale.write24BitInt(scaleZ); } else { scale.writeShort(scaleX); if (version < 14 && scaleY > 0xffff) { version = 14; } if (version < 14) { scale.writeShort(scaleY); } else { scale.write24BitInt(scaleY); } scale.writeShort(scaleZ); } rotation.writeByte(textureRotationY[face]); direction.writeByte(textureUVDirections[face]); translation.writeByte(particleLifespanZ[face]); translation.writeByte(texturePrimaryColor[face]); translation.writeByte(textureSecondaryColor[face]); } else if (type == 3) { complex.writeShort(textureTriangleX[face]); complex.writeShort(textureTriangleY[face]); complex.writeShort(textureTriangleZ[face]); if (version >= 15 || scaleX > 0xffff || scaleZ > 0xffff) { if (version < 15) { version = 15; } scale.write24BitInt(scaleX); scale.write24BitInt(scaleY); scale.write24BitInt(scaleZ); } else { scale.writeShort(scaleX); if (version < 14 && scaleY > 0xffff) { version = 14; } if (version < 14) { scale.writeShort(scaleY); } else { scale.write24BitInt(scaleY); } scale.writeShort(scaleZ); } rotation.writeByte(textureRotationY[face]); direction.writeByte(textureUVDirections[face]); translation.writeByte(particleLifespanZ[face]); } } } } private void encodeIndices(OutputStream ibuffer, OutputStream tbuffer) { short lasta = 0; short lastb = 0; short lastc = 0; int pacc = 0; for (int fndex = 0; fndex < faceCount; fndex++) { short cura = faceA[fndex]; short curb = faceB[fndex]; short curc = faceC[fndex]; if (cura == lastb && curb == lasta && curc != lastc) { tbuffer.writeByte(4); ibuffer.writeUnsignedSmart(curc - pacc); short back = lasta; lasta = lastb; lastb = back; pacc = lastc = curc; } else if (cura == lastc && curb == lastb && curc != lastc) { tbuffer.writeByte(3); ibuffer.writeUnsignedSmart(curc - pacc); lasta = lastc; pacc = lastc = curc; } else if (cura == lasta && curb == lastc && curc != lastc) { tbuffer.writeByte(2); ibuffer.writeUnsignedSmart(curc - pacc); lastb = lastc; pacc = lastc = curc; } else { tbuffer.writeByte(1); ibuffer.writeUnsignedSmart(cura - pacc); ibuffer.writeUnsignedSmart(curb - cura); ibuffer.writeUnsignedSmart(curc - curb); lasta = cura; lastb = curb; pacc = lastc = curc; } } } void calculateMaxDepthRS3(ByteBuffer class475_sub17, ByteBuffer class475_sub17_288_, ByteBuffer class475_sub17_289_) { short i = 0; short i_290_ = 0; short i_291_ = 0; int i_292_ = 0; for (int i_293_ = 0; i_293_ < faceCount; i_293_++) { int i_294_ = class475_sub17_288_.get() & 0xFF; int i_295_ = i_294_ & 0x7; if (i_295_ == 1) { faceA[i_293_] = i = (short) (ByteBufferUtils.getSmart1(class475_sub17) + i_292_); i_292_ = i; faceB[i_293_] = i_290_ = (short) (ByteBufferUtils.getSmart1(class475_sub17) + i_292_); i_292_ = i_290_; faceC[i_293_] = i_291_ = (short) (ByteBufferUtils.getSmart1(class475_sub17) + i_292_); i_292_ = i_291_; if (i > maxVertexUsed) maxVertexUsed = i; if (i_290_ > maxVertexUsed) maxVertexUsed = i_290_; if (i_291_ > maxVertexUsed) maxVertexUsed = i_291_; } if (i_295_ == 2) { i_290_ = i_291_; i_291_ = (short) (ByteBufferUtils.getSmart1(class475_sub17) + i_292_); i_292_ = i_291_; faceA[i_293_] = i; faceB[i_293_] = i_290_; faceC[i_293_] = i_291_; if (i_291_ > maxVertexUsed) maxVertexUsed = i_291_; } if (i_295_ == 3) { i = i_291_; i_291_ = (short) (ByteBufferUtils.getSmart1(class475_sub17) + i_292_); i_292_ = i_291_; faceA[i_293_] = i; faceB[i_293_] = i_290_; faceC[i_293_] = i_291_; if (i_291_ > maxVertexUsed) maxVertexUsed = i_291_; } if (i_295_ == 4) { short i_296_ = i; i = i_290_; i_290_ = i_296_; i_291_ = (short) (ByteBufferUtils.getSmart1(class475_sub17) + i_292_); i_292_ = i_291_; faceA[i_293_] = i; faceB[i_293_] = i_290_; faceC[i_293_] = i_291_; if (i_291_ > maxVertexUsed) maxVertexUsed = i_291_; } if (textureUVCoordCount > 0 && (i_294_ & 0x8) != 0) { uvCoordVertexA[i_293_] = (byte) (class475_sub17_289_.get() & 0xFF); uvCoordVertexB[i_293_] = (byte) (class475_sub17_289_.get() & 0xFF); uvCoordVertexC[i_293_] = (byte) (class475_sub17_289_.get() & 0xFF); } } maxVertexUsed++; } void calculateMaxDepth(InputStream rsbytebuffer_1, InputStream rsbytebuffer_2) { short s_3 = 0; short s_4 = 0; short s_5 = 0; short s_6 = 0; for (int i_7 = 0; i_7 < this.faceCount; i_7++) { int i_8 = rsbytebuffer_2.readUnsignedByte(); if (i_8 == 1) { s_3 = (short) (rsbytebuffer_1.readSignedSmart() + s_6); s_4 = (short) (rsbytebuffer_1.readSignedSmart() + s_3); s_5 = (short) (rsbytebuffer_1.readSignedSmart() + s_4); s_6 = s_5; this.faceA[i_7] = s_3; this.faceB[i_7] = s_4; this.faceC[i_7] = s_5; if (s_3 > this.maxVertexUsed) { this.maxVertexUsed = s_3; } if (s_4 > this.maxVertexUsed) { this.maxVertexUsed = s_4; } if (s_5 > this.maxVertexUsed) { this.maxVertexUsed = s_5; } } if (i_8 == 2) { s_4 = s_5; s_5 = (short) (rsbytebuffer_1.readSignedSmart() + s_6); s_6 = s_5; this.faceA[i_7] = s_3; this.faceB[i_7] = s_4; this.faceC[i_7] = s_5; if (s_5 > this.maxVertexUsed) { this.maxVertexUsed = s_5; } } if (i_8 == 3) { s_3 = s_5; s_5 = (short) (rsbytebuffer_1.readSignedSmart() + s_6); s_6 = s_5; this.faceA[i_7] = s_3; this.faceB[i_7] = s_4; this.faceC[i_7] = s_5; if (s_5 > this.maxVertexUsed) { this.maxVertexUsed = s_5; } } if (i_8 == 4) { short s_9 = s_3; s_3 = s_4; s_4 = s_9; s_5 = (short) (rsbytebuffer_1.readSignedSmart() + s_6); s_6 = s_5; this.faceA[i_7] = s_3; this.faceB[i_7] = s_9; this.faceC[i_7] = s_5; if (s_5 > this.maxVertexUsed) { this.maxVertexUsed = s_5; } } } ++this.maxVertexUsed; } void decodeTexturedTrianglesRS3(ByteBuffer class475_sub17, ByteBuffer class475_sub17_142_, ByteBuffer class475_sub17_143_, ByteBuffer class475_sub17_144_, ByteBuffer class475_sub17_145_, ByteBuffer class475_sub17_146_) { for (int i = 0; i < texturedFaceCount; i++) { int i_147_ = textureRenderTypes[i] & 0xff; if (i_147_ == 0) { textureTriangleX[i] = (short) (class475_sub17.getShort() & 0xFFFF); textureTriangleY[i] = (short) (class475_sub17.getShort() & 0xFFFF); textureTriangleZ[i] = (short) (class475_sub17.getShort() & 0xFFFF); } if (i_147_ == 1) { textureTriangleX[i] = (short) (class475_sub17_142_.getShort() & 0xFFFF); textureTriangleY[i] = (short) (class475_sub17_142_.getShort() & 0xFFFF); textureTriangleZ[i] = (short) (class475_sub17_142_.getShort() & 0xFFFF); if (version < 15) { textureScaleX[i] = class475_sub17_143_.getShort() & 0xFFFF; if (version < 14) textureScaleY[i] = class475_sub17_143_.getShort() & 0xFFFF; else textureScaleY[i] = ByteBufferUtils.getMedium(class475_sub17_143_); textureScaleZ[i] = class475_sub17_143_.getShort() & 0xFFFF; } else { textureScaleX[i] = ByteBufferUtils.getMedium(class475_sub17_143_); textureScaleY[i] = ByteBufferUtils.getMedium(class475_sub17_143_); textureScaleZ[i] = ByteBufferUtils.getMedium(class475_sub17_143_); } textureRotationY[i] = class475_sub17_144_.get(); textureUVDirections[i] = class475_sub17_145_.get(); particleLifespanZ[i] = class475_sub17_146_.get(); } if (i_147_ == 2) { textureTriangleX[i] = (short) (class475_sub17_142_.getShort() & 0xFFFF); textureTriangleY[i] = (short) (class475_sub17_142_.getShort() & 0xFFFF); textureTriangleZ[i] = (short) (class475_sub17_142_.getShort() & 0xFFFF); if (version < 15) { textureScaleX[i] = class475_sub17_143_.getShort() & 0xFFFF; if (version < 14) textureScaleY[i] = class475_sub17_143_.getShort() & 0xFFFF; else textureScaleY[i] = ByteBufferUtils.getMedium(class475_sub17_143_); textureScaleZ[i] = class475_sub17_143_.getShort() & 0xFFFF; } else { textureScaleX[i] = ByteBufferUtils.getMedium(class475_sub17_143_); textureScaleY[i] = ByteBufferUtils.getMedium(class475_sub17_143_); textureScaleZ[i] = ByteBufferUtils.getMedium(class475_sub17_143_); } textureRotationY[i] = class475_sub17_144_.get(); textureUVDirections[i] = class475_sub17_145_.get(); particleLifespanZ[i] = class475_sub17_146_.get(); texturePrimaryColor[i] = class475_sub17_146_.get(); textureSecondaryColor[i] = class475_sub17_146_.get(); } if (i_147_ == 3) { textureTriangleX[i] = (short) (class475_sub17_142_.getShort() & 0xFFFF); textureTriangleY[i] = (short) (class475_sub17_142_.getShort() & 0xFFFF); textureTriangleZ[i] = (short) (class475_sub17_142_.getShort() & 0xFFFF); if (version < 15) { textureScaleX[i] = class475_sub17_143_.getShort() & 0xFFFF; if (version < 14) textureScaleY[i] = class475_sub17_143_.getShort() & 0xFFFF; else textureScaleY[i] = ByteBufferUtils.getMedium(class475_sub17_143_); textureScaleZ[i] = class475_sub17_143_.getShort() & 0xFFFF; } else { textureScaleX[i] = ByteBufferUtils.getMedium(class475_sub17_143_); textureScaleY[i] = ByteBufferUtils.getMedium(class475_sub17_143_); textureScaleZ[i] = ByteBufferUtils.getMedium(class475_sub17_143_); } textureRotationY[i] = class475_sub17_144_.get(); textureUVDirections[i] = class475_sub17_145_.get(); particleLifespanZ[i] = class475_sub17_146_.get(); } } } void decodeTexturedTriangles(InputStream rsbytebuffer_1, InputStream rsbytebuffer_2, InputStream rsbytebuffer_3, InputStream rsbytebuffer_4, InputStream rsbytebuffer_5, InputStream rsbytebuffer_6) { for (int i_7 = 0; i_7 < this.texturedFaceCount; i_7++) { int i_8 = this.textureRenderTypes[i_7] & 0xff; if (i_8 == 0) { this.textureTriangleX[i_7] = (short) rsbytebuffer_1.readUnsignedShort(); this.textureTriangleY[i_7] = (short) rsbytebuffer_1.readUnsignedShort(); this.textureTriangleZ[i_7] = (short) rsbytebuffer_1.readUnsignedShort(); } if (i_8 == 1) { this.textureTriangleX[i_7] = (short) rsbytebuffer_2.readUnsignedShort(); this.textureTriangleY[i_7] = (short) rsbytebuffer_2.readUnsignedShort(); this.textureTriangleZ[i_7] = (short) rsbytebuffer_2.readUnsignedShort(); if (this.version < 15) { this.textureScaleX[i_7] = rsbytebuffer_3.readUnsignedShort(); if (this.version < 14) { this.textureScaleY[i_7] = rsbytebuffer_3.readUnsignedShort(); } else { this.textureScaleY[i_7] = rsbytebuffer_3.read24BitUnsignedInteger(); } this.textureScaleZ[i_7] = rsbytebuffer_3.readUnsignedShort(); } else { this.textureScaleX[i_7] = rsbytebuffer_3.read24BitUnsignedInteger(); this.textureScaleY[i_7] = rsbytebuffer_3.read24BitUnsignedInteger(); this.textureScaleZ[i_7] = rsbytebuffer_3.read24BitUnsignedInteger(); } this.textureRotationY[i_7] = (byte) rsbytebuffer_4.readByte(); this.textureUVDirections[i_7] = (byte) rsbytebuffer_5.readByte(); this.particleLifespanZ[i_7] = rsbytebuffer_6.readByte(); } if (i_8 == 2) { this.textureTriangleX[i_7] = (short) rsbytebuffer_2.readUnsignedShort(); this.textureTriangleY[i_7] = (short) rsbytebuffer_2.readUnsignedShort(); this.textureTriangleZ[i_7] = (short) rsbytebuffer_2.readUnsignedShort(); if (this.version < 15) { this.textureScaleX[i_7] = rsbytebuffer_3.readUnsignedShort(); if (this.version < 14) { this.textureScaleY[i_7] = rsbytebuffer_3.readUnsignedShort(); } else { this.textureScaleY[i_7] = rsbytebuffer_3.read24BitUnsignedInteger(); } this.textureScaleZ[i_7] = rsbytebuffer_3.readUnsignedShort(); } else { this.textureScaleX[i_7] = rsbytebuffer_3.read24BitUnsignedInteger(); this.textureScaleY[i_7] = rsbytebuffer_3.read24BitUnsignedInteger(); this.textureScaleZ[i_7] = rsbytebuffer_3.read24BitUnsignedInteger(); } this.textureRotationY[i_7] = (byte) rsbytebuffer_4.readByte(); this.textureUVDirections[i_7] = (byte) rsbytebuffer_5.readByte(); this.particleLifespanZ[i_7] = rsbytebuffer_6.readByte(); this.texturePrimaryColor[i_7] = rsbytebuffer_6.readByte(); this.textureSecondaryColor[i_7] = rsbytebuffer_6.readByte(); } if (i_8 == 3) { this.textureTriangleX[i_7] = (short) rsbytebuffer_2.readUnsignedShort(); this.textureTriangleY[i_7] = (short) rsbytebuffer_2.readUnsignedShort(); this.textureTriangleZ[i_7] = (short) rsbytebuffer_2.readUnsignedShort(); if (this.version < 15) { this.textureScaleX[i_7] = rsbytebuffer_3.readUnsignedShort(); if (this.version < 14) { this.textureScaleY[i_7] = rsbytebuffer_3.readUnsignedShort(); } else { this.textureScaleY[i_7] = rsbytebuffer_3.read24BitUnsignedInteger(); } this.textureScaleZ[i_7] = rsbytebuffer_3.readUnsignedShort(); } else { this.textureScaleX[i_7] = rsbytebuffer_3.read24BitUnsignedInteger(); this.textureScaleY[i_7] = rsbytebuffer_3.read24BitUnsignedInteger(); this.textureScaleZ[i_7] = rsbytebuffer_3.read24BitUnsignedInteger(); } this.textureRotationY[i_7] = (byte) rsbytebuffer_4.readByte(); this.textureUVDirections[i_7] = (byte) rsbytebuffer_5.readByte(); this.particleLifespanZ[i_7] = rsbytebuffer_6.readByte(); } } } public int method2662(int i_1, int i_2, int i_3) { for (int i_4 = 0; i_4 < this.vertexCount; i_4++) { if (this.vertexX[i_4] == i_1 && i_2 == this.vertexY[i_4] && i_3 == this.vertexZ[i_4]) { return i_4; } } this.vertexX[this.vertexCount] = i_1; this.vertexY[this.vertexCount] = i_2; this.vertexZ[this.vertexCount] = i_3; this.maxVertexUsed = this.vertexCount + 1; return this.vertexCount++; } public int method2663(int i_1, int i_2, int i_3, byte b_4, byte b_5, short s_6, byte b_7, short s_8) { this.faceA[this.faceCount] = (short) i_1; this.faceB[this.faceCount] = (short) i_2; this.faceC[this.faceCount] = (short) i_3; this.faceRenderTypes[this.faceCount] = b_4; this.faceTextureIndexes[this.faceCount] = b_5; this.faceColors[this.faceCount] = s_6; this.faceAlpha[this.faceCount] = b_7; this.faceTextures[this.faceCount] = s_8; return this.faceCount++; } public byte method2664() { if (this.texturedFaceCount >= 255) { throw new IllegalStateException(); } else { this.textureRenderTypes[this.texturedFaceCount] = 3; this.textureTriangleX[this.texturedFaceCount] = (short) 0; this.textureTriangleY[this.texturedFaceCount] = (short) 32767; this.textureTriangleZ[this.texturedFaceCount] = (short) 0; this.textureScaleX[this.texturedFaceCount] = (short) 1024; this.textureScaleY[this.texturedFaceCount] = (short) 1024; this.textureScaleZ[this.texturedFaceCount] = (short) 1024; this.textureRotationY[this.texturedFaceCount] = (byte) 0; this.textureUVDirections[this.texturedFaceCount] = (byte) 0; this.particleLifespanZ[this.texturedFaceCount] = (byte) 0; return (byte) (this.texturedFaceCount++); } } public int[][] method2665(boolean bool_1) { int[] ints_2 = new int[256]; int i_3 = 0; int i_4 = bool_1 ? this.vertexCount : this.maxVertexUsed; int i_6; for (int i_5 = 0; i_5 < i_4; i_5++) { i_6 = this.vertexBones[i_5]; if (i_6 >= 0) { ++ints_2[i_6]; if (i_6 > i_3) { i_3 = i_6; } } } int[][] ints_8 = new int[i_3 + 1][]; for (i_6 = 0; i_6 <= i_3; i_6++) { ints_8[i_6] = new int[ints_2[i_6]]; ints_2[i_6] = 0; } for (i_6 = 0; i_6 < i_4; i_6++) { int i_7 = this.vertexBones[i_6]; if (i_7 >= 0) { ints_8[i_7][ints_2[i_7]++] = i_6; } } return ints_8; } public int[][] method2666() { int[] ints_1 = new int[256]; int i_2 = 0; int i_4; for (int i_3 = 0; i_3 < this.faceCount; i_3++) { i_4 = this.faceBones[i_3]; if (i_4 >= 0) { ++ints_1[i_4]; if (i_4 > i_2) { i_2 = i_4; } } } int[][] ints_6 = new int[i_2 + 1][]; for (i_4 = 0; i_4 <= i_2; i_4++) { ints_6[i_4] = new int[ints_1[i_4]]; ints_1[i_4] = 0; } for (i_4 = 0; i_4 < this.faceCount; i_4++) { int i_5 = this.faceBones[i_4]; if (i_5 >= 0) { ints_6[i_5][ints_1[i_5]++] = i_4; } } return ints_6; } public int[][] method2667() { int[] ints_1 = new int[256]; int i_2 = 0; int i_4; for (int i_3 = 0; i_3 < this.billBoardConfigs.length; i_3++) { i_4 = this.billBoardConfigs[i_3].priority; if (i_4 >= 0) { ++ints_1[i_4]; if (i_4 > i_2) { i_2 = i_4; } } } int[][] ints_6 = new int[i_2 + 1][]; for (i_4 = 0; i_4 <= i_2; i_4++) { ints_6[i_4] = new int[ints_1[i_4]]; ints_1[i_4] = 0; } for (i_4 = 0; i_4 < this.billBoardConfigs.length; i_4++) { int i_5 = this.billBoardConfigs[i_4].priority; if (i_5 >= 0) { ints_6[i_5][ints_1[i_5]++] = i_4; } } return ints_6; } public void recolor(short s_1, short s_2) { for (int i_3 = 0; i_3 < this.faceCount; i_3++) { if (this.faceColors[i_3] == s_1) { this.faceColors[i_3] = s_2; } } } public void retexture(short s_1, short s_2) { if (this.faceTextures != null) { for (int i_3 = 0; i_3 < this.faceCount; i_3++) { if (this.faceTextures[i_3] == s_1) { this.faceTextures[i_3] = s_2; } } } } void decode317(byte[] bytes_1) { boolean bool_2 = false; boolean bool_3 = false; InputStream rsbytebuffer_4 = new InputStream(bytes_1); InputStream rsbytebuffer_5 = new InputStream(bytes_1); InputStream rsbytebuffer_6 = new InputStream(bytes_1); InputStream rsbytebuffer_7 = new InputStream(bytes_1); InputStream rsbytebuffer_8 = new InputStream(bytes_1); rsbytebuffer_4.offset = bytes_1.length - 18; this.vertexCount = rsbytebuffer_4.readUnsignedShort(); this.faceCount = rsbytebuffer_4.readUnsignedShort(); this.texturedFaceCount = rsbytebuffer_4.readUnsignedByte(); int i_9 = rsbytebuffer_4.readUnsignedByte(); int i_10 = rsbytebuffer_4.readUnsignedByte(); int i_11 = rsbytebuffer_4.readUnsignedByte(); int i_12 = rsbytebuffer_4.readUnsignedByte(); int i_13 = rsbytebuffer_4.readUnsignedByte(); int i_14 = rsbytebuffer_4.readUnsignedShort(); int i_15 = rsbytebuffer_4.readUnsignedShort(); int i_16 = rsbytebuffer_4.readUnsignedShort(); int i_17 = rsbytebuffer_4.readUnsignedShort(); byte b_18 = 0; int i_42 = b_18 + this.vertexCount; int i_20 = i_42; i_42 += this.faceCount; int i_21 = i_42; if (i_10 == 255) { i_42 += this.faceCount; } int i_22 = i_42; if (i_12 == 1) { i_42 += this.faceCount; } int i_23 = i_42; if (i_9 == 1) { i_42 += this.faceCount; } int i_24 = i_42; if (i_13 == 1) { i_42 += this.vertexCount; } int i_25 = i_42; if (i_11 == 1) { i_42 += this.faceCount; } int i_26 = i_42; i_42 += i_17; int i_27 = i_42; i_42 += this.faceCount * 2; int i_28 = i_42; i_42 += this.texturedFaceCount * 6; int i_29 = i_42; i_42 += i_14; int i_30 = i_42; i_42 += i_15; @SuppressWarnings(""unused"") int i_10000 = i_42 + i_16; this.vertexX = new int[this.vertexCount]; this.vertexY = new int[this.vertexCount]; this.vertexZ = new int[this.vertexCount]; this.faceA = new short[this.faceCount]; this.faceB = new short[this.faceCount]; this.faceC = new short[this.faceCount]; if (this.texturedFaceCount > 0) { this.textureRenderTypes = new byte[this.texturedFaceCount]; this.textureTriangleX = new short[this.texturedFaceCount]; this.textureTriangleY = new short[this.texturedFaceCount]; this.textureTriangleZ = new short[this.texturedFaceCount]; } if (i_13 == 1) { this.vertexBones = new int[this.vertexCount]; } if (i_9 == 1) { this.faceRenderTypes = new byte[this.faceCount]; this.faceTextureIndexes = new short[this.faceCount]; this.faceTextures = new short[this.faceCount]; } if (i_10 == 255) { this.facePriorities = new byte[this.faceCount]; } else { this.priority = (byte) i_10; } if (i_11 == 1) { this.faceAlpha = new byte[this.faceCount]; } if (i_12 == 1) { this.faceBones = new int[this.faceCount]; } this.faceColors = new short[this.faceCount]; rsbytebuffer_4.offset = b_18; rsbytebuffer_5.offset = i_29; rsbytebuffer_6.offset = i_30; rsbytebuffer_7.offset = i_42; rsbytebuffer_8.offset = i_24; int i_32 = 0; int i_33 = 0; int i_34 = 0; int i_35; int i_36; int i_39; for (i_35 = 0; i_35 < this.vertexCount; i_35++) { i_36 = rsbytebuffer_4.readUnsignedByte(); int i_37 = 0; if ((i_36 & 0x1) != 0) { i_37 = rsbytebuffer_5.readSignedSmart(); } int i_38 = 0; if ((i_36 & 0x2) != 0) { i_38 = rsbytebuffer_6.readSignedSmart(); } i_39 = 0; if ((i_36 & 0x4) != 0) { i_39 = rsbytebuffer_7.readSignedSmart(); } this.vertexX[i_35] = i_32 + i_37; this.vertexY[i_35] = i_33 + i_38; this.vertexZ[i_35] = i_34 + i_39; i_32 = this.vertexX[i_35]; i_33 = this.vertexY[i_35]; i_34 = this.vertexZ[i_35]; if (i_13 == 1) { this.vertexBones[i_35] = rsbytebuffer_8.readUnsignedByte(); } } rsbytebuffer_4.offset = i_27; rsbytebuffer_5.offset = i_23; rsbytebuffer_6.offset = i_21; rsbytebuffer_7.offset = i_25; rsbytebuffer_8.offset = i_22; for (i_35 = 0; i_35 < this.faceCount; i_35++) { this.faceColors[i_35] = (short) rsbytebuffer_4.readUnsignedShort(); if (i_9 == 1) { i_36 = rsbytebuffer_5.readUnsignedByte(); if ((i_36 & 0x1) == 1) { this.faceRenderTypes[i_35] = 1; bool_2 = true; } else { this.faceRenderTypes[i_35] = 0; } if ((i_36 & 0x2) == 2) { this.faceTextureIndexes[i_35] = (byte) (i_36 >> 2); this.faceTextures[i_35] = this.faceColors[i_35]; this.faceColors[i_35] = 127; if (this.faceTextures[i_35] != -1) { bool_3 = true; } } else { this.faceTextureIndexes[i_35] = -1; this.faceTextures[i_35] = -1; } } if (i_10 == 255) { this.facePriorities[i_35] = (byte) rsbytebuffer_6.readByte(); } if (i_11 == 1) { this.faceAlpha[i_35] = (byte) rsbytebuffer_7.readByte(); } if (i_12 == 1) { this.faceBones[i_35] = rsbytebuffer_8.readUnsignedByte(); } } this.maxVertexUsed = -1; rsbytebuffer_4.offset = i_26; rsbytebuffer_5.offset = i_20; short s_43 = 0; short s_44 = 0; short s_45 = 0; short s_46 = 0; int i_40; for (i_39 = 0; i_39 < this.faceCount; i_39++) { i_40 = rsbytebuffer_5.readUnsignedByte(); if (i_40 == 1) { s_43 = (short) (rsbytebuffer_4.readSignedSmart() + s_46); s_44 = (short) (rsbytebuffer_4.readSignedSmart() + s_43); s_45 = (short) (rsbytebuffer_4.readSignedSmart() + s_44); s_46 = s_45; this.faceA[i_39] = s_43; this.faceB[i_39] = s_44; this.faceC[i_39] = s_45; if (s_43 > this.maxVertexUsed) { this.maxVertexUsed = s_43; } if (s_44 > this.maxVertexUsed) { this.maxVertexUsed = s_44; } if (s_45 > this.maxVertexUsed) { this.maxVertexUsed = s_45; } } if (i_40 == 2) { s_44 = s_45; s_45 = (short) (rsbytebuffer_4.readSignedSmart() + s_46); s_46 = s_45; this.faceA[i_39] = s_43; this.faceB[i_39] = s_44; this.faceC[i_39] = s_45; if (s_45 > this.maxVertexUsed) { this.maxVertexUsed = s_45; } } if (i_40 == 3) { s_43 = s_45; s_45 = (short) (rsbytebuffer_4.readSignedSmart() + s_46); s_46 = s_45; this.faceA[i_39] = s_43; this.faceB[i_39] = s_44; this.faceC[i_39] = s_45; if (s_45 > this.maxVertexUsed) { this.maxVertexUsed = s_45; } } if (i_40 == 4) { short s_41 = s_43; s_43 = s_44; s_44 = s_41; s_45 = (short) (rsbytebuffer_4.readSignedSmart() + s_46); s_46 = s_45; this.faceA[i_39] = s_43; this.faceB[i_39] = s_41; this.faceC[i_39] = s_45; if (s_45 > this.maxVertexUsed) { this.maxVertexUsed = s_45; } } } ++this.maxVertexUsed; rsbytebuffer_4.offset = i_28; for (i_39 = 0; i_39 < this.texturedFaceCount; i_39++) { this.textureRenderTypes[i_39] = 0; this.textureTriangleX[i_39] = (short) rsbytebuffer_4.readUnsignedShort(); this.textureTriangleY[i_39] = (short) rsbytebuffer_4.readUnsignedShort(); this.textureTriangleZ[i_39] = (short) rsbytebuffer_4.readUnsignedShort(); } if (this.faceTextureIndexes != null) { boolean bool_47 = false; for (i_40 = 0; i_40 < this.faceCount; i_40++) { int i_48 = this.faceTextureIndexes[i_40] & 0xff; if (i_48 != 255) { if (this.faceA[i_40] == (this.textureTriangleX[i_48] & 0xffff) && this.faceB[i_40] == (this.textureTriangleY[i_48] & 0xffff) && this.faceC[i_40] == (this.textureTriangleZ[i_48] & 0xffff)) { this.faceTextureIndexes[i_40] = -1; } else { bool_47 = true; } } } if (!bool_47) { this.faceTextureIndexes = null; } } if (!bool_3) { this.faceTextures = null; } if (!bool_2) { this.faceRenderTypes = null; } } public void upscale() { int i_2; for (i_2 = 0; i_2 < this.vertexCount; i_2++) { this.vertexX[i_2] <<= 2; this.vertexY[i_2] <<= 2; this.vertexZ[i_2] <<= 2; } if (this.texturedFaceCount > 0 && this.textureScaleX != null) { for (i_2 = 0; i_2 < this.textureScaleX.length; i_2++) { this.textureScaleX[i_2] <<= 2; this.textureScaleY[i_2] <<= 2; if (this.textureRenderTypes[i_2] != 1) { this.textureScaleZ[i_2] <<= 2; } } } } public static RSModel getMesh(Store store, int meshId, boolean rs3) { byte[] data = store.getIndex(IndexType.MODELS).getFile(meshId, 0); if (data == null) return null; RSModel model = new RSModel(data, rs3); model.id = meshId; return model; } public static RSModel getMesh(int meshId) { return getMesh(Cache.STORE, meshId, false); } public void translate(int dx, int dy, int dz) { for (int i = 0; i < this.vertexCount; i++) { this.vertexX[i] += dx; this.vertexY[i] += dy; this.vertexZ[i] += dz; } } @Override public String toString() { StringBuilder result = new StringBuilder(); String newLine = System.getProperty(""line.separator""); result.append(this.getClass().getName()); result.append("" {""); result.append(newLine); // determine fields declared in this class only (no fields of // superclass) Field[] fields = this.getClass().getDeclaredFields(); // print field names paired with their values for (Field field : fields) { if (Modifier.isStatic(field.getModifiers())) continue; result.append("" ""); try { result.append(field.getType().getCanonicalName() + "" "" + field.getName() + "": ""); result.append(Utils.getFieldValue(this, field)); } catch (Throwable ex) { System.out.println(ex); } result.append(newLine); } result.append(""}""); return result.toString(); } private static Map PARTICLE_CONVERTS = new HashMap<>(); private static Map MAGNET_CONVERTS = new HashMap<>(); public byte[] convertTo727(Store to, Store from) throws IOException { if (faceTextures != null) { for (int index = 0; index < faceTextures.length; index++) { int texture = faceTextures[index]; if (texture != -1) { try { faceTextures[index] = (short) TextureConverter.convert(from, to, texture, true); } catch (IOException e) { e.printStackTrace(); } } } } if (emitterConfigs != null) { for (int i = 0;i < emitterConfigs.length;i++) { if (to.getIndex(IndexType.PARTICLES).getFile(0, emitterConfigs[i].type) != null) continue; if (PARTICLE_CONVERTS.get(emitterConfigs[i].type) != null) { emitterConfigs[i].type = PARTICLE_CONVERTS.get(emitterConfigs[i].type); continue; } int newId = to.getIndex(IndexType.PARTICLES).getLastFileId(0)+1; ParticleProducerDefinitions rs3 = new ParticleProducerDefinitions(); rs3.decode(from.getIndex(IndexType.PARTICLES).getFile(0, emitterConfigs[i].type), true); rs3.id = newId; //812 = dung cape, 744 = comp cape rs3.textureId = 744; //TextureConverter.convert(from, to, rs3.textureId, true); rs3.write(to); System.out.println(""Packed emitter def from "" + emitterConfigs[i].type + "" to "" + newId); PARTICLE_CONVERTS.put(emitterConfigs[i].type, newId); emitterConfigs[i].type = newId; } } if (magnetConfigs != null) { for (int i = 0;i < magnetConfigs.length;i++) { if (to.getIndex(IndexType.PARTICLES).getFile(1, magnetConfigs[i].type) != null) continue; if (MAGNET_CONVERTS.get(magnetConfigs[i].type) != null) { magnetConfigs[i].type = MAGNET_CONVERTS.get(magnetConfigs[i].type); continue; } int newId = to.getIndex(IndexType.PARTICLES).getLastFileId(1)+1; to.getIndex(IndexType.PARTICLES).putFile(1, newId, from.getIndex(IndexType.PARTICLES).getFile(1, magnetConfigs[i].type)); System.out.println(""Packed magnet def from "" + magnetConfigs[i].type + "" to "" + newId); MAGNET_CONVERTS.put(magnetConfigs[i].type, newId); magnetConfigs[i].type = newId; } } // if (billBoardConfigs != null) { // // } return encode(); } } " " package com.rs.cache.loaders.model; import java.io.IOException; import java.util.HashMap; import java.util.Map; import com.rs.cache.IndexType; import com.rs.cache.Store; import com.rs.cache.loaders.SpriteContainer; import com.rs.cache.loaders.TextureDefinitions; import com.rs.lib.io.OutputStream; public class TextureConverter { private static Map CONVERTED_MAP = new HashMap<>(); public static int convert(Store from, Store to, int textureId, boolean quantize) throws IOException { if (CONVERTED_MAP.get(textureId) != null) return CONVERTED_MAP.get(textureId); if (textureId <= 2000) return textureId; RS3Tex tex = new RS3Tex(textureId); tex.decode(from, quantize); int newSpriteId = to.getIndex(IndexType.SPRITES).getLastArchiveId() + 1; SpriteContainer sprite = new SpriteContainer(tex.getImage()); to.getIndex(IndexType.SPRITES).putFile(newSpriteId, 0, sprite.encode()); OutputStream buffer = new OutputStream(); // buffer.writeByte(3); // 3 operations // buffer.writeByte(0); // client doesnt read this byte // // buffer.writeByte(39); // sprite operation opcode // buffer.writeByte(1); // buffer.writeByte(1); // buffer.writeByte(0); // buffer.writeShort(newSpriteId); // sprite id // // buffer.writeBytes(new byte[] { 1, 0, 1, 0, 2, 0, 1, 1, 0, 0, 0, 1, 2, 0, 0, 1, 1, 0, 0, 0 }); // default operations // buffer.writeByte(34); // buffer.writeByte(0); // buffer.writeByte(0); buffer.writeByte(1); buffer.writeByte(0); buffer.writeByte(39); buffer.writeByte(1); buffer.writeByte(1); buffer.writeByte(0); buffer.writeShort(newSpriteId); buffer.writeByte(0); buffer.writeByte(0); buffer.writeByte(0); int newTex = to.getIndex(IndexType.MATERIALS).getLastArchiveId() + 1; if (to.getIndex(IndexType.MATERIALS).putFile(newTex, 0, buffer.toByteArray())) CONVERTED_MAP.put(textureId, newTex); TextureDefinitions def = TextureDefinitions.getRS3(newTex, from.getIndex(IndexType.TEXTURES).getFile(0, textureId)); TextureDefinitions.addDef(def); TextureDefinitions.encodeAndReplace(); System.out.println(""Converted texture "" + textureId + "" to sprite: "" + newSpriteId + "" and texture: "" + newTex); return newTex; } } " " package com.rs.cache.loaders.sound; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import com.rs.lib.io.InputStream; import com.rs.lib.util.Utils; public class Envelope { int form; int start; int end; int critical; int phaseIndex; int step; int amplitude; int ticks; int numPhases = 2; int[] phaseDuration = new int[2]; int[] phasePeak = new int[2]; final void decode(InputStream buffer) { this.form = buffer.readUnsignedByte(); this.start = buffer.readInt(); this.end = buffer.readInt(); this.decodeShape(buffer); } final void reset() { this.critical = 0; this.phaseIndex = 0; this.step = 0; this.amplitude = 0; this.ticks = 0; } Envelope() { this.phaseDuration[0] = 0; this.phaseDuration[1] = 65535; this.phasePeak[0] = 0; this.phasePeak[1] = 65535; } final void decodeShape(InputStream buffer) { this.numPhases = buffer.readUnsignedByte(); this.phaseDuration = new int[this.numPhases]; this.phasePeak = new int[this.numPhases]; for (int i = 0; i < this.numPhases; i++) { this.phaseDuration[i] = buffer.readUnsignedShort(); this.phasePeak[i] = buffer.readUnsignedShort(); } } final int step(int period) { if (this.ticks >= this.critical) { this.amplitude = this.phasePeak[this.phaseIndex++] << 15; if (this.phaseIndex >= this.numPhases) { this.phaseIndex = this.numPhases - 1; } this.critical = (int) ((double) this.phaseDuration[this.phaseIndex] / 65536.0D * (double) period); if (this.critical > this.ticks) { this.step = ((this.phasePeak[this.phaseIndex] << 15) - this.amplitude) / (this.critical - this.ticks); } } this.amplitude += this.step; ++this.ticks; return this.amplitude - this.step >> 15; } @Override public String toString() { StringBuilder result = new StringBuilder(); String newLine = System.getProperty(""line.separator""); result.append(this.getClass().getName()); result.append("" {""); result.append(newLine); // determine fields declared in this class only (no fields of // superclass) Field[] fields = this.getClass().getDeclaredFields(); // print field names paired with their values for (Field field : fields) { if (Modifier.isStatic(field.getModifiers())) continue; result.append("" ""); try { result.append(field.getType().getCanonicalName() + "" "" + field.getName() + "": ""); result.append(Utils.getFieldValue(this, field)); } catch (Throwable ex) { System.out.println(ex); } result.append(newLine); } result.append(""}""); return result.toString(); } } " " package com.rs.cache.loaders.sound; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import com.rs.lib.io.InputStream; import com.rs.lib.util.Utils; public class Filter { static float[][] coefficient_float = new float[2][8]; static int[][] coefficient_int = new int[2][8]; int[] numPairs = new int[2]; int[][][] pairPhase = new int[2][2][4]; int[][][] pairMagnitude = new int[2][2][4]; int[] unity = new int[2]; static float invUnity_float; static int invUnity_int; float adaptMagnitude(int dir, int k, float t) { float alpha = (float) this.pairMagnitude[dir][0][k] + t * (float) (this.pairMagnitude[dir][1][k] - this.pairMagnitude[dir][0][k]); alpha *= 0.0015258789F; return 1.0F - (float) Math.pow(10.0D, (double) (-alpha / 20.0F)); } static float normalize(float f) { float _f = 32.703197F * (float) Math.pow(2.0D, (double) f); return _f * 3.1415927F / 11025.0F; } float adaptPhase(int dir, int i, float t) { float _f = (float) this.pairPhase[dir][0][i] + t * (float) (this.pairPhase[dir][1][i] - this.pairPhase[dir][0][i]); _f *= 1.2207031E-4F; return normalize(_f); } final void decode(InputStream buffer, Envelope envelope) { int count = buffer.readUnsignedByte(); this.numPairs[0] = count >> 4; this.numPairs[1] = count & 0xf; if (count != 0) { this.unity[0] = buffer.readUnsignedShort(); this.unity[1] = buffer.readUnsignedShort(); int migrated = buffer.readUnsignedByte(); for (int dir = 0; dir < 2; dir++) { for (int term = 0; term < this.numPairs[dir]; term++) { this.pairPhase[dir][0][term] = buffer.readUnsignedShort(); this.pairMagnitude[dir][0][term] = buffer.readUnsignedShort(); } } for (int dir = 0; dir < 2; dir++) { for (int phase = 0; phase < this.numPairs[dir]; phase++) { if ((migrated & 1 << dir * 4 << phase) != 0) { this.pairPhase[dir][1][phase] = buffer.readUnsignedShort(); this.pairMagnitude[dir][1][phase] = buffer.readUnsignedShort(); } else { this.pairPhase[dir][1][phase] = this.pairPhase[dir][0][phase]; this.pairMagnitude[dir][1][phase] = this.pairMagnitude[dir][0][phase]; } } } if (migrated != 0 || this.unity[1] != this.unity[0]) { envelope.decodeShape(buffer); } } else { int[] placeholder = this.unity; this.unity[1] = 0; placeholder[0] = 0; } } int compute(int dir, float t) { if (dir == 0) { float a0 = (float) this.unity[0] + (float) (this.unity[1] - this.unity[0]) * t; a0 *= 0.0030517578F; invUnity_float = (float) Math.pow(0.1D, (double) (a0 / 20.0F)); invUnity_int = (int) (invUnity_float * 65536.0F); } if (this.numPairs[dir] == 0) { return 0; } else { float f_3 = this.adaptMagnitude(dir, 0, t); coefficient_float[dir][0] = -2.0F * f_3 * (float) Math.cos((double) this.adaptPhase(dir, 0, t)); coefficient_float[dir][1] = f_3 * f_3; int i_4; for (i_4 = 1; i_4 < this.numPairs[dir]; i_4++) { f_3 = this.adaptMagnitude(dir, i_4, t); float f_5 = -2.0F * f_3 * (float) Math.cos((double) this.adaptPhase(dir, i_4, t)); float f_6 = f_3 * f_3; coefficient_float[dir][i_4 * 2 + 1] = coefficient_float[dir][i_4 * 2 - 1] * f_6; coefficient_float[dir][i_4 * 2] = coefficient_float[dir][i_4 * 2 - 1] * f_5 + coefficient_float[dir][i_4 * 2 - 2] * f_6; for (int i_7 = i_4 * 2 - 1; i_7 >= 2; --i_7) { coefficient_float[dir][i_7] += coefficient_float[dir][i_7 - 1] * f_5 + coefficient_float[dir][i_7 - 2] * f_6; } coefficient_float[dir][1] += coefficient_float[dir][0] * f_5 + f_6; coefficient_float[dir][0] += f_5; } if (dir == 0) { for (i_4 = 0; i_4 < this.numPairs[0] * 2; i_4++) { coefficient_float[0][i_4] *= invUnity_float; } } for (i_4 = 0; i_4 < this.numPairs[dir] * 2; i_4++) { coefficient_int[dir][i_4] = (int) (coefficient_float[dir][i_4] * 65536.0F); } return this.numPairs[dir] * 2; } } @Override public String toString() { StringBuilder result = new StringBuilder(); String newLine = System.getProperty(""line.separator""); result.append(this.getClass().getName()); result.append("" {""); result.append(newLine); // determine fields declared in this class only (no fields of // superclass) Field[] fields = this.getClass().getDeclaredFields(); // print field names paired with their values for (Field field : fields) { if (Modifier.isStatic(field.getModifiers())) continue; result.append("" ""); try { result.append(field.getType().getCanonicalName() + "" "" + field.getName() + "": ""); result.append(Utils.getFieldValue(this, field)); } catch (Throwable ex) { System.out.println(ex); } result.append(newLine); } result.append(""}""); return result.toString(); } } " " package com.rs.cache.loaders.sound; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Random; import com.rs.lib.io.InputStream; import com.rs.lib.util.Utils; public class Instrument { static int[] noise = new int[32768]; static int[] sine; static int[] output; static int[] phases; static int[] delays; static int[] volumeStep; static int[] pitchStep; static int[] pitchBaseStep; Envelope pitch; Envelope volume; Envelope pitchModifier; Envelope pitchModifierAmplitude; Envelope volumeMultiplier; Envelope volumeAmplitude; Envelope release; Envelope attack; int delayTime = 0; int delayDecay = 100; int duration = 500; int offset = 0; Filter filter; Envelope filterEnvelope; int[] oscillatorVolume = new int[5]; int[] oscillatorPitch = new int[5]; int[] oscillatorDelays = new int[5]; static { Random rand = new Random(0L); for (int i = 0; i < 32768; i++) { noise[i] = (rand.nextInt() & 0x2) - 1; } sine = new int[32768]; for (int i = 0; i < 32768; i++) { sine[i] = (int) (Math.sin((double) i / 5215.1903D) * 16384.0D); } output = new int[220500]; phases = new int[5]; delays = new int[5]; volumeStep = new int[5]; pitchStep = new int[5]; pitchBaseStep = new int[5]; } final int[] synthesize(int mixDuration, int instrDuration) { Arrays.fill(output, 0, mixDuration, 0); if (instrDuration < 10) { return output; } else { double fs = (double) mixDuration / ((double) instrDuration + 0.0D); this.pitch.reset(); this.volume.reset(); int pitchModStep = 0; int pitchModBaseStep = 0; int pitchModPhase = 0; if (this.pitchModifier != null) { this.pitchModifier.reset(); this.pitchModifierAmplitude.reset(); pitchModStep = (int) ((double) (this.pitchModifier.end - this.pitchModifier.start) * 32.768D / fs); pitchModBaseStep = (int) ((double) this.pitchModifier.start * 32.768D / fs); } int volumeModStep = 0; int volumeModBaseStep = 0; int volumeModPhase = 0; if (this.volumeMultiplier != null) { this.volumeMultiplier.reset(); this.volumeAmplitude.reset(); volumeModStep = (int) ((double) (this.volumeMultiplier.end - this.volumeMultiplier.start) * 32.768D / fs); volumeModBaseStep = (int) ((double) this.volumeMultiplier.start * 32.768D / fs); } for (int i = 0; i < 5; i++) { if (this.oscillatorVolume[i] != 0) { phases[i] = 0; delays[i] = (int) ((double) this.oscillatorDelays[i] * fs); volumeStep[i] = (this.oscillatorVolume[i] << 14) / 100; pitchStep[i] = (int) ((double) (this.pitch.end - this.pitch.start) * 32.768D * Math.pow(1.0057929410678534D, (double) this.oscillatorPitch[i]) / fs); pitchBaseStep[i] = (int) ((double) this.pitch.start * 32.768D / fs); } } for (int i = 0; i < mixDuration; i++) { int pitchChange = this.pitch.step(mixDuration); int volumeChange = this.volume.step(mixDuration); if (this.pitchModifier != null) { int mod = this.pitchModifier.step(mixDuration); int modAmplitude = this.pitchModifierAmplitude.step(mixDuration); pitchChange += this.evaluateWave(pitchModPhase, modAmplitude, this.pitchModifier.form) >> 1; pitchModPhase = pitchModPhase + pitchModBaseStep + (mod * pitchModStep >> 16); } if (this.volumeMultiplier != null) { int mod = this.volumeMultiplier.step(mixDuration); int modAmplitude = this.volumeAmplitude.step(mixDuration); volumeChange = volumeChange * ((this.evaluateWave(volumeModPhase, modAmplitude, this.volumeMultiplier.form) >> 1) + 32768) >> 15; volumeModPhase = volumeModPhase + volumeModBaseStep + (mod * volumeModStep >> 16); } for (int j = 0; j < 5; j++) { if (this.oscillatorVolume[j] != 0) { int i_15 = delays[j] + i; if (i_15 < mixDuration) { output[i_15] += this.evaluateWave(phases[j], volumeChange * volumeStep[j] >> 15, this.pitch.form); phases[j] += (pitchChange * pitchStep[j] >> 16) + pitchBaseStep[j]; } } } } if (this.release != null) { this.release.reset(); this.attack.reset(); int counter = 0; boolean muted = true; for (int i = 0; i < mixDuration; i++) { int onStep = this.release.step(mixDuration); int offStep = this.attack.step(mixDuration); int threshold; if (muted) { threshold = (onStep * (this.release.end - this.release.start) >> 8) + this.release.start; } else { threshold = (offStep * (this.release.end - this.release.start) >> 8) + this.release.start; } counter += 256; if (counter >= threshold) { counter = 0; muted = !muted; } if (muted) { output[i] = 0; } } } if (this.delayTime > 0 && this.delayDecay > 0) { int delay = (int) ((double) this.delayTime * fs); for (int i = delay; i < mixDuration; i++) { output[i] += output[i - delay] * this.delayDecay / 100; } } if (this.filter.numPairs[0] > 0 || this.filter.numPairs[1] > 0) { this.filterEnvelope.reset(); int t = this.filterEnvelope.step(mixDuration + 1); int M = this.filter.compute(0, (float) t / 65536.0F); int N = this.filter.compute(1, (float) t / 65536.0F); if (mixDuration >= M + N) { int n = 0; int delay = N; if (N > mixDuration - M) { delay = mixDuration - M; } while (n < delay) { int y = (int) ((long) output[n + M] * (long) Filter.invUnity_int >> 16); for (int i_17 = 0; i_17 < M; i_17++) { y += (int) ((long) output[n + M - 1 - i_17] * (long) Filter.coefficient_int[0][i_17] >> 16); } for (int i_17 = 0; i_17 < n; i_17++) { y -= (int) ((long) output[n - 1 - i_17] * (long) Filter.coefficient_int[1][i_17] >> 16); } output[n] = y; t = this.filterEnvelope.step(mixDuration + 1); ++n; } delay = 128; while (true) { if (delay > mixDuration - M) { delay = mixDuration - M; } while (n < delay) { int y = (int) ((long) output[n + M] * (long) Filter.invUnity_int >> 16); for (int i = 0; i < M; i++) { y += (int) ((long) output[n + M - 1 - i] * (long) Filter.coefficient_int[0][i] >> 16); } for (int i = 0; i < N; i++) { y -= (int) ((long) output[n - 1 - i] * (long) Filter.coefficient_int[1][i] >> 16); } output[n] = y; t = this.filterEnvelope.step(mixDuration + 1); ++n; } if (n >= mixDuration - M) { while (n < mixDuration) { int y = 0; for (int i = n + M - mixDuration; i < M; i++) { y += (int) ((long) output[n + M - 1 - i] * (long) Filter.coefficient_int[0][i] >> 16); } for (int i = 0; i < N; i++) { y -= (int) ((long) output[n - 1 - i] * (long) Filter.coefficient_int[1][i] >> 16); } output[n] = y; this.filterEnvelope.step(mixDuration + 1); ++n; } break; } M = this.filter.compute(0, (float) t / 65536.0F); N = this.filter.compute(1, (float) t / 65536.0F); delay += 128; } } } for (int i = 0; i < mixDuration; i++) { if (output[i] < -32768) { output[i] = -32768; } if (output[i] > 32767) { output[i] = 32767; } } return output; } } final int evaluateWave(int table, int phase, int amplitude) { return amplitude == 1 ? ((table & 0x7fff) < 16384 ? phase : -phase) : (amplitude == 2 ? sine[table & 0x7fff] * phase >> 14 : (amplitude == 3 ? (phase * (table & 0x7fff) >> 14) - phase : (amplitude == 4 ? phase * noise[table / 2607 & 0x7fff] : 0))); } final void decodeInstruments(InputStream buffer) { this.pitch = new Envelope(); this.pitch.decode(buffer); this.volume = new Envelope(); this.volume.decode(buffer); int option = buffer.readUnsignedByte(); if (option != 0) { buffer.setOffset(buffer.getOffset()-1); this.pitchModifier = new Envelope(); this.pitchModifier.decode(buffer); this.pitchModifierAmplitude = new Envelope(); this.pitchModifierAmplitude.decode(buffer); } option = buffer.readUnsignedByte(); if (option != 0) { buffer.setOffset(buffer.getOffset()-1); this.volumeMultiplier = new Envelope(); this.volumeMultiplier.decode(buffer); this.volumeAmplitude = new Envelope(); this.volumeAmplitude.decode(buffer); } option = buffer.readUnsignedByte(); if (option != 0) { buffer.setOffset(buffer.getOffset()-1); this.release = new Envelope(); this.release.decode(buffer); this.attack = new Envelope(); this.attack.decode(buffer); } for (int i = 0; i < 10; i++) { int volume = buffer.readUnsignedSmart(); if (volume == 0) { break; } this.oscillatorVolume[i] = volume; this.oscillatorPitch[i] = buffer.readSignedSmart(); this.oscillatorDelays[i] = buffer.readUnsignedSmart(); } this.delayTime = buffer.readUnsignedSmart(); this.delayDecay = buffer.readUnsignedSmart(); this.duration = buffer.readUnsignedShort(); this.offset = buffer.readUnsignedShort(); this.filter = new Filter(); this.filterEnvelope = new Envelope(); this.filter.decode(buffer, this.filterEnvelope); } @Override public String toString() { StringBuilder result = new StringBuilder(); String newLine = System.getProperty(""line.separator""); result.append(this.getClass().getName()); result.append("" {""); result.append(newLine); // determine fields declared in this class only (no fields of // superclass) Field[] fields = this.getClass().getDeclaredFields(); // print field names paired with their values for (Field field : fields) { if (Modifier.isStatic(field.getModifiers())) continue; result.append("" ""); try { result.append(field.getType().getCanonicalName() + "" "" + field.getName() + "": ""); result.append(Utils.getFieldValue(this, field)); } catch (Throwable ex) { System.out.println(ex); } result.append(newLine); } result.append(""}""); return result.toString(); } } " " package com.rs.cache.loaders.sound; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import javax.sound.midi.MetaMessage; import javax.sound.midi.MidiEvent; import javax.sound.midi.MidiMessage; import javax.sound.midi.MidiSystem; import javax.sound.midi.Sequence; import javax.sound.midi.ShortMessage; import javax.sound.midi.Track; public class MIDIEncoder { //index 6 archive 803 = login public static final int NOTE_OFF = 0x80; public static final int NOTE_ON = 0x90; public static final int KEY_AFTER_TOUCH = 0xA0; public static final int CONTROL_CHANGE = 0xB0; public static final int PROGRAM_CHANGE = 0xC0; public static final int CHANNEL_AFTER_TOUCH = 0xD0; public static final int PITCH_WHEEL_CHANGE = 0xE0; public static final int END_OF_TRACK = 0x2F; public static final int SET_TEMPO = 0x51; public static void main(String[] args) throws Exception { Sequence sequence = MidiSystem.getSequence(new File(""time.mid"")); DataOutputStream dos = new DataOutputStream(new FileOutputStream(""time"")); for (Track track : sequence.getTracks()) { int prevChannel = 0; for (int i = 0; i < track.size(); i++) { MidiEvent event = track.get(i); MidiMessage message = event.getMessage(); if (message instanceof ShortMessage sm) { int ch = (sm.getChannel() ^ prevChannel) << 4; switch (sm.getCommand()) { case NOTE_OFF: dos.write(1 | ch); prevChannel = sm.getChannel(); break; case NOTE_ON: dos.write(0 | ch); prevChannel = sm.getChannel(); break; case KEY_AFTER_TOUCH: dos.write(5 | ch); prevChannel = sm.getChannel(); break; case CONTROL_CHANGE: dos.write(2 | ch); prevChannel = sm.getChannel(); break; case PROGRAM_CHANGE: dos.write(6 | ch); prevChannel = sm.getChannel(); break; case CHANNEL_AFTER_TOUCH: dos.write(4 | ch); prevChannel = sm.getChannel(); break; case PITCH_WHEEL_CHANGE: dos.write(3 | ch); prevChannel = sm.getChannel(); break; } } else if (message instanceof MetaMessage) { MetaMessage mm = (MetaMessage) message; switch (mm.getType()) { case END_OF_TRACK: dos.write(7); break; case SET_TEMPO: dos.write(23); break; default: // OTHER META EVENTS ARE IGNORED break; } } else { // SYSEX MESSAGES ARE IGNORED } } } // write event timestamp for used opcodes for (Track track : sequence.getTracks()) { int lastTick = 0; for (int i = 0; i < track.size(); i++) { MidiEvent event = track.get(i); MidiMessage message = event.getMessage(); if (message instanceof ShortMessage sm) { switch (sm.getCommand()) { case NOTE_OFF: case NOTE_ON: case KEY_AFTER_TOUCH: case CONTROL_CHANGE: case PROGRAM_CHANGE: case CHANNEL_AFTER_TOUCH: case PITCH_WHEEL_CHANGE: putVariableInt(dos, (int) event.getTick() - lastTick); lastTick = (int) event.getTick(); break; } } else if (message instanceof MetaMessage mm) { switch (mm.getType()) { case END_OF_TRACK: case SET_TEMPO: putVariableInt(dos, (int) event.getTick() - lastTick); lastTick = (int) event.getTick(); break; } } } } // jagex works with offset from the last one because this is usually 0 and gives // better compression rates int lastController = 0; int lastNote = 0; int lastNoteOnVelocity = 0; int lastNoteOffVelocity = 0; int lastWheelChangeT = 0; int lastWheelChangeB = 0; int lastChannelAfterTouch = 0; int lastKeyAfterTouchVelocity = 0; // write controller number changes int[] lastControllerValue = new int[128]; for (Track track : sequence.getTracks()) { for (int i = 0; i < track.size(); i++) { MidiEvent event = track.get(i); MidiMessage message = event.getMessage(); if (message instanceof ShortMessage sm) { if (sm.getCommand() == CONTROL_CHANGE) { dos.write(sm.getData1() - lastController); lastController = sm.getData1(); } } } } // controller 64 65 120 121 123 changes for (Track track : sequence.getTracks()) { for (int i = 0; i < track.size(); i++) { MidiEvent event = track.get(i); MidiMessage message = event.getMessage(); if (message instanceof ShortMessage sm) { if (sm.getCommand() == CONTROL_CHANGE && (sm.getData1() == 64 || sm.getData1() == 65 || sm.getData1() == 120 || sm.getData1() == 121 || sm.getData1() == 123)) { dos.write(sm.getData2() - lastControllerValue[sm.getData1()]); lastControllerValue[sm.getData1()] = sm.getData2(); } } } } // key after touch velocity changes for (Track track : sequence.getTracks()) { for (int i = 0; i < track.size(); i++) { MidiEvent event = track.get(i); MidiMessage message = event.getMessage(); if (message instanceof ShortMessage sm) { if (sm.getCommand() == KEY_AFTER_TOUCH) { dos.write(sm.getData2() - lastKeyAfterTouchVelocity); lastKeyAfterTouchVelocity = sm.getData2(); } } } } // channel after touch channel changes for (Track track : sequence.getTracks()) { for (int i = 0; i < track.size(); i++) { MidiEvent event = track.get(i); MidiMessage message = event.getMessage(); if (message instanceof ShortMessage sm) { if (sm.getCommand() == CHANNEL_AFTER_TOUCH) { dos.write(sm.getData1() - lastChannelAfterTouch); lastChannelAfterTouch = sm.getData1(); } } } } // pitch bend top values for (Track track : sequence.getTracks()) { for (int i = 0; i < track.size(); i++) { MidiEvent event = track.get(i); MidiMessage message = event.getMessage(); if (message instanceof ShortMessage sm) { if (sm.getCommand() == PITCH_WHEEL_CHANGE) { dos.write(sm.getData2() - lastWheelChangeT); lastWheelChangeT = sm.getData2(); } } } } // controller 1 changes for (Track track : sequence.getTracks()) { for (int i = 0; i < track.size(); i++) { MidiEvent event = track.get(i); MidiMessage message = event.getMessage(); if (message instanceof ShortMessage sm) { if (sm.getCommand() == CONTROL_CHANGE && sm.getData1() == 1) { dos.write(sm.getData2() - lastControllerValue[sm.getData1()]); lastControllerValue[sm.getData1()] = sm.getData2(); } } } } // controller 7 changes for (Track track : sequence.getTracks()) { for (int i = 0; i < track.size(); i++) { MidiEvent event = track.get(i); MidiMessage message = event.getMessage(); if (message instanceof ShortMessage sm) { if (sm.getCommand() == CONTROL_CHANGE && sm.getData1() == 7) { dos.write(sm.getData2() - lastControllerValue[sm.getData1()]); lastControllerValue[sm.getData1()] = sm.getData2(); } } } } // controller 10 changes for (Track track : sequence.getTracks()) { for (int i = 0; i < track.size(); i++) { MidiEvent event = track.get(i); MidiMessage message = event.getMessage(); if (message instanceof ShortMessage sm) { if (sm.getCommand() == CONTROL_CHANGE && sm.getData1() == 10) { dos.write(sm.getData2() - lastControllerValue[sm.getData1()]); lastControllerValue[sm.getData1()] = sm.getData2(); } } } } // note changes for (Track track : sequence.getTracks()) { for (int i = 0; i < track.size(); i++) { MidiEvent event = track.get(i); MidiMessage message = event.getMessage(); if (message instanceof ShortMessage sm) { if (sm.getCommand() == NOTE_OFF || sm.getCommand() == NOTE_ON || sm.getCommand() == KEY_AFTER_TOUCH) { dos.write(sm.getData1() - lastNote); lastNote = sm.getData1(); } } } } // note on velocity changes for (Track track : sequence.getTracks()) { for (int i = 0; i < track.size(); i++) { MidiEvent event = track.get(i); MidiMessage message = event.getMessage(); if (message instanceof ShortMessage sm) { if (sm.getCommand() == NOTE_ON) { dos.write(sm.getData2() - lastNoteOnVelocity); lastNoteOnVelocity = sm.getData2(); } } } } // all unlisted controller changes (controllers are probably grouped like this // because it gives an even better compression) for (Track track : sequence.getTracks()) { for (int i = 0; i < track.size(); i++) { MidiEvent event = track.get(i); MidiMessage message = event.getMessage(); if (message instanceof ShortMessage sm) { if (sm.getCommand() == CONTROL_CHANGE && !(sm.getData1() == 64 || sm.getData1() == 65 || sm.getData1() == 120 || sm.getData1() == 121 || sm.getData1() == 123 || sm.getData1() == 0 || sm.getData1() == 32 || sm.getData1() == 1 || sm.getData1() == 33 || sm.getData1() == 7 || sm.getData1() == 39 || sm.getData1() == 10 || sm.getData1() == 42 || sm.getData1() == 99 || sm.getData1() == 98 || sm.getData1() == 101 || sm.getData1() == 100)) { dos.write(sm.getData2() - lastControllerValue[sm.getData1()]); lastControllerValue[sm.getData1()] = sm.getData2(); } } } } // note off velocity changes for (Track track : sequence.getTracks()) { for (int i = 0; i < track.size(); i++) { MidiEvent event = track.get(i); MidiMessage message = event.getMessage(); if (message instanceof ShortMessage sm) { if (sm.getCommand() == NOTE_OFF) { dos.write(sm.getData2() - lastNoteOffVelocity); lastNoteOffVelocity = sm.getData2(); } } } } // controller 33 changes for (Track track : sequence.getTracks()) { for (int i = 0; i < track.size(); i++) { MidiEvent event = track.get(i); MidiMessage message = event.getMessage(); if (message instanceof ShortMessage sm) { if (sm.getCommand() == CONTROL_CHANGE && sm.getData1() == 33) { dos.write(sm.getData2() - lastControllerValue[sm.getData1()]); lastControllerValue[sm.getData1()] = sm.getData2(); } } } } // controller 39 changes for (Track track : sequence.getTracks()) { for (int i = 0; i < track.size(); i++) { MidiEvent event = track.get(i); MidiMessage message = event.getMessage(); if (message instanceof ShortMessage sm) { if (sm.getCommand() == CONTROL_CHANGE && sm.getData1() == 39) { dos.write(sm.getData2() - lastControllerValue[sm.getData1()]); lastControllerValue[sm.getData1()] = sm.getData2(); } } } } // controller 42 changes for (Track track : sequence.getTracks()) { for (int i = 0; i < track.size(); i++) { MidiEvent event = track.get(i); MidiMessage message = event.getMessage(); if (message instanceof ShortMessage sm) { if (sm.getCommand() == CONTROL_CHANGE && sm.getData1() == 42) { dos.write(sm.getData2() - lastControllerValue[sm.getData1()]); lastControllerValue[sm.getData1()] = sm.getData2(); } } } } // controller 0, 32 and program changes for (Track track : sequence.getTracks()) { for (int i = 0; i < track.size(); i++) { MidiEvent event = track.get(i); MidiMessage message = event.getMessage(); if (message instanceof ShortMessage sm) { if (sm.getCommand() == CONTROL_CHANGE && (sm.getData1() == 0 || sm.getData1() == 32)) { System.out.println(""WARNING SONG USES SOUND BANKS BYTE: "" + sm.getData1() + "" VALUE: "" + sm.getData2() + "" ""); dos.write(sm.getData2() - lastControllerValue[sm.getData1()]); lastControllerValue[sm.getData1()] = sm.getData2(); } else if (sm.getCommand() == PROGRAM_CHANGE) { dos.write(sm.getData1()); } } } } // pitch bend bottom changes for (Track track : sequence.getTracks()) { for (int i = 0; i < track.size(); i++) { MidiEvent event = track.get(i); MidiMessage message = event.getMessage(); if (message instanceof ShortMessage sm) { if (sm.getCommand() == PITCH_WHEEL_CHANGE) { dos.write(sm.getData1() - lastWheelChangeB); lastWheelChangeB = sm.getData1(); } } } } // controller 99 changes for (Track track : sequence.getTracks()) { for (int i = 0; i < track.size(); i++) { MidiEvent event = track.get(i); MidiMessage message = event.getMessage(); if (message instanceof ShortMessage sm) { if (sm.getCommand() == CONTROL_CHANGE && sm.getData1() == 99) { dos.write(sm.getData2() - lastControllerValue[sm.getData1()]); lastControllerValue[sm.getData1()] = sm.getData2(); } } } } // controller 98 changes for (Track track : sequence.getTracks()) { for (int i = 0; i < track.size(); i++) { MidiEvent event = track.get(i); MidiMessage message = event.getMessage(); if (message instanceof ShortMessage sm) { if (sm.getCommand() == CONTROL_CHANGE && sm.getData1() == 98) { dos.write(sm.getData2() - lastControllerValue[sm.getData1()]); lastControllerValue[sm.getData1()] = sm.getData2(); } } } } // controller 101 changes for (Track track : sequence.getTracks()) { for (int i = 0; i < track.size(); i++) { MidiEvent event = track.get(i); MidiMessage message = event.getMessage(); if (message instanceof ShortMessage sm) { if (sm.getCommand() == CONTROL_CHANGE && sm.getData1() == 101) { dos.write(sm.getData2() - lastControllerValue[sm.getData1()]); lastControllerValue[sm.getData1()] = sm.getData2(); } } } } // controller 100 changes for (Track track : sequence.getTracks()) { for (int i = 0; i < track.size(); i++) { MidiEvent event = track.get(i); MidiMessage message = event.getMessage(); if (message instanceof ShortMessage sm) { if (sm.getCommand() == CONTROL_CHANGE && sm.getData1() == 100) { dos.write(sm.getData2() - lastControllerValue[sm.getData1()]); lastControllerValue[sm.getData1()] = sm.getData2(); } } } } // tempo changes for (Track track : sequence.getTracks()) { for (int i = 0; i < track.size(); i++) { MidiEvent event = track.get(i); MidiMessage message = event.getMessage(); if (message instanceof MetaMessage mm) { if (mm.getType() == SET_TEMPO) { dos.write(mm.getData()); } } } } // write footer dos.write(sequence.getTracks().length); dos.writeShort(sequence.getResolution()); dos.flush(); dos.close(); } static final void putVariableInt(DataOutputStream dos, int value) throws IOException { if ((value & ~0x7f) != 0) { if ((value & ~0x3fff) != 0) { if ((~0x1fffff & value) != 0) { if ((~0xfffffff & value) != 0) { dos.write(value >>> 28 | 0x80); } dos.write(value >>> 21 | 0x80); } dos.write(value >>> 14 | 0x80); } dos.write(value >>> 7 | 0x80); } dos.write(0x7f & value); } } " " package com.rs.cache.loaders.sound; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashSet; import java.util.Set; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.cache.loaders.ObjectDefinitions; import com.rs.cache.loaders.animations.AnimationDefinitions; import com.rs.cache.loaders.cs2.CS2Definitions; import com.rs.cache.loaders.cs2.CS2Instruction; import com.rs.cache.loaders.cs2.CS2Script; import com.rs.lib.io.InputStream; import com.rs.lib.io.OutputStream; import com.rs.lib.util.Utils; public class SoundEffect { Instrument[] instruments = new Instrument[10]; int loopBegin; int loopEnd; SoundEffect(InputStream buffer) { for (int i = 0; i < 10; i++) { int hasInstruments = buffer.readUnsignedByte(); if (hasInstruments != 0) { buffer.setOffset(buffer.getOffset()-1); this.instruments[i] = new Instrument(); this.instruments[i].decodeInstruments(buffer); } } this.loopBegin = buffer.readUnsignedShort(); this.loopEnd = buffer.readUnsignedShort(); } public static void main(String[] args) throws IOException { Cache.init(""../cache/""); Set autoUsedIds = new HashSet<>(); for (int i = 0;i < Utils.getAnimationDefinitionsSize();i++) autoUsedIds.addAll(AnimationDefinitions.getDefs(i).getUsedSynthSoundIds()); for (int i = 0;i < Utils.getObjectDefinitionsSize();i++) { ObjectDefinitions defs = ObjectDefinitions.getDefs(i); if (defs == null) continue; if (defs.ambientSoundId > 0 && !defs.midiSound) autoUsedIds.add(ObjectDefinitions.getDefs(i).ambientSoundId); if (defs.soundEffectsTimed != null && defs.soundEffectsTimed.length > 0 && !defs.midiSoundEffectsTimed) for (int sound : defs.soundEffectsTimed) if (sound > 0) autoUsedIds.add(sound); } for (int i = 0;i < Cache.STORE.getIndex(IndexType.CS2_SCRIPTS).getLastArchiveId();i++) { CS2Script s = CS2Definitions.getScript(i); if (s == null) continue; for (int x = 0;x < s.operations.length;x++) { if (s.operations[x] == CS2Instruction.SOUND_SYNTH) { for (int op = 0;op < s.operations.length;op++) { if (s.operations[op] == CS2Instruction.SOUND_SYNTH && op-3 >= 0 && s.intOpValues[op-3] > 1) autoUsedIds.add(s.intOpValues[op-3]); } break; } if (s.operations[x] == CS2Instruction.SOUND_SYNTH_RATE) { for (int op = 0;op < s.operations.length;op++) { if (s.operations[op] == CS2Instruction.SOUND_SYNTH_RATE && op-5 >= 0 && s.intOpValues[op-5] > 1) autoUsedIds.add(s.intOpValues[op-5]); } break; } if (s.operations[x] == CS2Instruction.SOUND_SYNTH_VOLUME) { for (int op = 0;op < s.operations.length;op++) { if (s.operations[op] == CS2Instruction.SOUND_SYNTH_VOLUME && op-4 >= 0 && s.intOpValues[op-4] > 1) autoUsedIds.add(s.intOpValues[op-4]); } break; } } } for (int i = 0;i < Cache.STORE.getIndex(IndexType.SOUND_EFFECTS).getLastArchiveId() + 1;i++) { SoundEffect effect = getEffect(i); if (effect == null) continue; if (autoUsedIds.contains(i)) continue; System.out.println(i); } //Files.write(getEffect(168).toWAV(), new File(""./one.wav"")); } public static SoundEffect getEffect(int id) { byte[] data = Cache.STORE.getIndex(IndexType.SOUND_EFFECTS).getFile(id, 0); if (data == null) return null; return new SoundEffect(new InputStream(data)); } public byte[] toWAV() { byte[] mixed = mix(); /* * Convert to 16 bit audio */ byte[] fixed = new byte[mixed.length*2]; for (int i = 0;i < mixed.length;i++) { fixed[i * 2] = (byte) (mixed[i] >> 8 * 2); fixed[i * 2 + 1] = (byte) (mixed[i] >> 16 * 2 + 1); } OutputStream stream = new OutputStream(); stream.writeInt(0x52494646); /* 'RIFF' chunk name */ stream.writeIntLE(36 + fixed.length); /* 'RIFF' block size (36 = 4 + 4 + 4 + 2 + 2 + 4 + 4 + 2 + 2 + 4 + 4) */ stream.writeInt(0x57415645); /* 'WAVE' format */ stream.writeInt(0x666d7420); /* 'fmt ' subchunk */ stream.writeIntLE(16); /* 'fmt ' subchunk size (16 = 2 + 2 + 4 + 4 + 2 + 2) */ stream.writeShortLE(1); /* audio format is 1 i.e. linear-quantized pulse modulation (see: http://en.wikipedia.org/wiki/Linear_PCM) */ stream.writeShortLE(1); /* 1 audio channel, i.e. mono not stereo */ stream.writeIntLE(22050); /* sample rate is 22050 Hz */ stream.writeIntLE(22050); /* byte rate is 22050 Hz (each sample is 1 byte) */ stream.writeShortLE(1); /* bytes per each sample for our 1 channel */ stream.writeShortLE(16); /* 8 bits per sample */ stream.writeInt(0x64617461); /* 'data' subchunk */ stream.writeIntLE(fixed.length); /* encoded audio data */ stream.writeBytes(fixed); return stream.toByteArray(); } public final int getDelay() { int delay = 9999999; int i_2; for (i_2 = 0; i_2 < 10; i_2++) { if (this.instruments[i_2] != null && this.instruments[i_2].offset / 20 < delay) { delay = this.instruments[i_2].offset / 20; } } if (this.loopBegin < this.loopEnd && this.loopBegin / 20 < delay) { delay = this.loopBegin / 20; } if (delay != 9999999 && delay != 0) { for (i_2 = 0; i_2 < 10; i_2++) { if (this.instruments[i_2] != null) { this.instruments[i_2].offset -= delay * 20; } } if (this.loopBegin < this.loopEnd) { this.loopBegin -= delay * 20; this.loopEnd -= delay * 20; } return delay; } else { return 0; } } final byte[] mix() { int duration = 0; for (int i = 0; i < 10; i++) { if (this.instruments[i] != null && this.instruments[i].duration + this.instruments[i].offset > duration) { duration = this.instruments[i].duration + this.instruments[i].offset; } } if (duration == 0) { return new byte[0]; } else { int ns = duration * 22050 / 1000; byte[] mixed = new byte[ns]; for (int i = 0; i < 10; i++) { if (this.instruments[i] != null) { int mixDuration = this.instruments[i].duration * 22050 / 1000; int offset = this.instruments[i].offset * 22050 / 1000; int[] samples = this.instruments[i].synthesize(mixDuration, this.instruments[i].duration); for (int j = 0; j < mixDuration; j++) { int out = (samples[j] >> 8) + mixed[j + offset]; if ((out + 128 & ~0xff) != 0) { out = out >> 31 ^ 0x7f; } mixed[j + offset] = (byte) out; } } } return mixed; } } @Override public String toString() { StringBuilder result = new StringBuilder(); String newLine = System.getProperty(""line.separator""); result.append(this.getClass().getName()); result.append("" {""); result.append(newLine); // determine fields declared in this class only (no fields of // superclass) Field[] fields = this.getClass().getDeclaredFields(); // print field names paired with their values for (Field field : fields) { if (Modifier.isStatic(field.getModifiers())) continue; result.append("" ""); try { result.append(field.getType().getCanonicalName() + "" "" + field.getName() + "": ""); result.append(Utils.getFieldValue(this, field)); } catch (Throwable ex) { System.out.println(ex); } result.append(newLine); } result.append(""}""); return result.toString(); } } " " package com.rs.cache.utils; import java.math.BigInteger; import java.util.zip.CRC32; public final class CacheUtil { public static byte[] cryptRSA(byte[] data, BigInteger exponent, BigInteger modulus) { return new BigInteger(data).modPow(exponent, modulus).toByteArray(); } public static int getCrcChecksum(byte[] buffer, int length) { CRC32 crc = new CRC32(); crc.update(buffer, 0, length); return (int) crc.getValue(); } public static int getNameHash(String name) { return name.toLowerCase().hashCode(); } private CacheUtil() { } } " " package com.rs.cache.utils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import com.rs.cache.utils.bzip2.CBZip2InputStream; import com.rs.cache.utils.bzip2.CBZip2OutputStream; public class CompressionUtils { public static byte[] bunzip2(byte[] bytes) { try { byte[] bzip2 = new byte[bytes.length + 2]; bzip2[0] = 'h'; bzip2[1] = '1'; System.arraycopy(bytes, 0, bzip2, 2, bytes.length); InputStream is = new CBZip2InputStream(new ByteArrayInputStream(bzip2)); try { ByteArrayOutputStream os = new ByteArrayOutputStream(); try { byte[] buf = new byte[4096]; int len = 0; while ((len = is.read(buf, 0, buf.length)) != -1) { os.write(buf, 0, len); } } finally { os.close(); } return os.toByteArray(); } finally { is.close(); } } catch (IOException e) { e.printStackTrace(); return null; } } public static byte[] bzip2(byte[] bytes) { try { InputStream is = new ByteArrayInputStream(bytes); try { ByteArrayOutputStream bout = new ByteArrayOutputStream(); OutputStream os = new CBZip2OutputStream(bout, 1); try { byte[] buf = new byte[4096]; int len = 0; while ((len = is.read(buf, 0, buf.length)) != -1) { os.write(buf, 0, len); } } finally { os.close(); } bytes = bout.toByteArray(); byte[] bzip2 = new byte[bytes.length - 2]; System.arraycopy(bytes, 2, bzip2, 0, bzip2.length); return bzip2; } finally { is.close(); } } catch (IOException e) { e.printStackTrace(); return null; } } public static byte[] gunzip(byte[] bytes) { try { InputStream is = new GZIPInputStream(new ByteArrayInputStream(bytes)); try { ByteArrayOutputStream os = new ByteArrayOutputStream(); try { byte[] buf = new byte[4096]; int len = 0; while ((len = is.read(buf, 0, buf.length)) != -1) { os.write(buf, 0, len); } } finally { os.close(); } return os.toByteArray(); } finally { is.close(); } } catch (IOException e) { e.printStackTrace(); return null; } } public static byte[] gzip(byte[] bytes) { try { InputStream is = new ByteArrayInputStream(bytes); try { ByteArrayOutputStream bout = new ByteArrayOutputStream(); OutputStream os = new GZIPOutputStream(bout); try { byte[] buf = new byte[4096]; int len = 0; while ((len = is.read(buf, 0, buf.length)) != -1) { os.write(buf, 0, len); } } finally { os.close(); } return bout.toByteArray(); } finally { is.close(); } } catch (IOException e) { e.printStackTrace(); return null; } } } " " package com.rs.cache.utils; public final class Constants { public static final int NO_COMPRESSION = 0; public static final int BZIP2_COMPRESSION = 1; public static final int GZIP_COMPRESSION = 2; public static final int MAX_VALID_ARCHIVE_LENGTH = 1000000000; public static final int CLIENT_BUILD = 727; public static final boolean ENCRYPTED_CACHE = false; private Constants() { } } " " package com.rs.cache.utils; /** * The Whirlpool hashing function. * *

* References * *

* The Whirlpool algorithm was developed by * Paulo S. L. M. Barreto and * Vincent Rijmen. * * See * P.S.L.M. Barreto, V. Rijmen, * ``The Whirlpool hashing function,'' * First NESSIE workshop, 2000 (tweaked version, 2003), * * * @author Paulo S.L.M. Barreto * @author Vincent Rijmen. * * @version 3.0 (2003.03.12) * * ============================================================================= * * Differences from version 2.1: * * - Suboptimal diffusion matrix replaced by cir(1, 1, 4, 1, 8, 5, 2, 9). * * ============================================================================= * * Differences from version 2.0: * * - Generation of ISO/IEC 10118-3 test vectors. * - Bug fix: nonzero carry was ignored when tallying the data length * (this bug apparently only manifested itself when feeding data * in pieces rather than in a single chunk at once). * * Differences from version 1.0: * * - Original S-box replaced by the tweaked, hardware-efficient version. * * ============================================================================= * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ import java.util.Arrays; public class Whirlpool { public static final int DIGESTBITS = 512; public static final int DIGESTBYTES = DIGESTBITS >>> 3; protected static final int R = 10; private static final String sbox = ""\u1823\uc6E8\u87B8\u014F\u36A6\ud2F5\u796F\u9152"" + ""\u60Bc\u9B8E\uA30c\u7B35\u1dE0\ud7c2\u2E4B\uFE57"" + ""\u1577\u37E5\u9FF0\u4AdA\u58c9\u290A\uB1A0\u6B85"" + ""\uBd5d\u10F4\ucB3E\u0567\uE427\u418B\uA77d\u95d8"" + ""\uFBEE\u7c66\udd17\u479E\ucA2d\uBF07\uAd5A\u8333"" + ""\u6302\uAA71\uc819\u49d9\uF2E3\u5B88\u9A26\u32B0"" + ""\uE90F\ud580\uBEcd\u3448\uFF7A\u905F\u2068\u1AAE"" + ""\uB454\u9322\u64F1\u7312\u4008\uc3Ec\udBA1\u8d3d"" + ""\u9700\ucF2B\u7682\ud61B\uB5AF\u6A50\u45F3\u30EF"" + ""\u3F55\uA2EA\u65BA\u2Fc0\udE1c\uFd4d\u9275\u068A"" + ""\uB2E6\u0E1F\u62d4\uA896\uF9c5\u2559\u8472\u394c"" + ""\u5E78\u388c\ud1A5\uE261\uB321\u9c1E\u43c7\uFc04"" + ""\u5199\u6d0d\uFAdF\u7E24\u3BAB\ucE11\u8F4E\uB7EB"" + ""\u3c81\u94F7\uB913\u2cd3\uE76E\uc403\u5644\u7FA9"" + ""\u2ABB\uc153\udc0B\u9d6c\u3174\uF646\uAc89\u14E1"" + ""\u163A\u6909\u70B6\ud0Ed\ucc42\u98A4\u285c\uF886""; private static long[][] C = new long[8][256]; private static long[] rc = new long[R + 1]; static { for (int x = 0; x < 256; x++) { char c = sbox.charAt(x / 2); long v1 = ((x & 1) == 0) ? c >>> 8 : c & 0xff; long v2 = v1 << 1; if (v2 >= 0x100L) { v2 ^= 0x11dL; } long v4 = v2 << 1; if (v4 >= 0x100L) { v4 ^= 0x11dL; } long v5 = v4 ^ v1; long v8 = v4 << 1; if (v8 >= 0x100L) { v8 ^= 0x11dL; } long v9 = v8 ^ v1; C[0][x] = (v1 << 56) | (v1 << 48) | (v4 << 40) | (v1 << 32) | (v8 << 24) | (v5 << 16) | (v2 << 8) | (v9); for (int t = 1; t < 8; t++) { C[t][x] = (C[t - 1][x] >>> 8) | ((C[t - 1][x] << 56)); } } rc[0] = 0L; for (int r = 1; r <= R; r++) { int i = 8 * (r - 1); rc[r] = (C[0][i] & 0xff00000000000000L) ^ (C[1][i + 1] & 0x00ff000000000000L) ^ (C[2][i + 2] & 0x0000ff0000000000L) ^ (C[3][i + 3] & 0x000000ff00000000L) ^ (C[4][i + 4] & 0x00000000ff000000L) ^ (C[5][i + 5] & 0x0000000000ff0000L) ^ (C[6][i + 6] & 0x000000000000ff00L) ^ (C[7][i + 7] & 0x00000000000000ffL); } } public static byte[] getWhirlpool(byte[] data, int off, int len) { byte source[]; if (off <= 0) { source = data; } else { source = new byte[len]; for (int i = 0; i < len; i++) source[i] = data[off + i]; } Whirlpool whirlpool = new Whirlpool(); whirlpool.NESSIEinit(); whirlpool.NESSIEadd(source, len * 8); byte digest[] = new byte[64]; whirlpool.NESSIEfinalize(digest); return digest; } protected byte[] bitLength = new byte[32]; protected byte[] buffer = new byte[64]; protected int bufferBits = 0; protected int bufferPos = 0; protected long[] hash = new long[8]; protected long[] K = new long[8]; protected long[] L = new long[8]; protected long[] block = new long[8]; protected long[] state = new long[8]; public Whirlpool() { } public void NESSIEadd(byte[] source, long sourceBits) { int sourcePos = 0; int sourceGap = (8 - ((int) sourceBits & 7)) & 7; int bufferRem = bufferBits & 7; int b; long value = sourceBits; for (int i = 31, carry = 0; i >= 0; i--) { carry += (bitLength[i] & 0xff) + ((int) value & 0xff); bitLength[i] = (byte) carry; carry >>>= 8; value >>>= 8; } while (sourceBits > 8) { b = ((source[sourcePos] << sourceGap) & 0xff) | ((source[sourcePos + 1] & 0xff) >>> (8 - sourceGap)); if (b < 0 || b >= 256) { throw new RuntimeException(""LOGIC ERROR""); } buffer[bufferPos++] |= b >>> bufferRem; bufferBits += 8 - bufferRem; if (bufferBits == 512) { processBuffer(); bufferBits = bufferPos = 0; } buffer[bufferPos] = (byte) ((b << (8 - bufferRem)) & 0xff); bufferBits += bufferRem; sourceBits -= 8; sourcePos++; } if (sourceBits > 0) { b = (source[sourcePos] << sourceGap) & 0xff; buffer[bufferPos] |= b >>> bufferRem; } else { b = 0; } if (bufferRem + sourceBits < 8) { bufferBits += sourceBits; } else { bufferPos++; bufferBits += 8 - bufferRem; sourceBits -= 8 - bufferRem; if (bufferBits == 512) { processBuffer(); bufferBits = bufferPos = 0; } buffer[bufferPos] = (byte) ((b << (8 - bufferRem)) & 0xff); bufferBits += (int) sourceBits; } } public void NESSIEadd(String source) { if (source.length() > 0) { byte[] data = new byte[source.length()]; for (int i = 0; i < source.length(); i++) { data[i] = (byte) source.charAt(i); } NESSIEadd(data, 8 * data.length); } } public void NESSIEfinalize(byte[] digest) { buffer[bufferPos] |= 0x80 >>> (bufferBits & 7); bufferPos++; if (bufferPos > 32) { while (bufferPos < 64) { buffer[bufferPos++] = 0; } processBuffer(); bufferPos = 0; } while (bufferPos < 32) { buffer[bufferPos++] = 0; } System.arraycopy(bitLength, 0, buffer, 32, 32); processBuffer(); for (int i = 0, j = 0; i < 8; i++, j += 8) { long h = hash[i]; digest[j] = (byte) (h >>> 56); digest[j + 1] = (byte) (h >>> 48); digest[j + 2] = (byte) (h >>> 40); digest[j + 3] = (byte) (h >>> 32); digest[j + 4] = (byte) (h >>> 24); digest[j + 5] = (byte) (h >>> 16); digest[j + 6] = (byte) (h >>> 8); digest[j + 7] = (byte) (h); } } public void NESSIEinit() { Arrays.fill(bitLength, (byte) 0); bufferBits = bufferPos = 0; buffer[0] = 0; Arrays.fill(hash, 0L); } protected void processBuffer() { for (int i = 0, j = 0; i < 8; i++, j += 8) { block[i] = (((long) buffer[j]) << 56) ^ (((long) buffer[j + 1] & 0xffL) << 48) ^ (((long) buffer[j + 2] & 0xffL) << 40) ^ (((long) buffer[j + 3] & 0xffL) << 32) ^ (((long) buffer[j + 4] & 0xffL) << 24) ^ (((long) buffer[j + 5] & 0xffL) << 16) ^ (((long) buffer[j + 6] & 0xffL) << 8) ^ (((long) buffer[j + 7] & 0xffL)); } for (int i = 0; i < 8; i++) { state[i] = block[i] ^ (K[i] = hash[i]); } for (int r = 1; r <= R; r++) { for (int i = 0; i < 8; i++) { L[i] = 0L; for (int t = 0, s = 56; t < 8; t++, s -= 8) { L[i] ^= C[t][(int) (K[(i - t) & 7] >>> s) & 0xff]; } } for (int i = 0; i < 8; i++) { K[i] = L[i]; } K[0] ^= rc[r]; for (int i = 0; i < 8; i++) { L[i] = K[i]; for (int t = 0, s = 56; t < 8; t++, s -= 8) { L[i] ^= C[t][(int) (state[(i - t) & 7] >>> s) & 0xff]; } } for (int i = 0; i < 8; i++) { state[i] = L[i]; } } for (int i = 0; i < 8; i++) { hash[i] ^= state[i] ^ block[i]; } } } " " /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the ""License""); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /* * This package is based on the work done by Keiron Liddle, Aftex Software * to whom the Ant project is very grateful for his * great code. */ package com.rs.cache.utils.bzip2; /** * Base class for both the compress and decompress classes. * Holds common arrays, and static data. *

* This interface is public for historical purposes. * You should have no need to use it. *

*/ public interface BZip2Constants { int baseBlockSize = 100000; int MAX_ALPHA_SIZE = 258; int MAX_CODE_LEN = 23; int RUNA = 0; int RUNB = 1; int N_GROUPS = 6; int G_SIZE = 50; int N_ITERS = 4; int MAX_SELECTORS = (2 + (900000 / G_SIZE)); int NUM_OVERSHOOT_BYTES = 20; int[] rNums = { 619, 720, 127, 481, 931, 816, 813, 233, 566, 247, 985, 724, 205, 454, 863, 491, 741, 242, 949, 214, 733, 859, 335, 708, 621, 574, 73, 654, 730, 472, 419, 436, 278, 496, 867, 210, 399, 680, 480, 51, 878, 465, 811, 169, 869, 675, 611, 697, 867, 561, 862, 687, 507, 283, 482, 129, 807, 591, 733, 623, 150, 238, 59, 379, 684, 877, 625, 169, 643, 105, 170, 607, 520, 932, 727, 476, 693, 425, 174, 647, 73, 122, 335, 530, 442, 853, 695, 249, 445, 515, 909, 545, 703, 919, 874, 474, 882, 500, 594, 612, 641, 801, 220, 162, 819, 984, 589, 513, 495, 799, 161, 604, 958, 533, 221, 400, 386, 867, 600, 782, 382, 596, 414, 171, 516, 375, 682, 485, 911, 276, 98, 553, 163, 354, 666, 933, 424, 341, 533, 870, 227, 730, 475, 186, 263, 647, 537, 686, 600, 224, 469, 68, 770, 919, 190, 373, 294, 822, 808, 206, 184, 943, 795, 384, 383, 461, 404, 758, 839, 887, 715, 67, 618, 276, 204, 918, 873, 777, 604, 560, 951, 160, 578, 722, 79, 804, 96, 409, 713, 940, 652, 934, 970, 447, 318, 353, 859, 672, 112, 785, 645, 863, 803, 350, 139, 93, 354, 99, 820, 908, 609, 772, 154, 274, 580, 184, 79, 626, 630, 742, 653, 282, 762, 623, 680, 81, 927, 626, 789, 125, 411, 521, 938, 300, 821, 78, 343, 175, 128, 250, 170, 774, 972, 275, 999, 639, 495, 78, 352, 126, 857, 956, 358, 619, 580, 124, 737, 594, 701, 612, 669, 112, 134, 694, 363, 992, 809, 743, 168, 974, 944, 375, 748, 52, 600, 747, 642, 182, 862, 81, 344, 805, 988, 739, 511, 655, 814, 334, 249, 515, 897, 955, 664, 981, 649, 113, 974, 459, 893, 228, 433, 837, 553, 268, 926, 240, 102, 654, 459, 51, 686, 754, 806, 760, 493, 403, 415, 394, 687, 700, 946, 670, 656, 610, 738, 392, 760, 799, 887, 653, 978, 321, 576, 617, 626, 502, 894, 679, 243, 440, 680, 879, 194, 572, 640, 724, 926, 56, 204, 700, 707, 151, 457, 449, 797, 195, 791, 558, 945, 679, 297, 59, 87, 824, 713, 663, 412, 693, 342, 606, 134, 108, 571, 364, 631, 212, 174, 643, 304, 329, 343, 97, 430, 751, 497, 314, 983, 374, 822, 928, 140, 206, 73, 263, 980, 736, 876, 478, 430, 305, 170, 514, 364, 692, 829, 82, 855, 953, 676, 246, 369, 970, 294, 750, 807, 827, 150, 790, 288, 923, 804, 378, 215, 828, 592, 281, 565, 555, 710, 82, 896, 831, 547, 261, 524, 462, 293, 465, 502, 56, 661, 821, 976, 991, 658, 869, 905, 758, 745, 193, 768, 550, 608, 933, 378, 286, 215, 979, 792, 961, 61, 688, 793, 644, 986, 403, 106, 366, 905, 644, 372, 567, 466, 434, 645, 210, 389, 550, 919, 135, 780, 773, 635, 389, 707, 100, 626, 958, 165, 504, 920, 176, 193, 713, 857, 265, 203, 50, 668, 108, 645, 990, 626, 197, 510, 357, 358, 850, 858, 364, 936, 638 }; } " " /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the ""License""); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /* * This package is based on the work done by Keiron Liddle, Aftex Software * to whom the Ant project is very grateful for his * great code. */ package com.rs.cache.utils.bzip2; import java.io.IOException; import java.io.InputStream; /** * An input stream that decompresses from the BZip2 format (without the file * header chars) to be read as any other stream. * *

The decompression requires large amounts of memory. Thus you * should call the {@link #close() close()} method as soon as * possible, to force CBZip2InputStream to release the * allocated memory. See {@link CBZip2OutputStream * CBZip2OutputStream} for information about memory usage.

* *

CBZip2InputStream reads bytes from the compressed * source stream via the single byte {@link java.io.InputStream#read() * read()} method exclusively. Thus you should consider to use a * buffered source stream.

* *

Instances of this class are not threadsafe.

*/ public class CBZip2InputStream extends InputStream implements BZip2Constants { private static final class Data extends Object { // (with blockSize 900k) final boolean[] inUse = new boolean[256]; // 256 byte final byte[] seqToUnseq = new byte[256]; // 256 byte final byte[] selector = new byte[MAX_SELECTORS]; // 18002 byte final byte[] selectorMtf = new byte[MAX_SELECTORS]; // 18002 byte /** * Freq table collected to save a pass over the data during * decompression. */ final int[] unzftab = new int[256]; // 1024 byte final int[][] limit = new int[N_GROUPS][MAX_ALPHA_SIZE]; // 6192 byte final int[][] base = new int[N_GROUPS][MAX_ALPHA_SIZE]; // 6192 byte final int[][] perm = new int[N_GROUPS][MAX_ALPHA_SIZE]; // 6192 byte final int[] minLens = new int[N_GROUPS]; // 24 byte final int[] cftab = new int[257]; // 1028 byte final char[] getAndMoveToFrontDecode_yy = new char[256]; // 512 byte final char[][] temp_charArray2d = new char[N_GROUPS][MAX_ALPHA_SIZE]; // 3096 byte final byte[] recvDecodingTables_pos = new byte[N_GROUPS]; // 6 byte //--------------- // 60798 byte int[] tt; // 3600000 byte byte[] ll8; // 900000 byte //--------------- // 4560782 byte //=============== Data(int blockSize100k) { super(); this.ll8 = new byte[blockSize100k * BZip2Constants.baseBlockSize]; } /** * Initializes the {@link #tt} array. * * This method is called when the required length of the array * is known. I don't initialize it at construction time to * avoid unneccessary memory allocation when compressing small * files. */ final int[] initTT(int length) { int[] ttShadow = this.tt; // tt.length should always be >= length, but theoretically // it can happen, if the compressor mixed small and large // blocks. Normally only the last block will be smaller // than others. if ((ttShadow == null) || (ttShadow.length < length)) { this.tt = ttShadow = new int[length]; } return ttShadow; } } private static void reportCRCError() throws IOException { // The clean way would be to throw an exception. throw new IOException(""crc error""); // Just print a message, like the previous versions of this class did //System.err.println(""BZip2 CRC error""); } /** * Index of the last char in the block, so the block size == last + 1. */ private int last; /** * Index in zptr[] of original string after sorting. */ private int origPtr; /** * always: in the range 0 .. 9. * The current block size is 100000 * this number. */ private int blockSize100k; private boolean blockRandomised; private int bsBuff; private int bsLive; private final CRC crc = new CRC(); private int nInUse; private InputStream in; private int currentChar = -1; private static final int EOF = 0; private static final int START_BLOCK_STATE = 1; private static final int RAND_PART_A_STATE = 2; private static final int RAND_PART_B_STATE = 3; private static final int RAND_PART_C_STATE = 4; private static final int NO_RAND_PART_A_STATE = 5; private static final int NO_RAND_PART_B_STATE = 6; private static final int NO_RAND_PART_C_STATE = 7; /** * Called by createHuffmanDecodingTables() exclusively. */ private static void hbCreateDecodeTables(final int[] limit, final int[] base, final int[] perm, final char[] length, final int minLen, final int maxLen, final int alphaSize) { for (int i = minLen, pp = 0; i <= maxLen; i++) { for (int j = 0; j < alphaSize; j++) { if (length[j] == i) { perm[pp++] = j; } } } for (int i = MAX_CODE_LEN; --i > 0;) { base[i] = 0; limit[i] = 0; } for (int i = 0; i < alphaSize; i++) { base[length[i] + 1]++; } for (int i = 1, b = base[0]; i < MAX_CODE_LEN; i++) { b += base[i]; base[i] = b; } for (int i = minLen, vec = 0, b = base[i]; i <= maxLen; i++) { final int nb = base[i + 1]; vec += nb - b; b = nb; limit[i] = vec - 1; vec <<= 1; } for (int i = minLen + 1; i <= maxLen; i++) { base[i] = ((limit[i - 1] + 1) << 1) - base[i]; } } private int currentState = START_BLOCK_STATE; private int storedBlockCRC, storedCombinedCRC; // Variables used by setup* methods exclusively private int computedBlockCRC, computedCombinedCRC; private int su_count; private int su_ch2; private int su_chPrev; private int su_i2; private int su_j2; private int su_rNToGo; private int su_rTPos; private int su_tPos; private char su_z; /** * All memory intensive stuff. * This field is initialized by initBlock(). */ private CBZip2InputStream.Data data; /** * Constructs a new CBZip2InputStream which decompresses bytes read from * the specified stream. * *

Although BZip2 headers are marked with the magic * ""Bz"" this constructor expects the next byte in the * stream to be the first one after the magic. Thus callers have * to skip the first two bytes. Otherwise this constructor will * throw an exception.

* * @throws IOException * if the stream content is malformed or an I/O error occurs. * @throws NullPointerException * if in == null */ public CBZip2InputStream(final InputStream in) throws IOException { super(); this.in = in; init(); } private boolean bsGetBit() throws IOException { int bsLiveShadow = this.bsLive; int bsBuffShadow = this.bsBuff; if (bsLiveShadow < 1) { int thech = this.in.read(); if (thech < 0) { throw new IOException(""unexpected end of stream""); } bsBuffShadow = (bsBuffShadow << 8) | thech; bsLiveShadow += 8; this.bsBuff = bsBuffShadow; } this.bsLive = bsLiveShadow - 1; return ((bsBuffShadow >> (bsLiveShadow - 1)) & 1) != 0; } private int bsGetInt() throws IOException { return (((((bsR(8) << 8) | bsR(8)) << 8) | bsR(8)) << 8) | bsR(8); } private char bsGetUByte() throws IOException { return (char) bsR(8); } private int bsR(final int n) throws IOException { int bsLiveShadow = this.bsLive; int bsBuffShadow = this.bsBuff; if (bsLiveShadow < n) { final InputStream inShadow = this.in; do { int thech = inShadow.read(); if (thech < 0) { throw new IOException(""unexpected end of stream""); } bsBuffShadow = (bsBuffShadow << 8) | thech; bsLiveShadow += 8; } while (bsLiveShadow < n); this.bsBuff = bsBuffShadow; } this.bsLive = bsLiveShadow - n; return (bsBuffShadow >> (bsLiveShadow - n)) & ((1 << n) - 1); } public void close() throws IOException { InputStream inShadow = this.in; if (inShadow != null) { try { if (inShadow != System.in) { inShadow.close(); } } finally { this.data = null; this.in = null; } } } private void complete() throws IOException { this.storedCombinedCRC = bsGetInt(); this.currentState = EOF; this.data = null; if (this.storedCombinedCRC != this.computedCombinedCRC) { reportCRCError(); } } /** * Called by recvDecodingTables() exclusively. */ private void createHuffmanDecodingTables(final int alphaSize, final int nGroups) { final Data dataShadow = this.data; final char[][] len = dataShadow.temp_charArray2d; final int[] minLens = dataShadow.minLens; final int[][] limit = dataShadow.limit; final int[][] base = dataShadow.base; final int[][] perm = dataShadow.perm; for (int t = 0; t < nGroups; t++) { int minLen = 32; int maxLen = 0; final char[] len_t = len[t]; for (int i = alphaSize; --i >= 0;) { final char lent = len_t[i]; if (lent > maxLen) { maxLen = lent; } if (lent < minLen) { minLen = lent; } } hbCreateDecodeTables(limit[t], base[t], perm[t], len[t], minLen, maxLen, alphaSize); minLens[t] = minLen; } } private void endBlock() throws IOException { this.computedBlockCRC = this.crc.getFinalCRC(); // A bad CRC is considered a fatal error. if (this.storedBlockCRC != this.computedBlockCRC) { // make next blocks readable without error // (repair feature, not yet documented, not tested) this.computedCombinedCRC = (this.storedCombinedCRC << 1) | (this.storedCombinedCRC >>> 31); this.computedCombinedCRC ^= this.storedBlockCRC; reportCRCError(); } this.computedCombinedCRC = (this.computedCombinedCRC << 1) | (this.computedCombinedCRC >>> 31); this.computedCombinedCRC ^= this.computedBlockCRC; } private void getAndMoveToFrontDecode() throws IOException { this.origPtr = bsR(24); recvDecodingTables(); final InputStream inShadow = this.in; final Data dataShadow = this.data; final byte[] ll8 = dataShadow.ll8; final int[] unzftab = dataShadow.unzftab; final byte[] selector = dataShadow.selector; final byte[] seqToUnseq = dataShadow.seqToUnseq; final char[] yy = dataShadow.getAndMoveToFrontDecode_yy; final int[] minLens = dataShadow.minLens; final int[][] limit = dataShadow.limit; final int[][] base = dataShadow.base; final int[][] perm = dataShadow.perm; final int limitLast = this.blockSize100k * 100000; /* Setting up the unzftab entries here is not strictly necessary, but it does save having to do it later in a separate pass, and so saves a block's worth of cache misses. */ for (int i = 256; --i >= 0;) { yy[i] = (char) i; unzftab[i] = 0; } int groupNo = 0; int groupPos = G_SIZE - 1; final int eob = this.nInUse + 1; int nextSym = getAndMoveToFrontDecode0(0); int bsBuffShadow = this.bsBuff; int bsLiveShadow = this.bsLive; int lastShadow = -1; int zt = selector[groupNo] & 0xff; int[] base_zt = base[zt]; int[] limit_zt = limit[zt]; int[] perm_zt = perm[zt]; int minLens_zt = minLens[zt]; while (nextSym != eob) { if ((nextSym == RUNA) || (nextSym == RUNB)) { int s = -1; for (int n = 1; true; n <<= 1) { if (nextSym == RUNA) { s += n; } else if (nextSym == RUNB) { s += n << 1; } else { break; } if (groupPos == 0) { groupPos = G_SIZE - 1; zt = selector[++groupNo] & 0xff; base_zt = base[zt]; limit_zt = limit[zt]; perm_zt = perm[zt]; minLens_zt = minLens[zt]; } else { groupPos--; } int zn = minLens_zt; // Inlined: // int zvec = bsR(zn); while (bsLiveShadow < zn) { final int thech = inShadow.read(); if (thech >= 0) { bsBuffShadow = (bsBuffShadow << 8) | thech; bsLiveShadow += 8; continue; } else { throw new IOException(""unexpected end of stream""); } } int zvec = (bsBuffShadow >> (bsLiveShadow - zn)) & ((1 << zn) - 1); bsLiveShadow -= zn; while (zvec > limit_zt[zn]) { zn++; while (bsLiveShadow < 1) { final int thech = inShadow.read(); if (thech >= 0) { bsBuffShadow = (bsBuffShadow << 8) | thech; bsLiveShadow += 8; continue; } else { throw new IOException(""unexpected end of stream""); } } bsLiveShadow--; zvec = (zvec << 1) | ((bsBuffShadow >> bsLiveShadow) & 1); } nextSym = perm_zt[zvec - base_zt[zn]]; } final byte ch = seqToUnseq[yy[0]]; unzftab[ch & 0xff] += s + 1; while (s-- >= 0) { ll8[++lastShadow] = ch; } if (lastShadow >= limitLast) { throw new IOException(""block overrun""); } } else { if (++lastShadow >= limitLast) { throw new IOException(""block overrun""); } final char tmp = yy[nextSym - 1]; unzftab[seqToUnseq[tmp] & 0xff]++; ll8[lastShadow] = seqToUnseq[tmp]; /* This loop is hammered during decompression, hence avoid native method call overhead of System.arraycopy for very small ranges to copy. */ if (nextSym <= 16) { for (int j = nextSym - 1; j > 0;) { yy[j] = yy[--j]; } } else { System.arraycopy(yy, 0, yy, 1, nextSym - 1); } yy[0] = tmp; if (groupPos == 0) { groupPos = G_SIZE - 1; zt = selector[++groupNo] & 0xff; base_zt = base[zt]; limit_zt = limit[zt]; perm_zt = perm[zt]; minLens_zt = minLens[zt]; } else { groupPos--; } int zn = minLens_zt; // Inlined: // int zvec = bsR(zn); while (bsLiveShadow < zn) { final int thech = inShadow.read(); if (thech >= 0) { bsBuffShadow = (bsBuffShadow << 8) | thech; bsLiveShadow += 8; continue; } else { throw new IOException(""unexpected end of stream""); } } int zvec = (bsBuffShadow >> (bsLiveShadow - zn)) & ((1 << zn) - 1); bsLiveShadow -= zn; while (zvec > limit_zt[zn]) { zn++; while (bsLiveShadow < 1) { final int thech = inShadow.read(); if (thech >= 0) { bsBuffShadow = (bsBuffShadow << 8) | thech; bsLiveShadow += 8; continue; } else { throw new IOException(""unexpected end of stream""); } } bsLiveShadow--; zvec = (zvec << 1) | ((bsBuffShadow >> bsLiveShadow) & 1); } nextSym = perm_zt[zvec - base_zt[zn]]; } } this.last = lastShadow; this.bsLive = bsLiveShadow; this.bsBuff = bsBuffShadow; } private int getAndMoveToFrontDecode0(final int groupNo) throws IOException { final InputStream inShadow = this.in; final Data dataShadow = this.data; final int zt = dataShadow.selector[groupNo] & 0xff; final int[] limit_zt = dataShadow.limit[zt]; int zn = dataShadow.minLens[zt]; int zvec = bsR(zn); int bsLiveShadow = this.bsLive; int bsBuffShadow = this.bsBuff; while (zvec > limit_zt[zn]) { zn++; while (bsLiveShadow < 1) { final int thech = inShadow.read(); if (thech >= 0) { bsBuffShadow = (bsBuffShadow << 8) | thech; bsLiveShadow += 8; continue; } else { throw new IOException(""unexpected end of stream""); } } bsLiveShadow--; zvec = (zvec << 1) | ((bsBuffShadow >> bsLiveShadow) & 1); } this.bsLive = bsLiveShadow; this.bsBuff = bsBuffShadow; return dataShadow.perm[zt][zvec - dataShadow.base[zt][zn]]; } private void init() throws IOException { if (null == in) { throw new IOException(""No InputStream""); } if (in.available() == 0) { throw new IOException(""Empty InputStream""); } int magic2 = this.in.read(); if (magic2 != 'h') { throw new IOException(""Stream is not BZip2 formatted: expected 'h'"" + "" as first byte but got '"" + (char) magic2 + ""'""); } int blockSize = this.in.read(); if ((blockSize < '1') || (blockSize > '9')) { throw new IOException(""Stream is not BZip2 formatted: illegal "" + ""blocksize "" + (char) blockSize); } this.blockSize100k = blockSize - '0'; initBlock(); setupBlock(); } private void initBlock() throws IOException { char magic0 = bsGetUByte(); char magic1 = bsGetUByte(); char magic2 = bsGetUByte(); char magic3 = bsGetUByte(); char magic4 = bsGetUByte(); char magic5 = bsGetUByte(); if (magic0 == 0x17 && magic1 == 0x72 && magic2 == 0x45 && magic3 == 0x38 && magic4 == 0x50 && magic5 == 0x90) { complete(); // end of file } else if (magic0 != 0x31 || // '1' magic1 != 0x41 || // ')' magic2 != 0x59 || // 'Y' magic3 != 0x26 || // '&' magic4 != 0x53 || // 'S' magic5 != 0x59 // 'Y' ) { this.currentState = EOF; throw new IOException(""bad block header""); } else { this.storedBlockCRC = bsGetInt(); this.blockRandomised = bsR(1) == 1; /** * Allocate data here instead in constructor, so we do not * allocate it if the input file is empty. */ if (this.data == null) { this.data = new Data(this.blockSize100k); } // currBlockNo++; getAndMoveToFrontDecode(); this.crc.initialiseCRC(); this.currentState = START_BLOCK_STATE; } } private void makeMaps() { final boolean[] inUse = this.data.inUse; final byte[] seqToUnseq = this.data.seqToUnseq; int nInUseShadow = 0; for (int i = 0; i < 256; i++) { if (inUse[i]) seqToUnseq[nInUseShadow++] = (byte) i; } this.nInUse = nInUseShadow; } public int read() throws IOException { if (this.in != null) { return read0(); } else { throw new IOException(""stream closed""); } } public int read(final byte[] dest, final int offs, final int len) throws IOException { if (offs < 0) { throw new IndexOutOfBoundsException(""offs("" + offs + "") < 0.""); } if (len < 0) { throw new IndexOutOfBoundsException(""len("" + len + "") < 0.""); } if (offs + len > dest.length) { throw new IndexOutOfBoundsException(""offs("" + offs + "") + len("" + len + "") > dest.length("" + dest.length + "").""); } if (this.in == null) { throw new IOException(""stream closed""); } final int hi = offs + len; int destOffs = offs; for (int b; (destOffs < hi) && ((b = read0()) >= 0);) { dest[destOffs++] = (byte) b; } return (destOffs == offs) ? -1 : (destOffs - offs); } private int read0() throws IOException { final int retChar = this.currentChar; switch (this.currentState) { case EOF: return -1; case START_BLOCK_STATE: throw new IllegalStateException(); case RAND_PART_A_STATE: throw new IllegalStateException(); case RAND_PART_B_STATE: setupRandPartB(); break; case RAND_PART_C_STATE: setupRandPartC(); break; case NO_RAND_PART_A_STATE: throw new IllegalStateException(); case NO_RAND_PART_B_STATE: setupNoRandPartB(); break; case NO_RAND_PART_C_STATE: setupNoRandPartC(); break; default: throw new IllegalStateException(); } return retChar; } private void recvDecodingTables() throws IOException { final Data dataShadow = this.data; final boolean[] inUse = dataShadow.inUse; final byte[] pos = dataShadow.recvDecodingTables_pos; final byte[] selector = dataShadow.selector; final byte[] selectorMtf = dataShadow.selectorMtf; int inUse16 = 0; /* Receive the mapping table */ for (int i = 0; i < 16; i++) { if (bsGetBit()) { inUse16 |= 1 << i; } } for (int i = 256; --i >= 0;) { inUse[i] = false; } for (int i = 0; i < 16; i++) { if ((inUse16 & (1 << i)) != 0) { final int i16 = i << 4; for (int j = 0; j < 16; j++) { if (bsGetBit()) { inUse[i16 + j] = true; } } } } makeMaps(); final int alphaSize = this.nInUse + 2; /* Now the selectors */ final int nGroups = bsR(3); final int nSelectors = bsR(15); for (int i = 0; i < nSelectors; i++) { int j = 0; while (bsGetBit()) { j++; } selectorMtf[i] = (byte) j; } /* Undo the MTF values for the selectors. */ for (int v = nGroups; --v >= 0;) { pos[v] = (byte) v; } for (int i = 0; i < nSelectors; i++) { int v = selectorMtf[i] & 0xff; final byte tmp = pos[v]; while (v > 0) { // nearly all times v is zero, 4 in most other cases pos[v] = pos[v - 1]; v--; } pos[0] = tmp; selector[i] = tmp; } final char[][] len = dataShadow.temp_charArray2d; /* Now the coding tables */ for (int t = 0; t < nGroups; t++) { int curr = bsR(5); final char[] len_t = len[t]; for (int i = 0; i < alphaSize; i++) { while (bsGetBit()) { curr += bsGetBit() ? -1 : 1; } len_t[i] = (char) curr; } } // finally create the Huffman tables createHuffmanDecodingTables(alphaSize, nGroups); } private void setupBlock() throws IOException { if (this.data == null) { return; } final int[] cftab = this.data.cftab; final int[] tt = this.data.initTT(this.last + 1); final byte[] ll8 = this.data.ll8; cftab[0] = 0; System.arraycopy(this.data.unzftab, 0, cftab, 1, 256); for (int i = 1, c = cftab[0]; i <= 256; i++) { c += cftab[i]; cftab[i] = c; } for (int i = 0, lastShadow = this.last; i <= lastShadow; i++) { tt[cftab[ll8[i] & 0xff]++] = i; } if ((this.origPtr < 0) || (this.origPtr >= tt.length)) { throw new IOException(""stream corrupted""); } this.su_tPos = tt[this.origPtr]; this.su_count = 0; this.su_i2 = 0; this.su_ch2 = 256; /* not a char and not EOF */ if (this.blockRandomised) { this.su_rNToGo = 0; this.su_rTPos = 0; setupRandPartA(); } else { setupNoRandPartA(); } } private void setupNoRandPartA() throws IOException { if (this.su_i2 <= this.last) { this.su_chPrev = this.su_ch2; int su_ch2Shadow = this.data.ll8[this.su_tPos] & 0xff; this.su_ch2 = su_ch2Shadow; this.su_tPos = this.data.tt[this.su_tPos]; this.su_i2++; this.currentChar = su_ch2Shadow; this.currentState = NO_RAND_PART_B_STATE; this.crc.updateCRC(su_ch2Shadow); } else { this.currentState = NO_RAND_PART_A_STATE; endBlock(); initBlock(); setupBlock(); } } private void setupNoRandPartB() throws IOException { if (this.su_ch2 != this.su_chPrev) { this.su_count = 1; setupNoRandPartA(); } else if (++this.su_count >= 4) { this.su_z = (char) (this.data.ll8[this.su_tPos] & 0xff); this.su_tPos = this.data.tt[this.su_tPos]; this.su_j2 = 0; setupNoRandPartC(); } else { setupNoRandPartA(); } } private void setupNoRandPartC() throws IOException { if (this.su_j2 < this.su_z) { int su_ch2Shadow = this.su_ch2; this.currentChar = su_ch2Shadow; this.crc.updateCRC(su_ch2Shadow); this.su_j2++; this.currentState = NO_RAND_PART_C_STATE; } else { this.su_i2++; this.su_count = 0; setupNoRandPartA(); } } private void setupRandPartA() throws IOException { if (this.su_i2 <= this.last) { this.su_chPrev = this.su_ch2; int su_ch2Shadow = this.data.ll8[this.su_tPos] & 0xff; this.su_tPos = this.data.tt[this.su_tPos]; if (this.su_rNToGo == 0) { this.su_rNToGo = BZip2Constants.rNums[this.su_rTPos] - 1; if (++this.su_rTPos == 512) { this.su_rTPos = 0; } } else { this.su_rNToGo--; } this.su_ch2 = su_ch2Shadow ^= (this.su_rNToGo == 1) ? 1 : 0; this.su_i2++; this.currentChar = su_ch2Shadow; this.currentState = RAND_PART_B_STATE; this.crc.updateCRC(su_ch2Shadow); } else { endBlock(); initBlock(); setupBlock(); } } private void setupRandPartB() throws IOException { if (this.su_ch2 != this.su_chPrev) { this.currentState = RAND_PART_A_STATE; this.su_count = 1; setupRandPartA(); } else if (++this.su_count >= 4) { this.su_z = (char) (this.data.ll8[this.su_tPos] & 0xff); this.su_tPos = this.data.tt[this.su_tPos]; if (this.su_rNToGo == 0) { this.su_rNToGo = BZip2Constants.rNums[this.su_rTPos] - 1; if (++this.su_rTPos == 512) { this.su_rTPos = 0; } } else { this.su_rNToGo--; } this.su_j2 = 0; this.currentState = RAND_PART_C_STATE; if (this.su_rNToGo == 1) { this.su_z ^= 1; } setupRandPartC(); } else { this.currentState = RAND_PART_A_STATE; setupRandPartA(); } } private void setupRandPartC() throws IOException { if (this.su_j2 < this.su_z) { this.currentChar = this.su_ch2; this.crc.updateCRC(this.su_ch2); this.su_j2++; } else { this.currentState = RAND_PART_A_STATE; this.su_i2++; this.su_count = 0; setupRandPartA(); } } } " " /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the ""License""); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /* * This package is based on the work done by Keiron Liddle, Aftex Software * to whom the Ant project is very grateful for his * great code. */ package com.rs.cache.utils.bzip2; import java.io.IOException; import java.io.OutputStream; import java.lang.SuppressWarnings; /** * An output stream that compresses into the BZip2 format (without the file * header chars) into another stream. * *

* The compression requires large amounts of memory. Thus you should call the * {@link #close() close()} method as soon as possible, to force * CBZip2OutputStream to release the allocated memory. *

* *

You can shrink the amount of allocated memory and maybe raise * the compression speed by choosing a lower blocksize, which in turn * may cause a lower compression ratio. You can avoid unnecessary * memory allocation by avoiding using a blocksize which is bigger * than the size of the input.

* *

You can compute the memory usage for compressing by the * following formula:

* *
 * <code>400k + (9 * blocksize)</code>.
 * 
* *

To get the memory required for decompression by {@link * CBZip2InputStream CBZip2InputStream} use

* *
 * <code>65k + (5 * blocksize)</code>.
 * 
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Memory usage by blocksize
Blocksize Compression
* memory usage
Decompression
* memory usage
100k1300k565k
200k2200k1065k
300k3100k1565k
400k4000k2065k
500k4900k2565k
600k5800k3065k
700k6700k3565k
800k7600k4065k
900k8500k4565k
* *

* For decompression CBZip2InputStream allocates less memory if the * bzipped input is smaller than one block. *

* *

* Instances of this class are not threadsafe. *

* *

* TODO: Update to BZip2 1.0.1 *

* *

* This class has been modified so it does not use randomized blocks as * these are not supported by the client's bzip2 implementation. *

* */ public class CBZip2OutputStream extends OutputStream implements BZip2Constants { private static final class Data extends Object { // with blockSize 900k final boolean[] inUse = new boolean[256]; // 256 byte final byte[] unseqToSeq = new byte[256]; // 256 byte final int[] mtfFreq = new int[MAX_ALPHA_SIZE]; // 1032 byte final byte[] selector = new byte[MAX_SELECTORS]; // 18002 byte final byte[] selectorMtf = new byte[MAX_SELECTORS]; // 18002 byte final byte[] generateMTFValues_yy = new byte[256]; // 256 byte final byte[][] sendMTFValues_len = new byte[N_GROUPS][MAX_ALPHA_SIZE]; // 1548 // byte final int[][] sendMTFValues_rfreq = new int[N_GROUPS][MAX_ALPHA_SIZE]; // 6192 // byte final int[] sendMTFValues_fave = new int[N_GROUPS]; // 24 byte final short[] sendMTFValues_cost = new short[N_GROUPS]; // 12 byte final int[][] sendMTFValues_code = new int[N_GROUPS][MAX_ALPHA_SIZE]; // 6192 // byte final byte[] sendMTFValues2_pos = new byte[N_GROUPS]; // 6 byte final boolean[] sentMTFValues4_inUse16 = new boolean[16]; // 16 byte final int[] stack_ll = new int[QSORT_STACK_SIZE]; // 4000 byte final int[] stack_hh = new int[QSORT_STACK_SIZE]; // 4000 byte final int[] stack_dd = new int[QSORT_STACK_SIZE]; // 4000 byte final int[] mainSort_runningOrder = new int[256]; // 1024 byte final int[] mainSort_copy = new int[256]; // 1024 byte final boolean[] mainSort_bigDone = new boolean[256]; // 256 byte final int[] heap = new int[MAX_ALPHA_SIZE + 2]; // 1040 byte final int[] weight = new int[MAX_ALPHA_SIZE * 2]; // 2064 byte final int[] parent = new int[MAX_ALPHA_SIZE * 2]; // 2064 byte final int[] ftab = new int[65537]; // 262148 byte // ------------ // 333408 byte final byte[] block; // 900021 byte final int[] fmap; // 3600000 byte final char[] sfmap; // 3600000 byte // ------------ // 8433529 byte // ============ /** * Array instance identical to sfmap, both are used only * temporarily and indepently, so we do not need to allocate * additional memory. */ final char[] quadrant; Data(int blockSize100k) { super(); final int n = blockSize100k * BZip2Constants.baseBlockSize; this.block = new byte[(n + 1 + NUM_OVERSHOOT_BYTES)]; this.fmap = new int[n]; this.sfmap = new char[2 * n]; this.quadrant = this.sfmap; } } /** * The minimum supported blocksize == 1. */ public static final int MIN_BLOCKSIZE = 1; /** * The maximum supported blocksize == 9. */ public static final int MAX_BLOCKSIZE = 9; /** * This constant is accessible by subclasses for historical * purposes. If you don't know what it means then you don't need * it. */ protected static final int SETMASK = (1 << 21); /** * This constant is accessible by subclasses for historical * purposes. If you don't know what it means then you don't need * it. */ protected static final int CLEARMASK = (~SETMASK); /** * This constant is accessible by subclasses for historical * purposes. If you don't know what it means then you don't need * it. */ protected static final int GREATER_ICOST = 15; /** * This constant is accessible by subclasses for historical * purposes. If you don't know what it means then you don't need * it. */ protected static final int LESSER_ICOST = 0; /** * This constant is accessible by subclasses for historical * purposes. If you don't know what it means then you don't need * it. */ protected static final int SMALL_THRESH = 20; /** * This constant is accessible by subclasses for historical * purposes. If you don't know what it means then you don't need * it. */ protected static final int DEPTH_THRESH = 10; /** * This constant is accessible by subclasses for historical * purposes. If you don't know what it means then you don't need * it. */ protected static final int WORK_FACTOR = 30; /** * This constant is accessible by subclasses for historical * purposes. If you don't know what it means then you don't need * it. *

If you are ever unlucky/improbable enough to get a stack * overflow whilst sorting, increase the following constant and * try again. In practice I have never seen the stack go above 27 * elems, so the following limit seems very generous.

*/ protected static final int QSORT_STACK_SIZE = 1000; /** * Knuth's increments seem to work better than Incerpi-Sedgewick here. * Possibly because the number of elems to sort is usually small, typically * <= 20. */ private static final int[] INCS = { 1, 4, 13, 40, 121, 364, 1093, 3280, 9841, 29524, 88573, 265720, 797161, 2391484 }; /** * Chooses a blocksize based on the given length of the data to compress. * * @return The blocksize, between {@link #MIN_BLOCKSIZE} and * {@link #MAX_BLOCKSIZE} both inclusive. For a negative * inputLength this method returns MAX_BLOCKSIZE * always. * * @param inputLength * The length of the data which will be compressed by * CBZip2OutputStream. */ public static int chooseBlockSize(long inputLength) { return (inputLength > 0) ? (int) Math .min((inputLength / 132000) + 1, 9) : MAX_BLOCKSIZE; } private static void hbAssignCodes(final int[] code, final byte[] length, final int minLen, final int maxLen, final int alphaSize) { int vec = 0; for (int n = minLen; n <= maxLen; n++) { for (int i = 0; i < alphaSize; i++) { if ((length[i] & 0xff) == n) { code[i] = vec; vec++; } } vec <<= 1; } } private static void hbMakeCodeLengths(final byte[] len, final int[] freq, final Data dat, final int alphaSize, final int maxLen) { /* * Nodes and heap entries run from 1. Entry 0 for both the heap and * nodes is a sentinel. */ final int[] heap = dat.heap; final int[] weight = dat.weight; final int[] parent = dat.parent; for (int i = alphaSize; --i >= 0;) { weight[i + 1] = (freq[i] == 0 ? 1 : freq[i]) << 8; } for (boolean tooLong = true; tooLong;) { tooLong = false; int nNodes = alphaSize; int nHeap = 0; heap[0] = 0; weight[0] = 0; parent[0] = -2; for (int i = 1; i <= alphaSize; i++) { parent[i] = -1; nHeap++; heap[nHeap] = i; int zz = nHeap; int tmp = heap[zz]; while (weight[tmp] < weight[heap[zz >> 1]]) { heap[zz] = heap[zz >> 1]; zz >>= 1; } heap[zz] = tmp; } while (nHeap > 1) { int n1 = heap[1]; heap[1] = heap[nHeap]; nHeap--; int yy = 0; int zz = 1; int tmp = heap[1]; while (true) { yy = zz << 1; if (yy > nHeap) { break; } if ((yy < nHeap) && (weight[heap[yy + 1]] < weight[heap[yy]])) { yy++; } if (weight[tmp] < weight[heap[yy]]) { break; } heap[zz] = heap[yy]; zz = yy; } heap[zz] = tmp; int n2 = heap[1]; heap[1] = heap[nHeap]; nHeap--; yy = 0; zz = 1; tmp = heap[1]; while (true) { yy = zz << 1; if (yy > nHeap) { break; } if ((yy < nHeap) && (weight[heap[yy + 1]] < weight[heap[yy]])) { yy++; } if (weight[tmp] < weight[heap[yy]]) { break; } heap[zz] = heap[yy]; zz = yy; } heap[zz] = tmp; nNodes++; parent[n1] = parent[n2] = nNodes; final int weight_n1 = weight[n1]; final int weight_n2 = weight[n2]; weight[nNodes] = ((weight_n1 & 0xffffff00) + (weight_n2 & 0xffffff00)) | (1 + (((weight_n1 & 0x000000ff) > (weight_n2 & 0x000000ff)) ? (weight_n1 & 0x000000ff) : (weight_n2 & 0x000000ff))); parent[nNodes] = -1; nHeap++; heap[nHeap] = nNodes; tmp = 0; zz = nHeap; tmp = heap[zz]; final int weight_tmp = weight[tmp]; while (weight_tmp < weight[heap[zz >> 1]]) { heap[zz] = heap[zz >> 1]; zz >>= 1; } heap[zz] = tmp; } for (int i = 1; i <= alphaSize; i++) { int j = 0; int k = i; for (int parent_k; (parent_k = parent[k]) >= 0;) { k = parent_k; j++; } len[i - 1] = (byte) j; if (j > maxLen) { tooLong = true; } } if (tooLong) { for (int i = 1; i < alphaSize; i++) { int j = weight[i] >> 8; j = 1 + (j >> 1); weight[i] = j << 8; } } } } /** * This method is accessible by subclasses for historical * purposes. If you don't know what it does then you don't need * it. */ protected static void hbMakeCodeLengths(char[] len, int[] freq, int alphaSize, int maxLen) { /* * Nodes and heap entries run from 1. Entry 0 for both the heap and * nodes is a sentinel. */ final int[] heap = new int[MAX_ALPHA_SIZE * 2]; final int[] weight = new int[MAX_ALPHA_SIZE * 2]; final int[] parent = new int[MAX_ALPHA_SIZE * 2]; for (int i = alphaSize; --i >= 0;) { weight[i + 1] = (freq[i] == 0 ? 1 : freq[i]) << 8; } for (boolean tooLong = true; tooLong;) { tooLong = false; int nNodes = alphaSize; int nHeap = 0; heap[0] = 0; weight[0] = 0; parent[0] = -2; for (int i = 1; i <= alphaSize; i++) { parent[i] = -1; nHeap++; heap[nHeap] = i; int zz = nHeap; int tmp = heap[zz]; while (weight[tmp] < weight[heap[zz >> 1]]) { heap[zz] = heap[zz >> 1]; zz >>= 1; } heap[zz] = tmp; } // assert (nHeap < (MAX_ALPHA_SIZE + 2)) : nHeap; while (nHeap > 1) { int n1 = heap[1]; heap[1] = heap[nHeap]; nHeap--; int yy = 0; int zz = 1; int tmp = heap[1]; while (true) { yy = zz << 1; if (yy > nHeap) { break; } if ((yy < nHeap) && (weight[heap[yy + 1]] < weight[heap[yy]])) { yy++; } if (weight[tmp] < weight[heap[yy]]) { break; } heap[zz] = heap[yy]; zz = yy; } heap[zz] = tmp; int n2 = heap[1]; heap[1] = heap[nHeap]; nHeap--; yy = 0; zz = 1; tmp = heap[1]; while (true) { yy = zz << 1; if (yy > nHeap) { break; } if ((yy < nHeap) && (weight[heap[yy + 1]] < weight[heap[yy]])) { yy++; } if (weight[tmp] < weight[heap[yy]]) { break; } heap[zz] = heap[yy]; zz = yy; } heap[zz] = tmp; nNodes++; parent[n1] = parent[n2] = nNodes; final int weight_n1 = weight[n1]; final int weight_n2 = weight[n2]; weight[nNodes] = (((weight_n1 & 0xffffff00) + (weight_n2 & 0xffffff00)) | (1 + (((weight_n1 & 0x000000ff) > (weight_n2 & 0x000000ff)) ? (weight_n1 & 0x000000ff) : (weight_n2 & 0x000000ff)) )); parent[nNodes] = -1; nHeap++; heap[nHeap] = nNodes; tmp = 0; zz = nHeap; tmp = heap[zz]; final int weight_tmp = weight[tmp]; while (weight_tmp < weight[heap[zz >> 1]]) { heap[zz] = heap[zz >> 1]; zz >>= 1; } heap[zz] = tmp; } // assert (nNodes < (MAX_ALPHA_SIZE * 2)) : nNodes; for (int i = 1; i <= alphaSize; i++) { int j = 0; int k = i; for (int parent_k; (parent_k = parent[k]) >= 0;) { k = parent_k; j++; } len[i - 1] = (char) j; if (j > maxLen) { tooLong = true; } } if (tooLong) { for (int i = 1; i < alphaSize; i++) { int j = weight[i] >> 8; j = 1 + (j >> 1); weight[i] = j << 8; } } } } private static byte med3(byte a, byte b, byte c) { return (a < b) ? (b < c ? b : a < c ? c : a) : (b > c ? b : a > c ? c : a); } private static void vswap(int[] fmap, int p1, int p2, int n) { n += p1; while (p1 < n) { int t = fmap[p1]; fmap[p1++] = fmap[p2]; fmap[p2++] = t; } } /** * Index of the last char in the block, so the block size == last + 1. */ private int last; /** * Index in fmap[] of original string after sorting. */ private int origPtr; /** * Always: in the range 0 .. 9. The current block size is 100000 * this * number. */ private final int blockSize100k; private boolean blockRandomised; private int bsBuff; private int bsLive; private final CRC crc = new CRC(); private int nInUse; private int nMTF; /* * Used when sorting. If too many long comparisons happen, we stop sorting, * randomise the block slightly, and try again. */ private int workDone; private int workLimit; private boolean firstAttempt; private int currentChar = -1; private int runLength = 0; private int blockCRC; private int combinedCRC; private int allowableBlockSize; /** * All memory intensive stuff. */ private CBZip2OutputStream.Data data; private OutputStream out; /** * Constructs a new CBZip2OutputStream with a blocksize of 900k. * *

* Attention: The caller is resonsible to write the two BZip2 magic * bytes ""BZ"" to the specified stream prior to calling this * constructor. *

* * @param out * * the destination stream. * * @throws IOException * if an I/O error occurs in the specified stream. * @throws NullPointerException * if out == null. */ public CBZip2OutputStream(final OutputStream out) throws IOException { this(out, MAX_BLOCKSIZE); } /** * Constructs a new CBZip2OutputStream with specified blocksize. * *

* Attention: The caller is resonsible to write the two BZip2 magic * bytes ""BZ"" to the specified stream prior to calling this * constructor. *

* * * @param out * the destination stream. * @param blockSize * the blockSize as 100k units. * * @throws IOException * if an I/O error occurs in the specified stream. * @throws IllegalArgumentException * if (blockSize < 1) || (blockSize > 9). * @throws NullPointerException * if out == null. * * @see #MIN_BLOCKSIZE * @see #MAX_BLOCKSIZE */ public CBZip2OutputStream(final OutputStream out, final int blockSize) throws IOException { super(); if (blockSize < 1) { throw new IllegalArgumentException(""blockSize("" + blockSize + "") < 1""); } if (blockSize > 9) { throw new IllegalArgumentException(""blockSize("" + blockSize + "") > 9""); } this.blockSize100k = blockSize; this.out = out; init(); } private void blockSort() { this.workLimit = WORK_FACTOR * this.last; this.workDone = 0; this.blockRandomised = false; this.firstAttempt = true; mainSort(); if (this.firstAttempt && (this.workDone > this.workLimit)) { //randomiseBlock(); this.workLimit = this.workDone = 0; this.firstAttempt = false; mainSort(); } int[] fmap = this.data.fmap; this.origPtr = -1; for (int i = 0, lastShadow = this.last; i <= lastShadow; i++) { if (fmap[i] == 0) { this.origPtr = i; break; } } // assert (this.origPtr != -1) : this.origPtr; } private void bsFinishedWithStream() throws IOException { while (this.bsLive > 0) { int ch = this.bsBuff >> 24; this.out.write(ch); // write 8-bit this.bsBuff <<= 8; this.bsLive -= 8; } } private void bsPutInt(final int u) throws IOException { bsW(8, (u >> 24) & 0xff); bsW(8, (u >> 16) & 0xff); bsW(8, (u >> 8) & 0xff); bsW(8, u & 0xff); } private void bsPutUByte(final int c) throws IOException { bsW(8, c); } private void bsW(final int n, final int v) throws IOException { final OutputStream outShadow = this.out; int bsLiveShadow = this.bsLive; int bsBuffShadow = this.bsBuff; while (bsLiveShadow >= 8) { outShadow.write(bsBuffShadow >> 24); // write 8-bit bsBuffShadow <<= 8; bsLiveShadow -= 8; } this.bsBuff = bsBuffShadow | (v << (32 - bsLiveShadow - n)); this.bsLive = bsLiveShadow + n; } public void close() throws IOException { if (out != null) { OutputStream outShadow = this.out; finish(); outShadow.close(); } } private void endBlock() throws IOException { this.blockCRC = this.crc.getFinalCRC(); this.combinedCRC = (this.combinedCRC << 1) | (this.combinedCRC >>> 31); this.combinedCRC ^= this.blockCRC; // empty block at end of file if (this.last == -1) { return; } /* sort the block and establish posn of original string */ blockSort(); /* * A 6-byte block header, the value chosen arbitrarily as 0x314159265359 * :-). A 32 bit value does not really give a strong enough guarantee * that the value will not appear by chance in the compressed * datastream. Worst-case probability of this event, for a 900k block, * is about 2.0e-3 for 32 bits, 1.0e-5 for 40 bits and 4.0e-8 for 48 * bits. For a compressed file of size 100Gb -- about 100000 blocks -- * only a 48-bit marker will do. NB: normal compression/ decompression * donot rely on these statistical properties. They are only important * when trying to recover blocks from damaged files. */ bsPutUByte(0x31); bsPutUByte(0x41); bsPutUByte(0x59); bsPutUByte(0x26); bsPutUByte(0x53); bsPutUByte(0x59); /* Now the block's CRC, so it is in a known place. */ bsPutInt(this.blockCRC); /* Now a single bit indicating randomisation. */ if (this.blockRandomised) { bsW(1, 1); } else { bsW(1, 0); } /* Finally, block's contents proper. */ moveToFrontCodeAndSend(); } private void endCompression() throws IOException { /* * Now another magic 48-bit number, 0x177245385090, to indicate the end * of the last block. (sqrt(pi), if you want to know. I did want to use * e, but it contains too much repetition -- 27 18 28 18 28 46 -- for me * to feel statistically comfortable. Call me paranoid.) */ bsPutUByte(0x17); bsPutUByte(0x72); bsPutUByte(0x45); bsPutUByte(0x38); bsPutUByte(0x50); bsPutUByte(0x90); bsPutInt(this.combinedCRC); bsFinishedWithStream(); } public void finish() throws IOException { if (out != null) { try { if (this.runLength > 0) { writeRun(); } this.currentChar = -1; endBlock(); endCompression(); } finally { this.out.close(); this.out = null; this.data = null; } } } public void flush() throws IOException { OutputStream outShadow = this.out; if (outShadow != null) { outShadow.flush(); } } private void generateMTFValues() { final int lastShadow = this.last; final Data dataShadow = this.data; final boolean[] inUse = dataShadow.inUse; final byte[] block = dataShadow.block; final int[] fmap = dataShadow.fmap; final char[] sfmap = dataShadow.sfmap; final int[] mtfFreq = dataShadow.mtfFreq; final byte[] unseqToSeq = dataShadow.unseqToSeq; final byte[] yy = dataShadow.generateMTFValues_yy; // make maps int nInUseShadow = 0; for (int i = 0; i < 256; i++) { if (inUse[i]) { unseqToSeq[i] = (byte) nInUseShadow; nInUseShadow++; } } this.nInUse = nInUseShadow; final int eob = nInUseShadow + 1; for (int i = eob; i >= 0; i--) { mtfFreq[i] = 0; } for (int i = nInUseShadow; --i >= 0;) { yy[i] = (byte) i; } int wr = 0; int zPend = 0; for (int i = 0; i <= lastShadow; i++) { final byte ll_i = unseqToSeq[block[fmap[i]] & 0xff]; byte tmp = yy[0]; int j = 0; while (ll_i != tmp) { j++; byte tmp2 = tmp; tmp = yy[j]; yy[j] = tmp2; } yy[0] = tmp; if (j == 0) { zPend++; } else { if (zPend > 0) { zPend--; while (true) { if ((zPend & 1) == 0) { sfmap[wr] = RUNA; wr++; mtfFreq[RUNA]++; } else { sfmap[wr] = RUNB; wr++; mtfFreq[RUNB]++; } if (zPend >= 2) { zPend = (zPend - 2) >> 1; } else { break; } } zPend = 0; } sfmap[wr] = (char) (j + 1); wr++; mtfFreq[j + 1]++; } } if (zPend > 0) { zPend--; while (true) { if ((zPend & 1) == 0) { sfmap[wr] = RUNA; wr++; mtfFreq[RUNA]++; } else { sfmap[wr] = RUNB; wr++; mtfFreq[RUNB]++; } if (zPend >= 2) { zPend = (zPend - 2) >> 1; } else { break; } } } sfmap[wr] = (char) eob; mtfFreq[eob]++; this.nMTF = wr + 1; } /** * Returns the blocksize parameter specified at construction time. */ public final int getBlockSize() { return this.blockSize100k; } private void init() throws IOException { // write magic: done by caller who created this stream // this.out.write('B'); // this.out.write('Z'); this.data = new Data(this.blockSize100k); /* * Write `magic' bytes h indicating file-format == huffmanised, followed * by a digit indicating blockSize100k. */ bsPutUByte('h'); bsPutUByte('0' + this.blockSize100k); this.combinedCRC = 0; initBlock(); } private void initBlock() { // blockNo++; this.crc.initialiseCRC(); this.last = -1; // ch = 0; boolean[] inUse = this.data.inUse; for (int i = 256; --i >= 0;) { inUse[i] = false; } /* 20 is just a paranoia constant */ this.allowableBlockSize = (this.blockSize100k * BZip2Constants.baseBlockSize) - 20; } /** * Method ""mainQSort3"", file ""blocksort.c"", BZip2 1.0.2 */ private void mainQSort3(final Data dataShadow, final int loSt, final int hiSt, final int dSt) { final int[] stack_ll = dataShadow.stack_ll; final int[] stack_hh = dataShadow.stack_hh; final int[] stack_dd = dataShadow.stack_dd; final int[] fmap = dataShadow.fmap; final byte[] block = dataShadow.block; stack_ll[0] = loSt; stack_hh[0] = hiSt; stack_dd[0] = dSt; for (int sp = 1; --sp >= 0;) { final int lo = stack_ll[sp]; final int hi = stack_hh[sp]; final int d = stack_dd[sp]; if ((hi - lo < SMALL_THRESH) || (d > DEPTH_THRESH)) { if (mainSimpleSort(dataShadow, lo, hi, d)) { return; } } else { final int d1 = d + 1; final int med = med3(block[fmap[lo] + d1], block[fmap[hi] + d1], block[fmap[(lo + hi) >>> 1] + d1]) & 0xff; int unLo = lo; int unHi = hi; int ltLo = lo; int gtHi = hi; while (true) { while (unLo <= unHi) { final int n = ((int) block[fmap[unLo] + d1] & 0xff) - med; if (n == 0) { final int temp = fmap[unLo]; fmap[unLo++] = fmap[ltLo]; fmap[ltLo++] = temp; } else if (n < 0) { unLo++; } else { break; } } while (unLo <= unHi) { final int n = ((int) block[fmap[unHi] + d1] & 0xff) - med; if (n == 0) { final int temp = fmap[unHi]; fmap[unHi--] = fmap[gtHi]; fmap[gtHi--] = temp; } else if (n > 0) { unHi--; } else { break; } } if (unLo <= unHi) { final int temp = fmap[unLo]; fmap[unLo++] = fmap[unHi]; fmap[unHi--] = temp; } else { break; } } if (gtHi < ltLo) { stack_ll[sp] = lo; stack_hh[sp] = hi; stack_dd[sp] = d1; sp++; } else { int n = ((ltLo - lo) < (unLo - ltLo)) ? (ltLo - lo) : (unLo - ltLo); vswap(fmap, lo, unLo - n, n); int m = ((hi - gtHi) < (gtHi - unHi)) ? (hi - gtHi) : (gtHi - unHi); vswap(fmap, unLo, hi - m + 1, m); n = lo + unLo - ltLo - 1; m = hi - (gtHi - unHi) + 1; stack_ll[sp] = lo; stack_hh[sp] = n; stack_dd[sp] = d; sp++; stack_ll[sp] = n + 1; stack_hh[sp] = m - 1; stack_dd[sp] = d1; sp++; stack_ll[sp] = m; stack_hh[sp] = hi; stack_dd[sp] = d; sp++; } } } } /** * This is the most hammered method of this class. * *

* This is the version using unrolled loops. Normally I never use such ones * in Java code. The unrolling has shown a noticable performance improvement * on JRE 1.4.2 (Linux i586 / HotSpot Client). Of course it depends on the * JIT compiler of the vm. *

*/ private boolean mainSimpleSort(final Data dataShadow, final int lo, final int hi, final int d) { final int bigN = hi - lo + 1; if (bigN < 2) { return this.firstAttempt && (this.workDone > this.workLimit); } int hp = 0; while (INCS[hp] < bigN) { hp++; } final int[] fmap = dataShadow.fmap; final char[] quadrant = dataShadow.quadrant; final byte[] block = dataShadow.block; final int lastShadow = this.last; final int lastPlus1 = lastShadow + 1; final boolean firstAttemptShadow = this.firstAttempt; final int workLimitShadow = this.workLimit; int workDoneShadow = this.workDone; // Following block contains unrolled code which could be shortened by // coding it in additional loops. HP: while (--hp >= 0) { final int h = INCS[hp]; final int mj = lo + h - 1; for (int i = lo + h; i <= hi;) { // copy for (int k = 3; (i <= hi) && (--k >= 0); i++) { final int v = fmap[i]; final int vd = v + d; int j = i; // for (int a; // (j > mj) && mainGtU((a = fmap[j - h]) + d, vd, // block, quadrant, lastShadow); // j -= h) { // fmap[j] = a; // } // // unrolled version: // start inline mainGTU boolean onceRunned = false; int a = 0; HAMMER: while (true) { if (onceRunned) { fmap[j] = a; if ((j -= h) <= mj) { break HAMMER; } } else { onceRunned = true; } a = fmap[j - h]; int i1 = a + d; int i2 = vd; // following could be done in a loop, but // unrolled it for performance: if (block[i1 + 1] == block[i2 + 1]) { if (block[i1 + 2] == block[i2 + 2]) { if (block[i1 + 3] == block[i2 + 3]) { if (block[i1 + 4] == block[i2 + 4]) { if (block[i1 + 5] == block[i2 + 5]) { if (block[(i1 += 6)] == block[(i2 += 6)]) { int x = lastShadow; X: while (x > 0) { x -= 4; if (block[i1 + 1] == block[i2 + 1]) { if (quadrant[i1] == quadrant[i2]) { if (block[i1 + 2] == block[i2 + 2]) { if (quadrant[i1 + 1] == quadrant[i2 + 1]) { if (block[i1 + 3] == block[i2 + 3]) { if (quadrant[i1 + 2] == quadrant[i2 + 2]) { if (block[i1 + 4] == block[i2 + 4]) { if (quadrant[i1 + 3] == quadrant[i2 + 3]) { if ((i1 += 4) >= lastPlus1) { i1 -= lastPlus1; } if ((i2 += 4) >= lastPlus1) { i2 -= lastPlus1; } workDoneShadow++; continue X; } else if ((quadrant[i1 + 3] > quadrant[i2 + 3])) { continue HAMMER; } else { break HAMMER; } } else if ((block[i1 + 4] & 0xff) > (block[i2 + 4] & 0xff)) { continue HAMMER; } else { break HAMMER; } } else if ((quadrant[i1 + 2] > quadrant[i2 + 2])) { continue HAMMER; } else { break HAMMER; } } else if ((block[i1 + 3] & 0xff) > (block[i2 + 3] & 0xff)) { continue HAMMER; } else { break HAMMER; } } else if ((quadrant[i1 + 1] > quadrant[i2 + 1])) { continue HAMMER; } else { break HAMMER; } } else if ((block[i1 + 2] & 0xff) > (block[i2 + 2] & 0xff)) { continue HAMMER; } else { break HAMMER; } } else if ((quadrant[i1] > quadrant[i2])) { continue HAMMER; } else { break HAMMER; } } else if ((block[i1 + 1] & 0xff) > (block[i2 + 1] & 0xff)) { continue HAMMER; } else { break HAMMER; } } break HAMMER; } // while x > 0 else { if ((block[i1] & 0xff) > (block[i2] & 0xff)) { continue HAMMER; } else { break HAMMER; } } } else if ((block[i1 + 5] & 0xff) > (block[i2 + 5] & 0xff)) { continue HAMMER; } else { break HAMMER; } } else if ((block[i1 + 4] & 0xff) > (block[i2 + 4] & 0xff)) { continue HAMMER; } else { break HAMMER; } } else if ((block[i1 + 3] & 0xff) > (block[i2 + 3] & 0xff)) { continue HAMMER; } else { break HAMMER; } } else if ((block[i1 + 2] & 0xff) > (block[i2 + 2] & 0xff)) { continue HAMMER; } else { break HAMMER; } } else if ((block[i1 + 1] & 0xff) > (block[i2 + 1] & 0xff)) { continue HAMMER; } else { break HAMMER; } } // HAMMER // end inline mainGTU fmap[j] = v; } if (firstAttemptShadow && (i <= hi) && (workDoneShadow > workLimitShadow)) { break HP; } } } this.workDone = workDoneShadow; return firstAttemptShadow && (workDoneShadow > workLimitShadow); } private void mainSort() { final Data dataShadow = this.data; final int[] runningOrder = dataShadow.mainSort_runningOrder; final int[] copy = dataShadow.mainSort_copy; final boolean[] bigDone = dataShadow.mainSort_bigDone; final int[] ftab = dataShadow.ftab; final byte[] block = dataShadow.block; final int[] fmap = dataShadow.fmap; final char[] quadrant = dataShadow.quadrant; final int lastShadow = this.last; final int workLimitShadow = this.workLimit; final boolean firstAttemptShadow = this.firstAttempt; // Set up the 2-byte frequency table for (int i = 65537; --i >= 0;) { ftab[i] = 0; } /* * In the various block-sized structures, live data runs from 0 to * last+NUM_OVERSHOOT_BYTES inclusive. First, set up the overshoot area * for block. */ for (int i = 0; i < NUM_OVERSHOOT_BYTES; i++) { block[lastShadow + i + 2] = block[(i % (lastShadow + 1)) + 1]; } for (int i = lastShadow + NUM_OVERSHOOT_BYTES +1; --i >= 0;) { quadrant[i] = 0; } block[0] = block[lastShadow + 1]; // Complete the initial radix sort: int c1 = block[0] & 0xff; for (int i = 0; i <= lastShadow; i++) { final int c2 = block[i + 1] & 0xff; ftab[(c1 << 8) + c2]++; c1 = c2; } for (int i = 1; i <= 65536; i++) ftab[i] += ftab[i - 1]; c1 = block[1] & 0xff; for (int i = 0; i < lastShadow; i++) { final int c2 = block[i + 2] & 0xff; fmap[--ftab[(c1 << 8) + c2]] = i; c1 = c2; } fmap[--ftab[((block[lastShadow + 1] & 0xff) << 8) + (block[1] & 0xff)]] = lastShadow; /* * Now ftab contains the first loc of every small bucket. Calculate the * running order, from smallest to largest big bucket. */ for (int i = 256; --i >= 0;) { bigDone[i] = false; runningOrder[i] = i; } for (int h = 364; h != 1;) { h /= 3; for (int i = h; i <= 255; i++) { final int vv = runningOrder[i]; final int a = ftab[(vv + 1) << 8] - ftab[vv << 8]; final int b = h - 1; int j = i; for (int ro = runningOrder[j - h]; (ftab[(ro + 1) << 8] - ftab[ro << 8]) > a; ro = runningOrder[j - h]) { runningOrder[j] = ro; j -= h; if (j <= b) { break; } } runningOrder[j] = vv; } } /* * The main sorting loop. */ for (int i = 0; i <= 255; i++) { /* * Process big buckets, starting with the least full. */ final int ss = runningOrder[i]; // Step 1: /* * Complete the big bucket [ss] by quicksorting any unsorted small * buckets [ss, j]. Hopefully previous pointer-scanning phases have * already completed many of the small buckets [ss, j], so we don't * have to sort them at all. */ for (int j = 0; j <= 255; j++) { final int sb = (ss << 8) + j; final int ftab_sb = ftab[sb]; if ((ftab_sb & SETMASK) != SETMASK) { final int lo = ftab_sb & CLEARMASK; final int hi = (ftab[sb + 1] & CLEARMASK) - 1; if (hi > lo) { mainQSort3(dataShadow, lo, hi, 2); if (firstAttemptShadow && (this.workDone > workLimitShadow)) { return; } } ftab[sb] = ftab_sb | SETMASK; } } // Step 2: // Now scan this big bucket so as to synthesise the // sorted order for small buckets [t, ss] for all t != ss. for (int j = 0; j <= 255; j++) { copy[j] = ftab[(j << 8) + ss] & CLEARMASK; } for (int j = ftab[ss << 8] & CLEARMASK, hj = (ftab[(ss + 1) << 8] & CLEARMASK); j < hj; j++) { final int fmap_j = fmap[j]; c1 = block[fmap_j] & 0xff; if (!bigDone[c1]) { fmap[copy[c1]] = (fmap_j == 0) ? lastShadow : (fmap_j - 1); copy[c1]++; } } for (int j = 256; --j >= 0;) ftab[(j << 8) + ss] |= SETMASK; // Step 3: /* * The ss big bucket is now done. Record this fact, and update the * quadrant descriptors. Remember to update quadrants in the * overshoot area too, if necessary. The ""if (i < 255)"" test merely * skips this updating for the last bucket processed, since updating * for the last bucket is pointless. */ bigDone[ss] = true; if (i < 255) { final int bbStart = ftab[ss << 8] & CLEARMASK; final int bbSize = (ftab[(ss + 1) << 8] & CLEARMASK) - bbStart; int shifts = 0; while ((bbSize >> shifts) > 65534) { shifts++; } for (int j = 0; j < bbSize; j++) { final int a2update = fmap[bbStart + j]; final char qVal = (char) (j >> shifts); quadrant[a2update] = qVal; if (a2update < NUM_OVERSHOOT_BYTES) { quadrant[a2update + lastShadow + 1] = qVal; } } } } } private void moveToFrontCodeAndSend() throws IOException { bsW(24, this.origPtr); generateMTFValues(); sendMTFValues(); } @SuppressWarnings(""unused"") private void randomiseBlock() { final boolean[] inUse = this.data.inUse; final byte[] block = this.data.block; final int lastShadow = this.last; for (int i = 256; --i >= 0;) inUse[i] = false; int rNToGo = 0; int rTPos = 0; for (int i = 0, j = 1; i <= lastShadow; i = j, j++) { if (rNToGo == 0) { rNToGo = (char) BZip2Constants.rNums[rTPos]; if (++rTPos == 512) { rTPos = 0; } } rNToGo--; block[j] ^= ((rNToGo == 1) ? 1 : 0); // handle 16 bit signed numbers inUse[block[j] & 0xff] = true; } this.blockRandomised = true; } private void sendMTFValues() throws IOException { final byte[][] len = this.data.sendMTFValues_len; final int alphaSize = this.nInUse + 2; for (int t = N_GROUPS; --t >= 0;) { byte[] len_t = len[t]; for (int v = alphaSize; --v >= 0;) { len_t[v] = GREATER_ICOST; } } /* Decide how many coding tables to use */ // assert (this.nMTF > 0) : this.nMTF; final int nGroups = (this.nMTF < 200) ? 2 : (this.nMTF < 600) ? 3 : (this.nMTF < 1200) ? 4 : (this.nMTF < 2400) ? 5 : 6; /* Generate an initial set of coding tables */ sendMTFValues0(nGroups, alphaSize); /* * Iterate up to N_ITERS times to improve the tables. */ final int nSelectors = sendMTFValues1(nGroups, alphaSize); /* Compute MTF values for the selectors. */ sendMTFValues2(nGroups, nSelectors); /* Assign actual codes for the tables. */ sendMTFValues3(nGroups, alphaSize); /* Transmit the mapping table. */ sendMTFValues4(); /* Now the selectors. */ sendMTFValues5(nGroups, nSelectors); /* Now the coding tables. */ sendMTFValues6(nGroups, alphaSize); /* And finally, the block data proper */ sendMTFValues7(nSelectors); } private void sendMTFValues0(final int nGroups, final int alphaSize) { final byte[][] len = this.data.sendMTFValues_len; final int[] mtfFreq = this.data.mtfFreq; int remF = this.nMTF; int gs = 0; for (int nPart = nGroups; nPart > 0; nPart--) { final int tFreq = remF / nPart; int ge = gs - 1; int aFreq = 0; for (final int a = alphaSize - 1; (aFreq < tFreq) && (ge < a);) { aFreq += mtfFreq[++ge]; } if ((ge > gs) && (nPart != nGroups) && (nPart != 1) && (((nGroups - nPart) & 1) != 0)) { aFreq -= mtfFreq[ge--]; } final byte[] len_np = len[nPart - 1]; for (int v = alphaSize; --v >= 0;) { if ((v >= gs) && (v <= ge)) { len_np[v] = LESSER_ICOST; } else { len_np[v] = GREATER_ICOST; } } gs = ge + 1; remF -= aFreq; } } private int sendMTFValues1(final int nGroups, final int alphaSize) { final Data dataShadow = this.data; final int[][] rfreq = dataShadow.sendMTFValues_rfreq; final int[] fave = dataShadow.sendMTFValues_fave; final short[] cost = dataShadow.sendMTFValues_cost; final char[] sfmap = dataShadow.sfmap; final byte[] selector = dataShadow.selector; final byte[][] len = dataShadow.sendMTFValues_len; final byte[] len_0 = len[0]; final byte[] len_1 = len[1]; final byte[] len_2 = len[2]; final byte[] len_3 = len[3]; final byte[] len_4 = len[4]; final byte[] len_5 = len[5]; final int nMTFShadow = this.nMTF; int nSelectors = 0; for (int iter = 0; iter < N_ITERS; iter++) { for (int t = nGroups; --t >= 0;) { fave[t] = 0; int[] rfreqt = rfreq[t]; for (int i = alphaSize; --i >= 0;) { rfreqt[i] = 0; } } nSelectors = 0; for (int gs = 0; gs < this.nMTF;) { /* Set group start & end marks. */ /* * Calculate the cost of this group as coded by each of the * coding tables. */ final int ge = Math.min(gs + G_SIZE - 1, nMTFShadow - 1); if (nGroups == N_GROUPS) { // unrolled version of the else-block short cost0 = 0; short cost1 = 0; short cost2 = 0; short cost3 = 0; short cost4 = 0; short cost5 = 0; for (int i = gs; i <= ge; i++) { final int icv = sfmap[i]; cost0 += len_0[icv] & 0xff; cost1 += len_1[icv] & 0xff; cost2 += len_2[icv] & 0xff; cost3 += len_3[icv] & 0xff; cost4 += len_4[icv] & 0xff; cost5 += len_5[icv] & 0xff; } cost[0] = cost0; cost[1] = cost1; cost[2] = cost2; cost[3] = cost3; cost[4] = cost4; cost[5] = cost5; } else { for (int t = nGroups; --t >= 0;) { cost[t] = 0; } for (int i = gs; i <= ge; i++) { final int icv = sfmap[i]; for (int t = nGroups; --t >= 0;) { cost[t] += len[t][icv] & 0xff; } } } /* * Find the coding table which is best for this group, and * record its identity in the selector table. */ int bt = -1; for (int t = nGroups, bc = 999999999; --t >= 0;) { final int cost_t = cost[t]; if (cost_t < bc) { bc = cost_t; bt = t; } } fave[bt]++; selector[nSelectors] = (byte) bt; nSelectors++; /* * Increment the symbol frequencies for the selected table. */ final int[] rfreq_bt = rfreq[bt]; for (int i = gs; i <= ge; i++) { rfreq_bt[sfmap[i]]++; } gs = ge + 1; } /* * Recompute the tables based on the accumulated frequencies. */ for (int t = 0; t < nGroups; t++) { hbMakeCodeLengths(len[t], rfreq[t], this.data, alphaSize, 20); } } return nSelectors; } private void sendMTFValues2(final int nGroups, final int nSelectors) { // assert (nGroups < 8) : nGroups; final Data dataShadow = this.data; byte[] pos = dataShadow.sendMTFValues2_pos; for (int i = nGroups; --i >= 0;) { pos[i] = (byte) i; } for (int i = 0; i < nSelectors; i++) { final byte ll_i = dataShadow.selector[i]; byte tmp = pos[0]; int j = 0; while (ll_i != tmp) { j++; byte tmp2 = tmp; tmp = pos[j]; pos[j] = tmp2; } pos[0] = tmp; dataShadow.selectorMtf[i] = (byte) j; } } private void sendMTFValues3(final int nGroups, final int alphaSize) { int[][] code = this.data.sendMTFValues_code; byte[][] len = this.data.sendMTFValues_len; for (int t = 0; t < nGroups; t++) { int minLen = 32; int maxLen = 0; final byte[] len_t = len[t]; for (int i = alphaSize; --i >= 0;) { final int l = len_t[i] & 0xff; if (l > maxLen) { maxLen = l; } if (l < minLen) { minLen = l; } } // assert (maxLen <= 20) : maxLen; // assert (minLen >= 1) : minLen; hbAssignCodes(code[t], len[t], minLen, maxLen, alphaSize); } } private void sendMTFValues4() throws IOException { final boolean[] inUse = this.data.inUse; final boolean[] inUse16 = this.data.sentMTFValues4_inUse16; for (int i = 16; --i >= 0;) { inUse16[i] = false; final int i16 = i * 16; for (int j = 16; --j >= 0;) { if (inUse[i16 + j]) { inUse16[i] = true; } } } for (int i = 0; i < 16; i++) { bsW(1, inUse16[i] ? 1 : 0); } final OutputStream outShadow = this.out; int bsLiveShadow = this.bsLive; int bsBuffShadow = this.bsBuff; for (int i = 0; i < 16; i++) { if (inUse16[i]) { final int i16 = i * 16; for (int j = 0; j < 16; j++) { // inlined: bsW(1, inUse[i16 + j] ? 1 : 0); while (bsLiveShadow >= 8) { outShadow.write(bsBuffShadow >> 24); // write 8-bit bsBuffShadow <<= 8; bsLiveShadow -= 8; } if (inUse[i16 + j]) { bsBuffShadow |= 1 << (32 - bsLiveShadow - 1); } bsLiveShadow++; } } } this.bsBuff = bsBuffShadow; this.bsLive = bsLiveShadow; } private void sendMTFValues5(final int nGroups, final int nSelectors) throws IOException { bsW(3, nGroups); bsW(15, nSelectors); final OutputStream outShadow = this.out; final byte[] selectorMtf = this.data.selectorMtf; int bsLiveShadow = this.bsLive; int bsBuffShadow = this.bsBuff; for (int i = 0; i < nSelectors; i++) { for (int j = 0, hj = selectorMtf[i] & 0xff; j < hj; j++) { // inlined: bsW(1, 1); while (bsLiveShadow >= 8) { outShadow.write(bsBuffShadow >> 24); bsBuffShadow <<= 8; bsLiveShadow -= 8; } bsBuffShadow |= 1 << (32 - bsLiveShadow - 1); bsLiveShadow++; } // inlined: bsW(1, 0); while (bsLiveShadow >= 8) { outShadow.write(bsBuffShadow >> 24); bsBuffShadow <<= 8; bsLiveShadow -= 8; } // bsBuffShadow |= 0 << (32 - bsLiveShadow - 1); bsLiveShadow++; } this.bsBuff = bsBuffShadow; this.bsLive = bsLiveShadow; } private void sendMTFValues6(final int nGroups, final int alphaSize) throws IOException { final byte[][] len = this.data.sendMTFValues_len; final OutputStream outShadow = this.out; int bsLiveShadow = this.bsLive; int bsBuffShadow = this.bsBuff; for (int t = 0; t < nGroups; t++) { byte[] len_t = len[t]; int curr = len_t[0] & 0xff; // inlined: bsW(5, curr); while (bsLiveShadow >= 8) { outShadow.write(bsBuffShadow >> 24); // write 8-bit bsBuffShadow <<= 8; bsLiveShadow -= 8; } bsBuffShadow |= curr << (32 - bsLiveShadow - 5); bsLiveShadow += 5; for (int i = 0; i < alphaSize; i++) { int lti = len_t[i] & 0xff; while (curr < lti) { // inlined: bsW(2, 2); while (bsLiveShadow >= 8) { outShadow.write(bsBuffShadow >> 24); // write 8-bit bsBuffShadow <<= 8; bsLiveShadow -= 8; } bsBuffShadow |= 2 << (32 - bsLiveShadow - 2); bsLiveShadow += 2; curr++; /* 10 */ } while (curr > lti) { // inlined: bsW(2, 3); while (bsLiveShadow >= 8) { outShadow.write(bsBuffShadow >> 24); // write 8-bit bsBuffShadow <<= 8; bsLiveShadow -= 8; } bsBuffShadow |= 3 << (32 - bsLiveShadow - 2); bsLiveShadow += 2; curr--; /* 11 */ } // inlined: bsW(1, 0); while (bsLiveShadow >= 8) { outShadow.write(bsBuffShadow >> 24); // write 8-bit bsBuffShadow <<= 8; bsLiveShadow -= 8; } // bsBuffShadow |= 0 << (32 - bsLiveShadow - 1); bsLiveShadow++; } } this.bsBuff = bsBuffShadow; this.bsLive = bsLiveShadow; } private void sendMTFValues7(final int nSelectors) throws IOException { final Data dataShadow = this.data; final byte[][] len = dataShadow.sendMTFValues_len; final int[][] code = dataShadow.sendMTFValues_code; final OutputStream outShadow = this.out; final byte[] selector = dataShadow.selector; final char[] sfmap = dataShadow.sfmap; final int nMTFShadow = this.nMTF; int selCtr = 0; int bsLiveShadow = this.bsLive; int bsBuffShadow = this.bsBuff; for (int gs = 0; gs < nMTFShadow;) { final int ge = Math.min(gs + G_SIZE - 1, nMTFShadow - 1); final int selector_selCtr = selector[selCtr] & 0xff; final int[] code_selCtr = code[selector_selCtr]; final byte[] len_selCtr = len[selector_selCtr]; while (gs <= ge) { final int sfmap_i = sfmap[gs]; // // inlined: bsW(len_selCtr[sfmap_i] & 0xff, // code_selCtr[sfmap_i]); // while (bsLiveShadow >= 8) { outShadow.write(bsBuffShadow >> 24); bsBuffShadow <<= 8; bsLiveShadow -= 8; } final int n = len_selCtr[sfmap_i] & 0xFF; bsBuffShadow |= code_selCtr[sfmap_i] << (32 - bsLiveShadow - n); bsLiveShadow += n; gs++; } gs = ge + 1; selCtr++; } this.bsBuff = bsBuffShadow; this.bsLive = bsLiveShadow; } public void write(final byte[] buf, int offs, final int len) throws IOException { if (offs < 0) { throw new IndexOutOfBoundsException(""offs("" + offs + "") < 0.""); } if (len < 0) { throw new IndexOutOfBoundsException(""len("" + len + "") < 0.""); } if (offs + len > buf.length) { throw new IndexOutOfBoundsException(""offs("" + offs + "") + len("" + len + "") > buf.length("" + buf.length + "").""); } if (this.out == null) { throw new IOException(""stream closed""); } for (int hi = offs + len; offs < hi;) { write0(buf[offs++]); } } public void write(final int b) throws IOException { if (this.out != null) { write0(b); } else { throw new IOException(""closed""); } } private void write0(int b) throws IOException { if (this.currentChar != -1) { b &= 0xff; if (this.currentChar == b) { if (++this.runLength > 254) { writeRun(); this.currentChar = -1; this.runLength = 0; } // else nothing to do } else { writeRun(); this.runLength = 1; this.currentChar = b; } } else { this.currentChar = b & 0xff; this.runLength++; } } private void writeRun() throws IOException { final int lastShadow = this.last; if (lastShadow < this.allowableBlockSize) { final int currentCharShadow = this.currentChar; final Data dataShadow = this.data; dataShadow.inUse[currentCharShadow] = true; final byte ch = (byte) currentCharShadow; int runLengthShadow = this.runLength; this.crc.updateCRC(currentCharShadow, runLengthShadow); switch (runLengthShadow) { case 1: dataShadow.block[lastShadow + 2] = ch; this.last = lastShadow + 1; break; case 2: dataShadow.block[lastShadow + 2] = ch; dataShadow.block[lastShadow + 3] = ch; this.last = lastShadow + 2; break; case 3: { final byte[] block = dataShadow.block; block[lastShadow + 2] = ch; block[lastShadow + 3] = ch; block[lastShadow + 4] = ch; this.last = lastShadow + 3; } break; default: { runLengthShadow -= 4; dataShadow.inUse[runLengthShadow] = true; final byte[] block = dataShadow.block; block[lastShadow + 2] = ch; block[lastShadow + 3] = ch; block[lastShadow + 4] = ch; block[lastShadow + 5] = ch; block[lastShadow + 6] = (byte) runLengthShadow; this.last = lastShadow + 5; } break; } } else { endBlock(); initBlock(); writeRun(); } } } " " /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the ""License""); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /* * This package is based on the work done by Keiron Liddle, Aftex Software * to whom the Ant project is very grateful for his * great code. */ package com.rs.cache.utils.bzip2; /** * A simple class the hold and calculate the CRC for sanity checking * of the data. * */ final class CRC { static final int crc32Table[] = { 0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b, 0x1a864db2, 0x1e475005, 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61, 0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd, 0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9, 0x5f15adac, 0x5bd4b01b, 0x569796c2, 0x52568b75, 0x6a1936c8, 0x6ed82b7f, 0x639b0da6, 0x675a1011, 0x791d4014, 0x7ddc5da3, 0x709f7b7a, 0x745e66cd, 0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039, 0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5, 0xbe2b5b58, 0xbaea46ef, 0xb7a96036, 0xb3687d81, 0xad2f2d84, 0xa9ee3033, 0xa4ad16ea, 0xa06c0b5d, 0xd4326d90, 0xd0f37027, 0xddb056fe, 0xd9714b49, 0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95, 0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1, 0xe13ef6f4, 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d, 0x34867077, 0x30476dc0, 0x3d044b19, 0x39c556ae, 0x278206ab, 0x23431b1c, 0x2e003dc5, 0x2ac12072, 0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16, 0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca, 0x7897ab07, 0x7c56b6b0, 0x71159069, 0x75d48dde, 0x6b93dddb, 0x6f52c06c, 0x6211e6b5, 0x66d0fb02, 0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1, 0x53dc6066, 0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba, 0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e, 0xbfa1b04b, 0xbb60adfc, 0xb6238b25, 0xb2e29692, 0x8aad2b2f, 0x8e6c3698, 0x832f1041, 0x87ee0df6, 0x99a95df3, 0x9d684044, 0x902b669d, 0x94ea7b2a, 0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e, 0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2, 0xc6bcf05f, 0xc27dede8, 0xcf3ecb31, 0xcbffd686, 0xd5b88683, 0xd1799b34, 0xdc3abded, 0xd8fba05a, 0x690ce0ee, 0x6dcdfd59, 0x608edb80, 0x644fc637, 0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb, 0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f, 0x5c007b8a, 0x58c1663d, 0x558240e4, 0x51435d53, 0x251d3b9e, 0x21dc2629, 0x2c9f00f0, 0x285e1d47, 0x36194d42, 0x32d850f5, 0x3f9b762c, 0x3b5a6b9b, 0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff, 0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623, 0xf12f560e, 0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7, 0xe22b20d2, 0xe6ea3d65, 0xeba91bbc, 0xef68060b, 0xd727bbb6, 0xd3e6a601, 0xdea580d8, 0xda649d6f, 0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3, 0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7, 0xae3afba2, 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b, 0x9b3660c6, 0x9ff77d71, 0x92b45ba8, 0x9675461f, 0x8832161a, 0x8cf30bad, 0x81b02d74, 0x857130c3, 0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640, 0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c, 0x7b827d21, 0x7f436096, 0x7200464f, 0x76c15bf8, 0x68860bfd, 0x6c47164a, 0x61043093, 0x65c52d24, 0x119b4be9, 0x155a565e, 0x18197087, 0x1cd86d30, 0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec, 0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088, 0x2497d08d, 0x2056cd3a, 0x2d15ebe3, 0x29d4f654, 0xc5a92679, 0xc1683bce, 0xcc2b1d17, 0xc8ea00a0, 0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, 0xdbee767c, 0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18, 0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4, 0x89b8fd09, 0x8d79e0be, 0x803ac667, 0x84fbdbd0, 0x9abc8bd5, 0x9e7d9662, 0x933eb0bb, 0x97ffad0c, 0xafb010b1, 0xab710d06, 0xa6322bdf, 0xa2f33668, 0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4 }; int globalCrc; CRC() { initialiseCRC(); } int getFinalCRC() { return ~globalCrc; } int getGlobalCRC() { return globalCrc; } void initialiseCRC() { globalCrc = 0xffffffff; } void setGlobalCRC(int newCrc) { globalCrc = newCrc; } void updateCRC(int inCh) { int temp = (globalCrc >> 24) ^ inCh; if (temp < 0) { temp = 256 + temp; } globalCrc = (globalCrc << 8) ^ CRC.crc32Table[temp]; } void updateCRC(int inCh, int repeat) { int globalCrcShadow = this.globalCrc; while (repeat-- > 0) { int temp = (globalCrcShadow >> 24) ^ inCh; globalCrcShadow = (globalCrcShadow << 8) ^ crc32Table[(temp >= 0) ? temp : (temp + 256)]; } this.globalCrc = globalCrcShadow; } } " " package com.rs.lib; import java.math.BigInteger; public class Constants { /** * Tokens and keys */ public static String CAPTCHA_SITE = ""6Lfob18UAAAAAEx08Pvihg-vpSZ_wsFtG1aPotQw""; public static String CAPTCHA_SECRET = ""6Lfob18UAAAAAC1as5gXon-vEZYBdcLg7nt4pG3S""; public static final String GRAB_SERVER_TOKEN = ""ev9+VAp5/tMKeNR/7MOuH6lKWS+rGkHK""; public static final String WORLD_TOKEN = ""ev9+VAp5/tMKeNR/7MOuH6lKWS+rGkHK""; public static final int[] GRAB_SERVER_KEYS = { 1441, 78700, 44880, 39771, 363186, 44375, 0, 16140, 7316, 271148, 810710, 216189, 379672, 454149, 933950, 21006, 25367, 17247, 1244, 1, 14856, 1494, 119, 882901, 1818764, 3963, 3618 }; public static final BigInteger RSA_PRIVATE_MODULUS = new BigInteger(""117525752735533423040644219776209926525585489242340044375332234679786347045466594509203355398209678968096551043842518449703703964361320462967286756268851663407950384008240524570966471744081769815157355561961607944067477858512067883877129283799853947605780903005188603658779539811385137666347647991072028080201""); public static final BigInteger RSA_PRIVATE_EXPONENT = new BigInteger(""45769714620275867926001532284788836149236590657678028481492967724067121406860916606777808563536714166085238449913676219414798301454048585933351540049893959827785868628572203706265915752274580525376826724019249600701154664022299724373133271944352291456503171589594996734220177420375212353960806722706846977073""); public static final String SERVER_NAME = ""Darkan""; /** * Version/networking related static variables */ public static int CLIENT_BUILD = 727; public static int CUSTOM_CLIENT_BUILD = 1; public static int CLIENT_VERSION = 6; public static int PACKET_SIZE_LIMIT = 7500; public static final long WORLD_CYCLE_NS = 600000000L; public static final long WORLD_CYCLE_MS = WORLD_CYCLE_NS / 1000000L; /* * RS Related constants */ public static final String[] SKILL_NAME = { ""Attack"", ""Defence"", ""Strength"", ""Constitution"", ""Ranged"", ""Prayer"", ""Magic"", ""Cooking"", ""Woodcutting"", ""Fletching"", ""Fishing"", ""Firemaking"", ""Crafting"", ""Smithing"", ""Mining"", ""Herblore"", ""Agility"", ""Thieving"", ""Slayer"", ""Farming"", ""Runecrafting"", ""Hunter"", ""Construction"", ""Summoning"", ""Dungeoneering"" }; public static final int ATTACK = 0, DEFENSE = 1, STRENGTH = 2, HITPOINTS = 3, RANGE = 4, PRAYER = 5, MAGIC = 6, COOKING = 7, WOODCUTTING = 8, FLETCHING = 9, FISHING = 10, FIREMAKING = 11, CRAFTING = 12, SMITHING = 13, MINING = 14, HERBLORE = 15, AGILITY = 16, THIEVING = 17, SLAYER = 18, FARMING = 19, RUNECRAFTING = 20, HUNTER = 21, CONSTRUCTION = 22, SUMMONING = 23, DUNGEONEERING = 24; } " " package com.rs.lib; public class Globals { public static boolean DEBUG = false; } " " package com.rs.lib.db; import java.util.HashSet; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoDatabase; import com.rs.lib.db.model.ErrorLogManager; public class DBConnection { private MongoClient client; private MongoDatabase database; private String mongoUrl; private String dbName; private Set collections = new HashSet<>(); private static ErrorLogManager ERROR_LOG_MANAGER = new ErrorLogManager(); public DBConnection(String mongoUrl, String dbName) { this.mongoUrl = mongoUrl; this.dbName = dbName; addItemManager(ERROR_LOG_MANAGER); } public void init() { try { Logger logger = (Logger) Logger.getLogger(""org.mongodb.driver.cluster""); logger.setLevel(Level.OFF); Logger.getLogger(""log"").setLevel(Level.OFF); client = MongoClients.create(mongoUrl); database = client.getDatabase(dbName); for (DBItemManager coll : collections) coll.init(this); } catch (Exception e) { com.rs.lib.util.Logger.handleNoRecord(DBConnection.class, ""init"", ""Error connecting to mongodb"", e); } } public void addItemManager(DBItemManager mgr) { collections.add(mgr); } public MongoClient getClient() { return client; } public MongoDatabase getDb() { return database; } public static ErrorLogManager getErrors() { return ERROR_LOG_MANAGER; } } " " package com.rs.lib.db; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.bson.Document; import com.mongodb.client.MongoCollection; import com.rs.lib.thread.CatchExceptionRunnable; import com.rs.lib.util.MongoUtil; public abstract class DBItemManager { private ExecutorService executor; private String collection; private DBConnection conn; private MongoCollection documents; public DBItemManager(String collection) { this.collection = collection; this.executor = Executors.newVirtualThreadPerTaskExecutor(); } public void init(DBConnection conn) { this.conn = conn; if (!MongoUtil.collectionExists(conn.getDb(), collection)) { conn.getDb().createCollection(collection); documents = conn.getDb().getCollection(collection); initCollection(); } else documents = conn.getDb().getCollection(collection); } public abstract void initCollection(); public DBConnection getConn() { return conn; } public MongoCollection getDocs() { return documents; } public void execute(Runnable task) { executor.execute(new CatchExceptionRunnable(task)); } } " " package com.rs.lib.db; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; public class DBThreadFactory implements ThreadFactory { private static final AtomicInteger poolNumber = new AtomicInteger(1); private final ThreadGroup group; private final AtomicInteger threadNumber = new AtomicInteger(1); private final String namePrefix; public DBThreadFactory() { group = Thread.currentThread().getThreadGroup(); namePrefix = ""DB Pool-"" + poolNumber.getAndIncrement() + ""-thread-""; } @Override public Thread newThread(Runnable r) { Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); if (t.isDaemon()) t.setDaemon(false); if (t.getPriority() != Thread.MIN_PRIORITY) t.setPriority(Thread.MIN_PRIORITY); return t; } } " " package com.rs.lib.db.model; import static com.mongodb.client.model.Filters.eq; import java.io.CharArrayWriter; import java.io.PrintWriter; import java.util.concurrent.TimeUnit; import org.bson.Document; import com.mongodb.client.model.FindOneAndReplaceOptions; import com.mongodb.client.model.IndexOptions; import com.mongodb.client.model.Indexes; import com.rs.lib.db.DBItemManager; import com.rs.lib.file.JsonFileManager; public class ErrorLogManager extends DBItemManager { public ErrorLogManager() { super(""logs""); } @Override public void initCollection() { getDocs().createIndex(Indexes.text(""type"")); getDocs().createIndex(Indexes.descending(""hash"")); getDocs().createIndex(Indexes.ascending(""date""), new IndexOptions().expireAfter(180L, TimeUnit.DAYS)); } public void save(LogEntry entry) { save(entry, null); } public void save(LogEntry entry, Runnable done) { execute(() -> { saveSync(entry); if (done != null) done.run(); }); } public void saveSync(LogEntry entry) { try { getDocs().findOneAndReplace(eq(""hash"", entry.getHash()), Document.parse(JsonFileManager.toJson(entry)), new FindOneAndReplaceOptions().upsert(true)); } catch(Throwable e) { e.printStackTrace(); } } public void logError(String logger, Throwable throwable) { String stackTrace = logger + "" - "" + throwable.getMessage() + ""\r\n""; CharArrayWriter cw = new CharArrayWriter(); PrintWriter w = new PrintWriter(cw); throwable.printStackTrace(w); w.close(); stackTrace += cw.toString(); save(new LogEntry(LogEntry.LogType.ERROR, stackTrace.hashCode(), stackTrace)); } public void logError(String logger, String message, Throwable throwable) { String stackTrace = logger + "" - "" + throwable.getMessage() + "" - "" + message + ""\r\n""; CharArrayWriter cw = new CharArrayWriter(); PrintWriter w = new PrintWriter(cw); throwable.printStackTrace(w); w.close(); stackTrace += cw.toString(); save(new LogEntry(LogEntry.LogType.ERROR, stackTrace.hashCode(), stackTrace)); } public void logError(String logger, String error) { save(new LogEntry(LogEntry.LogType.ERROR, error.hashCode(), logger + "" - "" + error)); } } " "package com.rs.lib.db.model; import java.util.Date; public class LogEntry { public enum LogType { ERROR, GE, PICKUP, GRAVE, COMMAND, REPORT, TRADE } private Date date; private LogType type; private long hash; private Object data; public LogEntry(LogType type, long hash, Object data) { this.date = new Date(); this.type = type; this.hash = hash; this.data = data; } public Date getDate() { return date; } public LogType getType() { return type; } public long getHash() { return hash; } public Object getData() { return data; } } " " package com.rs.lib.file; import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import java.io.StringWriter; import com.rs.lib.util.Utils; public class FileManager { public static void writeToFile(String fileName, String text) { try { String[] parts = fileName.split(""/""); File file; for (int i = 0; i < parts.length - 1; ++i) { file = new File(""./logs/"" + parts[i]); if (!file.exists()) { file.mkdir(); } } FileWriter writer = new FileWriter(""./logs/"" + fileName, true); writer.write(""["" + Utils.getDateString() + ""]: ""+ text + ""\r\n""); writer.close(); } catch (Exception e) { } } public static void logError(Throwable throwable) { StringWriter errors = new StringWriter(); throwable.printStackTrace(new PrintWriter(errors)); writeToFile(""errorLog.txt"", Thread.currentThread().getName() + "": "" + errors.toString()); } public static void logError(String string) { writeToFile(""errorLog.txt"", string); } } " " package com.rs.lib.file; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.lang.reflect.Type; import com.google.gson.Gson; import com.google.gson.JsonIOException; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; public class JsonFileManager { private static Gson GSON; public static void setGSON(Gson gson) { GSON = gson; } public static Gson getGson() { return GSON; } public static T loadJsonFile(File f, Type clazz) throws JsonIOException, IOException { if (!f.exists()) return null; JsonReader reader = new JsonReader(new InputStreamReader(new FileInputStream(f), ""UTF-8"")); T obj = GSON.fromJson(reader, clazz); reader.close(); return obj; } public static T fromJSONString(String json, Type clazz) throws JsonIOException, IOException { T obj = GSON.fromJson(json, clazz); return obj; } public static final void saveJsonFile(Object o, File f) throws JsonIOException, IOException { File dir = new File(f.getParent()); if (!dir.exists()) { dir.mkdirs(); } JsonWriter writer = new JsonWriter(new OutputStreamWriter(new FileOutputStream(f), ""UTF-8"")); writer.setIndent("" ""); GSON.toJson(o, o.getClass(), writer); writer.flush(); writer.close(); } public static String toJson(Object o) { return GSON.toJson(o); } }" " package com.rs.lib.game; import com.rs.cache.loaders.animations.AnimationDefinitions; public final class Animation { private int[] ids; private int speed; public Animation(int id) { this(id, 0); } public Animation(int id, int speed) { this(id, id, id, id, speed); } public Animation(int id1, int id2, int id3, int id4, int speed) { this.ids = new int[] { id1, id2, id3, id4 }; this.speed = speed; } public int[] getIds() { return ids; } public int getSpeed() { return speed; } public AnimationDefinitions getDefs() { return AnimationDefinitions.getDefs(ids[0]); } } " " package com.rs.lib.game; public class GroundItem extends Item { public enum GroundItemType { NORMAL, INVISIBLE, FOREVER } private WorldTile tile; private int visibleToId = 0; private String creatorUsername; private int creatorId; private GroundItemType type; private int ticks; private int privateTime; private int deleteTime; public GroundItem(int id) { super(id); } @Override public Item setAmount(int amount) { this.amount = amount; return this; } public GroundItem(Item item, WorldTile tile, String ownerUsername, GroundItemType type) { super(item.getId(), item.getAmount(), item.getMetaData()); this.tile = tile; if (ownerUsername != null) { this.creatorUsername = ownerUsername; this.visibleToId = this.creatorId = ownerUsername.hashCode(); } this.type = type; this.privateTime = -1; this.deleteTime = -1; } public GroundItem(Item item, WorldTile tile, GroundItemType type) { this(item, tile, null, type); } public GroundItem(Item item, WorldTile tile) { this(item, tile, null, GroundItemType.NORMAL); } public WorldTile getTile() { return tile; } public boolean isInvisible() { return type == GroundItemType.INVISIBLE; } public boolean isRespawn() { return type == GroundItemType.FOREVER; } public String getCreatorUsername() { return creatorUsername; } public int getVisibleToId() { return visibleToId; } public boolean isPrivate() { return visibleToId != 0; } // public void setInvisible(boolean invisible) { // type = invisible ? GroundItemType.INVISIBLE : GroundItemType.NORMAL; // } @Override public String toString() { return ""[""+super.toString()+"", "" + tile.toString() + (creatorUsername != null ? ("" creator: ""+creatorUsername) : """") + ""]""; } public void removeOwner() { visibleToId = 0; } public void tick() { ticks++; } public int getSourceId() { return creatorId; } public int getTicks() { return ticks; } public int getPrivateTime() { return privateTime; } public void setPrivateTime(int privateTime) { this.privateTime = privateTime; } public void setDeleteTime(int deleteTime) { this.deleteTime = deleteTime; } public int getDeleteTime() { return deleteTime; } public void setHiddenTime(int ticks) { privateTime = this.ticks + ticks; } } " " package com.rs.lib.game; public final class HintIcon { private int coordX; private int coordY; private int plane; private int distanceFromFloor; private int targetType; private int targetIndex; private int arrowType; private int modelId; private int index; public HintIcon() { this.setIndex(7); } public HintIcon(int targetType, int modelId, int index) { this.setTargetType(targetType); this.setModelId(modelId); this.setIndex(index); } public HintIcon(int targetIndex, int targetType, int arrowType, int modelId, int index) { this.setTargetType(targetType); this.setTargetIndex(targetIndex); this.setArrowType(arrowType); this.setModelId(modelId); this.setIndex(index); } public HintIcon(int coordX, int coordY, int height, int distanceFromFloor, int targetType, int arrowType, int modelId, int index) { this.setCoordX(coordX); this.setCoordY(coordY); this.setPlane(height); this.setDistanceFromFloor(distanceFromFloor); this.setTargetType(targetType); this.setArrowType(arrowType); this.setModelId(modelId); this.setIndex(index); } public void setTargetType(int targetType) { this.targetType = targetType; } public int getTargetType() { return targetType; } public void setTargetIndex(int targetIndex) { this.targetIndex = targetIndex; } public int getTargetIndex() { return targetIndex; } public void setArrowType(int arrowType) { this.arrowType = arrowType; } public int getArrowType() { return arrowType; } public void setModelId(int modelId) { this.modelId = modelId; } public int getModelId() { return modelId; } public void setIndex(int modelPart) { this.index = modelPart; } public int getIndex() { return index; } public void setCoordX(int coordX) { this.coordX = coordX; } public int getCoordX() { return coordX; } public void setCoordY(int coordY) { this.coordY = coordY; } public int getCoordY() { return coordY; } public void setPlane(int plane) { this.plane = plane; } public int getPlane() { return plane; } public void setDistanceFromFloor(int distanceFromFloor) { this.distanceFromFloor = distanceFromFloor; } public int getDistanceFromFloor() { return distanceFromFloor; } } " " package com.rs.lib.game; import java.util.HashMap; import java.util.Map; import java.lang.SuppressWarnings; import com.rs.cache.loaders.ItemDefinitions; import com.rs.lib.util.Utils; public class Item { private transient int slot; private short id; protected int amount; private Map metaData; public int getId() { return id; } @Override public Item clone() { return new Item(id, amount, Utils.cloneMap(metaData)); } public Item(Item item) { this(item.getId(), item.getAmount(), Utils.cloneMap(item.getMetaData())); } public Item(int id) { this(id, 1); } public Item(int id, int amount) { this(id, amount, false); } public Item(int id, int amount, Map metaData) { this(id, amount); this.metaData = metaData; } public Item(int id, int amount, boolean amt0) { this.id = (short) id; this.amount = amount; if (this.amount <= 0 && !amt0) { this.amount = 1; } } public ItemDefinitions getDefinitions() { return ItemDefinitions.getDefs(id); } public int getEquipId() { return getDefinitions().getEquipId(); } public Item setAmount(int amount) { if (amount < 0 || amount > Integer.MAX_VALUE) return this; this.amount = amount; return this; } public void setId(int id) { this.id = (short) id; } public int getAmount() { return amount; } public String getName() { return getDefinitions().getName(); } public int getSlot() { return slot; } public Item setSlot(int slot) { this.slot = slot; return this; } public Item addMetaData(String key, Object value) { if (metaData == null) metaData = new HashMap(); metaData.put(key, value); return this; } public Map getMetaData() { return metaData; } public Object getMetaData(String key) { if (metaData != null) return metaData.get(key); return null; } @SuppressWarnings(""unchecked"") public T setMetaDataO(String name, Object value) { if (metaData == null) metaData = new HashMap<>(); if (value == null) { Object old = metaData.remove(name); return old == null ? null : (T) old; } Object old = metaData.put(name, value); return old == null ? null : (T) old; } @SuppressWarnings(""unchecked"") public T getMetaDataO(String name) { if (metaData == null) return null; if (metaData.get(name) == null) return null; return (T) metaData.get(name); } public int incMetaDataI(String key) { int val = getMetaDataI(key) + 1; addMetaData(key, val); return val; } public int decMetaDataI(String key) { int val = getMetaDataI(key) - 1; addMetaData(key, val); return val; } public int getMetaDataI(String key) { return getMetaDataI(key, -1); } public int getMetaDataI(String key, int defaultVal) { if (metaData != null && metaData.get(key) != null) { if (metaData.get(key) instanceof Integer value) return value; return (int) Math.floor(((double) metaData.get(key))); } return defaultVal; } public void deleteMetaData() { this.metaData = null; } @Override public String toString() { return ""["" + ItemDefinitions.getDefs(id).name + "" (""+id+""), "" + amount + ""]""; } public boolean containsMetaData() { return metaData != null; } public double getMetaDataD(String key, double defaultVal) { if (metaData != null) { if (metaData.get(key) != null); return (double) metaData.get(key); } return defaultVal; } public double getMetaDataD(String key) { return getMetaDataD(key, 0); } } " " package com.rs.lib.game; public class Projectile { protected WorldTile from, to; protected int sourceId; protected int lockOnId; private boolean useTerrainHeight; private int spotAnimId, startHeight, endHeight, startTime, endTime, slope, angle; protected int fromSizeX, fromSizeY; protected int toSizeX, toSizeY; private int basFrameHeightAdjust = -1; public Projectile(WorldTile from, int sourceId, WorldTile to, int lockOnId, int spotAnimId, int startHeight, int endHeight, int startTime, int endTime, int slope, int angle) { this.sourceId = sourceId; this.from = from; this.lockOnId = lockOnId; this.to = to; this.spotAnimId = spotAnimId; this.startHeight = startHeight; this.endHeight = endHeight; this.startTime = startTime; this.endTime = endTime; this.slope = slope; this.angle = angle; } public Projectile(WorldTile from, int sourceId, WorldTile to, int spotAnimId, int startHeight, int endHeight, int startTime, int endTime, int slope, int angle) { this(from, sourceId, to, -1, spotAnimId, startHeight, endHeight, startTime, endTime, slope, angle); } public Projectile(WorldTile from, WorldTile to, int lockOnId, int spotAnimId, int startHeight, int endHeight, int startTime, int endTime, int slope, int angle) { this(from, -1, to, lockOnId, spotAnimId, startHeight, endHeight, startTime, endTime, slope, angle); } public Projectile(WorldTile from, WorldTile to, int spotAnimId, int startHeight, int endHeight, int startTime, int endTime, int slope, int angle) { this(from, -1, to, -1, spotAnimId, startHeight, endHeight, startTime, endTime, slope, angle); } public Projectile setBASFrameHeightAdjust(int frameIndex) { basFrameHeightAdjust = frameIndex; return this; } public int getBASFrameHeightAdjust() { return basFrameHeightAdjust; } public Projectile setUseTerrainHeight() { useTerrainHeight = true; return this; } public boolean usesTerrainHeight() { return useTerrainHeight; } public int getSpotAnimId() { return spotAnimId; } public int getStartHeight() { return startHeight; } public int getEndHeight() { return endHeight; } public int getStartTime() { return startTime; } public int getEndTime() { return endTime; } public int getSlope() { return slope; } public int getAngle() { return angle; } public int getSourceId() { return sourceId; } public int getLockOnId() { return lockOnId; } public WorldTile getSource() { return WorldTile.of(from.getX() + fromSizeX, from.getY() + fromSizeY, from.getPlane()); } public WorldTile getDestination() { return WorldTile.of(to.getX() + toSizeX, to.getY() + toSizeY, to.getPlane()); } } " " package com.rs.lib.game; public class PublicChatMessage { private String message; private int effects; public PublicChatMessage(String message, int effects) { this.message = message; this.effects = effects; } public String getMessage() { return message; } public int getEffects() { return effects; } } " " package com.rs.lib.game; public class QuickChatMessage extends PublicChatMessage { private int fileId; private byte[] data; public QuickChatMessage(int fileId, byte[] data) { super(data == null ? null : new String(data), 0x8000); this.fileId = fileId; this.data = data; } public byte[] getData() { return data; } public int getFileId() { return fileId; } public void setFileId(int fileId) { this.fileId = fileId; } } " " package com.rs.lib.game; public enum Rights { PLAYER(0), MOD(1), ADMIN(2), DEVELOPER(2), OWNER(2); private int crown; private Rights(int crown) { this.crown = crown; } public int getCrown() { return crown; } } " " package com.rs.lib.game; public final class SpotAnim { private int id, height, speed, rotation; public SpotAnim(int id) { this(id, 0, 0, 0); } public SpotAnim(int id, int speed) { this(id, speed, 0); } public SpotAnim(int id, int speed, int height) { this(id, speed, height, 0); } public SpotAnim(int id, int speed, int height, int rotation) { this.id = id; this.speed = speed; this.height = height; this.rotation = rotation; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + height; result = prime * result + id; result = prime * result + rotation; result = prime * result + speed; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; SpotAnim other = (SpotAnim) obj; if (height != other.height) return false; if (id != other.id) return false; if (rotation != other.rotation) return false; if (speed != other.speed) return false; return true; } public int getId() { return id; } public int getSettingsHash() { return (speed & 0xffff) | (height << 16); } public int getSettings2Hash() { int hash = 0; hash |= rotation & 0x7; // hash |= value << 3; // hash |= 1 << 7; boolean return hash; } public int getSpeed() { return speed; } public int getHeight() { return height; } } " " package com.rs.lib.game; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import com.rs.cache.ArchiveType; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.cache.loaders.VarBitDefinitions; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.Session; import com.rs.lib.net.packets.encoders.vars.SetVarp; public class VarManager { public static final int[] BIT_MASKS = new int[32]; static { int i = 2; for (int i2 = 0; i2 < 32; i2++) { BIT_MASKS[i2] = i - 1; i += i; } } private transient HashSet modified; private transient final Object lock = new Object(); private transient int[] varpValues; private transient Session session; private Map vars; public VarManager() { } public void setSession(Session session) { this.session = session; if (vars == null) vars = new HashMap<>(); varpValues = new int[Cache.STORE.getIndex(IndexType.CONFIG).getLastFileId(ArchiveType.VARS.getId()) + 1]; modified = new HashSet<>(); for (int varId : vars.keySet()) setVar(varId, vars.get(varId)); } public void setVar(int id, int value, boolean forceSend, boolean save) { synchronized(lock) { if (forceSend) modified.add(id); if (id < 0 || id >= varpValues.length) return; if (varpValues[id] == value) return; varpValues[id] = value; if (save) vars.put(id, value); modified.add(id); } } public void setVar(int id, int value, boolean forceSend) { setVar(id, value, forceSend, false); } public void setVar(int id, int value) { setVar(id, value, false, false); } public void saveVar(int id, int value) { setVar(id, value, false, true); } public void setVarBit(int id, int value, boolean forceSend, boolean save) { VarBitDefinitions defs = VarBitDefinitions.getDefs(id); int mask = BIT_MASKS[defs.endBit - defs.startBit]; if (value < 0 || value > mask) { value = 0; } mask <<= defs.startBit; int varpValue = (varpValues[defs.baseVar] & (mask ^ 0xffffffff) | value << defs.startBit & mask); if (varpValue != varpValues[defs.baseVar]) { setVar(defs.baseVar, varpValue, forceSend, save); } } public void setVarBit(int id, int value, boolean forceSend) { setVarBit(id, value, forceSend, false); } public void setVarBit(int id, int value) { setVarBit(id, value, false, false); } public void saveVarBit(int id, int value) { setVarBit(id, value, false, true); } public int getVar(int id) { return varpValues[id]; } public int getVarBit(int id) { VarBitDefinitions defs = VarBitDefinitions.getDefs(id); return varpValues[defs.baseVar] >> defs.startBit & BIT_MASKS[defs.endBit - defs.startBit]; } public boolean bitFlagged(int id, int bit) { return (varpValues[id] & (1 << bit)) != 0; } public void syncVarsToClient() { synchronized(lock) { for (int id : modified) { session.writeToQueue(new SetVarp(id, varpValues[id])); } modified.clear(); } } public void clearVars() { for (int i = 0;i < varpValues.length;i++) varpValues[i] = 0; session.writeToQueue(ServerPacket.CLEAR_VARPS); } } " " package com.rs.lib.game; public record WorldInfo(int number, String ipAddress, int port, String activity, int country, boolean lootShare, boolean members) { public static String getCountryFromId(int country) { return switch(country) { case 1 -> ""USA""; default -> ""Murica""; }; } public String getCountryName() { return getCountryFromId(country); } public boolean isLobby() { return number >= 1000; } @Override public String toString() { return ""["" + number + "", "" + ipAddress + "", "" + port + "", "" + activity + ""]""; } } " " package com.rs.lib.game; import com.rs.cache.loaders.ObjectDefinitions; import com.rs.cache.loaders.ObjectType; public class WorldObject { protected WorldTile tile; protected int id; protected ObjectType type; protected int rotation; public WorldObject(int id, ObjectType type, int rotation, WorldTile tile) { this.tile = tile; this.id = id; this.type = type; this.rotation = rotation; } public WorldObject(int id, int rotation, int x, int y, int plane) { this.tile = WorldTile.of(x, y, plane); this.id = id; this.type = ObjectDefinitions.getDefs(id).getType(0); this.rotation = rotation; } public WorldObject(int id, ObjectType type, int rotation, int x, int y, int plane) { this.tile = WorldTile.of(x, y, plane); this.id = id; this.type = type; this.rotation = rotation; } public WorldObject(WorldObject object) { this.tile = object.tile; this.id = object.id; this.type = object.type; this.rotation = object.rotation; } public int getId() { return id; } public int getCoordFaceX() { return tile.getCoordFaceX(getDefinitions().sizeX, getDefinitions().sizeY, rotation); } public int getCoordFaceY() { return tile.getCoordFaceY(getDefinitions().sizeX, getDefinitions().sizeY, rotation); } public WorldTile getCoordFace() { return WorldTile.of(getCoordFaceX(), getCoordFaceY(), tile.getPlane()); } public ObjectDefinitions getDefinitions() { return ObjectDefinitions.getDefs(id); } public int getRotation(int turn) { int initial = rotation; if (turn == 0) return initial; if (turn > 0) { for (int i = 0;i < turn;i++) { initial++; if (initial == 4) initial = 0; } } else { for (int i = 0;i > turn;i--) { initial--; if (initial == -1) initial = 3; } } return initial; } public void setRotation(int rotation) { this.rotation = rotation; } public WorldTile getTile() { return tile; } public void setTile(WorldTile tile) { this.tile = tile; } public ObjectType getType() { return type; } public void setType(ObjectType i) { this.type = i; } public int getRotation() { return rotation; } public int getSlot() { return type.slot; } public int getX() { return tile.getX(); } public int getY() { return tile.getY(); } public int getPlane() { return tile.getPlane(); } } " " package com.rs.lib.game; import com.rs.lib.util.MapUtils; import com.rs.lib.util.MapUtils.Structure; import com.rs.lib.util.Utils; public record WorldTile(short x, short y, byte plane) { public static WorldTile of(int x, int y, int plane) { return new WorldTile((short) x, (short) y, (byte) plane); } public static WorldTile of(int x, int y, int plane, int size) { return new WorldTile((short) getCoordFaceX(x, size, size, -1), (short) getCoordFaceY(y, size, size, -1), (byte) plane); } public static WorldTile of(WorldTile tile) { return new WorldTile(tile.x, tile.y, tile.plane); } public static WorldTile of(WorldTile tile, int randomize) { return new WorldTile((short) (tile.x + Utils.random(randomize * 2 + 1) - randomize), (short) (tile.y + Utils.random(randomize * 2 + 1) - randomize), tile.plane); } public static WorldTile of(int hash) { return new WorldTile((short) (hash >> 14 & 0x3fff), (short) (hash & 0x3fff), (byte) (hash >> 28)); } public static WorldTile of(int z, int regionX, int regionY, int localX, int localY) { return new WorldTile((short) (regionX << 6 | localX), (short) (regionY << 6 | localY), (byte) z); } public boolean isAt(int x, int y) { return this.x == x && this.y == y; } public boolean isAt(int x, int y, int z) { return this.x == x && this.y == y && this.plane == z; } public int getX() { return x; } public int getXInRegion() { return x & 0x3F; } public int getYInRegion() { return y & 0x3F; } public int getXInChunk() { return x & 0x7; } public int getYInChunk() { return y & 0x7; } public int getY() { return y; } public int getPlane() { if (plane > 3) return 3; return plane; } public int getChunkX() { return (x >> 3); } public int getChunkId() { return MapUtils.encode(Structure.CHUNK, getChunkX(), getChunkY()); } public int getChunkXInScene(int chunkId) { return getChunkX() - MapUtils.decode(Structure.CHUNK, chunkId)[0]; } public int getChunkYInScene(int chunkId) { return getChunkY() - MapUtils.decode(Structure.CHUNK, chunkId)[1]; } public int getXInScene(int chunkId) { return getX() - MapUtils.decode(Structure.CHUNK, chunkId)[0] * 8; } public int getYInScene(int chunkId) { return getY() - MapUtils.decode(Structure.CHUNK, chunkId)[1] * 8; } public int getChunkY() { return (y >> 3); } public int getRegionX() { return (x >> 6); } public int getRegionY() { return (y >> 6); } public int getRegionId() { return ((getRegionX() << 8) + getRegionY()); } public int getRegionHash() { return getRegionY() + (getRegionX() << 8) + (plane << 16); } public static int toInt(int x, int y, int plane) { return y + (x << 14) + (plane << 28); } public int getTileHash() { return y + (x << 14) + (plane << 28); } @Override public int hashCode() { return getTileHash(); } public boolean withinDistance(WorldTile tile, int distance) { if (tile.plane != plane) return false; int deltaX = tile.x - x, deltaY = tile.y - y; return deltaX <= distance && deltaX >= -distance && deltaY <= distance && deltaY >= -distance; } public boolean withinDistance(WorldTile tile) { return withinDistance(tile, 14); } public int getCoordFaceX(int sizeX) { return getCoordFaceX(sizeX, -1, -1); } public static final int getCoordFaceX(int x, int sizeX, int sizeY, int rotation) { return x + ((rotation == 1 || rotation == 3 ? sizeY : sizeX) - 1) / 2; } public static final int getCoordFaceY(int y, int sizeX, int sizeY, int rotation) { return y + ((rotation == 1 || rotation == 3 ? sizeX : sizeY) - 1) / 2; } public int getCoordFaceX(int sizeX, int sizeY, int rotation) { return x + ((rotation == 1 || rotation == 3 ? sizeY : sizeX) - 1) / 2; } public int getCoordFaceY(int sizeY) { return getCoordFaceY(-1, sizeY, -1); } public int getCoordFaceY(int sizeX, int sizeY, int rotation) { return y + ((rotation == 1 || rotation == 3 ? sizeX : sizeY) - 1) / 2; } public int getLongestDelta(WorldTile other) { int deltaX = Math.abs(getX() - other.getX()); int deltaY = Math.abs(getY() - other.getY()); return Math.max(deltaX, deltaY); } public WorldTile transform(int x, int y) { return transform(x, y, 0); } public WorldTile transform(int x, int y, int plane) { return WorldTile.of(this.x + x, this.y + y, this.plane + plane); } public boolean matches(WorldTile other) { return x == other.x && y == other.y && plane == other.plane; } public boolean withinArea(int a, int b, int c, int d) { return getX() >= a && getY() >= b && getX() <= c && getY() <= d; } @Override public String toString() { return ""[ X: "" + x + "", Y: "" + y + "", Z: "" + plane + "" ]""; } } " " package com.rs.lib.io; import com.rs.lib.util.Utils; public final class InputStream extends Stream { public void initBitAccess() { bitPosition = offset * 8; } private static final int[] BIT_MASK = new int[] { 0, 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767, 65535, 131071, 262143, 524287, 1048575, 2097151, 4194303, 8388607, 16777215, 33554431, 67108863, 134217727, 268435455, 536870911, 1073741823, 2147483647, -1 }; public void finishBitAccess() { offset = (7 + bitPosition) / 8; } public int readBits(int bitOffset) { int bytePos = bitPosition >> 1779819011; int i_8_ = -(0x7 & bitPosition) + 8; bitPosition += bitOffset; int value = 0; for (/**/; (bitOffset ^ 0xffffffff) < (i_8_ ^ 0xffffffff); i_8_ = 8) { value += (BIT_MASK[i_8_] & buffer[bytePos++]) << -i_8_ + bitOffset; bitOffset -= i_8_; } if ((i_8_ ^ 0xffffffff) == (bitOffset ^ 0xffffffff)) value += buffer[bytePos] & BIT_MASK[i_8_]; else value += (buffer[bytePos] >> -bitOffset + i_8_ & BIT_MASK[bitOffset]); return value; } public InputStream(int capacity) { buffer = new byte[capacity]; } public InputStream(byte[] buffer) { this.buffer = buffer; this.length = buffer.length; } public void checkCapacity(int length) { if (offset + length >= buffer.length) { byte[] newBuffer = new byte[(offset + length) * 2]; System.arraycopy(buffer, 0, newBuffer, 0, buffer.length); buffer = newBuffer; } } public int read24BitInt() { return (readUnsignedByte() << 16) + (readUnsignedByte() << 8) + (readUnsignedByte()); } public void skip(int length) { offset += length; } public void setLength(int length) { this.length = length; } public void setOffset(int offset) { this.offset = offset; } public void addBytes(byte[] b, int offset, int length) { checkCapacity(length - offset); System.arraycopy(b, offset, buffer, this.offset, length); this.length += length - offset; } public int peekPacket(IsaacKeyPair isaac) { return (peekUnsignedByte() - isaac.inKey().peek()) & 0xff; } public int readPacket(IsaacKeyPair isaac) { return (readUnsignedByte() - isaac.inKey().nextInt()) & 0xff; } public int read24BitUnsignedInteger() { this.offset += 3; return ((buffer[offset - 3] & 0xff) << 16) + (buffer[offset - 1] & 0xff) + ((buffer[offset - 2] & 0xff) << 8); } public int peekUnsignedByte() { return peekByte() & 0xff; } public int peekByte() { return getRemaining() > 0 ? buffer[offset] : 0; } public int readByte() { return getRemaining() > 0 ? buffer[offset++] : 0; } public void readBytes(byte buffer[], int off, int len) { for (int k = off; k < len + off; k++) { buffer[k] = (byte) readByte(); } } public void readBytes(byte buffer[]) { readBytes(buffer, 0, buffer.length); } public int readSmart2() { int i = 0; int i_33_ = readUnsignedSmart(); while (i_33_ == 32767) { i_33_ = readUnsignedSmart(); i += 32767; } i += i_33_; return i; } public int readUnsignedByte() { return readByte() & 0xff; } public int readByte128() { return (byte) (readByte() - 128); } public int readByteC() { return (byte) -readByte(); } public int read128Byte() { return (byte) (128 - readByte()); } public int readUnsignedByte128() { return readUnsignedByte() - 128 & 0xff; } public int readUnsignedByteC() { return -readUnsignedByte() & 0xff; } public int readUnsigned128Byte() { return 128 - readUnsignedByte() & 0xff; } public int readShortLE() { int i = readUnsignedByte() + (readUnsignedByte() << 8); if (i > 32767) { i -= 0x10000; } return i; } public int readShort128() { int i = (readUnsignedByte() << 8) + (readByte() - 128 & 0xff); if (i > 32767) { i -= 0x10000; } return i; } public int readShortLE128() { int i = (readByte() - 128 & 0xff) + (readUnsignedByte() << 8); if (i > 32767) { i -= 0x10000; } return i; } public int read128ShortLE() { int i = (128 - readByte() & 0xff) + (readUnsignedByte() << 8); if (i > 32767) { i -= 0x10000; } return i; } public int readShort() { int i = (readUnsignedByte() << 8) + readUnsignedByte(); if (i > 32767) { i -= 65536; } return i; } public int readUnsignedShortLE() { return readUnsignedByte() + (readUnsignedByte() << 8); } public int readUnsignedShort() { return (readUnsignedByte() << 8) + readUnsignedByte(); } // @SuppressWarnings(""unused"") public int readBigSmart() { /* * if(Settings.CLIENT_BUILD < 670) return readUnsignedShort(); */ if ((buffer[offset] ^ 0xffffffff) <= -1) { int value = readUnsignedShort(); if (value == 32767) { return -1; } return value; } return readInt() & 0x7fffffff; } public int readUnsignedShort128() { return (readUnsignedByte() << 8) + (readByte() - 128 & 0xff); } public int readUnsignedShortLE128() { return (readByte() - 128 & 0xff) + (readUnsignedByte() << 8); } public int readInt() { return (readUnsignedByte() << 24) + (readUnsignedByte() << 16) + (readUnsignedByte() << 8) + readUnsignedByte(); } public int readTriByte() { return (readUnsignedByte() << 16) + (readUnsignedByte() << 8) + readUnsignedByte(); } public int readIntV1() { return (readUnsignedByte() << 8) + readUnsignedByte() + (readUnsignedByte() << 24) + (readUnsignedByte() << 16); } public int readIntV2() { return (readUnsignedByte() << 16) + (readUnsignedByte() << 24) + readUnsignedByte() + (readUnsignedByte() << 8); } public int readIntLE() { return readUnsignedByte() + (readUnsignedByte() << 8) + (readUnsignedByte() << 16) + (readUnsignedByte() << 24); } public long readLong() { long l = readInt() & 0xffffffffL; long l1 = readInt() & 0xffffffffL; return (l << 32) + l1; } public String readNoSpecString() { StringBuilder s = new StringBuilder(); int b; while ((b = readByte()) != 0) s.append((char) b); return s.toString(); } public String readString() { int i_1 = this.offset; while (this.buffer[++this.offset - 1] != 0) { } int i_2 = this.offset - i_1 - 1; return i_2 == 0 ? """" : Utils.readString(this.buffer, i_1, i_2); } public String readJagString() { readByte(); String s = """"; int b; while ((b = readByte()) != 0) { s += (char) b; } return s; } public String readGJString() { byte b = this.buffer[++this.offset - 1]; if (b != 0) { throw new IllegalStateException(""""); } else { int idx = this.offset; while (this.buffer[++this.offset - 1] != 0) { ; } int i_4 = this.offset - idx - 1; return i_4 == 0 ? """" : Utils.readString(this.buffer, idx, i_4); } } public final int readSignedSmart() { int v = this.buffer[this.offset] & 0xff; if (v < 128) return readUnsignedByte() - 64; return readUnsignedShort() - 49152; } public int readUnsignedSmart() { int i = buffer[offset] & 0xff; if (i >= 128) { return readUnsignedShort() - 32768; } return readUnsignedByte(); } public int readUnsignedSmartNegOne() { int i = buffer[offset] & 0xff; if (i >= 128) { return readUnsignedShort() - 32769; } return readUnsignedByte() - 1; } public String readNullString() { if (this.buffer[this.offset] == 0) { this.offset++; return null; } return readString(); } public long readSized(int size) { --size; if (size >= 0 && size <= 7) { int bitSize = size * 8; long val; for (val = 0L; bitSize >= 0; bitSize -= 8) { val |= ((long) this.buffer[++this.offset - 1] & 0xffL) << bitSize; } return val; } else { throw new IllegalArgumentException(); } } public float readFloat() { return Float.intBitsToFloat(readInt()); } }" " package com.rs.lib.io; public class ISAACCipher { private int[] seeds; private int count; private int c; private int b; private int a; private int[] memory = new int[256]; private int[] results = new int[256]; public ISAACCipher(int[] seeds) { this.seeds = new int[seeds.length]; System.arraycopy(seeds, 0, this.seeds, 0, seeds.length); System.arraycopy(seeds, 0, results, 0, seeds.length); init(); } void init() { int i_2 = -1640531527; int i_3 = -1640531527; int i_4 = -1640531527; int i_5 = -1640531527; int i_6 = -1640531527; int i_7 = -1640531527; int i_8 = -1640531527; int i_9 = -1640531527; int i_10; for (i_10 = 0; i_10 < 4; i_10++) { i_9 ^= i_8 << 11; i_6 += i_9; i_8 += i_7; i_8 ^= i_7 >>> 2; i_5 += i_8; i_7 += i_6; i_7 ^= i_6 << 8; i_4 += i_7; i_6 += i_5; i_6 ^= i_5 >>> 16; i_3 += i_6; i_5 += i_4; i_5 ^= i_4 << 10; i_2 += i_5; i_4 += i_3; i_4 ^= i_3 >>> 4; i_9 += i_4; i_3 += i_2; i_3 ^= i_2 << 8; i_8 += i_3; i_2 += i_9; i_2 ^= i_9 >>> 9; i_7 += i_2; i_9 += i_8; } for (i_10 = 0; i_10 < 256; i_10 += 8) { i_9 += results[i_10]; i_8 += results[i_10 + 1]; i_7 += results[i_10 + 2]; i_6 += results[i_10 + 3]; i_5 += results[i_10 + 4]; i_4 += results[i_10 + 5]; i_3 += results[i_10 + 6]; i_2 += results[i_10 + 7]; i_9 ^= i_8 << 11; i_6 += i_9; i_8 += i_7; i_8 ^= i_7 >>> 2; i_5 += i_8; i_7 += i_6; i_7 ^= i_6 << 8; i_4 += i_7; i_6 += i_5; i_6 ^= i_5 >>> 16; i_3 += i_6; i_5 += i_4; i_5 ^= i_4 << 10; i_2 += i_5; i_4 += i_3; i_4 ^= i_3 >>> 4; i_9 += i_4; i_3 += i_2; i_3 ^= i_2 << 8; i_8 += i_3; i_2 += i_9; i_2 ^= i_9 >>> 9; i_7 += i_2; i_9 += i_8; memory[i_10] = i_9; memory[i_10 + 1] = i_8; memory[i_10 + 2] = i_7; memory[i_10 + 3] = i_6; memory[i_10 + 4] = i_5; memory[i_10 + 5] = i_4; memory[i_10 + 6] = i_3; memory[i_10 + 7] = i_2; } for (i_10 = 0; i_10 < 256; i_10 += 8) { i_9 += memory[i_10]; i_8 += memory[i_10 + 1]; i_7 += memory[i_10 + 2]; i_6 += memory[i_10 + 3]; i_5 += memory[i_10 + 4]; i_4 += memory[i_10 + 5]; i_3 += memory[i_10 + 6]; i_2 += memory[i_10 + 7]; i_9 ^= i_8 << 11; i_6 += i_9; i_8 += i_7; i_8 ^= i_7 >>> 2; i_5 += i_8; i_7 += i_6; i_7 ^= i_6 << 8; i_4 += i_7; i_6 += i_5; i_6 ^= i_5 >>> 16; i_3 += i_6; i_5 += i_4; i_5 ^= i_4 << 10; i_2 += i_5; i_4 += i_3; i_4 ^= i_3 >>> 4; i_9 += i_4; i_3 += i_2; i_3 ^= i_2 << 8; i_8 += i_3; i_2 += i_9; i_2 ^= i_9 >>> 9; i_7 += i_2; i_9 += i_8; memory[i_10] = i_9; memory[i_10 + 1] = i_8; memory[i_10 + 2] = i_7; memory[i_10 + 3] = i_6; memory[i_10 + 4] = i_5; memory[i_10 + 5] = i_4; memory[i_10 + 6] = i_3; memory[i_10 + 7] = i_2; } isaac(); count = 256; } public int nextInt() { if (count == 0) { isaac(); count = 256; } //return 0; //Disables ISAAC return (results[(count -= 1)]); } public int peek() { if (count == 0) { isaac(); count = 256; } //return 0; //Disables ISAAC return (results[count - 1]); } void isaac() { b += ++c; for (int i_2 = 0; i_2 < 256; i_2++) { int i_3 = memory[i_2]; if ((i_2 & 0x2) == 0) { if ((i_2 & 0x1) == 0) { a ^= a << 13; } else { a ^= a >>> 6; } } else if ((i_2 & 0x1) == 0) { a ^= a << 2; } else { a ^= a >>> 16; } a += memory[128 + i_2 & 0xff]; int i_4; memory[i_2] = i_4 = memory[(i_3 & 0x3fc) >> 2] + b + a; results[i_2] = b = memory[(i_4 >> 8 & 0x3fc) >> 2] + i_3; } } public int[] getSeeds() { return seeds; } }" " package com.rs.lib.io; public class IsaacKeyPair { private ISAACCipher inKey, outKey; public IsaacKeyPair(int[] seed) { inKey = new ISAACCipher(seed); for (int i = 0; i < seed.length; i++) seed[i] += 50; outKey = new ISAACCipher(seed); } public ISAACCipher inKey() { return inKey; } public ISAACCipher outKey() { return outKey; } } " " package com.rs.lib.io; import com.rs.lib.model.Account; import com.rs.lib.util.Logger; import com.rs.lib.util.Utils; public final class OutputStream extends Stream { private static final int[] BIT_MASK = new int[32]; private int opcodeStart = 0; static { for (int i = 0; i < 32; i++) BIT_MASK[i] = (1 << i) - 1; } public OutputStream(int capacity) { setBuffer(new byte[capacity]); } public OutputStream() { setBuffer(new byte[16]); } public OutputStream(byte[] buffer) { this.setBuffer(buffer); this.offset = buffer.length; length = buffer.length; } public OutputStream(int[] buffer) { setBuffer(new byte[buffer.length]); for (int value : buffer) writeByte(value); } public void checkCapacityPosition(int position) { if (position >= getBuffer().length) { byte[] newBuffer = new byte[position + 16]; System.arraycopy(getBuffer(), 0, newBuffer, 0, getBuffer().length); setBuffer(newBuffer); } } public void skip(int length) { setOffset(getOffset() + length); } public void setOffset(int offset) { this.offset = offset; } public void writeBytes(byte[] b, int offset, int length) { checkCapacityPosition(this.getOffset() + length - offset); System.arraycopy(b, offset, getBuffer(), this.getOffset(), length); this.setOffset(this.getOffset() + (length - offset)); } public void writeBytes(byte[] b) { int offset = 0; int length = b.length; checkCapacityPosition(this.getOffset() + length - offset); System.arraycopy(b, offset, getBuffer(), this.getOffset(), length); this.setOffset(this.getOffset() + (length - offset)); } public void addBytes128(byte[] data, int offset, int len) { for (int k = offset; k < len; k++) writeByte((byte) (data[k] + 128)); } public void addBytesS(byte[] data, int offset, int len) { for (int k = offset; k < len; k++) writeByte((byte) (-128 + data[k])); } public void addBytes_Reverse(byte[] data, int offset, int len) { for (int i = len - 1; i >= 0; i--) { writeByte((data[i])); } } public void addBytes_Reverse128(byte[] data, int offset, int len) { for (int i = len - 1; i >= 0; i--) { writeByte((byte) (data[i] + 128)); } } public void writeByte(int i) { writeByte(i, offset++); } public void writeNegativeByte(int i) { writeByte(-i, offset++); } public void writeByte(int i, int position) { checkCapacityPosition(position); getBuffer()[position] = (byte) i; } public void writeByte128(int i) { writeByte(i + 128); } public void writeByteC(int i) { writeByte(-i); } public void write128Byte(int i) { writeByte(128 - i); } public void writeShortLE128(int i) { writeByte(i + 128); writeByte(i >> 8); } public void writeShort128(int i) { writeByte(i >> 8); writeByte(i + 128); } public void writeSmartNS(int i) { if (i >= 128) { writeShort(i + 32769); } else { writeByte(i + 1); } } public void writeUnsignedSmart(int value) { if (value < 64 && value >= -64) { writeByte(value + 64); return; } if (value < 16384 && value >= -16384) { writeShort(value + 49152); return; } else { System.err.println(""Error psmart out of range: "" + value); return; } } public void writeBigSmart(int i) { if (i >= Short.MAX_VALUE) writeInt(i - Integer.MAX_VALUE - 1); else { writeShort(i >= 0 ? i : 32767); } } public void writeShort(int i) { writeByte(i >> 8); writeByte(i); } public void writeShortLE(int i) { writeByte(i); writeByte(i >> 8); } public void write24BitInteger(int i) { writeByte(i >> 16); writeByte(i >> 8); writeByte(i); } public void write24BitIntegerV2(int i) { writeByte(i >> 16); writeByte(i); writeByte(i >> 8); } public void writeInt(int i) { writeByte(i >> 24); writeByte(i >> 16); writeByte(i >> 8); writeByte(i); } public void writeIntV1(int i) { writeByte(i >> 8); writeByte(i); writeByte(i >> 24); writeByte(i >> 16); } public void writeIntV2(int i) { writeByte(i >> 16); writeByte(i >> 24); writeByte(i); writeByte(i >> 8); } public void writeIntLE(int i) { writeByte(i); writeByte(i >> 8); writeByte(i >> 16); writeByte(i >> 24); } public void writeLong(long l) { writeByte((int) (l >> 56)); writeByte((int) (l >> 48)); writeByte((int) (l >> 40)); writeByte((int) (l >> 32)); writeByte((int) (l >> 24)); writeByte((int) (l >> 16)); writeByte((int) (l >> 8)); writeByte((int) l); } public void writePSmarts(int i) { if (i < 128) { writeByte(i); return; } if (i < 32768) { writeShort(32768 + i); return; } else { Logger.error(OutputStream.class, ""writePSmarts"", ""Error psmarts out of range: "" + i); return; } } public void writeString(String string) { int i_2 = string.indexOf(0); if (i_2 >= 0) { throw new IllegalArgumentException(""""); } else { checkCapacityPosition(getOffset() + string.length() + 1); this.offset += Utils.writeString(string, 0, string.length(), this.buffer, this.offset); this.buffer[++this.offset - 1] = 0; } } public void writeGJString2(String string) { byte[] packed = new byte[256]; int length = Utils.packGJString2(0, packed, string); writeByte(0); writeBytes(packed, 0, length); writeByte(0); } public void writeGJString(String s) { writeByte(0); writeString(s); } public void putGJString3(String s) { writeByte(0); writeString(s); writeByte(0); } public OutputStream writePacket(IsaacKeyPair isaac, int id, boolean worldPacket) { if (!worldPacket) writeSmart(id); else if (id >= 128) { if (isaac == null) { writeByte(id); writeByte(id); return this; } writeByte((id >> 8) + 128 + isaac.outKey().nextInt()); writeByte(id + isaac.outKey().nextInt()); } else { if (isaac == null) { writeByte(id); return this; } writeByte(id + isaac.outKey().nextInt()); } return this; } public void writePacketVarByte(IsaacKeyPair isaac, int id, boolean worldPacket) { writePacket(isaac, id, worldPacket); writeByte(0); opcodeStart = getOffset() - 1; } public void writePacketVarShort(IsaacKeyPair isaac, int id, boolean worldPacket) { writePacket(isaac, id, worldPacket); writeShort(0); opcodeStart = getOffset() - 2; } public void endPacketVarByte() { writeByte(getOffset() - (opcodeStart + 2) + 1, opcodeStart); } public void endPacketVarShort() { int size = getOffset() - (opcodeStart + 2); writeByte(size >> 8, opcodeStart++); writeByte(size, opcodeStart); } public void initBitAccess() { bitPosition = getOffset() * 8; } public void finishBitAccess() { setOffset((bitPosition + 7) / 8); } public int getBitPos(int i) { return 8 * i - bitPosition; } public void writeBits(int numBits, int value) { int bytePos = bitPosition >> 3; int bitOffset = 8 - (bitPosition & 7); bitPosition += numBits; for (; numBits > bitOffset; bitOffset = 8) { checkCapacityPosition(bytePos); getBuffer()[bytePos] &= ~BIT_MASK[bitOffset]; getBuffer()[bytePos++] |= value >> numBits - bitOffset & BIT_MASK[bitOffset]; numBits -= bitOffset; } checkCapacityPosition(bytePos); if (numBits == bitOffset) { getBuffer()[bytePos] &= ~BIT_MASK[bitOffset]; getBuffer()[bytePos] |= value & BIT_MASK[bitOffset]; } else { getBuffer()[bytePos] &= ~(BIT_MASK[numBits] << bitOffset - numBits); getBuffer()[bytePos] |= (value & BIT_MASK[numBits]) << bitOffset - numBits; } } public void writeDisplayNameChat(Account account) { if (account.getPrevDisplayName() == null || account.getPrevDisplayName().isEmpty() || account.getPrevDisplayName().equals(account.getDisplayName())) { writeByte(0); writeString(account.getDisplayName()); } else { writeByte(1); writeString(account.getDisplayName()); writeString(account.getPrevDisplayName()); } } public void setBuffer(byte[] buffer) { this.buffer = buffer; } public void write5ByteInteger(long value) { writeByte((int) (value >> 32)); writeInt((int) (value & 0xffffffff)); } public void writeSum(int i) { while (i >= 32767) { writeSmart(32767); i -= 32767; } writeSmart(i); } public void write24BitInt(int i) { writeByte(i >> 16); writeByte(i >> 8); writeByte(i); } public void writeBoolean(boolean bool) { writeByte(bool ? 1 : 0); } public void writeSmart(int value) { if (value >= 128) { writeShort(value + 32768); } else { writeByte(value); } } }" " package com.rs.lib.io; public abstract class Stream { public int offset; protected int length; protected byte[] buffer; protected int bitPosition; public int getLength() { return length; } public byte[] getBuffer() { return buffer; } public byte[] toByteArray() { byte[] arr = new byte[offset]; offset = 0; getBytes(arr, 0, arr.length); offset = arr.length; return arr; } public int getOffset() { return offset; } public void decodeXTEA(int keys[]) { decodeXTEA(keys, 5, length); } public void decodeXTEA(int keys[], int start, int end) { int l = offset; offset = start; int i1 = (end - start) / 8; for (int j1 = 0; j1 < i1; j1++) { int k1 = readInt(); int l1 = readInt(); int sum = 0xc6ef3720; int delta = 0x9e3779b9; for (int k2 = 32; k2-- > 0;) { l1 -= keys[(sum & 0x1c84) >>> 11] + sum ^ (k1 >>> 5 ^ k1 << 4) + k1; sum -= delta; k1 -= (l1 >>> 5 ^ l1 << 4) + l1 ^ keys[sum & 3] + sum; } offset -= 8; writeInt(k1); writeInt(l1); } offset = l; } public final void encodeXTEA(int keys[], int start, int end) { int o = offset; int j = (end - start) / 8; offset = start; for (int k = 0; k < j; k++) { int l = readInt(); int i1 = readInt(); int sum = 0; int delta = 0x9e3779b9; for (int l1 = 32; l1-- > 0;) { l += sum + keys[3 & sum] ^ i1 + (i1 >>> 5 ^ i1 << 4); sum += delta; i1 += l + (l >>> 5 ^ l << 4) ^ keys[(0x1eec & sum) >>> 11] + sum; } offset -= 8; writeInt(l); writeInt(i1); } offset = o; } private final int readInt() { offset += 4; return ((0xff & buffer[-3 + offset]) << 16) + ((((0xff & buffer[-4 + offset]) << 24) + ((buffer[-2 + offset] & 0xff) << 8)) + (buffer[-1 + offset] & 0xff)); } private final void writeInt(int value) { buffer[offset++] = (byte) (value >> 24); buffer[offset++] = (byte) (value >> 16); buffer[offset++] = (byte) (value >> 8); buffer[offset++] = (byte) value; } public final void getBytes(byte data[], int off, int len) { for (int k = off; k < len + off; k++) { data[k] = buffer[offset++]; } } public int read24BitInt() { return (readUnsignedByte() << 16) + (readUnsignedByte() << 8) + (readUnsignedByte()); } public int readUnsignedByte() { return readByte() & 0xff; } public int readByte() { return getRemaining() > 0 ? buffer[offset++] : 0; } public int getRemaining() { return offset < length ? length - offset : 0; } } " " package com.rs.lib.json; import java.lang.reflect.Type; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; public class DateAdapter implements JsonDeserializer { @Override public Date deserialize(JsonElement element, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { String date = element.getAsString(); SimpleDateFormat format1 = new SimpleDateFormat(""MMM dd, YYYY, h:mm:ss a""); SimpleDateFormat format2 = new SimpleDateFormat(""MMM dd, YYYY h:mm:ss a""); try { return format1.parse(date); } catch (ParseException exp) { try { return format2.parse(date); } catch (ParseException exp2) { System.err.println(""Failed to parse Date:"" + exp2); return null; } } } } " " package com.rs.lib.model; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashSet; import java.util.Set; import com.rs.lib.game.Rights; import com.rs.lib.util.Utils; public class Account { private String username; private String email; private String recoveryEmail; private String displayName; private String prevDisplayName = """"; private Rights rights; private Set prevPasswords; private byte[] password; private String legacyPass; private Social social; private long banned; private long muted; private String lastIp; public Account(String username) { this.username = username; this.displayName = Utils.formatPlayerNameForDisplay(username); this.prevDisplayName = """"; this.social = new Social(); } public Account(String username, byte[] password, String email) { this.username = Utils.formatPlayerNameForProtocol(username); this.displayName = Utils.formatPlayerNameForDisplay(username); this.prevDisplayName = """"; this.email = email; this.recoveryEmail = email; this.rights = Rights.PLAYER; this.password = password; this.prevPasswords = new HashSet<>(); this.prevPasswords.add(this.password); this.social = new Social(); } public String getUsername() { return username; } public String getDisplayName() { return displayName; } public String getEmail() { return email; } public Set getPrevPasswords() { return prevPasswords; } public byte[] getPassword() { return password; } public void setPassword(byte[] password) { if (this.prevPasswords == null) this.prevPasswords = new HashSet<>(); this.prevPasswords.add(this.password); this.password = password; } public String getLegacyPass() { return legacyPass; } public void setLegacyPass(String legacyPass) { this.legacyPass = legacyPass; } public Social getSocial() { return social; } public boolean isMuted() { return System.currentTimeMillis() < this.muted; } public void muteSpecific(long ms) { this.muted = System.currentTimeMillis() + ms; } public void muteDays(int days) { muteSpecific(days * (24 * 60 * 60 * 1000)); } public void mutePerm() { this.muted = Long.MAX_VALUE; } public void unmute() { this.muted = 0; } public String getUnmuteDate() { return new SimpleDateFormat(""dd MMM yyyy HH:mm:ss:SSS Z"").format(new Date(muted)); } public String getUnbanDate() { return new SimpleDateFormat(""dd MMM yyyy HH:mm:ss:SSS Z"").format(new Date(banned)); } public boolean isBanned() { return System.currentTimeMillis() < this.banned; } public void banSpecific(long ms) { this.banned = System.currentTimeMillis() + ms; } public void banDays(int days) { banSpecific(days * (24 * 60 * 60 * 1000)); } public void banPerm() { this.banned = Long.MAX_VALUE; } public void unban() { this.banned = 0; } public void copyPunishments(Account account) { this.banned = account.banned; this.muted = account.muted; } public boolean hasRights(Rights rights) { return this.rights.ordinal() >= rights.ordinal(); } public Rights getRights() { return rights; } public void setRights(Rights rights) { this.rights = rights; } public String getLastIP() { return lastIp; } public void setLastIP(String lastIp) { this.lastIp = lastIp; } public boolean onlineTo(Account other) { if (other.getSocial().getStatus() == 2 || (other.getSocial().getStatus() == 1 && !other.getSocial().getFriends().contains(getUsername()))) return false; return true; } public String getPrevDisplayName() { return prevDisplayName; } public void setPrevDisplayName(String prevDisplayName) { this.prevDisplayName = prevDisplayName; } public String getRecoveryEmail() { return recoveryEmail; } public void setRecoveryEmail(String recoveryEmail) { this.recoveryEmail = recoveryEmail; } public void setSocial(Social social) { this.social = social; } public long getBanExpiry() { return banned; } public long getMuteExpiry() { return muted; } public void setEmail(String email) { this.email = email; } /** * NEVER CALL THIS EVER * @param username */ @Deprecated public void setUsername(String username) { this.username = Utils.formatPlayerNameForProtocol(username); this.displayName = Utils.formatPlayerNameForDisplay(this.username); } } " "package com.rs.lib.model; public class DisplayNamePair { private String current; private String prev; public DisplayNamePair(String current, String prev) { this.current = current; this.prev = prev; } public String getCurrent() { return current; } public String getPrev() { return prev; } } " " package com.rs.lib.model; import com.rs.lib.game.WorldInfo; public class Friend { private Account account; private WorldInfo world; private boolean offline; public Friend(Account account, WorldInfo world, boolean offline) { this.account = account; this.world = world; this.offline = offline; } public Account getAccount() { return account; } public WorldInfo getWorld() { return world; } public boolean isOffline() { return offline; } public boolean onlineTo(Account player) { return account.onlineTo(player); } } " " package com.rs.lib.model; import java.util.HashMap; import java.util.Map; public class FriendsChat { private String name; private Map friendsChatRanks; private Rank rankToEnter = Rank.UNRANKED; private Rank rankToSpeak = Rank.UNRANKED; private Rank rankToKick = Rank.OWNER; private Rank rankToLS = Rank.FRIEND; private boolean coinshare; public enum Rank { UNRANKED(-1), FRIEND(0), RECRUIT(1), CORPORAL(2), SERGEANT(3), LIEUTENANT(4), CAPTAIN(5), GENERAL(6), OWNER(7), JMOD(127); private static Map MAP = new HashMap<>(); static { for (Rank r : Rank.values()) MAP.put(r.getId(), r); } public static Rank forId(int id) { return MAP.get(id); } private int id; private Rank(int id) { this.id = id; } public int getId() { return id; } } public FriendsChat() { friendsChatRanks = new HashMap<>(200); rankToKick = Rank.OWNER; rankToLS = Rank.UNRANKED; } public Rank getRank(String username) { Rank rank = getFriendsChatRanks().get(username); if (rank == null) return Rank.UNRANKED; return rank; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Map getFriendsChatRanks() { return friendsChatRanks; } public void setFriendsChatRanks(Map friendsChatRanks) { this.friendsChatRanks = friendsChatRanks; } public Rank getRankToEnter() { return rankToEnter; } public void setRankToEnter(Rank rankToEnter) { this.rankToEnter = rankToEnter; } public Rank getRankToSpeak() { return rankToSpeak; } public void setRankToSpeak(Rank rankToSpeak) { this.rankToSpeak = rankToSpeak; } public Rank getRankToKick() { return rankToKick; } public void setRankToKick(Rank rankToKick) { this.rankToKick = rankToKick; } public Rank getRankToLS() { return rankToLS; } public void setRankToLS(Rank rankToLS) { this.rankToLS = rankToLS; } public boolean isCoinshare() { return coinshare; } public void setCoinshare(boolean coinshare) { this.coinshare = coinshare; } public void setRank(String name, Rank rank) { if (rank == null) { getFriendsChatRanks().remove(name); return; } getFriendsChatRanks().put(name, rank); } } " " package com.rs.lib.model; import com.rs.lib.model.clan.ClanRank; public class MemberData { private ClanRank rank; private int job; private boolean banFromCitadel; private boolean banFromIsland; private boolean banFromKeep; private long joinDate; public MemberData(ClanRank rank) { this.rank = rank; joinDate = System.currentTimeMillis(); } public ClanRank getRank() { return rank; } public int getJob() { return job; } public void setJob(int job) { this.job = job; } public void setRank(ClanRank rank) { this.rank = rank; } public boolean isBanFromCitadel() { return banFromCitadel; } public void setBanFromCitadel(boolean banFromCitadel) { this.banFromCitadel = banFromCitadel; } public boolean isBanFromKeep() { return banFromKeep; } public void setBanFromKeep(boolean banFromKeep) { this.banFromKeep = banFromKeep; } public boolean isBanFromIsland() { return banFromIsland; } public void setBanFromIsland(boolean banFromIsland) { this.banFromIsland = banFromIsland; } public boolean firstWeek() { return System.currentTimeMillis() - joinDate < 7 * 24 * 60 * 60 * 1000; } } " " package com.rs.lib.model; import com.rs.lib.game.WorldInfo; public class MinimalSocial { private String username; private String displayName; private WorldInfo world; public MinimalSocial(Account account, WorldInfo world) { this.username = account.getUsername(); this.displayName = account.getDisplayName(); this.world = world; } public String getUsername() { return username; } public String getDisplayName() { return displayName; } public WorldInfo getWorld() { return world; } } " " package com.rs.lib.model; import java.util.HashSet; import java.util.Set; public class Social { private Set friends; private Set ignores; private transient Set tillLogoutIgnores; private byte status; private byte fcStatus; private String clanName; private boolean connectedToClan; private String currentFriendsChat; private String guestedClanChat; private FriendsChat friendsChat; public Social() { friends = new HashSet(200); ignores = new HashSet(100); this.friendsChat = new FriendsChat(); this.currentFriendsChat = ""help""; } public Set getFriends() { return friends; } public Set getIgnores() { return ignores; } public Set getTillLogoutIgnores() { return tillLogoutIgnores; } public byte getStatus() { return status; } public String getCurrentFriendsChat() { return currentFriendsChat; } public String getGuestedClanChat() { return guestedClanChat; } public FriendsChat getFriendsChat() { return friendsChat; } public void setStatus(int status) { this.status = (byte) status; } public void setCurrentFriendsChat(String currentFriendsChat) { this.currentFriendsChat = currentFriendsChat; } public void setGuestedClanChat(String guestedClanChat) { this.guestedClanChat = guestedClanChat; } public void setFriendsChat(FriendsChat friendsChat) { this.friendsChat = friendsChat; } public void addFriend(Account account) { friends.add(account.getUsername()); } public void addIgnore(Account account) { ignores.add(account.getUsername()); } public void removeFriend(Account account) { friends.remove(account.getUsername()); } public void removeIgnore(Account account) { ignores.remove(account.getUsername()); } public String getClanName() { return clanName; } public void setClanName(String clan) { this.clanName = clan; } public boolean isConnectedToClan() { return connectedToClan; } public void setConnectedToClan(boolean connectedToClan) { this.connectedToClan = connectedToClan; } public byte getFcStatus() { return fcStatus; } public void setFcStatus(int fcStatus) { this.fcStatus = (byte) fcStatus; } } " " package com.rs.lib.model.clan; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import com.rs.cache.loaders.ClanVarDefinitions; import com.rs.cache.loaders.ClanVarSettingsDefinitions; import com.rs.cache.loaders.EnumDefinitions; import com.rs.cache.loaders.cs2.CS2Type; import com.rs.lib.model.Account; import com.rs.lib.model.MemberData; import com.rs.lib.util.Logger; public class Clan { public static final int MAX_MEMBERS = 100; private String clanLeaderUsername; private String name; private Map members; private Set bannedUsers; private Map settings; private Map vars; private ClanRank ccChatRank; private ClanRank ccKickRank; private byte[] updateBlock; public Clan(String name, Account leader) { this.name = name; setDefaults(); this.members = new HashMap<>(); this.bannedUsers = new HashSet<>(); addMember(leader, ClanRank.OWNER); setClanLeaderUsername(leader.getUsername()); } public void setDefaults() { settings = new HashMap<>(); vars = new HashMap<>(); setCcChatRank(ClanRank.NONE); setCcKickRank(ClanRank.ADMIN); for (ClanSetting setting : ClanSetting.values()) if (setting.getDefault() != null) setSetting(setting, setting.getDefault()); } public void setMotifColor(int[] colors) { if (colors.length != 4) { Logger.error(Clan.class, ""setMotifColor"", ""Motif colors must be an array of size 4!""); return; } for (int i = 0;i < colors.length;i++) setMotifColor(i, colors[i]); } public void setMotifColor(int index, int color) { switch(index) { case 0 -> setSetting(ClanSetting.MOTIF_TOP_COLOR, color); case 1 -> setSetting(ClanSetting.MOTIF_BOTTOM_COLOR, color); case 2 -> setSetting(ClanSetting.MOTIF_PRIMARY_COLOR, color); case 3 -> setSetting(ClanSetting.MOTIF_SECONDARY_COLOR, color); } } public int getMotifTopIcon() { return (int) getSetting(ClanSetting.MOTIF_TOP_ICON); } public int getMotifBottomIcon() { return (int) getSetting(ClanSetting.MOTIF_BOTTOM_ICON); } public int[] getMotifColors() { return new int[] { (int) getSetting(ClanSetting.MOTIF_TOP_COLOR), (int) getSetting(ClanSetting.MOTIF_BOTTOM_COLOR), (int) getSetting(ClanSetting.MOTIF_PRIMARY_COLOR), (int) getSetting(ClanSetting.MOTIF_SECONDARY_COLOR) }; } public MemberData addMember(Account account, ClanRank rank) { MemberData member = new MemberData(rank); members.put(account.getUsername(), member); return member; } public void removeMember(String username) { members.remove(username); } public void setClanLeaderUsername(String username) { clanLeaderUsername = username; } public Map getMembers() { return members; } public Set getBannedUsers() { return bannedUsers; } public String getName() { return name; } public void switchRecruiting() { setSetting(ClanSetting.IS_RECRUITING, (int) getSetting(ClanSetting.IS_RECRUITING) == 0 ? 1 : 0); } public String getClanLeaderUsername() { return clanLeaderUsername; } public void setMotto(String motto) { setSetting(ClanSetting.MOTTO, motto); } public int[] getMotifTextures() { return new int[] { getMotifTexture((int) getSetting(ClanSetting.MOTIF_TOP_ICON)), getMotifTexture((int) getSetting(ClanSetting.MOTIF_BOTTOM_ICON)) }; } public static int getMotifTexture(int slotId) { return EnumDefinitions.getEnum(3685).getIntValue(slotId); } public byte[] getUpdateBlock() { return updateBlock; } public void setUpdateBlock(byte[] updateBlock) { this.updateBlock = updateBlock; } public Map getSettings() { if (settings == null) { settings = new HashMap<>(); setDefaults(); } return settings; } public Object getSetting(ClanSetting setting) { return getSetting(setting.getId()); } public Object getSetting(int id) { ClanVarSettingsDefinitions def = ClanVarSettingsDefinitions.getDefs(id); try { boolean varBit = def.baseVar != -1; if (varBit) { return getSettingBit(id); } else if (def.type == CS2Type.LONG) { if (getSettings().get(id) == null) return 0; if (getSettings().get(id) instanceof Double d) return d.intValue(); return (long) getSettings().get(id); } else if (def.type == CS2Type.INT) { if (getSettings().get(id) == null) return 0; if (getSettings().get(id) instanceof Double d) return d.intValue(); return (int) getSettings().get(id); } else if (def.type == CS2Type.STRING) { if (getSettings().get(id) == null) return null; return (String) getSettings().get(id); } } catch(Throwable e) { Logger.handle(Clan.class, ""getSetting"", e); } return null; } public int getSettingBit(ClanSetting setting) { return getSettingBit(setting.getId()); } public int getSettingBit(int id) { ClanVarSettingsDefinitions def = ClanVarSettingsDefinitions.getDefs(id); if (def.baseVar == -1) { Logger.error(Clan.class, ""getSettingBit"", ""Setting "" + id + "" is not a varbit.""); return 0; } int val = (int) getSetting(def.baseVar); int endMask = def.endBit == 31 ? -1 : (1 << def.endBit + 1) - 1; return Integer.valueOf((val & endMask) >>> def.startBit); } public void setSetting(ClanSetting setting, Object value) { try { boolean varBit = setting.getDef().baseVar != -1; if (varBit) { setSettingBit(setting.getId(), (int) value); } else if (setting.getDef().type == CS2Type.LONG) { setSettingLong(setting.getId(), (long) value); } else if (setting.getDef().type == CS2Type.INT) { setSettingInt(setting.getId(), (int) value); } else if (setting.getDef().type == CS2Type.STRING) { setSettingString(setting.getId(), (String) value); } } catch(Throwable e) { Logger.handle(Clan.class, ""setSetting"", e); } } public void setSettingInt(int varId, int value) { ClanVarSettingsDefinitions def = ClanVarSettingsDefinitions.getDefs(varId); if (def == null) { Logger.error(Clan.class, ""setSettingInt"", ""No def found for clan setting "" + varId); return; } if (def.type != CS2Type.INT) { Logger.error(Clan.class, ""setSettingInt"", ""Tried to set int value for "" + varId + "" which is "" + def.type); return; } if (def.baseVar != -1) { Logger.error(Clan.class, ""setSettingInt"", ""Setting "" + varId + "" should be a varbit.""); return; } getSettings().put(varId, value); } public void setSettingBit(int varId, int value) { ClanVarSettingsDefinitions def = ClanVarSettingsDefinitions.getDefs(varId); if (def == null) { Logger.error(Clan.class, ""setSettingBit"", ""No def found for clan var setting "" + varId); return; } if (def.type != CS2Type.INT) { Logger.error(Clan.class, ""setSettingBit"", ""Tried to set int value for "" + varId + "" which is "" + def.type); return; } if (def.baseVar == -1) { Logger.error(Clan.class, ""setSettingBit"", ""Var "" + varId + "" is not a valid varbit.""); return; } int startMask = (1 << def.startBit) - 1; int endMask = def.endBit == 31 ? -1 : (1 << def.endBit + 1) - 1; int mask = endMask ^ startMask; value <<= def.startBit; value &= mask; int orig = (int) getSetting(def.baseVar); orig &= ~mask; orig |= value; getSettings().put(def.baseVar, orig); } public void setSettingLong(int varId, long value) { ClanVarSettingsDefinitions def = ClanVarSettingsDefinitions.getDefs(varId); if (def == null) { Logger.error(Clan.class, ""setSettingLong"", ""No def found for clan var setting "" + varId); return; } if (def.type != CS2Type.LONG) { Logger.error(Clan.class, ""setSettingLong"", ""Tried to set long value for "" + varId + "" which is "" + def.type); return; } getSettings().put(varId, value); } public void setSettingString(int varId, String value) { ClanVarSettingsDefinitions def = ClanVarSettingsDefinitions.getDefs(varId); if (def == null) { Logger.error(Clan.class, ""setSettingString"", ""No def found for clan var setting "" + varId); return; } if (def.type != CS2Type.STRING) { Logger.error(Clan.class, ""setSettingString"", ""Tried to set string value for "" + varId + "" which is "" + def.type); return; } if (value.length() > 80) value = value.substring(0, 80); getSettings().put(varId, value); } public Map getVars() { if (vars == null) vars = new HashMap<>(); return vars; } public Object getVar(ClanVar var) { return getVar(var.getId()); } public Object getVar(int id) { ClanVarDefinitions def = ClanVarDefinitions.getDefs(id); try { boolean varBit = def.baseVar != -1; if (varBit) { return getVarBit(id); } else if (def.type == CS2Type.LONG) { if (getVars().get(id) == null) return 0; if (getVars().get(id) instanceof Double d) return d.intValue(); return (long) getVars().get(id); } else if (def.type == CS2Type.INT) { if (getVars().get(id) == null) return 0; if (getVars().get(id) instanceof Double d) return d.intValue(); return (int) getVars().get(id); } else if (def.type == CS2Type.STRING) { if (getVars().get(id) == null) return null; return (String) getVars().get(id); } } catch(Throwable e) { Logger.handle(Clan.class, ""getVar"", e); } return null; } public boolean hasPermissions(String username, ClanRank rank) { MemberData data = members.get(username); if (data == null) return false; return data.getRank().ordinal() >= rank.ordinal(); } public boolean hasPermissions(String username, ClanPermission permission) { return permission.hasPermission(this, getRank(username)); } public ClanRank getRank(String username) { MemberData data = members.get(username); if (data == null) return ClanRank.NONE; return data.getRank(); } public int getVarBit(ClanVar var) { return getVarBit(var.getId()); } public int getVarBit(int id) { ClanVarDefinitions def = ClanVarDefinitions.getDefs(id); if (def.baseVar == -1) { Logger.error(Clan.class, ""getVarBit"", ""Var "" + id + "" is not a varbit.""); return 0; } int val = (int) getVar(def.baseVar); int endMask = def.endBit == 31 ? -1 : (1 << def.endBit + 1) - 1; return Integer.valueOf((val & endMask) >>> def.startBit); } public void setVar(ClanVar var, Object value) { try { setVar(var.getId(), value); } catch(Throwable e) { Logger.handle(Clan.class, ""setVar"", e); } } public void setVar(int var, Object value) { ClanVarDefinitions def = ClanVarDefinitions.getDefs(var); try { boolean varBit = def.baseVar != -1; if (varBit) { setVarBit(var, (int) value); } else if (def.type == CS2Type.LONG) { setVarLong(var, (long) value); } else if (def.type == CS2Type.INT) { setVarInt(var, (int) value); } else if (def.type == CS2Type.STRING) { setVarString(var, (String) value); } } catch(Throwable e) { Logger.handle(Clan.class, ""setVar"", e); } } public void setVarInt(int varId, int value) { ClanVarDefinitions def = ClanVarDefinitions.getDefs(varId); if (def == null) { Logger.error(Clan.class, ""setVarInt"", ""No def found for clan var "" + varId); return; } if (def.type != CS2Type.INT) { Logger.error(Clan.class, ""setVarInt"", ""Tried to set int value for "" + varId + "" which is "" + def.type); return; } if (def.baseVar != -1) { Logger.error(Clan.class, ""setVarBit"", ""Var "" + varId + "" should be a varbit.""); return; } getVars().put(varId, value); } public void setVarBit(int varId, int value) { ClanVarDefinitions def = ClanVarDefinitions.getDefs(varId); if (def == null) { Logger.error(Clan.class, ""setVarBit"", ""No def found for clan var "" + varId); return; } if (def.type != CS2Type.INT) { Logger.error(Clan.class, ""setVarBit"", ""Tried to set int value for "" + varId + "" which is "" + def.type); return; } if (def.baseVar == -1) { Logger.error(Clan.class, ""setVarBit"", ""Var "" + varId + "" is not a valid varbit.""); return; } int startMask = (1 << def.startBit) - 1; int endMask = def.endBit == 31 ? -1 : (1 << def.endBit + 1) - 1; int mask = endMask ^ startMask; value <<= def.startBit; value &= mask; int orig = (int) getVar(def.baseVar); orig &= ~mask; orig |= value; getVars().put(def.baseVar, orig); } public void setVarLong(int varId, long value) { ClanVarDefinitions def = ClanVarDefinitions.getDefs(varId); if (def == null) { Logger.error(Clan.class, ""setVarLong"", ""No def found for clan var "" + varId); return; } if (def.type != CS2Type.LONG) { Logger.error(Clan.class, ""setVarLong"", ""Tried to set long value for "" + varId + "" which is "" + def.type); return; } getVars().put(varId, value); } public void setVarString(int varId, String value) { ClanVarDefinitions def = ClanVarDefinitions.getDefs(varId); if (def == null) { Logger.error(Clan.class, ""setVarLong"", ""No def found for clan var "" + varId); return; } if (def.type != CS2Type.STRING) { Logger.error(Clan.class, ""setVarLong"", ""Tried to set string value for "" + varId + "" which is "" + def.type); return; } if (value.length() > 80) value = value.substring(0, 80); getVars().put(varId, value); } public ClanRank getCcChatRank() { if (ccChatRank == null) setDefaults(); return ccChatRank; } public void setCcChatRank(ClanRank ccChatRank) { this.ccChatRank = ccChatRank; } public ClanRank getCcKickRank() { if (ccChatRank == null) setDefaults(); return ccKickRank; } public void setCcKickRank(ClanRank ccKickRank) { this.ccKickRank = ccKickRank; } } " " package com.rs.lib.model.clan; public enum ClanPermission { TALK_IN_CC(1571) { @Override boolean checkPermission(Clan clan, ClanRank rank) { return switch(rank) { case NONE -> false; case OWNER, JMOD -> true; default -> rank.ordinal() >= clan.getCcChatRank().ordinal(); }; } }, KICK_FROM_CC(1570) { @Override boolean checkPermission(Clan clan, ClanRank rank) { return switch(rank) { case NONE -> false; case OWNER, JMOD -> true; default -> rank.ordinal() >= clan.getCcKickRank().ordinal(); }; } }, INVITE(1576) { @Override boolean checkPermission(Clan clan, ClanRank rank) { return switch(rank) { case NONE -> false; case OWNER, JMOD -> true; default -> { int offset = rank.ordinal() - ClanRank.RECRUIT.ordinal(); int permissionBase = ClanSetting.RECRUIT_PERMISSION_INVITE.ordinal(); yield (int) clan.getSetting(ClanSetting.values()[permissionBase+offset]) == 1; } }; } }, LOCK_KEEP(1572) { @Override boolean checkPermission(Clan clan, ClanRank rank) { if (rank.ordinal() < ClanRank.ADMIN.ordinal()) return false; return switch(rank) { case OWNER, JMOD -> true; default -> { int offset = rank.ordinal() - ClanRank.ADMIN.ordinal(); int permissionBase = ClanSetting.ADMIN_PERMISSION_LOCK_KEEP.ordinal(); yield (int) clan.getSetting(ClanSetting.values()[permissionBase+offset]) == 1; } }; } }, ALLOWED_IN_KEEP(1573) { @Override boolean checkPermission(Clan clan, ClanRank rank) { return switch(rank) { case NONE -> false; case OWNER, JMOD -> true; default -> { int offset = rank.ordinal() - ClanRank.RECRUIT.ordinal(); int permissionBase = ClanSetting.RECRUIT_PERMISSION_ENTER_KEEP.ordinal(); yield (int) clan.getSetting(ClanSetting.values()[permissionBase+offset]) == 1; } }; } }, LOCK_CITADEL(1574) { @Override boolean checkPermission(Clan clan, ClanRank rank) { if (rank.ordinal() < ClanRank.ADMIN.ordinal()) return false; return switch(rank) { case NONE -> false; case OWNER, JMOD -> true; default -> { int offset = rank.ordinal() - ClanRank.ADMIN.ordinal(); int permissionBase = ClanSetting.ADMIN_PERMISSION_LOCK_CITADEL.ordinal(); yield (int) clan.getSetting(ClanSetting.values()[permissionBase+offset]) == 1; } }; } }, ALLOWED_IN_CITADEL(1575) { @Override boolean checkPermission(Clan clan, ClanRank rank) { return switch(rank) { case NONE -> false; case OWNER, JMOD -> true; default -> { int offset = rank.ordinal() - ClanRank.RECRUIT.ordinal(); int permissionBase = ClanSetting.RECRUIT_PERMISSION_ENTER_CITADEL.ordinal(); yield (int) clan.getSetting(ClanSetting.values()[permissionBase+offset]) == 1; } }; } }, START_BATTLE(1577) { @Override boolean checkPermission(Clan clan, ClanRank rank) { return switch(rank) { case NONE -> false; case OWNER, JMOD -> true; default -> { int offset = rank.ordinal() - ClanRank.RECRUIT.ordinal(); int permissionBase = ClanSetting.RECRUIT_PERMISSION_START_BATTLE.ordinal(); yield (int) clan.getSetting(ClanSetting.values()[permissionBase+offset]) == 1; } }; } }, LEAD_CLANWARS(1578) { @Override boolean checkPermission(Clan clan, ClanRank rank) { return switch(rank) { case NONE -> false; case OWNER, JMOD -> true; default -> { int offset = rank.ordinal() - ClanRank.RECRUIT.ordinal(); int permissionBase = ClanSetting.RECRUIT_PERMISSION_LEAD_CLANWARS.ordinal(); yield (int) clan.getSetting(ClanSetting.values()[permissionBase+offset]) == 1; } }; } }, CALL_VOTE(1579) { @Override boolean checkPermission(Clan clan, ClanRank rank) { return switch(rank) { case NONE -> false; case OWNER, JMOD -> true; default -> { int offset = rank.ordinal() - ClanRank.RECRUIT.ordinal(); int permissionBase = ClanSetting.RECRUIT_PERMISSION_CALL_VOTE.ordinal(); yield (int) clan.getSetting(ClanSetting.values()[permissionBase+offset]) == 1; } }; } }, BEGIN_MEETING(1580) { @Override boolean checkPermission(Clan clan, ClanRank rank) { return switch(rank) { case NONE -> false; case OWNER, JMOD -> true; default -> { int offset = rank.ordinal() - ClanRank.RECRUIT.ordinal(); int permissionBase = ClanSetting.RECRUIT_PERMISSION_BEGIN_MEETING.ordinal(); yield (int) clan.getSetting(ClanSetting.values()[permissionBase+offset]) == 1; } }; } }, PARTY_ROOM(1581) { @Override boolean checkPermission(Clan clan, ClanRank rank) { return switch(rank) { case NONE -> false; case OWNER, JMOD -> true; default -> { int offset = rank.ordinal() - ClanRank.RECRUIT.ordinal(); int permissionBase = ClanSetting.RECRUIT_PERMISSION_PARTY_ROOM.ordinal(); yield (int) clan.getSetting(ClanSetting.values()[permissionBase+offset]) == 1; } }; } }, THEATER(1582) { @Override boolean checkPermission(Clan clan, ClanRank rank) { return switch(rank) { case NONE -> false; case OWNER, JMOD -> true; default -> { int offset = rank.ordinal() - ClanRank.RECRUIT.ordinal(); int permissionBase = ClanSetting.RECRUIT_PERMISSION_THEATER.ordinal(); yield (int) clan.getSetting(ClanSetting.values()[permissionBase+offset]) == 1; } }; } }, NOTICE(1583) { @Override boolean checkPermission(Clan clan, ClanRank rank) { if (rank.ordinal() < ClanRank.ADMIN.ordinal()) return false; return switch(rank) { case NONE -> false; case OWNER, JMOD -> true; default -> { int offset = rank.ordinal() - ClanRank.ADMIN.ordinal(); int permissionBase = ClanSetting.ADMIN_PERMISSION_NOTICE.ordinal(); yield (int) clan.getSetting(ClanSetting.values()[permissionBase+offset]) == 1; } }; } }, SIGNPOST(1584) { @Override boolean checkPermission(Clan clan, ClanRank rank) { if (rank.ordinal() < ClanRank.ADMIN.ordinal()) return false; return switch(rank) { case NONE -> false; case OWNER, JMOD -> true; default -> { int offset = rank.ordinal() - ClanRank.ADMIN.ordinal(); int permissionBase = ClanSetting.ADMIN_PERMISSION_SIGNPOST.ordinal(); yield (int) clan.getSetting(ClanSetting.values()[permissionBase+offset]) == 1; } }; } }, EDIT_BATTLEFIELD(1585) { @Override boolean checkPermission(Clan clan, ClanRank rank) { return switch(rank) { case NONE -> false; case OWNER, JMOD -> true; case RECRUIT, CORPORAL, SERGEANT, LIEUTENANT, CAPTAIN, GENERAL -> { int offset = rank.ordinal() - ClanRank.RECRUIT.ordinal(); int permissionBase = ClanSetting.RECRUIT_PERMISSION_EDIT_BATTLEFIELD.ordinal(); yield (int) clan.getSetting(ClanSetting.values()[permissionBase+offset]) == 1; } case ADMIN, ORGANIZER, COORDINATOR, OVERSEER, DEPUTY_OWNER -> { int offset = rank.ordinal() - ClanRank.ADMIN.ordinal(); int permissionBase = ClanSetting.ADMIN_PERMISSION_EDIT_BATTLEFIELD.ordinal(); yield (int) clan.getSetting(ClanSetting.values()[permissionBase+offset]) == 1; } }; } }, CITADEL_UPGRADE(1586) { @Override boolean checkPermission(Clan clan, ClanRank rank) { if (rank.ordinal() < ClanRank.ADMIN.ordinal()) return false; return switch(rank) { case NONE -> false; case OWNER, JMOD -> true; default -> { int offset = rank.ordinal() - ClanRank.ADMIN.ordinal(); int permissionBase = ClanSetting.ADMIN_PERMISSION_CITADEL_UPGRADE.ordinal(); yield (int) clan.getSetting(ClanSetting.values()[permissionBase+offset]) == 1; } }; } }, CITADEL_DOWNGRADE(1587) { @Override boolean checkPermission(Clan clan, ClanRank rank) { if (rank.ordinal() < ClanRank.ADMIN.ordinal()) return false; return switch(rank) { case NONE -> false; case OWNER, JMOD -> true; default -> { int offset = rank.ordinal() - ClanRank.ADMIN.ordinal(); int permissionBase = ClanSetting.ADMIN_PERMISSION_CITADEL_DOWNGRADE.ordinal(); yield (int) clan.getSetting(ClanSetting.values()[permissionBase+offset]) == 1; } }; } }, RESOURCE_TRANSFER(1588) { @Override boolean checkPermission(Clan clan, ClanRank rank) { if (rank.ordinal() < ClanRank.ADMIN.ordinal()) return false; return switch(rank) { case NONE -> false; case OWNER, JMOD -> true; default -> { int offset = rank.ordinal() - ClanRank.ADMIN.ordinal(); int permissionBase = ClanSetting.ADMIN_PERMISSION_RESOURCE_TRANSFER.ordinal(); yield (int) clan.getSetting(ClanSetting.values()[permissionBase+offset]) == 1; } }; } }, RESOURCE_GATHER_GOALS(1589) { @Override boolean checkPermission(Clan clan, ClanRank rank) { if (rank.ordinal() < ClanRank.ADMIN.ordinal()) return false; return switch(rank) { case NONE -> false; case OWNER, JMOD -> true; default -> { int offset = rank.ordinal() - ClanRank.ADMIN.ordinal(); int permissionBase = ClanSetting.ADMIN_PERMISSION_RESOURCE_GATHER.ordinal(); yield (int) clan.getSetting(ClanSetting.values()[permissionBase+offset]) == 1; } }; } }, BUILD_TIME(1590) { @Override boolean checkPermission(Clan clan, ClanRank rank) { if (rank.ordinal() < ClanRank.OVERSEER.ordinal()) return false; return switch(rank) { case NONE -> false; case OWNER, JMOD -> true; default -> { int offset = rank.ordinal() - ClanRank.OVERSEER.ordinal(); int permissionBase = ClanSetting.OVERSEER_PERMISSION_BUILD_TIME.ordinal(); yield (int) clan.getSetting(ClanSetting.values()[permissionBase+offset]) == 1; } }; } }, CITADEL_LANGUAGE(1649) { @Override boolean checkPermission(Clan clan, ClanRank rank) { if (rank.ordinal() < ClanRank.OVERSEER.ordinal()) return false; return switch(rank) { case NONE -> false; case OWNER, JMOD -> true; default -> { int offset = rank.ordinal() - ClanRank.OVERSEER.ordinal(); int permissionBase = ClanSetting.OVERSEER_PERMISSION_CITADEL_LANGUAGE.ordinal(); yield (int) clan.getSetting(ClanSetting.values()[permissionBase+offset]) == 1; } }; } }, LOCK_PLOTS(1792) { @Override boolean checkPermission(Clan clan, ClanRank rank) { if (rank.ordinal() < ClanRank.ADMIN.ordinal()) return false; return switch(rank) { case NONE -> false; case OWNER, JMOD -> true; default -> { int offset = rank.ordinal() - ClanRank.ADMIN.ordinal(); int permissionBase = ClanSetting.ADMIN_PERMISSION_LOCK_PLOTS.ordinal(); yield (int) clan.getSetting(ClanSetting.values()[permissionBase+offset]) == 1; } }; } }, CHECK_RESOURCES(1793) { @Override boolean checkPermission(Clan clan, ClanRank rank) { return switch(rank) { case NONE -> false; case OWNER, JMOD -> true; default -> { int offset = rank.ordinal() - ClanRank.RECRUIT.ordinal(); int permissionBase = ClanSetting.RECRUIT_PERMISSION_CHECK_RESOURCES.ordinal(); yield (int) clan.getSetting(ClanSetting.values()[permissionBase+offset]) == 1; } }; } }; private int varc; ClanPermission(int varc) { this.varc = varc; } public int getVarc() { return varc; } public boolean hasPermission(Clan clan, ClanRank rank) { if (rank == ClanRank.OWNER) return true; return checkPermission(clan, rank); } abstract boolean checkPermission(Clan clan, ClanRank rank); } " " package com.rs.lib.model.clan; public enum ClanRank { NONE(-1), RECRUIT(0), CORPORAL(1), SERGEANT(2), LIEUTENANT(3), CAPTAIN(4), GENERAL(5), ADMIN(100), ORGANIZER(101), COORDINATOR(102), OVERSEER(103), DEPUTY_OWNER(125), OWNER(126), JMOD(127); public static ClanRank forId(int rank) { for (ClanRank r : ClanRank.values()) if (r.iconId == rank) return r; return RECRUIT; } private final int iconId; private ClanRank(int iconId) { this.iconId = iconId; } public int getIconId() { return iconId; } } " "package com.rs.lib.model.clan; import com.rs.cache.loaders.ClanVarSettingsDefinitions; public enum ClanSetting { /*0 int 2147483647*/GAME_TIME(0), /*1 string */ MOTTO(1), /*2 long 2147483647*/FORUM_QFC(2), /*4 int 1*/ IS_RECRUITING(4, 1), /*5 int 1*/ USES_CLANTIMEZONE(5), /*6 int 128*/ HOME_WORLD(6, 1), /*7 int 1024*/ NATIONAL_FLAG(7), /*8 int 1*/ GUESTS_CAN_ENTER_CC(8, 1), /*9 int 1*/ HIDE_MOTTO(9), /*10 int 1*/ HIDE_MOTIF(10), /*11 int 1*/ HIDE_FLAG(11), /*12 int 1*/ GUESTS_CAN_TALK_CC(12, 1), /*14 int 32768*/ MOTIF_TOP_ICON(14, 1), /*15 int 32768*/ MOTIF_BOTTOM_ICON(15, 2), /*16 int 2147483647*/MOTIF_TOP_COLOR(16, 6716), /*17 int 2147483647*/MOTIF_BOTTOM_COLOR(17, 6716), /*18 int 2147483647*/MOTIF_PRIMARY_COLOR(18, 42550), /*19 int 2147483647*/MOTIF_SECONDARY_COLOR(19, 39382), /*25 int 32*/ KEYWORD0_CATEGORY(25), /*26 int 512*/ KEYWORD0_INDEX(26), /*27 int 32*/ KEYWORD1_CATEGORY(27), /*28 int 512*/ KEYWORD1_INDEX(28), /*29 int 32*/ KEYWORD2_CATEGORY(29), /*30 int 512*/ KEYWORD2_INDEX(30), /*31 int 32*/ KEYWORD3_CATEGORY(31), /*32 int 512*/ KEYWORD3_INDEX(32), /*33 int 32*/ KEYWORD4_CATEGORY(33), /*34 int 512*/ KEYWORD4_INDEX(34), /*35 int 32*/ KEYWORD5_CATEGORY(35), /*36 int 512*/ KEYWORD5_INDEX(36), /*37 int 32*/ KEYWORD6_CATEGORY(37), /*38 int 512*/ KEYWORD6_INDEX(38), /*39 int 32*/ KEYWORD7_CATEGORY(39), /*40 int 512*/ KEYWORD7_INDEX(40), /*41 int 32*/ KEYWORD8_CATEGORY(41), /*42 int 512*/ KEYWORD8_INDEX(42), /*43 int 32*/ KEYWORD9_CATEGORY(43), /*44 int 512*/ KEYWORD9_INDEX(44), /*65 int 2147483647*/EVENT0_OPEN_TO_RANK(65), //3716 enum /*66 int 2147483647*/EVENT1_OPEN_TO_RANK(66), /*67 int 2147483647*/EVENT2_OPEN_TO_RANK(67), /*68 int 2147483647*/EVENT3_OPEN_TO_RANK(68), /*69 int 2147483647*/EVENT4_OPEN_TO_RANK(69), /*70 int 2147483647*/EVENT5_OPEN_TO_RANK(70), /*71 int 2147483647*/EVENT6_OPEN_TO_RANK(71), /*72 int 2147483647*/EVENT7_OPEN_TO_RANK(72), /*74 int 128*/ EVENT0_ACTIVITY_CATEGORY(74), //3687 -> 3689 enum /*75 int 128*/ EVENT1_ACTIVITY_CATEGORY(75), /*76 int 128*/ EVENT2_ACTIVITY_CATEGORY(76), /*77 int 128*/ EVENT3_ACTIVITY_CATEGORY(77), /*78 int 128*/ EVENT4_ACTIVITY_CATEGORY(78), /*79 int 128*/ EVENT5_ACTIVITY_CATEGORY(79), /*80 int 128*/ EVENT6_ACTIVITY_CATEGORY(80), /*81 int 128*/ EVENT7_ACTIVITY_CATEGORY(81), /*82 int 32768*/ EVENT0_LOCATION(82), //3696 enum for location /*83 int 32768*/ EVENT1_LOCATION(83), /*84 int 32768*/ EVENT2_LOCATION(84), /*85 int 32768*/ EVENT3_LOCATION(85), /*86 int 32768*/ EVENT4_LOCATION(86), /*87 int 32768*/ EVENT5_LOCATION(87), /*88 int 32768*/ EVENT6_LOCATION(88), /*89 int 32768*/ EVENT7_LOCATION(89), /*90 int 128*/ EVENT0_WORLD(90), /*91 int 128*/ EVENT1_WORLD(91), /*92 int 128*/ EVENT2_WORLD(92), /*93 int 128*/ EVENT3_WORLD(93), /*94 int 128*/ EVENT4_WORLD(94), /*95 int 128*/ EVENT5_WORLD(95), /*96 int 128*/ EVENT6_WORLD(96), /*97 int 128*/ EVENT7_WORLD(97), /*98 int 32768*/ EVENT0_RUNEDATE(98), /*99 int 32768*/ EVENT1_RUNEDATE(99), /*100 int 32768*/ EVENT2_RUNEDATE(100), /*101 int 32768*/ EVENT3_RUNEDATE(101), /*102 int 32768*/ EVENT4_RUNEDATE(102), /*103 int 32768*/ EVENT5_RUNEDATE(103), /*104 int 32768*/ EVENT6_RUNEDATE(104), /*105 int 32768*/ EVENT7_RUNEDATE(105), /*106 int 2048*/ EVENT0_TIME(106), //3695 enum for hours /*107 int 2048*/ EVENT1_TIME(107), /*108 int 2048*/ EVENT2_TIME(108), /*109 int 2048*/ EVENT3_TIME(109), /*110 int 2048*/ EVENT4_TIME(110), /*111 int 2048*/ EVENT5_TIME(111), /*112 int 2048*/ EVENT6_TIME(112), /*113 int 2048*/ EVENT7_TIME(113), /*114 int 32768*/ EVENT0_ACTIVITY_SLOT(114), //3689 enum /*115 int 32768*/ EVENT1_ACTIVITY_SLOT(115), /*116 int 32768*/ EVENT2_ACTIVITY_SLOT(116), /*117 int 32768*/ EVENT3_ACTIVITY_SLOT(117), /*118 int 32768*/ EVENT4_ACTIVITY_SLOT(118), /*119 int 32768*/ EVENT5_ACTIVITY_SLOT(119), /*120 int 32768*/ EVENT6_ACTIVITY_SLOT(120), /*121 int 32768*/ EVENT7_ACTIVITY_SLOT(121), /*122 long 2147483647*/EVENT0_FORUM_QFC(122), /*123 long 2147483647*/EVENT1_FORUM_QFC(123), /*124 long 2147483647*/EVENT2_FORUM_QFC(124), /*125 long 2147483647*/EVENT3_FORUM_QFC(125), /*126 long 2147483647*/EVENT4_FORUM_QFC(126), /*127 long 2147483647*/EVENT5_FORUM_QFC(127), /*128 long 2147483647*/EVENT6_FORUM_QFC(128), /*129 long 2147483647*/EVENT7_FORUM_QFC(129), /*130 int 8*/ HIGHLIGHTED_EVENT(130), /*131 int 1*/ //UNUSED by CS2 /*132 int 1*/ EVENT0_ATTENDANCE_MANDATORY(132), /*133 int 1*/ EVENT1_ATTENDANCE_MANDATORY(133), /*134 int 1*/ EVENT2_ATTENDANCE_MANDATORY(134), /*135 int 1*/ EVENT3_ATTENDANCE_MANDATORY(135), /*136 int 1*/ EVENT4_ATTENDANCE_MANDATORY(136), /*137 int 1*/ EVENT5_ATTENDANCE_MANDATORY(137), /*138 int 1*/ EVENT6_ATTENDANCE_MANDATORY(138), /*139 int 1*/ EVENT7_ATTENDANCE_MANDATORY(139), /*140 int 1*/ //UNUSED by CS2 /*146 int 1*/ ADMIN_PERMISSION_LOCK_KEEP(146, 1), /*147 int 1*/ ORGANIZER_PERMISSION_LOCK_KEEP(147, 1), /*148 int 1*/ COORDINATOR_PERMISSION_LOCK_KEEP(148, 1), /*149 int 1*/ OVERSEER_PERMISSION_LOCK_KEEP(149, 1), /*150 int 1*/ DEPUTY_OWNER_PERMISSION_LOCK_KEEP(150, 1), /*151 int 1*/ ADMIN_PERMISSION_LOCK_CITADEL(151, 1), /*152 int 1*/ ORGANIZER_PERMISSION_LOCK_CITADEL(152, 1), /*153 int 1*/ COORDINATOR_PERMISSION_LOCK_CITADEL(153, 1), /*154 int 1*/ OVERSEER_PERMISSION_LOCK_CITADEL(154, 1), /*155 int 1*/ DEPUTY_OWNER_PERMISSION_LOCK_CITADEL(155, 1), /*156 int 1*/ RECRUIT_PERMISSION_INVITE(156, 0), /*157 int 1*/ CORPORAL_PERMISSION_INVITE(157, 0), /*158 int 1*/ SERGEANT_PERMISSION_INVITE(158, 0), /*159 int 1*/ LIEUTENANT_PERMISSION_INVITE(159, 0), /*160 int 1*/ CAPTAIN_PERMISSION_INVITE(160, 0), /*161 int 1*/ GENERAL_PERMISSION_INVITE(161, 1), /*162 int 1*/ ADMIN_PERMISSION_INVITE(162, 1), /*163 int 1*/ ORGANIZER_PERMISSION_INVITE(163, 1), /*164 int 1*/ COORDINATOR_PERMISSION_INVITE(164, 1), /*165 int 1*/ OVERSEER_PERMISSION_INVITE(165, 1), /*166 int 1*/ DEPUTY_OWNER_PERMISSION_INVITE(166, 1), /*167 int 1*/ RECRUIT_PERMISSION_START_BATTLE(167, 1), /*168 int 1*/ CORPORAL_PERMISSION_START_BATTLE(168, 1), /*169 int 1*/ SERGEANT_PERMISSION_START_BATTLE(169, 1), /*170 int 1*/ LIEUTENANT_PERMISSION_START_BATTLE(170, 1), /*171 int 1*/ CAPTAIN_PERMISSION_START_BATTLE(171, 1), /*172 int 1*/ GENERAL_PERMISSION_START_BATTLE(172, 1), /*173 int 1*/ ADMIN_PERMISSION_START_BATTLE(173, 1), /*174 int 1*/ ORGANIZER_PERMISSION_START_BATTLE(174, 1), /*175 int 1*/ COORDINATOR_PERMISSION_START_BATTLE(175, 1), /*176 int 1*/ OVERSEER_PERMISSION_START_BATTLE(176, 1), /*177 int 1*/ DEPUTY_OWNER_PERMISSION_START_BATTLE(177, 1), /*178 int 1*/ RECRUIT_PERMISSION_LEAD_CLANWARS(178, 1), /*179 int 1*/ CORPORAL_PERMISSION_LEAD_CLANWARS(179, 1), /*180 int 1*/ SERGEANT_PERMISSION_LEAD_CLANWARS(180, 1), /*181 int 1*/ LIEUTENANT_PERMISSION_LEAD_CLANWARS(181, 1), /*182 int 1*/ CAPTAIN_PERMISSION_LEAD_CLANWARS(182, 1), /*183 int 1*/ GENERAL_PERMISSION_LEAD_CLANWARS(183, 1), /*184 int 1*/ ADMIN_PERMISSION_LEAD_CLANWARS(184, 1), /*185 int 1*/ ORGANIZER_PERMISSION_LEAD_CLANWARS(185, 1), /*186 int 1*/ COORDINATOR_PERMISSION_LEAD_CLANWARS(186, 1), /*187 int 1*/ OVERSEER_PERMISSION_LEAD_CLANWARS(187, 1), /*188 int 1*/ DEPUTY_OWNER_PERMISSION_LEAD_CLANWARS(188, 1), /*189 int 1*/ RECRUIT_PERMISSION_CALL_VOTE(189, 1), /*190 int 1*/ CORPORAL_PERMISSION_CALL_VOTE(190, 1), /*191 int 1*/ SERGEANT_PERMISSION_CALL_VOTE(191, 1), /*192 int 1*/ LIEUTENANT_PERMISSION_CALL_VOTE(192, 1), /*193 int 1*/ CAPTAIN_PERMISSION_CALL_VOTE(193, 1), /*194 int 1*/ GENERAL_PERMISSION_CALL_VOTE(194, 1), /*195 int 1*/ ADMIN_PERMISSION_CALL_VOTE(195, 1), /*196 int 1*/ ORGANIZER_PERMISSION_CALL_VOTE(196, 1), /*197 int 1*/ COORDINATOR_PERMISSION_CALL_VOTE(197, 1), /*198 int 1*/ OVERSEER_PERMISSION_CALL_VOTE(198, 1), /*199 int 1*/ DEPUTY_OWNER_PERMISSION_CALL_VOTE(199, 1), /*200 int 1*/ RECRUIT_PERMISSION_BEGIN_MEETING(200, 1), /*201 int 1*/ CORPORAL_PERMISSION_BEGIN_MEETING(201, 1), /*202 int 1*/ SERGEANT_PERMISSION_BEGIN_MEETING(202, 1), /*203 int 1*/ LIEUTENANT_PERMISSION_BEGIN_MEETING(203, 1), /*204 int 1*/ CAPTAIN_PERMISSION_BEGIN_MEETING(204, 1), /*205 int 1*/ GENERAL_PERMISSION_BEGIN_MEETING(205, 1), /*206 int 1*/ ADMIN_PERMISSION_BEGIN_MEETING(206, 1), /*207 int 1*/ ORGANIZER_PERMISSION_BEGIN_MEETING(207, 1), /*208 int 1*/ COORDINATOR_PERMISSION_BEGIN_MEETING(208, 1), /*209 int 1*/ OVERSEER_PERMISSION_BEGIN_MEETING(209, 1), /*210 int 1*/ DEPUTY_OWNER_PERMISSION_BEGIN_MEETING(210, 1), /*211 int 1*/ RECRUIT_PERMISSION_PARTY_ROOM(211, 1), /*212 int 1*/ CORPORAL_PERMISSION_PARTY_ROOM(212, 1), /*213 int 1*/ SERGEANT_PERMISSION_PARTY_ROOM(213, 1), /*214 int 1*/ LIEUTENANT_PERMISSION_PARTY_ROOM(214, 1), /*215 int 1*/ CAPTAIN_PERMISSION_PARTY_ROOM(215, 1), /*216 int 1*/ GENERAL_PERMISSION_PARTY_ROOM(216, 1), /*217 int 1*/ ADMIN_PERMISSION_PARTY_ROOM(217, 1), /*218 int 1*/ ORGANIZER_PERMISSION_PARTY_ROOM(218, 1), /*219 int 1*/ COORDINATOR_PERMISSION_PARTY_ROOM(219, 1), /*220 int 1*/ OVERSEER_PERMISSION_PARTY_ROOM(220, 1), /*221 int 1*/ DEPUTY_OWNER_PERMISSION_PARTY_ROOM(221, 1), /*222 int 1*/ RECRUIT_PERMISSION_THEATER(222, 1), /*223 int 1*/ CORPORAL_PERMISSION_THEATER(223, 1), /*224 int 1*/ SERGEANT_PERMISSION_THEATER(224, 1), /*225 int 1*/ LIEUTENANT_PERMISSION_THEATER(225, 1), /*226 int 1*/ CAPTAIN_PERMISSION_THEATER(226, 1), /*227 int 1*/ GENERAL_PERMISSION_THEATER(227, 1), /*228 int 1*/ ADMIN_PERMISSION_THEATER(228, 1), /*229 int 1*/ ORGANIZER_PERMISSION_THEATER(229, 1), /*230 int 1*/ COORDINATOR_PERMISSION_THEATER(230, 1), /*231 int 1*/ OVERSEER_PERMISSION_THEATER(231, 1), /*232 int 1*/ DEPUTY_OWNER_PERMISSION_THEATER(232, 1), /*233 int 1*/ ADMIN_PERMISSION_NOTICE(233, 1), /*234 int 1*/ ORGANIZER_PERMISSION_NOTICE(234, 1), /*235 int 1*/ COORDINATOR_PERMISSION_NOTICE(235, 1), /*236 int 1*/ OVERSEER_PERMISSION_NOTICE(236, 1), /*237 int 1*/ DEPUTY_OWNER_PERMISSION_NOTICE(237, 1), /*238 int 1*/ ADMIN_PERMISSION_SIGNPOST(238, 1), /*239 int 1*/ ORGANIZER_PERMISSION_SIGNPOST(239, 1), /*240 int 1*/ COORDINATOR_PERMISSION_SIGNPOST(240, 1), /*241 int 1*/ OVERSEER_PERMISSION_SIGNPOST(241, 1), /*242 int 1*/ DEPUTY_OWNER_PERMISSION_SIGNPOST(242, 1), /*243 int 1*/ ADMIN_PERMISSION_EDIT_BATTLEFIELD(243, 1), /*244 int 1*/ ORGANIZER_PERMISSION_EDIT_BATTLEFIELD(244, 1), /*245 int 1*/ COORDINATOR_PERMISSION_EDIT_BATTLEFIELD(245, 1), /*246 int 1*/ OVERSEER_PERMISSION_EDIT_BATTLEFIELD(246, 1), /*247 int 1*/ DEPUTY_OWNER_PERMISSION_EDIT_BATTLEFIELD(247, 1), /*248 int 1*/ ADMIN_PERMISSION_CITADEL_UPGRADE(248, 1), /*249 int 1*/ ORGANIZER_PERMISSION_CITADEL_UPGRADE(249, 1), /*250 int 1*/ COORDINATOR_PERMISSION_CITADEL_UPGRADE(250, 1), /*251 int 1*/ OVERSEER_PERMISSION_CITADEL_UPGRADE(251, 1), /*252 int 1*/ DEPUTY_OWNER_PERMISSION_CITADEL_UPGRADE(252, 1), /*253 int 1*/ ADMIN_PERMISSION_CITADEL_DOWNGRADE(253, 1), /*254 int 1*/ ORGANIZER_PERMISSION_CITADEL_DOWNGRADE(254, 1), /*255 int 1*/ COORDINATOR_PERMISSION_CITADEL_DOWNGRADE(255, 1), /*256 int 1*/ OVERSEER_PERMISSION_CITADEL_DOWNGRADE(256, 1), /*257 int 1*/ DEPUTY_OWNER_PERMISSION_CITADEL_DOWNGRADE(257, 1), /*258 int 1*/ ADMIN_PERMISSION_RESOURCE_TRANSFER(258, 1), /*259 int 1*/ ORGANIZER_PERMISSION_RESOURCE_TRANSFER(259, 1), /*260 int 1*/ COORDINATOR_PERMISSION_RESOURCE_TRANSFER(260, 1), /*261 int 1*/ OVERSEER_PERMISSION_RESOURCE_TRANSFER(261, 1), /*262 int 1*/ DEPUTY_OWNER_PERMISSION_RESOURCE_TRANSFER(262, 1), /*263 int 1*/ ADMIN_PERMISSION_RESOURCE_GATHER(263, 1), /*264 int 1*/ ORGANIZER_PERMISSION_RESOURCE_GATHER(264, 1), /*265 int 1*/ COORDINATOR_PERMISSION_RESOURCE_GATHER(265, 1), /*266 int 1*/ OVERSEER_PERMISSION_RESOURCE_GATHER(266, 1), /*267 int 1*/ DEPUTY_OWNER_PERMISSION_RESOURCE_GATHER(267, 1), /*268 int 1*/ OVERSEER_PERMISSION_BUILD_TIME(268, 1), /*269 int 1*/ DEPUTY_OWNER_PERMISSION_BUILD_TIME(269, 1), /*270 int 1*/ RECRUIT_PERMISSION_ENTER_KEEP(270, 1), /*271 int 1*/ CORPORAL_PERMISSION_ENTER_KEEP(271, 1), /*272 int 1*/ SERGEANT_PERMISSION_ENTER_KEEP(272, 1), /*273 int 1*/ LIEUTENANT_PERMISSION_ENTER_KEEP(273, 1), /*274 int 1*/ CAPTAIN_PERMISSION_ENTER_KEEP(274, 1), /*275 int 1*/ GENERAL_PERMISSION_ENTER_KEEP(275, 1), /*276 int 1*/ ADMIN_PERMISSION_ENTER_KEEP(276, 1), /*277 int 1*/ ORGANIZER_PERMISSION_ENTER_KEEP(277, 1), /*278 int 1*/ COORDINATOR_PERMISSION_ENTER_KEEP(278, 1), /*279 int 1*/ OVERSEER_PERMISSION_ENTER_KEEP(279, 1), /*280 int 1*/ DEPUTY_OWNER_PERMISSION_ENTER_KEEP(280, 1), /*281 int 1*/ RECRUIT_PERMISSION_ENTER_CITADEL(281, 1), /*282 int 1*/ CORPORAL_PERMISSION_ENTER_CITADEL(282, 1), /*283 int 1*/ SERGEANT_PERMISSION_ENTER_CITADEL(283, 1), /*284 int 1*/ LIEUTENANT_PERMISSION_ENTER_CITADEL(284, 1), /*285 int 1*/ CAPTAIN_PERMISSION_ENTER_CITADEL(285, 1), /*286 int 1*/ GENERAL_PERMISSION_ENTER_CITADEL(286, 1), /*287 int 1*/ ADMIN_PERMISSION_ENTER_CITADEL(287, 1), /*288 int 1*/ ORGANIZER_PERMISSION_ENTER_CITADEL(288, 1), /*289 int 1*/ COORDINATOR_PERMISSION_ENTER_CITADEL(289, 1), /*290 int 1*/ OVERSEER_PERMISSION_ENTER_CITADEL(290, 1), /*291 int 1*/ DEPUTY_OWNER_PERMISSION_ENTER_CITADEL(291, 1), /*292 int 2*/ GUEST_CITADEL_ACCESS(292, 1), //enum 4255 (keep, citadel, island) /*293 int 1*/ /*295 int 1*/ RECRUIT_PERMISSION_EDIT_BATTLEFIELD(295, 0), /*296 int 1*/ CORPORAL_PERMISSION_EDIT_BATTLEFIELD(296, 0), /*297 int 1*/ SERGEANT_PERMISSION_EDIT_BATTLEFIELD(297, 0), /*298 int 1*/ LIEUTENANT_PERMISSION_EDIT_BATTLEFIELD(298, 0), /*299 int 1*/ CAPTAIN_PERMISSION_EDIT_BATTLEFIELD(299, 0), /*300 int 1*/ GENERAL_PERMISSION_EDIT_BATTLEFIELD(300, 0), /*301 int 2147483647*/ /*302 int 1*/ /*303 int 1*/ /*304 int 1*/ /*305 int 1*/ OVERSEER_PERMISSION_CITADEL_LANGUAGE(305, 1), /*306 int 1*/ DEPUTY_OWNER_PERMISSION_CITADEL_LANGUAGE(306, 1), /*307 int 4*/ /*308 int 2147483647*/ /*310 int 1*/ /*311 int 1*/ ADMIN_PERMISSION_LOCK_PLOTS(311, 1), /*312 int 1*/ ORGANIZER_PERMISSION_LOCK_PLOTS(312, 1), /*313 int 1*/ COORDINATOR_PERMISSION_LOCK_PLOTS(313, 1), /*314 int 1*/ OVERSEER_PERMISSION_LOCK_PLOTS(314, 1), /*315 int 1*/ DEPUTY_OWNER_PERMISSION_LOCK_PLOTS(315, 1), /*316 int 1*/ RECRUIT_PERMISSION_CHECK_RESOURCES(316, 1), /*317 int 1*/ CORPORAL_PERMISSION_CHECK_RESOURCES(317, 1), /*318 int 1*/ SERGEANT_PERMISSION_CHECK_RESOURCES(318, 1), /*319 int 1*/ LIEUTENANT_PERMISSION_CHECK_RESOURCES(319, 1), /*320 int 1*/ CAPTAIN_PERMISSION_CHECK_RESOURCES(320, 1), /*321 int 1*/ GENERAL_PERMISSION_CHECK_RESOURCES(321, 1), /*322 int 1*/ ADMIN_PERMISSION_CHECK_RESOURCES(322, 1), /*323 int 1*/ ORGANIZER_PERMISSION_CHECK_RESOURCES(323, 1), /*324 int 1*/ COORDINATOR_PERMISSION_CHECK_RESOURCES(324, 1), /*325 int 1*/ OVERSEER_PERMISSION_CHECK_RESOURCES(325, 1), /*326 int 1*/ DEPUTY_OWNER_PERMISSION_CHECK_RESOURCES(326, 1), ; private int id; private Object defaultVal = null; ClanSetting(int id) { this.id = id; } ClanSetting(int id, Object defaultVal) { this.id = id; this.defaultVal = defaultVal; } public int getId() { return id; } public ClanVarSettingsDefinitions getDef() { return ClanVarSettingsDefinitions.getDefs(id); } public Object getDefault() { return defaultVal; } } " "package com.rs.lib.model.clan; import com.rs.cache.loaders.ClanVarDefinitions; public enum ClanVar { /*0 int 2147483647 */ /*1 int 2147483647 */ /*2 int 2147483647 */ /*3 int 2147483647 */ /*4 int 2147483647 */ /*5 int 2147483647 */ /*6 int 2147483647 */ /*7 int 2147483647 */ /*8 int 2147483647 */ /*9 int 2147483647 */ /*10 int 2147483647 */ /*11 int 2147483647 */ /*12 string -1 */ /*13 int 2147483647 */ /*14 string -1 */ /*15 int 2147483647 */ /*16 string -1 */ /*17 int 2147483647 */ /*18 string -1 */ /*19 int 2147483647 */ /*20 string -1 */ /*22 int 64 */ /*23 int 64 */ /*24 int 131072 */ /*26 int 64 */ /*27 int 64 */ /*28 int 131072 */ /*30 int 64 */ /*31 int 64 */ /*32 int 131072 */ /*34 int 64 */ /*35 int 64 */ /*36 int 131072 */ /*38 int 64 */ /*39 int 64 */ /*40 int 131072 */ /*42 int 64 */ /*43 int 64 */ /*44 int 131072 */ /*46 int 64 */ /*47 int 64 */ /*48 int 131072 */ /*50 int 64 */ /*51 int 64 */ /*52 int 131072 */ /*54 int 64 */ /*55 int 64 */ /*56 int 131072 */ /*58 int 64 */ /*59 int 64 */ /*60 int 131072 */ /*62 int 64 */ /*63 int 64 */ /*64 int 131072 */ /*66 int 64 */ /*67 int 64 */ /*68 int 131072 */ /*70 int 64 */ /*71 int 64 */ /*72 int 131072 */ /*74 int 64 */ /*75 int 64 */ /*76 int 131072 */ /*78 int 64 */ /*79 int 64 */ /*80 int 131072 */ /*82 int 64 */ /*83 int 64 */ /*84 int 131072 */ /*86 int 64 */ /*87 int 64 */ /*88 int 131072 */ /*90 int 64 */ /*91 int 64 */ /*92 int 131072 */ /*94 int 64 */ /*95 int 64 */ /*96 int 131072 */ /*98 int 64 */ /*99 int 64 */ /*100 int 131072 */ /*102 int 64 */ /*103 int 64 */ /*104 int 131072 */ /*106 int 64 */ /*107 int 64 */ /*108 int 131072 */ /*110 int 64 */ /*111 int 64 */ /*112 int 131072 */ /*114 int 64 */ /*115 int 64 */ /*116 int 131072 */ /*118 int 64 */ /*119 int 64 */ /*120 int 131072 */ /*122 int 64 */ /*123 int 64 */ /*124 int 131072 */ /*126 int 64 */ /*127 int 64 */ /*128 int 131072 */ /*130 int 64 */ /*131 int 64 */ /*132 int 131072 */ /*134 int 64 */ /*135 int 64 */ /*136 int 131072 */ /*138 int 64 */ /*139 int 64 */ /*140 int 131072 */ /*142 int 64 */ /*143 int 64 */ /*144 int 131072 */ /*146 int 64 */ /*147 int 64 */ /*148 int 131072 */ /*150 int 64 */ /*151 int 64 */ /*152 int 131072 */ /*154 int 64 */ /*155 int 64 */ /*156 int 131072 */ /*158 int 64 */ /*159 int 64 */ /*160 int 131072 */ /*162 int 64 */ /*163 int 64 */ /*164 int 131072 */ /*166 int 64 */ /*167 int 64 */ /*168 int 131072 */ /*170 int 64 */ /*171 int 64 */ /*172 int 131072 */ /*174 int 64 */ /*175 int 64 */ /*176 int 131072 */ /*178 int 64 */ /*179 int 64 */ /*180 int 131072 */ /*182 int 64 */ /*183 int 64 */ /*184 int 131072 */ /*186 int 64 */ /*187 int 64 */ /*188 int 131072 */ /*190 int 64 */ /*191 int 64 */ /*192 int 131072 */ /*194 int 64 */ /*195 int 64 */ /*196 int 131072 */ /*198 int 64 */ /*199 int 64 */ /*200 int 131072 */ /*202 int 64 */ /*203 int 64 */ /*204 int 131072 */ /*206 int 64 */ /*207 int 64 */ /*208 int 131072 */ /*210 int 64 */ /*211 int 64 */ /*212 int 131072 */ /*214 int 64 */ /*215 int 64 */ /*216 int 131072 */ /*218 int 64 */ /*219 int 64 */ /*220 int 131072 */ /*222 int 64 */ /*223 int 64 */ /*224 int 131072 */ /*226 int 64 */ /*227 int 64 */ /*228 int 131072 */ /*230 int 64 */ /*231 int 64 */ /*232 int 131072 */ /*234 int 64 */ /*235 int 64 */ /*236 int 131072 */ /*238 int 64 */ /*239 int 64 */ /*240 int 131072 */ /*242 int 64 */ /*243 int 64 */ /*244 int 131072 */ /*246 int 64 */ /*247 int 64 */ /*248 int 131072 */ /*250 int 64 */ /*251 int 64 */ /*252 int 131072 */ /*254 int 64 */ /*255 int 64 */ /*256 int 131072 */ /*258 int 64 */ /*259 int 64 */ /*260 int 131072 */ /*262 int 64 */ /*263 int 64 */ /*264 int 131072 */ /*266 int 64 */ /*267 int 64 */ /*268 int 131072 */ /*270 int 64 */ /*271 int 64 */ /*272 int 131072 */ /*274 int 64 */ /*275 int 64 */ /*276 int 131072 */ /*278 int 64 */ /*279 int 64 */ /*280 int 131072 */ /*282 int 64 */ /*283 int 64 */ /*284 int 131072 */ /*286 int 64 */ /*287 int 64 */ /*288 int 131072 */ /*290 int 64 */ /*291 int 64 */ /*292 int 131072 */ /*294 int 64 */ /*295 int 64 */ /*296 int 131072 */ /*298 int 64 */ /*299 int 64 */ /*300 int 131072 */ /*302 int 64 */ /*303 int 64 */ /*304 int 131072 */ /*306 int 64 */ /*307 int 64 */ /*308 int 131072 */ /*310 int 64 */ /*311 int 64 */ /*312 int 131072 */ /*314 int 64 */ /*315 int 64 */ /*316 int 131072 */ /*318 int 64 */ /*319 int 64 */ /*320 int 131072 */ /*322 int 64 */ /*323 int 64 */ /*324 int 131072 */ /*326 int 64 */ /*327 int 64 */ /*328 int 131072 */ /*330 int 64 */ /*331 int 64 */ /*332 int 131072 */ /*334 int 64 */ /*335 int 64 */ /*336 int 131072 */ /*338 int 64 */ /*339 int 64 */ /*340 int 131072 */ /*342 int 64 */ /*343 int 64 */ /*344 int 131072 */ /*346 int 64 */ /*347 int 64 */ /*348 int 131072 */ /*350 int 64 */ /*351 int 64 */ /*352 int 131072 */ /*354 int 64 */ /*355 int 64 */ /*356 int 131072 */ /*358 int 64 */ /*359 int 64 */ /*360 int 131072 */ /*362 int 64 */ /*363 int 64 */ /*364 int 131072 */ /*366 int 64 */ /*367 int 64 */ /*368 int 131072 */ /*370 int 64 */ /*371 int 64 */ /*372 int 131072 */ /*374 int 64 */ /*375 int 64 */ /*376 int 131072 */ /*378 int 64 */ /*379 int 64 */ /*380 int 131072 */ /*382 int 64 */ /*383 int 64 */ /*384 int 131072 */ /*386 int 64 */ /*387 int 64 */ /*388 int 131072 */ /*390 int 64 */ /*391 int 64 */ /*392 int 131072 */ /*394 int 64 */ /*395 int 64 */ /*396 int 131072 */ /*398 int 64 */ /*399 int 64 */ /*400 int 131072 */ /*402 int 64 */ /*403 int 64 */ /*404 int 131072 */ /*406 int 64 */ /*407 int 64 */ /*408 int 131072 */ /*410 int 64 */ /*411 int 64 */ /*412 int 131072 */ /*414 int 64 */ /*415 int 64 */ /*416 int 131072 */ /*418 int 64 */ /*419 int 64 */ /*420 int 131072 */ /*422 int 64 */ /*423 int 64 */ /*424 int 131072 */ /*426 int 64 */ /*427 int 64 */ /*428 int 131072 */ /*430 int 64 */ /*431 int 64 */ /*432 int 131072 */ /*434 int 64 */ /*435 int 64 */ /*436 int 131072 */ /*438 int 64 */ /*439 int 64 */ /*440 int 131072 */ /*442 int 64 */ /*443 int 64 */ /*444 int 131072 */ /*446 int 64 */ /*447 int 64 */ /*448 int 131072 */ /*450 int 64 */ /*451 int 64 */ /*452 int 131072 */ /*454 int 64 */ /*455 int 64 */ /*456 int 131072 */ /*458 int 64 */ /*459 int 64 */ /*460 int 131072 */ /*462 int 64 */ /*463 int 64 */ /*464 int 131072 */ /*466 int 64 */ /*467 int 64 */ /*468 int 131072 */ /*470 int 64 */ /*471 int 64 */ /*472 int 131072 */ /*474 int 64 */ /*475 int 64 */ /*476 int 131072 */ /*478 int 64 */ /*479 int 64 */ /*480 int 131072 */ /*482 int 64 */ /*483 int 64 */ /*484 int 131072 */ /*486 int 64 */ /*487 int 64 */ /*488 int 131072 */ /*490 int 64 */ /*491 int 64 */ /*492 int 131072 */ /*494 int 64 */ /*495 int 64 */ /*496 int 131072 */ /*498 int 64 */ /*499 int 64 */ /*500 int 131072 */ /*502 int 64 */ /*503 int 64 */ /*504 int 131072 */ /*506 int 64 */ /*507 int 64 */ /*508 int 131072 */ /*510 int 64 */ /*511 int 64 */ /*512 int 131072 */ /*514 int 64 */ /*515 int 64 */ /*516 int 131072 */ /*518 int 64 */ /*519 int 64 */ /*520 int 131072 */ /*522 int 64 */ /*523 int 64 */ /*524 int 131072 */ /*526 int 64 */ /*527 int 64 */ /*528 int 131072 */ /*530 int 64 */ /*531 int 64 */ /*532 int 131072 */ /*534 int 64 */ /*535 int 64 */ /*536 int 131072 */ /*538 int 64 */ /*539 int 64 */ /*540 int 131072 */ /*542 int 64 */ /*543 int 64 */ /*544 int 131072 */ /*546 int 64 */ /*547 int 64 */ /*548 int 131072 */ /*550 int 64 */ /*551 int 64 */ /*552 int 131072 */ /*554 int 64 */ /*555 int 64 */ /*556 int 131072 */ /*558 int 64 */ /*559 int 64 */ /*560 int 131072 */ /*562 int 64 */ /*563 int 64 */ /*564 int 131072 */ /*566 int 64 */ /*567 int 64 */ /*568 int 131072 */ /*570 int 64 */ /*571 int 64 */ /*572 int 131072 */ /*574 int 64 */ /*575 int 64 */ /*576 int 131072 */ /*578 int 64 */ /*579 int 64 */ /*580 int 131072 */ /*582 int 64 */ /*583 int 64 */ /*584 int 131072 */ /*586 int 64 */ /*587 int 64 */ /*588 int 131072 */ /*590 int 64 */ /*591 int 64 */ /*592 int 131072 */ /*594 int 64 */ /*595 int 64 */ /*596 int 131072 */ /*598 int 64 */ /*599 int 64 */ /*600 int 131072 */ /*602 int 64 */ /*603 int 64 */ /*604 int 131072 */ /*606 int 64 */ /*607 int 64 */ /*608 int 131072 */ /*610 int 64 */ /*611 int 64 */ /*612 int 131072 */ /*614 int 64 */ /*615 int 64 */ /*616 int 131072 */ /*618 int 64 */ /*619 int 64 */ /*620 int 131072 */ /*622 int 64 */ /*623 int 64 */ /*624 int 131072 */ /*626 int 64 */ /*627 int 64 */ /*628 int 131072 */ /*630 int 64 */ /*631 int 64 */ /*632 int 131072 */ /*634 int 64 */ /*635 int 64 */ /*636 int 131072 */ /*638 int 64 */ /*639 int 64 */ /*640 int 131072 */ /*642 int 64 */ /*643 int 64 */ /*644 int 131072 */ /*646 int 64 */ /*647 int 64 */ /*648 int 131072 */ /*650 int 64 */ /*651 int 64 */ /*652 int 131072 */ /*654 int 64 */ /*655 int 64 */ /*656 int 131072 */ /*658 int 64 */ /*659 int 64 */ /*660 int 131072 */ /*662 int 64 */ /*663 int 64 */ /*664 int 131072 */ /*666 int 64 */ /*667 int 64 */ /*668 int 131072 */ /*670 int 64 */ /*671 int 64 */ /*672 int 131072 */ /*674 int 64 */ /*675 int 64 */ /*676 int 131072 */ /*678 int 64 */ /*679 int 64 */ /*680 int 131072 */ /*682 int 64 */ /*683 int 64 */ /*684 int 131072 */ /*686 int 64 */ /*687 int 64 */ /*688 int 131072 */ /*690 int 64 */ /*691 int 64 */ /*692 int 131072 */ /*694 int 64 */ /*695 int 64 */ /*696 int 131072 */ /*698 int 64 */ /*699 int 64 */ /*700 int 131072 */ /*702 int 64 */ /*703 int 64 */ /*704 int 131072 */ /*706 int 64 */ /*707 int 64 */ /*708 int 131072 */ /*710 int 64 */ /*711 int 64 */ /*712 int 131072 */ /*714 int 64 */ /*715 int 64 */ /*716 int 131072 */ /*718 int 64 */ /*719 int 64 */ /*720 int 131072 */ /*722 int 64 */ /*723 int 64 */ /*724 int 131072 */ /*726 int 64 */ /*727 int 64 */ /*728 int 131072 */ /*730 int 64 */ /*731 int 64 */ /*732 int 131072 */ /*734 int 64 */ /*735 int 64 */ /*736 int 131072 */ /*738 int 64 */ /*739 int 64 */ /*740 int 131072 */ /*742 int 64 */ /*743 int 64 */ /*744 int 131072 */ /*746 int 64 */ /*747 int 64 */ /*748 int 131072 */ /*750 int 64 */ /*751 int 64 */ /*752 int 131072 */ /*754 int 64 */ /*755 int 64 */ /*756 int 131072 */ /*758 int 64 */ /*759 int 64 */ /*760 int 131072 */ /*762 int 64 */ /*763 int 64 */ /*764 int 131072 */ /*766 int 64 */ /*767 int 64 */ /*768 int 131072 */ /*770 int 64 */ /*771 int 64 */ /*772 int 131072 */ /*774 int 64 */ /*775 int 64 */ /*776 int 131072 */ /*778 int 64 */ /*779 int 64 */ /*780 int 131072 */ /*782 int 64 */ /*783 int 64 */ /*784 int 131072 */ /*786 int 64 */ /*787 int 64 */ /*788 int 131072 */ /*790 int 64 */ /*791 int 64 */ /*792 int 131072 */ /*794 int 64 */ /*795 int 64 */ /*796 int 131072 */ /*798 int 64 */ /*799 int 64 */ /*800 int 131072 */ /*802 int 64 */ /*803 int 64 */ /*804 int 131072 */ /*806 int 64 */ /*807 int 64 */ /*808 int 131072 */ /*810 int 64 */ /*811 int 64 */ /*812 int 131072 */ /*814 int 64 */ /*815 int 64 */ /*816 int 131072 */ /*818 int 64 */ /*819 int 64 */ /*820 int 131072 */ /*871 int 128 */ /*872 int 128 */ /*873 int 128 */ /*874 int 128 */ /*875 int 128 */ /*876 int 128 */ /*877 int 128 */ /*878 int 128 */ /*879 int 128 */ /*880 int 128 */ /*881 int 128 */ /*882 int 128 */ /*883 int 128 */ /*884 int 128 */ /*885 int 128 */ /*886 int 128 */ /*887 int 128 */ /*888 int 128 */ /*889 int 128 */ /*890 int 128 */ /*891 int 128 */ /*892 int 128 */ /*893 int 128 */ /*894 int 128 */ /*895 int 128 */ /*896 int 128 */ /*897 int 128 */ /*898 int 128 */ /*899 int 128 */ /*900 int 128 */ /*901 int 128 */ /*902 int 128 */ /*903 int 128 */ /*904 int 128 */ /*905 int 128 */ /*906 int 128 */ /*907 int 128 */ /*908 int 128 */ /*909 int 128 */ /*910 int 128 */ /*911 int 128 */ /*912 int 128 */ /*913 int 128 */ /*914 int 128 */ /*915 int 128 */ /*916 int 128 */ /*917 int 128 */ /*918 int 128 */ /*919 int 128 */ /*920 int 128 */ /*921 int 128 */ /*922 int 128 */ /*923 int 128 */ /*924 int 128 */ /*925 int 128 */ /*926 int 128 */ /*927 int 128 */ /*928 int 128 */ /*929 int 128 */ /*930 int 128 */ /*931 int 128 */ /*932 int 128 */ /*933 int 128 */ /*934 int 128 */ /*935 int 128 */ /*936 int 128 */ /*937 int 128 */ /*938 int 128 */ /*939 int 128 */ /*940 int 128 */ /*941 int 128 */ /*942 int 128 */ /*943 int 128 */ /*944 int 128 */ /*945 int 128 */ /*946 int 128 */ /*947 int 128 */ /*948 int 128 */ /*949 int 128 */ /*950 int 128 */ /*951 int 128 */ /*952 int 128 */ /*953 int 128 */ /*954 int 128 */ /*955 int 128 */ /*956 int 128 */ /*957 int 128 */ /*958 int 128 */ /*959 int 128 */ /*960 int 128 */ /*961 int 128 */ /*962 int 128 */ /*963 int 128 */ /*964 int 128 */ /*965 int 128 */ /*966 int 128 */ /*967 int 128 */ /*968 int 128 */ /*969 int 128 */ /*970 int 128 */ /*971 int 128 */ /*972 int 128 */ /*973 int 128 */ /*974 int 128 */ /*975 int 128 */ /*976 int 128 */ /*977 int 128 */ /*978 int 128 */ /*979 int 128 */ /*980 int 128 */ /*981 int 128 */ /*982 int 128 */ /*983 int 128 */ /*984 int 128 */ /*985 int 128 */ /*986 int 128 */ /*987 int 128 */ /*988 int 128 */ /*989 int 128 */ /*990 int 128 */ /*991 int 128 */ /*992 int 128 */ /*993 int 128 */ /*994 int 128 */ /*995 int 128 */ /*996 int 128 */ /*997 int 128 */ /*998 int 128 */ /*999 int 128 */ /*1000 int 128 */ /*1001 int 128 */ /*1002 int 128 */ /*1003 int 128 */ /*1004 int 128 */ /*1005 int 128 */ /*1006 int 128 */ /*1007 int 128 */ /*1008 int 128 */ /*1009 int 128 */ /*1010 int 128 */ /*1011 int 128 */ /*1012 int 128 */ /*1013 int 128 */ /*1014 int 128 */ /*1015 int 128 */ /*1016 int 128 */ /*1017 int 128 */ /*1018 int 128 */ /*1019 int 128 */ /*1020 int 128 */ /*1021 int 128 */ /*1022 int 128 */ /*1023 int 128 */ /*1024 int 128 */ /*1025 int 128 */ /*1026 int 128 */ /*1027 int 128 */ /*1028 int 128 */ /*1029 int 128 */ /*1030 int 128 */ /*1031 int 128 */ /*1032 int 128 */ /*1033 int 128 */ /*1034 int 128 */ /*1035 int 128 */ /*1036 int 128 */ /*1037 int 128 */ /*1038 int 128 */ /*1039 int 128 */ /*1040 int 128 */ /*1041 int 128 */ /*1042 int 128 */ /*1043 int 128 */ /*1044 int 128 */ /*1045 int 128 */ /*1046 int 128 */ /*1047 int 128 */ /*1048 int 128 */ /*1049 int 128 */ /*1050 int 128 */ /*1051 int 128 */ /*1052 int 128 */ /*1053 int 128 */ /*1054 int 128 */ /*1055 int 128 */ /*1056 int 128 */ /*1057 int 128 */ /*1058 int 128 */ /*1059 int 128 */ /*1060 int 128 */ /*1061 int 128 */ /*1062 int 128 */ /*1063 int 128 */ /*1064 int 128 */ /*1065 int 128 */ /*1066 int 128 */ /*1067 int 128 */ /*1068 int 128 */ /*1069 int 128 */ /*1070 int 128 */ /*1071 int 2147483647 */ /*1072 int 2147483647 */ /*1073 int 2147483647 */ /*1074 int 2147483647 */ /*1075 int 2147483647 */ /*1076 int 2147483647 */ /*1077 int 2147483647 */ /*1078 int 2147483647 */ /*1079 int 2147483647 */ /*1080 int 2147483647 */ /*1081 int 2147483647 */ /*1082 int 2147483647 */ /*1083 int 2147483647 */ /*1084 int 2147483647 */ /*1085 int 2147483647 */ /*1086 int 2147483647 */ /*1087 int 2147483647 */ /*1088 int 2147483647 */ /*1089 int 2147483647 */ /*1090 int 2147483647 */ /*1091 int 2147483647 */ /*1092 int 2147483647 */ /*1093 int 2147483647 */ /*1094 int 2147483647 */ /*1095 int 2147483647 */ /*1096 int 2147483647 */ /*1097 int 2147483647 */ /*1098 int 2147483647 */ /*1099 int 2147483647 */ /*1100 int 2147483647 */ /*1101 int 2147483647 */ /*1102 int 2147483647 */ /*1103 int 2147483647 */ /*1104 int 2147483647 */ /*1105 int 2147483647 */ /*1106 int 2147483647 */ /*1107 int 2147483647 */ /*1108 int 2147483647 */ /*1109 int 2147483647 */ /*1110 int 2147483647 */ /*1111 int 2147483647 */ /*1112 int 2147483647 */ /*1113 int 2147483647 */ /*1114 int 2147483647 */ /*1115 int 2147483647 */ /*1116 int 2147483647 */ /*1117 int 2147483647 */ /*1118 int 2147483647 */ /*1119 int 2147483647 */ /*1120 int 2147483647 */ /*1121 int 2147483647 */ /*1122 int 2147483647 */ /*1123 int 2147483647 */ /*1124 int 2147483647 */ /*1125 int 2147483647 */ /*1126 int 2147483647 */ /*1127 int 2147483647 */ /*1128 int 2147483647 */ /*1129 int 2147483647 */ /*1130 int 2147483647 */ /*1131 int 2147483647 */ /*1132 int 2147483647 */ /*1133 int 2147483647 */ /*1134 int 2147483647 */ /*1135 int 2147483647 */ /*1136 int 2147483647 */ /*1137 int 2147483647 */ /*1138 int 2147483647 */ /*1139 int 2147483647 */ /*1140 int 2147483647 */ /*1141 int 2147483647 */ /*1142 int 2147483647 */ /*1143 int 2147483647 */ /*1144 int 2147483647 */ /*1145 int 2147483647 */ /*1146 int 2147483647 */ /*1147 int 2147483647 */ /*1148 int 2147483647 */ /*1149 int 2147483647 */ /*1150 int 2147483647 */ /*1151 int 2147483647 */ /*1152 int 2147483647 */ /*1153 int 2147483647 */ /*1154 int 2147483647 */ /*1155 int 2147483647 */ /*1156 int 2147483647 */ /*1157 int 2147483647 */ /*1158 int 2147483647 */ /*1159 int 2147483647 */ /*1160 int 2147483647 */ /*1161 int 2147483647 */ /*1162 int 2147483647 */ /*1163 int 2147483647 */ /*1164 int 2147483647 */ /*1165 int 2147483647 */ /*1166 int 2147483647 */ /*1167 int 2147483647 */ /*1168 int 2147483647 */ /*1169 int 2147483647 */ /*1170 int 2147483647 */ /*1171 int 2147483647 */ /*1172 int 2147483647 */ /*1173 int 2147483647 */ /*1174 int 2147483647 */ /*1175 int 2147483647 */ /*1176 int 2147483647 */ /*1177 int 2147483647 */ /*1178 int 2147483647 */ /*1179 int 2147483647 */ /*1180 int 2147483647 */ /*1181 int 2147483647 */ /*1182 int 2147483647 */ /*1183 int 2147483647 */ /*1184 int 2147483647 */ /*1185 int 2147483647 */ /*1186 int 2147483647 */ /*1187 int 2147483647 */ /*1188 int 2147483647 */ /*1189 int 2147483647 */ /*1190 int 2147483647 */ /*1191 int 2147483647 */ /*1192 int 2147483647 */ /*1193 int 2147483647 */ /*1194 int 2147483647 */ /*1195 int 2147483647 */ /*1196 int 2147483647 */ /*1197 int 2147483647 */ /*1198 int 2147483647 */ /*1199 int 2147483647 */ /*1200 int 2147483647 */ /*1201 int 2147483647 */ /*1202 int 2147483647 */ /*1203 int 2147483647 */ /*1204 int 2147483647 */ /*1205 int 2147483647 */ /*1206 int 2147483647 */ /*1207 int 2147483647 */ /*1208 int 2147483647 */ /*1209 int 2147483647 */ /*1210 int 2147483647 */ /*1211 int 2147483647 */ /*1212 int 2147483647 */ /*1213 int 2147483647 */ /*1214 int 2147483647 */ /*1215 int 2147483647 */ /*1216 int 2147483647 */ /*1217 int 2147483647 */ /*1218 int 2147483647 */ /*1219 int 2147483647 */ /*1220 int 2147483647 */ /*1221 int 2147483647 */ /*1222 int 2147483647 */ /*1223 int 2147483647 */ /*1224 int 2147483647 */ /*1225 int 2147483647 */ /*1226 int 2147483647 */ /*1227 int 2147483647 */ /*1228 int 2147483647 */ /*1229 int 2147483647 */ /*1230 int 2147483647 */ /*1231 int 2147483647 */ /*1232 int 2147483647 */ /*1233 int 2147483647 */ /*1234 int 2147483647 */ /*1235 int 2147483647 */ /*1236 int 2147483647 */ /*1237 int 2147483647 */ /*1238 int 2147483647 */ /*1239 int 2147483647 */ /*1240 int 2147483647 */ /*1241 int 2147483647 */ /*1242 int 2147483647 */ /*1243 int 2147483647 */ /*1244 int 2147483647 */ /*1245 int 2147483647 */ /*1246 int 2147483647 */ /*1247 int 2147483647 */ /*1248 int 2147483647 */ /*1249 int 2147483647 */ /*1250 int 2147483647 */ /*1251 int 2147483647 */ /*1252 int 2147483647 */ /*1253 int 2147483647 */ /*1254 int 2147483647 */ /*1255 int 2147483647 */ /*1256 int 2147483647 */ /*1257 int 2147483647 */ /*1258 int 2147483647 */ /*1259 int 2147483647 */ /*1260 int 2147483647 */ /*1261 int 2147483647 */ /*1262 int 2147483647 */ /*1263 int 2147483647 */ /*1264 int 2147483647 */ /*1265 int 2147483647 */ /*1266 int 2147483647 */ /*1267 int 2147483647 */ /*1268 int 2147483647 */ /*1269 int 2147483647 */ /*1270 int 2147483647 */ /*1271 int 2147483647 */ /*1272 int 2147483647 */ /*1273 int 2147483647 */ /*1274 int 2147483647 */ /*1275 int 2147483647 */ /*1276 int 2147483647 */ /*1277 int 2147483647 */ /*1278 int 2147483647 */ /*1279 int 2147483647 */ /*1280 int 2147483647 */ /*1281 int 2147483647 */ /*1282 int 2147483647 */ /*1283 int 2147483647 */ /*1284 int 2147483647 */ /*1285 int 2147483647 */ /*1286 int 2147483647 */ /*1287 int 2147483647 */ /*1288 int 2147483647 */ /*1289 int 2147483647 */ /*1290 int 2147483647 */ /*1291 int 2147483647 */ /*1292 int 2147483647 */ /*1293 int 2147483647 */ /*1294 int 2147483647 */ /*1295 int 2147483647 */ /*1296 int 2147483647 */ /*1297 int 2147483647 */ /*1298 int 2147483647 */ /*1299 int 2147483647 */ /*1300 int 2147483647 */ /*1301 int 2147483647 */ /*1302 int 2147483647 */ /*1303 int 2147483647 */ /*1304 int 2147483647 */ /*1305 int 2147483647 */ /*1306 int 2147483647 */ /*1307 int 2147483647 */ /*1308 int 2147483647 */ /*1309 int 2147483647 */ /*1310 int 2147483647 */ /*1311 int 2147483647 */ /*1312 int 2147483647 */ /*1313 int 2147483647 */ /*1314 int 2147483647 */ /*1315 int 2147483647 */ /*1316 int 2147483647 */ /*1317 int 2147483647 */ /*1318 int 2147483647 */ /*1319 int 2147483647 */ /*1320 int 2147483647 */ /*1321 int 2147483647 */ /*1322 int 2147483647 */ /*1323 int 2147483647 */ /*1324 int 2147483647 */ /*1325 int 2147483647 */ /*1326 int 2147483647 */ /*1327 int 2147483647 */ /*1328 int 2147483647 */ /*1329 int 2147483647 */ /*1330 int 2147483647 */ /*1331 int 2147483647 */ /*1332 int 2147483647 */ /*1333 int 2147483647 */ /*1334 int 2147483647 */ /*1335 int 2147483647 */ /*1336 int 2147483647 */ /*1337 int 2147483647 */ /*1338 int 2147483647 */ /*1339 int 2147483647 */ /*1340 int 2147483647 */ /*1341 int 2147483647 */ /*1342 int 2147483647 */ /*1343 int 2147483647 */ /*1344 int 2147483647 */ /*1345 int 2147483647 */ /*1346 int 2147483647 */ /*1347 int 2147483647 */ /*1348 int 2147483647 */ /*1349 int 2147483647 */ /*1350 int 2147483647 */ /*1351 int 2147483647 */ /*1352 int 2147483647 */ /*1353 int 2147483647 */ /*1354 int 2147483647 */ /*1355 int 2147483647 */ /*1356 int 2147483647 */ /*1357 int 2147483647 */ /*1358 int 2147483647 */ /*1359 int 2147483647 */ /*1360 int 2147483647 */ /*1361 int 2147483647 */ /*1362 int 2147483647 */ /*1363 int 2147483647 */ /*1364 int 2147483647 */ /*1365 int 2147483647 */ /*1366 int 2147483647 */ /*1367 int 2147483647 */ /*1368 int 2147483647 */ /*1369 int 2147483647 */ /*1370 int 2147483647 */ /*1371 int 2147483647 */ /*1372 int 2147483647 */ /*1373 int 2147483647 */ /*1374 int 2147483647 */ /*1375 int 2147483647 */ /*1376 int 2147483647 */ /*1377 int 2147483647 */ /*1378 int 2147483647 */ /*1379 int 2147483647 */ /*1380 int 2147483647 */ /*1381 int 2147483647 */ /*1382 int 2147483647 */ /*1383 int 2147483647 */ /*1384 int 2147483647 */ /*1385 int 2147483647 */ /*1386 int 2147483647 */ /*1387 int 2147483647 */ /*1388 int 2147483647 */ /*1389 int 2147483647 */ /*1390 int 2147483647 */ /*1391 int 2147483647 */ /*1392 int 2147483647 */ /*1393 int 2147483647 */ /*1394 int 2147483647 */ /*1395 int 2147483647 */ /*1396 int 2147483647 */ /*1397 int 2147483647 */ /*1398 int 2147483647 */ /*1399 int 2147483647 */ /*1400 int 2147483647 */ /*1401 int 2147483647 */ /*1402 int 2147483647 */ /*1403 int 2147483647 */ /*1404 int 2147483647 */ /*1405 int 2147483647 */ /*1406 int 2147483647 */ /*1407 int 2147483647 */ /*1408 int 2147483647 */ /*1409 int 2147483647 */ /*1410 int 2147483647 */ /*1411 int 2147483647 */ /*1412 int 2147483647 */ /*1413 int 2147483647 */ /*1414 int 2147483647 */ /*1415 int 2147483647 */ /*1416 int 2147483647 */ /*1417 int 2147483647 */ /*1418 int 2147483647 */ /*1419 int 2147483647 */ /*1420 int 2147483647 */ /*1421 int 2147483647 */ /*1422 int 2147483647 */ /*1423 int 2147483647 */ /*1424 int 2147483647 */ /*1425 int 2147483647 */ /*1426 int 2147483647 */ /*1427 int 2147483647 */ /*1428 int 2147483647 */ /*1429 int 2147483647 */ /*1430 int 2147483647 */ /*1431 int 2147483647 */ /*1432 int 2147483647 */ /*1433 int 2147483647 */ /*1434 int 2147483647 */ /*1435 int 2147483647 */ /*1436 int 2147483647 */ /*1437 int 2147483647 */ /*1438 int 2147483647 */ /*1439 int 2147483647 */ /*1440 int 2147483647 */ /*1441 int 2147483647 */ /*1442 int 2147483647 */ /*1443 int 2147483647 */ /*1444 int 2147483647 */ /*1445 int 2147483647 */ /*1446 int 2147483647 */ /*1447 int 2147483647 */ /*1448 int 2147483647 */ /*1449 int 2147483647 */ /*1450 int 2147483647 */ /*1451 int 2147483647 */ /*1452 int 2147483647 */ /*1453 int 2147483647 */ /*1454 int 2147483647 */ /*1455 int 2147483647 */ /*1456 int 2147483647 */ /*1457 int 2147483647 */ /*1458 int 2147483647 */ /*1459 int 2147483647 */ /*1460 int 2147483647 */ /*1461 int 2147483647 */ /*1462 int 2147483647 */ /*1463 int 2147483647 */ /*1464 int 2147483647 */ /*1465 int 2147483647 */ /*1466 int 2147483647 */ /*1467 int 2147483647 */ /*1468 int 2147483647 */ /*1469 int 2147483647 */ /*1470 int 2147483647 */ /*1471 int 2147483647 */ /*1472 int 2147483647 */ /*1473 int 2147483647 */ /*1474 int 2147483647 */ /*1475 int 2147483647 */ /*1476 int 2147483647 */ /*1477 int 2147483647 */ /*1478 int 2147483647 */ /*1479 int 2147483647 */ /*1480 int 2147483647 */ /*1481 int 2147483647 */ /*1482 int 2147483647 */ /*1483 int 2147483647 */ /*1484 int 2147483647 */ /*1485 int 2147483647 */ /*1486 int 2147483647 */ /*1487 int 2147483647 */ /*1488 int 2147483647 */ /*1489 int 2147483647 */ /*1490 int 2147483647 */ /*1491 int 2147483647 */ /*1492 int 2147483647 */ /*1493 int 2147483647 */ /*1494 int 2147483647 */ /*1495 int 2147483647 */ /*1496 int 2147483647 */ /*1497 int 2147483647 */ /*1498 int 2147483647 */ /*1499 int 2147483647 */ /*1500 int 2147483647 */ /*1501 int 2147483647 */ /*1502 int 2147483647 */ /*1503 int 2147483647 */ /*1504 int 2147483647 */ /*1505 int 2147483647 */ /*1506 int 2147483647 */ /*1507 int 2147483647 */ /*1508 int 2147483647 */ /*1509 int 2147483647 */ /*1510 int 2147483647 */ /*1511 int 2147483647 */ /*1512 int 2147483647 */ /*1513 int 2147483647 */ /*1514 int 2147483647 */ /*1515 int 2147483647 */ /*1516 int 2147483647 */ /*1517 int 2147483647 */ /*1518 int 2147483647 */ /*1519 int 2147483647 */ /*1520 int 2147483647 */ /*1521 int 2147483647 */ /*1522 int 2147483647 */ /*1523 int 2147483647 */ /*1524 int 2147483647 */ /*1525 int 2147483647 */ /*1526 int 2147483647 */ /*1527 int 2147483647 */ /*1528 int 2147483647 */ /*1529 int 2147483647 */ /*1530 int 2147483647 */ /*1531 int 2147483647 */ /*1532 int 2147483647 */ /*1533 int 2147483647 */ /*1534 int 2147483647 */ /*1535 int 2147483647 */ /*1536 int 2147483647 */ /*1537 int 2147483647 */ /*1538 int 2147483647 */ /*1539 int 2147483647 */ /*1540 int 2147483647 */ /*1541 int 2147483647 */ /*1542 int 2147483647 */ /*1543 int 2147483647 */ /*1544 int 2147483647 */ /*1545 int 2147483647 */ /*1546 int 2147483647 */ /*1547 int 2147483647 */ /*1548 int 2147483647 */ /*1549 int 2147483647 */ /*1550 int 2147483647 */ /*1551 int 2147483647 */ /*1552 int 2147483647 */ /*1553 int 2147483647 */ /*1554 int 2147483647 */ /*1555 int 2147483647 */ /*1556 int 2147483647 */ /*1557 int 2147483647 */ /*1558 int 2147483647 */ /*1559 int 2147483647 */ /*1560 int 2147483647 */ /*1561 int 2147483647 */ /*1562 int 2147483647 */ /*1563 int 2147483647 */ /*1564 int 2147483647 */ /*1565 int 2147483647 */ /*1566 int 2147483647 */ /*1567 int 2147483647 */ /*1568 int 2147483647 */ /*1569 int 2147483647 */ /*1570 int 2147483647 */ /*1571 int 2147483647 */ /*1572 int 2147483647 */ /*1573 int 2147483647 */ /*1574 int 2147483647 */ /*1575 int 2147483647 */ /*1576 int 2147483647 */ /*1577 int 2147483647 */ /*1578 int 2147483647 */ /*1579 int 2147483647 */ /*1580 int 2147483647 */ /*1581 int 2147483647 */ /*1582 int 2147483647 */ /*1583 int 2147483647 */ /*1584 int 2147483647 */ /*1585 int 2147483647 */ /*1586 int 2147483647 */ /*1587 int 2147483647 */ /*1588 int 2147483647 */ /*1589 int 2147483647 */ /*1590 int 2147483647 */ /*1591 int 2147483647 */ /*1592 int 2147483647 */ /*1593 int 2147483647 */ /*1594 int 2147483647 */ /*1595 int 2147483647 */ /*1596 int 2147483647 */ /*1597 int 2147483647 */ /*1598 int 2147483647 */ /*1599 int 2147483647 */ /*1600 int 2147483647 */ /*1601 int 2147483647 */ /*1602 int 2147483647 */ /*1603 int 2147483647 */ /*1604 int 2147483647 */ /*1605 int 2147483647 */ /*1606 int 2147483647 */ /*1607 int 2147483647 */ /*1608 int 2147483647 */ /*1609 int 2147483647 */ /*1610 int 2147483647 */ /*1611 int 2147483647 */ /*1612 int 2147483647 */ /*1613 int 2147483647 */ /*1614 int 2147483647 */ /*1615 int 2147483647 */ /*1616 int 2147483647 */ /*1617 int 2147483647 */ /*1618 int 2147483647 */ /*1619 int 2147483647 */ /*1620 int 2147483647 */ /*1621 int 2147483647 */ /*1622 int 2147483647 */ /*1623 int 2147483647 */ /*1624 int 2147483647 */ /*1625 int 2147483647 */ /*1626 int 2147483647 */ /*1627 int 2147483647 */ /*1628 int 2147483647 */ /*1629 int 2147483647 */ /*1630 int 2147483647 */ /*1631 int 2147483647 */ /*1632 int 2147483647 */ /*1633 int 2147483647 */ /*1634 int 2147483647 */ /*1635 int 2147483647 */ /*1636 int 2147483647 */ /*1637 int 2147483647 */ /*1638 int 2147483647 */ /*1639 int 2147483647 */ /*1640 int 2147483647 */ /*1641 int 2147483647 */ /*1642 int 2147483647 */ /*1643 int 2147483647 */ /*1644 int 2147483647 */ /*1645 int 2147483647 */ /*1646 int 2147483647 */ /*1647 int 2147483647 */ /*1648 int 2147483647 */ /*1649 int 2147483647 */ /*1650 int 2147483647 */ /*1651 int 2147483647 */ /*1652 int 2147483647 */ /*1653 int 2147483647 */ /*1654 int 2147483647 */ /*1655 int 2147483647 */ /*1656 int 2147483647 */ /*1657 int 2147483647 */ /*1658 int 2147483647 */ /*1659 int 2147483647 */ /*1660 int 2147483647 */ /*1661 int 2147483647 */ /*1662 int 2147483647 */ /*1663 int 2147483647 */ /*1664 int 2147483647 */ /*1665 int 2147483647 */ /*1666 int 2147483647 */ /*1667 int 2147483647 */ /*1668 int 2147483647 */ /*1669 int 2147483647 */ /*1670 int 2147483647 */ /*1671 int 2147483647 */ /*1672 int 2147483647 */ /*1673 int 2147483647 */ /*1674 int 2147483647 */ /*1675 int 2147483647 */ /*1676 int 2147483647 */ /*1677 int 2147483647 */ /*1678 int 2147483647 */ /*1679 int 2147483647 */ /*1680 int 2147483647 */ /*1681 int 2147483647 */ /*1682 int 2147483647 */ /*1683 int 2147483647 */ /*1684 int 2147483647 */ /*1685 int 2147483647 */ /*1686 int 2147483647 */ /*1687 int 2147483647 */ /*1688 int 2147483647 */ /*1689 int 2147483647 */ /*1690 int 2147483647 */ /*1691 int 2147483647 */ /*1692 int 2147483647 */ /*1693 int 2147483647 */ /*1694 int 2147483647 */ /*1695 int 2147483647 */ /*1696 int 2147483647 */ /*1697 int 2147483647 */ /*1698 int 2147483647 */ /*1699 int 2147483647 */ /*1700 int 2147483647 */ /*1701 int 2147483647 */ /*1702 int 2147483647 */ /*1703 int 2147483647 */ /*1704 int 2147483647 */ /*1705 int 2147483647 */ /*1706 int 2147483647 */ /*1707 int 2147483647 */ /*1708 int 2147483647 */ /*1709 int 2147483647 */ /*1710 int 2147483647 */ /*1711 int 2147483647 */ /*1712 int 2147483647 */ /*1713 int 2147483647 */ /*1714 int 2147483647 */ /*1715 int 2147483647 */ /*1716 int 2147483647 */ /*1717 int 2147483647 */ /*1718 int 2147483647 */ /*1719 int 2147483647 */ /*1720 int 2147483647 */ /*1721 int 2147483647 */ /*1722 int 2147483647 */ /*1723 int 2147483647 */ /*1724 int 2147483647 */ /*1725 int 2147483647 */ /*1726 int 2147483647 */ /*1727 int 2147483647 */ /*1728 int 2147483647 */ /*1729 int 2147483647 */ /*1730 int 2147483647 */ /*1731 int 2147483647 */ /*1732 int 2147483647 */ /*1733 int 2147483647 */ /*1734 int 2147483647 */ /*1735 int 2147483647 */ /*1736 int 2147483647 */ /*1737 int 2147483647 */ /*1738 int 2147483647 */ /*1739 int 2147483647 */ /*1740 int 2147483647 */ /*1741 int 2147483647 */ /*1742 int 2147483647 */ /*1743 int 2147483647 */ /*1744 int 2147483647 */ /*1745 int 2147483647 */ /*1746 int 2147483647 */ /*1747 int 2147483647 */ /*1748 int 2147483647 */ /*1749 int 2147483647 */ /*1750 int 2147483647 */ /*1751 int 2147483647 */ /*1752 int 2147483647 */ /*1753 int 2147483647 */ /*1754 int 2147483647 */ /*1755 int 2147483647 */ /*1756 int 2147483647 */ /*1757 int 2147483647 */ /*1758 int 2147483647 */ /*1759 int 2147483647 */ /*1760 int 2147483647 */ /*1761 int 2147483647 */ /*1762 int 2147483647 */ /*1763 int 2147483647 */ /*1764 int 2147483647 */ /*1765 int 2147483647 */ /*1766 int 2147483647 */ /*1767 int 2147483647 */ /*1768 int 2147483647 */ /*1769 int 2147483647 */ /*1770 int 2147483647 */ /*1771 int 2147483647 */ /*1772 int 2147483647 */ /*1773 int 2147483647 */ /*1774 int 2147483647 */ /*1775 int 2147483647 */ /*1776 int 2147483647 */ /*1777 int 2147483647 */ /*1778 int 2147483647 */ /*1779 int 2147483647 */ /*1780 int 2147483647 */ /*1781 int 2147483647 */ /*1782 int 2147483647 */ /*1783 int 2147483647 */ /*1784 int 2147483647 */ /*1785 int 2147483647 */ /*1786 int 2147483647 */ /*1787 int 2147483647 */ /*1788 int 2147483647 */ /*1789 int 2147483647 */ /*1790 int 2147483647 */ /*1791 int 2147483647 */ /*1792 int 2147483647 */ /*1793 int 2147483647 */ /*1794 int 2147483647 */ /*1795 int 2147483647 */ /*1796 int 2147483647 */ /*1797 int 2147483647 */ /*1798 int 2147483647 */ /*1799 int 2147483647 */ /*1800 int 2147483647 */ /*1801 int 2147483647 */ /*1802 int 2147483647 */ /*1803 int 2147483647 */ /*1804 int 2147483647 */ /*1805 int 2147483647 */ /*1806 int 2147483647 */ /*1807 int 2147483647 */ /*1808 int 2147483647 */ /*1809 int 2147483647 */ /*1810 int 2147483647 */ /*1811 int 2147483647 */ /*1812 int 2147483647 */ /*1813 int 2147483647 */ /*1814 int 2147483647 */ /*1815 int 2147483647 */ /*1816 int 2147483647 */ /*1817 int 2147483647 */ /*1818 int 2147483647 */ /*1819 int 2147483647 */ /*1820 int 2147483647 */ /*1821 int 2147483647 */ /*1822 int 2147483647 */ /*1823 int 2147483647 */ /*1824 int 2147483647 */ /*1825 int 2147483647 */ /*1826 int 2147483647 */ /*1827 int 2147483647 */ /*1828 int 2147483647 */ /*1829 int 2147483647 */ /*1830 int 2147483647 */ /*1831 int 2147483647 */ /*1832 int 2147483647 */ /*1833 int 2147483647 */ /*1834 int 2147483647 */ /*1835 int 2147483647 */ /*1836 int 2147483647 */ /*1837 int 2147483647 */ /*1838 int 2147483647 */ /*1839 int 2147483647 */ /*1840 int 2147483647 */ /*1841 int 2147483647 */ /*1842 int 2147483647 */ /*1843 int 2147483647 */ /*1844 int 2147483647 */ /*1845 int 2147483647 */ /*1846 int 2147483647 */ /*1847 int 2147483647 */ /*1848 int 2147483647 */ /*1849 int 2147483647 */ /*1850 int 2147483647 */ /*1851 int 2147483647 */ /*1852 int 2147483647 */ /*1853 int 2147483647 */ /*1854 int 2147483647 */ /*1855 int 2147483647 */ /*1856 int 2147483647 */ /*1857 int 2147483647 */ /*1858 int 2147483647 */ /*1859 int 2147483647 */ /*1860 int 2147483647 */ /*1861 int 2147483647 */ /*1862 int 2147483647 */ /*1863 int 2147483647 */ /*1864 int 2147483647 */ /*1865 int 2147483647 */ /*1866 int 2147483647 */ /*1867 int 2147483647 */ /*1868 int 2147483647 */ /*1869 int 2147483647 */ /*1870 int 2147483647 */ /*1871 int 2147483647 */ /*1872 int 2147483647 */ /*1873 int 2147483647 */ /*1874 int 2147483647 */ /*1875 int 2147483647 */ /*1876 int 2147483647 */ /*1877 int 2147483647 */ /*1878 int 2147483647 */ /*1879 int 2147483647 */ /*1880 int 2147483647 */ /*1881 int 2147483647 */ /*1882 int 2147483647 */ /*1883 int 2147483647 */ /*1884 int 2147483647 */ /*1885 int 2147483647 */ /*1886 int 2147483647 */ /*1887 int 2147483647 */ /*1888 int 2147483647 */ /*1889 int 2147483647 */ /*1890 int 2147483647 */ /*1891 int 2147483647 */ /*1892 int 2147483647 */ /*1893 int 2147483647 */ /*1894 int 2147483647 */ /*1895 int 2147483647 */ /*1896 int 2147483647 */ /*1897 int 2147483647 */ /*1898 int 2147483647 */ /*1899 int 2147483647 */ /*1900 int 2147483647 */ /*1901 int 2147483647 */ /*1902 int 2147483647 */ /*1903 int 2147483647 */ /*1904 int 2147483647 */ /*1905 int 2147483647 */ /*1906 int 2147483647 */ /*1907 int 2147483647 */ /*1908 int 2147483647 */ /*1909 int 2147483647 */ /*1910 int 2147483647 */ /*1911 int 2147483647 */ /*1912 int 2147483647 */ /*1913 int 2147483647 */ /*1914 int 2147483647 */ /*1915 int 2147483647 */ /*1916 int 2147483647 */ /*1917 int 2147483647 */ /*1918 int 2147483647 */ /*1919 int 2147483647 */ /*1920 int 2147483647 */ /*1921 int 2147483647 */ /*1922 int 2147483647 */ /*1923 int 2147483647 */ /*1924 int 2147483647 */ /*1925 int 2147483647 */ /*1926 int 2147483647 */ /*1927 int 2147483647 */ /*1928 int 2147483647 */ /*1929 int 2147483647 */ /*1930 int 2147483647 */ /*1931 int 2147483647 */ /*1932 int 2147483647 */ /*1933 int 2147483647 */ /*1934 int 2147483647 */ /*1935 int 2147483647 */ /*1936 int 2147483647 */ /*1937 int 2147483647 */ /*1938 int 2147483647 */ /*1939 int 2147483647 */ /*1940 int 2147483647 */ /*1941 int 2147483647 */ /*1942 int 2147483647 */ /*1943 int 2147483647 */ /*1944 int 2147483647 */ /*1945 int 2147483647 */ /*1946 int 2147483647 */ /*1947 int 2147483647 */ /*1948 int 2147483647 */ /*1949 int 2147483647 */ /*1950 int 2147483647 */ /*1951 int 2147483647 */ /*1952 int 2147483647 */ /*1953 int 2147483647 */ /*1954 int 2147483647 */ /*1955 int 2147483647 */ /*1956 int 2147483647 */ /*1957 int 2147483647 */ /*1958 int 2147483647 */ /*1959 int 2147483647 */ /*1960 int 2147483647 */ /*1961 int 2147483647 */ /*1962 int 2147483647 */ /*1963 int 2147483647 */ /*1964 int 2147483647 */ /*1965 int 2147483647 */ /*1966 int 2147483647 */ /*1967 int 2147483647 */ /*1968 int 2147483647 */ /*1969 int 2147483647 */ /*1970 int 2147483647 */ /*1971 int 2147483647 */ /*1972 int 2147483647 */ /*1973 int 2147483647 */ /*1974 int 2147483647 */ /*1975 int 2147483647 */ /*1976 int 2147483647 */ /*1977 int 2147483647 */ /*1978 int 2147483647 */ /*1979 int 2147483647 */ /*1980 int 2147483647 */ /*1981 int 2147483647 */ /*1982 int 2147483647 */ /*1983 int 2147483647 */ /*1984 int 2147483647 */ /*1985 int 2147483647 */ /*1986 int 2147483647 */ /*1987 int 2147483647 */ /*1988 int 2147483647 */ /*1989 int 2147483647 */ /*1990 int 2147483647 */ /*1991 int 2147483647 */ /*1992 int 2147483647 */ /*1993 int 2147483647 */ /*1994 int 2147483647 */ /*1995 int 2147483647 */ /*1996 int 2147483647 */ /*1997 int 2147483647 */ /*1998 int 2147483647 */ /*1999 int 2147483647 */ /*2000 int 2147483647 */ /*2001 int 2147483647 */ /*2002 int 2147483647 */ /*2003 int 2147483647 */ /*2004 int 2147483647 */ /*2005 int 2147483647 */ /*2006 int 2147483647 */ /*2007 int 2147483647 */ /*2008 int 2147483647 */ /*2009 int 2147483647 */ /*2010 int 2147483647 */ /*2011 int 2147483647 */ /*2012 int 2147483647 */ /*2013 int 2147483647 */ /*2014 int 2147483647 */ /*2015 int 2147483647 */ /*2016 int 2147483647 */ /*2017 int 2147483647 */ /*2018 int 2147483647 */ /*2019 int 2147483647 */ /*2020 int 2147483647 */ /*2021 int 2147483647 */ /*2022 int 2147483647 */ /*2023 int 2147483647 */ /*2024 int 2147483647 */ /*2025 int 2147483647 */ /*2026 int 2147483647 */ /*2027 int 2147483647 */ /*2028 int 2147483647 */ /*2029 int 2147483647 */ /*2030 int 2147483647 */ /*2031 int 2147483647 */ /*2032 int 2147483647 */ /*2033 int 2147483647 */ /*2034 int 2147483647 */ /*2035 int 2147483647 */ /*2036 int 2147483647 */ /*2037 int 2147483647 */ /*2038 int 2147483647 */ /*2039 int 2147483647 */ /*2040 int 2147483647 */ /*2041 int 2147483647 */ /*2042 int 2147483647 */ /*2043 int 2147483647 */ /*2044 int 2147483647 */ /*2045 int 2147483647 */ /*2046 int 2147483647 */ /*2047 int 2147483647 */ /*2048 int 2147483647 */ /*2049 int 2147483647 */ /*2050 int 2147483647 */ /*2051 int 2147483647 */ /*2052 int 2147483647 */ /*2053 int 2147483647 */ /*2054 int 2147483647 */ /*2055 int 2147483647 */ /*2056 int 2147483647 */ /*2057 int 2147483647 */ /*2058 int 2147483647 */ /*2059 int 2147483647 */ /*2060 int 2147483647 */ /*2061 int 2147483647 */ /*2062 int 2147483647 */ /*2063 int 2147483647 */ /*2064 int 2147483647 */ /*2065 int 2147483647 */ /*2066 int 2147483647 */ /*2067 int 2147483647 */ /*2068 int 2147483647 */ /*2069 int 2147483647 */ /*2070 int 2147483647 */ /*2074 int 8 */ /*2075 int 1 */ /*2076 int 16 */ /*2077 int 16 */ /*2078 int 16 */ /*2079 int 16 */ /*2080 int 16 */ /*2081 int 16 */ /*2082 int 16 */ /*2083 int 16 */ /*2084 int 16 */ /*2085 int 16 */ /*2086 int 16 */ /*2087 int 16 */ /*2099 int 2147483647 */ /*2100 int 512 */ /*2101 int 512 */ /*2102 int 512 */ /*2103 int 512 */ /*2104 int 512 */ /*2105 int 512 */ /*2106 int 512 */ /*2107 int 512 */ /*2108 int 512 */ /*2109 int 512 */ /*2110 int 512 */ /*2111 int 512 */ /*2112 int 512 */ /*2113 int 512 */ /*2114 int 512 */ /*2115 int 512 */ /*2116 int 512 */ /*2117 int 512 */ /*2118 int 512 */ /*2119 int 512 */ /*2120 int 512 */ /*2121 int 512 */ /*2122 int 512 */ /*2123 int 512 */ /*2124 int 512 */ /*2125 int 512 */ /*2126 int 512 */ /*2127 int 512 */ /*2128 int 512 */ /*2129 int 512 */ /*2130 int 512 */ /*2131 int 2147483647 */ /*2132 int 2147483647 */ /*2133 int 2147483647 */ /*2134 int 2147483647 */ /*2135 int 2147483647 */ /*2136 int 2147483647 */ /*2137 int 2147483647 */ /*2139 int 128 */ /*2140 int 2 */ /*2141 int 2 */ /*2142 int 2 */ /*2143 int 2 */ /*2145 int 16 */ /*2146 int 16 */ /*2147 int 16 */ /*2148 int 128 */ /*2149 int 2147483647 */ /*2150 int 2147483647 */ /*2151 int 2147483647 */ /*2152 int 2147483647 */ /*2153 int 2147483647 */ /*2154 int 2147483647 */ /*2156 int 128 */ /*2157 int 2 */ /*2158 int 2 */ /*2159 int 2 */ /*2160 int 2 */ /*2162 int 16 */ /*2163 int 16 */ /*2164 int 16 */ /*2165 int 128 */ /*2166 int 2147483647 */ /*2167 int 2147483647 */ /*2168 int 2147483647 */ /*2169 int 2147483647 */ /*2170 int 2147483647 */ /*2171 int 2147483647 */ /*2173 int 128 */ /*2174 int 2 */ /*2175 int 2 */ /*2176 int 2 */ /*2177 int 2 */ /*2179 int 16 */ /*2180 int 16 */ /*2181 int 16 */ /*2182 int 128 */ /*2183 int 2147483647 */ /*2184 int 2147483647 */ /*2185 int 2147483647 */ /*2186 int 2147483647 */ /*2187 int 2147483647 */ /*2188 int 2147483647 */ /*2190 int 128 */ /*2191 int 2 */ /*2192 int 2 */ /*2193 int 2 */ /*2194 int 2 */ /*2196 int 16 */ /*2197 int 16 */ /*2198 int 16 */ /*2200 int 128 */ /*2201 int 2 */ /*2202 int 2 */ /*2203 int 2 */ /*2204 int 2 */ /*2206 int 16 */ /*2207 int 16 */ /*2208 int 16 */ /*2210 int 128 */ /*2211 int 2 */ /*2212 int 2 */ /*2213 int 2 */ /*2214 int 2 */ /*2216 int 16 */ /*2217 int 16 */ /*2218 int 16 */ /*2220 int 128 */ /*2221 int 2 */ /*2222 int 2 */ /*2223 int 2 */ /*2224 int 2 */ /*2226 int 16 */ /*2227 int 16 */ /*2228 int 16 */ /*2230 int 128 */ /*2231 int 2 */ /*2232 int 2 */ /*2233 int 2 */ /*2234 int 2 */ /*2236 int 16 */ /*2237 int 16 */ /*2238 int 16 */ /*2240 int 128 */ /*2241 int 2 */ /*2242 int 2 */ /*2243 int 2 */ /*2244 int 2 */ /*2246 int 16 */ /*2247 int 16 */ /*2248 int 16 */ /*2250 int 128 */ /*2251 int 2 */ /*2252 int 2 */ /*2253 int 2 */ /*2254 int 2 */ /*2256 int 16 */ /*2257 int 16 */ /*2258 int 16 */ /*2260 int 128 */ /*2261 int 2 */ /*2262 int 2 */ /*2263 int 2 */ /*2264 int 2 */ /*2266 int 16 */ /*2267 int 16 */ /*2268 int 16 */ /*2270 int 128 */ /*2271 int 2 */ /*2272 int 2 */ /*2273 int 2 */ /*2274 int 2 */ /*2276 int 16 */ /*2277 int 16 */ /*2278 int 16 */ /*2280 int 128 */ /*2281 int 2 */ /*2282 int 2 */ /*2283 int 2 */ /*2284 int 2 */ /*2286 int 16 */ /*2287 int 16 */ /*2288 int 16 */ /*2290 int 128 */ /*2291 int 2 */ /*2292 int 2 */ /*2293 int 2 */ /*2294 int 2 */ /*2296 int 16 */ /*2297 int 16 */ /*2298 int 16 */ /*2300 int 128 */ /*2301 int 2 */ /*2302 int 2 */ /*2303 int 2 */ /*2304 int 2 */ /*2306 int 16 */ /*2307 int 16 */ /*2308 int 16 */ /*2310 int 128 */ /*2311 int 2 */ /*2312 int 2 */ /*2313 int 2 */ /*2314 int 2 */ /*2316 int 16 */ /*2317 int 16 */ /*2318 int 16 */ /*2320 int 128 */ /*2321 int 2 */ /*2322 int 2 */ /*2323 int 2 */ /*2324 int 2 */ /*2326 int 16 */ /*2327 int 16 */ /*2328 int 16 */ /*2330 int 128 */ /*2331 int 2 */ /*2332 int 2 */ /*2333 int 2 */ /*2334 int 2 */ /*2336 int 16 */ /*2337 int 16 */ /*2338 int 16 */ /*2340 int 128 */ /*2341 int 2 */ /*2342 int 2 */ /*2343 int 2 */ /*2344 int 2 */ /*2346 int 16 */ /*2347 int 16 */ /*2348 int 16 */ /*2350 int 128 */ /*2351 int 2 */ /*2352 int 2 */ /*2353 int 2 */ /*2354 int 2 */ /*2356 int 16 */ /*2357 int 16 */ /*2358 int 16 */ /*2360 int 128 */ /*2361 int 2 */ /*2362 int 2 */ /*2363 int 2 */ /*2364 int 2 */ /*2366 int 16 */ /*2367 int 16 */ /*2368 int 16 */ /*2370 int 128 */ /*2371 int 2 */ /*2372 int 2 */ /*2373 int 2 */ /*2374 int 2 */ /*2376 int 16 */ /*2377 int 16 */ /*2378 int 16 */ /*2380 int 128 */ /*2381 int 2 */ /*2382 int 2 */ /*2383 int 2 */ /*2384 int 2 */ /*2386 int 16 */ /*2387 int 16 */ /*2388 int 16 */ /*2390 int 128 */ /*2391 int 2 */ /*2392 int 2 */ /*2393 int 2 */ /*2394 int 2 */ /*2396 int 16 */ /*2397 int 16 */ /*2398 int 16 */ /*2400 int 128 */ /*2401 int 2 */ /*2402 int 2 */ /*2403 int 2 */ /*2404 int 2 */ /*2406 int 16 */ /*2407 int 16 */ /*2408 int 16 */ /*2410 int 128 */ /*2411 int 2 */ /*2412 int 2 */ /*2413 int 2 */ /*2414 int 2 */ /*2416 int 16 */ /*2417 int 16 */ /*2418 int 16 */ /*2420 int 128 */ /*2421 int 2 */ /*2422 int 2 */ /*2423 int 2 */ /*2424 int 2 */ /*2426 int 16 */ /*2427 int 16 */ /*2428 int 16 */ /*2430 int 128 */ /*2431 int 2 */ /*2432 int 2 */ /*2433 int 2 */ /*2434 int 2 */ /*2436 int 16 */ /*2437 int 16 */ /*2438 int 16 */ /*2440 int 128 */ /*2441 int 2 */ /*2442 int 2 */ /*2443 int 2 */ /*2444 int 2 */ /*2446 int 16 */ /*2447 int 16 */ /*2448 int 16 */ /*2450 int 128 */ /*2451 int 2 */ /*2452 int 2 */ /*2453 int 2 */ /*2454 int 2 */ /*2456 int 16 */ /*2457 int 16 */ /*2458 int 16 */ /*2460 int 128 */ /*2461 int 2 */ /*2462 int 2 */ /*2463 int 2 */ /*2464 int 2 */ /*2466 int 16 */ /*2467 int 16 */ /*2468 int 16 */ /*2470 int 128 */ /*2471 int 2 */ /*2472 int 2 */ /*2473 int 2 */ /*2474 int 2 */ /*2476 int 16 */ /*2477 int 16 */ /*2478 int 16 */ /*2480 int 128 */ /*2481 int 2 */ /*2482 int 2 */ /*2483 int 2 */ /*2484 int 2 */ /*2486 int 16 */ /*2487 int 16 */ /*2488 int 16 */ /*2490 int 128 */ /*2491 int 2 */ /*2492 int 2 */ /*2493 int 2 */ /*2494 int 2 */ /*2496 int 16 */ /*2497 int 16 */ /*2498 int 16 */ /*2500 int 128 */ /*2501 int 2 */ /*2502 int 2 */ /*2503 int 2 */ /*2504 int 2 */ /*2506 int 16 */ /*2507 int 16 */ /*2508 int 16 */ /*2510 int 128 */ /*2511 int 2 */ /*2512 int 2 */ /*2513 int 2 */ /*2514 int 2 */ /*2516 int 16 */ /*2517 int 16 */ /*2518 int 16 */ /*2519 int 2147483647 */ /*2520 int 2147483647 */ /*2521 int 2147483647 */ /*2522 int 2147483647 */ /*2523 int 2147483647 */ /*2524 int 2147483647 */ /*2525 int 2147483647 */ /*2526 int 2147483647 */ /*2527 int 2147483647 */ /*2528 int 2147483647 */ /*2529 int 2147483647 */ /*2530 int 2147483647 */ /*2531 int 2147483647 */ /*2532 int 2147483647 */ /*2533 int 2147483647 */ /*2534 int 2147483647 */ /*2535 int 2147483647 */ /*2536 int 2147483647 */ /*2537 int 2147483647 */ /*2538 int 2147483647 */ /*2539 int 2147483647 */ /*2540 int 2147483647 */ /*2541 int 2147483647 */ /*2542 int 2147483647 */ /*2543 int 2147483647 */ /*2544 int 2147483647 */ /*2545 int 2147483647 */ /*2546 int 2147483647 */ /*2547 int 2147483647 */ /*2548 int 2147483647 */ /*2549 int 2147483647 */ /*2550 int 2147483647 */ /*2551 int 2147483647 */ /*2553 int 16 */ /*2554 int 16 */ /*2555 int 16 */ /*2556 int 16 */ /*2557 int 16 */ /*2558 int 32 */ /*2560 int 16 */ /*2561 int 16 */ /*2562 int 16 */ /*2563 int 16 */ /*2564 int 16 */ /*2565 int 32 */ /*2567 int 8 */ /*2568 int 8 */ /*2569 int 8 */ /*2570 int 8 */ /*2571 int 8 */ /*2572 int 8 */ /*2573 int 8 */ /*2574 int 8 */ /*2576 int 8 */ /*2577 int 8 */ /*2578 int 8 */ /*2579 int 8 */ /*2580 int 8 */ /*2581 int 8 */ /*2582 int 8 */ /*2584 int 1 */ /*2585 int 1 */ /*2586 int 1 */ /*2587 int 1 */ /*2588 int 1 */ /*2589 int 1 */ /*2590 int 1 */ /*2591 int 1 */ /*2592 int 1 */ /*2593 int 1 */ /*2594 int 1 */ /*2595 int 1 */ /*2596 int 1 */ /*2597 int 1 */ /*2598 int 32 */ /*2599 int 1 */ /*2600 int 1 */ /*2602 int 1 */ /*2603 int 1 */ /*2604 int 1 */ /*2605 int 1 */ /*2606 int 1 */ /*2607 int 1 */ /*2608 int 1 */ /*2609 int 1 */ /*2610 int 1 */ /*2611 int 1 */ /*2612 int 1 */ /*2613 int 1 */ /*2614 int 1 */ /*2615 int 1 */ /*2616 int 1 */ /*2617 int 8 */ /*2618 int 8 */ /*2620 int 8 */ /*2621 int 8 */ /*2622 int 8 */ /*2623 int 8 */ /*2624 int 8 */ /*2625 int 8 */ /*2626 int 8 */ /*2627 int 8 */ /*2629 int 8 */ /*2630 int 8 */ /*2631 int 8 */ /*2632 int 8 */ /*2633 int 8 */ /*2634 int 2147483647 */ /*2635 int 2147483647 */ /*2636 int 2147483647 */ /*2637 int 2147483647 */ /*2638 int 2147483647 */ /*2639 int 2147483647 */ /*2640 int 2147483647 */ /*2641 int 2147483647 */ /*2642 int 2147483647 */ /*2643 int 2147483647 */ /*2644 int 2147483647 */ /*2645 int 2147483647 */ /*2646 int 2147483647 */ /*2647 int 2147483647 */ /*2648 int 2147483647 */ /*2649 int 2147483647 */ /*2650 int 2147483647 */ /*2651 int 2147483647 */ /*2652 int 2147483647 */ /*2653 int 2147483647 */ /*2654 int 2147483647 */ /*2655 int 2147483647 */ /*2656 int 2147483647 */ /*2657 int 2147483647 */ /*2658 int 2147483647 */ /*2659 int 2147483647 */ /*2660 int 2147483647 */ /*2661 int 2147483647 */ /*2662 int 2147483647 */ /*2663 int 2147483647 */ /*2664 int 2147483647 */ /*2665 int 2147483647 */ /*2666 int 2147483647 */ /*2667 int 2147483647 */ /*2668 int 2147483647 */ /*2669 int 2147483647 */ /*2670 int 2147483647 */ /*2671 int 2147483647 */ /*2672 int 2147483647 */ /*2673 int 2147483647 */ /*2674 int 2147483647 */ /*2675 int 2147483647 */ /*2676 int 2147483647 */ /*2677 int 2147483647 */ /*2678 int 2147483647 */ /*2679 int 2147483647 */ /*2680 int 2147483647 */ /*2681 int 2147483647 */ /*2682 int 2147483647 */ /*2683 int 2147483647 */ /*2684 int 2147483647 */ /*2685 int 2147483647 */ /*2686 int 2147483647 */ /*2687 int 2147483647 */ /*2688 int 2147483647 */ /*2689 int 2147483647 */ /*2690 int 2147483647 */ /*2691 int 2147483647 */ /*2692 int 2147483647 */ /*2693 int 2147483647 */ /*2694 int 2147483647 */ /*2695 int 2147483647 */ /*2696 int 2147483647 */ /*2697 int 2147483647 */ /*2698 int 2147483647 */ /*2699 int 2147483647 */ /*2700 int 2147483647 */ /*2701 int 2147483647 */ /*2702 int 2147483647 */ /*2703 int 2147483647 */ /*2704 int 2147483647 */ /*2705 int 2147483647 */ /*2706 int 2147483647 */ /*2707 int 2147483647 */ /*2708 int 2147483647 */ /*2709 int 2147483647 */ /*2710 int 2147483647 */ /*2711 int 2147483647 */ /*2712 int 2147483647 */ /*2713 int 2147483647 */ /*2714 int 2147483647 */ /*2715 int 2147483647 */ /*2716 int 2147483647 */ /*2717 int 2147483647 */ /*2718 int 2147483647 */ /*2719 int 2147483647 */ /*2720 int 2147483647 */ /*2721 int 2147483647 */ /*2722 int 2147483647 */ /*2723 int 2147483647 */ /*2724 int 2147483647 */ /*2725 int 2147483647 */ /*2726 int 2147483647 */ /*2727 int 2147483647 */ /*2728 int 2147483647 */ /*2729 int 2147483647 */ /*2730 int 2147483647 */ /*2731 int 2147483647 */ /*2732 int 2147483647 */ /*2733 int 2147483647 */ /*2734 int 2147483647 */ /*2735 int 2147483647 */ /*2736 int 2147483647 */ /*2737 int 2147483647 */ /*2738 int 2147483647 */ /*2739 int 2147483647 */ /*2740 int 2147483647 */ /*2741 int 2147483647 */ /*2742 int 2147483647 */ /*2743 int 2147483647 */ /*2744 int 2147483647 */ /*2745 int 2147483647 */ /*2746 int 2147483647 */ /*2747 int 2147483647 */ /*2748 int 2147483647 */ /*2749 int 2147483647 */ /*2750 int 2147483647 */ /*2751 int 2147483647 */ /*2752 int 2147483647 */ /*2753 int 2147483647 */ /*2754 int 2147483647 */ /*2755 int 2147483647 */ /*2756 int 2147483647 */ /*2757 int 2147483647 */ /*2758 int 2147483647 */ /*2759 int 2147483647 */ /*2760 int 2147483647 */ /*2761 int 2147483647 */ /*2762 int 2147483647 */ /*2763 int 2147483647 */ /*2764 int 2147483647 */ /*2765 int 2147483647 */ /*2766 int 2147483647 */ /*2767 int 2147483647 */ /*2768 int 2147483647 */ /*2769 int 2147483647 */ /*2770 int 2147483647 */ /*2771 int 2147483647 */ /*2772 int 2147483647 */ /*2773 int 2147483647 */ /*2774 int 2147483647 */ /*2775 int 2147483647 */ /*2776 int 2147483647 */ /*2777 int 2147483647 */ /*2778 int 2147483647 */ /*2779 int 2147483647 */ /*2780 int 2147483647 */ /*2781 int 2147483647 */ /*2782 int 2147483647 */ /*2783 int 2147483647 */ /*2784 int 2147483647 */ /*2785 int 2147483647 */ /*2786 int 2147483647 */ /*2787 int 2147483647 */ /*2788 int 2147483647 */ /*2789 int 2147483647 */ /*2790 int 2147483647 */ /*2791 int 2147483647 */ /*2792 int 2147483647 */ /*2793 int 2147483647 */ /*2794 int 2147483647 */ /*2795 int 2147483647 */ /*2796 int 2147483647 */ /*2797 int 2147483647 */ /*2798 int 2147483647 */ /*2799 int 2147483647 */ /*2800 int 2147483647 */ /*2801 int 2147483647 */ /*2802 int 2147483647 */ /*2803 int 2147483647 */ /*2804 int 2147483647 */ /*2805 int 2147483647 */ /*2806 int 2147483647 */ /*2807 int 2147483647 */ /*2808 int 2147483647 */ /*2809 int 2147483647 */ /*2810 int 2147483647 */ /*2811 int 2147483647 */ /*2812 int 2147483647 */ /*2813 int 2147483647 */ /*2814 int 2147483647 */ /*2815 int 2147483647 */ /*2816 int 2147483647 */ /*2817 int 2147483647 */ /*2818 int 2147483647 */ /*2819 int 2147483647 */ /*2820 int 2147483647 */ /*2821 int 2147483647 */ /*2822 int 2147483647 */ /*2823 int 2147483647 */ /*2824 int 2147483647 */ /*2825 int 2147483647 */ /*2826 int 2147483647 */ /*2827 int 2147483647 */ /*2828 int 2147483647 */ /*2829 int 2147483647 */ /*2830 int 2147483647 */ /*2831 int 2147483647 */ /*2832 int 2147483647 */ /*2833 int 2147483647 */ /*2835 int 2 */ /*2836 int 2 */ /*2837 int 2 */ /*2838 int 2 */ /*2839 int 2 */ /*2840 int 2 */ /*2841 int 2 */ /*2842 int 2 */ /*2843 int 2 */ /*2844 int 2 */ ; private int id; ClanVar(int id) { this.id = id; } public int getId() { return id; } public ClanVarDefinitions getDef() { return ClanVarDefinitions.getDefs(id); } } " " package com.rs.lib.net; import java.util.HashMap; import java.util.Map; public enum ClientPacket { KEEPALIVE(0, 0), PLAYER_OP6(1, 3), SOUND_EFFECT_MUSIC_ENDED(2, 4), NPC_EXAMINE(3, 3), IF_ON_IF(4, 16), WORLD_MAP_CLICK(5, 4), PLAYER_OP2(6, 3), FC_SET_RANK(7, -1), GROUND_ITEM_OP4(8, 7), IF_OP4(9, 8), SEND_PREFERENCES(10, -1), RESUME_HSLDIALOG(11, 2), REMOVE_IGNORE(12, -1), IF_ON_PLAYER(13, 11), QUICKCHAT_PRIVATE(14, -1), SEND_PRIVATE_MESSAGE(15, -2), NPC_OP2(16, 3), GE_ITEM_SELECT(17, 2), SONG_LOADED(18, 4), IF_OP6(19, 8), CHAT_SETFILTER(20, 3), IF_OP8(21, 8), IF_OP9(22, 8), IF_OP7(23, 8), GROUND_ITEM_OP1(24, 7), GROUND_ITEM_OP2(25, 7), ADD_FRIEND(26, -1), IF_OP2(27, 8), KEY_PRESS(28, -2), REMOVE_FRIEND(29, -1), CHAT_TYPE(30, 1), PLAYER_OP3(31, 3), OBJECT_OP4(32, 9), WALK(33, 5), ADD_IGNORE(34, -1), BUG_REPORT(35, -2), REFLECTION_CHECK(36, -1), UNK_37(37, 2), //index 36 and some hook/click type related OBJECT_OP3(38, 9), UNUSED_CLAN_OP(39, -1), //Packet is referenced by one CS2 instruction but that CS2 instruction is present in no scripts MOVE_MOUSE(40, -1), IF_ON_NPC(41, 11), MINI_WALK(42, 18), GROUND_ITEM_OP5(43, 7), SEND_FPS(44, 9), CUTSCENE_FINISHED(45, 1), IF_ON_TILE(46, 12), REQUEST_WORLD_LIST(47, 4), OBJECT_OP5(48, 9), IF_CONTINUE(49, 6), NPC_OP3(50, 3), PLAYER_OP7(51, 3), EMAIL_VALIDATION_SUBMIT_CODE(52, -1), PLAYER_OP9(53, 3), GROUND_ITEM_OP3(54, 7), TRANSMITVAR_VERIFYID(55, 4), LOBBY_HYPERLINK(56, -2), MOUSE_BUTTON_CLICK(57, 7), RESUME_COUNTDIALOG(58, 4), MOUSE_CLICK(59, 6), CLOSE_INTERFACE(60, 0), GROUND_ITEM_EXAMINE(61, 7), CLIENT_FOCUS(62, 1), UNK_63(63, 4), //near where shift click teleporting so some kind of map click probably? QUICKCHAT_PUBLIC(64, -1), NPC_OP1(65, 3), PLAYER_OP1(66, 3), IF_ON_GROUND_ITEM(67, 15), IF_OP3(68, 8), RESUME_CLANFORUMQFCDIALOG(69, -1), PLAYER_OP10(70, 3), FC_JOIN(71, -1), IF_OP5(72, 8), OBJECT_EXAMINE(73, 9), IF_DRAG_ONTO_IF(74, 16), OBJECT_OP1(75, 9), REGION_LOADED_CONFIRM(76, 0), NPC_OP4(77, 3), MOVE_MOUSE_2(78, -1), ACCOUNT_CREATION_STAGE(79, 1), RESUME_NAMEDIALOG(80, -1), IF_OP10(81, 8), UNK_82(82, 4), //writes one identical int sometime during gamestate/region loading. Probably sends when something fails to load or error occurs MOVE_CAMERA(83, 4), SCREEN_SIZE(84, 6), CLIENT_CHEAT(85, -1), CHAT(86, -1), RESUME_TEXTDIALOG(87, -1), WRITE_PING(88, 2), PLAYER_OP4(89, 3), CLANCHANNEL_KICKUSER(90, -1), FC_KICK(91, -1), EMAIL_VALIDATION_ADD_NEW_ADDRESS(92, -2), OBJECT_OP2(93, 9), PLAYER_OP8(94, 3), NPC_OP5(95, 3), IF_OP1(96, 8), UNK_97(97, -1), //cs2 driven something during login stage? IF_ON_OBJECT(98, 17), EMAIL_VALIDATION_CHANGE_ADDRESS(99, -2), REPORT_ABUSE(100, -1), SEND_SIGN_UP_FORM(101, -2), CHECK_EMAIL_VALIDITY(102, -2), PLAYER_OP5(103, 3), //CUSTOM OPCODES FOR LOBBY CC_JOIN(5000, 0), CC_LEAVE(5001, 0), CC_BAN(5002, 0), CLAN_CHECKNAME(5003, 0), CLAN_CREATE(5004, 0), CLAN_LEAVE(5005, 0), CLAN_ADDMEMBER(5006, 0), CLAN_KICKMEMBER(5007, 0) ; private int id; private int size; private static Map PACKET_MAP = new HashMap<>(); static { for (ClientPacket packet : ClientPacket.values()) { PACKET_MAP.put(packet.id, packet); } } public static ClientPacket forOpcode(int opcode) { return PACKET_MAP.get(opcode); } ClientPacket(int id, int size) { this.id = id; this.size = size; } public int getOpcode() { return id; } public int getSize() { return size; } } " " package com.rs.lib.net; import com.rs.lib.io.InputStream; public abstract class Decoder { protected Session session; public Decoder() { } public Decoder(Session session) { this.session = session; } public final int _decode(InputStream stream) { session.refreshLastPacket(); return decode(stream); } public abstract int decode(InputStream stream); protected void setSession(Session session) { this.session = session; } } " " package com.rs.lib.net; public class Encoder { protected Session session; public Encoder(Session session) { this.session = session; } } " " package com.rs.lib.net; import java.lang.reflect.InvocationTargetException; import java.net.InetSocketAddress; import java.util.concurrent.Executors; import com.rs.lib.io.InputStream; import com.rs.lib.net.decoders.GameDecoder; import com.rs.lib.util.Logger; import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandler.Sharable; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.group.ChannelGroup; import io.netty.channel.group.DefaultChannelGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.util.AttributeKey; import io.netty.util.concurrent.GlobalEventExecutor; @Sharable public final class ServerChannelHandler extends ChannelInboundHandlerAdapter { private static final AttributeKey SESSION_KEY = AttributeKey.valueOf(""session""); private static ChannelGroup CHANNELS; private static ServerBootstrap BOOTSTRAP; private static EventLoopGroup BOSS_GROUP; private static EventLoopGroup WORKER_GROUP; private Class baseDecoderClass; public static final void init(int port, Class baseDecoderClass) { Logger.info(ServerChannelHandler.class, ""init"", ""Putting server online... ("" + baseDecoderClass + "")""); new ServerChannelHandler(port, baseDecoderClass); } public static int getConnectedChannelsSize() { return CHANNELS == null ? 0 : CHANNELS.size(); } private ServerChannelHandler(int port, Class baseDecoderClass) { this.baseDecoderClass = baseDecoderClass; BOSS_GROUP = new NioEventLoopGroup(16, Executors.newVirtualThreadPerTaskExecutor()); WORKER_GROUP = new NioEventLoopGroup(); CHANNELS = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); BOOTSTRAP = new ServerBootstrap(); BOOTSTRAP.group(BOSS_GROUP, WORKER_GROUP) .channel(NioServerSocketChannel.class) .childHandler(this) .option(ChannelOption.SO_REUSEADDR, true) .childOption(ChannelOption.TCP_NODELAY, true) .childOption(ChannelOption.SO_KEEPALIVE, true) .bind(new InetSocketAddress(port)); } @Override public void channelRegistered(ChannelHandlerContext ctx) { CHANNELS.add(ctx.channel()); } @Override public void channelUnregistered(ChannelHandlerContext ctx) { CHANNELS.remove(ctx.channel()); } @Override public void channelActive(ChannelHandlerContext ctx) { try { ctx.channel().attr(SESSION_KEY).set(new Session(ctx.channel(), baseDecoderClass.getConstructor().newInstance())); Logger.debug(ServerChannelHandler.class, ""channelActive"", ""Connection from "" + ctx.channel().remoteAddress()); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e1) { Logger.handle(ServerChannelHandler.class, ""channelActive"", e1); } } @Override public void channelInactive(ChannelHandlerContext ctx) { Logger.debug(ServerChannelHandler.class, ""channelInactive"", ""Connection disconnected "" + ctx.channel().remoteAddress()); Session session = ctx.channel().attr(SESSION_KEY).get(); if (session != null) { if (session.getDecoder() == null) return; if (session.getDecoder() instanceof GameDecoder) session.getChannel().close(); //TODO this might be messing with attempting to reestablish } } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (!(msg instanceof ByteBuf)) return; ByteBuf buf = (ByteBuf) msg; Session session = ctx.channel().attr(SESSION_KEY).get(); if (session != null) { if (session.getDecoder() == null) return; byte[] b = new byte[(session.buffer.length - session.bufferOffset) + buf.readableBytes()]; if ((session.buffer.length - session.bufferOffset) > 0) System.arraycopy(session.buffer, session.bufferOffset, b, 0, session.buffer.length - session.bufferOffset); buf.readBytes(b, session.buffer.length - session.bufferOffset, b.length - (session.buffer.length - session.bufferOffset)); buf.release(); session.buffer = b; session.bufferOffset = 0; try { InputStream is = new InputStream(b); session.bufferOffset = session.getDecoder()._decode(is); if (session.bufferOffset < 0) { // drop session.buffer = new byte[0]; session.bufferOffset = 0; } } catch (Throwable er) { Logger.handle(ServerChannelHandler.class, ""ServerChannelHandler"", er); } } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { //Logger.handle(cause); } public static final void shutdown() { CHANNELS.close().awaitUninterruptibly(); BOSS_GROUP.shutdownGracefully(); WORKER_GROUP.shutdownGracefully(); } } " " package com.rs.lib.net; import java.util.HashMap; import java.util.Map; public enum ServerPacket { IF_SETPLAYERHEAD(0, 4), CREATE_CHECK_EMAIL_REPLY(1, 1), PROCESS_DEV_CONSOLE_COMMAND(2, -1), GROUND_ITEM_COUNT(3, 7), UPDATE_INV_PARTIAL(4, -2), UPDATE_INV_FULL(5, -2), NPC_UPDATE(6, -2), IF_SETTEXTFONT(7, 8), VARP_LARGE(8, 6), LOGOUT_LOBBY(9, 0), MESSAGE_PRIVATE_ECHO(10, -2), aClass375_4362(11, 2), //vorbis preload sound related with sending packet 37 as response CLIENT_SETVARC_LARGE(12, 6), IF_MOVESUB(13, 8), PLAYER_WEIGHT(14, 2), UPDATE_ZONE_PARTIAL_FOLLOWS(15, 3), OPEN_URL(16, -2), aClass375_4368(17, 3), //vorbis preload sound probably VORBIS_SOUND(18, 8), UPDATE_FRIENDCHAT_CHANNEL_SINGLEUSER(19, -1), OUTDATED_SET_THEORA_STRING_SOMETHING(20, 6), //OUTDATED gets a string from some linkedlist populated from index 36 theora? SHOW_FACE_HERE(21, 1), MESSAGE_QUICKCHAT_PRIVATE(22, -1), IF_OPENSUB_ACTIVE_OBJECT(23, 32), CAM_LOOKAT(24, 6), MESSAGE_FRIENDS_CHAT(25, -1), VARCLAN_SET_LONG(26, 10), CREATE_GROUND_ITEM(27, 5), CLANCHANNEL_DELTA(28, -2), KEEPALIVE(29, 0), CHAT_FILTER_SETTINGS(30, 2), MESSAGE_QUICKCHAT_PRIVATE_ECHO(31, -1), LOYALTY_UPDATE(32, 5), IF_SETHIDE(33, 5), IF_OPENSUB_ACTIVE_PLAYER(59, 25), IF_SETGRAPHIC(35, 8), IF_SETTEXTANTIMACRO(36, 5), IF_OPENTOP(37, 19), IF_OPENSUB(38, 23), CAM_MOVETO(39, 6), aClass375_4399(40, 4), //map region x and y static variables? UPDATE_ZONE_FULL_FOLLOWS(41, 3), UPDATE_INV_STOP_TRANSMIT(42, 3), PLAYER_UPDATE(43, -2), IF_SETANGLE(44, 10), VARCLAN_ENABLE(45, 0), CLANSETTINGS_DELTA(46, -2), NPC_UPDATE_LARGE(47, -2), IF_SETPOSITION(48, 8), CLANCHANNEL_FULL(49, -2), SET_CLAN_STRING(50, -1), DYNAMIC_MAP_REGION(51, -2), DEPRECATED_52_CLIENTPACKET_97(52, 1), //boolean also set on login? IF_SETPLAYERMODEL_OTHER(53, 10), CLIENT_SETVARCSTR_SMALL(54, -1), IF_SETSCROLLPOS(55, 6), PROJANIM_SPECIFIC(56, 22), UPDATE_GE_SLOT(57, 20), QUICK_HOP_WORLDS(58, -1), IF_OPENSUB_ACTIVE_NPC(34, 25), MUSIC_EFFECT(60, 6), REDUCE_ATTACK_PRIORITY(61, 1), LOGOUT_FULL(62, 0), MUSIC_TRACK(63, 4), RUN_ENERGY(64, 1), UPDATE_ZONE_PARTIAL_ENCLOSED(65, -2), CAM_SMOOTHRESET(66, 0), CHAT_FILTER_SETTINGS_PRIVATECHAT(67, 1), VARBIT_SMALL(68, 3), DESTROY_OBJECT(69, 2), MINIMAP_FLAG(70, 2), CAM_SHAKE(71, 6), IF_SETPLAYERMODEL(72, 4), DEBUG_SERVER_TRIGGERS(73, -1), FRIEND_STATUS(74, -2), JCOINS_UPDATE(75, 4), APPLY_DEBUG(76, 2), PRELOAD_SONG(77, 2), IF_CLOSESUB(78, 4), HINT_ARROW(79, 14), OBJ_ANIM_SPECIFIC(80, 9), MESSAGE_CLANCHANNEL(81, -1), IF_SETANIM(82, 8), MESSAGE_QUICKCHAT_PLAYER_GROUP(83, -1), CUSTOMIZE_OBJECT(84, -1), REGION(85, -2), aClass375_4437(86, -2), //""opensn"" maybe social network login? CREATE_ACCOUNT_REPLY(87, 1), OBJECT_PREFETCH(88, 5), CAM_RESET(89, 0), UPDATE_UID192(90, 28), UPDATE_SITESETTINGS_COOKIE(91, -1), SEND_PRIVATE_MESSAGE(92, -2), aClass375_3828(93, 11), //play sound song but with specific volume or something? VARCLAN_DISABLE(94, 0), MAP_PROJANIM_HALFSQ(95, 17), DEPRECATED_PULSE_EVENT(96, 8), UPDATE_IGNORE_LIST(97, -2), REFLECTION_CHECK(98, -2), RUN_CS2_SCRIPT(99, -2), CLEAR_VARPS(100, 0), FRIENDLIST_LOADED(101, 0), //something with setting a number to 1 and refreshing interfaces? ignore list related? FRIENDLIST_LOADED? UPDATE_REBOOT_TIMER(102, 2), WORLD_LIST(103, -2), VORBIS_SPEECH_SOUND(104, 6), IF_SETCOLOR(105, 6), aClass375_4457(106, 2), //vorbis related? GROUND_ITEM_REVEAL(107, 7), VARBIT_LARGE(108, 6), IF_SETNPCHEAD(109, 8), CUTSCENE(110, -2), PLAYER_OPTION(111, -1), IF_SETITEM(112, 10), OBJ_ANIM(113, 6), TILE_MESSAGE(114, -1), VARP_SMALL(115, 3), CLIENT_SETVARC_SMALL(116, 3), CREATE_OBJECT(117, 6), CAM_FORCEANGLE(118, 4), CLIENT_SETVARCSTR_LARGE(119, -2), RESET_SOUNDS(120, 0), IF_SETEVENTS(121, 12), RESET_ALL_ANIMATIONS(122, 0), VARCLAN_SET_BYTE(123, 3), IF_SETTEXT(124, -2), REMOVE_GROUND_ITEM(125, 3), SPOT_ANIM_SPECIFIC(126, 12), FRIENDS_CHAT_CHANNEL(127, -2), MIDI_SONG_LOCATION(128, 6), SET_TARGET(129, 2), IF_SETPLAYERHEAD_IGNOREWORN(130, 10), MESSAGE_QUICKCHAT_CLANCHANNEL(131, -1), IF_SETRETEX(132, 9), MESSAGE_PLAYER_GROUP(133, -1), aClass375_4453(134, 2), //SOUND_MIXBUSS_SETLEVEL? Changes array of 16 values having to do with sound (volumes?) IF_SETMODEL(135, 8), SOUND_SYNTH(136, 8), CLANSETTINGS_FULL(137, -2), ADD_IGNORE(138, -1), SPOT_ANIM(139, 8), UPDATE_STAT(140, 6), VARCLAN_SET_INT(141, 6), MESSAGE_QUICKCHAT_FRIENDS_CHAT(142, -1), MAP_PROJANIM(143, 16), IF_SETRECOL(144, 9), ANIMATE_NPC(145, 19), TRIGGER_ONDIALOGABORT(146, 0), IDENTIFY_HOST_NAME(147, 4), IF_SETTARGETPARAM(148, 10), HINT_TRAIL(149, -2), IF_SETCLICKMASK(150, 5), SET_DRAW_ORDER(151, 1), MESSAGE_PUBLIC(152, -1), SET_CURSOR(153, -1), BLOCK_MINIMAP_STATE(154, 1), IF_OPENSUB_ACTIVE_GROUNDITEM(155, 29), aClass375_4507(156, -2), //calls a javascript method?.. UPDATE_DOB(157, 4), IF_SETPLAYERHEAD_OTHER(158, 10), REQUEST_FPS(159, 8), GAME_MESSAGE(160, -1), DISCORD_RICH_PRESENCE_UPDATE(161, -1), //Pre-world packets WORLD_LOGIN_DETAILS(2, -1), LOBBY_LOGIN_DETAILS(2, -1), ; public int opcode; public int size; private static Map PACKET_MAP = new HashMap<>(); static { for (ServerPacket packet : ServerPacket.values()) { PACKET_MAP.put(packet.opcode, packet); } } public static ServerPacket forOpcode(int opcode) { return PACKET_MAP.get(opcode); } ServerPacket(int opcode, int size) { this.opcode = opcode; this.size = size; } } " " package com.rs.lib.net; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.lang.SuppressWarnings; import com.rs.lib.Constants; import com.rs.lib.io.IsaacKeyPair; import com.rs.lib.io.OutputStream; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketEncoder; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; public class Session { private Channel channel; private Decoder decoder; private Encoder encoder; private long lastPacket = System.currentTimeMillis(); private IsaacKeyPair isaac; private transient OutputStream queuedStream; private final transient Object streamLock = new Object(); private transient Queue packetQueue; public byte[] buffer = new byte[0]; public int bufferOffset = 0; public Session(Channel channel, Decoder defaultDecoder) { this.channel = channel; this.packetQueue = new ConcurrentLinkedQueue(); this.queuedStream = new OutputStream(); if (channel == null) return; defaultDecoder.setSession(this); setDecoder(defaultDecoder); } public final void sendGrabStartup() { OutputStream stream = new OutputStream(1 + Constants.GRAB_SERVER_KEYS.length * 4); stream.writeByte(0); for (int key : Constants.GRAB_SERVER_KEYS) stream.writeInt(key); write(stream); } public final void sendLoginStartup() { OutputStream stream = new OutputStream(1); stream.writeByte(0); write(stream); } public final void sendClientPacket(int opcode) { OutputStream stream = new OutputStream(1); stream.writeByte(opcode); write(stream); } public void writeToQueue(PacketEncoder... encoders) { synchronized(streamLock) { for (PacketEncoder enc : encoders) enc.writeToStream(queuedStream, this); } } public void writeToQueue(ServerPacket packet) { synchronized(streamLock) { if (packet.size != 0) throw new Error(""Cannot write empty packet for a packet that isn't meant to be empty.""); queuedStream.writePacket(isaac, packet.opcode, true); } } public ChannelFuture flush() { synchronized(streamLock) { ChannelFuture future = write(queuedStream); queuedStream = new OutputStream(); return future; } } public void write(PacketEncoder... encoders) { synchronized(streamLock) { for (PacketEncoder enc : encoders) enc.writeToStream(queuedStream, this); flush(); } } public void write(ServerPacket packet) { synchronized(streamLock) { if (packet.size != 0) throw new Error(""Cannot write empty packet for a packet that isn't meant to be empty.""); queuedStream.writePacket(isaac, packet.opcode, true); flush(); } } public void writeNoIsaac(PacketEncoder encoder) { synchronized(streamLock) { encoder.writeToStream(queuedStream, null); flush(); } } public final ChannelFuture write(OutputStream outStream) { if (outStream == null || !channel.isActive()) return null; return channel.writeAndFlush(Unpooled.copiedBuffer(outStream.getBuffer(), 0, outStream.getOffset())); } public final ChannelFuture write(ByteBuf outStream) { if (outStream == null || !channel.isActive()) return null; return channel.writeAndFlush(outStream); } public final Channel getChannel() { return channel; } public final Decoder getDecoder() { return decoder; } @SuppressWarnings(""unchecked"") public final T getDecoder(Class clazz) { if (decoder != null && decoder.getClass().isAssignableFrom(clazz)) return (T) decoder; return null; } @SuppressWarnings(""unchecked"") public final T getEncoder(Class clazz) { if (encoder != null && encoder.getClass().isAssignableFrom(clazz)) return (T) encoder; return null; } public final void setDecoder(Decoder decoder) { packetQueue.clear(); this.decoder = decoder; } public final void setEncoder(Encoder encoder) { this.encoder = encoder; } public String getIP() { return channel == null ? """" : channel.remoteAddress().toString().split("":"")[0].replace(""/"", """"); } public String getLocalAddress() { return channel.localAddress().toString(); } public void refreshLastPacket() { this.lastPacket = System.currentTimeMillis(); } public boolean isClosed() { return System.currentTimeMillis() - this.lastPacket > 10000; } public IsaacKeyPair getIsaac() { return isaac; } public void setIsaac(IsaacKeyPair isaac) { this.isaac = isaac; } public void queuePacket(Packet packet) { if (packetQueue.size() > 100) packetQueue.poll(); packetQueue.add(packet); } public Queue getPacketQueue() { return packetQueue; } public void setPacketQueue(Queue packetQueue) { this.packetQueue = packetQueue; } public void incInIsaac() { if (isaac != null) isaac.inKey().nextInt(); } } " " package com.rs.lib.net.decoders; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.Decoder; import com.rs.lib.net.Session; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; import com.rs.lib.util.Logger; import com.rs.lib.util.Utils; public final class GameDecoder extends Decoder { private static Map PACKET_DECODERS = new HashMap<>(); private ClientPacket currPacket; public GameDecoder(Session session) { super(session); } public static void loadPacketDecoders() throws InvocationTargetException, NoSuchMethodException { try { Logger.info(GameDecoder.class, ""loadPacketDecoders"", ""Initializing packet decoders...""); List> classes = Utils.getClassesWithAnnotation(""com.rs.lib.net.packets.decoders"", PacketDecoder.class); for (Class clazz : classes) { ClientPacket[] packets = clazz.getAnnotation(PacketDecoder.class).value(); for (ClientPacket packet : packets) { if (PACKET_DECODERS.put(packet, (Packet) clazz.getConstructor().newInstance()) != null) System.err.println(""Duplicate decoders for packet: "" + packet); } } Set missing = new HashSet<>(); for (ClientPacket packet : ClientPacket.values()) { if (PACKET_DECODERS.get(packet) == null) { missing.add(packet); } } int handled = ClientPacket.values().length - missing.size(); Logger.info(GameDecoder.class, ""loadPacketsDecoder"", ""Packet decoders loaded for "" + handled + "" packets...""); Logger.info(GameDecoder.class, ""loadPacketsDecoder"", ""Packets missing: "" + missing); } catch (ClassNotFoundException | IOException | IllegalArgumentException | SecurityException | InstantiationException | IllegalAccessException e) { e.printStackTrace(); } } @Override public int decode(InputStream stream) { while (stream.getRemaining() > 0) { int opcode = currPacket != null ? currPacket.getOpcode() : stream.readPacket(session.getIsaac()); ClientPacket packet = currPacket = ClientPacket.forOpcode(opcode); if (packet == null) { Logger.error(GameDecoder.class, ""decode"", ""Invalid opcode: "" + opcode + "".""); return -1; } int start = stream.getOffset(); int length = packet.getSize(); if ((length == -1 && stream.getRemaining() < 1) || (length == -2 && stream.getRemaining() < 2)) return start; if (length == -1) length = stream.readUnsignedByte(); else if (length == -2) length = stream.readUnsignedShort(); if (stream.getRemaining() < length) return start; byte[] data = new byte[length]; stream.readBytes(data); try { currPacket = null; queuePacket(packet, new InputStream(data)); } catch (Throwable e) { Logger.handle(GameDecoder.class, ""decode"", e); } } return stream.getOffset(); } public void queuePacket(ClientPacket packet, InputStream stream) { Packet decoder = PACKET_DECODERS.get(packet); if (decoder != null) session.queuePacket(decoder.decodeAndCreateInstance(stream).setOpcode(packet)); else Logger.warn(GameDecoder.class, ""queuePacket"", ""Unhandled packet: "" + packet); } public static Map getDecoders() { return PACKET_DECODERS; } } " " package com.rs.lib.net.decoders; import com.rs.cache.Cache; import com.rs.lib.io.InputStream; import com.rs.lib.net.Decoder; import com.rs.lib.net.Session; import com.rs.lib.net.encoders.GrabEncoder; import com.rs.lib.util.Logger; public final class GrabDecoder extends Decoder { public GrabDecoder(Session connection) { super(connection); } @Override public final int decode(InputStream stream) { if (stream.getRemaining() > 750) { Logger.error(GrabDecoder.class, ""decode"", ""Incoming crash from: "" + session.getIP() + "" - Size: "" + stream.getRemaining()); session.getChannel().close(); } while (stream.getRemaining() >= 6 && session.getChannel().isActive()) { int packetId = stream.readUnsignedByte(); if (packetId == 0 || packetId == 1) decodeRequestCacheContainer(stream, packetId == 1); else decodeOtherPacket(stream, packetId); } return stream.getOffset(); } private final void decodeRequestCacheContainer(InputStream stream, boolean priority) { int indexId = stream.readUnsignedByte(); int archiveId = stream.readInt(); if (archiveId < 0) return; if (indexId != 255) { if (Cache.STORE.getIndices().length <= indexId || Cache.STORE.getIndices()[indexId] == null || !Cache.STORE.getIndices()[indexId].archiveExists(archiveId)) return; } else if (archiveId != 255) if (Cache.STORE.getIndices().length <= archiveId || Cache.STORE.getIndices()[archiveId] == null) return; session.getEncoder(GrabEncoder.class).sendCacheArchive(indexId, archiveId, priority); } private final void decodeOtherPacket(InputStream stream, int packetId) { if (packetId == 7) { session.getChannel().close(); return; } if (packetId == 4) { session.getEncoder(GrabEncoder.class).setEncryptionValue(stream.readUnsignedByte()); if (stream.readUnsignedShort() != 0) session.getChannel().close(); } else { stream.skip(5); } } } " " package com.rs.lib.net.encoders; import com.rs.lib.net.Encoder; import com.rs.lib.net.Session; import com.rs.lib.net.packets.PacketEncoder; public class GenericEncoder extends Encoder { public GenericEncoder(Session session) { super(session); } public void write(PacketEncoder packet) { session.writeToQueue(packet); } } " " package com.rs.lib.net.encoders; import java.io.IOException; import com.rs.cache.Cache; import com.rs.lib.Constants; import com.rs.lib.io.OutputStream; import com.rs.lib.net.Encoder; import com.rs.lib.net.Session; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; public final class GrabEncoder extends Encoder { private static byte[] CHECKSUM_CONTAINER; private int encryptionValue; public GrabEncoder(Session connection) { super(connection); } public final void sendOutdatedClientPacket() { OutputStream stream = new OutputStream(1); stream.writeByte(6); ChannelFuture future = session.write(stream); if (future != null) future.addListener(ChannelFutureListener.CLOSE); else session.getChannel().close(); } public final void sendOutOfDateClientVersionPacket() { OutputStream stream = new OutputStream(1); stream.writeByte(25); ChannelFuture future = session.write(stream); if (future != null) future.addListener(ChannelFutureListener.CLOSE); else session.getChannel().close(); } public final void sendStartUpPacket() { OutputStream stream = new OutputStream(1 + Constants.GRAB_SERVER_KEYS.length * 4); stream.writeByte(0); for (int key : Constants.GRAB_SERVER_KEYS) stream.writeInt(key); session.write(stream); } public final void sendCacheArchive(int indexId, int containerId, boolean priority) { if (indexId == 255 && containerId == 255) { if (CHECKSUM_CONTAINER == null) CHECKSUM_CONTAINER = Cache.STORE.getChecksumContainer(Constants.RSA_PRIVATE_EXPONENT, Constants.RSA_PRIVATE_MODULUS); session.write(new OutputStream(CHECKSUM_CONTAINER)); } else { session.write(getArchivePacketData(indexId, containerId, priority)); } } public final ByteBuf getArchivePacketData(int indexId, int archiveId, boolean priority) { try { if (indexId != 255) { if (archiveId > Cache.STORE.getIndices()[indexId].getMainFile().getArchivesCount()) return null; if (indexId > Cache.STORE.getIndices().length) return null; } } catch (IOException e) { e.printStackTrace(); } byte[] archive = indexId == 255 ? Cache.STORE.getIndex255().getArchiveData(archiveId) : Cache.STORE.getIndices()[indexId].getMainFile().getArchiveData(archiveId); if (archive == null) return null; int compression = archive[0] & 0xff; int length = ((archive[1] & 0xff) << 24) + ((archive[2] & 0xff) << 16) + ((archive[3] & 0xff) << 8) + (archive[4] & 0xff); int settings = compression; if (!priority) settings |= 0x80; ByteBuf buffer = Unpooled.buffer(); buffer.writeByte(indexId); buffer.writeInt(archiveId); buffer.writeByte(settings); buffer.writeInt(length); int realLength = compression != 0 ? length + 4 : length; for (int index = 5; index < realLength + 5; index++) { if (buffer.writerIndex() % 512 == 0) { buffer.writeByte(255); } buffer.writeByte(archive[index]); } int v = encryptionValue; if (v != 0) { for (int i = 0; i < buffer.arrayOffset(); i++) buffer.setByte(i, buffer.getByte(i) ^ v); } return buffer; } public void setEncryptionValue(int encryptionValue) { this.encryptionValue = encryptionValue; } } " " package com.rs.lib.net.packets; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; public abstract class Packet { private ClientPacket opcode; private long timeRecieved; public abstract Packet decodeAndCreateInstance(InputStream stream); public final ClientPacket getOpcode() { return opcode; } public final Packet setOpcode(ClientPacket opcode) { this.timeRecieved = System.currentTimeMillis(); this.opcode = opcode; return this; } public long getTimeRecieved() { return timeRecieved; } } " " package com.rs.lib.net.packets; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.rs.lib.net.ClientPacket; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface PacketDecoder { ClientPacket[] value(); } " " package com.rs.lib.net.packets; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.Session; public abstract class PacketEncoder { private ServerPacket packet; public PacketEncoder(ServerPacket packet) { this.packet = packet; } public abstract void encodeBody(OutputStream stream); public final void writeToStream(OutputStream stream, Session session) { switch(packet.size) { case -1: stream.writePacketVarByte(session == null ? null : session.getIsaac(), packet.opcode, true); encodeBody(stream); stream.endPacketVarByte(); break; case -2: stream.writePacketVarShort(session == null ? null : session.getIsaac(), packet.opcode, true); encodeBody(stream); stream.endPacketVarShort(); break; default: stream.writePacket(session == null ? null : session.getIsaac(), packet.opcode, true); encodeBody(stream); break; } } public ServerPacket getPacket() { return packet; } } " " package com.rs.lib.net.packets; public interface PacketHandler { void handle(T player, K packet); } " " package com.rs.lib.net.packets.decoders; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder({ ClientPacket.OBJECT_OP1, ClientPacket.OBJECT_OP2, ClientPacket.OBJECT_OP3, ClientPacket.OBJECT_OP4, ClientPacket.OBJECT_OP5, ClientPacket.OBJECT_EXAMINE }) public class ObjectOp extends Packet { private int objectId; private int x, y; private boolean forceRun; @Override public Packet decodeAndCreateInstance(InputStream stream) { ObjectOp p = new ObjectOp(); p.y = stream.readUnsignedShort(); p.x = stream.readUnsignedShort(); p.objectId = stream.readInt(); p.forceRun = stream.readUnsignedByte128() == 1; return p; } public int getObjectId() { return objectId; } public int getX() { return x; } public int getY() { return y; } public boolean isForceRun() { return forceRun; } } " " package com.rs.lib.net.packets.decoders; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.ACCOUNT_CREATION_STAGE) public class AccountCreationStage extends Packet { private int stage; @Override public Packet decodeAndCreateInstance(InputStream stream) { AccountCreationStage p = new AccountCreationStage(); p.stage = stream.readUnsignedByte(); return p; } public int getStage() { return stage; } } " " package com.rs.lib.net.packets.decoders; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; import java.lang.SuppressWarnings; @PacketDecoder(ClientPacket.CLIENT_CHEAT) public class ClientCheat extends Packet { private boolean client; private String command; @Override public Packet decodeAndCreateInstance(InputStream stream) { ClientCheat p = new ClientCheat(); p.client = stream.readUnsignedByte() == 1; @SuppressWarnings(""unused"") boolean unknown = stream.readUnsignedByte() == 1; p.command = stream.readString(); return p; } public String getCommand() { return command; } public boolean isClient() { return client; } } " " package com.rs.lib.net.packets.decoders; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.CLIENT_FOCUS) public class ClientFocus extends Packet { private boolean inFocus; @Override public Packet decodeAndCreateInstance(InputStream stream) { ClientFocus p = new ClientFocus(); p.inFocus = stream.readByte() == 1; return p; } public boolean isInFocus() { return inFocus; } } " " package com.rs.lib.net.packets.decoders; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.CLOSE_INTERFACE) public class CloseInterface extends Packet { @Override public Packet decodeAndCreateInstance(InputStream stream) { return new CloseInterface(); } } " " package com.rs.lib.net.packets.decoders; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.CUTSCENE_FINISHED) public class CutsceneFinished extends Packet { @Override public Packet decodeAndCreateInstance(InputStream stream) { return new CutsceneFinished(); } } " " package com.rs.lib.net.packets.decoders; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.EMAIL_VALIDATION_CHANGE_ADDRESS) public class EmailChangeAddress extends Packet { private String email; private String email2; @Override public Packet decodeAndCreateInstance(InputStream stream) { EmailChangeAddress p = new EmailChangeAddress(); p.email = stream.readString(); p.email2 = stream.readString(); return p; } public String getEmail() { return email; } public String getEmail2() { return email2; } }" " package com.rs.lib.net.packets.decoders; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.GE_ITEM_SELECT) public class GEItemSelect extends Packet { private int itemId; @Override public Packet decodeAndCreateInstance(InputStream stream) { GEItemSelect p = new GEItemSelect(); p.itemId = stream.readShort(); return p; } public int getItemId() { return itemId; } } " " package com.rs.lib.net.packets.decoders; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder({ ClientPacket.GROUND_ITEM_OP1, ClientPacket.GROUND_ITEM_OP2, ClientPacket.GROUND_ITEM_OP3, ClientPacket.GROUND_ITEM_OP4, ClientPacket.GROUND_ITEM_OP5, ClientPacket.GROUND_ITEM_EXAMINE }) public class GroundItemOp extends Packet { private int objectId; private int x, y; private boolean forceRun; @Override public Packet decodeAndCreateInstance(InputStream stream) { GroundItemOp packet = new GroundItemOp(); packet.objectId = stream.readUnsignedShortLE128(); packet.forceRun = stream.readByteC() == 1; packet.y = stream.readUnsignedShort(); packet.x = stream.readUnsignedShort128(); return packet; } public int getObjectId() { return objectId; } public int getX() { return x; } public int getY() { return y; } public boolean isForceRun() { return forceRun; } } " " package com.rs.lib.net.packets.decoders; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.KEEPALIVE) public class KeepAlive extends Packet { @Override public Packet decodeAndCreateInstance(InputStream stream) { return new KeepAlive(); } } " " package com.rs.lib.net.packets.decoders; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.KEY_PRESS) public class KeyPress extends Packet { private int keyCode; private int time; @Override public Packet decodeAndCreateInstance(InputStream stream) { KeyPress p = new KeyPress(); p.keyCode = stream.readByte(); p.time = stream.readTriByte(); return p; } public int getKeyCode() { return keyCode; } public int getTime() { return time; } } " " package com.rs.lib.net.packets.decoders; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.LOBBY_HYPERLINK) public class LobbyHyperlink extends Packet { private String service; private String page; private int flags; @Override public Packet decodeAndCreateInstance(InputStream stream) { LobbyHyperlink p = new LobbyHyperlink(); p.service = stream.readString(); p.page = stream.readString(); stream.readString(); p.flags = stream.readByte(); return p; } public String getService() { return service; } public String getPage() { return page; } public int getFlags() { return flags; } } " " package com.rs.lib.net.packets.decoders; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.MOVE_CAMERA) public class MoveCamera extends Packet { private int angleX, angleY; @Override public Packet decodeAndCreateInstance(InputStream stream) { MoveCamera p = new MoveCamera(); p.angleX = stream.readShortLE128(); p.angleY = stream.readShort128(); return p; } public int getAngleX() { return angleX; } public int getAngleY() { return angleY; } } " " package com.rs.lib.net.packets.decoders; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.SOUND_EFFECT_MUSIC_ENDED) public class MusicEnded extends Packet { private int musicId; @Override public Packet decodeAndCreateInstance(InputStream stream) { MusicEnded p = new MusicEnded(); p.musicId = stream.readInt(); return p; } public int getMusicId() { return musicId; } } " " package com.rs.lib.net.packets.decoders; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder({ ClientPacket.NPC_OP1, ClientPacket.NPC_OP2, ClientPacket.NPC_OP3, ClientPacket.NPC_OP4, ClientPacket.NPC_OP5, ClientPacket.NPC_EXAMINE }) public class NPCOp extends Packet { private int npcIndex; private boolean forceRun; @Override public Packet decodeAndCreateInstance(InputStream stream) { NPCOp p = new NPCOp(); p.npcIndex = stream.readUnsignedShort(); p.forceRun = stream.readByte() == 1; return p; } public int getNpcIndex() { return npcIndex; } public boolean isForceRun() { return forceRun; } } " " package com.rs.lib.net.packets.decoders; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder({ ClientPacket.PLAYER_OP1, ClientPacket.PLAYER_OP2, ClientPacket.PLAYER_OP3, ClientPacket.PLAYER_OP4, ClientPacket.PLAYER_OP5, ClientPacket.PLAYER_OP6, ClientPacket.PLAYER_OP7, ClientPacket.PLAYER_OP8, ClientPacket.PLAYER_OP9, ClientPacket.PLAYER_OP10 }) public class PlayerOp extends Packet { private int pid; private boolean forceRun; @Override public Packet decodeAndCreateInstance(InputStream stream) { PlayerOp p = new PlayerOp(); p.pid = stream.readShort(); p.forceRun = stream.read128Byte() == 1; return p; } public int getPid() { return pid; } public boolean isForceRun() { return forceRun; } } " " package com.rs.lib.net.packets.decoders; import java.util.HashMap; import java.util.Map; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.REFLECTION_CHECK) public class ReflectionCheckResponse extends Packet { public enum ResponseCode { SUCCESS(0), NUMBER(1), STRING(2), OTHER(4), CHECK_EXCEPTION_CLASS_NOT_FOUND(-1), CHECK_EXCEPTION_SECURITY(-2), //Thrown when classloader for desired class is null CHECK_EXCEPTION_NULLPOINTER(-3), CHECK_EXCEPTION(-4), CHECK_THROWABLE(-5), RESP_EXCEPTION_CLASS_NOT_FOUND(-10), RESP_EXCEPTION_INVALID_CLASS(-11), RESP_EXCEPTION_STREAM_CORRUPTED(-12), RESP_EXCEPTION_OPTIONAL_DATA(-13), RESP_EXCEPTION_ILLEGAL_ACCESS(-14), RESP_EXCEPTION_ILLEGAL_ARGUMENT(-15), RESP_EXCEPTION_INVOCATION_TARGET(-16), RESP_EXCEPTION_SECURITY(-17), RESP_EXCEPTION_IO(-18), RESP_EXCEPTION_NULLPOINTER(-19), RESP_EXCEPTION(-20), RESP_THROWABLE(-21); private static Map MAP = new HashMap<>(); static { for (ResponseCode r : ResponseCode.values()) MAP.put(r.id, r); } public static ResponseCode forId(int id) { return MAP.get(id); } private int id; ResponseCode(int id) { this.id = id; } } private int id; private ResponseCode reponseCode; private InputStream data; @Override public Packet decodeAndCreateInstance(InputStream stream) { ReflectionCheckResponse p = new ReflectionCheckResponse(); p.id = stream.readInt(); p.data = stream; return p; } public int getId() { return id; } public InputStream getData() { return data; } public ResponseCode getCode() { return reponseCode; } } " " package com.rs.lib.net.packets.decoders; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.REGION_LOADED_CONFIRM) public class RegionLoaded extends Packet { @Override public Packet decodeAndCreateInstance(InputStream stream) { return new RegionLoaded(); } } " " package com.rs.lib.net.packets.decoders; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.REPORT_ABUSE) public class ReportAbuse extends Packet { private String username; private int type; private boolean mute; @Override public Packet decodeAndCreateInstance(InputStream stream) { ReportAbuse p = new ReportAbuse(); this.username = stream.readString(); this.type = stream.readUnsignedByte(); this.mute = stream.readUnsignedByte() == 1; stream.readString(); return p; } public String getUsername() { return username; } public int getType() { return type; } public boolean isMute() { return mute; } } " " package com.rs.lib.net.packets.decoders; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.REQUEST_WORLD_LIST) public class RequestWorldList extends Packet { private int worldId; @Override public Packet decodeAndCreateInstance(InputStream stream) { RequestWorldList packet = new RequestWorldList(); packet.worldId = stream.readInt(); return packet; } public int getWorldId() { return worldId; } } " " package com.rs.lib.net.packets.decoders; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.RESUME_COUNTDIALOG) public class ResumeCountDialogue extends Packet { private int value; @Override public Packet decodeAndCreateInstance(InputStream stream) { ResumeCountDialogue p = new ResumeCountDialogue(); p.value = stream.readInt(); return p; } public int getValue() { return value; } } " " package com.rs.lib.net.packets.decoders; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.RESUME_HSLDIALOG) public class ResumeHSLDialogue extends Packet { private int colorId; @Override public Packet decodeAndCreateInstance(InputStream stream) { ResumeHSLDialogue d = new ResumeHSLDialogue(); d.colorId = stream.readUnsignedShort(); return d; } public int getColorId() { return colorId; } } " " package com.rs.lib.net.packets.decoders; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder({ ClientPacket.RESUME_TEXTDIALOG, ClientPacket.RESUME_CLANFORUMQFCDIALOG, ClientPacket.RESUME_NAMEDIALOG }) public class ResumeTextDialogue extends Packet { private String text; @Override public Packet decodeAndCreateInstance(InputStream stream) { ResumeTextDialogue p = new ResumeTextDialogue(); p.text = stream.readString(); return p; } public String getText() { return text; } } " " package com.rs.lib.net.packets.decoders; import java.util.HashMap; import java.util.Map; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.SEND_PREFERENCES) public class SendPreferences extends Packet { public enum Preference { ANTI_ALIASING(1), BLOOM(2), BRIGHTNESS(3), UNK4(4), UNK5(5), UNK6(6), FOG(7), UNK8(8), GROUND_DECORATION(9), IDLE_ANIMATIONS(10), LIGHT_DETAIL(11), SCENERY_SHADOWS(12), UNK13(13), PARTICLES(14), UNK15(15), UNK16(16), UNK17(17), UNK18(18), TEXTURES(19), UNK20(20), WATER(22), SCREEN_SIZE(23), CUSTOM_CURSORS(24), GRAPHICS(25), CPU(26), UNK27(27), SAFE_MODE(28), UNK29(29), SOUND_EFFECT_VOL(30), AMBIENT_SOUND_VOL(31), VOICE_VOL(32), MUSIC_VOL(33), UNK34(34), MONO_STEREO(35); private static Map MAP = new HashMap<>(); static { for (Preference p : Preference.values()) MAP.put(p.index, p); } public static Preference forIndex(int index) { return MAP.get(index); } private int index; private Preference(int index) { this.index = index; } } private Map preferences = new HashMap<>(); @Override public Packet decodeAndCreateInstance(InputStream stream) { SendPreferences s = new SendPreferences(); int currIdx = 0; while(stream.getRemaining() > 0) { Preference p = Preference.forIndex(currIdx++); if (p != null) s.preferences.put(p, stream.readUnsignedByte()); else stream.readUnsignedByte(); } return s; } } " " package com.rs.lib.net.packets.decoders; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.SCREEN_SIZE) public class SetScreenSize extends Packet { private int displayMode; private int width, height; private boolean switchScreenMode; @Override public Packet decodeAndCreateInstance(InputStream stream) { SetScreenSize p = new SetScreenSize(); p.displayMode = stream.readUnsignedByte(); p.width = stream.readUnsignedShort(); p.height = stream.readUnsignedShort(); p.switchScreenMode = stream.readUnsignedByte() == 1; return p; } public int getDisplayMode() { return displayMode; } public int getWidth() { return width; } public int getHeight() { return height; } public boolean isSwitchScreenMode() { return switchScreenMode; } } " " package com.rs.lib.net.packets.decoders; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder({ ClientPacket.ADD_FRIEND, ClientPacket.ADD_IGNORE, ClientPacket.REMOVE_FRIEND, ClientPacket.REMOVE_IGNORE }) public class SocialAddRemove extends Packet { private String name; private boolean temp; @Override public Packet decodeAndCreateInstance(InputStream stream) { SocialAddRemove p = new SocialAddRemove(); p.name = stream.readString(); p.temp = stream.getRemaining() > 0 ? stream.readUnsignedByte() == 1 : false; return p; } public String getName() { return name; } public boolean isTemp() { return temp; } } " " package com.rs.lib.net.packets.decoders; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.TRANSMITVAR_VERIFYID) public class TransmitVarVerifyId extends Packet { private int id; @Override public Packet decodeAndCreateInstance(InputStream stream) { TransmitVarVerifyId p = new TransmitVarVerifyId(); p.id = stream.readInt(); return p; } public int getId() { return id; } } " " package com.rs.lib.net.packets.decoders; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder({ ClientPacket.WALK, ClientPacket.MINI_WALK }) public class Walk extends Packet { private int x, y; private boolean forceRun; @Override public Packet decodeAndCreateInstance(InputStream stream) { Walk p = new Walk(); p.forceRun = stream.readUnsignedByte() == 1; p.x = stream.readUnsignedShort(); p.y = stream.readUnsignedShortLE(); return p; } public int getX() { return x; } public int getY() { return y; } public boolean isForceRun() { return forceRun; } } " " package com.rs.lib.net.packets.decoders; import com.rs.lib.game.WorldTile; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.WORLD_MAP_CLICK) public class WorldMapClick extends Packet { private WorldTile tile; @Override public Packet decodeAndCreateInstance(InputStream stream) { WorldMapClick packet = new WorldMapClick(); int coordinateHash = stream.readIntLE(); packet.tile = WorldTile.of(coordinateHash >> 14, coordinateHash & 0x3fff, coordinateHash >> 28); return packet; } public WorldTile getTile() { return tile; } } " "// This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see . // // Copyright � 2021 Trenton Kress // This file is part of project: Darkan // package com.rs.lib.net.packets.decoders; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.WRITE_PING) public class WritePing extends Packet { private int ping; @Override public Packet decodeAndCreateInstance(InputStream stream) { WritePing p = new WritePing(); p.ping = stream.readUnsignedShort(); return p; } public int getPing() { return ping; } } " " package com.rs.lib.net.packets.decoders; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.Session; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder({ ClientPacket.CHECK_EMAIL_VALIDITY, ClientPacket.SEND_SIGN_UP_FORM }) public class XTEACreationPacket extends Packet { private InputStream stream; @Override public Packet decodeAndCreateInstance(InputStream stream) { XTEACreationPacket p = new XTEACreationPacket(); p.stream = stream; return p; } public InputStream getDecodedBuffer(Session session) { stream.decodeXTEA(session.getIsaac().inKey().getSeeds(), stream.getOffset(), stream.getLength()); return stream; } } " " package com.rs.lib.net.packets.decoders.chat; import com.rs.cache.Cache; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; import com.rs.lib.util.Utils; @PacketDecoder(ClientPacket.CHAT) public class Chat extends Packet { private int type = -1; private int color; private int effect; private String message; @Override public Packet decodeAndCreateInstance(InputStream stream) { Chat chat = new Chat(); chat.color = Utils.clampI(stream.readUnsignedByte(), 0, 12); chat.effect = Utils.clampI(stream.readUnsignedByte(), 0, 5); chat.message = Utils.fixChatMessage(Cache.STORE.getHuffman().readEncryptedMessage(200, stream)); return chat; } public int getColor() { return color; } public int getEffect() { return effect; } public String getMessage() { return message; } public int getType() { return type; } public Chat setType(int type) { this.type = type; return this; } } " " package com.rs.lib.net.packets.decoders.chat; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.CHAT_SETFILTER) public class ChatSetFilter extends Packet { private int publicFilter; private int privateFilter; private int tradeFilter; @Override public Packet decodeAndCreateInstance(InputStream stream) { ChatSetFilter packet = new ChatSetFilter(); packet.publicFilter = stream.readByte(); packet.privateFilter = stream.readByte(); packet.tradeFilter = stream.readByte(); return packet; } public int getPublicFilter() { return publicFilter; } public int getPrivateFilter() { return privateFilter; } public int getTradeFilter() { return tradeFilter; } } " " package com.rs.lib.net.packets.decoders.chat; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.CHAT_TYPE) public class ChatType extends Packet { private int type; @Override public Packet decodeAndCreateInstance(InputStream stream) { ChatType packet = new ChatType(); packet.type = stream.readUnsignedByte(); return packet; } public int getType() { return type; } } " " package com.rs.lib.net.packets.decoders.chat; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.QUICKCHAT_PRIVATE) public class QCPrivate extends Packet { private String toUsername; private int qcId; private byte[] messageData; private byte[] completedData; @Override public Packet decodeAndCreateInstance(InputStream stream) { QCPrivate p = new QCPrivate(); p.toUsername = stream.readString(); p.qcId = stream.readUnsignedShort(); if (stream.getRemaining() > 3 + p.toUsername.length()) { p.messageData = new byte[stream.getRemaining() - (3 + p.toUsername.length())]; stream.readBytes(p.messageData); } return p; } public String getToUsername() { return toUsername; } public int getQcId() { return qcId; } public byte[] getMessageData() { return messageData; } public byte[] getCompletedData() { return completedData; } public void setCompletedData(byte[] completedData) { this.completedData = completedData; } } " " package com.rs.lib.net.packets.decoders.chat; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.QUICKCHAT_PUBLIC) public class QCPublic extends Packet { private int chatType; private int qcId; private byte[] messageData; private byte[] completedData; @Override public Packet decodeAndCreateInstance(InputStream stream) { QCPublic p = new QCPublic(); p.chatType = stream.readByte(); p.qcId = stream.readUnsignedShort(); p.messageData = null; if (stream.getRemaining() > 0) { p.messageData = new byte[stream.getRemaining()]; stream.readBytes(p.messageData); } return p; } public int getChatType() { return chatType; } public int getQcId() { return qcId; } public byte[] getMessageData() { return messageData; } public byte[] getCompletedData() { return completedData; } public void setCompletedData(byte[] completedData) { this.completedData = completedData; } } " " package com.rs.lib.net.packets.decoders.chat; import com.rs.cache.Cache; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; import com.rs.lib.util.Utils; @PacketDecoder(ClientPacket.SEND_PRIVATE_MESSAGE) public class SendPrivateMessage extends Packet { private String toDisplayName; private String message; @Override public Packet decodeAndCreateInstance(InputStream stream) { SendPrivateMessage p = new SendPrivateMessage(); p.toDisplayName = stream.readString(); p.message = Utils.fixChatMessage(Cache.STORE.getHuffman().readEncryptedMessage(150, stream)); return p; } public String getToDisplayName() { return toDisplayName; } public String getMessage() { return message; } } " " package com.rs.lib.net.packets.decoders.clan; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.CLANCHANNEL_KICKUSER) public class CCKick extends Packet { private boolean guest; private String name; @Override public Packet decodeAndCreateInstance(InputStream stream) { CCKick p = new CCKick(); p.guest = stream.readByte() == 1; stream.readUnsignedShort(); p.name = stream.readString(); return p; } public String getName() { return name; } public boolean isGuest() { return guest; } } " " package com.rs.lib.net.packets.decoders.fc; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.FC_JOIN) public class FCJoin extends Packet { private String name; //Required for reflection in decoder parsing public FCJoin() { } public FCJoin(String name) { this.name = name; } @Override public Packet decodeAndCreateInstance(InputStream stream) { FCJoin p = new FCJoin(); if (stream.getRemaining() > 0) p.name = stream.readString(); return p; } public String getName() { return name; } } " " package com.rs.lib.net.packets.decoders.fc; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.FC_KICK) public class FCKick extends Packet { private String name; @Override public Packet decodeAndCreateInstance(InputStream stream) { FCKick p = new FCKick(); p.name = stream.readString(); return p; } public String getName() { return name; } } " " package com.rs.lib.net.packets.decoders.fc; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.FC_SET_RANK) public class FCSetRank extends Packet { private String name; private int rank; @Override public Packet decodeAndCreateInstance(InputStream stream) { FCSetRank p = new FCSetRank(); p.rank = stream.readUnsigned128Byte(); p.name = stream.readString(); return p; } public String getName() { return name; } public int getRank() { return rank; } } " " package com.rs.lib.net.packets.decoders.interfaces; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.IF_CONTINUE) public class IFContinue extends Packet { private int interfaceId; private int componentId; private int slotId; @Override public Packet decodeAndCreateInstance(InputStream stream) { IFContinue p = new IFContinue(); int interfaceHash = stream.readIntV1(); stream.readShortLE128(); p.interfaceId = interfaceHash >> 16; p.slotId = (interfaceHash & 0xFF); p.componentId = interfaceHash - (p.interfaceId << 16); return p; } public int getInterfaceId() { return interfaceId; } public int getComponentId() { return componentId; } public int getSlotId() { return slotId; } } " " package com.rs.lib.net.packets.decoders.interfaces; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.IF_DRAG_ONTO_IF) public class IFDragOntoIF extends Packet { private int fromInter; private int toInter; private int fromComp; private int toComp; private int fromSlot; private int toSlot; @Override public Packet decodeAndCreateInstance(InputStream stream) { IFDragOntoIF p = new IFDragOntoIF(); p.toSlot = stream.readShortLE128(); p.fromSlot = stream.readShortLE(); stream.readShort(); stream.readShortLE128(); int fromInterfaceHash = stream.readIntV1(); int toInterfaceHash = stream.readIntLE(); p.toInter = toInterfaceHash >> 16; p.toComp = toInterfaceHash - (p.toInter << 16); p.fromInter = fromInterfaceHash >> 16; p.fromComp = fromInterfaceHash - (p.fromInter << 16); return p; } public int getFromInter() { return fromInter; } public int getToInter() { return toInter; } public int getFromComp() { return fromComp; } public int getToComp() { return toComp; } public int getFromSlot() { return fromSlot; } public int getToSlot() { return toSlot; } } " " package com.rs.lib.net.packets.decoders.interfaces; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.IF_ON_GROUND_ITEM) public class IFOnGroundItem extends Packet { private int interfaceId; private int componentId; private int slotId; private int itemIdContainer; private int itemId; private int x; private int y; private boolean forceRun; @Override public Packet decodeAndCreateInstance(InputStream stream) { IFOnGroundItem p = new IFOnGroundItem(); p.itemIdContainer = stream.readShort128(); int interfaceHash = stream.readIntV2(); p.itemId = stream.readShort(); p.forceRun = stream.read128Byte() == 1; p.slotId = stream.readShortLE128(); p.y = stream.readShortLE128(); p.x = stream.readShortLE(); p.interfaceId = interfaceHash >> 16; p.componentId = interfaceHash - (p.interfaceId << 16); return p; } public int getInterfaceId() { return interfaceId; } public int getComponentId() { return componentId; } public int getSlotId() { return slotId; } public int getItemId() { return itemId; } public int getX() { return x; } public int getY() { return y; } public int getItemIdContainer() { return itemIdContainer; } public boolean isForceRun() { return forceRun; } } " " package com.rs.lib.net.packets.decoders.interfaces; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.IF_ON_IF) public class IFOnIF extends Packet { private int fromInter; private int toInter; private int fromComp; private int toComp; private int fromSlot; private int toSlot; private int fromItemId; private int toItemId; @Override public Packet decodeAndCreateInstance(InputStream stream) { IFOnIF p = new IFOnIF(); p.toSlot = stream.readShortLE128(); p.fromSlot = stream.readShortLE(); p.toItemId = stream.readShortLE128(); int hash2 = stream.readIntLE(); int hash1 = stream.readIntV2(); p.fromItemId = stream.readShortLE(); p.fromInter = hash1 >> 16; p.toInter = hash2 >> 16; p.fromComp = hash1 & 0xFFFF; p.toComp = hash2 & 0xFFFF; return p; } public int getFromInter() { return fromInter; } public int getToInter() { return toInter; } public int getFromComp() { return fromComp; } public int getToComp() { return toComp; } public int getFromSlot() { return fromSlot; } public int getToSlot() { return toSlot; } public int getFromItemId() { return fromItemId; } public int getToItemId() { return toItemId; } } " " package com.rs.lib.net.packets.decoders.interfaces; import java.lang.SuppressWarnings; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.IF_ON_NPC) public class IFOnNPC extends Packet { private int interfaceId; private int componentId; private int slotId; private int itemId; private int npcIndex; @Override public Packet decodeAndCreateInstance(InputStream stream) { IFOnNPC p = new IFOnNPC(); int interfaceHash = stream.readIntV2(); p.npcIndex = stream.readUnsignedShortLE128(); @SuppressWarnings(""unused"") boolean unknown = stream.read128Byte() == 1; p.itemId = stream.readUnsignedShortLE128(); p.slotId = stream.readUnsignedShort128(); p.interfaceId = interfaceHash >> 16; p.componentId = interfaceHash - (p.interfaceId << 16); if (p.componentId == 65535) p.componentId = -1; return p; } public int getInterfaceId() { return interfaceId; } public int getComponentId() { return componentId; } public int getSlotId() { return slotId; } public int getItemId() { return itemId; } public int getNpcIndex() { return npcIndex; } } " " package com.rs.lib.net.packets.decoders.interfaces; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.IF_ON_OBJECT) public class IFOnObject extends Packet { private int interfaceId; private int componentId; private int slotId; private int itemId; private int objectId; private int x; private int y; private boolean forceRun; @Override public Packet decodeAndCreateInstance(InputStream stream) { IFOnObject p = new IFOnObject(); p.x = stream.readShortLE128(); p.forceRun = stream.read128Byte() == 1; p.objectId = stream.readIntV1(); int interfaceHash = stream.readInt(); p.itemId = stream.readShortLE(); p.slotId = stream.readShort128(); p.y = stream.readShortLE(); p.interfaceId = interfaceHash >> 16; p.componentId = interfaceHash - (p.interfaceId << 16); return p; } public int getInterfaceId() { return interfaceId; } public int getComponentId() { return componentId; } public int getSlotId() { return slotId; } public int getItemId() { return itemId; } public int getObjectId() { return objectId; } public int getX() { return x; } public int getY() { return y; } public boolean isForceRun() { return forceRun; } } " " package com.rs.lib.net.packets.decoders.interfaces; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; import java.lang.SuppressWarnings; @PacketDecoder(ClientPacket.IF_ON_PLAYER) public class IFOnPlayer extends Packet { private int interfaceId; private int componentId; private int slotId; private int itemId; private int playerIndex; @Override public Packet decodeAndCreateInstance(InputStream stream) { IFOnPlayer p = new IFOnPlayer(); p.slotId = stream.readUnsignedShort(); p.playerIndex = stream.readUnsignedShortLE(); @SuppressWarnings(""unused"") boolean unknown = stream.read128Byte() == 1; int interfaceHash = stream.readIntV2(); p.itemId = stream.readUnsignedShortLE(); p.interfaceId = interfaceHash >> 16; p.componentId = interfaceHash - (p.interfaceId << 16); if (p.componentId == 65535) p.componentId = -1; return p; } public int getInterfaceId() { return interfaceId; } public int getComponentId() { return componentId; } public int getSlotId() { return slotId; } public int getItemId() { return itemId; } public int getPlayerIndex() { return playerIndex; } } " " package com.rs.lib.net.packets.decoders.interfaces; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder({ ClientPacket.IF_OP1, ClientPacket.IF_OP2, ClientPacket.IF_OP3, ClientPacket.IF_OP4, ClientPacket.IF_OP5, ClientPacket.IF_OP6, ClientPacket.IF_OP7, ClientPacket.IF_OP8, ClientPacket.IF_OP9, ClientPacket.IF_OP10 }) public class IFOp extends Packet { private int interfaceId; private int componentId; private int slotId; private int itemId; @Override public Packet decodeAndCreateInstance(InputStream stream) { IFOp packet = new IFOp(); int interfaceHash = stream.readIntLE(); packet.interfaceId = interfaceHash >> 16; packet.componentId = interfaceHash - (packet.interfaceId << 16); packet.itemId = stream.readUnsignedShort(); packet.slotId = stream.readUnsignedShort128(); return packet; } public int getInterfaceId() { return interfaceId; } public int getComponentId() { return componentId; } public int getSlotId() { return slotId; } public int getItemId() { return itemId; } } " " package com.rs.lib.net.packets.decoders.lobby; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.CC_BAN) public class CCBan extends Packet { private String clan; public CCBan() { } public CCBan(String clan) { this.setOpcode(ClientPacket.CC_BAN); this.clan = clan; } @Override public Packet decodeAndCreateInstance(InputStream stream) { return null; } public String getClan() { return clan; } } " " package com.rs.lib.net.packets.decoders.lobby; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.CC_JOIN) public class CCJoin extends Packet { private String clan; public CCJoin() { } public CCJoin(String guestChatName) { this.setOpcode(ClientPacket.CC_JOIN); this.clan = guestChatName; } @Override public Packet decodeAndCreateInstance(InputStream stream) { return null; } public String getClan() { return clan; } } " " package com.rs.lib.net.packets.decoders.lobby; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.CC_LEAVE) public class CCLeave extends Packet { private boolean guest; public CCLeave() { } public CCLeave(boolean guest) { this.setOpcode(ClientPacket.CC_LEAVE); this.guest = guest; } @Override public Packet decodeAndCreateInstance(InputStream stream) { return null; } public boolean isGuest() { return guest; } } " "package com.rs.lib.net.packets.decoders.lobby; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.CLAN_ADDMEMBER) public class ClanAddMember extends Packet { private String username; public ClanAddMember() { } public ClanAddMember(String username) { this.setOpcode(ClientPacket.CLAN_ADDMEMBER); this.username = username; } @Override public Packet decodeAndCreateInstance(InputStream stream) { return null; } public String getUsername() { return username; } } " " package com.rs.lib.net.packets.decoders.lobby; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.CLAN_CHECKNAME) public class ClanCheckName extends Packet { private String name; private boolean approved; public ClanCheckName() { } public ClanCheckName(String name, boolean approved) { this.setOpcode(ClientPacket.CLAN_CHECKNAME); this.name = name; this.approved = approved; } @Override public Packet decodeAndCreateInstance(InputStream stream) { return null; } public String getName() { return name; } public boolean isApproved() { return approved; } } " " package com.rs.lib.net.packets.decoders.lobby; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.CLAN_CREATE) public class ClanCreate extends Packet { private String name; public ClanCreate() { } public ClanCreate(String name) { this.setOpcode(ClientPacket.CLAN_CREATE); this.name = name; } @Override public Packet decodeAndCreateInstance(InputStream stream) { return null; } public String getName() { return name; } } " "package com.rs.lib.net.packets.decoders.lobby; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.CLAN_KICKMEMBER) public class ClanKickMember extends Packet { private String username; public ClanKickMember() { } public ClanKickMember(String username) { this.setOpcode(ClientPacket.CLAN_KICKMEMBER); this.username = username; } @Override public Packet decodeAndCreateInstance(InputStream stream) { return null; } public String getUsername() { return username; } } " "package com.rs.lib.net.packets.decoders.lobby; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.CLAN_LEAVE) public class ClanLeave extends Packet { public ClanLeave() { this.setOpcode(ClientPacket.CLAN_LEAVE); } @Override public Packet decodeAndCreateInstance(InputStream stream) { return null; } } " " package com.rs.lib.net.packets.decoders.mouse; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.MOUSE_BUTTON_CLICK) public class MouseClickHW extends Packet { private int mouseButton; private int time; private int x, y; private boolean hardware; @Override public Packet decodeAndCreateInstance(InputStream stream) { MouseClickHW p = new MouseClickHW(); int positionHash = stream.readIntLE(); int flags = stream.readByte128(); p.time = stream.readShortLE(); p.y = positionHash >> 16; p.x = positionHash - (p.y << 16); p.mouseButton = flags >> 1; p.hardware = (flags - (p.mouseButton << 1)) == 0; return p; } public int getMouseButton() { return mouseButton; } public int getX() { return x; } public int getY() { return y; } public int getTime() { return time; } public boolean isHardware() { return hardware; } } " " package com.rs.lib.net.packets.decoders.mouse; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; @PacketDecoder(ClientPacket.MOUSE_CLICK) public class MouseClickJav extends Packet { private int mouseButton; private int time; private int x, y; @Override public Packet decodeAndCreateInstance(InputStream stream) { MouseClickJav p = new MouseClickJav(); int positionHash = stream.readIntLE(); int mouseHash = stream.readShort(); p.mouseButton = mouseHash >> 15; p.time = mouseHash - (p.mouseButton << 15); p.y = positionHash >> 16; p.x = positionHash - (p.y << 16); return p; } public int getMouseButton() { return mouseButton; } public int getTime() { return time; } public int getX() { return x; } public int getY() { return y; } } " "package com.rs.lib.net.packets.decoders.mouse; import java.util.ArrayList; import java.util.List; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; import com.rs.lib.net.packets.decoders.mouse.MouseTrailStep.Type; @PacketDecoder(ClientPacket.MOVE_MOUSE) public class MouseMoveHW extends Packet { private int frameCount; private int frameSteps; private List steps = new ArrayList<>(); @Override public Packet decodeAndCreateInstance(InputStream stream) { MouseMoveHW p = new MouseMoveHW(); p.frameSteps = stream.readUnsignedByte(); p.frameCount = stream.readUnsignedByte(); while(stream.getRemaining() > 0) { int peek = stream.peekUnsignedByte(); int frames, dX, dY; Type type = Type.MOVE_OFFSET; if (peek >= 224) { frames = stream.readUnsignedShort() - 57344; int posHash = stream.readInt(); dY = posHash >> 16; dX = posHash & 0xFFFF; type = Type.SET_POSITION; } else if (peek >= 192) { frames = stream.readUnsignedByte() - 192; int posHash = stream.readInt(); dY = posHash >> 16; dX = posHash & 0xFFFF; type = Type.SET_POSITION; } else if (peek >= 128) { frames = stream.readUnsignedByte() - 128; int posHash = stream.readUnsignedShort(); dY = posHash >> 8; dX = posHash & 0xFF; } else { int hash = stream.readUnsignedShort(); frames = hash >> 12; dX = hash >> 6 & 0x3F; dY = hash & 0x3F; } p.steps.add(new MouseTrailStep(type, frames, dX, dY, stream.readByte() == 0)); } return p; } public int getFrameCount() { return frameCount; } public int getFrameSteps() { return frameSteps; } public List getSteps() { return steps; } } " "package com.rs.lib.net.packets.decoders.mouse; import java.util.ArrayList; import java.util.List; import com.rs.lib.io.InputStream; import com.rs.lib.net.ClientPacket; import com.rs.lib.net.packets.Packet; import com.rs.lib.net.packets.PacketDecoder; import com.rs.lib.net.packets.decoders.mouse.MouseTrailStep.Type; @PacketDecoder(ClientPacket.MOVE_MOUSE_2) public class MouseMoveJav extends Packet { private int frameCount; private int frameSteps; private List steps = new ArrayList<>(); @Override public Packet decodeAndCreateInstance(InputStream stream) { MouseMoveJav p = new MouseMoveJav(); p.frameSteps = stream.readUnsignedByte(); p.frameCount = stream.readUnsignedByte(); while(stream.getRemaining() > 0) { int peek = stream.peekUnsignedByte(); if (peek >= 224) { int frames = stream.readUnsignedShort() - 57344; int posHash = stream.readInt(); int dY = posHash >> 16; int dX = posHash & 0xFFFF; p.steps.add(new MouseTrailStep(Type.SET_POSITION, frames, dX, dY, true)); } else if (peek >= 192) { int frames = stream.readUnsignedByte() - 192; int posHash = stream.readInt(); int dY = posHash >> 16; int dX = posHash & 0xFFFF; p.steps.add(new MouseTrailStep(Type.SET_POSITION, frames, dX, dY, true)); } else if (peek >= 128) { int frames = stream.readUnsignedByte() - 128; int posHash = stream.readUnsignedShort(); int dY = posHash >> 8; int dX = posHash & 0xFF; p.steps.add(new MouseTrailStep(Type.MOVE_OFFSET, frames, dX, dY, true)); } else { int hash = stream.readUnsignedShort(); int frames = hash >> 12; int dX = hash >> 6 & 0x3F; int dY = hash & 0x3F; p.steps.add(new MouseTrailStep(Type.MOVE_OFFSET, frames, dX, dY, true)); } } return p; } public int getFrameCount() { return frameCount; } public int getFrameSteps() { return frameSteps; } public List getSteps() { return steps; } } " "package com.rs.lib.net.packets.decoders.mouse; public class MouseTrailStep { public enum Type { SET_POSITION, MOVE_OFFSET } private Type type; private int frames; private int x, y; private boolean hardware; public MouseTrailStep(Type type, int frames, int x, int y, boolean hardware) { this.type = type; this.frames = frames; this.x = x; this.y = y; this.hardware = hardware; } public Type getType() { return type; } public int getX() { return x; } public int getY() { return y; } public boolean isHardware() { return hardware; } public int getFrames() { return frames; } } " " package com.rs.lib.net.packets.encoders; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class BlockMinimapState extends PacketEncoder { private int state; public BlockMinimapState(int state) { super(ServerPacket.BLOCK_MINIMAP_STATE); this.state = state; } @Override public void encodeBody(OutputStream stream) { stream.writeByte(state); } } " " package com.rs.lib.net.packets.encoders; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class ChatFilterSettings extends PacketEncoder { private int tradeStatus; private int publicStatus; public ChatFilterSettings(int tradeStatus, int publicStatus) { super(ServerPacket.CHAT_FILTER_SETTINGS); this.tradeStatus = tradeStatus; this.publicStatus = publicStatus; } @Override public void encodeBody(OutputStream stream) { stream.writeByteC(tradeStatus); stream.writeByte128(publicStatus); } } " " package com.rs.lib.net.packets.encoders; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class ChatFilterSettingsPriv extends PacketEncoder { private int privateStatus; public ChatFilterSettingsPriv(int privateStatus) { super(ServerPacket.CHAT_FILTER_SETTINGS_PRIVATECHAT); this.privateStatus = privateStatus; } @Override public void encodeBody(OutputStream stream) { stream.writeByte(privateStatus); } } " " package com.rs.lib.net.packets.encoders; import com.rs.cache.loaders.cutscenes.CutsceneArea; import com.rs.cache.loaders.cutscenes.CutsceneDefinitions; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; import com.rs.lib.util.MapXTEAs; public class Cutscene extends PacketEncoder { private int id; private byte[] appearanceBlock; public Cutscene(int id, byte[] appearanceBlock) { super(ServerPacket.CUTSCENE); this.id = id; this.appearanceBlock = appearanceBlock; } @Override public void encodeBody(OutputStream stream) { stream.writeShort(id); CutsceneDefinitions def = CutsceneDefinitions.getDefs(id); stream.writeShort(def.areas.size()); for (CutsceneArea area : def.areas) { int[] xteas = MapXTEAs.getMapKeys(area.mapBase.getRegionId()); for (int i = 0; i < 4; i++) { stream.writeInt(xteas != null ? xteas[i] : 0); } } stream.writeByte(appearanceBlock.length); stream.writeBytes(appearanceBlock); } } " " package com.rs.lib.net.packets.encoders; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class DrawOrder extends PacketEncoder { private boolean playerFirst; public DrawOrder(boolean playerFirst) { super(ServerPacket.SET_DRAW_ORDER); this.playerFirst = playerFirst; } @Override public void encodeBody(OutputStream stream) { stream.writeByteC(playerFirst ? 1 : 0); } } " " package com.rs.lib.net.packets.encoders; import com.rs.cache.loaders.map.RegionSize; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; import com.rs.lib.util.MapXTEAs; public class DynamicMapRegion extends PacketEncoder { private byte[] lswp; private RegionSize mapSize; private int chunkX, chunkY; private boolean forceMapRefresh; private byte[] dynamicBytes; private int[] realRegionIds; public DynamicMapRegion(byte[] lswp, RegionSize mapSize, int chunkX, int chunkY, boolean forceMapRefresh, byte[] dynamicBytes, int[] realRegionIds) { super(ServerPacket.DYNAMIC_MAP_REGION); this.lswp = lswp; this.mapSize = mapSize; this.chunkX = chunkX; this.chunkY = chunkY; this.forceMapRefresh = forceMapRefresh; this.dynamicBytes = dynamicBytes; this.realRegionIds = realRegionIds; } @Override public void encodeBody(OutputStream stream) { if (lswp != null) stream.writeBytes(lswp); int regionX = chunkX; int regionY = chunkY; stream.writeByteC(forceMapRefresh ? 1 : 0); stream.write128Byte(2); stream.writeByte128(mapSize.ordinal()); stream.writeShort128(regionY); stream.writeShort(regionX); stream.writeBytes(dynamicBytes); for (int index = 0; index < realRegionIds.length; index++) { int[] xteas = MapXTEAs.getMapKeys(realRegionIds[index]); if (xteas == null) xteas = new int[4]; for (int keyIndex = 0; keyIndex < 4; keyIndex++) stream.writeInt(xteas[keyIndex]); } } } " " package com.rs.lib.net.packets.encoders; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class ExecuteCS2 extends PacketEncoder { private int id; private Object[] params; public ExecuteCS2(int id, Object... params) { super(ServerPacket.RUN_CS2_SCRIPT); this.id = id; this.params = params; } @Override public void encodeBody(OutputStream stream) { String parameterTypes = """"; if (params != null) { for (int count = params.length - 1; count >= 0; count--) { if (params[count] instanceof String) parameterTypes += ""s""; // string else parameterTypes += ""i""; // integer } } stream.writeString(parameterTypes); if (params != null) { int index = 0; for (int count = parameterTypes.length() - 1; count >= 0; count--) { if (parameterTypes.charAt(count) == 's') stream.writeString((String) params[index++]); else stream.writeInt((Integer) params[index++]); } } stream.writeInt(id); } } " " package com.rs.lib.net.packets.encoders; import com.rs.lib.game.HintIcon; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class HintArrow extends PacketEncoder { private HintIcon icon; public HintArrow(HintIcon icon) { super(ServerPacket.HINT_ARROW); this.icon = icon; } @Override public void encodeBody(OutputStream stream) { stream.writeByte((icon.getTargetType() & 0x1f) | (icon.getIndex() << 5)); if (icon.getTargetType() == 0) stream.skip(13); else { stream.writeByte(icon.getArrowType()); if (icon.getTargetType() == 1 || icon.getTargetType() == 10) { stream.writeShort(icon.getTargetIndex()); stream.writeShort(2500); stream.skip(4); } else if ((icon.getTargetType() >= 2 && icon.getTargetType() <= 6)) { // directions stream.writeByte(icon.getPlane()); // unknown stream.writeShort(icon.getCoordX()); stream.writeShort(icon.getCoordY()); stream.writeByte(icon.getDistanceFromFloor() * 4 >> 2); stream.writeShort(-1); //distance to show } stream.writeInt(icon.getModelId()); } } } " " package com.rs.lib.net.packets.encoders; import com.rs.lib.game.WorldTile; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class HintTrail extends PacketEncoder { private WorldTile start; private int index = 0; private int modelId; private int[] stepsX, stepsY; private int size; public HintTrail(WorldTile start, int modelId, int[] stepsX, int[] stepsY, int size) { super(ServerPacket.HINT_TRAIL); this.start = start; this.modelId = modelId; this.stepsX = stepsX; this.stepsY = stepsY; this.size = size; } @Override public void encodeBody(OutputStream stream) { stream.writeByte(index); //0-8 multiple trails if (size == -1) { stream.writeBigSmart(-1); return; } stream.writeBigSmart(modelId); stream.writeUnsignedSmart(size+1); //add 1 to steps since routefinder doesn't include first step? stream.writeShort(start.getX()); stream.writeShort(start.getY()); stream.writeByte(0); //0 offset to make sure first step is added stream.writeByte(0); //^ for (int i = size - 1; i >= 0; i--) { stream.writeByte(stepsX[i] - start.getX()); stream.writeByte(stepsY[i] - start.getY()); } } } " " package com.rs.lib.net.packets.encoders; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import com.rs.cache.loaders.map.RegionSize; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; import com.rs.lib.util.MapXTEAs; public class MapRegion extends PacketEncoder { private byte[] lswp; private RegionSize mapSize; private int chunkX, chunkY; private boolean forceMapRefresh; private Set regionIds; public MapRegion(byte[] lswp, RegionSize mapSize, int chunkX, int chunkY, boolean forceMapRefresh, Set regionIds) { super(ServerPacket.REGION); this.lswp = lswp; this.mapSize = mapSize; this.chunkX = chunkX; this.chunkY = chunkY; this.forceMapRefresh = forceMapRefresh; this.regionIds = regionIds; } @Override public void encodeBody(OutputStream stream) { if (lswp != null) stream.writeBytes(lswp); stream.writeByte(mapSize.ordinal()); stream.writeShort(chunkX); stream.writeShort(chunkY); stream.writeByte(forceMapRefresh ? 1 : 0); List regionList = new ArrayList<>(regionIds); Collections.sort(regionList); for (int regionId : regionList) { int[] xteas = MapXTEAs.getMapKeys(regionId); if (xteas == null) xteas = new int[] { 0, 0, 0, 0 }; for (int index = 0; index < 4; index++) stream.writeInt(xteas[index]); } } } " " package com.rs.lib.net.packets.encoders; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class MinimapFlag extends PacketEncoder { private int localX; private int localY; public MinimapFlag(int localX, int localY) { super(ServerPacket.MINIMAP_FLAG); this.localX = localX; this.localY = localY; } public MinimapFlag() { this(255, 255); } @Override public void encodeBody(OutputStream stream) { stream.write128Byte(localX); stream.write128Byte(localY); } } " " package com.rs.lib.net.packets.encoders; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class NPCUpdate extends PacketEncoder { private byte[] data; public NPCUpdate(boolean largeSceneView, byte[] data) { super(largeSceneView ? ServerPacket.NPC_UPDATE_LARGE : ServerPacket.NPC_UPDATE); this.data = data; } @Override public void encodeBody(OutputStream stream) { stream.writeBytes(data); } } " " package com.rs.lib.net.packets.encoders; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class OpenURL extends PacketEncoder { private String url; public OpenURL(String url) { super(ServerPacket.OPEN_URL); this.url = url; } @Override public void encodeBody(OutputStream stream) { stream.writeByte(0); stream.writeString(url); } } " " package com.rs.lib.net.packets.encoders; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class PlayerOption extends PacketEncoder { private String option; private int slot; private boolean top; private int cursor; public PlayerOption(String option, int slot, boolean top, int cursor) { super(ServerPacket.PLAYER_OPTION); this.option = option; this.slot = slot; this.top = top; this.cursor = cursor; } @Override public void encodeBody(OutputStream stream) { stream.writeString(option); stream.writeByte128(slot); stream.writeShortLE128(cursor); stream.writeByteC(top ? 1 : 0); } } " " package com.rs.lib.net.packets.encoders; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class PlayerUpdate extends PacketEncoder { private byte[] data; public PlayerUpdate(byte[] data) { super(ServerPacket.PLAYER_UPDATE); this.data = data; } @Override public void encodeBody(OutputStream stream) { stream.writeBytes(data); } } " " package com.rs.lib.net.packets.encoders; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; import com.rs.lib.util.reflect.ReflectionCheck; import com.rs.lib.util.reflect.ReflectionChecks; public class ReflectionCheckRequest extends PacketEncoder { private ReflectionChecks checks; public ReflectionCheckRequest(ReflectionChecks checks) { super(ServerPacket.REFLECTION_CHECK); this.checks = checks; } @Override public void encodeBody(OutputStream stream) { stream.writeByte(checks.getChecks().length); stream.writeInt(checks.getId()); for (ReflectionCheck check : checks.getChecks()) check.encode(stream); } } " " package com.rs.lib.net.packets.encoders; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class RunEnergy extends PacketEncoder { private int energy; public RunEnergy(int energy) { super(ServerPacket.RUN_ENERGY); this.energy = energy; } @Override public void encodeBody(OutputStream stream) { stream.writeByte(energy); } } " " package com.rs.lib.net.packets.encoders; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class RunWeight extends PacketEncoder { private int weight; public RunWeight(int weight) { super(ServerPacket.PLAYER_WEIGHT); this.weight = weight; } @Override public void encodeBody(OutputStream stream) { stream.writeShort(weight); } } " " package com.rs.lib.net.packets.encoders; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class SendDevConsoleCommand extends PacketEncoder { private String command; public SendDevConsoleCommand(String command) { super(ServerPacket.PROCESS_DEV_CONSOLE_COMMAND); this.command = command; } @Override public void encodeBody(OutputStream stream) { stream.writeString(command); } } " " package com.rs.lib.net.packets.encoders; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class SetCursor extends PacketEncoder { private String walkHereReplace; private int cursor; public SetCursor(String walkHereReplace, int cursor) { super(ServerPacket.SET_CURSOR); this.walkHereReplace = walkHereReplace; this.cursor = cursor; } @Override public void encodeBody(OutputStream stream) { stream.writeString(walkHereReplace); stream.writeShort(cursor); } } " "package com.rs.lib.net.packets.encoders; import java.util.Objects; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class Sound extends PacketEncoder { public enum SoundType { EFFECT, VORB_EFFECT, VOICE, JINGLE, MUSIC } private int id; private int repeat; private int delay; private int volume; private int sampleRate; private SoundType type; public Sound(int id, int delay, int volume, int sampleRate, SoundType type) { super(soundToPacket(type)); this.repeat = 1; this.id = id; this.delay = delay; this.volume = volume; this.sampleRate = sampleRate; this.type = type; } private static ServerPacket soundToPacket(SoundType type) { return switch(type) { case EFFECT -> ServerPacket.SOUND_SYNTH; case VORB_EFFECT -> ServerPacket.VORBIS_SOUND; case JINGLE -> ServerPacket.MUSIC_EFFECT; case MUSIC -> ServerPacket.MUSIC_TRACK; case VOICE -> ServerPacket.VORBIS_SPEECH_SOUND; default -> throw new IllegalArgumentException(""Invalid sound type provided to sound.""); }; } public Sound(int id, int delay, int volume, SoundType type) { this(id, delay, volume, 256, type); } public Sound(int id, int delay, SoundType type) { this(id, delay, 255, 256, type); } public Sound(int id, SoundType type) { this(id, 0, 255, 256, type); } public Sound volume(int volume) { this.volume = volume; return this; } public Sound delay(int delay) { this.delay = delay; return this; } public Sound sampleRate(int sampleRate) { this.sampleRate = sampleRate; return this; } public Sound repeat(int repeat) { this.repeat = repeat; return this; } @Override public void encodeBody(OutputStream stream) { switch(getPacket()) { case SOUND_SYNTH -> { stream.writeShort(id); stream.writeByte(repeat); stream.writeShort(delay); stream.writeByte(volume); stream.writeShort(sampleRate); } case VORBIS_SOUND -> { stream.writeShort(id); stream.writeByte(repeat); stream.writeShort(delay); stream.writeByte(volume); stream.writeShort(sampleRate); } case MUSIC_EFFECT -> { stream.write24BitIntegerV2(0); stream.write128Byte(volume); stream.writeShortLE(id); } case MUSIC_TRACK -> { stream.writeByte128(delay); stream.writeByte128(volume); stream.writeShort128(id); } case VORBIS_SPEECH_SOUND -> { stream.writeShort(id); stream.writeByte(repeat); stream.writeShort(delay); stream.writeByte(volume); } default -> throw new IllegalArgumentException(""Invalid packet type provided to sound.""); } } public int getId() { return id; } public int getDelay() { return delay; } public SoundType getType() { return type; } public int getVolume() { return volume; } public int getSampleRate() { return sampleRate; } @Override public int hashCode() { return Objects.hash(delay, id, volume, sampleRate, repeat, type); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Sound other = (Sound) obj; return delay == other.delay && id == other.id && repeat == other.repeat && type == other.type && sampleRate == other.sampleRate && volume == other.volume; } public int getRepeat() { return repeat; } } " " package com.rs.lib.net.packets.encoders; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class SystemUpdateTimer extends PacketEncoder { private int delay; public SystemUpdateTimer(int delay) { super(ServerPacket.UPDATE_REBOOT_TIMER); this.delay = delay; } @Override public void encodeBody(OutputStream stream) { stream.writeShort(delay); } } " " package com.rs.lib.net.packets.encoders; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class UpdateGESlot extends PacketEncoder { private int slot; private int progress; private int item; private int price; private int amount; private int currAmount; private int totalPrice; public UpdateGESlot(int slot, int progress, int item, int price, int amount, int currAmount, int totalPrice) { super(ServerPacket.UPDATE_GE_SLOT); this.slot = slot; this.progress = progress; this.item = item; this.price = price; this.amount = amount; this.currAmount = currAmount; this.totalPrice = totalPrice; } @Override public void encodeBody(OutputStream stream) { stream.writeByte(slot); stream.writeByte(progress); stream.writeShort(item); stream.writeInt(price); stream.writeInt(amount); stream.writeInt(currAmount); stream.writeInt(totalPrice); } } " " package com.rs.lib.net.packets.encoders; import com.rs.lib.game.Item; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class UpdateItemContainer extends PacketEncoder { private int key; private boolean negativeKey; private Item[] items; private int[] slots; public UpdateItemContainer(int key, boolean negativeKey, Item[] items, int... slots) { super(slots != null && slots.length > 0 ? ServerPacket.UPDATE_INV_PARTIAL : ServerPacket.UPDATE_INV_FULL); this.key = key; this.negativeKey = negativeKey; this.items = items; this.slots = slots; } @Override public void encodeBody(OutputStream stream) { if (slots != null && slots.length > 0) { stream.writeShort(key); stream.writeByte(negativeKey ? 1 : 0); for (int slotId : slots) { if (slotId >= items.length) continue; stream.writeSmart(slotId); int id = -1; int amount = 0; Item item = items[slotId]; if (item != null) { id = item.getId(); amount = item.getAmount(); } stream.writeShort(id + 1); if (id != -1) { stream.writeByte(amount >= 255 ? 255 : amount); if (amount >= 255) stream.writeInt(amount); } } } else { stream.writeShort(key); stream.writeByte(negativeKey ? 1 : 0); stream.writeShort(items.length); for (int index = 0; index < items.length; index++) { Item item = items[index]; int id = -1; int amount = 0; if (item != null) { id = item.getId(); amount = item.getAmount(); } stream.write128Byte(amount >= 255 ? 255 : amount); if (amount >= 255) stream.writeIntV2(amount); stream.writeShortLE128(id + 1); } } } } " " package com.rs.lib.net.packets.encoders; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class UpdateRichPresence extends PacketEncoder { private String fieldName; private Object value; public UpdateRichPresence(String fieldName, Object value) { super(ServerPacket.DISCORD_RICH_PRESENCE_UPDATE); this.fieldName = fieldName; this.value = value; } @Override public void encodeBody(OutputStream stream) { stream.writeString(fieldName); if (value instanceof Integer i) { stream.writeInt(0); stream.writeInt(i); } else if (value instanceof String s) { stream.writeInt(1); stream.writeString(s); } else if (value instanceof Long l) { stream.writeInt(2); stream.writeLong(l); } } } " " package com.rs.lib.net.packets.encoders; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class UpdateStat extends PacketEncoder { private int skillId, xp, level; public UpdateStat(int skillId, int xp, int level) { super(ServerPacket.UPDATE_STAT); this.skillId = skillId; this.xp = xp; this.level = level; } @Override public void encodeBody(OutputStream stream) { stream.writeInt(xp); stream.writeByte(skillId); stream.writeByte(level); } } " " package com.rs.lib.net.packets.encoders; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class WorldLoginDetails extends PacketEncoder { private int rights; private int pid; private String displayName; public WorldLoginDetails(int rights, int pid, String displayName) { super(ServerPacket.WORLD_LOGIN_DETAILS); this.rights = rights; this.pid = pid; this.displayName = displayName; } @Override public void encodeBody(OutputStream stream) { stream.writeByte(rights); stream.writeByte(0); stream.writeByte(0); stream.writeByte(0); stream.writeByte(1); stream.writeByte(0); stream.writeShort(pid); stream.writeByte(1); stream.write24BitInteger(0); stream.writeByte(1); // is member world stream.writeString(displayName); } } " " package com.rs.lib.net.packets.encoders.accountcreation; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class CheckEmailResponse extends PacketEncoder { private int code; public CheckEmailResponse(int code) { super(ServerPacket.CREATE_CHECK_EMAIL_REPLY); this.code = code; } @Override public void encodeBody(OutputStream stream) { stream.writeByte(code); } } " " package com.rs.lib.net.packets.encoders.accountcreation; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class CreateAccountResponse extends PacketEncoder { public enum CAResp { ERROR_CONTACTING_SERVER(1), LOGIN(2), CANNOT_CREATE_ACCOUNT_ATM(9), UNEXPECTED_SERVER_RESPONSE(10), EMAIL_ALREADY_IN_USE(20), INVALID_EMAIL(21), PLEASE_SUPPLY_VALID_PASS(30), PASSWORDS_MAY_ONLY_CONTAIN_LETTERS_AND_NUMBERS(31), PASSWORD_TOO_EASY(32); private int code; private CAResp(int code) { this.code = code; } } private CAResp response; private int code = -1; public CreateAccountResponse(CAResp response) { super(ServerPacket.CREATE_ACCOUNT_REPLY); this.response = response; } public CreateAccountResponse(int code) { super(ServerPacket.CREATE_ACCOUNT_REPLY); this.code = code; } @Override public void encodeBody(OutputStream stream) { stream.writeByte(response != null ? response.code : code); } } " " package com.rs.lib.net.packets.encoders.camera; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class CamForceAngle extends PacketEncoder { private int angleX, angleY; public CamForceAngle(int angleX, int angleY) { super(ServerPacket.CAM_FORCEANGLE); this.angleX = angleX; this.angleY = angleY; } @Override public void encodeBody(OutputStream stream) { stream.writeShort128(angleY); stream.writeShortLE128(angleX); } } " " package com.rs.lib.net.packets.encoders.camera; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class CamLookAt extends PacketEncoder { private int viewLocalX, viewLocalY, viewZ; private int speed1, speed2; public CamLookAt(int viewLocalX, int viewLocalY, int viewZ, int speed1, int speed2) { super(ServerPacket.CAM_LOOKAT); this.viewLocalX = viewLocalX; this.viewLocalY = viewLocalY; this.viewZ = viewZ; this.speed1 = speed1; this.speed2 = speed2; } @Override public void encodeBody(OutputStream stream) { stream.writeByte(viewLocalX); stream.writeShort128(viewZ >> 2); stream.writeByte128(viewLocalY); stream.writeByteC(speed1); stream.write128Byte(speed2); } } " " package com.rs.lib.net.packets.encoders.camera; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class CamMoveTo extends PacketEncoder { private int moveLocalX, moveLocalY; private int moveZ; private int speed1; private int speed2; public CamMoveTo(int moveLocalX, int moveLocalY, int moveZ, int speed1, int speed2) { super(ServerPacket.CAM_MOVETO); this.moveLocalX = moveLocalX; this.moveLocalY = moveLocalY; this.moveZ = moveZ; this.speed1 = speed1; this.speed2 = speed2; } @Override public void encodeBody(OutputStream stream) { stream.writeByte(moveLocalY); stream.writeByte(moveLocalX); stream.write128Byte(speed1); stream.writeShortLE(moveZ >> 2); stream.writeByte128(speed2); } } " " package com.rs.lib.net.packets.encoders.camera; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class CamShake extends PacketEncoder { //slot seems to work like this: //0 = camX addition //1 = camZ addition //2 = camY addition private int slotId; private int v1, v2, v3, v4; public CamShake(int slotId, int v1, int v2, int v3, int v4) { super(ServerPacket.CAM_SHAKE); this.slotId = slotId; this.v1 = v1; this.v2 = v2; this.v3 = v3; this.v4 = v4; } @Override public void encodeBody(OutputStream stream) { stream.write128Byte(v2); stream.writeShort(v4); stream.writeByteC(slotId); stream.writeByteC(v1); stream.write128Byte(v3); } } " " package com.rs.lib.net.packets.encoders.interfaces; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class IFCloseSub extends PacketEncoder { private int componentId; public IFCloseSub(int componentId) { super(ServerPacket.IF_CLOSESUB); this.componentId = componentId; } public IFCloseSub(int parentId, int parentComponentId) { this(parentId << 16 | parentComponentId); } @Override public void encodeBody(OutputStream stream) { stream.writeInt(componentId); } } " " package com.rs.lib.net.packets.encoders.interfaces; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class IFOpenTop extends PacketEncoder { private int interfaceId; private int type; public IFOpenTop(int interfaceId, int type) { super(ServerPacket.IF_OPENTOP); this.interfaceId = interfaceId; this.type = type; } @Override public void encodeBody(OutputStream stream) { int[] xteas = new int[4]; stream.writeIntV1(xteas[2]); stream.writeIntV1(xteas[3]); stream.writeShort128(interfaceId); stream.write128Byte(type); stream.writeIntLE(xteas[1]); stream.writeIntLE(xteas[0]); } } " " package com.rs.lib.net.packets.encoders.interfaces; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class IFSetAngle extends PacketEncoder { private int interfaceHash; private int pitch; private int roll; private int scale; public IFSetAngle(int interfaceId, int componentId, int pitch, int roll, int scale) { super(ServerPacket.IF_SETANGLE); this.interfaceHash = interfaceId << 16 | componentId; this.pitch = pitch; this.roll = roll; this.scale = scale; } @Override public void encodeBody(OutputStream stream) { stream.writeInt(interfaceHash); stream.writeShortLE(pitch); stream.writeShortLE(roll); stream.writeShortLE128(scale); } } " " package com.rs.lib.net.packets.encoders.interfaces; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class IFSetAnimation extends PacketEncoder { private int interfaceHash; private int animationId; public IFSetAnimation(int interfaceId, int componentId, int animationId) { super(ServerPacket.IF_SETANIM); this.interfaceHash = interfaceId << 16 | componentId; this.animationId = animationId; } @Override public void encodeBody(OutputStream stream) { stream.writeIntV2(animationId); stream.writeInt(interfaceHash); } } " " package com.rs.lib.net.packets.encoders.interfaces; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class IFSetClickMask extends PacketEncoder { private int interfaceHash; private boolean clickMask; public IFSetClickMask(int interfaceId, int componentId, boolean clickMask) { super(ServerPacket.IF_SETCLICKMASK); this.interfaceHash = interfaceId << 16 | componentId; this.clickMask = clickMask; } @Override public void encodeBody(OutputStream stream) { stream.write128Byte(clickMask ? 1 : 0); stream.writeIntLE(interfaceHash); } } " " package com.rs.lib.net.packets.encoders.interfaces; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class IFSetColor extends PacketEncoder { private int interfaceHash; private int color; public IFSetColor(int interfaceId, int componentId, int color) { super(ServerPacket.IF_SETCOLOR); this.interfaceHash = interfaceId << 16 | componentId; this.color = color; } @Override public void encodeBody(OutputStream stream) { stream.writeIntLE(interfaceHash); stream.writeShort128(color); } } " " package com.rs.lib.net.packets.encoders.interfaces; import com.rs.cache.loaders.interfaces.IFEvents; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class IFSetEvents extends PacketEncoder { private IFEvents params; public IFSetEvents(IFEvents params) { super(ServerPacket.IF_SETEVENTS); this.params = params; } @Override public void encodeBody(OutputStream stream) { stream.writeShortLE128(params.getToSlot()); stream.writeIntV2(params.getInterfaceId() << 16 | params.getComponentId()); stream.writeShort(params.getFromSlot()); stream.writeIntLE(params.getSettings()); } } " " package com.rs.lib.net.packets.encoders.interfaces; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class IFSetGraphic extends PacketEncoder { private int interfaceHash; private int spriteId; public IFSetGraphic(int interfaceId, int componentId, int spriteId) { super(ServerPacket.IF_SETGRAPHIC); this.interfaceHash = interfaceId << 16 | componentId; this.spriteId = spriteId; } @Override public void encodeBody(OutputStream stream) { stream.writeIntV2(spriteId); stream.writeIntV2(interfaceHash); } } " " package com.rs.lib.net.packets.encoders.interfaces; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class IFSetHide extends PacketEncoder { private int interfaceHash; private boolean hidden; public IFSetHide(int interfaceId, int componentId, boolean hidden) { super(ServerPacket.IF_SETHIDE); this.interfaceHash = interfaceId << 16 | componentId; this.hidden = hidden; } @Override public void encodeBody(OutputStream stream) { stream.writeByte128(hidden ? 1 : 0); stream.writeInt(interfaceHash); } } " " package com.rs.lib.net.packets.encoders.interfaces; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class IFSetItem extends PacketEncoder { private int interfaceHash; private int itemId; private int amount; public IFSetItem(int interfaceId, int componentId, int itemId, int amount) { super(ServerPacket.IF_SETITEM); this.interfaceHash = interfaceId << 16 | componentId; this.itemId = itemId; this.amount = amount; } @Override public void encodeBody(OutputStream stream) { stream.writeShort(itemId); stream.writeInt(interfaceHash); stream.writeIntV2(amount); } } " " package com.rs.lib.net.packets.encoders.interfaces; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class IFSetModel extends PacketEncoder { private int interfaceHash; private int modelId; public IFSetModel(int interfaceId, int componentId, int modelId) { super(ServerPacket.IF_SETMODEL); this.interfaceHash = interfaceId << 16 | componentId; this.modelId = modelId; } @Override public void encodeBody(OutputStream stream) { stream.writeInt(interfaceHash); stream.writeIntV2(modelId); } } " " package com.rs.lib.net.packets.encoders.interfaces; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class IFSetNPCHead extends PacketEncoder { private int interfaceHash; private int npcId; public IFSetNPCHead(int interfaceId, int componentId, int npcId) { super(ServerPacket.IF_SETNPCHEAD); this.interfaceHash = interfaceId << 16 | componentId; this.npcId = npcId; } @Override public void encodeBody(OutputStream stream) { stream.writeIntLE(interfaceHash); stream.writeIntV1(npcId); } } " " package com.rs.lib.net.packets.encoders.interfaces; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class IFSetPlayerHead extends PacketEncoder { private int interfaceHash; public IFSetPlayerHead(int interfaceId, int componentId) { super(ServerPacket.IF_SETPLAYERHEAD); this.interfaceHash = interfaceId << 16 | componentId; } @Override public void encodeBody(OutputStream stream) { stream.writeIntLE(interfaceHash); } } " " package com.rs.lib.net.packets.encoders.interfaces; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class IFSetPlayerHeadIgnoreWorn extends PacketEncoder { private int interfaceHash; private int identitiKit1; private int identitiKit2; private int identitiKit3; public IFSetPlayerHeadIgnoreWorn(int interfaceId, int componentId, int identitiKit1, int identitiKit2, int identitiKit3) { super(ServerPacket.IF_SETPLAYERHEAD_IGNOREWORN); this.interfaceHash = interfaceId << 16 | componentId; this.identitiKit1 = identitiKit1; this.identitiKit2 = identitiKit2; this.identitiKit3 = identitiKit3; } @Override public void encodeBody(OutputStream stream) { stream.writeShortLE(identitiKit1); stream.writeShort128(identitiKit2); stream.writeShort128(identitiKit3); stream.writeIntV2(interfaceHash); } } " " package com.rs.lib.net.packets.encoders.interfaces; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; import com.rs.lib.util.Utils; public class IFSetPlayerHeadOther extends PacketEncoder { private int interfaceHash; private String displayName; private int pid; public IFSetPlayerHeadOther(int interfaceId, int componentId, String displayName, int pid) { super(ServerPacket.IF_SETPLAYERHEAD_OTHER); this.interfaceHash = interfaceId << 16 | componentId; this.displayName = displayName; this.pid = pid; } @Override public void encodeBody(OutputStream stream) { stream.writeInt(Utils.stringToInt(displayName)); stream.writeShortLE128(pid); stream.writeIntV1(interfaceHash); } } " " package com.rs.lib.net.packets.encoders.interfaces; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class IFSetPlayerModel extends PacketEncoder { private int interfaceHash; public IFSetPlayerModel(int interfaceId, int componentId) { super(ServerPacket.IF_SETPLAYERMODEL); this.interfaceHash = interfaceId << 16 | componentId; } @Override public void encodeBody(OutputStream stream) { stream.writeIntV1(interfaceHash); } } " " package com.rs.lib.net.packets.encoders.interfaces; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; import com.rs.lib.util.Utils; public class IFSetPlayerModelOther extends PacketEncoder { private int interfaceHash; private String displayName; private int pid; public IFSetPlayerModelOther(int interfaceId, int componentId, String displayName, int pid) { super(ServerPacket.IF_SETPLAYERMODEL_OTHER); this.interfaceHash = interfaceId << 16 | componentId; this.displayName = displayName; this.pid = pid; } @Override public void encodeBody(OutputStream stream) { stream.writeShort128(pid); stream.writeIntV1(interfaceHash); stream.writeIntV1(Utils.stringToInt(displayName)); } } " " package com.rs.lib.net.packets.encoders.interfaces; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class IFSetPosition extends PacketEncoder { private int interfaceHash; private int x; private int y; public IFSetPosition(int interfaceId, int componentId, int x, int y) { super(ServerPacket.IF_SETPOSITION); this.interfaceHash = interfaceId << 16 | componentId; this.x = x; this.y = y; } @Override public void encodeBody(OutputStream stream) { stream.writeShort128(y); stream.writeIntV2(interfaceHash); stream.writeShortLE128(x); } } " " package com.rs.lib.net.packets.encoders.interfaces; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class IFSetScrollPos extends PacketEncoder { private int interfaceHash; private int pos; public IFSetScrollPos(int interfaceId, int componentId, int pos) { super(ServerPacket.IF_SETSCROLLPOS); this.interfaceHash = interfaceId << 16 | componentId; this.pos = pos; } @Override public void encodeBody(OutputStream stream) { stream.writeShort(pos); stream.writeInt(interfaceHash); } } " " package com.rs.lib.net.packets.encoders.interfaces; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class IFSetTargetParam extends PacketEncoder { private int interfaceHash; private int fromSlot; private int toSlot; private int targetParam; public IFSetTargetParam(int interfaceId, int componentId, int fromSlot, int toSlot, int targetParam) { super(ServerPacket.IF_SETTARGETPARAM); this.interfaceHash = interfaceId << 16 | componentId; this.fromSlot = fromSlot; this.toSlot = toSlot; this.targetParam = targetParam; } @Override public void encodeBody(OutputStream stream) { stream.writeIntV1(interfaceHash); stream.writeShortLE128(targetParam); stream.writeShort(toSlot); stream.writeShort128(fromSlot); } } " " package com.rs.lib.net.packets.encoders.interfaces; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class IFSetText extends PacketEncoder { private int interfaceHash; private String text; public IFSetText(int interfaceId, int componentId, String text) { super(ServerPacket.IF_SETTEXT); this.interfaceHash = interfaceId << 16 | componentId; this.text = text; } @Override public void encodeBody(OutputStream stream) { stream.writeString(text); stream.writeIntV1(interfaceHash); } } " " package com.rs.lib.net.packets.encoders.interfaces; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class IFSetTextFont extends PacketEncoder { private int interfaceHash; private int fontId; public IFSetTextFont(int interfaceId, int componentId, int fontId) { super(ServerPacket.IF_SETTEXTFONT); this.interfaceHash = interfaceId << 16 | componentId; this.fontId = fontId; } @Override public void encodeBody(OutputStream stream) { stream.writeInt(fontId); stream.writeIntV1(interfaceHash); } } " " package com.rs.lib.net.packets.encoders.interfaces.opensub; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class IFOpenSub extends PacketEncoder { private boolean overlay; private int topId; private int topChildId; private int subId; public IFOpenSub(int topId, int topChildId, int subId, boolean overlay) { super(ServerPacket.IF_OPENSUB); this.subId = subId; this.topId = topId; this.topChildId = topChildId; this.overlay = overlay; } @Override public void encodeBody(OutputStream stream) { int[] xteas = new int[4]; int topUid = topId << 16 | topChildId; stream.writeInt(xteas[0]); stream.writeIntV2(xteas[2]); stream.writeIntV2(xteas[1]); stream.writeShortLE128(subId); stream.writeIntLE(xteas[3]); stream.writeInt(topUid); stream.writeByteC(overlay ? 1 : 0); } } " " package com.rs.lib.net.packets.encoders.interfaces.opensub; import com.rs.lib.game.GroundItem; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class IFOpenSubActiveGroundItem extends PacketEncoder { private boolean overlay; private int topId; private int topChildId; private int subId; private GroundItem item; public IFOpenSubActiveGroundItem(int topId, int topChildId, int subId, boolean overlay, GroundItem item) { super(ServerPacket.IF_OPENSUB_ACTIVE_GROUNDITEM); this.topId = topId; this.topChildId = topChildId; this.subId = subId; this.overlay = overlay; this.item = item; } @Override public void encodeBody(OutputStream stream) { int[] xteas = new int[4]; int topUid = topId << 16 | topChildId; stream.writeIntV2(topUid); stream.writeIntLE(xteas[2]); stream.writeShortLE(subId); stream.writeInt(xteas[3]); stream.writeIntV1(xteas[0]); stream.write128Byte(overlay ? 1 : 0); stream.writeIntV1((item.getTile().getPlane() << 28) | (item.getTile().getX() << 14) | item.getTile().getY()); stream.writeIntV1(xteas[1]); stream.writeShortLE128(item.getId()); } } " " package com.rs.lib.net.packets.encoders.interfaces.opensub; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class IFOpenSubActiveNPC extends PacketEncoder { private int npcSid; private boolean overlay; private int topId; private int topChildId; private int subId; public IFOpenSubActiveNPC(int topId, int topChildId, int subId, boolean overlay, int npcSid) { super(ServerPacket.IF_OPENSUB_ACTIVE_NPC); this.npcSid = npcSid; this.topId = topId; this.topChildId = topChildId; this.subId = subId; this.overlay = overlay; } @Override public void encodeBody(OutputStream stream) { int[] xteas = new int[4]; int topUid = topId << 16 | topChildId; stream.writeShort128(npcSid); stream.writeIntLE(xteas[1]); stream.writeByteC(overlay ? 1 : 0); stream.writeInt(topUid); stream.writeIntLE(xteas[3]); stream.writeShortLE128(subId); stream.writeInt(xteas[2]); stream.writeInt(xteas[0]); } } " " package com.rs.lib.net.packets.encoders.interfaces.opensub; import com.rs.lib.game.WorldObject; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class IFOpenSubActiveObject extends PacketEncoder { private boolean overlay; private int topId; private int topChildId; private int subId; private WorldObject object; public IFOpenSubActiveObject(int topId, int topChildId, int subId, boolean overlay, WorldObject object) { super(ServerPacket.IF_OPENSUB_ACTIVE_OBJECT); this.topId = topId; this.topChildId = topChildId; this.subId = subId; this.overlay = overlay; this.object = object; } @Override public void encodeBody(OutputStream stream) { int[] xteas = new int[4]; int topUid = topId << 16 | topChildId; stream.writeIntV2(topUid); stream.writeIntV2(xteas[2]); stream.writeByte128(overlay ? 1 : 0); stream.writeInt(xteas[1]); stream.writeIntV1(xteas[0]); stream.writeShort128(subId); stream.write128Byte((object.getType().id << 2) | (object.getRotation() & 0x3)); stream.writeInt(xteas[3]); stream.writeIntV2((object.getTile().getPlane() << 28) | (object.getTile().getX() << 14) | object.getTile().getY()); stream.writeInt(object.getId()); } } " " package com.rs.lib.net.packets.encoders.interfaces.opensub; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class IFOpenSubActivePlayer extends PacketEncoder { private int pid; private boolean overlay; private int topId; private int topChildId; private int subId; public IFOpenSubActivePlayer(int topId, int topChildId, int subId, boolean overlay, int pid) { super(ServerPacket.IF_OPENSUB_ACTIVE_PLAYER); this.pid = pid; this.topId = topId; this.topChildId = topChildId; this.subId = subId; this.overlay = overlay; } @Override public void encodeBody(OutputStream stream) { int[] xteas = new int[4]; int topUid = topId << 16 | topChildId; stream.writeIntLE(xteas[3]); stream.writeByte(overlay ? 1 : 0); stream.writeIntV1(xteas[0]); stream.writeShort(subId); stream.writeInt(xteas[1]); stream.writeIntV1(topUid); stream.writeIntV1(xteas[2]); stream.writeShortLE(pid); } } " " package com.rs.lib.net.packets.encoders.social; import com.rs.lib.io.OutputStream; import com.rs.lib.model.Account; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class AddIgnore extends PacketEncoder { private Account account; public AddIgnore(Account account) { super(ServerPacket.ADD_IGNORE); this.account = account; } @Override public void encodeBody(OutputStream stream) { stream.writeByte(0x2); stream.writeString(account.getDisplayName()); stream.writeString(account.getPrevDisplayName()); } } " " package com.rs.lib.net.packets.encoders.social; import java.util.List; import com.rs.lib.io.OutputStream; import com.rs.lib.model.MemberData; import com.rs.lib.model.MinimalSocial; import com.rs.lib.model.clan.Clan; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class ClanChannelFull extends PacketEncoder { private boolean guest; private byte[] block; public ClanChannelFull(byte[] block, boolean guest) { super(ServerPacket.CLANCHANNEL_FULL); this.guest = guest; this.block = block; } public static byte[] generateBlock(Clan clan, int updateNum, List chatters) { OutputStream stream = new OutputStream(); stream.writeByte(0x2); // read name as string, 0x1 for long stream.writeLong(4062231702422979939L); // uid stream.writeLong(updateNum); stream.writeString(clan.getName()); stream.writeByte(0); // unused stream.writeByte(clan.getCcKickRank().getIconId()); stream.writeByte(clan.getCcChatRank().getIconId()); // maybe stream.writeShort(chatters.size()); for (MinimalSocial player : chatters) { // stream.writeLong(); //Username as long MemberData data = clan.getMembers().get(player.getUsername()); stream.writeString(player.getDisplayName()); stream.writeByte(data == null ? -1 : data.getRank().getIconId()); stream.writeShort(player.getWorld().number()); } return stream.getBuffer(); } @Override public void encodeBody(OutputStream stream) { stream.writeByte(guest ? 0 : 1); if (block == null) return; stream.writeBytes(block); } } " " package com.rs.lib.net.packets.encoders.social; import java.util.Map; import com.rs.cache.loaders.ClanVarSettingsDefinitions; import com.rs.cache.loaders.cs2.CS2Type; import com.rs.lib.io.OutputStream; import com.rs.lib.model.DisplayNamePair; import com.rs.lib.model.MemberData; import com.rs.lib.model.clan.Clan; import com.rs.lib.model.clan.ClanRank; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; import com.rs.lib.util.Logger; public class ClanSettingsFull extends PacketEncoder { private boolean guest; private byte[] block; public ClanSettingsFull(byte[] block, boolean guest) { super(ServerPacket.CLANSETTINGS_FULL); this.block = block; this.guest = guest; } public static byte[] generateBlock(Clan clan, Map displayNameMap, int updateNum) { OutputStream stream = new OutputStream(); int version = 3; stream.writeByte(version); // lowest clan version protocol stream.writeByte(0x2); // read name as string, 0x1 for long stream.writeInt(updateNum); stream.writeInt(0); // probably had same usage anyway doesnt anymore int fillerCount = 5 - clan.getMembers().size(); if (fillerCount < 0) fillerCount = 0; stream.writeShort(clan.getMembers().size() + fillerCount); stream.writeByte(clan.getBannedUsers().size()); stream.writeString(clan.getName()); if (version >= 4) stream.writeInt(0); stream.writeByte(clan.getCcChatRank() == ClanRank.NONE ? 1 : 0); stream.writeByte(clan.getCcChatRank().getIconId()); stream.writeByte(clan.getCcKickRank().getIconId()); stream.writeByte(0); // lootshareRank stream.writeByte(0); // lootshareRank for (String username : clan.getMembers().keySet()) { MemberData data = clan.getMembers().get(username); // stream.writeLong( stream.writeString(displayNameMap.get(username).getCurrent()); stream.writeByte(data.getRank().getIconId()); if (version >= 2) stream.writeInt(0); // memberInt1 if (version >= 5) stream.writeShort(0); // memberShort1 } if (fillerCount > 0) { for (int i = 0;i < fillerCount;i++) { stream.writeString(""FILLER_CHARACTER""+i); stream.writeByte(0); if (version >= 2) stream.writeInt(0); if (version >= 5) stream.writeShort(0); } } for (String bannedUser : clan.getBannedUsers()) { // stream.writeLong(bannedUser); stream.writeString(displayNameMap.get(bannedUser).getCurrent()); } if (version >= 3) { int offset = stream.getOffset(); stream.writeShort(0); int count = 0; for (int key : clan.getSettings().keySet()) { if (writeClanSetting(stream, key, clan.getSettings().get(key))) count++; } int end = stream.getOffset(); stream.setOffset(offset); stream.writeShort(count); stream.setOffset(end); } return stream.getBuffer(); } public static boolean writeClanSetting(OutputStream stream, int varId, Object value) { ClanVarSettingsDefinitions def = ClanVarSettingsDefinitions.getDefs(varId); if (def == null) { Logger.error(ClanSettingsFull.class, ""writeClanSetting"", ""No def found for clan var setting "" + varId); return false; } if (def.type == CS2Type.INT) { stream.writeInt(varId | 0 << 30); stream.writeInt(value instanceof Double d ? d.intValue() : (int) value); } else if (def.type == CS2Type.LONG) { stream.writeInt(varId | 1 << 30); stream.writeLong(value instanceof Double d ? d.intValue() : (long) value); } else if (def.type == CS2Type.STRING) { stream.writeInt(varId | 2 << 30); stream.writeString((String) value); } else { Logger.error(ClanSettingsFull.class, ""writeClanSetting"", ""Unsupported var type "" + def.type + "" for var "" + varId); return false; } return true; } @Override public void encodeBody(OutputStream stream) { stream.writeByte(guest ? 0 : 1); if (block == null) return; stream.writeBytes(block); } public static final char[] VALID_CHARS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; public static int getCharacterIndex(int c) { for (int i = 0; i < VALID_CHARS.length; i++) if (VALID_CHARS[i] == c) return i; return -1; } public static long convertToLong(String text) { long hash = 0; int count = text.length() - 1; for (char c : text.toCharArray()) { hash += getCharacterIndex(c) * Math.pow(36, count--); } return hash; } } " " package com.rs.lib.net.packets.encoders.social; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class FriendsChatChannel extends PacketEncoder { private byte[] block; public FriendsChatChannel(byte[] block) { super(ServerPacket.FRIENDS_CHAT_CHANNEL); this.block = block; } public FriendsChatChannel() { super(ServerPacket.FRIENDS_CHAT_CHANNEL); } @Override public void encodeBody(OutputStream stream) { if (block != null) stream.writeBytes(block); } } " " package com.rs.lib.net.packets.encoders.social; import com.rs.lib.io.OutputStream; import com.rs.lib.model.Account; import com.rs.lib.model.Friend; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class FriendStatus extends PacketEncoder { private Account base; private Friend[] friends; public FriendStatus(Account base, Friend... friends) { super(ServerPacket.FRIEND_STATUS); this.base = base; this.friends = friends; } @Override public void encodeBody(OutputStream stream) { for (Friend friend : friends) encodePlayer(base, friend, stream); } public void encodePlayer(Account player, Friend other, OutputStream stream) { boolean online = false; if (!other.isOffline() && player.onlineTo(other.getAccount())) online = true; stream.writeByte(0); //idk, was called warnMessage in matrix? stream.writeString(other.getAccount().getDisplayName()); stream.writeString(other.getAccount().getPrevDisplayName()); stream.writeShort(online ? other.getWorld() != null ? other.getWorld().number() : 0 : 0); stream.writeByte(player.getSocial().getFriendsChat().getRank(other.getAccount().getUsername()).getId()); stream.writeByte(0); // 1 = referrer if (online) { String worldText = ""None""; if (other.getWorld() != null) { if (other.getWorld().number() > 1100) worldText = ""Lobby "" + (other.getWorld().number() - 1100); else worldText = ""World "" + other.getWorld().number(); } stream.writeString(worldText); stream.writeByte(0); //Platform 0 = RS, 1 = Other (Quickchat related) stream.writeInt(0); //World flags? } } } " " package com.rs.lib.net.packets.encoders.social; import java.util.Map; import com.rs.lib.io.OutputStream; import com.rs.lib.model.DisplayNamePair; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class IgnoreList extends PacketEncoder { private Map ignores; public IgnoreList(Map ignores) { super(ServerPacket.UPDATE_IGNORE_LIST); this.ignores = ignores; } @Override public void encodeBody(OutputStream stream) { stream.writeByte(ignores.size()); for (String username : ignores.keySet()) { if (username != null) { stream.writeString(ignores.get(username).getCurrent()); stream.writeString(ignores.get(username).getPrev()); } } } } " " package com.rs.lib.net.packets.encoders.social; import com.rs.cache.Cache; import com.rs.lib.io.OutputStream; import com.rs.lib.model.Account; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; import com.rs.lib.util.Utils; public class MessageClan extends PacketEncoder { private Account account; private String message; private boolean guest; public MessageClan(Account account, String message, boolean guest) { super(ServerPacket.MESSAGE_CLANCHANNEL); this.account = account; this.message = message; this.guest = guest; } @Override public void encodeBody(OutputStream stream) { stream.writeByte(guest ? 0 : 1); stream.writeString(account.getDisplayName()); for (int i = 0; i < 5; i++) stream.writeByte(Utils.getRandomInclusive(255)); stream.writeByte(account.getRights().getCrown()); Cache.STORE.getHuffman().sendEncryptMessage(stream, message); } } " " package com.rs.lib.net.packets.encoders.social; import com.rs.cache.Cache; import com.rs.lib.io.OutputStream; import com.rs.lib.model.Account; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; import com.rs.lib.util.Utils; public class MessageFriendsChat extends PacketEncoder { private Account account; private String chatName; private String message; public MessageFriendsChat(Account account, String chatName, String message) { super(ServerPacket.MESSAGE_FRIENDS_CHAT); this.account = account; this.chatName = chatName; this.message = message; } @Override public void encodeBody(OutputStream stream) { stream.writeDisplayNameChat(account); stream.writeLong(Utils.stringToLong(chatName)); for (int i = 0; i < 5; i++) stream.writeByte(Utils.getRandomInclusive(255)); stream.writeByte(account.getRights().getCrown()); Cache.STORE.getHuffman().sendEncryptMessage(stream, message); } } " " package com.rs.lib.net.packets.encoders.social; import com.rs.lib.io.OutputStream; import com.rs.lib.model.Account; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class MessageGame extends PacketEncoder { private MessageType type; private String message; private Account target; public MessageGame(String message) { this(MessageType.UNFILTERABLE, message, null); } public MessageGame(MessageType type, String message) { this(type, message, null); } public MessageGame(MessageType type, String message, Account target) { super(ServerPacket.GAME_MESSAGE); this.type = type; this.message = message; this.target = target; } @Override public void encodeBody(OutputStream stream) { int maskData = 0; if (message.length() >= 248) message = message.substring(0, 248); if (target != null) { maskData |= 0x1; //maskData |= 0x2; } stream.writeSmart(type.getValue()); stream.writeInt(0); //junk stream.writeByte(maskData); if (target != null) { stream.writeString(target.getDisplayName()); //stream.writeString(target.getDisplayName()); } stream.writeString(message); } public enum MessageType { UNFILTERABLE(0), STAFF_CHAT(1), PUBLIC_CHAT(2), PRIVATE_MESSAGE_ECHO(3), GAME(4), FRIENDS_STATUS(5), PRIVATE_MESSAGE(6), PRIVATE_STAFF(7), UNK_8(8), FC_CHAT(9), UNK_10(10), FC_NOTIFICATION(11), UNK_12(12), UNK_13(13), UNK_14(14), UNK_15(15), UNK_16(16), PUBLIC_QUICKCHAT(17), PRIVATE_QUICKCHAT_ECHO(18), PRIVATE_QUICKCHAT(19), FC_QUICKCHAT(20), UNK_21(21), UNK_22(22), UNK_23(23), GROUP_CHAT(24), GROUP_QUICKCHAT(25), UNK_26(26), ITEM_EXAMINE(27), NPC_EXAMINE(28), OBJECT_EXAMINE(29), FRIEND_NOTIFICATION(30), IGNORE_NOTIFICATION(31), UNK_32(32), UNK_33(33), UNK_34(34), UNK_35(35), UNK_36(36), UNK_37(37), UNK_38(38), UNK_39(39), UNK_40(40), CLAN_CHAT(41), CLAN_QUICKCHAT(42), CLAN_NOTIFICATION(43), GUEST_CLAN_CHAT(44), GUEST_CLAN_QUICKCHAT(45), UNK_46(46), UNK_47(47), UNK_48(48), UNK_49(49), UNK_50(50), UNK_51(51), UNK_52(52), UNK_53(53), UNK_54(54), UNK_55(55), UNK_56(56), UNK_57(57), UNK_58(58), UNK_59(59), UNK_60(60), UNK_61(61), UNK_62(62), UNK_63(63), UNK_64(64), UNK_65(65), UNK_66(66), UNK_67(67), UNK_68(68), UNK_69(69), UNK_70(70), UNK_71(71), UNK_72(72), UNK_73(73), UNK_74(74), UNK_75(75), UNK_76(76), UNK_77(77), UNK_78(78), UNK_79(79), UNK_80(80), UNK_81(81), UNK_82(82), UNK_83(83), UNK_84(84), UNK_85(85), UNK_86(86), UNK_87(87), UNK_88(88), UNK_89(89), UNK_90(90), UNK_91(91), UNK_92(92), UNK_93(93), UNK_94(94), UNK_95(95), UNK_96(96), UNK_97(97), DEV_CONSOLE_CLEAR(98), DEV_CONSOLE(99), TRADE_REQUEST(100), DUEL_REQUEST(101), ASSIST_REQUEST(102), UNK_103(103), UNK_104(104), UNK_CHALLENGE_105(105), UNK_CHALLENGE_106(106), UNK_CHALLENGE_107(107), ALLIANCE_REQUEST(108), FILTERABLE(109), UNK_GAME_110(110), DUNGEONEERING_INVITE(111), VOTE_REQUEST(112), UNK_CHALLENGE_113(113), UNK_CHALLENGE_114(114), UNK_DARK_RED_115(115), UNK_PLAIN_NOTIFICATION_116(116), CLAN_INVITE(117), CLAN_CHALLENGE_REQUEST(118), UNK_119(119), UNK_120(120), UNK_121(121); private int value; private MessageType(int value) { this.value = value; } public int getValue() { return value; } } } " " package com.rs.lib.net.packets.encoders.social; import com.rs.cache.Cache; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class MessagePrivate extends PacketEncoder { private String username; private String message; public MessagePrivate(String username, String message) { super(ServerPacket.SEND_PRIVATE_MESSAGE); this.username = username; this.message = message; } @Override public void encodeBody(OutputStream stream) { stream.writeString(username); Cache.STORE.getHuffman().sendEncryptMessage(stream, message); } } " " package com.rs.lib.net.packets.encoders.social; import com.rs.cache.Cache; import com.rs.lib.io.OutputStream; import com.rs.lib.model.Account; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; import com.rs.lib.util.Utils; public class MessagePrivateEcho extends PacketEncoder { private Account account; private String message; public MessagePrivateEcho(Account account, String message) { super(ServerPacket.MESSAGE_PRIVATE_ECHO); this.account = account; this.message = message; } @Override public void encodeBody(OutputStream stream) { stream.writeDisplayNameChat(account); for (int i = 0; i < 5; i++) stream.writeByte(Utils.getRandomInclusive(255)); stream.writeByte(account.getRights().getCrown()); Cache.STORE.getHuffman().sendEncryptMessage(stream, message); } } " " package com.rs.lib.net.packets.encoders.social; import com.rs.cache.Cache; import com.rs.lib.game.PublicChatMessage; import com.rs.lib.game.QuickChatMessage; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class MessagePublic extends PacketEncoder { private int pid; private int messageIcon; private PublicChatMessage message; public MessagePublic(int pid, int messageIcon, PublicChatMessage message) { super(ServerPacket.MESSAGE_PUBLIC); this.pid = pid; this.messageIcon = messageIcon; this.message = message; } @Override public void encodeBody(OutputStream stream) { stream.writeShort(pid); stream.writeShort(message.getEffects()); stream.writeByte(messageIcon); String filtered = message.getMessage(); if (message instanceof QuickChatMessage qc) { stream.writeShort(qc.getFileId()); if (qc.getData() != null) stream.writeBytes(qc.getData()); } else { byte[] chatStr = new byte[250]; chatStr[0] = (byte) filtered.length(); int offset = 1 + Cache.STORE.getHuffman().encryptMessage(1, filtered.length(), chatStr, 0, filtered.getBytes()); stream.writeBytes(chatStr, 0, offset); } } } " " package com.rs.lib.net.packets.encoders.social; import com.rs.lib.game.QuickChatMessage; import com.rs.lib.io.OutputStream; import com.rs.lib.model.Account; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; import com.rs.lib.util.Utils; public class QuickChatClan extends PacketEncoder { private Account account; private QuickChatMessage message; private boolean guest; public QuickChatClan(Account account, QuickChatMessage message, boolean guest) { super(ServerPacket.MESSAGE_QUICKCHAT_CLANCHANNEL); this.account = account; this.message = message; this.guest = guest; } @Override public void encodeBody(OutputStream stream) { stream.writeByte(guest ? 0 : 1); stream.writeString(account.getDisplayName()); for (int i = 0; i < 5; i++) stream.writeByte(Utils.getRandomInclusive(255)); stream.writeByte(account.getRights().getCrown()); stream.writeShort(message.getFileId()); if (message.getData() != null) stream.writeBytes(message.getData()); } } " " package com.rs.lib.net.packets.encoders.social; import com.rs.lib.game.QuickChatMessage; import com.rs.lib.io.OutputStream; import com.rs.lib.model.Account; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; import com.rs.lib.util.Utils; public class QuickChatFriendsChat extends PacketEncoder { private Account account; private String chatName; private QuickChatMessage message; public QuickChatFriendsChat(Account account, String chatName, QuickChatMessage message) { super(ServerPacket.MESSAGE_QUICKCHAT_FRIENDS_CHAT); this.account = account; this.chatName = chatName; this.message = message; } @Override public void encodeBody(OutputStream stream) { stream.writeDisplayNameChat(account); stream.writeLong(Utils.stringToLong(chatName)); for (int i = 0; i < 5; i++) stream.writeByte(Utils.random(255)); //^ is in place of /* long l_160_ = stream.readUnsignedShort(); * long l_161_ = stream.read24BitUnsignedInteger(); * long l_164_ = (l_160_ << 32) + l_161_; */ stream.writeByte(account.getRights().getCrown()); stream.writeShort(message.getFileId()); if (message.getData() != null) stream.writeBytes(message.getData()); } } " " package com.rs.lib.net.packets.encoders.social; import com.rs.lib.game.QuickChatMessage; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class QuickChatPrivate extends PacketEncoder { private String displayName; private QuickChatMessage message; public QuickChatPrivate(String displayName, QuickChatMessage message) { super(ServerPacket.MESSAGE_QUICKCHAT_PRIVATE); this.displayName = displayName; this.message = message; } @Override public void encodeBody(OutputStream stream) { stream.writeString(displayName); stream.writeShort(message.getFileId()); if (message.getData() != null) stream.writeBytes(message.getData()); } } " " package com.rs.lib.net.packets.encoders.social; import com.rs.lib.game.QuickChatMessage; import com.rs.lib.io.OutputStream; import com.rs.lib.model.Account; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class QuickChatPrivateEcho extends PacketEncoder { private Account account; private QuickChatMessage message; public QuickChatPrivateEcho(Account account, QuickChatMessage message) { super(ServerPacket.MESSAGE_QUICKCHAT_PRIVATE_ECHO); this.account = account; this.message = message; } @Override public void encodeBody(OutputStream stream) { stream.writeDisplayNameChat(account); stream.writeShort(0); //unk stream.write24BitInteger(0); //unk stream.writeByte(account.getRights().getCrown()); stream.writeShort(message.getFileId()); if (message.getData() != null) stream.writeBytes(message.getData()); } } " " package com.rs.lib.net.packets.encoders.updatezone; import com.rs.lib.game.WorldObject; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class AddObject extends PacketEncoder { private WorldObject object; public AddObject(WorldObject object) { super(ServerPacket.CREATE_OBJECT); this.object = object; } @Override public void encodeBody(OutputStream stream) { stream.writeInt(object.getId()); stream.write128Byte((object.getTile().getXInChunk() << 4) | object.getTile().getYInChunk()); stream.write128Byte((object.getType().id << 2) + (object.getRotation() & 0x3)); } } " " package com.rs.lib.net.packets.encoders.updatezone; import com.rs.lib.game.GroundItem; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class CreateGroundItem extends PacketEncoder { private GroundItem item; public CreateGroundItem(GroundItem item) { super(ServerPacket.CREATE_GROUND_ITEM); this.item = item; } @Override public void encodeBody(OutputStream stream) { stream.writeShortLE128(item.getAmount()); stream.writeShort128(item.getId()); stream.writeByteC((item.getTile().getXInChunk() << 4) | item.getTile().getYInChunk()); } } " " package com.rs.lib.net.packets.encoders.updatezone; import com.rs.cache.loaders.ObjectDefinitions; import com.rs.lib.game.WorldObject; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class CustomizeObject extends PacketEncoder { private WorldObject object; private int[] modifiedModels, modifiedColors, modifiedTextures; public CustomizeObject(WorldObject object, int[] modifiedModels, int[] modifiedColors, int[] modifiedTextures) { super(ServerPacket.CUSTOMIZE_OBJECT); this.object = object; this.modifiedModels = modifiedModels; this.modifiedColors = modifiedColors; this.modifiedTextures = modifiedTextures; } @Override public void encodeBody(OutputStream stream) { ObjectDefinitions defs = object.getDefinitions(); if (defs == null) throw new Error(""Cannot modify object without any definitions.""); stream.writeInt(object.getId()); stream.writeByte128((object.getType().id << 2) + (object.getRotation() & 0x3)); int flags = 0; if (modifiedModels == null && modifiedColors == null && modifiedTextures == null) flags |= 0x1; if (modifiedModels != null) flags |= 0x2; if (modifiedColors != null) flags |= 0x4; if (modifiedTextures != null) flags |= 0x8; stream.writeByte(flags); stream.writeByte128((object.getTile().getXInChunk() << 4) | object.getTile().getYInChunk()); if ((flags & 0x2) == 2) { int count = defs.getModels(object.getType()).length; for (int i = 0;i < count;i++) { stream.writeInt(modifiedModels[i]); } } if ((flags & 0x4) == 4) { int count = 0; if (null != defs.modifiedColors) count = defs.modifiedColors.length; for (int i = 0;i < count;i++) { stream.writeShort(modifiedColors[i]); } } if ((flags & 0x8) == 8) { int count = 0; if (defs.modifiedTextures != null) count = defs.modifiedTextures.length; for (int i = 0;i < count;i++) { stream.writeShort(modifiedTextures[i]); } } } } " " package com.rs.lib.net.packets.encoders.updatezone; import com.rs.lib.game.Animation; import com.rs.lib.game.WorldObject; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class ObjectAnim extends PacketEncoder { private WorldObject object; private Animation animation; public ObjectAnim(WorldObject object, Animation animation) { super(ServerPacket.OBJ_ANIM); this.object = object; this.animation = animation; } @Override public void encodeBody(OutputStream stream) { stream.write128Byte((object.getType().id << 2) + (object.getRotation() & 0x3)); stream.write128Byte((object.getTile().getXInChunk() << 4) | object.getTile().getYInChunk()); stream.writeIntLE(animation.getIds()[0]); } } " " package com.rs.lib.net.packets.encoders.updatezone; import com.rs.lib.game.Projectile; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class ProjAnim extends PacketEncoder { private Projectile proj; public ProjAnim(Projectile proj) { super(ServerPacket.MAP_PROJANIM); this.proj = proj; } @Override public void encodeBody(OutputStream stream) { int flags = ((proj.getSource().getXInChunk() << 3) | proj.getSource().getYInChunk()); if (proj.usesTerrainHeight()) flags |= 0x80; stream.writeByte(flags); stream.writeByte(proj.getDestination().getX() - proj.getSource().getX()); stream.writeByte(proj.getDestination().getY() - proj.getSource().getY()); stream.writeShort(proj.getLockOnId()); stream.writeShort(proj.getSpotAnimId()); stream.writeByte(proj.getStartHeight()); stream.writeByte(proj.getEndHeight()); stream.writeShort(proj.getStartTime()); stream.writeShort(proj.getEndTime()); stream.writeByte(proj.getAngle()); stream.writeShort(proj.getSlope()); } } " " package com.rs.lib.net.packets.encoders.updatezone; import com.rs.lib.game.Projectile; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class ProjAnimHalfSq extends PacketEncoder { private Projectile proj; public ProjAnimHalfSq(Projectile proj) { super(ServerPacket.MAP_PROJANIM_HALFSQ); this.proj = proj; } @Override public void encodeBody(OutputStream stream) { int flags = 0; if (proj.usesTerrainHeight()) flags |= 0x1; if (proj.getBASFrameHeightAdjust() != -1) { flags |= 0x2; flags += (proj.getBASFrameHeightAdjust() << 2); //startHeight will not be multiplied by 4 with this flag active? } stream.writeByte((proj.getSource().getXInChunk() << 3) | proj.getSource().getYInChunk()); stream.writeByte(flags); stream.writeByte(proj.getDestination().getX() - proj.getSource().getX()); stream.writeByte(proj.getDestination().getY() - proj.getSource().getY()); stream.writeShort(proj.getSourceId()); stream.writeShort(proj.getLockOnId()); stream.writeShort(proj.getSpotAnimId()); stream.writeByte(proj.getStartHeight()); stream.writeByte(proj.getEndHeight()); stream.writeShort(proj.getStartTime()); stream.writeShort(proj.getEndTime()); stream.writeByte(proj.getAngle()); stream.writeShort(proj.getSlope()); } } " " package com.rs.lib.net.packets.encoders.updatezone; import com.rs.lib.game.GroundItem; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class RemoveGroundItem extends PacketEncoder { private GroundItem item; public RemoveGroundItem(GroundItem item) { super(ServerPacket.REMOVE_GROUND_ITEM); this.item = item; } @Override public void encodeBody(OutputStream stream) { stream.writeByteC((item.getTile().getXInChunk() << 4) | item.getTile().getYInChunk()); stream.writeShortLE128(item.getId()); } } " " package com.rs.lib.net.packets.encoders.updatezone; import com.rs.lib.game.WorldObject; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class RemoveObject extends PacketEncoder { private WorldObject object; public RemoveObject(WorldObject object) { super(ServerPacket.DESTROY_OBJECT); this.object = object; } @Override public void encodeBody(OutputStream stream) { stream.writeByte128((object.getType().id << 2) + (object.getRotation() & 0x3)); stream.writeByte((object.getTile().getXInChunk() << 4) | object.getTile().getYInChunk()); } } " " package com.rs.lib.net.packets.encoders.updatezone; import com.rs.lib.game.GroundItem; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class SetGroundItemAmount extends PacketEncoder { private GroundItem item; private int oldAmount; public SetGroundItemAmount(GroundItem item, int oldAmount) { super(ServerPacket.GROUND_ITEM_COUNT); this.item = item; this.oldAmount = oldAmount; } @Override public void encodeBody(OutputStream stream) { stream.writeByte((item.getTile().getXInChunk() << 4) | item.getTile().getYInChunk()); stream.writeShort(item.getId()); stream.writeShort(oldAmount); stream.writeShort(item.getAmount()); } } " " package com.rs.lib.net.packets.encoders.updatezone; import com.rs.lib.game.WorldTile; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class TileMessage extends PacketEncoder { private WorldTile tile; private String message; private int delay, height, color; public TileMessage(WorldTile tile, String message, int delay, int height, int color) { super(ServerPacket.TILE_MESSAGE); this.tile = tile; this.message = message; this.delay = delay; this.height = height; this.color = color; } @Override public void encodeBody(OutputStream stream) { stream.skip(1); stream.writeByte((tile.getXInChunk() << 4) | tile.getYInChunk()); stream.writeShort(delay / 30); stream.writeByte(height); stream.write24BitInteger(color); stream.writeString(message); } } " " package com.rs.lib.net.packets.encoders.updatezone; import com.rs.lib.game.WorldTile; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class UpdateZoneFullFollows extends PacketEncoder { private WorldTile tile; private int sceneBaseChunkId; public UpdateZoneFullFollows(WorldTile tile, int sceneBaseChunkId) { super(ServerPacket.UPDATE_ZONE_FULL_FOLLOWS); this.tile = tile; this.sceneBaseChunkId = sceneBaseChunkId; } @Override public void encodeBody(OutputStream stream) { stream.writeByte128(tile.getYInScene(sceneBaseChunkId) >> 3); stream.writeByte128(tile.getPlane()); stream.writeByte128(tile.getXInScene(sceneBaseChunkId) >> 3); } } " " package com.rs.lib.net.packets.encoders.updatezone.partial; import com.rs.lib.net.packets.PacketEncoder; public class UpdateZoneEvent { private UpdateZonePacket packet; private PacketEncoder encoder; public UpdateZoneEvent(UpdateZonePacket packet, PacketEncoder encoder) { this.packet = packet; this.encoder = encoder; } public UpdateZonePacket getPacket() { return packet; } public PacketEncoder getEncoder() { return encoder; } } " " package com.rs.lib.net.packets.encoders.updatezone.partial; import com.rs.lib.net.ServerPacket; public enum UpdateZonePacket { CUSTOMIZE_OBJECT(ServerPacket.CUSTOMIZE_OBJECT, -1), REMOVE_GROUND_ITEM(ServerPacket.REMOVE_GROUND_ITEM, 3), CREATE_GROUND_ITEM(ServerPacket.CREATE_GROUND_ITEM, 5), DESTROY_OBJECT(ServerPacket.DESTROY_OBJECT, 2), CREATE_OBJECT(ServerPacket.CREATE_OBJECT, 6), MAP_PROJANIM(ServerPacket.MAP_PROJANIM, 16), MAP_PROJANIM_HALFSQ(ServerPacket.MAP_PROJANIM_HALFSQ, 19), OBJECT_PREFETCH(ServerPacket.OBJECT_PREFETCH, 5), GROUND_ITEM_REVEAL(ServerPacket.GROUND_ITEM_REVEAL, 7), GROUND_ITEM_COUNT(ServerPacket.GROUND_ITEM_COUNT, 7), MIDI_SONG_LOCATION(ServerPacket.MIDI_SONG_LOCATION, 8), TILE_MESSAGE(ServerPacket.TILE_MESSAGE, -1), OBJ_ANIM(ServerPacket.OBJ_ANIM, 6), SOUND_AREA(null, 9), SPOT_ANIM(ServerPacket.SPOT_ANIM, 8); private ServerPacket serverPacket; private int size; UpdateZonePacket(ServerPacket serverPacket, int size) { this.serverPacket = serverPacket; this.size = size; } public int getSize() { return size; } public ServerPacket getServerPacket() { return serverPacket; } } " " package com.rs.lib.net.packets.encoders.updatezone.partial; import com.rs.lib.game.WorldTile; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class UpdateZonePartialEnclosed extends PacketEncoder { private WorldTile tile; private int sceneBaseChunkId; private UpdateZoneEvent[] events; public UpdateZonePartialEnclosed(WorldTile tile, int sceneBaseChunkId, UpdateZoneEvent... events) { super(ServerPacket.UPDATE_ZONE_PARTIAL_ENCLOSED); this.events = events; this.sceneBaseChunkId = sceneBaseChunkId; } @Override public void encodeBody(OutputStream stream) { stream.write128Byte(tile.getYInScene(sceneBaseChunkId) >> 3); stream.writeByte128(tile.getPlane()); stream.writeByte(tile.getXInScene(sceneBaseChunkId) >> 3); for (UpdateZoneEvent event : events) { stream.writeByte(event.getPacket().ordinal()); event.getEncoder().encodeBody(stream); } } } " " package com.rs.lib.net.packets.encoders.vars; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class SetVarc extends PacketEncoder { private int id; private int value; public SetVarc(int id, int value) { super((value < Byte.MIN_VALUE || value > Byte.MAX_VALUE) ? ServerPacket.CLIENT_SETVARC_LARGE : ServerPacket.CLIENT_SETVARC_SMALL); this.id = id; this.value = value; } @Override public void encodeBody(OutputStream stream) { if (value < Byte.MIN_VALUE || value > Byte.MAX_VALUE) { stream.writeShortLE(id); stream.writeIntV2(value); } else { stream.write128Byte(value); stream.writeShortLE(id); } } } " "package com.rs.lib.net.packets.encoders.vars; import com.rs.cache.loaders.ClanVarDefinitions; import com.rs.cache.loaders.cs2.CS2Type; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class SetVarClan extends PacketEncoder { private int id; private Object value; public SetVarClan(int id, Object value) { super(getPacketForValue(id, value)); this.id = id; this.value = value; } private static ServerPacket getPacketForValue(int id, Object value) { ClanVarDefinitions def = ClanVarDefinitions.getDefs(id); if (def.type == CS2Type.STRING) { if (!(value instanceof String)) throw new RuntimeException(""Clan var "" + id + "" should be a string.""); return ServerPacket.SET_CLAN_STRING; } if (def.type == CS2Type.LONG) { if (!(value instanceof Long) && !(value instanceof Integer)) throw new RuntimeException(""Clan var "" + id + "" should be a long or integer.""); return ServerPacket.VARCLAN_SET_LONG; } if (def.type == CS2Type.INT) { if (!(value instanceof Long) && !(value instanceof Integer)) throw new RuntimeException(""Clan var "" + id + "" should be a long or integer.""); return ((int) value < Byte.MIN_VALUE || (int) value > Byte.MAX_VALUE) ? ServerPacket.VARCLAN_SET_INT : ServerPacket.VARCLAN_SET_BYTE; } throw new RuntimeException(""Mismatching types for var "" + id); } @Override public void encodeBody(OutputStream stream) { switch(getPacket()) { case SET_CLAN_STRING -> { stream.writeShort(id); stream.writeString((String) value); } case VARCLAN_SET_LONG -> { stream.writeShort(id); stream.writeLong((long) value); } case VARCLAN_SET_BYTE -> { stream.writeShort(id); stream.writeByte((int) value); } case VARCLAN_SET_INT -> { stream.writeShort(id); stream.writeInt((int) value); } default -> throw new IllegalArgumentException(""Unexpected value: "" + getPacket()); } } } " " package com.rs.lib.net.packets.encoders.vars; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class SetVarcString extends PacketEncoder { private int id; private String string; public SetVarcString(int id, String string) { super(string.length()+2 > Byte.MAX_VALUE ? ServerPacket.CLIENT_SETVARCSTR_LARGE : ServerPacket.CLIENT_SETVARCSTR_SMALL); this.id = id; this.string = string; } @Override public void encodeBody(OutputStream stream) { if (string.length()+2 > Byte.MAX_VALUE) { stream.writeShortLE(id); stream.writeString(string); } else { stream.writeString(string); stream.writeShortLE128(id); } } } " " package com.rs.lib.net.packets.encoders.vars; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class SetVarp extends PacketEncoder { private int id; private int value; public SetVarp(int id, int value) { super((value < Byte.MIN_VALUE || value > Byte.MAX_VALUE) ? ServerPacket.VARP_LARGE : ServerPacket.VARP_SMALL); this.id = id; this.value = value; } @Override public void encodeBody(OutputStream stream) { switch(getPacket()) { case VARP_SMALL -> { stream.writeByte(value); stream.writeShortLE128(id); } case VARP_LARGE -> { stream.writeIntV2(value); stream.writeShortLE128(id); } default -> throw new IllegalArgumentException(""Unexpected value: "" + getPacket()); } } } " " package com.rs.lib.net.packets.encoders.vars; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class SetVarpBit extends PacketEncoder { private int id; private int value; public SetVarpBit(int id, int value) { super((value < Byte.MIN_VALUE || value > Byte.MAX_VALUE) ? ServerPacket.VARBIT_LARGE : ServerPacket.VARBIT_SMALL); this.id = id; this.value = value; } @Override public void encodeBody(OutputStream stream) { if (value < Byte.MIN_VALUE || value > Byte.MAX_VALUE) { stream.writeIntV2(value); stream.writeShort128(id); } else { stream.writeShort(id); stream.writeByte128(value); } } } " " package com.rs.lib.net.packets.encoders.zonespecific; import com.rs.lib.game.Animation; import com.rs.lib.game.WorldObject; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class ObjectAnimSpecific extends PacketEncoder { private WorldObject object; private Animation animation; public ObjectAnimSpecific(WorldObject object, Animation animation) { super(ServerPacket.OBJ_ANIM_SPECIFIC); this.object = object; this.animation = animation; } @Override public void encodeBody(OutputStream stream) { stream.writeIntV2(object.getTile().getTileHash()); stream.writeIntLE(animation.getIds()[0]); stream.write128Byte((object.getType().id << 2) + (object.getRotation() & 0x3)); } } " " package com.rs.lib.net.packets.encoders.zonespecific; import com.rs.lib.game.Projectile; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class ProjAnimSpecific extends PacketEncoder { private Projectile proj; public ProjAnimSpecific(Projectile proj) { super(ServerPacket.PROJANIM_SPECIFIC); this.proj = proj; } @Override public void encodeBody(OutputStream stream) { int flags = 0; if (proj.usesTerrainHeight()) flags |= 0x1; if (proj.getBASFrameHeightAdjust() != -1) { flags |= 0x2; flags += (proj.getBASFrameHeightAdjust() << 2); //startHeight will not be multiplied by 4 with this flag active? } stream.writeByte128(proj.getEndHeight()); stream.writeShortLE128(proj.getSourceId()); stream.writeShortLE(proj.getEndTime()); stream.writeShort(proj.getLockOnId()); stream.writeByte128(flags); stream.writeShort128(proj.getSource().getY()); stream.writeShort(proj.getSlope()); stream.writeShortLE128(proj.getStartTime()); stream.writeShortLE128(proj.getSpotAnimId()); stream.writeByte128(proj.getAngle()); stream.writeByteC(proj.getDestination().getX() - proj.getSource().getX()); stream.writeByteC(proj.getDestination().getY() - proj.getSource().getY()); stream.writeShort128(proj.getSource().getX()); stream.writeByteC(proj.getStartHeight()); } } " " package com.rs.lib.net.packets.encoders.zonespecific; import com.rs.lib.game.SpotAnim; import com.rs.lib.io.OutputStream; import com.rs.lib.net.ServerPacket; import com.rs.lib.net.packets.PacketEncoder; public class SpotAnimSpecific extends PacketEncoder { private SpotAnim spotAnim; private int targetHash; public SpotAnimSpecific(SpotAnim spotAnim, int targetHash) { super(ServerPacket.SPOT_ANIM_SPECIFIC); this.spotAnim = spotAnim; this.targetHash = targetHash; } @Override public void encodeBody(OutputStream stream) { stream.writeByteC(0); stream.writeShort128(spotAnim.getId()); stream.writeByteC(spotAnim.getSettings2Hash()); stream.writeShort128(spotAnim.getSpeed()); stream.writeIntLE(targetHash); stream.writeShortLE(spotAnim.getHeight()); } } " " package com.rs.lib.thread; import com.rs.lib.util.Logger; public class CatchExceptionRunnable implements Runnable { private Runnable runnable; public CatchExceptionRunnable(Runnable runnable) { this.runnable = runnable; } @Override public void run() { try { runnable.run(); } catch(Throwable e) { Logger.handle(CatchExceptionRunnable.class, ""run"", e); } } } " " package com.rs.lib.thread; import com.rs.lib.util.Logger; import io.netty.util.Timeout; import io.netty.util.TimerTask; public class CatchExceptionTimerTask implements TimerTask { private TimerTask task; public CatchExceptionTimerTask(TimerTask task) { this.task = task; } @Override public void run(Timeout timeout) { try { task.run(timeout); } catch(Throwable e) { Logger.handle(CatchExceptionTimerTask.class, ""run"", e); } } } " " package com.rs.lib.thread; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; public class DecoderThreadFactory implements ThreadFactory { private static final AtomicInteger poolNumber = new AtomicInteger(1); private final ThreadGroup group; private final AtomicInteger threadNumber = new AtomicInteger(1); private final String namePrefix; public DecoderThreadFactory() { group = Thread.currentThread().getThreadGroup(); namePrefix = ""Decoder Pool-"" + poolNumber.getAndIncrement() + ""-thread-""; } @Override public Thread newThread(Runnable r) { Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); if (t.isDaemon()) t.setDaemon(false); if (t.getPriority() != Thread.MAX_PRIORITY - 1) t.setPriority(Thread.MAX_PRIORITY - 1); return t; } } " " package com.rs.lib.tools; import java.io.IOException; import java.util.HashMap; import java.util.Map; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.cache.Store; import com.rs.cache.loaders.ItemDefinitions; import com.rs.cache.loaders.model.RSModel; import com.rs.cache.loaders.model.TextureConverter; import com.rs.lib.util.Utils; public class ItemDefEditor { private static Store NEW; private static Map PACKED_MAP = new HashMap<>(); private static Map ID_MAP = new HashMap<>(); public static final void main(String[] args) throws IOException { //Cache.init(); NEW = new Store(""D:/RSPS/876cache/"", true); // ItemDefinitions dungCape = ItemDefinitions.getDefs(19709); // for (int i = 25324; i <= 25348; i++) { // ItemDefinitions def = ItemDefinitions.getItemDefinitions(i, false); // def.setBonuses(dungCape.getBonuses()); // System.out.println(""Writing "" + def.getName()); // def.write(Cache.STORE); // } // for (int i = 31851;i <= 31866;i++) // packItem(NEW, Cache.STORE, i, true); // for (int i = 31869;i <= 31880;i++) // packItem(NEW, Cache.STORE, i, true); // for (int i = 32151;i <= 32153;i++) // packItem(NEW, Cache.STORE, i, true); // for (int i = 39322;i <= 39387;i++) // packItem(NEW, Cache.STORE, i, true); // RSModel model = RSModel.getMesh(ItemDefinitions.getItemDefinitions(20771, false).getMaleWornModelId1()); // if (model.emitterConfigs != null) // System.out.println(ParticleProducerDefinitions.getDefs(model.emitterConfigs[0].type)); // ItemDefinitions cape = ItemDefinitions.getItemDefinitions(NEW, 31268, false); // RSModel model = RSModel.getMesh(NEW, cape.getMaleWornModelId1(), true); // byte[] buffer = model.convertTo727(Cache.STORE, NEW, false); // RSModel converted = new RSModel(buffer); // System.err.println(""COMPARE""); // System.out.println(model.version + "" -> "" + converted.version); // System.out.println(model.faceCount + "" -> "" + converted.faceCount); // System.out.println(model.texturedFaceCount + "" -> "" + converted.texturedFaceCount); // System.out.println(model.vertexCount + "" -> "" + converted.vertexCount); // System.out.println(model.maxVertexUsed + "" -> "" + converted.maxVertexUsed); // System.out.println(model.emitterConfigs + "", "" + converted.emitterConfigs); // System.out.println(""textureRenderTypes: "" + Arrays.equals(model.textureRenderTypes, converted.textureRenderTypes)); // System.out.println(""vertexX: "" + Arrays.equals(model.vertexX, converted.vertexX)); // System.out.println(""vertexY: "" + Arrays.equals(model.vertexY, converted.vertexY)); // System.out.println(""vertexZ: "" + Arrays.equals(model.vertexZ, converted.vertexZ)); // System.out.println(""vertexBones: "" + Arrays.equals(model.vertexBones, converted.vertexBones)); // System.out.println(""faceColors: "" + Arrays.equals(model.faceTextures, converted.faceTextures)); // System.out.println(""faceRenderTypes: "" + Arrays.equals(model.faceRenderTypes, converted.faceRenderTypes)); // System.out.println(""facePriorities: "" + Arrays.equals(model.facePriorities, converted.facePriorities)); // System.out.println(""faceAlpha: "" + Arrays.equals(model.faceAlpha, converted.faceAlpha)); // System.out.println(""faceBones: "" + Arrays.equals(model.faceBones, converted.faceBones)); // System.out.println(""faceTextures: "" + Arrays.equals(model.faceTextures, converted.faceTextures)); // System.out.println(""faceTextureIndexes: "" + Arrays.equals(model.faceTextureIndexes, converted.faceTextureIndexes)); // // System.out.println(""faceA: "" + Arrays.equals(model.faceA, converted.faceA)); // System.out.println(""faceB: "" + Arrays.equals(model.faceB, converted.faceB)); // System.out.println(""faceC: "" + Arrays.equals(model.faceC, converted.faceC)); // // System.out.println(""textureTriangleX: "" + Arrays.equals(model.textureTriangleX, converted.textureTriangleX)); // System.out.println(""textureTriangleY: "" + Arrays.equals(model.textureTriangleY, converted.textureTriangleY)); // System.out.println(""textureTriangleZ: "" + Arrays.equals(model.textureTriangleZ, converted.textureTriangleZ)); // // System.out.println(""textureScaleX: "" + Arrays.equals(model.textureScaleX, converted.textureScaleX)); // System.out.println(""textureScaleY: "" + Arrays.equals(model.textureScaleY, converted.textureScaleY)); // System.out.println(""textureScaleZ: "" + Arrays.equals(model.textureScaleZ, converted.textureScaleZ)); } public static boolean packItem(Store from, Store to, int itemId, boolean rs3) throws IOException { int newId = Utils.getItemDefinitionsSize(); ItemDefinitions def = ItemDefinitions.getItemDefinitions(from, itemId, false); packModels(from, to, def, rs3); ID_MAP.put(itemId, newId); def.id = newId; if (def.certId != -1) { if (def.certTemplateId != -1) def.certId = ID_MAP.get(def.certId); else def.certId = newId+1; } if (def.lendId != -1) { if (def.lendTemplateId != -1) def.lendId = ID_MAP.get(def.lendId); else def.lendId = newId+2; } if (def.write(Cache.STORE)) System.out.println(""Packed: "" + def.name + "" to ID "" + newId); else System.err.println(""Error packing item "" + itemId); return true; } public static boolean packTexture(Store cache, int id) { return cache.getIndex(IndexType.MATERIALS).putFile(id, 0, NEW.getIndex(IndexType.MATERIALS).getFile(id, 0)); } public static int packModel(Store from, Store to, int modelId, boolean rs3) throws IOException { if (modelId == -1) return -1; if (modelId == 0) return 0; if (RSModel.getMesh(modelId) != null) return modelId; if (PACKED_MAP.get(modelId) != null) return PACKED_MAP.get(modelId); int archiveId = to.getIndex(IndexType.MODELS).getLastArchiveId()+1; System.out.println(""Packing model: "" + modelId + "" to "" + archiveId); if (rs3) { RSModel model = RSModel.getMesh(from, modelId, rs3); if (to.getIndex(IndexType.MODELS).putFile(archiveId, 0, model.convertTo727(to, from))) return archiveId; } else { PACKED_MAP.put(modelId, archiveId); if (to.getIndex(IndexType.MODELS).putFile(archiveId, 0, from.getIndex(IndexType.MODELS).getFile(modelId, 0))) return archiveId; } throw new RuntimeException(); } public static void packModels(Store from, Store to, ItemDefinitions def, boolean rs3) throws IOException { def.modelId = packModel(from, to, def.modelId, rs3); def.maleEquip1 = packModel(from, to, def.maleEquip1, rs3); def.maleEquip2 = packModel(from, to, def.maleEquip2, rs3); def.maleEquip3 = packModel(from, to, def.maleEquip3, rs3); def.femaleEquip1 = packModel(from, to, def.femaleEquip1, rs3); def.femaleEquip2 = packModel(from, to, def.femaleEquip2, rs3); def.femaleEquip3 = packModel(from, to, def.femaleEquip3, rs3); def.maleHead1 = packModel(from, to, def.maleHead1, rs3); def.maleHead2 = packModel(from, to, def.maleHead2, rs3); def.femaleHead1 = packModel(from, to, def.femaleHead1, rs3); def.femaleHead2 = packModel(from, to, def.femaleHead2, rs3); if (rs3 && def.originalTextureIds != null) { for (int i = 0;i < def.originalTextureIds.length;i++) { def.originalTextureIds[i] = TextureConverter.convert(from, to, def.originalTextureIds[i], true); } for (int i = 0;i < def.modifiedTextureIds.length;i++) { def.modifiedTextureIds[i] = TextureConverter.convert(from, to, def.modifiedTextureIds[i], true); } } } } " " package com.rs.lib.util; import java.security.MessageDigest; /** * Handles the encryption of player passwords. * * @author Apache Ah64 */ public class Encrypt { /** * Encrypt the string using the SHA-1 encryption algorithm. * * @param string * The string. * @return The encrypted string. */ public static String encryptSHA1(String string) { String hash = null; try { hash = byteArrayToHexString(hash(string)); } catch (Exception e) { e.printStackTrace(); } return hash; } /** * Encrypt the string to a SHA-1 hash. * * @param x * The string to encrypt. * @return The byte array. * @throws Exception * when an exception occurs. */ public static byte[] hash(String x) throws Exception { MessageDigest string; string = java.security.MessageDigest.getInstance(""SHA-1""); string.reset(); string.update(x.getBytes()); return string.digest(); } /** * Converts a byte array to hex string. * * @param b * The byte array. * @return The hex string. */ public static String byteArrayToHexString(byte[] b) { StringBuffer string = new StringBuffer(b.length * 2); for (byte element : b) { int v = element & 0xff; if (v < 16) string.append('0'); string.append(Integer.toHexString(v)); } return string.toString(); } }" " package com.rs.lib.util; import java.util.concurrent.ConcurrentHashMap; import java.lang.SuppressWarnings; public class GenericAttribMap { private ConcurrentHashMap attribs; public GenericAttribMap() { this.attribs = new ConcurrentHashMap<>(); } @SuppressWarnings(""unchecked"") public T setO(String name, Object value) { if (value == null) { Object old = attribs.remove(""O""+name); return old == null ? null : (T) old; } Object old = attribs.put(""O""+name, value); return old == null ? null : (T) old; } @SuppressWarnings(""unchecked"") public T getO(String name) { if (attribs.get(""O""+name) == null) return null; return (T) attribs.get(""O""+name); } public void setI(String name, int value) { attribs.put(""I""+name, value); } public void setD(String name, double value) { attribs.put(""D""+name, value); } public void setB(String name, boolean value) { attribs.put(""B""+name, value); } public void setL(String name, long value) { attribs.put(""L""+name, value); } public boolean getB(String name) { if (attribs.get(""B""+name) == null) return false; return (Boolean) attribs.get(""B""+name); } public int getI(String name, int def) { Object val = attribs.get(""I""+name); if (val == null) return def; return (int) (val instanceof Integer ? (int) val : (double) val); } public int getI(String name) { return getI(name, 0); } public double getD(String name, double def) { if (attribs.get(""D""+name) == null) return def; return (Double) attribs.get(""D""+name); } public double getD(String name) { return getD(name, 0.0); } public long getL(String name) { if (attribs.get(""L""+name) == null) return 0; return (Long) attribs.get(""L""+name); } public void incI(String name) { int newVal = getI(name) + 1; setI(name, newVal); } public void clear() { attribs.clear(); } public int removeI(String name) { int i = getI(name); attribs.remove(""I""+name); return i; } public boolean removeB(String name) { boolean b = getB(name); attribs.remove(""B""+name); return b; } public T removeO(String name) { T o = getO(name); attribs.remove(""O""+name); return o; } public long removeL(String name) { long l = getL(name); attribs.remove(""L""+name); return l; } public int removeI(String name, int defaultVal) { int i = getI(name, defaultVal); attribs.remove(""I""+name); return i; } public void decI(String name) { int newVal = getI(name) - 1; setI(name, newVal); } } " "package com.rs.lib.util; import java.util.logging.ConsoleHandler; import java.util.logging.Handler; import java.util.logging.Level; import com.rs.lib.Globals; import com.rs.lib.db.DBConnection; public final class Logger { private static final String ROOT_KEY = ""DarkanRS""; private static final java.util.logging.Logger DARKAN_ROOT_LOGGER = java.util.logging.Logger.getLogger(ROOT_KEY); public static final void setupFormat() { //System.setProperty(""java.util.logging.SimpleFormatter.format"", ""%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$s %2$s %5$s%6$s%n""); System.setProperty(""java.util.logging.SimpleFormatter.format"", ""[%1$tF %1$tT %1$tL] [%4$-7s] %5$s %n""); DARKAN_ROOT_LOGGER.addHandler(new ConsoleHandler()); DARKAN_ROOT_LOGGER.setUseParentHandlers(false); } public static final void setLevel(Level level) { DARKAN_ROOT_LOGGER.setLevel(level); for (Handler handler : DARKAN_ROOT_LOGGER.getHandlers()) handler.setLevel(level); } public static final void handle(Class source, String method, Throwable e) { if (DBConnection.getErrors() != null && DBConnection.getErrors().getDocs() != null) DBConnection.getErrors().logError(method, e); DARKAN_ROOT_LOGGER.log(Level.SEVERE, ""["" + source.getSimpleName() + ""."" + method + ""] "" + (e.getClass().getEnclosingMethod() != null ? ""[""+e.getClass().getEnclosingMethod().getName() + ""]: "" : """"), e); if (Globals.DEBUG && e != null) e.printStackTrace(); } public static final void handle(Class source, String method, String message, Throwable e) { if (DBConnection.getErrors() != null && DBConnection.getErrors().getDocs() != null) { if (e == null) DBConnection.getErrors().logError(method, message); else DBConnection.getErrors().logError(method, message, e); } handleNoRecord(source, method, message, e); } public static final void handleNoRecord(Class source, String method, String message, Throwable e) { DARKAN_ROOT_LOGGER.log(Level.SEVERE, ""["" + source.getSimpleName() + ""."" + method + ""] "" + (e.getClass().getEnclosingMethod() != null ? ""[""+e.getClass().getEnclosingMethod().getName() + ""]: "" : """") + """" + message, e); if (Globals.DEBUG && e != null) e.printStackTrace(); } public static final void error(Class source, String method, Object msg) { DARKAN_ROOT_LOGGER.log(Level.SEVERE, ""["" + source.getSimpleName() + ""."" + method + ""] "" + msg); } public static final void warn(Class source, String method, Object msg) { DARKAN_ROOT_LOGGER.log(Level.WARNING, ""["" + source.getSimpleName() + ""."" + method + ""] "" + msg); } public static final void info(Class source, String method, Object msg) { DARKAN_ROOT_LOGGER.log(Level.CONFIG, ""["" + source.getSimpleName() + ""."" + method + ""] "" + msg); } public static final void debug(Class source, String method, Object msg) { DARKAN_ROOT_LOGGER.log(Level.FINE, ""["" + source.getSimpleName() + ""."" + method + ""] "" + msg); } public static final void trace(Class source, String method, Object msg) { DARKAN_ROOT_LOGGER.log(Level.FINER, ""["" + source.getSimpleName() + ""."" + method + ""] "" + msg); } } " " package com.rs.lib.util; import com.rs.lib.game.WorldTile; /* * @author Dragonkk/Alex */ public class MapUtils { private static interface StructureEncoder { public abstract int encode(int x, int y, int plane); } private static interface StructureDecoder { public abstract int[] decode(int id); } public static enum Structure { TILE(null, 1, 1, new StructureEncoder() { @Override public int encode(int x, int y, int plane) { return y | (x << 14) | (plane << 28); } }, new StructureDecoder() { @Override public int[] decode(int id) { return new int[] { id >> 14 & 16383, id & 16383, id >> 28 & 3 }; } }), CHUNK(TILE, 8, 8, new StructureEncoder() { @Override public int encode(int x, int y, int plane) { return (x << 14) | (y << 3) | (plane << 24); } }, new StructureDecoder() { @Override public int[] decode(int id) { return new int[] { id >> 14 & 2047, id >> 3 & 2047, id >> 24 & 3 }; } }), REGION(CHUNK, 8, 8, new StructureEncoder() { @Override public int encode(int x, int y, int plane) { return ((x << 8) | y | (plane << 16)); } }, new StructureDecoder() { @Override public int[] decode(int id) { return new int[] { id >> 8 & 255, id & 255, id >> 24 & 3 }; } }), MAP(REGION, 256, 256); private Structure child; private int width, height; private StructureEncoder encoder; private StructureDecoder decoder; /* * width * height squares. For instance 4x4: S S S S S S S S S S S S */ private Structure(Structure child, int width, int height, StructureEncoder encode, StructureDecoder decoder) { this.child = child; this.width = width; this.height = height; this.encoder = encode; this.decoder = decoder; } private Structure(Structure child, int width, int height) { this(child, width, height, null, null); } public int getWidth() { int x = width; Structure nextChild = child; while (nextChild != null) { x *= nextChild.width; nextChild = nextChild.child; } return x; } public int getChildWidth() { return width; } public int getHeight() { int y = height; Structure nextChild = child; while (nextChild != null) { y *= nextChild.height; nextChild = nextChild.child; } return y; } public int encode(int x, int y) { return encode(x, y, 0); } public int[] decode(int id) { return decoder == null ? null : decoder.decode(id); } public int encode(int x, int y, int plane) { return encoder == null ? -1 : encoder.encode(x, y, plane); } public int getChildHeight() { return width; } @Override public String toString() { return Utils.formatPlayerNameForDisplay(name()); } } public static final class Area { private Structure structure; private int x, y, width, height; public Area(Structure structure, int x, int y, int width, int height) { this.structure = structure; this.x = x; this.y = y; this.width = width; this.height = height; } public int getX() { return x; } public int getY() { return y; } public int getMapX() { return x * structure.getWidth(); } public int getMapY() { return y * structure.getHeight(); } public int getMapWidth() { return width * structure.getWidth(); } public int getMapHeight() { return height * structure.getHeight(); } public Structure getStructure() { return structure; } @Override public int hashCode() { return structure.encode(x, y, 0); } @Override public String toString() { return ""Structure: "" + structure.toString() + "", x: "" + x + "", y: "" + y + "", width: "" + width + "", height: "" + height; } } public static Area getArea(int minX, int minY, int maxX, int maxY) { return getArea(Structure.TILE, minX, minY, maxX, maxY); } public static Area getArea(Structure structure, int minX, int minY, int maxX, int maxY) { return new Area(structure, minX, minY, maxX - minY, maxY - minY); } /* * returns converted area */ public static Area convert(Structure to, Area area) { int x = area.getMapX() / to.getWidth(); int y = area.getMapY() / to.getHeight(); int width = area.getMapWidth() / to.getWidth(); int height = area.getMapHeight() / to.getHeight(); return new Area(to, x, y, width, height); } /* * converted pos return converted x and y */ public static int[] convert(Structure from, Structure to, int... xy) { return new int[] { xy[0] * from.getWidth() / to.getWidth(), xy[1] * from.getHeight() / to.getHeight() }; } public static int encode(Structure structure, int... xyp) { return structure.encode(xyp[0], xyp[1], xyp.length == 3 ? xyp[2] : 0); } public static int[] decode(Structure structure, int id) { return structure.decode(id); } public static int chunkToRegionId(int chunkId) { int[] tile = Structure.CHUNK.decode(chunkId); return WorldTile.of(tile[0] << 3, tile[1] << 3, 0).getRegionId(); } }" " package com.rs.lib.util; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.HashMap; import java.util.Map; import com.google.gson.JsonIOException; import com.google.gson.reflect.TypeToken; import com.rs.lib.file.JsonFileManager; public final class MapXTEAs { private static Map KEYS = new HashMap<>(); private final static String PATH = ""./data/map/xteaKeys.json""; public static final int[] getMapKeys(int regionId) { int[] arr = (int[]) KEYS.get(regionId); if (arr == null || (arr[0] == 0 && arr[1] == 0 && arr[2] == 0 && arr[3] == 0)) return null; return arr; } public static void loadKeys() throws JsonIOException, IOException { Logger.info(MapXTEAs.class, ""loadKeys"", ""Loading map XTEAs...""); if (!new File(PATH).exists()) throw new FileNotFoundException(""No map keys file found!""); else KEYS = JsonFileManager.loadJsonFile(new File(PATH), new TypeToken>(){}.getType()); } } " " package com.rs.lib.util; import com.mongodb.client.MongoDatabase; import com.mongodb.client.MongoIterable; public class MongoUtil { public static boolean collectionExists(MongoDatabase db, String collectionName) { MongoIterable collectionNames = db.listCollectionNames(); for (String name : collectionNames) { if (name.equalsIgnoreCase(collectionName)) { return true; } } return false; } } " " package com.rs.lib.util; import java.lang.reflect.Type; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import com.rs.lib.net.packets.Packet; public class PacketAdapter implements JsonSerializer, JsonDeserializer { private static final String CLASS_KEY = ""2_CMK""; @Override public Packet deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { JsonObject jsonObj = jsonElement.getAsJsonObject(); String className = jsonObj.get(CLASS_KEY).getAsString(); try { Class clz = Class.forName(className); return jsonDeserializationContext.deserialize(jsonElement, clz); } catch (ClassNotFoundException e) { throw new JsonParseException(e); } } @Override public JsonElement serialize(Packet object, Type type, JsonSerializationContext jsonSerializationContext) { JsonElement jsonEle = jsonSerializationContext.serialize(object, object.getClass()); jsonEle.getAsJsonObject().addProperty(CLASS_KEY, object.getClass().getCanonicalName()); return jsonEle; } }" " package com.rs.lib.util; import java.lang.reflect.Type; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import com.rs.lib.net.packets.PacketEncoder; public class PacketEncoderAdapter implements JsonSerializer, JsonDeserializer { private static final String CLASS_KEY = ""1_CMK""; @Override public PacketEncoder deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { JsonObject jsonObj = jsonElement.getAsJsonObject(); String className = jsonObj.get(CLASS_KEY).getAsString(); try { Class clz = Class.forName(className); return jsonDeserializationContext.deserialize(jsonElement, clz); } catch (ClassNotFoundException e) { throw new JsonParseException(e); } } @Override public JsonElement serialize(PacketEncoder object, Type type, JsonSerializationContext jsonSerializationContext) { JsonElement jsonEle = jsonSerializationContext.serialize(object, object.getClass()); jsonEle.getAsJsonObject().addProperty(CLASS_KEY, object.getClass().getCanonicalName()); return jsonEle; } }" " package com.rs.lib.util; public class Rational { private long num, denom; public Rational(double d) { String s = String.valueOf(d); int digitsDec = s.length() - 1 - s.indexOf('.'); int denom = 1; for (int i = 0; i < digitsDec; i++) { d *= 10; denom *= 10; } int num = (int) Math.round(d); this.num = num; this.denom = denom; } public Rational(long num, long denom) { this.num = num; this.denom = denom; } public long getNum() { return num; } public long denom() { return denom; } public String toString() { return Utils.asFraction(num, denom); } public static Rational toRational(double number) { return toRational(number, 4); } public static Rational toRational(double number, int largestRightOfDecimal) { long sign = 1; if (number < 0) { number = -number; sign = -1; } final long SECOND_MULTIPLIER_MAX = (long) Math.pow(10, largestRightOfDecimal - 1); final long FIRST_MULTIPLIER_MAX = SECOND_MULTIPLIER_MAX * 10L; final double ERROR = Math.pow(10, -largestRightOfDecimal - 1); long firstMultiplier = 1; long secondMultiplier = 1; boolean notIntOrIrrational = false; long truncatedNumber = (long) number; Rational rationalNumber = new Rational((long) (sign * number * FIRST_MULTIPLIER_MAX), FIRST_MULTIPLIER_MAX); double error = number - truncatedNumber; while ((error >= ERROR) && (firstMultiplier <= FIRST_MULTIPLIER_MAX)) { secondMultiplier = 1; firstMultiplier *= 10; while ((secondMultiplier <= SECOND_MULTIPLIER_MAX) && (secondMultiplier < firstMultiplier)) { double difference = (number * firstMultiplier) - (number * secondMultiplier); truncatedNumber = (long) difference; error = difference - truncatedNumber; if (error < ERROR) { notIntOrIrrational = true; break; } secondMultiplier *= 10; } } if (notIntOrIrrational) { rationalNumber = new Rational(sign * truncatedNumber, firstMultiplier - secondMultiplier); } return rationalNumber; } }" " package com.rs.lib.util; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.SuppressWarnings; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.RecordComponent; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.annotations.SerializedName; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; /** * Gson support for Java 16+ record types. * Taken from https://github.com/google/gson/issues/1794 and adjusted for performance and proper handling of * {@link SerializedName} annotations */ public class RecordTypeAdapterFactory implements TypeAdapterFactory { private static final Map, Object> PRIMITIVE_DEFAULTS = new HashMap<>(); static { PRIMITIVE_DEFAULTS.put(byte.class, (byte) 0); PRIMITIVE_DEFAULTS.put(int.class, 0); PRIMITIVE_DEFAULTS.put(long.class, 0L); PRIMITIVE_DEFAULTS.put(short.class, (short) 0); PRIMITIVE_DEFAULTS.put(double.class, 0D); PRIMITIVE_DEFAULTS.put(float.class, 0F); PRIMITIVE_DEFAULTS.put(char.class, '\0'); PRIMITIVE_DEFAULTS.put(boolean.class, false); } private final Map> recordComponentNameCache = new ConcurrentHashMap<>(); /** * Get all names of a record component * If annotated with {@link SerializedName} the list returned will be the primary name first, then any alternative names * Otherwise, the component name will be returned. */ private List getRecordComponentNames(final RecordComponent recordComponent) { List inCache = recordComponentNameCache.get(recordComponent); if (inCache != null) { return inCache; } List names = new ArrayList<>(); // The @SerializedName is compiled to be part of the componentName() method // The use of a loop is also deliberate, getAnnotation seemed to return null if Gson's package was relocated SerializedName annotation = null; for (Annotation a : recordComponent.getAccessor().getAnnotations()) { if (a.annotationType() == SerializedName.class) { annotation = (SerializedName) a; break; } } if (annotation != null) { names.add(annotation.value()); names.addAll(Arrays.asList(annotation.alternate())); } else { names.add(recordComponent.getName()); } var namesList = List.copyOf(names); recordComponentNameCache.put(recordComponent, namesList); return namesList; } @Override public TypeAdapter create(Gson gson, TypeToken type) { @SuppressWarnings(""unchecked"") Class clazz = (Class) type.getRawType(); if (!clazz.isRecord()) { return null; } TypeAdapter delegate = gson.getDelegateAdapter(this, type); return new TypeAdapter<>() { @Override public void write(JsonWriter out, T value) throws IOException { delegate.write(out, value); } @Override public T read(JsonReader reader) throws IOException { if (reader.peek() == JsonToken.NULL) { reader.nextNull(); return null; } var recordComponents = clazz.getRecordComponents(); var typeMap = new HashMap>(); for (RecordComponent recordComponent : recordComponents) { for (String name : getRecordComponentNames(recordComponent)) { typeMap.put(name, TypeToken.get(recordComponent.getGenericType())); } } var argsMap = new HashMap(); reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); var type = typeMap.get(name); if (type != null) { argsMap.put(name, gson.getAdapter(type).read(reader)); } else { gson.getAdapter(Object.class).read(reader); } } reader.endObject(); var argTypes = new Class[recordComponents.length]; var args = new Object[recordComponents.length]; for (int i = 0; i < recordComponents.length; i++) { argTypes[i] = recordComponents[i].getType(); List names = getRecordComponentNames(recordComponents[i]); Object value = null; TypeToken type = null; // Find the first matching type and value for (String name : names) { value = argsMap.get(name); type = typeMap.get(name); if (value != null && type != null) { break; } } if (value == null && (type != null && type.getRawType().isPrimitive())) { value = PRIMITIVE_DEFAULTS.get(type.getRawType()); } args[i] = value; } Constructor constructor; try { constructor = clazz.getDeclaredConstructor(argTypes); constructor.setAccessible(true); return constructor.newInstance(args); } catch (NoSuchMethodException | InstantiationException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new RuntimeException(e); } } }; } }" "package com.rs.lib.util; import java.awt.Color; public class RSColor { public static final int HUE_MAX = 63; public static final int SATURATION_MAX = 7; public static final int LUMINANCE_MAX = 127; private int hue, saturation, luminance; private RSColor(int hue, int saturation, int luminance) { this.hue = hue; this.saturation = saturation; this.luminance = luminance; } public int getValue() { return packHSL(hue, saturation, luminance); } public RSColor adjustHue(int amount) { hue = Utils.clampI(hue+amount, 0, HUE_MAX); return this; } public RSColor adjustSaturation(int amount) { saturation = Utils.clampI(saturation+amount, 0, SATURATION_MAX); return this; } public RSColor adjustLuminance(int amount) { luminance = Utils.clampI(luminance+amount, 0, LUMINANCE_MAX); return this; } public static RSColor fromHSL(int hsl) { return new RSColor(unpackHue(hsl), unpackSaturation(hsl), unpackLuminance(hsl)); } public static short packHSL(int hue, int saturation, int luminance) { return (short) ((short) (hue & HUE_MAX) << 10 | (short) (saturation & SATURATION_MAX) << 7 | (short) (luminance & LUMINANCE_MAX)); } public static int unpackHue(int hsl) { return hsl >> 10 & HUE_MAX; } public static int unpackSaturation(int hsl) { return hsl >> 7 & SATURATION_MAX; } public static int unpackLuminance(int hsl) { return hsl & LUMINANCE_MAX; } public static String formatHSL(int hsl) { return String.format(""%02Xh%Xs%02Xl"", unpackHue(hsl), unpackSaturation(hsl), unpackLuminance(hsl)); } public static int rgbToHSL(int rgb, double brightness) { if (rgb == 1) return 0; brightness = 1.D / brightness; double r = (double) (rgb >> 16 & 255) / 256.0D; double g = (double) (rgb >> 8 & 255) / 256.0D; double b = (double) (rgb & 255) / 256.0D; r = Math.pow(r, brightness); g = Math.pow(g, brightness); b = Math.pow(b, brightness); float[] hsv = Color.RGBtoHSB((int) (r * 256.D), (int) (g * 256.D), (int) (b * 256.D), null); double hue = hsv[0]; double luminance = hsv[2] - ((hsv[2] * hsv[1]) / 2.F); double saturation = (hsv[2] - luminance) / Math.min(luminance, 1 - luminance); return packHSL((int) (Math.ceil(hue * 64.D) % 63.D), (int) Math.ceil(saturation * 7.D), (int) Math.ceil(luminance * 127.D)); } public static int RGB_to_HSL(int red, int green, int blue) { float[] HSB = Color.RGBtoHSB(red, green, blue, null); float hue = (HSB[0]); float saturation = (HSB[1]); float brightness = (HSB[2]); int encode_hue = (int) (hue * 63); // to 6-bits int encode_saturation = (int) (saturation * 7); // to 3-bits int encode_brightness = (int) (brightness * 127); // to 7-bits return (encode_hue << 10) + (encode_saturation << 7) + (encode_brightness); } public static int HSL_to_RGB(int hsl) { int decode_hue = (hsl >> 10) & 0x3f; int decode_saturation = (hsl >> 7) & 0x07; int decode_brightness = (hsl & 0x7f); return Color.HSBtoRGB((float) decode_hue / 63, (float) decode_saturation / 7, (float) decode_brightness / 127); } } " " package com.rs.lib.util; import java.awt.Color; import java.lang.SuppressWarnings; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.nio.channels.FileChannel; import java.security.MessageDigest; import java.security.SecureRandom; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.rs.cache.ArchiveType; import com.rs.cache.Cache; import com.rs.cache.IndexType; import com.rs.cache.Store; import com.rs.cache.loaders.EnumDefinitions; import com.rs.cache.loaders.ItemDefinitions; import com.rs.cache.loaders.NPCDefinitions; import com.rs.cache.loaders.QCMesDefinitions.QCValueType; import com.rs.cache.loaders.StructDefinitions; import com.rs.cache.loaders.animations.AnimationFrame; import com.rs.cache.loaders.animations.AnimationFrameSet; import com.rs.cache.loaders.cs2.CS2Instruction; import com.rs.cache.loaders.cs2.CS2Type; import com.rs.cache.loaders.sound.Instrument; import com.rs.lib.Constants; import com.rs.lib.game.Item; import com.rs.lib.game.WorldTile; import io.github.classgraph.ClassGraph; import io.github.classgraph.ClassInfo; import io.github.classgraph.ScanResult; public final class Utils { private static final Object ALGORITHM_LOCK = new Object(); private static final Random RANDOM = new SecureRandom(); public static final int[] ROTATION_DIR_X = { -1, 0, 1, 0 }; public static final int[] ROTATION_DIR_Y = { 0, 1, 0, -1 }; public static DecimalFormat FORMAT = new DecimalFormat(""###,###.##""); private static final byte[][] ANGLE_DIRECTION_DELTA = { { 0, -1 }, { -1, -1 }, { -1, 0 }, { -1, 1 }, { 0, 1 }, { 1, 1 }, { 1, 0 }, { 1, -1 } }; public static char[] CP_1252_CHARACTERS = { '\u20ac', '\0', '\u201a', '\u0192', '\u201e', '\u2026', '\u2020', '\u2021', '\u02c6', '\u2030', '\u0160', '\u2039', '\u0152', '\0', '\u017d', '\0', '\0', '\u2018', '\u2019', '\u201c', '\u201d', '\u2022', '\u2013', '\u2014', '\u02dc', '\u2122', '\u0161', '\u203a', '\u0153', '\0', '\u017e', '\u0178' }; public String getLevelDifferenceColor(int hiddenLevel, int displayedLevel) { int levelDifference = displayedLevel - hiddenLevel; if (levelDifference > 0) return String.format(""%02X%02X%02X"", 255, levelDifference > 10 ? 0 : 255 - (25 * levelDifference), 0); else if (levelDifference < 0) return String.format(""%02X%02X%02X"", levelDifference < -10 ? 0 : 255 - (25 * Math.abs(levelDifference)), 255, 0); else return String.format(""%02X%02X%02X"", 255, 255, 0); } public static int[] randSum(int numVars, int total) { double randNums[] = new double[numVars], sum = 0; for (int i = 0; i < randNums.length; i++) { randNums[i] = Math.random(); sum += randNums[i]; } for (int i = 0; i < randNums.length; i++) { randNums[i] = randNums[i] / sum * total; } int[] randInt = new int[numVars]; for (int i = 0; i < numVars; i++) randInt[i] = (int) randNums[i]; return randInt; } public static int interfaceIdFromHash(int hash) { return hash >> 16; } public static int componentIdFromHash(int hash) { return hash - ((hash >> 16) << 16); } public static Map cloneMap(Map from) { if (from == null) return null; Map newMap = new HashMap(); for (Entry entry : from.entrySet()) { newMap.put(entry.getKey(), entry.getValue()); } return newMap; } public static Object CS2ValTranslate(CS2Type valueType, Object o) { if (valueType == CS2Type.ICOMPONENT) { if (o instanceof String) return o; long interfaceId = ((int) o) >> 16; long componentId = ((int) o) - (interfaceId << 16); return ""IComponent("" + interfaceId + "", "" + componentId + "")""; } else if (valueType == CS2Type.LOCATION) { if (o instanceof String) return o; return WorldTile.of(((int) o)); } else if (valueType == CS2Type.SKILL) { if (o instanceof String) return o; int idx = (int) o; if (idx >= Constants.SKILL_NAME.length) return o; return idx + ""("" + Constants.SKILL_NAME[((int) o)] + "")""; } else if (valueType == CS2Type.ITEM) { if (o instanceof String) return o; return ((int) o) + "" ("" + ItemDefinitions.getDefs(((int) o)).getName() + "")""; } else if (valueType == CS2Type.NPCDEF) { if (o instanceof String) return o; return ((int) o) + "" ("" + NPCDefinitions.getDefs(((int) o)).getName() + "")""; } else if (valueType == CS2Type.STRUCT) { return o + "": "" + StructDefinitions.getStruct((int) o); } else if (valueType == CS2Type.ENUM) { return o + "": "" + EnumDefinitions.getEnum((int) o); } return o; } public static int[] range(int min, int max) { int[] range = new int[max - min + 1]; for (int i = min, j = 0; i <= max; i++, j++) range[j] = i; return range; } public static int[] range(int min, int max, int step) { int[] range = new int[(max - min) / step + 1]; for (int i = min, j = 0; i <= max; i += step, j++) range[j] = i; return range; } public static String formatDouble(double d) { return FORMAT.format(d); } public static double round(double value, int places) { if (places < 0) throw new IllegalArgumentException(); BigDecimal bd = new BigDecimal(Double.toString(value)); bd = bd.setScale(places, RoundingMode.HALF_UP); return bd.doubleValue(); } public static int[] shuffleIntArray(int[] array) { int[] shuffledArray = new int[array.length]; System.arraycopy(array, 0, shuffledArray, 0, array.length); for (int i = shuffledArray.length - 1; i > 0; i--) { int index = RANDOM.nextInt(i + 1); int a = shuffledArray[index]; shuffledArray[index] = shuffledArray[i]; shuffledArray[i] = a; } return shuffledArray; } public static int findClosestIdx(int[] arr, int target) { int distance = Math.abs(arr[0] - target); int idx = 0; for (int c = 1; c < arr.length; c++) { int cdistance = Math.abs(arr[c] - target); if (cdistance < distance) { idx = c; distance = cdistance; } } return idx; } public static double clampD(double val, double min, double max) { return Math.max(min, Math.min(max, val)); } public static int clampI(int val, int min, int max) { return Math.max(min, Math.min(max, val)); } public static long gcm(long a, long b) { return b == 0 ? a : gcm(b, a % b); // Not bad for one line of code :) } public static int[] asFractionArr(long a, long b) { int gcm = (int) gcm(a, b); return new int[] { (int) (a / gcm), (int) (b / gcm) }; } public static String asFraction(long a, long b) { long gcm = gcm(a, b); return (a / gcm) + ""/"" + (b / gcm); } public static Rational toRational(double number) { return toRational(number, 5); } public static boolean skillSuccess(int level, int rate1, int rate99) { return skillSuccess(level, 1.0, rate1, rate99); } public static boolean skillSuccess(int level, double percModifier, int rate1, int rate99) { return skillSuccess(level, percModifier, rate1, rate99, 256); } public static boolean skillSuccess(int level, double percModifier, int rate1, int rate99, int maxSuccess) { rate1 = (int) (percModifier * (double) rate1); rate99 = (int) (percModifier * (double) rate99); double perc = (double) level / 99.0; int chance = clampI((int) ((double) rate1 + (((double) rate99 - (double) rate1) * perc)), 0, maxSuccess); // if (Globals.DEBUG) // System.out.println(""Skilling chance: "" + chance + ""/256 - "" + Utils.formatDouble(((double) chance / 256.0) * 100.0) + ""%""); return random(255) <= chance; } public static Rational toRational(double number, int largestRightOfDecimal) { long sign = 1; if (number < 0) { number = -number; sign = -1; } final long SECOND_MULTIPLIER_MAX = (long) Math.pow(10, largestRightOfDecimal - 1); final long FIRST_MULTIPLIER_MAX = SECOND_MULTIPLIER_MAX * 10L; final double ERROR = Math.pow(10, -largestRightOfDecimal - 1); long firstMultiplier = 1; long secondMultiplier = 1; boolean notIntOrIrrational = false; long truncatedNumber = (long) number; Rational rationalNumber = new Rational((long) (sign * number * FIRST_MULTIPLIER_MAX), FIRST_MULTIPLIER_MAX); double error = number - truncatedNumber; while ((error >= ERROR) && (firstMultiplier <= FIRST_MULTIPLIER_MAX)) { secondMultiplier = 1; firstMultiplier *= 10; while ((secondMultiplier <= SECOND_MULTIPLIER_MAX) && (secondMultiplier < firstMultiplier)) { double difference = (number * firstMultiplier) - (number * secondMultiplier); truncatedNumber = (long) difference; error = difference - truncatedNumber; if (error < ERROR) { notIntOrIrrational = true; break; } secondMultiplier *= 10; } } if (notIntOrIrrational) { rationalNumber = new Rational(sign * truncatedNumber, firstMultiplier - secondMultiplier); } return rationalNumber; } public static int getRSColor(int red, int green, int blue) { float[] HSB = Color.RGBtoHSB(red, green, blue, null); float hue = (HSB[0]); float saturation = (HSB[1]); float brightness = (HSB[2]); int encode_hue = (int) (hue * 63); // to 6-bits int encode_saturation = (int) (saturation * 7); // to 3-bits int encode_brightness = (int) (brightness * 127); // to 7-bits return (encode_hue << 10) + (encode_saturation << 7) + (encode_brightness); } public static int greatestCommonDenominator(int a, int b) { if (a == 0) return b; return greatestCommonDenominator(b % a, a); } public static int greatestCommonDenominator(int... arr) { int result = arr[0]; for (int i = 1; i < arr.length; i++) result = greatestCommonDenominator(arr[i], result); return result; } public static int leastCommonMultiple(int a, int b) { return a * (b / greatestCommonDenominator(a, b)); } public static int leastCommonMultiple(int... arr) { int result = arr[0]; for (int i = 1; i < arr.length; i++) result = leastCommonMultiple(result, arr[i]); return result; } public static String quote(String str) { StringBuffer result = new StringBuffer(""\""""); for (int i = 0; i < str.length(); i++) { char c; switch (c = str.charAt(i)) { case '\0': result.append(""\\0""); break; case '\t': result.append(""\\t""); break; case '\n': result.append(""\\n""); break; case '\r': result.append(""\\r""); break; case '\\': result.append(""\\\\""); break; case '\""': result.append(""\\\""""); break; default: if (c < 32) { String oct = Integer.toOctalString(c); result.append(""\\000"".substring(0, 4 - oct.length())).append(oct); } else if (c >= 32 && c < 127) result.append(str.charAt(i)); else { String hex = Integer.toHexString(c); result.append(""\\u0000"".substring(0, 6 - hex.length())).append(hex); } } } return result.append(""\"""").toString(); } public static String quote(char c) { switch (c) { case '\0': return ""\'\\0\'""; case '\t': return ""\'\\t\'""; case '\n': return ""\'\\n\'""; case '\r': return ""\'\\r\'""; case '\\': return ""\'\\\\\'""; case '\""': return ""\'\\\""\'""; case '\'': return ""\'\\\'\'""; } if (c < 32) { String oct = Integer.toOctalString(c); return ""\'\\000"".substring(0, 5 - oct.length()) + oct + ""\'""; } if (c >= 32 && c < 127) return ""\'"" + c + ""\'""; else { String hex = Integer.toHexString(c); return ""\'\\u0000"".substring(0, 7 - hex.length()) + hex + ""\'""; } } public static char cp1252ToChar(byte i) { int i_35_ = i & 0xff; if (0 == i_35_) { throw new IllegalArgumentException(""Non cp1252 character 0x"" + Integer.toString(i_35_, 16) + "" provided""); } if (i_35_ >= 128 && i_35_ < 160) { int i_36_ = CP_1252_CHARACTERS[i_35_ - 128]; if (0 == i_36_) { i_36_ = 63; } i_35_ = i_36_; } return (char) i_35_; } public static byte charToCp1252(char c) { byte i_18_; if (c > 0 && c < '\u0080' || c >= '\u00a0' && c <= '\u00ff') { i_18_ = (byte) c; } else if ('\u20ac' == c) { i_18_ = (byte) -128; } else if (c == '\u201a') { i_18_ = (byte) -126; } else if (c == '\u0192') { i_18_ = (byte) -125; } else if (c == '\u201e') { i_18_ = (byte) -124; } else if ('\u2026' == c) { i_18_ = (byte) -123; } else if ('\u2020' == c) { i_18_ = (byte) -122; } else if ('\u2021' == c) { i_18_ = (byte) -121; } else if ('\u02c6' == c) { i_18_ = (byte) -120; } else if ('\u2030' == c) { i_18_ = (byte) -119; } else if (c == '\u0160') { i_18_ = (byte) -118; } else if (c == '\u2039') { i_18_ = (byte) -117; } else if ('\u0152' == c) { i_18_ = (byte) -116; } else if (c == '\u017d') { i_18_ = (byte) -114; } else if ('\u2018' == c) { i_18_ = (byte) -111; } else if ('\u2019' == c) { i_18_ = (byte) -110; } else if ('\u201c' == c) { i_18_ = (byte) -109; } else if ('\u201d' == c) { i_18_ = (byte) -108; } else if ('\u2022' == c) { i_18_ = (byte) -107; } else if (c == '\u2013') { i_18_ = (byte) -106; } else if ('\u2014' == c) { i_18_ = (byte) -105; } else if (c == '\u02dc') { i_18_ = (byte) -104; } else if (c == '\u2122') { i_18_ = (byte) -103; } else if ('\u0161' == c) { i_18_ = (byte) -102; } else if (c == '\u203a') { i_18_ = (byte) -101; } else if ('\u0153' == c) { i_18_ = (byte) -100; } else if ('\u017e' == c) { i_18_ = (byte) -98; } else if (c == '\u0178') { i_18_ = (byte) -97; } else { i_18_ = (byte) 63; } return i_18_; } static int getNumOfChars(CharSequence str, char val) { int count = 0; int size = str.length(); for (int i_5 = 0; i_5 < size; i_5++) { if (str.charAt(i_5) == val) { ++count; } } return count; } public static String[] splitByChar(String str, char val) { int numChars = getNumOfChars(str, val); String[] arr_4 = new String[numChars + 1]; int i_5 = 0; int i_6 = 0; for (int i_7 = 0; i_7 < numChars; i_7++) { int i_8; for (i_8 = i_6; str.charAt(i_8) != val; i_8++) { ; } arr_4[i_5++] = str.substring(i_6, i_8); i_6 = i_8 + 1; } arr_4[numChars] = str.substring(i_6); return arr_4; } public static String readString(byte[] buffer, int i_1, int i_2) { char[] arr_4 = new char[i_2]; int offset = 0; for (int i_6 = 0; i_6 < i_2; i_6++) { int i_7 = buffer[i_6 + i_1] & 0xff; if (i_7 != 0) { if (i_7 >= 128 && i_7 < 160) { char var_8 = CP_1252_CHARACTERS[i_7 - 128]; if (var_8 == 0) { var_8 = 63; } i_7 = var_8; } arr_4[offset++] = (char) i_7; } } return new String(arr_4, 0, offset); } public static int writeString(CharSequence string, int start, int end, byte[] buffer, int offset) { int length = end - start; for (int i = 0; i < length; i++) { char c = string.charAt(i + start); if (c > 0 && c < 128 || c >= 160 && c <= 255) { buffer[i + offset] = (byte) c; } else if (c == 8364) { buffer[i + offset] = -128; } else if (c == 8218) { buffer[i + offset] = -126; } else if (c == 402) { buffer[i + offset] = -125; } else if (c == 8222) { buffer[i + offset] = -124; } else if (c == 8230) { buffer[i + offset] = -123; } else if (c == 8224) { buffer[i + offset] = -122; } else if (c == 8225) { buffer[i + offset] = -121; } else if (c == 710) { buffer[i + offset] = -120; } else if (c == 8240) { buffer[i + offset] = -119; } else if (c == 352) { buffer[i + offset] = -118; } else if (c == 8249) { buffer[i + offset] = -117; } else if (c == 338) { buffer[i + offset] = -116; } else if (c == 381) { buffer[i + offset] = -114; } else if (c == 8216) { buffer[i + offset] = -111; } else if (c == 8217) { buffer[i + offset] = -110; } else if (c == 8220) { buffer[i + offset] = -109; } else if (c == 8221) { buffer[i + offset] = -108; } else if (c == 8226) { buffer[i + offset] = -107; } else if (c == 8211) { buffer[i + offset] = -106; } else if (c == 8212) { buffer[i + offset] = -105; } else if (c == 732) { buffer[i + offset] = -104; } else if (c == 8482) { buffer[i + offset] = -103; } else if (c == 353) { buffer[i + offset] = -102; } else if (c == 8250) { buffer[i + offset] = -101; } else if (c == 339) { buffer[i + offset] = -100; } else if (c == 382) { buffer[i + offset] = -98; } else if (c == 376) { buffer[i + offset] = -97; } else { buffer[i + offset] = 63; } } return length; } public static void add(List list, Item[] items) { for (Item item : items) { list.add(item); } } public static Object getFieldValue(Object object, Field field) throws Throwable { field.setAccessible(true); Class type = field.getType(); if (type == int[][].class) { return Arrays.deepToString((int[][]) field.get(object)); } else if (type == AnimationFrameSet[].class) { return Arrays.toString((AnimationFrameSet[]) field.get(object)); } else if (type == Instrument[].class) { return Arrays.toString((Instrument[]) field.get(object)); } else if (type == HashMap[].class) { return Arrays.toString((HashMap[]) field.get(object)); } else if (type == CS2Instruction[].class) { return Arrays.toString((CS2Instruction[]) field.get(object)); } else if (type == CS2Type[].class) { return Arrays.toString((CS2Type[]) field.get(object)); } else if (type == QCValueType[].class) { return Arrays.toString((QCValueType[]) field.get(object)); } else if (type == AnimationFrame[].class) { return Arrays.toString((AnimationFrame[]) field.get(object)); } else if (type == byte[].class) { return Arrays.toString((byte[]) field.get(object)); } else if (type == int[].class) { return Arrays.toString((int[]) field.get(object)); } else if (type == byte[].class) { return Arrays.toString((byte[]) field.get(object)); } else if (type == short[].class) { return Arrays.toString((short[]) field.get(object)); } else if (type == double[].class) { return Arrays.toString((double[]) field.get(object)); } else if (type == float[].class) { return Arrays.toString((float[]) field.get(object)); } else if (type == boolean[].class) { return Arrays.toString((boolean[]) field.get(object)); } else if (type == Object[].class) { return Arrays.toString((Object[]) field.get(object)); } else if (type == String[].class) { return Arrays.toString((String[]) field.get(object)); } return field.get(object); } public static String wrap(final String str, final int wrapLength) { return wrap(str, wrapLength, null, false); } public static String wrap(final String str, final int wrapLength, final String newLineStr, final boolean wrapLongWords) { return wrap(str, wrapLength, newLineStr, wrapLongWords, "" ""); } public static String wrap(final String str, int wrapLength, String newLineStr, final boolean wrapLongWords, String wrapOn) { if (str == null) { return null; } if (newLineStr == null) { newLineStr = System.lineSeparator(); } if (wrapLength < 1) { wrapLength = 1; } if (wrapOn == null || wrapOn.equals("""")) { wrapOn = "" ""; } final Pattern patternToWrapOn = Pattern.compile(wrapOn); final int inputLineLength = str.length(); int offset = 0; final StringBuilder wrappedLine = new StringBuilder(inputLineLength + 32); while (offset < inputLineLength) { int spaceToWrapAt = -1; Matcher matcher = patternToWrapOn.matcher(str.substring(offset, Math.min((int) Math.min(Integer.MAX_VALUE, offset + wrapLength + 1L), inputLineLength))); if (matcher.find()) { if (matcher.start() == 0) { offset += matcher.end(); continue; } spaceToWrapAt = matcher.start() + offset; } // only last line without leading spaces is left if (inputLineLength - offset <= wrapLength) { break; } while (matcher.find()) { spaceToWrapAt = matcher.start() + offset; } if (spaceToWrapAt >= offset) { // normal case wrappedLine.append(str, offset, spaceToWrapAt); wrappedLine.append(newLineStr); offset = spaceToWrapAt + 1; } else { // really long word or URL if (wrapLongWords) { // wrap really long word one line at a time wrappedLine.append(str, offset, wrapLength + offset); wrappedLine.append(newLineStr); offset += wrapLength; } else { // do not wrap really long word, just extend beyond limit matcher = patternToWrapOn.matcher(str.substring(offset + wrapLength)); if (matcher.find()) { spaceToWrapAt = matcher.start() + offset + wrapLength; } if (spaceToWrapAt >= 0) { wrappedLine.append(str, offset, spaceToWrapAt); wrappedLine.append(newLineStr); offset = spaceToWrapAt + 1; } else { wrappedLine.append(str, offset, str.length()); offset = inputLineLength; } } } } // Whatever is left in line is short enough to just pass through wrappedLine.append(str, offset, str.length()); return wrappedLine.toString(); } public static byte[] getDirection(int angle) { int v = angle >> 11; return ANGLE_DIRECTION_DELTA[v]; } public static String ticksToTime(double ticks) { long millis = Math.round(ticks) * 600; int seconds = (int) (millis / 1000); int minutes = seconds / 60; int hours = minutes / 60; minutes = minutes - (hours * 60); seconds = seconds - (hours * 60 * 60) - (minutes * 60); String time = """"; if (hours > 0) time += """" + hours + "" hours ""; if (minutes > 0) time += """" + minutes + "" minutes ""; if (seconds > 0) time += """" + seconds + "" seconds ""; if (time == """") time = ""moment or two""; time = time.trim() + "".""; return time; } public static void delete(File f) throws IOException { if (f.isDirectory()) { for (File c : f.listFiles()) delete(c); } if (!f.delete()) throw new FileNotFoundException(""Failed to delete file: "" + f); } // public static int getMapArchiveId(int regionX, int regionY) { // return regionX | regionY << 7; // } public static int getTodayDate() { Calendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone(""UTC"")); int day = cal.get(Calendar.DAY_OF_MONTH); int month = cal.get(Calendar.MONTH); return (month * 100 + day); } private static DateFormat dateFormat = new SimpleDateFormat(""MM/dd/yy HH:mm:ss""); private static Calendar cal = Calendar.getInstance(); public static String getDateString() { return dateFormat.format(cal.getTime()); } public static String formatNumber(int number) { return NumberFormat.getNumberInstance(Locale.US).format(number); } public static String getFormattedNumber(int amount) { return new DecimalFormat(""#,###,###"").format(amount); } public static String getFormattedNumber(double amount, char seperator) { String str = new DecimalFormat(""#,###,###"").format(amount); char[] rebuff = new char[str.length()]; for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (c >= '0' && c <= '9') rebuff[i] = c; else rebuff[i] = seperator; } return new String(rebuff); } public static String formatTypicalInteger(int integer) { return NumberFormat.getInstance().format(integer); } public static String formatLong(long longg) { return NumberFormat.getInstance().format(longg); } public static byte[] cryptRSA(byte[] data, BigInteger exponent, BigInteger modulus) { return new BigInteger(data).modPow(exponent, modulus).toByteArray(); } public static final byte[] encryptUsingMD5(byte[] buffer) { // prevents concurrency problems with the algorithm synchronized (ALGORITHM_LOCK) { try { MessageDigest algorithm = MessageDigest.getInstance(""MD5""); algorithm.update(buffer); byte[] digest = algorithm.digest(); algorithm.reset(); return digest; } catch (Throwable e) { Logger.handle(Utils.class, ""encryptUsingMD5"", e); } return null; } } public static boolean inCircle(WorldTile location, WorldTile center, int radius) { return getDistance(center, location) < radius; } @SuppressWarnings(""resource"") public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } public static final int getDistanceI(WorldTile t1, WorldTile t2) { return getDistanceI(t1.getX(), t1.getY(), t2.getX(), t2.getY()); } public static final int getDistanceI(int coordX1, int coordY1, int coordX2, int coordY2) { int deltaX = coordX2 - coordX1; int deltaY = coordY2 - coordY1; return ((int) Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2))); } public static final double getDistance(WorldTile t1, WorldTile t2) { return getDistance(t1.getX(), t1.getY(), t2.getX(), t2.getY()); } public static final double getDistance(int coordX1, int coordY1, int coordX2, int coordY2) { int deltaX = coordX2 - coordX1; int deltaY = coordY2 - coordY1; return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2)); } public static final boolean isQCValid(int id) { return Cache.STORE.getIndex(IndexType.QC_MESSAGES).fileExists(1, id); } public static final int getAngleTo(WorldTile fromTile, WorldTile toTile) { return getAngleTo(toTile.getX() - fromTile.getX(), toTile.getY() - fromTile.getY()); } public static final int getAngleTo(int xOffset, int yOffset) { return ((int) (Math.atan2(-xOffset, -yOffset) * 2607.5945876176133)) & 0x3fff; } public static final int[] getBackFace(int dir) { double ang = dir / 2607.5945876176133; return new int[] { (int) Math.round(Math.sin(ang)), (int) Math.round(Math.cos(ang)) }; } public static final int[] getFrontFace(int dir) { int[] front = getBackFace(dir); return new int[] { front[0] * -1, front[1] * -1 }; } // public static final Direction getMoveDirection(int xOffset, int yOffset) { // if (xOffset < 0) { // if (yOffset < 0) // return 5; // else if (yOffset > 0) // return 0; // else // return 3; // } else if (xOffset > 0) { // if (yOffset < 0) // return 7; // else if (yOffset > 0) // return 2; // else // return 4; // } else { // if (yOffset < 0) // return 6; // else if (yOffset > 0) // return 1; // else // return -1; // } // } public static final int getSpotAnimDefinitionsSize() { int lastArchiveId = Cache.STORE.getIndex(IndexType.SPOT_ANIMS).getLastArchiveId(); return lastArchiveId * 256 + Cache.STORE.getIndex(IndexType.SPOT_ANIMS).getValidFilesCount(lastArchiveId); } public static final int getAnimationDefinitionsSize() { int lastArchiveId = Cache.STORE.getIndex(IndexType.ANIMATIONS).getLastArchiveId(); return lastArchiveId * 128 + Cache.STORE.getIndex(IndexType.ANIMATIONS).getValidFilesCount(lastArchiveId); } public static final int getBASAnimDefSize() { return Cache.STORE.getIndex(IndexType.CONFIG).getValidFilesCount(ArchiveType.BAS.getId()); } public static final int getConfigDefinitionsSize() { int lastArchiveId = Cache.STORE.getIndex(IndexType.VARBITS).getLastArchiveId(); return lastArchiveId * 256 + Cache.STORE.getIndex(IndexType.VARBITS).getValidFilesCount(lastArchiveId); } public static final int getObjectDefinitionsSize() { int lastArchiveId = Cache.STORE.getIndex(IndexType.OBJECTS).getLastArchiveId(); return lastArchiveId * 256 + Cache.STORE.getIndex(IndexType.OBJECTS).getValidFilesCount(lastArchiveId); } public static final int getNPCDefinitionsSize() { int lastArchiveId = Cache.STORE.getIndex(IndexType.NPCS).getLastArchiveId(); return lastArchiveId * 128 + Cache.STORE.getIndex(IndexType.NPCS).getValidFilesCount(lastArchiveId); } // 22314 public static final int getItemDefinitionsSize() { int lastArchiveId = Cache.STORE.getIndex(IndexType.ITEMS).getLastArchiveId(); return (lastArchiveId * 256 + Cache.STORE.getIndex(IndexType.ITEMS).getValidFilesCount(lastArchiveId)); } public static final int getItemDefinitionsSize(Store store) { int lastArchiveId = store.getIndex(IndexType.ITEMS).getLastArchiveId(); return (lastArchiveId * 256 + store.getIndex(IndexType.ITEMS).getValidFilesCount(lastArchiveId)); } public static final int getVarbitDefinitionsSize() { return Cache.STORE.getIndex(IndexType.VARBITS).getLastArchiveId() * 0x3ff; } public static boolean itemExists(int id) { if (id >= getItemDefinitionsSize()) return false; return Cache.STORE.getIndex(IndexType.ITEMS).fileExists(id >>> 8, 0xff & id); } public static final int getInterfaceDefinitionsSize() { return Cache.STORE.getIndex(IndexType.INTERFACES).getLastArchiveId() + 1; } public static final int getInterfaceDefinitionsComponentsSize(int interfaceId) { return Cache.STORE.getIndex(IndexType.INTERFACES).getLastFileId(interfaceId) + 1; } public static String formatPlayerNameForProtocol(String name) { if (name == null) return """"; name = name.replaceAll("" "", ""_""); name = name.toLowerCase(); return name; } public static String formatPlayerNameForDisplay(String name) { if (name == null) return """"; name = name.replaceAll(""_"", "" ""); name = name.toLowerCase(); StringBuilder newName = new StringBuilder(); boolean wasSpace = true; for (int i = 0; i < name.length(); i++) { if (wasSpace) { newName.append(("""" + name.charAt(i)).toUpperCase()); wasSpace = false; } else { newName.append(name.charAt(i)); } if (name.charAt(i) == ' ') { wasSpace = true; } } return newName.toString(); } public static final int getRandomInclusive(int maxValue) { return (int) (Math.random() * (maxValue + 1)); } public static final int random(int min, int max) { final int n = Math.abs(max - min); return Math.min(min, max) + (n == 0 ? 0 : random(n)); } public static final int randomInclusive(int min, int max) { return random(min, max + 1); } public static final double random(double min, double max) { return min + (max - min) * RANDOM.nextDouble(); } public static final double randomD() { return RANDOM.nextDouble(); } public static final int next(int max, int min) { return min + (int) (Math.random() * ((max - min) + 1)); } public static final double random(double maxValue) { return random(0.0, maxValue); } public static final int random(int maxValue) { if (maxValue <= 0) return 0; return RANDOM.nextInt(maxValue); } public static final long randomLong(long n) { long bits, val; do { bits = (RANDOM.nextLong() << 1) >>> 1; val = bits % n; } while (bits - val + (n - 1) < 0L); return val; } public static final String longToString(long l) { if (l <= 0L || l >= 0x5b5b57f8a98a5dd1L) return null; if (l % 37L == 0L) return null; int i = 0; char ac[] = new char[12]; while (l != 0L) { long l1 = l; l /= 37L; ac[11 - i++] = VALID_CHARS[(int) (l1 - l * 37L)]; } return new String(ac, 12 - i, i); } public static final char[] VALID_CHARS = { '_', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; public static final char[] SUPER_VALID_CHARS = { ' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; public static boolean invalidAccountName(String name) { return name.length() == 0 || name.length() > 12 || name.startsWith(""_"") || name.endsWith(""_"") || name.contains(""__"") || containsInvalidCharacter(name); } public static boolean invalidAuthId(String auth) { return auth.length() != 10 || auth.contains(""_"") || containsInvalidCharacter(auth); } public static boolean containsBadCharacter(char c) { for (char vc : SUPER_VALID_CHARS) { if (vc == c) return false; } return true; } public static boolean containsInvalidCharacter(char c) { for (char vc : VALID_CHARS) { if (vc == c) return false; } return true; } public static boolean containsInvalidCharacter(String name) { for (char c : name.toCharArray()) { if (containsInvalidCharacter(c)) return true; } return false; } public static boolean containsBadCharacter(String name) { for (char c : name.toCharArray()) { if (containsBadCharacter(c)) return true; } return false; } public static final long stringToLong(String s) { long l = 0L; for (int i = 0; i < s.length() && i < 12; i++) { char c = s.charAt(i); l *= 37L; if (c >= 'A' && c <= 'Z') l += (1 + c) - 65; else if (c >= 'a' && c <= 'z') l += (1 + c) - 97; else if (c >= '0' && c <= '9') l += (27 + c) - 48; } while (l % 37L == 0L && l != 0L) { l /= 37L; } return l; } public static final int packGJString2(int position, byte[] buffer, String String) { int length = String.length(); int offset = position; for (int index = 0; length > index; index++) { int character = String.charAt(index); if (character > 127) { if (character > 2047) { buffer[offset++] = (byte) ((character | 919275) >> 12); buffer[offset++] = (byte) (128 | ((character >> 6) & 63)); buffer[offset++] = (byte) (128 | (character & 63)); } else { buffer[offset++] = (byte) ((character | 12309) >> 6); buffer[offset++] = (byte) (128 | (character & 63)); } } else buffer[offset++] = (byte) character; } return offset - position; } public static final int calculateGJString2Length(String String) { int length = String.length(); int gjStringLength = 0; for (int index = 0; length > index; index++) { char c = String.charAt(index); if (c > '\u007f') { if (c <= '\u07ff') gjStringLength += 2; else gjStringLength += 3; } else gjStringLength++; } return gjStringLength; } public static final int getNameHash(String name) { name = name.toLowerCase(); int hash = 0; for (int index = 0; index < name.length(); index++) hash = method1258(name.charAt(index)) + ((hash << 5) - hash); return hash; } public static final byte method1258(char c) { byte charByte; if (c > 0 && c < '\200' || c >= '\240' && c <= '\377') { charByte = (byte) c; } else if (c != '\u20AC') { if (c != '\u201A') { if (c != '\u0192') { if (c == '\u201E') { charByte = -124; } else if (c != '\u2026') { if (c != '\u2020') { if (c == '\u2021') { charByte = -121; } else if (c == '\u02C6') { charByte = -120; } else if (c == '\u2030') { charByte = -119; } else if (c == '\u0160') { charByte = -118; } else if (c == '\u2039') { charByte = -117; } else if (c == '\u0152') { charByte = -116; } else if (c != '\u017D') { if (c == '\u2018') { charByte = -111; } else if (c != '\u2019') { if (c != '\u201C') { if (c == '\u201D') { charByte = -108; } else if (c != '\u2022') { if (c == '\u2013') { charByte = -106; } else if (c == '\u2014') { charByte = -105; } else if (c == '\u02DC') { charByte = -104; } else if (c == '\u2122') { charByte = -103; } else if (c != '\u0161') { if (c == '\u203A') { charByte = -101; } else if (c != '\u0153') { if (c == '\u017E') { charByte = -98; } else if (c != '\u0178') { charByte = 63; } else { charByte = -97; } } else { charByte = -100; } } else { charByte = -102; } } else { charByte = -107; } } else { charByte = -109; } } else { charByte = -110; } } else { charByte = -114; } } else { charByte = -122; } } else { charByte = -123; } } else { charByte = -125; } } else { charByte = -126; } } else { charByte = -128; } return charByte; } public static char[] aCharArray6385 = { '\u20ac', '\0', '\u201a', '\u0192', '\u201e', '\u2026', '\u2020', '\u2021', '\u02c6', '\u2030', '\u0160', '\u2039', '\u0152', '\0', '\u017d', '\0', '\0', '\u2018', '\u2019', '\u201c', '\u201d', '\u2022', '\u2013', '\u2014', '\u02dc', '\u2122', '\u0161', '\u203a', '\u0153', '\0', '\u017e', '\u0178' }; public static final String getUnformatedMessage(int messageDataLength, int messageDataOffset, byte[] messageData) { char[] cs = new char[messageDataLength]; int i = 0; for (int i_6_ = 0; i_6_ < messageDataLength; i_6_++) { int i_7_ = 0xff & messageData[i_6_ + messageDataOffset]; if ((i_7_ ^ 0xffffffff) != -1) { if ((i_7_ ^ 0xffffffff) <= -129 && (i_7_ ^ 0xffffffff) > -161) { int i_8_ = aCharArray6385[i_7_ - 128]; if (i_8_ == 0) i_8_ = 63; i_7_ = i_8_; } cs[i++] = (char) i_7_; } } return new String(cs, 0, i); } public static final byte[] getFormatedMessage(String message) { int i_0_ = message.length(); byte[] is = new byte[i_0_]; for (int i_1_ = 0; (i_1_ ^ 0xffffffff) > (i_0_ ^ 0xffffffff); i_1_++) { int i_2_ = message.charAt(i_1_); if (((i_2_ ^ 0xffffffff) >= -1 || i_2_ >= 128) && (i_2_ < 160 || i_2_ > 255)) { if ((i_2_ ^ 0xffffffff) != -8365) { if ((i_2_ ^ 0xffffffff) == -8219) is[i_1_] = (byte) -126; else if ((i_2_ ^ 0xffffffff) == -403) is[i_1_] = (byte) -125; else if (i_2_ == 8222) is[i_1_] = (byte) -124; else if (i_2_ != 8230) { if ((i_2_ ^ 0xffffffff) != -8225) { if ((i_2_ ^ 0xffffffff) != -8226) { if ((i_2_ ^ 0xffffffff) == -711) is[i_1_] = (byte) -120; else if (i_2_ == 8240) is[i_1_] = (byte) -119; else if ((i_2_ ^ 0xffffffff) == -353) is[i_1_] = (byte) -118; else if ((i_2_ ^ 0xffffffff) != -8250) { if (i_2_ == 338) is[i_1_] = (byte) -116; else if (i_2_ == 381) is[i_1_] = (byte) -114; else if ((i_2_ ^ 0xffffffff) == -8217) is[i_1_] = (byte) -111; else if (i_2_ == 8217) is[i_1_] = (byte) -110; else if (i_2_ != 8220) { if (i_2_ == 8221) is[i_1_] = (byte) -108; else if ((i_2_ ^ 0xffffffff) == -8227) is[i_1_] = (byte) -107; else if ((i_2_ ^ 0xffffffff) != -8212) { if (i_2_ == 8212) is[i_1_] = (byte) -105; else if ((i_2_ ^ 0xffffffff) != -733) { if (i_2_ != 8482) { if (i_2_ == 353) is[i_1_] = (byte) -102; else if (i_2_ != 8250) { if ((i_2_ ^ 0xffffffff) == -340) is[i_1_] = (byte) -100; else if (i_2_ != 382) { if (i_2_ == 376) is[i_1_] = (byte) -97; else is[i_1_] = (byte) 63; } else is[i_1_] = (byte) -98; } else is[i_1_] = (byte) -101; } else is[i_1_] = (byte) -103; } else is[i_1_] = (byte) -104; } else is[i_1_] = (byte) -106; } else is[i_1_] = (byte) -109; } else is[i_1_] = (byte) -117; } else is[i_1_] = (byte) -121; } else is[i_1_] = (byte) -122; } else is[i_1_] = (byte) -123; } else is[i_1_] = (byte) -128; } else is[i_1_] = (byte) i_2_; } return is; } public static int getHashMapSize(int size) { size--; size |= size >>> -1810941663; size |= size >>> 2010624802; size |= size >>> 10996420; size |= size >>> 491045480; size |= size >>> 1388313616; return 1 + size; } /** * Walk dirs 0 - South-West 1 - South 2 - South-East 3 - West 4 - East 5 - * North-West 6 - North 7 - North-East */ public static int getPlayerWalkingDirection(int dx, int dy) { if (dx == -1 && dy == -1) { return 0; } if (dx == 0 && dy == -1) { return 1; } if (dx == 1 && dy == -1) { return 2; } if (dx == -1 && dy == 0) { return 3; } if (dx == 1 && dy == 0) { return 4; } if (dx == -1 && dy == 1) { return 5; } if (dx == 0 && dy == 1) { return 6; } if (dx == 1 && dy == 1) { return 7; } return -1; } public static int getPlayerRunningDirection(int dx, int dy) { if (dx == -2 && dy == -2) return 0; if (dx == -1 && dy == -2) return 1; if (dx == 0 && dy == -2) return 2; if (dx == 1 && dy == -2) return 3; if (dx == 2 && dy == -2) return 4; if (dx == -2 && dy == -1) return 5; if (dx == 2 && dy == -1) return 6; if (dx == -2 && dy == 0) return 7; if (dx == 2 && dy == 0) return 8; if (dx == -2 && dy == 1) return 9; if (dx == 2 && dy == 1) return 10; if (dx == -2 && dy == 2) return 11; if (dx == -1 && dy == 2) return 12; if (dx == 0 && dy == 2) return 13; if (dx == 1 && dy == 2) return 14; if (dx == 2 && dy == 2) return 15; return -1; } public static List> getClassesWithAnnotation(String packageName, Class annotation) throws ClassNotFoundException, IOException { List> classes = new ArrayList>(); try (ScanResult scanResult = new ClassGraph().enableClassInfo().enableAnnotationInfo().acceptPackages(packageName).scan()) { for (ClassInfo classInfo : scanResult.getClassesWithAnnotation(annotation.getName())) classes.add(classInfo.loadClass()); } return classes; } public static List> getClasses(String packageName) throws ClassNotFoundException, IOException { List> classes = new ArrayList>(); try (ScanResult scanResult = new ClassGraph().enableClassInfo().acceptPackages(packageName).scan()) { for (ClassInfo classInfo : scanResult.getAllClasses()) classes.add(classInfo.loadClass()); } return classes; } public static List> getSubClasses(String packageName, Class superClass) throws ClassNotFoundException, IOException { List> classes = new ArrayList>(); try (ScanResult scanResult = new ClassGraph().enableClassInfo().acceptPackages(packageName).scan()) { for (ClassInfo classInfo : scanResult.getSubclasses(superClass.getName())) classes.add(classInfo.loadClass()); } return classes; } public static String[] SYMBOLS = { "":"", "";"" }; public static boolean isSymbol(String line) { for (int i = 0; i < SYMBOLS.length; i++) { if (line.equals(SYMBOLS[i])) { return true; } } return false; } public static String fixChatMessage(String message) { StringBuilder sb = new StringBuilder(); boolean space = false; boolean forcedCaps = true; for (int i = 0; i < message.length(); i++) { if (forcedCaps) { if (String.valueOf(message.charAt(i)).equals("" "") || isSymbol(String.valueOf(message.charAt(i)))) { sb.append(message.charAt(i)); } else { sb.append(String.valueOf(message.charAt(i)).toUpperCase()); forcedCaps = false; } } else { String line = String.valueOf(message.charAt(i)); if (line.equals(""?"") || line.equals(""!"") || line.equals(""."") || line.equals("":"") || line.equals("";"")) { forcedCaps = true; sb.append(line); } else if (line.equals("" "")) { space = true; sb.append(line); } else if (line.equals(line.toUpperCase())) { if (space) { sb.append(line); space = false; } else { sb.append(line.toLowerCase()); } } else { sb.append(line); space = false; forcedCaps = false; } } } return sb.toString(); } public static int getProjectileTime(int i, WorldTile startTile, WorldTile endTile, int startHeight, int endHeight, int speed, int delay, int curve, int startDistanceOffset, int creatorSize) { int distance = (int) (Utils.getDistance(startTile, endTile) + 1); if (speed == 0) // cant be 0, happens cuz method wrong and so /10 needed // so may round to 0 speed = 1; return (int) ((delay * 10) + (distance * ((30 / speed) * 10) /** Math.cos(Math.toRadians(curve)) */ )); } public static int getProjectileTime(WorldTile startTile, WorldTile endTile, int startHeight, int endHeight, int speed, int delay, int curve, int startDistanceOffset, int creatorSize) { int distance = (int) (Utils.getDistance(startTile, endTile) + 1); if (speed == 0) // cant be 0, happens cuz method wrong and so /10 needed // so may round to 0 speed = 1; return (delay * 10) + (distance * ((30 / speed) * 10) /** Math.cos(Math.toRadians(curve)) */ ); } public static int getProjectileTimeNew(WorldTile from, int fromSizeX, int fromSizeY, WorldTile to, int toSizeX, int toSizeY, double speed) { int fromX = from.getX() * 2 + fromSizeX; int fromY = from.getY() * 2 + fromSizeY; int toX = to.getX() * 2 + toSizeX; int toY = to.getY() * 2 + toSizeY; fromX /= 2; fromY /= 2; toX /= 2; toY /= 2; int deltaX = fromX - toX; int deltaY = fromY - toY; int sqrt = (int) Math.sqrt((deltaX * deltaX) + (deltaY * deltaY)); return (int) (sqrt * (10 / speed)); } public static int getProjectileTimeSoulsplit(WorldTile from, int fromSizeX, int fromSizeY, WorldTile to, int toSizeX, int toSizeY) { int fromX = from.getX() * 2 + fromSizeX; int fromY = from.getY() * 2 + fromSizeY; int toX = to.getX() * 2 + toSizeX; int toY = to.getY() * 2 + toSizeY; fromX /= 2; fromY /= 2; toX /= 2; toY /= 2; int deltaX = fromX - toX; int deltaY = fromY - toY; int sqrt = (int) Math.sqrt((deltaX * deltaX) + (deltaY * deltaY)); sqrt *= 15; sqrt -= sqrt % 30; return Math.max(30, sqrt); } public static int projectileTimeToCycles(int time) { return (time + 29) / 30; /* return Math.max(1, (time+14)/30); */ } public static boolean isWithin(int i, int min, int max) { if (i > min && i < max) return true; return false; } public static boolean isWithinInclusive(int i, int min, int max) { if (i >= min && i <= max) return true; return false; } public static String formatTime(long time) { long seconds = time / 1000; long minutes = seconds / 60; long hours = minutes / 60; seconds = seconds % 60; minutes = minutes % 60; hours = hours % 24; StringBuilder string = new StringBuilder(); string.append(hours > 9 ? hours : (""0"" + hours)); string.append("":"" + (minutes > 9 ? minutes : (""0"" + minutes))); string.append("":"" + (seconds > 9 ? seconds : (""0"" + seconds))); return string.toString(); } public static int djb2(String str) { int hash = 0; for (int i = 0; i < str.length(); i++) { hash = str.charAt(i) + ((hash << 5) - hash); } return hash; } public static String getFormatedDate() { Calendar c = Calendar.getInstance(); return ""["" + ((c.get(Calendar.MONTH)) + 1) + ""/"" + c.get(Calendar.DATE) + ""/"" + c.get(Calendar.YEAR) + ""]""; } public static int calculateKerning(byte[][] bytes_0, byte[][] bytes_1, int[] ints_2, byte[] bytes_3, int[] ints_4, int i_5, int i_6) { int i_8 = ints_2[i_5]; int i_9 = i_8 + ints_4[i_5]; int i_10 = ints_2[i_6]; int i_11 = i_10 + ints_4[i_6]; int i_12 = i_8; if (i_10 > i_8) { i_12 = i_10; } int i_13 = i_9; if (i_11 < i_9) { i_13 = i_11; } int i_14 = bytes_3[i_5] & 0xff; if ((bytes_3[i_6] & 0xff) < i_14) { i_14 = bytes_3[i_6] & 0xff; } byte[] bytes_15 = bytes_1[i_5]; byte[] bytes_16 = bytes_0[i_6]; int i_17 = i_12 - i_8; int i_18 = i_12 - i_10; for (int i_19 = i_12; i_19 < i_13; i_19++) { int i_20 = bytes_15[i_17++] + bytes_16[i_18++]; if (i_20 < i_14) { i_14 = i_20; } } return -i_14; } public static int stringToInt(CharSequence charsequence_0) { int i_2 = charsequence_0.length(); int i_3 = 0; for (int i_4 = 0; i_4 < i_2; i_4++) { i_3 = (i_3 << 5) - i_3 + charsequence_0.charAt(i_4); } return i_3; } public static final Pattern VALID_EMAIL_ADDRESS_REGEX = Pattern.compile(""^(?=.{1,64}@)[A-Za-z0-9_-]+(\\.[A-Za-z0-9_-]+)*@[^-][A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})$"", Pattern.CASE_INSENSITIVE); public static boolean validEmail(String emailStr) { Matcher matcher = Utils.VALID_EMAIL_ADDRESS_REGEX.matcher(emailStr); return matcher.find(); } public static String concat(String[] args) { String str = """"; for (int i = 0; i < args.length; i++) str += args[i] + ((i == args.length - 1) ? """" : "" ""); return str; } public static String concat(String[] args, int start) { String str = """"; for (int i = start; i < args.length; i++) str += args[i] + ((i == args.length - 1) ? """" : "" ""); return str; } public static String addArticle(String name) { if (name == null || name.isEmpty()) return """"; String s = """"; switch (name.toCharArray()[0]) { case 'a': case 'e': case 'i': case 'o': case 'u': case 'A': case 'E': case 'I': case 'O': case 'U': s += ""an ""; break; default: s += ""a ""; break; } s += name; return s; } public static int diff(int a, int b) { return Math.abs(a - b); } public static String removeInvalidChars(String s) { return s.replaceAll(""[^\\sa-zA-Z0-9_]"", """").replace("" "", "" ""); } public static int toInterfaceHash(int interfaceId, int componentId) { return (interfaceId << 16) + componentId; } public static String kmify(int num) { if (num < 0) return """"; if (num < 10000) return """" + num; if (num < 10000000) return (num / 1000) + ""K""; return (num / 1000000) + ""M""; } public static Object[] streamObjects(Object... objects) { List list = new ArrayList<>(); for (Object object : objects) { if (object.getClass().isArray()) { for (int i = 0; i < Array.getLength(object); i++) { list.add(Array.get(object, i)); } } else list.add(object); } return list.toArray(); } } " " package com.rs.lib.util; import com.rs.lib.game.WorldTile; public class Vec2 { private float x, y; public Vec2(float x, float y) { this.x = x; this.y = y; } public Vec2(WorldTile tile) { this.x = tile.getX(); this.y = tile.getY(); } public float getX() { return x; } public void setX(float x) { this.x = x; } public float getY() { return y; } public void setY(float y) { this.y = y; } public Vec2 sub(Vec2 v2) { return new Vec2(this.x - v2.x, this.y - v2.y); } public void norm() { float mag = (float) Math.sqrt(this.x*this.x + this.y*this.y); this.x = (float) (this.x / mag); this.y = (float) (this.y / mag); } public WorldTile toTile() { return toTile(0); } public WorldTile toTile(int plane) { return WorldTile.of((int) Math.round(this.x), (int) Math.round(this.y), plane); } @Override public String toString() { return ""["" + x +"",""+y+""]""; } } " " package com.rs.lib.util.reflect; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.lang.reflect.Modifier; import com.rs.lib.io.InputStream; import com.rs.lib.io.OutputStream; import com.rs.lib.net.packets.decoders.ReflectionCheckResponse.ResponseCode; public class ReflectionCheck { public enum Type { GET_INT, SET_INT, GET_FIELD_MODIFIERS, GET_METHOD_RETURN_VALUE, GET_METHOD_MODIFIERS } private Type type; private String className; private String returnType; private String methodName; private String[] paramTypes; private Object[] paramValues; private int fieldValue; private ReflectionResponse response; public ReflectionCheck(String className, String fieldName, boolean getInt) { this.type = Type.GET_INT; this.className = className; this.methodName = fieldName; } public ReflectionCheck(String className, String fieldName) { this.type = Type.GET_FIELD_MODIFIERS; this.className = className; this.methodName = fieldName; } public ReflectionCheck(String className, String methodName, int fieldValue) { this.type = Type.SET_INT; this.className = className; this.methodName = methodName; this.fieldValue = fieldValue; } public ReflectionCheck(String className, String returnType, String methodName, String[] paramTypes) { this.type = Type.GET_METHOD_MODIFIERS; this.className = className; this.returnType = returnType; this.methodName = methodName; this.paramTypes = paramTypes; } public ReflectionCheck(String className, String returnType, String methodName, Object[] paramValues) { this.type = Type.GET_METHOD_RETURN_VALUE; this.className = className; this.returnType = returnType; this.methodName = methodName; this.paramTypes = new String[paramValues.length]; for (int i = 0;i < paramTypes.length;i++) { if (paramValues[i] instanceof Byte) paramTypes[i] = ""B""; else if (paramValues[i] instanceof Integer) paramTypes[i] = ""I""; else if (paramValues[i] instanceof Short) paramTypes[i] = ""S""; else if (paramValues[i] instanceof Long) paramTypes[i] = ""J""; else if (paramValues[i] instanceof Boolean) paramTypes[i] = ""Z""; else if (paramValues[i] instanceof Float) paramTypes[i] = ""F""; else if (paramValues[i] instanceof Double) paramTypes[i] = ""D""; else if (paramValues[i] instanceof Character) paramTypes[i] = ""C""; else if (paramValues[i] instanceof Void) paramTypes[i] = ""void""; else paramTypes[i] = paramValues[i].getClass().getName(); } this.paramValues = paramValues; } public void decode(InputStream stream) { ResponseCode code = ResponseCode.forId(stream.readByte()); response = new ReflectionResponse(code); switch(type) { case GET_INT, GET_FIELD_MODIFIERS, GET_METHOD_MODIFIERS -> { if (code == ResponseCode.SUCCESS) { response.setData(stream.readInt()); if (type == Type.GET_FIELD_MODIFIERS || type == Type.GET_METHOD_MODIFIERS) response.setStringData(Modifier.toString((int) response.getData())); } } case GET_METHOD_RETURN_VALUE -> { switch(code) { case NUMBER -> response.setData(stream.readLong()); case STRING -> response.setStringData(stream.readString()); default -> {} } } case SET_INT -> {} } } public void encode(OutputStream stream) { stream.writeByte(type.ordinal()); switch(type) { case GET_INT, SET_INT, GET_FIELD_MODIFIERS -> { stream.writeString(className); stream.writeString(methodName); if (type == Type.SET_INT) stream.writeInt(fieldValue); } case GET_METHOD_RETURN_VALUE, GET_METHOD_MODIFIERS -> { stream.writeString(className); stream.writeString(methodName); stream.writeByte(paramTypes.length); for (String param : paramTypes) stream.writeString(param); stream.writeString(returnType); if (type == Type.GET_METHOD_RETURN_VALUE) { for (Object obj : paramValues) { try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos)) { oos.writeObject(obj); byte[] data = bos.toByteArray(); stream.writeInt(data.length); stream.writeBytes(data); } catch (IOException e) { e.printStackTrace(); } } } } } } public String getClassName() { return className; } public String getReturnType() { return returnType; } public String getMethodName() { return methodName; } public String[] getParamTypes() { return paramTypes; } public Type getType() { return type; } public ReflectionResponse getResponse() { return response; } } " "package com.rs.lib.util.reflect; import com.rs.lib.util.Utils; public class ReflectionChecks { private int id; private ReflectionCheck[] checks; public ReflectionChecks() { this.id = Utils.random(Integer.MAX_VALUE-1); } public int getId() { return id; } public ReflectionCheck[] getChecks() { return checks; } public ReflectionChecks setReflectionChecks(ReflectionCheck[] checks) { this.checks = checks; return this; } } " "package com.rs.lib.util.reflect; import com.rs.lib.net.packets.decoders.ReflectionCheckResponse.ResponseCode; public class ReflectionResponse { private ResponseCode code; private long data; private String stringData; public ReflectionResponse(ResponseCode code) { this.code = code; } public ResponseCode getCode() { return code; } public long getData() { return data; } public void setData(long data) { this.data = data; } public String getStringData() { return stringData; } public void setStringData(String stringData) { this.stringData = stringData; } @Override public String toString() { return ""{ "" + code + "", "" + data + "", "" + stringData + "" }""; } } " " package com.rs.lib.web; import io.undertow.Handlers; import io.undertow.Undertow; import io.undertow.UndertowOptions; import io.undertow.server.handlers.ExceptionHandler; public class APIServer { private String prefixPath; private int port; private ExceptionHandler api; private Undertow server; public APIServer(String prefixPath, int port, ExceptionHandler api) { this.prefixPath = prefixPath; this.port = port; this.api = api; } public void start() { server = Undertow.builder() .addHttpListener(port, ""0.0.0.0"") .setServerOption(UndertowOptions.RECORD_REQUEST_START_TIME, true) .setHandler(Handlers.path().addPrefixPath(prefixPath, api)) .build(); server.start(); } public Undertow getUndertow() { return server; } } " " package com.rs.lib.web; import java.io.IOException; import java.net.ConnectException; import java.net.NoRouteToHostException; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.util.Deque; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import com.rs.lib.file.JsonFileManager; import com.rs.lib.util.Logger; import io.undertow.server.HttpServerExchange; import io.undertow.util.HeaderValues; import io.undertow.util.Headers; import io.undertow.util.StatusCodes; import okhttp3.Call; import okhttp3.Callback; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Request.Builder; import okhttp3.RequestBody; import okhttp3.Response; public class APIUtil { private static OkHttpClient client = new OkHttpClient.Builder() .readTimeout(10, TimeUnit.SECONDS) .build(); public static void sendResponse(HttpServerExchange exchange, int stateCode, Object responseObject) { try { exchange.setStatusCode(stateCode); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, ""application/json""); exchange.getResponseSender().send(JsonFileManager.toJson(responseObject)); } catch(Throwable e) { Logger.handle(APIUtil.class, ""sendResponse"", e); } } public static void readJSON(HttpServerExchange ex, Class clazz, Consumer cb) { ex.getRequestReceiver().receiveFullBytes((e, m) -> { try { T obj = JsonFileManager.fromJSONString(new String(m), clazz); cb.accept(obj); } catch (Throwable t) { Logger.handle(APIUtil.class, ""readJSON"", t); sendResponse(ex, StatusCodes.BAD_REQUEST, new ErrorResponse(""Error parsing body."")); } }); } public static boolean authenticate(HttpServerExchange ex, String key) { HeaderValues header = ex.getRequestHeaders().get(""key""); if (header != null && header.getFirst() != null && header.getFirst().equals(key)) return true; return false; } public static void post(Class returnType, Object body, String url, String apiKey, Consumer cb) { if (body == null) { Logger.error(APIUtil.class, ""post"", ""Async POST connection attempted with null body "" + url); cb.accept(null); } Logger.trace(APIUtil.class, ""post"", ""Sending request: "" + url); try { Builder builder = new Request.Builder() .url(url) .post(RequestBody.create(JsonFileManager.toJson(body), MediaType.parse(""application/json""))) .header(""accept"", ""application/json""); if (apiKey != null) builder.header(""key"", apiKey); Request request = builder.build(); Call call = client.newCall(request); call.enqueue(new Callback() { public void onResponse(Call call, Response response) { try { String json = response.body().string(); Logger.trace(APIUtil.class, ""post"", ""Request finished: "" + json); if (returnType != null) { if (cb != null) cb.accept(JsonFileManager.fromJSONString(json, returnType)); } else { if (cb != null) cb.accept(null); } } catch (Throwable e) { if (e instanceof ConnectException || e instanceof SocketTimeoutException) { Logger.error(APIUtil.class, ""post"", ""Async POST Connection timed out to "" + url); cb.accept(null); return; } if (e instanceof UnknownHostException || e instanceof NoRouteToHostException) { Logger.error(APIUtil.class, ""post"", ""POST Connection timed out (Unknown host) to "" + url); cb.accept(null); return; } Logger.handle(APIUtil.class, ""post"", ""Error parsing body..."", e); if (cb != null) cb.accept(null); } } public void onFailure(Call call, IOException e) { if (e instanceof ConnectException || e instanceof SocketTimeoutException) { Logger.error(APIUtil.class, ""post"", ""POST Connection timed out to "" + url); cb.accept(null); return; } if (e instanceof UnknownHostException || e instanceof NoRouteToHostException) { Logger.error(APIUtil.class, ""post"", ""POST Connection timed out (Unknown host) to "" + url); cb.accept(null); return; } Logger.trace(APIUtil.class, ""post"", ""Request failed to "" + url); if (cb != null) cb.accept(null); } }); } catch(Throwable e) { Logger.handle(APIUtil.class, ""post"", ""Error sending async post request."", e); } } public static T postSync(Class returnType, Object body, String url, String apiKey) { Logger.trace(APIUtil.class, ""postSync"", ""Sending request: "" + url); if (body == null) { Logger.error(APIUtil.class, ""postSync"", ""POST connection attempted with null body "" + url); return null; } try { Builder builder = new Request.Builder() .url(url) .post(RequestBody.create(JsonFileManager.toJson(body), MediaType.parse(""application/json""))) .header(""accept"", ""application/json""); if (apiKey != null) builder.header(""key"", apiKey); Request request = builder.build(); Call call = client.newCall(request); try { Response response = call.execute(); String json = response.body().string(); Logger.trace(APIUtil.class, ""postSync"", ""Request finished: "" + json); try { if (returnType != null) return JsonFileManager.fromJSONString(json, returnType); return null; } catch(Throwable e) { Logger.handle(APIUtil.class, ""postSync"", ""Error parsing body..."", e); return null; } } catch(Throwable e) { if (e instanceof ConnectException || e instanceof SocketTimeoutException) { Logger.error(APIUtil.class, ""postSync"", ""POST Connection timed out to "" + url); return null; } if (e instanceof UnknownHostException || e instanceof NoRouteToHostException) { Logger.error(APIUtil.class, ""postSync"", ""POST Connection timed out (Unknown host) to "" + url); return null; } Logger.handle(APIUtil.class, ""postSync"", ""Request failed to "" + url, e); return null; } } catch(Throwable e) { Logger.handle(APIUtil.class, ""postSync"", ""Error sending post request."", e); return null; } } public static void get(Class returnType, String url, String apiKey, Consumer cb) { Logger.trace(APIUtil.class, ""get"", ""Sending request: "" + url); try { Builder builder = new Request.Builder() .url(url) .get() .header(""accept"", ""application/json""); if (apiKey != null) builder.header(""key"", apiKey); Request request = builder.build(); Call call = client.newCall(request); call.enqueue(new Callback() { public void onResponse(Call call, Response response) { try { String json = response.body().string(); Logger.trace(APIUtil.class, ""get"", ""Request finished: "" + json); if (returnType != null) { if (cb != null) cb.accept(JsonFileManager.fromJSONString(json, returnType)); } else { if (cb != null) cb.accept(null); } } catch (Throwable e) { if (e instanceof ConnectException || e instanceof SocketTimeoutException) { Logger.error(APIUtil.class, ""get"", ""Async GET Connection timed out to "" + url); cb.accept(null); return; } if (e instanceof UnknownHostException || e instanceof NoRouteToHostException) { Logger.error(APIUtil.class, ""get"", ""Async GET Connection timed out (Unknown host) to "" + url); cb.accept(null); return; } Logger.handle(APIUtil.class, ""get"", ""Error parsing body..."", e); if (cb != null) cb.accept(null); } } public void onFailure(Call call, IOException e) { Logger.handle(APIUtil.class, ""get"", ""Get request failed... "" + url, e); if (cb != null) cb.accept(null); } }); } catch(Throwable e) { Logger.handle(APIUtil.class, ""get"", ""Error sending async get request."", e); } } public static T getSync(Class returnType, String url, String apiKey) { Logger.trace(APIUtil.class, ""getSync"", ""Sending request: "" + url); try { Builder builder = new Request.Builder() .url(url) .get() .header(""accept"", ""application/json""); if (apiKey != null) builder.header(""key"", apiKey); Request request = builder.build(); Call call = client.newCall(request); try { Response response = call.execute(); String json = response.body().string(); Logger.trace(APIUtil.class, ""getSync"", ""Request finished: "" + json); try { if (returnType != null) return JsonFileManager.fromJSONString(json, returnType); return null; } catch(Throwable e) { Logger.handle(APIUtil.class, ""getSync"", ""Error parsing body into "" + returnType, e); return null; } } catch(Throwable e) { if (e instanceof ConnectException || e instanceof SocketTimeoutException) { Logger.error(APIUtil.class, ""getSync"", ""GET Connection timed out to "" + url); return null; } if (e instanceof UnknownHostException || e instanceof NoRouteToHostException) { Logger.error(APIUtil.class, ""getSync"", ""GET Connection timed out (Unknown host) to "" + url); return null; } Logger.handle(APIUtil.class, ""getSync"", ""Request failed... "" + url, e); return null; } } catch(Throwable e) { Logger.handle(APIUtil.class, ""getSync"", ""Error sending get request."", e); return null; } } public static Optional pathParam(HttpServerExchange exchange, String name) { return Optional.ofNullable(exchange.getQueryParameters().get(name)).map(Deque::getFirst); } public static Optional pathParamAsLong(HttpServerExchange exchange, String name) { return pathParam(exchange, name).map(Long::parseLong); } public static Optional pathParamAsInteger(HttpServerExchange exchange, String name) { return pathParam(exchange, name).map(Integer::parseInt); } } " " package com.rs.lib.web; public class ErrorResponse { private String error; public ErrorResponse(String error) { this.error = error; } public String getError() { return error; } } " " package com.rs.lib.web; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UncheckedIOException; import java.net.http.HttpResponse; import java.util.function.Supplier; import com.rs.lib.file.JsonFileManager; public class JSONBodyHandler implements HttpResponse.BodyHandler> { private final Class targetClass; public JSONBodyHandler(Class targetClass) { this.targetClass = targetClass; } @Override public HttpResponse.BodySubscriber> apply(HttpResponse.ResponseInfo responseInfo) { return asJSON(this.targetClass); } public static HttpResponse.BodySubscriber> asJSON(Class targetType) { HttpResponse.BodySubscriber upstream = HttpResponse.BodySubscribers.ofInputStream(); return HttpResponse.BodySubscribers.mapping(upstream, inputStream -> toSupplierOfType(inputStream, targetType)); } public static Supplier toSupplierOfType(InputStream inputStream, Class targetType) { return () -> { try (InputStream stream = inputStream) { return JsonFileManager.getGson().fromJson(new InputStreamReader(stream, ""UTF-8""), targetType); } catch (IOException e) { throw new UncheckedIOException(e); } }; } } " " package com.rs.lib.web; import io.undertow.server.RoutingHandler; public interface Route { public abstract void build(RoutingHandler route); } " " package com.rs.lib.web; import com.rs.lib.util.Logger; import io.undertow.Handlers; import io.undertow.server.HttpServerExchange; import io.undertow.server.RoutingHandler; import io.undertow.server.handlers.ExceptionHandler; public class WebAPI extends Thread { public enum HTTP { GET, POST, PUT, DELETE } private String prefixPath; private int port; protected RoutingHandler routes = Handlers.routing(); private APIServer server; public WebAPI(String prefixPath, int port) { this.prefixPath = prefixPath; this.port = port; this.setName(""WebAPI Thread""); this.setUncaughtExceptionHandler(new UncaughtExceptionHandler() { public void uncaughtException(Thread th, Throwable ex) { Logger.handle(WebAPI.class, th.getName(), ex); } }); } public void start() { this.run(); } public void addRoute(Route route) { route.build(routes); } @Override public void run() { Logger.info(WebAPI.class, ""run"", ""Starting "" + getClass().getSimpleName() + "" on 0.0.0.0:"" + port); server = new APIServer(prefixPath, port, new ExceptionHandler(routes) { @Override public void handleRequest(HttpServerExchange exchange) throws Exception { java.util.logging.Logger.getLogger(""Web"").finest(""API Request: "" + exchange.getRequestURL()); super.handleRequest(exchange); } }); server.start(); Logger.info(WebAPI.class, ""run"", getClass().getSimpleName() + "" listening on 0.0.0.0:"" + port); } } " " package com.rs.lib.web.dto; public record CreateAccount(String username, String password, String email) { } " " package com.rs.lib.web.dto; import com.rs.lib.game.Rights; import com.rs.lib.model.Account; import com.rs.lib.model.Social; public class ExposedAccount { private String username; private String displayName; private Rights rights; private Social social; public ExposedAccount(Account account) { this.username = account.getUsername(); this.displayName = account.getDisplayName(); this.rights = account.getRights(); this.social = account.getSocial(); } public String getDisplayName() { return displayName; } public String getUsername() { return username; } public Rights getRights() { return rights; } public Social getSocial() { return social; } } " " package com.rs.lib.web.dto; import java.util.Set; import com.rs.lib.game.Rights; import com.rs.lib.model.Account; import com.rs.lib.model.FriendsChat; import com.rs.lib.model.FriendsChat.Rank; public class FCData { private String ownerUsername; private String ownerDisplayName; private FriendsChat settings; private Set usernames; public FCData(String ownerUsername, String ownerDisplayName, FriendsChat settings, Set usernames) { this.ownerUsername = ownerUsername; this.ownerDisplayName = ownerDisplayName; this.settings = settings; this.usernames = usernames; } public Rank getRank(Account account) { return getRank(account.getRights(), account.getUsername()); } private Rank getRank(Rights rights, String username) { if (rights.ordinal() >= Rights.ADMIN.ordinal()) return Rank.JMOD; if (username.equals(ownerUsername)) return Rank.OWNER; return settings.getRank(username); } public Set getUsernames() { return usernames; } public FriendsChat getSettings() { return settings; } public String getOwnerDisplayName() { return ownerDisplayName; } } " " package com.rs.lib.web.dto; public record LoginRequest(String username, String password) { } " " package com.rs.lib.web.dto; import com.rs.lib.net.packets.Packet; public record PacketDto(String username, Packet... packets) { } " " package com.rs.lib.web.dto; import com.rs.lib.net.packets.PacketEncoder; public record PacketEncoderDto(String username, PacketEncoder... encoders) { } " "package com.rs.lib.web.dto; import com.rs.lib.model.clan.Clan; public record UpdateClanGuest(String username, Clan clan) { } " " package com.rs.lib.web.dto; import com.rs.lib.model.FriendsChat; public record UpdateFC(String ownerDisplayName, FriendsChat chat) { } " " package com.rs.lib.web.dto; import com.rs.lib.game.WorldInfo; import com.rs.lib.model.Account; public record WorldPlayerAction(Account account, WorldInfo world) { } "