text
stringlengths 67
71k
|
|---|
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<Integer, MapSpriteDefinitions> defs = new ConcurrentHashMap<Integer, MapSpriteDefinitions>();
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<Integer, AreaDefinitions> defs = new ConcurrentHashMap<Integer, AreaDefinitions>();
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<Integer, Object> clientScriptMap = new HashMap<Integer, Object>();
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<Integer, BASDefinitions> RENDER_ANIM_CACHE = new ConcurrentHashMap<Integer, BASDefinitions>();
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<Integer, ClanVarDefinitions> 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<Integer> 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<Integer, ClanVarSettingsDefinitions> 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<Integer> 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<Integer, CursorDefinitions> 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<Integer, DefinitionsTemplate> 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<Long, Object> values;
private static final ConcurrentHashMap<Integer, EnumDefinitions> ENUMS_CACHE = new ConcurrentHashMap<Integer, EnumDefinitions>();
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<Long, Object> 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<Long, Object>(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<Integer, FontMetrics> 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<Integer, HitbarDefinitions> 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<Integer, HitsplatDefinitions> 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<Integer, IdentiKitDefinitions> 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<Integer, InventoryDefinitions> maps = new ConcurrentHashMap<Integer, InventoryDefinitions>();
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<Integer, ItemDefinitions> ITEM_DEFINITIONS = new HashMap<>();
private static final HashMap<Integer, Integer> EQUIP_IDS = new HashMap<Integer, Integer>();
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<Integer, Object> params;
private HashMap<Integer, Integer> 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<Integer, Object> getClientScriptData() {
return params;
}
public HashMap<Integer, Integer> getWearingSkillRequiriments() {
if (params == null)
return null;
if (wieldRequirements == null) {
HashMap<Integer, Integer> skills = new HashMap<Integer, Integer>();
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<Integer, Object>(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<Integer, Tab> 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<Integer, Reward> ITEMID_MAP = new HashMap<Integer, Reward>();
private static HashMap<Integer, Reward> PREREQ_MAP = new HashMap<Integer, Reward>();
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<Integer, NPCDefinitions> MAP = new ConcurrentHashMap<Integer, NPCDefinitions>();
public int id;
public HashMap<Integer, Object> 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<Integer> getCompatibleAnimations() {
HashSet<Integer> animsWithSkeleton = new HashSet<Integer>();
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<Integer> 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<Integer, Object>(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<Integer, ObjectDefinitions> objectDefinitions = new ConcurrentHashMap<Integer, ObjectDefinitions>();
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<Integer, Object> 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<Integer, Object>(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<Integer, ObjectType> 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<Integer, OverlayDefinitions> defs = new ConcurrentHashMap<Integer, OverlayDefinitions>();
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<Integer, ParticleProducerDefinitions> PARTICLE_DEFS = new ConcurrentHashMap<Integer, ParticleProducerDefinitions>();
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<Integer, QCCategoryDefinitions> 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<Integer, QCMesDefinitions> 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<Integer, QCValueType> 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<Integer, SkyboxDefinitions> 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<Integer, SpotAnimDefinitions> SPOT_ANIM_DEFS = new ConcurrentHashMap<Integer, SpotAnimDefinitions>();
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<BufferedImage> 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<BufferedImage>();
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<BufferedImage>();
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<BufferedImage> 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<Integer> colours;
public boolean done() {
if (colours == null) {
colours = new ArrayList<Integer>();
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<Long, Object> values;
private static final ConcurrentHashMap<Integer, StructDefinitions> maps = new ConcurrentHashMap<Integer, StructDefinitions>();
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<Long, Object> 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<Long, Object>(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<Integer, SunDefinitions> 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<Integer, TextureDefinitions> 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<Integer, UnderlayDefinitions> defs = new ConcurrentHashMap<Integer, UnderlayDefinitions>();
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<Integer, VarBitDefinitions> varpbitDefs = new ConcurrentHashMap<Integer, VarBitDefinitions>();
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<Integer, VarcDefinitions> 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<Integer, VarDefinitions> VAR_DEFS = new ConcurrentHashMap<Integer, VarDefinitions>();
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<Integer, Object> clientScriptMap = new HashMap<Integer, Object>();
private static final ConcurrentHashMap<Integer, AnimationDefinitions> animDefs = new ConcurrentHashMap<Integer, AnimationDefinitions>();
private static final HashMap<Integer, Integer> itemAnims = new HashMap<Integer, Integer>();
public static void main(String[] args) throws IOException {
Cache.init("../cache/");
int[] itemIds = { 1351, 1349, 1353, 1361, 1355, 1357, 1359, 6739, 13661 };
Map<Integer, Map<Integer, Integer>> 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<Integer, Integer> 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<Integer> getUsedSynthSoundIds() {
Set<Integer> 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<Integer, AnimationFrameBase> FRAME_BASES = new ConcurrentHashMap<Integer, AnimationFrameBase>();
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<Integer, AnimationFrameSet> FRAME_COLLECTIONS = new ConcurrentHashMap<Integer, AnimationFrameSet>();
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<Integer, CS2Script> scripts = new HashMap<Integer, CS2Script>();
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<CS2Instruction> 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<Integer, CS2Instruction> 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<Integer, CS2ParamDefs> maps = new ConcurrentHashMap<Integer, CS2ParamDefs>();
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<Integer, Integer>[] 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<Integer, Integer>(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<Integer, Integer> 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<Integer, Integer> map1 = this.switchMaps[i];
HashMap<Integer, Integer> 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<Integer, CS2Type> 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<CS2Type> cache = new ArrayList<CS2Type>();
//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<CS2Type> composite = new ArrayList<>();
private CS2Type(List<CS2Type> 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<CS2Type> 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<CS2Type> 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<Integer, CutsceneDefinitions> CACHE = new HashMap<>();
public int id;
public int anInt825;
public int anInt824;
public List<CutsceneArea> areas = new ArrayList<>();
public List<CutsceneCameraMovement> camMovements = new ArrayList<>();
public List<CutsceneEntity> entities = new ArrayList<>();
public List<CutsceneObject> objects = new ArrayList<>();
public List<CutsceneEntityMovement> 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<IComponentDefinitions> 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<Integer> 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<Integer, IComponentDefinitions> 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<Integer, WorldMapDefinitions> 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<WorldMapRect> 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 <code>true</code> 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 <code>true</code> 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
* <code>image</code>.
*/
public static int countDistictColors(BufferedImage image) {
return getDistictColors(image).length;
}
/**
* Returns the <code>image</code>'s distinct colors in an RGB format, discarding
* transparency information.
*/
public static int[] getDistictColors(BufferedImage image) {
return getDistictColors(image, 0);
}
/**
* Returns the <code>image</code>'s distinct colors in an RGB format, discarding
* transparency information. Adds <code>padding</code> 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<Integer> 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 <code>image</code>'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 <code>source</code> image using
* <code>matteColor</code>. Matting is rendering partial transparencies using
* solid color as if the original image was put on top of a bitmap filled with
* <code>matteColor</code>.
*/
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 <code>image</code> on the <code>canvas</code> placing the top left
* corner of <code>image</code> at <code>x</code> / <code>y</code> offset from
* the top left corner of <code>canvas</code>.
*/
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
* <a href="http://www.imagemagick.org/">ImageMagick</a>. 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.
* <p>
*
* Here is the copyright notice from ImageMagick:
*
* <pre>
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 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. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
* </pre>
*
*
* @version 0.90 19 Sep 2000
* @author <a href="http://www.gurge.com/amd/">Adam Doppelt</a>
*/
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<RSModel> 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<Integer, Integer> PARTICLE_CONVERTS = new HashMap<>();
private static Map<Integer, Integer> 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<Integer, Integer> 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<Integer> 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.
*
* <P>
* <b>References</b>
*
* <P>
* The Whirlpool algorithm was developed by
* <a href="mailto:pbarreto@scopus.com.br">Paulo S. L. M. Barreto</a> and
* <a href="mailto:vincent.rijmen@cryptomathic.com">Vincent Rijmen</a>.
*
* See
* P.S.L.M. Barreto, V. Rijmen,
* ``The Whirlpool hashing function,''
* First NESSIE workshop, 2000 (tweaked version, 2003),
* <https://www.cosic.esat.kuleuven.ac.be/nessie/workshop/submissions/whirlpool.zip>
*
* @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
* <keiron@aftexsw.com> 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.
* <p>
* This interface is public for historical purposes.
* You should have no need to use it.
* </p>
*/
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
* <keiron@aftexsw.com> 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.
*
* <p>The decompression requires large amounts of memory. Thus you
* should call the {@link #close() close()} method as soon as
* possible, to force <tt>CBZip2InputStream</tt> to release the
* allocated memory. See {@link CBZip2OutputStream
* CBZip2OutputStream} for information about memory usage.</p>
*
* <p><tt>CBZip2InputStream</tt> 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.</p>
*
* <p>Instances of this class are not threadsafe.</p>
*/
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.
*
* <p>Although BZip2 headers are marked with the magic
* <tt>"Bz"</tt> 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. </p>
*
* @throws IOException
* if the stream content is malformed or an I/O error occurs.
* @throws NullPointerException
* if <tt>in == null</tt>
*/
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
* <keiron@aftexsw.com> 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.
*
* <p>
* The compression requires large amounts of memory. Thus you should call the
* {@link #close() close()} method as soon as possible, to force
* <tt>CBZip2OutputStream</tt> to release the allocated memory.
* </p>
*
* <p> 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. </p>
*
* <p> You can compute the memory usage for compressing by the
* following formula: </p>
*
* <pre>
* <code>400k + (9 * blocksize)</code>.
* </pre>
*
* <p> To get the memory required for decompression by {@link
* CBZip2InputStream CBZip2InputStream} use </p>
*
* <pre>
* <code>65k + (5 * blocksize)</code>.
* </pre>
*
* <table width="100%" border="1">
* <colgroup> <col width="33%" /> <col width="33%" /> <col width="33%" />
* </colgroup>
* <tr>
* <th colspan="3">Memory usage by blocksize</th>
* </tr>
* <tr>
* <th align="right">Blocksize</th> <th align="right">Compression<br>
* memory usage</th> <th align="right">Decompression<br>
* memory usage</th>
* </tr>
* <tr>
* <td align="right">100k</td>
* <td align="right">1300k</td>
* <td align="right">565k</td>
* </tr>
* <tr>
* <td align="right">200k</td>
* <td align="right">2200k</td>
* <td align="right">1065k</td>
* </tr>
* <tr>
* <td align="right">300k</td>
* <td align="right">3100k</td>
* <td align="right">1565k</td>
* </tr>
* <tr>
* <td align="right">400k</td>
* <td align="right">4000k</td>
* <td align="right">2065k</td>
* </tr>
* <tr>
* <td align="right">500k</td>
* <td align="right">4900k</td>
* <td align="right">2565k</td>
* </tr>
* <tr>
* <td align="right">600k</td>
* <td align="right">5800k</td>
* <td align="right">3065k</td>
* </tr>
* <tr>
* <td align="right">700k</td>
* <td align="right">6700k</td>
* <td align="right">3565k</td>
* </tr>
* <tr>
* <td align="right">800k</td>
* <td align="right">7600k</td>
* <td align="right">4065k</td>
* </tr>
* <tr>
* <td align="right">900k</td>
* <td align="right">8500k</td>
* <td align="right">4565k</td>
* </tr>
* </table>
*
* <p>
* For decompression <tt>CBZip2InputStream</tt> allocates less memory if the
* bzipped input is smaller than one block.
* </p>
*
* <p>
* Instances of this class are not threadsafe.
* </p>
*
* <p>
* TODO: Update to BZip2 1.0.1
* </p>
*
* <p>
* <strong>This class has been modified so it does not use randomized blocks as
* these are not supported by the client's bzip2 implementation.</strong>
* </p>
*
*/
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 <tt> == 1</tt>.
*/
public static final int MIN_BLOCKSIZE = 1;
/**
* The maximum supported blocksize <tt> == 9</tt>.
*/
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.
* <p> 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. </p>
*/
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
* <tt>inputLength</tt> this method returns <tt>MAX_BLOCKSIZE</tt>
* always.
*
* @param inputLength
* The length of the data which will be compressed by
* <tt>CBZip2OutputStream</tt>.
*/
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 <tt>CBZip2OutputStream</tt> with a blocksize of 900k.
*
* <p>
* <b>Attention: </b>The caller is resonsible to write the two BZip2 magic
* bytes <tt>"BZ"</tt> to the specified stream prior to calling this
* constructor.
* </p>
*
* @param out *
* the destination stream.
*
* @throws IOException
* if an I/O error occurs in the specified stream.
* @throws NullPointerException
* if <code>out == null</code>.
*/
public CBZip2OutputStream(final OutputStream out) throws IOException {
this(out, MAX_BLOCKSIZE);
}
/**
* Constructs a new <tt>CBZip2OutputStream</tt> with specified blocksize.
*
* <p>
* <b>Attention: </b>The caller is resonsible to write the two BZip2 magic
* bytes <tt>"BZ"</tt> to the specified stream prior to calling this
* constructor.
* </p>
*
*
* @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 <code>(blockSize < 1) || (blockSize > 9)</code>.
* @throws NullPointerException
* if <code>out == null</code>.
*
* @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.
*
* <p>
* 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.
* </p>
*/
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
* <keiron@aftexsw.com> 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<DBItemManager> 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<Document> 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<Document> 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;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.