Skip to content

Instantly share code, notes, and snippets.

@jedjoud10
Created March 25, 2024 00:03
Show Gist options
  • Save jedjoud10/ae20c889cd5a9efa36ded79343661785 to your computer and use it in GitHub Desktop.
Save jedjoud10/ae20c889cd5a9efa36ded79343661785 to your computer and use it in GitHub Desktop.
RLE (De)Compression in Unity Jobs System
using Unity.Burst;
using Unity.Collections;
using Unity.Jobs;
[BurstCompile(CompileSynchronously = true)]
internal struct RleCompressionJob : IJob {
[ReadOnly]
public NativeArray<byte> bytesIn;
[WriteOnly]
public NativeList<uint> uintsOut;
// 1 BYTES FOR DATA, 3 BYTES FOR COUNT
// MAX COUNT: 16 MIL
public void Execute() {
byte lastByte = bytesIn[0];
int byteCount = 0;
for (int i = 0; i < bytesIn.Length; i++) {
byte cur = bytesIn[i];
if (cur == lastByte) {
byteCount++;
} else {
uintsOut.Add((uint)byteCount << 8 | (uint)lastByte);
lastByte = cur;
byteCount = 1;
}
}
}
}
using Unity.Burst;
using Unity.Collections;
using Unity.Jobs;
[BurstCompile(CompileSynchronously = true)]
internal struct RleDecompressionJob : IJob {
public byte defaultValue;
[WriteOnly]
public NativeArray<byte> bytesOut;
[ReadOnly]
public NativeArray<uint> uintsIn;
// 1 BYTES FOR DATA, 3 BYTES FOR COUNT
// MAX COUNT: 16 MIL
public void Execute() {
int byteOffset = 0;
for (int j = 0; j < uintsIn.Length; j++) {
uint compressed = uintsIn[j];
int count = (int)(compressed & ~0xFF) >> 8;
byte value = (byte)(compressed & 0xFF);
for (int k = 0; k < count; k++) {
bytesOut[k + byteOffset] = value;
}
byteOffset += count;
}
for (int i = byteOffset; i < bytesOut.Length; i++) {
bytesOut[i] = defaultValue;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment