skadistats.clarity.decoder.Util Java Examples

The following examples show how to use skadistats.clarity.decoder.Util. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: clarity   Author: skadistats   File: NormalBitStream64.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void readBitsIntoByteArray(byte[] dest, int n) {
    int nBytes = (n + 7) / 8;
    if ((pos & 7) == 0) {
        Util.byteCopy(data, pos >> 3, dest, 0, nBytes);
        pos += n;
        return;
    }
    int i = 0;
    while (n > 7) {
        dest[i++] = (byte) readUBitInt(8);
        n -= 8;
    }
    if (n != 0) {
        dest[i] = (byte) readUBitInt(n);
    }
}
 
Example #2
Source Project: clarity   Author: skadistats   File: BitStream.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public String readString(int n) {
    int o = 0;
    while (o < n) {
        byte c = (byte) readUBitInt(8);
        if (c == 0) {
            break;
        }
        stringTemp[o] = c;
        o++;
    }
    try {
        return new String(stringTemp, 0, o, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        Util.uncheckedThrow(e);
        return null;
    }
}
 
Example #3
Source Project: clarity   Author: skadistats   File: NormalBitStream32.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void readBitsIntoByteArray(byte[] dest, int n) {
    int nBytes = (n + 7) / 8;
    if ((pos & 7) == 0) {
        Util.byteCopy(data, pos >> 3, dest, 0, nBytes);
        pos += n;
        return;
    }
    int i = 0;
    while (n > 7) {
        dest[i++] = (byte) readUBitInt(8);
        n -= 8;
    }
    if (n != 0) {
        dest[i] = (byte) readUBitInt(n);
    }
}
 
Example #4
Source Project: parser   Author: odota   File: Parse.java    License: MIT License 5 votes vote down vote up
/**
 * Uses "EntityNames" string table and Entities processor
 * @param ctx Context
 * @param eHero Hero entity
 * @param idx 0-5 - inventory, 6-8 - backpack, 9-16 - stash
 * @return {@code null} - empty slot. Throws @{@link UnknownItemFoundException} if item information can't be extracted
 */
private Item getHeroItem(Context ctx, Entity eHero, int idx) throws UnknownItemFoundException {
    StringTable stEntityNames = ctx.getProcessor(StringTables.class).forName("EntityNames");
    Entities entities = ctx.getProcessor(Entities.class);

    Integer hItem = eHero.getProperty("m_hItems." + Util.arrayIdxToString(idx));
    if (hItem == 0xFFFFFF) {
        return null;
    }
    Entity eItem = entities.getByHandle(hItem);
    if(eItem == null) {
        throw new UnknownItemFoundException(String.format("Can't find item by its handle (%d)", hItem));
    }
    String itemName = stEntityNames.getNameByIndex(eItem.getProperty("m_pEntity.m_nameStringableIndex"));
    if(itemName == null) {
        throw new UnknownItemFoundException("Can't get item name from EntityName string table");
    }

    Item item = new Item();
    item.id = itemName;
    int numCharges = eItem.getProperty("m_iCurrentCharges");
    if(numCharges != 0) {
        item.num_charges = numCharges;
    }
    int numSecondaryCharges = eItem.getProperty("m_iSecondaryCharges");
    if(numSecondaryCharges != 0) {
        item.num_secondary_charges = numSecondaryCharges;
    }

    return item;
}
 
Example #5
Source Project: parser   Author: odota   File: Parse.java    License: MIT License 5 votes vote down vote up
public <T> T getEntityProperty(Entity e, String property, Integer idx) {
	try {
     if (e == null) {
         return null;
     }
     if (idx != null) {
         property = property.replace("%i", Util.arrayIdxToString(idx));
     }
     FieldPath fp = e.getDtClass().getFieldPathForName(property);
     return e.getPropertyForFieldPath(fp);
	}
	catch (Exception ex) {
		return null;
	}
}
 
Example #6
Source Project: clarity-analyzer   Author: spheenik   File: ReplayController.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void haltIfRunning() {
    setPlaying(false);
    if (getRunner() != null) {
        getRunner().halt();
        try {
            getRunner().getSource().close();
        } catch (IOException e) {
            Util.uncheckedThrow(e);
        }
    }
}
 
Example #7
Source Project: clarity-examples   Author: skadistats   File: Main.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public V resolveValue(int index, int team, int pos) {
    String fieldPathString = pattern
            .replaceAll("%i", Util.arrayIdxToString(index))
            .replaceAll("%t", Util.arrayIdxToString(team))
            .replaceAll("%p", Util.arrayIdxToString(pos));
    String compiledName = entityName.replaceAll("%n", getTeamName(team));
    Entity entity = getEntity(compiledName);
    FieldPath fieldPath = entity.getDtClass().getFieldPathForName(fieldPathString);
    return entity.getPropertyForFieldPath(fieldPath);
}
 
Example #8
Source Project: clarity-examples   Author: skadistats   File: Main.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void parse(ByteString raw) throws IOException {
    BitStream bs = BitStream.createBitStream(raw);
    boolean isCompressed = bs.readBitFlag();
    int size = bs.readUBitInt(24);

    byte[] data;
    if (isCompressed) {
        data = LZSS.unpack(bs);
    } else {
        data = new byte[size];
        bs.readBitsIntoByteArray(data, size * 8);
    }
    bs = BitStream.createBitStream(ZeroCopy.wrap(data));

    List<String> types = new ArrayList<>();
    List<String> dirs = new ArrayList<>();

    int nTypes = bs.readUBitInt(16);
    int nDirs = bs.readUBitInt(16);
    int nEntries = bs.readUBitInt(16);
    for (int i = 0; i < nTypes; i++) {
        types.add(bs.readString(Integer.MAX_VALUE));
    }
    for (int i = 0; i < nDirs; i++) {
        dirs.add(bs.readString(Integer.MAX_VALUE));
    }
    int bitsForType = Math.max(1, Util.calcBitsNeededFor(types.size() - 1));
    int bitsForDir = Math.max(1, Util.calcBitsNeededFor(dirs.size() - 1));
    System.out.format("\n\nbitsForType: %d, bitsForDir: %d, nEntries: %d\n", bitsForType, bitsForDir, nEntries);
    System.out.printf("dirs: %s\n", dirs);
    System.out.printf("types: %s\n", types);
    for (int i = 0; i < nEntries; i++) {
        int x = bs.readUBitInt(bitsForDir);
        String s = bs.readString(Integer.MAX_VALUE);
        int y = bs.readUBitInt(bitsForType);
        System.out.format("[%03d] %s%s.%s\n", i, dirs.get(x), s, types.get(y));
    }
    System.out.format("finished %d/%d\n\n", bs.pos(), bs.len());
}
 
Example #9
Source Project: clarity   Author: skadistats   File: S1DTClassEmitter.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@OnMessage(Demo.CDemoClassInfo.class)
public void onClassInfo(Demo.CDemoClassInfo message) {
    for (Demo.CDemoClassInfo.class_t ct : message.getClassesList()) {
        DTClass dt = dtClasses.forDtName(ct.getTableName());
        if (dt == null) {
            throw new ClarityException("DTClass for '%s' not found.", ct.getTableName());
        }
        dt.setClassId(ct.getClassId());
        dtClasses.byClassId.put(ct.getClassId(), dt);
    }
    dtClasses.classBits = Util.calcBitsNeededFor(dtClasses.byClassId.size() - 1);
}
 
Example #10
Source Project: clarity   Author: skadistats   File: S2DTClassEmitter.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@OnMessage(Demo.CDemoClassInfo.class)
public void onDemoClassInfo(Demo.CDemoClassInfo message) {
    for (Demo.CDemoClassInfo.class_t ct : message.getClassesList()) {
        DTClass dt = dtClasses.forDtName(ct.getNetworkName());
        dt.setClassId(ct.getClassId());
        dtClasses.byClassId.put(ct.getClassId(), dt);
    }
    dtClasses.classBits = Util.calcBitsNeededFor(dtClasses.byClassId.size() - 1);
    evClassesComplete.raise();
}
 
Example #11
Source Project: clarity   Author: skadistats   File: S2DTClassEmitter.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@OnMessage(NetMessages.CSVCMsg_ClassInfo.class)
public void onServerClassInfo(NetMessages.CSVCMsg_ClassInfo message) {
    for (NetMessages.CSVCMsg_ClassInfo.class_t ct : message.getClassesList()) {
        DTClass dt = dtClasses.forDtName(ct.getClassName());
        dt.setClassId(ct.getClassId());
        dtClasses.byClassId.put(ct.getClassId(), dt);
    }
    dtClasses.classBits = Util.calcBitsNeededFor(dtClasses.byClassId.size() - 1);
    evClassesComplete.raise();
}
 
Example #12
Source Project: clarity   Author: skadistats   File: ExecutionModel.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void instantiateMissingProcessors() {
    for (Map.Entry<Class<?>, Object> entry : processors.entrySet()) {
        if (entry.getValue() == null) {
            try {
                entry.setValue(entry.getKey().newInstance());
            } catch (Exception e) {
                Util.uncheckedThrow(e);
            }
        }
    }
}
 
Example #13
Source Project: clarity   Author: skadistats   File: ExecutionModel.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void bindInvocationPoints(skadistats.clarity.processor.runner.Context context) {
    for (UsagePoint up : usagePoints) {
        if (up instanceof InvocationPoint) {
            try {
                ((InvocationPoint) up).bind(context);
            } catch (IllegalAccessException e) {
                Util.uncheckedThrow(e);
            }
        }
    }
}
 
Example #14
Source Project: clarity   Author: skadistats   File: ExecutionModel.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void callInitializers() {
    for (UsagePoint up : usagePoints) {
        if (up instanceof InitializerMethod) {
            continue;
        }
        InitializerMethod im = initializers.get(up.getUsagePointClass());
        if (im != null) {
            try {
                im.invoke(up);
            } catch (Throwable e) {
                Util.uncheckedThrow(e);
            }
        }
    }
}
 
Example #15
Source Project: clarity   Author: skadistats   File: Event.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void raise(Object... args){
    for (Set<EventListener<A>> listeners : orderedListeners.values()) {
        for (EventListener<A> listener : listeners) {
            if (listener.isInvokedForArguments(args)) {
                try {
                    listener.invoke(args);
                } catch (Throwable throwable) {
                    Util.uncheckedThrow(throwable);
                }
            }
        }
    }
}
 
Example #16
Source Project: clarity   Author: skadistats   File: NormalBitStream64.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected NormalBitStream64(ByteString input) {
    len = input.size();
    data = new long[(len + 15)  >> 3];
    pos = 0;
    Util.byteCopy(ZeroCopy.extract(input), 0, data, 0, len);
    len = len * 8; // from now on size in bits
}
 
Example #17
Source Project: clarity   Author: skadistats   File: BitStream.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static BitStream createBitStream(ByteString input) {
    try {
        return bitStreamConstructor.newInstance(input);
    } catch (Exception e) {
        Util.uncheckedThrow(e);
        return null;
    }
}
 
Example #18
Source Project: clarity   Author: skadistats   File: NormalBitStream32.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected NormalBitStream32(ByteString input) {
    len = input.size();
    data = new int[(len + 7)  >> 2];
    pos = 0;
    Util.byteCopy(ZeroCopy.extract(input), 0, data, 0, len);
    len = len * 8; // from now on size in bits
}
 
Example #19
Source Project: clarity   Author: skadistats   File: BitStreamImplementations.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static Constructor<BitStream> determineConstructor() {
    if (implementation == null) {
        implementation = System.getProperty("os.arch").contains("64") ? 2 : 0;
        implementation += classForName("sun.misc.Unsafe") != null ? 1 : 0;
    }
    try {
        Class<?> implClass = classForName(bitStreamClasses[implementation]);
        return (Constructor<BitStream>) implClass.getDeclaredConstructor(ByteString.class);
    } catch (Exception e) {
        Util.uncheckedThrow(e);
        return null;
    }
}
 
Example #20
Source Project: clarity   Author: skadistats   File: CsGoEngineType.java    License: BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private String readHeaderString(Source source) throws IOException {
    return Util.readFixedZeroTerminated(source, 260);
}
 
Example #21
Source Project: clarity   Author: skadistats   File: PlayerInfoType.java    License: BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private String readZeroTerminated(ByteBuffer buffer, int size) throws IOException {
    return Util.readFixedZeroTerminated(buffer, size);
}
 
Example #22
Source Project: clarity   Author: skadistats   File: S1StringTableEmitter.java    License: BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void decodeEntries(StringTable table, ByteString encodedData, int numEntries) {
    BitStream stream = BitStream.createBitStream(encodedData);
    int bitsPerIndex = Util.calcBitsNeededFor(table.getMaxEntries() - 1);
    String[] keyHistory = new String[KEY_HISTORY_SIZE];

    boolean mysteryFlag = stream.readBitFlag();
    int index = -1;
    for (int i = 0; i < numEntries; i++) {
        // read index
        if (stream.readBitFlag()) {
            index++;
        } else {
            index = stream.readUBitInt(bitsPerIndex);
        }

        // read name
        String name = null;
        if (stream.readBitFlag()) {
            if (mysteryFlag && stream.readBitFlag()) {
                throw new ClarityException("mystery_flag assert failed!");
            }
            if (stream.readBitFlag()) {
                int base = i > KEY_HISTORY_SIZE ? i : 0;
                int offs = stream.readUBitInt(5);
                int len = stream.readUBitInt(5);
                String str = keyHistory[(base + offs) & KEY_HISTORY_MASK];
                name = str.substring(0, len) + stream.readString(MAX_NAME_LENGTH);
            } else {
                name = stream.readString(MAX_NAME_LENGTH);
            }
        }
        // read value
        ByteString data = null;
        if (stream.readBitFlag()) {
            int bitLength;
            if (table.getUserDataFixedSize()) {
                bitLength = table.getUserDataSizeBits();
            } else {
                bitLength = stream.readUBitInt(14) * 8;
            }
            byte[] valueBuf = new byte[(bitLength + 7) / 8];
            stream.readBitsIntoByteArray(valueBuf, bitLength);
            data = ZeroCopy.wrap(valueBuf);
        }

        int entryCount = table.getEntryCount();
        if (index < entryCount) {
            // update old entry
            table.setValueForIndex(index, data);
            assert(name == null || Objects.equals(name, table.getNameByIndex(index)));
            name = table.getNameByIndex(index);
        } else if (index == entryCount) {
            // add a new entry
            assert(name != null);
            table.addEntry(name, data);
        } else {
            throw new IllegalStateException("index > entryCount");
        }

        keyHistory[i & KEY_HISTORY_MASK] = name;

        raise(table, index, name, data);
    }
}
 
Example #23
Source Project: clarity   Author: skadistats   File: Resources.java    License: BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
protected void addManifestData(Manifest manifest, ByteString raw) throws IOException {

        BitStream bs = BitStream.createBitStream(raw);
        boolean isCompressed = bs.readBitFlag();
        int size = bs.readUBitInt(24);

        byte[] data;
        if (isCompressed) {
            data = LZSS.unpack(bs);
        } else {
            data = new byte[size];
            bs.readBitsIntoByteArray(data, size * 8);
        }
        bs = BitStream.createBitStream(ZeroCopy.wrap(data));

        List<Long> extHashes = new ArrayList<>();
        List<Long> dirHashes = new ArrayList<>();

        int nTypes = bs.readUBitInt(16);
        int nDirs = bs.readUBitInt(16);
        int nEntries = bs.readUBitInt(16);

        for (int i = 0; i < nTypes; i++) {
            extHashes.add(storeHash(exts, bs.readString(Integer.MAX_VALUE)));
        }
        for (int i = 0; i < nDirs; i++) {
            dirHashes.add(storeHash(dirs, bs.readString(Integer.MAX_VALUE)));
        }
        int bitsForType = Math.max(1, Util.calcBitsNeededFor(nTypes - 1));
        int bitsForDir = Math.max(1, Util.calcBitsNeededFor(nDirs - 1));

        for (int i = 0; i < nEntries; i++) {

            int dirIdx = bs.readUBitInt(bitsForDir);
            String file = bs.readString(Integer.MAX_VALUE);
            int extIdx = bs.readUBitInt(bitsForType);
            Entry entry = new Entry(dirHashes.get(dirIdx), file, extHashes.get(extIdx));

            manifest.entries.add(entry);

            addEntryToResourceHandles(entry);

            //System.out.format("%20d %s\n", hash, entryStr);
        }
    }
 
Example #24
Source Project: clarity   Author: skadistats   File: FloatQuantizedUnpacker.java    License: BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void initialize() {
    float offset;
    int quanta = (1 << bitCount);

    if ((flags & (QFE_ROUNDDOWN | QFE_ROUNDUP)) == (QFE_ROUNDDOWN | QFE_ROUNDUP)) {
        log.warn("Field %s was flagged to both round up and down, these flags are mutually exclusive [%f->%f]\n", fieldName, minValue, maxValue);
    }

    if ((flags & QFE_ROUNDDOWN) != 0) {
        offset = ((maxValue - minValue) / quanta);
        maxValue -= offset;
    } else if ((flags & QFE_ROUNDUP) != 0) {
        offset = ((maxValue - minValue) / quanta);
        minValue += offset;
    }

    if ((flags & QFE_ENCODE_INTEGERS_EXACTLY) != 0) {
        int delta = ((int) minValue) - ((int) maxValue);
        int trueRange = (1 << Util.calcBitsNeededFor(Math.max(delta, 1)));

        int nBits = this.bitCount;
        while ((1 << nBits) < trueRange) {
            ++nBits;
        }
        if (nBits > bitCount) {
            log.warn("Field %s was flagged QFE_ENCODE_INTEGERS_EXACTLY, but didn't specify enough bits, upping bitcount from %d to %d for range [%f->%f]", fieldName, bitCount, nBits, minValue, maxValue);
            bitCount = nBits;
            quanta = (1 << bitCount);
        }

        float floatRange = (float) trueRange;
        offset = (floatRange / (float) quanta);
        maxValue = minValue + floatRange - offset;
    }

    highLowMultiplier = assignRangeMultiplier(bitCount, maxValue - minValue);
    decodeMultiplier = 1.0f / (quanta - 1);
    if (highLowMultiplier == 0.0f) {
        throw new ClarityException("Assert failed: highLowMultiplier is zero!");
    }

    if ((encodeFlags & QFE_ROUNDDOWN) != 0) {
        if (quantize(minValue) == minValue) {
            encodeFlags &= ~QFE_ROUNDDOWN;
        }
    }
    if ((encodeFlags & QFE_ROUNDUP) != 0) {
        if (quantize(maxValue) == maxValue) {
            encodeFlags &= ~QFE_ROUNDUP;
        }
    }
    if ((encodeFlags & QFE_ENCODE_ZERO_EXACTLY) != 0) {
        if (quantize(0.0f) == 0.0f) {
            encodeFlags &= ~QFE_ENCODE_ZERO_EXACTLY;
        }
    }
}
 
Example #25
Source Project: clarity   Author: skadistats   File: ArrayUnpackerFactory.java    License: BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static Unpacker<?> createUnpackerStatic(SendProp prop) {
    return new ArrayUnpacker(
        S1UnpackerFactory.createUnpacker(prop.getTemplate()),
        Util.calcBitsNeededFor(prop.getNumElements())
    );
}