Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(tilemap): the atlas carries the guarantee, so the UV rect stops shrinking

yhh690ebea0bf2e
diff --git a/pipeline/src/assets/tilesetExtrude.ts b/pipeline/src/assets/tilesetExtrude.ts
new file mode 100644
index 000000000..f300a2697
--- /dev/null
+++ b/pipeline/src/assets/tilesetExtrude.ts
@@ -0,0 +1,157 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Tileset atlas extrusion for the asset import. Pure and deterministic:
+ * the same pixels and grid produce byte-identical output, so it composes
+ * with content-addressed staging exactly like {@link atlasPacker}.
+ *
+ * WHY THIS EXISTS. A tile quad's UV rect and its geometry rect must be the same
+ * rect, or the tile's texture is stretched and the sampling phase resets at every
+ * cell boundary — a visible seam on a wall of repeated tiles, and one that moves
+ * as the camera does, because which boundary lands mid-pixel keeps changing.
+ * The renderer used to buy no-bleed by insetting the UV half a texel per edge,
+ * which is exactly that stretch: the sampled rect lost a whole texel while the
+ * quad kept the full tile.
+ *
+ * On a gapless atlas the two cannot both hold from UVs alone. Extrusion removes
+ * the conflict from the DATA instead: give every cell a border made of copies of
+ * its own edge pixels, and a sample that strays outside the cell reads the value
+ * it would have clamped to anyway. The renderer then sends the exact cell rect
+ * and insets nothing.
+ *
+ * The output is a repack, not an edit in place: cells move to `margin = extrude`,
+ * `spacing = 2 * extrude`, which is the only layout where every cell gets its own
+ * border regardless of what the source spacing was.
+ */
+import { PNG } from 'pngjs';
+import { atlasCells } from '../../../sdk/src/tilemap/tilesetResolve';
+
+/** Raw RGBA8, row 0 = image top. Structurally an `AtlasInputImage` without the key. */
+export interface RgbaImage {
+ width: number;
+ height: number;
+ /** RGBA8, width*height*4 bytes. */
+ rgba: Uint8Array;
+}
+
+/** Where an atlas's cells are, in the source image's own pixels (Tiled's model). */
+export interface TilesetGrid {
+ tileWidth: number;
+ tileHeight: number;
+ /** Border before the first cell, on every side. */
+ margin: number;
+ /** Gap between adjacent cells. */
+ spacing: number;
+ /** Cells per row. 0 or absent → derived from the image width. */
+ columns?: number;
+}
+
+/** An extruded atlas plus the grid that now describes it. */
+export interface ExtrudedTileset extends RgbaImage {
+ /** Always `extrude` — the border every cell now carries. */
+ margin: number;
+ /** Always `2 * extrude` — one border from each of the two cells it separates. */
+ spacing: number;
+ extrude: number;
+ columns: number;
+ rows: number;
+}
+
+/**
+ * ONE texel is enough, and the reason is a property of the filter rather than of
+ * the art: `GL_LINEAR` without mipmaps weights a 2x2 texel neighbourhood, so a
+ * sample taken anywhere inside a cell reaches at most one texel outside it.
+ * A tileset that ever gains mipmaps needs this to grow with the chain — mip n
+ * reaches 2^n texels — which is why the renderer reads the number back off the
+ * asset instead of assuming it.
+ */
+export const DEFAULT_EXTRUDE = 1;
+
+/**
+ * The cells `grid` describes in an image of this size. Asks the SDK's
+ * `atlasCells` rather than repeating the arithmetic: the engine skips a tile
+ * whose cell the atlas does not hold, and it must skip the same ones.
+ */
+export function gridCells(img: RgbaImage, grid: TilesetGrid): { columns: number; rows: number } {
+ const wide = atlasCells(img.width, grid.margin, grid.tileWidth, grid.spacing);
+ const tall = atlasCells(img.height, grid.margin, grid.tileHeight, grid.spacing);
+ // An authored column count may be NARROWER than the image (a tileset that
+ // uses the left part of a sheet); it may not be wider, or ids would address
+ // cells with no texels. The engine clamps the same way.
+ const columns = grid.columns && grid.columns > 0 ? Math.min(grid.columns, wide) : wide;
+ return { columns, rows: tall };
+}
+
+/**
+ * Rebuild `img` with `extrude` px of its own edge pixels around every cell.
+ *
+ * Each output cell block is filled by sampling the source cell at clamped
+ * coordinates — which IS per-cell `CLAMP_TO_EDGE`, and gets the four corners
+ * right for free rather than as four more cases.
+ *
+ * Throws on a grid that describes no cells: an atlas that silently extruded to
+ * nothing would ship a blank tileset, and the caller can still choose to leave
+ * the texture alone.
+ */
+export function extrudeTileset(
+ img: RgbaImage,
+ grid: TilesetGrid,
+ extrude: number = DEFAULT_EXTRUDE,
+): ExtrudedTileset {
+ const e = Math.max(0, Math.floor(extrude));
+ const { columns, rows } = gridCells(img, grid);
+ if (columns <= 0 || rows <= 0) {
+ throw new Error(
+ `tileset grid describes no cells: ${img.width}x${img.height} px, `
+ + `tile ${grid.tileWidth}x${grid.tileHeight}, margin ${grid.margin}, spacing ${grid.spacing}`);
+ }
+
+ const cellW = grid.tileWidth + 2 * e;
+ const cellH = grid.tileHeight + 2 * e;
+ const outW = columns * cellW;
+ const outH = rows * cellH;
+ const out = new Uint8Array(outW * outH * 4);
+
+ for (let row = 0; row < rows; row++) {
+ const srcY0 = grid.margin + row * (grid.tileHeight + grid.spacing);
+ const dstY0 = row * cellH;
+ for (let col = 0; col < columns; col++) {
+ const srcX0 = grid.margin + col * (grid.tileWidth + grid.spacing);
+ const dstX0 = col * cellW;
+ for (let oy = 0; oy < cellH; oy++) {
+ const sy = srcY0 + clamp(oy - e, 0, grid.tileHeight - 1);
+ for (let ox = 0; ox < cellW; ox++) {
+ const sx = srcX0 + clamp(ox - e, 0, grid.tileWidth - 1);
+ const s = (sy * img.width + sx) * 4;
+ const d = ((dstY0 + oy) * outW + dstX0 + ox) * 4;
+ out[d] = img.rgba[s]!;
+ out[d + 1] = img.rgba[s + 1]!;
+ out[d + 2] = img.rgba[s + 2]!;
+ out[d + 3] = img.rgba[s + 3]!;
+ }
+ }
+ }
+ }
+
+ // margin = e and spacing = 2e is not a choice among layouts, it is the only
+ // one: every cell needs its own e-px border, and two neighbours contribute
+ // one each to the gap between them.
+ return { width: outW, height: outH, rgba: out, margin: e, spacing: 2 * e, extrude: e, columns, rows };
+}
+
+function clamp(v: number, lo: number, hi: number): number {
+ return v < lo ? lo : v > hi ? hi : v;
+}
+
+/** Decode a PNG into the extruder's input shape. */
+export function decodeRgbaPng(png: Uint8Array): RgbaImage {
+ const decoded = PNG.sync.read(Buffer.from(png));
+ return { width: decoded.width, height: decoded.height, rgba: new Uint8Array(decoded.data) };
+}
+
+/** Encode raw RGBA8 (row 0 = top) to PNG bytes. */
+export function encodeRgbaPng(width: number, height: number, rgba: Uint8Array): Uint8Array {
+ const png = new PNG({ width, height });
+ Buffer.from(rgba).copy(png.data);
+ return new Uint8Array(PNG.sync.write(png));
+}
diff --git a/pipeline/tests/tileset-extrude.test.ts b/pipeline/tests/tileset-extrude.test.ts
new file mode 100644
index 000000000..6eec15a07
--- /dev/null
+++ b/pipeline/tests/tileset-extrude.test.ts
@@ -0,0 +1,290 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Tileset extrusion — the property is "a sample taken inside a cell never
+ * reads another cell", so the tests SAMPLE, with the same bilinear filter
+ * the GPU uses. A test that only compared sizes and border bytes would
+ * pass on an extruder that copied the right pixels to the wrong place.
+ *
+ * Every claim about the extruded atlas is paired with the same
+ * measurement on the packed one, which must FAIL it — otherwise the
+ * measurement is not sensitive to the thing being fixed.
+ */
+import { describe, it, expect } from 'vitest';
+import {
+ extrudeTileset, gridCells, decodeRgbaPng, encodeRgbaPng, DEFAULT_EXTRUDE,
+ type RgbaImage, type TilesetGrid,
+} from '../src/assets/tilesetExtrude';
+
+/** An atlas of solid cells, one distinct colour each — so "which cell did this pixel come from" is decidable. */
+function solidCells(tileW: number, tileH: number, cols: number, rows: number,
+ margin = 0, spacing = 0): RgbaImage {
+ const width = 2 * margin + cols * tileW + (cols - 1) * spacing;
+ const height = 2 * margin + rows * tileH + (rows - 1) * spacing;
+ const rgba = new Uint8Array(width * height * 4);
+ for (let row = 0; row < rows; row++) {
+ for (let col = 0; col < cols; col++) {
+ const id = row * cols + col + 1;
+ for (let y = 0; y < tileH; y++) {
+ for (let x = 0; x < tileW; x++) {
+ const px = margin + col * (tileW + spacing) + x;
+ const py = margin + row * (tileH + spacing) + y;
+ const i = (py * width + px) * 4;
+ rgba[i] = id * 20; rgba[i + 1] = 255 - id * 20; rgba[i + 2] = id; rgba[i + 3] = 255;
+ }
+ }
+ }
+ }
+ return { width, height, rgba };
+}
+
+/** GL_LINEAR with CLAMP_TO_EDGE, in texel units: texel (i,j) is centred at (i+0.5, j+0.5). */
+function bilinear(img: RgbaImage, u: number, v: number): [number, number, number, number] {
+ const fx = u - 0.5, fy = v - 0.5;
+ const x0 = Math.floor(fx), y0 = Math.floor(fy);
+ const tx = fx - x0, ty = fy - y0;
+ const at = (x: number, y: number, c: number) => {
+ const cx = Math.min(img.width - 1, Math.max(0, x));
+ const cy = Math.min(img.height - 1, Math.max(0, y));
+ return img.rgba[(cy * img.width + cx) * 4 + c]!;
+ };
+ const out: [number, number, number, number] = [0, 0, 0, 0];
+ for (let c = 0; c < 4; c++) {
+ const a = at(x0, y0, c) * (1 - tx) + at(x0 + 1, y0, c) * tx;
+ const b = at(x0, y0 + 1, c) * (1 - tx) + at(x0 + 1, y0 + 1, c) * tx;
+ out[c] = a * (1 - ty) + b * ty;
+ }
+ return out;
+}
+
+describe('extrudeTileset — layout', () => {
+ it('repacks to margin = extrude, spacing = 2 * extrude', () => {
+ const src = solidCells(8, 8, 3, 2);
+ const out = extrudeTileset(src, { tileWidth: 8, tileHeight: 8, margin: 0, spacing: 0 });
+ expect(out.extrude).toBe(DEFAULT_EXTRUDE);
+ expect(out.margin).toBe(1);
+ expect(out.spacing).toBe(2);
+ expect(out.columns).toBe(3);
+ expect(out.rows).toBe(2);
+ expect(out.width).toBe(3 * (8 + 2));
+ expect(out.height).toBe(2 * (8 + 2));
+ });
+
+ it('the layout it writes is the one the engine reads back', () => {
+ // The renderer locates cell (col,row) from margin/spacing alone. If the
+ // repack and that arithmetic disagree, every tile samples its neighbour.
+ const src = solidCells(6, 10, 4, 3, 2, 4);
+ const out = extrudeTileset(src, { tileWidth: 6, tileHeight: 10, margin: 2, spacing: 4 });
+ const cells = gridCells(out, { tileWidth: 6, tileHeight: 10, margin: out.margin, spacing: out.spacing });
+ expect(cells).toEqual({ columns: 4, rows: 3 });
+ });
+
+ it('keeps the cell body byte-identical — extrusion adds a border, it does not resample', () => {
+ const src = solidCells(5, 7, 2, 2, 1, 3);
+ const grid: TilesetGrid = { tileWidth: 5, tileHeight: 7, margin: 1, spacing: 3 };
+ const out = extrudeTileset(src, grid);
+ for (let row = 0; row < 2; row++) {
+ for (let col = 0; col < 2; col++) {
+ for (let y = 0; y < 7; y++) {
+ for (let x = 0; x < 5; x++) {
+ const s = ((1 + row * (7 + 3) + y) * src.width + 1 + col * (5 + 3) + x) * 4;
+ const d = ((row * 9 + 1 + y) * out.width + col * 7 + 1 + x) * 4;
+ expect([out.rgba[d], out.rgba[d + 1], out.rgba[d + 2], out.rgba[d + 3]])
+ .toEqual([src.rgba[s], src.rgba[s + 1], src.rgba[s + 2], src.rgba[s + 3]]);
+ }
+ }
+ }
+ }
+ });
+
+ it('refuses a grid that describes no cells rather than emitting a blank atlas', () => {
+ const src = solidCells(8, 8, 1, 1);
+ expect(() => extrudeTileset(src, { tileWidth: 64, tileHeight: 64, margin: 0, spacing: 0 }))
+ .toThrow(/no cells/);
+ });
+
+ it('is deterministic — the same pixels give the same bytes', () => {
+ const src = solidCells(4, 4, 3, 3);
+ const grid: TilesetGrid = { tileWidth: 4, tileHeight: 4, margin: 0, spacing: 0 };
+ const a = extrudeTileset(src, grid);
+ const b = extrudeTileset(src, grid);
+ expect(Buffer.from(a.rgba).equals(Buffer.from(b.rgba))).toBe(true);
+ expect(Buffer.from(encodeRgbaPng(a.width, a.height, a.rgba))
+ .equals(Buffer.from(encodeRgbaPng(b.width, b.height, b.rgba)))).toBe(true);
+ });
+
+ it('survives a PNG round trip', () => {
+ const src = solidCells(8, 8, 2, 2);
+ const out = extrudeTileset(src, { tileWidth: 8, tileHeight: 8, margin: 0, spacing: 0 });
+ const back = decodeRgbaPng(encodeRgbaPng(out.width, out.height, out.rgba));
+ expect(back.width).toBe(out.width);
+ expect(back.height).toBe(out.height);
+ expect(Buffer.from(back.rgba).equals(Buffer.from(out.rgba))).toBe(true);
+ });
+});
+
+describe('extrudeTileset — the property the seam came from', () => {
+ const TILE = 8, COLS = 3, ROWS = 3;
+
+ /** Sample right across a cell's exact rect and report every colour seen. */
+ function sweepCell(img: RgbaImage, x0: number, y0: number, w: number, h: number): Set<string> {
+ const seen = new Set<string>();
+ const STEPS = 40;
+ for (let i = 0; i <= STEPS; i++) {
+ for (let j = 0; j <= STEPS; j++) {
+ const c = bilinear(img, x0 + (i / STEPS) * w, y0 + (j / STEPS) * h);
+ seen.add(c.map((v) => Math.round(v)).join(','));
+ }
+ }
+ return seen;
+ }
+
+ it('a sample anywhere in an extruded cell reads only that cell', () => {
+ const src = solidCells(TILE, TILE, COLS, ROWS);
+ const out = extrudeTileset(src, { tileWidth: TILE, tileHeight: TILE, margin: 0, spacing: 0 });
+ for (let row = 0; row < ROWS; row++) {
+ for (let col = 0; col < COLS; col++) {
+ const id = row * COLS + col + 1;
+ const want = [id * 20, 255 - id * 20, id, 255].join(',');
+ const seen = sweepCell(out, col * (TILE + 2) + 1, row * (TILE + 2) + 1, TILE, TILE);
+ expect([...seen]).toEqual([want]);
+ }
+ }
+ });
+
+ it('...and the same sweep on the PACKED atlas does not — so the sweep can tell them apart', () => {
+ const src = solidCells(TILE, TILE, COLS, ROWS);
+ // The interior cell is surrounded on all four sides, so it is the one a
+ // gapless atlas must fail on.
+ const seen = sweepCell(src, 1 * TILE, 1 * TILE, TILE, TILE);
+ expect(seen.size).toBeGreaterThan(1);
+ });
+});
+
+describe('extrudeTileset — the seam itself, as the renderer draws it', () => {
+ /**
+ * Two cells of art that is continuous across their shared edge — a ramp — is
+ * the shape the reported bug appeared on: a wall of tiles meant to butt
+ * together. Draw a scanline the way TilemapRenderPlugin does and compare it
+ * with the ramp it is supposed to reproduce.
+ *
+ * Three modes, and the third is why extrusion is the answer rather than just
+ * dropping the inset. Measured at 6 screen px per texel, worst departure from
+ * the art in levels (the ramp rises 16 per texel):
+ *
+ * mode whole tile interior only step at the boundary
+ * packed+inset 7.83 6.83 18.33
+ * extruded 6.67 0.00 16.00
+ * packed+exact 0.00 0.00 2.67
+ *
+ * `packed+exact` looks perfect ONLY because this fixture's atlas neighbour is
+ * also its map neighbour. In a real map the next tile is an arbitrary cell, so
+ * that column is reading foreign content — which the bleed test below shows.
+ */
+ const TILE = 8, COLS = 2, SCALE = 6.0;
+
+ function ramp(): RgbaImage {
+ const width = COLS * TILE, height = TILE;
+ const rgba = new Uint8Array(width * height * 4);
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ const i = (y * width + x) * 4;
+ rgba[i] = x * 16; rgba[i + 1] = x * 16; rgba[i + 2] = x * 16; rgba[i + 3] = 255;
+ }
+ }
+ return { width, height, rgba };
+ }
+
+ /** One scanline of the two quads, `inset` texels in from each cell edge. */
+ function scanline(img: RgbaImage, cellX: (c: number) => number, inset: number, vRow: number): number[] {
+ const out: number[] = [];
+ for (let c = 0; c < COLS; c++) {
+ const uMin = cellX(c) + inset;
+ const uMax = cellX(c) + TILE - inset;
+ const quadWidth = TILE * SCALE;
+ for (let p = 0; p < quadWidth; p++) {
+ const s = (p + 0.5) / quadWidth;
+ out.push(bilinear(img, uMin + s * (uMax - uMin), vRow)[0]);
+ }
+ }
+ return out;
+ }
+
+ /** What a single un-tiled image of the same ramp would have produced. */
+ function ideal(img: RgbaImage, vRow: number): number[] {
+ const out: number[] = [];
+ for (let p = 0; p < COLS * TILE * SCALE; p++) {
+ out.push(bilinear(img, (p + 0.5) / SCALE, vRow)[0]);
+ }
+ return out;
+ }
+
+ /** Worst departure from the art over a span of the scanline. */
+ function worstOver(line: number[], want: number[], lo: number, hi: number): number {
+ return Math.max(...line.slice(lo, hi).map((v, i) => Math.abs(v - want[lo + i]!)));
+ }
+
+ const N = COLS * TILE * SCALE;
+ const BOUNDARY = TILE * SCALE; // first screen px of cell 1
+ const EDGE = Math.ceil(0.5 * SCALE); // the outer half-texel, in screen px
+
+ it('THE FIX: the tile interior becomes exact, where the inset was wrong everywhere', () => {
+ const src = ramp();
+ const out = extrudeTileset(src, { tileWidth: TILE, tileHeight: TILE, margin: 0, spacing: 0 });
+ const want = ideal(src, 2);
+ // The extruded row-0 body starts one px down, so the same art row is v + 1.
+ const extruded = scanline(out, (c) => c * (TILE + 2) + 1, 0, 3);
+ const inset = scanline(src, (c) => c * TILE, 0.5, 2);
+ const interior = (l: number[]) => Math.max(
+ worstOver(l, want, EDGE, BOUNDARY - EDGE),
+ worstOver(l, want, BOUNDARY + EDGE, N - EDGE));
+
+ expect(interior(extruded)).toBeLessThan(1e-9); // f64 residue in the test's own filter, not a departure
+ // Not a near miss: the inset displaces the art by up to a full texel, and it
+ // does so across the WHOLE tile, not just at its edges. That ramp of error
+ // is what made a boundary read as a break in the pattern.
+ expect(interior(inset)).toBeGreaterThan(6);
+ });
+
+ it('what extrusion does NOT do: the filter still stops at the tile boundary', () => {
+ // Stated so it cannot be mistaken for a regression later. The map's next tile
+ // is not the atlas's next cell, so no atlas layout can let the filter blend
+ // across a tile edge; the border clamps instead. The step is therefore one
+ // texel of art — the same as NEAREST would give there — and it is a residual,
+ // not a defect. It is still SMALLER than the inset's, which adds its own
+ // displacement on top.
+ const src = ramp();
+ const out = extrudeTileset(src, { tileWidth: TILE, tileHeight: TILE, margin: 0, spacing: 0 });
+ const step = (l: number[]) => Math.abs(l[BOUNDARY]! - l[BOUNDARY - 1]!);
+ const extruded = scanline(out, (c) => c * (TILE + 2) + 1, 0, 3);
+ const inset = scanline(src, (c) => c * TILE, 0.5, 2);
+
+ expect(step(extruded)).toBeCloseTo(16, 5); // exactly one texel of the ramp
+ expect(step(inset)).toBeGreaterThan(step(extruded));
+ // A camera that lands tiles on whole pixels removes even this one; that is a
+ // property of the camera, not of the atlas. See Camera.pixelPerfect.
+ });
+
+ it('why not simply drop the inset: a packed atlas then reads the next cell', () => {
+ // The mode that measured perfectly on a ramp does so only because the ramp's
+ // atlas neighbour IS its map neighbour. Give the two cells unrelated content
+ // and the exact rect on a packed atlas pulls one into the other.
+ const width = COLS * TILE, height = TILE;
+ const rgba = new Uint8Array(width * height * 4);
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ const i = (y * width + x) * 4;
+ const v = x < TILE ? 0 : 255; // cell 0 black, cell 1 white
+ rgba[i] = v; rgba[i + 1] = v; rgba[i + 2] = v; rgba[i + 3] = 255;
+ }
+ }
+ const src: RgbaImage = { width, height, rgba };
+ const out = extrudeTileset(src, { tileWidth: TILE, tileHeight: TILE, margin: 0, spacing: 0 });
+
+ const packedExact = scanline(src, (c) => c * TILE, 0, 2);
+ const extruded = scanline(out, (c) => c * (TILE + 2) + 1, 0, 3);
+ // Cell 0 is solid black. Anything above 0 in its span came from cell 1.
+ expect(Math.max(...packedExact.slice(0, BOUNDARY))).toBeGreaterThan(0);
+ expect(Math.max(...extruded.slice(0, BOUNDARY))).toBe(0);
+ });
+});
diff --git a/sdk/src/tilemap/tilemapAPI.ts b/sdk/src/tilemap/tilemapAPI.ts
index 999209147..4164a885c 100644
--- a/sdk/src/tilemap/tilemapAPI.ts
+++ b/sdk/src/tilemap/tilemapAPI.ts
@@ -95,6 +95,16 @@ export function shutdownTilemapAPI(): void {
* calls are the host/tooling surface (the editor's tile tools, tests) where no
* App is in scope. Both names are the same object.
*/
+/**
+ * u32s per slot in the `tilemap_setTilesets` buffer, and the order they are in:
+ * [firstId, textureHandle, columns, margin, spacing, extrude].
+ *
+ * Two files unpack this — here and `TilemapBindings.cpp`. There is no generator
+ * for it, so the number is named on both sides and the field list is stated
+ * once, rather than a bare 6 appearing twice and drifting.
+ */
+export const TILESET_SLOT_STRIDE = 6;
+
export const TilemapAPI = {
initLayer(entity: number, width: number, height: number,
tileWidth: number, tileHeight: number): void {
@@ -129,11 +139,19 @@ export const TilemapAPI = {
});
},
- /** Replace the layer's multi-tileset table. Empty array reverts to single-tileset. */
- setTilesets(entity: number, slots: { firstId: number; textureHandle: number; columns: number; margin?: number; spacing?: number }[]): void {
+ /**
+ * Replace the layer's multi-tileset table. Empty array reverts to single-tileset.
+ *
+ * The packed field ORDER is the contract with `tilemap_setTilesets`, and it is
+ * written down here and read there — see TILESET_SLOT_STRIDE.
+ */
+ setTilesets(entity: number, slots: {
+ firstId: number; textureHandle: number; columns: number;
+ margin?: number; spacing?: number; extrude?: number;
+ }[]): void {
const m = module_;
if (!m) return;
- const STRIDE = 5;
+ const STRIDE = TILESET_SLOT_STRIDE;
const packed = new Uint32Array(slots.length * STRIDE);
for (let i = 0; i < slots.length; i++) {
packed[i * STRIDE] = slots[i].firstId;
@@ -141,6 +159,7 @@ export const TilemapAPI = {
packed[i * STRIDE + 2] = slots[i].columns;
packed[i * STRIDE + 3] = slots[i].margin ?? 0;
packed[i * STRIDE + 4] = slots[i].spacing ?? 0;
+ packed[i * STRIDE + 5] = slots[i].extrude ?? 0;
}
withMalloc(m, packed.byteLength, ptr => {
new Uint32Array(m.HEAPU8.buffer, ptr, packed.length).set(packed);
diff --git a/sdk/src/tilemap/tilesetAsset.ts b/sdk/src/tilemap/tilesetAsset.ts
index 7e964e586..70ba5cceb 100644
--- a/sdk/src/tilemap/tilesetAsset.ts
+++ b/sdk/src/tilemap/tilesetAsset.ts
@@ -114,6 +114,24 @@ export interface TilesetAsset {
margin: number;
/** Gap (px) between adjacent tiles. */
spacing: number;
+ /**
+ * Border of duplicated edge pixels each cell carries in the atlas, in px.
+ *
+ * A PROPERTY OF THE TEXTURE, established by whoever produced it — the import
+ * writes an extruded atlas and stamps the number here. Non-zero means a
+ * sample that strays outside a cell reads a copy of that cell's own edge, so
+ * the renderer sends the exact cell rect and insets nothing.
+ *
+ * Zero means it must still buy no-bleed with a half-texel inset, and on a
+ * gapless atlas those two cannot both hold from UVs alone: the inset shrinks
+ * the sampled rect by a whole texel while the quad keeps the full tile, so
+ * every tile is stretched by N/(N-1) and the sampling phase resets at each
+ * boundary. That is a seam on tiles meant to butt together.
+ *
+ * Non-zero implies `margin === extrude` and `spacing === 2 * extrude`: the
+ * extruded layout is the only one where every cell gets its own border.
+ */
+ extrude: number;
/** Total tile count (optional; otherwise derived from the texture + grid). */
tileCount?: number;
/** Per-tile metadata keyed by tile id (1-based; id 0 = empty). */
@@ -242,6 +260,7 @@ export function parseTileset(rawJson: unknown): TilesetAsset {
columns: posInt(raw?.columns, 1),
margin: nonNeg(raw?.margin, 0),
spacing: nonNeg(raw?.spacing, 0),
+ extrude: nonNeg(raw?.extrude, 0),
tileCount: Number.isInteger(raw?.tileCount) ? raw?.tileCount : undefined,
tiles,
...(terrains.length > 0 ? { terrains } : {}),
@@ -262,6 +281,9 @@ export function serializeTileset(asset: TilesetAsset): Record<string, unknown> {
spacing: asset.spacing,
tiles,
};
+ // Only written when it is true: an `extrude: 0` on every tileset ever made
+ // would be a field that says nothing, and older assets already mean 0.
+ if (asset.extrude > 0) out.extrude = asset.extrude;
if (asset.tileCount !== undefined) out.tileCount = asset.tileCount;
if (asset.terrains && asset.terrains.length > 0) out.terrains = asset.terrains;
return out;
@@ -274,7 +296,7 @@ export function createTileset(
return {
version: TILESET_FORMAT_VERSION,
texture, tileWidth, tileHeight, columns,
- margin: 0, spacing: 0, tiles: {},
+ margin: 0, spacing: 0, extrude: 0, tiles: {},
};
}
diff --git a/sdk/src/tilemap/tilesetResolve.ts b/sdk/src/tilemap/tilesetResolve.ts
index 95a696189..4ece28e1a 100644
--- a/sdk/src/tilemap/tilesetResolve.ts
+++ b/sdk/src/tilemap/tilesetResolve.ts
@@ -37,6 +37,8 @@ export interface TilesetModelSlot {
/** Atlas border (px) before the first tile, and gap (px) between tiles (Tiled). */
margin: number;
spacing: number;
+ /** Duplicated-edge border each cell carries; 0 = none. See `TilesetAsset.extrude`. */
+ extrude: number;
}
/**
@@ -149,6 +151,7 @@ export function resolveTilesetModel(tilesets: ResolvedTileset[]): TilesetModel {
slots.push({
firstId, textureHandle, columns: asset.columns,
margin: asset.margin || 0, spacing: asset.spacing || 0,
+ extrude: asset.extrude || 0,
});
const tw = asset.tileWidth || 1;
const th = asset.tileHeight || 1;
diff --git a/sdk/tests/tileset-asset.test.ts b/sdk/tests/tileset-asset.test.ts
index e117f1f84..34e06ad8c 100644
--- a/sdk/tests/tileset-asset.test.ts
+++ b/sdk/tests/tileset-asset.test.ts
@@ -18,7 +18,7 @@ describe('tilesetAsset (.estileset format)', () => {
version: TILESET_FORMAT_VERSION,
texture: '@uuid:abc',
tileWidth: 16, tileHeight: 16, columns: 8,
- margin: 0, spacing: 0, tiles: {},
+ margin: 0, spacing: 0, extrude: 0, tiles: {},
});
});
});
@@ -83,7 +83,9 @@ describe('tilesetAsset (.estileset format)', () => {
it('parse(serialize(x)) is identity over a rich tileset', () => {
const original: TilesetAsset = {
version: '1', texture: '@uuid:t', tileWidth: 16, tileHeight: 16,
- columns: 8, margin: 1, spacing: 2, tileCount: 64,
+ // margin 1 / spacing 2 IS the extruded layout for extrude 1, which is
+ // the case that exercises the serializer's write-only-when-set branch.
+ columns: 8, margin: 1, spacing: 2, extrude: 1, tileCount: 64,
tiles: {
5: { collision: { type: 'box' } },
12: { collision: { type: 'polygon', points: [[0, 0], [16, 0], [16, 16]] }, properties: { kind: 'slope' } },
@@ -92,6 +94,23 @@ describe('tilesetAsset (.estileset format)', () => {
};
expect(parseTileset(serializeTileset(original))).toEqual(original);
});
+
+ it('a packed tileset round-trips too, with no extrude key written', () => {
+ // The other branch: an asset made before extrusion existed, and every
+ // asset that has not been re-imported. It must come back as extrude 0
+ // WITHOUT the serializer adding a key that says nothing.
+ const packed: TilesetAsset = {
+ version: '1', texture: '@uuid:t', tileWidth: 16, tileHeight: 16,
+ columns: 8, margin: 0, spacing: 0, extrude: 0, tiles: {},
+ };
+ expect(serializeTileset(packed)).not.toHaveProperty('extrude');
+ expect(parseTileset(serializeTileset(packed))).toEqual(packed);
+ // And a file written before the field existed reads back the same way.
+ expect(parseTileset({
+ version: '1', texture: '@uuid:t', tileWidth: 16, tileHeight: 16,
+ columns: 8, margin: 0, spacing: 0, tiles: {},
+ })).toEqual(packed);
+ });
});
describe('collidableTileIds', () => {
diff --git a/sdk/tests/tileset-resolve.test.ts b/sdk/tests/tileset-resolve.test.ts
index 0180df0d6..943466492 100644
--- a/sdk/tests/tileset-resolve.test.ts
+++ b/sdk/tests/tileset-resolve.test.ts
@@ -8,7 +8,7 @@ import type { TilesetAsset } from '../src/tilemap/tilesetAsset';
function tileset(over: Partial<TilesetAsset>): TilesetAsset {
return {
version: '1', texture: '@uuid:tex', tileWidth: 16, tileHeight: 16,
- columns: 4, margin: 0, spacing: 0, tiles: {}, ...over,
+ columns: 4, margin: 0, spacing: 0, extrude: 0, tiles: {}, ...over,
};
}
@@ -22,7 +22,7 @@ describe('resolveTilesetModel', () => {
}),
};
const m = resolveTilesetModel([rt]);
- expect(m.slots).toEqual([{ firstId: 1, textureHandle: 100, columns: 4, margin: 0, spacing: 0 }]);
+ expect(m.slots).toEqual([{ firstId: 1, textureHandle: 100, columns: 4, margin: 0, spacing: 0, extrude: 0 }]);
// box tiles greedy-merge (collidableTileIds); polygon tiles carry their own shape.
expect(m.collidableTileIds).toEqual([2]);
expect(m.tileShapes.get(7)?.shape).toEqual({ type: 'polygon', points: [[0, 1], [1, 1], [0, 0]] }); // normalized
@@ -41,8 +41,8 @@ describe('resolveTilesetModel', () => {
const m = resolveTilesetModel([a, b]);
// tileset B starts at firstId 1 + 8 = 9
expect(m.slots).toEqual([
- { firstId: 1, textureHandle: 100, columns: 4, margin: 0, spacing: 0 },
- { firstId: 9, textureHandle: 200, columns: 4, margin: 0, spacing: 0 },
+ { firstId: 1, textureHandle: 100, columns: 4, margin: 0, spacing: 0, extrude: 0 },
+ { firstId: 9, textureHandle: 200, columns: 4, margin: 0, spacing: 0, extrude: 0 },
]);
// A local 2 → global 2; B locals 1,2 → globals 9,10
expect(m.collidableTileIds).toEqual([2, 9, 10]);
@@ -54,7 +54,7 @@ describe('resolveTilesetModel', () => {
asset: tileset({ columns: 4, tileCount: 8, margin: 4, spacing: 8 }),
};
const m = resolveTilesetModel([rt]);
- expect(m.slots).toEqual([{ firstId: 1, textureHandle: 100, columns: 4, margin: 4, spacing: 8 }]);
+ expect(m.slots).toEqual([{ firstId: 1, textureHandle: 100, columns: 4, margin: 4, spacing: 8, extrude: 0 }]);
});
it('animations re-key both the tile and its frames to global ids', () => {
diff --git a/src/esengine/bindings/TilemapBindings.cpp b/src/esengine/bindings/TilemapBindings.cpp
index 132691815..e4e3d93b3 100644
--- a/src/esengine/bindings/TilemapBindings.cpp
+++ b/src/esengine/bindings/TilemapBindings.cpp
@@ -83,22 +83,29 @@ void tilemap_setTiles(u32 entity, uintptr_t tilesPtr, u32 count) {
getTilemapSystem().setTiles(e, tiles, count);
}
-// Multi-tileset table: `count` slots, each 3 packed u32 [first_id, textureHandle,
-// columns]. Empty table reverts the layer to its single tileset.
+// Multi-tileset table: `count` slots, each SLOT_STRIDE packed u32
+// [first_id, textureHandle, columns, margin, spacing, extrude].
+// Empty table reverts the layer to its single tileset.
void tilemap_setTilesets(u32 entity, uintptr_t dataPtr, u32 count) {
+ // The SDK's TILESET_SLOT_STRIDE. No generator spans this boundary, so the
+ // field list above is the contract and this number is the other half of it.
+ constexpr u32 SLOT_STRIDE = 6;
auto e = Entity::fromRaw(entity);
if (e == INVALID_ENTITY || !getTilemapSystem().hasLayer(e)) return;
- const auto* d = count ? boundarySpan<u32>(dataPtr, static_cast<u64>(count) * 5, "tilemap_setTilesets") : nullptr;
+ const auto* d = count
+ ? boundarySpan<u32>(dataPtr, static_cast<u64>(count) * SLOT_STRIDE, "tilemap_setTilesets")
+ : nullptr;
if (count && !d) return;
std::vector<tilemap::TilesetSlot> slots;
slots.reserve(count);
for (u32 i = 0; i < count; ++i) {
tilemap::TilesetSlot slot;
- slot.first_id = static_cast<u16>(d[i * 5 + 0]);
- slot.texture_handle = d[i * 5 + 1];
- slot.columns = d[i * 5 + 2];
- slot.margin = d[i * 5 + 3];
- slot.spacing = d[i * 5 + 4];
+ slot.first_id = static_cast<u16>(d[i * SLOT_STRIDE + 0]);
+ slot.texture_handle = d[i * SLOT_STRIDE + 1];
+ slot.columns = d[i * SLOT_STRIDE + 2];
+ slot.margin = d[i * SLOT_STRIDE + 3];
+ slot.spacing = d[i * SLOT_STRIDE + 4];
+ slot.extrude = d[i * SLOT_STRIDE + 5];
slots.push_back(slot);
}
getTilemapSystem().setTilesets(e, std::move(slots));
diff --git a/src/esengine/renderer/plugins/TilemapRenderPlugin.cpp b/src/esengine/renderer/plugins/TilemapRenderPlugin.cpp
index 30bd0d30d..19edff35b 100644
--- a/src/esengine/renderer/plugins/TilemapRenderPlugin.cpp
+++ b/src/esengine/renderer/plugins/TilemapRenderPlugin.cpp
@@ -111,8 +111,8 @@ void TilemapRenderPlugin::rebuildChunk(
// Base tile UV rect (GL v increases upward, so vBottom < vTop), with
// the atlas margin + spacing folded into offset/step so a Tiled tileset
- // with gaps samples the right cell; inset half a texel per edge so
- // samples stay inside this tile.
+ // with gaps samples the right cell. `inset` is zero on an extruded
+ // atlas and half a texel on a packed one — see where it is resolved.
f32 uMin = rs.uvOffsetX + static_cast<f32>(tileCol) * rs.uvStepX + rs.insetU;
f32 uMax = uMin + uvTileW - 2.0f * rs.insetU;
f32 vBottom = 1.0f - rs.uvOffsetY - static_cast<f32>(tileRow) * rs.uvStepY - uvTileH + rs.insetV;
@@ -235,8 +235,14 @@ void TilemapRenderPlugin::collect(RenderCollectContext& collect_ctx) {
resolved[i].uvOffsetY = margin / th;
resolved[i].uvStepX = (layer.tile_width + spacing) / tw;
resolved[i].uvStepY = (layer.tile_height + spacing) / th;
- resolved[i].insetU = 0.5f / tw;
- resolved[i].insetV = 0.5f / th;
+ // An extruded atlas already carries the guarantee the inset was
+ // buying — a sample that leaves the cell reads a copy of that cell's
+ // own edge — so the exact rect is safe, and the exact rect is the
+ // only one that does not stretch the tile. On a packed atlas the
+ // inset is still the trade that has to be made.
+ const bool extruded = slots[i].extrude > 0;
+ resolved[i].insetU = extruded ? 0.0f : 0.5f / tw;
+ resolved[i].insetV = extruded ? 0.0f : 0.5f / th;
resolved[i].atlasCols = tilemap::atlasCells(tw, margin, layer.tile_width, spacing);
resolved[i].atlasRows = tilemap::atlasCells(th, margin, layer.tile_height, spacing);
anySlotValid = true;
diff --git a/src/esengine/renderer/plugins/TilemapRenderPlugin.hpp b/src/esengine/renderer/plugins/TilemapRenderPlugin.hpp
index 1281b76c4..f36602428 100644
--- a/src/esengine/renderer/plugins/TilemapRenderPlugin.hpp
+++ b/src/esengine/renderer/plugins/TilemapRenderPlugin.hpp
@@ -61,10 +61,18 @@ private:
f32 uvStepX = 0.0f;
f32 uvOffsetY = 0.0f;
f32 uvStepY = 0.0f;
- // Half a texel in UV space. Tile-corner UVs are inset by this so
- // interpolated samples never cross into the neighboring atlas tile —
- // the classic packed-atlas seam fix, for both linear and nearest
- // (which otherwise rounds across the boundary at fractional zoom).
+ // How far each tile-corner UV is pulled in from the cell rect, so an
+ // interpolated sample never crosses into the neighbouring atlas cell.
+ //
+ // ZERO when the tileset is extruded, which is the case worth having: the
+ // atlas itself guarantees no crossing, so the quad's UV rect equals its
+ // geometry rect and the tile is drawn undistorted.
+ //
+ // HALF A TEXEL on a packed atlas, where the two cannot both hold. It buys
+ // no-bleed by shrinking the sampled rect a whole texel while the quad keeps
+ // the full tile — so every tile is stretched by N/(N-1) and the sampling
+ // phase resets at each boundary, which is a visible seam on tiles meant to
+ // butt together. Extrude the tileset to stop paying it.
f32 insetU = 0.0f;
f32 insetV = 0.0f;
// How many tiles the texture actually holds, at this layer's cell size.
diff --git a/src/esengine/tilemap/TilesetTable.hpp b/src/esengine/tilemap/TilesetTable.hpp
index adc98385b..c22dd846e 100644
--- a/src/esengine/tilemap/TilesetTable.hpp
+++ b/src/esengine/tilemap/TilesetTable.hpp
@@ -23,6 +23,11 @@ struct TilesetSlot {
uint32_t columns = 1; // tiles per row in the tileset texture
uint32_t margin = 0; // atlas border in px before the first tile (Tiled margin)
uint32_t spacing = 0; // gap in px between adjacent tiles (Tiled spacing)
+ // Duplicated-edge border each cell carries, in px. Non-zero says a sample may
+ // leave the cell and still read that cell's own colour, which is what lets the
+ // renderer send the exact cell rect instead of insetting half a texel and
+ // stretching every tile. 0 = a packed atlas, and the inset is still needed.
+ uint32_t extrude = 0;
};
/**