BlueGit

timfa questward

Files

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

generate-stone-wall-sprites.mjs

generate-stone-wall-sprites.mjs 15.0 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 * Shape sources (authoritative):
6 * example-stone-thin.png / example-stone-thin-connecting.png
7 * example-stone-thick.png / example-stone-thick-connecting.png
8 *
9 * Alone = free-standing frustum / bevelled block.
10 * *-connecting = same bands extruded to the east edge (free west end kept).
11 * Other directions are mirrors / vertical extrusions of that rule.
12 * Diagonal bits fill the concave L cutout so solid 2×2 reads continuous.
13 *
14 * node client/scripts/generate-stone-wall-sprites.mjs
15 */
16import { mkdirSync, writeFileSync, readdirSync, unlinkSync, readFileSync } from "node:fs";
17import { deflateSync, inflateSync } from "node:zlib";
18import { fileURLToPath } from "node:url";
19import { dirname, join } from "node:path";
20import {
21 NeighborBit,
22 listValidNeighborConnectCornerMasks
23} from "../../shared/world/neighborConnect.js";
24
25const SIZE = 16;
26const ROOT = join(dirname(fileURLToPath(import.meta.url)), "../assets/blocks");
27const OUT_THICK = join(ROOT, "stone-wall");
28const OUT_THIN = join(ROOT, "stone-wall-thin");
29const EXAMPLES = join(ROOT, "stone-wall");
30
31const MORTAR = [0x58, 0x58, 0x5c, 255];
32
33function crcTable ()
34{
35 const table = new Uint32Array(256);
36 for (let n = 0; n < 256; n++)
37 {
38 let c = n;
39 for (let k = 0; k < 8; k++)
40 { c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1); }
41 table[n] = c >>> 0;
42 }
43 return table;
44}
45
46const CRC_TABLE = crcTable();
47
48function crc32 (buf)
49{
50 let c = 0xffffffff;
51 for (let i = 0; i < buf.length; i++)
52 { c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8); }
53 return (c ^ 0xffffffff) >>> 0;
54}
55
56function chunk (type, data)
57{
58 const len = Buffer.alloc(4);
59 len.writeUInt32BE(data.length);
60 const typeBuf = Buffer.from(type, "ascii");
61 const crcBuf = Buffer.alloc(4);
62 crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])));
63 return Buffer.concat([len, typeBuf, data, crcBuf]);
64}
65
66function encodePng (rgba)
67{
68 const raw = Buffer.alloc((SIZE * 4 + 1) * SIZE);
69 for (let y = 0; y < SIZE; y++)
70 {
71 const row = y * (SIZE * 4 + 1);
72 raw[row] = 0;
73 for (let x = 0; x < SIZE; x++)
74 {
75 const i = (y * SIZE + x) * 4;
76 const o = row + 1 + x * 4;
77 raw[o] = rgba[i];
78 raw[o + 1] = rgba[i + 1];
79 raw[o + 2] = rgba[i + 2];
80 raw[o + 3] = rgba[i + 3];
81 }
82 }
83 const ihdr = Buffer.alloc(13);
84 ihdr.writeUInt32BE(SIZE, 0);
85 ihdr.writeUInt32BE(SIZE, 4);
86 ihdr[8] = 8;
87 ihdr[9] = 6;
88 return Buffer.concat([
89 Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
90 chunk("IHDR", ihdr),
91 chunk("IDAT", deflateSync(raw, { level: 9 })),
92 chunk("IEND", Buffer.alloc(0))
93 ]);
94}
95
96/** Decode 8-bit RGBA PNG (with scanline filters) into Uint8ClampedArray. */
97function decodePngRgba (path)
98{
99 const buf = readFileSync(path);
100 let off = 8;
101 let w = 0;
102 let h = 0;
103 const idat = [];
104 while (off < buf.length)
105 {
106 const len = buf.readUInt32BE(off);
107 const type = buf.slice(off + 4, off + 8).toString("ascii");
108 const data = buf.slice(off + 8, off + 8 + len);
109 if (type === "IHDR")
110 {
111 w = data.readUInt32BE(0);
112 h = data.readUInt32BE(4);
113 if (data[8] !== 8 || data[9] !== 6)
114 { throw new Error(`${path}: expected 8-bit RGBA`); }
115 }
116 else if (type === "IDAT")
117 { idat.push(data); }
118 else if (type === "IEND")
119 { break; }
120 off += 12 + len;
121 }
122 const raw = inflateSync(Buffer.concat(idat));
123 const bpp = 4;
124 const stride = w * bpp;
125 const rgba = new Uint8ClampedArray(w * h * 4);
126 let src = 0;
127 const prev = Buffer.alloc(stride);
128 const cur = Buffer.alloc(stride);
129 for (let y = 0; y < h; y++)
130 {
131 const filter = raw[src++];
132 for (let i = 0; i < stride; i++)
133 { cur[i] = raw[src++]; }
134 for (let i = 0; i < stride; i++)
135 {
136 const left = i >= bpp ? cur[i - bpp] : 0;
137 const up = prev[i];
138 const upLeft = i >= bpp ? prev[i - bpp] : 0;
139 let val = cur[i];
140 if (filter === 1)
141 { val = (val + left) & 255; }
142 else if (filter === 2)
143 { val = (val + up) & 255; }
144 else if (filter === 3)
145 { val = (val + ((left + up) >> 1)) & 255; }
146 else if (filter === 4)
147 {
148 const p = left + up - upLeft;
149 const pa = Math.abs(p - left);
150 const pb = Math.abs(p - up);
151 const pc = Math.abs(p - upLeft);
152 const pr = (pa <= pb && pa <= pc) ? left : (pb <= pc ? up : upLeft);
153 val = (val + pr) & 255;
154 }
155 cur[i] = val;
156 }
157 rgba.set(cur, y * stride);
158 prev.set(cur);
159 }
160 if (w !== SIZE || h !== SIZE)
161 { throw new Error(`${path}: expected ${SIZE}×${SIZE}, got ${w}×${h}`); }
162 return rgba;
163}
164
165function getPx (rgba, x, y)
166{
167 if (x < 0 || y < 0 || x >= SIZE || y >= SIZE)
168 { return [0, 0, 0, 0]; }
169 const i = (y * SIZE + x) * 4;
170 return [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]];
171}
172
173function setPx (rgba, x, y, color)
174{
175 if (x < 0 || y < 0 || x >= SIZE || y >= SIZE)
176 { return; }
177 const i = (y * SIZE + x) * 4;
178 rgba[i] = color[0];
179 rgba[i + 1] = color[1];
180 rgba[i + 2] = color[2];
181 rgba[i + 3] = color[3];
182}
183
184function opaque (rgba, x, y)
185{
186 return getPx(rgba, x, y)[3] > 128;
187}
188
189function mirrorX (rgba)
190{
191 const out = new Uint8ClampedArray(rgba.length);
192 for (let y = 0; y < SIZE; y++)
193 {
194 for (let x = 0; x < SIZE; x++)
195 { setPx(out, x, y, getPx(rgba, SIZE - 1 - x, y)); }
196 }
197 return out;
198}
199
200function hash2 (x, y)
201{
202 let n = (x * 374761393 + y * 668265263) | 0;
203 n = (n ^ (n >>> 13)) * 1274126177;
204 return (n ^ (n >>> 16)) >>> 0;
205}
206
207function cobbleShade (base, x, y)
208{
209 if (base[3] < 128)
210 { return base; }
211 const h = hash2(x, y);
212 const speck = h & 7;
213 if (speck === 0)
214 { return MORTAR; }
215 if (speck === 1)
216 {
217 return [
218 Math.min(255, base[0] + 14),
219 Math.min(255, base[1] + 14),
220 Math.min(255, base[2] + 14),
221 255
222 ];
223 }
224 if (speck === 2)
225 {
226 return [
227 Math.max(0, base[0] - 12),
228 Math.max(0, base[1] - 12),
229 Math.max(0, base[2] - 12),
230 255
231 ];
232 }
233 return base;
234}
235
236function decodeMask (mask)
237{
238 return {
239 n: (mask & NeighborBit.n) !== 0,
240 e: (mask & NeighborBit.e) !== 0,
241 s: (mask & NeighborBit.s) !== 0,
242 w: (mask & NeighborBit.w) !== 0,
243 ne: (mask & NeighborBit.ne) !== 0,
244 se: (mask & NeighborBit.se) !== 0,
245 sw: (mask & NeighborBit.sw) !== 0,
246 nw: (mask & NeighborBit.nw) !== 0
247 };
248}
249
250function aloneRowRange (alone, y)
251{
252 let x0 = -1;
253 let x1 = -1;
254 for (let x = 0; x < SIZE; x++)
255 {
256 if (!opaque(alone, x, y))
257 { continue; }
258 if (x0 < 0)
259 { x0 = x; }
260 x1 = x;
261 }
262 return x0 < 0 ? null : { x0, x1 };
263}
264
265function aloneColRange (alone, x)
266{
267 let y0 = -1;
268 let y1 = -1;
269 for (let y = 0; y < SIZE; y++)
270 {
271 if (!opaque(alone, x, y))
272 { continue; }
273 if (y0 < 0)
274 { y0 = y; }
275 y1 = y;
276 }
277 return y0 < 0 ? null : { y0, y1 };
278}
279
280function aloneBounds (alone)
281{
282 let minX = SIZE;
283 let maxX = -1;
284 let minY = SIZE;
285 let maxY = -1;
286 for (let y = 0; y < SIZE; y++)
287 {
288 for (let x = 0; x < SIZE; x++)
289 {
290 if (!opaque(alone, x, y))
291 { continue; }
292 minX = Math.min(minX, x);
293 maxX = Math.max(maxX, x);
294 minY = Math.min(minY, y);
295 maxY = Math.max(maxY, y);
296 }
297 }
298 return { minX, maxX, minY, maxY };
299}
300
301/**
302 * Strip-union of alone rows (E/W extrusion) and alone columns (N/S extrusion),
303 * plus diagonal fills for solid 2×2 corners.
304 */
305function thinOccupied (x, y, c, alone)
306{
307 if (!c.n && !c.e && !c.s && !c.w)
308 { return opaque(alone, x, y); }
309
310 const row = aloneRowRange(alone, y);
311 if (row && (c.e || c.w || opaque(alone, x, y)))
312 {
313 const x0 = c.w ? 0 : row.x0;
314 const x1 = c.e ? SIZE - 1 : row.x1;
315 if (x >= x0 && x <= x1)
316 { return true; }
317 }
318
319 const col = aloneColRange(alone, x);
320 if (col && (c.n || c.s || opaque(alone, x, y)))
321 {
322 const y0 = c.n ? 0 : col.y0;
323 const y1 = c.s ? SIZE - 1 : col.y1;
324 if (y >= y0 && y <= y1)
325 { return true; }
326 }
327
328 if (opaque(alone, x, y))
329 { return true; }
330
331 const b = aloneBounds(alone);
332 // Diagonal fills close the concave cutout of an L/T.
333 if (c.se && c.s && c.e && x > b.maxX && y > b.maxY)
334 { return true; }
335 if (c.sw && c.s && c.w && x < b.minX && y > b.maxY)
336 { return true; }
337 if (c.ne && c.n && c.e && x > b.maxX && y < b.minY)
338 { return true; }
339 if (c.nw && c.n && c.w && x < b.minX && y < b.minY)
340 { return true; }
341
342 // Also fill the "inside" corner within the extruded AABB when diagonal joins
343 // (region east of alone footprint ∩ south of alone footprint, etc.).
344 if (c.se && c.s && c.e && x > b.maxX && y >= b.minY && y <= SIZE - 1 && x <= SIZE - 1)
345 {
346 // Only below the horizontal band's natural bottom is the true cutout;
347 // pixels with y in alone rows are already filled by E extrusion.
348 if (y > b.maxY)
349 { return true; }
350 }
351 if (c.sw && c.s && c.w && x < b.minX && y > b.maxY)
352 { return true; }
353 if (c.ne && c.n && c.e && x > b.maxX && y < b.minY)
354 { return true; }
355 if (c.nw && c.n && c.w && x < b.minX && y < b.minY)
356 { return true; }
357
358 return false;
359}
360
361/**
362 * Colour for a thin pixel: prefer alone, else east/west connecting template,
363 * else sample the nearest alone edge colour along the extrusion axis.
364 */
365function thinColor (x, y, c, alone, east, west)
366{
367 if (opaque(alone, x, y))
368 { return getPx(alone, x, y); }
369
370 if (c.e && !c.w && opaque(east, x, y))
371 { return getPx(east, x, y); }
372 if (c.w && !c.e && opaque(west, x, y))
373 { return getPx(west, x, y); }
374 if (c.e && c.w)
375 {
376 // Full E–W run: take interior colour from the east template at this y.
377 const row = aloneRowRange(alone, y);
378 if (row)
379 {
380 const sampleX = Math.min(SIZE - 1, row.x1);
381 const col = getPx(east, sampleX, y);
382 if (col[3] > 128)
383 { return col; }
384 return getPx(alone, sampleX, y);
385 }
386 }
387
388 // N/S extrusion: continue the colour of the alone column end.
389 const col = aloneColRange(alone, x);
390 if (col)
391 {
392 if (c.n && y < col.y0)
393 { return getPx(alone, x, col.y0); }
394 if (c.s && y > col.y1)
395 { return getPx(alone, x, col.y1); }
396 }
397
398 // Diagonal fill / extended cutout: pick nearest alone interior.
399 const b = aloneBounds(alone);
400 const sx = Math.min(b.maxX, Math.max(b.minX, x));
401 const sy = Math.min(b.maxY, Math.max(b.minY, y));
402 return getPx(alone, sx, sy);
403}
404
405/**
406 * Thick walls always fill the tile. Shading: start from alone; for each
407 * connected side, replace that edge's bevel with the extruded connecting look.
408 */
409function thickColor (x, y, c, alone, east, west)
410{
411 // Build by compositing directional templates.
412 // Base = alone.
413 let color = getPx(alone, x, y);
414
415 const fromEast = opaque(east, x, y) ? getPx(east, x, y) : null;
416 const fromWest = opaque(west, x, y) ? getPx(west, x, y) : null;
417
418 // East connection: use east template where it differs from alone on the right half,
419 // or more simply — if only E: use east template entirely.
420 if (c.e && !c.w && !c.n && !c.s)
421 { return fromEast ?? color; }
422 if (c.w && !c.e && !c.n && !c.s)
423 { return fromWest ?? color; }
424
425 // General case: for each axis, prefer the connecting template's pixel when
426 // that side is connected and we're on the extruded side of the tile.
427 if (c.e && x >= 8 && fromEast)
428 { color = fromEast; }
429 if (c.w && x <= 7 && fromWest)
430 { color = fromWest; }
431
432 // North/south: extend the top/bottom band colours toward the edge.
433 if (c.n && y <= 2)
434 {
435 // Sample the y=1 band from the appropriate horizontal template.
436 const src = c.e && !c.w ? east : (c.w && !c.e ? west : alone);
437 color = getPx(src, x, 1);
438 }
439 if (c.s && y >= 13)
440 {
441 const src = c.e && !c.w ? east : (c.w && !c.e ? west : alone);
442 color = getPx(src, x, 14);
443 }
444
445 // Both E+W: full horizontal extrusion like two connecting halves.
446 if (c.e && c.w)
447 {
448 const left = getPx(west, Math.min(x, 7), y);
449 const right = getPx(east, Math.max(x, 8), y);
450 color = x <= 7 ? left : right;
451 }
452
453 // Open L corner (cardinals without diagonal): keep alone's outer-corner bevel
454 // in that quadrant. Filled diagonal: use connecting interior instead.
455 if (c.e && c.s && !c.se && x >= 12 && y >= 12)
456 { color = getPx(alone, x, y); }
457 if (c.e && c.s && c.se && x >= 12 && y >= 12)
458 { color = getPx(east, Math.min(15, x), Math.min(14, y)); }
459
460 if (c.w && c.s && !c.sw && x <= 3 && y >= 12)
461 { color = getPx(alone, x, y); }
462 if (c.w && c.s && c.sw && x <= 3 && y >= 12)
463 { color = getPx(west, Math.max(0, x), Math.min(14, y)); }
464
465 if (c.e && c.n && !c.ne && x >= 12 && y <= 3)
466 { color = getPx(alone, x, y); }
467 if (c.e && c.n && c.ne && x >= 12 && y <= 3)
468 { color = getPx(east, Math.min(15, x), Math.max(1, y)); }
469
470 if (c.w && c.n && !c.nw && x <= 3 && y <= 3)
471 { color = getPx(alone, x, y); }
472 if (c.w && c.n && c.nw && x <= 3 && y <= 3)
473 { color = getPx(west, Math.max(0, x), Math.max(1, y)); }
474
475 // Interior of solid block (all 4 + diagonals): flat top mid colour.
476 if (c.n && c.e && c.s && c.w && c.ne && c.se && c.sw && c.nw)
477 {
478 if (x > 0 && x < SIZE - 1 && y > 0 && y < SIZE - 1)
479 { color = getPx(east, 8, 5); }
480 }
481
482 return color;
483}
484
485function paintThin (mask, alone, east, west)
486{
487 const rgba = new Uint8ClampedArray(SIZE * SIZE * 4);
488 const c = decodeMask(mask);
489 for (let y = 0; y < SIZE; y++)
490 {
491 for (let x = 0; x < SIZE; x++)
492 {
493 if (!thinOccupied(x, y, c, alone))
494 { continue; }
495 const col = thinColor(x, y, c, alone, east, west);
496 setPx(rgba, x, y, cobbleShade(col, x, y));
497 }
498 }
499 return rgba;
500}
501
502function paintThick (mask, alone, east, west)
503{
504 const rgba = new Uint8ClampedArray(SIZE * SIZE * 4);
505 const c = decodeMask(mask);
506 for (let y = 0; y < SIZE; y++)
507 {
508 for (let x = 0; x < SIZE; x++)
509 {
510 const col = thickColor(x, y, c, alone, east, west);
511 setPx(rgba, x, y, cobbleShade(col, x, y));
512 }
513 }
514 return rgba;
515}
516
517function clearGenerated (dir)
518{
519 mkdirSync(dir, { recursive: true });
520 for (const name of readdirSync(dir))
521 {
522 if (!/^\d+\.png$/i.test(name))
523 { continue; }
524 unlinkSync(join(dir, name));
525 }
526}
527
528function writeSet (dir, paint, label)
529{
530 clearGenerated(dir);
531 const masks = listValidNeighborConnectCornerMasks();
532 for (const mask of masks)
533 {
534 writeFileSync(join(dir, `${mask}.png`), encodePng(paint(mask)));
535 }
536 console.log(`Wrote ${masks.length} ${label} stone-wall sprites to ${dir}`);
537}
538
539const thinAlone = decodePngRgba(join(EXAMPLES, "example-stone-thin.png"));
540const thinEast = decodePngRgba(join(EXAMPLES, "example-stone-thin-connecting.png"));
541const thinWest = mirrorX(thinEast);
542const thickAlone = decodePngRgba(join(EXAMPLES, "example-stone-thick.png"));
543const thickEast = decodePngRgba(join(EXAMPLES, "example-stone-thick-connecting.png"));
544const thickWest = mirrorX(thickEast);
545
546// Sanity: alone / east templates must decode to expected coverage.
547const thinAloneCount = [...thinAlone].filter((_, i) => i % 4 === 3 && thinAlone[i] > 128).length;
548const thinEastCount = [...thinEast].filter((_, i) => i % 4 === 3 && thinEast[i] > 128).length;
549if (thinAloneCount < 80 || thinEastCount < 120)
550{
551 throw new Error(`Example decode looks wrong (alone=${thinAloneCount}, east=${thinEastCount})`);
552}
553
554writeSet(OUT_THICK, (mask) => paintThick(mask, thickAlone, thickEast, thickWest), "thick");
555writeSet(OUT_THIN, (mask) => paintThin(mask, thinAlone, thinEast, thinWest), "thin");
556
557// Keep mask 0 / east-only (2) pixel-identical to examples (minus cobble speck on 0).
558writeFileSync(join(OUT_THIN, "0.png"), encodePng(thinAlone));
559writeFileSync(join(OUT_THICK, "0.png"), encodePng(thickAlone));
560writeFileSync(join(OUT_THIN, "2.png"), encodePng(thinEast));
561writeFileSync(join(OUT_THICK, "2.png"), encodePng(thickEast));
562writeFileSync(join(OUT_THIN, "8.png"), encodePng(thinWest));
563writeFileSync(join(OUT_THICK, "8.png"), encodePng(thickWest));
564console.log("Pinned 0 / E / W templates to example pixels");