BlueGit

timfa questward

Files

questward / client / scripts / generate-stone-wall-sprites.mjs

generate-stone-wall-sprites.mjs

generate-stone-wall-sprites.mjs 15.9 KiB Download Raw
1/**
2 * Generate thin + thick stone-wall PNGs for blob neighbor-connect masks
3 * (cardinals + diagonal corners — 47 valid states).
4 *
5 * Flat greys only (no texture). Authoritative examples live beside the outputs:
6 * example-stone-{thin|thick}.png
7 * example-stone-{thin|thick}-connecting.png E
8 * example-stone-{thin|thick}-connecting-up.png N
9 * example-stone-thin-connecting-down.png S (thin)
10 * example-stone-{thin|thick}-connecting-updown.png N+S
11 * example-stone-{thin|thick}-connecting-L.png N+E (concave)
12 * example-stone-thin-connecting-Ldownright.png S+E (concave, thin)
13 * example-stone-{thin|thick}-connecting-2x2.png N+E+NE (filled)
14 * example-stone-thin-connecting-T.png E+S+W
15 * example-stone-thin-connecting-T-upsidedown.png N+E+W
16 * example-stone-thick-T.png E+S+W (thick)
17 *
18 * West variants are X-mirrors. Remaining masks compose from these stamps +
19 * the L↔2×2 corner-fill delta.
20 *
21 * node client/scripts/generate-stone-wall-sprites.mjs
22 */
23import { mkdirSync, writeFileSync, readdirSync, unlinkSync, readFileSync, existsSync } from "node:fs";
24import { deflateSync, inflateSync } from "node:zlib";
25import { fileURLToPath } from "node:url";
26import { dirname, join } from "node:path";
27import {
28 NeighborBit,
29 listValidNeighborConnectCornerMasks
30} from "../../shared/world/neighborConnect.js";
31
32const SIZE = 16;
33const ROOT = join(dirname(fileURLToPath(import.meta.url)), "../assets/blocks");
34const OUT_THICK = join(ROOT, "stone-wall");
35const OUT_THIN = join(ROOT, "stone-wall-thin");
36const EXAMPLES = join(ROOT, "stone-wall");
37
38function crcTable ()
39{
40 const table = new Uint32Array(256);
41 for (let n = 0; n < 256; n++)
42 {
43 let c = n;
44 for (let k = 0; k < 8; k++)
45 { c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1); }
46 table[n] = c >>> 0;
47 }
48 return table;
49}
50
51const CRC_TABLE = crcTable();
52
53function crc32 (buf)
54{
55 let c = 0xffffffff;
56 for (let i = 0; i < buf.length; i++)
57 { c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8); }
58 return (c ^ 0xffffffff) >>> 0;
59}
60
61function chunk (type, data)
62{
63 const len = Buffer.alloc(4);
64 len.writeUInt32BE(data.length);
65 const typeBuf = Buffer.from(type, "ascii");
66 const crcBuf = Buffer.alloc(4);
67 crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])));
68 return Buffer.concat([len, typeBuf, data, crcBuf]);
69}
70
71function encodePng (rgba)
72{
73 const raw = Buffer.alloc((SIZE * 4 + 1) * SIZE);
74 for (let y = 0; y < SIZE; y++)
75 {
76 const row = y * (SIZE * 4 + 1);
77 raw[row] = 0;
78 for (let x = 0; x < SIZE; x++)
79 {
80 const i = (y * SIZE + x) * 4;
81 const o = row + 1 + x * 4;
82 raw[o] = rgba[i];
83 raw[o + 1] = rgba[i + 1];
84 raw[o + 2] = rgba[i + 2];
85 raw[o + 3] = rgba[i + 3];
86 }
87 }
88 const ihdr = Buffer.alloc(13);
89 ihdr.writeUInt32BE(SIZE, 0);
90 ihdr.writeUInt32BE(SIZE, 4);
91 ihdr[8] = 8;
92 ihdr[9] = 6;
93 return Buffer.concat([
94 Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
95 chunk("IHDR", ihdr),
96 chunk("IDAT", deflateSync(raw, { level: 9 })),
97 chunk("IEND", Buffer.alloc(0))
98 ]);
99}
100
101function decodePngRgba (path)
102{
103 const buf = readFileSync(path);
104 let off = 8;
105 let w = 0;
106 let h = 0;
107 const idat = [];
108 while (off < buf.length)
109 {
110 const len = buf.readUInt32BE(off);
111 const type = buf.slice(off + 4, off + 8).toString("ascii");
112 const data = buf.slice(off + 8, off + 8 + len);
113 if (type === "IHDR")
114 {
115 w = data.readUInt32BE(0);
116 h = data.readUInt32BE(4);
117 if (data[8] !== 8 || data[9] !== 6)
118 { throw new Error(`${path}: expected 8-bit RGBA`); }
119 }
120 else if (type === "IDAT")
121 { idat.push(data); }
122 else if (type === "IEND")
123 { break; }
124 off += 12 + len;
125 }
126 const raw = inflateSync(Buffer.concat(idat));
127 const bpp = 4;
128 const stride = w * bpp;
129 const rgba = new Uint8ClampedArray(w * h * 4);
130 let src = 0;
131 const prev = Buffer.alloc(stride);
132 const cur = Buffer.alloc(stride);
133 for (let y = 0; y < h; y++)
134 {
135 const filter = raw[src++];
136 for (let i = 0; i < stride; i++)
137 { cur[i] = raw[src++]; }
138 for (let i = 0; i < stride; i++)
139 {
140 const left = i >= bpp ? cur[i - bpp] : 0;
141 const up = prev[i];
142 const upLeft = i >= bpp ? prev[i - bpp] : 0;
143 let val = cur[i];
144 if (filter === 1)
145 { val = (val + left) & 255; }
146 else if (filter === 2)
147 { val = (val + up) & 255; }
148 else if (filter === 3)
149 { val = (val + ((left + up) >> 1)) & 255; }
150 else if (filter === 4)
151 {
152 const p = left + up - upLeft;
153 const pa = Math.abs(p - left);
154 const pb = Math.abs(p - up);
155 const pc = Math.abs(p - upLeft);
156 const pr = (pa <= pb && pa <= pc) ? left : (pb <= pc ? up : upLeft);
157 val = (val + pr) & 255;
158 }
159 cur[i] = val;
160 }
161 rgba.set(cur, y * stride);
162 prev.set(cur);
163 }
164 if (w !== SIZE || h !== SIZE)
165 { throw new Error(`${path}: expected ${SIZE}×${SIZE}, got ${w}×${h}`); }
166 return rgba;
167}
168
169function loadExample (name)
170{
171 const path = join(EXAMPLES, name);
172 if (!existsSync(path))
173 { return null; }
174 return decodePngRgba(path);
175}
176
177function getPx (rgba, x, y)
178{
179 if (x < 0 || y < 0 || x >= SIZE || y >= SIZE)
180 { return [0, 0, 0, 0]; }
181 const i = (y * SIZE + x) * 4;
182 return [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]];
183}
184
185function setPx (rgba, x, y, color)
186{
187 if (x < 0 || y < 0 || x >= SIZE || y >= SIZE)
188 { return; }
189 const i = (y * SIZE + x) * 4;
190 rgba[i] = color[0];
191 rgba[i + 1] = color[1];
192 rgba[i + 2] = color[2];
193 rgba[i + 3] = color[3];
194}
195
196function opaque (rgba, x, y)
197{
198 return getPx(rgba, x, y)[3] > 128;
199}
200
201function copyRgba (rgba)
202{
203 return new Uint8ClampedArray(rgba);
204}
205
206function clearRgba ()
207{
208 return new Uint8ClampedArray(SIZE * SIZE * 4);
209}
210
211function mirrorX (rgba)
212{
213 const out = clearRgba();
214 for (let y = 0; y < SIZE; y++)
215 {
216 for (let x = 0; x < SIZE; x++)
217 { setPx(out, x, y, getPx(rgba, SIZE - 1 - x, y)); }
218 }
219 return out;
220}
221
222function blit (dst, src)
223{
224 if (!src)
225 { return; }
226 for (let y = 0; y < SIZE; y++)
227 {
228 for (let x = 0; x < SIZE; x++)
229 {
230 const c = getPx(src, x, y);
231 if (c[3] > 128)
232 { setPx(dst, x, y, c); }
233 }
234 }
235}
236
237/** Pixels where filled differs from concave (the diagonal corner fill). */
238function cornerDelta (concave, filled)
239{
240 const deltas = [];
241 for (let y = 0; y < SIZE; y++)
242 {
243 for (let x = 0; x < SIZE; x++)
244 {
245 const a = getPx(concave, x, y);
246 const b = getPx(filled, x, y);
247 if (b[3] > 128 && (a[3] <= 128 || a[0] !== b[0] || a[1] !== b[1] || a[2] !== b[2]))
248 { deltas.push({ x, y, color: b }); }
249 else if (a[3] > 128 && b[3] <= 128)
250 { deltas.push({ x, y, color: [0, 0, 0, 0] }); }
251 }
252 }
253 return deltas;
254}
255
256function applyDelta (dst, deltas, mapX, mapY)
257{
258 for (const d of deltas)
259 {
260 const x = mapX(d.x);
261 const y = mapY(d.y);
262 setPx(dst, x, y, d.color);
263 }
264}
265
266function idX (x)
267{ return x; }
268function idY (y)
269{ return y; }
270function flipX (x)
271{ return SIZE - 1 - x; }
272function flipY (y)
273{ return SIZE - 1 - y; }
274
275/**
276 * Build south-east L by compositing down+east and punching the SE corner using
277 * the NE L↔2×2 delta rotated 180° in corner space (flipX+flipY of NE delta
278 * relative to tile — actually SE is flipY of NE region for thin).
279 *
280 * Simpler: if we have an authored Ldownright, use it. Otherwise compose.
281 */
282function composeSEFromNE (ellNE, fillNE, east, south)
283{
284 const out = clearRgba();
285 blit(out, south);
286 blit(out, east);
287 // Remove NE-style fill if any leaked; then we want SE concave by default.
288 // Punch using mapped NE delta: NE fill region → clear for concave SE.
289 const delta = cornerDelta(ellNE, fillNE);
290 for (const d of delta)
291 {
292 // Map NE corner (top-right) → SE corner (bottom-right): keep x, flip y.
293 const x = d.x;
294 const y = flipY(d.y);
295 // Only clear / don't apply fill for the concave L.
296 if (d.color[3] > 128)
297 {
298 // Was a fill pixel in 2x2 — ensure concave leaves it empty (or outline).
299 const src = getPx(ellNE, d.x, d.y);
300 setPx(out, x, y, src[3] > 128 ? getPx(east, x, Math.min(12, y)) : [0, 0, 0, 0]);
301 if (src[3] <= 128)
302 { setPx(out, x, y, [0, 0, 0, 0]); }
303 }
304 }
305 return out;
306}
307
308function fillSEFromNE (ellSE, ellNE, fillNE)
309{
310 const out = copyRgba(ellSE);
311 const delta = cornerDelta(ellNE, fillNE);
312 for (const d of delta)
313 {
314 const x = d.x;
315 const y = flipY(d.y);
316 if (d.color[3] > 128)
317 {
318 // Prefer sampling from the SE L's nearby interior.
319 const sample = getPx(ellSE, Math.min(SIZE - 1, Math.max(0, x - 1)), Math.min(SIZE - 1, Math.max(0, y - 1)));
320 setPx(out, x, y, sample[3] > 128 ? sample : d.color);
321 }
322 }
323 return out;
324}
325
326function buildPack (kind)
327{
328 const alone = loadExample(`example-stone-${kind}.png`);
329 const east = loadExample(`example-stone-${kind}-connecting.png`);
330 const north = loadExample(`example-stone-${kind}-connecting-up.png`);
331 const southAuthored = loadExample(`example-stone-${kind}-connecting-down.png`);
332 const ns = loadExample(`example-stone-${kind}-connecting-updown.png`);
333 const ellNE = loadExample(`example-stone-${kind}-connecting-L.png`);
334 const fillNE = loadExample(`example-stone-${kind}-connecting-2x2.png`);
335 const ellSEAuthored = loadExample(`example-stone-${kind}-connecting-Ldownright.png`);
336 const teeESW = loadExample(`example-stone-${kind}-T.png`)
337 ?? loadExample(`example-stone-${kind}-connecting-T.png`);
338 const teeNEW = loadExample(`example-stone-${kind}-connecting-T-upsidedown.png`);
339
340 if (!alone || !east || !north || !ellNE || !fillNE || !ns)
341 { throw new Error(`Missing core ${kind} examples`); }
342
343 const west = mirrorX(east);
344 const southFinal = southAuthored ?? (() =>
345 {
346 // No authored south: alone top + updown shaft through the bottom.
347 const out = copyRgba(alone);
348 for (let y = 0; y < SIZE; y++)
349 {
350 for (let x = 0; x < SIZE; x++)
351 {
352 if (y < 2 && opaque(alone, x, y))
353 { continue; }
354 if (opaque(ns, x, y))
355 { setPx(out, x, y, getPx(ns, x, y)); }
356 }
357 }
358 // Ensure bottom rows are open shaft from updown.
359 for (let y = 10; y < SIZE; y++)
360 {
361 for (let x = 0; x < SIZE; x++)
362 {
363 if (opaque(ns, x, y))
364 { setPx(out, x, y, getPx(ns, x, y)); }
365 }
366 }
367 return out;
368 })();
369
370 const ellSEFinal = ellSEAuthored ?? composeSEFromNE(ellNE, fillNE, east, southFinal);
371 const fillSE = fillSEFromNE(ellSEFinal, ellNE, fillNE);
372
373 const ellNW = mirrorX(ellNE);
374 const fillNW = mirrorX(fillNE);
375 const ellSW = mirrorX(ellSEFinal);
376 const fillSW = mirrorX(fillSE);
377
378 const ew = (() =>
379 {
380 const out = clearRgba();
381 blit(out, east);
382 blit(out, west);
383 // Close the center seam: fill any gap on rows that both sides use.
384 for (let y = 0; y < SIZE; y++)
385 {
386 let fill = null;
387 for (let x = 0; x < SIZE; x++)
388 {
389 const c = getPx(east, x, y);
390 if (c[3] > 128)
391 { fill = c; }
392 }
393 if (!fill)
394 { continue; }
395 for (let x = 0; x < SIZE; x++)
396 {
397 if (!opaque(out, x, y) && (opaque(east, SIZE - 1, y) || opaque(west, 0, y)))
398 { setPx(out, x, y, fill); }
399 }
400 // Force full row when east template opens to the edge on this row.
401 if (opaque(east, SIZE - 1, y))
402 {
403 for (let x = 0; x < SIZE; x++)
404 {
405 if (!opaque(out, x, y))
406 { setPx(out, x, y, fill); }
407 }
408 }
409 }
410 return out;
411 })();
412
413 const teeESWFinal = teeESW ?? (() =>
414 {
415 const out = clearRgba();
416 blit(out, ew);
417 blit(out, southFinal);
418 return out;
419 })();
420 const teeNEWFinal = teeNEW ?? (() =>
421 {
422 const out = clearRgba();
423 blit(out, ew);
424 blit(out, north);
425 return out;
426 })();
427 const teeNES = (() =>
428 {
429 const out = clearRgba();
430 blit(out, north);
431 blit(out, east);
432 blit(out, southFinal);
433 return out;
434 })();
435 const teeNWS = mirrorX(teeNES);
436
437 /** Exact mask → rgba for authored / derived cardinal templates (no diagonals). */
438 const byMask = new Map();
439 byMask.set(0, alone);
440 byMask.set(NeighborBit.n, north);
441 byMask.set(NeighborBit.e, east);
442 byMask.set(NeighborBit.s, southFinal);
443 byMask.set(NeighborBit.w, west);
444 byMask.set(NeighborBit.n | NeighborBit.s, ns);
445 byMask.set(NeighborBit.e | NeighborBit.w, ew);
446 byMask.set(NeighborBit.n | NeighborBit.e, ellNE);
447 byMask.set(NeighborBit.n | NeighborBit.w, ellNW);
448 byMask.set(NeighborBit.s | NeighborBit.e, ellSEFinal);
449 byMask.set(NeighborBit.s | NeighborBit.w, ellSW);
450 byMask.set(NeighborBit.e | NeighborBit.s | NeighborBit.w, teeESWFinal);
451 byMask.set(NeighborBit.n | NeighborBit.e | NeighborBit.w, teeNEWFinal);
452 byMask.set(NeighborBit.n | NeighborBit.e | NeighborBit.s, teeNES);
453 byMask.set(NeighborBit.n | NeighborBit.w | NeighborBit.s, teeNWS);
454 byMask.set(
455 NeighborBit.n | NeighborBit.e | NeighborBit.s | NeighborBit.w,
456 (() =>
457 {
458 const out = clearRgba();
459 blit(out, ns);
460 blit(out, ew);
461 blit(out, teeESWFinal);
462 blit(out, teeNEWFinal);
463 return out;
464 })()
465 );
466
467 // Filled-corner variants for the primary L corners.
468 byMask.set(NeighborBit.n | NeighborBit.e | NeighborBit.ne, fillNE);
469 byMask.set(NeighborBit.n | NeighborBit.w | NeighborBit.nw, fillNW);
470 byMask.set(NeighborBit.s | NeighborBit.e | NeighborBit.se, fillSE);
471 byMask.set(NeighborBit.s | NeighborBit.w | NeighborBit.sw, fillSW);
472
473 const neDelta = cornerDelta(ellNE, fillNE);
474 const nwDelta = cornerDelta(ellNW, fillNW);
475 const seDelta = cornerDelta(ellSEFinal, fillSE);
476 const swDelta = cornerDelta(ellSW, fillSW);
477
478 return {
479 byMask,
480 neDelta,
481 nwDelta,
482 seDelta,
483 swDelta,
484 alone,
485 east,
486 west,
487 north,
488 south: southFinal,
489 ns,
490 ew,
491 ellNE,
492 fillNE
493 };
494}
495
496function paintMask (mask, pack)
497{
498 const n = (mask & NeighborBit.n) !== 0;
499 const e = (mask & NeighborBit.e) !== 0;
500 const s = (mask & NeighborBit.s) !== 0;
501 const w = (mask & NeighborBit.w) !== 0;
502 const ne = (mask & NeighborBit.ne) !== 0;
503 const se = (mask & NeighborBit.se) !== 0;
504 const sw = (mask & NeighborBit.sw) !== 0;
505 const nw = (mask & NeighborBit.nw) !== 0;
506
507 const cardinal = (n ? NeighborBit.n : 0)
508 | (e ? NeighborBit.e : 0)
509 | (s ? NeighborBit.s : 0)
510 | (w ? NeighborBit.w : 0);
511
512 // Exact hit (including known filled corners).
513 if (pack.byMask.has(mask))
514 { return copyRgba(pack.byMask.get(mask)); }
515
516 // Start from cardinal-only template, then apply diagonal fills.
517 let out;
518 if (pack.byMask.has(cardinal))
519 { out = copyRgba(pack.byMask.get(cardinal)); }
520 else
521 {
522 out = clearRgba();
523 if (n)
524 { blit(out, pack.north); }
525 if (s)
526 { blit(out, pack.south); }
527 if (e)
528 { blit(out, pack.east); }
529 if (w)
530 { blit(out, pack.west); }
531 if (n && s)
532 { blit(out, pack.ns); }
533 if (e && w)
534 { blit(out, pack.ew); }
535 }
536
537 if (n && e && ne)
538 { applyDelta(out, pack.neDelta, idX, idY); }
539 if (n && w && nw)
540 { applyDelta(out, pack.nwDelta, idX, idY); }
541 if (s && e && se)
542 { applyDelta(out, pack.seDelta, idX, idY); }
543 if (s && w && sw)
544 { applyDelta(out, pack.swDelta, idX, idY); }
545
546 // When diagonal is absent but cardinal template accidentally included fill,
547 // strip using inverse delta (already concave templates are used for cardinal).
548 return out;
549}
550
551function clearGenerated (dir)
552{
553 mkdirSync(dir, { recursive: true });
554 for (const name of readdirSync(dir))
555 {
556 if (!/^\d+\.png$/i.test(name))
557 { continue; }
558 unlinkSync(join(dir, name));
559 }
560}
561
562function writeSet (dir, pack, label)
563{
564 clearGenerated(dir);
565 const masks = listValidNeighborConnectCornerMasks();
566 for (const mask of masks)
567 {
568 writeFileSync(join(dir, `${mask}.png`), encodePng(paintMask(mask, pack)));
569 }
570 console.log(`Wrote ${masks.length} ${label} stone-wall sprites to ${dir}`);
571}
572
573function assertSame (a, b, label)
574{
575 for (let i = 0; i < a.length; i++)
576 {
577 if (a[i] !== b[i])
578 { throw new Error(`Mismatch ${label} @${i}: ${a[i]}≠${b[i]}`); }
579 }
580}
581
582const thin = buildPack("thin");
583const thick = buildPack("thick");
584
585assertSame(paintMask(0, thin), thin.alone, "thin/0");
586assertSame(paintMask(1, thin), thin.north, "thin/1");
587assertSame(paintMask(2, thin), thin.east, "thin/2");
588assertSame(paintMask(3, thin), thin.ellNE, "thin/3");
589assertSame(paintMask(5, thin), thin.ns, "thin/5");
590assertSame(paintMask(19, thin), thin.fillNE, "thin/19");
591assertSame(paintMask(0, thick), thick.alone, "thick/0");
592assertSame(paintMask(1, thick), thick.north, "thick/1");
593assertSame(paintMask(2, thick), thick.east, "thick/2");
594assertSame(paintMask(3, thick), thick.ellNE, "thick/3");
595assertSame(paintMask(5, thick), thick.ns, "thick/5");
596assertSame(paintMask(19, thick), thick.fillNE, "thick/19");
597
598writeSet(OUT_THIN, thin, "thin");
599writeSet(OUT_THICK, thick, "thick");
600console.log("All authored core templates verified.");