/** * Bake wall textures onto thick/thin greyscale face-id shape masks. * * Shape masks (greyscale face-IDs) belong in: * client/assets/blocks/_examples/stone-wall/{thick,thin}-stone-wall*.png * * Workflow when editing shapes in the live gameplay folders: * 1. Paint face-id greys in thick-stone-wall / thin-stone-wall * 2. node client/scripts/texture-wall-sprites.mjs --sync-shapes * (copies live → examples only if files are still face-id greyscale) * 3. node client/scripts/texture-wall-sprites.mjs --variant=… * * Usage: * node client/scripts/texture-wall-sprites.mjs --sync-shapes * node client/scripts/texture-wall-sprites.mjs --variant=cobble|smooth|brick|wood|cliff|--all * * cobble overwrites thick/thin-stone-wall — pass --force (required) so hand tweaks are not clobbered. */ import { mkdirSync, writeFileSync, readdirSync, readFileSync, existsSync, cpSync } from "node:fs"; import { deflateSync, inflateSync } from "node:zlib"; import { fileURLToPath } from "node:url"; import { dirname, join } from "node:path"; import { cardinalConnectionSuffix } from "../../shared/world/neighborConnect.js"; const SIZE = 16; const ROOT = join(dirname(fileURLToPath(import.meta.url)), "../assets/blocks"); const EXAMPLES = join(ROOT, "_examples/stone-wall"); const GROUNDS = join(dirname(fileURLToPath(import.meta.url)), "../assets/grounds"); const THICK_ROLE = { 0xaf: "N", 0x95: "W", 0x80: "T", 0x6c: "E", 0x54: "S", 0x40: "O" }; const THIN_ROLE = { 0xb6: "W", 0x95: "N", 0x80: "E", 0x73: "S", 0x40: "O" }; function roleOf (prefix, g) { const map = prefix.startsWith("thin") ? THIN_ROLE : THICK_ROLE; return map[g] ?? null; } function isTopRole (role) { return role === "T" || role === "N"; } function crcTable () { const table = new Uint32Array(256); for (let n = 0; n < 256; n++) { let c = n; for (let k = 0; k < 8; k++) { c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1); } table[n] = c >>> 0; } return table; } const CRC_TABLE = crcTable(); function crc32 (buf) { let c = 0xffffffff; for (let i = 0; i < buf.length; i++) { c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8); } return (c ^ 0xffffffff) >>> 0; } function chunk (type, data) { const len = Buffer.alloc(4); len.writeUInt32BE(data.length); const typeBuf = Buffer.from(type, "ascii"); const crcBuf = Buffer.alloc(4); crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data]))); return Buffer.concat([len, typeBuf, data, crcBuf]); } function encodePng (rgba) { const raw = Buffer.alloc((SIZE * 4 + 1) * SIZE); for (let y = 0; y < SIZE; y++) { const row = y * (SIZE * 4 + 1); raw[row] = 0; for (let x = 0; x < SIZE; x++) { const i = (y * SIZE + x) * 4; const o = row + 1 + x * 4; raw[o] = rgba[i]; raw[o + 1] = rgba[i + 1]; raw[o + 2] = rgba[i + 2]; raw[o + 3] = rgba[i + 3]; } } const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(SIZE, 0); ihdr.writeUInt32BE(SIZE, 4); ihdr[8] = 8; ihdr[9] = 6; return Buffer.concat([ Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk("IHDR", ihdr), chunk("IDAT", deflateSync(raw, { level: 9 })), chunk("IEND", Buffer.alloc(0)) ]); } function decodePngRgba (path) { const buf = readFileSync(path); let off = 8; let w = 0; let h = 0; let colorType = 6; const idat = []; while (off < buf.length) { const len = buf.readUInt32BE(off); const type = buf.slice(off + 4, off + 8).toString("ascii"); const data = buf.slice(off + 8, off + 8 + len); if (type === "IHDR") { w = data.readUInt32BE(0); h = data.readUInt32BE(4); colorType = data[9]; } else if (type === "IDAT") { idat.push(data); } else if (type === "IEND") { break; } off += 12 + len; } const channels = colorType === 2 ? 3 : colorType === 6 ? 4 : 0; if (!channels) { throw new Error(`${path}: unsupported PNG color type ${colorType}`); } const inflated = inflateSync(Buffer.concat(idat)); const rgba = new Uint8Array(w * h * 4); let src = 0; const prevRow = new Uint8Array(w * channels); const curRow = new Uint8Array(w * channels); for (let y = 0; y < h; y++) { const filter = inflated[src++]; for (let i = 0; i < w * channels; i++) { let v = inflated[src++]; if (filter === 1) { v = (v + (i >= channels ? curRow[i - channels] : 0)) & 255; } else if (filter === 2) { v = (v + prevRow[i]) & 255; } else if (filter === 3) { const a = i >= channels ? curRow[i - channels] : 0; v = (v + Math.floor((a + prevRow[i]) / 2)) & 255; } else if (filter === 4) { const a = i >= channels ? curRow[i - channels] : 0; const b = prevRow[i]; const c = i >= channels ? prevRow[i - channels] : 0; const p = a + b - c; const pa = Math.abs(p - a); const pb = Math.abs(p - b); const pc = Math.abs(p - c); v = (v + (pa <= pb && pa <= pc ? a : pb <= pc ? b : c)) & 255; } curRow[i] = v; } for (let x = 0; x < w; x++) { const si = x * channels; const di = (y * w + x) * 4; rgba[di] = curRow[si]; rgba[di + 1] = curRow[si + 1]; rgba[di + 2] = curRow[si + 2]; rgba[di + 3] = channels === 4 ? curRow[si + 3] : 255; } prevRow.set(curRow); } if (w !== SIZE || h !== SIZE) { throw new Error(`${path}: expected ${SIZE}×${SIZE}, got ${w}×${h}`); } return rgba; } function hash2 (x, y) { let n = (x * 374761393 + y * 668265263) | 0; n = (n ^ (n >>> 13)) * 1274126177; return (n ^ (n >>> 16)) >>> 0; } function rgba (r, g, b, a = 255) { return [r, g, b, a]; } function mulRgb (c, factor) { return rgba( Math.min(255, Math.round(c[0] * factor)), Math.min(255, Math.round(c[1] * factor)), Math.min(255, Math.round(c[2] * factor)), c[3] ?? 255 ); } function mixRgb (a, b, t) { return rgba( Math.round(a[0] + (b[0] - a[0]) * t), Math.round(a[1] + (b[1] - a[1]) * t), Math.round(a[2] + (b[2] - a[2]) * t), 255 ); } /** Face role → lighting factor (NW light). */ const ROLE_LIT = { N: 1.15, W: 1.0, T: 1.05, E: 0.82, S: 0.62, O: 0.45 }; function faceLit (role) { return ROLE_LIT[role] ?? 0.9; } function loadDirt () { const path = join(GROUNDS, "dirt/dirt.png"); if (!existsSync(path)) { throw new Error(`Missing dirt texture: ${path}`); } return decodePngRgba(path); } let dirtRgba = null; function dirtAt (x, y) { if (!dirtRgba) { dirtRgba = loadDirt(); } const i = ((y & 15) * SIZE + (x & 15)) * 4; return rgba(dirtRgba[i], dirtRgba[i + 1], dirtRgba[i + 2]); } /* ---- palettes ---- */ const COBBLE = { N: rgba(198, 198, 202), W: rgba(132, 132, 136), T: rgba(168, 168, 172), E: rgba(112, 112, 116), S: rgba(88, 88, 92), O: rgba(70, 70, 74), mortar: rgba(78, 78, 82), hiN: rgba(210, 210, 214), loS: rgba(78, 78, 82) }; const BRICK = { N: rgba(196, 92, 72), W: rgba(168, 72, 56), T: rgba(178, 78, 60), E: rgba(148, 58, 46), S: rgba(118, 48, 38), O: rgba(72, 36, 30), mortar: rgba(92, 78, 68), hi: rgba(210, 110, 88), lo: rgba(100, 42, 34), /** Flat cement cap (no brick bond on tops). */ cement: rgba(168, 160, 152), cementHi: rgba(184, 176, 168), cementLo: rgba(148, 140, 132) }; function cobbleLike (basePal, x, y, role, gritMask) { if (role === "O") { const h = hash2(x, y); return (h & 15) === 0 ? basePal.mortar : basePal.O; } const base = basePal[role] ?? basePal.T; const h = hash2(x, y); const speck = h & gritMask; if (speck === 0) { return basePal.mortar; } if (gritMask === 7) { if (speck === 1 || speck === 2) { return role === "N" || role === "T" ? (basePal.hiN ?? basePal.hi ?? mulRgb(base, 1.12)) : (basePal.hi ?? mulRgb(base, 1.1)); } if (speck === 3) { return role === "S" ? (basePal.loS ?? basePal.lo ?? mulRgb(base, 0.88)) : (basePal.lo ?? mulRgb(base, 0.9)); } } else if (gritMask === 31) { // Smooth: rare soft variation only. if (speck === 1) { return mulRgb(base, 1.06); } if (speck === 2) { return mulRgb(base, 0.94); } } return base; } /** * Brick mortar follows each face: * - T (thick) / N (thin ridge): flat cement cap * - S: running bond elevation * - N (thick bevel): vertical joints along the rim * - W / E: diagonal course marks — outer column 1px below inner */ function brickShade (x, y, role, shapePrefix, faceRgba) { if (role === "O") { return BRICK.O; } const thin = shapePrefix.startsWith("thin"); const isCap = role === "T" || (thin && role === "N"); if (isCap) { const h = hash2(x, y); if ((h & 31) === 0) { return BRICK.cementHi; } if ((h & 31) === 1) { return BRICK.cementLo; } return BRICK.cement; } const courseH = 4; const brickW = 6; let onMortar = false; if (role === "W" || role === "E") { const phase = y % courseH; const outer = role === "W" ? !isSameFace(faceRgba, x - 1, y, role, shapePrefix) : !isSameFace(faceRgba, x + 1, y, role, shapePrefix); // Diagonal: ·O then O· on west (outer 1px down); mirrored on east. if (phase === 0) { onMortar = !outer; } else if (phase === 1) { onMortar = outer; } } else if (role === "N") { onMortar = (x % brickW) === 0; } else { const row = Math.floor(y / courseH); const brickX = x + (row & 1) * Math.floor(brickW / 2); onMortar = (y % courseH) === 0 || (brickX % brickW) === 0; } if (onMortar) { return BRICK.mortar; } const h = hash2(x + role.charCodeAt(0) * 17, y); if ((h & 15) === 0) { return BRICK.hi; } if ((h & 15) === 1) { return BRICK.lo; } return BRICK[role] ?? BRICK.T; } function isSameFace (faceRgba, x, y, role, shapePrefix) { if (x < 0 || y < 0 || x >= SIZE || y >= SIZE || !faceRgba) { return false; } const i = (y * SIZE + x) * 4; if (faceRgba[i + 3] === 0) { return false; } return roleOf(shapePrefix, faceRgba[i]) === role; } function woodMagenta (role) { // Flat fallback (role only) — prefer woodShade for textured planks. const L = { O: 55, S: 95, E: 113, W: 143, T: 177, N: 205 }[role] ?? 140; const gHi = role === "N" || role === "T" ? Math.min(L - 20, 50) : 0; return rgba(L, gHi, L); } /** Magenta (R=B, G name.startsWith(shapeKey) && name.endsWith(".png") && !name.includes("ref-")) .sort(); } function namedOutName (outPrefix, shapeName, shapeKey) { // thick-stone-wall-esw.png → thick-smooth-stone-wall-esw.png const suffix = shapeName.slice(shapeKey.length); // "" or "-esw" return `${outPrefix}${suffix}`; } const FACE_ID_GREYS = new Set([ 0x40, 0x54, 0x6c, 0x73, 0x80, 0x95, 0xaf, 0xb6 ]); function isFaceIdMask (rgba) { for (let i = 0; i < rgba.length; i += 4) { if (rgba[i + 3] === 0) { continue; } if (rgba[i] !== rgba[i + 1] || rgba[i] !== rgba[i + 2]) { return false; } if (!FACE_ID_GREYS.has(rgba[i])) { return false; } } return true; } /** Copy face-id greyscale from live thick/thin-stone-wall → _examples (never textured art). */ function syncShapesFromLive () { mkdirSync(EXAMPLES, { recursive: true }); let copied = 0; for (const kind of ["thick", "thin"]) { const shapeKey = `${kind}-stone-wall`; const liveDir = join(ROOT, shapeKey); if (!existsSync(liveDir)) { throw new Error(`Missing live folder ${liveDir}`); } const files = readdirSync(liveDir) .filter((name) => name.startsWith(shapeKey) && name.endsWith(".png")) .sort(); if (files.length !== 16) { throw new Error(`Expected 16 live ${shapeKey} sprites, found ${files.length}`); } for (const name of files) { const rgba = decodePngRgba(join(liveDir, name)); if (!isFaceIdMask(rgba)) { throw new Error( `${shapeKey}/${name} is not a face-id greyscale mask (already textured?). ` + `Paint face-id greys in the live folder, then re-run --sync-shapes.` ); } cpSync(join(liveDir, name), join(EXAMPLES, name)); copied++; } console.log(` synced ${kind} → ${EXAMPLES}`); } console.log(`Synced ${copied} face-id masks into examples.`); } function bakeVariant (variant, { force = false } = {}) { const cfg = VARIANT_OUT[variant]; if (!cfg) { throw new Error(`Unknown variant: ${variant}`); } if (variant === "cobble" && !force) { throw new Error( "Refusing to overwrite thick/thin-stone-wall without --force " + "(hand-tweaked gameplay sprites). Sync shapes with --sync-shapes first if needed." ); } let wrote = 0; for (const kind of ["thick", "thin"]) { const out = cfg[kind]; if (!out) { continue; } const shapeKey = `${kind}-stone-wall`; const outDir = join(ROOT, out.dir); mkdirSync(outDir, { recursive: true }); const files = shapeFiles(shapeKey); if (files.length !== 16) { throw new Error(`Expected 16 ${shapeKey} masks, found ${files.length}`); } if (out.named) { for (const name of files) { const shaped = decodePngRgba(join(EXAMPLES, name)); const textured = textureMask(shaped, variant, shapeKey); const outName = namedOutName(out.prefix, name, shapeKey); writeFileSync(join(outDir, outName), encodePng(textured)); wrote++; } } else { for (let mask = 0; mask < 16; mask++) { const suffix = cardinalConnectionSuffix(mask); const shapeName = suffix ? `${shapeKey}-${suffix}.png` : `${shapeKey}.png`; const shaped = decodePngRgba(join(EXAMPLES, shapeName)); const textured = textureMask(shaped, variant, shapeKey); writeFileSync(join(outDir, `${mask}.png`), encodePng(textured)); wrote++; } } console.log(` ${variant} ${kind} → ${outDir} (${out.named ? "named" : "0–15"})`); } return wrote; } if (process.argv.includes("--sync-shapes")) { syncShapesFromLive(); process.exit(0); } const arg = process.argv.find((a) => a.startsWith("--variant=")); const variant = arg ? arg.slice("--variant=".length) : null; if (!variant) { console.error("Usage: --sync-shapes | --variant=cobble|smooth|brick|wood|cliff|all [--force]"); process.exit(1); } const force = process.argv.includes("--force"); const list = variant === "all" ? ["cobble", "smooth", "brick", "wood", "cliff"] : [variant]; if (!existsSync(EXAMPLES)) { throw new Error(`Missing ${EXAMPLES}`); } let total = 0; for (const v of list) { console.log(`Baking ${v}…`); total += bakeVariant(v, { force }); } console.log(`Done (${total} sprites).`);