Skip to content

Instantly share code, notes, and snippets.

@nurpax
Created October 2, 2018 20:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nurpax/328b20364d7092a880948860fc5767d7 to your computer and use it in GitHub Desktop.
Save nurpax/328b20364d7092a880948860fc5767d7 to your computer and use it in GitHub Desktop.
const CW = 6;
const CH = 7;
function readSprites({readFileSync, resolveRelative}, filename) {
const buf = readFileSync(resolveRelative(filename.lit));
const numSprites = buf.readUInt8(4);
const data = [];
for (let i = 0; i < numSprites; i++) {
const offs = i*64+9;
const bytes = [];
for (let j = 0; j < 64; j++) {
bytes.push(buf.readUInt8(offs + j));
}
data.push(bytes);
}
return {
numSprites,
enableMask: (1<<numSprites)-1,
bg: buf.readUInt8(6),
multicol1: buf.readUInt8(7),
multicol2: buf.readUInt8(8),
data
};
}
function swap(a) {
const b = ((a & 0b11110000) >> 4) | ((a & 0b00001111) << 4);
return ((b & 0b11001100) >> 2) | ((b & 0b00110011) << 2);
}
function readPix(data, x, y) {
const row = swap(data[y*3]) | (swap(data[y*3+1])<<8) | (swap(data[y*3+2])<<16);
let bitoffs = x * 2;
return (row >> bitoffs) & 3;
}
function appendChar(out, data, cx, cy) {
for (let y = 0; y < CH; y++) {
let row = 0;
for (let x = 0; x < CW; x++) {
row |= readPix(data, cx + x, cy + y) << (x * 2);
}
out.push(swap(row) & 255);
out.push(swap(row>>8) & 255);
}
}
// Blit into sprite layout, just to test it produces the right kind of sprites.
function makeTestData(font) {
const dst = Array(3*21).fill(0);
for (let y = 0; y < 3; y++) {
const ydst = 3*7*y;
for (let yy = 0; yy < 7; yy++) {
dst[ydst + yy*3 + 0] = font[(y*7+yy)*2 + 0]
dst[ydst + yy*3 + 1] = font[(y*7+yy)*2 + 1]
}
}
return dst;
}
// unpack sprites from the following format
//
// 000000111111 <-- sprite 0 rows 0-6
// 000000111111
// 000000111111
// 000000111111
// 000000111111
// 000000111111
// XXXXXXXXXXXX
// 222222333333 <-- sprite 0 rows 7-13
// 222222333333
// 222222333333
// 222222333333
// 222222333333
// 222222333333
// XXXXXXXXXXXX
// -"- for 3rd sprite 0 chars
//
// ..to a an array of [[0,0], [1,1], [2,2]] (flattened)
// where 0,1,2 refer to letter indices.
module.exports = (ctx, filename) => {
const {
numSprites,
bg,
multicol1,
multicol2,
data
} = readSprites(ctx, filename);
const fontData = []
for (let si = 0; si < numSprites; si++) {
// Loop over chars
for (let cy = 0; cy < 3; cy++) {
for (let cx = 0; cx < 2; cx++) {
// Blit one char to output
appendChar(fontData, data[si], cx*CW, cy*CH);
}
}
}
return {
numChars: numSprites*6,
fontData,
testData: makeTestData(fontData)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment