BlueGit

timfa questward

Files

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

texture-wall-sprites.mjs

texture-wall-sprites.mjs 12.3 KiB Download Raw
1/**
2 * Bake wall textures onto thick/thin greyscale face-id shape masks.
3 *
4 * Shapes (source of truth):
5 * client/assets/blocks/_examples/stone-wall/{thick,thin}-stone-wall*.png
6 *
7 * Usage:
8 * node client/scripts/texture-wall-sprites.mjs --variant=cobble|smooth|brick|wood|cliff
9 * node client/scripts/texture-wall-sprites.mjs --variant=all
10 *
11 * cobble → thick-stone-wall / thin-stone-wall (named)
12 * smooth → thick-smooth-stone-wall / thin-smooth-stone-wall (named)
13 * brick → thick-brick-wall / thin-brick-wall (named)
14 * wood → thick-wood-wall / thin-wood-wall (magenta masks 0–15)
15 * cliff → thick-cliff / thin-cliff (dirt sides + magenta top, named)
16 */
17import { mkdirSync, writeFileSync, readdirSync, readFileSync, existsSync } from "node:fs";
18import { deflateSync, inflateSync } from "node:zlib";
19import { fileURLToPath } from "node:url";
20import { dirname, join } from "node:path";
21import { cardinalConnectionSuffix } from "../../shared/world/neighborConnect.js";
22
23const SIZE = 16;
24const ROOT = join(dirname(fileURLToPath(import.meta.url)), "../assets/blocks");
25const EXAMPLES = join(ROOT, "_examples/stone-wall");
26const GROUNDS = join(dirname(fileURLToPath(import.meta.url)), "../assets/grounds");
27
28const THICK_ROLE = {
29 0xaf: "N",
30 0x95: "W",
31 0x80: "T",
32 0x6c: "E",
33 0x54: "S",
34 0x40: "O"
35};
36
37const THIN_ROLE = {
38 0xb6: "W",
39 0x95: "N",
40 0x80: "E",
41 0x73: "S",
42 0x40: "O"
43};
44
45function roleOf (prefix, g)
46{
47 const map = prefix.startsWith("thin") ? THIN_ROLE : THICK_ROLE;
48 return map[g] ?? null;
49}
50
51function isTopRole (role)
52{
53 return role === "T" || role === "N";
54}
55
56function crcTable ()
57{
58 const table = new Uint32Array(256);
59 for (let n = 0; n < 256; n++)
60 {
61 let c = n;
62 for (let k = 0; k < 8; k++)
63 { c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1); }
64 table[n] = c >>> 0;
65 }
66 return table;
67}
68
69const CRC_TABLE = crcTable();
70
71function crc32 (buf)
72{
73 let c = 0xffffffff;
74 for (let i = 0; i < buf.length; i++)
75 { c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8); }
76 return (c ^ 0xffffffff) >>> 0;
77}
78
79function chunk (type, data)
80{
81 const len = Buffer.alloc(4);
82 len.writeUInt32BE(data.length);
83 const typeBuf = Buffer.from(type, "ascii");
84 const crcBuf = Buffer.alloc(4);
85 crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])));
86 return Buffer.concat([len, typeBuf, data, crcBuf]);
87}
88
89function encodePng (rgba)
90{
91 const raw = Buffer.alloc((SIZE * 4 + 1) * SIZE);
92 for (let y = 0; y < SIZE; y++)
93 {
94 const row = y * (SIZE * 4 + 1);
95 raw[row] = 0;
96 for (let x = 0; x < SIZE; x++)
97 {
98 const i = (y * SIZE + x) * 4;
99 const o = row + 1 + x * 4;
100 raw[o] = rgba[i];
101 raw[o + 1] = rgba[i + 1];
102 raw[o + 2] = rgba[i + 2];
103 raw[o + 3] = rgba[i + 3];
104 }
105 }
106 const ihdr = Buffer.alloc(13);
107 ihdr.writeUInt32BE(SIZE, 0);
108 ihdr.writeUInt32BE(SIZE, 4);
109 ihdr[8] = 8;
110 ihdr[9] = 6;
111 return Buffer.concat([
112 Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
113 chunk("IHDR", ihdr),
114 chunk("IDAT", deflateSync(raw, { level: 9 })),
115 chunk("IEND", Buffer.alloc(0))
116 ]);
117}
118
119function decodePngRgba (path)
120{
121 const buf = readFileSync(path);
122 let off = 8;
123 let w = 0;
124 let h = 0;
125 const idat = [];
126 while (off < buf.length)
127 {
128 const len = buf.readUInt32BE(off);
129 const type = buf.slice(off + 4, off + 8).toString("ascii");
130 const data = buf.slice(off + 8, off + 8 + len);
131 if (type === "IHDR")
132 {
133 w = data.readUInt32BE(0);
134 h = data.readUInt32BE(4);
135 }
136 else if (type === "IDAT")
137 { idat.push(data); }
138 else if (type === "IEND")
139 { break; }
140 off += 12 + len;
141 }
142 const inflated = inflateSync(Buffer.concat(idat));
143 const rgba = new Uint8Array(w * h * 4);
144 const bpp = 4;
145 let src = 0;
146 for (let y = 0; y < h; y++)
147 {
148 const filter = inflated[src++];
149 const row = inflated.subarray(src, src + w * bpp);
150 src += w * bpp;
151 const prev = y > 0 ? rgba.subarray((y - 1) * w * bpp, y * w * bpp) : null;
152 const out = rgba.subarray(y * w * bpp, (y + 1) * w * bpp);
153 for (let i = 0; i < row.length; i++)
154 {
155 let v = row[i];
156 if (filter === 1)
157 { v = (v + (i >= bpp ? out[i - bpp] : 0)) & 255; }
158 else if (filter === 2)
159 { v = (v + (prev ? prev[i] : 0)) & 255; }
160 else if (filter === 3)
161 {
162 const a = i >= bpp ? out[i - bpp] : 0;
163 const b = prev ? prev[i] : 0;
164 v = (v + Math.floor((a + b) / 2)) & 255;
165 }
166 else if (filter === 4)
167 {
168 const a = i >= bpp ? out[i - bpp] : 0;
169 const b = prev ? prev[i] : 0;
170 const c = prev && i >= bpp ? prev[i - bpp] : 0;
171 const p = a + b - c;
172 const pa = Math.abs(p - a);
173 const pb = Math.abs(p - b);
174 const pc = Math.abs(p - c);
175 v = (v + (pa <= pb && pa <= pc ? a : pb <= pc ? b : c)) & 255;
176 }
177 out[i] = v;
178 }
179 }
180 if (w !== SIZE || h !== SIZE)
181 { throw new Error(`${path}: expected ${SIZE}×${SIZE}, got ${w}×${h}`); }
182 return rgba;
183}
184
185function hash2 (x, y)
186{
187 let n = (x * 374761393 + y * 668265263) | 0;
188 n = (n ^ (n >>> 13)) * 1274126177;
189 return (n ^ (n >>> 16)) >>> 0;
190}
191
192function rgba (r, g, b, a = 255)
193{
194 return [r, g, b, a];
195}
196
197function mulRgb (c, factor)
198{
199 return rgba(
200 Math.min(255, Math.round(c[0] * factor)),
201 Math.min(255, Math.round(c[1] * factor)),
202 Math.min(255, Math.round(c[2] * factor)),
203 c[3] ?? 255
204 );
205}
206
207function mixRgb (a, b, t)
208{
209 return rgba(
210 Math.round(a[0] + (b[0] - a[0]) * t),
211 Math.round(a[1] + (b[1] - a[1]) * t),
212 Math.round(a[2] + (b[2] - a[2]) * t),
213 255
214 );
215}
216
217/** Face role → lighting factor (NW light). */
218const ROLE_LIT = { N: 1.15, W: 1.0, T: 1.05, E: 0.82, S: 0.62, O: 0.45 };
219
220function faceLit (role)
221{
222 return ROLE_LIT[role] ?? 0.9;
223}
224
225function loadDirt ()
226{
227 const path = join(GROUNDS, "dirt/dirt.png");
228 if (!existsSync(path))
229 { throw new Error(`Missing dirt texture: ${path}`); }
230 return decodePngRgba(path);
231}
232
233let dirtRgba = null;
234function dirtAt (x, y)
235{
236 if (!dirtRgba)
237 { dirtRgba = loadDirt(); }
238 const i = ((y & 15) * SIZE + (x & 15)) * 4;
239 return rgba(dirtRgba[i], dirtRgba[i + 1], dirtRgba[i + 2]);
240}
241
242/* ---- palettes ---- */
243
244const COBBLE = {
245 N: rgba(198, 198, 202),
246 W: rgba(132, 132, 136),
247 T: rgba(168, 168, 172),
248 E: rgba(112, 112, 116),
249 S: rgba(88, 88, 92),
250 O: rgba(70, 70, 74),
251 mortar: rgba(78, 78, 82),
252 hiN: rgba(210, 210, 214),
253 loS: rgba(78, 78, 82)
254};
255
256const BRICK = {
257 N: rgba(196, 92, 72),
258 W: rgba(168, 72, 56),
259 T: rgba(178, 78, 60),
260 E: rgba(148, 58, 46),
261 S: rgba(118, 48, 38),
262 O: rgba(72, 36, 30),
263 mortar: rgba(92, 78, 68),
264 hi: rgba(210, 110, 88),
265 lo: rgba(100, 42, 34)
266};
267
268function cobbleLike (basePal, x, y, role, gritMask)
269{
270 if (role === "O")
271 {
272 const h = hash2(x, y);
273 return (h & 15) === 0 ? basePal.mortar : basePal.O;
274 }
275 const base = basePal[role] ?? basePal.T;
276 const h = hash2(x, y);
277 const speck = h & gritMask;
278 if (speck === 0)
279 { return basePal.mortar; }
280 if (gritMask === 7)
281 {
282 if (speck === 1 || speck === 2)
283 { return role === "N" || role === "T" ? (basePal.hiN ?? basePal.hi ?? mulRgb(base, 1.12)) : (basePal.hi ?? mulRgb(base, 1.1)); }
284 if (speck === 3)
285 { return role === "S" ? (basePal.loS ?? basePal.lo ?? mulRgb(base, 0.88)) : (basePal.lo ?? mulRgb(base, 0.9)); }
286 }
287 else if (gritMask === 31)
288 {
289 // Smooth: rare soft variation only.
290 if (speck === 1)
291 { return mulRgb(base, 1.06); }
292 if (speck === 2)
293 { return mulRgb(base, 0.94); }
294 }
295 return base;
296}
297
298function brickShade (x, y, role)
299{
300 if (role === "O")
301 { return BRICK.O; }
302 const row = Math.floor(y / 4);
303 const brickX = x + (row & 1) * 3;
304 const onHMortar = (y % 4) === 0;
305 const onVMortar = (brickX % 6) === 0;
306 if (onHMortar || onVMortar)
307 { return BRICK.mortar; }
308 const h = hash2(x, y);
309 if ((h & 15) === 0)
310 { return BRICK.hi; }
311 if ((h & 15) === 1)
312 { return BRICK.lo; }
313 return BRICK[role] ?? BRICK.T;
314}
315
316function woodMagenta (role)
317{
318 // R≈B, G<R — lightness encodes face.
319 const L = {
320 O: 55,
321 S: 95,
322 E: 120,
323 W: 155,
324 T: 185,
325 N: 210
326 }[role] ?? 140;
327 const gHi = role === "N" || role === "T" ? Math.min(L - 20, 50) : 0;
328 return rgba(L, gHi, L);
329}
330
331function cliffShade (x, y, role)
332{
333 if (isTopRole(role))
334 {
335 // Full magenta top — replaced in-game by ground sample shader.
336 return rgba(255, 0, 255);
337 }
338 if (role === "O")
339 {
340 const d = dirtAt(x, y);
341 return mulRgb(d, 0.35);
342 }
343 const d = dirtAt(x, y);
344 return mulRgb(d, faceLit(role));
345}
346
347function paintPixel (variant, prefix, g, x, y)
348{
349 const role = roleOf(prefix, g);
350 if (!role)
351 {
352 // Unknown grey: luminance fallback toward mid face.
353 const lit = g / 128;
354 if (variant === "wood")
355 { return rgba(Math.round(140 * lit), 0, Math.round(140 * lit)); }
356 if (variant === "cliff")
357 { return mulRgb(dirtAt(x, y), lit); }
358 if (variant === "brick")
359 { return mulRgb(BRICK.T, lit); }
360 return mulRgb(COBBLE.T, lit);
361 }
362 if (variant === "cobble")
363 { return cobbleLike(COBBLE, x, y, role, 7); }
364 if (variant === "smooth")
365 { return cobbleLike(COBBLE, x, y, role, 31); }
366 if (variant === "brick")
367 { return brickShade(x, y, role); }
368 if (variant === "wood")
369 { return woodMagenta(role); }
370 if (variant === "cliff")
371 { return cliffShade(x, y, role); }
372 throw new Error(`Unknown variant ${variant}`);
373}
374
375function textureMask (rgbaIn, variant, shapePrefix)
376{
377 const out = new Uint8Array(SIZE * SIZE * 4);
378 for (let y = 0; y < SIZE; y++)
379 {
380 for (let x = 0; x < SIZE; x++)
381 {
382 const i = (y * SIZE + x) * 4;
383 if (rgbaIn[i + 3] === 0)
384 { continue; }
385 const color = paintPixel(variant, shapePrefix, rgbaIn[i], x, y);
386 out[i] = color[0];
387 out[i + 1] = color[1];
388 out[i + 2] = color[2];
389 out[i + 3] = 255;
390 }
391 }
392 return out;
393}
394
395const VARIANT_OUT = {
396 cobble: {
397 thick: { dir: "thick-stone-wall", named: true, prefix: "thick-stone-wall" },
398 thin: { dir: "thin-stone-wall", named: true, prefix: "thin-stone-wall" }
399 },
400 smooth: {
401 thick: { dir: "thick-smooth-stone-wall", named: true, prefix: "thick-smooth-stone-wall" },
402 thin: { dir: "thin-smooth-stone-wall", named: true, prefix: "thin-smooth-stone-wall" }
403 },
404 brick: {
405 thick: { dir: "thick-brick-wall", named: true, prefix: "thick-brick-wall" },
406 thin: { dir: "thin-brick-wall", named: true, prefix: "thin-brick-wall" }
407 },
408 wood: {
409 thick: { dir: "thick-wood-wall", named: false, prefix: "thick-stone-wall" },
410 thin: { dir: "thin-wood-wall", named: false, prefix: "thin-stone-wall" }
411 },
412 cliff: {
413 thick: { dir: "thick-cliff", named: true, prefix: "thick-cliff" },
414 thin: { dir: "thin-cliff", named: true, prefix: "thin-cliff" }
415 }
416};
417
418function shapeFiles (shapeKey)
419{
420 return readdirSync(EXAMPLES)
421 .filter((name) => name.startsWith(shapeKey) && name.endsWith(".png") && !name.includes("ref-"))
422 .sort();
423}
424
425function namedOutName (outPrefix, shapeName, shapeKey)
426{
427 // thick-stone-wall-esw.png → thick-smooth-stone-wall-esw.png
428 const suffix = shapeName.slice(shapeKey.length); // "" or "-esw"
429 return `${outPrefix}${suffix}`;
430}
431
432function bakeVariant (variant)
433{
434 const cfg = VARIANT_OUT[variant];
435 if (!cfg)
436 { throw new Error(`Unknown variant: ${variant}`); }
437 let wrote = 0;
438 for (const kind of ["thick", "thin"])
439 {
440 const shapeKey = `${kind}-stone-wall`;
441 const out = cfg[kind];
442 const outDir = join(ROOT, out.dir);
443 mkdirSync(outDir, { recursive: true });
444 const files = shapeFiles(shapeKey);
445 if (files.length !== 16)
446 { throw new Error(`Expected 16 ${shapeKey} masks, found ${files.length}`); }
447
448 if (out.named)
449 {
450 for (const name of files)
451 {
452 const shaped = decodePngRgba(join(EXAMPLES, name));
453 const textured = textureMask(shaped, variant, shapeKey);
454 const outName = namedOutName(out.prefix, name, shapeKey);
455 writeFileSync(join(outDir, outName), encodePng(textured));
456 wrote++;
457 }
458 }
459 else
460 {
461 // Material-connect: write 0.png … 15.png from matching named shapes.
462 for (let mask = 0; mask < 16; mask++)
463 {
464 const suffix = cardinalConnectionSuffix(mask);
465 const shapeName = suffix ? `${shapeKey}-${suffix}.png` : `${shapeKey}.png`;
466 const shaped = decodePngRgba(join(EXAMPLES, shapeName));
467 const textured = textureMask(shaped, variant, shapeKey);
468 writeFileSync(join(outDir, `${mask}.png`), encodePng(textured));
469 wrote++;
470 }
471 }
472 console.log(` ${variant} ${kind} → ${outDir} (${out.named ? "named" : "0–15"})`);
473 }
474 return wrote;
475}
476
477const arg = process.argv.find((a) => a.startsWith("--variant="));
478const variant = arg ? arg.slice("--variant=".length) : "cobble";
479const list = variant === "all"
480 ? ["cobble", "smooth", "brick", "wood", "cliff"]
481 : [variant];
482
483if (!existsSync(EXAMPLES))
484{ throw new Error(`Missing ${EXAMPLES}`); }
485
486let total = 0;
487for (const v of list)
488{
489 console.log(`Baking ${v}…`);
490 total += bakeVariant(v);
491}
492console.log(`Done (${total} sprites).`);