Merge branch 'feature/thin-thick-stone-walls'
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
@@ -0,0 +1,120 @@
#!/usr/bin/env python3
"""Export face-id / heightmap / upscaled refs from thick-stone-wall alone.
Run from repo root:
python3 client/scripts/export-thick-wall-refs.py
Requires: Pillow
"""
from __future__ import annotations
from pathlib import Path
from PIL import Image, ImageDraw
ROOT = Path(__file__).resolve().parents[1]
ALONE = ROOT / "assets/blocks/_examples/stone-wall/thick-stone-wall.png"
OUT = ROOT / "assets/blocks/_examples/stone-wall"
# Source greys → semantic face roles (see docs/STONE_WALL_SHAPES.md)
FACE_RGB = {
(175, 175, 175): (255, 255, 255), # N bevel
(149, 149, 149): (220, 60, 60), # W face
(108, 108, 108): (60, 100, 220), # E face
(84, 84, 84): (60, 180, 80), # S face
(128, 128, 128): (220, 180, 60), # top plateau
(64, 64, 64): (20, 20, 20), # outline
}
HEIGHT = {
(64, 64, 64): 40,
(84, 84, 84): 80,
(108, 108, 108): 140,
(149, 149, 149): 160,
(128, 128, 128): 200,
(175, 175, 175): 220,
}
def main() -> None:
OUT.mkdir(parents=True, exist_ok=True)
alone = Image.open(ALONE).convert("RGBA")
w, h = alone.size
face = Image.new("RGBA", (w, h), (0, 0, 0, 0))
height = Image.new("L", (w, h), 0)
for y in range(h):
for x in range(w):
r, g, b, a = alone.getpixel((x, y))
if a == 0:
continue
key = (r, g, b)
if key not in FACE_RGB:
raise SystemExit(f"Unknown grey {key} at ({x},{y})")
fr, fg, fb = FACE_RGB[key]
face.putpixel((x, y), (fr, fg, fb, 255))
height.putpixel((x, y), HEIGHT[key])
face.save(OUT / "ref-thick-face-id-16.png")
face.resize((w * 16, h * 16), Image.NEAREST).save(OUT / "ref-thick-face-id-256.png")
height.save(OUT / "ref-thick-height-16.png")
height.resize((w * 16, h * 16), Image.NEAREST).save(OUT / "ref-thick-height-256.png")
alone.resize((w * 16, h * 16), Image.NEAREST).save(OUT / "ref-thick-alone-256.png")
leg = Image.new("RGBA", (280, 200), (30, 30, 30, 255))
d = ImageDraw.Draw(leg)
items = [
((255, 255, 255), "North bevel 0xAF"),
((220, 60, 60), "West face 0x95"),
((60, 100, 220), "East face 0x6C"),
((60, 180, 80), "South face 0x54"),
((220, 180, 60), "Top plateau 0x80"),
((20, 20, 20), "Outline 0x40"),
]
for i, (c, label) in enumerate(items):
yy = 16 + i * 28
d.rectangle([16, yy, 40, yy + 20], fill=(*c, 255))
d.text((52, yy + 2), label, fill=(230, 230, 230, 255))
leg.save(OUT / "ref-thick-face-legend.png")
# Labeled contact sheet of all 16 thick *shape* states (bit order).
wall_dir = OUT
names = [
("alone", "thick-stone-wall.png"),
("n", "thick-stone-wall-n.png"),
("e", "thick-stone-wall-e.png"),
("ne", "thick-stone-wall-ne.png"),
("s", "thick-stone-wall-s.png"),
("ns", "thick-stone-wall-ns.png"),
("es", "thick-stone-wall-es.png"),
("nes", "thick-stone-wall-nes.png"),
("w", "thick-stone-wall-w.png"),
("wn", "thick-stone-wall-wn.png"),
("we", "thick-stone-wall-we.png"),
("wne", "thick-stone-wall-wne.png"),
("sw", "thick-stone-wall-sw.png"),
("swn", "thick-stone-wall-swn.png"),
("esw", "thick-stone-wall-esw.png"),
("nesw", "thick-stone-wall-nesw.png"),
]
scale, pad, label_h, cols = 8, 28, 14, 4
cell = 16 * scale
rows = 4
sheet_w = cols * cell + (cols + 1) * pad
sheet_h = rows * (cell + label_h) + (rows + 1) * pad
sheet = Image.new("RGBA", (sheet_w, sheet_h), (24, 24, 28, 255))
draw = ImageDraw.Draw(sheet)
for i, (label, fname) in enumerate(names):
r, c = divmod(i, cols)
x = pad + c * (cell + pad)
y = pad + r * (cell + label_h + pad)
im = Image.open(wall_dir / fname).convert("RGBA").resize((cell, cell), Image.NEAREST)
sheet.paste(im, (x, y), im)
draw.text((x, y + cell + 2), label, fill=(220, 220, 220, 255))
sheet.save(OUT / "ref-thick-all-variants.png")
print(f"Wrote refs to {OUT}")
if __name__ == "__main__":
main()
@@ -0,0 +1,120 @@#!/usr/bin/env python3"""Export face-id / heightmap / upscaled refs from thick-stone-wall alone.Run from repo root: python3 client/scripts/export-thick-wall-refs.pyRequires: Pillow"""from __future__ import annotationsfrom pathlib import Pathfrom PIL import Image, ImageDrawROOT = Path(__file__).resolve().parents[1]ALONE = ROOT / "assets/blocks/_examples/stone-wall/thick-stone-wall.png"OUT = ROOT / "assets/blocks/_examples/stone-wall"# Source greys → semantic face roles (see docs/STONE_WALL_SHAPES.md)FACE_RGB = { (175, 175, 175): (255, 255, 255), # N bevel (149, 149, 149): (220, 60, 60), # W face (108, 108, 108): (60, 100, 220), # E face (84, 84, 84): (60, 180, 80), # S face (128, 128, 128): (220, 180, 60), # top plateau (64, 64, 64): (20, 20, 20), # outline}HEIGHT = { (64, 64, 64): 40, (84, 84, 84): 80, (108, 108, 108): 140, (149, 149, 149): 160, (128, 128, 128): 200, (175, 175, 175): 220,}def main() -> None: OUT.mkdir(parents=True, exist_ok=True) alone = Image.open(ALONE).convert("RGBA") w, h = alone.size face = Image.new("RGBA", (w, h), (0, 0, 0, 0)) height = Image.new("L", (w, h), 0) for y in range(h): for x in range(w): r, g, b, a = alone.getpixel((x, y)) if a == 0: continue key = (r, g, b) if key not in FACE_RGB: raise SystemExit(f"Unknown grey {key} at ({x},{y})") fr, fg, fb = FACE_RGB[key] face.putpixel((x, y), (fr, fg, fb, 255)) height.putpixel((x, y), HEIGHT[key]) face.save(OUT / "ref-thick-face-id-16.png") face.resize((w * 16, h * 16), Image.NEAREST).save(OUT / "ref-thick-face-id-256.png") height.save(OUT / "ref-thick-height-16.png") height.resize((w * 16, h * 16), Image.NEAREST).save(OUT / "ref-thick-height-256.png") alone.resize((w * 16, h * 16), Image.NEAREST).save(OUT / "ref-thick-alone-256.png") leg = Image.new("RGBA", (280, 200), (30, 30, 30, 255)) d = ImageDraw.Draw(leg) items = [ ((255, 255, 255), "North bevel 0xAF"), ((220, 60, 60), "West face 0x95"), ((60, 100, 220), "East face 0x6C"), ((60, 180, 80), "South face 0x54"), ((220, 180, 60), "Top plateau 0x80"), ((20, 20, 20), "Outline 0x40"), ] for i, (c, label) in enumerate(items): yy = 16 + i * 28 d.rectangle([16, yy, 40, yy + 20], fill=(*c, 255)) d.text((52, yy + 2), label, fill=(230, 230, 230, 255)) leg.save(OUT / "ref-thick-face-legend.png") # Labeled contact sheet of all 16 thick *shape* states (bit order). wall_dir = OUT names = [ ("alone", "thick-stone-wall.png"), ("n", "thick-stone-wall-n.png"), ("e", "thick-stone-wall-e.png"), ("ne", "thick-stone-wall-ne.png"), ("s", "thick-stone-wall-s.png"), ("ns", "thick-stone-wall-ns.png"), ("es", "thick-stone-wall-es.png"), ("nes", "thick-stone-wall-nes.png"), ("w", "thick-stone-wall-w.png"), ("wn", "thick-stone-wall-wn.png"), ("we", "thick-stone-wall-we.png"), ("wne", "thick-stone-wall-wne.png"), ("sw", "thick-stone-wall-sw.png"), ("swn", "thick-stone-wall-swn.png"), ("esw", "thick-stone-wall-esw.png"), ("nesw", "thick-stone-wall-nesw.png"), ] scale, pad, label_h, cols = 8, 28, 14, 4 cell = 16 * scale rows = 4 sheet_w = cols * cell + (cols + 1) * pad sheet_h = rows * (cell + label_h) + (rows + 1) * pad sheet = Image.new("RGBA", (sheet_w, sheet_h), (24, 24, 28, 255)) draw = ImageDraw.Draw(sheet) for i, (label, fname) in enumerate(names): r, c = divmod(i, cols) x = pad + c * (cell + pad) y = pad + r * (cell + label_h + pad) im = Image.open(wall_dir / fname).convert("RGBA").resize((cell, cell), Image.NEAREST) sheet.paste(im, (x, y), im) draw.text((x, y + cell + 2), label, fill=(220, 220, 220, 255)) sheet.save(OUT / "ref-thick-all-variants.png") print(f"Wrote refs to {OUT}")if __name__ == "__main__": main()@@ -1,39 +1,43 @@
/**
* Generate 16×16 gray cobblestone stone-wall PNGs for neighbor-connect masks 0–15.
* Generate thin + thick stone-wall PNGs for the 16 cardinal neighbor masks.
*
* Truncated-pyramid / frustum look when alone or at free ends. Connected runs use a
* constant cross-section extruded to the tile edge (strip-union like tables/fences)
* so N/S and E/W seams match.
* Naming: `{key}.png` alone, `{key}-{suffix}.png` when connected.
* Suffixes: n/e/s/w, ns, we, ne/es/sw/wn, esw/wne/swn/nes, nesw.
*
* Examples (shape only, no texture) live in
* client/assets/blocks/_examples/stone-wall/
*
* node client/scripts/generate-stone-wall-sprites.mjs
*/
import { mkdirSync, writeFileSync } from "node:fs";
import { deflateSync } from "node:zlib";
import
{
mkdirSync,
writeFileSync,
readdirSync,
unlinkSync,
readFileSync,
existsSync,
cpSync,
rmSync
} from "node:fs";
import { deflateSync, inflateSync } from "node:zlib";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
import { NeighborBit } from "../../shared/world/neighborConnect.js";
import
{
NeighborBit,
cardinalConnectionSuffix,
composeNamedNeighborConnectState
} from "../../shared/world/neighborConnect.js";
const SIZE = 16;
const OUT = join(dirname(fileURLToPath(import.meta.url)), "../assets/blocks/stone-wall");
const TOP = [168, 168, 172, 255];
const TOP_HI = [198, 198, 202, 255];
const TOP_LO = [140, 140, 144, 255];
const FACE = [112, 112, 116, 255];
const FACE_HI = [132, 132, 136, 255];
const FACE_LO = [88, 88, 92, 255];
const EDGE = [70, 70, 74, 255];
const MORTAR = [78, 78, 82, 255];
/** Constant core used for connected runs (must meet neighbour tile edges cleanly). */
const CORE_X0 = 5;
const CORE_X1 = 10;
const TOP_Y0 = 3;
const TOP_Y1 = 6;
const FACE_Y1 = 12;
/** Alone / free-end base is wider than the top (frustum). */
const BASE_X0 = 3;
const BASE_X1 = 12;
const ROOT = join(dirname(fileURLToPath(import.meta.url)), "../assets/blocks");
const EXAMPLES = join(ROOT, "_examples/stone-wall");
const OUT_THICK = join(ROOT, "thick-stone-wall");
const OUT_THIN = join(ROOT, "thin-stone-wall");
const THICK = { key: "thick-stone-wall", neighborConnect: true, neighborConnectNamed: true };
const THIN = { key: "thin-stone-wall", neighborConnect: true, neighborConnectNamed: true };
function crcTable ()
{
@@ -98,6 +102,90 @@ function encodePng (rgba)
]);
}
function decodePngRgba (path)
{
const buf = readFileSync(path);
let off = 8;
let w = 0;
let h = 0;
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);
if (data[8] !== 8 || data[9] !== 6)
{ throw new Error(`${path}: expected 8-bit RGBA`); }
}
else if (type === "IDAT")
{ idat.push(data); }
else if (type === "IEND")
{ break; }
off += 12 + len;
}
const raw = inflateSync(Buffer.concat(idat));
const bpp = 4;
const stride = w * bpp;
const rgba = new Uint8ClampedArray(w * h * 4);
let src = 0;
const prev = Buffer.alloc(stride);
const cur = Buffer.alloc(stride);
for (let y = 0; y < h; y++)
{
const filter = raw[src++];
for (let i = 0; i < stride; i++)
{ cur[i] = raw[src++]; }
for (let i = 0; i < stride; i++)
{
const left = i >= bpp ? cur[i - bpp] : 0;
const up = prev[i];
const upLeft = i >= bpp ? prev[i - bpp] : 0;
let val = cur[i];
if (filter === 1)
{ val = (val + left) & 255; }
else if (filter === 2)
{ val = (val + up) & 255; }
else if (filter === 3)
{ val = (val + ((left + up) >> 1)) & 255; }
else if (filter === 4)
{
const p = left + up - upLeft;
const pa = Math.abs(p - left);
const pb = Math.abs(p - up);
const pc = Math.abs(p - upLeft);
const pr = (pa <= pb && pa <= pc) ? left : (pb <= pc ? up : upLeft);
val = (val + pr) & 255;
}
cur[i] = val;
}
rgba.set(cur, y * stride);
prev.set(cur);
}
if (w !== SIZE || h !== SIZE)
{ throw new Error(`${path}: expected ${SIZE}×${SIZE}, got ${w}×${h}`); }
return rgba;
}
function loadExample (name)
{
const path = join(EXAMPLES, name);
if (!existsSync(path))
{ return null; }
return decodePngRgba(path);
}
function getPx (rgba, x, y)
{
if (x < 0 || y < 0 || x >= SIZE || y >= SIZE)
{ return [0, 0, 0, 0]; }
const i = (y * SIZE + x) * 4;
return [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]];
}
function setPx (rgba, x, y, color)
{
if (x < 0 || y < 0 || x >= SIZE || y >= SIZE)
@@ -109,148 +197,250 @@ function setPx (rgba, x, y, color)
rgba[i + 3] = color[3];
}
/** Frustum half-width in X at row y (alone / free-end silhouette). */
function frustumX0X1 (y)
function opaque (rgba, x, y)
{
if (y <= TOP_Y1)
{ return { x0: CORE_X0, x1: CORE_X1 }; }
if (y >= FACE_Y1)
{ return { x0: BASE_X0, x1: BASE_X1 }; }
const t = (y - TOP_Y1) / (FACE_Y1 - TOP_Y1);
const x0 = Math.round(CORE_X0 + (BASE_X0 - CORE_X0) * t);
const x1 = Math.round(CORE_X1 + (BASE_X1 - CORE_X1) * t);
return { x0, x1 };
return getPx(rgba, x, y)[3] > 128;
}
/**
* Strip-union with constant core thickness on connected sides.
* Free ends keep the frustum taper so alone / stubs still read as 3D.
*/
function inWall (x, y, connectN, connectE, connectS, connectW)
function copyRgba (rgba)
{
return new Uint8ClampedArray(rgba);
}
function clearRgba ()
{
const alone = !connectN && !connectE && !connectS && !connectW;
const wantH = alone || connectE || connectW;
const wantV = alone || connectN || connectS;
return new Uint8ClampedArray(SIZE * SIZE * 4);
}
if (wantH)
function mirrorX (rgba)
{
const out = clearRgba();
for (let y = 0; y < SIZE; y++)
{
const y0 = connectN ? 0 : TOP_Y0;
const y1 = connectS ? SIZE - 1 : FACE_Y1;
if (y >= y0 && y <= y1)
{
const { x0: fx0, x1: fx1 } = frustumX0X1(Math.min(FACE_Y1, Math.max(TOP_Y0, y)));
// Connected cardinals run to the tile edge (constant seam).
// Free ends keep the frustum taper.
const x0 = connectW ? 0 : fx0;
const x1 = connectE ? SIZE - 1 : fx1;
if (x >= x0 && x <= x1)
{ return true; }
}
for (let x = 0; x < SIZE; x++)
{ setPx(out, x, y, getPx(rgba, SIZE - 1 - x, y)); }
}
return out;
}
if (wantV)
function blit (dst, src)
{
if (!src)
{ return; }
for (let y = 0; y < SIZE; y++)
{
const x0 = CORE_X0;
const x1 = CORE_X1;
if (x >= x0 && x <= x1)
for (let x = 0; x < SIZE; x++)
{
const y0 = connectN ? 0 : TOP_Y0;
const y1 = connectS ? SIZE - 1 : FACE_Y1;
if (y >= y0 && y <= y1)
{ return true; }
const c = getPx(src, x, y);
if (c[3] > 128)
{ setPx(dst, x, y, c); }
}
}
return false;
}
function hash2 (x, y)
/** Ensure example folder exists; migrate from legacy stone-wall/ if needed. */
function ensureExamples ()
{
let n = (x * 374761393 + y * 668265263) | 0;
n = (n ^ (n >>> 13)) * 1274126177;
return (n ^ (n >>> 16)) >>> 0;
}
function cobbleShade (base, x, y)
{
const h = hash2(x, y);
const speck = (h & 7);
if (speck === 0)
{ return MORTAR; }
if (speck === 1 || speck === 2)
{ return base === TOP || base === TOP_HI || base === TOP_LO ? TOP_HI : FACE_HI; }
if (speck === 3)
{ return base === TOP || base === TOP_HI || base === TOP_LO ? TOP_LO : FACE_LO; }
return base;
mkdirSync(EXAMPLES, { recursive: true });
const legacy = join(ROOT, "stone-wall");
if (!existsSync(legacy))
{ return; }
for (const name of readdirSync(legacy))
{
if (!name.startsWith("example-") || !name.endsWith(".png"))
{ continue; }
const dest = join(EXAMPLES, name);
if (!existsSync(dest))
{ cpSync(join(legacy, name), dest); }
}
}
function isTopRow (y, connectN)
function buildPack (kind)
{
if (connectN)
{ return y <= TOP_Y1; }
return y >= TOP_Y0 && y <= TOP_Y1;
}
const alone = loadExample(`example-stone-${kind}.png`);
const east = loadExample(`example-stone-${kind}-connecting.png`);
const north = loadExample(`example-stone-${kind}-connecting-up.png`);
const south = loadExample(`example-stone-${kind}-connecting-down.png`);
const ns = loadExample(`example-stone-${kind}-connecting-updown.png`);
const ellNE = loadExample(`example-stone-${kind}-connecting-L.png`);
const ellSE = loadExample(`example-stone-${kind}-connecting-Ldownright.png`);
const teeESW = loadExample(`example-stone-${kind}-T.png`)
?? loadExample(`example-stone-${kind}-connecting-T.png`);
const teeNEW = loadExample(`example-stone-${kind}-connecting-T-upsidedown.png`);
function paintWall (mask)
{
const rgba = new Uint8Array(SIZE * SIZE * 4);
const connectN = (mask & NeighborBit.n) !== 0;
const connectE = (mask & NeighborBit.e) !== 0;
const connectS = (mask & NeighborBit.s) !== 0;
const connectW = (mask & NeighborBit.w) !== 0;
if (!alone || !east || !north || !ns)
{ throw new Error(`Missing core ${kind} examples in ${EXAMPLES}`); }
for (let y = 0; y < SIZE; y++)
const west = mirrorX(east);
const southFinal = south ?? (() =>
{
for (let x = 0; x < SIZE; x++)
const out = copyRgba(alone);
for (let y = 10; y < SIZE; y++)
{
if (!inWall(x, y, connectN, connectE, connectS, connectW))
{ continue; }
for (let x = 0; x < SIZE; x++)
{
if (opaque(ns, x, y))
{ setPx(out, x, y, getPx(ns, x, y)); }
}
}
return out;
})();
const n = inWall(x, y - 1, connectN, connectE, connectS, connectW);
const e = inWall(x + 1, y, connectN, connectE, connectS, connectW);
const s = inWall(x, y + 1, connectN, connectE, connectS, connectW);
const w = inWall(x - 1, y, connectN, connectE, connectS, connectW);
const ellNEFinal = ellNE ?? (() =>
{
const out = clearRgba();
blit(out, north);
blit(out, east);
return out;
})();
const ellSEFinal = ellSE ?? (() =>
{
const out = clearRgba();
blit(out, southFinal);
blit(out, east);
return out;
})();
const ellNW = mirrorX(ellNEFinal);
const ellSW = mirrorX(ellSEFinal);
let base;
if (isTopRow(y, connectN))
const ew = (() =>
{
const out = clearRgba();
blit(out, east);
blit(out, west);
for (let y = 0; y < SIZE; y++)
{
if (!opaque(east, SIZE - 1, y))
{ continue; }
let fill = null;
for (let x = SIZE - 1; x >= 0; x--)
{
if (!n)
{ base = TOP_HI; }
else if (!s && y === TOP_Y1)
{ base = TOP_LO; }
else
{ base = TOP; }
const c = getPx(east, x, y);
if (c[3] > 128)
{ fill = c; break; }
}
else
if (!fill)
{ continue; }
for (let x = 0; x < SIZE; x++)
{
if (!s)
{ base = FACE_LO; }
else if (!n)
{ base = FACE_HI; }
else
{ base = FACE; }
if (!opaque(out, x, y))
{ setPx(out, x, y, fill); }
}
}
return out;
})();
// Free side bevels (not on edges that continue into a neighbour).
const freeW = !w && !(connectW && x === 0);
const freeE = !e && !(connectE && x === SIZE - 1);
if (freeW || freeE)
{
if (base === TOP || base === TOP_HI)
{ base = TOP_LO; }
else if (base === FACE || base === FACE_HI)
{ base = EDGE; }
}
const teeESWFinal = teeESW ?? (() =>
{
const out = clearRgba();
blit(out, ew);
blit(out, southFinal);
return out;
})();
const teeNEWFinal = teeNEW ?? (() =>
{
const out = clearRgba();
blit(out, ew);
blit(out, north);
return out;
})();
const teeNES = (() =>
{
const out = clearRgba();
blit(out, north);
blit(out, east);
blit(out, southFinal);
return out;
})();
const teeNWS = mirrorX(teeNES);
const all = (() =>
{
const out = clearRgba();
blit(out, ns);
blit(out, ew);
return out;
})();
setPx(rgba, x, y, cobbleShade(base, x, y));
}
const byMask = new Map([
[0, alone],
[NeighborBit.n, north],
[NeighborBit.e, east],
[NeighborBit.s, southFinal],
[NeighborBit.w, west],
[NeighborBit.n | NeighborBit.s, ns],
[NeighborBit.e | NeighborBit.w, ew],
[NeighborBit.n | NeighborBit.e, ellNEFinal],
[NeighborBit.e | NeighborBit.s, ellSEFinal],
[NeighborBit.s | NeighborBit.w, ellSW],
[NeighborBit.w | NeighborBit.n, ellNW],
[NeighborBit.e | NeighborBit.s | NeighborBit.w, teeESWFinal],
[NeighborBit.w | NeighborBit.n | NeighborBit.e, teeNEWFinal],
[NeighborBit.n | NeighborBit.e | NeighborBit.s, teeNES],
[NeighborBit.n | NeighborBit.w | NeighborBit.s, teeNWS],
[NeighborBit.n | NeighborBit.e | NeighborBit.s | NeighborBit.w, all]
]);
return { byMask, alone, east, north, ns, ellNE: ellNEFinal };
}
function clearGenerated (dir)
{
mkdirSync(dir, { recursive: true });
for (const name of readdirSync(dir))
{
if (!name.endsWith(".png") || name.startsWith("example"))
{ continue; }
unlinkSync(join(dir, name));
}
return rgba;
}
mkdirSync(OUT, { recursive: true });
for (let mask = 0; mask < 16; mask++)
function writeSet (dir, def, pack)
{
writeFileSync(join(OUT, `${mask}.png`), encodePng(paintWall(mask)));
clearGenerated(dir);
for (let mask = 0; mask < 16; mask++)
{
const rgba = pack.byMask.get(mask);
if (!rgba)
{ throw new Error(`Missing mask ${mask} for ${def.key}`); }
const state = composeNamedNeighborConnectState(def, mask);
writeFileSync(join(dir, `${state}.png`), encodePng(rgba));
}
console.log(`Wrote 16 ${def.key} sprites → ${dir}`);
}
console.log(`Wrote cobblestone frustum stone-wall sprites 0–15 to ${OUT}`);
function removeLegacyFolders ()
{
for (const name of ["stone-wall", "stone-wall-thin"])
{
const dir = join(ROOT, name);
if (!existsSync(dir))
{ continue; }
// Keep examples only in _examples/; remove entire legacy folder.
rmSync(dir, { recursive: true, force: true });
console.log(`Removed legacy ${name}/`);
}
}
ensureExamples();
const thin = buildPack("thin");
const thick = buildPack("thick");
function assertSame (a, b, label)
{
for (let i = 0; i < a.length; i++)
{
if (a[i] !== b[i])
{ throw new Error(`Mismatch ${label}`); }
}
}
assertSame(thin.byMask.get(0), thin.alone, "thin alone");
assertSame(thin.byMask.get(1), thin.north, "thin n");
assertSame(thin.byMask.get(2), thin.east, "thin e");
assertSame(thin.byMask.get(5), thin.ns, "thin ns");
assertSame(thick.byMask.get(0), thick.alone, "thick alone");
writeSet(OUT_THIN, THIN, thin);
writeSet(OUT_THICK, THICK, thick);
removeLegacyFolders();
console.log("Suffixes:", [...Array(16)].map((_, m) => `${m}=${cardinalConnectionSuffix(m) || "(alone)"}`).join(", "));
@@ -1,39 +1,43 @@/**/** * Generate 16×16 gray cobblestone stone-wall PNGs for neighbor-connect masks 0–15. * Generate thin + thick stone-wall PNGs for the 16 cardinal neighbor masks. * * * Truncated-pyramid / frustum look when alone or at free ends. Connected runs use a * Naming: `{key}.png` alone, `{key}-{suffix}.png` when connected. * constant cross-section extruded to the tile edge (strip-union like tables/fences) * Suffixes: n/e/s/w, ns, we, ne/es/sw/wn, esw/wne/swn/nes, nesw. * so N/S and E/W seams match. * * Examples (shape only, no texture) live in * client/assets/blocks/_examples/stone-wall/ * * * node client/scripts/generate-stone-wall-sprites.mjs * node client/scripts/generate-stone-wall-sprites.mjs */ */import { mkdirSync, writeFileSync } from "node:fs";importimport { deflateSync } from "node:zlib"; { mkdirSync, writeFileSync, readdirSync, unlinkSync, readFileSync, existsSync, cpSync, rmSync } from "node:fs";import { deflateSync, inflateSync } from "node:zlib";import { fileURLToPath } from "node:url";import { fileURLToPath } from "node:url";import { dirname, join } from "node:path";import { dirname, join } from "node:path";import { NeighborBit } from "../../shared/world/neighborConnect.js";import { NeighborBit, cardinalConnectionSuffix, composeNamedNeighborConnectState } from "../../shared/world/neighborConnect.js";const SIZE = 16;const SIZE = 16;const OUT = join(dirname(fileURLToPath(import.meta.url)), "../assets/blocks/stone-wall");const ROOT = join(dirname(fileURLToPath(import.meta.url)), "../assets/blocks");const EXAMPLES = join(ROOT, "_examples/stone-wall");const TOP = [168, 168, 172, 255];const OUT_THICK = join(ROOT, "thick-stone-wall");const TOP_HI = [198, 198, 202, 255];const OUT_THIN = join(ROOT, "thin-stone-wall");const TOP_LO = [140, 140, 144, 255];const FACE = [112, 112, 116, 255];const THICK = { key: "thick-stone-wall", neighborConnect: true, neighborConnectNamed: true };const FACE_HI = [132, 132, 136, 255];const THIN = { key: "thin-stone-wall", neighborConnect: true, neighborConnectNamed: true };const FACE_LO = [88, 88, 92, 255];const EDGE = [70, 70, 74, 255];const MORTAR = [78, 78, 82, 255];/** Constant core used for connected runs (must meet neighbour tile edges cleanly). */const CORE_X0 = 5;const CORE_X1 = 10;const TOP_Y0 = 3;const TOP_Y1 = 6;const FACE_Y1 = 12;/** Alone / free-end base is wider than the top (frustum). */const BASE_X0 = 3;const BASE_X1 = 12;function crcTable ()function crcTable (){{@@ -98,6 +102,90 @@ function encodePng (rgba) ]); ]);}}function decodePngRgba (path){ const buf = readFileSync(path); let off = 8; let w = 0; let h = 0; 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); if (data[8] !== 8 || data[9] !== 6) { throw new Error(`${path}: expected 8-bit RGBA`); } } else if (type === "IDAT") { idat.push(data); } else if (type === "IEND") { break; } off += 12 + len; } const raw = inflateSync(Buffer.concat(idat)); const bpp = 4; const stride = w * bpp; const rgba = new Uint8ClampedArray(w * h * 4); let src = 0; const prev = Buffer.alloc(stride); const cur = Buffer.alloc(stride); for (let y = 0; y < h; y++) { const filter = raw[src++]; for (let i = 0; i < stride; i++) { cur[i] = raw[src++]; } for (let i = 0; i < stride; i++) { const left = i >= bpp ? cur[i - bpp] : 0; const up = prev[i]; const upLeft = i >= bpp ? prev[i - bpp] : 0; let val = cur[i]; if (filter === 1) { val = (val + left) & 255; } else if (filter === 2) { val = (val + up) & 255; } else if (filter === 3) { val = (val + ((left + up) >> 1)) & 255; } else if (filter === 4) { const p = left + up - upLeft; const pa = Math.abs(p - left); const pb = Math.abs(p - up); const pc = Math.abs(p - upLeft); const pr = (pa <= pb && pa <= pc) ? left : (pb <= pc ? up : upLeft); val = (val + pr) & 255; } cur[i] = val; } rgba.set(cur, y * stride); prev.set(cur); } if (w !== SIZE || h !== SIZE) { throw new Error(`${path}: expected ${SIZE}×${SIZE}, got ${w}×${h}`); } return rgba;}function loadExample (name){ const path = join(EXAMPLES, name); if (!existsSync(path)) { return null; } return decodePngRgba(path);}function getPx (rgba, x, y){ if (x < 0 || y < 0 || x >= SIZE || y >= SIZE) { return [0, 0, 0, 0]; } const i = (y * SIZE + x) * 4; return [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]];}function setPx (rgba, x, y, color)function setPx (rgba, x, y, color){{ if (x < 0 || y < 0 || x >= SIZE || y >= SIZE) if (x < 0 || y < 0 || x >= SIZE || y >= SIZE)@@ -109,148 +197,250 @@ function setPx (rgba, x, y, color) rgba[i + 3] = color[3]; rgba[i + 3] = color[3];}}/** Frustum half-width in X at row y (alone / free-end silhouette). */function opaque (rgba, x, y)function frustumX0X1 (y){{ if (y <= TOP_Y1) return getPx(rgba, x, y)[3] > 128; { return { x0: CORE_X0, x1: CORE_X1 }; } if (y >= FACE_Y1) { return { x0: BASE_X0, x1: BASE_X1 }; } const t = (y - TOP_Y1) / (FACE_Y1 - TOP_Y1); const x0 = Math.round(CORE_X0 + (BASE_X0 - CORE_X0) * t); const x1 = Math.round(CORE_X1 + (BASE_X1 - CORE_X1) * t); return { x0, x1 };}}/**function copyRgba (rgba) * Strip-union with constant core thickness on connected sides.{ * Free ends keep the frustum taper so alone / stubs still read as 3D. return new Uint8ClampedArray(rgba); */}function inWall (x, y, connectN, connectE, connectS, connectW)function clearRgba (){{ const alone = !connectN && !connectE && !connectS && !connectW; return new Uint8ClampedArray(SIZE * SIZE * 4); const wantH = alone || connectE || connectW;} const wantV = alone || connectN || connectS; if (wantH)function mirrorX (rgba){ const out = clearRgba(); for (let y = 0; y < SIZE; y++) { { const y0 = connectN ? 0 : TOP_Y0; for (let x = 0; x < SIZE; x++) const y1 = connectS ? SIZE - 1 : FACE_Y1; { setPx(out, x, y, getPx(rgba, SIZE - 1 - x, y)); } if (y >= y0 && y <= y1) { const { x0: fx0, x1: fx1 } = frustumX0X1(Math.min(FACE_Y1, Math.max(TOP_Y0, y))); // Connected cardinals run to the tile edge (constant seam). // Free ends keep the frustum taper. const x0 = connectW ? 0 : fx0; const x1 = connectE ? SIZE - 1 : fx1; if (x >= x0 && x <= x1) { return true; } } } } return out;} if (wantV)function blit (dst, src){ if (!src) { return; } for (let y = 0; y < SIZE; y++) { { const x0 = CORE_X0; for (let x = 0; x < SIZE; x++) const x1 = CORE_X1; if (x >= x0 && x <= x1) { { const y0 = connectN ? 0 : TOP_Y0; const c = getPx(src, x, y); const y1 = connectS ? SIZE - 1 : FACE_Y1; if (c[3] > 128) if (y >= y0 && y <= y1) { setPx(dst, x, y, c); } { return true; } } } } } return false;}}function hash2 (x, y)/** Ensure example folder exists; migrate from legacy stone-wall/ if needed. */function ensureExamples (){{ let n = (x * 374761393 + y * 668265263) | 0; mkdirSync(EXAMPLES, { recursive: true }); n = (n ^ (n >>> 13)) * 1274126177; const legacy = join(ROOT, "stone-wall"); return (n ^ (n >>> 16)) >>> 0; if (!existsSync(legacy))} { return; } for (const name of readdirSync(legacy))function cobbleShade (base, x, y) {{ if (!name.startsWith("example-") || !name.endsWith(".png")) const h = hash2(x, y); { continue; } const speck = (h & 7); const dest = join(EXAMPLES, name); if (speck === 0) if (!existsSync(dest)) { return MORTAR; } { cpSync(join(legacy, name), dest); } if (speck === 1 || speck === 2) } { return base === TOP || base === TOP_HI || base === TOP_LO ? TOP_HI : FACE_HI; } if (speck === 3) { return base === TOP || base === TOP_HI || base === TOP_LO ? TOP_LO : FACE_LO; } return base;}}function isTopRow (y, connectN)function buildPack (kind){{ if (connectN) const alone = loadExample(`example-stone-${kind}.png`); { return y <= TOP_Y1; } const east = loadExample(`example-stone-${kind}-connecting.png`); return y >= TOP_Y0 && y <= TOP_Y1; const north = loadExample(`example-stone-${kind}-connecting-up.png`);} const south = loadExample(`example-stone-${kind}-connecting-down.png`); const ns = loadExample(`example-stone-${kind}-connecting-updown.png`); const ellNE = loadExample(`example-stone-${kind}-connecting-L.png`); const ellSE = loadExample(`example-stone-${kind}-connecting-Ldownright.png`); const teeESW = loadExample(`example-stone-${kind}-T.png`) ?? loadExample(`example-stone-${kind}-connecting-T.png`); const teeNEW = loadExample(`example-stone-${kind}-connecting-T-upsidedown.png`);function paintWall (mask) if (!alone || !east || !north || !ns){ { throw new Error(`Missing core ${kind} examples in ${EXAMPLES}`); } const rgba = new Uint8Array(SIZE * SIZE * 4); const connectN = (mask & NeighborBit.n) !== 0; const connectE = (mask & NeighborBit.e) !== 0; const connectS = (mask & NeighborBit.s) !== 0; const connectW = (mask & NeighborBit.w) !== 0; for (let y = 0; y < SIZE; y++) const west = mirrorX(east); const southFinal = south ?? (() => { { for (let x = 0; x < SIZE; x++) const out = copyRgba(alone); for (let y = 10; y < SIZE; y++) { { if (!inWall(x, y, connectN, connectE, connectS, connectW)) for (let x = 0; x < SIZE; x++) { continue; } { if (opaque(ns, x, y)) { setPx(out, x, y, getPx(ns, x, y)); } } } return out; })(); const n = inWall(x, y - 1, connectN, connectE, connectS, connectW); const ellNEFinal = ellNE ?? (() => const e = inWall(x + 1, y, connectN, connectE, connectS, connectW); { const s = inWall(x, y + 1, connectN, connectE, connectS, connectW); const out = clearRgba(); const w = inWall(x - 1, y, connectN, connectE, connectS, connectW); blit(out, north); blit(out, east); return out; })(); const ellSEFinal = ellSE ?? (() => { const out = clearRgba(); blit(out, southFinal); blit(out, east); return out; })(); const ellNW = mirrorX(ellNEFinal); const ellSW = mirrorX(ellSEFinal); let base; const ew = (() => if (isTopRow(y, connectN)) { const out = clearRgba(); blit(out, east); blit(out, west); for (let y = 0; y < SIZE; y++) { if (!opaque(east, SIZE - 1, y)) { continue; } let fill = null; for (let x = SIZE - 1; x >= 0; x--) { { if (!n) const c = getPx(east, x, y); { base = TOP_HI; } if (c[3] > 128) else if (!s && y === TOP_Y1) { fill = c; break; } { base = TOP_LO; } else { base = TOP; } } } else if (!fill) { continue; } for (let x = 0; x < SIZE; x++) { { if (!s) if (!opaque(out, x, y)) { base = FACE_LO; } { setPx(out, x, y, fill); } else if (!n) { base = FACE_HI; } else { base = FACE; } } } } return out; })(); // Free side bevels (not on edges that continue into a neighbour). const teeESWFinal = teeESW ?? (() => const freeW = !w && !(connectW && x === 0); { const freeE = !e && !(connectE && x === SIZE - 1); const out = clearRgba(); if (freeW || freeE) blit(out, ew); { blit(out, southFinal); if (base === TOP || base === TOP_HI) return out; { base = TOP_LO; } })(); else if (base === FACE || base === FACE_HI) const teeNEWFinal = teeNEW ?? (() => { base = EDGE; } { } const out = clearRgba(); blit(out, ew); blit(out, north); return out; })(); const teeNES = (() => { const out = clearRgba(); blit(out, north); blit(out, east); blit(out, southFinal); return out; })(); const teeNWS = mirrorX(teeNES); const all = (() => { const out = clearRgba(); blit(out, ns); blit(out, ew); return out; })(); setPx(rgba, x, y, cobbleShade(base, x, y)); const byMask = new Map([ } [0, alone], [NeighborBit.n, north], [NeighborBit.e, east], [NeighborBit.s, southFinal], [NeighborBit.w, west], [NeighborBit.n | NeighborBit.s, ns], [NeighborBit.e | NeighborBit.w, ew], [NeighborBit.n | NeighborBit.e, ellNEFinal], [NeighborBit.e | NeighborBit.s, ellSEFinal], [NeighborBit.s | NeighborBit.w, ellSW], [NeighborBit.w | NeighborBit.n, ellNW], [NeighborBit.e | NeighborBit.s | NeighborBit.w, teeESWFinal], [NeighborBit.w | NeighborBit.n | NeighborBit.e, teeNEWFinal], [NeighborBit.n | NeighborBit.e | NeighborBit.s, teeNES], [NeighborBit.n | NeighborBit.w | NeighborBit.s, teeNWS], [NeighborBit.n | NeighborBit.e | NeighborBit.s | NeighborBit.w, all] ]); return { byMask, alone, east, north, ns, ellNE: ellNEFinal };}function clearGenerated (dir){ mkdirSync(dir, { recursive: true }); for (const name of readdirSync(dir)) { if (!name.endsWith(".png") || name.startsWith("example")) { continue; } unlinkSync(join(dir, name)); } } return rgba;}}mkdirSync(OUT, { recursive: true });function writeSet (dir, def, pack)for (let mask = 0; mask < 16; mask++){{ writeFileSync(join(OUT, `${mask}.png`), encodePng(paintWall(mask))); clearGenerated(dir); for (let mask = 0; mask < 16; mask++) { const rgba = pack.byMask.get(mask); if (!rgba) { throw new Error(`Missing mask ${mask} for ${def.key}`); } const state = composeNamedNeighborConnectState(def, mask); writeFileSync(join(dir, `${state}.png`), encodePng(rgba)); } console.log(`Wrote 16 ${def.key} sprites → ${dir}`);}}console.log(`Wrote cobblestone frustum stone-wall sprites 0–15 to ${OUT}`);function removeLegacyFolders (){ for (const name of ["stone-wall", "stone-wall-thin"]) { const dir = join(ROOT, name); if (!existsSync(dir)) { continue; } // Keep examples only in _examples/; remove entire legacy folder. rmSync(dir, { recursive: true, force: true }); console.log(`Removed legacy ${name}/`); }}ensureExamples();const thin = buildPack("thin");const thick = buildPack("thick");function assertSame (a, b, label){ for (let i = 0; i < a.length; i++) { if (a[i] !== b[i]) { throw new Error(`Mismatch ${label}`); } }}assertSame(thin.byMask.get(0), thin.alone, "thin alone");assertSame(thin.byMask.get(1), thin.north, "thin n");assertSame(thin.byMask.get(2), thin.east, "thin e");assertSame(thin.byMask.get(5), thin.ns, "thin ns");assertSame(thick.byMask.get(0), thick.alone, "thick alone");writeSet(OUT_THIN, THIN, thin);writeSet(OUT_THICK, THICK, thick);removeLegacyFolders();console.log("Suffixes:", [...Array(16)].map((_, m) => `${m}=${cardinalConnectionSuffix(m) || "(alone)"}`).join(", "));@@ -0,0 +1,13 @@
/**
* Bake grey cobblestone onto thick/thin stone-wall shape masks.
* Delegates to texture-wall-sprites.mjs --variant=cobble
*
* node client/scripts/texture-stone-wall-sprites.mjs
*/
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
const script = join(dirname(fileURLToPath(import.meta.url)), "texture-wall-sprites.mjs");
const result = spawnSync(process.execPath, [script, "--variant=cobble"], { stdio: "inherit" });
process.exit(result.status ?? 1);
@@ -0,0 +1,13 @@/** * Bake grey cobblestone onto thick/thin stone-wall shape masks. * Delegates to texture-wall-sprites.mjs --variant=cobble * * node client/scripts/texture-stone-wall-sprites.mjs */import { spawnSync } from "node:child_process";import { fileURLToPath } from "node:url";import { dirname, join } from "node:path";const script = join(dirname(fileURLToPath(import.meta.url)), "texture-wall-sprites.mjs");const result = spawnSync(process.execPath, [script, "--variant=cobble"], { stdio: "inherit" });process.exit(result.status ?? 1);@@ -0,0 +1,714 @@
/**
* 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<R) with face-aware plank grain, matching authored thick 1×1. */
function mag (L, g = 0)
{
const lit = Math.max(1, Math.min(255, L | 0));
const gv = Math.max(0, Math.min(lit - 1, g | 0));
return rgba(lit, gv, lit);
}
/**
* Wood planks by face (from thick-wood-wall/0.png reference):
* - S: vertical boards (~4px), alternating grain by board+row
* - W/E: horizontal plank bands; outer/inner columns swap each band (diagonal step)
* - T: N–S boards with brighter center grain + slight G highlight
* - N: bright rim, two-tone split
*/
function woodShade (x, y, role, shapePrefix, faceRgba)
{
if (role === "O")
{ return mag(55); }
if (role === "S")
{
const board = Math.floor(x / 4);
const light = ((board + y) & 1) !== 0;
return mag(light ? 102 : 95);
}
if (role === "W" || role === "E")
{
const lo = role === "W" ? 143 : 113;
const hi = role === "W" ? 155 : 120;
// Plank bands ~5px tall, aligned like authored alone (y2–6, y7–11, …).
const band = Math.floor(Math.max(0, y - 2) / 5);
const outer = role === "W"
? !isSameFace(faceRgba, x - 1, y, role, shapePrefix)
: !isSameFace(faceRgba, x + 1, y, role, shapePrefix);
const swap = (band & 1) !== 0;
let useHi;
if (outer)
{ useHi = swap; }
else
{ useHi = !swap; }
return mag(useHi ? hi : lo);
}
if (role === "T" || (shapePrefix.startsWith("thin") && role === "N"))
{
const rowTone = (y & 1) !== 0;
const leftEdge = !isSameFace(faceRgba, x - 1, y, role, shapePrefix);
const rightEdge = !isSameFace(faceRgba, x + 1, y, role, shapePrefix);
const edge = leftEdge || rightEdge;
let L;
if (edge)
{ L = rowTone ? 161 : 159; }
else
{ L = rowTone ? 177 : 168; }
const g = rowTone ? 20 : 0;
return mag(L, g);
}
if (role === "N")
{
// Thick north bevel: split highlight
const L = x < 8 ? 200 : 210;
return mag(L, x < 8 ? 47 : 50);
}
return woodMagenta(role);
}
/**
* Cliff magenta tops: thick = plateau only (N is a dirt north face).
* Thin has no separate T — ridge top is role N.
*/
function isCliffTopRole (role, shapePrefix)
{
if (shapePrefix.startsWith("thin"))
{ return role === "N"; }
return role === "T";
}
function cliffShade (x, y, role, shapePrefix)
{
if (isCliffTopRole(role, shapePrefix))
{
// Full magenta top — replaced in-game by ground sample shader.
return rgba(255, 0, 255);
}
if (role === "O")
{
const d = dirtAt(x, y);
return mulRgb(d, 0.35);
}
const d = dirtAt(x, y);
return mulRgb(d, faceLit(role));
}
function paintPixel (variant, prefix, g, x, y, faceRgba = null)
{
const role = roleOf(prefix, g);
if (!role)
{
// Unknown grey: luminance fallback toward mid face.
const lit = g / 128;
if (variant === "wood")
{ return rgba(Math.round(140 * lit), 0, Math.round(140 * lit)); }
if (variant === "cliff")
{ return mulRgb(dirtAt(x, y), lit); }
if (variant === "brick")
{ return mulRgb(BRICK.cement, lit); }
return mulRgb(COBBLE.T, lit);
}
if (variant === "cobble")
{ return cobbleLike(COBBLE, x, y, role, 7); }
if (variant === "smooth")
{ return cobbleLike(COBBLE, x, y, role, 31); }
if (variant === "brick")
{ return brickShade(x, y, role, prefix, faceRgba); }
if (variant === "wood")
{ return woodShade(x, y, role, prefix, faceRgba); }
if (variant === "cliff")
{ return cliffShade(x, y, role, prefix); }
throw new Error(`Unknown variant ${variant}`);
}
function textureMask (rgbaIn, variant, shapePrefix)
{
const out = new Uint8Array(SIZE * SIZE * 4);
for (let y = 0; y < SIZE; y++)
{
for (let x = 0; x < SIZE; x++)
{
const i = (y * SIZE + x) * 4;
if (rgbaIn[i + 3] === 0)
{ continue; }
const color = paintPixel(variant, shapePrefix, rgbaIn[i], x, y, rgbaIn);
out[i] = color[0];
out[i + 1] = color[1];
out[i + 2] = color[2];
out[i + 3] = 255;
}
}
return out;
}
const VARIANT_OUT = {
cobble: {
thick: { dir: "thick-stone-wall", named: true, prefix: "thick-stone-wall" },
thin: { dir: "thin-stone-wall", named: true, prefix: "thin-stone-wall" }
},
smooth: {
thick: { dir: "thick-smooth-stone-wall", named: true, prefix: "thick-smooth-stone-wall" },
thin: { dir: "thin-smooth-stone-wall", named: true, prefix: "thin-smooth-stone-wall" }
},
brick: {
thick: { dir: "thick-brick-wall", named: true, prefix: "thick-brick-wall" },
thin: { dir: "thin-brick-wall", named: true, prefix: "thin-brick-wall" }
},
wood: {
thick: { dir: "thick-wood-wall", named: false, prefix: "thick-stone-wall" },
thin: { dir: "thin-wood-wall", named: false, prefix: "thin-stone-wall" }
},
cliff: {
thick: { dir: "thick-cliff", named: true, prefix: "thick-cliff" },
thin: { dir: "thin-cliff", named: true, prefix: "thin-cliff" }
}
};
function shapeFiles (shapeKey)
{
return readdirSync(EXAMPLES)
.filter((name) => 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 shapeKey = `${kind}-stone-wall`;
const out = cfg[kind];
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).`);
@@ -0,0 +1,714 @@/** * 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<R) with face-aware plank grain, matching authored thick 1×1. */function mag (L, g = 0){ const lit = Math.max(1, Math.min(255, L | 0)); const gv = Math.max(0, Math.min(lit - 1, g | 0)); return rgba(lit, gv, lit);}/** * Wood planks by face (from thick-wood-wall/0.png reference): * - S: vertical boards (~4px), alternating grain by board+row * - W/E: horizontal plank bands; outer/inner columns swap each band (diagonal step) * - T: N–S boards with brighter center grain + slight G highlight * - N: bright rim, two-tone split */function woodShade (x, y, role, shapePrefix, faceRgba){ if (role === "O") { return mag(55); } if (role === "S") { const board = Math.floor(x / 4); const light = ((board + y) & 1) !== 0; return mag(light ? 102 : 95); } if (role === "W" || role === "E") { const lo = role === "W" ? 143 : 113; const hi = role === "W" ? 155 : 120; // Plank bands ~5px tall, aligned like authored alone (y2–6, y7–11, …). const band = Math.floor(Math.max(0, y - 2) / 5); const outer = role === "W" ? !isSameFace(faceRgba, x - 1, y, role, shapePrefix) : !isSameFace(faceRgba, x + 1, y, role, shapePrefix); const swap = (band & 1) !== 0; let useHi; if (outer) { useHi = swap; } else { useHi = !swap; } return mag(useHi ? hi : lo); } if (role === "T" || (shapePrefix.startsWith("thin") && role === "N")) { const rowTone = (y & 1) !== 0; const leftEdge = !isSameFace(faceRgba, x - 1, y, role, shapePrefix); const rightEdge = !isSameFace(faceRgba, x + 1, y, role, shapePrefix); const edge = leftEdge || rightEdge; let L; if (edge) { L = rowTone ? 161 : 159; } else { L = rowTone ? 177 : 168; } const g = rowTone ? 20 : 0; return mag(L, g); } if (role === "N") { // Thick north bevel: split highlight const L = x < 8 ? 200 : 210; return mag(L, x < 8 ? 47 : 50); } return woodMagenta(role);}/** * Cliff magenta tops: thick = plateau only (N is a dirt north face). * Thin has no separate T — ridge top is role N. */function isCliffTopRole (role, shapePrefix){ if (shapePrefix.startsWith("thin")) { return role === "N"; } return role === "T";}function cliffShade (x, y, role, shapePrefix){ if (isCliffTopRole(role, shapePrefix)) { // Full magenta top — replaced in-game by ground sample shader. return rgba(255, 0, 255); } if (role === "O") { const d = dirtAt(x, y); return mulRgb(d, 0.35); } const d = dirtAt(x, y); return mulRgb(d, faceLit(role));}function paintPixel (variant, prefix, g, x, y, faceRgba = null){ const role = roleOf(prefix, g); if (!role) { // Unknown grey: luminance fallback toward mid face. const lit = g / 128; if (variant === "wood") { return rgba(Math.round(140 * lit), 0, Math.round(140 * lit)); } if (variant === "cliff") { return mulRgb(dirtAt(x, y), lit); } if (variant === "brick") { return mulRgb(BRICK.cement, lit); } return mulRgb(COBBLE.T, lit); } if (variant === "cobble") { return cobbleLike(COBBLE, x, y, role, 7); } if (variant === "smooth") { return cobbleLike(COBBLE, x, y, role, 31); } if (variant === "brick") { return brickShade(x, y, role, prefix, faceRgba); } if (variant === "wood") { return woodShade(x, y, role, prefix, faceRgba); } if (variant === "cliff") { return cliffShade(x, y, role, prefix); } throw new Error(`Unknown variant ${variant}`);}function textureMask (rgbaIn, variant, shapePrefix){ const out = new Uint8Array(SIZE * SIZE * 4); for (let y = 0; y < SIZE; y++) { for (let x = 0; x < SIZE; x++) { const i = (y * SIZE + x) * 4; if (rgbaIn[i + 3] === 0) { continue; } const color = paintPixel(variant, shapePrefix, rgbaIn[i], x, y, rgbaIn); out[i] = color[0]; out[i + 1] = color[1]; out[i + 2] = color[2]; out[i + 3] = 255; } } return out;}const VARIANT_OUT = { cobble: { thick: { dir: "thick-stone-wall", named: true, prefix: "thick-stone-wall" }, thin: { dir: "thin-stone-wall", named: true, prefix: "thin-stone-wall" } }, smooth: { thick: { dir: "thick-smooth-stone-wall", named: true, prefix: "thick-smooth-stone-wall" }, thin: { dir: "thin-smooth-stone-wall", named: true, prefix: "thin-smooth-stone-wall" } }, brick: { thick: { dir: "thick-brick-wall", named: true, prefix: "thick-brick-wall" }, thin: { dir: "thin-brick-wall", named: true, prefix: "thin-brick-wall" } }, wood: { thick: { dir: "thick-wood-wall", named: false, prefix: "thick-stone-wall" }, thin: { dir: "thin-wood-wall", named: false, prefix: "thin-stone-wall" } }, cliff: { thick: { dir: "thick-cliff", named: true, prefix: "thick-cliff" }, thin: { dir: "thin-cliff", named: true, prefix: "thin-cliff" } }};function shapeFiles (shapeKey){ return readdirSync(EXAMPLES) .filter((name) => 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 shapeKey = `${kind}-stone-wall`; const out = cfg[kind]; 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).`);@@ -686,6 +686,26 @@ function refreshNeighborConnect (localX, localY, typeId)
}
}
/** Fix legacy/wrong connect states (e.g. old diagonal masks saved as nesw) from live neighbors. */
function recomputeAllNeighborConnectInDraft ()
{
if (!draft)
{ return; }
for (let localY = 0; localY < CHUNK_SIZE; localY++)
{
for (let localX = 0; localX < CHUNK_SIZE; localX++)
{
const block = draft.blocks[localY * CHUNK_SIZE + localX];
if (!block)
{ continue; }
const def = BLOCK_DEFINITIONS[block.typeId];
if (!definitionUsesNeighborConnect(def))
{ continue; }
refreshNeighborConnect(localX, localY, block.typeId);
}
}
}
function updateRevisionUI ()
{
const applyBtn = $("apply");
@@ -748,6 +768,8 @@ function showSelectedChunk (payload)
view.applySnapshot(snapshotFromPayload(payload));
syncSpawnersOverlay(payload.chunkX, payload.chunkY, draft.spawners);
captureDraftBaseline();
recomputeAllNeighborConnectInDraft();
syncSaveButton();
if (navigateAfterSave && pendingNavigate)
{
const next = pendingNavigate;
@@ -686,6 +686,26 @@ function refreshNeighborConnect (localX, localY, typeId) } }}}/** Fix legacy/wrong connect states (e.g. old diagonal masks saved as nesw) from live neighbors. */function recomputeAllNeighborConnectInDraft (){ if (!draft) { return; } for (let localY = 0; localY < CHUNK_SIZE; localY++) { for (let localX = 0; localX < CHUNK_SIZE; localX++) { const block = draft.blocks[localY * CHUNK_SIZE + localX]; if (!block) { continue; } const def = BLOCK_DEFINITIONS[block.typeId]; if (!definitionUsesNeighborConnect(def)) { continue; } refreshNeighborConnect(localX, localY, block.typeId); } }}function updateRevisionUI ()function updateRevisionUI (){{ const applyBtn = $("apply"); const applyBtn = $("apply");@@ -748,6 +768,8 @@ function showSelectedChunk (payload) view.applySnapshot(snapshotFromPayload(payload)); view.applySnapshot(snapshotFromPayload(payload)); syncSpawnersOverlay(payload.chunkX, payload.chunkY, draft.spawners); syncSpawnersOverlay(payload.chunkX, payload.chunkY, draft.spawners); captureDraftBaseline(); captureDraftBaseline(); recomputeAllNeighborConnectInDraft(); syncSaveButton(); if (navigateAfterSave && pendingNavigate) if (navigateAfterSave && pendingNavigate) { { const next = pendingNavigate; const next = pendingNavigate;@@ -5,13 +5,14 @@ import { bakeChunkOcclusion } from "/shared/lighting/chunkOcclusion.js";
import { smoothLitCorner } from "/shared/lighting/lightCorners.js";
import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
import { EQUIPMENT_SLOT, itemEquipSprite, itemSpriteName, itemDefinition } from "/shared/definitions/items.js";
import {
resolveItemTint,
resolveEquipTint,
resolveItemDualTint,
resolveEquipDualTint,
normalizeRgb
} from "/shared/render/tint.js";
import
{
resolveItemTint,
resolveEquipTint,
resolveItemDualTint,
resolveEquipDualTint,
normalizeRgb
} from "/shared/render/tint.js";
import { layersFromSpawnerConfig } from "/shared/appearance/layers.js";
import { chargeSpriteFrameIndex, itemMaxCharges } from "/shared/items/charges.js";
import { normalizeGround, isWadeGroundInSeason, isWaterGround, isLiquidWaterGround, isGroundPassable, isBlockOccludingLight, LightOcclusion } from "/shared/definitions/tiles.js";
@@ -352,8 +353,49 @@ const ATLAS_LIGHTING_FRAG = [
"}"
].join("\n");
/**
* Block-row atlas: magenta → sample the ground atlas (u_bump) at the same
* tile-local UV (1:1 scale). The ground atlas already includes soft-terrain
* blending when that preference is on, so cliff tops match the floor beneath.
* Darkness matches ATLAS_LIGHTING_FRAG (lightmap in u_secondary).
*/
const ATLAS_BLOCK_GROUND_TOP_FRAG = [
"precision mediump float;",
"varying vec2 v_texCoord;",
"uniform sampler2D u_texture;",
"uniform sampler2D u_secondary;",
"uniform sampler2D u_bump;",
"uniform float u_alpha;",
"uniform float u_ambientDark;",
"uniform float u_lightRow;",
"void main() {",
" vec4 color = texture2D(u_texture, v_texCoord);",
" if (color.a <= 0.0) { discard; }",
" vec3 rgb = color.rgb;",
" // Magenta family (R≈B, G<R): replace with blended ground under this pixel.",
" float rbDiff = abs(rgb.r - rgb.b);",
" if (rbDiff < 0.02 && rgb.g < rgb.r - 0.02) {",
" float tileX = floor(v_texCoord.x * 16.0);",
" float tileY = max(u_lightRow, 0.0);",
" float localX = fract(v_texCoord.x * 16.0);",
" float localY = v_texCoord.y;",
" vec2 groundUV = vec2((tileX + localX) / 16.0, (tileY + localY) / 16.0);",
" rgb = texture2D(u_bump, groundUV).rgb;",
" }",
" vec2 lightUV = v_texCoord;",
" if (u_lightRow >= 0.0) {",
" lightUV.y = (u_lightRow + v_texCoord.y) / 16.0;",
" }",
" float lit = texture2D(u_secondary, lightUV).r;",
" float darkness = u_ambientDark * (1.0 - lit);",
" rgb = mix(rgb, vec3(0.0), darkness);",
" gl_FragColor = vec4(rgb, color.a * u_alpha);",
"}"
].join("\n");
let spriteLightingShader = null;
let atlasLightingShader = null;
let atlasBlockGroundTopShader = null;
let waterGroundShader = null;
let tintLitSpriteShader = null;
let dualTintLitSpriteShader = null;
@@ -374,6 +416,13 @@ function getAtlasLightingShader ()
return atlasLightingShader;
}
function getAtlasBlockGroundTopShader ()
{
if (!atlasBlockGroundTopShader)
{ atlasBlockGroundTopShader = Shader.fragment(ATLAS_BLOCK_GROUND_TOP_FRAG); }
return atlasBlockGroundTopShader;
}
function getWaterGroundShader ()
{
if (!waterGroundShader)
@@ -3297,7 +3346,7 @@ export class WorldView
for (let row = 0; row < CHUNK_SIZE; row++)
{
const object = new GameObject(0, 0, baked.blockImages[row], SORT_BLOCK);
this.#applyAtlasLighting(object, baked.lightmapImage, row);
this.#applyAtlasLighting(object, baked.lightmapImage, row, baked.groundImage);
this.scene.addObject(object);
baked.blockObjects.push(object);
}
@@ -3314,6 +3363,7 @@ export class WorldView
baked.groundCanvas = atlases.ground;
baked.groundImage = groundImage;
baked.groundObject.renderer.sprite = groundImage;
this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1);
}
for (let row = 0; row < CHUNK_SIZE; row++)
{
@@ -3323,6 +3373,12 @@ export class WorldView
baked.blockImages[row] = blockImages[row];
baked.blockObjects[row].renderer.sprite = blockImages[row];
}
this.#applyAtlasLighting(
baked.blockObjects[row],
baked.lightmapImage,
row,
baked.groundImage
);
}
if (baked.bloomCanvas !== atlases.bloom)
{
@@ -3419,12 +3475,21 @@ export class WorldView
{ this.#scheduleTextureWarm(); }
}
#applyAtlasLighting (object, lightmapImage, lightRow)
#applyAtlasLighting (object, lightmapImage, lightRow, groundImage = null)
{
if (!object?.renderer)
{ return; }
object._lit = true;
object.renderer.shader = getAtlasLightingShader();
if (groundImage)
{
object.renderer.shader = getAtlasBlockGroundTopShader();
object.renderer.bumpMap = groundImage;
}
else
{
object.renderer.shader = getAtlasLightingShader();
object.renderer.bumpMap = null;
}
object.renderer.secondaryMap = lightmapImage;
object.renderer.shaderUniforms = {
u_ambientDark: 0,
@@ -5,13 +5,14 @@ import { bakeChunkOcclusion } from "/shared/lighting/chunkOcclusion.js";import { smoothLitCorner } from "/shared/lighting/lightCorners.js";import { smoothLitCorner } from "/shared/lighting/lightCorners.js";import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";import { EQUIPMENT_SLOT, itemEquipSprite, itemSpriteName, itemDefinition } from "/shared/definitions/items.js";import { EQUIPMENT_SLOT, itemEquipSprite, itemSpriteName, itemDefinition } from "/shared/definitions/items.js";import {import resolveItemTint, { resolveEquipTint, resolveItemTint, resolveItemDualTint, resolveEquipTint, resolveEquipDualTint, resolveItemDualTint, normalizeRgb resolveEquipDualTint,} from "/shared/render/tint.js"; normalizeRgb } from "/shared/render/tint.js";import { layersFromSpawnerConfig } from "/shared/appearance/layers.js";import { layersFromSpawnerConfig } from "/shared/appearance/layers.js";import { chargeSpriteFrameIndex, itemMaxCharges } from "/shared/items/charges.js";import { chargeSpriteFrameIndex, itemMaxCharges } from "/shared/items/charges.js";import { normalizeGround, isWadeGroundInSeason, isWaterGround, isLiquidWaterGround, isGroundPassable, isBlockOccludingLight, LightOcclusion } from "/shared/definitions/tiles.js";import { normalizeGround, isWadeGroundInSeason, isWaterGround, isLiquidWaterGround, isGroundPassable, isBlockOccludingLight, LightOcclusion } from "/shared/definitions/tiles.js";@@ -352,8 +353,49 @@ const ATLAS_LIGHTING_FRAG = [ "}" "}"].join("\n");].join("\n");/** * Block-row atlas: magenta → sample the ground atlas (u_bump) at the same * tile-local UV (1:1 scale). The ground atlas already includes soft-terrain * blending when that preference is on, so cliff tops match the floor beneath. * Darkness matches ATLAS_LIGHTING_FRAG (lightmap in u_secondary). */const ATLAS_BLOCK_GROUND_TOP_FRAG = [ "precision mediump float;", "varying vec2 v_texCoord;", "uniform sampler2D u_texture;", "uniform sampler2D u_secondary;", "uniform sampler2D u_bump;", "uniform float u_alpha;", "uniform float u_ambientDark;", "uniform float u_lightRow;", "void main() {", " vec4 color = texture2D(u_texture, v_texCoord);", " if (color.a <= 0.0) { discard; }", " vec3 rgb = color.rgb;", " // Magenta family (R≈B, G<R): replace with blended ground under this pixel.", " float rbDiff = abs(rgb.r - rgb.b);", " if (rbDiff < 0.02 && rgb.g < rgb.r - 0.02) {", " float tileX = floor(v_texCoord.x * 16.0);", " float tileY = max(u_lightRow, 0.0);", " float localX = fract(v_texCoord.x * 16.0);", " float localY = v_texCoord.y;", " vec2 groundUV = vec2((tileX + localX) / 16.0, (tileY + localY) / 16.0);", " rgb = texture2D(u_bump, groundUV).rgb;", " }", " vec2 lightUV = v_texCoord;", " if (u_lightRow >= 0.0) {", " lightUV.y = (u_lightRow + v_texCoord.y) / 16.0;", " }", " float lit = texture2D(u_secondary, lightUV).r;", " float darkness = u_ambientDark * (1.0 - lit);", " rgb = mix(rgb, vec3(0.0), darkness);", " gl_FragColor = vec4(rgb, color.a * u_alpha);", "}"].join("\n");let spriteLightingShader = null;let spriteLightingShader = null;let atlasLightingShader = null;let atlasLightingShader = null;let atlasBlockGroundTopShader = null;let waterGroundShader = null;let waterGroundShader = null;let tintLitSpriteShader = null;let tintLitSpriteShader = null;let dualTintLitSpriteShader = null;let dualTintLitSpriteShader = null;@@ -374,6 +416,13 @@ function getAtlasLightingShader () return atlasLightingShader; return atlasLightingShader;}}function getAtlasBlockGroundTopShader (){ if (!atlasBlockGroundTopShader) { atlasBlockGroundTopShader = Shader.fragment(ATLAS_BLOCK_GROUND_TOP_FRAG); } return atlasBlockGroundTopShader;}function getWaterGroundShader ()function getWaterGroundShader (){{ if (!waterGroundShader) if (!waterGroundShader)@@ -3297,7 +3346,7 @@ export class WorldView for (let row = 0; row < CHUNK_SIZE; row++) for (let row = 0; row < CHUNK_SIZE; row++) { { const object = new GameObject(0, 0, baked.blockImages[row], SORT_BLOCK); const object = new GameObject(0, 0, baked.blockImages[row], SORT_BLOCK); this.#applyAtlasLighting(object, baked.lightmapImage, row); this.#applyAtlasLighting(object, baked.lightmapImage, row, baked.groundImage); this.scene.addObject(object); this.scene.addObject(object); baked.blockObjects.push(object); baked.blockObjects.push(object); } }@@ -3314,6 +3363,7 @@ export class WorldView baked.groundCanvas = atlases.ground; baked.groundCanvas = atlases.ground; baked.groundImage = groundImage; baked.groundImage = groundImage; baked.groundObject.renderer.sprite = groundImage; baked.groundObject.renderer.sprite = groundImage; this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1); } } for (let row = 0; row < CHUNK_SIZE; row++) for (let row = 0; row < CHUNK_SIZE; row++) { {@@ -3323,6 +3373,12 @@ export class WorldView baked.blockImages[row] = blockImages[row]; baked.blockImages[row] = blockImages[row]; baked.blockObjects[row].renderer.sprite = blockImages[row]; baked.blockObjects[row].renderer.sprite = blockImages[row]; } } this.#applyAtlasLighting( baked.blockObjects[row], baked.lightmapImage, row, baked.groundImage ); } } if (baked.bloomCanvas !== atlases.bloom) if (baked.bloomCanvas !== atlases.bloom) { {@@ -3419,12 +3475,21 @@ export class WorldView { this.#scheduleTextureWarm(); } { this.#scheduleTextureWarm(); } } } #applyAtlasLighting (object, lightmapImage, lightRow) #applyAtlasLighting (object, lightmapImage, lightRow, groundImage = null) { { if (!object?.renderer) if (!object?.renderer) { return; } { return; } object._lit = true; object._lit = true; object.renderer.shader = getAtlasLightingShader(); if (groundImage) { object.renderer.shader = getAtlasBlockGroundTopShader(); object.renderer.bumpMap = groundImage; } else { object.renderer.shader = getAtlasLightingShader(); object.renderer.bumpMap = null; } object.renderer.secondaryMap = lightmapImage; object.renderer.secondaryMap = lightmapImage; object.renderer.shaderUniforms = { object.renderer.shaderUniforms = { u_ambientDark: 0, u_ambientDark: 0,@@ -0,0 +1,342 @@
# Stone wall shape system
How **thick** stone-wall sprites encode a 3D block as flat greyscale face-IDs, how **connections** open faces into neighbours, and how cobble texture is baked onto those masks for gameplay.
Thin walls use the same face vocabulary on a narrower frustum; this document centres on **thick**, which is the clearest reference.
---
## Reference files
| Path | What it is |
|------|------------|
| `client/assets/blocks/thick-stone-wall/thick-stone-wall.png` | **Gameplay** alone 1×1 (textured) |
| `client/assets/blocks/_examples/stone-wall/thick-stone-wall.png` | **Shape mask** alone 1×1 (face-id greys) |
| `client/assets/blocks/thick-stone-wall/thick-stone-wall-*.png` | 15 connected gameplay variants |
| `client/assets/blocks/_examples/stone-wall/ref-thick-alone-256.png` | Nearest-neighbour ×16 alone (shape) |
| `…/ref-thick-face-id-16.png` / `…-256.png` | False-colour face roles |
| `…/ref-thick-height-16.png` / `…-256.png` | Relative heightmap from roles |
| `…/ref-thick-face-legend.png` | Colour key for face-id |
| `…/ref-thick-all-variants.png` | Labeled 4×4 sheet of all 16 thick states |
| `client/scripts/export-thick-wall-refs.py` | Regenerates face-id / height / alone refs |
Gameplay keys: `thick-stone-wall`, `thin-stone-wall`. Suffixes from cardinal neighbours only (`n`/`e`/`s`/`w` → e.g. `we`, `ns`, `esw`, `wne`, `nesw`). See `shared/world/neighborConnect.js`.
---
## 1. Camera and axes
- Tile size: **16×16** px.
- **+X = east** (right), **+Y = south** (down on screen).
- View: **top-down with a front bias** — you see the flat **top**, thin **west/east** vertical sides, and a tall **south** front face.
- Greys are **face identity**, not painted lighting noise. Texture work must stay inside these regions.
```text
N (−Y)
↑
W ← tile → E
↓
S (+Y, toward camera)
```
---
## 2. Greyscale vocabulary (face IDs)
Exact values from `thick-stone-wall.png`. Six tones only:
| Grey | Hex | Role | Reads as |
|------|-----|------|----------|
| 64 | `0x40` | **Outline / crease** | Outer rim + lip between faces |
| 175 | `0xAF` | **North bevel** | Top rim facing north (−Y) — brightest body |
| 149 | `0x95` | **West face** | Vertical face facing west (−X) |
| 128 | `0x80` | **Top plateau** | Flat upper surface of the volume |
| 108 | `0x6C` | **East face** | Vertical face facing east (+X) — darker than west |
| 84 | `0x54` | **South face** | Vertical face facing south (+Y) — darkest body |
Mnemonic on a free 1×1:
```text
N = 0xAF (bright)
W = 0x95 E = 0x6C
top = 0x80
S = 0x54 (dark)
outline = 0x40 everywhere edges meet
```
**Do not invent intermediate greys** when cloning the structure. Remap these six roles to material colours / normals later.
---
## 3. Alone anatomy (pixel-exact)
Role map of `thick-stone-wall.png` (`#` outline, `N`/`W`/`E`/`T`/`S` as above):
```text
y\x 0 1 2 3 4 5 6 7 8 9 A B C D E F
0 # # # # # # # # # # # # # # # #
1 # # # N N N N N N N N N N # # #
2 # W W # # # # # # # # # # E E #
3 # W W # T T T T T T T T # E E #
4 # W W # T T T T T T T T # E E #
5 # W W # T T T T T T T T # E E #
6 # W W # T T T T T T T T # E E #
7 # W W # T T T T T T T T # E E #
8 # W W # T T T T T T T T # E E #
9 # W W # # # # # # # # # # E E #
10 # W W # S S S S S S S S # E E #
11 # W # S S S S S S S S S S # E #
12 # W # S S S S S S S S S S # E #
13 # # S S S S S S S S S S S S # #
14 # # S S S S S S S S S S S S # #
15 # # # # # # # # # # # # # # # #
```
### Region boxes (inclusive)
| Role | Pixels | Notes |
|------|--------|-------|
| Outline | Full perimeter + every lip between faces | Never fill with body grey |
| North bevel | `y=1`, `x=3..12` | Only when **north is free** |
| West face | `x=1..2`, `y=2..12` (tapers: one px at `y=11..12`) | Only when **west is free** |
| East face | `x=13..14`, `y=2..12` (tapers) | Only when **east is free** |
| Top plateau | `x=4..11`, `y=3..8` | Surrounded by `0x40` lips |
| South face | `y=10..14`, widens downward (`x=4..11` → `x=2..13`) | Only when **south is free** |
### Volume model
Read the tile as a **truncated box / frustum**:
1. **Roof** — plateau `0x80` with north lip `0xAF`.
2. **Side walls** — west `0x95`, east `0x6C` (asymmetry = light from NW).
3. **Front wall** — south `0x54`, taller in screen space.
4. **Creases** — `0x40` at every face junction and the tile border.
Corners are mitered: NW = N↔W, NE = N↔E, SW = S↔W, SE = S↔E, resolved by outline pixels.
---
## 4. Connection rule (core)
A suffix letter means: **this tile continues into a neighbour on that side**.
For each connected cardinal:
1. **Remove** that side’s free-face band (`N`/`E`/`S`/`W` grey).
2. **Extrude** interior bands (plateau, remaining free faces, and their outline lips) **to the tile edge** on that side so the neighbour can match.
3. **Keep** free-face bands only on sides that are **not** connected.
| Open | Remove | Extrude to edge |
|------|--------|-----------------|
| **N** | North bevel `0xAF` (+ north rim treatment) | W / E / T run to `y=0` |
| **E** | East face `0x6C` | N (if free) / T / S run to `x=15` |
| **S** | South face `0x54` | W / E / T run to `y=15` |
| **W** | West face `0x95` | N (if free) / T / S run to `x=0` |
### Opposite pairs
**`ns`** — vertical run: full-height W + T + E columns; no N bevel, no S front.
```text
##WW##TTTTTTTT##EE## (repeats y=0..15)
```
**`we`** — horizontal run: full-width N rim (if free), T band, S band; no W/E sides.
```text
################ y0
NNNNNNNNNNNNNNNN y1
################ y2
TTTTTTTTTTTTTTTT y3..8
################ y9
SSSSSSSSSSSSSSSS y10..14
################ y15
```
### Seam contract
Across a shared edge, both tiles paint the **same continuing role** to `x=0|15` or `y=0|15`. Example: A=`…e` and B=`…w` both show plateau `0x80` (and matching N/S bands) meeting mid-edge — **no** side-face grey on that shared edge.
---
## 5. Corners, T-junctions, and concave pockets
Corners (`ne`, `es`, `sw`, `wn`) and T’s (`esw`, `wne`, `swn`, `nes`) are **unions** of the open-face rules.
Where two **free** faces would have met at a concave inner corner after opening the other sides, the art keeps a small **pocket**: outline + a stub of the free face greys. That pocket is what makes an L or T read as a turn rather than a flat extrusion.
Examples (schematic):
**`es`** (open E+S → free N+W): south-east corner keeps an E/S pocket while T extrudes east and south elsewhere.
**`esw`** (T, free N only): full-width N + T like `we`, but south edge shows **two** S/W and S/E pockets at the SW and SE corners (the stem of the T going south).
**`wne`** (T, free S only): full-width S band; north edge shows N pockets at NW/NE where the stem goes north.
**`nesw`** (all four open): no full free faces; T fills the centre and runs to all edges, with **four corner pockets** (N stubs at top, S/W/E stubs at bottom corners). Those pockets are intentional — they are the miters where four neighbour walls meet around this cell in a solid fill / 2×2 interior is different from a true cross; authored `nesw` still carries corner detail for visual continuity with T/L art.
### 2×2 solid block
Four tiles use **corner** suffixes, not `nesw`:
| Cell | Suffix |
|------|--------|
| NW | `es` |
| NE | `sw` |
| SW | `ne` |
| SE | `wn` |
Each keeps the two **outer** free faces and opens the two **inner** sides into the cluster. (`nesw` is for a cell with neighbours on all four cardinals — e.g. interior of a thicker shape — not for the four cells of a minimal 2×2.)
---
## 6. Worked single-open examples
**`n`** — north open: row 0 becomes the old “interior” W/T/E pattern; south stack unchanged.
```text
##WW##TTTTTTTT##EE## y0..8
##WW############EE## y9
##WW##SSSSSSSS##EE## y10
… south taper …
################ y15
```
**`s`** — south open: plateau + sides continue through `y=15`; no `0x54`.
**`e`** — east open: N/T/S (and W) run to `x=15`; no `0x6C`.
**`w`** — west open: N/T/S run to `x=0`; free east column remains.
> **Note:** free east on `thick-stone-wall-w` uses `0x6C` (corrected). When flipping `e`↔`w` art, always reassign face greys — do not keep mirrored luminance.
---
## 7. Heightmap (for cloning / normals)
`ref-thick-height-*.png` maps roles → relative height (0–255):
| Role | Height | Order |
|------|--------|-------|
| Outline | 40 | Lowest (crease / contact) |
| South face | 80 | Front of prism |
| East face | 140 | Side |
| West face | 160 | Side (slightly higher = lit side) |
| Top plateau | 200 | Roof |
| North bevel | 220 | Upper lip |
Ordering to preserve when editing:
`outline ≤ south ≤ east ≤ west ≤ top ≤ north`.
Uses:
- Extrude a new material with the **same silhouettes**.
- Bake normals: up on plateau, −Y on north bevel, ±X on sides, +Y on south.
- Validate connection variants (no south-height pixels on the plateau).
This is a **role-derived** height field, not scanned depth. Absolute values may shift for a shader; keep the order.
---
## 8. Face-id map (tooling)
False colour in `ref-thick-face-id-*.png`:
| Colour | Role |
|--------|------|
| White | North bevel |
| Red | West face |
| Blue | East face |
| Green | South face |
| Amber | Top plateau |
| Near-black | Outline |
Suggested pipeline for a new wall set:
1. Author or copy **face-id** (or height + face-id) at 16×16.
2. Fill each role with albedo / material detail **inside** the mask.
3. Optional soft light multiply that still respects N lightest → S darkest.
4. Keep outline as mortar/edge or replace with a 1px edge pass.
5. Derive the 15 connection variants by applying §4–§5 (or paint from thick examples with recolour-by-role).
---
## 9. Checklist — new thick-style wall
**Alone**
- [ ] Full-tile thick footprint (or intentional inset for a thin family).
- [ ] Only the six role greys (or 1:1 mapped equivalents).
- [ ] Free N → `0xAF` rim; free W → `0x95`; free E → `0x6C`; free S → `0x54`; centre → `0x80`.
- [ ] Outline separates every face pair.
**Each suffix**
- [ ] Connected side has no free-face band of that direction.
- [ ] Interior bands meet the tile edge on connected sides.
- [ ] Free sides keep the correct face grey (`E` = `0x6C`, not a flipped `0x95`).
- [ ] Seam matches the opposite suffix on the neighbour (`e`↔`w`, `n`↔`s`).
- [ ] L/T/`nesw` keep concave corner pockets where needed.
**Texturing**
- [ ] No detail crossing role boundaries without an outline.
- [ ] Normals follow face directions in §7.
- [ ] After recolour, regenerate face-id/height refs and spot-check all 16 states.
---
## 10. Thin walls
`thin-stone-wall` uses the **same idea** on a **narrow frustum**, but a slightly different grey vocabulary:
| Grey | Hex | Thin role |
|------|-----|-----------|
| 64 | `0x40` | Outline |
| 182 | `0xB6` | West face |
| 149 | `0x95` | North rim / ridge top |
| 128 | `0x80` | East face (**not** top plateau — differs from thick) |
| 115 | `0x73` | South / front body |
Clone thin silhouettes; recolour via this table (or `texture-stone-wall-sprites.mjs`).
---
## 11. Baking cobble texture
Gameplay sprites in `thick-stone-wall/` and `thin-stone-wall/` are **textured**. Greyscale face-id masks stay in `_examples/stone-wall/`.
```bash
node client/scripts/texture-stone-wall-sprites.mjs
```
Reads example masks → writes cobble-shaded PNGs using the old cool-grey stone palette (TOP / FACE / EDGE / MORTAR speckles), keyed by face role. Re-run after editing shapes in `_examples`.
---
## 12. Code touchpoints
| Concern | Location |
|---------|----------|
| Cardinal suffix / mask (`& 15`) | `shared/world/neighborConnect.js` |
| Block defs | `shared/definitions/tiles.js` |
| Textured sprites (gameplay) | `client/assets/blocks/thick-stone-wall/`, `thin-stone-wall/` |
| Greyscale shape masks + refs | `client/assets/blocks/_examples/stone-wall/` |
| Shape generator from connecting examples | `client/scripts/generate-stone-wall-sprites.mjs` |
| Cobble texture bake | `client/scripts/texture-stone-wall-sprites.mjs` |
| Ref export | `client/scripts/export-thick-wall-refs.py` |
Editor recomputes neighbour suffixes on paint and on chunk load so a 2×2 stays on corner suffixes, not `nesw`.
---
## 13. Regenerate reference maps
Whenever the thick alone **shape** mask changes:
```bash
python3 client/scripts/export-thick-wall-refs.py
node client/scripts/texture-stone-wall-sprites.mjs
```
Then update the grey table in §2 / §10 if the vocabulary shifted.
@@ -0,0 +1,342 @@# Stone wall shape systemHow **thick** stone-wall sprites encode a 3D block as flat greyscale face-IDs, how **connections** open faces into neighbours, and how cobble texture is baked onto those masks for gameplay.Thin walls use the same face vocabulary on a narrower frustum; this document centres on **thick**, which is the clearest reference.---## Reference files| Path | What it is ||------|------------|| `client/assets/blocks/thick-stone-wall/thick-stone-wall.png` | **Gameplay** alone 1×1 (textured) || `client/assets/blocks/_examples/stone-wall/thick-stone-wall.png` | **Shape mask** alone 1×1 (face-id greys) || `client/assets/blocks/thick-stone-wall/thick-stone-wall-*.png` | 15 connected gameplay variants || `client/assets/blocks/_examples/stone-wall/ref-thick-alone-256.png` | Nearest-neighbour ×16 alone (shape) || `…/ref-thick-face-id-16.png` / `…-256.png` | False-colour face roles || `…/ref-thick-height-16.png` / `…-256.png` | Relative heightmap from roles || `…/ref-thick-face-legend.png` | Colour key for face-id || `…/ref-thick-all-variants.png` | Labeled 4×4 sheet of all 16 thick states || `client/scripts/export-thick-wall-refs.py` | Regenerates face-id / height / alone refs |Gameplay keys: `thick-stone-wall`, `thin-stone-wall`. Suffixes from cardinal neighbours only (`n`/`e`/`s`/`w` → e.g. `we`, `ns`, `esw`, `wne`, `nesw`). See `shared/world/neighborConnect.js`.---## 1. Camera and axes- Tile size: **16×16** px. - **+X = east** (right), **+Y = south** (down on screen). - View: **top-down with a front bias** — you see the flat **top**, thin **west/east** vertical sides, and a tall **south** front face. - Greys are **face identity**, not painted lighting noise. Texture work must stay inside these regions.```text N (−Y) ↑ W ← tile → E ↓ S (+Y, toward camera)```---## 2. Greyscale vocabulary (face IDs)Exact values from `thick-stone-wall.png`. Six tones only:| Grey | Hex | Role | Reads as ||------|-----|------|----------|| 64 | `0x40` | **Outline / crease** | Outer rim + lip between faces || 175 | `0xAF` | **North bevel** | Top rim facing north (−Y) — brightest body || 149 | `0x95` | **West face** | Vertical face facing west (−X) || 128 | `0x80` | **Top plateau** | Flat upper surface of the volume || 108 | `0x6C` | **East face** | Vertical face facing east (+X) — darker than west || 84 | `0x54` | **South face** | Vertical face facing south (+Y) — darkest body |Mnemonic on a free 1×1:```text N = 0xAF (bright)W = 0x95 E = 0x6C top = 0x80 S = 0x54 (dark) outline = 0x40 everywhere edges meet```**Do not invent intermediate greys** when cloning the structure. Remap these six roles to material colours / normals later.---## 3. Alone anatomy (pixel-exact)Role map of `thick-stone-wall.png` (`#` outline, `N`/`W`/`E`/`T`/`S` as above):```text y\x 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 # # # # # # # # # # # # # # # # 1 # # # N N N N N N N N N N # # # 2 # W W # # # # # # # # # # E E # 3 # W W # T T T T T T T T # E E # 4 # W W # T T T T T T T T # E E # 5 # W W # T T T T T T T T # E E # 6 # W W # T T T T T T T T # E E # 7 # W W # T T T T T T T T # E E # 8 # W W # T T T T T T T T # E E # 9 # W W # # # # # # # # # # E E # 10 # W W # S S S S S S S S # E E # 11 # W # S S S S S S S S S S # E # 12 # W # S S S S S S S S S S # E # 13 # # S S S S S S S S S S S S # # 14 # # S S S S S S S S S S S S # # 15 # # # # # # # # # # # # # # # #```### Region boxes (inclusive)| Role | Pixels | Notes ||------|--------|-------|| Outline | Full perimeter + every lip between faces | Never fill with body grey || North bevel | `y=1`, `x=3..12` | Only when **north is free** || West face | `x=1..2`, `y=2..12` (tapers: one px at `y=11..12`) | Only when **west is free** || East face | `x=13..14`, `y=2..12` (tapers) | Only when **east is free** || Top plateau | `x=4..11`, `y=3..8` | Surrounded by `0x40` lips || South face | `y=10..14`, widens downward (`x=4..11` → `x=2..13`) | Only when **south is free** |### Volume modelRead the tile as a **truncated box / frustum**:1. **Roof** — plateau `0x80` with north lip `0xAF`. 2. **Side walls** — west `0x95`, east `0x6C` (asymmetry = light from NW). 3. **Front wall** — south `0x54`, taller in screen space. 4. **Creases** — `0x40` at every face junction and the tile border.Corners are mitered: NW = N↔W, NE = N↔E, SW = S↔W, SE = S↔E, resolved by outline pixels.---## 4. Connection rule (core)A suffix letter means: **this tile continues into a neighbour on that side**.For each connected cardinal:1. **Remove** that side’s free-face band (`N`/`E`/`S`/`W` grey). 2. **Extrude** interior bands (plateau, remaining free faces, and their outline lips) **to the tile edge** on that side so the neighbour can match. 3. **Keep** free-face bands only on sides that are **not** connected.| Open | Remove | Extrude to edge ||------|--------|-----------------|| **N** | North bevel `0xAF` (+ north rim treatment) | W / E / T run to `y=0` || **E** | East face `0x6C` | N (if free) / T / S run to `x=15` || **S** | South face `0x54` | W / E / T run to `y=15` || **W** | West face `0x95` | N (if free) / T / S run to `x=0` |### Opposite pairs**`ns`** — vertical run: full-height W + T + E columns; no N bevel, no S front.```text##WW##TTTTTTTT##EE## (repeats y=0..15)```**`we`** — horizontal run: full-width N rim (if free), T band, S band; no W/E sides.```text################ y0NNNNNNNNNNNNNNNN y1################ y2TTTTTTTTTTTTTTTT y3..8################ y9SSSSSSSSSSSSSSSS y10..14################ y15```### Seam contractAcross a shared edge, both tiles paint the **same continuing role** to `x=0|15` or `y=0|15`. Example: A=`…e` and B=`…w` both show plateau `0x80` (and matching N/S bands) meeting mid-edge — **no** side-face grey on that shared edge.---## 5. Corners, T-junctions, and concave pocketsCorners (`ne`, `es`, `sw`, `wn`) and T’s (`esw`, `wne`, `swn`, `nes`) are **unions** of the open-face rules.Where two **free** faces would have met at a concave inner corner after opening the other sides, the art keeps a small **pocket**: outline + a stub of the free face greys. That pocket is what makes an L or T read as a turn rather than a flat extrusion.Examples (schematic):**`es`** (open E+S → free N+W): south-east corner keeps an E/S pocket while T extrudes east and south elsewhere.**`esw`** (T, free N only): full-width N + T like `we`, but south edge shows **two** S/W and S/E pockets at the SW and SE corners (the stem of the T going south).**`wne`** (T, free S only): full-width S band; north edge shows N pockets at NW/NE where the stem goes north.**`nesw`** (all four open): no full free faces; T fills the centre and runs to all edges, with **four corner pockets** (N stubs at top, S/W/E stubs at bottom corners). Those pockets are intentional — they are the miters where four neighbour walls meet around this cell in a solid fill / 2×2 interior is different from a true cross; authored `nesw` still carries corner detail for visual continuity with T/L art.### 2×2 solid blockFour tiles use **corner** suffixes, not `nesw`:| Cell | Suffix ||------|--------|| NW | `es` || NE | `sw` || SW | `ne` || SE | `wn` |Each keeps the two **outer** free faces and opens the two **inner** sides into the cluster. (`nesw` is for a cell with neighbours on all four cardinals — e.g. interior of a thicker shape — not for the four cells of a minimal 2×2.)---## 6. Worked single-open examples**`n`** — north open: row 0 becomes the old “interior” W/T/E pattern; south stack unchanged.```text##WW##TTTTTTTT##EE## y0..8##WW############EE## y9##WW##SSSSSSSS##EE## y10… south taper …################ y15```**`s`** — south open: plateau + sides continue through `y=15`; no `0x54`.**`e`** — east open: N/T/S (and W) run to `x=15`; no `0x6C`.**`w`** — west open: N/T/S run to `x=0`; free east column remains.> **Note:** free east on `thick-stone-wall-w` uses `0x6C` (corrected). When flipping `e`↔`w` art, always reassign face greys — do not keep mirrored luminance.---## 7. Heightmap (for cloning / normals)`ref-thick-height-*.png` maps roles → relative height (0–255):| Role | Height | Order ||------|--------|-------|| Outline | 40 | Lowest (crease / contact) || South face | 80 | Front of prism || East face | 140 | Side || West face | 160 | Side (slightly higher = lit side) || Top plateau | 200 | Roof || North bevel | 220 | Upper lip |Ordering to preserve when editing: `outline ≤ south ≤ east ≤ west ≤ top ≤ north`.Uses:- Extrude a new material with the **same silhouettes**. - Bake normals: up on plateau, −Y on north bevel, ±X on sides, +Y on south. - Validate connection variants (no south-height pixels on the plateau).This is a **role-derived** height field, not scanned depth. Absolute values may shift for a shader; keep the order.---## 8. Face-id map (tooling)False colour in `ref-thick-face-id-*.png`:| Colour | Role ||--------|------|| White | North bevel || Red | West face || Blue | East face || Green | South face || Amber | Top plateau || Near-black | Outline |Suggested pipeline for a new wall set:1. Author or copy **face-id** (or height + face-id) at 16×16. 2. Fill each role with albedo / material detail **inside** the mask. 3. Optional soft light multiply that still respects N lightest → S darkest. 4. Keep outline as mortar/edge or replace with a 1px edge pass. 5. Derive the 15 connection variants by applying §4–§5 (or paint from thick examples with recolour-by-role).---## 9. Checklist — new thick-style wall**Alone**- [ ] Full-tile thick footprint (or intentional inset for a thin family). - [ ] Only the six role greys (or 1:1 mapped equivalents). - [ ] Free N → `0xAF` rim; free W → `0x95`; free E → `0x6C`; free S → `0x54`; centre → `0x80`. - [ ] Outline separates every face pair.**Each suffix**- [ ] Connected side has no free-face band of that direction. - [ ] Interior bands meet the tile edge on connected sides. - [ ] Free sides keep the correct face grey (`E` = `0x6C`, not a flipped `0x95`). - [ ] Seam matches the opposite suffix on the neighbour (`e`↔`w`, `n`↔`s`). - [ ] L/T/`nesw` keep concave corner pockets where needed.**Texturing**- [ ] No detail crossing role boundaries without an outline. - [ ] Normals follow face directions in §7. - [ ] After recolour, regenerate face-id/height refs and spot-check all 16 states.---## 10. Thin walls`thin-stone-wall` uses the **same idea** on a **narrow frustum**, but a slightly different grey vocabulary:| Grey | Hex | Thin role ||------|-----|-----------|| 64 | `0x40` | Outline || 182 | `0xB6` | West face || 149 | `0x95` | North rim / ridge top || 128 | `0x80` | East face (**not** top plateau — differs from thick) || 115 | `0x73` | South / front body |Clone thin silhouettes; recolour via this table (or `texture-stone-wall-sprites.mjs`).---## 11. Baking cobble textureGameplay sprites in `thick-stone-wall/` and `thin-stone-wall/` are **textured**. Greyscale face-id masks stay in `_examples/stone-wall/`.```bashnode client/scripts/texture-stone-wall-sprites.mjs```Reads example masks → writes cobble-shaded PNGs using the old cool-grey stone palette (TOP / FACE / EDGE / MORTAR speckles), keyed by face role. Re-run after editing shapes in `_examples`.---## 12. Code touchpoints| Concern | Location ||---------|----------|| Cardinal suffix / mask (`& 15`) | `shared/world/neighborConnect.js` || Block defs | `shared/definitions/tiles.js` || Textured sprites (gameplay) | `client/assets/blocks/thick-stone-wall/`, `thin-stone-wall/` || Greyscale shape masks + refs | `client/assets/blocks/_examples/stone-wall/` || Shape generator from connecting examples | `client/scripts/generate-stone-wall-sprites.mjs` || Cobble texture bake | `client/scripts/texture-stone-wall-sprites.mjs` || Ref export | `client/scripts/export-thick-wall-refs.py` |Editor recomputes neighbour suffixes on paint and on chunk load so a 2×2 stays on corner suffixes, not `nesw`.---## 13. Regenerate reference mapsWhenever the thick alone **shape** mask changes:```bashpython3 client/scripts/export-thick-wall-refs.pynode client/scripts/texture-stone-wall-sprites.mjs```Then update the grey table in §2 / §10 if the vocabulary shifted.@@ -504,5 +504,6 @@ function listPngStems (folder)
return entries
.filter((entry) => entry.isFile() && extname(entry.name).toLowerCase() === ".png")
.map((entry) => entry.name.slice(0, -extname(entry.name).length))
.filter((stem) => !stem.startsWith("example") && !stem.startsWith("_"))
.sort((a, b) => a.localeCompare(b, "en", { numeric: true, sensitivity: "base" }));
}
@@ -504,5 +504,6 @@ function listPngStems (folder) return entries return entries .filter((entry) => entry.isFile() && extname(entry.name).toLowerCase() === ".png") .filter((entry) => entry.isFile() && extname(entry.name).toLowerCase() === ".png") .map((entry) => entry.name.slice(0, -extname(entry.name).length)) .map((entry) => entry.name.slice(0, -extname(entry.name).length)) .filter((stem) => !stem.startsWith("example") && !stem.startsWith("_")) .sort((a, b) => a.localeCompare(b, "en", { numeric: true, sensitivity: "base" })); .sort((a, b) => a.localeCompare(b, "en", { numeric: true, sensitivity: "base" }));}}@@ -1,6 +1,7 @@
import test from "node:test";
import assert from "node:assert/strict";
import {
import
{
NeighborBit,
computeNeighborConnectMask,
neighborConnectStateName,
@@ -9,7 +10,10 @@ import {
neighborConnectBlocksMatch,
parseMaterialNeighborConnectState,
worldTileToChunkLocal,
neighborConnectRefreshTiles
neighborConnectRefreshTiles,
cardinalConnectionSuffix,
composeNamedNeighborConnectState,
parseNamedNeighborConnectMask
} from "../../shared/world/neighborConnect.js";
import { CENTRAL_EXCHANGE_STAFF, pickExchangeClerk } from "../../shared/market/exchange.js";
import { MobId, normalizeSpawnerConfig, isCentralExchangeSpawner } from "../../shared/definitions/mobs.js";
@@ -30,6 +34,43 @@ test("neighbor connect masks cover all NESW combinations", () =>
assert.equal(mask, NeighborBit.n | NeighborBit.e);
});
test("named wall connection suffixes follow nesw / we / esw / wne", () =>
{
assert.equal(cardinalConnectionSuffix(0), "");
assert.equal(cardinalConnectionSuffix(NeighborBit.e | NeighborBit.w), "we");
assert.equal(cardinalConnectionSuffix(NeighborBit.n | NeighborBit.s), "ns");
assert.equal(
cardinalConnectionSuffix(NeighborBit.e | NeighborBit.s | NeighborBit.w),
"esw"
);
assert.equal(
cardinalConnectionSuffix(NeighborBit.w | NeighborBit.n | NeighborBit.e),
"wne"
);
assert.equal(
cardinalConnectionSuffix(NeighborBit.n | NeighborBit.e | NeighborBit.s | NeighborBit.w),
"nesw"
);
const def = { key: "thick-stone-wall", neighborConnect: true, neighborConnectNamed: true };
assert.equal(composeNamedNeighborConnectState(def, 0), "thick-stone-wall");
assert.equal(
composeNamedNeighborConnectState(def, NeighborBit.e | NeighborBit.s | NeighborBit.w),
"thick-stone-wall-esw"
);
assert.equal(parseNamedNeighborConnectMask("thick-stone-wall-wne", def), NeighborBit.w | NeighborBit.n | NeighborBit.e);
assert.equal(parseNamedNeighborConnectMask("14", def), 14);
assert.deepEqual(neighborConnectRefreshTiles(15, 8).length, 5);
});
test("legacy diagonal wall masks keep cardinals only (19 → ne, not nesw)", () =>
{
const def = { key: "thin-stone-wall", neighborConnect: true, neighborConnectNamed: true };
assert.equal(parseNamedNeighborConnectMask("19", def), NeighborBit.n | NeighborBit.e);
assert.equal(composeNamedNeighborConnectState(def, parseNamedNeighborConnectMask("19", def)), "thin-stone-wall-ne");
assert.equal(parseNamedNeighborConnectMask("38", def), NeighborBit.e | NeighborBit.s);
assert.equal(parseNamedNeighborConnectMask("255", def), 15);
});
test("material neighbor-connect states keep wood id and only match same material", () =>
{
const def = BLOCK_DEFINITIONS[BlockType.table];
@@ -1,6 +1,7 @@import test from "node:test";import test from "node:test";import assert from "node:assert/strict";import assert from "node:assert/strict";import {import{ NeighborBit, NeighborBit, computeNeighborConnectMask, computeNeighborConnectMask, neighborConnectStateName, neighborConnectStateName,@@ -9,7 +10,10 @@ import { neighborConnectBlocksMatch, neighborConnectBlocksMatch, parseMaterialNeighborConnectState, parseMaterialNeighborConnectState, worldTileToChunkLocal, worldTileToChunkLocal, neighborConnectRefreshTiles neighborConnectRefreshTiles, cardinalConnectionSuffix, composeNamedNeighborConnectState, parseNamedNeighborConnectMask} from "../../shared/world/neighborConnect.js";} from "../../shared/world/neighborConnect.js";import { CENTRAL_EXCHANGE_STAFF, pickExchangeClerk } from "../../shared/market/exchange.js";import { CENTRAL_EXCHANGE_STAFF, pickExchangeClerk } from "../../shared/market/exchange.js";import { MobId, normalizeSpawnerConfig, isCentralExchangeSpawner } from "../../shared/definitions/mobs.js";import { MobId, normalizeSpawnerConfig, isCentralExchangeSpawner } from "../../shared/definitions/mobs.js";@@ -30,6 +34,43 @@ test("neighbor connect masks cover all NESW combinations", () => assert.equal(mask, NeighborBit.n | NeighborBit.e); assert.equal(mask, NeighborBit.n | NeighborBit.e);});});test("named wall connection suffixes follow nesw / we / esw / wne", () =>{ assert.equal(cardinalConnectionSuffix(0), ""); assert.equal(cardinalConnectionSuffix(NeighborBit.e | NeighborBit.w), "we"); assert.equal(cardinalConnectionSuffix(NeighborBit.n | NeighborBit.s), "ns"); assert.equal( cardinalConnectionSuffix(NeighborBit.e | NeighborBit.s | NeighborBit.w), "esw" ); assert.equal( cardinalConnectionSuffix(NeighborBit.w | NeighborBit.n | NeighborBit.e), "wne" ); assert.equal( cardinalConnectionSuffix(NeighborBit.n | NeighborBit.e | NeighborBit.s | NeighborBit.w), "nesw" ); const def = { key: "thick-stone-wall", neighborConnect: true, neighborConnectNamed: true }; assert.equal(composeNamedNeighborConnectState(def, 0), "thick-stone-wall"); assert.equal( composeNamedNeighborConnectState(def, NeighborBit.e | NeighborBit.s | NeighborBit.w), "thick-stone-wall-esw" ); assert.equal(parseNamedNeighborConnectMask("thick-stone-wall-wne", def), NeighborBit.w | NeighborBit.n | NeighborBit.e); assert.equal(parseNamedNeighborConnectMask("14", def), 14); assert.deepEqual(neighborConnectRefreshTiles(15, 8).length, 5);});test("legacy diagonal wall masks keep cardinals only (19 → ne, not nesw)", () =>{ const def = { key: "thin-stone-wall", neighborConnect: true, neighborConnectNamed: true }; assert.equal(parseNamedNeighborConnectMask("19", def), NeighborBit.n | NeighborBit.e); assert.equal(composeNamedNeighborConnectState(def, parseNamedNeighborConnectMask("19", def)), "thin-stone-wall-ne"); assert.equal(parseNamedNeighborConnectMask("38", def), NeighborBit.e | NeighborBit.s); assert.equal(parseNamedNeighborConnectMask("255", def), 15);});test("material neighbor-connect states keep wood id and only match same material", () =>test("material neighbor-connect states keep wood id and only match same material", () =>{{ const def = BLOCK_DEFINITIONS[BlockType.table]; const def = BLOCK_DEFINITIONS[BlockType.table];@@ -2,19 +2,20 @@ import test from "node:test";
import assert from "node:assert/strict";
import { fileURLToPath } from "node:url";
import { join } from "node:path";
import {
SeasonId,
GrowthSeasonId,
seasonIdAt,
growthSeasonIdAt,
regrowDurationMultiplier,
scaleRegrowDurationMs,
resolveSeasonalVisualState,
preferredSeasonalDefaultState,
typeHasSeasonalStates,
seasonalCycleStates,
seasonIdFromVisualState
} from "../../shared/world/season.js";
import
{
SeasonId,
GrowthSeasonId,
seasonIdAt,
growthSeasonIdAt,
regrowDurationMultiplier,
scaleRegrowDurationMs,
resolveSeasonalVisualState,
preferredSeasonalDefaultState,
typeHasSeasonalStates,
seasonalCycleStates,
seasonIdFromVisualState
} from "../../shared/world/season.js";
import { shopRestockDayKey } from "../../shared/shop/pricing.js";
import { buildSpriteCatalog } from "../src/assets/spriteCatalog.js";
@@ -143,8 +144,8 @@ test("catalog exposes seasonal grass and pine-tree states", () =>
assert.equal(catalog.blocks["pine-tree"].defaultState, "summer");
assert.equal(catalog.blocks["pine-tree"].outdoor, true);
assert.equal(catalog.blocks["pine-tree"].seasonal, true);
assert.equal(catalog.blocks["stone-wall"].outdoor, false);
assert.equal(catalog.blocks["stone-wall"].seasonal, false);
assert.equal(catalog.blocks["thick-stone-wall"].outdoor, false);
assert.equal(catalog.blocks["thick-stone-wall"].seasonal, false);
assert.ok(catalog.images.some((image) => image.name === "block:boulder:boulder-winter"));
assert.ok(catalog.images.some((image) => image.name === "block:boulder:copper-ore-winter"));
assert.ok(catalog.images.some((image) => image.url.includes("boulder-ore-winter.png")));
@@ -2,19 +2,20 @@ import test from "node:test";import assert from "node:assert/strict";import assert from "node:assert/strict";import { fileURLToPath } from "node:url";import { fileURLToPath } from "node:url";import { join } from "node:path";import { join } from "node:path";import {import SeasonId, { GrowthSeasonId, SeasonId, seasonIdAt, GrowthSeasonId, growthSeasonIdAt, seasonIdAt, regrowDurationMultiplier, growthSeasonIdAt, scaleRegrowDurationMs, regrowDurationMultiplier, resolveSeasonalVisualState, scaleRegrowDurationMs, preferredSeasonalDefaultState, resolveSeasonalVisualState, typeHasSeasonalStates, preferredSeasonalDefaultState, seasonalCycleStates, typeHasSeasonalStates, seasonIdFromVisualState seasonalCycleStates,} from "../../shared/world/season.js"; seasonIdFromVisualState } from "../../shared/world/season.js";import { shopRestockDayKey } from "../../shared/shop/pricing.js";import { shopRestockDayKey } from "../../shared/shop/pricing.js";import { buildSpriteCatalog } from "../src/assets/spriteCatalog.js";import { buildSpriteCatalog } from "../src/assets/spriteCatalog.js";@@ -143,8 +144,8 @@ test("catalog exposes seasonal grass and pine-tree states", () => assert.equal(catalog.blocks["pine-tree"].defaultState, "summer"); assert.equal(catalog.blocks["pine-tree"].defaultState, "summer"); assert.equal(catalog.blocks["pine-tree"].outdoor, true); assert.equal(catalog.blocks["pine-tree"].outdoor, true); assert.equal(catalog.blocks["pine-tree"].seasonal, true); assert.equal(catalog.blocks["pine-tree"].seasonal, true); assert.equal(catalog.blocks["stone-wall"].outdoor, false); assert.equal(catalog.blocks["thick-stone-wall"].outdoor, false); assert.equal(catalog.blocks["stone-wall"].seasonal, false); assert.equal(catalog.blocks["thick-stone-wall"].seasonal, false); assert.ok(catalog.images.some((image) => image.name === "block:boulder:boulder-winter")); assert.ok(catalog.images.some((image) => image.name === "block:boulder:boulder-winter")); assert.ok(catalog.images.some((image) => image.name === "block:boulder:copper-ore-winter")); assert.ok(catalog.images.some((image) => image.name === "block:boulder:copper-ore-winter")); assert.ok(catalog.images.some((image) => image.url.includes("boulder-ore-winter.png"))); assert.ok(catalog.images.some((image) => image.url.includes("boulder-ore-winter.png")));@@ -5,7 +5,8 @@ import { join } from "node:path";
import { buildSpriteCatalog } from "../src/assets/spriteCatalog.js";
import { cycleState, isCompanionSpriteStem, parseSpriteStem, resolveState } from "../../shared/definitions/tileSprites.js";
import { decodeChunkBlob, createEmptyChunkData } from "../src/world/chunkData.js";
import { GroundType, BlockType, normalizeGround, setBlockVisualState } from "../../shared/definitions/tiles.js";
import { GroundType, BlockType, normalizeGround, normalizeBlock, setBlockVisualState } from "../../shared/definitions/tiles.js";
import { WOOD_TIER_ORDER } from "../../shared/definitions/materialTiers.js";
import { diffChunks } from "../src/editor/service.js";
const ASSET_ROOT = join(fileURLToPath(new URL("../../client/assets", import.meta.url)));
@@ -13,11 +14,27 @@ const ASSET_ROOT = join(fileURLToPath(new URL("../../client/assets", import.meta
test("sprite folders expose alphabetical states; first is default", () =>
{
const catalog = buildSpriteCatalog(ASSET_ROOT);
assert.deepEqual(catalog.blocks["stone-wall"].states, [
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"
]);
assert.equal(catalog.blocks["stone-wall"].defaultState, "0");
assert.ok(catalog.images.some((image) => image.name === "block:stone-wall:15"));
assert.equal(catalog.blocks["thick-stone-wall"].defaultState, "thick-stone-wall");
assert.ok(catalog.blocks["thick-stone-wall"].states.includes("thick-stone-wall"));
assert.ok(catalog.blocks["thick-stone-wall"].states.includes("thick-stone-wall-esw"));
assert.ok(catalog.blocks["thick-stone-wall"].states.includes("thick-stone-wall-nesw"));
assert.equal(catalog.blocks["thick-stone-wall"].states.length, 16);
assert.ok(catalog.images.some((image) => image.name === "block:thick-stone-wall:thick-stone-wall-nesw"));
assert.equal(catalog.blocks["thin-stone-wall"].defaultState, "thin-stone-wall");
assert.equal(catalog.blocks["thin-stone-wall"].states.length, 16);
assert.ok(catalog.images.some((image) => image.name === "block:thin-stone-wall:thin-stone-wall-wne"));
assert.equal(catalog.blocks["thick-smooth-stone-wall"].states.length, 16);
assert.equal(catalog.blocks["thin-smooth-stone-wall"].states.length, 16);
assert.ok(catalog.images.some((image) => image.name === "block:thick-smooth-stone-wall:thick-smooth-stone-wall"));
assert.equal(catalog.blocks["thick-brick-wall"].states.length, 16);
assert.equal(catalog.blocks["thin-brick-wall"].states.length, 16);
assert.ok(catalog.images.some((image) => image.name === "block:thick-brick-wall:thick-brick-wall-we"));
assert.ok(catalog.images.some((image) => image.name === "block:thick-wood-wall:pine-0"));
assert.ok(catalog.images.some((image) => image.name === "block:thin-wood-wall:oak-15"));
assert.equal(catalog.blocks["thick-wood-wall"].states.length, WOOD_TIER_ORDER.length * 16);
assert.equal(catalog.blocks["thick-cliff"].states.length, 16);
assert.equal(catalog.blocks["thin-cliff"].states.length, 16);
assert.ok(catalog.images.some((image) => image.name === "block:thick-cliff:thick-cliff-nesw"));
assert.equal(catalog.images[0].subImgTotal, 1);
assert.equal(catalog.images[0].perRow, 1);
});
@@ -117,17 +134,28 @@ test("gameplay can set a block visual state", () =>
{
const data = createEmptyChunkData();
data.blocks[0] = { typeId: BlockType.stoneWall, state: null, config: null };
setBlockVisualState(data.blocks[0], "2");
assert.equal(data.blocks[0].state, "2");
setBlockVisualState(data.blocks[0], "thick-stone-wall-e");
assert.equal(data.blocks[0].state, "thick-stone-wall-e");
});
test("chunk diffs mention visual state changes", () =>
{
const previous = createEmptyChunkData();
const next = createEmptyChunkData();
previous.blocks[0] = { typeId: BlockType.stoneWall, state: "1", config: null };
next.blocks[0] = { typeId: BlockType.stoneWall, state: "2", config: null };
previous.blocks[0] = { typeId: BlockType.stoneWall, state: "thick-stone-wall-n", config: null };
next.blocks[0] = { typeId: BlockType.stoneWall, state: "thick-stone-wall-e", config: null };
const bullets = diffChunks(0, 0, previous, next, true);
assert.ok(bullets.some((line) => line.includes("state changed from 1 to 2")));
assert.ok(bullets.some((line) =>
line.includes("state changed from thick-stone-wall-n to thick-stone-wall-e")));
assert.equal(normalizeGround(GroundType.grass).typeId, GroundType.grass);
});
test("normalizeBlock migrates legacy numeric wall states to named suffixes", () =>
{
const migrated = normalizeBlock({ typeId: BlockType.stoneWall, state: "14", config: null });
assert.equal(migrated.state, "thick-stone-wall-esw");
const alone = normalizeBlock({ typeId: BlockType.stoneWallThin, state: "0", config: null });
assert.equal(alone.state, "thin-stone-wall");
const corner = normalizeBlock({ typeId: BlockType.stoneWallThin, state: "19", config: null });
assert.equal(corner.state, "thin-stone-wall-ne");
});
@@ -5,7 +5,8 @@ import { join } from "node:path";import { buildSpriteCatalog } from "../src/assets/spriteCatalog.js";import { buildSpriteCatalog } from "../src/assets/spriteCatalog.js";import { cycleState, isCompanionSpriteStem, parseSpriteStem, resolveState } from "../../shared/definitions/tileSprites.js";import { cycleState, isCompanionSpriteStem, parseSpriteStem, resolveState } from "../../shared/definitions/tileSprites.js";import { decodeChunkBlob, createEmptyChunkData } from "../src/world/chunkData.js";import { decodeChunkBlob, createEmptyChunkData } from "../src/world/chunkData.js";import { GroundType, BlockType, normalizeGround, setBlockVisualState } from "../../shared/definitions/tiles.js";import { GroundType, BlockType, normalizeGround, normalizeBlock, setBlockVisualState } from "../../shared/definitions/tiles.js";import { WOOD_TIER_ORDER } from "../../shared/definitions/materialTiers.js";import { diffChunks } from "../src/editor/service.js";import { diffChunks } from "../src/editor/service.js";const ASSET_ROOT = join(fileURLToPath(new URL("../../client/assets", import.meta.url)));const ASSET_ROOT = join(fileURLToPath(new URL("../../client/assets", import.meta.url)));@@ -13,11 +14,27 @@ const ASSET_ROOT = join(fileURLToPath(new URL("../../client/assets", import.metatest("sprite folders expose alphabetical states; first is default", () =>test("sprite folders expose alphabetical states; first is default", () =>{{ const catalog = buildSpriteCatalog(ASSET_ROOT); const catalog = buildSpriteCatalog(ASSET_ROOT); assert.deepEqual(catalog.blocks["stone-wall"].states, [ assert.equal(catalog.blocks["thick-stone-wall"].defaultState, "thick-stone-wall"); "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15" assert.ok(catalog.blocks["thick-stone-wall"].states.includes("thick-stone-wall")); ]); assert.ok(catalog.blocks["thick-stone-wall"].states.includes("thick-stone-wall-esw")); assert.equal(catalog.blocks["stone-wall"].defaultState, "0"); assert.ok(catalog.blocks["thick-stone-wall"].states.includes("thick-stone-wall-nesw")); assert.ok(catalog.images.some((image) => image.name === "block:stone-wall:15")); assert.equal(catalog.blocks["thick-stone-wall"].states.length, 16); assert.ok(catalog.images.some((image) => image.name === "block:thick-stone-wall:thick-stone-wall-nesw")); assert.equal(catalog.blocks["thin-stone-wall"].defaultState, "thin-stone-wall"); assert.equal(catalog.blocks["thin-stone-wall"].states.length, 16); assert.ok(catalog.images.some((image) => image.name === "block:thin-stone-wall:thin-stone-wall-wne")); assert.equal(catalog.blocks["thick-smooth-stone-wall"].states.length, 16); assert.equal(catalog.blocks["thin-smooth-stone-wall"].states.length, 16); assert.ok(catalog.images.some((image) => image.name === "block:thick-smooth-stone-wall:thick-smooth-stone-wall")); assert.equal(catalog.blocks["thick-brick-wall"].states.length, 16); assert.equal(catalog.blocks["thin-brick-wall"].states.length, 16); assert.ok(catalog.images.some((image) => image.name === "block:thick-brick-wall:thick-brick-wall-we")); assert.ok(catalog.images.some((image) => image.name === "block:thick-wood-wall:pine-0")); assert.ok(catalog.images.some((image) => image.name === "block:thin-wood-wall:oak-15")); assert.equal(catalog.blocks["thick-wood-wall"].states.length, WOOD_TIER_ORDER.length * 16); assert.equal(catalog.blocks["thick-cliff"].states.length, 16); assert.equal(catalog.blocks["thin-cliff"].states.length, 16); assert.ok(catalog.images.some((image) => image.name === "block:thick-cliff:thick-cliff-nesw")); assert.equal(catalog.images[0].subImgTotal, 1); assert.equal(catalog.images[0].subImgTotal, 1); assert.equal(catalog.images[0].perRow, 1); assert.equal(catalog.images[0].perRow, 1);});});@@ -117,17 +134,28 @@ test("gameplay can set a block visual state", () =>{{ const data = createEmptyChunkData(); const data = createEmptyChunkData(); data.blocks[0] = { typeId: BlockType.stoneWall, state: null, config: null }; data.blocks[0] = { typeId: BlockType.stoneWall, state: null, config: null }; setBlockVisualState(data.blocks[0], "2"); setBlockVisualState(data.blocks[0], "thick-stone-wall-e"); assert.equal(data.blocks[0].state, "2"); assert.equal(data.blocks[0].state, "thick-stone-wall-e");});});test("chunk diffs mention visual state changes", () =>test("chunk diffs mention visual state changes", () =>{{ const previous = createEmptyChunkData(); const previous = createEmptyChunkData(); const next = createEmptyChunkData(); const next = createEmptyChunkData(); previous.blocks[0] = { typeId: BlockType.stoneWall, state: "1", config: null }; previous.blocks[0] = { typeId: BlockType.stoneWall, state: "thick-stone-wall-n", config: null }; next.blocks[0] = { typeId: BlockType.stoneWall, state: "2", config: null }; next.blocks[0] = { typeId: BlockType.stoneWall, state: "thick-stone-wall-e", config: null }; const bullets = diffChunks(0, 0, previous, next, true); const bullets = diffChunks(0, 0, previous, next, true); assert.ok(bullets.some((line) => line.includes("state changed from 1 to 2"))); assert.ok(bullets.some((line) => line.includes("state changed from thick-stone-wall-n to thick-stone-wall-e"))); assert.equal(normalizeGround(GroundType.grass).typeId, GroundType.grass); assert.equal(normalizeGround(GroundType.grass).typeId, GroundType.grass);});});test("normalizeBlock migrates legacy numeric wall states to named suffixes", () =>{ const migrated = normalizeBlock({ typeId: BlockType.stoneWall, state: "14", config: null }); assert.equal(migrated.state, "thick-stone-wall-esw"); const alone = normalizeBlock({ typeId: BlockType.stoneWallThin, state: "0", config: null }); assert.equal(alone.state, "thin-stone-wall"); const corner = normalizeBlock({ typeId: BlockType.stoneWallThin, state: "19", config: null }); assert.equal(corner.state, "thin-stone-wall-ne");});