BlueGit

timfa questward

Files

questward / client / scripts / texture-wall-sprites.mjs

texture-wall-sprites.mjs

texture-wall-sprites.mjs 16.4 KiB Download Raw
1/**
2 * Bake wall textures onto thick/thin greyscale face-id shape masks.
3 *
4 * Shape masks (greyscale face-IDs) belong in:
5 * client/assets/blocks/_examples/stone-wall/{thick,thin}-stone-wall*.png
6 *
7 * Workflow when editing shapes in the live gameplay folders:
8 * 1. Paint face-id greys in thick-stone-wall / thin-stone-wall
9 * 2. node client/scripts/texture-wall-sprites.mjs --sync-shapes
10 * (copies live → examples only if files are still face-id greyscale)
11 * 3. node client/scripts/texture-wall-sprites.mjs --variant=…
12 *
13 * Usage:
14 * node client/scripts/texture-wall-sprites.mjs --sync-shapes
15 * node client/scripts/texture-wall-sprites.mjs --variant=cobble|smooth|brick|wood|cliff|--all
16 *
17 * cobble overwrites thick/thin-stone-wall — pass --force (required) so hand tweaks are not clobbered.
18 */
19import { mkdirSync, writeFileSync, readdirSync, readFileSync, existsSync, cpSync } from "node:fs";
20import { deflateSync, inflateSync } from "node:zlib";
21import { fileURLToPath } from "node:url";
22import { dirname, join } from "node:path";
23import { cardinalConnectionSuffix } from "../../shared/world/neighborConnect.js";
24
25const SIZE = 16;
26const ROOT = join(dirname(fileURLToPath(import.meta.url)), "../assets/blocks");
27const EXAMPLES = join(ROOT, "_examples/stone-wall");
28const GROUNDS = join(dirname(fileURLToPath(import.meta.url)), "../assets/grounds");
29
30const THICK_ROLE = {
31 0xaf: "N",
32 0x95: "W",
33 0x80: "T",
34 0x6c: "E",
35 0x54: "S",
36 0x40: "O"
37};
38
39const THIN_ROLE = {
40 0xb6: "W",
41 0x95: "N",
42 0x80: "E",
43 0x73: "S",
44 0x40: "O"
45};
46
47function roleOf (prefix, g)
48{
49 const map = prefix.startsWith("thin") ? THIN_ROLE : THICK_ROLE;
50 return map[g] ?? null;
51}
52
53function isTopRole (role)
54{
55 return role === "T" || role === "N";
56}
57
58function crcTable ()
59{
60 const table = new Uint32Array(256);
61 for (let n = 0; n < 256; n++)
62 {
63 let c = n;
64 for (let k = 0; k < 8; k++)
65 { c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1); }
66 table[n] = c >>> 0;
67 }
68 return table;
69}
70
71const CRC_TABLE = crcTable();
72
73function crc32 (buf)
74{
75 let c = 0xffffffff;
76 for (let i = 0; i < buf.length; i++)
77 { c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8); }
78 return (c ^ 0xffffffff) >>> 0;
79}
80
81function chunk (type, data)
82{
83 const len = Buffer.alloc(4);
84 len.writeUInt32BE(data.length);
85 const typeBuf = Buffer.from(type, "ascii");
86 const crcBuf = Buffer.alloc(4);
87 crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])));
88 return Buffer.concat([len, typeBuf, data, crcBuf]);
89}
90
91function encodePng (rgba)
92{
93 const raw = Buffer.alloc((SIZE * 4 + 1) * SIZE);
94 for (let y = 0; y < SIZE; y++)
95 {
96 const row = y * (SIZE * 4 + 1);
97 raw[row] = 0;
98 for (let x = 0; x < SIZE; x++)
99 {
100 const i = (y * SIZE + x) * 4;
101 const o = row + 1 + x * 4;
102 raw[o] = rgba[i];
103 raw[o + 1] = rgba[i + 1];
104 raw[o + 2] = rgba[i + 2];
105 raw[o + 3] = rgba[i + 3];
106 }
107 }
108 const ihdr = Buffer.alloc(13);
109 ihdr.writeUInt32BE(SIZE, 0);
110 ihdr.writeUInt32BE(SIZE, 4);
111 ihdr[8] = 8;
112 ihdr[9] = 6;
113 return Buffer.concat([
114 Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
115 chunk("IHDR", ihdr),
116 chunk("IDAT", deflateSync(raw, { level: 9 })),
117 chunk("IEND", Buffer.alloc(0))
118 ]);
119}
120
121function decodePngRgba (path)
122{
123 const buf = readFileSync(path);
124 let off = 8;
125 let w = 0;
126 let h = 0;
127 let colorType = 6;
128 const idat = [];
129 while (off < buf.length)
130 {
131 const len = buf.readUInt32BE(off);
132 const type = buf.slice(off + 4, off + 8).toString("ascii");
133 const data = buf.slice(off + 8, off + 8 + len);
134 if (type === "IHDR")
135 {
136 w = data.readUInt32BE(0);
137 h = data.readUInt32BE(4);
138 colorType = data[9];
139 }
140 else if (type === "IDAT")
141 { idat.push(data); }
142 else if (type === "IEND")
143 { break; }
144 off += 12 + len;
145 }
146 const channels = colorType === 2 ? 3 : colorType === 6 ? 4 : 0;
147 if (!channels)
148 { throw new Error(`${path}: unsupported PNG color type ${colorType}`); }
149 const inflated = inflateSync(Buffer.concat(idat));
150 const rgba = new Uint8Array(w * h * 4);
151 let src = 0;
152 const prevRow = new Uint8Array(w * channels);
153 const curRow = new Uint8Array(w * channels);
154 for (let y = 0; y < h; y++)
155 {
156 const filter = inflated[src++];
157 for (let i = 0; i < w * channels; i++)
158 {
159 let v = inflated[src++];
160 if (filter === 1)
161 { v = (v + (i >= channels ? curRow[i - channels] : 0)) & 255; }
162 else if (filter === 2)
163 { v = (v + prevRow[i]) & 255; }
164 else if (filter === 3)
165 {
166 const a = i >= channels ? curRow[i - channels] : 0;
167 v = (v + Math.floor((a + prevRow[i]) / 2)) & 255;
168 }
169 else if (filter === 4)
170 {
171 const a = i >= channels ? curRow[i - channels] : 0;
172 const b = prevRow[i];
173 const c = i >= channels ? prevRow[i - channels] : 0;
174 const p = a + b - c;
175 const pa = Math.abs(p - a);
176 const pb = Math.abs(p - b);
177 const pc = Math.abs(p - c);
178 v = (v + (pa <= pb && pa <= pc ? a : pb <= pc ? b : c)) & 255;
179 }
180 curRow[i] = v;
181 }
182 for (let x = 0; x < w; x++)
183 {
184 const si = x * channels;
185 const di = (y * w + x) * 4;
186 rgba[di] = curRow[si];
187 rgba[di + 1] = curRow[si + 1];
188 rgba[di + 2] = curRow[si + 2];
189 rgba[di + 3] = channels === 4 ? curRow[si + 3] : 255;
190 }
191 prevRow.set(curRow);
192 }
193 if (w !== SIZE || h !== SIZE)
194 { throw new Error(`${path}: expected ${SIZE}×${SIZE}, got ${w}×${h}`); }
195 return rgba;
196}
197
198function hash2 (x, y)
199{
200 let n = (x * 374761393 + y * 668265263) | 0;
201 n = (n ^ (n >>> 13)) * 1274126177;
202 return (n ^ (n >>> 16)) >>> 0;
203}
204
205function rgba (r, g, b, a = 255)
206{
207 return [r, g, b, a];
208}
209
210function mulRgb (c, factor)
211{
212 return rgba(
213 Math.min(255, Math.round(c[0] * factor)),
214 Math.min(255, Math.round(c[1] * factor)),
215 Math.min(255, Math.round(c[2] * factor)),
216 c[3] ?? 255
217 );
218}
219
220function mixRgb (a, b, t)
221{
222 return rgba(
223 Math.round(a[0] + (b[0] - a[0]) * t),
224 Math.round(a[1] + (b[1] - a[1]) * t),
225 Math.round(a[2] + (b[2] - a[2]) * t),
226 255
227 );
228}
229
230/** Face role → lighting factor (NW light). */
231const ROLE_LIT = { N: 1.15, W: 1.0, T: 1.05, E: 0.82, S: 0.62, O: 0.45 };
232
233function faceLit (role)
234{
235 return ROLE_LIT[role] ?? 0.9;
236}
237
238function loadDirt ()
239{
240 const path = join(GROUNDS, "dirt/dirt.png");
241 if (!existsSync(path))
242 { throw new Error(`Missing dirt texture: ${path}`); }
243 return decodePngRgba(path);
244}
245
246let dirtRgba = null;
247function dirtAt (x, y)
248{
249 if (!dirtRgba)
250 { dirtRgba = loadDirt(); }
251 const i = ((y & 15) * SIZE + (x & 15)) * 4;
252 return rgba(dirtRgba[i], dirtRgba[i + 1], dirtRgba[i + 2]);
253}
254
255/* ---- palettes ---- */
256
257const COBBLE = {
258 N: rgba(198, 198, 202),
259 W: rgba(132, 132, 136),
260 T: rgba(168, 168, 172),
261 E: rgba(112, 112, 116),
262 S: rgba(88, 88, 92),
263 O: rgba(70, 70, 74),
264 mortar: rgba(78, 78, 82),
265 hiN: rgba(210, 210, 214),
266 loS: rgba(78, 78, 82)
267};
268
269const BRICK = {
270 N: rgba(196, 92, 72),
271 W: rgba(168, 72, 56),
272 T: rgba(178, 78, 60),
273 E: rgba(148, 58, 46),
274 S: rgba(118, 48, 38),
275 O: rgba(72, 36, 30),
276 mortar: rgba(92, 78, 68),
277 hi: rgba(210, 110, 88),
278 lo: rgba(100, 42, 34),
279 /** Flat cement cap (no brick bond on tops). */
280 cement: rgba(168, 160, 152),
281 cementHi: rgba(184, 176, 168),
282 cementLo: rgba(148, 140, 132)
283};
284
285function cobbleLike (basePal, x, y, role, gritMask)
286{
287 if (role === "O")
288 {
289 const h = hash2(x, y);
290 return (h & 15) === 0 ? basePal.mortar : basePal.O;
291 }
292 const base = basePal[role] ?? basePal.T;
293 const h = hash2(x, y);
294 const speck = h & gritMask;
295 if (speck === 0)
296 { return basePal.mortar; }
297 if (gritMask === 7)
298 {
299 if (speck === 1 || speck === 2)
300 { return role === "N" || role === "T" ? (basePal.hiN ?? basePal.hi ?? mulRgb(base, 1.12)) : (basePal.hi ?? mulRgb(base, 1.1)); }
301 if (speck === 3)
302 { return role === "S" ? (basePal.loS ?? basePal.lo ?? mulRgb(base, 0.88)) : (basePal.lo ?? mulRgb(base, 0.9)); }
303 }
304 else if (gritMask === 31)
305 {
306 // Smooth: rare soft variation only.
307 if (speck === 1)
308 { return mulRgb(base, 1.06); }
309 if (speck === 2)
310 { return mulRgb(base, 0.94); }
311 }
312 return base;
313}
314
315/**
316 * Brick mortar follows each face:
317 * - T (thick) / N (thin ridge): flat cement cap
318 * - S: running bond elevation
319 * - N (thick bevel): vertical joints along the rim
320 * - W / E: diagonal course marks — outer column 1px below inner
321 */
322function brickShade (x, y, role, shapePrefix, faceRgba)
323{
324 if (role === "O")
325 { return BRICK.O; }
326
327 const thin = shapePrefix.startsWith("thin");
328 const isCap = role === "T" || (thin && role === "N");
329 if (isCap)
330 {
331 const h = hash2(x, y);
332 if ((h & 31) === 0)
333 { return BRICK.cementHi; }
334 if ((h & 31) === 1)
335 { return BRICK.cementLo; }
336 return BRICK.cement;
337 }
338
339 const courseH = 4;
340 const brickW = 6;
341 let onMortar = false;
342
343 if (role === "W" || role === "E")
344 {
345 const phase = y % courseH;
346 const outer = role === "W"
347 ? !isSameFace(faceRgba, x - 1, y, role, shapePrefix)
348 : !isSameFace(faceRgba, x + 1, y, role, shapePrefix);
349 // Diagonal: ·O then O· on west (outer 1px down); mirrored on east.
350 if (phase === 0)
351 { onMortar = !outer; }
352 else if (phase === 1)
353 { onMortar = outer; }
354 }
355 else if (role === "N")
356 {
357 onMortar = (x % brickW) === 0;
358 }
359 else
360 {
361 const row = Math.floor(y / courseH);
362 const brickX = x + (row & 1) * Math.floor(brickW / 2);
363 onMortar = (y % courseH) === 0 || (brickX % brickW) === 0;
364 }
365
366 if (onMortar)
367 { return BRICK.mortar; }
368
369 const h = hash2(x + role.charCodeAt(0) * 17, y);
370 if ((h & 15) === 0)
371 { return BRICK.hi; }
372 if ((h & 15) === 1)
373 { return BRICK.lo; }
374 return BRICK[role] ?? BRICK.T;
375}
376
377function isSameFace (faceRgba, x, y, role, shapePrefix)
378{
379 if (x < 0 || y < 0 || x >= SIZE || y >= SIZE || !faceRgba)
380 { return false; }
381 const i = (y * SIZE + x) * 4;
382 if (faceRgba[i + 3] === 0)
383 { return false; }
384 return roleOf(shapePrefix, faceRgba[i]) === role;
385}
386
387function woodMagenta (role)
388{
389 // R≈B, G<R — lightness encodes face.
390 const L = {
391 O: 55,
392 S: 95,
393 E: 120,
394 W: 155,
395 T: 185,
396 N: 210
397 }[role] ?? 140;
398 const gHi = role === "N" || role === "T" ? Math.min(L - 20, 50) : 0;
399 return rgba(L, gHi, L);
400}
401
402/**
403 * Cliff magenta tops: thick = plateau only (N is a dirt north face).
404 * Thin has no separate T — ridge top is role N.
405 */
406function isCliffTopRole (role, shapePrefix)
407{
408 if (shapePrefix.startsWith("thin"))
409 { return role === "N"; }
410 return role === "T";
411}
412
413function cliffShade (x, y, role, shapePrefix)
414{
415 if (isCliffTopRole(role, shapePrefix))
416 {
417 // Full magenta top — replaced in-game by ground sample shader.
418 return rgba(255, 0, 255);
419 }
420 if (role === "O")
421 {
422 const d = dirtAt(x, y);
423 return mulRgb(d, 0.35);
424 }
425 const d = dirtAt(x, y);
426 return mulRgb(d, faceLit(role));
427}
428
429function paintPixel (variant, prefix, g, x, y, faceRgba = null)
430{
431 const role = roleOf(prefix, g);
432 if (!role)
433 {
434 // Unknown grey: luminance fallback toward mid face.
435 const lit = g / 128;
436 if (variant === "wood")
437 { return rgba(Math.round(140 * lit), 0, Math.round(140 * lit)); }
438 if (variant === "cliff")
439 { return mulRgb(dirtAt(x, y), lit); }
440 if (variant === "brick")
441 { return mulRgb(BRICK.cement, lit); }
442 return mulRgb(COBBLE.T, lit);
443 }
444 if (variant === "cobble")
445 { return cobbleLike(COBBLE, x, y, role, 7); }
446 if (variant === "smooth")
447 { return cobbleLike(COBBLE, x, y, role, 31); }
448 if (variant === "brick")
449 { return brickShade(x, y, role, prefix, faceRgba); }
450 if (variant === "wood")
451 { return woodMagenta(role); }
452 if (variant === "cliff")
453 { return cliffShade(x, y, role, prefix); }
454 throw new Error(`Unknown variant ${variant}`);
455}
456
457function textureMask (rgbaIn, variant, shapePrefix)
458{
459 const out = new Uint8Array(SIZE * SIZE * 4);
460 for (let y = 0; y < SIZE; y++)
461 {
462 for (let x = 0; x < SIZE; x++)
463 {
464 const i = (y * SIZE + x) * 4;
465 if (rgbaIn[i + 3] === 0)
466 { continue; }
467 const color = paintPixel(variant, shapePrefix, rgbaIn[i], x, y, rgbaIn);
468 out[i] = color[0];
469 out[i + 1] = color[1];
470 out[i + 2] = color[2];
471 out[i + 3] = 255;
472 }
473 }
474 return out;
475}
476
477const VARIANT_OUT = {
478 cobble: {
479 thick: { dir: "thick-stone-wall", named: true, prefix: "thick-stone-wall" },
480 thin: { dir: "thin-stone-wall", named: true, prefix: "thin-stone-wall" }
481 },
482 smooth: {
483 thick: { dir: "thick-smooth-stone-wall", named: true, prefix: "thick-smooth-stone-wall" },
484 thin: { dir: "thin-smooth-stone-wall", named: true, prefix: "thin-smooth-stone-wall" }
485 },
486 brick: {
487 thick: { dir: "thick-brick-wall", named: true, prefix: "thick-brick-wall" },
488 thin: { dir: "thin-brick-wall", named: true, prefix: "thin-brick-wall" }
489 },
490 wood: {
491 thick: { dir: "thick-wood-wall", named: false, prefix: "thick-stone-wall" },
492 thin: { dir: "thin-wood-wall", named: false, prefix: "thin-stone-wall" }
493 },
494 cliff: {
495 thick: { dir: "thick-cliff", named: true, prefix: "thick-cliff" },
496 thin: { dir: "thin-cliff", named: true, prefix: "thin-cliff" }
497 }
498};
499
500function shapeFiles (shapeKey)
501{
502 return readdirSync(EXAMPLES)
503 .filter((name) => name.startsWith(shapeKey) && name.endsWith(".png") && !name.includes("ref-"))
504 .sort();
505}
506
507function namedOutName (outPrefix, shapeName, shapeKey)
508{
509 // thick-stone-wall-esw.png → thick-smooth-stone-wall-esw.png
510 const suffix = shapeName.slice(shapeKey.length); // "" or "-esw"
511 return `${outPrefix}${suffix}`;
512}
513
514const FACE_ID_GREYS = new Set([
515 0x40, 0x54, 0x6c, 0x73, 0x80, 0x95, 0xaf, 0xb6
516]);
517
518function isFaceIdMask (rgba)
519{
520 for (let i = 0; i < rgba.length; i += 4)
521 {
522 if (rgba[i + 3] === 0)
523 { continue; }
524 if (rgba[i] !== rgba[i + 1] || rgba[i] !== rgba[i + 2])
525 { return false; }
526 if (!FACE_ID_GREYS.has(rgba[i]))
527 { return false; }
528 }
529 return true;
530}
531
532/** Copy face-id greyscale from live thick/thin-stone-wall → _examples (never textured art). */
533function syncShapesFromLive ()
534{
535 mkdirSync(EXAMPLES, { recursive: true });
536 let copied = 0;
537 for (const kind of ["thick", "thin"])
538 {
539 const shapeKey = `${kind}-stone-wall`;
540 const liveDir = join(ROOT, shapeKey);
541 if (!existsSync(liveDir))
542 { throw new Error(`Missing live folder ${liveDir}`); }
543 const files = readdirSync(liveDir)
544 .filter((name) => name.startsWith(shapeKey) && name.endsWith(".png"))
545 .sort();
546 if (files.length !== 16)
547 { throw new Error(`Expected 16 live ${shapeKey} sprites, found ${files.length}`); }
548 for (const name of files)
549 {
550 const rgba = decodePngRgba(join(liveDir, name));
551 if (!isFaceIdMask(rgba))
552 {
553 throw new Error(
554 `${shapeKey}/${name} is not a face-id greyscale mask (already textured?). ` +
555 `Paint face-id greys in the live folder, then re-run --sync-shapes.`
556 );
557 }
558 cpSync(join(liveDir, name), join(EXAMPLES, name));
559 copied++;
560 }
561 console.log(` synced ${kind} → ${EXAMPLES}`);
562 }
563 console.log(`Synced ${copied} face-id masks into examples.`);
564}
565
566function bakeVariant (variant, { force = false } = {})
567{
568 const cfg = VARIANT_OUT[variant];
569 if (!cfg)
570 { throw new Error(`Unknown variant: ${variant}`); }
571 if (variant === "cobble" && !force)
572 {
573 throw new Error(
574 "Refusing to overwrite thick/thin-stone-wall without --force " +
575 "(hand-tweaked gameplay sprites). Sync shapes with --sync-shapes first if needed."
576 );
577 }
578 let wrote = 0;
579 for (const kind of ["thick", "thin"])
580 {
581 const shapeKey = `${kind}-stone-wall`;
582 const out = cfg[kind];
583 const outDir = join(ROOT, out.dir);
584 mkdirSync(outDir, { recursive: true });
585 const files = shapeFiles(shapeKey);
586 if (files.length !== 16)
587 { throw new Error(`Expected 16 ${shapeKey} masks, found ${files.length}`); }
588
589 if (out.named)
590 {
591 for (const name of files)
592 {
593 const shaped = decodePngRgba(join(EXAMPLES, name));
594 const textured = textureMask(shaped, variant, shapeKey);
595 const outName = namedOutName(out.prefix, name, shapeKey);
596 writeFileSync(join(outDir, outName), encodePng(textured));
597 wrote++;
598 }
599 }
600 else
601 {
602 for (let mask = 0; mask < 16; mask++)
603 {
604 const suffix = cardinalConnectionSuffix(mask);
605 const shapeName = suffix ? `${shapeKey}-${suffix}.png` : `${shapeKey}.png`;
606 const shaped = decodePngRgba(join(EXAMPLES, shapeName));
607 const textured = textureMask(shaped, variant, shapeKey);
608 writeFileSync(join(outDir, `${mask}.png`), encodePng(textured));
609 wrote++;
610 }
611 }
612 console.log(` ${variant} ${kind} → ${outDir} (${out.named ? "named" : "0–15"})`);
613 }
614 return wrote;
615}
616
617if (process.argv.includes("--sync-shapes"))
618{
619 syncShapesFromLive();
620 process.exit(0);
621}
622
623const arg = process.argv.find((a) => a.startsWith("--variant="));
624const variant = arg ? arg.slice("--variant=".length) : null;
625if (!variant)
626{
627 console.error("Usage: --sync-shapes | --variant=cobble|smooth|brick|wood|cliff|all [--force]");
628 process.exit(1);
629}
630const force = process.argv.includes("--force");
631const list = variant === "all"
632 ? ["cobble", "smooth", "brick", "wood", "cliff"]
633 : [variant];
634
635if (!existsSync(EXAMPLES))
636{ throw new Error(`Missing ${EXAMPLES}`); }
637
638let total = 0;
639for (const v of list)
640{
641 console.log(`Baking ${v}…`);
642 total += bakeVariant(v, { force });
643}
644console.log(`Done (${total} sprites).`);