From 824cae072fd5444f17739a28e8decf080c978a4f Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 00:10:04 +0000 Subject: [PATCH 01/51] Tests: the MaskEffect drawing checks run on a WebGPU device On a machine with a WebGPU adapter, 14 tests of mask-effect-image.spec.js failed: the pixel helper's WebGPU branch called a method the renderer does not have, and the WebGPU application made in the same file took the place of the Canvas one the later tests use. - helpers/pixels.js: grabFrame() reads a whole frame on any backend (a texture-to-buffer copy on WebGPU), and drawOffscreen() has a WebGPU renderer draw into a texture of its own, which reads back the same on a headless software adapter, where a canvas texture cannot be presented - the drawing checks move to helpers/mask-effect-checks.js, and take each frame once, as it is drawn: an application's loop draws over it while a test awaits - the WebGPU checks get a spec file of their own, with a projection set Verified with a software WebGPU adapter: the 12 WebGPU checks pass, and skip as before where there is no adapter. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- .../tests/helpers/mask-effect-checks.js | 271 ++++++++++++++++ packages/melonjs/tests/helpers/pixels.js | 121 +++++++- .../tests/mask-effect-image-webgpu.spec.js | 67 ++++ .../melonjs/tests/mask-effect-image.spec.js | 288 +----------------- 4 files changed, 467 insertions(+), 280 deletions(-) create mode 100644 packages/melonjs/tests/helpers/mask-effect-checks.js create mode 100644 packages/melonjs/tests/mask-effect-image-webgpu.spec.js diff --git a/packages/melonjs/tests/helpers/mask-effect-checks.js b/packages/melonjs/tests/helpers/mask-effect-checks.js new file mode 100644 index 0000000000..335e83fbcb --- /dev/null +++ b/packages/melonjs/tests/helpers/mask-effect-checks.js @@ -0,0 +1,271 @@ +/** + * What the `MaskEffect` drawing tests share, so that each renderer can run + * them in a spec file of its own: an application with a GPU device takes the + * place of the one before it, and the checks below only need a renderer. + */ +import { expect, it, vi } from "vitest"; +import { Camera2d, Ellipse, MaskEffect, Polygon } from "../../src/index.js"; +import { grabFrame } from "./pixels.js"; + +export const SIZE = 64; + +/** a 32 px disc, radius 14, with a hole of radius 4 at its centre */ +export const discWithHole = () => { + const canvas = document.createElement("canvas"); + canvas.width = canvas.height = 32; + const ctx = canvas.getContext("2d"); + ctx.fillStyle = "#3a7"; + ctx.beginPath(); + ctx.arc(16, 16, 14, 0, Math.PI * 2); + ctx.fill(); + ctx.globalCompositeOperation = "destination-out"; + ctx.beginPath(); + ctx.arc(16, 16, 4, 0, Math.PI * 2); + ctx.fill(); + return canvas; +}; + +/** an image whose left half only is opaque */ +export const leftHalf = (w = 20, h = 30) => { + const canvas = document.createElement("canvas"); + canvas.width = w; + canvas.height = h; + const ctx = canvas.getContext("2d"); + ctx.fillStyle = "#f00"; + ctx.fillRect(0, 0, w / 2, h); + return canvas; +}; + +/** a 32 px U: its middle is open to the outside, so not part of it */ +export const uShape = () => { + const canvas = document.createElement("canvas"); + canvas.width = canvas.height = 32; + const ctx = canvas.getContext("2d"); + ctx.fillStyle = "#000"; + ctx.fillRect(2, 2, 8, 28); + ctx.fillRect(22, 2, 8, 28); + ctx.fillRect(2, 22, 28, 8); + return canvas; +}; + +/** an image whose top left quarter only is opaque */ +export const topLeftQuarter = (w = 20, h = 30) => { + const canvas = document.createElement("canvas"); + canvas.width = w; + canvas.height = h; + const ctx = canvas.getContext("2d"); + ctx.fillStyle = "#0f0"; + ctx.fillRect(0, 0, w / 2, h / 2); + return canvas; +}; + +/** a unit square that does not surround its origin */ +export const offOrigin = () => { + return new Polygon(0, 0, [ + { x: 0.2, y: 0.2 }, + { x: 1, y: 0.2 }, + { x: 1, y: 1 }, + { x: 0.2, y: 1 }, + ]); +}; + +/** an effect at a given progress (1 = all visible, 0 = all covered) */ +export const at = (camera, progress, options) => { + const effect = new MaskEffect(camera, { + color: "#000", + duration: 1000, + direction: "hide", + ...options, + }); + effect.tween.stop(); + effect.progress.value = progress; + return effect; +}; + +/** + * Draw an effect over a white screen, and return the frame. The frame is + * taken at once, in one piece: an application's own loop draws its next + * frame while a test awaits, over the one a pixel would be read from. + */ +export const drawOverWhite = (renderer, effect) => { + // a frame of its own: a GPU renderer draws nothing outside one + renderer.clear(); + renderer.save(); + renderer.resetTransform(); + renderer.setColor("#ffffff"); + renderer.fillRect(0, 0, SIZE, SIZE); + renderer.restore(); + effect.draw(renderer, SIZE, SIZE); + return grabFrame(renderer); +}; + +/** 1 where a pixel of a frame is covered (dark), 0 where it is visible (light) */ +export const covered = (frame, x, y) => { + return frame.data[(y * frame.width + x) * 4] < 128 ? 1 : 0; +}; + +export const CORNERS = [ + [1, 1], + [SIZE - 2, 1], + [1, SIZE - 2], + [SIZE - 2, SIZE - 2], +]; + +/** the same drawing checks, on one renderer */ +export const drawingChecks = (getRenderer) => { + const camera = new Camera2d(0, 0, SIZE, SIZE); + + it("an image: the scene shows through its silhouette, hole filled in", async (ctx) => { + const renderer = getRenderer(ctx); + let frame; + const effect = at(camera, 0.3, { shape: discWithHole() }); + frame = await drawOverWhite(renderer, effect); + // the centre is the image's hole: part of the silhouette, so visible + expect(covered(frame, 32, 32)).toBe(0); + expect(covered(frame, 32, 26)).toBe(0); + for (const [x, y] of CORNERS) { + expect(covered(frame, x, y)).toBe(1); + } + effect.destroy(); + }); + + it("an image: covers everything once closed", async (ctx) => { + const renderer = getRenderer(ctx); + let frame; + const effect = at(camera, 0, { shape: discWithHole() }); + frame = await drawOverWhite(renderer, effect); + expect(covered(frame, 32, 32)).toBe(1); + expect(covered(frame, 1, 1)).toBe(1); + effect.destroy(); + }); + + it("an image: just before the end, the whole screen is already uncovered", async (ctx) => { + const renderer = getRenderer(ctx); + let frame; + const effect = at(camera, 0.995, { shape: discWithHole() }); + frame = await drawOverWhite(renderer, effect); + for (const [x, y] of CORNERS) { + expect(covered(frame, x, y)).toBe(0); + } + effect.destroy(); + }); + + it("a polygon: just before the end, the whole screen is already uncovered", async (ctx) => { + const renderer = getRenderer(ctx); + let frame; + const diamond = new Polygon(0, 0, [ + { x: 0, y: -1 }, + { x: 1, y: 0 }, + { x: 0, y: 1 }, + { x: -1, y: 0 }, + ]); + const effect = at(camera, 0.995, { shape: diamond }); + frame = await drawOverWhite(renderer, effect); + for (const [x, y] of CORNERS) { + expect(covered(frame, x, y)).toBe(0); + } + effect.destroy(); + }); + + it("inverted: the silhouette is the cover, the scene shows round it", async (ctx) => { + const renderer = getRenderer(ctx); + let frame; + const effect = at(camera, 0.7, { shape: discWithHole(), invert: true }); + frame = await drawOverWhite(renderer, effect); + expect(covered(frame, 32, 32)).toBe(1); + for (const [x, y] of CORNERS) { + expect(covered(frame, x, y)).toBe(0); + } + effect.destroy(); + }); + + it("inverted: covers everything once closed, nothing at the start", async (ctx) => { + const renderer = getRenderer(ctx); + let frame; + const closed = at(camera, 0, { shape: discWithHole(), invert: true }); + frame = await drawOverWhite(renderer, closed); + expect(covered(frame, 1, 1)).toBe(1); + expect(covered(frame, 32, 32)).toBe(1); + closed.destroy(); + const open = at(camera, 1, { shape: discWithHole(), invert: true }); + frame = await drawOverWhite(renderer, open); + expect(covered(frame, 32, 32)).toBe(0); + open.destroy(); + }); + + it("inverted geometry: an iris filled, growing out of the centre", async (ctx) => { + const renderer = getRenderer(ctx); + let frame; + const effect = at(camera, 0.7, { + shape: new Ellipse(0, 0, 1, 1), + invert: true, + }); + frame = await drawOverWhite(renderer, effect); + expect(covered(frame, 32, 32)).toBe(1); + expect(covered(frame, 1, 1)).toBe(0); + effect.destroy(); + }); + + it("an image open in its middle (a U): grows about its thickest part, and still uncovers everything", async (ctx) => { + const renderer = getRenderer(ctx); + let frame; + // just after the hide starts, the middle of the screen is still seen + const start = at(camera, 0.99, { shape: uShape() }); + frame = await drawOverWhite(renderer, start); + expect(covered(frame, 32, 32)).toBe(0); + start.destroy(); + // and just before a reveal ends, nothing is covered + const end = at(camera, 0.995, { shape: uShape() }); + frame = await drawOverWhite(renderer, end); + for (const [x, y] of [...CORNERS, [32, 32], [32, 3]]) { + expect(covered(frame, x, y)).toBe(0); + } + end.destroy(); + }); + + it("a polygon off its origin: still uncovers everything, and inverted still covers it", async (ctx) => { + const renderer = getRenderer(ctx); + let frame; + const open = at(camera, 0.995, { shape: offOrigin() }); + frame = await drawOverWhite(renderer, open); + for (const [x, y] of CORNERS) { + expect(covered(frame, x, y)).toBe(0); + } + open.destroy(); + // the cover nearly grown: the screen is covered by the polygon itself + const cover = at(camera, 0.005, { shape: offOrigin(), invert: true }); + frame = await drawOverWhite(renderer, cover); + for (const [x, y] of [...CORNERS, [32, 32]]) { + expect(covered(frame, x, y)).toBe(1); + } + cover.destroy(); + }); + + it("nearly closed, the image is still drawn, a sliver of the scene in the middle", async (ctx) => { + const renderer = getRenderer(ctx); + let frame; + const effect = at(camera, 0.05, { shape: discWithHole() }); + const drawImage = vi.spyOn(renderer, "drawImage"); + frame = await drawOverWhite(renderer, effect); + expect(drawImage).toHaveBeenCalled(); + drawImage.mockRestore(); + expect(covered(frame, 32, 32)).toBe(0); + for (const [x, y] of [...CORNERS, [32, 20], [44, 32]]) { + expect(covered(frame, x, y)).toBe(1); + } + effect.destroy(); + }); + + it("center: closes on that point, not on the centre of the screen", async (ctx) => { + const renderer = getRenderer(ctx); + let frame; + const effect = at(camera, 0.2, { + shape: discWithHole(), + center: { x: 12, y: 12 }, + }); + frame = await drawOverWhite(renderer, effect); + expect(covered(frame, 12, 12)).toBe(0); + expect(covered(frame, 52, 52)).toBe(1); + effect.destroy(); + }); +}; diff --git a/packages/melonjs/tests/helpers/pixels.js b/packages/melonjs/tests/helpers/pixels.js index 31aa566198..5a27f80540 100644 --- a/packages/melonjs/tests/helpers/pixels.js +++ b/packages/melonjs/tests/helpers/pixels.js @@ -43,10 +43,12 @@ export async function readPixel(renderer, x, y) { return Array.from(out); } - // WebGPU: async readback off the presented texture - if (typeof renderer.readCanvasPixels === "function") { - const data = await renderer.readCanvasPixels(px, py, 1, 1); - return Array.from(data.data ?? data).slice(0, 4); + // WebGPU: its canvas has no synchronous readback, but still holds the + // frame just submitted until this task ends + if (renderer.type === "WebGPU") { + const frame = await grabFrame(renderer); + const o = (py * frame.width + px) * 4; + return Array.from(frame.data.subarray(o, o + 4)); } // Canvas 2D: top-down rows already @@ -55,6 +57,117 @@ export async function readPixel(renderer, x, y) { return Array.from(ctx.getImageData(px, py, 1, 1).data); } +/** + * Have a WebGPU renderer draw its frames into a texture of its own, in place + * of its canvas's, and return that renderer. + * + * A test reads a frame back from the texture it was drawn into (see + * {@link grabFrame}), and a canvas's texture is only there until the browser + * presents it. Presenting is also what a headless browser on a software + * adapter cannot do: the device is lost the moment a canvas texture is + * asked for. Drawn into a plain texture, the renderer's own work (its + * pipelines, shaders and passes) runs and reads back the same everywhere. + * + * Call it right after `app.init()`, before the first frame. A renderer that + * is not WebGPU is returned as it is. + * @param {object} renderer - any melonJS renderer + * @returns {object} the renderer + */ +export function drawOffscreen(renderer) { + if (renderer.type !== "WebGPU" || renderer.context.__offscreen === true) { + return renderer; + } + const canvas = renderer.getCanvas(); + const context = renderer.context; + const format = + context.getConfiguration?.()?.format ?? + navigator.gpu.getPreferredCanvasFormat(); + let texture; + context.getCurrentTexture = () => { + if ( + texture === undefined || + texture.width !== canvas.width || + texture.height !== canvas.height + ) { + texture?.destroy(); + texture = renderer.device.createTexture({ + label: "test frame", + size: [canvas.width, canvas.height], + format, + usage: + GPUTextureUsage.RENDER_ATTACHMENT | + GPUTextureUsage.COPY_SRC | + GPUTextureUsage.TEXTURE_BINDING, + }); + } + return texture; + }; + context.__offscreen = true; + return renderer; +} + +/** + * The whole frame a renderer has just drawn, as straight-alpha `ImageData`, + * rows top-down, on any backend. + * + * To be called in the task that drew the frame, before anything is awaited: + * a GPU canvas only holds its frame until the browser presents it. On WebGPU + * the frame must have been begun with `renderer.clear()`; it is submitted + * here, and its texture copied into a buffer before this returns its promise + * (see {@link drawOffscreen}, which a test on WebGPU wants first). + * @param {object} renderer - any melonJS renderer + * @returns {Promise} the frame + */ +export async function grabFrame(renderer) { + renderer.flush?.(); + const source = renderer.getCanvas(); + const width = source.width; + const height = source.height; + + if (renderer.type === "WebGPU") { + // the canvas texture of this frame, still current until presented + const device = renderer.device; + const texture = renderer.context.getCurrentTexture(); + const bytesPerRow = Math.ceil((width * 4) / 256) * 256; + const buffer = device.createBuffer({ + size: bytesPerRow * height, + usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ, + }); + const encoder = device.createCommandEncoder(); + encoder.copyTextureToBuffer( + { texture }, + { buffer, bytesPerRow }, + { width, height }, + ); + device.queue.submit([encoder.finish()]); + await buffer.mapAsync(GPUMapMode.READ); + const raw = new Uint8Array(buffer.getMappedRange()); + const bgra = texture.format.startsWith("bgra"); + const out = new Uint8ClampedArray(width * height * 4); + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + const i = y * bytesPerRow + x * 4; + const o = (y * width + x) * 4; + out[o] = raw[i + (bgra ? 2 : 0)]; + out[o + 1] = raw[i + 1]; + out[o + 2] = raw[i + (bgra ? 0 : 2)]; + out[o + 3] = raw[i + 3]; + } + } + buffer.unmap(); + buffer.destroy(); + return new ImageData(out, width, height); + } + + // WebGL and Canvas: copied through a 2D canvas, while the frame is there + const canvas = document.createElement("canvas"); + canvas.width = width; + canvas.height = height; + const context = canvas.getContext("2d", { willReadFrequently: true }); + context.drawImage(source, 0, 0); + return context.getImageData(0, 0, width, height); +} + /** * Read the same pixel from several renderers at once, in canvas coordinates. * @param {object[]} renderers - the renderers to sample diff --git a/packages/melonjs/tests/mask-effect-image-webgpu.spec.js b/packages/melonjs/tests/mask-effect-image-webgpu.spec.js new file mode 100644 index 0000000000..68aa4eb03e --- /dev/null +++ b/packages/melonjs/tests/mask-effect-image-webgpu.spec.js @@ -0,0 +1,67 @@ +/** + * The `MaskEffect` drawing checks (#1399) on WebGPU, in a spec file of its + * own: an application with a GPU device takes the place of the one before + * it, which the Canvas and WebGL checks of `mask-effect-image.spec.js` use. + * + * Skipped, visibly, where the browser has no WebGPU adapter. + */ +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { Application, boot, Camera2d, video } from "../src/index.js"; +import { + at, + discWithHole, + drawingChecks, + drawOverWhite, + SIZE, +} from "./helpers/mask-effect-checks.js"; +import { drawOffscreen } from "./helpers/pixels.js"; + +describe("MaskEffect: image and sprite shapes, on WebGPU", () => { + let app; + let available = false; + beforeAll(async () => { + boot(); + try { + app = new Application(SIZE, SIZE, { + parent: "screen", + renderer: video.WEBGPU, + consoleHeader: false, + }); + await app.init(); + available = app.renderer.type === "WebGPU"; + if (available) { + const renderer = drawOffscreen(app.renderer); + // the checks draw without a camera, which is what sets the + // projection in a game + renderer.projectionMatrix.ortho(0, SIZE, SIZE, 0, -1000, 1000); + renderer.setProjection(renderer.projectionMatrix); + } + } catch { + available = false; + } + }); + afterAll(() => { + app?.destroy(); + }); + + const getRenderer = (ctx) => { + if (!available) { + ctx.skip("WebGPU not available in this environment"); + } + return app.renderer; + }; + + drawingChecks(getRenderer); + + it("destroy frees the copy of the image uploaded to the GPU", async (ctx) => { + const renderer = getRenderer(ctx); + const effect = at(new Camera2d(0, 0, SIZE, SIZE), 0.5, { + shape: discWithHole(), + }); + await drawOverWhite(renderer, effect); + const canvas = effect._cover.canvas; + expect(renderer.cache.has(canvas)).toBe(true); + effect.destroy(); + expect(renderer.cache.has(canvas)).toBe(false); + }); +}); diff --git a/packages/melonjs/tests/mask-effect-image.spec.js b/packages/melonjs/tests/mask-effect-image.spec.js index e1f8cafd6e..be070555de 100644 --- a/packages/melonjs/tests/mask-effect-image.spec.js +++ b/packages/melonjs/tests/mask-effect-image.spec.js @@ -32,258 +32,21 @@ import { video, } from "../src/index.js"; import GLTFScene from "../src/level/gltf/GLTFScene.js"; -import { readPixel } from "./helpers/pixels.js"; +import { + at, + discWithHole, + drawingChecks, + drawOverWhite, + leftHalf, + offOrigin, + SIZE, + topLeftQuarter, +} from "./helpers/mask-effect-checks.js"; import { getWebGLRenderer, releaseWebGLRenderer, } from "./helpers/webgl-context.js"; -const SIZE = 64; - -/** a 32 px disc, radius 14, with a hole of radius 4 at its centre */ -const discWithHole = () => { - const canvas = document.createElement("canvas"); - canvas.width = canvas.height = 32; - const ctx = canvas.getContext("2d"); - ctx.fillStyle = "#3a7"; - ctx.beginPath(); - ctx.arc(16, 16, 14, 0, Math.PI * 2); - ctx.fill(); - ctx.globalCompositeOperation = "destination-out"; - ctx.beginPath(); - ctx.arc(16, 16, 4, 0, Math.PI * 2); - ctx.fill(); - return canvas; -}; - -/** an image whose left half only is opaque */ -const leftHalf = (w = 20, h = 30) => { - const canvas = document.createElement("canvas"); - canvas.width = w; - canvas.height = h; - const ctx = canvas.getContext("2d"); - ctx.fillStyle = "#f00"; - ctx.fillRect(0, 0, w / 2, h); - return canvas; -}; - -/** a 32 px U: its middle is open to the outside, so not part of it */ -const uShape = () => { - const canvas = document.createElement("canvas"); - canvas.width = canvas.height = 32; - const ctx = canvas.getContext("2d"); - ctx.fillStyle = "#000"; - ctx.fillRect(2, 2, 8, 28); - ctx.fillRect(22, 2, 8, 28); - ctx.fillRect(2, 22, 28, 8); - return canvas; -}; - -/** an image whose top left quarter only is opaque */ -const topLeftQuarter = (w = 20, h = 30) => { - const canvas = document.createElement("canvas"); - canvas.width = w; - canvas.height = h; - const ctx = canvas.getContext("2d"); - ctx.fillStyle = "#0f0"; - ctx.fillRect(0, 0, w / 2, h / 2); - return canvas; -}; - -/** a unit square that does not surround its origin */ -const offOrigin = () => { - return new Polygon(0, 0, [ - { x: 0.2, y: 0.2 }, - { x: 1, y: 0.2 }, - { x: 1, y: 1 }, - { x: 0.2, y: 1 }, - ]); -}; - -/** an effect at a given progress (1 = all visible, 0 = all covered) */ -const at = (camera, progress, options) => { - const effect = new MaskEffect(camera, { - color: "#000", - duration: 1000, - direction: "hide", - ...options, - }); - effect.tween.stop(); - effect.progress.value = progress; - return effect; -}; - -/** draw an effect over a white screen */ -const drawOverWhite = (renderer, effect) => { - renderer.save(); - renderer.resetTransform(); - renderer.setColor("#ffffff"); - renderer.fillRect(0, 0, SIZE, SIZE); - renderer.restore(); - effect.draw(renderer, SIZE, SIZE); - renderer.flush(); -}; - -/** 1 where a pixel is covered (dark), 0 where it is visible (light) */ -const covered = async (renderer, x, y) => { - return (await readPixel(renderer, x, y))[0] < 128 ? 1 : 0; -}; - -const CORNERS = [ - [1, 1], - [SIZE - 2, 1], - [1, SIZE - 2], - [SIZE - 2, SIZE - 2], -]; - -/** the same drawing checks, on one renderer */ -const drawingChecks = (getRenderer) => { - const camera = new Camera2d(0, 0, SIZE, SIZE); - - it("an image: the scene shows through its silhouette, hole filled in", async (ctx) => { - const renderer = getRenderer(ctx); - const effect = at(camera, 0.3, { shape: discWithHole() }); - drawOverWhite(renderer, effect); - // the centre is the image's hole: part of the silhouette, so visible - expect(await covered(renderer, 32, 32)).toBe(0); - expect(await covered(renderer, 32, 26)).toBe(0); - for (const [x, y] of CORNERS) { - expect(await covered(renderer, x, y)).toBe(1); - } - effect.destroy(); - }); - - it("an image: covers everything once closed", async (ctx) => { - const renderer = getRenderer(ctx); - const effect = at(camera, 0, { shape: discWithHole() }); - drawOverWhite(renderer, effect); - expect(await covered(renderer, 32, 32)).toBe(1); - expect(await covered(renderer, 1, 1)).toBe(1); - effect.destroy(); - }); - - it("an image: just before the end, the whole screen is already uncovered", async (ctx) => { - const renderer = getRenderer(ctx); - const effect = at(camera, 0.995, { shape: discWithHole() }); - drawOverWhite(renderer, effect); - for (const [x, y] of CORNERS) { - expect(await covered(renderer, x, y)).toBe(0); - } - effect.destroy(); - }); - - it("a polygon: just before the end, the whole screen is already uncovered", async (ctx) => { - const renderer = getRenderer(ctx); - const diamond = new Polygon(0, 0, [ - { x: 0, y: -1 }, - { x: 1, y: 0 }, - { x: 0, y: 1 }, - { x: -1, y: 0 }, - ]); - const effect = at(camera, 0.995, { shape: diamond }); - drawOverWhite(renderer, effect); - for (const [x, y] of CORNERS) { - expect(await covered(renderer, x, y)).toBe(0); - } - effect.destroy(); - }); - - it("inverted: the silhouette is the cover, the scene shows round it", async (ctx) => { - const renderer = getRenderer(ctx); - const effect = at(camera, 0.7, { shape: discWithHole(), invert: true }); - drawOverWhite(renderer, effect); - expect(await covered(renderer, 32, 32)).toBe(1); - for (const [x, y] of CORNERS) { - expect(await covered(renderer, x, y)).toBe(0); - } - effect.destroy(); - }); - - it("inverted: covers everything once closed, nothing at the start", async (ctx) => { - const renderer = getRenderer(ctx); - const closed = at(camera, 0, { shape: discWithHole(), invert: true }); - drawOverWhite(renderer, closed); - expect(await covered(renderer, 1, 1)).toBe(1); - expect(await covered(renderer, 32, 32)).toBe(1); - closed.destroy(); - const open = at(camera, 1, { shape: discWithHole(), invert: true }); - drawOverWhite(renderer, open); - expect(await covered(renderer, 32, 32)).toBe(0); - open.destroy(); - }); - - it("inverted geometry: an iris filled, growing out of the centre", async (ctx) => { - const renderer = getRenderer(ctx); - const effect = at(camera, 0.7, { - shape: new Ellipse(0, 0, 1, 1), - invert: true, - }); - drawOverWhite(renderer, effect); - expect(await covered(renderer, 32, 32)).toBe(1); - expect(await covered(renderer, 1, 1)).toBe(0); - effect.destroy(); - }); - - it("an image open in its middle (a U): grows about its thickest part, and still uncovers everything", async (ctx) => { - const renderer = getRenderer(ctx); - // just after the hide starts, the middle of the screen is still seen - const start = at(camera, 0.99, { shape: uShape() }); - drawOverWhite(renderer, start); - expect(await covered(renderer, 32, 32)).toBe(0); - start.destroy(); - // and just before a reveal ends, nothing is covered - const end = at(camera, 0.995, { shape: uShape() }); - drawOverWhite(renderer, end); - for (const [x, y] of [...CORNERS, [32, 32], [32, 3]]) { - expect(await covered(renderer, x, y)).toBe(0); - } - end.destroy(); - }); - - it("a polygon off its origin: still uncovers everything, and inverted still covers it", async (ctx) => { - const renderer = getRenderer(ctx); - const open = at(camera, 0.995, { shape: offOrigin() }); - drawOverWhite(renderer, open); - for (const [x, y] of CORNERS) { - expect(await covered(renderer, x, y)).toBe(0); - } - open.destroy(); - // the cover nearly grown: the screen is covered by the polygon itself - const cover = at(camera, 0.005, { shape: offOrigin(), invert: true }); - drawOverWhite(renderer, cover); - for (const [x, y] of [...CORNERS, [32, 32]]) { - expect(await covered(renderer, x, y)).toBe(1); - } - cover.destroy(); - }); - - it("nearly closed, the image is still drawn, a sliver of the scene in the middle", async (ctx) => { - const renderer = getRenderer(ctx); - const effect = at(camera, 0.05, { shape: discWithHole() }); - const drawImage = vi.spyOn(renderer, "drawImage"); - drawOverWhite(renderer, effect); - expect(drawImage).toHaveBeenCalled(); - drawImage.mockRestore(); - expect(await covered(renderer, 32, 32)).toBe(0); - for (const [x, y] of [...CORNERS, [32, 20], [44, 32]]) { - expect(await covered(renderer, x, y)).toBe(1); - } - effect.destroy(); - }); - - it("center: closes on that point, not on the centre of the screen", async (ctx) => { - const renderer = getRenderer(ctx); - const effect = at(camera, 0.2, { - shape: discWithHole(), - center: { x: 12, y: 12 }, - }); - drawOverWhite(renderer, effect); - expect(await covered(renderer, 12, 12)).toBe(0); - expect(await covered(renderer, 52, 52)).toBe(1); - effect.destroy(); - }); -}; - // One Canvas application for the whole file, made first: the engine gives a // viewport only to the application live at the first `init()` let app; @@ -333,7 +96,7 @@ describe("MaskEffect: image and sprite shapes", () => { return renderer; }); - it("destroy frees the copy of the image uploaded to the GPU", (ctx) => { + it("destroy frees the copy of the image uploaded to the GPU", async (ctx) => { if (renderer === undefined) { ctx.skip("WebGL renderer not available in this environment"); return; @@ -341,40 +104,13 @@ describe("MaskEffect: image and sprite shapes", () => { const effect = at(new Camera2d(0, 0, SIZE, SIZE), 0.5, { shape: discWithHole(), }); - drawOverWhite(renderer, effect); + await drawOverWhite(renderer, effect); const canvas = effect._cover.canvas; expect(renderer.cache.has(canvas)).toBe(true); effect.destroy(); expect(renderer.cache.has(canvas)).toBe(false); }); }); - - describe("WebGPU", () => { - let gpuApp; - let available = false; - beforeAll(async () => { - try { - gpuApp = new Application(SIZE, SIZE, { - parent: "screen", - renderer: video.WEBGPU, - consoleHeader: false, - }); - await gpuApp.init(); - available = gpuApp.renderer.type === "WebGPU"; - } catch { - available = false; - } - }); - afterAll(() => { - gpuApp?.destroy(); - }); - drawingChecks((ctx) => { - if (!available) { - ctx.skip("WebGPU not available in this environment"); - } - return gpuApp.renderer; - }); - }); }); describe("MaskEffect: what a shape and a center resolve to", () => { From 5a3557e7a9a1bffa5d8f1141dd2ac758a67da269 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 00:18:36 +0000 Subject: [PATCH 02/51] GPU tile layers for isometric maps: the shader render mode (#1897) An isometric tile layer can take the "shader" render mode, on WebGL 2 and on WebGPU: one quad for the view, the fragment shader finding each pixel's tile. For a pixel it walks the cells whose tile image could cover it, front to back (the reverse of the order TMXIsometricRenderer draws in), and keeps the first texel that is not transparent, so tall tiles overlap the rows behind them as on the CPU path. - shaders: the part every orientation shares (index and animation lookups, flips, atlas sampling) is split from the orthogonal part, in GLSL and in WGSL; the isometric part adds only its cell maths - renderers: a TMXLayerGPURenderer base per backend, with the orthogonal and isometric ones on top; the part of a layer a view shows is computed in one module both backends read (gpu/tmxlayer_region.js) - TMXLayer: an isometric layer is eligible when its tiles come from one tileset (they overlap, and a pass draws one tileset), an image one, with tiles within the shader's bounds; a tileoffset is supported. A tile of another tileset set at run time moves the layer back to the CPU path - tests: helpers/tile-layer-compare.js draws a layer through the CPU and the GPU path, with the whole engine in between, and compares the frames Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- packages/melonjs/src/level/tiled/TMXLayer.js | 111 +++- .../melonjs/src/video/gpu/tmxlayer_region.js | 143 +++++ .../webgl/renderers/tmxlayer/isometric.js | 54 ++ .../webgl/renderers/tmxlayer/orthogonal.js | 438 +-------------- .../webgl/renderers/tmxlayer/tmxlayer.js | 488 +++++++++++++++++ .../webgl/shaders/isometric-tmxlayer.frag | 67 +++ .../webgl/shaders/orthogonal-tmxlayer.frag | 166 +----- .../video/webgl/shaders/tmxlayer-common.frag | 168 ++++++ ...orthogonal-tmxlayer.vert => tmxlayer.vert} | 0 .../melonjs/src/video/webgl/webgl_renderer.js | 62 ++- .../webgpu/renderers/tmxlayer/isometric.js | 54 ++ .../webgpu/renderers/tmxlayer/orthogonal.js | 449 +-------------- .../webgpu/renderers/tmxlayer/tmxlayer.js | 515 ++++++++++++++++++ .../{tmxlayer.wgsl => tmxlayer-common.wgsl} | 85 +-- .../webgpu/shaders/tmxlayer-isometric.wgsl | 67 +++ .../webgpu/shaders/tmxlayer-orthogonal.wgsl | 69 +++ .../src/video/webgpu/webgpu_renderer.js | 40 +- .../tests/helpers/tile-layer-compare.js | 333 +++++++++++ 18 files changed, 2172 insertions(+), 1137 deletions(-) create mode 100644 packages/melonjs/src/video/gpu/tmxlayer_region.js create mode 100644 packages/melonjs/src/video/webgl/renderers/tmxlayer/isometric.js create mode 100644 packages/melonjs/src/video/webgl/renderers/tmxlayer/tmxlayer.js create mode 100644 packages/melonjs/src/video/webgl/shaders/isometric-tmxlayer.frag create mode 100644 packages/melonjs/src/video/webgl/shaders/tmxlayer-common.frag rename packages/melonjs/src/video/webgl/shaders/{orthogonal-tmxlayer.vert => tmxlayer.vert} (100%) create mode 100644 packages/melonjs/src/video/webgpu/renderers/tmxlayer/isometric.js create mode 100644 packages/melonjs/src/video/webgpu/renderers/tmxlayer/tmxlayer.js rename packages/melonjs/src/video/webgpu/shaders/{tmxlayer.wgsl => tmxlayer-common.wgsl} (73%) create mode 100644 packages/melonjs/src/video/webgpu/shaders/tmxlayer-isometric.wgsl create mode 100644 packages/melonjs/src/video/webgpu/shaders/tmxlayer-orthogonal.wgsl create mode 100644 packages/melonjs/tests/helpers/tile-layer-compare.js diff --git a/packages/melonjs/src/level/tiled/TMXLayer.js b/packages/melonjs/src/level/tiled/TMXLayer.js index e5bd7d2d72..54c7fb89d9 100644 --- a/packages/melonjs/src/level/tiled/TMXLayer.js +++ b/packages/melonjs/src/level/tiled/TMXLayer.js @@ -26,6 +26,13 @@ const FLIP_H_BIT = 1 << 0; const FLIP_V_BIT = 1 << 1; const FLIP_AD_BIT = 1 << 2; +// The largest tiles the isometric shader path draws, in grid cells: the +// bounds of the loops in `isometric-tmxlayer.frag` and its WGSL twin. +const ISOMETRIC_MAX_TILE_WIDTHS = 4; +const ISOMETRIC_MAX_TILE_HEIGHTS = 8; +const ISOMETRIC_ONE_TILESET = + "tiles of more than one tileset in an isometric layer"; + // the area an offset camera shows, handed to the tile renderers in its place // (made on first use) let viewRect; @@ -680,7 +687,7 @@ export default class TMXLayer extends Renderable { if (!renderer || renderer.supportsShaderTileLayers !== true) { return { ok: false, reason: "no-gpu-renderer" }; } - if (this.orientation !== "orthogonal") { + if (this.orientation !== "orthogonal" && this.orientation !== "isometric") { return { ok: false, reason: `no gpu renderer supported yet for "${this.orientation}" orientation`, @@ -689,6 +696,9 @@ export default class TMXLayer extends Renderable { if (!this.tilesets || this.tilesets.tilesets.length === 0) { return { ok: false, reason: "no tilesets" }; } + if (this.orientation === "isometric") { + return this._checkIsometricShaderEligibility(); + } // the shader iterates a fixed-size loop over candidate cells to // support oversized tiles (tile dim > cell dim) drawn bottom-aligned. // Loop bound is MAX_OVERFLOW + 1; anything beyond would silently clip, @@ -719,6 +729,102 @@ export default class TMXLayer extends Renderable { return { ok: true }; } + /** + * Check whether this isometric layer can take the shader path, and note + * the tileset it would draw with. + * + * Isometric tiles overlap (each is drawn as its whole image, over the + * rows behind it), and the shader path draws one tileset at a time: it + * can keep the tile drawn last among those of one tileset, not across + * two. So the layer's tiles must all come from the same tileset. Which + * one is found by looking at the tiles, not at the map's list: a map + * commonly has a tileset per layer. + * @returns {{ok: boolean, reason?: string}} + * @ignore + * @internal + */ + _checkIsometricShaderEligibility() { + /** + * the one tileset an isometric layer on the shader path draws with + * @ignore + */ + this._shaderTileset = undefined; + const data = this.layerData; + let tileset = null; + for (let i = 0; i < data.length; i += 2) { + const gid = data[i]; + if (gid !== 0 && (tileset === null || !tileset.contains(gid))) { + if (tileset !== null) { + return { ok: false, reason: ISOMETRIC_ONE_TILESET }; + } + tileset = this.tilesets.getTilesetByGid(gid); + } + } + // an empty layer: its tileset is the first one a tile is set from + if (tileset !== null) { + const reason = this._isometricTilesetReason(tileset); + if (reason !== undefined) { + return { ok: false, reason }; + } + this._shaderTileset = tileset; + } + return { ok: true }; + } + + /** + * Why the isometric shader path cannot draw the tiles of a tileset, if + * it cannot. + * @param {TMXTileset} tileset - the tileset + * @returns {string|undefined} the reason, or undefined when it can + * @ignore + * @internal + */ + _isometricTilesetReason(tileset) { + if (tileset.isCollection) { + return "collection-of-image tileset"; + } + if (tileset.tilerendersize !== "tile") { + return `tilerendersize "${tileset.tilerendersize}" not supported`; + } + // the shader looks, for each pixel, at every cell whose tile image + // could cover it: a bounded number + if ( + tileset.tilewidth > this.tilewidth * ISOMETRIC_MAX_TILE_WIDTHS || + tileset.tileheight > this.tileheight * ISOMETRIC_MAX_TILE_HEIGHTS + ) { + return `tiles larger than the shader's limit (${ISOMETRIC_MAX_TILE_WIDTHS} grid widths by ${ISOMETRIC_MAX_TILE_HEIGHTS} grid heights)`; + } + return undefined; + } + + /** + * An isometric layer on the shader path draws with one tileset: a tile + * set at run time from another one, or from one the path cannot draw, + * moves the layer back to the legacy renderer. + * @param {number} gid - the gid of the tile just set + * @ignore + * @internal + */ + _keepIsometricShaderTileset(gid) { + const current = this._shaderTileset; + if (current?.contains(gid)) { + return; + } + let reason = ISOMETRIC_ONE_TILESET; + if (current === undefined) { + const tileset = this.tilesets.getTilesetByGid(gid); + reason = this._isometricTilesetReason(tileset); + if (reason === undefined) { + this._shaderTileset = tileset; + return; + } + } + console.warn( + `melonJS: layer "${this.name}" back to the legacy tile renderer (${reason})`, + ); + this.renderMode = "perTile"; + } + // called when the layer is removed from the game world or a container onDeactivateEvent() { // renderer-side caches keyed by this layer (e.g. the WebGL2 shader @@ -825,6 +931,9 @@ export default class TMXLayer extends Renderable { this.dataVersion++; this.isDirty = true; this._preRenderCell(x, y); + if (this.renderMode === "shader" && this.orientation === "isometric") { + this._keepIsometricShaderTileset(cleanGid); + } return tile; } diff --git a/packages/melonjs/src/video/gpu/tmxlayer_region.js b/packages/melonjs/src/video/gpu/tmxlayer_region.js new file mode 100644 index 0000000000..b83f5211bf --- /dev/null +++ b/packages/melonjs/src/video/gpu/tmxlayer_region.js @@ -0,0 +1,143 @@ +/** + * The part of a tile layer a view shows, as the GPU tile layer renderers + * need it: the same on WebGL and WebGPU, so both read it from here. + * + * A region is the quad to draw (`x`, `y`, `width`, `height`, in the layer's + * pixels), the shader's `uVisibleStart` and `uVisibleSize` (the quad's + * corner and size, in the units the orientation's fragment shader works in) + * and its `uOverflow`. + * @import { default as TMXLayer } from "../../level/tiled/TMXLayer.js"; + */ + +/** + * @returns {object} an empty region, for a renderer to fill again and again + * @ignore + */ +export function createRegion() { + return { + x: 0, + y: 0, + width: 0, + height: 0, + startX: 0, + startY: 0, + sizeX: 0, + sizeY: 0, + overflowX: 0, + overflowY: 0, + }; +} + +/** + * The cells of an orthogonal layer a view shows, for the tiles of one + * tileset: the quad covers them, and the shader works in cells. + * @param {TMXLayer} layer - the layer + * @param {object} rect - the visible viewport rect (world coords) + * @param {object} tileset - the tileset whose tiles are drawn + * @param {object} out - the region to fill + * @returns {boolean} false when the view shows nothing of the layer + * @ignore + * @internal + */ +export function orthogonalRegion(layer, rect, tileset, out) { + const tileWidth = layer.tilewidth; + const tileHeight = layer.tileheight; + + // compute the visible region in tile-coord space + const startTileX = Math.max(0, Math.floor(rect.pos.x / tileWidth)); + const startTileY = Math.max(0, Math.floor(rect.pos.y / tileHeight)); + const endTileX = Math.min( + layer.cols, + Math.ceil((rect.pos.x + rect.width) / tileWidth), + ); + const endTileY = Math.min( + layer.rows, + Math.ceil((rect.pos.y + rect.height) / tileHeight), + ); + + // visible rect entirely outside the layer — nothing to draw + if (endTileX <= startTileX || endTileY <= startTileY) { + return false; + } + + // quad world coords + out.x = startTileX * tileWidth; + out.y = startTileY * tileHeight; + out.width = (endTileX - startTileX) * tileWidth; + out.height = (endTileY - startTileY) * tileHeight; + + // visible region in tile units (matches the quad's [0..1] UV span — + // shader recovers the per-fragment tile coord as + // `uVisibleStart + uv * uVisibleSize`) + out.startX = startTileX; + out.startY = startTileY; + out.sizeX = endTileX - startTileX; + out.sizeY = endTileY - startTileY; + + // how many cells a tile reaches past its own, across and up + out.overflowX = Math.max(0, Math.ceil(tileset.tilewidth / tileWidth) - 1); + out.overflowY = Math.max(0, Math.ceil(tileset.tileheight / tileHeight) - 1); + return true; +} + +/** + * The part of an isometric layer a view shows, for the tiles of one tileset: + * the same on every GPU backend, so their renderers share it. + * + * The quad is the view, cut to where the tileset's tiles can be: a tile is + * drawn as its whole image, bottom-aligned on its cell's diamond and moved by + * the tileset's `tileoffset`, so tall tiles reach above the map's top corner + * and wide ones past its right one. + * + * The shader works in the layer's pixels, measured across from the map's top + * corner and with the `tileoffset` taken off: both are in `startX` / + * `startY`, and the shader needs neither. + * @param {TMXLayer} layer - the layer + * @param {object} rect - the visible viewport rect (world coords) + * @param {object} tileset - the tileset whose tiles are drawn + * @param {object} out - the region to fill + * @returns {boolean} false when the view shows nothing of the layer + * @ignore + * @internal + */ +export function isometricRegion(layer, rect, tileset, out) { + const halfWidth = layer.tilewidth / 2; + const halfHeight = layer.tileheight / 2; + const originX = layer.getRenderer().originX; + const offsetX = tileset.tileoffset.x; + const offsetY = tileset.tileoffset.y; + const cols = layer.cols; + const rows = layer.rows; + + // where the tiles can be: from the left of the cell (0, rows - 1) to the + // right of the image of (cols - 1, 0), from the top of the image of + // (0, 0) to the bottom of the diamond of (cols - 1, rows - 1) + const left = originX - rows * halfWidth + offsetX; + const right = originX + (cols - 2) * halfWidth + tileset.tilewidth + offsetX; + const top = layer.tileheight - tileset.tileheight + offsetY; + const bottom = (cols + rows) * halfHeight + offsetY; + + // the view, cut to it, on whole pixels + const x0 = Math.floor(Math.max(rect.pos.x, left)); + const y0 = Math.floor(Math.max(rect.pos.y, top)); + const x1 = Math.ceil(Math.min(rect.pos.x + rect.width, right)); + const y1 = Math.ceil(Math.min(rect.pos.y + rect.height, bottom)); + if (x1 <= x0 || y1 <= y0) { + return false; + } + + out.x = x0; + out.y = y0; + out.width = x1 - x0; + out.height = y1 - y0; + out.startX = x0 - originX - offsetX; + out.startY = y0 - offsetY; + out.sizeX = out.width; + out.sizeY = out.height; + // how many cells' images reach a pixel: as many across as the image is + // wide in half grid widths, as many down as it is tall in half grid + // heights + out.overflowX = Math.ceil(tileset.tilewidth / halfWidth); + out.overflowY = Math.ceil(tileset.tileheight / halfHeight); + return true; +} diff --git a/packages/melonjs/src/video/webgl/renderers/tmxlayer/isometric.js b/packages/melonjs/src/video/webgl/renderers/tmxlayer/isometric.js new file mode 100644 index 0000000000..3483c8e8ce --- /dev/null +++ b/packages/melonjs/src/video/webgl/renderers/tmxlayer/isometric.js @@ -0,0 +1,54 @@ +import { isometricRegion } from "../../../gpu/tmxlayer_region.js"; +import isometricTMXLayerFragment from "../../shaders/isometric-tmxlayer.frag"; +import TMXLayerGPURenderer from "./tmxlayer.js"; + +/** + * additional imports for TypeScript + * @import { default as TMXLayer } from "../../../../level/tiled/TMXLayer.js"; + * @import { default as WebGLRenderer } from "../../webgl_renderer.js"; + */ + +/** + * GPU-accelerated renderer for isometric TMX tile layers (WebGL2): the + * shared {@link TMXLayerGPURenderer}, with an isometric grid's geometry. + * The quad covers the view, and the shader works in pixels. + * + * Isometric tiles overlap, and the shader keeps the one drawn last among + * those of ONE tileset: a layer takes this path only when all its tiles + * come from the same one (`layer._shaderTileset`, set by the layer when it + * is found eligible). + * @ignore + * @internal + */ +export default class IsometricTMXLayerGPURenderer extends TMXLayerGPURenderer { + /** + * @param {WebGLRenderer} renderer - the WebGL renderer instance + */ + constructor(renderer) { + super(renderer, isometricTMXLayerFragment); + this._tilesets = []; + } + + /** + * @ignore + * @internal + */ + _region(layer, rect, tileset, out) { + return isometricRegion(layer, rect, tileset, out); + } + + /** + * The one tileset an isometric layer on this path draws with. + * @param {TMXLayer} layer - the layer + * @returns {object[]} that tileset, or none for an empty layer + * @ignore + * @internal + */ + _tilesetsOf(layer) { + this._tilesets.length = 0; + if (layer._shaderTileset) { + this._tilesets.push(layer._shaderTileset); + } + return this._tilesets; + } +} diff --git a/packages/melonjs/src/video/webgl/renderers/tmxlayer/orthogonal.js b/packages/melonjs/src/video/webgl/renderers/tmxlayer/orthogonal.js index 1d7e8a79f3..f6e6f6fd74 100644 --- a/packages/melonjs/src/video/webgl/renderers/tmxlayer/orthogonal.js +++ b/packages/melonjs/src/video/webgl/renderers/tmxlayer/orthogonal.js @@ -1,7 +1,6 @@ -import { BufferTextureResource } from "../../../texture/resource.js"; -import GLShader from "../../glshader.js"; +import { orthogonalRegion } from "../../../gpu/tmxlayer_region.js"; import orthogonalTMXLayerFragment from "../../shaders/orthogonal-tmxlayer.frag"; -import orthogonalTMXLayerVertex from "../../shaders/orthogonal-tmxlayer.vert"; +import TMXLayerGPURenderer from "./tmxlayer.js"; /** * additional imports for TypeScript @@ -9,445 +8,26 @@ import orthogonalTMXLayerVertex from "../../shaders/orthogonal-tmxlayer.vert"; * @import { default as WebGLRenderer } from "../../webgl_renderer.js"; */ -// Default `uTint` when the layer has no tint set. Module-scoped so the -// fallback path doesn't allocate per frame. -const DEFAULT_TINT = new Float32Array([1, 1, 1, 1]); - /** - * GPU-accelerated renderer for orthogonal TMX tile layers (WebGL2). Draws - * the visible region of a layer as one screen-aligned quad per tileset - * referenced by the layer — the fragment shader samples a per-layer GID - * index texture and the tileset atlas, eliminating the per-tile draw - * loop. The visible rect, GID range, tile size, opacity, and tint are - * pushed as uniforms; the index texture is uploaded once at activation - * and re-uploaded only when `layer.dataVersion` changes (mutations from - * `setTile`/`clearTile`). - * - * The per-layer index texture is a `BufferTextureResource` flowing - * through the standard `TextureCache` / batcher path — same lane as - * every other texture in the engine. Dynamic unit allocation, correct - * `boundTextures` bookkeeping, and per-resource premultiplied-alpha / - * filter all come for free; nothing here pokes `gl.bindTexture` or - * `gl.activeTexture` directly. - * - * Cache lifecycle: one `BufferTextureResource` per `TMXLayer`. Tile - * layers don't come and go individually — they only churn on game reset - * — so the cache is freed in bulk via `reset()`, called from - * `WebGLRenderer.reset()` (which the `GAME_RESET` event already - * triggers). - * + * GPU-accelerated renderer for orthogonal TMX tile layers (WebGL2): the + * shared {@link TMXLayerGPURenderer}, with an orthogonal grid's geometry. + * The quad covers the cells in view, and the shader works in cells. * @ignore * @internal */ -export default class OrthogonalTMXLayerGPURenderer { +export default class OrthogonalTMXLayerGPURenderer extends TMXLayerGPURenderer { /** * @param {WebGLRenderer} renderer - the WebGL renderer instance */ constructor(renderer) { - this.renderer = renderer; - this.gl = renderer.gl; - // Standalone `GLShader` (not `ShaderEffect`) so we own both the - // vertex and the fragment source — they're paired in GLSL ES 3.00, - // which lets the fragment shader use `texelFetch` for byte-exact - // reads from the index / animation lookup textures (samplers stay - // `sampler2D` and decode the 8-bit channels as normalized floats; - // `usampler2D` would conflict with the engine's multi-texture - // batching cache). `setBatcher("quad", this.shader)` integrates - // the program with the quad batcher just like a `ShaderEffect` — - // only the per-fragment math gets cleaner. - this.shader = new GLShader( - renderer.gl, - orthogonalTMXLayerVertex, - orthogonalTMXLayerFragment, - renderer.shaderPrecision, - ); - // per-layer `BufferTextureResource`. `Map` (not `WeakMap`) so we - // can iterate on `reset()` to walk through the global texture - // cache and free GL handles. The world's container holds the - // strong ref to each layer anyway, so this doesn't change layer - // lifetime. - this.resources = new Map(); - // per-tileset animation-lookup resources, keyed by `TMXTileset`. - // Only allocated for tilesets that actually have animated tiles - // (`tileset.isAnimated === true`). - this.animLookups = new Map(); - // pre-allocated scratch for uniform uploads — avoids per-frame - // allocation in the hot path - /** - * @ignore - * @internal - */ - this._v2 = new Float32Array(2); - /** - * @ignore - * @internal - */ - this._v4 = new Float32Array(4); - } - - /** - * Free every cached per-layer index texture and empty the local - * resource map. Called from `WebGLRenderer.reset()` (which - * `GAME_RESET` triggers) so each level transition starts clean. - * @ignore - * @internal - */ - reset() { - // Uploads happen via the quad batcher (see `_drawLayer`), so pin - // the cleanup to that same batcher rather than whatever happens - // to be `currentBatcher` at reset time. `currentBatcher` may - // legitimately be a `PrimitiveBatcher` (e.g. debug-plugin drew - // its quadtree overlay on the previous frame) which has no - // `deleteTexture2D` and would crash the reset. Issue #1471. - const batcher = this.renderer.batchers.get("quad"); - const cache = this.renderer.cache; - const drop = (resource) => { - // route through the batcher so its `boundTextures` bookkeeping - // stays in sync. When no batcher is available (context tear- - // down) or the registered "quad" batcher is a user-supplied - // custom class that doesn't extend `MaterialBatcher`, we - // don't have a clean GL deletion path — still need to free - // the unit assignment, since `cache.delete()` only touches - // the image→atlas map and would leave the unit slot held - // forever otherwise. - if (typeof batcher?.deleteTexture2D === "function") { - batcher.deleteTexture2D(resource); - } else { - cache.freeTextureUnit(resource); - cache.delete(resource); - } - }; - for (const resource of this.resources.values()) { - drop(resource); - } - for (const entry of this.animLookups.values()) { - drop(entry.resource); - } - this.resources.clear(); - this.animLookups.clear(); - } - - /** - * Write a `vec2` uniform without allocating a fresh Float32Array per - * call. Both components flow into the shared `_v2` scratch buffer, - * which `setUniform` reads synchronously and forwards to - * `gl.uniform2fv` — so reusing the buffer across calls is safe. - * @param {string} name - * @param {number} x - * @param {number} y - * @private - * @ignore - * @internal - */ - _setV2(name, x, y) { - this._v2[0] = x; - this._v2[1] = y; - this.shader.setUniform(name, this._v2); + super(renderer, orthogonalTMXLayerFragment); } /** - * `vec4` counterpart to {@link _setV2}. - * @param {string} name - * @param {number} x - * @param {number} y - * @param {number} z - * @param {number} w - * @private * @ignore * @internal */ - _setV4(name, x, y, z, w) { - this._v4[0] = x; - this._v4[1] = y; - this._v4[2] = z; - this._v4[3] = w; - this.shader.setUniform(name, this._v4); - } - - /** - * Get-or-create the per-tileset animation-lookup entry. Returns - * `undefined` for tilesets that have no animated tiles (the shader's - * `uAnimEnabled` uniform is then set to 0 and the lookup texture is - * not bound). - * - * The entry holds a `tileCount × 1` RGBA8 `BufferTextureResource` - * where texel `localId` encodes the CURRENT frame's local id as - * `R = lo byte, G = hi byte` (same encoding as the GID index - * texture). Each call walks `tileset.animations` and rewrites - * dirty texels — `tileset.update(dt)` (driven by the layer) advances - * `anim.cur.tileid` independently of this renderer. - * - * @param {object} tileset - * @param {number} tileCount - tiles in the tileset's atlas grid - * (`atlasCols * atlasRows`) - * @returns {{resource: BufferTextureResource, data: Uint8Array, - * tileCount: number, dirty: boolean}|undefined} - * @ignore - * @internal - */ - _getOrUpdateAnimLookup(tileset, tileCount) { - if (!tileset.isAnimated || tileset.animations.size === 0) { - return undefined; - } - let entry = this.animLookups.get(tileset); - if (entry === undefined) { - // allocate the lookup texture and initialize it to identity - // (localId → localId); animated entries get overwritten below - const data = new Uint8Array(tileCount * 4); - for (let id = 0; id < tileCount; id++) { - data[id * 4 + 0] = id & 0xff; - data[id * 4 + 1] = (id >> 8) & 0xff; - } - const resource = new BufferTextureResource(data, { - width: tileCount, - height: 1, - premultipliedAlpha: false, - repeat: "no-repeat", - // NEAREST so the shader's `texelFetch` reads byte-exact - // channel values back as normalized floats - filter: this.gl.NEAREST, - format: "rgba8", - }); - // new entry → first upload happens unconditionally via the - // batcher's `boundTextures[unit] === undefined` path - entry = { resource, data, tileCount, dirty: false }; - this.animLookups.set(tileset, entry); - } - // walk animations and rewrite the current-frame ids. The dirty - // flag flips true only when at least one texel actually changed - // — the batcher then force-reuploads on the next bind, otherwise - // reuses the existing GL texture untouched. - const data = entry.data; - for (const [localId, anim] of tileset.animations) { - const off = localId * 4; - const cur = anim.cur.tileid; - const lo = cur & 0xff; - const hi = (cur >> 8) & 0xff; - if (data[off] !== lo || data[off + 1] !== hi) { - data[off] = lo; - data[off + 1] = hi; - entry.dirty = true; - } - } - return entry; - } - - /** - * Get-or-create the per-layer index `BufferTextureResource`. - * @param {TMXLayer} layer - * @returns {BufferTextureResource} - * @ignore - * @internal - */ - _getResource(layer) { - let resource = this.resources.get(layer); - if (resource === undefined) { - // reinterpret the layer's `Uint16Array` payload as RGBA bytes - // (zero-copy on every little-endian platform = every browser) - resource = new BufferTextureResource( - new Uint8Array(layer.layerData.buffer), - { - width: layer.cols, - height: layer.rows, - // raw GID bytes — must NOT have alpha pre-multiplied - // into RGB, otherwise A=0 cells wipe their R/G/B - premultipliedAlpha: false, - repeat: "no-repeat", - // NEAREST so `texelFetch` returns the original byte - // values (as normalized floats) for the GID/flip - // decode below - filter: this.gl.NEAREST, - format: "rgba8", - }, - ); - // track the last-uploaded version so we know when to force a - // re-upload after `setTile` / `clearTile` mutations - resource._uploadedVersion = -1; - this.resources.set(layer, resource); - } - return resource; - } - - /** - * Draw an orthogonal TMX layer through the shader path. - * @param {TMXLayer} layer - * @param {object} rect - the visible viewport rect (world coords) - */ - draw(layer, rect) { - const renderer = this.renderer; - const tileWidth = layer.tilewidth; - const tileHeight = layer.tileheight; - const cols = layer.cols; - const rows = layer.rows; - - // compute the visible region in tile-coord space - const startTileX = Math.max(0, Math.floor(rect.pos.x / tileWidth)); - const startTileY = Math.max(0, Math.floor(rect.pos.y / tileHeight)); - const endTileX = Math.min( - cols, - Math.ceil((rect.pos.x + rect.width) / tileWidth), - ); - const endTileY = Math.min( - rows, - Math.ceil((rect.pos.y + rect.height) / tileHeight), - ); - - // visible rect entirely outside the layer — nothing to draw - if (endTileX <= startTileX || endTileY <= startTileY) { - return; - } - - // quad world coords - const worldX = startTileX * tileWidth; - const worldY = startTileY * tileHeight; - const worldW = (endTileX - startTileX) * tileWidth; - const worldH = (endTileY - startTileY) * tileHeight; - - // visible region size in tile units (matches the quad's [0..1] UV - // span — shader recovers the per-fragment tile coord as - // `uVisibleStart + uv * uVisibleSize`) - const visStartX = startTileX; - const visStartY = startTileY; - const visSizeX = endTileX - startTileX; - const visSizeY = endTileY - startTileY; - - // switch the quad batcher to our custom shader. This flushes any - // queued sprite vertices first so they render under their original - // shader, then re-binds for our pass. - const batcher = renderer.setBatcher("quad", this.shader); - - // upload (or rebind) the index texture through the standard cache - // path: dynamic unit allocation, correct `boundTextures` tracking, - // per-resource premultiply / filter applied automatically - const resource = this._getResource(layer); - const indexUnit = batcher.uploadTexture( - resource, - cols, - rows, - resource._uploadedVersion !== layer.dataVersion, - ); - resource._uploadedVersion = layer.dataVersion; - - this.shader.setUniform("uTileIndex", indexUnit); - this._setV2("uMapSize", cols, rows); - this._setV2("uVisibleStart", visStartX, visStartY); - this._setV2("uVisibleSize", visSizeX, visSizeY); - this._setV2("uCellSize", tileWidth, tileHeight); - // the layer's opacity, and the fade of everything it is drawn in: - // set on the renderer by the layer's preDraw - this.shader.setUniform("uOpacity", renderer.getGlobalAlpha()); - this.shader.setUniform( - "uTint", - layer.tint ? layer.tint.toArray() : DEFAULT_TINT, - ); - - // one pass per tileset — the shader's uGidRange uniform + discard - // hides cells outside the active tileset's GID range - const tilesets = layer.tilesets.tilesets; - for (let i = 0; i < tilesets.length; i++) { - const tileset = tilesets[i]; - // skip collection-of-image tilesets (caller's eligibility check - // should have downgraded these layers to the legacy path, but - // guard defensively — we can't compute uTilesetCols for them) - if (tileset.isCollection || tileset.image === undefined) { - continue; - } - - const tsW = tileset.tilewidth; - const tsH = tileset.tileheight; - const margin = tileset.margin; - const spacing = tileset.spacing; - const atlasW = tileset.image.width; - const atlasH = tileset.image.height; - - // atlas geometry (margin + spacing) — number of tiles per row/col - // in the atlas image - const atlasCols = Math.max( - 1, - Math.floor((atlasW - margin * 2 + spacing) / (tsW + spacing)), - ); - const atlasRows = Math.max( - 1, - Math.floor((atlasH - margin * 2 + spacing) / (tsH + spacing)), - ); - - // per-tileset animation lookup. Only allocated/bound for - // tilesets that actually have animated tiles — static tilesets - // pay neither a texture-unit nor an upload. - const tileCount = atlasCols * atlasRows; - const animEntry = this._getOrUpdateAnimLookup(tileset, tileCount); - if (animEntry !== undefined) { - const animUnit = batcher.uploadTexture( - animEntry.resource, - animEntry.tileCount, - 1, - animEntry.dirty, - ); - animEntry.dirty = false; - this.shader.setUniform("uAnimLookup", animUnit); - this.shader.setUniform("uAnimSize", animEntry.tileCount); - } else { - // shader skips the animation lookup when uAnimSize == 0, - // but every declared sampler must still point at a valid - // unit — reuse the index unit so WebGL's draw-time - // validation is happy (the sampler is never read because - // of the uAnimSize guard) - this.shader.setUniform("uAnimLookup", indexUnit); - this.shader.setUniform("uAnimSize", 0); - } - - this._setV2("uTileSize", tsW, tsH); - this._setV2("uTilesetCols", atlasCols, atlasRows); - this._setV2("uInvTilesetSize", 1 / atlasW, 1 / atlasH); - this._setV4("uTilesetMargin", margin, margin, spacing, spacing); - this._setV2( - "uOverflow", - Math.max(0, Math.ceil(tsW / tileWidth) - 1), - Math.max(0, Math.ceil(tsH / tileHeight) - 1), - ); - this._setV2("uGidRange", tileset.firstgid, tileset.lastgid); - // the tileset samples its mipmaps when the batcher binds it a - // mip sampler: the "linear-mipmap" filter, on a linear texture - const filter = - typeof tileset.texture.filter !== "undefined" - ? tileset.texture.filter - : batcher.renderer._glTextureFilter(); - this.shader.setUniform( - "uMipmaps", - (filter === this.gl.LINEAR || filter === "linear") && - batcher.renderer.wantsMipmaps(tileset.texture) - ? 1 - : 0, - ); - - // emit one screen-quad. The batcher will bind the tileset's - // TextureAtlas to uSampler (single-texture fallback path is - // active because we have a custom ShaderEffect). - // on whole pixels unless `subPixel` is set, as a sprite is: the - // tiles move with the quad (see Renderer#_pixelSnapBegin) - const snapped = batcher.renderer._pixelSnapBegin( - worldX, - worldY, - worldW, - worldH, - ); - batcher.addQuad( - tileset.texture, - worldX, - worldY, - worldW, - worldH, - 0, - 0, - 1, - 1, - 0xffffffff, - ); - batcher.renderer._pixelSnapEnd(snapped); - - // flush per-pass so each tileset's draw call uses its own - // uniforms (uGidRange / uTileSize / uTilesetCols differ) - batcher.flush(); - } + _region(layer, rect, tileset, out) { + return orthogonalRegion(layer, rect, tileset, out); } } diff --git a/packages/melonjs/src/video/webgl/renderers/tmxlayer/tmxlayer.js b/packages/melonjs/src/video/webgl/renderers/tmxlayer/tmxlayer.js new file mode 100644 index 0000000000..b740e8591f --- /dev/null +++ b/packages/melonjs/src/video/webgl/renderers/tmxlayer/tmxlayer.js @@ -0,0 +1,488 @@ +import { createRegion } from "../../../gpu/tmxlayer_region.js"; +import { BufferTextureResource } from "../../../texture/resource.js"; +import GLShader from "../../glshader.js"; +import tmxLayerVertex from "../../shaders/tmxlayer.vert"; +import tmxLayerCommonFragment from "../../shaders/tmxlayer-common.frag"; + +/** + * additional imports for TypeScript + * @import { default as TMXLayer } from "../../../../level/tiled/TMXLayer.js"; + * @import { default as WebGLRenderer } from "../../webgl_renderer.js"; + */ + +// Default `uTint` when the layer has no tint set. Module-scoped so the +// fallback path doesn't allocate per frame. +const DEFAULT_TINT = new Float32Array([1, 1, 1, 1]); + +/** + * GPU-accelerated renderer for TMX tile layers (WebGL2): what every map + * orientation shares. Draws the visible region of a layer as one + * screen-aligned quad per tileset — the fragment shader samples a per-layer + * GID index texture and the tileset atlas, eliminating the per-tile draw + * loop. The visible rect, GID range, tile size, opacity, and tint are + * pushed as uniforms; the index texture is uploaded once at activation + * and re-uploaded only when `layer.dataVersion` changes (mutations from + * `setTile`/`clearTile`). + * + * An orientation's renderer extends this one with the two things that + * differ: its part of the fragment shader (where a cell's tile is, and which + * cells can cover a fragment), and {@link TMXLayerGPURenderer#_region}, the + * part of the layer a view shows. + * + * The per-layer index texture is a `BufferTextureResource` flowing + * through the standard `TextureCache` / batcher path — same lane as + * every other texture in the engine. Dynamic unit allocation, correct + * `boundTextures` bookkeeping, and per-resource premultiplied-alpha / + * filter all come for free; nothing here pokes `gl.bindTexture` or + * `gl.activeTexture` directly. + * + * Cache lifecycle: one `BufferTextureResource` per `TMXLayer`. Tile + * layers don't come and go individually — they only churn on game reset + * — so the cache is freed in bulk via `reset()`, called from + * `WebGLRenderer.reset()` (which the `GAME_RESET` event already + * triggers). + * + * @ignore + * @internal + */ +export default class TMXLayerGPURenderer { + /** + * @param {WebGLRenderer} renderer - the WebGL renderer instance + * @param {string} fragment - the orientation's part of the fragment + * shader, appended to the shared one + */ + constructor(renderer, fragment) { + this.renderer = renderer; + this.gl = renderer.gl; + // Standalone `GLShader` (not `ShaderEffect`) so we own both the + // vertex and the fragment source — they're paired in GLSL ES 3.00, + // which lets the fragment shader use `texelFetch` for byte-exact + // reads from the index / animation lookup textures (samplers stay + // `sampler2D` and decode the 8-bit channels as normalized floats; + // `usampler2D` would conflict with the engine's multi-texture + // batching cache). `setBatcher("quad", this.shader)` integrates + // the program with the quad batcher just like a `ShaderEffect` — + // only the per-fragment math gets cleaner. + this.shader = new GLShader( + renderer.gl, + tmxLayerVertex, + `${tmxLayerCommonFragment}\n${fragment}`, + renderer.shaderPrecision, + ); + // per-layer `BufferTextureResource`. `Map` (not `WeakMap`) so we + // can iterate on `reset()` to walk through the global texture + // cache and free GL handles. The world's container holds the + // strong ref to each layer anyway, so this doesn't change layer + // lifetime. + this.resources = new Map(); + // per-tileset animation-lookup resources, keyed by `TMXTileset`. + // Only allocated for tilesets that actually have animated tiles + // (`tileset.isAnimated === true`). + this.animLookups = new Map(); + // pre-allocated scratch for uniform uploads — avoids per-frame + // allocation in the hot path + /** + * @ignore + * @internal + */ + this._v2 = new Float32Array(2); + /** + * @ignore + * @internal + */ + this._v4 = new Float32Array(4); + /** + * the texture unit of the index texture of the layer being drawn + * @ignore + * @internal + */ + this._indexUnit = 0; + /** + * what {@link TMXLayerGPURenderer#_region} fills: the quad to draw, + * in the layer's pixels, and what the shader needs to find a + * fragment's place in the layer from its place in the quad + * @ignore + * @internal + */ + this._regionScratch = createRegion(); + } + + /** + * The part of a layer a view shows, for the tiles of one tileset: the + * quad to draw (`x`, `y`, `width`, `height`, in the layer's pixels), the + * shader's `uVisibleStart` and `uVisibleSize` (the quad's corner and + * size, in the units its fragment shader works in) and `uOverflow`. + * @param {TMXLayer} layer - the layer + * @param {object} rect - the visible viewport rect (world coords) + * @param {object} tileset - the tileset whose tiles are drawn + * @param {object} out - the region to fill + * @returns {boolean} false when the view shows nothing of the layer + * @abstract + * @ignore + * @internal + */ + // eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars + _region(layer, rect, tileset, out) { + return false; + } + + /** + * The tilesets a layer is drawn with, one pass each. + * @param {TMXLayer} layer - the layer + * @returns {object[]} the tilesets + * @ignore + * @internal + */ + _tilesetsOf(layer) { + return layer.tilesets.tilesets; + } + + /** + * Free every cached per-layer index texture and empty the local + * resource map. Called from `WebGLRenderer.reset()` (which + * `GAME_RESET` triggers) so each level transition starts clean. + * @ignore + * @internal + */ + reset() { + // Uploads happen via the quad batcher (see `_drawLayer`), so pin + // the cleanup to that same batcher rather than whatever happens + // to be `currentBatcher` at reset time. `currentBatcher` may + // legitimately be a `PrimitiveBatcher` (e.g. debug-plugin drew + // its quadtree overlay on the previous frame) which has no + // `deleteTexture2D` and would crash the reset. Issue #1471. + const batcher = this.renderer.batchers.get("quad"); + const cache = this.renderer.cache; + const drop = (resource) => { + // route through the batcher so its `boundTextures` bookkeeping + // stays in sync. When no batcher is available (context tear- + // down) or the registered "quad" batcher is a user-supplied + // custom class that doesn't extend `MaterialBatcher`, we + // don't have a clean GL deletion path — still need to free + // the unit assignment, since `cache.delete()` only touches + // the image→atlas map and would leave the unit slot held + // forever otherwise. + if (typeof batcher?.deleteTexture2D === "function") { + batcher.deleteTexture2D(resource); + } else { + cache.freeTextureUnit(resource); + cache.delete(resource); + } + }; + for (const resource of this.resources.values()) { + drop(resource); + } + for (const entry of this.animLookups.values()) { + drop(entry.resource); + } + this.resources.clear(); + this.animLookups.clear(); + } + + /** + * Write a `vec2` uniform without allocating a fresh Float32Array per + * call. Both components flow into the shared `_v2` scratch buffer, + * which `setUniform` reads synchronously and forwards to + * `gl.uniform2fv` — so reusing the buffer across calls is safe. + * @param {string} name + * @param {number} x + * @param {number} y + * @private + * @ignore + * @internal + */ + _setV2(name, x, y) { + this._v2[0] = x; + this._v2[1] = y; + this.shader.setUniform(name, this._v2); + } + + /** + * `vec4` counterpart to {@link _setV2}. + * @param {string} name + * @param {number} x + * @param {number} y + * @param {number} z + * @param {number} w + * @private + * @ignore + * @internal + */ + _setV4(name, x, y, z, w) { + this._v4[0] = x; + this._v4[1] = y; + this._v4[2] = z; + this._v4[3] = w; + this.shader.setUniform(name, this._v4); + } + + /** + * Get-or-create the per-tileset animation-lookup entry. Returns + * `undefined` for tilesets that have no animated tiles (the shader's + * `uAnimEnabled` uniform is then set to 0 and the lookup texture is + * not bound). + * + * The entry holds a `tileCount × 1` RGBA8 `BufferTextureResource` + * where texel `localId` encodes the CURRENT frame's local id as + * `R = lo byte, G = hi byte` (same encoding as the GID index + * texture). Each call walks `tileset.animations` and rewrites + * dirty texels — `tileset.update(dt)` (driven by the layer) advances + * `anim.cur.tileid` independently of this renderer. + * + * @param {object} tileset + * @param {number} tileCount - tiles in the tileset's atlas grid + * (`atlasCols * atlasRows`) + * @returns {{resource: BufferTextureResource, data: Uint8Array, + * tileCount: number, dirty: boolean}|undefined} + * @ignore + * @internal + */ + _getOrUpdateAnimLookup(tileset, tileCount) { + if (!tileset.isAnimated || tileset.animations.size === 0) { + return undefined; + } + let entry = this.animLookups.get(tileset); + if (entry === undefined) { + // allocate the lookup texture and initialize it to identity + // (localId → localId); animated entries get overwritten below + const data = new Uint8Array(tileCount * 4); + for (let id = 0; id < tileCount; id++) { + data[id * 4 + 0] = id & 0xff; + data[id * 4 + 1] = (id >> 8) & 0xff; + } + const resource = new BufferTextureResource(data, { + width: tileCount, + height: 1, + premultipliedAlpha: false, + repeat: "no-repeat", + // NEAREST so the shader's `texelFetch` reads byte-exact + // channel values back as normalized floats + filter: this.gl.NEAREST, + format: "rgba8", + }); + // new entry → first upload happens unconditionally via the + // batcher's `boundTextures[unit] === undefined` path + entry = { resource, data, tileCount, dirty: false }; + this.animLookups.set(tileset, entry); + } + // walk animations and rewrite the current-frame ids. The dirty + // flag flips true only when at least one texel actually changed + // — the batcher then force-reuploads on the next bind, otherwise + // reuses the existing GL texture untouched. + const data = entry.data; + for (const [localId, anim] of tileset.animations) { + const off = localId * 4; + const cur = anim.cur.tileid; + const lo = cur & 0xff; + const hi = (cur >> 8) & 0xff; + if (data[off] !== lo || data[off + 1] !== hi) { + data[off] = lo; + data[off + 1] = hi; + entry.dirty = true; + } + } + return entry; + } + + /** + * Get-or-create the per-layer index `BufferTextureResource`. + * @param {TMXLayer} layer + * @returns {BufferTextureResource} + * @ignore + * @internal + */ + _getResource(layer) { + let resource = this.resources.get(layer); + if (resource === undefined) { + // reinterpret the layer's `Uint16Array` payload as RGBA bytes + // (zero-copy on every little-endian platform = every browser) + resource = new BufferTextureResource( + new Uint8Array(layer.layerData.buffer), + { + width: layer.cols, + height: layer.rows, + // raw GID bytes — must NOT have alpha pre-multiplied + // into RGB, otherwise A=0 cells wipe their R/G/B + premultipliedAlpha: false, + repeat: "no-repeat", + // NEAREST so `texelFetch` returns the original byte + // values (as normalized floats) for the GID/flip + // decode below + filter: this.gl.NEAREST, + format: "rgba8", + }, + ); + // track the last-uploaded version so we know when to force a + // re-upload after `setTile` / `clearTile` mutations + resource._uploadedVersion = -1; + this.resources.set(layer, resource); + } + return resource; + } + + /** + * Bind the layer's shader and what all its tilesets share: called for + * the first tileset the view shows something of. + * @param {TMXLayer} layer - the layer + * @returns {object} the quad batcher, on this renderer's shader + * @ignore + * @internal + */ + _begin(layer) { + const renderer = this.renderer; + const cols = layer.cols; + const rows = layer.rows; + + // switch the quad batcher to our custom shader. This flushes any + // queued sprite vertices first so they render under their original + // shader, then re-binds for our pass. + const batcher = renderer.setBatcher("quad", this.shader); + + // upload (or rebind) the index texture through the standard cache + // path: dynamic unit allocation, correct `boundTextures` tracking, + // per-resource premultiply / filter applied automatically + const resource = this._getResource(layer); + this._indexUnit = batcher.uploadTexture( + resource, + cols, + rows, + resource._uploadedVersion !== layer.dataVersion, + ); + resource._uploadedVersion = layer.dataVersion; + + this.shader.setUniform("uTileIndex", this._indexUnit); + this._setV2("uMapSize", cols, rows); + this._setV2("uCellSize", layer.tilewidth, layer.tileheight); + // the layer's opacity, and the fade of everything it is drawn in: + // set on the renderer by the layer's preDraw + this.shader.setUniform("uOpacity", renderer.getGlobalAlpha()); + this.shader.setUniform( + "uTint", + layer.tint ? layer.tint.toArray() : DEFAULT_TINT, + ); + return batcher; + } + + /** + * Draw a TMX layer through the shader path. + * @param {TMXLayer} layer + * @param {object} rect - the visible viewport rect (world coords) + */ + draw(layer, rect) { + const region = this._regionScratch; + let batcher; + + // one pass per tileset — the shader's uGidRange uniform + discard + // hides cells outside the active tileset's GID range + const tilesets = this._tilesetsOf(layer); + for (let i = 0; i < tilesets.length; i++) { + const tileset = tilesets[i]; + // skip collection-of-image tilesets (caller's eligibility check + // should have downgraded these layers to the legacy path, but + // guard defensively — we can't compute uTilesetCols for them) + if (tileset.isCollection || tileset.image === undefined) { + continue; + } + // the view shows nothing of this tileset's tiles + if (!this._region(layer, rect, tileset, region)) { + continue; + } + batcher ??= this._begin(layer); + const indexUnit = this._indexUnit; + + const tsW = tileset.tilewidth; + const tsH = tileset.tileheight; + const margin = tileset.margin; + const spacing = tileset.spacing; + const atlasW = tileset.image.width; + const atlasH = tileset.image.height; + + // atlas geometry (margin + spacing) — number of tiles per row/col + // in the atlas image + const atlasCols = Math.max( + 1, + Math.floor((atlasW - margin * 2 + spacing) / (tsW + spacing)), + ); + const atlasRows = Math.max( + 1, + Math.floor((atlasH - margin * 2 + spacing) / (tsH + spacing)), + ); + + // per-tileset animation lookup. Only allocated/bound for + // tilesets that actually have animated tiles — static tilesets + // pay neither a texture-unit nor an upload. + const tileCount = atlasCols * atlasRows; + const animEntry = this._getOrUpdateAnimLookup(tileset, tileCount); + if (animEntry !== undefined) { + const animUnit = batcher.uploadTexture( + animEntry.resource, + animEntry.tileCount, + 1, + animEntry.dirty, + ); + animEntry.dirty = false; + this.shader.setUniform("uAnimLookup", animUnit); + this.shader.setUniform("uAnimSize", animEntry.tileCount); + } else { + // shader skips the animation lookup when uAnimSize == 0, + // but every declared sampler must still point at a valid + // unit — reuse the index unit so WebGL's draw-time + // validation is happy (the sampler is never read because + // of the uAnimSize guard) + this.shader.setUniform("uAnimLookup", indexUnit); + this.shader.setUniform("uAnimSize", 0); + } + + this._setV2("uTileSize", tsW, tsH); + this._setV2("uTilesetCols", atlasCols, atlasRows); + this._setV2("uInvTilesetSize", 1 / atlasW, 1 / atlasH); + this._setV4("uTilesetMargin", margin, margin, spacing, spacing); + this._setV2("uVisibleStart", region.startX, region.startY); + this._setV2("uVisibleSize", region.sizeX, region.sizeY); + this._setV2("uOverflow", region.overflowX, region.overflowY); + this._setV2("uGidRange", tileset.firstgid, tileset.lastgid); + // the tileset samples its mipmaps when the batcher binds it a + // mip sampler: the "linear-mipmap" filter, on a linear texture + const filter = + typeof tileset.texture.filter !== "undefined" + ? tileset.texture.filter + : batcher.renderer._glTextureFilter(); + this.shader.setUniform( + "uMipmaps", + (filter === this.gl.LINEAR || filter === "linear") && + batcher.renderer.wantsMipmaps(tileset.texture) + ? 1 + : 0, + ); + + // emit one screen-quad. The batcher will bind the tileset's + // TextureAtlas to uSampler (single-texture fallback path is + // active because we have a custom ShaderEffect). + // on whole pixels unless `subPixel` is set, as a sprite is: the + // tiles move with the quad (see Renderer#_pixelSnapBegin) + const snapped = batcher.renderer._pixelSnapBegin( + region.x, + region.y, + region.width, + region.height, + ); + batcher.addQuad( + tileset.texture, + region.x, + region.y, + region.width, + region.height, + 0, + 0, + 1, + 1, + 0xffffffff, + ); + batcher.renderer._pixelSnapEnd(snapped); + + // flush per-pass so each tileset's draw call uses its own + // uniforms (uGidRange / uTileSize / uTilesetCols differ) + batcher.flush(); + } + } +} diff --git a/packages/melonjs/src/video/webgl/shaders/isometric-tmxlayer.frag b/packages/melonjs/src/video/webgl/shaders/isometric-tmxlayer.frag new file mode 100644 index 0000000000..6c7f1ac61f --- /dev/null +++ b/packages/melonjs/src/video/webgl/shaders/isometric-tmxlayer.frag @@ -0,0 +1,67 @@ +// The isometric part of the TMX layer fragment shader: appended to +// `tmxlayer-common.frag`. +// +// A fragment's position is in the layer's pixels, measured across from the +// map's top corner (the renderer takes the map's `originX` and the +// tileset's `tileoffset` off before it gets here), so the cell maths below +// is that of `TMXIsometricRenderer` with no origin in it. +// +// The tile of cell (col, row) is drawn as its whole image, bottom-aligned on +// the cell's diamond: with u = col - row and s = col + row, its left edge is +// at (u - 1) half grid widths and its bottom edge at (s + 2) half grid +// heights. So the cells whose image covers a fragment are a run of `u`, as +// long as the image is wide in half grid widths, and a run of `s`, as long +// as it is tall in half grid heights: `uOverflow` holds the two lengths. +// Only pairs of the same parity are cells. +// +// The CPU renderer draws rows of constant `s` from the top of the screen +// down, each from left to right. The last tile drawn is the one seen, so the +// scan here goes the other way, s high→low then u high→low, and the FIRST +// cell with an opaque texel is the fragment. + +// bounds of the two runs: tiles up to 8 grid heights tall and 4 grid widths +// wide (the layer falls back to the CPU renderer past them) +const int MAX_ROWS = 16; +const int MAX_COLS = 4; + +// the left of the cell's diamond, and as far above its bottom as the tile +// is tall +vec2 tileOrigin(int cx, int cy) { + return vec2( + float(cx - cy - 1) * uCellSize.x * 0.5, + float(cx + cy + 2) * uCellSize.y * 0.5 - uTileSize.y + ); +} + +void main(void) { + vec2 worldPx = uVisibleStart + vRegion * uVisibleSize; + vec2 dWorldX = dFdx(worldPx); + vec2 dWorldY = dFdy(worldPx); + + vec2 halfCell = uCellSize * 0.5; + // the rightmost and the lowest cell whose image can reach the fragment + int uMax = int(floor(worldPx.x / halfCell.x)) + 1; + int sMax = int(floor((worldPx.y + uTileSize.y) / halfCell.y)) - 2; + int spanU = int(uOverflow.x + 0.5); + int spanS = int(uOverflow.y + 0.5); + + vec4 result; + bool found = false; + for (int j = 0; j < MAX_ROWS; j++) { + if (j >= spanS) break; + int s = sMax - j; + // the first u of this row's parity, then every other one + int u = uMax - ((uMax + s) & 1); + for (int i = 0; i < MAX_COLS; i++) { + if (uMax - u >= spanU) break; + if (tryRenderCell((s + u) / 2, (s - u) / 2, worldPx, dWorldX, dWorldY, result)) { + found = true; + break; + } + u -= 2; + } + if (found) break; + } + if (!found) discard; + fragColor = layerColor(result); +} diff --git a/packages/melonjs/src/video/webgl/shaders/orthogonal-tmxlayer.frag b/packages/melonjs/src/video/webgl/shaders/orthogonal-tmxlayer.frag index e81ed0f6fb..b7c7afd905 100644 --- a/packages/melonjs/src/video/webgl/shaders/orthogonal-tmxlayer.frag +++ b/packages/melonjs/src/video/webgl/shaders/orthogonal-tmxlayer.frag @@ -1,14 +1,5 @@ -#version 300 es - -// Fragment shader for the orthogonal TMX layer GPU renderer (WebGL2 / -// GLSL ES 3.00). -// -// Per fragment the shader: -// 1. recovers the world-pixel position from the host UV, -// 2. walks candidate cells (geometric cell + cells whose oversized, -// bottom-aligned tiles could reach this fragment), -// 3. fetches GIDs from the per-layer index texture, and -// 4. samples the tileset atlas at the correct sub-region. +// The orthogonal part of the TMX layer fragment shader: appended to +// `tmxlayer-common.frag`. // // Fast path: when the tileset has no oversized tiles (`uOverflow == (0, 0)`) // — the common case for grid-aligned maps — only the geometric cell can @@ -20,160 +11,17 @@ // Slow path: tiles drawing larger than the cell are bottom-aligned // vertically and left-aligned horizontally. Render order is "right-down": // later cells end up on top, so the candidate loop scans dy high→low, -// dx low→high and picks the FIRST match. -// -// Index texture encoding (`RGBA8`, one cell per texel): -// R = GID low byte -// G = GID high byte (combined: R | (G << 8) = 16-bit GID) -// B = flip mask (bit 0 = H, bit 1 = V, bit 2 = AD) -// A = unused -// -// Animation lookup (`RGBA8`, 1 row, `tileCount` texels wide): per local -// tile id, the CURRENT frame's local id, same R/G byte-pair encoding. -// -// Why `sampler2D` + float decode rather than `usampler2D`: the engine's -// multi-texture default shader declares `uSampler0..uSamplerN-1` as -// `sampler2D` — all of them are active for WebGL's draw-time validation. -// A `usampler2D`-backed `RGBA8UI` texture cached at any of those units -// (units 0..15 on a typical 16-unit fragment stage) would mismatch when -// the default shader next draws sprites, killing every quad with -// `GL_INVALID_OPERATION`. Staying on regular RGBA8 keeps the cache -// path coherent — the cost is one `floor(c * 255 + 0.5)` per fetch. -// -// `texelFetch` is still used (vs `texture()`) for byte-exact reads — -// it bypasses interpolation, so the integer byte values come out -// unmolested even on a normalized-float sampler. - -// The engine's `setPrecision` step injects precision declarations for -// float and int after the `#version` line, using whatever precision the -// renderer was configured with (`highPrecisionShader` setting on the -// Application). Individual shader files don't hardcode precision so the -// engine-wide preference applies. - -in vec2 vRegion; -in vec4 vColor; - -uniform sampler2D uSampler; // tileset atlas (RGBA) -uniform sampler2D uTileIndex; // per-layer GID index (RGBA8) -uniform sampler2D uAnimLookup; // per-tileset animation table (RGBA8) - -uniform vec2 uMapSize; -uniform vec2 uCellSize; -uniform vec2 uTileSize; -uniform vec2 uOverflow; -uniform vec2 uTilesetCols; -uniform vec2 uInvTilesetSize; -uniform vec4 uTilesetMargin; // (marginX, marginY, spacingX, spacingY) -uniform vec2 uGidRange; // (firstgid, lastgid) -uniform vec2 uVisibleStart; -uniform vec2 uVisibleSize; -uniform int uAnimSize; // number of entries in uAnimLookup, 0 if disabled -uniform float uOpacity; -uniform vec4 uTint; -uniform float uMipmaps; // 1 under the "linear-mipmap" filter, else 0 - -out vec4 fragColor; +// dx low→high and picks the FIRST match. `uOverflow` is how many cells a +// tile reaches past its own, across and up. const int MAX_OVERFLOW = 4; -// Try to render the tile at cell (cx, cy) for the current fragment. -// Returns true and writes the sampled color to `outColor` when the cell -// contains a visible, in-range tile whose pixel covers this fragment. -// Identical logic for both fast and slow paths — GLSL inlines this -// trivially so there's no function-call overhead at runtime. -// -// `dWorldX` / `dWorldY` are the world position's screen derivatives, taken -// in `main` where control flow is still uniform: the atlas coordinate jumps -// from one tile to the next, so its own derivatives would pick a tiny mip -// level along every tile edge. A texel of the atlas is a world pixel, so -// the world's derivatives are the atlas's. -bool tryRenderCell(int cx, int cy, vec2 worldPx, vec2 dWorldX, vec2 dWorldY, out vec4 outColor) { - int mapW = int(uMapSize.x); - int mapH = int(uMapSize.y); - if (cx < 0 || cx >= mapW || cy < 0 || cy >= mapH) { - return false; - } - - // `texelFetch` skips filtering — the 8-bit channel values come back - // as normalized floats, decoded to byte ints below - vec4 cellF = texelFetch(uTileIndex, ivec2(cx, cy), 0); - uvec4 cell = uvec4(cellF * 255.0 + 0.5); - int firstGid = int(uGidRange.x); - int gid = int(cell.r) | (int(cell.g) << 8); - if (gid < firstGid || gid > int(uGidRange.y)) { - return false; - } - - vec2 tileWorldOrigin = vec2( +// a tile is bottom-aligned on its cell, and left-aligned +vec2 tileOrigin(int cx, int cy) { + return vec2( float(cx) * uCellSize.x, (float(cy) + 1.0) * uCellSize.y - uTileSize.y ); - vec2 inTile = (worldPx - tileWorldOrigin) / uTileSize; - if (inTile.x < 0.0 || inTile.x >= 1.0 || inTile.y < 0.0 || inTile.y >= 1.0) { - return false; - } - - // flip mask + axis-swap trick: see TMX shader-path flip spec. - // AD performs a transpose; with AD set, H and V swap their effective - // axes (matches the legacy `buildFlipTransform`). - int flipMask = int(cell.b); - float flipH = float(flipMask & 1); - float flipV = float((flipMask >> 1) & 1); - float flipAD = float((flipMask >> 2) & 1); - inTile = mix(inTile, inTile.yx, flipAD); - float effH = mix(flipH, flipV, flipAD); - float effV = mix(flipV, flipH, flipAD); - inTile.x = mix(inTile.x, 1.0 - inTile.x, effH); - inTile.y = mix(inTile.y, 1.0 - inTile.y, effV); - - int localId = gid - firstGid; - - // animation: if the tileset has animated tiles, swap the local id for - // its current frame's id via the lookup texture (CPU updates the - // lookup in lockstep with `tileset.update(dt)`). - if (uAnimSize > 0) { - vec4 animF = texelFetch(uAnimLookup, ivec2(localId, 0), 0); - uvec4 animTexel = uvec4(animF * 255.0 + 0.5); - localId = int(animTexel.r) | (int(animTexel.g) << 8); - } - - float row = floor(float(localId) / uTilesetCols.x); - float col = float(localId) - row * uTilesetCols.x; - vec2 tileOriginPx = uTilesetMargin.xy - + vec2(col, row) * (uTileSize + uTilesetMargin.zw); - vec2 texelPx = tileOriginPx + inTile * uTileSize; - // keep the sample half a texel of the level it reads inside the tile, - // so filtering never blends in the next tile of the tileset, or the - // spacing around it, along the tile's edge: a seam between two tiles - // (never past the tile's centre). Without mipmaps that level is the - // full-size art; under them, the deepest level read is the next one up - // once the level is past a whole number, by more than a rounding error: - // drawn at its size, the derivatives are 1 give or take a few ulps, and - // level 0 it is. Sampled nearest, the sample stays in the same texel - float lod = ceil(log2(max(max(length(dWorldX), length(dWorldY)), 1.0)) - 0.01); - vec2 inset = min(vec2(0.5 * exp2(lod * uMipmaps)), uTileSize * 0.5); - texelPx = clamp(texelPx, tileOriginPx + inset, tileOriginPx + uTileSize - inset); - vec2 texelUV = texelPx * uInvTilesetSize; - - vec4 sampled = textureGrad( - uSampler, - texelUV, - dWorldX * uInvTilesetSize, - dWorldY * uInvTilesetSize - ); - if (sampled.a <= 0.0) { - return false; - } - outColor = sampled; - return true; -} - -// the layer's opacity and tint applied to a texel. The texel is -// premultiplied, as the blending expects: the opacity scales its color as -// well as its alpha. The tint colors it; its alpha is not an opacity, as on -// a sprite -vec4 layerColor(vec4 texel) { - return texel * uOpacity * vec4(uTint.rgb, 1.0); } void main(void) { diff --git a/packages/melonjs/src/video/webgl/shaders/tmxlayer-common.frag b/packages/melonjs/src/video/webgl/shaders/tmxlayer-common.frag new file mode 100644 index 0000000000..4458270c3e --- /dev/null +++ b/packages/melonjs/src/video/webgl/shaders/tmxlayer-common.frag @@ -0,0 +1,168 @@ +#version 300 es + +// Fragment shader for the TMX layer GPU renderers (WebGL2 / GLSL ES 3.00): +// the part every map orientation shares. An orientation's own file follows +// it in the program (`orthogonal-tmxlayer.frag`, `isometric-tmxlayer.frag`) +// and gives the two things that differ: where a cell's tile is drawn +// (`tileOrigin`), and which cells could cover a fragment, front to back +// (`main`). +// +// Per fragment, `main`: +// 1. recovers the fragment's position in the layer from the host UV, +// 2. walks the cells whose tile could cover it, the one drawn last first, +// 3. and for each, `tryRenderCell` fetches the GID from the per-layer +// index texture and samples the tileset atlas at the right sub-region. +// The first cell with a texel that is not transparent is the fragment. +// +// Index texture encoding (`RGBA8`, one cell per texel): +// R = GID low byte +// G = GID high byte (combined: R | (G << 8) = 16-bit GID) +// B = flip mask (bit 0 = H, bit 1 = V, bit 2 = AD) +// A = unused +// +// Animation lookup (`RGBA8`, 1 row, `tileCount` texels wide): per local +// tile id, the CURRENT frame's local id, same R/G byte-pair encoding. +// +// Why `sampler2D` + float decode rather than `usampler2D`: the engine's +// multi-texture default shader declares `uSampler0..uSamplerN-1` as +// `sampler2D` — all of them are active for WebGL's draw-time validation. +// A `usampler2D`-backed `RGBA8UI` texture cached at any of those units +// (units 0..15 on a typical 16-unit fragment stage) would mismatch when +// the default shader next draws sprites, killing every quad with +// `GL_INVALID_OPERATION`. Staying on regular RGBA8 keeps the cache +// path coherent — the cost is one `floor(c * 255 + 0.5)` per fetch. +// +// `texelFetch` is still used (vs `texture()`) for byte-exact reads — +// it bypasses interpolation, so the integer byte values come out +// unmolested even on a normalized-float sampler. + +// The engine's `setPrecision` step injects precision declarations for +// float and int after the `#version` line, using whatever precision the +// renderer was configured with (`highPrecisionShader` setting on the +// Application). Individual shader files don't hardcode precision so the +// engine-wide preference applies. + +in vec2 vRegion; +in vec4 vColor; + +uniform sampler2D uSampler; // tileset atlas (RGBA) +uniform sampler2D uTileIndex; // per-layer GID index (RGBA8) +uniform sampler2D uAnimLookup; // per-tileset animation table (RGBA8) + +uniform vec2 uMapSize; +uniform vec2 uCellSize; +uniform vec2 uTileSize; +uniform vec2 uOverflow; // how far a tile reaches past its cell (see each `main`) +uniform vec2 uTilesetCols; +uniform vec2 uInvTilesetSize; +uniform vec4 uTilesetMargin; // (marginX, marginY, spacingX, spacingY) +uniform vec2 uGidRange; // (firstgid, lastgid) +uniform vec2 uVisibleStart; +uniform vec2 uVisibleSize; +uniform int uAnimSize; // number of entries in uAnimLookup, 0 if disabled +uniform float uOpacity; +uniform vec4 uTint; +uniform float uMipmaps; // 1 under the "linear-mipmap" filter, else 0 + +out vec4 fragColor; + +// Where the tile of cell (cx, cy) is drawn from: the top left corner of its +// image, in the same pixels as `worldPx`. Defined per orientation. +vec2 tileOrigin(int cx, int cy); + +// Try to render the tile at cell (cx, cy) for the current fragment. +// Returns true and writes the sampled color to `outColor` when the cell +// contains a visible, in-range tile whose pixel covers this fragment. +// Identical logic for both fast and slow paths — GLSL inlines this +// trivially so there's no function-call overhead at runtime. +// +// `dWorldX` / `dWorldY` are the world position's screen derivatives, taken +// in `main` where control flow is still uniform: the atlas coordinate jumps +// from one tile to the next, so its own derivatives would pick a tiny mip +// level along every tile edge. A texel of the atlas is a world pixel, so +// the world's derivatives are the atlas's. +bool tryRenderCell(int cx, int cy, vec2 worldPx, vec2 dWorldX, vec2 dWorldY, out vec4 outColor) { + int mapW = int(uMapSize.x); + int mapH = int(uMapSize.y); + if (cx < 0 || cx >= mapW || cy < 0 || cy >= mapH) { + return false; + } + + // `texelFetch` skips filtering — the 8-bit channel values come back + // as normalized floats, decoded to byte ints below + vec4 cellF = texelFetch(uTileIndex, ivec2(cx, cy), 0); + uvec4 cell = uvec4(cellF * 255.0 + 0.5); + int firstGid = int(uGidRange.x); + int gid = int(cell.r) | (int(cell.g) << 8); + if (gid < firstGid || gid > int(uGidRange.y)) { + return false; + } + + vec2 inTile = (worldPx - tileOrigin(cx, cy)) / uTileSize; + if (inTile.x < 0.0 || inTile.x >= 1.0 || inTile.y < 0.0 || inTile.y >= 1.0) { + return false; + } + + // flip mask + axis-swap trick: see TMX shader-path flip spec. + // AD performs a transpose; with AD set, H and V swap their effective + // axes (matches the legacy `buildFlipTransform`). + int flipMask = int(cell.b); + float flipH = float(flipMask & 1); + float flipV = float((flipMask >> 1) & 1); + float flipAD = float((flipMask >> 2) & 1); + inTile = mix(inTile, inTile.yx, flipAD); + float effH = mix(flipH, flipV, flipAD); + float effV = mix(flipV, flipH, flipAD); + inTile.x = mix(inTile.x, 1.0 - inTile.x, effH); + inTile.y = mix(inTile.y, 1.0 - inTile.y, effV); + + int localId = gid - firstGid; + + // animation: if the tileset has animated tiles, swap the local id for + // its current frame's id via the lookup texture (CPU updates the + // lookup in lockstep with `tileset.update(dt)`). + if (uAnimSize > 0) { + vec4 animF = texelFetch(uAnimLookup, ivec2(localId, 0), 0); + uvec4 animTexel = uvec4(animF * 255.0 + 0.5); + localId = int(animTexel.r) | (int(animTexel.g) << 8); + } + + float row = floor(float(localId) / uTilesetCols.x); + float col = float(localId) - row * uTilesetCols.x; + vec2 tileOriginPx = uTilesetMargin.xy + + vec2(col, row) * (uTileSize + uTilesetMargin.zw); + vec2 texelPx = tileOriginPx + inTile * uTileSize; + // keep the sample half a texel of the level it reads inside the tile, + // so filtering never blends in the next tile of the tileset, or the + // spacing around it, along the tile's edge: a seam between two tiles + // (never past the tile's centre). Without mipmaps that level is the + // full-size art; under them, the deepest level read is the next one up + // once the level is past a whole number, by more than a rounding error: + // drawn at its size, the derivatives are 1 give or take a few ulps, and + // level 0 it is. Sampled nearest, the sample stays in the same texel + float lod = ceil(log2(max(max(length(dWorldX), length(dWorldY)), 1.0)) - 0.01); + vec2 inset = min(vec2(0.5 * exp2(lod * uMipmaps)), uTileSize * 0.5); + texelPx = clamp(texelPx, tileOriginPx + inset, tileOriginPx + uTileSize - inset); + vec2 texelUV = texelPx * uInvTilesetSize; + + vec4 sampled = textureGrad( + uSampler, + texelUV, + dWorldX * uInvTilesetSize, + dWorldY * uInvTilesetSize + ); + if (sampled.a <= 0.0) { + return false; + } + outColor = sampled; + return true; +} + +// the layer's opacity and tint applied to a texel. The texel is +// premultiplied, as the blending expects: the opacity scales its color as +// well as its alpha. The tint colors it; its alpha is not an opacity, as on +// a sprite +vec4 layerColor(vec4 texel) { + return texel * uOpacity * vec4(uTint.rgb, 1.0); +} + diff --git a/packages/melonjs/src/video/webgl/shaders/orthogonal-tmxlayer.vert b/packages/melonjs/src/video/webgl/shaders/tmxlayer.vert similarity index 100% rename from packages/melonjs/src/video/webgl/shaders/orthogonal-tmxlayer.vert rename to packages/melonjs/src/video/webgl/shaders/tmxlayer.vert diff --git a/packages/melonjs/src/video/webgl/webgl_renderer.js b/packages/melonjs/src/video/webgl/webgl_renderer.js index 2e19c26cb6..173d773aff 100644 --- a/packages/melonjs/src/video/webgl/webgl_renderer.js +++ b/packages/melonjs/src/video/webgl/webgl_renderer.js @@ -46,6 +46,7 @@ import PrimitiveBatcher from "./batchers/primitive_batcher"; import QuadBatcher from "./batchers/quad_batcher"; import { markContextLost } from "./buffer/deletable.js"; import { createLightUniformScratch, packLights } from "./lighting/pack.ts"; +import IsometricTMXLayerGPURenderer from "./renderers/tmxlayer/isometric.js"; import OrthogonalTMXLayerGPURenderer from "./renderers/tmxlayer/orthogonal.js"; import { WebGLTextureStore } from "./texture/store.js"; import { resolveMaxTextures } from "./utils/maxtextures.js"; @@ -71,6 +72,15 @@ import { GLSamplerCache } from "./utils/samplercache.js"; */ // reusable constants for 2D→3D matrix operations +/** + * the GPU tile layer renderer of each map orientation that has one + * @ignore + */ +const TMX_GPU_RENDERERS = { + orthogonal: OrthogonalTMXLayerGPURenderer, + isometric: IsometricTMXLayerGPURenderer, +}; + const _tempMatrix = new Matrix3d(); // pre-allocated matrices for blitEffect (avoids per-frame allocation) @@ -1341,7 +1351,9 @@ export default class WebGLRenderer extends Renderer { // drop every per-layer GPU tilemap texture — tile layers churn on // game reset and we'd otherwise leak a WebGLTexture per layer // across each level transition - this._orthogonalTMXGPURenderer?.reset(); + this._tmxGPURenderers?.forEach((gpu) => { + gpu?.reset(); + }); // initial viewport size this.setViewport(); @@ -1430,7 +1442,7 @@ export default class WebGLRenderer extends Renderer { * @ignore * @internal */ - this._orthogonalTMXGPURenderer = undefined; + this._tmxGPURenderers = undefined; } } @@ -1487,30 +1499,32 @@ export default class WebGLRenderer extends Renderer { * @internal */ _getTMXGPURendererFor(orientation) { - if (orientation === "orthogonal") { - if (this._orthogonalTMXGPURenderer === undefined) { - try { - this._orthogonalTMXGPURenderer = new OrthogonalTMXLayerGPURenderer( - this, - ); - } catch (err) { - // shader compile / link failure on this driver — disable - // the GPU path permanently for the rest of the session - // (the next `drawTileLayer` call falls through to the - // legacy renderer). Stored as `null` so subsequent - // attempts short-circuit without re-trying the failing - // compile every frame. - console.warn( - "melonJS: GPU tilemap shader failed to compile, falling back to legacy renderer", - err, - ); - this._orthogonalTMXGPURenderer = null; - } + const Class = TMX_GPU_RENDERERS[orientation]; + if (Class === undefined) { + // staggered, hexagonal, oblique: drawn by the legacy renderer + return undefined; + } + this._tmxGPURenderers ??= new Map(); + let gpu = this._tmxGPURenderers.get(orientation); + if (gpu === undefined) { + try { + gpu = new Class(this); + } catch (err) { + // shader compile / link failure on this driver — disable + // the GPU path permanently for the rest of the session + // (the next `drawTileLayer` call falls through to the + // legacy renderer). Stored as `null` so subsequent + // attempts short-circuit without re-trying the failing + // compile every frame. + console.warn( + "melonJS: GPU tilemap shader failed to compile, falling back to legacy renderer", + err, + ); + gpu = null; } - return this._orthogonalTMXGPURenderer || undefined; + this._tmxGPURenderers.set(orientation, gpu); } - // isometric / staggered / hexagonal: phase 2 - return undefined; + return gpu || undefined; } /** diff --git a/packages/melonjs/src/video/webgpu/renderers/tmxlayer/isometric.js b/packages/melonjs/src/video/webgpu/renderers/tmxlayer/isometric.js new file mode 100644 index 0000000000..232d8676f6 --- /dev/null +++ b/packages/melonjs/src/video/webgpu/renderers/tmxlayer/isometric.js @@ -0,0 +1,54 @@ +import { isometricRegion } from "../../../gpu/tmxlayer_region.js"; +import isometricWGSL from "../../shaders/tmxlayer-isometric.wgsl"; +import TMXLayerGPURenderer from "./tmxlayer.js"; + +/** + * additional imports for TypeScript + * @import { default as TMXLayer } from "../../../../level/tiled/TMXLayer.js"; + * @import { default as WebGPURenderer } from "../../webgpu_renderer.js"; + */ + +/** + * GPU-accelerated renderer for isometric TMX tile layers on the WebGPU + * backend: the shared {@link TMXLayerGPURenderer}, with an isometric grid's + * geometry. The quad covers the view, and the shader works in pixels. + * + * Isometric tiles overlap, and the shader keeps the one drawn last among + * those of ONE tileset: a layer takes this path only when all its tiles + * come from the same one (`layer._shaderTileset`, set by the layer when it + * is found eligible). + * @ignore + * @internal + */ +export default class IsometricTMXLayerGPURenderer extends TMXLayerGPURenderer { + /** + * @param {WebGPURenderer} renderer - the WebGPU renderer instance + */ + constructor(renderer) { + super(renderer, isometricWGSL); + this.tilesets = []; + } + + /** + * @ignore + * @internal + */ + region(layer, rect, tileset, out) { + return isometricRegion(layer, rect, tileset, out); + } + + /** + * The one tileset an isometric layer on this path draws with. + * @param {TMXLayer} layer - the layer + * @returns {object[]} that tileset, or none for an empty layer + * @ignore + * @internal + */ + tilesetsOf(layer) { + this.tilesets.length = 0; + if (layer._shaderTileset) { + this.tilesets.push(layer._shaderTileset); + } + return this.tilesets; + } +} diff --git a/packages/melonjs/src/video/webgpu/renderers/tmxlayer/orthogonal.js b/packages/melonjs/src/video/webgpu/renderers/tmxlayer/orthogonal.js index bd861bc1ec..3131648d73 100644 --- a/packages/melonjs/src/video/webgpu/renderers/tmxlayer/orthogonal.js +++ b/packages/melonjs/src/video/webgpu/renderers/tmxlayer/orthogonal.js @@ -1,462 +1,33 @@ -import VertexArrayBuffer from "../../../buffer/vertex.js"; -import { transformQuadCorners } from "../../../gpu/quadcorners.ts"; -import tmxLayerWGSL from "../../shaders/tmxlayer.wgsl"; +import { orthogonalRegion } from "../../../gpu/tmxlayer_region.js"; +import orthogonalWGSL from "../../shaders/tmxlayer-orthogonal.wgsl"; +import TMXLayerGPURenderer from "./tmxlayer.js"; /** * additional imports for TypeScript - * @import { default as TMXLayer } from "../../../../level/tiled/TMXLayer.js"; * @import { default as WebGPURenderer } from "../../webgpu_renderer.js"; */ -/** - * byte size of the TMXUniforms block (see tmxlayer.wgsl): ten vec2f (80) - * interleaved with one vec4f at a 16-aligned offset, two f32, the vec4f - * tint (ending at 112) and the mipmap flag, rounded up to the block's - * 16-byte alignment → 128 bytes - * @ignore - * @internal - */ -const TMX_UNIFORM_SIZE = 128; - /** * GPU-accelerated renderer for orthogonal TMX tile layers on the WebGPU - * backend — the WGSL realization of the WebGL shader tile path: the - * visible region draws as ONE quad per tileset, with the fragment shader - * sampling a per-layer GID index texture and the tileset atlas. - * - * Structure mirrors the WebGL twin; the mechanisms are the backend's: - * - the GID index / animation lookup are renderer-owned `rgba8unorm` - * textures written with `queue.writeTexture` (byte-exact `textureLoad` - * reads, no sampler needed) — re-uploaded only when `layer.dataVersion` - * moves or an animation frame advances - * - the per-draw uniforms snapshot into the effect uniform arena with a - * dynamic offset (each tileset pass gets its own region, per the - * queue-write-before-draws ordering) - * - the tileset atlas rides the standard texture-store material path - * - pipelines flow through the registered `tmxlayer.wgsl` family, keyed - * on the frame's blend/stencil state like every other draw + * backend: the shared {@link TMXLayerGPURenderer}, with an orthogonal grid's + * geometry. The quad covers the cells in view, and the shader works in + * cells. * @ignore * @internal */ -export default class OrthogonalTMXLayerGPURenderer { +export default class OrthogonalTMXLayerGPURenderer extends TMXLayerGPURenderer { /** * @param {WebGPURenderer} renderer - the WebGPU renderer instance */ constructor(renderer) { - this.renderer = renderer; - const cache = renderer.pipelineCache; - - // group-3 shape: the uniform block + the two lookup textures - this.tmxLayout = cache.getEffectLayout("tmx", [ - { - binding: 0, - visibility: GPUShaderStage.FRAGMENT, - buffer: { - type: "uniform", - hasDynamicOffset: true, - minBindingSize: TMX_UNIFORM_SIZE, - }, - }, - { binding: 1, visibility: GPUShaderStage.FRAGMENT, texture: {} }, - { binding: 2, visibility: GPUShaderStage.FRAGMENT, texture: {} }, - ]); - this.key = cache.registerShader(tmxLayerWGSL, { - bindGroupLayouts: [ - cache.frameLayout, - cache.materialLayout, - cache.emptyLayout, - this.tmxLayout, - ], - vertexLayoutKey: "quad", - label: "melonJS tmx layer shader", - }); - // the pipeline cache this state was built against — a device loss - // rebuilds the cache, and the renderer drops this instance with it - this.epoch = cache.epoch; - - /** - * per-layer GID index texture: layer → {texture, view, version} - * @type {Map} - */ - this.resources = new Map(); - /** - * per-tileset animation lookup: tileset → {texture, view, data, tileCount} - * @type {Map} - */ - this.animLookups = new Map(); - /** - * per-(layer, tileset) cached group-3 bind group, keyed on the - * uniform arena page it binds - * @type {Map>} - */ - this.bindGroups = new Map(); - - // CPU staging for the uniform block; the quad's vertices are staged - // in the quad batcher's own layout, sized on first draw - this.uniformScratch = new Float32Array(TMX_UNIFORM_SIZE / 4); - /** - * @type {VertexArrayBuffer|undefined} - */ - this.vertexScratch = undefined; + super(renderer, orthogonalWGSL); } /** - * Retire every lookup texture and empty the local maps — called from - * `WebGPURenderer.reset()` (GAME_RESET) so each level starts clean. * @ignore * @internal */ - reset() { - for (const resource of this.resources.values()) { - this.renderer.retireTexture(resource.texture); - } - for (const entry of this.animLookups.values()) { - this.renderer.retireTexture(entry.texture); - } - this.resources.clear(); - this.animLookups.clear(); - this.bindGroups.clear(); - } - - /** - * Get-or-create the per-layer GID index texture, re-uploading when the - * layer's data version moved (`setTile`/`clearTile` mutations). - * @param {TMXLayer} layer - the layer - * @returns {{texture: GPUTexture, view: GPUTextureView, version: number}} - * @ignore - * @internal - */ - getResource(layer) { - const device = this.renderer.device; - let resource = this.resources.get(layer); - if (resource === undefined) { - const texture = device.createTexture({ - label: "melonJS tmx index", - size: [layer.cols, layer.rows], - format: "rgba8unorm", - usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST, - }); - resource = { texture, view: texture.createView(), version: -1 }; - this.resources.set(layer, resource); - } - if (resource.version !== layer.dataVersion) { - // reinterpret the layer's Uint16Array payload as RGBA bytes - // (zero-copy view; little-endian = every browser) - device.queue.writeTexture( - { texture: resource.texture }, - new Uint8Array(layer.layerData.buffer), - { bytesPerRow: layer.cols * 4, rowsPerImage: layer.rows }, - [layer.cols, layer.rows], - ); - resource.version = layer.dataVersion; - } - return resource; - } - - /** - * Get-or-update the per-tileset animation lookup (undefined for - * tilesets without animated tiles). Texel `localId` encodes the - * CURRENT frame's local id as (R = lo byte, G = hi byte). - * @param {object} tileset - the tileset - * @param {number} tileCount - atlas grid tile count - * @returns {object|undefined} the lookup entry - * @ignore - * @internal - */ - getOrUpdateAnimLookup(tileset, tileCount) { - if (!tileset.isAnimated || tileset.animations.size === 0) { - return undefined; - } - const device = this.renderer.device; - let entry = this.animLookups.get(tileset); - if (entry === undefined) { - // identity mapping (localId → localId); animated entries get - // overwritten below - const data = new Uint8Array(tileCount * 4); - for (let id = 0; id < tileCount; id++) { - data[id * 4 + 0] = id & 0xff; - data[id * 4 + 1] = (id >> 8) & 0xff; - } - const texture = device.createTexture({ - label: "melonJS tmx anim lookup", - size: [tileCount, 1], - format: "rgba8unorm", - usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST, - }); - entry = { - texture, - view: texture.createView(), - data, - tileCount, - uploaded: false, - }; - this.animLookups.set(tileset, entry); - } - // rewrite current-frame ids; upload only when a texel changed - // (tileset.update advanced a frame). At most one upload per frame — - // queue writes execute before every recorded draw, and animation - // state only moves in the update phase, so the frame stays coherent. - const data = entry.data; - let dirty = !entry.uploaded; - for (const [localId, anim] of tileset.animations) { - const off = localId * 4; - const cur = anim.cur.tileid; - const lo = cur & 0xff; - const hi = (cur >> 8) & 0xff; - if (data[off] !== lo || data[off + 1] !== hi) { - data[off] = lo; - data[off + 1] = hi; - dirty = true; - } - } - if (dirty) { - device.queue.writeTexture( - { texture: entry.texture }, - data, - { bytesPerRow: entry.tileCount * 4, rowsPerImage: 1 }, - [entry.tileCount, 1], - ); - entry.uploaded = true; - } - return entry; - } - - /** - * Draw an orthogonal TMX layer through the shader path. - * @param {TMXLayer} layer - the layer to draw - * @param {object} rect - the visible viewport rect (world coords) - */ - draw(layer, rect) { - const renderer = this.renderer; - const tileWidth = layer.tilewidth; - const tileHeight = layer.tileheight; - const cols = layer.cols; - const rows = layer.rows; - - // visible region in tile-coord space - const startTileX = Math.max(0, Math.floor(rect.pos.x / tileWidth)); - const startTileY = Math.max(0, Math.floor(rect.pos.y / tileHeight)); - const endTileX = Math.min( - cols, - Math.ceil((rect.pos.x + rect.width) / tileWidth), - ); - const endTileY = Math.min( - rows, - Math.ceil((rect.pos.y + rect.height) / tileHeight), - ); - if (endTileX <= startTileX || endTileY <= startTileY) { - return; - } - - const worldX = startTileX * tileWidth; - const worldY = startTileY * tileHeight; - const worldW = (endTileX - startTileX) * tileWidth; - const worldH = (endTileY - startTileY) * tileHeight; - - // drain pending sprite vertices under their own pipeline, then use - // the quad batcher's frozen machinery (staging layout, index buffer) - const batcher = renderer.setBatcher("quad"); - batcher.flush(); - const pass = renderer.ensurePass(); - const device = renderer.device; - - const resource = this.getResource(layer); - - // the transformed quad, shared by every tileset pass, in the quad - // batcher's layout (its pipelines ride that layout). The shader keeps - // to its own tiles, so the quad carries no frame - // on whole pixels unless `subPixel` is set, as a sprite is: the tiles - // move with the quad (see Renderer#_pixelSnapBegin) - const snapped = renderer._pixelSnapBegin(worldX, worldY, worldW, worldH); - const corners = transformQuadCorners( - renderer.currentTransform, - worldX, - worldY, - worldW, - worldH, - renderer.currentDepth, - ); - renderer._pixelSnapEnd(snapped); - if (this.vertexScratch?.vertexSize !== batcher.vertexSize) { - this.vertexScratch = new VertexArrayBuffer(batcher.vertexSize, 4); - } - const vertices = this.vertexScratch; - vertices.clear(); - vertices.pushSpriteQuad( - corners[0], - corners[1], - corners[2], - corners[3], - 0, - 0, - 1, - 1, - 0xffffffff, - 0, - false, - ); - const byteLength = 4 * batcher.stride; - const vertexRegion = renderer.vertexArena.alloc(byteLength); - device.queue.writeBuffer( - vertexRegion.buffer, - vertexRegion.offset, - vertices.toUint8(), - 0, - byteLength, - ); - - // layer-level uniform values (identical for every tileset pass) - const scratch = this.uniformScratch; - scratch[0] = cols; - scratch[1] = rows; - scratch[2] = tileWidth; - scratch[3] = tileHeight; - scratch[18] = startTileX; - scratch[19] = startTileY; - scratch[20] = endTileX - startTileX; - scratch[21] = endTileY - startTileY; - // the layer's opacity, and the fade of everything it is drawn in: - // set on the renderer by the layer's preDraw - scratch[22] = renderer.getGlobalAlpha(); - const tint = layer.tint ? layer.tint.toArray() : null; - scratch[24] = tint ? tint[0] : 1; - scratch[25] = tint ? tint[1] : 1; - scratch[26] = tint ? tint[2] : 1; - scratch[27] = tint ? tint[3] : 1; - - const pipeline = renderer.pipelineCache.get( - this.key, - "triangle-list", - renderer.currentBlendMode, - renderer.premultipliedAlpha, - renderer.stencilMode, - ); - if (pipeline !== renderer.currentPipeline) { - pass.setPipeline(pipeline); - renderer.currentPipeline = pipeline; - } - const frame = renderer.currentFrameBinding; - pass.setBindGroup(0, frame.bindGroup, [frame.dynamicOffset]); - pass.setBindGroup(2, renderer.pipelineCache.emptyBindGroup); - pass.setVertexBuffer( - 0, - vertexRegion.buffer, - vertexRegion.offset, - byteLength, - ); - pass.setIndexBuffer(batcher.indexBuffer, "uint32"); - - // one pass per tileset — the GID-range guard hides other tilesets - const tilesets = layer.tilesets.tilesets; - let layerGroups = this.bindGroups.get(layer); - if (layerGroups === undefined) { - layerGroups = new Map(); - this.bindGroups.set(layer, layerGroups); - } - for (let i = 0; i < tilesets.length; i++) { - const tileset = tilesets[i]; - // eligibility should have excluded these — guard defensively - if (tileset.isCollection || tileset.image === undefined) { - continue; - } - - const tsW = tileset.tilewidth; - const tsH = tileset.tileheight; - const margin = tileset.margin; - const spacing = tileset.spacing; - const atlasW = tileset.image.width; - const atlasH = tileset.image.height; - const atlasCols = Math.max( - 1, - Math.floor((atlasW - margin * 2 + spacing) / (tsW + spacing)), - ); - const atlasRows = Math.max( - 1, - Math.floor((atlasH - margin * 2 + spacing) / (tsH + spacing)), - ); - - const animEntry = this.getOrUpdateAnimLookup( - tileset, - atlasCols * atlasRows, - ); - // every declared binding needs a view — reuse the index texture - // as the filler (never read: uAnimSize stays 0) - const animView = animEntry ? animEntry.view : resource.view; - - // per-tileset uniform values + snapshot into the arena - scratch[4] = tsW; - scratch[5] = tsH; - scratch[6] = Math.max(0, Math.ceil(tsW / tileWidth) - 1); - scratch[7] = Math.max(0, Math.ceil(tsH / tileHeight) - 1); - scratch[8] = atlasCols; - scratch[9] = atlasRows; - scratch[10] = 1 / atlasW; - scratch[11] = 1 / atlasH; - scratch[12] = margin; - scratch[13] = margin; - scratch[14] = spacing; - scratch[15] = spacing; - scratch[16] = tileset.firstgid; - scratch[17] = tileset.lastgid; - scratch[23] = animEntry ? animEntry.tileCount : 0; - // the "linear-mipmap" filter, on a linear tileset: the binding - // below asks the store for a chain, and the shader keeps each - // sample clear of the neighbouring tiles at the level it reads - const filter = - typeof tileset.texture.filter === "string" - ? tileset.texture.filter - : renderer.getDefaultTextureFilter(); - const mipmaps = - filter === "linear" && renderer.wantsMipmaps(tileset.texture); - scratch[28] = mipmaps ? 1 : 0; - const region = renderer.effectUniformArena.alloc( - TMX_UNIFORM_SIZE, - device.limits?.minUniformBufferOffsetAlignment ?? 256, - ); - device.queue.writeBuffer( - region.buffer, - region.offset, - scratch.buffer, - 0, - TMX_UNIFORM_SIZE, - ); - - // group-3 bind group, cached per (layer, tileset) while the - // arena page and lookup views stay the same - let cached = layerGroups.get(tileset); - if ( - cached === undefined || - cached.pageLabel !== region.buffer.label || - cached.animView !== animView - ) { - cached = { - pageLabel: region.buffer.label, - animView, - bindGroup: device.createBindGroup({ - label: "melonJS tmx binding", - layout: this.tmxLayout, - entries: [ - { - binding: 0, - resource: { - buffer: region.buffer, - size: TMX_UNIFORM_SIZE, - }, - }, - { binding: 1, resource: resource.view }, - { binding: 2, resource: animView }, - ], - }), - }; - layerGroups.set(tileset, cached); - } - - pass.setBindGroup( - 1, - renderer.textureStore.getBinding(tileset.texture, { mipmaps }), - ); - pass.setBindGroup(3, cached.bindGroup, [region.offset]); - pass.drawIndexed(6); - } + region(layer, rect, tileset, out) { + return orthogonalRegion(layer, rect, tileset, out); } } diff --git a/packages/melonjs/src/video/webgpu/renderers/tmxlayer/tmxlayer.js b/packages/melonjs/src/video/webgpu/renderers/tmxlayer/tmxlayer.js new file mode 100644 index 0000000000..9ca29e901a --- /dev/null +++ b/packages/melonjs/src/video/webgpu/renderers/tmxlayer/tmxlayer.js @@ -0,0 +1,515 @@ +import VertexArrayBuffer from "../../../buffer/vertex.js"; +import { transformQuadCorners } from "../../../gpu/quadcorners.ts"; +import { createRegion } from "../../../gpu/tmxlayer_region.js"; +import tmxLayerCommonWGSL from "../../shaders/tmxlayer-common.wgsl"; + +/** + * additional imports for TypeScript + * @import { default as TMXLayer } from "../../../../level/tiled/TMXLayer.js"; + * @import { default as WebGPURenderer } from "../../webgpu_renderer.js"; + */ + +/** + * byte size of the TMXUniforms block (see tmxlayer-common.wgsl): ten vec2f (80) + * interleaved with one vec4f at a 16-aligned offset, two f32, the vec4f + * tint (ending at 112) and the mipmap flag, rounded up to the block's + * 16-byte alignment → 128 bytes + * @ignore + * @internal + */ +const TMX_UNIFORM_SIZE = 128; + +/** + * GPU-accelerated renderer for TMX tile layers on the WebGPU backend, the + * part every map orientation shares — the WGSL realization of the WebGL + * shader tile path: the visible region draws as ONE quad per tileset, with + * the fragment shader sampling a per-layer GID index texture and the + * tileset atlas. + * + * An orientation's renderer extends this one with the two things that + * differ: its part of the shader (where a cell's tile is, and which cells + * can cover a fragment), and {@link TMXLayerGPURenderer#region}, the part of + * the layer a view shows. + * + * Structure mirrors the WebGL twin; the mechanisms are the backend's: + * - the GID index / animation lookup are renderer-owned `rgba8unorm` + * textures written with `queue.writeTexture` (byte-exact `textureLoad` + * reads, no sampler needed) — re-uploaded only when `layer.dataVersion` + * moves or an animation frame advances + * - the per-draw uniforms snapshot into the effect uniform arena with a + * dynamic offset (each tileset pass gets its own region, per the + * queue-write-before-draws ordering) + * - the tileset atlas rides the standard texture-store material path + * - pipelines flow through the registered shader family (the shared + * module text plus the orientation's), keyed on the frame's blend/stencil + * state like every other draw + * @ignore + * @internal + */ +export default class TMXLayerGPURenderer { + /** + * @param {WebGPURenderer} renderer - the WebGPU renderer instance + * @param {string} wgsl - the orientation's part of the shader module, + * appended to the shared one + */ + constructor(renderer, wgsl) { + this.renderer = renderer; + const cache = renderer.pipelineCache; + + // group-3 shape: the uniform block + the two lookup textures + this.tmxLayout = cache.getEffectLayout("tmx", [ + { + binding: 0, + visibility: GPUShaderStage.FRAGMENT, + buffer: { + type: "uniform", + hasDynamicOffset: true, + minBindingSize: TMX_UNIFORM_SIZE, + }, + }, + { binding: 1, visibility: GPUShaderStage.FRAGMENT, texture: {} }, + { binding: 2, visibility: GPUShaderStage.FRAGMENT, texture: {} }, + ]); + this.key = cache.registerShader(`${tmxLayerCommonWGSL}\n${wgsl}`, { + bindGroupLayouts: [ + cache.frameLayout, + cache.materialLayout, + cache.emptyLayout, + this.tmxLayout, + ], + vertexLayoutKey: "quad", + label: "melonJS tmx layer shader", + }); + // the pipeline cache this state was built against — a device loss + // rebuilds the cache, and the renderer drops this instance with it + this.epoch = cache.epoch; + + /** + * per-layer GID index texture: layer → {texture, view, version} + * @type {Map} + */ + this.resources = new Map(); + /** + * per-tileset animation lookup: tileset → {texture, view, data, tileCount} + * @type {Map} + */ + this.animLookups = new Map(); + /** + * per-(layer, tileset) cached group-3 bind group, keyed on the + * uniform arena page it binds + * @type {Map>} + */ + this.bindGroups = new Map(); + + // CPU staging for the uniform block; the quad's vertices are staged + // in the quad batcher's own layout, sized on first draw + this.uniformScratch = new Float32Array(TMX_UNIFORM_SIZE / 4); + /** + * @type {VertexArrayBuffer|undefined} + */ + this.vertexScratch = undefined; + /** + * what {@link TMXLayerGPURenderer#region} fills + * @ignore + * @internal + */ + this.regionScratch = createRegion(); + } + + /** + * The part of a layer a view shows, for the tiles of one tileset (see + * `gpu/tmxlayer_region.js`). The quad it gives must be the same for + * every tileset of a layer: it is written once, for the first one. + * @param {TMXLayer} layer - the layer + * @param {object} rect - the visible viewport rect (world coords) + * @param {object} tileset - the tileset whose tiles are drawn + * @param {object} out - the region to fill + * @returns {boolean} false when the view shows nothing of the layer + * @abstract + * @ignore + * @internal + */ + // eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars + region(layer, rect, tileset, out) { + return false; + } + + /** + * The tilesets a layer is drawn with, one pass each. + * @param {TMXLayer} layer - the layer + * @returns {object[]} the tilesets + * @ignore + * @internal + */ + tilesetsOf(layer) { + return layer.tilesets.tilesets; + } + + /** + * Retire every lookup texture and empty the local maps — called from + * `WebGPURenderer.reset()` (GAME_RESET) so each level starts clean. + * @ignore + * @internal + */ + reset() { + for (const resource of this.resources.values()) { + this.renderer.retireTexture(resource.texture); + } + for (const entry of this.animLookups.values()) { + this.renderer.retireTexture(entry.texture); + } + this.resources.clear(); + this.animLookups.clear(); + this.bindGroups.clear(); + } + + /** + * Get-or-create the per-layer GID index texture, re-uploading when the + * layer's data version moved (`setTile`/`clearTile` mutations). + * @param {TMXLayer} layer - the layer + * @returns {{texture: GPUTexture, view: GPUTextureView, version: number}} + * @ignore + * @internal + */ + getResource(layer) { + const device = this.renderer.device; + let resource = this.resources.get(layer); + if (resource === undefined) { + const texture = device.createTexture({ + label: "melonJS tmx index", + size: [layer.cols, layer.rows], + format: "rgba8unorm", + usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST, + }); + resource = { texture, view: texture.createView(), version: -1 }; + this.resources.set(layer, resource); + } + if (resource.version !== layer.dataVersion) { + // reinterpret the layer's Uint16Array payload as RGBA bytes + // (zero-copy view; little-endian = every browser) + device.queue.writeTexture( + { texture: resource.texture }, + new Uint8Array(layer.layerData.buffer), + { bytesPerRow: layer.cols * 4, rowsPerImage: layer.rows }, + [layer.cols, layer.rows], + ); + resource.version = layer.dataVersion; + } + return resource; + } + + /** + * Get-or-update the per-tileset animation lookup (undefined for + * tilesets without animated tiles). Texel `localId` encodes the + * CURRENT frame's local id as (R = lo byte, G = hi byte). + * @param {object} tileset - the tileset + * @param {number} tileCount - atlas grid tile count + * @returns {object|undefined} the lookup entry + * @ignore + * @internal + */ + getOrUpdateAnimLookup(tileset, tileCount) { + if (!tileset.isAnimated || tileset.animations.size === 0) { + return undefined; + } + const device = this.renderer.device; + let entry = this.animLookups.get(tileset); + if (entry === undefined) { + // identity mapping (localId → localId); animated entries get + // overwritten below + const data = new Uint8Array(tileCount * 4); + for (let id = 0; id < tileCount; id++) { + data[id * 4 + 0] = id & 0xff; + data[id * 4 + 1] = (id >> 8) & 0xff; + } + const texture = device.createTexture({ + label: "melonJS tmx anim lookup", + size: [tileCount, 1], + format: "rgba8unorm", + usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST, + }); + entry = { + texture, + view: texture.createView(), + data, + tileCount, + uploaded: false, + }; + this.animLookups.set(tileset, entry); + } + // rewrite current-frame ids; upload only when a texel changed + // (tileset.update advanced a frame). At most one upload per frame — + // queue writes execute before every recorded draw, and animation + // state only moves in the update phase, so the frame stays coherent. + const data = entry.data; + let dirty = !entry.uploaded; + for (const [localId, anim] of tileset.animations) { + const off = localId * 4; + const cur = anim.cur.tileid; + const lo = cur & 0xff; + const hi = (cur >> 8) & 0xff; + if (data[off] !== lo || data[off + 1] !== hi) { + data[off] = lo; + data[off + 1] = hi; + dirty = true; + } + } + if (dirty) { + device.queue.writeTexture( + { texture: entry.texture }, + data, + { bytesPerRow: entry.tileCount * 4, rowsPerImage: 1 }, + [entry.tileCount, 1], + ); + entry.uploaded = true; + } + return entry; + } + + /** + * Start a layer's draw, for the first tileset the view shows something + * of: the quad (shared by every tileset pass), the layer's uniform + * values, the pipeline and the bindings that do not change per tileset. + * @param {TMXLayer} layer - the layer + * @param {object} region - the region of that first tileset + * @returns {object} what the tileset passes need: the pass, the index + * texture's resource and the layer's bind group cache + * @ignore + * @internal + */ + begin(layer, region) { + const renderer = this.renderer; + + // drain pending sprite vertices under their own pipeline, then use + // the quad batcher's frozen machinery (staging layout, index buffer) + const batcher = renderer.setBatcher("quad"); + batcher.flush(); + const pass = renderer.ensurePass(); + const device = renderer.device; + + const resource = this.getResource(layer); + + // the transformed quad, shared by every tileset pass, in the quad + // batcher's layout (its pipelines ride that layout). The shader keeps + // to its own tiles, so the quad carries no frame + // on whole pixels unless `subPixel` is set, as a sprite is: the tiles + // move with the quad (see Renderer#_pixelSnapBegin) + const snapped = renderer._pixelSnapBegin( + region.x, + region.y, + region.width, + region.height, + ); + const corners = transformQuadCorners( + renderer.currentTransform, + region.x, + region.y, + region.width, + region.height, + renderer.currentDepth, + ); + renderer._pixelSnapEnd(snapped); + if (this.vertexScratch?.vertexSize !== batcher.vertexSize) { + this.vertexScratch = new VertexArrayBuffer(batcher.vertexSize, 4); + } + const vertices = this.vertexScratch; + vertices.clear(); + vertices.pushSpriteQuad( + corners[0], + corners[1], + corners[2], + corners[3], + 0, + 0, + 1, + 1, + 0xffffffff, + 0, + false, + ); + const byteLength = 4 * batcher.stride; + const vertexRegion = renderer.vertexArena.alloc(byteLength); + device.queue.writeBuffer( + vertexRegion.buffer, + vertexRegion.offset, + vertices.toUint8(), + 0, + byteLength, + ); + + // layer-level uniform values (identical for every tileset pass) + const scratch = this.uniformScratch; + scratch[0] = layer.cols; + scratch[1] = layer.rows; + scratch[2] = layer.tilewidth; + scratch[3] = layer.tileheight; + // the layer's opacity, and the fade of everything it is drawn in: + // set on the renderer by the layer's preDraw + scratch[22] = renderer.getGlobalAlpha(); + const tint = layer.tint ? layer.tint.toArray() : null; + scratch[24] = tint ? tint[0] : 1; + scratch[25] = tint ? tint[1] : 1; + scratch[26] = tint ? tint[2] : 1; + scratch[27] = tint ? tint[3] : 1; + + const pipeline = renderer.pipelineCache.get( + this.key, + "triangle-list", + renderer.currentBlendMode, + renderer.premultipliedAlpha, + renderer.stencilMode, + ); + if (pipeline !== renderer.currentPipeline) { + pass.setPipeline(pipeline); + renderer.currentPipeline = pipeline; + } + const frame = renderer.currentFrameBinding; + pass.setBindGroup(0, frame.bindGroup, [frame.dynamicOffset]); + pass.setBindGroup(2, renderer.pipelineCache.emptyBindGroup); + pass.setVertexBuffer( + 0, + vertexRegion.buffer, + vertexRegion.offset, + byteLength, + ); + pass.setIndexBuffer(batcher.indexBuffer, "uint32"); + + let layerGroups = this.bindGroups.get(layer); + if (layerGroups === undefined) { + layerGroups = new Map(); + this.bindGroups.set(layer, layerGroups); + } + return { pass, resource, layerGroups }; + } + + /** + * Draw a TMX layer through the shader path. + * @param {TMXLayer} layer - the layer to draw + * @param {object} rect - the visible viewport rect (world coords) + */ + draw(layer, rect) { + const renderer = this.renderer; + const device = renderer.device; + const scratch = this.uniformScratch; + const region = this.regionScratch; + let begun; + + // one pass per tileset — the GID-range guard hides other tilesets + const tilesets = this.tilesetsOf(layer); + for (let i = 0; i < tilesets.length; i++) { + const tileset = tilesets[i]; + // eligibility should have excluded these — guard defensively + if (tileset.isCollection || tileset.image === undefined) { + continue; + } + // the view shows nothing of this tileset's tiles + if (!this.region(layer, rect, tileset, region)) { + continue; + } + begun ??= this.begin(layer, region); + const { pass, resource, layerGroups } = begun; + + const tsW = tileset.tilewidth; + const tsH = tileset.tileheight; + const margin = tileset.margin; + const spacing = tileset.spacing; + const atlasW = tileset.image.width; + const atlasH = tileset.image.height; + const atlasCols = Math.max( + 1, + Math.floor((atlasW - margin * 2 + spacing) / (tsW + spacing)), + ); + const atlasRows = Math.max( + 1, + Math.floor((atlasH - margin * 2 + spacing) / (tsH + spacing)), + ); + + const animEntry = this.getOrUpdateAnimLookup( + tileset, + atlasCols * atlasRows, + ); + // every declared binding needs a view — reuse the index texture + // as the filler (never read: uAnimSize stays 0) + const animView = animEntry ? animEntry.view : resource.view; + + // per-tileset uniform values + snapshot into the arena + scratch[4] = tsW; + scratch[5] = tsH; + scratch[6] = region.overflowX; + scratch[7] = region.overflowY; + scratch[8] = atlasCols; + scratch[9] = atlasRows; + scratch[10] = 1 / atlasW; + scratch[11] = 1 / atlasH; + scratch[12] = margin; + scratch[13] = margin; + scratch[14] = spacing; + scratch[15] = spacing; + scratch[16] = tileset.firstgid; + scratch[17] = tileset.lastgid; + scratch[18] = region.startX; + scratch[19] = region.startY; + scratch[20] = region.sizeX; + scratch[21] = region.sizeY; + scratch[23] = animEntry ? animEntry.tileCount : 0; + // the "linear-mipmap" filter, on a linear tileset: the binding + // below asks the store for a chain, and the shader keeps each + // sample clear of the neighbouring tiles at the level it reads + const filter = + typeof tileset.texture.filter === "string" + ? tileset.texture.filter + : renderer.getDefaultTextureFilter(); + const mipmaps = + filter === "linear" && renderer.wantsMipmaps(tileset.texture); + scratch[28] = mipmaps ? 1 : 0; + const uniforms = renderer.effectUniformArena.alloc( + TMX_UNIFORM_SIZE, + device.limits?.minUniformBufferOffsetAlignment ?? 256, + ); + device.queue.writeBuffer( + uniforms.buffer, + uniforms.offset, + scratch.buffer, + 0, + TMX_UNIFORM_SIZE, + ); + + // group-3 bind group, cached per (layer, tileset) while the + // arena page and lookup views stay the same + let cached = layerGroups.get(tileset); + if ( + cached === undefined || + cached.pageLabel !== uniforms.buffer.label || + cached.animView !== animView + ) { + cached = { + pageLabel: uniforms.buffer.label, + animView, + bindGroup: device.createBindGroup({ + label: "melonJS tmx binding", + layout: this.tmxLayout, + entries: [ + { + binding: 0, + resource: { + buffer: uniforms.buffer, + size: TMX_UNIFORM_SIZE, + }, + }, + { binding: 1, resource: resource.view }, + { binding: 2, resource: animView }, + ], + }), + }; + layerGroups.set(tileset, cached); + } + + pass.setBindGroup( + 1, + renderer.textureStore.getBinding(tileset.texture, { mipmaps }), + ); + pass.setBindGroup(3, cached.bindGroup, [uniforms.offset]); + pass.drawIndexed(6); + } + } +} diff --git a/packages/melonjs/src/video/webgpu/shaders/tmxlayer.wgsl b/packages/melonjs/src/video/webgpu/shaders/tmxlayer-common.wgsl similarity index 73% rename from packages/melonjs/src/video/webgpu/shaders/tmxlayer.wgsl rename to packages/melonjs/src/video/webgpu/shaders/tmxlayer-common.wgsl index d892c921bb..fda81795e1 100644 --- a/packages/melonjs/src/video/webgpu/shaders/tmxlayer.wgsl +++ b/packages/melonjs/src/video/webgpu/shaders/tmxlayer-common.wgsl @@ -1,12 +1,15 @@ -// melonJS WebGPU orthogonal TMX layer shader — the WGSL port of -// orthogonal-tmxlayer.vert/frag (WebGL2). +// melonJS WebGPU TMX layer shader — the WGSL port of tmxlayer.vert and +// tmxlayer-common.frag (WebGL2): the part every map orientation shares. An +// orientation's own file follows it in the module (tmxlayer-orthogonal.wgsl, +// tmxlayer-isometric.wgsl) and gives the two things that differ: where a +// cell's tile is drawn (`tileOrigin`), and which cells could cover a +// fragment, front to back (`fragment_main`). // -// Per fragment: recover the world-pixel position from the quad UV, walk -// candidate cells (the geometric cell, plus cells whose oversized -// bottom-aligned tiles could reach this fragment), fetch GIDs from the -// per-layer index texture, and sample the tileset atlas at the correct -// sub-region. One draw per tileset — the GID-range guard discards cells -// belonging to other tilesets. +// Per fragment: recover the fragment's position in the layer from the quad +// UV, walk the cells whose tile could cover it, the one drawn last first, +// fetch GIDs from the per-layer index texture, and sample the tileset atlas +// at the correct sub-region. One draw per tileset — the GID-range guard +// discards cells belonging to other tilesets. // // Index texture encoding (rgba8unorm, one cell per texel): // R = GID low byte, G = GID high byte, B = flip mask (H|V<<1|AD<<2) @@ -27,7 +30,7 @@ struct TMXUniforms { uMapSize : vec2f, uCellSize : vec2f, uTileSize : vec2f, - uOverflow : vec2f, + uOverflow : vec2f, // how far a tile reaches past its cell (see each fragment_main) uTilesetCols : vec2f, uInvTilesetSize : vec2f, uTilesetMargin : vec4f, // (marginX, marginY, spacingX, spacingY) @@ -69,8 +72,6 @@ fn vertex_main( return out; } -const MAX_OVERFLOW : i32 = 4; - struct CellSample { hit : bool, color : vec4f, @@ -110,12 +111,8 @@ fn tryRenderCell( return miss; } - // oversized tiles are bottom-aligned vertically, left-aligned horizontally - let tileWorldOrigin = vec2f( - f32(cx) * tmx.uCellSize.x, - (f32(cy) + 1.0) * tmx.uCellSize.y - tmx.uTileSize.y, - ); - var inTile = (worldPx - tileWorldOrigin) / tmx.uTileSize; + // where the cell's tile is drawn from: the orientation's own + var inTile = (worldPx - tileOrigin(cx, cy)) / tmx.uTileSize; if (inTile.x < 0.0 || inTile.x >= 1.0 || inTile.y < 0.0 || inTile.y >= 1.0) { return miss; } @@ -186,57 +183,3 @@ fn layerColor(texel : vec4f) -> vec4f { return texel * tmx.uOpacity * vec4f(tmx.uTint.rgb, 1.0); } -@fragment -fn fragment_main(in : VSOut) -> @location(0) vec4f { - let tileCoord = tmx.uVisibleStart + in.vRegion * tmx.uVisibleSize; - let geomCell = floor(tileCoord); - let worldPx = tileCoord * tmx.uCellSize; - let dWorldX = dpdx(worldPx); - let dWorldY = dpdy(worldPx); - - let gx = i32(geomCell.x); - let gy = i32(geomCell.y); - let overflowX = i32(tmx.uOverflow.x + 0.5); - let overflowY = i32(tmx.uOverflow.y + 0.5); - - var result : CellSample; - - // fast path: tiles fit the cell exactly — only the geometric cell can - // contain this fragment's tile - if (overflowX == 0 && overflowY == 0) { - result = tryRenderCell(gx, gy, worldPx, dWorldX, dWorldY); - if (!result.hit) { - discard; - } - return layerColor(result.color); - } - - // slow path: oversized tiles. Scan candidates dy high→low, dx low→high - // and take the FIRST match — "right-down" render order puts later - // cells on top - var found = false; - for (var idy = 0; idy <= MAX_OVERFLOW; idy++) { - let dy = MAX_OVERFLOW - idy; - if (dy > overflowY) { - continue; - } - for (var dx = 0; dx <= MAX_OVERFLOW; dx++) { - if (dx > overflowX) { - break; - } - let candidate = tryRenderCell(gx - dx, gy + dy, worldPx, dWorldX, dWorldY); - if (candidate.hit) { - result = candidate; - found = true; - break; - } - } - if (found) { - break; - } - } - if (!found) { - discard; - } - return layerColor(result.color); -} diff --git a/packages/melonjs/src/video/webgpu/shaders/tmxlayer-isometric.wgsl b/packages/melonjs/src/video/webgpu/shaders/tmxlayer-isometric.wgsl new file mode 100644 index 0000000000..8baea0fdbc --- /dev/null +++ b/packages/melonjs/src/video/webgpu/shaders/tmxlayer-isometric.wgsl @@ -0,0 +1,67 @@ +// The isometric part of the TMX layer shader: appended to +// tmxlayer-common.wgsl. The WGSL port of isometric-tmxlayer.frag, where the +// cell maths is explained. +// +// A fragment's position is in the layer's pixels, measured across from the +// map's top corner. With u = col - row and s = col + row, the cells whose +// tile image covers it are a run of `u` and a run of `s`, of the lengths in +// `uOverflow`, scanned s high→low then u high→low: the reverse of the order +// the CPU renderer draws in, so the FIRST opaque texel is the fragment. + +// bounds of the two runs: tiles up to 8 grid heights tall and 4 grid widths +// wide (the layer falls back to the CPU renderer past them) +const MAX_ROWS : i32 = 16; +const MAX_COLS : i32 = 4; + +// the left of the cell's diamond, and as far above its bottom as the tile +// is tall +fn tileOrigin(cx : i32, cy : i32) -> vec2f { + return vec2f( + f32(cx - cy - 1) * tmx.uCellSize.x * 0.5, + f32(cx + cy + 2) * tmx.uCellSize.y * 0.5 - tmx.uTileSize.y, + ); +} + +@fragment +fn fragment_main(in : VSOut) -> @location(0) vec4f { + let worldPx = tmx.uVisibleStart + in.vRegion * tmx.uVisibleSize; + let dWorldX = dpdx(worldPx); + let dWorldY = dpdy(worldPx); + + let halfCell = tmx.uCellSize * 0.5; + // the rightmost and the lowest cell whose image can reach the fragment + let uMax = i32(floor(worldPx.x / halfCell.x)) + 1; + let sMax = i32(floor((worldPx.y + tmx.uTileSize.y) / halfCell.y)) - 2; + let spanU = i32(tmx.uOverflow.x + 0.5); + let spanS = i32(tmx.uOverflow.y + 0.5); + + var result : CellSample; + var found = false; + for (var j = 0; j < MAX_ROWS; j++) { + if (j >= spanS) { + break; + } + let s = sMax - j; + // the first u of this row's parity, then every other one + var u = uMax - ((uMax + s) & 1); + for (var i = 0; i < MAX_COLS; i++) { + if (uMax - u >= spanU) { + break; + } + let candidate = tryRenderCell((s + u) / 2, (s - u) / 2, worldPx, dWorldX, dWorldY); + if (candidate.hit) { + result = candidate; + found = true; + break; + } + u -= 2; + } + if (found) { + break; + } + } + if (!found) { + discard; + } + return layerColor(result.color); +} diff --git a/packages/melonjs/src/video/webgpu/shaders/tmxlayer-orthogonal.wgsl b/packages/melonjs/src/video/webgpu/shaders/tmxlayer-orthogonal.wgsl new file mode 100644 index 0000000000..644a16d72d --- /dev/null +++ b/packages/melonjs/src/video/webgpu/shaders/tmxlayer-orthogonal.wgsl @@ -0,0 +1,69 @@ +// The orthogonal part of the TMX layer shader: appended to +// tmxlayer-common.wgsl. The WGSL port of orthogonal-tmxlayer.frag. +// +// `uOverflow` is how many cells a tile reaches past its own, across and up. + +const MAX_OVERFLOW : i32 = 4; + +// a tile is bottom-aligned on its cell, and left-aligned +fn tileOrigin(cx : i32, cy : i32) -> vec2f { + return vec2f( + f32(cx) * tmx.uCellSize.x, + (f32(cy) + 1.0) * tmx.uCellSize.y - tmx.uTileSize.y, + ); +} + +@fragment +fn fragment_main(in : VSOut) -> @location(0) vec4f { + let tileCoord = tmx.uVisibleStart + in.vRegion * tmx.uVisibleSize; + let geomCell = floor(tileCoord); + let worldPx = tileCoord * tmx.uCellSize; + let dWorldX = dpdx(worldPx); + let dWorldY = dpdy(worldPx); + + let gx = i32(geomCell.x); + let gy = i32(geomCell.y); + let overflowX = i32(tmx.uOverflow.x + 0.5); + let overflowY = i32(tmx.uOverflow.y + 0.5); + + var result : CellSample; + + // fast path: tiles fit the cell exactly — only the geometric cell can + // contain this fragment's tile + if (overflowX == 0 && overflowY == 0) { + result = tryRenderCell(gx, gy, worldPx, dWorldX, dWorldY); + if (!result.hit) { + discard; + } + return layerColor(result.color); + } + + // slow path: oversized tiles. Scan candidates dy high→low, dx low→high + // and take the FIRST match — "right-down" render order puts later + // cells on top + var found = false; + for (var idy = 0; idy <= MAX_OVERFLOW; idy++) { + let dy = MAX_OVERFLOW - idy; + if (dy > overflowY) { + continue; + } + for (var dx = 0; dx <= MAX_OVERFLOW; dx++) { + if (dx > overflowX) { + break; + } + let candidate = tryRenderCell(gx - dx, gy + dy, worldPx, dWorldX, dWorldY); + if (candidate.hit) { + result = candidate; + found = true; + break; + } + } + if (found) { + break; + } + } + if (!found) { + discard; + } + return layerColor(result.color); +} diff --git a/packages/melonjs/src/video/webgpu/webgpu_renderer.js b/packages/melonjs/src/video/webgpu/webgpu_renderer.js index 5d506dcebf..e6c92eaffb 100644 --- a/packages/melonjs/src/video/webgpu/webgpu_renderer.js +++ b/packages/melonjs/src/video/webgpu/webgpu_renderer.js @@ -54,6 +54,7 @@ import WebGPUBufferArena from "./buffer/arena.js"; import WebGPUUniformRing from "./buffer/uniformring.js"; import { buildEffectGPU } from "./effect_binding.js"; import WebGPUPipelineCache, { DEPTH_STENCIL_FORMAT } from "./pipeline/cache.js"; +import IsometricTMXLayerGPURenderer from "./renderers/tmxlayer/isometric.js"; import OrthogonalTMXLayerGPURenderer from "./renderers/tmxlayer/orthogonal.js"; import { COMPRESSION_FEATURES } from "./texture/compressed.js"; import { WebGPUFrameTexture } from "./texture/frametexture.js"; @@ -104,6 +105,15 @@ export function resolveDepthOps(meshDepthActive, pendingDepthClear) { }; } +/** + * the GPU tile layer renderer of each map orientation that has one + * @ignore + */ +const TMX_GPU_RENDERERS = { + orthogonal: OrthogonalTMXLayerGPURenderer, + isometric: IsometricTMXLayerGPURenderer, +}; + /** * The **experimental** WebGPU renderer. * @@ -213,11 +223,11 @@ export default class WebGPURenderer extends Renderer { this._resolveToneMapping(); // presentation is settled again by init(), once the surface exists this.setHDROutput(this.settings.hdrOutput === true); - // lazy orientation-specific GPU tilemap renderer (device-scoped: - // dropped on device loss, rebuilt on first use) + // lazy orientation-specific GPU tilemap renderers, by orientation + // (device-scoped: dropped on device loss, rebuilt on first use) /** @ignore * @internal */ - this.orthogonalTMXRenderer = undefined; + this.tmxRenderers = new Map(); // create a texture cache /** @@ -2509,16 +2519,16 @@ export default class WebGPURenderer extends Renderer { * @override */ drawTileLayer(layer, rect) { - if (layer.renderMode === "shader" && layer.orientation === "orthogonal") { + const Class = TMX_GPU_RENDERERS[layer.orientation]; + if (layer.renderMode === "shader" && Class !== undefined) { // device-scoped, lazily (re)built: a device loss rebuilds the // pipeline cache, detected via the epoch stamp - if ( - this.orthogonalTMXRenderer === undefined || - this.orthogonalTMXRenderer.epoch !== this.pipelineCache.epoch - ) { - this.orthogonalTMXRenderer = new OrthogonalTMXLayerGPURenderer(this); + let tmx = this.tmxRenderers.get(layer.orientation); + if (tmx === undefined || tmx.epoch !== this.pipelineCache.epoch) { + tmx = new Class(this); + this.tmxRenderers.set(layer.orientation, tmx); } - this.orthogonalTMXRenderer.draw(layer, rect); + tmx.draw(layer, rect); return; } super.drawTileLayer(layer, rect); @@ -4744,8 +4754,8 @@ export default class WebGPURenderer extends Renderer { this.stubTextureView = null; this.currentRenderTarget = null; // tile-path lookup textures died with the device; the epoch check - // in drawTileLayer rebuilds the renderer lazily - this.orthogonalTMXRenderer = undefined; + // in drawTileLayer rebuilds the renderers lazily + this.tmxRenderers.clear(); this.depthTexture = null; this.msaaDepthTexture = null; this.msaaColorTexture = null; @@ -4802,7 +4812,9 @@ export default class WebGPURenderer extends Renderer { this.effectPassDepth = 0; this.customShader = undefined; // level transition: free the per-layer/per-tileset lookup textures - this.orthogonalTMXRenderer?.reset(); + this.tmxRenderers.forEach((tmx) => { + tmx.reset(); + }); super.reset(); // re-init batchers when recovering from a device loss, plain reset // otherwise — the same split as the WebGL restore path. A reset @@ -4867,7 +4879,7 @@ export default class WebGPURenderer extends Renderer { this.pipelineCache?.clear(); this.captureTexture?.destroy(); this.captureTexture = undefined; - this.orthogonalTMXRenderer = undefined; + this.tmxRenderers.clear(); this._renderTargetPool?.destroy(); this._renderTargetPool = null; this.effectUniformArena?.destroy(); diff --git a/packages/melonjs/tests/helpers/tile-layer-compare.js b/packages/melonjs/tests/helpers/tile-layer-compare.js new file mode 100644 index 0000000000..683d2792b0 --- /dev/null +++ b/packages/melonjs/tests/helpers/tile-layer-compare.js @@ -0,0 +1,333 @@ +/** + * Draw the same tile layers through the CPU renderer (`renderMode` + * "perTile") and through the GPU one ("shader"), with the whole engine in + * between (world, camera, renderer), and compare the two frames. + * + * The tiles are painted pixel by pixel, with no soft edges, and every pixel + * of every tile has a colour of its own: a tile that lands one pixel off, is + * flipped the wrong way, or shows in front of the wrong neighbour, changes + * pixels. So the two paths are held to the same picture, exactly. + */ +import { vi } from "vitest"; +import { Application, boot, TMXTileMap } from "../../src/index.js"; +import { imgList } from "../../src/loader/cache.js"; +import Renderer from "../../src/video/renderer.js"; +import { drawOffscreen, grabFrame } from "./pixels.js"; + +export const FLIP_H = 0x80000000; +export const FLIP_V = 0x40000000; +export const FLIP_AD = 0x20000000; + +let nextName = 0; + +/** + * Whether a pixel of a `w` × `h` tile image belongs to an isometric block + * standing on a `tw` × `th` diamond at the bottom of the image: the diamond, + * the same diamond at the top, and everything between them. A tile as tall + * as its diamond is the diamond alone. + * @param {number} x - pixel column in the tile + * @param {number} y - pixel row in the tile + * @param {number} w - tile image width + * @param {number} h - tile image height + * @param {number} tw - diamond width + * @param {number} th - diamond height + * @returns {boolean} whether the pixel is opaque + */ +export function inBlock(x, y, w, h, tw, th) { + // across: how far from the diamond's vertical axis, in half widths + const dx = Math.abs(x + 0.5 - w / 2) / (tw / 2); + if (dx > 1) { + return false; + } + // the diamond's edge at this column, from its centre line + const edge = (1 - dx) * (th / 2); + const top = th / 2 - edge; + const bottom = h - th / 2 + edge; + return y + 0.5 >= top && y + 0.5 <= bottom; +} + +/** + * Make a tileset image, registered with the loader, and its Tiled JSON. + * @param {object} options + * @param {number} options.tw - tile image width + * @param {number} options.th - tile image height + * @param {number} [options.count=8] - number of tiles + * @param {number} [options.columns=4] - tiles per row of the image + * @param {number} [options.margin=0] - margin round the image + * @param {number} [options.spacing=0] - spacing between tiles + * @param {(x: number, y: number, id: number) => boolean} [options.opaque] - + * which pixels of a tile are opaque (all of them by default) + * @param {object} [options.extra] - more Tiled tileset properties + * (`tileoffset`, `tiles` with animations...) + * @returns {object} the tileset's Tiled JSON, without its `firstgid` + */ +export function makeTileset(options) { + const { + tw, + th, + count = 8, + columns = 4, + margin = 0, + spacing = 0, + opaque, + extra = {}, + } = options; + const rows = Math.ceil(count / columns); + const canvas = document.createElement("canvas"); + canvas.width = margin * 2 + columns * tw + (columns - 1) * spacing; + canvas.height = margin * 2 + rows * th + (rows - 1) * spacing; + const ctx = canvas.getContext("2d"); + const image = ctx.createImageData(canvas.width, canvas.height); + const seed = nextName * 37; + // the margin and spacing are a colour no tile has: sampled, they show + for (let i = 0; i < image.data.length; i += 4) { + image.data[i] = 255; + image.data[i + 1] = 0; + image.data[i + 2] = 255; + image.data[i + 3] = 255; + } + for (let id = 0; id < count; id++) { + const ox = margin + (id % columns) * (tw + spacing); + const oy = margin + Math.floor(id / columns) * (th + spacing); + for (let y = 0; y < th; y++) { + for (let x = 0; x < tw; x++) { + const o = ((oy + y) * canvas.width + ox + x) * 4; + if (opaque !== undefined && !opaque(x, y, id)) { + image.data[o + 3] = 0; + image.data[o] = image.data[o + 1] = image.data[o + 2] = 0; + continue; + } + // a colour per tile, and per pixel in it: never the + // margin's, never the background's + image.data[o] = 40 + ((id * 53 + seed) % 180); + image.data[o + 1] = 30 + ((x * 7 + id * 11) % 200); + image.data[o + 2] = 30 + ((y * 5 + id * 29) % 200); + image.data[o + 3] = 255; + } + } + } + ctx.putImageData(image, 0, 0); + const name = `tile-compare-${nextName++}`; + imgList[name] = canvas; + return { + name, + tilewidth: tw, + tileheight: th, + spacing, + margin, + tilecount: count, + columns, + image: `${name}.png`, + imagewidth: canvas.width, + imageheight: canvas.height, + ...extra, + }; +} + +/** + * Build a map from tilesets and layers. + * @param {object} options + * @param {string} options.orientation - Tiled orientation + * @param {number} options.cols - map width, in tiles + * @param {number} options.rows - map height, in tiles + * @param {number} options.tw - grid tile width + * @param {number} options.th - grid tile height + * @param {object[]} options.tilesets - from {@link makeTileset}; their + * `firstgid` is set here, one after the other + * @param {object[]} options.layers - `{ data }` (gids, row by row) or + * `{ chunks }` for an infinite map, plus any Tiled layer property + * @param {object} [options.extra] - more Tiled map properties + * @returns {TMXTileMap} the map + */ +export function makeMap(options) { + const { + orientation, + cols, + rows, + tw, + th, + tilesets, + layers, + extra = {}, + } = options; + let firstgid = 1; + const sets = tilesets.map((tileset) => { + const set = { ...tileset, firstgid }; + firstgid += tileset.tilecount; + return set; + }); + return new TMXTileMap(`tile-compare-map-${nextName++}`, { + width: cols, + height: rows, + tilewidth: tw, + tileheight: th, + orientation, + renderorder: "right-down", + infinite: false, + version: "1.10", + tiledversion: "1.10.2", + tilesets: sets, + layers: layers.map((layer, i) => { + return { + type: "tilelayer", + name: `layer${i}`, + width: cols, + height: rows, + visible: true, + opacity: 1, + ...layer, + }; + }), + ...extra, + }); +} + +/** + * A layer's data, filled by a function of each cell. + * @param {number} cols - columns + * @param {number} rows - rows + * @param {(col: number, row: number) => number} gidOf - the cell's gid, 0 for none + * @returns {number[]} the gids, row by row + */ +export function fill(cols, rows, gidOf) { + const data = []; + for (let row = 0; row < rows; row++) { + for (let col = 0; col < cols; col++) { + data.push(gidOf(col, row)); + } + } + return data; +} + +/** + * The application the comparisons draw with, its loop held still so that + * frames are drawn only when a test asks. `null` when the renderer asked + * for is not available (a WebGPU device, on a machine without one). + * @param {number} renderer - `video.WEBGL` or `video.WEBGPU` + * @param {string} type - the `renderer.type` expected + * @param {number} [width=320] - canvas width + * @param {number} [height=240] - canvas height + * @returns {Promise} the application + */ +export async function makeApp(renderer, type, width = 320, height = 240) { + // no frame of the engine's own: a test draws each one + vi.spyOn(globalThis, "requestAnimationFrame").mockImplementation(() => { + return 1; + }); + vi.spyOn(globalThis, "cancelAnimationFrame").mockImplementation(() => {}); + boot(); + let app; + try { + app = new Application(width, height, { + parent: "screen", + renderer, + consoleHeader: false, + }); + await app.init(); + } catch { + return null; + } + if (!app.renderer.type.startsWith(type)) { + app.destroy(); + return null; + } + drawOffscreen(app.renderer); + // not black: a tile that is not drawn shows + app.renderer.backgroundColor.setColor(16, 24, 48); + app.viewport.setBounds(-100000, -100000, 200000, 200000); + return app; +} + +/** + * Put a map's layers in the world, in place of whatever was there. + * @param {Application} app - the application + * @param {TMXTileMap} map - the map + * @returns {object[]} the map's tile layers + */ +export function show(app, map) { + app.world.reset(); + app.renderer.reset?.(); + app.renderer.backgroundColor.setColor(16, 24, 48); + map.addTo(app.world, true, false); + app.viewport.setBounds(-100000, -100000, 200000, 200000); + return map.getLayers(); +} + +let clock = 1000; + +/** + * Draw one frame with every layer in the given mode, and return it with how + * many times the CPU tile renderer was reached while drawing it. + * @param {Application} app - the application + * @param {object[]} layers - the layers + * @param {string} mode - "perTile", "shader" or "prerender" + * @param {number} [dt=0] - game time to pass before the frame, in ms + * @returns {Promise<{frame: ImageData, cpuDraws: number}>} the frame + */ +export async function drawIn(app, layers, mode, dt = 0) { + for (const layer of layers) { + layer.renderMode = mode; + } + // the world updated (what is in view, and animated tiles when time + // passes), then drawn + clock += dt; + app.world.update(dt); + app.viewport.update(dt); + const cpu = vi.spyOn(Renderer.prototype, "drawTileLayer"); + app.repaint(); + app.draw(); + const cpuDraws = cpu.mock.calls.length; + cpu.mockRestore(); + const frame = await grabFrame(app.renderer); + return { frame, cpuDraws }; +} + +/** + * Compare two frames. + * @param {ImageData} a - one frame + * @param {ImageData} b - the other + * @param {number} [tolerance=0] - largest difference of a channel that is + * not counted + * @returns {{different: number, worst: number, first: string}} how many + * pixels differ, by how much at most, and the first one + */ +export function diff(a, b, tolerance = 0) { + let different = 0; + let worst = 0; + let first = ""; + for (let i = 0; i < a.data.length; i += 4) { + const d = Math.max( + Math.abs(a.data[i] - b.data[i]), + Math.abs(a.data[i + 1] - b.data[i + 1]), + Math.abs(a.data[i + 2] - b.data[i + 2]), + ); + if (d > tolerance) { + different++; + if (first === "") { + const p = i / 4; + first = `(${p % a.width}, ${Math.floor(p / a.width)}): [${a.data.slice(i, i + 3)}] against [${b.data.slice(i, i + 3)}]`; + } + } + worst = Math.max(worst, d); + } + return { different, worst, first }; +} + +/** + * How many pixels of a frame are not the background: how much was drawn. + * @param {ImageData} frame - the frame + * @returns {number} the count + */ +export function drawn(frame) { + let count = 0; + for (let i = 0; i < frame.data.length; i += 4) { + if ( + frame.data[i] !== 16 || + frame.data[i + 1] !== 24 || + frame.data[i + 2] !== 48 + ) { + count++; + } + } + return count; +} From 74c3e6c2afe3310ef854e93c427d4f22bfe6c4b0 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 00:47:54 +0000 Subject: [PATCH 03/51] GPU tile layers: blend soft tile edges, and hold both paths to a reference (#1897) The GPU path took the first texel that was not transparent, front to back. With drawn art that is wrong wherever tiles overlap, which on an isometric map is everywhere: the soft edge of a tile showed the background in place of the tile behind it. Each texel now goes behind the ones before it until the fragment is opaque, which is what drawing the tiles one over the other comes to. The orthogonal shader shares it, for tiles larger than the grid. Found by a scenario suite that draws every case through the CPU renderer and the GPU one, on WebGL and on WebGPU, and compares both with a reference painted with no engine at all. It also found, and this fixes: - the isometric CPU renderer left out tiles by the first tileset's size, and by no tileset's `tileoffset` - the orthogonal CPU renderer widened the wrong side of the view for tiles taller than the grid - the orthogonal GPU quad cut tiles larger than the grid above the first row and right of the last column - a tile that is not square, flipped diagonally, is wrong on the GPU path: such a layer is left to the CPU renderer Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- packages/melonjs/src/level/tiled/TMXLayer.js | 107 +- .../tiled/renderer/TMXIsometricRenderer.js | 18 +- .../tiled/renderer/TMXOrthogonalRenderer.js | 26 +- .../melonjs/src/video/gpu/tmxlayer_region.js | 17 +- .../webgl/shaders/isometric-tmxlayer.frag | 25 +- .../webgl/shaders/orthogonal-tmxlayer.frag | 28 +- .../video/webgl/shaders/tmxlayer-common.frag | 17 +- .../video/webgpu/shaders/tmxlayer-common.wgsl | 13 + .../webgpu/shaders/tmxlayer-isometric.wgsl | 18 +- .../webgpu/shaders/tmxlayer-orthogonal.wgsl | 28 +- .../tests/helpers/tile-layer-compare.js | 181 ++- .../helpers/tile-layer-isometric-scenarios.js | 1296 +++++++++++++++++ packages/melonjs/tests/texture-mipmap.spec.js | 12 +- .../tests/tmxlayer-shader-isometric.spec.js | 8 + .../tests/webgpu_tmxlayer_isometric.spec.js | 9 + 15 files changed, 1703 insertions(+), 100 deletions(-) create mode 100644 packages/melonjs/tests/helpers/tile-layer-isometric-scenarios.js create mode 100644 packages/melonjs/tests/tmxlayer-shader-isometric.spec.js create mode 100644 packages/melonjs/tests/webgpu_tmxlayer_isometric.spec.js diff --git a/packages/melonjs/src/level/tiled/TMXLayer.js b/packages/melonjs/src/level/tiled/TMXLayer.js index 54c7fb89d9..98585e4196 100644 --- a/packages/melonjs/src/level/tiled/TMXLayer.js +++ b/packages/melonjs/src/level/tiled/TMXLayer.js @@ -32,6 +32,10 @@ const ISOMETRIC_MAX_TILE_WIDTHS = 4; const ISOMETRIC_MAX_TILE_HEIGHTS = 8; const ISOMETRIC_ONE_TILESET = "tiles of more than one tileset in an isometric layer"; +// A diagonal flip turns a tile a quarter: one that is not square then covers +// other pixels than its own image's rectangle, which is all the shader looks +// at. +const DIAGONAL_NOT_SQUARE = "a tile that is not square, flipped diagonally"; // the area an offset camera shows, handed to the tile renderers in its place // (made on first use) @@ -218,8 +222,23 @@ export default class TMXLayer extends Renderable { width: 0, height: 0, }; + /** + * how far a tileset's `tileoffset` moves its tiles, at most, across + * and down: with `maxTileSize`, how far from its cell a tile of this + * layer can be drawn + * @ignore + */ + this.maxTileOffset = { x: 0, y: 0 }; for (let i = 0; i < this.tilesets.length; i++) { const tileset = this.tilesets.getTilesetByIndex(i); + this.maxTileOffset.x = Math.max( + this.maxTileOffset.x, + Math.abs(tileset.tileoffset.x), + ); + this.maxTileOffset.y = Math.max( + this.maxTileOffset.y, + Math.abs(tileset.tileoffset.y), + ); this.maxTileSize.width = Math.max( this.maxTileSize.width, tileset.tilewidth, @@ -726,9 +745,41 @@ export default class TMXLayer extends Renderable { }; } } + if (this._hasDiagonalFlipNotSquare()) { + return { ok: false, reason: DIAGONAL_NOT_SQUARE }; + } return { ok: true }; } + /** + * Whether a tile of this layer is flipped diagonally and not square, + * which the shader path cannot draw. Only looks at the tiles when a + * tileset has tiles that are not square. + * @returns {boolean} + * @ignore + * @internal + */ + _hasDiagonalFlipNotSquare() { + const tilesets = this.tilesets.tilesets; + if ( + tilesets.every((tileset) => { + return tileset.tilewidth === tileset.tileheight; + }) + ) { + return false; + } + const data = this.layerData; + for (let i = 0; i < data.length; i += 2) { + if (data[i] !== 0 && (data[i + 1] & FLIP_AD_BIT) !== 0) { + const tileset = this.tilesets.getTilesetByGid(data[i]); + if (tileset.tilewidth !== tileset.tileheight) { + return true; + } + } + } + return false; + } + /** * Check whether this isometric layer can take the shader path, and note * the tileset it would draw with. @@ -768,6 +819,9 @@ export default class TMXLayer extends Renderable { } this._shaderTileset = tileset; } + if (this._hasDiagonalFlipNotSquare()) { + return { ok: false, reason: DIAGONAL_NOT_SQUARE }; + } return { ok: true }; } @@ -798,31 +852,46 @@ export default class TMXLayer extends Renderable { } /** - * An isometric layer on the shader path draws with one tileset: a tile - * set at run time from another one, or from one the path cannot draw, - * moves the layer back to the legacy renderer. + * A tile set at run time on a layer on the shader path: one that path + * cannot draw moves the layer back to the legacy renderer. + * + * That is a tile flipped diagonally and not square, and on an isometric + * layer, which draws with one tileset, a tile of another one, or of one + * the path cannot draw. * @param {number} gid - the gid of the tile just set + * @param {number} flipMask - its flips * @ignore * @internal */ - _keepIsometricShaderTileset(gid) { - const current = this._shaderTileset; - if (current?.contains(gid)) { - return; + _keepShaderEligible(gid, flipMask) { + let reason; + if ( + this.orientation === "isometric" && + this._shaderTileset?.contains(gid) !== true + ) { + if (this._shaderTileset !== undefined) { + reason = ISOMETRIC_ONE_TILESET; + } else { + // an empty layer takes its tileset from its first tile + const tileset = this.tilesets.getTilesetByGid(gid); + reason = this._isometricTilesetReason(tileset); + if (reason === undefined) { + this._shaderTileset = tileset; + } + } } - let reason = ISOMETRIC_ONE_TILESET; - if (current === undefined) { + if (reason === undefined && (flipMask & FLIP_AD_BIT) !== 0) { const tileset = this.tilesets.getTilesetByGid(gid); - reason = this._isometricTilesetReason(tileset); - if (reason === undefined) { - this._shaderTileset = tileset; - return; + if (tileset.tilewidth !== tileset.tileheight) { + reason = DIAGONAL_NOT_SQUARE; } } - console.warn( - `melonJS: layer "${this.name}" back to the legacy tile renderer (${reason})`, - ); - this.renderMode = "perTile"; + if (reason !== undefined) { + console.warn( + `melonJS: layer "${this.name}" back to the legacy tile renderer (${reason})`, + ); + this.renderMode = "perTile"; + } } // called when the layer is removed from the game world or a container @@ -931,8 +1000,8 @@ export default class TMXLayer extends Renderable { this.dataVersion++; this.isDirty = true; this._preRenderCell(x, y); - if (this.renderMode === "shader" && this.orientation === "isometric") { - this._keepIsometricShaderTileset(cleanGid); + if (this.renderMode === "shader") { + this._keepShaderEligible(cleanGid, this.layerData[idx + 1]); } return tile; } diff --git a/packages/melonjs/src/level/tiled/renderer/TMXIsometricRenderer.js b/packages/melonjs/src/level/tiled/renderer/TMXIsometricRenderer.js index 3c884b086c..b0fd0514ba 100644 --- a/packages/melonjs/src/level/tiled/renderer/TMXIsometricRenderer.js +++ b/packages/melonjs/src/level/tiled/renderer/TMXIsometricRenderer.js @@ -159,15 +159,23 @@ export default class TMXIsometricRenderer extends TMXRenderer { // cache a couple of useful references let tileset = layer.tileset; - // get top-left and bottom-right tile position + // get top-left and bottom-right tile position: the view, widened by + // the largest tile of ANY of the layer's tilesets, as a tile is drawn + // from its cell up, and by how far a `tileoffset` moves one. By the + // first tileset's size alone, the tall tiles of another one went + // missing along the bottom of the view, where their cell is below it + // and their image still reaches in, and so did tiles moved into view + // by an offset larger than a tile + const reachX = layer.maxTileSize.width + layer.maxTileOffset.x; + const reachY = layer.maxTileSize.height + layer.maxTileOffset.y; const rowItr = this.pixelToTileCoords( - rect.pos.x - tileset.tilewidth, - rect.pos.y - tileset.tileheight, + rect.pos.x - reachX, + rect.pos.y - reachY, vector2dPool.get(), ).floorSelf(); const tileEnd = this.pixelToTileCoords( - rect.pos.x + rect.width + tileset.tilewidth, - rect.pos.y + rect.height + tileset.tileheight, + rect.pos.x + rect.width + reachX, + rect.pos.y + rect.height + reachY, vector2dPool.get(), ).ceilSelf(); diff --git a/packages/melonjs/src/level/tiled/renderer/TMXOrthogonalRenderer.js b/packages/melonjs/src/level/tiled/renderer/TMXOrthogonalRenderer.js index 5de0ae9ff9..a6cb4412dd 100644 --- a/packages/melonjs/src/level/tiled/renderer/TMXOrthogonalRenderer.js +++ b/packages/melonjs/src/level/tiled/renderer/TMXOrthogonalRenderer.js @@ -87,22 +87,26 @@ export default class TMXOrthogonalRenderer extends TMXRenderer { let incX = 1; let incY = 1; - // get top-left and bottom-right tile position + // get top-left and bottom-right tile position: the cells whose tile + // can reach the view. A tile larger than its cell is drawn from the + // cell's bottom left corner, so it reaches to the RIGHT of its cell + // and ABOVE it: the cells that matter past the view are those to its + // left and BELOW it. (The rows above were the ones added, so a tile + // more than two cells tall went missing along the bottom of the + // view.) A tileset's `tileoffset` moves its tiles either way. + const overX = Math.max(layer.maxTileSize.width - layer.tilewidth, 0); + const overY = Math.max(layer.maxTileSize.height - layer.tileheight, 0); + const offsetX = layer.maxTileOffset.x; + const offsetY = layer.maxTileOffset.y; const start = this.pixelToTileCoords( - Math.max( - rect.pos.x - Math.max(layer.maxTileSize.width - layer.tilewidth, 0), - 0, - ), - Math.max( - rect.pos.y - Math.max(layer.maxTileSize.height - layer.tileheight, 0), - 0, - ), + Math.max(rect.pos.x - overX - offsetX, 0), + Math.max(rect.pos.y - offsetY, 0), vector2dPool.get(), ).floorSelf(); const end = this.pixelToTileCoords( - rect.pos.x + rect.width + this.tilewidth, - rect.pos.y + rect.height + this.tileheight, + rect.pos.x + rect.width + this.tilewidth + offsetX, + rect.pos.y + rect.height + this.tileheight + overY + offsetY, vector2dPool.get(), ).ceilSelf(); diff --git a/packages/melonjs/src/video/gpu/tmxlayer_region.js b/packages/melonjs/src/video/gpu/tmxlayer_region.js index b83f5211bf..34ffe5318b 100644 --- a/packages/melonjs/src/video/gpu/tmxlayer_region.js +++ b/packages/melonjs/src/video/gpu/tmxlayer_region.js @@ -43,11 +43,24 @@ export function orthogonalRegion(layer, rect, tileset, out) { const tileWidth = layer.tilewidth; const tileHeight = layer.tileheight; + // A tile larger than its cell is drawn from the cell's bottom left + // corner: it reaches to the right of its cell and above it, so the tiles + // of the last column and of the first row reach past the grid. The quad + // covers that too, by the layer's LARGEST tile, so that it is the same + // for every tileset of the layer (the shader drops what a pass has no + // tile for). + const largest = layer.maxTileSize ?? { + width: tileset.tilewidth, + height: tileset.tileheight, + }; + const reachX = Math.max(0, Math.ceil(largest.width / tileWidth) - 1); + const reachY = Math.max(0, Math.ceil(largest.height / tileHeight) - 1); + // compute the visible region in tile-coord space const startTileX = Math.max(0, Math.floor(rect.pos.x / tileWidth)); - const startTileY = Math.max(0, Math.floor(rect.pos.y / tileHeight)); + const startTileY = Math.max(-reachY, Math.floor(rect.pos.y / tileHeight)); const endTileX = Math.min( - layer.cols, + layer.cols + reachX, Math.ceil((rect.pos.x + rect.width) / tileWidth), ); const endTileY = Math.min( diff --git a/packages/melonjs/src/video/webgl/shaders/isometric-tmxlayer.frag b/packages/melonjs/src/video/webgl/shaders/isometric-tmxlayer.frag index 6c7f1ac61f..befc47ff0c 100644 --- a/packages/melonjs/src/video/webgl/shaders/isometric-tmxlayer.frag +++ b/packages/melonjs/src/video/webgl/shaders/isometric-tmxlayer.frag @@ -15,9 +15,11 @@ // Only pairs of the same parity are cells. // // The CPU renderer draws rows of constant `s` from the top of the screen -// down, each from left to right. The last tile drawn is the one seen, so the -// scan here goes the other way, s high→low then u high→low, and the FIRST -// cell with an opaque texel is the fragment. +// down, each from left to right. The last tile drawn is the one in front, +// so the scan here goes the other way, s high→low then u high→low, and puts +// each texel behind the ones before it until the fragment is opaque: an +// opaque texel ends it at once, and the soft edge of a tile shows the tiles +// behind it. // bounds of the two runs: tiles up to 8 grid heights tall and 4 grid widths // wide (the layer falls back to the CPU renderer past them) @@ -45,8 +47,9 @@ void main(void) { int spanU = int(uOverflow.x + 0.5); int spanS = int(uOverflow.y + 0.5); - vec4 result; - bool found = false; + vec4 result = vec4(0.0); + vec4 texel; + bool opaque = false; for (int j = 0; j < MAX_ROWS; j++) { if (j >= spanS) break; int s = sMax - j; @@ -54,14 +57,16 @@ void main(void) { int u = uMax - ((uMax + s) & 1); for (int i = 0; i < MAX_COLS; i++) { if (uMax - u >= spanU) break; - if (tryRenderCell((s + u) / 2, (s - u) / 2, worldPx, dWorldX, dWorldY, result)) { - found = true; - break; + if (tryRenderCell((s + u) / 2, (s - u) / 2, worldPx, dWorldX, dWorldY, texel)) { + if (under(result, texel)) { + opaque = true; + break; + } } u -= 2; } - if (found) break; + if (opaque) break; } - if (!found) discard; + if (result.a <= 0.0) discard; fragColor = layerColor(result); } diff --git a/packages/melonjs/src/video/webgl/shaders/orthogonal-tmxlayer.frag b/packages/melonjs/src/video/webgl/shaders/orthogonal-tmxlayer.frag index b7c7afd905..3e29c4a3ad 100644 --- a/packages/melonjs/src/video/webgl/shaders/orthogonal-tmxlayer.frag +++ b/packages/melonjs/src/video/webgl/shaders/orthogonal-tmxlayer.frag @@ -11,8 +11,9 @@ // Slow path: tiles drawing larger than the cell are bottom-aligned // vertically and left-aligned horizontally. Render order is "right-down": // later cells end up on top, so the candidate loop scans dy high→low, -// dx low→high and picks the FIRST match. `uOverflow` is how many cells a -// tile reaches past its own, across and up. +// dx low→high, the tile in front first, and puts each texel behind the +// ones before it until the fragment is opaque. `uOverflow` is how many +// cells a tile reaches past its own, across and up. const int MAX_OVERFLOW = 4; @@ -36,7 +37,7 @@ void main(void) { int overflowX = int(uOverflow.x + 0.5); int overflowY = int(uOverflow.y + 0.5); - vec4 result; + vec4 result = vec4(0.0); // Fast path: tiles fit the cell exactly (the common case) — only the // geometric cell can contain this fragment's tile. @@ -48,22 +49,25 @@ void main(void) { return; } - // Slow path: oversized tiles. Walk candidates dy high→low, dx low→high - // and pick the FIRST match — render order is "right-down" so later - // cells go on top. - bool found = false; + // Slow path: oversized tiles. Walk candidates dy high→low, dx low→high, + // front to back — render order is "right-down" so later cells go on + // top — until the fragment is opaque. + vec4 texel; + bool opaque = false; for (int idy = 0; idy <= MAX_OVERFLOW; idy++) { int dy = MAX_OVERFLOW - idy; if (dy > overflowY) continue; for (int dx = 0; dx <= MAX_OVERFLOW; dx++) { if (dx > overflowX) break; - if (tryRenderCell(gx - dx, gy + dy, worldPx, dWorldX, dWorldY, result)) { - found = true; - break; + if (tryRenderCell(gx - dx, gy + dy, worldPx, dWorldX, dWorldY, texel)) { + if (under(result, texel)) { + opaque = true; + break; + } } } - if (found) break; + if (opaque) break; } - if (!found) discard; + if (result.a <= 0.0) discard; fragColor = layerColor(result); } diff --git a/packages/melonjs/src/video/webgl/shaders/tmxlayer-common.frag b/packages/melonjs/src/video/webgl/shaders/tmxlayer-common.frag index 4458270c3e..7e91ff18f1 100644 --- a/packages/melonjs/src/video/webgl/shaders/tmxlayer-common.frag +++ b/packages/melonjs/src/video/webgl/shaders/tmxlayer-common.frag @@ -12,7 +12,9 @@ // 2. walks the cells whose tile could cover it, the one drawn last first, // 3. and for each, `tryRenderCell` fetches the GID from the per-layer // index texture and samples the tileset atlas at the right sub-region. -// The first cell with a texel that is not transparent is the fragment. +// Each texel found goes behind the ones before it (`under`), until the +// fragment is opaque: the soft edge of a tile shows the tile behind it, as +// it does when the tiles are drawn one over the other. // // Index texture encoding (`RGBA8`, one cell per texel): // R = GID low byte @@ -158,6 +160,19 @@ bool tryRenderCell(int cx, int cy, vec2 worldPx, vec2 dWorldX, vec2 dWorldY, out return true; } +// A fragment is opaque from this alpha on: nothing behind it would change a +// channel by a whole step of 8 bits +const float OPAQUE = 0.996; + +// Put a texel behind what a fragment has so far, both premultiplied: what +// drawing the tiles back to front, each over the last, comes to, taken from +// the front. Returns whether the fragment is opaque now, and nothing behind +// it can show +bool under(inout vec4 color, vec4 texel) { + color += (1.0 - color.a) * texel; + return color.a >= OPAQUE; +} + // the layer's opacity and tint applied to a texel. The texel is // premultiplied, as the blending expects: the opacity scales its color as // well as its alpha. The tint colors it; its alpha is not an opacity, as on diff --git a/packages/melonjs/src/video/webgpu/shaders/tmxlayer-common.wgsl b/packages/melonjs/src/video/webgpu/shaders/tmxlayer-common.wgsl index fda81795e1..ee5758c0c4 100644 --- a/packages/melonjs/src/video/webgpu/shaders/tmxlayer-common.wgsl +++ b/packages/melonjs/src/video/webgpu/shaders/tmxlayer-common.wgsl @@ -175,6 +175,19 @@ fn tryRenderCell( return out; } +// A fragment is opaque from this alpha on: nothing behind it would change a +// channel by a whole step of 8 bits +const OPAQUE : f32 = 0.996; + +// Put a texel behind what a fragment has so far, both premultiplied: what +// drawing the tiles back to front, each over the last, comes to, taken from +// the front. Returns whether the fragment is opaque now, and nothing behind +// it can show +fn under(color : ptr, texel : vec4f) -> bool { + *color += (1.0 - (*color).a) * texel; + return (*color).a >= OPAQUE; +} + // the layer's opacity and tint applied to a texel. The texel is // premultiplied, as the blending expects: the opacity scales its color as // well as its alpha. The tint colors it; its alpha is not an opacity, as on diff --git a/packages/melonjs/src/video/webgpu/shaders/tmxlayer-isometric.wgsl b/packages/melonjs/src/video/webgpu/shaders/tmxlayer-isometric.wgsl index 8baea0fdbc..2e3b35ed7b 100644 --- a/packages/melonjs/src/video/webgpu/shaders/tmxlayer-isometric.wgsl +++ b/packages/melonjs/src/video/webgpu/shaders/tmxlayer-isometric.wgsl @@ -6,7 +6,8 @@ // map's top corner. With u = col - row and s = col + row, the cells whose // tile image covers it are a run of `u` and a run of `s`, of the lengths in // `uOverflow`, scanned s high→low then u high→low: the reverse of the order -// the CPU renderer draws in, so the FIRST opaque texel is the fragment. +// the CPU renderer draws in, each texel put behind the ones before it until +// the fragment is opaque. // bounds of the two runs: tiles up to 8 grid heights tall and 4 grid widths // wide (the layer falls back to the CPU renderer past them) @@ -35,8 +36,8 @@ fn fragment_main(in : VSOut) -> @location(0) vec4f { let spanU = i32(tmx.uOverflow.x + 0.5); let spanS = i32(tmx.uOverflow.y + 0.5); - var result : CellSample; - var found = false; + var result = vec4f(0.0); + var opaque = false; for (var j = 0; j < MAX_ROWS; j++) { if (j >= spanS) { break; @@ -49,19 +50,18 @@ fn fragment_main(in : VSOut) -> @location(0) vec4f { break; } let candidate = tryRenderCell((s + u) / 2, (s - u) / 2, worldPx, dWorldX, dWorldY); - if (candidate.hit) { - result = candidate; - found = true; + if (candidate.hit && under(&result, candidate.color)) { + opaque = true; break; } u -= 2; } - if (found) { + if (opaque) { break; } } - if (!found) { + if (result.a <= 0.0) { discard; } - return layerColor(result.color); + return layerColor(result); } diff --git a/packages/melonjs/src/video/webgpu/shaders/tmxlayer-orthogonal.wgsl b/packages/melonjs/src/video/webgpu/shaders/tmxlayer-orthogonal.wgsl index 644a16d72d..1585827ba8 100644 --- a/packages/melonjs/src/video/webgpu/shaders/tmxlayer-orthogonal.wgsl +++ b/packages/melonjs/src/video/webgpu/shaders/tmxlayer-orthogonal.wgsl @@ -26,22 +26,21 @@ fn fragment_main(in : VSOut) -> @location(0) vec4f { let overflowX = i32(tmx.uOverflow.x + 0.5); let overflowY = i32(tmx.uOverflow.y + 0.5); - var result : CellSample; - // fast path: tiles fit the cell exactly — only the geometric cell can // contain this fragment's tile if (overflowX == 0 && overflowY == 0) { - result = tryRenderCell(gx, gy, worldPx, dWorldX, dWorldY); - if (!result.hit) { + let only = tryRenderCell(gx, gy, worldPx, dWorldX, dWorldY); + if (!only.hit) { discard; } - return layerColor(result.color); + return layerColor(only.color); } - // slow path: oversized tiles. Scan candidates dy high→low, dx low→high - // and take the FIRST match — "right-down" render order puts later - // cells on top - var found = false; + // slow path: oversized tiles. Scan candidates dy high→low, dx low→high, + // front to back — "right-down" render order puts later cells on top — + // each texel behind the ones before it, until the fragment is opaque + var result = vec4f(0.0); + var opaque = false; for (var idy = 0; idy <= MAX_OVERFLOW; idy++) { let dy = MAX_OVERFLOW - idy; if (dy > overflowY) { @@ -52,18 +51,17 @@ fn fragment_main(in : VSOut) -> @location(0) vec4f { break; } let candidate = tryRenderCell(gx - dx, gy + dy, worldPx, dWorldX, dWorldY); - if (candidate.hit) { - result = candidate; - found = true; + if (candidate.hit && under(&result, candidate.color)) { + opaque = true; break; } } - if (found) { + if (opaque) { break; } } - if (!found) { + if (result.a <= 0.0) { discard; } - return layerColor(result.color); + return layerColor(result); } diff --git a/packages/melonjs/tests/helpers/tile-layer-compare.js b/packages/melonjs/tests/helpers/tile-layer-compare.js index 683d2792b0..3b3021ffb9 100644 --- a/packages/melonjs/tests/helpers/tile-layer-compare.js +++ b/packages/melonjs/tests/helpers/tile-layer-compare.js @@ -3,13 +3,14 @@ * "perTile") and through the GPU one ("shader"), with the whole engine in * between (world, camera, renderer), and compare the two frames. * - * The tiles are painted pixel by pixel, with no soft edges, and every pixel - * of every tile has a colour of its own: a tile that lands one pixel off, is - * flipped the wrong way, or shows in front of the wrong neighbour, changes - * pixels. So the two paths are held to the same picture, exactly. + * The tiles are painted pixel by pixel, and every pixel of every tile has a + * colour of its own: a tile that lands one pixel off, is flipped the wrong + * way, or shows in front of the wrong neighbour, changes pixels. With hard + * edges (the default) the two paths are held to the same picture, exactly; + * with soft ones (`alpha`), to a rounding step or two. */ import { vi } from "vitest"; -import { Application, boot, TMXTileMap } from "../../src/index.js"; +import { Application, boot, TMXTileMap, timer } from "../../src/index.js"; import { imgList } from "../../src/loader/cache.js"; import Renderer from "../../src/video/renderer.js"; import { drawOffscreen, grabFrame } from "./pixels.js"; @@ -55,8 +56,11 @@ export function inBlock(x, y, w, h, tw, th) { * @param {number} [options.columns=4] - tiles per row of the image * @param {number} [options.margin=0] - margin round the image * @param {number} [options.spacing=0] - spacing between tiles - * @param {(x: number, y: number, id: number) => boolean} [options.opaque] - + * @param {(x: number, y: number, id: number) => boolean} [options.opaque] * which pixels of a tile are opaque (all of them by default) + * @param {(x: number, y: number, id: number) => number} [options.alpha] + * how opaque each pixel is, 0 to 255, for soft edges and see-through tiles + * (in place of `opaque`) * @param {object} [options.extra] - more Tiled tileset properties * (`tileoffset`, `tiles` with animations...) * @returns {object} the tileset's Tiled JSON, without its `firstgid` @@ -70,6 +74,7 @@ export function makeTileset(options) { margin = 0, spacing = 0, opaque, + alpha, extra = {}, } = options; const rows = Math.ceil(count / columns); @@ -92,7 +97,8 @@ export function makeTileset(options) { for (let y = 0; y < th; y++) { for (let x = 0; x < tw; x++) { const o = ((oy + y) * canvas.width + ox + x) * 4; - if (opaque !== undefined && !opaque(x, y, id)) { + const a = alpha !== undefined ? alpha(x, y, id) : 255; + if (a <= 0 || (opaque !== undefined && !opaque(x, y, id))) { image.data[o + 3] = 0; image.data[o] = image.data[o + 1] = image.data[o + 2] = 0; continue; @@ -102,7 +108,7 @@ export function makeTileset(options) { image.data[o] = 40 + ((id * 53 + seed) % 180); image.data[o + 1] = 30 + ((x * 7 + id * 11) % 200); image.data[o + 2] = 30 + ((y * 5 + id * 29) % 200); - image.data[o + 3] = 255; + image.data[o + 3] = a; } } } @@ -182,6 +188,142 @@ export function makeMap(options) { }); } +/** + * The picture of a map, painted here with a 2D canvas and no engine: every + * tile of every layer, in the order Tiled draws them (rows from the top, + * each from the left), where Tiled draws them, with nothing left out for + * being out of view. What both of the engine's renderers are held to. + * + * Tiles are drawn whole, bottom-aligned on their cell and moved by their + * tileset's `tileoffset`; flipped across, down or along the diagonal (the + * last on square tiles only, where a flip is a quarter turn in place). + * Layer opacity and tint are for the caller to apply to the picture. A + * layer is drawn at the map's origin: the engine's tile layers are, whatever + * their `pos` or Tiled's layer offset. + * + * One rule here is the engine's and not Tiled's: a layer whose grid is + * wholly out of view is not drawn, though a tile taller than its cell, in + * the map's first rows, reaches above the grid and could still show. The + * engine draws what is in view going by a layer's bounds, which are its + * grid's. + * @param {object} scene - what {@link makeMap} was given + * @param {number} viewX - the view's left, in the map's pixels + * @param {number} viewY - the view's top + * @param {number} width - the view's width + * @param {number} height - the view's height + * @returns {ImageData} the picture + */ +export function reference(scene, viewX, viewY, width, height) { + const { orientation, cols, rows, tw, th, tilesets, layers } = scene; + const canvas = document.createElement("canvas"); + canvas.width = width; + canvas.height = height; + const ctx = canvas.getContext("2d", { willReadFrequently: true }); + ctx.imageSmoothingEnabled = false; + ctx.fillStyle = "rgb(16, 24, 48)"; + ctx.fillRect(0, 0, width, height); + ctx.translate(-viewX, -viewY); + + let firstgid = 1; + const sets = tilesets.map((tileset) => { + const set = { ...tileset, firstgid, image: imgList[tileset.name] }; + firstgid += tileset.tilecount; + return set; + }); + const drawTile = (raw, left, bottom) => { + const gid = raw & 0x1fffffff; + const set = sets.findLast((candidate) => { + return gid >= candidate.firstgid; + }); + const id = gid - set.firstgid; + const w = set.tilewidth; + const h = set.tileheight; + const sx = set.margin + (id % set.columns) * (w + set.spacing); + const sy = set.margin + Math.floor(id / set.columns) * (h + set.spacing); + const x = left + (set.tileoffset?.x ?? 0); + const y = bottom - h + (set.tileoffset?.y ?? 0); + ctx.save(); + ctx.translate(x + w / 2, y + h / 2); + if ((raw & FLIP_AD) !== 0) { + ctx.rotate(-Math.PI / 2); + ctx.scale(-1, 1); + } + const ad = (raw & FLIP_AD) !== 0; + if ((raw & FLIP_H) !== 0) { + ctx.scale(ad ? 1 : -1, ad ? -1 : 1); + } + if ((raw & FLIP_V) !== 0) { + ctx.scale(ad ? -1 : 1, ad ? 1 : -1); + } + ctx.drawImage(set.image, sx, sy, w, h, -w / 2, -h / 2, w, h); + ctx.restore(); + }; + + for (const layer of layers) { + if (layer.chunks === undefined) { + // the grid's bounds: an isometric map's are its diamond's + const isIso = orientation === "isometric"; + const gridWidth = isIso ? ((cols + rows) * tw) / 2 : cols * tw; + const gridHeight = isIso ? ((cols + rows) * th) / 2 : rows * th; + if ( + viewX + width <= 0 || + gridWidth <= viewX || + viewY + height <= 0 || + gridHeight <= viewY + ) { + continue; + } + } + // the layer's cells: a plain grid, or an infinite map's chunks + const cells = new Map(); + const put = (col, row, gid) => { + if (gid !== 0) { + cells.set(`${col},${row}`, gid); + } + }; + if (layer.chunks !== undefined) { + for (const chunk of layer.chunks) { + chunk.data.forEach((gid, i) => { + put( + chunk.x + (i % chunk.width), + chunk.y + Math.floor(i / chunk.width), + gid, + ); + }); + } + } else { + layer.data.forEach((gid, i) => { + put(i % cols, Math.floor(i / cols), gid); + }); + } + const ordered = [...cells.entries()].map(([key, gid]) => { + const [col, row] = key.split(",").map(Number); + return { col, row, gid }; + }); + if (orientation === "isometric") { + // rows of constant col + row, each from the left + ordered.sort((a, b) => { + return a.col + a.row - (b.col + b.row) || a.col - b.col; + }); + for (const { col, row, gid } of ordered) { + drawTile( + gid, + ((col - row - 1) * tw) / 2 + (rows * tw) / 2, + ((col + row + 2) * th) / 2, + ); + } + } else { + ordered.sort((a, b) => { + return a.row - b.row || a.col - b.col; + }); + for (const { col, row, gid } of ordered) { + drawTile(gid, col * tw, (row + 1) * th); + } + } + } + return ctx.getImageData(0, 0, width, height); +} + /** * A layer's data, filled by a function of each cell. * @param {number} cols - columns @@ -242,18 +384,28 @@ export async function makeApp(renderer, type, width = 320, height = 240) { * Put a map's layers in the world, in place of whatever was there. * @param {Application} app - the application * @param {TMXTileMap} map - the map + * @param {string} [renderMode] - a render mode to ask of every layer before + * it is activated ("prerender" needs asking then: it bakes at activation) * @returns {object[]} the map's tile layers */ -export function show(app, map) { +export function show(app, map, renderMode) { app.world.reset(); app.renderer.reset?.(); app.renderer.backgroundColor.setColor(16, 24, 48); + if (renderMode !== undefined) { + for (const layer of map.getLayers()) { + layer.renderMode = renderMode; + } + } map.addTo(app.world, true, false); + // the layers in their order now: the world sorts its children later, on + // a timer no frame of these tests waits for + app.world.sortNow(true); app.viewport.setBounds(-100000, -100000, 200000, 200000); return map.getLayers(); } -let clock = 1000; +let clock = 0; /** * Draw one frame with every layer in the given mode, and return it with how @@ -268,9 +420,12 @@ export async function drawIn(app, layers, mode, dt = 0) { for (const layer of layers) { layer.renderMode = mode; } - // the world updated (what is in view, and animated tiles when time - // passes), then drawn - clock += dt; + // time passes (animated tiles advance once per tick of the engine's + // clock), then the world is updated: what is in view, what has changed + if (dt > 0) { + clock = Math.max(clock, timer.getTime()) + dt; + timer.update(clock); + } app.world.update(dt); app.viewport.update(dt); const cpu = vi.spyOn(Renderer.prototype, "drawTileLayer"); diff --git a/packages/melonjs/tests/helpers/tile-layer-isometric-scenarios.js b/packages/melonjs/tests/helpers/tile-layer-isometric-scenarios.js new file mode 100644 index 0000000000..6c9bb42d2a --- /dev/null +++ b/packages/melonjs/tests/helpers/tile-layer-isometric-scenarios.js @@ -0,0 +1,1296 @@ +/** + * Tile layers on the GPU ("shader" render mode), isometric ones above all + * (#1897), held to the picture Tiled draws. + * + * Every scenario draws the same layers through the CPU renderer ("perTile") + * and through the GPU one, with the whole engine in between, and compares + * both frames pixel by pixel with a reference painted here with no engine + * at all (see `tile-layer-compare.js`). Where the reference does not reach + * (a faded or tinted layer, a zoomed camera, animated tiles), the two paths + * are compared with each other. + * + * The scenarios are the same on every GPU backend, so each one's spec file + * calls this with its renderer: an application with a GPU device takes the + * place of the one before it, and a spec file has its own page. + */ +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { grabFrame } from "./pixels.js"; +import { + diff, + drawIn, + drawn, + FLIP_AD, + FLIP_H, + FLIP_V, + fill, + inBlock, + makeApp, + makeMap, + makeTileset, + reference, + show, +} from "./tile-layer-compare.js"; + +const TW = 64; +const TH = 32; + +/** a tileset of isometric blocks, `tw` × `th`, on the 64 × 32 grid */ +const blocks = (tw = TW, th = TH, options = {}) => { + return makeTileset({ + tw, + th, + opaque: (x, y) => { + return inBlock(x, y, tw, th, Math.min(tw, TW), TH); + }, + ...options, + }); +}; + +/** + * a tileset of blocks with soft edges, as drawn art has: a pixel is as + * opaque as the share of its 3 × 3 neighbours that are in the block. Every + * fourth tile is see-through all over, as glass or water is + */ +const softBlocks = (tw, th, options = {}) => { + const dw = Math.min(tw, TW); + return makeTileset({ + tw, + th, + alpha: (x, y, id) => { + let inside = 0; + for (let dy = -1; dy <= 1; dy++) { + for (let dx = -1; dx <= 1; dx++) { + inside += inBlock(x + dx, y + dy, tw, th, dw, TH) ? 1 : 0; + } + } + return Math.round((inside / 9) * (id % 4 === 3 ? 120 : 255)); + }, + ...options, + }); +}; + +/** a map with most cells filled, from one tileset, and a few holes */ +const scattered = (cols, rows, count = 8, firstgid = 1) => { + return fill(cols, rows, (c, r) => { + return (c * 3 + r) % 7 === 0 ? 0 : firstgid + ((c + r * 2) % count); + }); +}; + +/** an isometric scene, on the 64 × 32 grid */ +const iso = (options) => { + return { orientation: "isometric", tw: TW, th: TH, ...options }; +}; + +const WIDTH = 320; +const HEIGHT = 240; + +/** views over a map: inside, over each edge, and scrolled part way */ +const VIEWS = [ + [0, 0], + [70, 20], + [-40, -80], + [230, 110], + [-150, 30], + [100, -200], +]; + +/** the frames' background, as `makeApp` sets it */ +const BACKGROUND = [16, 24, 48]; + +/** + * What a picture becomes when its layer is faded or tinted as a whole: each + * drawn pixel multiplied by the tint, then blended with the background. + * @param {ImageData} picture - the reference picture + * @param {number} opacity - the layer's opacity + * @param {number[]} [tint] - the layer's tint, 0 to 255 a channel + * @returns {ImageData} the picture expected + */ +const layered = (picture, opacity, tint = [255, 255, 255]) => { + const out = new ImageData(picture.width, picture.height); + for (let i = 0; i < picture.data.length; i += 4) { + const isBackground = + picture.data[i] === BACKGROUND[0] && + picture.data[i + 1] === BACKGROUND[1] && + picture.data[i + 2] === BACKGROUND[2]; + for (let c = 0; c < 3; c++) { + out.data[i + c] = isBackground + ? BACKGROUND[c] + : Math.round( + ((picture.data[i + c] * tint[c]) / 255) * opacity + + BACKGROUND[c] * (1 - opacity), + ); + } + out.data[i + 3] = 255; + } + return out; +}; + +const ALL_FLIPS = [ + 0, + FLIP_H, + FLIP_V, + FLIP_H + FLIP_V, + FLIP_AD, + FLIP_H + FLIP_AD, + FLIP_V + FLIP_AD, + FLIP_H + FLIP_V + FLIP_AD, +]; + +/** + * Declare the scenarios for one GPU backend. + * @param {number} renderer - `video.WEBGL` or `video.WEBGPU` + * @param {string} type - the `renderer.type` expected ("WebGL", "WebGPU") + */ +export function isometricScenarios(renderer, type) { + describe(`tile layers on the GPU, against the CPU renderer and a reference (${type})`, () => { + let app; + beforeAll(async () => { + app = await makeApp(renderer, type, WIDTH, HEIGHT); + }); + afterAll(() => { + app?.destroy(); + vi.restoreAllMocks(); + }); + + const need = (ctx) => { + if (app === null || app === undefined) { + ctx.skip(`${type} not available in this environment`); + } + }; + + /** + * Draw a scene both ways from each view, and expect the reference + * picture from both, the GPU path drawing alone. + * @param {object} scene - what `makeMap` takes + * @param {object} [options] + * @param {number[][]} [options.views] - where to look from + * @param {object[]} [options.layers] - the scene's layers, when + * they are in the world already (and were changed there). Without + * them the scene is put in the world here, and every layer of it is + * expected to take the GPU path of its own accord + * @param {boolean} [options.oracle=true] - false where the reference + * does not reach (a zoomed camera): the two paths are then compared + * with each other alone + * @param {(picture: ImageData) => ImageData} [options.expected] + * what the reference becomes (a faded or tinted layer) + * @param {number} [options.tolerance=0] - the largest difference of a + * channel that is not counted + * @param {number} [options.share=0] - the largest share of the pixels + * drawn that the two paths may differ by + * @returns {Promise} how many pixels were drawn, in all + */ + const same = async (scene, options = {}) => { + const { + views = VIEWS, + oracle = true, + expected, + tolerance = 0, + share = 0, + } = options; + let layers = options.layers; + if (layers === undefined) { + layers = show(app, makeMap(scene)); + for (const layer of layers) { + expect(layer.renderMode, layer.name).toBe("shader"); + } + } + let total = 0; + for (const [x, y] of views) { + app.viewport.moveTo(x, y); + const cpu = await drawIn(app, layers, "perTile"); + const gpu = await drawIn(app, layers, "shader"); + // a layer out of view is not drawn at all; one in view is + // drawn tile by tile by the CPU path, and never by the GPU one + expect(cpu.cpuDraws).toBeLessThanOrEqual(layers.length); + expect(gpu.cpuDraws, "the GPU path reaches no CPU renderer").toBe(0); + const at = `view (${x}, ${y})`; + const count = drawn(gpu.frame); + const allowed = Math.floor(count * share); + if (oracle) { + let ref = reference(scene, x, y, WIDTH, HEIGHT); + if (expected !== undefined) { + ref = expected(ref); + } + const c = diff(ref, cpu.frame, tolerance); + expect(c.different, `${at}, CPU path: ${c.first}`).toBe(0); + const g = diff(ref, gpu.frame, tolerance); + expect(g.different, `${at}, GPU path: ${g.first}`).toBe(0); + } + const d = diff(cpu.frame, gpu.frame, tolerance); + expect( + d.different, + `${at}, CPU against GPU: ${d.first}`, + ).toBeLessThanOrEqual(allowed); + total += count; + } + return total; + }; + + /** how a layer of the scene ends up drawn, and what was warned */ + const modeOf = (scene) => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + const layer = show(app, makeMap(scene))[0]; + return [layer.renderMode, warn.mock.calls.flat().join(" ")]; + } finally { + warn.mockRestore(); + } + }; + + describe("isometric: tiles of every size", () => { + for (const [label, tw, th] of [ + ["as tall as the grid (flat diamonds)", 64, 32], + ["twice as tall", 64, 64], + ["four times as tall, as the Isometric Dungeon's", 64, 128], + ["eight times as tall, the limit", 64, 256], + ["a height that is no multiple of the grid", 64, 50], + ["shorter than the grid", 64, 20], + ["narrower than the grid", 40, 64], + ["twice as wide", 128, 32], + ["four times as wide, the limit", 256, 64], + ["wider and taller, no multiple of the grid", 90, 70], + ]) { + it(label, async (ctx) => { + need(ctx); + const scene = iso({ + cols: 8, + rows: 6, + tilesets: [blocks(tw, th)], + layers: [{ data: scattered(8, 6) }], + }); + expect(await same(scene)).toBeGreaterThan(0); + }); + } + + for (const [tw, th] of [ + [64, 96], + [128, 128], + [100, 30], + ]) { + it(`${tw} × ${th} tiles that fill their whole image, so every overlap shows`, async (ctx) => { + need(ctx); + // no transparent pixel: which tile is in front decides + // every pixel where two images overlap + const scene = iso({ + cols: 7, + rows: 9, + tilesets: [makeTileset({ tw, th })], + layers: [{ data: scattered(7, 9) }], + }); + expect(await same(scene)).toBeGreaterThan(0); + }); + } + + it("on a grid of another size, and an odd one", async (ctx) => { + need(ctx); + for (const [tw, th] of [ + [32, 16], + [100, 50], + [30, 14], + [48, 48], + ]) { + const scene = { + orientation: "isometric", + cols: 9, + rows: 7, + tw, + th, + tilesets: [ + makeTileset({ + tw, + th: th * 2, + opaque: (x, y) => { + return inBlock(x, y, tw, th * 2, tw, th); + }, + }), + ], + layers: [{ data: scattered(9, 7) }], + }; + expect(await same(scene), `${tw} × ${th}`).toBeGreaterThan(0); + } + }); + }); + + describe("isometric: maps of every shape", () => { + for (const [cols, rows] of [ + [1, 1], + [1, 7], + [7, 1], + [3, 11], + [12, 4], + [20, 20], + ]) { + it(`${cols} × ${rows}`, async (ctx) => { + need(ctx); + const scene = iso({ + cols, + rows, + tilesets: [blocks(64, 64)], + layers: [ + { + data: fill(cols, rows, (c, r) => { + return 1 + ((c + r * 3) % 8); + }), + }, + ], + }); + expect(await same(scene)).toBeGreaterThan(0); + }); + } + + it("a large map, of tiles like the Isometric Dungeon's", async (ctx) => { + need(ctx); + const scene = { + orientation: "isometric", + cols: 64, + rows: 64, + tw: 128, + th: 64, + tilesets: [ + makeTileset({ + tw: 128, + th: 256, + count: 16, + columns: 8, + opaque: (x, y) => { + return inBlock(x, y, 128, 256, 128, 64); + }, + }), + ], + layers: [{ data: scattered(64, 64, 16) }], + }; + const views = [ + [4096 - 160, 0], + [4096 - 160, 2000], + [100, 2040], + [7900, 2040], + [4096, 4000], + [3000, 1500], + ]; + expect(await same(scene, { views })).toBeGreaterThan(0); + }); + + it("an empty layer draws nothing, either way", async (ctx) => { + need(ctx); + const scene = iso({ + cols: 6, + rows: 6, + tilesets: [blocks()], + layers: [ + { + data: fill(6, 6, () => { + return 0; + }), + }, + ], + }); + expect(await same(scene, { views: [[0, 0]] })).toBe(0); + }); + + it("a single tile, and tiles in the corners alone", async (ctx) => { + need(ctx); + const corners = iso({ + cols: 9, + rows: 5, + tilesets: [blocks(64, 128)], + layers: [ + { + data: fill(9, 5, (c, r) => { + return (c === 0 || c === 8) && (r === 0 || r === 4) ? 3 : 0; + }), + }, + ], + }); + expect(await same(corners)).toBeGreaterThan(0); + const one = iso({ + cols: 9, + rows: 5, + tilesets: [blocks(64, 128)], + layers: [ + { + data: fill(9, 5, (c, r) => { + return c === 4 && r === 2 ? 6 : 0; + }), + }, + ], + }); + expect(await same(one)).toBeGreaterThan(0); + }); + }); + + describe("isometric: what a tile can be", () => { + it("flipped, every way", async (ctx) => { + need(ctx); + // square tiles: a diagonal flip turns the image a quarter + const tileset = makeTileset({ + tw: 64, + th: 64, + opaque: (x, y) => { + return x + y > 20; + }, + }); + const scene = iso({ + cols: 8, + rows: 8, + tilesets: [tileset], + layers: [ + { + data: fill(8, 8, (c, r) => { + return 1 + ((c + r) % 8) + ALL_FLIPS[(c * 3 + r) % 8]; + }), + }, + ], + }); + expect(await same(scene)).toBeGreaterThan(0); + }); + + it("flipped across and down, taller than wide", async (ctx) => { + need(ctx); + const flips = [0, FLIP_H, FLIP_V, FLIP_H + FLIP_V]; + const scene = iso({ + cols: 8, + rows: 6, + tilesets: [blocks(64, 128)], + layers: [ + { + data: fill(8, 6, (c, r) => { + return 1 + ((c + r) % 8) + flips[(c + r * 3) % 4]; + }), + }, + ], + }); + expect(await same(scene)).toBeGreaterThan(0); + }); + + it("animated: each frame, as time passes", async (ctx) => { + need(ctx); + const tileset = blocks(64, 64, { + extra: { + tiles: [ + { + id: 0, + animation: [ + { tileid: 0, duration: 100 }, + { tileid: 5, duration: 100 }, + { tileid: 6, duration: 100 }, + ], + }, + { + id: 3, + animation: [ + { tileid: 3, duration: 150 }, + { tileid: 7, duration: 150 }, + ], + }, + ], + }, + }); + const layers = show( + app, + makeMap( + iso({ + cols: 8, + rows: 6, + tilesets: [tileset], + layers: [ + { + data: fill(8, 6, (c, r) => { + return 1 + ((c + r) % 4); + }), + }, + ], + }), + ), + ); + expect(layers[0].isAnimated).toBe(true); + expect(layers[0].renderMode).toBe("shader"); + app.viewport.moveTo(0, 0); + const frames = []; + for (let step = 0; step < 6; step++) { + // 60 ms a step: the two animations change at their own times + const cpu = await drawIn(app, layers, "perTile", 60); + const gpu = await drawIn(app, layers, "shader"); + expect(gpu.cpuDraws).toBe(0); + const d = diff(cpu.frame, gpu.frame); + expect(d.different, `step ${step}: ${d.first}`).toBe(0); + frames.push(gpu.frame); + } + // and the picture did change along the way + expect(diff(frames[0], frames[2]).different).toBeGreaterThan(0); + expect(diff(frames[2], frames[5]).different).toBeGreaterThan(0); + }); + + it("from a tileset with a margin and spacing", async (ctx) => { + need(ctx); + const scene = iso({ + cols: 8, + rows: 6, + tilesets: [blocks(64, 64, { margin: 3, spacing: 5 })], + layers: [{ data: scattered(8, 6) }], + }); + expect(await same(scene)).toBeGreaterThan(0); + }); + + for (const [x, y] of [ + [0, 16], + [-12, 0], + [7, -23], + // further than a tile is large: the tile shows in cells that + // are not its own, and from views its cell is not in + [0, -80], + [150, 150], + [-200, 90], + ]) { + it(`moved by a tileset tileoffset of (${x}, ${y})`, async (ctx) => { + need(ctx); + const scene = iso({ + cols: 8, + rows: 6, + tilesets: [blocks(64, 64, { extra: { tileoffset: { x, y } } })], + layers: [{ data: scattered(8, 6) }], + }); + expect(await same(scene)).toBeGreaterThan(0); + }); + } + + for (const [tw, th] of [ + [64, 32], + [64, 64], + [64, 128], + [128, 96], + ]) { + it(`with soft edges, and see-through, ${tw} × ${th}: each shows the tiles behind it`, async (ctx) => { + need(ctx); + // a texel that is not opaque is blended over the tiles + // behind it, as many as there are: one over the other + // in 8 bits a step tile by tile, in one go on the GPU, + // a rounding step or two apart + const scene = iso({ + cols: 8, + rows: 6, + tilesets: [softBlocks(tw, th)], + layers: [{ data: scattered(8, 6) }], + }); + expect(await same(scene, { tolerance: 3 })).toBeGreaterThan(0); + }); + } + + it("from the map's second tileset", async (ctx) => { + need(ctx); + // the first tileset is not used by this layer at all, and is + // of another size: nothing of it may count + const scene = iso({ + cols: 8, + rows: 6, + tilesets: [blocks(64, 32), blocks(64, 96)], + layers: [{ data: scattered(8, 6, 8, 9) }], + }); + expect(await same(scene)).toBeGreaterThan(0); + }); + + it("from a tileset smaller than another of the map's", async (ctx) => { + need(ctx); + // the other way round: the unused tileset is the large one + const scene = iso({ + cols: 8, + rows: 6, + tilesets: [blocks(128, 256), blocks(64, 48)], + layers: [{ data: scattered(8, 6, 8, 9) }], + }); + expect(await same(scene)).toBeGreaterThan(0); + }); + }); + + describe("isometric: what a layer can be", () => { + it("half transparent, its tiles side by side", async (ctx) => { + need(ctx); + // flat diamonds do not overlap: each pixel is blended once, + // a rounding step apart at most + const scene = iso({ + cols: 8, + rows: 6, + tilesets: [blocks(64, 32)], + layers: [{ data: scattered(8, 6), opacity: 0.5 }], + }); + const expected = (picture) => { + return layered(picture, 0.5); + }; + expect(await same(scene, { expected, tolerance: 1 })).toBeGreaterThan( + 0, + ); + }); + + it("half transparent, its tiles overlapping: faded as one picture", async (ctx) => { + need(ctx); + // The GPU path draws the layer flat, then fades it: what is + // behind a tile does not show through it, as with a layer + // baked into one image ("prerender"). Tile by tile, each + // tile is blended on the ones behind it instead. + const scene = iso({ + cols: 8, + rows: 6, + tilesets: [blocks(64, 128)], + layers: [{ data: scattered(8, 6), opacity: 0.5 }], + }); + const views = VIEWS.slice(0, 3); + const baked = []; + let layers = show(app, makeMap(scene), "prerender"); + for (const [x, y] of views) { + app.viewport.moveTo(x, y); + baked.push((await drawIn(app, layers, "prerender")).frame); + } + layers = show(app, makeMap(scene)); + expect(layers[0].renderMode).toBe("shader"); + for (const [i, [x, y]] of views.entries()) { + app.viewport.moveTo(x, y); + const gpu = await drawIn(app, layers, "shader"); + expect(gpu.cpuDraws).toBe(0); + const flat = layered(reference(scene, x, y, WIDTH, HEIGHT), 0.5); + const d = diff(flat, gpu.frame, 1); + expect(d.different, `view (${x}, ${y}): ${d.first}`).toBe(0); + const b = diff(baked[i], gpu.frame, 1); + expect(b.different, `as prerender, view (${x}, ${y})`).toBe(0); + expect(drawn(gpu.frame)).toBeGreaterThan(0); + } + }); + + it("tinted", async (ctx) => { + need(ctx); + const scene = iso({ + cols: 8, + rows: 6, + tilesets: [blocks(64, 128)], + layers: [{ data: scattered(8, 6), tintcolor: "#ff8040" }], + }); + const expected = (picture) => { + return layered(picture, 1, [255, 128, 64]); + }; + expect(await same(scene, { expected, tolerance: 1 })).toBeGreaterThan( + 0, + ); + }); + + it("one of several, each on a tileset of its own", async (ctx) => { + need(ctx); + // a floor of flat tiles under walls of tall ones + const scene = iso({ + cols: 8, + rows: 6, + tilesets: [blocks(64, 32), blocks(64, 128)], + layers: [ + { + data: fill(8, 6, (c, r) => { + return 1 + ((c + r) % 8); + }), + }, + { + data: fill(8, 6, (c, r) => { + return (c + r) % 3 === 0 ? 9 + ((c * 2 + r) % 8) : 0; + }), + }, + ], + }); + expect(await same(scene)).toBeGreaterThan(0); + }); + + it("one of several, on tilesets of several sizes moved by a tileoffset", async (ctx) => { + need(ctx); + const scene = iso({ + cols: 8, + rows: 6, + tilesets: [ + blocks(64, 32, { extra: { tileoffset: { x: 5, y: 9 } } }), + blocks(64, 128, { extra: { tileoffset: { x: -20, y: 40 } } }), + blocks(128, 64), + ], + layers: [ + { data: scattered(8, 6) }, + { data: scattered(8, 6, 8, 9) }, + { + data: fill(8, 6, (c, r) => { + return (c + r) % 4 === 1 ? 17 + ((c + r * 3) % 8) : 0; + }), + }, + ], + }); + expect(await same(scene)).toBeGreaterThan(0); + }); + + it("of an infinite map, starting left of and above the origin", async (ctx) => { + need(ctx); + const chunk = (x, y) => { + return { + x, + y, + width: 4, + height: 4, + data: fill(4, 4, (c, r) => { + return (c + r + x) % 5 === 0 ? 0 : 1 + ((c + r * 2) % 8); + }), + }; + }; + const scene = iso({ + cols: 8, + rows: 8, + tilesets: [blocks(64, 64)], + extra: { infinite: true }, + layers: [ + { + startx: -4, + starty: -4, + width: 12, + height: 8, + data: undefined, + chunks: [chunk(-4, -4), chunk(0, -4), chunk(4, 0), chunk(0, 0)], + }, + ], + }); + const layers = show(app, makeMap(scene)); + expect(layers[0].startx).toBe(-4); + expect(layers[0].renderMode).toBe("shader"); + const views = [ + [0, 0], + [-200, -150], + [150, -100], + [-60, 40], + ]; + expect(await same(scene, { views, layers })).toBeGreaterThan(0); + }); + }); + + describe("isometric: what a camera can do", () => { + const tall = () => { + return iso({ + cols: 10, + rows: 8, + tilesets: [blocks(64, 128)], + layers: [{ data: scattered(10, 8) }], + }); + }; + + it("look from anywhere, and from where nothing shows", async (ctx) => { + need(ctx); + const scene = tall(); + const layers = show(app, makeMap(scene)); + const views = []; + for (let x = -400; x <= 700; x += 137) { + for (let y = -300; y <= 400; y += 97) { + views.push([x, y]); + } + } + expect(await same(scene, { views, layers })).toBeGreaterThan(0); + // far off the map: nothing, either way + const far = [ + [5000, 5000], + [-5000, 0], + ]; + expect(await same(scene, { views: far, layers })).toBe(0); + }); + + it("scroll a pixel at a time, across a tile", async (ctx) => { + need(ctx); + const scene = tall(); + const layers = show(app, makeMap(scene)); + const views = []; + for (let step = 0; step <= 64; step += 3) { + views.push([40 + step, 10 + Math.floor(step / 2)]); + } + expect(await same(scene, { views, layers })).toBeGreaterThan(0); + }); + + it("stand between pixels", async (ctx) => { + need(ctx); + // the camera's position is rounded to whole pixels when the + // world is drawn: the reference is painted from there + const scene = tall(); + const layers = show(app, makeMap(scene)); + for (const [x, y] of [ + [10.5, 7.25], + [-33.75, 60.5], + [120.1, -45.9], + ]) { + app.viewport.moveTo(x, y); + const cpu = await drawIn(app, layers, "perTile"); + const gpu = await drawIn(app, layers, "shader"); + expect(gpu.cpuDraws).toBe(0); + const d = diff(cpu.frame, gpu.frame); + expect(d.different, `view (${x}, ${y}): ${d.first}`).toBe(0); + expect(drawn(gpu.frame)).toBeGreaterThan(0); + } + }); + + it("be shifted by its offset, as a shake does", async (ctx) => { + need(ctx); + const scene = tall(); + app.viewport.offset.set(13, -9); + try { + expect(await same(scene, { oracle: false })).toBeGreaterThan(0); + } finally { + app.viewport.offset.set(0, 0); + } + }); + + for (const zoom of [2, 3]) { + it(`zoom ${zoom} times`, async (ctx) => { + need(ctx); + const scene = tall(); + app.viewport.zoom = zoom; + try { + expect(await same(scene, { oracle: false })).toBeGreaterThan(0); + } finally { + app.viewport.zoom = 1; + } + }); + } + + for (const zoom of [0.5, 1.5]) { + it(`zoom ${zoom} times, a texel apart at most but for a few pixels`, async (ctx) => { + need(ctx); + // Tiles are sampled without smoothing: where a screen + // pixel's centre falls exactly between two texels, a + // quad per tile and one quad for the layer do not round + // the same way. A texel apart is within the tolerance + // (colours change by 7 a texel at most here); the + // outlines of the tiles, where the next texel is another + // tile's, are the share left. An orthogonal layer's two + // paths are as far apart. + const scene = tall(); + app.viewport.zoom = zoom; + try { + expect( + await same(scene, { oracle: false, tolerance: 8, share: 0.06 }), + ).toBeGreaterThan(0); + } finally { + app.viewport.zoom = 1; + } + }); + } + }); + + describe("isometric: tiles changed while the game runs", () => { + /** set a cell in the world and in the scene the reference reads */ + const setCell = (scene, layer, col, row, gid) => { + scene.layers[0].data[row * scene.cols + col] = gid; + if (gid === 0) { + layer.clearTile(col, row); + } else { + layer.setTile(layer.getTileById(gid, col, row), col, row); + } + }; + + it("setTile and clearTile show at once", async (ctx) => { + need(ctx); + const scene = iso({ + cols: 8, + rows: 6, + tilesets: [blocks(64, 128)], + layers: [{ data: scattered(8, 6) }], + }); + const layers = show(app, makeMap(scene)); + const layer = layers[0]; + const options = { views: [[0, 0]], layers }; + await same(scene, options); + const before = (await drawIn(app, layers, "shader")).frame; + + setCell(scene, layer, 3, 2, 5); + setCell(scene, layer, 0, 5, 2 + FLIP_H); + await same(scene, options); + const set = (await drawIn(app, layers, "shader")).frame; + expect(diff(before, set).different).toBeGreaterThan(0); + + setCell(scene, layer, 3, 2, 0); + setCell(scene, layer, 7, 0, 0); + await same(scene, options); + const cleared = (await drawIn(app, layers, "shader")).frame; + expect(diff(set, cleared).different).toBeGreaterThan(0); + expect(layer.renderMode).toBe("shader"); + }); + + it("every cell changed, one frame after the other", async (ctx) => { + need(ctx); + const scene = iso({ + cols: 6, + rows: 5, + tilesets: [blocks(64, 96)], + layers: [{ data: scattered(6, 5) }], + }); + const layers = show(app, makeMap(scene)); + const options = { views: [[0, 0]], layers }; + for (let step = 0; step < 4; step++) { + for (let row = 0; row < 5; row++) { + for (let col = 0; col < 6; col++) { + const gid = + (col + row + step) % 4 === 0 ? 0 : 1 + ((col * step + row) % 8); + setCell(scene, layers[0], col, row, gid); + } + } + await same(scene, options); + } + expect(layers[0].renderMode).toBe("shader"); + }); + + it("an empty layer takes its tileset from the first tile set", async (ctx) => { + need(ctx); + const scene = iso({ + cols: 6, + rows: 6, + tilesets: [blocks(64, 32), blocks(64, 96)], + layers: [ + { + data: fill(6, 6, () => { + return 0; + }), + }, + ], + }); + const layers = show(app, makeMap(scene)); + const layer = layers[0]; + expect(layer._shaderTileset).toBeUndefined(); + setCell(scene, layer, 2, 3, 12); + setCell(scene, layer, 3, 3, 10); + expect(layer.renderMode).toBe("shader"); + expect(layer._shaderTileset.firstgid).toBe(9); + expect(await same(scene, { views: [[0, 0]], layers })).toBeGreaterThan( + 0, + ); + }); + + it("a tile of a second tileset moves the layer back to the CPU renderer", async (ctx) => { + need(ctx); + const scene = iso({ + cols: 6, + rows: 6, + tilesets: [blocks(64, 32), blocks(64, 96)], + layers: [{ data: scattered(6, 6) }], + }); + const layers = show(app, makeMap(scene)); + const layer = layers[0]; + expect(layer.renderMode).toBe("shader"); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + // one of the same tileset: nothing changes + setCell(scene, layer, 1, 1, 3); + expect(layer.renderMode).toBe("shader"); + expect(warn).not.toHaveBeenCalled(); + // one of the other + setCell(scene, layer, 2, 2, 10); + expect(layer.renderMode).toBe("perTile"); + expect(warn.mock.calls.flat().join(" ")).toMatch( + /more than one tileset/, + ); + } finally { + warn.mockRestore(); + } + // and the layer is drawn right from there on + app.viewport.moveTo(0, 0); + app.world.update(0); + app.repaint(); + app.draw(); + const frame = await grabFrame(app.renderer); + const d = diff(reference(scene, 0, 0, WIDTH, HEIGHT), frame); + expect(d.different, d.first).toBe(0); + }); + + it("a tile that is not square, flipped diagonally, does too", async (ctx) => { + need(ctx); + const scene = iso({ + cols: 6, + rows: 6, + tilesets: [blocks(64, 96)], + layers: [{ data: scattered(6, 6) }], + }); + const layers = show(app, makeMap(scene)); + const layer = layers[0]; + expect(layer.renderMode).toBe("shader"); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + setCell(scene, layer, 1, 1, 3 + FLIP_H + FLIP_V); + expect(layer.renderMode).toBe("shader"); + setCell(scene, layer, 2, 2, 4 + FLIP_AD); + expect(layer.renderMode).toBe("perTile"); + expect(warn.mock.calls.flat().join(" ")).toMatch( + /not square, flipped diagonally/, + ); + } finally { + warn.mockRestore(); + } + }); + }); + + describe("isometric: layers the GPU path does not take", () => { + it("tiles of two tilesets in one layer", (ctx) => { + need(ctx); + const [mode, said] = modeOf( + iso({ + cols: 6, + rows: 6, + tilesets: [blocks(64, 32), blocks(64, 96)], + layers: [ + { + data: fill(6, 6, (c, r) => { + return 1 + ((c + r) % 16); + }), + }, + ], + }), + ); + expect(mode).toBe("perTile"); + expect(said).toMatch(/more than one tileset in an isometric layer/); + }); + + it("tiles past the size the shader walks", (ctx) => { + need(ctx); + const [tall, saidTall] = modeOf( + iso({ + cols: 4, + rows: 4, + tilesets: [blocks(64, 257)], + layers: [{ data: scattered(4, 4) }], + }), + ); + expect(tall).toBe("perTile"); + expect(saidTall).toMatch(/larger than the shader's limit/); + const [wide] = modeOf( + iso({ + cols: 4, + rows: 4, + tilesets: [makeTileset({ tw: 257, th: 32 })], + layers: [{ data: scattered(4, 4) }], + }), + ); + expect(wide).toBe("perTile"); + }); + + it("a tileset drawn at the map's grid size", (ctx) => { + need(ctx); + const [mode, said] = modeOf( + iso({ + cols: 4, + rows: 4, + tilesets: [blocks(64, 64, { extra: { tilerendersize: "grid" } })], + layers: [{ data: scattered(4, 4) }], + }), + ); + expect(mode).toBe("perTile"); + expect(said).toMatch(/tilerendersize/); + }); + + it("a tile that is not square, flipped diagonally", (ctx) => { + need(ctx); + const [mode, said] = modeOf( + iso({ + cols: 4, + rows: 4, + tilesets: [blocks(64, 96)], + layers: [ + { + data: fill(4, 4, (c, r) => { + return 1 + ((c + r) % 8) + (c === 2 && r === 1 ? FLIP_AD : 0); + }), + }, + ], + }), + ); + expect(mode).toBe("perTile"); + expect(said).toMatch(/not square, flipped diagonally/); + }); + + it("a staggered map, still", (ctx) => { + need(ctx); + const [mode, said] = modeOf({ + orientation: "staggered", + cols: 4, + rows: 4, + tw: TW, + th: TH, + tilesets: [blocks()], + layers: [{ data: scattered(4, 4) }], + extra: { staggeraxis: "y", staggerindex: "odd" }, + }); + expect(mode).toBe("perTile"); + expect(said).toMatch(/no gpu renderer supported yet for "staggered"/); + }); + + it("any layer, with gpuTilemap off", (ctx) => { + need(ctx); + app.world.gpuTilemap = false; + try { + const [mode] = modeOf( + iso({ + cols: 4, + rows: 4, + tilesets: [blocks()], + layers: [{ data: scattered(4, 4) }], + }), + ); + expect(mode).toBe("perTile"); + } finally { + app.world.gpuTilemap = true; + } + }); + }); + + describe("orthogonal: the same picture, both ways", () => { + const ortho = (options) => { + return { orientation: "orthogonal", tw: 32, th: 32, ...options }; + }; + const ORTHO_VIEWS = [ + [0, 0], + [40, 30], + [-50, -60], + [200, 150], + [-250, 20], + [90, -150], + ]; + + it("tiles the size of the grid, flipped every way", async (ctx) => { + need(ctx); + const scene = ortho({ + cols: 12, + rows: 10, + tilesets: [makeTileset({ tw: 32, th: 32 })], + layers: [ + { + data: fill(12, 10, (c, r) => { + return (c * 3 + r) % 5 === 0 + ? 0 + : 1 + ((c + r * 2) % 8) + ALL_FLIPS[(c + r) % 8]; + }), + }, + ], + }); + expect(await same(scene, { views: ORTHO_VIEWS })).toBeGreaterThan(0); + }); + + // tiles larger than the grid stand on their cell and reach above + // it and to its right: above the map's first row and right of + // its last column too + for (const [tw, th] of [ + [32, 64], + [32, 128], + [64, 32], + [96, 96], + [48, 40], + ]) { + it(`${tw} × ${th} tiles on a 32 × 32 grid`, async (ctx) => { + need(ctx); + const scene = ortho({ + cols: 10, + rows: 8, + tilesets: [ + makeTileset({ + tw, + th, + opaque: (x, y) => { + return (x + y) % 9 !== 0 || x < 4; + }, + }), + ], + layers: [{ data: scattered(10, 8) }], + }); + expect(await same(scene, { views: ORTHO_VIEWS })).toBeGreaterThan(0); + }); + } + + it("layers on tilesets of several sizes", async (ctx) => { + need(ctx); + const scene = ortho({ + cols: 10, + rows: 8, + tilesets: [ + makeTileset({ tw: 32, th: 32 }), + makeTileset({ + tw: 64, + th: 96, + opaque: (x, y) => { + return x > 10 && y > 6; + }, + }), + ], + layers: [ + { data: scattered(10, 8) }, + { + data: fill(10, 8, (c, r) => { + return (c + r * 2) % 4 === 0 ? 9 + ((c + r) % 8) : 0; + }), + }, + ], + }); + expect(await same(scene, { views: ORTHO_VIEWS })).toBeGreaterThan(0); + }); + + it("tiles larger than the grid, with soft edges and see-through", async (ctx) => { + need(ctx); + for (const [tw, th] of [ + [64, 64], + [32, 96], + [80, 48], + ]) { + const scene = ortho({ + cols: 10, + rows: 8, + tilesets: [ + makeTileset({ + tw, + th, + alpha: (x, y, id) => { + // a soft border, and every third tile + // see-through all over + const edge = Math.min(x, y, tw - 1 - x, th - 1 - y); + const a = id % 3 === 2 ? 110 : 255; + return Math.round(a * Math.min(1, (edge + 1) / 4)); + }, + }), + ], + layers: [{ data: scattered(10, 8) }], + }); + expect( + await same(scene, { views: ORTHO_VIEWS, tolerance: 3 }), + `${tw} × ${th}`, + ).toBeGreaterThan(0); + } + }); + + it("a tile that is not square, flipped diagonally, is left to the CPU renderer", (ctx) => { + need(ctx); + const [mode, said] = modeOf( + ortho({ + cols: 4, + rows: 4, + tilesets: [makeTileset({ tw: 32, th: 64 })], + layers: [ + { + data: fill(4, 4, (c, r) => { + return 1 + ((c + r) % 8) + (c === 1 && r === 2 ? FLIP_AD : 0); + }), + }, + ], + }), + ); + expect(mode).toBe("perTile"); + expect(said).toMatch(/not square, flipped diagonally/); + }); + }); + + it("a level change frees what the GPU path kept for its layers", async (ctx) => { + need(ctx); + const scene = iso({ + cols: 6, + rows: 6, + tilesets: [blocks(64, 64)], + layers: [{ data: scattered(6, 6) }], + }); + const layers = show(app, makeMap(scene)); + const options = { views: [[0, 0]], layers }; + await same(scene, options); + const gpu = + app.renderer._tmxGPURenderers?.get("isometric") ?? + app.renderer.tmxRenderers?.get("isometric"); + expect(gpu.resources.size).toBe(1); + app.renderer.reset(); + expect(gpu.resources.size).toBe(0); + // and the layer draws again after it + expect(await same(scene, options)).toBeGreaterThan(0); + }); + }); +} diff --git a/packages/melonjs/tests/texture-mipmap.spec.js b/packages/melonjs/tests/texture-mipmap.spec.js index 9e11496a88..9d9a64dcc8 100644 --- a/packages/melonjs/tests/texture-mipmap.spec.js +++ b/packages/melonjs/tests/texture-mipmap.spec.js @@ -23,13 +23,17 @@ import { createAtlas, TextureAtlas } from "../src/video/texture/atlas.js"; import WebGPULitQuadBatcher from "../src/video/webgpu/batchers/lit_quad_batcher.js"; import WebGPUQuadBatcher from "../src/video/webgpu/batchers/quad_batcher.js"; import WebGPUTMXRenderer from "../src/video/webgpu/renderers/tmxlayer/orthogonal.js"; -import tmxlayerWGSL from "../src/video/webgpu/shaders/tmxlayer.wgsl"; +import tmxlayerCommonWGSL from "../src/video/webgpu/shaders/tmxlayer-common.wgsl"; +import tmxlayerOrthogonalWGSL from "../src/video/webgpu/shaders/tmxlayer-orthogonal.wgsl"; import { getWebGLRenderer, releaseWebGLRenderer, } from "./helpers/webgl-context.js"; import { createMockWebGPURenderer } from "./helpers/webgpu-mock-renderer.js"; +// the orthogonal tile shader's module, as its renderer puts it together +const tmxlayerWGSL = `${tmxlayerCommonWGSL}\n${tmxlayerOrthogonalWGSL}`; + const SIZE = 64; // a checkerboard of single texels, `size` square, at (x, y) of `ctx` @@ -582,8 +586,10 @@ describe("linear-mipmap texture filter (WebGPU, mock renderer)", () => { expect(code).toContain( "return texel * tmx.uOpacity * vec4f(tmx.uTint.rgb, 1.0);", ); - expect(code.match(/layerColor\(result\.color\)/g)).toHaveLength(2); - expect(code).not.toMatch(/result\.color\.a \* tmx\.uOpacity/); + // every color the fragment stage returns goes through it: the + // single cell of the fast path, and what the cells add up to + expect(code.match(/return layerColor\(/g)).toHaveLength(2); + expect(code).not.toMatch(/\.a \* tmx\.uOpacity/); }); it("keeps each sample half a texel inside its tile, mipmaps or not", () => { diff --git a/packages/melonjs/tests/tmxlayer-shader-isometric.spec.js b/packages/melonjs/tests/tmxlayer-shader-isometric.spec.js new file mode 100644 index 0000000000..e8363cc0f4 --- /dev/null +++ b/packages/melonjs/tests/tmxlayer-shader-isometric.spec.js @@ -0,0 +1,8 @@ +/** + * Isometric tile layers on the GPU, on WebGL: see + * `helpers/tile-layer-isometric-scenarios.js`. + */ +import { video } from "../src/index.js"; +import { isometricScenarios } from "./helpers/tile-layer-isometric-scenarios.js"; + +isometricScenarios(video.WEBGL, "WebGL"); diff --git a/packages/melonjs/tests/webgpu_tmxlayer_isometric.spec.js b/packages/melonjs/tests/webgpu_tmxlayer_isometric.spec.js new file mode 100644 index 0000000000..c4ae0bf009 --- /dev/null +++ b/packages/melonjs/tests/webgpu_tmxlayer_isometric.spec.js @@ -0,0 +1,9 @@ +/** + * Isometric tile layers on the GPU, on WebGPU: see + * `helpers/tile-layer-isometric-scenarios.js`. Skipped, visibly, where the + * browser has no WebGPU adapter. + */ +import { video } from "../src/index.js"; +import { isometricScenarios } from "./helpers/tile-layer-isometric-scenarios.js"; + +isometricScenarios(video.WEBGPU, "WebGPU"); From b5f1e0dfe4235a8dcee9b6764b96379da07bbfb3 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 01:42:04 +0000 Subject: [PATCH 04/51] GPU tile layers: review fixes, shared orientation module, benchmark (#1897) From an independent review of the isometric GPU path: - a grid of odd size, and a blend mode other than the normal one, are left to the CPU renderer: the first stands half the tiles half a pixel off, the second shows where tiles overlap - a tileset image with no margin after its last tiles was counted a column short (the orthogonal path too) - a layer asked for "shader" by hand after it was found unfit for it is drawn tile by tile, where an isometric one drew nothing - the tile shader declares full precision itself, and finds a tile's place in the atlas in whole numbers Faster per fragment: what sampling needs of a fragment is taken once instead of for every cell tried, a cell whose tile cannot reach the fragment is dropped before its index is fetched, and the isometric walk skips the rows outside the map. What differs with a map's orientation is in one module for both backends (`gpu/tmxlayer_orientation.js`: the region, the tilesets, the shader's limits, which the layer's checks read too), so each backend has one renderer class and the shader text. `tests/tmxlayer_bench.spec.js` measures the main thread's share of a frame tile by tile and on the GPU path, orthogonal and isometric. Changelog, API docs and the tilemaps skill. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- packages/melonjs/CHANGELOG.md | 14 ++ .../melonjs/skills/melonjs-tilemaps/SKILL.md | 30 ++- packages/melonjs/src/application/settings.ts | 20 +- packages/melonjs/src/level/tiled/TMXLayer.js | 53 +++-- packages/melonjs/src/physics/world.js | 25 ++- ...ayer_region.js => tmxlayer_orientation.js} | 113 +++++++++- .../webgl/renderers/tmxlayer/isometric.js | 54 ----- .../webgl/renderers/tmxlayer/orthogonal.js | 33 --- .../webgl/renderers/tmxlayer/tmxlayer.js | 99 ++++----- .../webgl/shaders/isometric-tmxlayer.frag | 19 +- .../webgl/shaders/orthogonal-tmxlayer.frag | 11 +- .../video/webgl/shaders/tmxlayer-common.frag | 97 +++++---- .../melonjs/src/video/webgl/webgl_renderer.js | 22 +- .../webgpu/renderers/tmxlayer/isometric.js | 54 ----- .../webgpu/renderers/tmxlayer/orthogonal.js | 33 --- .../webgpu/renderers/tmxlayer/tmxlayer.js | 90 ++++---- .../video/webgpu/shaders/tmxlayer-common.wgsl | 82 +++---- .../webgpu/shaders/tmxlayer-isometric.wgsl | 20 +- .../webgpu/shaders/tmxlayer-orthogonal.wgsl | 10 +- .../src/video/webgpu/webgpu_renderer.js | 23 +- .../tests/helpers/tile-layer-compare.js | 9 +- .../helpers/tile-layer-isometric-scenarios.js | 104 +++++++++ .../melonjs/tests/sprite-frame-clamp.spec.js | 4 +- packages/melonjs/tests/texture-mipmap.spec.js | 6 +- .../melonjs/tests/tmxlayer-shader.spec.js | 4 +- packages/melonjs/tests/tmxlayer_bench.spec.js | 201 ++++++++++++++++++ .../melonjs/tests/webgpu_tmxlayer.spec.js | 100 ++++++++- 27 files changed, 863 insertions(+), 467 deletions(-) rename packages/melonjs/src/video/gpu/{tmxlayer_region.js => tmxlayer_orientation.js} (59%) delete mode 100644 packages/melonjs/src/video/webgl/renderers/tmxlayer/isometric.js delete mode 100644 packages/melonjs/src/video/webgl/renderers/tmxlayer/orthogonal.js delete mode 100644 packages/melonjs/src/video/webgpu/renderers/tmxlayer/isometric.js delete mode 100644 packages/melonjs/src/video/webgpu/renderers/tmxlayer/orthogonal.js create mode 100644 packages/melonjs/tests/tmxlayer_bench.spec.js diff --git a/packages/melonjs/CHANGELOG.md b/packages/melonjs/CHANGELOG.md index 3419546c1e..774ae5ab0b 100644 --- a/packages/melonjs/CHANGELOG.md +++ b/packages/melonjs/CHANGELOG.md @@ -5,7 +5,21 @@ ### Added - Transitions: a mask transition can be shaped like an image or a `Sprite`, close on the player with `center`, and fill the shape with `invert`, on `state.transition`, `MaskEffect` and `Trigger` ([#1399](https://github.com/melonjs/melonJS/issues/1399)) +### Changed +- Tiled: an isometric tile layer with an `opacity` below 1 fades as one flat picture on WebGL and WebGPU, where each tile was faded over the ones behind it and showed through the one in front. Set the layer's `renderMode` to `"perTile"` for the look it had + +### Performance +- Tiled: isometric tile layers are drawn by the GPU on WebGL and WebGPU, as orthogonal ones are: one quad for the layer, its tiles found by the fragment shader, in place of a quad per tile in view found and placed in JavaScript every frame. On a 100 × 100 map with about 4000 tiles in view, drawing the layer takes under **0.1 ms** of main-thread time a frame, down from about **2 ms**, and no longer grows with the number of tiles shown. A layer takes this path by itself when all its tiles come from one tileset, up to 4 grid widths wide and 8 grid heights tall (a `tileoffset`, flipped and animated tiles, and `setTile` are all fine); any other is drawn as before, and the console says why ([#1897](https://github.com/melonjs/melonJS/issues/1897)) +- Tiled: a reminder that orthogonal tile layers have been drawn this way since 19.4, with the same gain (about 1.9 ms down to under 0.1 ms for 3600 tiles in view). A layer that is not says why in the console when it is activated: most often a tileset with a `tileoffset`, a collection of images, or the Canvas renderer. + ### Fixed +- Tiled, GPU tile layers: the soft edge of a tile larger than the grid shows the tile behind it; it was drawn over the background instead, a thin outline round such tiles +- Tiled, GPU tile layers: tiles larger than the grid are drawn whole above the map's first row and right of its last column, where they were cut off +- Tiled, GPU tile layers: a tileset with a `margin` whose image stops at its last tiles, with no margin after them, draws the right tiles; they were counted a column or a row short +- Tiled, GPU tile layers: a layer with a tile that is not square, flipped diagonally, is drawn tile by tile; the shader drew such a tile wrong +- Tiled, GPU tile layers: the shader runs at full precision whatever `highPrecisionShader` says; at a lower one a phone could misplace the tiles of a large map +- Tiled, isometric maps drawn tile by tile: tiles of a tileset larger than the map's first one, or moved by a `tileoffset`, went missing along the edges of the view +- Tiled, orthogonal maps drawn tile by tile: tiles more than two cells tall went missing along the bottom of the view - `NineSliceSprite` blinks with `flicker()`, as a `Sprite` does; it ignored it - glTF: a model compressed with Draco or meshopt, which the loader cannot decode, says so in the console, naming the extension, instead of failing on an accessor error that did not mention it diff --git a/packages/melonjs/skills/melonjs-tilemaps/SKILL.md b/packages/melonjs/skills/melonjs-tilemaps/SKILL.md index 51481cf2af..bb5933e1a6 100644 --- a/packages/melonjs/skills/melonjs-tilemaps/SKILL.md +++ b/packages/melonjs/skills/melonjs-tilemaps/SKILL.md @@ -453,11 +453,28 @@ per-pixel GID lookup in the fragment shader. It requires **all** of: - a renderer that reports GPU tile-layer support (WebGL 2 / WebGPU — not Canvas), - `world.gpuTilemap !== false` (the `gpuTilemap` application setting, default `true`), -- an **orthogonal** layer — isometric, hexagonal, staggered and oblique always - fall back, -- no collection-of-image tileset, no non-zero `tileoffset`, a tileset tile - render size of "Tile size" (`tilerendersize`, not "Map grid size"), and tile - overflow within the shader's 4-cell limit. +- an **orthogonal** or **isometric** layer — hexagonal, staggered and oblique + always fall back, +- no collection-of-image tileset, and a tileset tile render size of "Tile + size" (`tilerendersize`, not "Map grid size"), +- on an orthogonal map: no non-zero `tileoffset`, and tiles that reach at most + 4 cells past their own, +- on an isometric map: every tile of the layer from **one tileset** (tiles + overlap, and their order is kept within a tileset, not across two: split + floor and walls into a layer each, which a map usually does already), tiles + at most 4 grid widths wide and 8 grid heights tall, a grid of even size + (64 × 32, not 65 × 33), and the normal blend mode. A `tileoffset` is fine, +- no tile that is not square flipped diagonally (rotated, in Tiled). + +A tile set at run time with `setTile` that breaks one of these moves the layer +back to `"perTile"`, with a warning. The two paths draw the same picture, with +one difference: a layer with `opacity` below 1 is faded as one flat picture on +the shader path (as `preRender` does), where tile by tile each tile is faded +over the ones behind it, which shows where tiles overlap. + +The gain is main-thread time: tile by tile, every tile in view is found and +placed in JavaScript each frame (about 2 ms for 4000 tiles); the shader path +draws one quad whatever is in view. When a layer falls back, melonJS `console.warn`s the reason each time the layer is activated (once per page when the renderer has no GPU tile support at @@ -509,6 +526,9 @@ layer into the offscreen-bake path instead. | changing tiles at runtime is slow on a pre-rendered layer | outside an orthogonal map whose tiles fit their cells, a changed tile re-bakes the whole layer before it next draws: keep layers you edit often off `preRender` | | thin lines between tiles on the Canvas renderer, with smoothing on | filtering blends in the next tile of the tileset or its spacing, which a canvas cannot prevent: set `antiAlias: false`, or `preRender` the layer. WebGL and WebGPU keep each tile to itself | | tilemap slow on some machines | layer fell back off the shader path — check the console warning for the reason | +| an isometric layer warns `tiles of more than one tileset in an isometric layer` and is slow | the shader path draws an isometric layer with one tileset: put the tiles of each tileset on a layer of their own, or pack them into one tileset | +| a half-transparent isometric layer of tall tiles looks flatter than before 20.17 | on the shader path a layer fades as one picture, and a tile no longer shows through the one in front: set that layer's `renderMode` to `"perTile"` (a `renderMode` custom property in Tiled) for the old look | +| the soft edges of tiles larger than the grid showed a thin dark outline on the shader path | before 20.17 the edge of such a tile was not blended over the tile behind it: update | ## Related skills diff --git a/packages/melonjs/src/application/settings.ts b/packages/melonjs/src/application/settings.ts index 6010e6f77b..f4733069dc 100644 --- a/packages/melonjs/src/application/settings.ts +++ b/packages/melonjs/src/application/settings.ts @@ -476,15 +476,17 @@ export type ApplicationSettings = { physic: PhysicsType; /** - * Enable the GPU procedural shader path for orthogonal tile layers - * (backends advertising `renderer.supportsShaderTileLayers` — WebGL 2 - * and WebGPU). When `true` (default), eligible layers render via a - * single quad per tileset + a fragment shader doing per-fragment GID - * lookup, bypassing the per-tile draw loop entirely. Layers that - * don't qualify (Canvas renderer, non-orthogonal, - * collection-of-image tilesets, tilerendersize "grid", non-zero - * tileoffset, oversampled beyond the shader's overflow window) fall - * back to the legacy path automatically. + * Enable the GPU procedural shader path for orthogonal and isometric + * tile layers (backends advertising + * `renderer.supportsShaderTileLayers` — WebGL 2 and WebGPU). When + * `true` (default), eligible layers render via a single quad per + * tileset + a fragment shader doing per-fragment GID lookup, bypassing + * the per-tile draw loop entirely. Layers that don't qualify (Canvas + * renderer, a staggered, hexagonal or oblique map, collection-of-image + * tilesets, tilerendersize "grid", tiles larger than the shader walks; + * on an orthogonal map a non-zero tileoffset, on an isometric one + * tiles of several tilesets in one layer) fall back to the legacy path + * automatically, saying why in the console. * Set to `false` to disable globally. * @default true */ diff --git a/packages/melonjs/src/level/tiled/TMXLayer.js b/packages/melonjs/src/level/tiled/TMXLayer.js index 98585e4196..a18991eff2 100644 --- a/packages/melonjs/src/level/tiled/TMXLayer.js +++ b/packages/melonjs/src/level/tiled/TMXLayer.js @@ -5,6 +5,7 @@ import { boundsPool } from "../../physics/bounds.ts"; import Renderable from "../../renderable/renderable.js"; import CanvasRenderer from "../../video/canvas/canvas_renderer"; import { createCanvas } from "../../video/canvas_factory.js"; +import { TMX_ORIENTATIONS } from "../../video/gpu/tmxlayer_orientation.js"; import { TMX_CLEAR_BIT_MASK, TMX_FLIP_AD, @@ -26,10 +27,14 @@ const FLIP_H_BIT = 1 << 0; const FLIP_V_BIT = 1 << 1; const FLIP_AD_BIT = 1 << 2; -// The largest tiles the isometric shader path draws, in grid cells: the -// bounds of the loops in `isometric-tmxlayer.frag` and its WGSL twin. -const ISOMETRIC_MAX_TILE_WIDTHS = 4; -const ISOMETRIC_MAX_TILE_HEIGHTS = 8; +// The largest tiles the shader path draws: the bounds of the loops of the +// fragment shaders, which are declared from the same numbers. An orthogonal +// tile can reach so many cells past its own; an isometric one be so many +// grid cells wide and tall. +const ORTHOGONAL_MAX_OVERFLOW = TMX_ORIENTATIONS.orthogonal.limits.MAX_OVERFLOW; +const ISOMETRIC_MAX_TILE_WIDTHS = TMX_ORIENTATIONS.isometric.limits.MAX_COLS; +const ISOMETRIC_MAX_TILE_HEIGHTS = + TMX_ORIENTATIONS.isometric.limits.MAX_ROWS / 2; const ISOMETRIC_ONE_TILESET = "tiles of more than one tileset in an isometric layer"; // A diagonal flip turns a tile a quarter: one that is not square then covers @@ -229,6 +234,14 @@ export default class TMXLayer extends Renderable { * @ignore */ this.maxTileOffset = { x: 0, y: 0 }; + /** + * The one tileset an isometric layer on the shader path draws with: + * `undefined` for an empty layer (it takes the tileset of the first + * tile set), `null` for a layer that path cannot draw, or that was + * not checked for it. + * @ignore + */ + this._shaderTileset = null; for (let i = 0; i < this.tilesets.length; i++) { const tileset = this.tilesets.getTilesetByIndex(i); this.maxTileOffset.x = Math.max( @@ -385,7 +398,7 @@ export default class TMXLayer extends Renderable { /** * How this layer is rendered. Resolved by `onActivateEvent` to one of: - * - `"shader"` — WebGL2 procedural shader path (single quad per tileset, fragment GID lookup) + * - `"shader"` — GPU procedural shader path, on WebGL 2 and WebGPU, for orthogonal and isometric maps (single quad per tileset, fragment GID lookup) * - `"prerender"`— offscreen-canvas bake at activation, blitted as one drawImage per frame * - `"perTile"` — per-frame loop, one drawImage per visible tile * @@ -722,7 +735,7 @@ export default class TMXLayer extends Renderable { // support oversized tiles (tile dim > cell dim) drawn bottom-aligned. // Loop bound is MAX_OVERFLOW + 1; anything beyond would silently clip, // so refuse the shader path for layers with extreme oversampling. - const MAX_OVERFLOW_CELLS = 4; + const MAX_OVERFLOW_CELLS = ORTHOGONAL_MAX_OVERFLOW; for (const ts of this.tilesets.tilesets) { if (ts.isCollection) { return { ok: false, reason: "collection-of-image tileset" }; @@ -795,11 +808,22 @@ export default class TMXLayer extends Renderable { * @internal */ _checkIsometricShaderEligibility() { - /** - * the one tileset an isometric layer on the shader path draws with - * @ignore - */ - this._shaderTileset = undefined; + this._shaderTileset = null; + // Half the tiles of a grid of odd size stand half a pixel off. Tile + // by tile, each is moved to a whole pixel; the shader has one quad + // for all of them, and would draw those a pixel away. + if (this.tilewidth % 2 !== 0 || this.tileheight % 2 !== 0) { + return { ok: false, reason: "an isometric grid of odd size" }; + } + // Tiles overlap, and the shader draws the layer flat, then blends it + // as one picture: where tile by tile each tile is blended over the + // ones behind it, which shows with every mode but the normal one. + if (this.blendMode !== "normal") { + return { + ok: false, + reason: `blend mode "${this.blendMode}" on an isometric layer`, + }; + } const data = this.layerData; let tileset = null; for (let i = 0; i < data.length; i += 2) { @@ -811,17 +835,17 @@ export default class TMXLayer extends Renderable { tileset = this.tilesets.getTilesetByGid(gid); } } - // an empty layer: its tileset is the first one a tile is set from if (tileset !== null) { const reason = this._isometricTilesetReason(tileset); if (reason !== undefined) { return { ok: false, reason }; } - this._shaderTileset = tileset; } if (this._hasDiagonalFlipNotSquare()) { return { ok: false, reason: DIAGONAL_NOT_SQUARE }; } + // an empty layer: its tileset is the first one a tile is set from + this._shaderTileset = tileset ?? undefined; return { ok: true }; } @@ -869,7 +893,7 @@ export default class TMXLayer extends Renderable { this.orientation === "isometric" && this._shaderTileset?.contains(gid) !== true ) { - if (this._shaderTileset !== undefined) { + if (this._shaderTileset) { reason = ISOMETRIC_ONE_TILESET; } else { // an empty layer takes its tileset from its first tile @@ -891,6 +915,7 @@ export default class TMXLayer extends Renderable { `melonJS: layer "${this.name}" back to the legacy tile renderer (${reason})`, ); this.renderMode = "perTile"; + this._shaderTileset = null; } } diff --git a/packages/melonjs/src/physics/world.js b/packages/melonjs/src/physics/world.js index a16706e07b..d26e8eb103 100644 --- a/packages/melonjs/src/physics/world.js +++ b/packages/melonjs/src/physics/world.js @@ -215,17 +215,20 @@ export default class World extends Container { this.preRender = false; /** - * Enable the WebGL2 procedural shader path for orthogonal tile - * layers. When `true` (default), eligible layers render via a - * single quad per tileset + a fragment shader doing per-pixel GID - * lookup — bypassing the per-tile drawImage loop entirely. - * Supported features on the shader path: animated tiles, all - * three flip bits (H/V/AD), per-layer opacity/tint/blend mode, - * and oversized bottom-aligned tiles up to 4 cells of overflow. - * Layers that don't qualify (Canvas/WebGL1, non-orthogonal, - * collection-of-image tilesets, non-zero `tileoffset`, or tile - * overflow beyond the shader's 4-cell limit) fall back to the - * legacy path automatically. Set to `false` to disable globally. + * Enable the GPU procedural shader path (WebGL 2 and WebGPU) for + * orthogonal and isometric tile layers. When `true` (default), + * eligible layers render via a single quad per tileset + a + * fragment shader doing per-pixel GID lookup — bypassing the + * per-tile drawImage loop entirely. + * Supported features on the shader path: animated tiles, flipped + * tiles, per-layer opacity and tint, and tiles larger than the + * grid: up to 4 cells of overflow on an orthogonal map, up to 4 + * grid widths by 8 grid heights on an isometric one. + * Layers that don't qualify (Canvas, a staggered, hexagonal or + * oblique map, collection-of-image tilesets, larger tiles; on an + * orthogonal map a non-zero `tileoffset`, on an isometric one + * tiles of several tilesets in one layer) fall back to the legacy + * path automatically. Set to `false` to disable globally. * @type {boolean} * @default true */ diff --git a/packages/melonjs/src/video/gpu/tmxlayer_region.js b/packages/melonjs/src/video/gpu/tmxlayer_orientation.js similarity index 59% rename from packages/melonjs/src/video/gpu/tmxlayer_region.js rename to packages/melonjs/src/video/gpu/tmxlayer_orientation.js index 34ffe5318b..13b08fdbf1 100644 --- a/packages/melonjs/src/video/gpu/tmxlayer_region.js +++ b/packages/melonjs/src/video/gpu/tmxlayer_orientation.js @@ -1,11 +1,19 @@ /** - * The part of a tile layer a view shows, as the GPU tile layer renderers - * need it: the same on WebGL and WebGPU, so both read it from here. + * What the GPU tile layer renderers need to know of a map orientation, the + * same on WebGL and WebGPU: each backend brings the shader text, and reads + * the rest from here ({@link TMX_ORIENTATIONS}). * - * A region is the quad to draw (`x`, `y`, `width`, `height`, in the layer's - * pixels), the shader's `uVisibleStart` and `uVisibleSize` (the quad's - * corner and size, in the units the orientation's fragment shader works in) - * and its `uOverflow`. + * - `region`: the part of a layer a view shows, for the tiles of one + * tileset. A region is the quad to draw (`x`, `y`, `width`, `height`, in + * the layer's pixels), the shader's `uVisibleStart` and `uVisibleSize` + * (the quad's corner and size, in the units the orientation's fragment + * shader works in) and its `uOverflow`. + * - `tilesetsOf`: the tilesets a layer is drawn with, one pass each. + * - `draws`: whether a layer can be drawn at all (its `renderMode` can be + * set to "shader" by hand, after it was found unfit for it). + * - `limits`: the bounds of the loops of the orientation's fragment shader, + * declared in it as constants of the same names, and what a layer is + * checked against before it takes the GPU path. * @import { default as TMXLayer } from "../../level/tiled/TMXLayer.js"; */ @@ -154,3 +162,96 @@ export function isometricRegion(layer, rect, tileset, out) { out.overflowY = Math.ceil(tileset.tileheight / halfHeight); return true; } + +/** + * How many tiles a tileset's image has across: counted from the margin, a + * tile plus the spacing apart, the last column going without its outer + * margin, as Tiled and the tileset's own atlas count them. + * @param {object} tileset - the tileset + * @returns {number} the number of columns + * @ignore + * @internal + */ +export function atlasColumns(tileset) { + return Math.max( + 1, + Math.floor( + (tileset.image.width - tileset.margin + tileset.spacing) / + (tileset.tilewidth + tileset.spacing), + ), + ); +} + +/** + * How many tiles a tileset's image has down (see {@link atlasColumns}). + * @param {object} tileset - the tileset + * @returns {number} the number of rows + * @ignore + * @internal + */ +export function atlasRows(tileset) { + return Math.max( + 1, + Math.floor( + (tileset.image.height - tileset.margin + tileset.spacing) / + (tileset.tileheight + tileset.spacing), + ), + ); +} + +/** + * The map orientations the GPU tile layer renderers draw. + * @ignore + * @internal + */ +export const TMX_ORIENTATIONS = { + orthogonal: { + region: orthogonalRegion, + /** + * every tileset of the map: a pass shows the tiles of its own + * @param {TMXLayer} layer - the layer + * @returns {object[]} the tilesets + */ + tilesetsOf(layer) { + return layer.tilesets.tilesets; + }, + draws() { + return true; + }, + // how many cells a tile can reach past its own, across and up + limits: { MAX_OVERFLOW: 4 }, + }, + isometric: { + region: isometricRegion, + /** + * The one tileset an isometric layer draws with: its tiles overlap, + * and a pass keeps the order of the tiles of one tileset, not across + * two (`layer._shaderTileset`, found by the layer when it is checked + * for this path). + * @param {TMXLayer} layer - the layer + * @param {object[]} scratch - an array to fill + * @returns {object[]} that tileset, or none for an empty layer + */ + tilesetsOf(layer, scratch) { + scratch.length = 0; + if (layer._shaderTileset) { + scratch.push(layer._shaderTileset); + } + return scratch; + }, + /** + * not a layer with no tileset to draw with: one that was never + * checked, or whose tiles come from several (`null`; an empty layer + * has `undefined`, and draws nothing) + * @param {TMXLayer} layer - the layer + * @returns {boolean} whether the layer can be drawn + */ + draws(layer) { + return layer._shaderTileset !== null; + }, + // the cells whose image can reach a pixel: rows of them, half a + // grid height apart, and in each, cells a grid width apart. So + // tiles up to MAX_ROWS / 2 grid heights tall, MAX_COLS wide + limits: { MAX_ROWS: 16, MAX_COLS: 4 }, + }, +}; diff --git a/packages/melonjs/src/video/webgl/renderers/tmxlayer/isometric.js b/packages/melonjs/src/video/webgl/renderers/tmxlayer/isometric.js deleted file mode 100644 index 3483c8e8ce..0000000000 --- a/packages/melonjs/src/video/webgl/renderers/tmxlayer/isometric.js +++ /dev/null @@ -1,54 +0,0 @@ -import { isometricRegion } from "../../../gpu/tmxlayer_region.js"; -import isometricTMXLayerFragment from "../../shaders/isometric-tmxlayer.frag"; -import TMXLayerGPURenderer from "./tmxlayer.js"; - -/** - * additional imports for TypeScript - * @import { default as TMXLayer } from "../../../../level/tiled/TMXLayer.js"; - * @import { default as WebGLRenderer } from "../../webgl_renderer.js"; - */ - -/** - * GPU-accelerated renderer for isometric TMX tile layers (WebGL2): the - * shared {@link TMXLayerGPURenderer}, with an isometric grid's geometry. - * The quad covers the view, and the shader works in pixels. - * - * Isometric tiles overlap, and the shader keeps the one drawn last among - * those of ONE tileset: a layer takes this path only when all its tiles - * come from the same one (`layer._shaderTileset`, set by the layer when it - * is found eligible). - * @ignore - * @internal - */ -export default class IsometricTMXLayerGPURenderer extends TMXLayerGPURenderer { - /** - * @param {WebGLRenderer} renderer - the WebGL renderer instance - */ - constructor(renderer) { - super(renderer, isometricTMXLayerFragment); - this._tilesets = []; - } - - /** - * @ignore - * @internal - */ - _region(layer, rect, tileset, out) { - return isometricRegion(layer, rect, tileset, out); - } - - /** - * The one tileset an isometric layer on this path draws with. - * @param {TMXLayer} layer - the layer - * @returns {object[]} that tileset, or none for an empty layer - * @ignore - * @internal - */ - _tilesetsOf(layer) { - this._tilesets.length = 0; - if (layer._shaderTileset) { - this._tilesets.push(layer._shaderTileset); - } - return this._tilesets; - } -} diff --git a/packages/melonjs/src/video/webgl/renderers/tmxlayer/orthogonal.js b/packages/melonjs/src/video/webgl/renderers/tmxlayer/orthogonal.js deleted file mode 100644 index f6e6f6fd74..0000000000 --- a/packages/melonjs/src/video/webgl/renderers/tmxlayer/orthogonal.js +++ /dev/null @@ -1,33 +0,0 @@ -import { orthogonalRegion } from "../../../gpu/tmxlayer_region.js"; -import orthogonalTMXLayerFragment from "../../shaders/orthogonal-tmxlayer.frag"; -import TMXLayerGPURenderer from "./tmxlayer.js"; - -/** - * additional imports for TypeScript - * @import { default as TMXLayer } from "../../../../level/tiled/TMXLayer.js"; - * @import { default as WebGLRenderer } from "../../webgl_renderer.js"; - */ - -/** - * GPU-accelerated renderer for orthogonal TMX tile layers (WebGL2): the - * shared {@link TMXLayerGPURenderer}, with an orthogonal grid's geometry. - * The quad covers the cells in view, and the shader works in cells. - * @ignore - * @internal - */ -export default class OrthogonalTMXLayerGPURenderer extends TMXLayerGPURenderer { - /** - * @param {WebGLRenderer} renderer - the WebGL renderer instance - */ - constructor(renderer) { - super(renderer, orthogonalTMXLayerFragment); - } - - /** - * @ignore - * @internal - */ - _region(layer, rect, tileset, out) { - return orthogonalRegion(layer, rect, tileset, out); - } -} diff --git a/packages/melonjs/src/video/webgl/renderers/tmxlayer/tmxlayer.js b/packages/melonjs/src/video/webgl/renderers/tmxlayer/tmxlayer.js index b740e8591f..0ad3e0fbf0 100644 --- a/packages/melonjs/src/video/webgl/renderers/tmxlayer/tmxlayer.js +++ b/packages/melonjs/src/video/webgl/renderers/tmxlayer/tmxlayer.js @@ -1,6 +1,13 @@ -import { createRegion } from "../../../gpu/tmxlayer_region.js"; +import { + atlasColumns, + atlasRows, + createRegion, + TMX_ORIENTATIONS, +} from "../../../gpu/tmxlayer_orientation.js"; import { BufferTextureResource } from "../../../texture/resource.js"; import GLShader from "../../glshader.js"; +import isometricFragment from "../../shaders/isometric-tmxlayer.frag"; +import orthogonalFragment from "../../shaders/orthogonal-tmxlayer.frag"; import tmxLayerVertex from "../../shaders/tmxlayer.vert"; import tmxLayerCommonFragment from "../../shaders/tmxlayer-common.frag"; @@ -10,6 +17,12 @@ import tmxLayerCommonFragment from "../../shaders/tmxlayer-common.frag"; * @import { default as WebGLRenderer } from "../../webgl_renderer.js"; */ +// each orientation's part of the fragment shader, appended to the shared one +const FRAGMENTS = { + orthogonal: orthogonalFragment, + isometric: isometricFragment, +}; + // Default `uTint` when the layer has no tint set. Module-scoped so the // fallback path doesn't allocate per frame. const DEFAULT_TINT = new Float32Array([1, 1, 1, 1]); @@ -24,10 +37,10 @@ const DEFAULT_TINT = new Float32Array([1, 1, 1, 1]); * and re-uploaded only when `layer.dataVersion` changes (mutations from * `setTile`/`clearTile`). * - * An orientation's renderer extends this one with the two things that - * differ: its part of the fragment shader (where a cell's tile is, and which - * cells can cover a fragment), and {@link TMXLayerGPURenderer#_region}, the - * part of the layer a view shows. + * There is one of these per map orientation drawn (see `TMX_ORIENTATIONS` + * in `gpu/tmxlayer_orientation.js`). Two things differ from one to the next: + * its part of the fragment shader (where a cell's tile is, and which cells + * can cover a fragment), and the part of a layer a view shows. * * The per-layer index texture is a `BufferTextureResource` flowing * through the standard `TextureCache` / batcher path — same lane as @@ -48,11 +61,23 @@ const DEFAULT_TINT = new Float32Array([1, 1, 1, 1]); export default class TMXLayerGPURenderer { /** * @param {WebGLRenderer} renderer - the WebGL renderer instance - * @param {string} fragment - the orientation's part of the fragment - * shader, appended to the shared one + * @param {string} orientation - the map orientation to draw, one of + * `TMX_ORIENTATIONS` */ - constructor(renderer, fragment) { + constructor(renderer, orientation) { this.renderer = renderer; + /** + * what differs with the map's orientation + * @ignore + * @internal + */ + this.orientation = TMX_ORIENTATIONS[orientation]; + // the bounds of the shader's loops, declared ahead of its own part + const limits = Object.entries(this.orientation.limits) + .map(([name, value]) => { + return `const int ${name} = ${value};`; + }) + .join("\n"); this.gl = renderer.gl; // Standalone `GLShader` (not `ShaderEffect`) so we own both the // vertex and the fragment source — they're paired in GLSL ES 3.00, @@ -66,7 +91,7 @@ export default class TMXLayerGPURenderer { this.shader = new GLShader( renderer.gl, tmxLayerVertex, - `${tmxLayerCommonFragment}\n${fragment}`, + `${tmxLayerCommonFragment}\n${limits}\n${FRAGMENTS[orientation]}`, renderer.shaderPrecision, ); // per-layer `BufferTextureResource`. `Map` (not `WeakMap`) so we @@ -98,43 +123,19 @@ export default class TMXLayerGPURenderer { */ this._indexUnit = 0; /** - * what {@link TMXLayerGPURenderer#_region} fills: the quad to draw, + * what the orientation's `region` fills: the quad to draw, * in the layer's pixels, and what the shader needs to find a * fragment's place in the layer from its place in the quad * @ignore * @internal */ this._regionScratch = createRegion(); - } - - /** - * The part of a layer a view shows, for the tiles of one tileset: the - * quad to draw (`x`, `y`, `width`, `height`, in the layer's pixels), the - * shader's `uVisibleStart` and `uVisibleSize` (the quad's corner and - * size, in the units its fragment shader works in) and `uOverflow`. - * @param {TMXLayer} layer - the layer - * @param {object} rect - the visible viewport rect (world coords) - * @param {object} tileset - the tileset whose tiles are drawn - * @param {object} out - the region to fill - * @returns {boolean} false when the view shows nothing of the layer - * @abstract - * @ignore - * @internal - */ - // eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars - _region(layer, rect, tileset, out) { - return false; - } - - /** - * The tilesets a layer is drawn with, one pass each. - * @param {TMXLayer} layer - the layer - * @returns {object[]} the tilesets - * @ignore - * @internal - */ - _tilesetsOf(layer) { - return layer.tilesets.tilesets; + /** + * what the orientation's `tilesetsOf` fills, when it needs to + * @ignore + * @internal + */ + this._tilesetsScratch = []; } /** @@ -374,7 +375,7 @@ export default class TMXLayerGPURenderer { // one pass per tileset — the shader's uGidRange uniform + discard // hides cells outside the active tileset's GID range - const tilesets = this._tilesetsOf(layer); + const tilesets = this.orientation.tilesetsOf(layer, this._tilesetsScratch); for (let i = 0; i < tilesets.length; i++) { const tileset = tilesets[i]; // skip collection-of-image tilesets (caller's eligibility check @@ -384,7 +385,7 @@ export default class TMXLayerGPURenderer { continue; } // the view shows nothing of this tileset's tiles - if (!this._region(layer, rect, tileset, region)) { + if (!this.orientation.region(layer, rect, tileset, region)) { continue; } batcher ??= this._begin(layer); @@ -399,19 +400,13 @@ export default class TMXLayerGPURenderer { // atlas geometry (margin + spacing) — number of tiles per row/col // in the atlas image - const atlasCols = Math.max( - 1, - Math.floor((atlasW - margin * 2 + spacing) / (tsW + spacing)), - ); - const atlasRows = Math.max( - 1, - Math.floor((atlasH - margin * 2 + spacing) / (tsH + spacing)), - ); + const atlasCols = atlasColumns(tileset); + const atlasRowCount = atlasRows(tileset); // per-tileset animation lookup. Only allocated/bound for // tilesets that actually have animated tiles — static tilesets // pay neither a texture-unit nor an upload. - const tileCount = atlasCols * atlasRows; + const tileCount = atlasCols * atlasRowCount; const animEntry = this._getOrUpdateAnimLookup(tileset, tileCount); if (animEntry !== undefined) { const animUnit = batcher.uploadTexture( @@ -434,7 +429,7 @@ export default class TMXLayerGPURenderer { } this._setV2("uTileSize", tsW, tsH); - this._setV2("uTilesetCols", atlasCols, atlasRows); + this._setV2("uTilesetCols", atlasCols, atlasRowCount); this._setV2("uInvTilesetSize", 1 / atlasW, 1 / atlasH); this._setV4("uTilesetMargin", margin, margin, spacing, spacing); this._setV2("uVisibleStart", region.startX, region.startY); diff --git a/packages/melonjs/src/video/webgl/shaders/isometric-tmxlayer.frag b/packages/melonjs/src/video/webgl/shaders/isometric-tmxlayer.frag index befc47ff0c..ea42ad41a0 100644 --- a/packages/melonjs/src/video/webgl/shaders/isometric-tmxlayer.frag +++ b/packages/melonjs/src/video/webgl/shaders/isometric-tmxlayer.frag @@ -21,10 +21,9 @@ // opaque texel ends it at once, and the soft edge of a tile shows the tiles // behind it. -// bounds of the two runs: tiles up to 8 grid heights tall and 4 grid widths -// wide (the layer falls back to the CPU renderer past them) -const int MAX_ROWS = 16; -const int MAX_COLS = 4; +// `MAX_ROWS` and `MAX_COLS`, the bounds of the two runs, are declared ahead +// of this file (see `TMX_ORIENTATIONS` in `gpu/tmxlayer_orientation.js`): a +// layer of larger tiles is left to the CPU renderer. // the left of the cell's diamond, and as far above its bottom as the tile // is tall @@ -37,8 +36,7 @@ vec2 tileOrigin(int cx, int cy) { void main(void) { vec2 worldPx = uVisibleStart + vRegion * uVisibleSize; - vec2 dWorldX = dFdx(worldPx); - vec2 dWorldY = dFdy(worldPx); + Footprint fp = footprint(worldPx); vec2 halfCell = uCellSize * 0.5; // the rightmost and the lowest cell whose image can reach the fragment @@ -50,14 +48,17 @@ void main(void) { vec4 result = vec4(0.0); vec4 texel; bool opaque = false; - for (int j = 0; j < MAX_ROWS; j++) { - if (j >= spanS) break; + // rows past the map's last one, or before its first, hold no cell: most + // of a fragment's run, along the bottom of the map and above its top + int sLast = int(uMapSize.x) + int(uMapSize.y) - 2; + for (int j = max(sMax - sLast, 0); j < MAX_ROWS; j++) { int s = sMax - j; + if (j >= spanS || s < 0) break; // the first u of this row's parity, then every other one int u = uMax - ((uMax + s) & 1); for (int i = 0; i < MAX_COLS; i++) { if (uMax - u >= spanU) break; - if (tryRenderCell((s + u) / 2, (s - u) / 2, worldPx, dWorldX, dWorldY, texel)) { + if (tryRenderCell((s + u) / 2, (s - u) / 2, worldPx, fp, texel)) { if (under(result, texel)) { opaque = true; break; diff --git a/packages/melonjs/src/video/webgl/shaders/orthogonal-tmxlayer.frag b/packages/melonjs/src/video/webgl/shaders/orthogonal-tmxlayer.frag index 3e29c4a3ad..ef36adad72 100644 --- a/packages/melonjs/src/video/webgl/shaders/orthogonal-tmxlayer.frag +++ b/packages/melonjs/src/video/webgl/shaders/orthogonal-tmxlayer.frag @@ -15,7 +15,9 @@ // ones before it until the fragment is opaque. `uOverflow` is how many // cells a tile reaches past its own, across and up. -const int MAX_OVERFLOW = 4; +// `MAX_OVERFLOW`, the bound of both loops, is declared ahead of this file +// (see `TMX_ORIENTATIONS` in `gpu/tmxlayer_orientation.js`): a layer whose +// tiles reach further is left to the CPU renderer. // a tile is bottom-aligned on its cell, and left-aligned vec2 tileOrigin(int cx, int cy) { @@ -29,8 +31,7 @@ void main(void) { vec2 tileCoord = uVisibleStart + vRegion * uVisibleSize; vec2 geomCell = floor(tileCoord); vec2 worldPx = tileCoord * uCellSize; - vec2 dWorldX = dFdx(worldPx); - vec2 dWorldY = dFdy(worldPx); + Footprint fp = footprint(worldPx); int gx = int(geomCell.x); int gy = int(geomCell.y); @@ -42,7 +43,7 @@ void main(void) { // Fast path: tiles fit the cell exactly (the common case) — only the // geometric cell can contain this fragment's tile. if (overflowX == 0 && overflowY == 0) { - if (!tryRenderCell(gx, gy, worldPx, dWorldX, dWorldY, result)) { + if (!tryRenderCell(gx, gy, worldPx, fp, result)) { discard; } fragColor = layerColor(result); @@ -59,7 +60,7 @@ void main(void) { if (dy > overflowY) continue; for (int dx = 0; dx <= MAX_OVERFLOW; dx++) { if (dx > overflowX) break; - if (tryRenderCell(gx - dx, gy + dy, worldPx, dWorldX, dWorldY, texel)) { + if (tryRenderCell(gx - dx, gy + dy, worldPx, fp, texel)) { if (under(result, texel)) { opaque = true; break; diff --git a/packages/melonjs/src/video/webgl/shaders/tmxlayer-common.frag b/packages/melonjs/src/video/webgl/shaders/tmxlayer-common.frag index 7e91ff18f1..79f5bc8f6e 100644 --- a/packages/melonjs/src/video/webgl/shaders/tmxlayer-common.frag +++ b/packages/melonjs/src/video/webgl/shaders/tmxlayer-common.frag @@ -1,4 +1,11 @@ #version 300 es +// Full precision, whatever the application asked for its other shaders +// (`highPrecisionShader`): a fragment's position is in pixels of the map, +// and a gid has 16 bits, which the 16 bits a phone can give a `mediump` +// value do not hold past a small map. The engine's `setPrecision` step +// leaves a shader that declares its own alone. +precision highp float; +precision highp int; // Fragment shader for the TMX layer GPU renderers (WebGL2 / GLSL ES 3.00): // the part every map orientation shares. An orientation's own file follows @@ -38,12 +45,6 @@ // it bypasses interpolation, so the integer byte values come out // unmolested even on a normalized-float sampler. -// The engine's `setPrecision` step injects precision declarations for -// float and int after the `#version` line, using whatever precision the -// renderer was configured with (`highPrecisionShader` setting on the -// Application). Individual shader files don't hardcode precision so the -// engine-wide preference applies. - in vec2 vRegion; in vec4 vColor; @@ -72,24 +73,55 @@ out vec4 fragColor; // image, in the same pixels as `worldPx`. Defined per orientation. vec2 tileOrigin(int cx, int cy); +// What sampling the atlas needs of a fragment, the same for every cell +// tried for it: taken once, in `main`, where control flow is still uniform. +// +// `gradX` / `gradY` are the atlas coordinate's screen derivatives. The atlas +// coordinate itself jumps from one tile to the next, so its own derivatives +// would pick a tiny mip level along every tile edge; a texel of the atlas is +// a world pixel, so the world's derivatives are the atlas's. +// +// `inset` keeps a sample half a texel of the level it reads inside its tile, +// so filtering never blends in the next tile of the tileset, or the spacing +// around it, along the tile's edge: a seam between two tiles (never past the +// tile's centre). Without mipmaps that level is the full-size art; under +// them, the deepest level read is the next one up once the level is past a +// whole number, by more than a rounding error: drawn at its size, the +// derivatives are 1 give or take a few ulps, and level 0 it is. Sampled +// nearest, the sample stays in the same texel +struct Footprint { + vec2 gradX; + vec2 gradY; + vec2 inset; +}; + +Footprint footprint(vec2 worldPx) { + vec2 dWorldX = dFdx(worldPx); + vec2 dWorldY = dFdy(worldPx); + float lod = ceil(log2(max(max(length(dWorldX), length(dWorldY)), 1.0)) - 0.01); + vec2 inset = min(vec2(0.5 * exp2(lod * uMipmaps)), uTileSize * 0.5); + return Footprint(dWorldX * uInvTilesetSize, dWorldY * uInvTilesetSize, inset); +} + // Try to render the tile at cell (cx, cy) for the current fragment. // Returns true and writes the sampled color to `outColor` when the cell // contains a visible, in-range tile whose pixel covers this fragment. // Identical logic for both fast and slow paths — GLSL inlines this // trivially so there's no function-call overhead at runtime. -// -// `dWorldX` / `dWorldY` are the world position's screen derivatives, taken -// in `main` where control flow is still uniform: the atlas coordinate jumps -// from one tile to the next, so its own derivatives would pick a tiny mip -// level along every tile edge. A texel of the atlas is a world pixel, so -// the world's derivatives are the atlas's. -bool tryRenderCell(int cx, int cy, vec2 worldPx, vec2 dWorldX, vec2 dWorldY, out vec4 outColor) { +bool tryRenderCell(int cx, int cy, vec2 worldPx, Footprint fp, out vec4 outColor) { int mapW = int(uMapSize.x); int mapH = int(uMapSize.y); if (cx < 0 || cx >= mapW || cy < 0 || cy >= mapH) { return false; } + // the cell's tile does not reach the fragment: known before anything + // is fetched + vec2 inTile = (worldPx - tileOrigin(cx, cy)) / uTileSize; + if (inTile.x < 0.0 || inTile.x >= 1.0 || inTile.y < 0.0 || inTile.y >= 1.0) { + return false; + } + // `texelFetch` skips filtering — the 8-bit channel values come back // as normalized floats, decoded to byte ints below vec4 cellF = texelFetch(uTileIndex, ivec2(cx, cy), 0); @@ -100,11 +132,6 @@ bool tryRenderCell(int cx, int cy, vec2 worldPx, vec2 dWorldX, vec2 dWorldY, out return false; } - vec2 inTile = (worldPx - tileOrigin(cx, cy)) / uTileSize; - if (inTile.x < 0.0 || inTile.x >= 1.0 || inTile.y < 0.0 || inTile.y >= 1.0) { - return false; - } - // flip mask + axis-swap trick: see TMX shader-path flip spec. // AD performs a transpose; with AD set, H and V swap their effective // axes (matches the legacy `buildFlipTransform`). @@ -129,30 +156,16 @@ bool tryRenderCell(int cx, int cy, vec2 worldPx, vec2 dWorldX, vec2 dWorldY, out localId = int(animTexel.r) | (int(animTexel.g) << 8); } - float row = floor(float(localId) / uTilesetCols.x); - float col = float(localId) - row * uTilesetCols.x; + // the tile's place in the atlas, in whole numbers: a float division + // may land a hair under the row it should + int cols = int(uTilesetCols.x); + int row = localId / cols; vec2 tileOriginPx = uTilesetMargin.xy - + vec2(col, row) * (uTileSize + uTilesetMargin.zw); + + vec2(float(localId - row * cols), float(row)) * (uTileSize + uTilesetMargin.zw); vec2 texelPx = tileOriginPx + inTile * uTileSize; - // keep the sample half a texel of the level it reads inside the tile, - // so filtering never blends in the next tile of the tileset, or the - // spacing around it, along the tile's edge: a seam between two tiles - // (never past the tile's centre). Without mipmaps that level is the - // full-size art; under them, the deepest level read is the next one up - // once the level is past a whole number, by more than a rounding error: - // drawn at its size, the derivatives are 1 give or take a few ulps, and - // level 0 it is. Sampled nearest, the sample stays in the same texel - float lod = ceil(log2(max(max(length(dWorldX), length(dWorldY)), 1.0)) - 0.01); - vec2 inset = min(vec2(0.5 * exp2(lod * uMipmaps)), uTileSize * 0.5); - texelPx = clamp(texelPx, tileOriginPx + inset, tileOriginPx + uTileSize - inset); - vec2 texelUV = texelPx * uInvTilesetSize; - - vec4 sampled = textureGrad( - uSampler, - texelUV, - dWorldX * uInvTilesetSize, - dWorldY * uInvTilesetSize - ); + texelPx = clamp(texelPx, tileOriginPx + fp.inset, tileOriginPx + uTileSize - fp.inset); + + vec4 sampled = textureGrad(uSampler, texelPx * uInvTilesetSize, fp.gradX, fp.gradY); if (sampled.a <= 0.0) { return false; } @@ -161,8 +174,8 @@ bool tryRenderCell(int cx, int cy, vec2 worldPx, vec2 dWorldX, vec2 dWorldY, out } // A fragment is opaque from this alpha on: nothing behind it would change a -// channel by a whole step of 8 bits -const float OPAQUE = 0.996; +// channel by half a step of 8 bits +const float OPAQUE = 0.998; // Put a texel behind what a fragment has so far, both premultiplied: what // drawing the tiles back to front, each over the last, comes to, taken from diff --git a/packages/melonjs/src/video/webgl/webgl_renderer.js b/packages/melonjs/src/video/webgl/webgl_renderer.js index 173d773aff..1ffd68dcfd 100644 --- a/packages/melonjs/src/video/webgl/webgl_renderer.js +++ b/packages/melonjs/src/video/webgl/webgl_renderer.js @@ -24,6 +24,7 @@ import { import AmbientLightEffect from "../effects/ambientlight.js"; import BlendEffect from "../effects/blendEffect.js"; import RadialGradientEffect from "../effects/radialGradient.js"; +import { TMX_ORIENTATIONS } from "../gpu/tmxlayer_orientation.js"; import { Gradient } from "../gradient.js"; import Renderer from "./../renderer.js"; import RenderTargetPool from "../rendertarget/render_target_pool.js"; @@ -46,8 +47,7 @@ import PrimitiveBatcher from "./batchers/primitive_batcher"; import QuadBatcher from "./batchers/quad_batcher"; import { markContextLost } from "./buffer/deletable.js"; import { createLightUniformScratch, packLights } from "./lighting/pack.ts"; -import IsometricTMXLayerGPURenderer from "./renderers/tmxlayer/isometric.js"; -import OrthogonalTMXLayerGPURenderer from "./renderers/tmxlayer/orthogonal.js"; +import TMXLayerGPURenderer from "./renderers/tmxlayer/tmxlayer.js"; import { WebGLTextureStore } from "./texture/store.js"; import { resolveMaxTextures } from "./utils/maxtextures.js"; import { getMaxShaderPrecision } from "./utils/precision.js"; @@ -72,15 +72,6 @@ import { GLSamplerCache } from "./utils/samplercache.js"; */ // reusable constants for 2D→3D matrix operations -/** - * the GPU tile layer renderer of each map orientation that has one - * @ignore - */ -const TMX_GPU_RENDERERS = { - orthogonal: OrthogonalTMXLayerGPURenderer, - isometric: IsometricTMXLayerGPURenderer, -}; - const _tempMatrix = new Matrix3d(); // pre-allocated matrices for blitEffect (avoids per-frame allocation) @@ -1458,7 +1449,9 @@ export default class WebGLRenderer extends Renderer { drawTileLayer(layer, rect) { if (layer.renderMode === "shader") { const gpu = this._getTMXGPURendererFor(layer.orientation); - if (gpu !== undefined) { + // a layer asked for this path after it was found unfit for it + // is still drawn, tile by tile + if (gpu !== undefined && gpu.orientation.draws(layer)) { gpu.draw(layer, rect); return; } @@ -1499,8 +1492,7 @@ export default class WebGLRenderer extends Renderer { * @internal */ _getTMXGPURendererFor(orientation) { - const Class = TMX_GPU_RENDERERS[orientation]; - if (Class === undefined) { + if (TMX_ORIENTATIONS[orientation] === undefined) { // staggered, hexagonal, oblique: drawn by the legacy renderer return undefined; } @@ -1508,7 +1500,7 @@ export default class WebGLRenderer extends Renderer { let gpu = this._tmxGPURenderers.get(orientation); if (gpu === undefined) { try { - gpu = new Class(this); + gpu = new TMXLayerGPURenderer(this, orientation); } catch (err) { // shader compile / link failure on this driver — disable // the GPU path permanently for the rest of the session diff --git a/packages/melonjs/src/video/webgpu/renderers/tmxlayer/isometric.js b/packages/melonjs/src/video/webgpu/renderers/tmxlayer/isometric.js deleted file mode 100644 index 232d8676f6..0000000000 --- a/packages/melonjs/src/video/webgpu/renderers/tmxlayer/isometric.js +++ /dev/null @@ -1,54 +0,0 @@ -import { isometricRegion } from "../../../gpu/tmxlayer_region.js"; -import isometricWGSL from "../../shaders/tmxlayer-isometric.wgsl"; -import TMXLayerGPURenderer from "./tmxlayer.js"; - -/** - * additional imports for TypeScript - * @import { default as TMXLayer } from "../../../../level/tiled/TMXLayer.js"; - * @import { default as WebGPURenderer } from "../../webgpu_renderer.js"; - */ - -/** - * GPU-accelerated renderer for isometric TMX tile layers on the WebGPU - * backend: the shared {@link TMXLayerGPURenderer}, with an isometric grid's - * geometry. The quad covers the view, and the shader works in pixels. - * - * Isometric tiles overlap, and the shader keeps the one drawn last among - * those of ONE tileset: a layer takes this path only when all its tiles - * come from the same one (`layer._shaderTileset`, set by the layer when it - * is found eligible). - * @ignore - * @internal - */ -export default class IsometricTMXLayerGPURenderer extends TMXLayerGPURenderer { - /** - * @param {WebGPURenderer} renderer - the WebGPU renderer instance - */ - constructor(renderer) { - super(renderer, isometricWGSL); - this.tilesets = []; - } - - /** - * @ignore - * @internal - */ - region(layer, rect, tileset, out) { - return isometricRegion(layer, rect, tileset, out); - } - - /** - * The one tileset an isometric layer on this path draws with. - * @param {TMXLayer} layer - the layer - * @returns {object[]} that tileset, or none for an empty layer - * @ignore - * @internal - */ - tilesetsOf(layer) { - this.tilesets.length = 0; - if (layer._shaderTileset) { - this.tilesets.push(layer._shaderTileset); - } - return this.tilesets; - } -} diff --git a/packages/melonjs/src/video/webgpu/renderers/tmxlayer/orthogonal.js b/packages/melonjs/src/video/webgpu/renderers/tmxlayer/orthogonal.js deleted file mode 100644 index 3131648d73..0000000000 --- a/packages/melonjs/src/video/webgpu/renderers/tmxlayer/orthogonal.js +++ /dev/null @@ -1,33 +0,0 @@ -import { orthogonalRegion } from "../../../gpu/tmxlayer_region.js"; -import orthogonalWGSL from "../../shaders/tmxlayer-orthogonal.wgsl"; -import TMXLayerGPURenderer from "./tmxlayer.js"; - -/** - * additional imports for TypeScript - * @import { default as WebGPURenderer } from "../../webgpu_renderer.js"; - */ - -/** - * GPU-accelerated renderer for orthogonal TMX tile layers on the WebGPU - * backend: the shared {@link TMXLayerGPURenderer}, with an orthogonal grid's - * geometry. The quad covers the cells in view, and the shader works in - * cells. - * @ignore - * @internal - */ -export default class OrthogonalTMXLayerGPURenderer extends TMXLayerGPURenderer { - /** - * @param {WebGPURenderer} renderer - the WebGPU renderer instance - */ - constructor(renderer) { - super(renderer, orthogonalWGSL); - } - - /** - * @ignore - * @internal - */ - region(layer, rect, tileset, out) { - return orthogonalRegion(layer, rect, tileset, out); - } -} diff --git a/packages/melonjs/src/video/webgpu/renderers/tmxlayer/tmxlayer.js b/packages/melonjs/src/video/webgpu/renderers/tmxlayer/tmxlayer.js index 9ca29e901a..a0ccbd8eaf 100644 --- a/packages/melonjs/src/video/webgpu/renderers/tmxlayer/tmxlayer.js +++ b/packages/melonjs/src/video/webgpu/renderers/tmxlayer/tmxlayer.js @@ -1,7 +1,14 @@ import VertexArrayBuffer from "../../../buffer/vertex.js"; import { transformQuadCorners } from "../../../gpu/quadcorners.ts"; -import { createRegion } from "../../../gpu/tmxlayer_region.js"; +import { + atlasColumns, + atlasRows, + createRegion, + TMX_ORIENTATIONS, +} from "../../../gpu/tmxlayer_orientation.js"; import tmxLayerCommonWGSL from "../../shaders/tmxlayer-common.wgsl"; +import isometricWGSL from "../../shaders/tmxlayer-isometric.wgsl"; +import orthogonalWGSL from "../../shaders/tmxlayer-orthogonal.wgsl"; /** * additional imports for TypeScript @@ -19,6 +26,12 @@ import tmxLayerCommonWGSL from "../../shaders/tmxlayer-common.wgsl"; */ const TMX_UNIFORM_SIZE = 128; +// each orientation's part of the shader module, appended to the shared one +const ORIENTATION_WGSL = { + orthogonal: orthogonalWGSL, + isometric: isometricWGSL, +}; + /** * GPU-accelerated renderer for TMX tile layers on the WebGPU backend, the * part every map orientation shares — the WGSL realization of the WebGL @@ -49,11 +62,25 @@ const TMX_UNIFORM_SIZE = 128; export default class TMXLayerGPURenderer { /** * @param {WebGPURenderer} renderer - the WebGPU renderer instance - * @param {string} wgsl - the orientation's part of the shader module, - * appended to the shared one + * @param {string} orientation - the map orientation to draw, one of + * `TMX_ORIENTATIONS` */ - constructor(renderer, wgsl) { + constructor(renderer, orientation) { this.renderer = renderer; + /** + * what differs with the map's orientation (see + * `gpu/tmxlayer_orientation.js`) + * @ignore + * @internal + */ + this.orientation = TMX_ORIENTATIONS[orientation]; + // the bounds of the shader's loops, declared ahead of its own part + const limits = Object.entries(this.orientation.limits) + .map(([name, value]) => { + return `const ${name} : i32 = ${value};`; + }) + .join("\n"); + const wgsl = `${limits}\n${ORIENTATION_WGSL[orientation]}`; const cache = renderer.pipelineCache; // group-3 shape: the uniform block + the two lookup textures @@ -109,40 +136,17 @@ export default class TMXLayerGPURenderer { */ this.vertexScratch = undefined; /** - * what {@link TMXLayerGPURenderer#region} fills + * what the orientation's `region` fills * @ignore * @internal */ this.regionScratch = createRegion(); - } - - /** - * The part of a layer a view shows, for the tiles of one tileset (see - * `gpu/tmxlayer_region.js`). The quad it gives must be the same for - * every tileset of a layer: it is written once, for the first one. - * @param {TMXLayer} layer - the layer - * @param {object} rect - the visible viewport rect (world coords) - * @param {object} tileset - the tileset whose tiles are drawn - * @param {object} out - the region to fill - * @returns {boolean} false when the view shows nothing of the layer - * @abstract - * @ignore - * @internal - */ - // eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars - region(layer, rect, tileset, out) { - return false; - } - - /** - * The tilesets a layer is drawn with, one pass each. - * @param {TMXLayer} layer - the layer - * @returns {object[]} the tilesets - * @ignore - * @internal - */ - tilesetsOf(layer) { - return layer.tilesets.tilesets; + /** + * what the orientation's `tilesetsOf` fills, when it needs to + * @ignore + * @internal + */ + this.tilesetsScratch = []; } /** @@ -395,7 +399,7 @@ export default class TMXLayerGPURenderer { let begun; // one pass per tileset — the GID-range guard hides other tilesets - const tilesets = this.tilesetsOf(layer); + const tilesets = this.orientation.tilesetsOf(layer, this.tilesetsScratch); for (let i = 0; i < tilesets.length; i++) { const tileset = tilesets[i]; // eligibility should have excluded these — guard defensively @@ -403,7 +407,7 @@ export default class TMXLayerGPURenderer { continue; } // the view shows nothing of this tileset's tiles - if (!this.region(layer, rect, tileset, region)) { + if (!this.orientation.region(layer, rect, tileset, region)) { continue; } begun ??= this.begin(layer, region); @@ -415,18 +419,12 @@ export default class TMXLayerGPURenderer { const spacing = tileset.spacing; const atlasW = tileset.image.width; const atlasH = tileset.image.height; - const atlasCols = Math.max( - 1, - Math.floor((atlasW - margin * 2 + spacing) / (tsW + spacing)), - ); - const atlasRows = Math.max( - 1, - Math.floor((atlasH - margin * 2 + spacing) / (tsH + spacing)), - ); + const atlasCols = atlasColumns(tileset); + const atlasRowCount = atlasRows(tileset); const animEntry = this.getOrUpdateAnimLookup( tileset, - atlasCols * atlasRows, + atlasCols * atlasRowCount, ); // every declared binding needs a view — reuse the index texture // as the filler (never read: uAnimSize stays 0) @@ -438,7 +436,7 @@ export default class TMXLayerGPURenderer { scratch[6] = region.overflowX; scratch[7] = region.overflowY; scratch[8] = atlasCols; - scratch[9] = atlasRows; + scratch[9] = atlasRowCount; scratch[10] = 1 / atlasW; scratch[11] = 1 / atlasH; scratch[12] = margin; diff --git a/packages/melonjs/src/video/webgpu/shaders/tmxlayer-common.wgsl b/packages/melonjs/src/video/webgpu/shaders/tmxlayer-common.wgsl index ee5758c0c4..5cc80843d8 100644 --- a/packages/melonjs/src/video/webgpu/shaders/tmxlayer-common.wgsl +++ b/packages/melonjs/src/video/webgpu/shaders/tmxlayer-common.wgsl @@ -77,21 +77,35 @@ struct CellSample { color : vec4f, } +// What sampling the atlas needs of a fragment, the same for every cell +// tried for it: taken once, in `fragment_main`, where control flow is still +// uniform (see `footprint` in tmxlayer-common.frag). +struct Footprint { + gradX : vec2f, + gradY : vec2f, + inset : vec2f, +} + +fn footprint(worldPx : vec2f) -> Footprint { + let dWorldX = dpdx(worldPx); + let dWorldY = dpdy(worldPx); + // keep the sample half a texel of the level it reads inside the tile, + // so filtering never blends in the next tile of the tileset, or the + // spacing around it, along the tile's edge: a seam between two tiles + // (never past the tile's centre). Without mipmaps that level is the + // full-size art; under them, the deepest level read is the next one up + // once the level is past a whole number, by more than a rounding error: + // drawn at its size, the derivatives are 1 give or take a few ulps, and + // level 0 it is. Sampled nearest, the sample stays in the same texel + let lod = ceil(log2(max(max(length(dWorldX), length(dWorldY)), 1.0)) - 0.01); + let inset = min(vec2f(0.5 * exp2(lod * tmx.uMipmaps)), tmx.uTileSize * 0.5); + return Footprint(dWorldX * tmx.uInvTilesetSize, dWorldY * tmx.uInvTilesetSize, inset); +} + // Try to render the tile at cell (cx, cy) for the current fragment — // identical logic to the GLSL tryRenderCell, returning a hit/color pair // (WGSL has no out parameters). -// `dWorldX` / `dWorldY`: the world position's screen derivatives, taken in -// `fragment_main` while control flow is still uniform. The atlas coordinate -// jumps from one tile to the next, so its own derivatives would pick a tiny -// mip level along every tile edge; a texel of the atlas is a world pixel, -// so the world's derivatives are the atlas's. -fn tryRenderCell( - cx : i32, - cy : i32, - worldPx : vec2f, - dWorldX : vec2f, - dWorldY : vec2f, -) -> CellSample { +fn tryRenderCell(cx : i32, cy : i32, worldPx : vec2f, fp : Footprint) -> CellSample { var miss : CellSample; miss.hit = false; miss.color = vec4f(0.0); @@ -102,6 +116,13 @@ fn tryRenderCell( return miss; } + // the cell's tile does not reach the fragment (where it is drawn from + // is the orientation's own): known before anything is fetched + var inTile = (worldPx - tileOrigin(cx, cy)) / tmx.uTileSize; + if (inTile.x < 0.0 || inTile.x >= 1.0 || inTile.y < 0.0 || inTile.y >= 1.0) { + return miss; + } + // byte-exact read: rgba8unorm texel back to byte ints let cellF = textureLoad(uTileIndex, vec2i(cx, cy), 0); let cell = vec4u(cellF * 255.0 + 0.5); @@ -111,12 +132,6 @@ fn tryRenderCell( return miss; } - // where the cell's tile is drawn from: the orientation's own - var inTile = (worldPx - tileOrigin(cx, cy)) / tmx.uTileSize; - if (inTile.x < 0.0 || inTile.x >= 1.0 || inTile.y < 0.0 || inTile.y >= 1.0) { - return miss; - } - // flip mask + axis-swap trick: AD transposes; with AD set, H and V // swap their effective axes (matches the legacy buildFlipTransform) let flipMask = i32(cell.b); @@ -139,32 +154,23 @@ fn tryRenderCell( localId = i32(animTexel.r) | (i32(animTexel.g) << 8u); } - let row = floor(f32(localId) / tmx.uTilesetCols.x); - let col = f32(localId) - row * tmx.uTilesetCols.x; + // the tile's place in the atlas, in whole numbers: a float division + // may land a hair under the row it should + let cols = i32(tmx.uTilesetCols.x); + let row = localId / cols; let tileOriginPx = tmx.uTilesetMargin.xy - + vec2f(col, row) * (tmx.uTileSize + tmx.uTilesetMargin.zw); + + vec2f(f32(localId - row * cols), f32(row)) * (tmx.uTileSize + tmx.uTilesetMargin.zw); var texelPx = tileOriginPx + inTile * tmx.uTileSize; - // keep the sample half a texel of the level it reads inside the tile, - // so filtering never blends in the next tile of the tileset, or the - // spacing around it, along the tile's edge: a seam between two tiles - // (never past the tile's centre). Without mipmaps that level is the - // full-size art; under them, the deepest level read is the next one up - // once the level is past a whole number, by more than a rounding error: - // drawn at its size, the derivatives are 1 give or take a few ulps, and - // level 0 it is. Sampled nearest, the sample stays in the same texel - let lod = ceil(log2(max(max(length(dWorldX), length(dWorldY)), 1.0)) - 0.01); - let inset = min(vec2f(0.5 * exp2(lod * tmx.uMipmaps)), tmx.uTileSize * 0.5); - texelPx = clamp(texelPx, tileOriginPx + inset, tileOriginPx + tmx.uTileSize - inset); - let texelUV = texelPx * tmx.uInvTilesetSize; + texelPx = clamp(texelPx, tileOriginPx + fp.inset, tileOriginPx + tmx.uTileSize - fp.inset); // explicit gradients, so the sample is legal here (non-uniform control // flow); a sampler without mipmaps clamps to level 0, as before let sampled = textureSampleGrad( uTexture, uSampler, - texelUV, - dWorldX * tmx.uInvTilesetSize, - dWorldY * tmx.uInvTilesetSize, + texelPx * tmx.uInvTilesetSize, + fp.gradX, + fp.gradY, ); if (sampled.a <= 0.0) { return miss; @@ -176,8 +182,8 @@ fn tryRenderCell( } // A fragment is opaque from this alpha on: nothing behind it would change a -// channel by a whole step of 8 bits -const OPAQUE : f32 = 0.996; +// channel by half a step of 8 bits +const OPAQUE : f32 = 0.998; // Put a texel behind what a fragment has so far, both premultiplied: what // drawing the tiles back to front, each over the last, comes to, taken from diff --git a/packages/melonjs/src/video/webgpu/shaders/tmxlayer-isometric.wgsl b/packages/melonjs/src/video/webgpu/shaders/tmxlayer-isometric.wgsl index 2e3b35ed7b..e948a3263e 100644 --- a/packages/melonjs/src/video/webgpu/shaders/tmxlayer-isometric.wgsl +++ b/packages/melonjs/src/video/webgpu/shaders/tmxlayer-isometric.wgsl @@ -9,10 +9,8 @@ // the CPU renderer draws in, each texel put behind the ones before it until // the fragment is opaque. -// bounds of the two runs: tiles up to 8 grid heights tall and 4 grid widths -// wide (the layer falls back to the CPU renderer past them) -const MAX_ROWS : i32 = 16; -const MAX_COLS : i32 = 4; +// `MAX_ROWS` and `MAX_COLS`, the bounds of the two runs, are declared ahead +// of this file (see `TMX_ORIENTATIONS` in gpu/tmxlayer_orientation.js). // the left of the cell's diamond, and as far above its bottom as the tile // is tall @@ -26,8 +24,7 @@ fn tileOrigin(cx : i32, cy : i32) -> vec2f { @fragment fn fragment_main(in : VSOut) -> @location(0) vec4f { let worldPx = tmx.uVisibleStart + in.vRegion * tmx.uVisibleSize; - let dWorldX = dpdx(worldPx); - let dWorldY = dpdy(worldPx); + let fp = footprint(worldPx); let halfCell = tmx.uCellSize * 0.5; // the rightmost and the lowest cell whose image can reach the fragment @@ -38,18 +35,21 @@ fn fragment_main(in : VSOut) -> @location(0) vec4f { var result = vec4f(0.0); var opaque = false; - for (var j = 0; j < MAX_ROWS; j++) { - if (j >= spanS) { + // rows past the map's last one, or before its first, hold no cell: most + // of a fragment's run, along the bottom of the map and above its top + let sLast = i32(tmx.uMapSize.x) + i32(tmx.uMapSize.y) - 2; + for (var j = max(sMax - sLast, 0); j < MAX_ROWS; j++) { + let s = sMax - j; + if (j >= spanS || s < 0) { break; } - let s = sMax - j; // the first u of this row's parity, then every other one var u = uMax - ((uMax + s) & 1); for (var i = 0; i < MAX_COLS; i++) { if (uMax - u >= spanU) { break; } - let candidate = tryRenderCell((s + u) / 2, (s - u) / 2, worldPx, dWorldX, dWorldY); + let candidate = tryRenderCell((s + u) / 2, (s - u) / 2, worldPx, fp); if (candidate.hit && under(&result, candidate.color)) { opaque = true; break; diff --git a/packages/melonjs/src/video/webgpu/shaders/tmxlayer-orthogonal.wgsl b/packages/melonjs/src/video/webgpu/shaders/tmxlayer-orthogonal.wgsl index 1585827ba8..d2ac310b81 100644 --- a/packages/melonjs/src/video/webgpu/shaders/tmxlayer-orthogonal.wgsl +++ b/packages/melonjs/src/video/webgpu/shaders/tmxlayer-orthogonal.wgsl @@ -3,7 +3,8 @@ // // `uOverflow` is how many cells a tile reaches past its own, across and up. -const MAX_OVERFLOW : i32 = 4; +// `MAX_OVERFLOW`, the bound of both loops, is declared ahead of this file +// (see `TMX_ORIENTATIONS` in gpu/tmxlayer_orientation.js). // a tile is bottom-aligned on its cell, and left-aligned fn tileOrigin(cx : i32, cy : i32) -> vec2f { @@ -18,8 +19,7 @@ fn fragment_main(in : VSOut) -> @location(0) vec4f { let tileCoord = tmx.uVisibleStart + in.vRegion * tmx.uVisibleSize; let geomCell = floor(tileCoord); let worldPx = tileCoord * tmx.uCellSize; - let dWorldX = dpdx(worldPx); - let dWorldY = dpdy(worldPx); + let fp = footprint(worldPx); let gx = i32(geomCell.x); let gy = i32(geomCell.y); @@ -29,7 +29,7 @@ fn fragment_main(in : VSOut) -> @location(0) vec4f { // fast path: tiles fit the cell exactly — only the geometric cell can // contain this fragment's tile if (overflowX == 0 && overflowY == 0) { - let only = tryRenderCell(gx, gy, worldPx, dWorldX, dWorldY); + let only = tryRenderCell(gx, gy, worldPx, fp); if (!only.hit) { discard; } @@ -50,7 +50,7 @@ fn fragment_main(in : VSOut) -> @location(0) vec4f { if (dx > overflowX) { break; } - let candidate = tryRenderCell(gx - dx, gy + dy, worldPx, dWorldX, dWorldY); + let candidate = tryRenderCell(gx - dx, gy + dy, worldPx, fp); if (candidate.hit && under(&result, candidate.color)) { opaque = true; break; diff --git a/packages/melonjs/src/video/webgpu/webgpu_renderer.js b/packages/melonjs/src/video/webgpu/webgpu_renderer.js index e6c92eaffb..dfadff3173 100644 --- a/packages/melonjs/src/video/webgpu/webgpu_renderer.js +++ b/packages/melonjs/src/video/webgpu/webgpu_renderer.js @@ -25,6 +25,7 @@ import BlendEffect from "../effects/blendEffect.js"; import { meshHostingBlocker } from "../effects/mesh_splice.js"; import RadialGradientEffect from "../effects/radialGradient.js"; import { frameClampMode } from "../gpu/frame.js"; +import { TMX_ORIENTATIONS } from "../gpu/tmxlayer_orientation.js"; import { Gradient } from "../gradient.js"; import Renderer from "../renderer.js"; import RenderTargetPool from "../rendertarget/render_target_pool.js"; @@ -54,8 +55,7 @@ import WebGPUBufferArena from "./buffer/arena.js"; import WebGPUUniformRing from "./buffer/uniformring.js"; import { buildEffectGPU } from "./effect_binding.js"; import WebGPUPipelineCache, { DEPTH_STENCIL_FORMAT } from "./pipeline/cache.js"; -import IsometricTMXLayerGPURenderer from "./renderers/tmxlayer/isometric.js"; -import OrthogonalTMXLayerGPURenderer from "./renderers/tmxlayer/orthogonal.js"; +import TMXLayerGPURenderer from "./renderers/tmxlayer/tmxlayer.js"; import { COMPRESSION_FEATURES } from "./texture/compressed.js"; import { WebGPUFrameTexture } from "./texture/frametexture.js"; import WebGPUTextureStore from "./texture/store.js"; @@ -105,15 +105,6 @@ export function resolveDepthOps(meshDepthActive, pendingDepthClear) { }; } -/** - * the GPU tile layer renderer of each map orientation that has one - * @ignore - */ -const TMX_GPU_RENDERERS = { - orthogonal: OrthogonalTMXLayerGPURenderer, - isometric: IsometricTMXLayerGPURenderer, -}; - /** * The **experimental** WebGPU renderer. * @@ -2519,13 +2510,17 @@ export default class WebGPURenderer extends Renderer { * @override */ drawTileLayer(layer, rect) { - const Class = TMX_GPU_RENDERERS[layer.orientation]; - if (layer.renderMode === "shader" && Class !== undefined) { + // a layer asked for this path after it was found unfit for it is + // still drawn, tile by tile + if ( + layer.renderMode === "shader" && + TMX_ORIENTATIONS[layer.orientation]?.draws(layer) === true + ) { // device-scoped, lazily (re)built: a device loss rebuilds the // pipeline cache, detected via the epoch stamp let tmx = this.tmxRenderers.get(layer.orientation); if (tmx === undefined || tmx.epoch !== this.pipelineCache.epoch) { - tmx = new Class(this); + tmx = new TMXLayerGPURenderer(this, layer.orientation); this.tmxRenderers.set(layer.orientation, tmx); } tmx.draw(layer, rect); diff --git a/packages/melonjs/tests/helpers/tile-layer-compare.js b/packages/melonjs/tests/helpers/tile-layer-compare.js index 3b3021ffb9..4275e82c83 100644 --- a/packages/melonjs/tests/helpers/tile-layer-compare.js +++ b/packages/melonjs/tests/helpers/tile-layer-compare.js @@ -61,6 +61,9 @@ export function inBlock(x, y, w, h, tw, th) { * @param {(x: number, y: number, id: number) => number} [options.alpha] * how opaque each pixel is, 0 to 255, for soft edges and see-through tiles * (in place of `opaque`) + * @param {boolean} [options.outerMargin=true] - false for an image that + * stops at its last column and row, with no margin after them, as Tiled + * lets one * @param {object} [options.extra] - more Tiled tileset properties * (`tileoffset`, `tiles` with animations...) * @returns {object} the tileset's Tiled JSON, without its `firstgid` @@ -75,12 +78,14 @@ export function makeTileset(options) { spacing = 0, opaque, alpha, + outerMargin = true, extra = {}, } = options; const rows = Math.ceil(count / columns); const canvas = document.createElement("canvas"); - canvas.width = margin * 2 + columns * tw + (columns - 1) * spacing; - canvas.height = margin * 2 + rows * th + (rows - 1) * spacing; + const outer = outerMargin ? margin : 0; + canvas.width = margin + outer + columns * tw + (columns - 1) * spacing; + canvas.height = margin + outer + rows * th + (rows - 1) * spacing; const ctx = canvas.getContext("2d"); const image = ctx.createImageData(canvas.width, canvas.height); const seed = nextName * 37; diff --git a/packages/melonjs/tests/helpers/tile-layer-isometric-scenarios.js b/packages/melonjs/tests/helpers/tile-layer-isometric-scenarios.js index 6c9bb42d2a..0bf2c405bf 100644 --- a/packages/melonjs/tests/helpers/tile-layer-isometric-scenarios.js +++ b/packages/melonjs/tests/helpers/tile-layer-isometric-scenarios.js @@ -531,6 +531,21 @@ export function isometricScenarios(renderer, type) { expect(await same(scene)).toBeGreaterThan(0); }); + it("from a tileset whose image has no margin after its last tiles", async (ctx) => { + need(ctx); + // as Tiled lets one be: the tiles are counted from the first + // margin, not as if there were two + const scene = iso({ + cols: 8, + rows: 6, + tilesets: [ + blocks(64, 64, { margin: 7, spacing: 2, outerMargin: false }), + ], + layers: [{ data: scattered(8, 6) }], + }); + expect(await same(scene)).toBeGreaterThan(0); + }); + for (const [x, y] of [ [0, 16], [-12, 0], @@ -1095,6 +1110,76 @@ export function isometricScenarios(renderer, type) { expect(said).toMatch(/not square, flipped diagonally/); }); + it("a grid of odd size, whose tiles stand half a pixel off", async (ctx) => { + need(ctx); + for (const [tw, th] of [ + [33, 17], + [64, 31], + [63, 32], + ]) { + const scene = { + orientation: "isometric", + cols: 9, + rows: 7, + tw, + th, + tilesets: [makeTileset({ tw, th: th * 2 })], + layers: [{ data: scattered(9, 7) }], + }; + const [mode, said] = modeOf(scene); + expect(mode, `${tw} × ${th}`).toBe("perTile"); + expect(said).toMatch(/isometric grid of odd size/); + } + }); + + it("a layer blended another way than the normal one", (ctx) => { + need(ctx); + for (const mode of ["add", "multiply", "screen"]) { + const [took, said] = modeOf( + iso({ + cols: 4, + rows: 4, + tilesets: [blocks(64, 128)], + layers: [{ data: scattered(4, 4), mode }], + }), + ); + expect(took, mode).toBe("perTile"); + expect(said).toMatch(/blend mode/); + } + }); + + it("and one asked for by hand afterwards is still drawn, tile by tile", async (ctx) => { + need(ctx); + // two tilesets in one layer: the layer has no tileset to + // draw with on the GPU + const scene = iso({ + cols: 6, + rows: 6, + tilesets: [blocks(64, 32), blocks(64, 96)], + layers: [ + { + data: fill(6, 6, (c, r) => { + return 1 + ((c + r) % 16); + }), + }, + ], + }); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + let layers; + try { + layers = show(app, makeMap(scene)); + } finally { + warn.mockRestore(); + } + expect(layers[0].renderMode).toBe("perTile"); + app.viewport.moveTo(0, 0); + const forced = await drawIn(app, layers, "shader"); + expect(forced.cpuDraws).toBe(1); + const d = diff(reference(scene, 0, 0, WIDTH, HEIGHT), forced.frame); + expect(d.different, d.first).toBe(0); + expect(drawn(forced.frame)).toBeGreaterThan(0); + }); + it("a staggered map, still", (ctx) => { need(ctx); const [mode, said] = modeOf({ @@ -1192,6 +1277,25 @@ export function isometricScenarios(renderer, type) { }); } + it("a tileset whose image has no margin after its last tiles", async (ctx) => { + need(ctx); + const scene = ortho({ + cols: 10, + rows: 8, + tilesets: [ + makeTileset({ + tw: 32, + th: 32, + margin: 5, + spacing: 3, + outerMargin: false, + }), + ], + layers: [{ data: scattered(10, 8) }], + }); + expect(await same(scene, { views: ORTHO_VIEWS })).toBeGreaterThan(0); + }); + it("layers on tilesets of several sizes", async (ctx) => { need(ctx); const scene = ortho({ diff --git a/packages/melonjs/tests/sprite-frame-clamp.spec.js b/packages/melonjs/tests/sprite-frame-clamp.spec.js index 49ad1afbd8..653912a0c0 100644 --- a/packages/melonjs/tests/sprite-frame-clamp.spec.js +++ b/packages/melonjs/tests/sprite-frame-clamp.spec.js @@ -44,7 +44,7 @@ import WebGPULitQuadBatcher from "../src/video/webgpu/batchers/lit_quad_batcher. import WebGPUQuadBatcher from "../src/video/webgpu/batchers/quad_batcher.js"; import WebGPUUniformRing from "../src/video/webgpu/buffer/uniformring.js"; import { FRAME_UNIFORM_SIZE } from "../src/video/webgpu/pipeline/bindgroups.js"; -import WebGPUTMXRenderer from "../src/video/webgpu/renderers/tmxlayer/orthogonal.js"; +import WebGPUTMXRenderer from "../src/video/webgpu/renderers/tmxlayer/tmxlayer.js"; import quadWGSL from "../src/video/webgpu/shaders/quad.wgsl"; import quadLitWGSL from "../src/video/webgpu/shaders/quad-lit.wgsl"; import WebGPURenderer from "../src/video/webgpu/webgpu_renderer.js"; @@ -1191,7 +1191,7 @@ describe("sprites keep to their frame (WebGPU, mock renderer)", () => { renderer.setBatcher = () => { return batcher; }; - const tmx = new WebGPUTMXRenderer(renderer); + const tmx = new WebGPUTMXRenderer(renderer, "orthogonal"); tmx.draw( { cols: 4, diff --git a/packages/melonjs/tests/texture-mipmap.spec.js b/packages/melonjs/tests/texture-mipmap.spec.js index 9d9a64dcc8..3998929914 100644 --- a/packages/melonjs/tests/texture-mipmap.spec.js +++ b/packages/melonjs/tests/texture-mipmap.spec.js @@ -22,7 +22,7 @@ import Renderer from "../src/video/renderer.js"; import { createAtlas, TextureAtlas } from "../src/video/texture/atlas.js"; import WebGPULitQuadBatcher from "../src/video/webgpu/batchers/lit_quad_batcher.js"; import WebGPUQuadBatcher from "../src/video/webgpu/batchers/quad_batcher.js"; -import WebGPUTMXRenderer from "../src/video/webgpu/renderers/tmxlayer/orthogonal.js"; +import WebGPUTMXRenderer from "../src/video/webgpu/renderers/tmxlayer/tmxlayer.js"; import tmxlayerCommonWGSL from "../src/video/webgpu/shaders/tmxlayer-common.wgsl"; import tmxlayerOrthogonalWGSL from "../src/video/webgpu/shaders/tmxlayer-orthogonal.wgsl"; import { @@ -556,7 +556,7 @@ describe("linear-mipmap texture filter (WebGPU, mock renderer)", () => { renderer.setBatcher = () => { return batcher; }; - const tmx = new WebGPUTMXRenderer(renderer); + const tmx = new WebGPUTMXRenderer(renderer, "orthogonal"); tmx.draw(layer(atlas()), { pos: { x: 0, y: 0 }, width: 64, @@ -600,7 +600,7 @@ describe("linear-mipmap texture filter (WebGPU, mock renderer)", () => { "let inset = min(vec2f(0.5 * exp2(lod * tmx.uMipmaps)), tmx.uTileSize * 0.5);", ); expect(code).toContain( - "texelPx = clamp(texelPx, tileOriginPx + inset, tileOriginPx + tmx.uTileSize - inset);", + "texelPx = clamp(texelPx, tileOriginPx + fp.inset, tileOriginPx + tmx.uTileSize - fp.inset);", ); }); }); diff --git a/packages/melonjs/tests/tmxlayer-shader.spec.js b/packages/melonjs/tests/tmxlayer-shader.spec.js index d1e3b61818..d12529101b 100644 --- a/packages/melonjs/tests/tmxlayer-shader.spec.js +++ b/packages/melonjs/tests/tmxlayer-shader.spec.js @@ -1,7 +1,7 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { boot } from "../src/index.js"; import { BufferTextureResource } from "../src/video/texture/resource.js"; -import OrthogonalTMXLayerGPURenderer from "../src/video/webgl/renderers/tmxlayer/orthogonal.js"; +import TMXLayerGPURenderer from "../src/video/webgl/renderers/tmxlayer/tmxlayer.js"; import { getWebGLRenderer, releaseWebGLRenderer, @@ -44,7 +44,7 @@ describe("TMXLayer shader path", () => { // `_getTMXGPURendererFor` is the lazy factory on WebGLRenderer const r1 = renderer._getTMXGPURendererFor("orthogonal"); const r2 = renderer._getTMXGPURendererFor("orthogonal"); - expect(r1).toBeInstanceOf(OrthogonalTMXLayerGPURenderer); + expect(r1).toBeInstanceOf(TMXLayerGPURenderer); expect(r2).toBe(r1); }); diff --git a/packages/melonjs/tests/tmxlayer_bench.spec.js b/packages/melonjs/tests/tmxlayer_bench.spec.js new file mode 100644 index 0000000000..bd8f38f9ec --- /dev/null +++ b/packages/melonjs/tests/tmxlayer_bench.spec.js @@ -0,0 +1,201 @@ +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { video } from "../src/index.js"; +import TMXTileset from "../src/level/tiled/TMXTileset.js"; +import Renderer from "../src/video/renderer.js"; +import { + fill, + inBlock, + makeApp, + makeMap, + makeTileset, + show, +} from "./helpers/tile-layer-compare.js"; + +/** + * Benchmark of the two ways a tile layer is drawn on WebGL: tile by tile + * (`renderMode` "perTile", the CPU renderer: a quad per tile in view, each + * found and placed in JavaScript every frame) against the GPU path + * ("shader": one quad per layer, the tiles found by the fragment shader), + * on a map of medium size, orthogonal and isometric (#1897). + * + * Read the times as **CPU-side** cost, the main thread's share of a frame: + * the run happens under a software rasterizer, whose own time is no measure + * of a graphics card's, and is left out (the frames are timed up to the + * flush, and the rasterizer is let catch up between runs). What the GPU + * path takes off the main thread is the walk over the cells in view and a + * quad for each: its cost does not grow with the number of tiles shown, + * which is what the wider views show. + * + * The canvas is a quarter of the view's size each way, and the camera + * zoomed out to match: as many tiles are in view, and walked, as in the + * view named, with a sixteenth of the pixels for the software rasterizer. + */ + +const SCALE = 4; +// the views measured: what a camera shows, in pixels of the map +const VIEWS = [ + [1280, 720], + [2560, 1440], + [3840, 2160], +]; +const SIZE = 100; // cells a side +const FRAMES = 20; +const RUNS = 3; + +/** most cells filled, a few holes, as a drawn map has */ +const cells = () => { + return fill(SIZE, SIZE, (c, r) => { + return (c * 7 + r * 3) % 23 === 0 ? 0 : 1 + ((c * 5 + r * 11) % 8); + }); +}; + +const MAPS = [ + { + label: "orthogonal, 32 × 32", + scene: () => { + return { + orientation: "orthogonal", + cols: SIZE, + rows: SIZE, + tw: 32, + th: 32, + tilesets: [makeTileset({ tw: 32, th: 32 })], + layers: [{ data: cells() }], + }; + }, + // the middle of the map + center: [(SIZE * 32) / 2, (SIZE * 32) / 2], + }, + { + label: "isometric, 64 × 64 on a 64 × 32 grid", + scene: () => { + return { + orientation: "isometric", + cols: SIZE, + rows: SIZE, + tw: 64, + th: 32, + tilesets: [ + makeTileset({ + tw: 64, + th: 64, + opaque: (x, y) => { + return inBlock(x, y, 64, 64, 64, 32); + }, + }), + ], + layers: [{ data: cells() }], + }; + }, + center: [(SIZE * 64) / 2, (SIZE * 32) / 2], + }, +]; + +describe("tile layer benchmark: tile by tile against the GPU path", () => { + let app; + beforeAll(async () => { + app = await makeApp( + video.WEBGL, + "WebGL", + VIEWS[0][0] / SCALE, + VIEWS[0][1] / SCALE, + ); + }); + afterAll(() => { + app?.destroy(); + vi.restoreAllMocks(); + }); + + it(`${SIZE} × ${SIZE} maps, three sizes of view`, (ctx) => { + if (app === null || app === undefined) { + // a bare return reports as a PASS, so a benchmark that never + // ran would look identical to one that did + ctx.skip("WebGL not available: nothing to measure"); + return; + } + const gl = app.renderer.gl; + const pixel = new Uint8Array(4); + const frame = () => { + app.world.update(0); + app.viewport.update(0); + app.repaint(); + app.draw(); + app.renderer.flush(); + }; + // let the rasterizer finish what it was sent, outside the timings + const settle = () => { + gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel); + }; + /** the median time of a frame, in ms */ + const time = () => { + for (let i = 0; i < 5; i++) { + frame(); + } + settle(); + const runs = []; + for (let run = 0; run < RUNS; run++) { + const start = performance.now(); + for (let i = 0; i < FRAMES; i++) { + frame(); + } + runs.push((performance.now() - start) / FRAMES); + settle(); + } + runs.sort((a, b) => { + return a - b; + }); + return runs[Math.floor(RUNS / 2)]; + }; + + const rows = []; + for (const { label, scene, center } of MAPS) { + const layers = show(app, makeMap(scene())); + expect(layers[0].renderMode).toBe("shader"); + for (const [width, height] of VIEWS) { + app.viewport.zoom = VIEWS[0][0] / SCALE / width; + app.viewport.moveTo(center[0] - width / 2, center[1] - height / 2); + + layers[0].renderMode = "perTile"; + const tiles = vi.spyOn(TMXTileset.prototype, "drawTileRaw"); + frame(); + const inView = tiles.mock.calls.length; + tiles.mockRestore(); + const perTile = time(); + + layers[0].renderMode = "shader"; + const cpu = vi.spyOn(Renderer.prototype, "drawTileLayer"); + frame(); + // the GPU path draws alone + expect(cpu).not.toHaveBeenCalled(); + cpu.mockRestore(); + const shader = time(); + + expect(inView).toBeGreaterThan(0); + rows.push({ + label, + view: `${width} × ${height}`, + inView, + perTile, + shader, + }); + } + app.viewport.zoom = 1; + } + + const line = "═".repeat(86); + console.log(`╔${line}╗`); + console.log( + `║ ${`TILE LAYER BENCHMARK — ${SIZE} × ${SIZE} map, CPU ms per frame`.padEnd(85)}║`, + ); + console.log(`╠${line}╣`); + console.log( + `║ ${"map".padEnd(36)}${"view".padStart(13)}${"tiles".padStart(8)}${"perTile".padStart(10)}${"shader".padStart(9)}${"ratio".padStart(8)} ║`, + ); + for (const row of rows) { + console.log( + `║ ${row.label.padEnd(36)}${row.view.padStart(13)}${String(row.inView).padStart(8)}${row.perTile.toFixed(3).padStart(10)}${row.shader.toFixed(3).padStart(9)}${`${(row.perTile / row.shader).toFixed(1)}×`.padStart(8)} ║`, + ); + } + console.log(`╚${line}╝`); + }); +}); diff --git a/packages/melonjs/tests/webgpu_tmxlayer.spec.js b/packages/melonjs/tests/webgpu_tmxlayer.spec.js index f5ebdb8117..bb48fc2765 100644 --- a/packages/melonjs/tests/webgpu_tmxlayer.spec.js +++ b/packages/melonjs/tests/webgpu_tmxlayer.spec.js @@ -1,7 +1,7 @@ import "./helpers/webgpu-globals.js"; import { beforeEach, describe, expect, it } from "vitest"; import WebGPUQuadBatcher from "../src/video/webgpu/batchers/quad_batcher.js"; -import OrthogonalTMXLayerGPURenderer from "../src/video/webgpu/renderers/tmxlayer/orthogonal.js"; +import TMXLayerGPURenderer from "../src/video/webgpu/renderers/tmxlayer/tmxlayer.js"; import { createMockWebGPURenderer } from "./helpers/webgpu-mock-renderer.js"; /** @@ -58,13 +58,13 @@ describe("WebGPU orthogonal TMX layer renderer (mock)", () => { renderer.currentBatcher ??= new WebGPUQuadBatcher(renderer); return renderer.currentBatcher; }; - tmx = new OrthogonalTMXLayerGPURenderer(renderer); + tmx = new TMXLayerGPURenderer(renderer, "orthogonal"); }); it("registers the shader family once with the quad vertex layout", () => { expect(tmx.key).toMatch(/^effect:/); // a second instance (device-loss rebuild) reuses the module text - const again = new OrthogonalTMXLayerGPURenderer(renderer); + const again = new TMXLayerGPURenderer(renderer, "orthogonal"); expect(again.key).toBe(tmx.key); }); @@ -185,3 +185,97 @@ describe("WebGPU orthogonal TMX layer renderer (mock)", () => { expect(tmx.animLookups.size).toBe(0); }); }); + +/** + * The isometric orientation on the same renderer (#1897): its own shader + * module, one pass with the layer's one tileset whatever the map has, and + * the two run lengths its shader walks in place of the orthogonal overflow. + * What it draws is compared with the CPU renderer, pixel by pixel, on a real + * device in `webgpu_tmxlayer_isometric.spec.js`. + */ +describe("WebGPU isometric TMX layer renderer (mock)", () => { + let renderer; + let tmx; + + const tileset = (firstgid, tilewidth, tileheight) => { + return { + isCollection: false, + image: { width: 256, height: 256 }, + tilewidth, + tileheight, + margin: 0, + spacing: 0, + tileoffset: { x: 0, y: 0 }, + firstgid, + lastgid: firstgid + 15, + isAnimated: false, + animations: new Map(), + texture: { name: `iso-atlas-${firstgid}` }, + }; + }; + const floor = tileset(1, 64, 32); + const walls = tileset(17, 64, 128); + + const layerOf = (shaderTileset) => { + return { + orientation: "isometric", + cols: 8, + rows: 8, + tilewidth: 64, + tileheight: 32, + dataVersion: 1, + layerData: new Uint16Array(8 * 8 * 2), + getOpacity() { + return 1; + }, + getRenderer() { + return { originX: 8 * 32 }; + }, + tint: null, + tilesets: { tilesets: [floor, walls] }, + _shaderTileset: shaderTileset, + }; + }; + + const RECT = { pos: { x: 100, y: 40 }, width: 320, height: 240 }; + + beforeEach(() => { + renderer = createMockWebGPURenderer(); + renderer.setBatcher = () => { + renderer.currentBatcher ??= new WebGPUQuadBatcher(renderer); + return renderer.currentBatcher; + }; + tmx = new TMXLayerGPURenderer(renderer, "isometric"); + }); + + it("has a shader module of its own", () => { + const orthogonal = new TMXLayerGPURenderer(renderer, "orthogonal"); + expect(tmx.key).toMatch(/^effect:/); + expect(tmx.key).not.toBe(orthogonal.key); + }); + + it("draws one quad, with the layer's tileset alone", () => { + tmx.draw(layerOf(walls), RECT); + expect(renderer.calls.drawIndexed).toEqual([6]); + // the tiles' size, and how many cells' images reach a pixel: as + // many across as the image is wide in half grid widths, as many + // down as it is tall in half grid heights + const uniforms = tmx.uniformScratch; + expect([uniforms[4], uniforms[5]]).toEqual([64, 128]); + expect([uniforms[6], uniforms[7]]).toEqual([2, 8]); + }); + + it("draws nothing for a layer with no tile yet", () => { + tmx.draw(layerOf(undefined), RECT); + expect(renderer.calls.drawIndexed).toEqual([]); + }); + + it("draws nothing where the view shows none of the layer", () => { + tmx.draw(layerOf(floor), { + pos: { x: 5000, y: 5000 }, + width: 320, + height: 240, + }); + expect(renderer.calls.drawIndexed).toEqual([]); + }); +}); From 3aa084e98d5cc5fbd71790cabefdf60264bc1b32 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 02:17:47 +0000 Subject: [PATCH 05/51] Tiled: tile layers follow their offset, and are in view as far as their tiles reach Two gaps the reference picture of the tile layer tests had to work around (#1897), on every renderer and render mode. A tile layer ignored its offset in Tiled (`offsetx`, `offsety`) and its own `pos`: it was always drawn at the map's origin, where image layers followed theirs. The offset now goes into `pos`, and the layer draws its tiles, and `getTile()` finds them, where `pos` says. A layer was skipped once its grid left the view, though tiles larger than a cell, or moved by a `tileoffset`, still reached in: the tops of tall tiles vanished above the map. The layer's bounds now cover how far its tiles reach; its `width` and `height` stay the grid's. Tests written first and seen to fail: both paths against the reference on WebGL and WebGPU (offset layers, several layers, an infinite map, a layer moved at run time, views that hold only the reach), and on the Canvas renderer tile by tile and baked, with `getTile`, the bounds, and staggered and hexagonal maps. The reference no longer leaves out a layer whose grid is out of view. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- packages/melonjs/CHANGELOG.md | 2 + .../melonjs/skills/melonjs-tilemaps/SKILL.md | 12 + packages/melonjs/src/level/tiled/TMXLayer.js | 84 ++++- .../tests/helpers/tile-layer-compare.js | 33 +- .../helpers/tile-layer-isometric-scenarios.js | 311 ++++++++++++++++ .../melonjs/tests/tmxlayer-offset.spec.js | 335 ++++++++++++++++++ 6 files changed, 743 insertions(+), 34 deletions(-) create mode 100644 packages/melonjs/tests/tmxlayer-offset.spec.js diff --git a/packages/melonjs/CHANGELOG.md b/packages/melonjs/CHANGELOG.md index 774ae5ab0b..3f2dcd8acf 100644 --- a/packages/melonjs/CHANGELOG.md +++ b/packages/melonjs/CHANGELOG.md @@ -18,6 +18,8 @@ - Tiled, GPU tile layers: a tileset with a `margin` whose image stops at its last tiles, with no margin after them, draws the right tiles; they were counted a column or a row short - Tiled, GPU tile layers: a layer with a tile that is not square, flipped diagonally, is drawn tile by tile; the shader drew such a tile wrong - Tiled, GPU tile layers: the shader runs at full precision whatever `highPrecisionShader` says; at a lower one a phone could misplace the tiles of a large map +- Tiled: a tile layer follows its offset in Tiled (`offsetx`, `offsety`), and its own `pos` when the game moves it: its tiles are drawn there and `getTile()` finds them there, on every renderer and map orientation. Both were ignored, and the layer drawn at the map's origin; only image layers followed their offset. A map whose tile layers have an offset now looks as it does in Tiled +- Tiled: tiles that reach past their layer's grid (taller or wider than a cell, or moved by a `tileoffset`) are drawn when they are in view and the grid is not; the whole layer was skipped, so the tops of tall tiles vanished once the map scrolled out of view. `getBounds()` of a tile layer covers that reach; its `width` and `height` are still the grid's - Tiled, isometric maps drawn tile by tile: tiles of a tileset larger than the map's first one, or moved by a `tileoffset`, went missing along the edges of the view - Tiled, orthogonal maps drawn tile by tile: tiles more than two cells tall went missing along the bottom of the view - `NineSliceSprite` blinks with `flicker()`, as a `Sprite` does; it ignored it diff --git a/packages/melonjs/skills/melonjs-tilemaps/SKILL.md b/packages/melonjs/skills/melonjs-tilemaps/SKILL.md index bb5933e1a6..0bd9874f8f 100644 --- a/packages/melonjs/skills/melonjs-tilemaps/SKILL.md +++ b/packages/melonjs/skills/melonjs-tilemaps/SKILL.md @@ -301,6 +301,15 @@ collision: solid ground comes from collision object layers (below), so a tile set or cleared changes what is drawn and what `cellAt` returns, not what a body runs into. Keep a layer you edit often off `preRender` (see the symptom table). +A tile layer is where its `pos` says: its offset in Tiled (Layer → Offset) +to start with, and wherever the game moves it afterwards. Its tiles are drawn +there, and `getTile(x, y)` answers for where they are drawn: + +```js +board.pos.y -= 8; // the whole layer, 8 pixels up +board.getTile(pointer.x, pointer.y); // still the tile under the pointer +``` + The map's own custom properties (Map → Map Properties in Tiled) are set on the map object, which `level.getCurrentLevel()` returns once it is loaded: a `theme` string property is `level.getCurrentLevel().theme`. They are set @@ -525,6 +534,9 @@ layer into the offscreen-bake path instead. | the level's `name` is not its id after loading | a map custom property named `name` replaced it: map properties are set over the map's own fields | | changing tiles at runtime is slow on a pre-rendered layer | outside an orthogonal map whose tiles fit their cells, a changed tile re-bakes the whole layer before it next draws: keep layers you edit often off `preRender` | | thin lines between tiles on the Canvas renderer, with smoothing on | filtering blends in the next tile of the tileset or its spacing, which a canvas cannot prevent: set `antiAlias: false`, or `preRender` the layer. WebGL and WebGPU keep each tile to itself | +| a tile layer given an offset in Tiled (a roof nudged up, a shadow shifted) is drawn where the others are | before 20.17 a tile layer ignored its offset, and its `pos`; only image layers followed theirs: update | +| after updating to 20.17 a tile layer sits away from where it did | it has an offset in Tiled that was ignored until then, and now moves it as in the editor: clear the layer's Offset in Tiled if it was not meant | +| the tops of tall tiles vanish when the map itself scrolls out of view | before 20.17 a layer was skipped once its grid left the view, though tiles larger than a cell (or moved by a `tileoffset`) still reached in: update | | tilemap slow on some machines | layer fell back off the shader path — check the console warning for the reason | | an isometric layer warns `tiles of more than one tileset in an isometric layer` and is slow | the shader path draws an isometric layer with one tileset: put the tiles of each tileset on a layer of their own, or pack them into one tileset | | a half-transparent isometric layer of tall tiles looks flatter than before 20.17 | on the shader path a layer fades as one picture, and a tile no longer shows through the one in front: set that layer's `renderMode` to `"perTile"` (a `renderMode` custom property in Tiled) for the old look | diff --git a/packages/melonjs/src/level/tiled/TMXLayer.js b/packages/melonjs/src/level/tiled/TMXLayer.js index a18991eff2..f54f591be6 100644 --- a/packages/melonjs/src/level/tiled/TMXLayer.js +++ b/packages/melonjs/src/level/tiled/TMXLayer.js @@ -242,8 +242,17 @@ export default class TMXLayer extends Renderable { * @ignore */ this._shaderTileset = null; + // how far a `tileoffset` moves tiles, each way + let offsetLeft = 0; + let offsetTop = 0; + let offsetRight = 0; + let offsetBottom = 0; for (let i = 0; i < this.tilesets.length; i++) { const tileset = this.tilesets.getTilesetByIndex(i); + offsetLeft = Math.max(offsetLeft, -tileset.tileoffset.x); + offsetRight = Math.max(offsetRight, tileset.tileoffset.x); + offsetTop = Math.max(offsetTop, -tileset.tileoffset.y); + offsetBottom = Math.max(offsetBottom, tileset.tileoffset.y); this.maxTileOffset.x = Math.max( this.maxTileOffset.x, Math.abs(tileset.tileoffset.x), @@ -261,6 +270,25 @@ export default class TMXLayer extends Renderable { tileset.tileheight, ); } + // A tile larger than its cell reaches past it: up and to the right + // on an orthogonal or an isometric map, where a tile stands on the + // bottom left of its cell (any way on the others) + const overX = Math.max(this.maxTileSize.width - this.tilewidth, 0); + const overY = Math.max(this.maxTileSize.height - this.tileheight, 0); + const upRight = orientation === "orthogonal" || orientation === "isometric"; + /** + * How far past the layer's grid its tiles can be drawn, on each + * side: by tiles larger than a cell, and by a tileset's + * `tileoffset`. The layer is in view as far as they reach (see + * {@link TMXLayer#updateBounds}). + * @ignore + */ + this._reach = { + left: (upRight ? 0 : overX) + offsetLeft, + top: overY + offsetTop, + right: overX + offsetRight, + bottom: (upRight ? 0 : overY) + offsetBottom, + }; /** * All animated tilesets in this layer @@ -446,12 +474,42 @@ export default class TMXLayer extends Renderable { // layer left of and above the map's origin const bounds = this.getRenderer().getBounds(this); const origin = this._cellOrigin(vector2dPool.get()); - this.pos.x = bounds.left + origin.x; - this.pos.y = bounds.top + origin.y; + /** + * where the layer is in its map, with nothing moving it: what `pos` + * is measured from to know how far the layer was moved + * @ignore + */ + this._mapPos = { x: bounds.left + origin.x, y: bounds.top + origin.y }; this.width = bounds.width; this.height = bounds.height; + // the layer's offset in Tiled moves it from there, as setting `pos` + // does afterwards: its tiles are drawn, and found, where it is + this.pos.x = this._mapPos.x + (+data.offsetx || 0); + this.pos.y = this._mapPos.y + (+data.offsety || 0); vector2dPool.release(origin); boundsPool.release(bounds); + this.updateBounds(); + } + + /** + * The layer's bounds: its grid, where it is, and as far past it as its + * tiles reach. A tile larger than its cell, or moved by its tileset's + * `tileoffset`, is drawn outside the grid, and the layer is in view + * while such a tile is. Its `width` and `height` stay the grid's. + * @ignore + */ + updateBounds(absolute = true) { + const bounds = super.updateBounds(absolute); + const reach = this._reach; + if (reach !== undefined && bounds.isFinite()) { + bounds.setMinMax( + bounds.left - reach.left, + bounds.top - reach.top, + bounds.right + reach.right, + bounds.bottom + reach.bottom, + ); + } + return bounds; } /** @@ -977,9 +1035,10 @@ export default class TMXLayer extends Renderable { let tile = null; if (this.contains(x, y)) { + // in the map's pixels: back from where the layer was moved to const coord = this.getRenderer().pixelToTileCoords( - x, - y, + x - (this.pos.x - this._mapPos.x), + y - (this.pos.y - this._mapPos.y), vector2dPool.get(), ); tile = this.cellAt(coord.x, coord.y); @@ -1180,11 +1239,20 @@ export default class TMXLayer extends Renderable { viewRect.pos.set(rect.pos.x + offset.x, rect.pos.y + offset.y); rect = viewRect.setSize(rect.width, rect.height); } - // an infinite map's layer that starts left of or above the map's - // origin: its renderer draws the layer's grid from its first cell, - // moved to where that cell's tile is in the world - if (this.startx !== 0 || this.starty !== 0) { + // A layer moved from its place in the map, by its offset in Tiled or + // by its `pos`, and an infinite map's layer that starts left of or + // above the map's origin: the layer's renderer draws its grid from + // its first cell, moved to where that cell's tile is in the world + const movedX = this.pos.x - this._mapPos.x; + const movedY = this.pos.y - this._mapPos.y; + if ( + movedX !== 0 || + movedY !== 0 || + this.startx !== 0 || + this.starty !== 0 + ) { const origin = this._cellOrigin(vector2dPool.get()); + origin.set(origin.x + movedX, origin.y + movedY); cellRect ??= new Rect(0, 0, 0, 0); cellRect.pos.set(rect.pos.x - origin.x, rect.pos.y - origin.y); cellRect.setSize(rect.width, rect.height); diff --git a/packages/melonjs/tests/helpers/tile-layer-compare.js b/packages/melonjs/tests/helpers/tile-layer-compare.js index 4275e82c83..3b13bba0e9 100644 --- a/packages/melonjs/tests/helpers/tile-layer-compare.js +++ b/packages/melonjs/tests/helpers/tile-layer-compare.js @@ -202,15 +202,8 @@ export function makeMap(options) { * Tiles are drawn whole, bottom-aligned on their cell and moved by their * tileset's `tileoffset`; flipped across, down or along the diagonal (the * last on square tiles only, where a flip is a quarter turn in place). - * Layer opacity and tint are for the caller to apply to the picture. A - * layer is drawn at the map's origin: the engine's tile layers are, whatever - * their `pos` or Tiled's layer offset. - * - * One rule here is the engine's and not Tiled's: a layer whose grid is - * wholly out of view is not drawn, though a tile taller than its cell, in - * the map's first rows, reaches above the grid and could still show. The - * engine draws what is in view going by a layer's bounds, which are its - * grid's. + * A layer is moved by its offset in Tiled (`offsetx`, `offsety`). Layer + * opacity and tint are for the caller to apply to the picture. * @param {object} scene - what {@link makeMap} was given * @param {number} viewX - the view's left, in the map's pixels * @param {number} viewY - the view's top @@ -265,20 +258,8 @@ export function reference(scene, viewX, viewY, width, height) { }; for (const layer of layers) { - if (layer.chunks === undefined) { - // the grid's bounds: an isometric map's are its diamond's - const isIso = orientation === "isometric"; - const gridWidth = isIso ? ((cols + rows) * tw) / 2 : cols * tw; - const gridHeight = isIso ? ((cols + rows) * th) / 2 : rows * th; - if ( - viewX + width <= 0 || - gridWidth <= viewX || - viewY + height <= 0 || - gridHeight <= viewY - ) { - continue; - } - } + const ox = layer.offsetx ?? 0; + const oy = layer.offsety ?? 0; // the layer's cells: a plain grid, or an infinite map's chunks const cells = new Map(); const put = (col, row, gid) => { @@ -313,8 +294,8 @@ export function reference(scene, viewX, viewY, width, height) { for (const { col, row, gid } of ordered) { drawTile( gid, - ((col - row - 1) * tw) / 2 + (rows * tw) / 2, - ((col + row + 2) * th) / 2, + ox + ((col - row - 1) * tw) / 2 + (rows * tw) / 2, + oy + ((col + row + 2) * th) / 2, ); } } else { @@ -322,7 +303,7 @@ export function reference(scene, viewX, viewY, width, height) { return a.row - b.row || a.col - b.col; }); for (const { col, row, gid } of ordered) { - drawTile(gid, col * tw, (row + 1) * th); + drawTile(gid, ox + col * tw, oy + (row + 1) * th); } } } diff --git a/packages/melonjs/tests/helpers/tile-layer-isometric-scenarios.js b/packages/melonjs/tests/helpers/tile-layer-isometric-scenarios.js index 0bf2c405bf..7debb5bf20 100644 --- a/packages/melonjs/tests/helpers/tile-layer-isometric-scenarios.js +++ b/packages/melonjs/tests/helpers/tile-layer-isometric-scenarios.js @@ -1376,6 +1376,317 @@ export function isometricScenarios(renderer, type) { }); }); + describe("a layer moved, in Tiled or in the game", () => { + const ortho = (options) => { + return { orientation: "orthogonal", tw: 32, th: 32, ...options }; + }; + + /** the scene baked into one image ("prerender"), from each view */ + const baked = async (scene, views = VIEWS.slice(0, 4)) => { + const layers = show(app, makeMap(scene), "prerender"); + for (const [x, y] of views) { + app.viewport.moveTo(x, y); + const { frame } = await drawIn(app, layers, "prerender"); + const d = diff(reference(scene, x, y, WIDTH, HEIGHT), frame); + expect(d.different, `baked, view (${x}, ${y}): ${d.first}`).toBe(0); + } + }; + + for (const [x, y] of [ + [37, -21], + [-130, 75], + [0, 200], + ]) { + it(`isometric, offset by (${x}, ${y}) in Tiled`, async (ctx) => { + need(ctx); + const scene = iso({ + cols: 8, + rows: 6, + tilesets: [blocks(64, 128)], + layers: [{ data: scattered(8, 6), offsetx: x, offsety: y }], + }); + expect(await same(scene)).toBeGreaterThan(0); + await baked(scene); + }); + + it(`orthogonal, offset by (${x}, ${y}) in Tiled`, async (ctx) => { + need(ctx); + const scene = ortho({ + cols: 10, + rows: 8, + tilesets: [makeTileset({ tw: 32, th: 64 })], + layers: [{ data: scattered(10, 8), offsetx: x, offsety: y }], + }); + expect(await same(scene)).toBeGreaterThan(0); + await baked(scene); + }); + } + + it("isometric layers, each with an offset of its own, on tilesets moved by a tileoffset", async (ctx) => { + need(ctx); + const scene = iso({ + cols: 8, + rows: 6, + tilesets: [ + blocks(64, 32, { extra: { tileoffset: { x: 5, y: 9 } } }), + blocks(64, 128, { extra: { tileoffset: { x: -20, y: 40 } } }), + blocks(128, 64), + ], + layers: [ + { data: scattered(8, 6), offsetx: -10, offsety: 30 }, + { data: scattered(8, 6, 8, 9), offsetx: 64, offsety: 0 }, + { + data: fill(8, 6, (c, r) => { + return (c + r) % 4 === 1 ? 17 + ((c + r * 3) % 8) : 0; + }), + offsetx: 3, + offsety: -70, + }, + ], + }); + expect(await same(scene)).toBeGreaterThan(0); + }); + + it("orthogonal layers, each with an offset of its own", async (ctx) => { + need(ctx); + const scene = ortho({ + cols: 10, + rows: 8, + tilesets: [ + makeTileset({ tw: 32, th: 32 }), + makeTileset({ tw: 64, th: 96 }), + ], + layers: [ + { data: scattered(10, 8), offsetx: 16, offsety: 8 }, + { + data: fill(10, 8, (c, r) => { + return (c + r * 2) % 4 === 0 ? 9 + ((c + r) % 8) : 0; + }), + offsetx: -45, + offsety: 61, + }, + ], + }); + expect(await same(scene)).toBeGreaterThan(0); + }); + + it("a layer of an infinite isometric map, offset", async (ctx) => { + need(ctx); + const chunk = (x, y) => { + return { + x, + y, + width: 4, + height: 4, + data: fill(4, 4, (c, r) => { + return (c + r + x) % 5 === 0 ? 0 : 1 + ((c + r * 2) % 8); + }), + }; + }; + const scene = iso({ + cols: 8, + rows: 8, + tilesets: [blocks(64, 64)], + extra: { infinite: true }, + layers: [ + { + startx: -4, + starty: -4, + width: 12, + height: 8, + data: undefined, + chunks: [chunk(-4, -4), chunk(0, -4), chunk(4, 0), chunk(0, 0)], + offsetx: 48, + offsety: -36, + }, + ], + }); + const layers = show(app, makeMap(scene)); + expect(layers[0].renderMode).toBe("shader"); + const views = [ + [0, 0], + [-200, -150], + [150, -100], + ]; + expect(await same(scene, { views, layers })).toBeGreaterThan(0); + }); + + for (const orientation of ["isometric", "orthogonal"]) { + it(`${orientation}: moved in the game, by its pos`, async (ctx) => { + need(ctx); + const layer0 = { offsetx: 12, offsety: 7 }; + const scene = + orientation === "isometric" + ? iso({ + cols: 8, + rows: 6, + tilesets: [blocks(64, 128)], + layers: [{ data: scattered(8, 6), ...layer0 }], + }) + : ortho({ + cols: 10, + rows: 8, + tilesets: [makeTileset({ tw: 32, th: 32 })], + layers: [{ data: scattered(10, 8), ...layer0 }], + }); + const layers = show(app, makeMap(scene)); + const layer = layers[0]; + // where Tiled put it + const startX = layer.pos.x; + const startY = layer.pos.y; + expect(await same(scene, { layers })).toBeGreaterThan(0); + for (const [dx, dy] of [ + [50, -30], + [-170, 90], + [0, 0], + ]) { + layer.pos.x = startX + dx; + layer.pos.y = startY + dy; + // the reference follows + scene.layers[0].offsetx = 12 + dx; + scene.layers[0].offsety = 7 + dy; + expect( + await same(scene, { layers }), + `moved by (${dx}, ${dy})`, + ).toBeGreaterThan(0); + } + }); + } + }); + + describe("tiles that reach past the grid, when only they are in view", () => { + const ortho = (options) => { + return { orientation: "orthogonal", tw: 32, th: 32, ...options }; + }; + const all = (cols, rows) => { + return fill(cols, rows, (c, r) => { + return 1 + ((c + r * 2) % 8); + }); + }; + + /** the scene baked into one image ("prerender"), from each view */ + const baked = async (scene, views) => { + const layers = show(app, makeMap(scene), "prerender"); + let total = 0; + for (const [x, y] of views) { + app.viewport.moveTo(x, y); + const { frame } = await drawIn(app, layers, "prerender"); + const d = diff(reference(scene, x, y, WIDTH, HEIGHT), frame); + expect(d.different, `baked, view (${x}, ${y}): ${d.first}`).toBe(0); + total += drawn(frame); + } + return total; + }; + + it("isometric: tall tiles, above the map's top corner", async (ctx) => { + need(ctx); + // the 64 × 128 tiles of the first rows reach 96 pixels above + // the grid, which starts at 0: these views end above it + const scene = iso({ + cols: 10, + rows: 8, + tilesets: [blocks(64, 128)], + layers: [{ data: all(10, 8) }], + }); + const views = [ + [160, -HEIGHT - 10], + [100, -HEIGHT - 40], + [220, -HEIGHT - 70], + [-126, -300], + ]; + expect(await same(scene, { views })).toBeGreaterThan(0); + expect(await baked(scene, views)).toBeGreaterThan(0); + }); + + it("orthogonal: tall tiles, above the first row", async (ctx) => { + need(ctx); + const scene = ortho({ + cols: 10, + rows: 8, + tilesets: [makeTileset({ tw: 32, th: 128 })], + layers: [{ data: all(10, 8) }], + }); + const views = [ + [0, -HEIGHT - 10], + [40, -HEIGHT - 50], + [-200, -HEIGHT - 80], + ]; + expect(await same(scene, { views })).toBeGreaterThan(0); + expect(await baked(scene, views)).toBeGreaterThan(0); + }); + + it("orthogonal: wide tiles, right of the last column", async (ctx) => { + need(ctx); + // 96 pixels wide on a 32 pixel grid: 64 pixels past the map, + // which ends at 320 + const scene = ortho({ + cols: 10, + rows: 8, + tilesets: [makeTileset({ tw: 96, th: 32 })], + layers: [{ data: all(10, 8) }], + }); + const views = [ + [325, 0], + [350, 40], + [380, -100], + ]; + expect(await same(scene, { views })).toBeGreaterThan(0); + expect(await baked(scene, views)).toBeGreaterThan(0); + }); + + it("isometric tiles moved off the grid by their tileset's tileoffset", async (ctx) => { + need(ctx); + // moved 150 pixels up and to the left: where the grid is not + const scene = iso({ + cols: 6, + rows: 6, + tilesets: [ + blocks(64, 64, { extra: { tileoffset: { x: -150, y: -150 } } }), + ], + layers: [{ data: all(6, 6) }], + }); + const views = [ + [-WIDTH - 10, 0], + [-100, -HEIGHT - 20], + [-WIDTH - 60, -80], + ]; + expect(await same(scene, { views })).toBeGreaterThan(0); + }); + + it("orthogonal tiles moved off the grid by their tileset's tileoffset", async (ctx) => { + need(ctx); + // under the map, which ends at 192. An orthogonal tileoffset + // leaves the layer to the CPU renderer: it is drawn as well + const scene = ortho({ + cols: 8, + rows: 6, + tilesets: [ + makeTileset({ + tw: 32, + th: 32, + extra: { tileoffset: { x: 0, y: 90 } }, + }), + ], + layers: [{ data: all(8, 6) }], + }); + const [mode] = modeOf(scene); + expect(mode).toBe("perTile"); + const layers = app.world.getChildren().filter((child) => { + return child.layerData !== undefined; + }); + for (const [x, y] of [ + [0, 200], + [-40, 250], + ]) { + app.viewport.moveTo(x, y); + const { frame } = await drawIn(app, layers, "perTile"); + const d = diff(reference(scene, x, y, WIDTH, HEIGHT), frame); + expect(d.different, `view (${x}, ${y}): ${d.first}`).toBe(0); + expect(drawn(frame)).toBeGreaterThan(0); + } + }); + }); + it("a level change frees what the GPU path kept for its layers", async (ctx) => { need(ctx); const scene = iso({ diff --git a/packages/melonjs/tests/tmxlayer-offset.spec.js b/packages/melonjs/tests/tmxlayer-offset.spec.js new file mode 100644 index 0000000000..1f25aa597b --- /dev/null +++ b/packages/melonjs/tests/tmxlayer-offset.spec.js @@ -0,0 +1,335 @@ +/** + * Where a tile layer is: moved by its offset in Tiled and by its own `pos`, + * and in view as far as its tiles reach, which is past its grid when they + * are larger than a cell or moved by their tileset's `tileoffset`. + * + * Checked here on the Canvas renderer, tile by tile and baked into one + * image, against the picture painted with no engine (see + * `helpers/tile-layer-compare.js`), and for what `getTile` answers. The GPU + * renderers are held to the same in `helpers/tile-layer-isometric-scenarios.js`. + */ +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { video } from "../src/index.js"; +import { + diff, + drawIn, + drawn, + fill, + inBlock, + makeApp, + makeMap, + makeTileset, + reference, + show, +} from "./helpers/tile-layer-compare.js"; + +const WIDTH = 320; +const HEIGHT = 240; + +const filled = (cols, rows) => { + return fill(cols, rows, (c, r) => { + return (c * 3 + r) % 7 === 0 ? 0 : 1 + ((c + r * 2) % 8); + }); +}; + +const orthogonal = (options = {}) => { + return { + orientation: "orthogonal", + cols: 10, + rows: 8, + tw: 32, + th: 32, + tilesets: [makeTileset({ tw: 32, th: options.tall ?? 32 })], + layers: [{ data: filled(10, 8), ...options.layer }], + }; +}; + +const isometric = (options = {}) => { + const th = options.tall ?? 64; + return { + orientation: "isometric", + cols: 8, + rows: 6, + tw: 64, + th: 32, + tilesets: [ + makeTileset({ + tw: 64, + th, + opaque: (x, y) => { + return inBlock(x, y, 64, th, 64, 32); + }, + }), + ], + layers: [{ data: filled(8, 6), ...options.layer }], + }; +}; + +describe("where a tile layer is (Canvas renderer)", () => { + let app; + beforeAll(async () => { + app = await makeApp(video.CANVAS, "CANVAS", WIDTH, HEIGHT); + }); + afterAll(() => { + app?.destroy(); + vi.restoreAllMocks(); + }); + + /** + * Draw a scene tile by tile and baked, from each view, and expect the + * reference picture. + * @returns {Promise} how many pixels were drawn, in all + */ + const asTiled = async (scene, views) => { + let total = 0; + for (const mode of ["perTile", "prerender"]) { + const layers = show(app, makeMap(scene), mode); + for (const [x, y] of views) { + app.viewport.moveTo(x, y); + const { frame } = await drawIn(app, layers, mode); + const d = diff(reference(scene, x, y, WIDTH, HEIGHT), frame); + expect(d.different, `${mode}, view (${x}, ${y}): ${d.first}`).toBe(0); + total += drawn(frame); + } + } + return total; + }; + + const VIEWS = [ + [0, 0], + [70, 20], + [-40, -80], + [230, 110], + ]; + + describe("moved by its offset in Tiled", () => { + for (const [x, y] of [ + [37, -21], + [-130, 75], + ]) { + it(`an orthogonal layer, by (${x}, ${y})`, async () => { + const scene = orthogonal({ + tall: 64, + layer: { offsetx: x, offsety: y }, + }); + expect(await asTiled(scene, VIEWS)).toBeGreaterThan(0); + }); + + it(`an isometric layer, by (${x}, ${y})`, async () => { + const scene = isometric({ + tall: 128, + layer: { offsetx: x, offsety: y }, + }); + expect(await asTiled(scene, VIEWS)).toBeGreaterThan(0); + }); + } + + for (const [orientation, extra] of [ + ["staggered", { staggeraxis: "y", staggerindex: "odd" }], + [ + "hexagonal", + { staggeraxis: "x", staggerindex: "even", hexsidelength: 16 }, + ], + ]) { + it(`a ${orientation} layer: the same picture, moved`, async () => { + // no reference is painted for these maps: the layer moved by + // (37, -21) is the layer where it was, seen from that much + // the other way + const scene = (layer) => { + return { + orientation, + cols: 8, + rows: 8, + tw: 64, + th: 32, + tilesets: [tileset], + layers: [{ data: filled(8, 8), ...layer }], + extra, + }; + }; + const tileset = makeTileset({ + tw: 64, + th: 48, + opaque: (x, y) => { + return inBlock(x, y, 64, 48, 64, 32); + }, + }); + for (const mode of ["perTile", "prerender"]) { + const plain = show(app, makeMap(scene({})), mode); + const frames = []; + for (const [x, y] of VIEWS) { + app.viewport.moveTo(x - 37, y + 21); + frames.push((await drawIn(app, plain, mode)).frame); + } + const moved = show( + app, + makeMap(scene({ offsetx: 37, offsety: -21 })), + mode, + ); + for (const [i, [x, y]] of VIEWS.entries()) { + app.viewport.moveTo(x, y); + const { frame } = await drawIn(app, moved, mode); + const d = diff(frames[i], frame); + expect(d.different, `${mode}, view (${x}, ${y}): ${d.first}`).toBe( + 0, + ); + expect(drawn(frame)).toBeGreaterThan(0); + } + } + }); + } + + it("the layer's pos is its offset, and its bounds move with it", () => { + const [layer] = show( + app, + makeMap(orthogonal({ layer: { offsetx: 37, offsety: -21 } })), + ); + expect([layer.pos.x, layer.pos.y]).toEqual([37, -21]); + expect([layer.width, layer.height]).toEqual([320, 256]); + const bounds = layer.getBounds(); + expect([bounds.left, bounds.top]).toEqual([37, -21]); + expect([bounds.right, bounds.bottom]).toEqual([357, 235]); + // no offset: where it always was + const [plain] = show(app, makeMap(orthogonal())); + expect([plain.pos.x, plain.pos.y]).toEqual([0, 0]); + }); + + it("getTile answers for where the tiles are drawn", () => { + const [layer] = show( + app, + makeMap(orthogonal({ layer: { offsetx: 40, offsety: -24 } })), + ); + // the cell (2, 3) is drawn from (64 + 40, 96 - 24) + const tile = layer.getTile(64 + 40 + 5, 96 - 24 + 5); + expect([tile.col, tile.row]).toEqual([2, 3]); + expect(tile.tileId).toBe(layer.cellAt(2, 3).tileId); + // its last pixel, and the first of the next cell + expect(layer.getTile(95 + 40, 127 - 24).col).toBe(2); + expect(layer.getTile(96 + 40, 127 - 24).col).toBe(3); + // left of where the layer now starts: no tile, where there was + // one before the layer was moved + expect(layer.getTile(5, 40)).toBeNull(); + const first = layer.getTile(32 + 40 + 5, -20); + expect([first.col, first.row]).toEqual([1, 0]); + + const [iso] = show( + app, + makeMap(isometric({ layer: { offsetx: -30, offsety: 50 } })), + ); + // the middle of the diamond of cell (3, 2): the map's top + // corner is at x = rows × half a tile + const originX = 6 * 32; + const middle = iso.getTile( + (3 - 2) * 32 + originX - 30, + (3 + 2 + 1) * 16 + 50, + ); + expect([middle.col, middle.row]).toEqual([3, 2]); + }); + }); + + describe("moved in the game, by its pos", () => { + for (const make of [orthogonal, isometric]) { + it(`${make.name}: drawn, and found by getTile, where it was moved to`, async () => { + const scene = make({ tall: 64 }); + const layers = show(app, makeMap(scene), "perTile"); + const layer = layers[0]; + const before = layer.getTile(150, 100); + expect(before).not.toBeNull(); + for (const [dx, dy] of [ + [50, -30], + [-170, 90], + [0, 0], + ]) { + layer.pos.x = dx; + layer.pos.y = dy; + scene.layers[0].offsetx = dx; + scene.layers[0].offsety = dy; + for (const [x, y] of VIEWS) { + app.viewport.moveTo(x, y); + const { frame } = await drawIn(app, layers, "perTile"); + const d = diff(reference(scene, x, y, WIDTH, HEIGHT), frame); + expect( + d.different, + `moved by (${dx}, ${dy}), view (${x}, ${y}): ${d.first}`, + ).toBe(0); + } + // the same cell, where it is now + const now = layer.getTile(150 + dx, 100 + dy); + expect([now.col, now.row]).toEqual([before.col, before.row]); + } + }); + } + }); + + describe("in view as far as its tiles reach", () => { + it("isometric: tall tiles, above the map's top corner", async () => { + const scene = isometric({ tall: 128 }); + scene.layers[0].data = fill(8, 6, (c, r) => { + return 1 + ((c + r * 2) % 8); + }); + // the grid starts at y = 0: these views end above it + const views = [ + [40, -HEIGHT - 10], + [100, -HEIGHT - 60], + ]; + expect(await asTiled(scene, views)).toBeGreaterThan(0); + }); + + it("orthogonal: tall tiles above the first row, wide ones right of the last column", async () => { + const tall = orthogonal({ tall: 128 }); + expect( + await asTiled(tall, [ + [0, -HEIGHT - 10], + [-200, -HEIGHT - 80], + ]), + ).toBeGreaterThan(0); + const wide = orthogonal(); + wide.tilesets = [makeTileset({ tw: 96, th: 32 })]; + expect( + await asTiled(wide, [ + [325, 0], + [380, -100], + ]), + ).toBeGreaterThan(0); + }); + + it("tiles moved off the grid by their tileset's tileoffset", async () => { + const scene = orthogonal(); + scene.tilesets = [ + makeTileset({ tw: 32, th: 32, extra: { tileoffset: { x: 0, y: 90 } } }), + ]; + // the grid ends at y = 256 + expect( + await asTiled(scene, [ + [0, 260], + [-40, 300], + ]), + ).toBeGreaterThan(0); + }); + + it("the bounds cover the reach, the size stays the grid's", () => { + const [layer] = show(app, makeMap(orthogonal({ tall: 128 }))); + expect([layer.width, layer.height]).toEqual([320, 256]); + const bounds = layer.getBounds(); + // 128 pixel tiles on a 32 pixel grid stand 96 above their cell + expect(bounds.top).toBe(-96); + expect([bounds.left, bounds.right, bounds.bottom]).toEqual([0, 320, 256]); + // and getTile has nothing above the grid: no cell is there + expect(layer.getTile(10, -50)).toBeNull(); + // tiles the size of the grid: the grid, no more + const plain = show(app, makeMap(orthogonal()))[0].getBounds(); + expect([plain.left, plain.top, plain.right, plain.bottom]).toEqual([ + 0, 0, 320, 256, + ]); + }); + + it("and far from all of it, the layer is not drawn at all", async () => { + const scene = orthogonal({ tall: 128 }); + const layers = show(app, makeMap(scene), "perTile"); + app.viewport.moveTo(0, -HEIGHT - 200); + const far = await drawIn(app, layers, "perTile"); + expect(far.cpuDraws).toBe(0); + expect(drawn(far.frame)).toBe(0); + }); + }); +}); From a3dd9148ddef7b6c4cc079b4339ca590335aec23 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 02:57:47 +0000 Subject: [PATCH 06/51] GPU tile layers for staggered and hexagonal maps (#1897) Both are one geometry, on the base the isometric path shares: lines of cells a row height apart, every other one shifted by a column width, along the map's rows or its columns. One shader chunk (GLSL and WGSL) and one region function draw both; a hexagonal map's cells are longer by its side length, which is in the two lengths the shader is given (in what was the padding of the WGSL uniform block). The layer's checks are those of an isometric layer: one tileset, tiles up to 4 cells wide and 8 tall, a grid of even size. The CPU renderer of these maps is fixed first, as the reference of the tests showed it away from Tiled: its drawing loop hung a tile larger than its cell from the top of the cell and ignored the tileset's `tileoffset`, where its own `drawTile` (and Tiled) stand the tile on the cell and move it by the offset; and it left out tiles of a large tileset along the edges of the view. Tests: the reference paints staggered and hexagonal maps; 24 scenes (both orientations, either axis, either index, three kinds of tiles) on the Canvas renderer tile by tile and baked, and 38 scenarios on WebGL and WebGPU through both paths, with soft edges, flips, animation, layer offsets, infinite maps, setTile and the fallbacks. The comparison of the two paths moves to the shared test helper. Changelog, API docs and the tilemaps skill. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- packages/melonjs/CHANGELOG.md | 5 +- .../melonjs/skills/melonjs-tilemaps/SKILL.md | 20 +- packages/melonjs/src/application/settings.ts | 12 +- packages/melonjs/src/level/tiled/TMXLayer.js | 113 ++-- .../tiled/renderer/TMXHexagonalRenderer.js | 52 +- packages/melonjs/src/physics/world.js | 13 +- .../src/video/gpu/tmxlayer_orientation.js | 144 ++++- .../webgl/renderers/tmxlayer/tmxlayer.js | 8 + .../webgl/shaders/staggered-tmxlayer.frag | 85 +++ .../webgpu/renderers/tmxlayer/tmxlayer.js | 9 + .../video/webgpu/shaders/tmxlayer-common.wgsl | 4 + .../webgpu/shaders/tmxlayer-staggered.wgsl | 83 +++ .../tests/helpers/tile-layer-compare.js | 122 +++- .../helpers/tile-layer-isometric-scenarios.js | 85 +-- .../helpers/tile-layer-staggered-scenarios.js | 536 ++++++++++++++++++ .../tests/tmxlayer-shader-staggered.spec.js | 8 + .../melonjs/tests/tmxlayer-staggered.spec.js | 53 ++ .../melonjs/tests/webgpu_tmxlayer.spec.js | 107 ++++ .../tests/webgpu_tmxlayer_staggered.spec.js | 9 + 19 files changed, 1274 insertions(+), 194 deletions(-) create mode 100644 packages/melonjs/src/video/webgl/shaders/staggered-tmxlayer.frag create mode 100644 packages/melonjs/src/video/webgpu/shaders/tmxlayer-staggered.wgsl create mode 100644 packages/melonjs/tests/helpers/tile-layer-staggered-scenarios.js create mode 100644 packages/melonjs/tests/tmxlayer-shader-staggered.spec.js create mode 100644 packages/melonjs/tests/tmxlayer-staggered.spec.js create mode 100644 packages/melonjs/tests/webgpu_tmxlayer_staggered.spec.js diff --git a/packages/melonjs/CHANGELOG.md b/packages/melonjs/CHANGELOG.md index 3f2dcd8acf..7155fc5c06 100644 --- a/packages/melonjs/CHANGELOG.md +++ b/packages/melonjs/CHANGELOG.md @@ -6,10 +6,10 @@ - Transitions: a mask transition can be shaped like an image or a `Sprite`, close on the player with `center`, and fill the shape with `invert`, on `state.transition`, `MaskEffect` and `Trigger` ([#1399](https://github.com/melonjs/melonJS/issues/1399)) ### Changed -- Tiled: an isometric tile layer with an `opacity` below 1 fades as one flat picture on WebGL and WebGPU, where each tile was faded over the ones behind it and showed through the one in front. Set the layer's `renderMode` to `"perTile"` for the look it had +- Tiled: an isometric, staggered or hexagonal tile layer with an `opacity` below 1 fades as one flat picture on WebGL and WebGPU, where each tile was faded over the ones behind it and showed through the one in front. Set the layer's `renderMode` to `"perTile"` for the look it had ### Performance -- Tiled: isometric tile layers are drawn by the GPU on WebGL and WebGPU, as orthogonal ones are: one quad for the layer, its tiles found by the fragment shader, in place of a quad per tile in view found and placed in JavaScript every frame. On a 100 × 100 map with about 4000 tiles in view, drawing the layer takes under **0.1 ms** of main-thread time a frame, down from about **2 ms**, and no longer grows with the number of tiles shown. A layer takes this path by itself when all its tiles come from one tileset, up to 4 grid widths wide and 8 grid heights tall (a `tileoffset`, flipped and animated tiles, and `setTile` are all fine); any other is drawn as before, and the console says why ([#1897](https://github.com/melonjs/melonJS/issues/1897)) +- Tiled: isometric, staggered and hexagonal tile layers are drawn by the GPU on WebGL and WebGPU, as orthogonal ones are: one quad for the layer, its tiles found by the fragment shader, in place of a quad per tile in view found and placed in JavaScript every frame. On a 100 × 100 isometric map with about 4000 tiles in view, drawing the layer takes under **0.1 ms** of main-thread time a frame, down from about **2 ms**, and no longer grows with the number of tiles shown. A layer takes this path by itself when all its tiles come from one tileset, up to 4 cells wide and 8 tall (a `tileoffset`, flipped and animated tiles, and `setTile` are all fine); any other is drawn as before, and the console says why ([#1897](https://github.com/melonjs/melonJS/issues/1897)) - Tiled: a reminder that orthogonal tile layers have been drawn this way since 19.4, with the same gain (about 1.9 ms down to under 0.1 ms for 3600 tiles in view). A layer that is not says why in the console when it is activated: most often a tileset with a `tileoffset`, a collection of images, or the Canvas renderer. ### Fixed @@ -20,6 +20,7 @@ - Tiled, GPU tile layers: the shader runs at full precision whatever `highPrecisionShader` says; at a lower one a phone could misplace the tiles of a large map - Tiled: a tile layer follows its offset in Tiled (`offsetx`, `offsety`), and its own `pos` when the game moves it: its tiles are drawn there and `getTile()` finds them there, on every renderer and map orientation. Both were ignored, and the layer drawn at the map's origin; only image layers followed their offset. A map whose tile layers have an offset now looks as it does in Tiled - Tiled: tiles that reach past their layer's grid (taller or wider than a cell, or moved by a `tileoffset`) are drawn when they are in view and the grid is not; the whole layer was skipped, so the tops of tall tiles vanished once the map scrolled out of view. `getBounds()` of a tile layer covers that reach; its `width` and `height` are still the grid's +- Tiled, staggered and hexagonal maps: a tile larger than its cell stands on the cell, and a tileset's `tileoffset` moves its tiles, as in Tiled and on every other map. Drawn tile by tile, such a tile hung down from the top of its cell and the offset was ignored, so the map sat lower than its objects (and than a tile redrawn in a baked layer); tiles of a large tileset also went missing along the edges of the view - Tiled, isometric maps drawn tile by tile: tiles of a tileset larger than the map's first one, or moved by a `tileoffset`, went missing along the edges of the view - Tiled, orthogonal maps drawn tile by tile: tiles more than two cells tall went missing along the bottom of the view - `NineSliceSprite` blinks with `flicker()`, as a `Sprite` does; it ignored it diff --git a/packages/melonjs/skills/melonjs-tilemaps/SKILL.md b/packages/melonjs/skills/melonjs-tilemaps/SKILL.md index 0bd9874f8f..04cc022a75 100644 --- a/packages/melonjs/skills/melonjs-tilemaps/SKILL.md +++ b/packages/melonjs/skills/melonjs-tilemaps/SKILL.md @@ -462,17 +462,18 @@ per-pixel GID lookup in the fragment shader. It requires **all** of: - a renderer that reports GPU tile-layer support (WebGL 2 / WebGPU — not Canvas), - `world.gpuTilemap !== false` (the `gpuTilemap` application setting, default `true`), -- an **orthogonal** or **isometric** layer — hexagonal, staggered and oblique - always fall back, +- an **orthogonal**, **isometric**, **staggered** or **hexagonal** layer — + oblique always falls back, - no collection-of-image tileset, and a tileset tile render size of "Tile size" (`tilerendersize`, not "Map grid size"), - on an orthogonal map: no non-zero `tileoffset`, and tiles that reach at most 4 cells past their own, -- on an isometric map: every tile of the layer from **one tileset** (tiles - overlap, and their order is kept within a tileset, not across two: split - floor and walls into a layer each, which a map usually does already), tiles - at most 4 grid widths wide and 8 grid heights tall, a grid of even size - (64 × 32, not 65 × 33), and the normal blend mode. A `tileoffset` is fine, +- on an isometric, staggered or hexagonal map: every tile of the layer from + **one tileset** (tiles overlap, and their order is kept within a tileset, + not across two: split floor and walls into a layer each, which a map + usually does already), tiles at most 4 cells wide and 8 tall, a grid of + even size (64 × 32, not 65 × 33; a hexagon side of even length), and the + normal blend mode. A `tileoffset` is fine, - no tile that is not square flipped diagonally (rotated, in Tiled). A tile set at run time with `setTile` that breaks one of these moves the layer @@ -538,8 +539,9 @@ layer into the offscreen-bake path instead. | after updating to 20.17 a tile layer sits away from where it did | it has an offset in Tiled that was ignored until then, and now moves it as in the editor: clear the layer's Offset in Tiled if it was not meant | | the tops of tall tiles vanish when the map itself scrolls out of view | before 20.17 a layer was skipped once its grid left the view, though tiles larger than a cell (or moved by a `tileoffset`) still reached in: update | | tilemap slow on some machines | layer fell back off the shader path — check the console warning for the reason | -| an isometric layer warns `tiles of more than one tileset in an isometric layer` and is slow | the shader path draws an isometric layer with one tileset: put the tiles of each tileset on a layer of their own, or pack them into one tileset | -| a half-transparent isometric layer of tall tiles looks flatter than before 20.17 | on the shader path a layer fades as one picture, and a tile no longer shows through the one in front: set that layer's `renderMode` to `"perTile"` (a `renderMode` custom property in Tiled) for the old look | +| a staggered or hexagonal map sits higher than before 20.17, by how much its tiles are taller than a cell (or by its tileset's `tileoffset`) | it is drawn as Tiled draws it: until then a tile hung from the top of its cell and the offset was ignored, away from the map's objects | +| an isometric (staggered, hexagonal) layer warns `tiles of more than one tileset in an isometric layer` and is slow | the shader path draws such a layer with one tileset: put the tiles of each tileset on a layer of their own, or pack them into one tileset | +| a half-transparent isometric (staggered, hexagonal) layer of tall tiles looks flatter than before 20.17 | on the shader path a layer fades as one picture, and a tile no longer shows through the one in front: set that layer's `renderMode` to `"perTile"` (a `renderMode` custom property in Tiled) for the old look | | the soft edges of tiles larger than the grid showed a thin dark outline on the shader path | before 20.17 the edge of such a tile was not blended over the tile behind it: update | ## Related skills diff --git a/packages/melonjs/src/application/settings.ts b/packages/melonjs/src/application/settings.ts index f4733069dc..d58847735c 100644 --- a/packages/melonjs/src/application/settings.ts +++ b/packages/melonjs/src/application/settings.ts @@ -476,16 +476,16 @@ export type ApplicationSettings = { physic: PhysicsType; /** - * Enable the GPU procedural shader path for orthogonal and isometric - * tile layers (backends advertising + * Enable the GPU procedural shader path for orthogonal, isometric, + * staggered and hexagonal tile layers (backends advertising * `renderer.supportsShaderTileLayers` — WebGL 2 and WebGPU). When * `true` (default), eligible layers render via a single quad per * tileset + a fragment shader doing per-fragment GID lookup, bypassing * the per-tile draw loop entirely. Layers that don't qualify (Canvas - * renderer, a staggered, hexagonal or oblique map, collection-of-image - * tilesets, tilerendersize "grid", tiles larger than the shader walks; - * on an orthogonal map a non-zero tileoffset, on an isometric one - * tiles of several tilesets in one layer) fall back to the legacy path + * renderer, an oblique map, collection-of-image tilesets, + * tilerendersize "grid", tiles larger than the shader walks; on an + * orthogonal map a non-zero tileoffset, on the others tiles of + * several tilesets in one layer) fall back to the legacy path * automatically, saying why in the console. * Set to `false` to disable globally. * @default true diff --git a/packages/melonjs/src/level/tiled/TMXLayer.js b/packages/melonjs/src/level/tiled/TMXLayer.js index f54f591be6..44b6edbfdf 100644 --- a/packages/melonjs/src/level/tiled/TMXLayer.js +++ b/packages/melonjs/src/level/tiled/TMXLayer.js @@ -27,16 +27,18 @@ const FLIP_H_BIT = 1 << 0; const FLIP_V_BIT = 1 << 1; const FLIP_AD_BIT = 1 << 2; -// The largest tiles the shader path draws: the bounds of the loops of the -// fragment shaders, which are declared from the same numbers. An orthogonal -// tile can reach so many cells past its own; an isometric one be so many -// grid cells wide and tall. +// The largest tiles the shader path draws are the bounds of the loops of the +// fragment shaders, which are declared from the same numbers (see +// `TMX_ORIENTATIONS`). An orthogonal tile can reach so many cells past its +// own. const ORTHOGONAL_MAX_OVERFLOW = TMX_ORIENTATIONS.orthogonal.limits.MAX_OVERFLOW; -const ISOMETRIC_MAX_TILE_WIDTHS = TMX_ORIENTATIONS.isometric.limits.MAX_COLS; -const ISOMETRIC_MAX_TILE_HEIGHTS = - TMX_ORIENTATIONS.isometric.limits.MAX_ROWS / 2; -const ISOMETRIC_ONE_TILESET = - "tiles of more than one tileset in an isometric layer"; +// "an isometric", "a staggered", "a hexagonal": a layer's kind, in a reason +const kindOf = (orientation) => { + return `${orientation === "isometric" ? "an" : "a"} ${orientation}`; +}; +const oneTilesetReason = (orientation) => { + return `tiles of more than one tileset in ${kindOf(orientation)} layer`; +}; // A diagonal flip turns a tile a quarter: one that is not square then covers // other pixels than its own image's rectangle, which is all the shader looks // at. @@ -270,12 +272,12 @@ export default class TMXLayer extends Renderable { tileset.tileheight, ); } - // A tile larger than its cell reaches past it: up and to the right - // on an orthogonal or an isometric map, where a tile stands on the - // bottom left of its cell (any way on the others) + // A tile larger than its cell reaches past it: up and to the right, + // as a tile stands on the bottom left of its cell (any way on an + // oblique map) const overX = Math.max(this.maxTileSize.width - this.tilewidth, 0); const overY = Math.max(this.maxTileSize.height - this.tileheight, 0); - const upRight = orientation === "orthogonal" || orientation === "isometric"; + const upRight = orientation !== "oblique"; /** * How far past the layer's grid its tiles can be drawn, on each * side: by tiles larger than a cell, and by a tileset's @@ -426,7 +428,7 @@ export default class TMXLayer extends Renderable { /** * How this layer is rendered. Resolved by `onActivateEvent` to one of: - * - `"shader"` — GPU procedural shader path, on WebGL 2 and WebGPU, for orthogonal and isometric maps (single quad per tileset, fragment GID lookup) + * - `"shader"` — GPU procedural shader path, on WebGL 2 and WebGPU, for orthogonal, isometric, staggered and hexagonal maps (single quad per tileset, fragment GID lookup) * - `"prerender"`— offscreen-canvas bake at activation, blitted as one drawImage per frame * - `"perTile"` — per-frame loop, one drawImage per visible tile * @@ -579,7 +581,7 @@ export default class TMXLayer extends Renderable { const renderer = this.getRenderer(); const bounds = renderer.getBounds(this); // an oversized tile reaches past its cell (which way depends on the - // orientation: up on an orthogonal map, down on a hexagonal one), and + // orientation: up and to the right, any way on an oblique map), and // a tileset's offset moves all of its tiles const overX = Math.max(this.maxTileSize.width - this.tilewidth, 0); const overY = Math.max(this.maxTileSize.height - this.tileheight, 0); @@ -777,7 +779,7 @@ export default class TMXLayer extends Renderable { if (!renderer || renderer.supportsShaderTileLayers !== true) { return { ok: false, reason: "no-gpu-renderer" }; } - if (this.orientation !== "orthogonal" && this.orientation !== "isometric") { + if (TMX_ORIENTATIONS[this.orientation] === undefined) { return { ok: false, reason: `no gpu renderer supported yet for "${this.orientation}" orientation`, @@ -786,8 +788,8 @@ export default class TMXLayer extends Renderable { if (!this.tilesets || this.tilesets.tilesets.length === 0) { return { ok: false, reason: "no tilesets" }; } - if (this.orientation === "isometric") { - return this._checkIsometricShaderEligibility(); + if (this.orientation !== "orthogonal") { + return this._checkOverlappingShaderEligibility(); } // the shader iterates a fixed-size loop over candidate cells to // support oversized tiles (tile dim > cell dim) drawn bottom-aligned. @@ -852,12 +854,12 @@ export default class TMXLayer extends Renderable { } /** - * Check whether this isometric layer can take the shader path, and note - * the tileset it would draw with. + * Check whether this layer of an isometric, staggered or hexagonal map + * can take the shader path, and note the tileset it would draw with. * - * Isometric tiles overlap (each is drawn as its whole image, over the - * rows behind it), and the shader path draws one tileset at a time: it - * can keep the tile drawn last among those of one tileset, not across + * On these maps tiles overlap (each is drawn as its whole image, over + * the ones behind it), and the shader path draws one tileset at a time: + * it can keep the tile drawn last among those of one tileset, not across * two. So the layer's tiles must all come from the same tileset. Which * one is found by looking at the tiles, not at the map's list: a map * commonly has a tileset per layer. @@ -865,13 +867,21 @@ export default class TMXLayer extends Renderable { * @ignore * @internal */ - _checkIsometricShaderEligibility() { + _checkOverlappingShaderEligibility() { this._shaderTileset = null; - // Half the tiles of a grid of odd size stand half a pixel off. Tile - // by tile, each is moved to a whole pixel; the shader has one quad - // for all of them, and would draw those a pixel away. - if (this.tilewidth % 2 !== 0 || this.tileheight % 2 !== 0) { - return { ok: false, reason: "an isometric grid of odd size" }; + const kind = kindOf(this.orientation); + // Half the cells of a grid of odd size stand half a pixel off (on a + // hexagonal map, of a side of odd length). Tile by tile, each tile + // is moved to a whole pixel; the shader has one quad for all of + // them, and would draw those a pixel away. + const map = this.getRenderer(); + if ( + this.tilewidth % 2 !== 0 || + this.tileheight % 2 !== 0 || + (this.orientation !== "isometric" && + !(Number.isInteger(map.columnwidth) && Number.isInteger(map.rowheight))) + ) { + return { ok: false, reason: `${kind} grid of odd size` }; } // Tiles overlap, and the shader draws the layer flat, then blends it // as one picture: where tile by tile each tile is blended over the @@ -879,7 +889,7 @@ export default class TMXLayer extends Renderable { if (this.blendMode !== "normal") { return { ok: false, - reason: `blend mode "${this.blendMode}" on an isometric layer`, + reason: `blend mode "${this.blendMode}" on ${kind} layer`, }; } const data = this.layerData; @@ -888,13 +898,13 @@ export default class TMXLayer extends Renderable { const gid = data[i]; if (gid !== 0 && (tileset === null || !tileset.contains(gid))) { if (tileset !== null) { - return { ok: false, reason: ISOMETRIC_ONE_TILESET }; + return { ok: false, reason: oneTilesetReason(this.orientation) }; } tileset = this.tilesets.getTilesetByGid(gid); } } if (tileset !== null) { - const reason = this._isometricTilesetReason(tileset); + const reason = this._overlappingTilesetReason(tileset); if (reason !== undefined) { return { ok: false, reason }; } @@ -908,27 +918,34 @@ export default class TMXLayer extends Renderable { } /** - * Why the isometric shader path cannot draw the tiles of a tileset, if - * it cannot. + * Why the shader path of an isometric, staggered or hexagonal map cannot + * draw the tiles of a tileset, if it cannot. * @param {TMXTileset} tileset - the tileset * @returns {string|undefined} the reason, or undefined when it can * @ignore * @internal */ - _isometricTilesetReason(tileset) { + _overlappingTilesetReason(tileset) { if (tileset.isCollection) { return "collection-of-image tileset"; } if (tileset.tilerendersize !== "tile") { return `tilerendersize "${tileset.tilerendersize}" not supported`; } - // the shader looks, for each pixel, at every cell whose tile image - // could cover it: a bounded number - if ( - tileset.tilewidth > this.tilewidth * ISOMETRIC_MAX_TILE_WIDTHS || - tileset.tileheight > this.tileheight * ISOMETRIC_MAX_TILE_HEIGHTS - ) { - return `tiles larger than the shader's limit (${ISOMETRIC_MAX_TILE_WIDTHS} grid widths by ${ISOMETRIC_MAX_TILE_HEIGHTS} grid heights)`; + // The shader looks, for each pixel, at every cell whose tile image + // could cover it: a bounded number, of lines of cells and of cells + // in a line. On an isometric map the lines are half a grid height + // apart and their cells a grid width; on the others, a row height + // and two column widths + const { MAX_ROWS, MAX_COLS } = TMX_ORIENTATIONS[this.orientation].limits; + const map = this.getRenderer(); + const isometric = this.orientation === "isometric"; + const maxWidth = + MAX_COLS * (isometric ? this.tilewidth : map.columnwidth * 2); + const maxHeight = + MAX_ROWS * (isometric ? this.tileheight / 2 : map.rowheight); + if (tileset.tilewidth > maxWidth || tileset.tileheight > maxHeight) { + return `tiles larger than the shader's limit (${maxWidth} by ${maxHeight} pixels on this grid)`; } return undefined; } @@ -937,9 +954,9 @@ export default class TMXLayer extends Renderable { * A tile set at run time on a layer on the shader path: one that path * cannot draw moves the layer back to the legacy renderer. * - * That is a tile flipped diagonally and not square, and on an isometric - * layer, which draws with one tileset, a tile of another one, or of one - * the path cannot draw. + * That is a tile flipped diagonally and not square, and on a layer of an + * isometric, staggered or hexagonal map, which draws with one tileset, a + * tile of another one, or of one the path cannot draw. * @param {number} gid - the gid of the tile just set * @param {number} flipMask - its flips * @ignore @@ -948,15 +965,15 @@ export default class TMXLayer extends Renderable { _keepShaderEligible(gid, flipMask) { let reason; if ( - this.orientation === "isometric" && + this.orientation !== "orthogonal" && this._shaderTileset?.contains(gid) !== true ) { if (this._shaderTileset) { - reason = ISOMETRIC_ONE_TILESET; + reason = oneTilesetReason(this.orientation); } else { // an empty layer takes its tileset from its first tile const tileset = this.tilesets.getTilesetByGid(gid); - reason = this._isometricTilesetReason(tileset); + reason = this._overlappingTilesetReason(tileset); if (reason === undefined) { this._shaderTileset = tileset; } diff --git a/packages/melonjs/src/level/tiled/renderer/TMXHexagonalRenderer.js b/packages/melonjs/src/level/tiled/renderer/TMXHexagonalRenderer.js index 4d1c27eb9f..63d1bf2935 100644 --- a/packages/melonjs/src/level/tiled/renderer/TMXHexagonalRenderer.js +++ b/packages/melonjs/src/level/tiled/renderer/TMXHexagonalRenderer.js @@ -379,12 +379,32 @@ export default class TMXHexagonalRenderer extends TMXRenderer { * @internal */ drawTileLayer(renderer, layer, rect) { + // The cells whose tile can reach the view. A tile stands on the + // bottom left of its cell, as on every map: one larger than the cell + // reaches up and to the right of it, so the cells that matter past + // the view are those to its left and below it, and a tileset's + // `tileoffset` moves its tiles either way. + const overX = Math.max( + (layer.maxTileSize?.width ?? this.tilewidth) - this.tilewidth, + 0, + ); + const overY = Math.max( + (layer.maxTileSize?.height ?? this.tileheight) - this.tileheight, + 0, + ); + const offsetX = layer.maxTileOffset?.x ?? 0; + const offsetY = layer.maxTileOffset?.y ?? 0; + const left = rect.pos.x - overX - offsetX; + const top = rect.pos.y - offsetY; + const right = rect.right + offsetX; + const bottom = rect.bottom + overY + offsetY; + // the tile at the top-left corner of the area, rounded down to its // column and row (a staggered map's renderer gives a point's place // within its tile too) const startTile = this.pixelToTileCoords( - rect.pos.x, - rect.pos.y, + left, + top, vector2dPool.get(), ).floorSelf(); @@ -403,8 +423,8 @@ export default class TMXHexagonalRenderer extends TMXRenderer { * up due to those tiles being visible as well. How we go up one row * depends on whether we're in the left or right half of the tile. */ - const inUpperHalf = rect.pos.y - startPos.y < this.sideoffsety; - const inLeftHalf = rect.pos.x - startPos.x < this.sideoffsetx; + const inUpperHalf = top - startPos.y < this.sideoffsety; + const inLeftHalf = left - startPos.x < this.sideoffsetx; if (inUpperHalf) { startTile.y--; @@ -452,11 +472,11 @@ export default class TMXHexagonalRenderer extends TMXRenderer { let staggeredRow = this.doStaggerX(startTile.x); // main drawing loop - for (; startPos.y < rect.bottom && startTile.y < endY; ) { + for (; startPos.y < bottom && startTile.y < endY; ) { rowTile.setV(startTile); rowPos.setV(startPos); - for (; rowPos.x < rect.right && rowTile.x < endX; rowTile.x += 2) { + for (; rowPos.x < right && rowTile.x < endX; rowTile.x += 2) { if (rowTile.x >= 0 && rowTile.y >= 0 && rowTile.y < layer.rows) { const idx = (rowTile.y * layerCols + rowTile.x) * 2; const gid = data[idx]; @@ -465,10 +485,14 @@ export default class TMXHexagonalRenderer extends TMXRenderer { if (!tilesetCache.contains(gid)) { tilesetCache = tilesets.getTilesetByGid(gid); } + // standing on its cell, and moved by its + // tileset's offset: where `drawTile` draws it tilesetCache.drawTileRaw( renderer, - rowPos.x, - rowPos.y, + tilesetCache.tileoffset.x + rowPos.x, + tilesetCache.tileoffset.y + + rowPos.y + + (this.tileheight - tilesetCache.tileheight), gid, flipMask, ); @@ -505,7 +529,7 @@ export default class TMXHexagonalRenderer extends TMXRenderer { } // main drawing loop - for (; startPos.y < rect.bottom && startTile.y < endY; startTile.y++) { + for (; startPos.y < bottom && startTile.y < endY; startTile.y++) { rowTile.setV(startTile); rowPos.setV(startPos); @@ -513,7 +537,7 @@ export default class TMXHexagonalRenderer extends TMXRenderer { rowPos.x += this.columnwidth; } - for (; rowPos.x < rect.right && rowTile.x < endX; rowTile.x++) { + for (; rowPos.x < right && rowTile.x < endX; rowTile.x++) { if (rowTile.x >= 0 && rowTile.y >= 0 && rowTile.y < layer.rows) { const idx = (rowTile.y * layerCols + rowTile.x) * 2; const gid = data[idx]; @@ -522,10 +546,14 @@ export default class TMXHexagonalRenderer extends TMXRenderer { if (!tilesetCache.contains(gid)) { tilesetCache = tilesets.getTilesetByGid(gid); } + // standing on its cell, and moved by its + // tileset's offset: where `drawTile` draws it tilesetCache.drawTileRaw( renderer, - rowPos.x, - rowPos.y, + tilesetCache.tileoffset.x + rowPos.x, + tilesetCache.tileoffset.y + + rowPos.y + + (this.tileheight - tilesetCache.tileheight), gid, flipMask, ); diff --git a/packages/melonjs/src/physics/world.js b/packages/melonjs/src/physics/world.js index d26e8eb103..601442e88d 100644 --- a/packages/melonjs/src/physics/world.js +++ b/packages/melonjs/src/physics/world.js @@ -216,18 +216,19 @@ export default class World extends Container { /** * Enable the GPU procedural shader path (WebGL 2 and WebGPU) for - * orthogonal and isometric tile layers. When `true` (default), + * orthogonal, isometric, staggered and hexagonal tile layers. When + * `true` (default), * eligible layers render via a single quad per tileset + a * fragment shader doing per-pixel GID lookup — bypassing the * per-tile drawImage loop entirely. * Supported features on the shader path: animated tiles, flipped * tiles, per-layer opacity and tint, and tiles larger than the * grid: up to 4 cells of overflow on an orthogonal map, up to 4 - * grid widths by 8 grid heights on an isometric one. - * Layers that don't qualify (Canvas, a staggered, hexagonal or - * oblique map, collection-of-image tilesets, larger tiles; on an - * orthogonal map a non-zero `tileoffset`, on an isometric one - * tiles of several tilesets in one layer) fall back to the legacy + * cells wide and 8 tall on the others. + * Layers that don't qualify (Canvas, an oblique map, + * collection-of-image tilesets, larger tiles; on an orthogonal map + * a non-zero `tileoffset`, on the others tiles of several tilesets + * in one layer) fall back to the legacy * path automatically. Set to `false` to disable globally. * @type {boolean} * @default true diff --git a/packages/melonjs/src/video/gpu/tmxlayer_orientation.js b/packages/melonjs/src/video/gpu/tmxlayer_orientation.js index 13b08fdbf1..0691c50798 100644 --- a/packages/melonjs/src/video/gpu/tmxlayer_orientation.js +++ b/packages/melonjs/src/video/gpu/tmxlayer_orientation.js @@ -33,6 +33,11 @@ export function createRegion() { sizeY: 0, overflowX: 0, overflowY: 0, + // a staggered or hexagonal map's: its column width and row height, + // and its stagger axis and index as the shader reads them + staggerX: 0, + staggerY: 0, + staggerMode: 0, }; } @@ -163,6 +168,73 @@ export function isometricRegion(layer, rect, tileset, out) { return true; } +/** + * The part of a staggered or hexagonal layer a view shows, for the tiles of + * one tileset: the two are one geometry (see `staggered-tmxlayer.frag`), + * the second with cells longer by its `hexsidelength`. + * + * As on an isometric map, the quad is the view, cut to where the tileset's + * tiles can be, and the shader works in the layer's pixels with the + * `tileoffset` taken off. + * @param {TMXLayer} layer - the layer + * @param {object} rect - the visible viewport rect (world coords) + * @param {object} tileset - the tileset whose tiles are drawn + * @param {object} out - the region to fill + * @returns {boolean} false when the view shows nothing of the layer + * @ignore + * @internal + */ +export function staggeredRegion(layer, rect, tileset, out) { + const map = layer.getRenderer(); + const columnWidth = map.columnwidth; + const rowHeight = map.rowheight; + const offsetX = tileset.tileoffset.x; + const offsetY = tileset.tileoffset.y; + const cols = layer.cols; + const rows = layer.rows; + + // The cells' boxes: lines a row height apart, and in each, cells two + // column widths apart, every other line shifted by one. A row of the map + // is one line, or two when the stagger axis is x + const lines = map.staggerX ? rows * 2 : rows; + // the last box of a line, in column widths from the first (of a shifted + // line, when the axis is y) + const lastBox = map.staggerX ? cols - 1 : cols * 2 - 1; + // where the tiles can be: from the left of the first box to the right of + // the last one's image, from the top of the first line's images to the + // bottom of the last line's boxes + const left = offsetX; + const right = lastBox * columnWidth + tileset.tilewidth + offsetX; + const top = layer.tileheight - tileset.tileheight + offsetY; + const bottom = (lines - 1) * rowHeight + layer.tileheight + offsetY; + + // the view, cut to it, on whole pixels + const x0 = Math.floor(Math.max(rect.pos.x, left)); + const y0 = Math.floor(Math.max(rect.pos.y, top)); + const x1 = Math.ceil(Math.min(rect.pos.x + rect.width, right)); + const y1 = Math.ceil(Math.min(rect.pos.y + rect.height, bottom)); + if (x1 <= x0 || y1 <= y0) { + return false; + } + + out.x = x0; + out.y = y0; + out.width = x1 - x0; + out.height = y1 - y0; + out.startX = x0 - offsetX; + out.startY = y0 - offsetY; + out.sizeX = out.width; + out.sizeY = out.height; + // how many cells' images reach a pixel: as many in a line as the image + // is wide in cell spacings, as many lines as it is tall in row heights + out.overflowX = Math.ceil(tileset.tilewidth / (columnWidth * 2)); + out.overflowY = Math.ceil(tileset.tileheight / rowHeight); + out.staggerX = columnWidth; + out.staggerY = rowHeight; + out.staggerMode = (map.staggerX ? 1 : 0) + (map.staggerEven ? 2 : 0); + return true; +} + /** * How many tiles a tileset's image has across: counted from the margin, a * tile plus the spacing apart, the last column going without its outer @@ -199,6 +271,37 @@ export function atlasRows(tileset) { ); } +/** + * What the orientations whose tiles overlap share: a layer is drawn with + * ONE tileset. A pass keeps the order of the tiles of one tileset, not + * across two (`layer._shaderTileset`, found by the layer when it is checked + * for this path). + */ +const ONE_TILESET = { + /** + * @param {TMXLayer} layer - the layer + * @param {object[]} scratch - an array to fill + * @returns {object[]} that tileset, or none for an empty layer + */ + tilesetsOf(layer, scratch) { + scratch.length = 0; + if (layer._shaderTileset) { + scratch.push(layer._shaderTileset); + } + return scratch; + }, + /** + * not a layer with no tileset to draw with: one that was never + * checked, or whose tiles come from several (`null`; an empty layer + * has `undefined`, and draws nothing) + * @param {TMXLayer} layer - the layer + * @returns {boolean} whether the layer can be drawn + */ + draws(layer) { + return layer._shaderTileset !== null; + }, +}; + /** * The map orientations the GPU tile layer renderers draw. * @ignore @@ -223,35 +326,24 @@ export const TMX_ORIENTATIONS = { }, isometric: { region: isometricRegion, - /** - * The one tileset an isometric layer draws with: its tiles overlap, - * and a pass keeps the order of the tiles of one tileset, not across - * two (`layer._shaderTileset`, found by the layer when it is checked - * for this path). - * @param {TMXLayer} layer - the layer - * @param {object[]} scratch - an array to fill - * @returns {object[]} that tileset, or none for an empty layer - */ - tilesetsOf(layer, scratch) { - scratch.length = 0; - if (layer._shaderTileset) { - scratch.push(layer._shaderTileset); - } - return scratch; - }, - /** - * not a layer with no tileset to draw with: one that was never - * checked, or whose tiles come from several (`null`; an empty layer - * has `undefined`, and draws nothing) - * @param {TMXLayer} layer - the layer - * @returns {boolean} whether the layer can be drawn - */ - draws(layer) { - return layer._shaderTileset !== null; - }, + ...ONE_TILESET, // the cells whose image can reach a pixel: rows of them, half a // grid height apart, and in each, cells a grid width apart. So // tiles up to MAX_ROWS / 2 grid heights tall, MAX_COLS wide limits: { MAX_ROWS: 16, MAX_COLS: 4 }, }, + // one geometry for both: lines of cells, a row height apart, and in + // each, cells two column widths apart + staggered: { + region: staggeredRegion, + ...ONE_TILESET, + staggered: true, + limits: { MAX_ROWS: 16, MAX_COLS: 4 }, + }, + hexagonal: { + region: staggeredRegion, + ...ONE_TILESET, + staggered: true, + limits: { MAX_ROWS: 16, MAX_COLS: 4 }, + }, }; diff --git a/packages/melonjs/src/video/webgl/renderers/tmxlayer/tmxlayer.js b/packages/melonjs/src/video/webgl/renderers/tmxlayer/tmxlayer.js index 0ad3e0fbf0..c2cb1d7017 100644 --- a/packages/melonjs/src/video/webgl/renderers/tmxlayer/tmxlayer.js +++ b/packages/melonjs/src/video/webgl/renderers/tmxlayer/tmxlayer.js @@ -8,6 +8,7 @@ import { BufferTextureResource } from "../../../texture/resource.js"; import GLShader from "../../glshader.js"; import isometricFragment from "../../shaders/isometric-tmxlayer.frag"; import orthogonalFragment from "../../shaders/orthogonal-tmxlayer.frag"; +import staggeredFragment from "../../shaders/staggered-tmxlayer.frag"; import tmxLayerVertex from "../../shaders/tmxlayer.vert"; import tmxLayerCommonFragment from "../../shaders/tmxlayer-common.frag"; @@ -21,6 +22,9 @@ import tmxLayerCommonFragment from "../../shaders/tmxlayer-common.frag"; const FRAGMENTS = { orthogonal: orthogonalFragment, isometric: isometricFragment, + // one geometry: a hexagonal map's cells are longer, no more + staggered: staggeredFragment, + hexagonal: staggeredFragment, }; // Default `uTint` when the layer has no tint set. Module-scoped so the @@ -435,6 +439,10 @@ export default class TMXLayerGPURenderer { this._setV2("uVisibleStart", region.startX, region.startY); this._setV2("uVisibleSize", region.sizeX, region.sizeY); this._setV2("uOverflow", region.overflowX, region.overflowY); + if (this.orientation.staggered === true) { + this._setV2("uStagger", region.staggerX, region.staggerY); + this.shader.setUniform("uStaggerMode", region.staggerMode); + } this._setV2("uGidRange", tileset.firstgid, tileset.lastgid); // the tileset samples its mipmaps when the batcher binds it a // mip sampler: the "linear-mipmap" filter, on a linear texture diff --git a/packages/melonjs/src/video/webgl/shaders/staggered-tmxlayer.frag b/packages/melonjs/src/video/webgl/shaders/staggered-tmxlayer.frag new file mode 100644 index 0000000000..d3324e176e --- /dev/null +++ b/packages/melonjs/src/video/webgl/shaders/staggered-tmxlayer.frag @@ -0,0 +1,85 @@ +// The staggered and hexagonal part of the TMX layer fragment shader: +// appended to `tmxlayer-common.frag`. +// +// Both maps are one geometry, in the layer's pixels (the renderer takes the +// tileset's `tileoffset` off before a position gets here). Cells stand in +// lines, a `rowheight` apart down the screen; in a line they are two +// `columnwidth` apart, and every other line is shifted by one `columnwidth` +// (which ones, `staggerindex` says). A hexagonal map's cells are longer by +// its `hexsidelength`, which is in those two lengths already. +// +// What `staggeraxis` changes is which cell a place in a line is: +// "y": a line is a row of the map, and its cells are that row's columns; +// "x": a row of the map is two lines, its columns alternating between +// them, so a line holds every other column of one row. +// +// The tile of a cell is drawn as its whole image, standing on the bottom +// left of the cell. So the cells whose image covers a fragment are a run of +// lines, as long as the image is tall in row heights, and in each a run of +// cells, as long as it is wide in cell spacings: `uOverflow` holds the two +// lengths. The CPU renderer draws the lines from the top of the screen +// down, each from the left: the scan here goes the other way, and puts each +// texel behind the ones before it until the fragment is opaque. +// +// `MAX_ROWS` and `MAX_COLS`, the bounds of the two runs, are declared ahead +// of this file (see `TMX_ORIENTATIONS` in `gpu/tmxlayer_orientation.js`): a +// layer of larger tiles is left to the CPU renderer. + +uniform vec2 uStagger; // (columnwidth, rowheight) +uniform float uStaggerMode; // 1 when the stagger axis is x, + 2 when the index is even + +// whether a line is one of the shifted ones: 1, or 0 +int shifted(int line) { + return (line & 1) ^ (int(uStaggerMode) >> 1); +} + +// the bottom left of the cell's box, less the tile's height +vec2 tileOrigin(int cx, int cy) { + bool staggerX = (int(uStaggerMode) & 1) == 1; + // the cell's line, and how far along it the cell is + int line = staggerX ? 2 * cy + shifted(cx) : cy; + float x = staggerX + ? float(cx) * uStagger.x + : float(2 * cx + shifted(cy)) * uStagger.x; + return vec2(x, float(line) * uStagger.y + uCellSize.y - uTileSize.y); +} + +void main(void) { + vec2 worldPx = uVisibleStart + vRegion * uVisibleSize; + Footprint fp = footprint(worldPx); + + bool staggerX = (int(uStaggerMode) & 1) == 1; + float spacing = uStagger.x * 2.0; + // the lowest line whose image can reach the fragment + int lineMax = int(floor((worldPx.y - uCellSize.y + uTileSize.y) / uStagger.y)); + int spanK = int(uOverflow.x + 0.5); + int spanL = int(uOverflow.y + 0.5); + // lines past the map's last one, or before its first, hold no cell + int lineLast = (staggerX ? 2 * int(uMapSize.y) : int(uMapSize.y)) - 1; + + vec4 result = vec4(0.0); + vec4 texel; + bool opaque = false; + for (int j = max(lineMax - lineLast, 0); j < MAX_ROWS; j++) { + int line = lineMax - j; + if (j >= spanL || line < 0) break; + int shift = shifted(line); + // the rightmost cell of the line whose image can reach the fragment + int kMax = int(floor((worldPx.x - float(shift) * uStagger.x) / spacing)); + for (int i = 0; i < MAX_COLS; i++) { + if (i >= spanK) break; + int k = kMax - i; + int cx = staggerX ? 2 * k + shift : k; + int cy = staggerX ? line >> 1 : line; + if (tryRenderCell(cx, cy, worldPx, fp, texel)) { + if (under(result, texel)) { + opaque = true; + break; + } + } + } + if (opaque) break; + } + if (result.a <= 0.0) discard; + fragColor = layerColor(result); +} diff --git a/packages/melonjs/src/video/webgpu/renderers/tmxlayer/tmxlayer.js b/packages/melonjs/src/video/webgpu/renderers/tmxlayer/tmxlayer.js index a0ccbd8eaf..750487c91e 100644 --- a/packages/melonjs/src/video/webgpu/renderers/tmxlayer/tmxlayer.js +++ b/packages/melonjs/src/video/webgpu/renderers/tmxlayer/tmxlayer.js @@ -9,6 +9,7 @@ import { import tmxLayerCommonWGSL from "../../shaders/tmxlayer-common.wgsl"; import isometricWGSL from "../../shaders/tmxlayer-isometric.wgsl"; import orthogonalWGSL from "../../shaders/tmxlayer-orthogonal.wgsl"; +import staggeredWGSL from "../../shaders/tmxlayer-staggered.wgsl"; /** * additional imports for TypeScript @@ -30,6 +31,9 @@ const TMX_UNIFORM_SIZE = 128; const ORIENTATION_WGSL = { orthogonal: orthogonalWGSL, isometric: isometricWGSL, + // one geometry: a hexagonal map's cells are longer, no more + staggered: staggeredWGSL, + hexagonal: staggeredWGSL, }; /** @@ -460,6 +464,11 @@ export default class TMXLayerGPURenderer { const mipmaps = filter === "linear" && renderer.wantsMipmaps(tileset.texture); scratch[28] = mipmaps ? 1 : 0; + // a staggered or hexagonal map's (0 on the others, which have + // no use for them) + scratch[29] = region.staggerMode; + scratch[30] = region.staggerX; + scratch[31] = region.staggerY; const uniforms = renderer.effectUniformArena.alloc( TMX_UNIFORM_SIZE, device.limits?.minUniformBufferOffsetAlignment ?? 256, diff --git a/packages/melonjs/src/video/webgpu/shaders/tmxlayer-common.wgsl b/packages/melonjs/src/video/webgpu/shaders/tmxlayer-common.wgsl index 5cc80843d8..711d52a2b3 100644 --- a/packages/melonjs/src/video/webgpu/shaders/tmxlayer-common.wgsl +++ b/packages/melonjs/src/video/webgpu/shaders/tmxlayer-common.wgsl @@ -41,6 +41,10 @@ struct TMXUniforms { uAnimSize : f32, // entries in the anim lookup, 0 when disabled uTint : vec4f, uMipmaps : f32, // 1 under the "linear-mipmap" filter, else 0 + // a staggered or hexagonal map's (see tmxlayer-staggered.wgsl); they + // fill what was the block's padding + uStaggerMode : f32, // 1 when the stagger axis is x, + 2 when the index is even + uStagger : vec2f, // (columnwidth, rowheight) }; @group(0) @binding(0) var uFrame : FrameUniforms; diff --git a/packages/melonjs/src/video/webgpu/shaders/tmxlayer-staggered.wgsl b/packages/melonjs/src/video/webgpu/shaders/tmxlayer-staggered.wgsl new file mode 100644 index 0000000000..90d06b8939 --- /dev/null +++ b/packages/melonjs/src/video/webgpu/shaders/tmxlayer-staggered.wgsl @@ -0,0 +1,83 @@ +// The staggered and hexagonal part of the TMX layer shader: appended to +// tmxlayer-common.wgsl. The WGSL port of staggered-tmxlayer.frag, where the +// geometry is explained. +// +// Cells stand in lines, `tmx.uStagger.y` (a row height) apart down the +// screen; in a line they are two `tmx.uStagger.x` (a column width) apart, +// and every other line is shifted by one. With the stagger axis "y" a line +// is a row of the map; with "x" a row is two lines, its columns alternating +// between them. +// +// `MAX_ROWS` and `MAX_COLS`, the bounds of the two runs, are declared ahead +// of this file (see `TMX_ORIENTATIONS` in gpu/tmxlayer_orientation.js). + +// whether a line is one of the shifted ones: 1, or 0 +fn shifted(line : i32) -> i32 { + return (line & 1) ^ (i32(tmx.uStaggerMode) >> 1u); +} + +// the bottom left of the cell's box, less the tile's height +fn tileOrigin(cx : i32, cy : i32) -> vec2f { + let staggerX = (i32(tmx.uStaggerMode) & 1) == 1; + var line = cy; + var x = f32(2 * cx + shifted(cy)) * tmx.uStagger.x; + if (staggerX) { + line = 2 * cy + shifted(cx); + x = f32(cx) * tmx.uStagger.x; + } + return vec2f(x, f32(line) * tmx.uStagger.y + tmx.uCellSize.y - tmx.uTileSize.y); +} + +@fragment +fn fragment_main(in : VSOut) -> @location(0) vec4f { + let worldPx = tmx.uVisibleStart + in.vRegion * tmx.uVisibleSize; + let fp = footprint(worldPx); + + let staggerX = (i32(tmx.uStaggerMode) & 1) == 1; + let spacing = tmx.uStagger.x * 2.0; + // the lowest line whose image can reach the fragment + let lineMax = i32(floor((worldPx.y - tmx.uCellSize.y + tmx.uTileSize.y) / tmx.uStagger.y)); + let spanK = i32(tmx.uOverflow.x + 0.5); + let spanL = i32(tmx.uOverflow.y + 0.5); + // lines past the map's last one, or before its first, hold no cell + var lineLast = i32(tmx.uMapSize.y) - 1; + if (staggerX) { + lineLast = 2 * i32(tmx.uMapSize.y) - 1; + } + + var result = vec4f(0.0); + var opaque = false; + for (var j = max(lineMax - lineLast, 0); j < MAX_ROWS; j++) { + let line = lineMax - j; + if (j >= spanL || line < 0) { + break; + } + let shift = shifted(line); + // the rightmost cell of the line whose image can reach the fragment + let kMax = i32(floor((worldPx.x - f32(shift) * tmx.uStagger.x) / spacing)); + for (var i = 0; i < MAX_COLS; i++) { + if (i >= spanK) { + break; + } + let k = kMax - i; + var cx = k; + var cy = line; + if (staggerX) { + cx = 2 * k + shift; + cy = line >> 1u; + } + let candidate = tryRenderCell(cx, cy, worldPx, fp); + if (candidate.hit && under(&result, candidate.color)) { + opaque = true; + break; + } + } + if (opaque) { + break; + } + } + if (result.a <= 0.0) { + discard; + } + return layerColor(result); +} diff --git a/packages/melonjs/tests/helpers/tile-layer-compare.js b/packages/melonjs/tests/helpers/tile-layer-compare.js index 3b13bba0e9..2c5afa8521 100644 --- a/packages/melonjs/tests/helpers/tile-layer-compare.js +++ b/packages/melonjs/tests/helpers/tile-layer-compare.js @@ -9,7 +9,7 @@ * edges (the default) the two paths are held to the same picture, exactly; * with soft ones (`alpha`), to a rounding step or two. */ -import { vi } from "vitest"; +import { expect, vi } from "vitest"; import { Application, boot, TMXTileMap, timer } from "../../src/index.js"; import { imgList } from "../../src/loader/cache.js"; import Renderer from "../../src/video/renderer.js"; @@ -199,8 +199,10 @@ export function makeMap(options) { * each from the left), where Tiled draws them, with nothing left out for * being out of view. What both of the engine's renderers are held to. * - * Tiles are drawn whole, bottom-aligned on their cell and moved by their - * tileset's `tileoffset`; flipped across, down or along the diagonal (the + * Orthogonal, isometric, staggered and hexagonal maps (the last two take + * their `staggeraxis`, `staggerindex` and `hexsidelength` from the scene's + * `extra`). Tiles are drawn whole, bottom-aligned on their cell and moved by + * their tileset's `tileoffset`; flipped across, down or along the diagonal (the * last on square tiles only, where a flip is a quarter turn in place). * A layer is moved by its offset in Tiled (`offsetx`, `offsety`). Layer * opacity and tint are for the caller to apply to the picture. @@ -298,6 +300,40 @@ export function reference(scene, viewX, viewY, width, height) { oy + ((col + row + 2) * th) / 2, ); } + } else if (orientation === "staggered" || orientation === "hexagonal") { + // Every other row (or column, with `staggeraxis` "x") is + // shifted by half a cell; a hexagonal map's cells are longer + // by `hexsidelength` along the stagger axis. Tiles are drawn + // from the top of the screen down, each line from the left. + const { staggeraxis, staggerindex, hexsidelength = 0 } = scene.extra; + const staggerX = staggeraxis === "x"; + const even = staggerindex === "even" ? 1 : 0; + const side = orientation === "hexagonal" ? hexsidelength : 0; + const sideX = staggerX ? side : 0; + const sideY = staggerX ? 0 : side; + const columnWidth = (tw - sideX) / 2 + sideX; + const rowHeight = (th - sideY) / 2 + sideY; + const place = ({ col, row }) => { + // `& 1` and not `% 2`: an infinite map has negative cells + return staggerX + ? { + x: col * columnWidth, + y: row * (th + sideY) + ((col & 1) ^ even) * rowHeight, + } + : { + x: col * (tw + sideX) + ((row & 1) ^ even) * columnWidth, + y: row * rowHeight, + }; + }; + const placed = ordered.map((cell) => { + return { ...cell, ...place(cell) }; + }); + placed.sort((a, b) => { + return a.y - b.y || a.x - b.x; + }); + for (const { gid, x, y } of placed) { + drawTile(gid, ox + x, oy + y + th); + } } else { ordered.sort((a, b) => { return a.row - b.row || a.col - b.col; @@ -472,3 +508,83 @@ export function drawn(frame) { } return count; } + +/** views over a map: inside, over each edge, and scrolled part way */ +const DEFAULT_VIEWS = [ + [0, 0], + [70, 20], + [-40, -80], + [230, 110], + [-150, 30], + [100, -200], +]; + +/** + * Draw a scene both ways from each view, and expect the reference + * picture from both, the GPU path drawing alone. + * @param {Application} app - the application, from {@link makeApp} + * @param {object} scene - what {@link makeMap} takes + * @param {object} [options] + * @param {number[][]} [options.views] - where to look from + * @param {object[]} [options.layers] - the scene's layers, when + * they are in the world already (and were changed there). Without + * them the scene is put in the world here, and every layer of it is + * expected to take the GPU path of its own accord + * @param {boolean} [options.oracle=true] - false where the reference + * does not reach (a zoomed camera): the two paths are then compared + * with each other alone + * @param {(picture: ImageData) => ImageData} [options.expected] + * what the reference becomes (a faded or tinted layer) + * @param {number} [options.tolerance=0] - the largest difference of a + * channel that is not counted + * @param {number} [options.share=0] - the largest share of the pixels + * drawn that the two paths may differ by + * @returns {Promise} how many pixels were drawn, in all + */ +export async function comparePaths(app, scene, options = {}) { + const { + views = DEFAULT_VIEWS, + oracle = true, + expected, + tolerance = 0, + share = 0, + } = options; + const { width, height } = app.viewport; + let layers = options.layers; + if (layers === undefined) { + layers = show(app, makeMap(scene)); + for (const layer of layers) { + expect(layer.renderMode, layer.name).toBe("shader"); + } + } + let total = 0; + for (const [x, y] of views) { + app.viewport.moveTo(x, y); + const cpu = await drawIn(app, layers, "perTile"); + const gpu = await drawIn(app, layers, "shader"); + // a layer out of view is not drawn at all; one in view is + // drawn tile by tile by the CPU path, and never by the GPU one + expect(cpu.cpuDraws).toBeLessThanOrEqual(layers.length); + expect(gpu.cpuDraws, "the GPU path reaches no CPU renderer").toBe(0); + const at = `view (${x}, ${y})`; + const count = drawn(gpu.frame); + const allowed = Math.floor(count * share); + if (oracle) { + let ref = reference(scene, x, y, width, height); + if (expected !== undefined) { + ref = expected(ref); + } + const c = diff(ref, cpu.frame, tolerance); + expect(c.different, `${at}, CPU path: ${c.first}`).toBe(0); + const g = diff(ref, gpu.frame, tolerance); + expect(g.different, `${at}, GPU path: ${g.first}`).toBe(0); + } + const d = diff(cpu.frame, gpu.frame, tolerance); + expect( + d.different, + `${at}, CPU against GPU: ${d.first}`, + ).toBeLessThanOrEqual(allowed); + total += count; + } + return total; +} diff --git a/packages/melonjs/tests/helpers/tile-layer-isometric-scenarios.js b/packages/melonjs/tests/helpers/tile-layer-isometric-scenarios.js index 7debb5bf20..1764611e2e 100644 --- a/packages/melonjs/tests/helpers/tile-layer-isometric-scenarios.js +++ b/packages/melonjs/tests/helpers/tile-layer-isometric-scenarios.js @@ -16,6 +16,7 @@ import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; import { grabFrame } from "./pixels.js"; import { + comparePaths, diff, drawIn, drawn, @@ -158,72 +159,8 @@ export function isometricScenarios(renderer, type) { } }; - /** - * Draw a scene both ways from each view, and expect the reference - * picture from both, the GPU path drawing alone. - * @param {object} scene - what `makeMap` takes - * @param {object} [options] - * @param {number[][]} [options.views] - where to look from - * @param {object[]} [options.layers] - the scene's layers, when - * they are in the world already (and were changed there). Without - * them the scene is put in the world here, and every layer of it is - * expected to take the GPU path of its own accord - * @param {boolean} [options.oracle=true] - false where the reference - * does not reach (a zoomed camera): the two paths are then compared - * with each other alone - * @param {(picture: ImageData) => ImageData} [options.expected] - * what the reference becomes (a faded or tinted layer) - * @param {number} [options.tolerance=0] - the largest difference of a - * channel that is not counted - * @param {number} [options.share=0] - the largest share of the pixels - * drawn that the two paths may differ by - * @returns {Promise} how many pixels were drawn, in all - */ - const same = async (scene, options = {}) => { - const { - views = VIEWS, - oracle = true, - expected, - tolerance = 0, - share = 0, - } = options; - let layers = options.layers; - if (layers === undefined) { - layers = show(app, makeMap(scene)); - for (const layer of layers) { - expect(layer.renderMode, layer.name).toBe("shader"); - } - } - let total = 0; - for (const [x, y] of views) { - app.viewport.moveTo(x, y); - const cpu = await drawIn(app, layers, "perTile"); - const gpu = await drawIn(app, layers, "shader"); - // a layer out of view is not drawn at all; one in view is - // drawn tile by tile by the CPU path, and never by the GPU one - expect(cpu.cpuDraws).toBeLessThanOrEqual(layers.length); - expect(gpu.cpuDraws, "the GPU path reaches no CPU renderer").toBe(0); - const at = `view (${x}, ${y})`; - const count = drawn(gpu.frame); - const allowed = Math.floor(count * share); - if (oracle) { - let ref = reference(scene, x, y, WIDTH, HEIGHT); - if (expected !== undefined) { - ref = expected(ref); - } - const c = diff(ref, cpu.frame, tolerance); - expect(c.different, `${at}, CPU path: ${c.first}`).toBe(0); - const g = diff(ref, gpu.frame, tolerance); - expect(g.different, `${at}, GPU path: ${g.first}`).toBe(0); - } - const d = diff(cpu.frame, gpu.frame, tolerance); - expect( - d.different, - `${at}, CPU against GPU: ${d.first}`, - ).toBeLessThanOrEqual(allowed); - total += count; - } - return total; + const same = (scene, options) => { + return comparePaths(app, scene, options); }; /** how a layer of the scene ends up drawn, and what was warned */ @@ -1180,22 +1117,6 @@ export function isometricScenarios(renderer, type) { expect(drawn(forced.frame)).toBeGreaterThan(0); }); - it("a staggered map, still", (ctx) => { - need(ctx); - const [mode, said] = modeOf({ - orientation: "staggered", - cols: 4, - rows: 4, - tw: TW, - th: TH, - tilesets: [blocks()], - layers: [{ data: scattered(4, 4) }], - extra: { staggeraxis: "y", staggerindex: "odd" }, - }); - expect(mode).toBe("perTile"); - expect(said).toMatch(/no gpu renderer supported yet for "staggered"/); - }); - it("any layer, with gpuTilemap off", (ctx) => { need(ctx); app.world.gpuTilemap = false; diff --git a/packages/melonjs/tests/helpers/tile-layer-staggered-scenarios.js b/packages/melonjs/tests/helpers/tile-layer-staggered-scenarios.js new file mode 100644 index 0000000000..a78cb54f47 --- /dev/null +++ b/packages/melonjs/tests/helpers/tile-layer-staggered-scenarios.js @@ -0,0 +1,536 @@ +/** + * Staggered and hexagonal tile layers, held to the picture Tiled draws: the + * scenes, and for a GPU backend the same comparison as the isometric ones + * (`tile-layer-isometric-scenarios.js`): the CPU renderer, the GPU one and + * a reference painted with no engine, pixel by pixel. + * + * Both orientations are one geometry: lines of cells, every other one + * shifted by half a cell, along the map's rows (`staggeraxis` "y") or its + * columns ("x"); a hexagonal map's cells are longer by `hexsidelength`. + */ +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { + comparePaths, + diff, + drawIn, + drawn, + FLIP_AD, + FLIP_H, + FLIP_V, + fill, + inBlock, + makeApp, + makeMap, + makeTileset, + reference, + show, +} from "./tile-layer-compare.js"; + +export const WIDTH = 320; +export const HEIGHT = 240; + +const COLS = 9; +const ROWS = 11; + +/** most cells filled, a few holes */ +const scattered = (cols = COLS, rows = ROWS, firstgid = 1) => { + return fill(cols, rows, (c, r) => { + return (c * 3 + r) % 7 === 0 ? 0 : firstgid + ((c + r * 2) % 8); + }); +}; + +/** the grids: a staggered map's diamonds, and hexagons either way up */ +const GRIDS = [ + { orientation: "staggered", tw: 64, th: 32 }, + { orientation: "hexagonal", tw: 28, th: 24, hexsidelength: 12 }, +]; + +/** + * A staggered or hexagonal scene. + * @param {object} grid - one of `GRIDS` + * @param {string} staggeraxis - "x" or "y" + * @param {string} staggerindex - "odd" or "even" + * @param {object} tileset - from `makeTileset` + * @param {object} [more] - what else the scene has (its layers, by default + * one of `scattered` cells) + * @returns {object} the scene, for `makeMap` and `reference` + */ +export const staggeredScene = ( + grid, + staggeraxis, + staggerindex, + tileset, + more = {}, +) => { + const { orientation, tw, th, hexsidelength } = grid; + return { + orientation, + cols: COLS, + rows: ROWS, + tw, + th, + tilesets: [tileset], + layers: [{ data: scattered() }], + ...more, + extra: { staggeraxis, staggerindex, hexsidelength, ...more.extra }, + }; +}; + +/** the kinds of tiles each grid is drawn with */ +const TILES = [ + { + label: "tiles the size of a cell, filling it: every overlap shows", + make: ({ tw, th }) => { + return makeTileset({ tw, th }); + }, + }, + { + label: "tiles taller than a cell, standing on it", + make: ({ tw, th }) => { + return makeTileset({ + tw, + th: th * 3, + opaque: (x, y) => { + return inBlock(x, y, tw, th * 3, tw, th); + }, + }); + }, + }, + { + label: "tiles wider and taller than a cell, moved by a tileoffset", + make: ({ tw, th }) => { + return makeTileset({ + tw: tw + 20, + th: th * 2 + 6, + opaque: (x, y) => { + return (x + y) % 11 !== 0; + }, + extra: { tileoffset: { x: -6, y: 10 } }, + }); + }, + }, +]; + +/** every grid, either axis, either index, each kind of tiles */ +export const STAGGERED_SCENES = []; +for (const grid of GRIDS) { + for (const staggeraxis of ["y", "x"]) { + for (const staggerindex of ["odd", "even"]) { + for (const tiles of TILES) { + STAGGERED_SCENES.push({ + label: `${grid.orientation}, axis ${staggeraxis}, ${staggerindex}: ${tiles.label}`, + scene: () => { + return staggeredScene( + grid, + staggeraxis, + staggerindex, + tiles.make(grid), + ); + }, + }); + } + } + } +} + +export const STAGGERED_VIEWS = [ + [0, 0], + [70, 20], + [-40, -80], + [230, 110], + [-150, 30], + [100, -200], + [33, 57], +]; + +/** + * Declare the scenarios for one GPU backend. + * @param {number} renderer - `video.WEBGL` or `video.WEBGPU` + * @param {string} type - the `renderer.type` expected ("WebGL", "WebGPU") + */ +export function staggeredScenarios(renderer, type) { + describe(`staggered and hexagonal tile layers on the GPU, against the CPU renderer and a reference (${type})`, () => { + let app; + beforeAll(async () => { + app = await makeApp(renderer, type, WIDTH, HEIGHT); + }); + afterAll(() => { + app?.destroy(); + vi.restoreAllMocks(); + }); + + const need = (ctx) => { + if (app === null || app === undefined) { + ctx.skip(`${type} not available in this environment`); + } + }; + const same = (scene, options = {}) => { + return comparePaths(app, scene, { views: STAGGERED_VIEWS, ...options }); + }; + const modeOf = (scene) => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + const layer = show(app, makeMap(scene))[0]; + return [layer.renderMode, warn.mock.calls.flat().join(" ")]; + } finally { + warn.mockRestore(); + } + }; + const [STAGGERED, HEXAGONAL] = GRIDS; + const blocks = (grid, tall = 2, options = {}) => { + return makeTileset({ + tw: grid.tw, + th: grid.th * tall, + opaque: (x, y) => { + return inBlock(x, y, grid.tw, grid.th * tall, grid.tw, grid.th); + }, + ...options, + }); + }; + + describe("every grid, either way", () => { + for (const { label, scene } of STAGGERED_SCENES) { + it(label, async (ctx) => { + need(ctx); + expect(await same(scene())).toBeGreaterThan(0); + }); + } + }); + + describe("what a tile and a layer can be", () => { + it("tiles with soft edges, and see-through: each shows the tiles behind it", async (ctx) => { + need(ctx); + for (const grid of GRIDS) { + const tileset = makeTileset({ + tw: grid.tw, + th: grid.th * 2, + alpha: (x, y, id) => { + const edge = Math.min(x, y, grid.tw - 1 - x, grid.th * 2 - 1 - y); + const a = id % 3 === 2 ? 110 : 255; + return Math.round(a * Math.min(1, (edge + 1) / 4)); + }, + }); + for (const axis of ["y", "x"]) { + expect( + await same(staggeredScene(grid, axis, "odd", tileset), { + tolerance: 3, + }), + `${grid.orientation}, axis ${axis}`, + ).toBeGreaterThan(0); + } + } + }); + + it("tiles flipped, every way", async (ctx) => { + need(ctx); + const flips = [ + 0, + FLIP_H, + FLIP_V, + FLIP_H + FLIP_V, + FLIP_AD, + FLIP_H + FLIP_AD, + FLIP_V + FLIP_AD, + FLIP_H + FLIP_V + FLIP_AD, + ]; + // square tiles: a diagonal flip turns the image a quarter + const tileset = makeTileset({ + tw: 64, + th: 64, + opaque: (x, y) => { + return x + y > 20; + }, + }); + const scene = staggeredScene(STAGGERED, "y", "odd", tileset, { + layers: [ + { + data: fill(COLS, ROWS, (c, r) => { + return 1 + ((c + r) % 8) + flips[(c * 3 + r) % 8]; + }), + }, + ], + }); + expect(await same(scene)).toBeGreaterThan(0); + }); + + it("animated tiles, as time passes", async (ctx) => { + need(ctx); + const tileset = blocks(STAGGERED, 2, { + extra: { + tiles: [ + { + id: 0, + animation: [ + { tileid: 0, duration: 100 }, + { tileid: 5, duration: 100 }, + ], + }, + ], + }, + }); + const layers = show( + app, + makeMap(staggeredScene(STAGGERED, "x", "even", tileset)), + ); + expect(layers[0].renderMode).toBe("shader"); + app.viewport.moveTo(0, 0); + const frames = []; + for (let step = 0; step < 4; step++) { + const cpu = await drawIn(app, layers, "perTile", 60); + const gpu = await drawIn(app, layers, "shader"); + expect(gpu.cpuDraws).toBe(0); + const d = diff(cpu.frame, gpu.frame); + expect(d.different, `step ${step}: ${d.first}`).toBe(0); + frames.push(gpu.frame); + } + expect(diff(frames[0], frames[2]).different).toBeGreaterThan(0); + }); + + it("a layer offset in Tiled, and moved in the game", async (ctx) => { + need(ctx); + for (const grid of GRIDS) { + const scene = staggeredScene(grid, "y", "even", blocks(grid), { + layers: [{ data: scattered(), offsetx: 37, offsety: -21 }], + }); + const layers = show(app, makeMap(scene)); + expect(await same(scene, { layers })).toBeGreaterThan(0); + layers[0].pos.x += 50; + layers[0].pos.y += 64; + scene.layers[0].offsetx += 50; + scene.layers[0].offsety += 64; + expect(await same(scene, { layers })).toBeGreaterThan(0); + } + }); + + it("two layers, each on a tileset of its own", async (ctx) => { + need(ctx); + const scene = staggeredScene( + STAGGERED, + "y", + "odd", + blocks(STAGGERED, 1), + { + tilesets: [blocks(STAGGERED, 1), blocks(STAGGERED, 3)], + layers: [ + { data: scattered() }, + { + data: fill(COLS, ROWS, (c, r) => { + return (c + r) % 3 === 0 ? 9 + ((c * 2 + r) % 8) : 0; + }), + }, + ], + }, + ); + expect(await same(scene)).toBeGreaterThan(0); + }); + + it("a layer of an infinite map, starting left of and above the origin", async (ctx) => { + need(ctx); + const chunk = (x, y) => { + return { + x, + y, + width: 4, + height: 4, + data: fill(4, 4, (c, r) => { + return (c + r + x) % 5 === 0 ? 0 : 1 + ((c + r * 2) % 8); + }), + }; + }; + for (const grid of GRIDS) { + for (const axis of ["y", "x"]) { + const scene = staggeredScene(grid, axis, "odd", blocks(grid), { + cols: 8, + rows: 8, + layers: [ + { + startx: -4, + starty: -4, + width: 12, + height: 8, + data: undefined, + chunks: [ + chunk(-4, -4), + chunk(0, -4), + chunk(4, 0), + chunk(0, 0), + ], + }, + ], + extra: { infinite: true }, + }); + const layers = show(app, makeMap(scene)); + expect(layers[0].renderMode).toBe("shader"); + const views = [ + [0, 0], + [-200, -150], + [150, -60], + ]; + expect( + await same(scene, { views, layers }), + `${grid.orientation}, axis ${axis}`, + ).toBeGreaterThan(0); + } + } + }); + + it("tiles set and cleared while the game runs", async (ctx) => { + need(ctx); + for (const grid of GRIDS) { + const scene = staggeredScene(grid, "x", "odd", blocks(grid, 3)); + const layers = show(app, makeMap(scene)); + const layer = layers[0]; + const options = { views: [[0, 0]], layers }; + for (let step = 0; step < 3; step++) { + for (let row = 0; row < ROWS; row++) { + for (let col = 0; col < COLS; col++) { + const gid = + (col + row + step) % 4 === 0 + ? 0 + : 1 + ((col * step + row) % 8); + scene.layers[0].data[row * COLS + col] = gid; + if (gid === 0) { + layer.clearTile(col, row); + } else { + layer.setTile(layer.getTileById(gid, col, row), col, row); + } + } + } + await same(scene, options); + } + expect(layer.renderMode).toBe("shader"); + } + }); + + it("views that hold only what reaches past the grid", async (ctx) => { + need(ctx); + for (const grid of GRIDS) { + // tiles four cells tall stand three cells above the grid + const scene = staggeredScene(grid, "y", "odd", blocks(grid, 4), { + layers: [ + { + data: fill(COLS, ROWS, (c, r) => { + return 1 + ((c + r * 2) % 8); + }), + }, + ], + }); + const views = [ + [0, -HEIGHT - 5], + [60, -HEIGHT - grid.th], + ]; + expect( + await same(scene, { views }), + grid.orientation, + ).toBeGreaterThan(0); + } + }); + }); + + describe("layers the GPU path does not take", () => { + it("tiles of two tilesets in one layer", (ctx) => { + need(ctx); + for (const grid of GRIDS) { + const [mode, said] = modeOf( + staggeredScene(grid, "y", "odd", blocks(grid), { + tilesets: [blocks(grid), blocks(grid, 3)], + layers: [ + { + data: fill(COLS, ROWS, (c, r) => { + return 1 + ((c + r) % 16); + }), + }, + ], + }), + ); + expect(mode).toBe("perTile"); + expect(said).toMatch( + new RegExp( + `more than one tileset in an? ${grid.orientation} layer`, + ), + ); + } + }); + + it("tiles past the size the shader walks", (ctx) => { + need(ctx); + const [mode, said] = modeOf( + staggeredScene(STAGGERED, "y", "odd", blocks(STAGGERED, 9)), + ); + expect(mode).toBe("perTile"); + expect(said).toMatch(/larger than the shader's limit/); + }); + + it("a grid whose cells stand half a pixel off", (ctx) => { + need(ctx); + // a hexagon side of odd length: every other column is half a + // pixel off + const grid = { + orientation: "hexagonal", + tw: 28, + th: 24, + hexsidelength: 11, + }; + const [mode, said] = modeOf( + staggeredScene(grid, "x", "odd", makeTileset({ tw: 28, th: 24 })), + ); + expect(mode).toBe("perTile"); + expect(said).toMatch(/odd size/); + }); + + it("a tile of another tileset set while the game runs", (ctx) => { + need(ctx); + const scene = staggeredScene(HEXAGONAL, "y", "odd", blocks(HEXAGONAL), { + tilesets: [blocks(HEXAGONAL), blocks(HEXAGONAL, 2)], + }); + const layer = show(app, makeMap(scene))[0]; + expect(layer.renderMode).toBe("shader"); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + layer.setTile(layer.getTileById(10, 2, 2), 2, 2); + expect(layer.renderMode).toBe("perTile"); + expect(warn.mock.calls.flat().join(" ")).toMatch( + /more than one tileset/, + ); + } finally { + warn.mockRestore(); + } + }); + + it("an oblique map, still", (ctx) => { + need(ctx); + const [mode, said] = modeOf({ + orientation: "oblique", + cols: 4, + rows: 4, + tw: 32, + th: 32, + tilesets: [makeTileset({ tw: 32, th: 32 })], + layers: [{ data: scattered(4, 4) }], + extra: { skewx: 10, skewy: 0 }, + }); + expect(mode).toBe("perTile"); + expect(said).toMatch(/no gpu renderer supported yet for "oblique"/); + }); + }); + + it("and each is drawn the same baked into one image", async (ctx) => { + need(ctx); + for (const { label, scene: build } of STAGGERED_SCENES.filter((_, i) => { + return i % 5 === 1; + })) { + const scene = build(); + const layers = show(app, makeMap(scene), "prerender"); + for (const [x, y] of STAGGERED_VIEWS.slice(0, 4)) { + app.viewport.moveTo(x, y); + const { frame } = await drawIn(app, layers, "prerender"); + const d = diff(reference(scene, x, y, WIDTH, HEIGHT), frame); + expect(d.different, `${label}, view (${x}, ${y}): ${d.first}`).toBe( + 0, + ); + expect(drawn(frame)).toBeGreaterThanOrEqual(0); + } + } + }); + }); +} diff --git a/packages/melonjs/tests/tmxlayer-shader-staggered.spec.js b/packages/melonjs/tests/tmxlayer-shader-staggered.spec.js new file mode 100644 index 0000000000..625d924051 --- /dev/null +++ b/packages/melonjs/tests/tmxlayer-shader-staggered.spec.js @@ -0,0 +1,8 @@ +/** + * Staggered and hexagonal tile layers on the GPU, on WebGL: see + * `helpers/tile-layer-staggered-scenarios.js`. + */ +import { video } from "../src/index.js"; +import { staggeredScenarios } from "./helpers/tile-layer-staggered-scenarios.js"; + +staggeredScenarios(video.WEBGL, "WebGL"); diff --git a/packages/melonjs/tests/tmxlayer-staggered.spec.js b/packages/melonjs/tests/tmxlayer-staggered.spec.js new file mode 100644 index 0000000000..47cc976e3e --- /dev/null +++ b/packages/melonjs/tests/tmxlayer-staggered.spec.js @@ -0,0 +1,53 @@ +/** + * Staggered and hexagonal maps drawn tile by tile, and baked into one image, + * on the Canvas renderer: held to the picture Tiled draws (a tile stands on + * its cell and follows its tileset's `tileoffset`, as on every other map). + * The GPU renderers are held to the same in + * `helpers/tile-layer-staggered-scenarios.js`. + */ +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { video } from "../src/index.js"; +import { + diff, + drawIn, + drawn, + makeApp, + makeMap, + reference, + show, +} from "./helpers/tile-layer-compare.js"; +import { + HEIGHT, + STAGGERED_SCENES, + STAGGERED_VIEWS, + WIDTH, +} from "./helpers/tile-layer-staggered-scenarios.js"; + +describe("staggered and hexagonal maps, as Tiled draws them (Canvas renderer)", () => { + let app; + beforeAll(async () => { + app = await makeApp(video.CANVAS, "CANVAS", WIDTH, HEIGHT); + }); + afterAll(() => { + app?.destroy(); + vi.restoreAllMocks(); + }); + + for (const { label, scene: build } of STAGGERED_SCENES) { + it(label, async () => { + const scene = build(); + let total = 0; + for (const mode of ["perTile", "prerender"]) { + const layers = show(app, makeMap(scene), mode); + for (const [x, y] of STAGGERED_VIEWS) { + app.viewport.moveTo(x, y); + const { frame } = await drawIn(app, layers, mode); + const d = diff(reference(scene, x, y, WIDTH, HEIGHT), frame); + expect(d.different, `${mode}, view (${x}, ${y}): ${d.first}`).toBe(0); + total += drawn(frame); + } + } + expect(total).toBeGreaterThan(0); + }); + } +}); diff --git a/packages/melonjs/tests/webgpu_tmxlayer.spec.js b/packages/melonjs/tests/webgpu_tmxlayer.spec.js index bb48fc2765..e8745aee51 100644 --- a/packages/melonjs/tests/webgpu_tmxlayer.spec.js +++ b/packages/melonjs/tests/webgpu_tmxlayer.spec.js @@ -279,3 +279,110 @@ describe("WebGPU isometric TMX layer renderer (mock)", () => { expect(renderer.calls.drawIndexed).toEqual([]); }); }); + +/** + * Staggered and hexagonal maps on the same renderer: one shader module for + * both, with the map's column width, row height, stagger axis and index in + * what was the uniform block's padding. + */ +describe("WebGPU staggered and hexagonal TMX layer renderer (mock)", () => { + let renderer; + + const tileset = { + isCollection: false, + image: { width: 256, height: 256 }, + tilewidth: 28, + tileheight: 48, + margin: 0, + spacing: 0, + tileoffset: { x: 0, y: 0 }, + firstgid: 1, + lastgid: 16, + isAnimated: false, + animations: new Map(), + texture: { name: "hex-atlas" }, + }; + + const layerOf = (orientation, map) => { + return { + orientation, + cols: 8, + rows: 8, + tilewidth: 28, + tileheight: 24, + dataVersion: 1, + layerData: new Uint16Array(8 * 8 * 2), + getOpacity() { + return 1; + }, + getRenderer() { + return map; + }, + tint: null, + tilesets: { tilesets: [tileset] }, + _shaderTileset: tileset, + }; + }; + + const RECT = { pos: { x: 10, y: 20 }, width: 320, height: 240 }; + + beforeEach(() => { + renderer = createMockWebGPURenderer(); + renderer.setBatcher = () => { + renderer.currentBatcher ??= new WebGPUQuadBatcher(renderer); + return renderer.currentBatcher; + }; + }); + + it("one shader module for both, apart from the other orientations'", () => { + const staggered = new TMXLayerGPURenderer(renderer, "staggered"); + const hexagonal = new TMXLayerGPURenderer(renderer, "hexagonal"); + const isometric = new TMXLayerGPURenderer(renderer, "isometric"); + expect(hexagonal.key).toBe(staggered.key); + expect(staggered.key).not.toBe(isometric.key); + }); + + it("hands the shader the map's lines: their spacing, axis and index", () => { + const tmx = new TMXLayerGPURenderer(renderer, "hexagonal"); + // a hexagon side of 12 along x: columns 20 apart, rows of 12 + tmx.draw( + layerOf("hexagonal", { + columnwidth: 20, + rowheight: 12, + staggerX: true, + staggerEven: true, + }), + RECT, + ); + expect(renderer.calls.drawIndexed).toEqual([6]); + const uniforms = tmx.uniformScratch; + // axis x (1) and an even index (2) + expect(uniforms[29]).toBe(3); + expect([uniforms[30], uniforms[31]]).toEqual([20, 12]); + // 28 pixels wide in spacings of 40, 48 tall in rows of 12 + expect([uniforms[6], uniforms[7]]).toEqual([1, 4]); + + const other = new TMXLayerGPURenderer(renderer, "staggered"); + other.draw( + layerOf("staggered", { + columnwidth: 14, + rowheight: 12, + staggerX: false, + staggerEven: false, + }), + RECT, + ); + expect(other.uniformScratch[29]).toBe(0); + expect([other.uniformScratch[30], other.uniformScratch[31]]).toEqual([ + 14, 12, + ]); + }); + + it("leaves them at 0 for the other orientations", () => { + const tmx = new TMXLayerGPURenderer(renderer, "isometric"); + const layer = layerOf("isometric", { originX: 8 * 14 }); + tmx.draw(layer, RECT); + expect(renderer.calls.drawIndexed).toEqual([6]); + expect([...tmx.uniformScratch.slice(29, 32)]).toEqual([0, 0, 0]); + }); +}); diff --git a/packages/melonjs/tests/webgpu_tmxlayer_staggered.spec.js b/packages/melonjs/tests/webgpu_tmxlayer_staggered.spec.js new file mode 100644 index 0000000000..4fd65a742f --- /dev/null +++ b/packages/melonjs/tests/webgpu_tmxlayer_staggered.spec.js @@ -0,0 +1,9 @@ +/** + * Staggered and hexagonal tile layers on the GPU, on WebGPU: see + * `helpers/tile-layer-staggered-scenarios.js`. Skipped, visibly, where the + * browser has no WebGPU adapter. + */ +import { video } from "../src/index.js"; +import { staggeredScenarios } from "./helpers/tile-layer-staggered-scenarios.js"; + +staggeredScenarios(video.WEBGPU, "WebGPU"); From 3b898941f27936efa19aad70d2fb840ec4de12e2 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 03:57:06 +0000 Subject: [PATCH 07/51] Tile layers: final review fixes (#1897) A layer reads the camera's view in its own coordinates. It is handed the view in the world's, and is drawn where its ancestors put it: a map centred in the view by moving the world (`level.load`) lost the tiles reaching above or left of its grid on the GPU and baked paths, and a layer in a moved container lost tiles tile by tile. A layer keeps track of whether the shader path can still draw it whichever way it is drawn: a tile of a second tileset set while the layer was switched to "perTile" by hand was left undrawn once it was switched back. A tile layer's bounds are its grid's again. What its tiles reach past the grid is asked for separately (`getDrawBounds`, read by `Camera2d#isVisible`): growing `getBounds()` moved what read it as the map's area. Pathfinding plugin: a grid from a tile layer stands where the layer was moved to (its offset in Tiled, its `pos`), as the layer is now drawn. One helper cuts the view to a layer's tiles for the isometric and the staggered regions; stale comments and the docs corrected. Tests: a layer in a centred map and in a moved container, on Canvas, WebGL and WebGPU, in every render mode and orientation, against the reference; render modes switched by hand with tiles set in between. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- packages/melonjs/CHANGELOG.md | 3 +- .../melonjs/skills/melonjs-tilemaps/SKILL.md | 9 +- packages/melonjs/src/application/settings.ts | 13 +- packages/melonjs/src/camera/camera2d.ts | 10 +- packages/melonjs/src/level/tiled/TMXLayer.js | 90 ++++-- .../tiled/renderer/TMXIsometricRenderer.js | 4 +- .../tiled/renderer/TMXOrthogonalRenderer.js | 4 +- packages/melonjs/src/physics/world.js | 12 +- .../src/video/gpu/tmxlayer_orientation.js | 79 ++--- .../video/webgl/shaders/tmxlayer-common.frag | 4 +- .../melonjs/src/video/webgl/webgl_renderer.js | 2 +- .../webgpu/renderers/tmxlayer/tmxlayer.js | 13 +- .../video/webgpu/shaders/tmxlayer-common.wgsl | 9 +- .../tests/helpers/tile-layer-compare.js | 13 +- .../helpers/tile-layer-placement-checks.js | 277 ++++++++++++++++++ .../melonjs/tests/tmxlayer-offset.spec.js | 22 +- .../tests/tmxlayer-placement-webgl.spec.js | 8 + .../melonjs/tests/tmxlayer-placement.spec.js | 8 + .../tests/webgpu_tmxlayer_placement.spec.js | 9 + packages/pathfinding-plugin/CHANGELOG.md | 5 + packages/pathfinding-plugin/package.json | 2 +- packages/pathfinding-plugin/src/grid.ts | 8 + .../pathfinding-plugin/tests/sources.spec.ts | 21 ++ 23 files changed, 526 insertions(+), 99 deletions(-) create mode 100644 packages/melonjs/tests/helpers/tile-layer-placement-checks.js create mode 100644 packages/melonjs/tests/tmxlayer-placement-webgl.spec.js create mode 100644 packages/melonjs/tests/tmxlayer-placement.spec.js create mode 100644 packages/melonjs/tests/webgpu_tmxlayer_placement.spec.js diff --git a/packages/melonjs/CHANGELOG.md b/packages/melonjs/CHANGELOG.md index 7155fc5c06..fa0d70370c 100644 --- a/packages/melonjs/CHANGELOG.md +++ b/packages/melonjs/CHANGELOG.md @@ -19,7 +19,8 @@ - Tiled, GPU tile layers: a layer with a tile that is not square, flipped diagonally, is drawn tile by tile; the shader drew such a tile wrong - Tiled, GPU tile layers: the shader runs at full precision whatever `highPrecisionShader` says; at a lower one a phone could misplace the tiles of a large map - Tiled: a tile layer follows its offset in Tiled (`offsetx`, `offsety`), and its own `pos` when the game moves it: its tiles are drawn there and `getTile()` finds them there, on every renderer and map orientation. Both were ignored, and the layer drawn at the map's origin; only image layers followed their offset. A map whose tile layers have an offset now looks as it does in Tiled -- Tiled: tiles that reach past their layer's grid (taller or wider than a cell, or moved by a `tileoffset`) are drawn when they are in view and the grid is not; the whole layer was skipped, so the tops of tall tiles vanished once the map scrolled out of view. `getBounds()` of a tile layer covers that reach; its `width` and `height` are still the grid's +- Tiled: tiles that reach past their layer's grid (taller or wider than a cell, or moved by a `tileoffset`) are drawn when they are in view and the grid is not; the whole layer was skipped, so the tops of tall tiles vanished once the map scrolled out of view. The layer's bounds are still its grid's +- Tiled: a map centred in the view because it is smaller (as `level.load` centres it), and a tile layer in a container that was moved, are drawn whole. The layer read the camera's view as if it stood at the world's origin: on WebGL, WebGPU and a pre-rendered layer the tiles reaching above or left of the grid were cut, and tile by tile a layer far from the origin lost tiles - Tiled, staggered and hexagonal maps: a tile larger than its cell stands on the cell, and a tileset's `tileoffset` moves its tiles, as in Tiled and on every other map. Drawn tile by tile, such a tile hung down from the top of its cell and the offset was ignored, so the map sat lower than its objects (and than a tile redrawn in a baked layer); tiles of a large tileset also went missing along the edges of the view - Tiled, isometric maps drawn tile by tile: tiles of a tileset larger than the map's first one, or moved by a `tileoffset`, went missing along the edges of the view - Tiled, orthogonal maps drawn tile by tile: tiles more than two cells tall went missing along the bottom of the view diff --git a/packages/melonjs/skills/melonjs-tilemaps/SKILL.md b/packages/melonjs/skills/melonjs-tilemaps/SKILL.md index 04cc022a75..da107d41cc 100644 --- a/packages/melonjs/skills/melonjs-tilemaps/SKILL.md +++ b/packages/melonjs/skills/melonjs-tilemaps/SKILL.md @@ -301,9 +301,11 @@ collision: solid ground comes from collision object layers (below), so a tile set or cleared changes what is drawn and what `cellAt` returns, not what a body runs into. Keep a layer you edit often off `preRender` (see the symptom table). -A tile layer is where its `pos` says: its offset in Tiled (Layer → Offset) -to start with, and wherever the game moves it afterwards. Its tiles are drawn -there, and `getTile(x, y)` answers for where they are drawn: +A tile layer moves with its `pos`. It starts where its offset in Tiled puts +it (Layer → Offset), and the game moves it from there; its tiles are drawn +where it is, and `getTile(x, y)` answers for where they are drawn. Move it +by a difference, not to a point: `pos` is not (0, 0) to begin with on every +map (an infinite one, an oblique one). ```js board.pos.y -= 8; // the whole layer, 8 pixels up @@ -537,6 +539,7 @@ layer into the offscreen-bake path instead. | thin lines between tiles on the Canvas renderer, with smoothing on | filtering blends in the next tile of the tileset or its spacing, which a canvas cannot prevent: set `antiAlias: false`, or `preRender` the layer. WebGL and WebGPU keep each tile to itself | | a tile layer given an offset in Tiled (a roof nudged up, a shadow shifted) is drawn where the others are | before 20.17 a tile layer ignored its offset, and its `pos`; only image layers followed theirs: update | | after updating to 20.17 a tile layer sits away from where it did | it has an offset in Tiled that was ignored until then, and now moves it as in the editor: clear the layer's Offset in Tiled if it was not meant | +| a map smaller than the screen (centred by `level.load`) had the tops of its tall tiles cut on WebGL or WebGPU | before 20.17 a layer read the camera's view as if it stood at the world's origin, and so did a layer in a container the game had moved: update | | the tops of tall tiles vanish when the map itself scrolls out of view | before 20.17 a layer was skipped once its grid left the view, though tiles larger than a cell (or moved by a `tileoffset`) still reached in: update | | tilemap slow on some machines | layer fell back off the shader path — check the console warning for the reason | | a staggered or hexagonal map sits higher than before 20.17, by how much its tiles are taller than a cell (or by its tileset's `tileoffset`) | it is drawn as Tiled draws it: until then a tile hung from the top of its cell and the offset was ignored, away from the map's objects | diff --git a/packages/melonjs/src/application/settings.ts b/packages/melonjs/src/application/settings.ts index d58847735c..425ab6ca7d 100644 --- a/packages/melonjs/src/application/settings.ts +++ b/packages/melonjs/src/application/settings.ts @@ -481,12 +481,13 @@ export type ApplicationSettings = { * `renderer.supportsShaderTileLayers` — WebGL 2 and WebGPU). When * `true` (default), eligible layers render via a single quad per * tileset + a fragment shader doing per-fragment GID lookup, bypassing - * the per-tile draw loop entirely. Layers that don't qualify (Canvas - * renderer, an oblique map, collection-of-image tilesets, - * tilerendersize "grid", tiles larger than the shader walks; on an - * orthogonal map a non-zero tileoffset, on the others tiles of - * several tilesets in one layer) fall back to the legacy path - * automatically, saying why in the console. + * the per-tile draw loop entirely. Layers that don't qualify fall + * back to the legacy path automatically, saying why in the console: + * among them the Canvas renderer, an oblique map, collection-of-image + * tilesets, tilerendersize "grid", tiles larger than the shader walks; + * on an orthogonal map a non-zero tileoffset; on the others tiles of + * several tilesets in one layer, a grid of odd size, or a blend mode + * other than the normal one. * Set to `false` to disable globally. * @default true */ diff --git a/packages/melonjs/src/camera/camera2d.ts b/packages/melonjs/src/camera/camera2d.ts index 1b8675742c..6dfa51c740 100644 --- a/packages/melonjs/src/camera/camera2d.ts +++ b/packages/melonjs/src/camera/camera2d.ts @@ -1091,8 +1091,14 @@ export default class Camera2d extends Renderable { ); } // non-floating objects use world coordinates, check against - // the camera's visible world area (accounts for position and zoom) - return obj.getBounds().overlaps(this.worldView); + // the camera's visible world area (accounts for position and zoom). + // What a renderable draws can reach past its bounds (a tile layer's + // tiles, taller than their cell, stand above its grid): it says so + // with `getDrawBounds` + const drawn = ( + obj as Renderable & { getDrawBounds?: () => Bounds } + ).getDrawBounds?.(); + return (drawn ?? obj.getBounds()).overlaps(this.worldView); } /** diff --git a/packages/melonjs/src/level/tiled/TMXLayer.js b/packages/melonjs/src/level/tiled/TMXLayer.js index 44b6edbfdf..996375c0fe 100644 --- a/packages/melonjs/src/level/tiled/TMXLayer.js +++ b/packages/melonjs/src/level/tiled/TMXLayer.js @@ -237,7 +237,8 @@ export default class TMXLayer extends Renderable { */ this.maxTileOffset = { x: 0, y: 0 }; /** - * The one tileset an isometric layer on the shader path draws with: + * The one tileset a layer of an isometric, staggered or hexagonal + * map draws with on the shader path: * `undefined` for an empty layer (it takes the tileset of the first * tile set), `null` for a layer that path cannot draw, or that was * not checked for it. @@ -282,7 +283,7 @@ export default class TMXLayer extends Renderable { * How far past the layer's grid its tiles can be drawn, on each * side: by tiles larger than a cell, and by a tileset's * `tileoffset`. The layer is in view as far as they reach (see - * {@link TMXLayer#updateBounds}). + * {@link TMXLayer#getDrawBounds}). * @ignore */ this._reach = { @@ -490,28 +491,30 @@ export default class TMXLayer extends Renderable { this.pos.y = this._mapPos.y + (+data.offsety || 0); vector2dPool.release(origin); boundsPool.release(bounds); - this.updateBounds(); } /** - * The layer's bounds: its grid, where it is, and as far past it as its - * tiles reach. A tile larger than its cell, or moved by its tileset's - * `tileoffset`, is drawn outside the grid, and the layer is in view - * while such a tile is. Its `width` and `height` stay the grid's. + * The area the layer draws in: its bounds, which are its grid's, and as + * far past them as its tiles reach. A tile larger than its cell, or + * moved by its tileset's `tileoffset`, is drawn outside the grid, and a + * camera has the layer in view while such a tile is (see + * `Camera2d#isVisible`). The layer's bounds, `width` and `height` stay + * the grid's. + * @returns {Bounds} that area, in the same coordinates as `getBounds()` * @ignore */ - updateBounds(absolute = true) { - const bounds = super.updateBounds(absolute); + getDrawBounds() { + const bounds = this.getBounds(); const reach = this._reach; - if (reach !== undefined && bounds.isFinite()) { - bounds.setMinMax( - bounds.left - reach.left, - bounds.top - reach.top, - bounds.right + reach.right, - bounds.bottom + reach.bottom, - ); - } - return bounds; + /** @ignore */ + this._drawBounds ??= boundsPool.get(); + this._drawBounds.setMinMax( + bounds.left - reach.left, + bounds.top - reach.top, + bounds.right + reach.right, + bounds.bottom + reach.bottom, + ); + return this._drawBounds; } /** @@ -707,6 +710,13 @@ export default class TMXLayer extends Renderable { typeof this.preRender === "boolean" ? this.preRender : root?.preRender; const elig = this._checkShaderEligibility(renderer, gpuAllowed); + /** + * whether the shader path can draw the layer, as its tiles are now + * (kept up to date by `setTile`): a layer asked for that path by + * hand when it cannot is drawn tile by tile + * @ignore + */ + this._shaderFit = elig.ok; const requested = this.renderMode; // explicit "shader" — honor if eligible, warn otherwise @@ -986,11 +996,15 @@ export default class TMXLayer extends Renderable { } } if (reason !== undefined) { - console.warn( - `melonJS: layer "${this.name}" back to the legacy tile renderer (${reason})`, - ); - this.renderMode = "perTile"; + this._shaderFit = false; this._shaderTileset = null; + // drawn another way for now (by hand): nothing to move back + if (this.renderMode === "shader") { + console.warn( + `melonJS: layer "${this.name}" back to the legacy tile renderer (${reason})`, + ); + this.renderMode = "perTile"; + } } } @@ -1101,7 +1115,9 @@ export default class TMXLayer extends Renderable { this.dataVersion++; this.isDirty = true; this._preRenderCell(x, y); - if (this.renderMode === "shader") { + // whichever way the layer is drawn now: it may be asked for the + // shader path again + if (this._shaderFit === true) { this._keepShaderEligible(cleanGid, this.layerData[idx + 1]); } return tile; @@ -1256,6 +1272,27 @@ export default class TMXLayer extends Renderable { viewRect.pos.set(rect.pos.x + offset.x, rect.pos.y + offset.y); rect = viewRect.setSize(rect.width, rect.height); } + // The view is the camera's, in the world's coordinates, and the layer + // is drawn where its ancestors put it: a world moved to centre a map + // smaller than the view, a container the game moved. Read in the + // layer's own coordinates, the view starts that much earlier. (A + // camera other than the default one draws the world unmoved.) + let shiftX = 0; + let shiftY = 0; + const parent = this.ancestor; + if (parent !== undefined && parent !== null) { + const at = parent.getAbsolutePosition(); + shiftX = at.x; + shiftY = at.y; + if (rect.isDefault === false) { + let root = parent; + while (root.ancestor) { + root = root.ancestor; + } + shiftX -= root.pos.x; + shiftY -= root.pos.y; + } + } // A layer moved from its place in the map, by its offset in Tiled or // by its `pos`, and an infinite map's layer that starts left of or // above the map's origin: the layer's renderer draws its grid from @@ -1265,13 +1302,18 @@ export default class TMXLayer extends Renderable { if ( movedX !== 0 || movedY !== 0 || + shiftX !== 0 || + shiftY !== 0 || this.startx !== 0 || this.starty !== 0 ) { const origin = this._cellOrigin(vector2dPool.get()); origin.set(origin.x + movedX, origin.y + movedY); cellRect ??= new Rect(0, 0, 0, 0); - cellRect.pos.set(rect.pos.x - origin.x, rect.pos.y - origin.y); + cellRect.pos.set( + rect.pos.x - shiftX - origin.x, + rect.pos.y - shiftY - origin.y, + ); cellRect.setSize(rect.width, rect.height); renderer.translate(origin.x, origin.y); renderer.drawTileLayer(this, cellRect); diff --git a/packages/melonjs/src/level/tiled/renderer/TMXIsometricRenderer.js b/packages/melonjs/src/level/tiled/renderer/TMXIsometricRenderer.js index b0fd0514ba..f81f5de6e0 100644 --- a/packages/melonjs/src/level/tiled/renderer/TMXIsometricRenderer.js +++ b/packages/melonjs/src/level/tiled/renderer/TMXIsometricRenderer.js @@ -166,8 +166,8 @@ export default class TMXIsometricRenderer extends TMXRenderer { // missing along the bottom of the view, where their cell is below it // and their image still reaches in, and so did tiles moved into view // by an offset larger than a tile - const reachX = layer.maxTileSize.width + layer.maxTileOffset.x; - const reachY = layer.maxTileSize.height + layer.maxTileOffset.y; + const reachX = layer.maxTileSize.width + (layer.maxTileOffset?.x ?? 0); + const reachY = layer.maxTileSize.height + (layer.maxTileOffset?.y ?? 0); const rowItr = this.pixelToTileCoords( rect.pos.x - reachX, rect.pos.y - reachY, diff --git a/packages/melonjs/src/level/tiled/renderer/TMXOrthogonalRenderer.js b/packages/melonjs/src/level/tiled/renderer/TMXOrthogonalRenderer.js index a6cb4412dd..1f5354a43c 100644 --- a/packages/melonjs/src/level/tiled/renderer/TMXOrthogonalRenderer.js +++ b/packages/melonjs/src/level/tiled/renderer/TMXOrthogonalRenderer.js @@ -96,8 +96,8 @@ export default class TMXOrthogonalRenderer extends TMXRenderer { // view.) A tileset's `tileoffset` moves its tiles either way. const overX = Math.max(layer.maxTileSize.width - layer.tilewidth, 0); const overY = Math.max(layer.maxTileSize.height - layer.tileheight, 0); - const offsetX = layer.maxTileOffset.x; - const offsetY = layer.maxTileOffset.y; + const offsetX = layer.maxTileOffset?.x ?? 0; + const offsetY = layer.maxTileOffset?.y ?? 0; const start = this.pixelToTileCoords( Math.max(rect.pos.x - overX - offsetX, 0), Math.max(rect.pos.y - offsetY, 0), diff --git a/packages/melonjs/src/physics/world.js b/packages/melonjs/src/physics/world.js index 601442e88d..dbfa3d58d6 100644 --- a/packages/melonjs/src/physics/world.js +++ b/packages/melonjs/src/physics/world.js @@ -225,11 +225,13 @@ export default class World extends Container { * tiles, per-layer opacity and tint, and tiles larger than the * grid: up to 4 cells of overflow on an orthogonal map, up to 4 * cells wide and 8 tall on the others. - * Layers that don't qualify (Canvas, an oblique map, - * collection-of-image tilesets, larger tiles; on an orthogonal map - * a non-zero `tileoffset`, on the others tiles of several tilesets - * in one layer) fall back to the legacy - * path automatically. Set to `false` to disable globally. + * Layers that don't qualify fall back to the legacy path + * automatically, saying why in the console: among them Canvas, an + * oblique map, collection-of-image tilesets, a `tilerendersize` + * of "grid", larger tiles; on an orthogonal map a non-zero + * `tileoffset`; on the others tiles of several tilesets in one + * layer, a grid of odd size, or a blend mode other than the + * normal one. Set to `false` to disable globally. * @type {boolean} * @default true */ diff --git a/packages/melonjs/src/video/gpu/tmxlayer_orientation.js b/packages/melonjs/src/video/gpu/tmxlayer_orientation.js index 0691c50798..c3fdf54e96 100644 --- a/packages/melonjs/src/video/gpu/tmxlayer_orientation.js +++ b/packages/melonjs/src/video/gpu/tmxlayer_orientation.js @@ -106,6 +106,39 @@ export function orthogonalRegion(layer, rect, tileset, out) { return true; } +/** + * The view, cut to where a layer's tiles can be, on whole pixels: the quad + * to draw, for an orientation whose shader works in the layer's pixels. + * @param {object} rect - the visible viewport rect (world coords) + * @param {number} left - where the tiles can be, in the layer's pixels + * @param {number} top - where the tiles can be + * @param {number} right - where the tiles can be + * @param {number} bottom - where the tiles can be + * @param {number} originX - where the shader's pixels are measured from + * @param {number} originY - where the shader's pixels are measured from + * @param {object} out - the region to fill + * @returns {boolean} false when the view shows none of it + * @ignore + */ +function viewIn(rect, left, top, right, bottom, originX, originY, out) { + const x0 = Math.floor(Math.max(rect.pos.x, left)); + const y0 = Math.floor(Math.max(rect.pos.y, top)); + const x1 = Math.ceil(Math.min(rect.pos.x + rect.width, right)); + const y1 = Math.ceil(Math.min(rect.pos.y + rect.height, bottom)); + if (x1 <= x0 || y1 <= y0) { + return false; + } + out.x = x0; + out.y = y0; + out.width = x1 - x0; + out.height = y1 - y0; + out.startX = x0 - originX; + out.startY = y0 - originY; + out.sizeX = out.width; + out.sizeY = out.height; + return true; +} + /** * The part of an isometric layer a view shows, for the tiles of one tileset: * the same on every GPU backend, so their renderers share it. @@ -143,23 +176,11 @@ export function isometricRegion(layer, rect, tileset, out) { const top = layer.tileheight - tileset.tileheight + offsetY; const bottom = (cols + rows) * halfHeight + offsetY; - // the view, cut to it, on whole pixels - const x0 = Math.floor(Math.max(rect.pos.x, left)); - const y0 = Math.floor(Math.max(rect.pos.y, top)); - const x1 = Math.ceil(Math.min(rect.pos.x + rect.width, right)); - const y1 = Math.ceil(Math.min(rect.pos.y + rect.height, bottom)); - if (x1 <= x0 || y1 <= y0) { + if ( + !viewIn(rect, left, top, right, bottom, originX + offsetX, offsetY, out) + ) { return false; } - - out.x = x0; - out.y = y0; - out.width = x1 - x0; - out.height = y1 - y0; - out.startX = x0 - originX - offsetX; - out.startY = y0 - offsetY; - out.sizeX = out.width; - out.sizeY = out.height; // how many cells' images reach a pixel: as many across as the image is // wide in half grid widths, as many down as it is tall in half grid // heights @@ -208,23 +229,9 @@ export function staggeredRegion(layer, rect, tileset, out) { const top = layer.tileheight - tileset.tileheight + offsetY; const bottom = (lines - 1) * rowHeight + layer.tileheight + offsetY; - // the view, cut to it, on whole pixels - const x0 = Math.floor(Math.max(rect.pos.x, left)); - const y0 = Math.floor(Math.max(rect.pos.y, top)); - const x1 = Math.ceil(Math.min(rect.pos.x + rect.width, right)); - const y1 = Math.ceil(Math.min(rect.pos.y + rect.height, bottom)); - if (x1 <= x0 || y1 <= y0) { + if (!viewIn(rect, left, top, right, bottom, offsetX, offsetY, out)) { return false; } - - out.x = x0; - out.y = y0; - out.width = x1 - x0; - out.height = y1 - y0; - out.startX = x0 - offsetX; - out.startY = y0 - offsetY; - out.sizeX = out.width; - out.sizeY = out.height; // how many cells' images reach a pixel: as many in a line as the image // is wide in cell spacings, as many lines as it is tall in row heights out.overflowX = Math.ceil(tileset.tilewidth / (columnWidth * 2)); @@ -298,7 +305,7 @@ const ONE_TILESET = { * @returns {boolean} whether the layer can be drawn */ draws(layer) { - return layer._shaderTileset !== null; + return layer._shaderTileset !== null && layer._shaderFit !== false; }, }; @@ -318,8 +325,14 @@ export const TMX_ORIENTATIONS = { tilesetsOf(layer) { return layer.tilesets.tilesets; }, - draws() { - return true; + /** + * not a layer found unfit for this path, or made so by a tile set + * since (a layer never checked is drawn) + * @param {TMXLayer} layer - the layer + * @returns {boolean} whether the layer can be drawn + */ + draws(layer) { + return layer._shaderFit !== false; }, // how many cells a tile can reach past its own, across and up limits: { MAX_OVERFLOW: 4 }, diff --git a/packages/melonjs/src/video/webgl/shaders/tmxlayer-common.frag b/packages/melonjs/src/video/webgl/shaders/tmxlayer-common.frag index 79f5bc8f6e..214b7a5e84 100644 --- a/packages/melonjs/src/video/webgl/shaders/tmxlayer-common.frag +++ b/packages/melonjs/src/video/webgl/shaders/tmxlayer-common.frag @@ -9,8 +9,8 @@ precision highp int; // Fragment shader for the TMX layer GPU renderers (WebGL2 / GLSL ES 3.00): // the part every map orientation shares. An orientation's own file follows -// it in the program (`orthogonal-tmxlayer.frag`, `isometric-tmxlayer.frag`) -// and gives the two things that differ: where a cell's tile is drawn +// it in the program (`orthogonal-tmxlayer.frag`, `isometric-tmxlayer.frag`, +// `staggered-tmxlayer.frag` for staggered and hexagonal maps) and gives the two things that differ: where a cell's tile is drawn // (`tileOrigin`), and which cells could cover a fragment, front to back // (`main`). // diff --git a/packages/melonjs/src/video/webgl/webgl_renderer.js b/packages/melonjs/src/video/webgl/webgl_renderer.js index 1ffd68dcfd..0aaf2676c2 100644 --- a/packages/melonjs/src/video/webgl/webgl_renderer.js +++ b/packages/melonjs/src/video/webgl/webgl_renderer.js @@ -1493,7 +1493,7 @@ export default class WebGLRenderer extends Renderer { */ _getTMXGPURendererFor(orientation) { if (TMX_ORIENTATIONS[orientation] === undefined) { - // staggered, hexagonal, oblique: drawn by the legacy renderer + // an oblique map: drawn by the legacy renderer return undefined; } this._tmxGPURenderers ??= new Map(); diff --git a/packages/melonjs/src/video/webgpu/renderers/tmxlayer/tmxlayer.js b/packages/melonjs/src/video/webgpu/renderers/tmxlayer/tmxlayer.js index 750487c91e..868f2d0e63 100644 --- a/packages/melonjs/src/video/webgpu/renderers/tmxlayer/tmxlayer.js +++ b/packages/melonjs/src/video/webgpu/renderers/tmxlayer/tmxlayer.js @@ -20,8 +20,9 @@ import staggeredWGSL from "../../shaders/tmxlayer-staggered.wgsl"; /** * byte size of the TMXUniforms block (see tmxlayer-common.wgsl): ten vec2f (80) * interleaved with one vec4f at a 16-aligned offset, two f32, the vec4f - * tint (ending at 112) and the mipmap flag, rounded up to the block's - * 16-byte alignment → 128 bytes + * tint (ending at 112), the mipmap flag (112), and a staggered map's mode + * (116) and two lengths (a vec2f at 120) → 128 bytes, a multiple of the + * block's 16-byte alignment * @ignore * @internal */ @@ -43,10 +44,10 @@ const ORIENTATION_WGSL = { * the fragment shader sampling a per-layer GID index texture and the * tileset atlas. * - * An orientation's renderer extends this one with the two things that - * differ: its part of the shader (where a cell's tile is, and which cells - * can cover a fragment), and {@link TMXLayerGPURenderer#region}, the part of - * the layer a view shows. + * There is one of these per map orientation drawn (see `TMX_ORIENTATIONS` + * in `gpu/tmxlayer_orientation.js`). Two things differ from one to the next: + * its part of the shader (where a cell's tile is, and which cells can cover + * a fragment), and the part of a layer a view shows. * * Structure mirrors the WebGL twin; the mechanisms are the backend's: * - the GID index / animation lookup are renderer-owned `rgba8unorm` diff --git a/packages/melonjs/src/video/webgpu/shaders/tmxlayer-common.wgsl b/packages/melonjs/src/video/webgpu/shaders/tmxlayer-common.wgsl index 711d52a2b3..a5b208c24b 100644 --- a/packages/melonjs/src/video/webgpu/shaders/tmxlayer-common.wgsl +++ b/packages/melonjs/src/video/webgpu/shaders/tmxlayer-common.wgsl @@ -1,7 +1,8 @@ // melonJS WebGPU TMX layer shader — the WGSL port of tmxlayer.vert and // tmxlayer-common.frag (WebGL2): the part every map orientation shares. An // orientation's own file follows it in the module (tmxlayer-orthogonal.wgsl, -// tmxlayer-isometric.wgsl) and gives the two things that differ: where a +// tmxlayer-isometric.wgsl, tmxlayer-staggered.wgsl for staggered and +// hexagonal maps) and gives the two things that differ: where a // cell's tile is drawn (`tileOrigin`), and which cells could cover a // fragment, front to back (`fragment_main`). // @@ -17,9 +18,9 @@ // local id, same R/G byte-pair encoding. // // textureLoad replaces texelFetch (byte-exact, no sampler); the atlas -// sample uses textureSampleLevel — the sample sites sit in non-uniform -// control flow, where implicit-derivative sampling is not allowed (WGSL -// uniformity rule; atlases are single-level so the output is identical). +// sample uses textureSampleGrad, with derivatives taken once per fragment — +// the sample sites sit in non-uniform control flow, where +// implicit-derivative sampling is not allowed (WGSL uniformity rule). struct FrameUniforms { projection : mat4x4, diff --git a/packages/melonjs/tests/helpers/tile-layer-compare.js b/packages/melonjs/tests/helpers/tile-layer-compare.js index 2c5afa8521..64e59d8da7 100644 --- a/packages/melonjs/tests/helpers/tile-layer-compare.js +++ b/packages/melonjs/tests/helpers/tile-layer-compare.js @@ -408,10 +408,14 @@ export async function makeApp(renderer, type, width = 320, height = 240) { * @param {TMXTileMap} map - the map * @param {string} [renderMode] - a render mode to ask of every layer before * it is activated ("prerender" needs asking then: it bakes at activation) + * @param {boolean} [centered=false] - as `level.load` adds a map: one + * smaller than the view is centred in it, by moving the world (`world.pos`) * @returns {object[]} the map's tile layers */ -export function show(app, map, renderMode) { +export function show(app, map, renderMode, centered = false) { app.world.reset(); + // where a map centred before this one left it + app.world.pos.set(0, 0, app.world.pos.z); app.renderer.reset?.(); app.renderer.backgroundColor.setColor(16, 24, 48); if (renderMode !== undefined) { @@ -419,7 +423,7 @@ export function show(app, map, renderMode) { layer.renderMode = renderMode; } } - map.addTo(app.world, true, false); + map.addTo(app.world, true, centered); // the layers in their order now: the world sorts its children later, on // a timer no frame of these tests waits for app.world.sortNow(true); @@ -539,6 +543,8 @@ const DEFAULT_VIEWS = [ * channel that is not counted * @param {number} [options.share=0] - the largest share of the pixels * drawn that the two paths may differ by + * @param {number[]} [options.origin] - where the map's origin is drawn, + * when the world or a container the layers are in was moved * @returns {Promise} how many pixels were drawn, in all */ export async function comparePaths(app, scene, options = {}) { @@ -548,6 +554,7 @@ export async function comparePaths(app, scene, options = {}) { expected, tolerance = 0, share = 0, + origin = [0, 0], } = options; const { width, height } = app.viewport; let layers = options.layers; @@ -570,7 +577,7 @@ export async function comparePaths(app, scene, options = {}) { const count = drawn(gpu.frame); const allowed = Math.floor(count * share); if (oracle) { - let ref = reference(scene, x, y, width, height); + let ref = reference(scene, x - origin[0], y - origin[1], width, height); if (expected !== undefined) { ref = expected(ref); } diff --git a/packages/melonjs/tests/helpers/tile-layer-placement-checks.js b/packages/melonjs/tests/helpers/tile-layer-placement-checks.js new file mode 100644 index 0000000000..ddcf86d3f7 --- /dev/null +++ b/packages/melonjs/tests/helpers/tile-layer-placement-checks.js @@ -0,0 +1,277 @@ +/** + * A tile layer drawn where its ancestors put it: in a world moved to centre + * a map smaller than the view (what `level.load` does), or in a container + * that was moved. The layer is handed the camera's view in the world's + * coordinates, and has to read it in its own: the tiles that reach above or + * left of its grid were cut on the GPU and baked paths, and a layer far + * enough from the origin lost tiles tile by tile. + * + * Also here: a layer's `renderMode` switched by hand, and tiles set in + * between. + * + * One spec file per renderer calls this: an application takes the place of + * the one before it, and a spec file has its own page. + */ +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { Container } from "../../src/index.js"; +import { + comparePaths, + diff, + drawIn, + drawn, + FLIP_AD, + fill, + inBlock, + makeApp, + makeMap, + makeTileset, + reference, + show, +} from "./tile-layer-compare.js"; + +const WIDTH = 320; +const HEIGHT = 240; + +const all = (cols, rows) => { + return fill(cols, rows, (c, r) => { + return 1 + ((c + r * 2) % 8); + }); +}; + +/** small maps of tiles that reach past their grid, one per orientation */ +const SCENES = { + orthogonal: () => { + return { + orientation: "orthogonal", + cols: 4, + rows: 3, + tw: 32, + th: 32, + tilesets: [makeTileset({ tw: 48, th: 64 })], + layers: [{ data: all(4, 3) }], + }; + }, + isometric: () => { + return { + orientation: "isometric", + cols: 3, + rows: 3, + tw: 64, + th: 32, + tilesets: [ + makeTileset({ + tw: 64, + th: 96, + opaque: (x, y) => { + return inBlock(x, y, 64, 96, 64, 32); + }, + }), + ], + layers: [{ data: all(3, 3) }], + }; + }, + staggered: () => { + return { + orientation: "staggered", + cols: 3, + rows: 5, + tw: 64, + th: 32, + tilesets: [ + makeTileset({ + tw: 64, + th: 80, + extra: { tileoffset: { x: -20, y: 0 } }, + }), + ], + layers: [{ data: all(3, 5) }], + extra: { staggeraxis: "y", staggerindex: "odd" }, + }; + }, + hexagonal: () => { + return { + orientation: "hexagonal", + cols: 5, + rows: 5, + tw: 28, + th: 24, + tilesets: [makeTileset({ tw: 28, th: 60 })], + layers: [{ data: all(5, 5) }], + extra: { staggeraxis: "x", staggerindex: "even", hexsidelength: 12 }, + }; + }, +}; + +const VIEWS = [ + [0, 0], + [30, 20], + [-45, -60], +]; + +/** + * Declare the checks for one renderer. + * @param {number} renderer - `video.CANVAS`, `video.WEBGL` or `video.WEBGPU` + * @param {string} type - the `renderer.type` expected + * @param {string[]} modes - the render modes that renderer has + */ +export function placementChecks(renderer, type, modes) { + describe(`a tile layer where its ancestors put it (${type})`, () => { + let app; + beforeAll(async () => { + app = await makeApp(renderer, type, WIDTH, HEIGHT); + }); + afterAll(() => { + app?.world.pos.set(0, 0, 0); + app?.destroy(); + vi.restoreAllMocks(); + }); + + const need = (ctx) => { + if (app === null || app === undefined) { + ctx.skip(`${type} not available in this environment`); + } + }; + + for (const [orientation, build] of Object.entries(SCENES)) { + it(`${orientation}: a map centred in the view keeps the tiles that reach past its grid`, async (ctx) => { + need(ctx); + const scene = build(); + let total = 0; + for (const mode of modes) { + const layers = show( + app, + makeMap(scene), + mode === "prerender" ? mode : undefined, + true, + ); + const { x: ox, y: oy } = app.world.pos; + // smaller than the view: centred, by moving the world + expect(ox, "centred across").toBeGreaterThan(0); + expect(oy, "centred down").toBeGreaterThan(0); + for (const [x, y] of VIEWS) { + app.viewport.moveTo(x, y); + const { frame } = await drawIn(app, layers, mode); + const ref = reference(scene, x - ox, y - oy, WIDTH, HEIGHT); + const d = diff(ref, frame); + expect(d.different, `${mode}, view (${x}, ${y}): ${d.first}`).toBe( + 0, + ); + total += drawn(frame); + } + } + expect(total).toBeGreaterThan(0); + }); + + for (const [gx, gy] of [ + [120, 80], + [-700, 900], + ]) { + it(`${orientation}: in a container moved to (${gx}, ${gy})`, async (ctx) => { + need(ctx); + const scene = build(); + let total = 0; + for (const mode of modes) { + app.world.reset(); + app.world.pos.set(0, 0, app.world.pos.z); + app.renderer.reset?.(); + app.renderer.backgroundColor.setColor(16, 24, 48); + const map = makeMap(scene); + const layers = map.getLayers(); + if (mode === "prerender") { + layers[0].renderMode = mode; + } + const group = new Container(); + group.pos.set(gx, gy, 0); + app.world.addChild(group); + map.addTo(group, true, false); + app.world.sortNow(true); + app.viewport.setBounds(-100000, -100000, 200000, 200000); + for (const [x, y] of VIEWS) { + // the view follows the container + app.viewport.moveTo(x + gx, y + gy); + const { frame } = await drawIn(app, layers, mode); + const ref = reference(scene, x, y, WIDTH, HEIGHT); + const d = diff(ref, frame); + expect( + d.different, + `${mode}, view (${x}, ${y}): ${d.first}`, + ).toBe(0); + total += drawn(frame); + } + } + expect(total).toBeGreaterThan(0); + }); + } + } + + if (type !== "CANVAS") { + it("both paths, centred: the same as the reference", async (ctx) => { + need(ctx); + for (const build of Object.values(SCENES)) { + const scene = build(); + const layers = show(app, makeMap(scene), undefined, true); + expect(layers[0].renderMode).toBe("shader"); + const origin = [app.world.pos.x, app.world.pos.y]; + expect( + await comparePaths(app, scene, { views: VIEWS, layers, origin }), + scene.orientation, + ).toBeGreaterThan(0); + } + }); + + describe("a render mode switched by hand, and tiles set in between", () => { + const two = (orientation) => { + const scene = SCENES[orientation](); + const [first] = scene.tilesets; + scene.tilesets = [ + first, + makeTileset({ tw: first.tilewidth, th: first.tileheight }), + ]; + return scene; + }; + + for (const orientation of ["isometric", "staggered", "hexagonal"]) { + it(`${orientation}: a tile of another tileset set while the layer was drawn tile by tile`, async (ctx) => { + need(ctx); + const scene = two(orientation); + const layers = show(app, makeMap(scene)); + const layer = layers[0]; + expect(layer.renderMode).toBe("shader"); + layer.renderMode = "perTile"; + // no warning: nothing is moved off the GPU path now + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + scene.layers[0].data[1 * scene.cols + 1] = 11; + layer.setTile(layer.getTileById(11, 1, 1), 1, 1); + expect(warn).not.toHaveBeenCalled(); + warn.mockRestore(); + // asked for the GPU path again: the layer has tiles of + // two tilesets, and is drawn tile by tile, whole + app.viewport.moveTo(0, 0); + const forced = await drawIn(app, layers, "shader"); + expect(forced.cpuDraws).toBe(1); + const d = diff(reference(scene, 0, 0, WIDTH, HEIGHT), forced.frame); + expect(d.different, d.first).toBe(0); + }); + } + + it("orthogonal: a tile not square, flipped diagonally, set while the layer was drawn tile by tile", async (ctx) => { + need(ctx); + const scene = SCENES.orthogonal(); + const layers = show(app, makeMap(scene)); + const layer = layers[0]; + expect(layer.renderMode).toBe("shader"); + app.viewport.moveTo(0, 0); + layer.renderMode = "perTile"; + layer.setTile(layer.getTileById(3 + FLIP_AD, 1, 1), 1, 1); + const cpu = await drawIn(app, layers, "perTile"); + // asked for the GPU path again: still tile by tile, and the + // same picture + const forced = await drawIn(app, layers, "shader"); + expect(forced.cpuDraws).toBe(1); + expect(diff(cpu.frame, forced.frame).different).toBe(0); + expect(drawn(forced.frame)).toBeGreaterThan(0); + }); + }); + } + }); +} diff --git a/packages/melonjs/tests/tmxlayer-offset.spec.js b/packages/melonjs/tests/tmxlayer-offset.spec.js index 1f25aa597b..82e6e1c737 100644 --- a/packages/melonjs/tests/tmxlayer-offset.spec.js +++ b/packages/melonjs/tests/tmxlayer-offset.spec.js @@ -307,17 +307,31 @@ describe("where a tile layer is (Canvas renderer)", () => { ).toBeGreaterThan(0); }); - it("the bounds cover the reach, the size stays the grid's", () => { + it("its bounds stay the grid's: the reach is for what is in view alone", () => { const [layer] = show(app, makeMap(orthogonal({ tall: 128 }))); expect([layer.width, layer.height]).toEqual([320, 256]); const bounds = layer.getBounds(); + expect([bounds.left, bounds.top, bounds.right, bounds.bottom]).toEqual([ + 0, 0, 320, 256, + ]); // 128 pixel tiles on a 32 pixel grid stand 96 above their cell - expect(bounds.top).toBe(-96); - expect([bounds.left, bounds.right, bounds.bottom]).toEqual([0, 320, 256]); + const reach = layer.getDrawBounds(); + expect([reach.left, reach.top, reach.right, reach.bottom]).toEqual([ + 0, -96, 320, 256, + ]); // and getTile has nothing above the grid: no cell is there expect(layer.getTile(10, -50)).toBeNull(); + // moved, both move with it + layer.pos.x = 40; + layer.pos.y = -10; + expect([layer.getBounds().left, layer.getBounds().top]).toEqual([ + 40, -10, + ]); + expect([layer.getDrawBounds().left, layer.getDrawBounds().top]).toEqual([ + 40, -106, + ]); // tiles the size of the grid: the grid, no more - const plain = show(app, makeMap(orthogonal()))[0].getBounds(); + const plain = show(app, makeMap(orthogonal()))[0].getDrawBounds(); expect([plain.left, plain.top, plain.right, plain.bottom]).toEqual([ 0, 0, 320, 256, ]); diff --git a/packages/melonjs/tests/tmxlayer-placement-webgl.spec.js b/packages/melonjs/tests/tmxlayer-placement-webgl.spec.js new file mode 100644 index 0000000000..0b47582a68 --- /dev/null +++ b/packages/melonjs/tests/tmxlayer-placement-webgl.spec.js @@ -0,0 +1,8 @@ +/** + * A tile layer drawn where its ancestors put it, on WebGL, with the GPU + * path: see `helpers/tile-layer-placement-checks.js`. + */ +import { video } from "../src/index.js"; +import { placementChecks } from "./helpers/tile-layer-placement-checks.js"; + +placementChecks(video.WEBGL, "WebGL", ["perTile", "shader", "prerender"]); diff --git a/packages/melonjs/tests/tmxlayer-placement.spec.js b/packages/melonjs/tests/tmxlayer-placement.spec.js new file mode 100644 index 0000000000..d073279d17 --- /dev/null +++ b/packages/melonjs/tests/tmxlayer-placement.spec.js @@ -0,0 +1,8 @@ +/** + * A tile layer drawn where its ancestors put it, on the Canvas renderer: + * see `helpers/tile-layer-placement-checks.js`. + */ +import { video } from "../src/index.js"; +import { placementChecks } from "./helpers/tile-layer-placement-checks.js"; + +placementChecks(video.CANVAS, "CANVAS", ["perTile", "prerender"]); diff --git a/packages/melonjs/tests/webgpu_tmxlayer_placement.spec.js b/packages/melonjs/tests/webgpu_tmxlayer_placement.spec.js new file mode 100644 index 0000000000..6ebc8fba77 --- /dev/null +++ b/packages/melonjs/tests/webgpu_tmxlayer_placement.spec.js @@ -0,0 +1,9 @@ +/** + * A tile layer drawn where its ancestors put it, on WebGPU: see + * `helpers/tile-layer-placement-checks.js`. Skipped where the browser has + * no WebGPU adapter. + */ +import { video } from "../src/index.js"; +import { placementChecks } from "./helpers/tile-layer-placement-checks.js"; + +placementChecks(video.WEBGPU, "WebGPU", ["perTile", "shader", "prerender"]); diff --git a/packages/pathfinding-plugin/CHANGELOG.md b/packages/pathfinding-plugin/CHANGELOG.md index 21c213f86d..6de3ce7d2b 100644 --- a/packages/pathfinding-plugin/CHANGELOG.md +++ b/packages/pathfinding-plugin/CHANGELOG.md @@ -1,5 +1,10 @@ # Changelog +## [1.1.1] - _unreleased_ + +### Fixed +- `Grid.fromTileLayer`: the grid stands where the layer's tiles are drawn when the layer has an offset in Tiled or was moved by its `pos`, which melonJS 20.17 follows when it draws the layer; the grid stayed at the map's origin + ## [1.1.0] - _2026-11-15_ ### Added diff --git a/packages/pathfinding-plugin/package.json b/packages/pathfinding-plugin/package.json index e6b114272d..9b894c5672 100644 --- a/packages/pathfinding-plugin/package.json +++ b/packages/pathfinding-plugin/package.json @@ -1,6 +1,6 @@ { "name": "@melonjs/pathfinding-plugin", - "version": "1.1.0", + "version": "1.1.1", "description": "melonJS A* pathfinding plugin", "homepage": "https://www.npmjs.com/package/@melonjs/pathfinding-plugin", "type": "module", diff --git a/packages/pathfinding-plugin/src/grid.ts b/packages/pathfinding-plugin/src/grid.ts index b9f9deb7c6..fa9c4472c8 100644 --- a/packages/pathfinding-plugin/src/grid.ts +++ b/packages/pathfinding-plugin/src/grid.ts @@ -595,6 +595,14 @@ export class Grid { corner.x += at.x - layer.pos.x; corner.y += at.y - layer.pos.y; } + // and where the layer was moved to in its map, by its offset in + // Tiled or by its `pos` (an engine that draws it there says where it + // stands unmoved; an older one drew it unmoved, whatever its `pos`) + const unmoved = (layer as { _mapPos?: { x: number; y: number } })._mapPos; + if (unmoved !== undefined) { + corner.x += layer.pos.x - unmoved.x; + corner.y += layer.pos.y - unmoved.y; + } if (isometric) { // the grid's corner is the box around its diamonds corner.x -= (layer.rows * layer.tilewidth) / 2; diff --git a/packages/pathfinding-plugin/tests/sources.spec.ts b/packages/pathfinding-plugin/tests/sources.spec.ts index 406eb64448..d293d76a50 100644 --- a/packages/pathfinding-plugin/tests/sources.spec.ts +++ b/packages/pathfinding-plugin/tests/sources.spec.ts @@ -230,6 +230,27 @@ describe("grids from a level", () => { grid.refresh(); expect(grid.isSolid(2, 1)).toBe(true); }); + + it("stands where the layer's tiles are drawn, when the layer was moved", () => { + // by its offset in Tiled, or as here by its `pos`: the tiles + // are drawn there, and the grid's cells are theirs + const layer = wallsLayer(); + const before = Grid.fromTileLayer(layer).getPointPosition(2, 1); + const { x, y } = layer.pos; + layer.pos.x = x + 24; + layer.pos.y = y - 10; + try { + const grid = Grid.fromTileLayer(layer); + const at = grid.getPointPosition(2, 1); + expect([at.x - before.x, at.y - before.y]).toEqual([24, -10]); + // the same cells, moved + expect(grid.isSolid(2, 0)).toBe(true); + expect(grid.isSolid(0, 0)).toBe(false); + } finally { + layer.pos.x = x; + layer.pos.y = y; + } + }); }); describe("Grid.fromBodies", () => { From 2e788199dde5947c41e7ee59d726cfeeef0dfbda Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 04:20:03 +0000 Subject: [PATCH 08/51] Tile layers: fixes from an adversarial test audit (#1897) Probes written to break the tile layer code, each against the reference picture, and what they found: - An orthogonal layer whose tiles are larger than the grid lay them over each other in the wrong order on the GPU when they came from more than one tileset (a pass per tileset) or the map's render order was not "right-down": such a layer is drawn tile by tile. - A layer with more columns or rows than the largest texture drew nothing on the GPU: drawn tile by tile. - A hexagonal map whose side leaves an odd number of pixels of a cell is laid out on whole pixels, as Tiled's own numbers are; and so drawn by the GPU too. The baked canvas of a staggered or hexagonal map of odd tile size was a pixel short. - The isometric CPU renderer left out tiles narrower than half a cell at the right edge of the view. - A camera with an offset over a moved world: the layer asked a plain rectangle, in place of the camera, whether it was the default one. - A container with a size of its own (a level loaded into one) is in view by its bounds before its layers are asked: it is told how far their tiles reach. - A layer taken out of its container and added again threw; a tile its tileset's image does not hold threw every frame tile by tile, and is now left undrawn on both paths. The probes are kept as tests (`tile-layer-edge-cases.js`, on WebGL and WebGPU), with the reference taught the orthogonal render orders and Tiled's whole numbers for hexagons. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- packages/melonjs/CHANGELOG.md | 5 + .../melonjs/skills/melonjs-tilemaps/SKILL.md | 8 +- packages/melonjs/src/level/tiled/TMXLayer.js | 222 +++++++- .../melonjs/src/level/tiled/TMXTileset.js | 12 +- .../tiled/renderer/TMXHexagonalRenderer.js | 18 +- .../tiled/renderer/TMXIsometricRenderer.js | 11 +- packages/melonjs/src/renderable/container.js | 31 ++ packages/melonjs/src/video/renderer.js | 10 + .../video/webgl/shaders/tmxlayer-common.frag | 5 + .../melonjs/src/video/webgl/webgl_renderer.js | 1 + .../video/webgpu/shaders/tmxlayer-common.wgsl | 5 + .../src/video/webgpu/webgpu_renderer.js | 3 + .../tests/helpers/tile-layer-compare.js | 22 +- .../tests/helpers/tile-layer-edge-cases.js | 501 ++++++++++++++++++ .../helpers/tile-layer-staggered-scenarios.js | 14 +- .../melonjs/tests/tmxlayer-edge-cases.spec.js | 8 + .../tests/webgpu_tmxlayer_edge_cases.spec.js | 9 + 17 files changed, 832 insertions(+), 53 deletions(-) create mode 100644 packages/melonjs/tests/helpers/tile-layer-edge-cases.js create mode 100644 packages/melonjs/tests/tmxlayer-edge-cases.spec.js create mode 100644 packages/melonjs/tests/webgpu_tmxlayer_edge_cases.spec.js diff --git a/packages/melonjs/CHANGELOG.md b/packages/melonjs/CHANGELOG.md index fa0d70370c..56cb535b29 100644 --- a/packages/melonjs/CHANGELOG.md +++ b/packages/melonjs/CHANGELOG.md @@ -16,12 +16,17 @@ - Tiled, GPU tile layers: the soft edge of a tile larger than the grid shows the tile behind it; it was drawn over the background instead, a thin outline round such tiles - Tiled, GPU tile layers: tiles larger than the grid are drawn whole above the map's first row and right of its last column, where they were cut off - Tiled, GPU tile layers: a tileset with a `margin` whose image stops at its last tiles, with no margin after them, draws the right tiles; they were counted a column or a row short +- Tiled, GPU tile layers: an orthogonal layer whose tiles are larger than the grid and come from more than one tileset, or whose map has a render order other than "right-down", is drawn tile by tile; on the GPU such tiles lay over each other in the wrong order +- Tiled, GPU tile layers: a layer with more columns or rows than the largest texture the GPU takes is drawn tile by tile; it drew nothing - Tiled, GPU tile layers: a layer with a tile that is not square, flipped diagonally, is drawn tile by tile; the shader drew such a tile wrong - Tiled, GPU tile layers: the shader runs at full precision whatever `highPrecisionShader` says; at a lower one a phone could misplace the tiles of a large map - Tiled: a tile layer follows its offset in Tiled (`offsetx`, `offsety`), and its own `pos` when the game moves it: its tiles are drawn there and `getTile()` finds them there, on every renderer and map orientation. Both were ignored, and the layer drawn at the map's origin; only image layers followed their offset. A map whose tile layers have an offset now looks as it does in Tiled - Tiled: tiles that reach past their layer's grid (taller or wider than a cell, or moved by a `tileoffset`) are drawn when they are in view and the grid is not; the whole layer was skipped, so the tops of tall tiles vanished once the map scrolled out of view. The layer's bounds are still its grid's - Tiled: a map centred in the view because it is smaller (as `level.load` centres it), and a tile layer in a container that was moved, are drawn whole. The layer read the camera's view as if it stood at the world's origin: on WebGL, WebGPU and a pre-rendered layer the tiles reaching above or left of the grid were cut, and tile by tile a layer far from the origin lost tiles - Tiled, staggered and hexagonal maps: a tile larger than its cell stands on the cell, and a tileset's `tileoffset` moves its tiles, as in Tiled and on every other map. Drawn tile by tile, such a tile hung down from the top of its cell and the offset was ignored, so the map sat lower than its objects (and than a tile redrawn in a baked layer); tiles of a large tileset also went missing along the edges of the view +- Tiled, hexagonal maps: a side whose length leaves an odd number of pixels of a cell is laid out on whole pixels, as Tiled lays it out; every other column or row drifted half a pixel further. A staggered or hexagonal map of odd tile size, pre-rendered, no longer loses a row and a column of pixels +- Tiled: a tile layer taken out of its container and added again is drawn; it threw. A tile its tileset's image does not hold (an image cropped since the map was saved) is not drawn; drawing it threw every frame +- Tiled, isometric maps drawn tile by tile: tiles narrower than half a cell are no longer left out at the right edge of the view - Tiled, isometric maps drawn tile by tile: tiles of a tileset larger than the map's first one, or moved by a `tileoffset`, went missing along the edges of the view - Tiled, orthogonal maps drawn tile by tile: tiles more than two cells tall went missing along the bottom of the view - `NineSliceSprite` blinks with `flicker()`, as a `Sprite` does; it ignored it diff --git a/packages/melonjs/skills/melonjs-tilemaps/SKILL.md b/packages/melonjs/skills/melonjs-tilemaps/SKILL.md index da107d41cc..3ea557a668 100644 --- a/packages/melonjs/skills/melonjs-tilemaps/SKILL.md +++ b/packages/melonjs/skills/melonjs-tilemaps/SKILL.md @@ -469,14 +469,17 @@ per-pixel GID lookup in the fragment shader. It requires **all** of: - no collection-of-image tileset, and a tileset tile render size of "Tile size" (`tilerendersize`, not "Map grid size"), - on an orthogonal map: no non-zero `tileoffset`, and tiles that reach at most - 4 cells past their own, + 4 cells past their own; a layer of tiles **larger than a cell** takes them + from one tileset, on a map in the default render order ("right-down"), - on an isometric, staggered or hexagonal map: every tile of the layer from **one tileset** (tiles overlap, and their order is kept within a tileset, not across two: split floor and walls into a layer each, which a map usually does already), tiles at most 4 cells wide and 8 tall, a grid of even size (64 × 32, not 65 × 33; a hexagon side of even length), and the normal blend mode. A `tileoffset` is fine, -- no tile that is not square flipped diagonally (rotated, in Tiled). +- no tile that is not square flipped diagonally (rotated, in Tiled), and no + more columns or rows than the largest texture has pixels (4096 on the + smallest devices). A tile set at run time with `setTile` that breaks one of these moves the layer back to `"perTile"`, with a warning. The two paths draw the same picture, with @@ -541,6 +544,7 @@ layer into the offscreen-bake path instead. | after updating to 20.17 a tile layer sits away from where it did | it has an offset in Tiled that was ignored until then, and now moves it as in the editor: clear the layer's Offset in Tiled if it was not meant | | a map smaller than the screen (centred by `level.load`) had the tops of its tall tiles cut on WebGL or WebGPU | before 20.17 a layer read the camera's view as if it stood at the world's origin, and so did a layer in a container the game had moved: update | | the tops of tall tiles vanish when the map itself scrolls out of view | before 20.17 a layer was skipped once its grid left the view, though tiles larger than a cell (or moved by a `tileoffset`) still reached in: update | +| an orthogonal layer warns `tiles larger than the grid, of more than one tileset in a layer` | tiles larger than a cell overlap, and the shader path keeps their order within one tileset: put each tileset's large tiles on a layer of their own (trees apart from the ground they stand on) | | tilemap slow on some machines | layer fell back off the shader path — check the console warning for the reason | | a staggered or hexagonal map sits higher than before 20.17, by how much its tiles are taller than a cell (or by its tileset's `tileoffset`) | it is drawn as Tiled draws it: until then a tile hung from the top of its cell and the offset was ignored, away from the map's objects | | an isometric (staggered, hexagonal) layer warns `tiles of more than one tileset in an isometric layer` and is slow | the shader path draws such a layer with one tileset: put the tiles of each tileset on a layer of their own, or pack them into one tileset | diff --git a/packages/melonjs/src/level/tiled/TMXLayer.js b/packages/melonjs/src/level/tiled/TMXLayer.js index 996375c0fe..5fb50e7b7c 100644 --- a/packages/melonjs/src/level/tiled/TMXLayer.js +++ b/packages/melonjs/src/level/tiled/TMXLayer.js @@ -276,8 +276,13 @@ export default class TMXLayer extends Renderable { // A tile larger than its cell reaches past it: up and to the right, // as a tile stands on the bottom left of its cell (any way on an // oblique map) - const overX = Math.max(this.maxTileSize.width - this.tilewidth, 0); - const overY = Math.max(this.maxTileSize.height - this.tileheight, 0); + // (a staggered or a hexagonal map is laid on the even size below its + // tiles': a tile of odd size stands a pixel past its cell) + const evenGrid = orientation === "staggered" || orientation === "hexagonal"; + const cellWidth = evenGrid ? this.tilewidth & ~1 : this.tilewidth; + const cellHeight = evenGrid ? this.tileheight & ~1 : this.tileheight; + const overX = Math.max(this.maxTileSize.width - cellWidth, 0); + const overY = Math.max(this.maxTileSize.height - cellHeight, 0); const upRight = orientation !== "oblique"; /** * How far past the layer's grid its tiles can be drawn, on each @@ -541,6 +546,32 @@ export default class TMXLayer extends Renderable { // called when the layer is added to the game world or a container onActivateEvent() { + // afresh: a layer taken out of a container and put back is + // activated again + this.animatedTilesets = []; + // A container with a size of its own (one a level was loaded into) + // is in view by its bounds, before its children are asked: it is + // told how far past them this layer's tiles reach + const reach = this._reach; + if ( + reach.left > 0 || + reach.top > 0 || + reach.right > 0 || + reach.bottom > 0 + ) { + for (let node = this.ancestor; node; node = node.ancestor) { + const kept = (node._drawReach ??= { + left: 0, + top: 0, + right: 0, + bottom: 0, + }); + kept.left = Math.max(kept.left, reach.left); + kept.top = Math.max(kept.top, reach.top); + kept.right = Math.max(kept.right, reach.right); + kept.bottom = Math.max(kept.bottom, reach.bottom); + } + } if (this.tilesets) { const tileset = this.tilesets.tilesets; for (let i = 0; i < tileset.length; i++) { @@ -586,8 +617,14 @@ export default class TMXLayer extends Renderable { // an oversized tile reaches past its cell (which way depends on the // orientation: up and to the right, any way on an oblique map), and // a tileset's offset moves all of its tiles - const overX = Math.max(this.maxTileSize.width - this.tilewidth, 0); - const overY = Math.max(this.maxTileSize.height - this.tileheight, 0); + const overX = Math.max( + this.maxTileSize.width - (renderer.tilewidth ?? this.tilewidth), + 0, + ); + const overY = Math.max( + this.maxTileSize.height - (renderer.tileheight ?? this.tileheight), + 0, + ); let left = bounds.left - overX; let top = bounds.top - overY; let right = bounds.right + overX; @@ -798,8 +835,17 @@ export default class TMXLayer extends Renderable { if (!this.tilesets || this.tilesets.tilesets.length === 0) { return { ok: false, reason: "no tilesets" }; } + // the path keeps a texel per cell: no more of them, either way, than + // the largest texture has + const maxTexture = renderer.maxTextureSize ?? Infinity; + if (this.cols > maxTexture || this.rows > maxTexture) { + return { + ok: false, + reason: `more columns or rows than the largest texture has pixels (${maxTexture})`, + }; + } if (this.orientation !== "orthogonal") { - return this._checkOverlappingShaderEligibility(); + return this._checkOverlappingShaderEligibility(renderer); } // the shader iterates a fixed-size loop over candidate cells to // support oversized tiles (tile dim > cell dim) drawn bottom-aligned. @@ -807,14 +853,9 @@ export default class TMXLayer extends Renderable { // so refuse the shader path for layers with extreme oversampling. const MAX_OVERFLOW_CELLS = ORTHOGONAL_MAX_OVERFLOW; for (const ts of this.tilesets.tilesets) { - if (ts.isCollection) { - return { ok: false, reason: "collection-of-image tileset" }; - } - if (ts.tilerendersize !== "tile") { - return { - ok: false, - reason: `tilerendersize "${ts.tilerendersize}" not supported`, - }; + const reason = this._tilesetReason(ts, renderer); + if (reason !== undefined) { + return { ok: false, reason }; } if (ts.tileoffset.x !== 0 || ts.tileoffset.y !== 0) { return { ok: false, reason: "non-zero tileoffset" }; @@ -828,6 +869,10 @@ export default class TMXLayer extends Renderable { }; } } + const overlap = this._checkOrthogonalOverlap(); + if (overlap !== undefined) { + return { ok: false, reason: overlap }; + } if (this._hasDiagonalFlipNotSquare()) { return { ok: false, reason: DIAGONAL_NOT_SQUARE }; } @@ -863,6 +908,116 @@ export default class TMXLayer extends Renderable { return false; } + /** + * Why the shader path cannot draw the tiles of a tileset, on any map, if + * it cannot. + * @param {TMXTileset} tileset - the tileset + * @param {object} [renderer] - the renderer, for its largest texture + * @returns {string|undefined} the reason, or undefined when it can + * @ignore + * @internal + */ + _tilesetReason(tileset, renderer) { + if (tileset.isCollection) { + return "collection-of-image tileset"; + } + if (tileset.tilerendersize !== "tile") { + return `tilerendersize "${tileset.tilerendersize}" not supported`; + } + // an animated tileset has a texel per tile, in one row + const maxTexture = renderer?.maxTextureSize ?? Infinity; + if ( + tileset.isAnimated && + tileset.lastgid - tileset.firstgid + 1 > maxTexture + ) { + return `an animated tileset of more tiles than the largest texture has pixels (${maxTexture})`; + } + return undefined; + } + + /** + * Whether a tileset's tiles are larger than a cell: they overlap the + * cells around theirs. + * @param {TMXTileset} tileset - the tileset + * @returns {boolean} + * @ignore + * @internal + */ + _largerThanCell(tileset) { + return ( + tileset.tilewidth > this.tilewidth || tileset.tileheight > this.tileheight + ); + } + + /** + * Check an orthogonal layer for tiles that overlap in a way the shader + * path does not keep, and note the tilesets its tiles come from. + * + * Tiles the size of a cell never overlap, and any layer of them is fine. + * Tiles larger than a cell lie over their neighbours, the one drawn last + * on top: the shader keeps that order among the tiles of ONE tileset (it + * draws a pass per tileset, each whole pass over the last), and for the + * map's default order alone, from the top down and the left across + * ("right-down"). + * @returns {string|undefined} why the path cannot draw the layer, or + * undefined when it can + * @ignore + * @internal + */ + _checkOrthogonalOverlap() { + /** + * the tilesets an orthogonal layer's tiles come from, when some of + * the map's are larger than a cell (`setTile` adds to them): + * undefined when none is, and nothing can overlap + * @ignore + */ + this._usedTilesets = undefined; + if ( + !this.tilesets.tilesets.some((tileset) => { + return this._largerThanCell(tileset); + }) + ) { + return undefined; + } + const used = new Set(); + const data = this.layerData; + let tileset = null; + for (let i = 0; i < data.length; i += 2) { + const gid = data[i]; + if (gid !== 0 && (tileset === null || !tileset.contains(gid))) { + tileset = this.tilesets.getTilesetByGid(gid); + used.add(tileset); + } + } + this._usedTilesets = used; + return this._orthogonalOverlapReason(); + } + + /** + * Why the tiles of the tilesets an orthogonal layer uses overlap in a way + * the shader path does not keep, if they do (see + * {@link TMXLayer#_checkOrthogonalOverlap}). + * @returns {string|undefined} the reason, or undefined + * @ignore + * @internal + */ + _orthogonalOverlapReason() { + let larger = false; + for (const tileset of this._usedTilesets) { + larger = larger || this._largerThanCell(tileset); + } + if (!larger) { + return undefined; + } + if (this._usedTilesets.size > 1) { + return "tiles larger than the grid, of more than one tileset in a layer"; + } + if (this.renderorder !== "right-down") { + return `render order "${this.renderorder}" with tiles larger than the grid`; + } + return undefined; + } + /** * Check whether this layer of an isometric, staggered or hexagonal map * can take the shader path, and note the tileset it would draw with. @@ -877,7 +1032,7 @@ export default class TMXLayer extends Renderable { * @ignore * @internal */ - _checkOverlappingShaderEligibility() { + _checkOverlappingShaderEligibility(renderer) { this._shaderTileset = null; const kind = kindOf(this.orientation); // Half the cells of a grid of odd size stand half a pixel off (on a @@ -914,7 +1069,7 @@ export default class TMXLayer extends Renderable { } } if (tileset !== null) { - const reason = this._overlappingTilesetReason(tileset); + const reason = this._overlappingTilesetReason(tileset, renderer); if (reason !== undefined) { return { ok: false, reason }; } @@ -935,12 +1090,10 @@ export default class TMXLayer extends Renderable { * @ignore * @internal */ - _overlappingTilesetReason(tileset) { - if (tileset.isCollection) { - return "collection-of-image tileset"; - } - if (tileset.tilerendersize !== "tile") { - return `tilerendersize "${tileset.tilerendersize}" not supported`; + _overlappingTilesetReason(tileset, renderer) { + const unfit = this._tilesetReason(tileset, renderer); + if (unfit !== undefined) { + return unfit; } // The shader looks, for each pixel, at every cell whose tile image // could cover it: a bounded number, of lines of cells and of cells @@ -974,16 +1127,25 @@ export default class TMXLayer extends Renderable { */ _keepShaderEligible(gid, flipMask) { let reason; - if ( - this.orientation !== "orthogonal" && - this._shaderTileset?.contains(gid) !== true - ) { + if (this.orientation === "orthogonal") { + // a tileset the layer did not use yet, where tiles can overlap + if (this._usedTilesets !== undefined) { + const tileset = this.tilesets.getTilesetByGid(gid); + if (!this._usedTilesets.has(tileset)) { + this._usedTilesets.add(tileset); + reason = this._orthogonalOverlapReason(); + } + } + } else if (this._shaderTileset?.contains(gid) !== true) { if (this._shaderTileset) { reason = oneTilesetReason(this.orientation); } else { // an empty layer takes its tileset from its first tile const tileset = this.tilesets.getTilesetByGid(gid); - reason = this._overlappingTilesetReason(tileset); + reason = this._overlappingTilesetReason( + tileset, + this.parentApp?.renderer, + ); if (reason === undefined) { this._shaderTileset = tileset; } @@ -1013,7 +1175,7 @@ export default class TMXLayer extends Renderable { // renderer-side caches keyed by this layer (e.g. the WebGL2 shader // path's per-layer GID index texture) are cleared from the renderer's // own `reset()` path — tile layers only come and go on game reset. - this.animatedTilesets = undefined; + this.animatedTilesets = []; // keep canvasRenderer for reuse — dropping the reference would leak // event listeners registered by CanvasRenderer's constructor } @@ -1264,6 +1426,10 @@ export default class TMXLayer extends Renderable { this.canvasRenderer.renderTarget.invalidate(renderer); renderer.cache.tinted?.delete(this.canvasRenderer.getCanvas()); } + // whether the view is the default camera's, which draws the world + // where its `pos` puts it (any other draws it unmoved): asked of the + // camera, before a plain rectangle stands in for it below + const unmovedWorld = rect.isDefault === false; // the camera's offset (a look ahead, a shake) shifts what it shows // without moving it: the tiles to draw are the ones in that view const offset = rect.offset; @@ -1284,7 +1450,7 @@ export default class TMXLayer extends Renderable { const at = parent.getAbsolutePosition(); shiftX = at.x; shiftY = at.y; - if (rect.isDefault === false) { + if (unmovedWorld) { let root = parent; while (root.ancestor) { root = root.ancestor; diff --git a/packages/melonjs/src/level/tiled/TMXTileset.js b/packages/melonjs/src/level/tiled/TMXTileset.js index 23f32c8cf3..05c390af59 100644 --- a/packages/melonjs/src/level/tiled/TMXTileset.js +++ b/packages/melonjs/src/level/tiled/TMXTileset.js @@ -860,6 +860,16 @@ export default class TMXTileset { dy += this._renderDyCenter; } + // a tile the tileset's image does not hold (an image cropped since the + // map was saved, a `tilecount` larger than the image has): nothing + // to draw, as in Tiled + const frame = this.isCollection + ? undefined + : this.atlas[this.getViewTileId(gid)]; + if (!this.isCollection && frame === undefined) { + return; + } + // check if any transformation is required if (flipMask !== 0) { renderer.save(); @@ -892,7 +902,7 @@ export default class TMXTileset { dh, ); } else { - const offset = this.atlas[this.getViewTileId(gid)].offset; + const offset = frame.offset; renderer.drawImage( this.image, offset.x, diff --git a/packages/melonjs/src/level/tiled/renderer/TMXHexagonalRenderer.js b/packages/melonjs/src/level/tiled/renderer/TMXHexagonalRenderer.js index 63d1bf2935..93f84d5abc 100644 --- a/packages/melonjs/src/level/tiled/renderer/TMXHexagonalRenderer.js +++ b/packages/melonjs/src/level/tiled/renderer/TMXHexagonalRenderer.js @@ -46,8 +46,12 @@ export default class TMXHexagonalRenderer extends TMXRenderer { } } - this.sideoffsetx = (this.tilewidth - this.sidelengthx) / 2; - this.sideoffsety = (this.tileheight - this.sidelengthy) / 2; + // in whole numbers, as Tiled's own (libtiled's `RenderParams`): a + // side of odd length leaves an odd number of pixels to halve, and + // the half pixel is dropped, not kept: columns and rows stay on + // whole pixels, where Tiled has them + this.sideoffsetx = Math.trunc((this.tilewidth - this.sidelengthx) / 2); + this.sideoffsety = Math.trunc((this.tileheight - this.sidelengthy) / 2); this.columnwidth = this.sideoffsetx + this.sidelengthx; this.rowheight = this.sideoffsety + this.sidelengthy; @@ -498,7 +502,10 @@ export default class TMXHexagonalRenderer extends TMXRenderer { ); } } - rowPos.x += this.tilewidth + this.sidelengthx; + // the next cell of the line, two columns on: where + // `tileToPixelCoords` puts it (a side of odd length + // leaves the tile's width a pixel more than that) + rowPos.x += this.columnwidth * 2; } if (staggeredRow) { @@ -559,7 +566,10 @@ export default class TMXHexagonalRenderer extends TMXRenderer { ); } } - rowPos.x += this.tilewidth + this.sidelengthx; + // the next cell of the line, two columns on: where + // `tileToPixelCoords` puts it (a side of odd length + // leaves the tile's width a pixel more than that) + rowPos.x += this.columnwidth * 2; } startPos.y += this.rowheight; } diff --git a/packages/melonjs/src/level/tiled/renderer/TMXIsometricRenderer.js b/packages/melonjs/src/level/tiled/renderer/TMXIsometricRenderer.js index f81f5de6e0..2f9e2d0d64 100644 --- a/packages/melonjs/src/level/tiled/renderer/TMXIsometricRenderer.js +++ b/packages/melonjs/src/level/tiled/renderer/TMXIsometricRenderer.js @@ -166,8 +166,15 @@ export default class TMXIsometricRenderer extends TMXRenderer { // missing along the bottom of the view, where their cell is below it // and their image still reaches in, and so did tiles moved into view // by an offset larger than a tile - const reachX = layer.maxTileSize.width + (layer.maxTileOffset?.x ?? 0); - const reachY = layer.maxTileSize.height + (layer.maxTileOffset?.y ?? 0); + // (by a cell at least: the corners below are rounded to whole + // cells, half a cell either way, which a tile narrower than that + // does not make up for) + const reachX = + Math.max(layer.maxTileSize.width, this.tilewidth) + + (layer.maxTileOffset?.x ?? 0); + const reachY = + Math.max(layer.maxTileSize.height, this.tileheight) + + (layer.maxTileOffset?.y ?? 0); const rowItr = this.pixelToTileCoords( rect.pos.x - reachX, rect.pos.y - reachY, diff --git a/packages/melonjs/src/renderable/container.js b/packages/melonjs/src/renderable/container.js index c7673d4712..ad02df323e 100644 --- a/packages/melonjs/src/renderable/container.js +++ b/packages/melonjs/src/renderable/container.js @@ -1,5 +1,6 @@ import { colorPool } from "../math/color.ts"; import { Matrix3d } from "../math/matrix3d.ts"; +import { boundsPool } from "../physics/bounds.ts"; import Body from "../physics/builtin/body.js"; import { needsShapeResolution, @@ -1130,6 +1131,36 @@ export default class Container extends Renderable { return obj.length > 0 ? obj[0] : null; } + /** + * The area this container draws in, when something in it draws past its + * own bounds and has said so (a tile layer whose tiles stand above its + * grid, see `TMXLayer#getDrawBounds`): the container's bounds, grown by + * as much. A camera has the container in view by this area, as it would + * the layer (see `Camera2d#isVisible`). + * @returns {Bounds|undefined} that area, or undefined when it is the + * container's bounds (or the container has no size of its own) + * @ignore + */ + getDrawBounds() { + const reach = this._drawReach; + if (reach === undefined) { + return undefined; + } + const bounds = this.getBounds(); + if (!bounds.isFinite()) { + return undefined; + } + /** @ignore */ + this._drawBounds ??= boundsPool.get(); + this._drawBounds.setMinMax( + bounds.left - reach.left, + bounds.top - reach.top, + bounds.right + reach.right, + bounds.bottom + reach.bottom, + ); + return this._drawBounds; + } + /** * return all child in this container * @returns {Renderable[]} an array of renderable object diff --git a/packages/melonjs/src/video/renderer.js b/packages/melonjs/src/video/renderer.js index 28a65333bc..c4a1b8f5a9 100644 --- a/packages/melonjs/src/video/renderer.js +++ b/packages/melonjs/src/video/renderer.js @@ -211,6 +211,16 @@ export default class Renderer { */ this.supportsShaderTileLayers = false; + /** + * The largest texture this renderer can make, in pixels a side: no + * limit on Canvas. A tile layer drawn by the GPU keeps a texel per + * cell, so a layer with more columns or rows than this is drawn + * tile by tile. + * @type {number} + * @ignore + */ + this.maxTextureSize = Infinity; + /** * Whether this backend can render into a half-float color buffer. * Renderability alone; {@link Renderer#supportsHDR} is the one to diff --git a/packages/melonjs/src/video/webgl/shaders/tmxlayer-common.frag b/packages/melonjs/src/video/webgl/shaders/tmxlayer-common.frag index 214b7a5e84..d6fc5fa175 100644 --- a/packages/melonjs/src/video/webgl/shaders/tmxlayer-common.frag +++ b/packages/melonjs/src/video/webgl/shaders/tmxlayer-common.frag @@ -160,6 +160,11 @@ bool tryRenderCell(int cx, int cy, vec2 worldPx, Footprint fp, out vec4 outColor // may land a hair under the row it should int cols = int(uTilesetCols.x); int row = localId / cols; + // a tile the tileset's image does not hold (an image cropped since the + // map was saved): nothing to draw + if (row >= int(uTilesetCols.y)) { + return false; + } vec2 tileOriginPx = uTilesetMargin.xy + vec2(float(localId - row * cols), float(row)) * (uTileSize + uTilesetMargin.zw); vec2 texelPx = tileOriginPx + inTile * uTileSize; diff --git a/packages/melonjs/src/video/webgl/webgl_renderer.js b/packages/melonjs/src/video/webgl/webgl_renderer.js index 0aaf2676c2..6afeb19b87 100644 --- a/packages/melonjs/src/video/webgl/webgl_renderer.js +++ b/packages/melonjs/src/video/webgl/webgl_renderer.js @@ -521,6 +521,7 @@ export default class WebGLRenderer extends Renderer { // this backend renders TMX tile layers on the GPU (see TMXLayer) this.supportsShaderTileLayers = true; + this.maxTextureSize = this.gl.getParameter(this.gl.MAX_TEXTURE_SIZE); // this backend keeps mesh geometry resident on the GPU, so meshes can // hand it their model matrix instead of pre-transformed vertices diff --git a/packages/melonjs/src/video/webgpu/shaders/tmxlayer-common.wgsl b/packages/melonjs/src/video/webgpu/shaders/tmxlayer-common.wgsl index a5b208c24b..4e7f1f6151 100644 --- a/packages/melonjs/src/video/webgpu/shaders/tmxlayer-common.wgsl +++ b/packages/melonjs/src/video/webgpu/shaders/tmxlayer-common.wgsl @@ -163,6 +163,11 @@ fn tryRenderCell(cx : i32, cy : i32, worldPx : vec2f, fp : Footprint) -> CellSam // may land a hair under the row it should let cols = i32(tmx.uTilesetCols.x); let row = localId / cols; + // a tile the tileset's image does not hold (an image cropped since the + // map was saved): nothing to draw + if (row >= i32(tmx.uTilesetCols.y)) { + return miss; + } let tileOriginPx = tmx.uTilesetMargin.xy + vec2f(f32(localId - row * cols), f32(row)) * (tmx.uTileSize + tmx.uTilesetMargin.zw); var texelPx = tileOriginPx + inTile * tmx.uTileSize; diff --git a/packages/melonjs/src/video/webgpu/webgpu_renderer.js b/packages/melonjs/src/video/webgpu/webgpu_renderer.js index dfadff3173..d2c25cdb55 100644 --- a/packages/melonjs/src/video/webgpu/webgpu_renderer.js +++ b/packages/melonjs/src/video/webgpu/webgpu_renderer.js @@ -199,6 +199,7 @@ export default class WebGPURenderer extends Renderer { this.supportsDepthBuffer = true; this.supportsRetainedMesh = true; this.supportsInstancing = true; + // (`maxTextureSize` is the device's, once there is one: see `init`) // `rgba16float` is renderable, blendable and filterable in core // WebGPU, with no optional feature to request and nothing to probe — // unlike WebGL2, where it takes an extension that some drivers do @@ -555,6 +556,8 @@ export default class WebGPURenderer extends Renderer { return adapter.features.has(feature); }), }); + this.maxTextureSize = + this.device.limits?.maxTextureDimension2D ?? this.maxTextureSize; // identify the driver in the console header, same as the WebGL // backend does through its debug-renderer-info strings. The diff --git a/packages/melonjs/tests/helpers/tile-layer-compare.js b/packages/melonjs/tests/helpers/tile-layer-compare.js index 64e59d8da7..5f925c086b 100644 --- a/packages/melonjs/tests/helpers/tile-layer-compare.js +++ b/packages/melonjs/tests/helpers/tile-layer-compare.js @@ -311,17 +311,22 @@ export function reference(scene, viewX, viewY, width, height) { const side = orientation === "hexagonal" ? hexsidelength : 0; const sideX = staggerX ? side : 0; const sideY = staggerX ? 0 : side; - const columnWidth = (tw - sideX) / 2 + sideX; - const rowHeight = (th - sideY) / 2 + sideY; + // Tiled's own numbers (libtiled's hexagonal `RenderParams`), all + // whole: the grid is the even size below the tiles', and half + // of what a side leaves of a cell is rounded down + const cw = tw & ~1; + const ch = th & ~1; + const columnWidth = Math.trunc((cw - sideX) / 2) + sideX; + const rowHeight = Math.trunc((ch - sideY) / 2) + sideY; const place = ({ col, row }) => { // `& 1` and not `% 2`: an infinite map has negative cells return staggerX ? { x: col * columnWidth, - y: row * (th + sideY) + ((col & 1) ^ even) * rowHeight, + y: row * (ch + sideY) + ((col & 1) ^ even) * rowHeight, } : { - x: col * (tw + sideX) + ((row & 1) ^ even) * columnWidth, + x: col * (cw + sideX) + ((row & 1) ^ even) * columnWidth, y: row * rowHeight, }; }; @@ -332,11 +337,16 @@ export function reference(scene, viewX, viewY, width, height) { return a.y - b.y || a.x - b.x; }); for (const { gid, x, y } of placed) { - drawTile(gid, ox + x, oy + y + th); + drawTile(gid, ox + x, oy + y + ch); } } else { + // the map's render order: rows from the top or the bottom, each + // from the left or the right ("right-down" unless said) + const order = scene.extra?.renderorder ?? "right-down"; + const down = order.endsWith("down") ? 1 : -1; + const right = order.startsWith("right") ? 1 : -1; ordered.sort((a, b) => { - return a.row - b.row || a.col - b.col; + return down * (a.row - b.row) || right * (a.col - b.col); }); for (const { col, row, gid } of ordered) { drawTile(gid, ox + col * tw, oy + (row + 1) * th); diff --git a/packages/melonjs/tests/helpers/tile-layer-edge-cases.js b/packages/melonjs/tests/helpers/tile-layer-edge-cases.js new file mode 100644 index 0000000000..1990d88a1d --- /dev/null +++ b/packages/melonjs/tests/helpers/tile-layer-edge-cases.js @@ -0,0 +1,501 @@ +/** + * Tile layers at their edges: the cases a set of adversarial probes broke, + * each held to the picture painted with no engine (`tile-layer-compare.js`). + * A layer the GPU path cannot draw right is left to the CPU renderer, with a + * word in the console, and is still drawn as Tiled draws it. + * + * One spec file per GPU backend calls this. + */ +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { Container } from "../../src/index.js"; +import { + comparePaths, + diff, + drawIn, + drawn, + fill, + makeApp, + makeMap, + makeTileset, + reference, + show, +} from "./tile-layer-compare.js"; + +const W = 320; +const H = 240; + +const all = (cols, rows) => { + return fill(cols, rows, (c, r) => { + return 1 + ((c + r * 3) % 8); + }); +}; + +/** + * Declare the cases for one GPU backend. + * @param {number} renderer - `video.WEBGL` or `video.WEBGPU` + * @param {string} type - the `renderer.type` expected ("WebGL", "WebGPU") + */ +export function edgeCases(renderer, type) { + describe(`tile layers at their edges (${type})`, () => { + let app; + beforeAll(async () => { + app = await makeApp(renderer, type, W, H); + }); + afterAll(() => { + app?.world.pos.set(0, 0, 0); + app?.destroy(); + vi.restoreAllMocks(); + }); + const need = (ctx) => { + if (app === null || app === undefined) { + ctx.skip(`${type} not available in this environment`); + } + }; + + /** + * Put a scene in the world, and say how its first layer is drawn and + * what was warned. + */ + const shown = (scene) => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + const layers = show(app, makeMap(scene)); + return { + layers, + mode: layers[0].renderMode, + said: warn.mock.calls.flat().join(" "), + }; + } finally { + warn.mockRestore(); + } + }; + + /** + * A layer left to the CPU renderer for `reason`: drawn as the + * reference, as it stands and when asked for the GPU path by hand. + */ + const fallsBack = async (scene, reason, views = [[-40, -60]]) => { + const { layers, mode, said } = shown(scene); + expect(mode).toBe("perTile"); + expect(said).toMatch(reason); + for (const [x, y] of views) { + app.viewport.moveTo(x, y); + const ref = reference(scene, x, y, W, H); + expect(drawn(ref)).toBeGreaterThan(0); + const cpu = await drawIn(app, layers, "perTile"); + const c = diff(ref, cpu.frame); + expect(c.different, `tile by tile: ${c.first}`).toBe(0); + // by hand: still tile by tile, and the same picture + const forced = await drawIn(app, layers, "shader"); + expect(forced.cpuDraws).toBe(layers.length); + const f = diff(ref, forced.frame); + expect(f.different, `asked for by hand: ${f.first}`).toBe(0); + } + }; + + describe("what is in view", () => { + it("isometric, tile by tile: a tile narrower than half a cell, at the right edge of the view", async (ctx) => { + need(ctx); + // the view's corners are rounded to whole cells, half a cell + // either way: a tile 8 pixels wide does not make up for it + const scene = { + orientation: "isometric", + cols: 1, + rows: 1, + tw: 64, + th: 32, + tilesets: [makeTileset({ tw: 8, th: 8 })], + layers: [{ data: [1] }], + }; + const layers = show(app, makeMap(scene)); + // the one tile is drawn at x 0 to 7: these views end 1 to 8 + // pixels right of its left edge + for (let right = 1; right <= 8; right++) { + const x = right - W; + app.viewport.moveTo(x, -120); + const ref = reference(scene, x, -120, W, H); + expect(drawn(ref), "the tile is in view").toBe(right * 8); + for (const mode of ["shader", "perTile"]) { + const { frame } = await drawIn(app, layers, mode); + const d = diff(ref, frame); + expect(d.different, `${mode}, ${right} px in view`).toBe(0); + } + } + }); + + it("a layer in a container with a size: the tops of tall tiles, the grid out of view", async (ctx) => { + need(ctx); + // a level loaded into a container gives it the map's size: + // the camera has the container in view by its bounds before + // it asks the layer, whose tiles stand 64 pixels above + const scene = { + orientation: "orthogonal", + cols: 4, + rows: 3, + tw: 32, + th: 32, + tilesets: [makeTileset({ tw: 32, th: 96 })], + layers: [{ data: all(4, 3) }], + }; + // the view ends 10 pixels above the grid's first row + const view = [-40, -H - 10]; + const ref = reference(scene, ...view, W, H); + expect(drawn(ref)).toBeGreaterThan(0); + for (const boxed of [false, true]) { + app.world.reset(); + app.world.pos.set(0, 0, app.world.pos.z); + app.renderer.reset?.(); + app.renderer.backgroundColor.setColor(16, 24, 48); + const map = makeMap(scene); + const box = boxed ? new Container() : app.world; + if (boxed) { + app.world.addChild(box); + } + map.addTo(box, true, false); + app.world.sortNow(true); + app.viewport.setBounds(-100000, -100000, 200000, 200000); + app.viewport.moveTo(...view); + for (const mode of ["perTile", "shader"]) { + const { frame } = await drawIn(app, map.getLayers(), mode); + const d = diff(ref, frame); + expect( + d.different, + `${boxed ? "in a container" : "in the world"}, ${mode}: ${d.first}`, + ).toBe(0); + } + } + }); + + for (const mode of ["perTile", "shader", "prerender"]) { + it(`a zoomed camera with an offset, over a moved world, drawn "${mode}"`, async (ctx) => { + need(ctx); + // the camera at `pos + offset` with no offset shows the + // same thing, by definition: zoomed, it is not the + // default camera, and draws the world unmoved + const scene = { + orientation: "orthogonal", + cols: 12, + rows: 12, + tw: 32, + th: 32, + tilesets: [makeTileset({ tw: 32, th: 32 })], + layers: [{ data: all(12, 12) }], + }; + app.world.reset(); + app.renderer.reset?.(); + app.renderer.backgroundColor.setColor(16, 24, 48); + // the world moved first, as a centred map leaves it + app.world.pos.set(100, 60, app.world.pos.z); + const map = makeMap(scene); + const layers = map.getLayers(); + if (mode === "prerender") { + layers[0].renderMode = mode; + } + map.addTo(app.world, true, false); + app.world.sortNow(true); + app.viewport.setBounds(-100000, -100000, 200000, 200000); + try { + for (const zoom of [1, 2]) { + app.viewport.zoom = zoom; + app.viewport.offset.set(0, 0); + app.viewport.moveTo(60 + 26, 40 - 18); + const moved = await drawIn(app, layers, mode); + expect(drawn(moved.frame)).toBeGreaterThan(0); + app.viewport.offset.set(26, -18); + app.viewport.moveTo(60, 40); + const shaken = await drawIn(app, layers, mode); + const d = diff(moved.frame, shaken.frame); + expect(d.different, `zoom ${zoom}: ${d.first}`).toBe(0); + } + } finally { + app.viewport.zoom = 1; + app.viewport.offset.set(0, 0); + app.world.pos.set(0, 0, app.world.pos.z); + } + }); + } + }); + + describe("grids of odd sizes, laid out as Tiled lays them out", () => { + it("a staggered map of odd tile size: on the even grid below, tile by tile and baked", async (ctx) => { + need(ctx); + // 63 x 31 tiles stand on 62 x 30 cells: one pixel above and + // one to the right of each + const scene = { + orientation: "staggered", + cols: 4, + rows: 4, + tw: 63, + th: 31, + tilesets: [makeTileset({ tw: 63, th: 31 })], + layers: [{ data: all(4, 4) }], + extra: { staggeraxis: "y", staggerindex: "odd" }, + }; + await fallsBack(scene, /odd size/, [ + [-20, -20], + [40, 10], + ]); + const baked = show(app, makeMap(scene), "prerender"); + for (const [x, y] of [ + [-20, -20], + [40, 10], + ]) { + app.viewport.moveTo(x, y); + const { frame } = await drawIn(app, baked, "prerender"); + const d = diff(reference(scene, x, y, W, H), frame); + expect(d.different, `baked: ${d.first}`).toBe(0); + } + }); + + for (const [axis, tw, th, side] of [ + ["x", 28, 24, 11], + ["y", 28, 24, 11], + ["x", 30, 24, 7], + // longer than the tile: the half left of a cell is negative + ["x", 28, 24, 33], + ]) { + it(`a hexagon side of ${side} on ${tw} x ${th} cells, axis ${axis}: columns and rows on whole pixels`, async (ctx) => { + need(ctx); + // Tiled halves what a side leaves of a cell in whole + // numbers: 28 wide with a side of 11 is columns 19 + // pixels apart, not 19.5 + const scene = { + orientation: "hexagonal", + cols: 6, + rows: 5, + tw, + th, + tilesets: [makeTileset({ tw, th })], + layers: [{ data: all(6, 5) }], + extra: { + staggeraxis: axis, + staggerindex: "odd", + hexsidelength: side, + }, + }; + const views = [ + [-20, -20], + [35, 12], + ]; + expect(await comparePaths(app, scene, { views })).toBeGreaterThan(0); + }); + } + }); + + describe("orthogonal layers whose tiles overlap", () => { + const big = (options = {}) => { + return makeTileset({ tw: 48, th: 48, ...options }); + }; + + it("tiles of two tilesets, larger than the grid, in one layer", async (ctx) => { + need(ctx); + // a later cell lies over an earlier one, whichever tileset + // its tile is from: a pass per tileset cannot keep that + const scene = { + orientation: "orthogonal", + cols: 4, + rows: 3, + tw: 32, + th: 32, + tilesets: [big(), big()], + layers: [ + { + // a checkerboard of the two tilesets + data: fill(4, 3, (c, r) => { + return 1 + ((c + r) % 2) * 8 + ((c + r * 3) % 8); + }), + }, + ], + }; + await fallsBack(scene, /more than one tileset/); + }); + + it("tiles of two tilesets, the size of the grid: nothing overlaps, and the GPU draws them", async (ctx) => { + need(ctx); + const scene = { + orientation: "orthogonal", + cols: 6, + rows: 5, + tw: 32, + th: 32, + tilesets: [ + makeTileset({ tw: 32, th: 32 }), + makeTileset({ tw: 32, th: 32 }), + ], + layers: [ + { + data: fill(6, 5, (c, r) => { + return 1 + ((c + r) % 2) * 8 + ((c + r * 3) % 8); + }), + }, + ], + }; + expect(await comparePaths(app, scene)).toBeGreaterThan(0); + }); + + it("a large tileset in the map that the layer does not use", async (ctx) => { + need(ctx); + // the layer's own tiles are the size of the grid + const scene = { + orientation: "orthogonal", + cols: 6, + rows: 5, + tw: 32, + th: 32, + tilesets: [ + makeTileset({ tw: 32, th: 32 }), + makeTileset({ tw: 32, th: 32 }), + big(), + ], + layers: [ + { + data: fill(6, 5, (c, r) => { + return 1 + ((c + r) % 2) * 8 + ((c + r * 3) % 8); + }), + }, + ], + }; + const { layers, mode } = shown(scene); + expect(mode).toBe("shader"); + expect(await comparePaths(app, scene, { layers })).toBeGreaterThan(0); + // until a tile of the large one is set: three tilesets in + // use, one of them overlapping + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + scene.layers[0].data[2 * 6 + 2] = 19; + layers[0].setTile(layers[0].getTileById(19, 2, 2), 2, 2); + expect(layers[0].renderMode).toBe("perTile"); + expect(warn.mock.calls.flat().join(" ")).toMatch( + /more than one tileset/, + ); + } finally { + warn.mockRestore(); + } + app.viewport.moveTo(0, 0); + const { frame } = await drawIn(app, layers, "perTile"); + const d = diff(reference(scene, 0, 0, W, H), frame); + expect(d.different, d.first).toBe(0); + }); + + for (const order of ["right-up", "left-down", "left-up"]) { + it(`render order "${order}", tiles larger than the grid`, async (ctx) => { + need(ctx); + // the map walks its rows and columns the way it says: + // with "left-up" the first cell's tile is in front + const scene = { + orientation: "orthogonal", + cols: 4, + rows: 3, + tw: 32, + th: 32, + tilesets: [big()], + layers: [{ data: all(4, 3) }], + extra: { renderorder: order }, + }; + await fallsBack(scene, /render order/); + }); + + it(`render order "${order}", tiles the size of the grid: on the GPU`, async (ctx) => { + need(ctx); + const scene = { + orientation: "orthogonal", + cols: 6, + rows: 5, + tw: 32, + th: 32, + tilesets: [makeTileset({ tw: 32, th: 32 })], + layers: [{ data: all(6, 5) }], + extra: { renderorder: order }, + }; + expect(await comparePaths(app, scene)).toBeGreaterThan(0); + }); + } + }); + + describe("layers past what the GPU holds, and tiles the image does not", () => { + for (const orientation of ["orthogonal", "isometric"]) { + it(`${orientation}: a layer with more columns than the largest texture has pixels`, async (ctx) => { + need(ctx); + // the GPU path keeps a texel per cell + const cols = app.renderer.maxTextureSize + 1; + expect(Number.isFinite(cols)).toBe(true); + const iso = orientation === "isometric"; + const scene = { + orientation, + cols, + rows: 1, + tw: iso ? 64 : 32, + th: 32, + tilesets: [makeTileset({ tw: iso ? 64 : 32, th: 32 })], + layers: [ + { + data: fill(cols, 1, (c) => { + return 1 + (c % 8); + }), + }, + ], + }; + await fallsBack(scene, /largest texture/, [[0, iso ? -100 : 0]]); + }); + } + + it("a tile the tileset's image does not hold is not drawn, either way", async (ctx) => { + need(ctx); + // an image cropped since the map was saved: 4 tiles of the 8 + // the tileset says it has + const scene = { + orientation: "orthogonal", + cols: 6, + rows: 5, + tw: 32, + th: 32, + tilesets: [ + makeTileset({ tw: 32, th: 32, count: 4, extra: { tilecount: 8 } }), + ], + layers: [{ data: all(6, 5) }], + }; + const { layers } = shown(scene); + app.viewport.moveTo(0, 0); + const cpu = await drawIn(app, layers, "perTile"); + const gpu = await drawIn(app, layers, "shader"); + // the tiles the image holds, and none of the others + const held = { + ...scene, + layers: [ + { + data: scene.layers[0].data.map((gid) => { + return gid <= 4 ? gid : 0; + }), + }, + ], + }; + const ref = reference(held, 0, 0, W, H); + expect(drawn(ref)).toBeGreaterThan(0); + expect(diff(ref, cpu.frame).different, "tile by tile").toBe(0); + expect(diff(ref, gpu.frame).different, "on the GPU").toBe(0); + }); + + it("a layer taken out of the world and put back is drawn again", async (ctx) => { + need(ctx); + const scene = { + orientation: "orthogonal", + cols: 6, + rows: 5, + tw: 32, + th: 32, + tilesets: [makeTileset({ tw: 32, th: 32 })], + layers: [{ data: all(6, 5) }], + }; + const layers = show(app, makeMap(scene)); + const layer = layers[0]; + app.world.removeChildNow(layer, true); + expect(() => { + app.world.addChild(layer); + }).not.toThrow(); + app.world.sortNow(true); + expect(layer.renderMode).toBe("shader"); + expect(await comparePaths(app, scene, { layers })).toBeGreaterThan(0); + }); + }); + }); +} diff --git a/packages/melonjs/tests/helpers/tile-layer-staggered-scenarios.js b/packages/melonjs/tests/helpers/tile-layer-staggered-scenarios.js index a78cb54f47..58b15352e1 100644 --- a/packages/melonjs/tests/helpers/tile-layer-staggered-scenarios.js +++ b/packages/melonjs/tests/helpers/tile-layer-staggered-scenarios.js @@ -461,18 +461,12 @@ export function staggeredScenarios(renderer, type) { expect(said).toMatch(/larger than the shader's limit/); }); - it("a grid whose cells stand half a pixel off", (ctx) => { + it("tiles of odd size, which stand a pixel past their cell", (ctx) => { need(ctx); - // a hexagon side of odd length: every other column is half a - // pixel off - const grid = { - orientation: "hexagonal", - tw: 28, - th: 24, - hexsidelength: 11, - }; + // the map is laid on the even grid below: 62 x 30 cells + const grid = { orientation: "staggered", tw: 63, th: 31 }; const [mode, said] = modeOf( - staggeredScene(grid, "x", "odd", makeTileset({ tw: 28, th: 24 })), + staggeredScene(grid, "y", "odd", makeTileset({ tw: 63, th: 31 })), ); expect(mode).toBe("perTile"); expect(said).toMatch(/odd size/); diff --git a/packages/melonjs/tests/tmxlayer-edge-cases.spec.js b/packages/melonjs/tests/tmxlayer-edge-cases.spec.js new file mode 100644 index 0000000000..70835be045 --- /dev/null +++ b/packages/melonjs/tests/tmxlayer-edge-cases.spec.js @@ -0,0 +1,8 @@ +/** + * Tile layers at their edges, on WebGL: see + * `helpers/tile-layer-edge-cases.js`. + */ +import { video } from "../src/index.js"; +import { edgeCases } from "./helpers/tile-layer-edge-cases.js"; + +edgeCases(video.WEBGL, "WebGL"); diff --git a/packages/melonjs/tests/webgpu_tmxlayer_edge_cases.spec.js b/packages/melonjs/tests/webgpu_tmxlayer_edge_cases.spec.js new file mode 100644 index 0000000000..4f5f3b8e28 --- /dev/null +++ b/packages/melonjs/tests/webgpu_tmxlayer_edge_cases.spec.js @@ -0,0 +1,9 @@ +/** + * Tile layers at their edges, on WebGPU: see + * `helpers/tile-layer-edge-cases.js`. Skipped where the browser has no + * WebGPU adapter. + */ +import { video } from "../src/index.js"; +import { edgeCases } from "./helpers/tile-layer-edge-cases.js"; + +edgeCases(video.WEBGPU, "WebGPU"); From 4ada8ff291202f4b2038422baa794ccaa6dc5c60 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 04:40:29 +0000 Subject: [PATCH 09/51] Tile layers: the rest of the adversarial audit (#1897) Staggered and hexagonal maps are laid out with Tiled 1.10's own numbers: what a side leaves of a tile is halved in whole numbers, and the cell a tile stands on is made of those halves, a pixel smaller than a tile of odd size. A map of odd sizes is on whole pixels, so the GPU path takes it; the shader's pixels are measured from as much lower as the cell is shorter. A painter written apart from the tests' reference, from Tiled's source, agrees with both paths. A container holds the tile layers that can draw outside its bounds, and is in view as far as they do: their tiles' reach, a layer's offset, an infinite map's first chunks. (A level loaded into a container gives it the map's size, and the camera asks the container before its layers.) A tile its tileset's image does not hold is left undrawn by `drawTile` too: setting one on a baked layer threw. Tests, from the gaps the audit listed: pictures for the grids of odd sizes, where only the render mode was looked at; flips on hexagons; an infinite map with chunks at odd coordinates; a layer offset and an infinite map in a container; a sliver of 1, 2 and 5 pixels of each orientation at each edge of the view, and a pixel out of sight; `getTile` at the middle of every cell of every kind of map, the layer moved; and two assertions that could not fail made to. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- packages/melonjs/CHANGELOG.md | 3 +- packages/melonjs/src/level/tiled/TMXLayer.js | 58 ++--- .../melonjs/src/level/tiled/TMXTileset.js | 11 +- .../tiled/renderer/TMXHexagonalRenderer.js | 20 +- packages/melonjs/src/renderable/container.js | 27 ++- .../src/video/gpu/tmxlayer_orientation.js | 13 +- .../tests/helpers/tile-layer-compare.js | 21 +- .../tests/helpers/tile-layer-edge-cases.js | 228 +++++++++++++++++- .../helpers/tile-layer-staggered-scenarios.js | 80 +++++- .../melonjs/tests/tmxlayer-offset.spec.js | 78 ++++++ 10 files changed, 455 insertions(+), 84 deletions(-) diff --git a/packages/melonjs/CHANGELOG.md b/packages/melonjs/CHANGELOG.md index 56cb535b29..ac85585d49 100644 --- a/packages/melonjs/CHANGELOG.md +++ b/packages/melonjs/CHANGELOG.md @@ -24,7 +24,8 @@ - Tiled: tiles that reach past their layer's grid (taller or wider than a cell, or moved by a `tileoffset`) are drawn when they are in view and the grid is not; the whole layer was skipped, so the tops of tall tiles vanished once the map scrolled out of view. The layer's bounds are still its grid's - Tiled: a map centred in the view because it is smaller (as `level.load` centres it), and a tile layer in a container that was moved, are drawn whole. The layer read the camera's view as if it stood at the world's origin: on WebGL, WebGPU and a pre-rendered layer the tiles reaching above or left of the grid were cut, and tile by tile a layer far from the origin lost tiles - Tiled, staggered and hexagonal maps: a tile larger than its cell stands on the cell, and a tileset's `tileoffset` moves its tiles, as in Tiled and on every other map. Drawn tile by tile, such a tile hung down from the top of its cell and the offset was ignored, so the map sat lower than its objects (and than a tile redrawn in a baked layer); tiles of a large tileset also went missing along the edges of the view -- Tiled, hexagonal maps: a side whose length leaves an odd number of pixels of a cell is laid out on whole pixels, as Tiled lays it out; every other column or row drifted half a pixel further. A staggered or hexagonal map of odd tile size, pre-rendered, no longer loses a row and a column of pixels +- Tiled, staggered and hexagonal maps of odd sizes are laid out in whole numbers, as Tiled 1.10 lays them out: a tile of odd size stands on a cell a pixel smaller, and a hexagon side that leaves an odd number of pixels of a tile drops the half pixel. Every other column or row drifted half a pixel further, and a pre-rendered layer lost a row and a column of pixels +- Tiled: a level loaded into a container of its own is in view as far as its tile layers draw: their tiles' reach, a layer's offset, and an infinite map's chunks left of and above its origin were cut off once the map's own rectangle left the view - Tiled: a tile layer taken out of its container and added again is drawn; it threw. A tile its tileset's image does not hold (an image cropped since the map was saved) is not drawn; drawing it threw every frame - Tiled, isometric maps drawn tile by tile: tiles narrower than half a cell are no longer left out at the right edge of the view - Tiled, isometric maps drawn tile by tile: tiles of a tileset larger than the map's first one, or moved by a `tileoffset`, went missing along the edges of the view diff --git a/packages/melonjs/src/level/tiled/TMXLayer.js b/packages/melonjs/src/level/tiled/TMXLayer.js index 5fb50e7b7c..c1d62d3396 100644 --- a/packages/melonjs/src/level/tiled/TMXLayer.js +++ b/packages/melonjs/src/level/tiled/TMXLayer.js @@ -276,11 +276,11 @@ export default class TMXLayer extends Renderable { // A tile larger than its cell reaches past it: up and to the right, // as a tile stands on the bottom left of its cell (any way on an // oblique map) - // (a staggered or a hexagonal map is laid on the even size below its - // tiles': a tile of odd size stands a pixel past its cell) - const evenGrid = orientation === "staggered" || orientation === "hexagonal"; - const cellWidth = evenGrid ? this.tilewidth & ~1 : this.tilewidth; - const cellHeight = evenGrid ? this.tileheight & ~1 : this.tileheight; + // (the cell is the map renderer's: on a staggered or a hexagonal map + // it can be a pixel less than the map's tile size) + const grid = map.getRenderer?.(); + const cellWidth = grid?.tilewidth ?? this.tilewidth; + const cellHeight = grid?.tileheight ?? this.tileheight; const overX = Math.max(this.maxTileSize.width - cellWidth, 0); const overY = Math.max(this.maxTileSize.height - cellHeight, 0); const upRight = orientation !== "oblique"; @@ -550,27 +550,14 @@ export default class TMXLayer extends Renderable { // activated again this.animatedTilesets = []; // A container with a size of its own (one a level was loaded into) - // is in view by its bounds, before its children are asked: it is - // told how far past them this layer's tiles reach - const reach = this._reach; - if ( - reach.left > 0 || - reach.top > 0 || - reach.right > 0 || - reach.bottom > 0 - ) { - for (let node = this.ancestor; node; node = node.ancestor) { - const kept = (node._drawReach ??= { - left: 0, - top: 0, - right: 0, - bottom: 0, - }); - kept.left = Math.max(kept.left, reach.left); - kept.top = Math.max(kept.top, reach.top); - kept.right = Math.max(kept.right, reach.right); - kept.bottom = Math.max(kept.bottom, reach.bottom); - } + // is in view by its bounds, before its children are asked: each one + // the layer is in is told that the layer can draw outside them (its + // tiles' reach, its offset, an infinite map's first chunks) + /** @ignore */ + this._toldAncestors = []; + for (let node = this.ancestor; node; node = node.ancestor) { + (node._drawPast ??= new Set()).add(this); + this._toldAncestors.push(node); } if (this.tilesets) { const tileset = this.tilesets.tilesets; @@ -1035,16 +1022,13 @@ export default class TMXLayer extends Renderable { _checkOverlappingShaderEligibility(renderer) { this._shaderTileset = null; const kind = kindOf(this.orientation); - // Half the cells of a grid of odd size stand half a pixel off (on a - // hexagonal map, of a side of odd length). Tile by tile, each tile - // is moved to a whole pixel; the shader has one quad for all of - // them, and would draw those a pixel away. - const map = this.getRenderer(); + // Half the tiles of an isometric grid of odd size stand half a pixel + // off. Tile by tile, each is moved to a whole pixel; the shader has + // one quad for all of them, and would draw those a pixel away. (A + // staggered or a hexagonal map is laid out in whole numbers.) if ( - this.tilewidth % 2 !== 0 || - this.tileheight % 2 !== 0 || - (this.orientation !== "isometric" && - !(Number.isInteger(map.columnwidth) && Number.isInteger(map.rowheight))) + this.orientation === "isometric" && + (this.tilewidth % 2 !== 0 || this.tileheight % 2 !== 0) ) { return { ok: false, reason: `${kind} grid of odd size` }; } @@ -1176,6 +1160,10 @@ export default class TMXLayer extends Renderable { // path's per-layer GID index texture) are cleared from the renderer's // own `reset()` path — tile layers only come and go on game reset. this.animatedTilesets = []; + for (const node of this._toldAncestors ?? []) { + node._drawPast?.delete(this); + } + this._toldAncestors = undefined; // keep canvasRenderer for reuse — dropping the reference would leak // event listeners registered by CanvasRenderer's constructor } diff --git a/packages/melonjs/src/level/tiled/TMXTileset.js b/packages/melonjs/src/level/tiled/TMXTileset.js index 05c390af59..408ae04e76 100644 --- a/packages/melonjs/src/level/tiled/TMXTileset.js +++ b/packages/melonjs/src/level/tiled/TMXTileset.js @@ -753,6 +753,15 @@ export default class TMXTileset { dy += this._renderDyCenter; } + // a tile the tileset's image does not hold: nothing to draw (see + // `drawTileRaw`) + const frame = this.isCollection + ? undefined + : this.atlas[this.getViewTileId(tmxTile.tileId)]; + if (!this.isCollection && frame === undefined) { + return; + } + // check if any transformation is required if (tmxTile.flipped) { renderer.save(); @@ -779,7 +788,7 @@ export default class TMXTileset { ); } else { // use the tileset texture atlas - const offset = this.atlas[this.getViewTileId(tmxTile.tileId)].offset; + const offset = frame.offset; renderer.drawImage( this.image, offset.x, diff --git a/packages/melonjs/src/level/tiled/renderer/TMXHexagonalRenderer.js b/packages/melonjs/src/level/tiled/renderer/TMXHexagonalRenderer.js index 93f84d5abc..7ca646e3b3 100644 --- a/packages/melonjs/src/level/tiled/renderer/TMXHexagonalRenderer.js +++ b/packages/melonjs/src/level/tiled/renderer/TMXHexagonalRenderer.js @@ -29,7 +29,7 @@ export default class TMXHexagonalRenderer extends TMXRenderer { * @param {TMXTileMap} map - the TMX map */ constructor(map) { - super(map.cols, map.rows, map.tilewidth & ~1, map.tileheight & ~1); + super(map.cols, map.rows, map.tilewidth, map.tileheight); this.hexsidelength = map.hexsidelength || 0; this.staggerX = map.staggeraxis === "x"; @@ -46,16 +46,22 @@ export default class TMXHexagonalRenderer extends TMXRenderer { } } - // in whole numbers, as Tiled's own (libtiled's `RenderParams`): a - // side of odd length leaves an odd number of pixels to halve, and - // the half pixel is dropped, not kept: columns and rows stay on - // whole pixels, where Tiled has them - this.sideoffsetx = Math.trunc((this.tilewidth - this.sidelengthx) / 2); - this.sideoffsety = Math.trunc((this.tileheight - this.sidelengthy) / 2); + // In whole numbers, as Tiled's own (libtiled's hexagonal + // `RenderParams`): what a side leaves of a tile is halved, and when + // that is an odd number of pixels the half pixel is dropped. + // Columns and rows stay on whole pixels, where Tiled has them + this.sideoffsetx = Math.trunc((map.tilewidth - this.sidelengthx) / 2); + this.sideoffsety = Math.trunc((map.tileheight - this.sidelengthy) / 2); this.columnwidth = this.sideoffsetx + this.sidelengthx; this.rowheight = this.sideoffsety + this.sidelengthy; + // and the cell a tile stands on is made of those: the map's tile + // size, less the pixel dropped (63 x 31 tiles of a staggered map + // stand on 62 x 30 cells) + this.tilewidth = this.columnwidth + this.sideoffsetx; + this.tileheight = this.rowheight + this.sideoffsety; + this.centers = [ new Vector2d(), new Vector2d(), diff --git a/packages/melonjs/src/renderable/container.js b/packages/melonjs/src/renderable/container.js index ad02df323e..c313297482 100644 --- a/packages/melonjs/src/renderable/container.js +++ b/packages/melonjs/src/renderable/container.js @@ -1132,18 +1132,20 @@ export default class Container extends Renderable { } /** - * The area this container draws in, when something in it draws past its - * own bounds and has said so (a tile layer whose tiles stand above its - * grid, see `TMXLayer#getDrawBounds`): the container's bounds, grown by - * as much. A camera has the container in view by this area, as it would - * the layer (see `Camera2d#isVisible`). + * The area this container draws in, when something in it draws outside + * the container's own bounds and has said so: a tile layer does (see + * `TMXLayer#getDrawBounds`), whose tiles stand above its grid, which an + * offset can move, and which on an infinite map starts left of and above + * the map's origin. A container with a size of its own (one a level was + * loaded into) is in view by this area, as the layer would be (see + * `Camera2d#isVisible`). * @returns {Bounds|undefined} that area, or undefined when it is the * container's bounds (or the container has no size of its own) * @ignore */ getDrawBounds() { - const reach = this._drawReach; - if (reach === undefined) { + const layers = this._drawPast; + if (layers === undefined || layers.size === 0) { return undefined; } const bounds = this.getBounds(); @@ -1153,11 +1155,14 @@ export default class Container extends Renderable { /** @ignore */ this._drawBounds ??= boundsPool.get(); this._drawBounds.setMinMax( - bounds.left - reach.left, - bounds.top - reach.top, - bounds.right + reach.right, - bounds.bottom + reach.bottom, + bounds.left, + bounds.top, + bounds.right, + bounds.bottom, ); + for (const layer of layers) { + this._drawBounds.addBounds(layer.getDrawBounds()); + } return this._drawBounds; } diff --git a/packages/melonjs/src/video/gpu/tmxlayer_orientation.js b/packages/melonjs/src/video/gpu/tmxlayer_orientation.js index c3fdf54e96..b3fe304f8a 100644 --- a/packages/melonjs/src/video/gpu/tmxlayer_orientation.js +++ b/packages/melonjs/src/video/gpu/tmxlayer_orientation.js @@ -226,10 +226,17 @@ export function staggeredRegion(layer, rect, tileset, out) { // bottom of the last line's boxes const left = offsetX; const right = lastBox * columnWidth + tileset.tilewidth + offsetX; - const top = layer.tileheight - tileset.tileheight + offsetY; - const bottom = (lines - 1) * rowHeight + layer.tileheight + offsetY; + // (a tile stands on the cell the map lays out, which can be a pixel + // less than the map's tile size: see `TMXHexagonalRenderer`) + const top = map.tileheight - tileset.tileheight + offsetY; + const bottom = (lines - 1) * rowHeight + map.tileheight + offsetY; - if (!viewIn(rect, left, top, right, bottom, offsetX, offsetY, out)) { + // the shader stands a tile on `uCellSize`, the map's tile size: where + // the cell is shorter, its pixels are measured from as much lower + const shorter = layer.tileheight - map.tileheight; + if ( + !viewIn(rect, left, top, right, bottom, offsetX, offsetY - shorter, out) + ) { return false; } // how many cells' images reach a pixel: as many in a line as the image diff --git a/packages/melonjs/tests/helpers/tile-layer-compare.js b/packages/melonjs/tests/helpers/tile-layer-compare.js index 5f925c086b..e45feb4236 100644 --- a/packages/melonjs/tests/helpers/tile-layer-compare.js +++ b/packages/melonjs/tests/helpers/tile-layer-compare.js @@ -311,13 +311,16 @@ export function reference(scene, viewX, viewY, width, height) { const side = orientation === "hexagonal" ? hexsidelength : 0; const sideX = staggerX ? side : 0; const sideY = staggerX ? 0 : side; - // Tiled's own numbers (libtiled's hexagonal `RenderParams`), all - // whole: the grid is the even size below the tiles', and half - // of what a side leaves of a cell is rounded down - const cw = tw & ~1; - const ch = th & ~1; - const columnWidth = Math.trunc((cw - sideX) / 2) + sideX; - const rowHeight = Math.trunc((ch - sideY) / 2) + sideY; + // Tiled's own numbers (libtiled's hexagonal `RenderParams`, as + // of Tiled 1.10), all whole: half of what a side leaves of a + // tile, rounded down; a column and a row; and the cell a tile + // stands on, the tile's size less the pixel dropped + const offsetX = Math.trunc((tw - sideX) / 2); + const offsetY = Math.trunc((th - sideY) / 2); + const columnWidth = offsetX + sideX; + const rowHeight = offsetY + sideY; + const cw = columnWidth + offsetX; + const ch = rowHeight + offsetY; const place = ({ col, row }) => { // `& 1` and not `% 2`: an infinite map has negative cells return staggerX @@ -593,6 +596,10 @@ export async function comparePaths(app, scene, options = {}) { } const c = diff(ref, cpu.frame, tolerance); expect(c.different, `${at}, CPU path: ${c.first}`).toBe(0); + // and where something is to be seen, the layer was asked for it + if (drawn(ref) > 0) { + expect(cpu.cpuDraws, `${at}, CPU draws`).toBeGreaterThan(0); + } const g = diff(ref, gpu.frame, tolerance); expect(g.different, `${at}, GPU path: ${g.first}`).toBe(0); } diff --git a/packages/melonjs/tests/helpers/tile-layer-edge-cases.js b/packages/melonjs/tests/helpers/tile-layer-edge-cases.js index 1990d88a1d..15bdf446e6 100644 --- a/packages/melonjs/tests/helpers/tile-layer-edge-cases.js +++ b/packages/melonjs/tests/helpers/tile-layer-edge-cases.js @@ -123,6 +123,95 @@ export function edgeCases(renderer, type) { } }); + for (const [orientation, tw, th, extra] of [ + ["orthogonal", 32, 32, {}], + ["isometric", 64, 32, {}], + ["staggered", 64, 32, { staggeraxis: "y", staggerindex: "odd" }], + [ + "hexagonal", + 28, + 24, + { staggeraxis: "x", staggerindex: "even", hexsidelength: 12 }, + ], + ]) { + it(`${orientation}: a sliver of the map, a pixel or a few, at each edge of the view`, async (ctx) => { + need(ctx); + // tiles larger than a cell, moved by a tileoffset where + // the GPU takes one: how far the map reaches is measured + // on the reference itself + const scene = { + orientation, + cols: 5, + rows: 5, + tw, + th, + tilesets: [ + makeTileset({ + tw: tw + 10, + th: th * 2, + // (an orthogonal tileset with an offset is left + // to the CPU renderer) + extra: + orientation === "orthogonal" + ? {} + : { tileoffset: { x: -7, y: 5 } }, + }), + ], + layers: [{ data: all(5, 5) }], + extra, + }; + const wide = reference(scene, -400, -400, 1200, 1000); + let left = Infinity; + let top = Infinity; + let right = -Infinity; + let bottom = -Infinity; + for (let y = 0; y < wide.height; y++) { + for (let x = 0; x < wide.width; x++) { + const i = (y * wide.width + x) * 4; + if ( + wide.data[i] !== 16 || + wide.data[i + 1] !== 24 || + wide.data[i + 2] !== 48 + ) { + left = Math.min(left, x - 400); + right = Math.max(right, x - 400 + 1); + top = Math.min(top, y - 400); + bottom = Math.max(bottom, y - 400 + 1); + } + } + } + expect(right - left).toBeGreaterThan(100); + const middleX = Math.round((left + right - W) / 2); + const middleY = Math.round((top + bottom - H) / 2); + const views = []; + for (const k of [1, 2, 5]) { + // the map's left edge at the view's right, and so on + views.push([left + k - W, middleY]); + views.push([right - k, middleY]); + views.push([middleX, top + k - H]); + views.push([middleX, bottom - k]); + } + const layers = show(app, makeMap(scene)); + expect(layers[0].renderMode).toBe("shader"); + for (const view of views) { + expect( + await comparePaths(app, scene, { views: [view], layers }), + `view (${view})`, + ).toBeGreaterThan(0); + } + // and a pixel out of sight: nothing, either way + const out = [ + [left - W, middleY], + [right, middleY], + [middleX, top - H], + [middleX, bottom], + ]; + expect(await comparePaths(app, scene, { views: out, layers })).toBe( + 0, + ); + }); + } + it("a layer in a container with a size: the tops of tall tiles, the grid out of view", async (ctx) => { need(ctx); // a level loaded into a container gives it the map's size: @@ -166,6 +255,83 @@ export function edgeCases(renderer, type) { } }); + /** a scene put in a container of its own, as a level loaded into one */ + const boxed = (scene) => { + app.world.reset(); + app.world.pos.set(0, 0, app.world.pos.z); + app.renderer.reset?.(); + app.renderer.backgroundColor.setColor(16, 24, 48); + const map = makeMap(scene); + const box = new Container(); + app.world.addChild(box); + map.addTo(box, true, false); + app.world.sortNow(true); + app.viewport.setBounds(-100000, -100000, 200000, 200000); + return map.getLayers(); + }; + + it("a layer offset in Tiled, in a container with a size: drawn where it is, the map's rectangle out of view", async (ctx) => { + need(ctx); + // the container has the map's size: 160 wide, and the layer + // is 200 to its right + const scene = { + orientation: "orthogonal", + cols: 5, + rows: 4, + tw: 32, + th: 32, + tilesets: [makeTileset({ tw: 32, th: 32 })], + layers: [{ data: all(5, 4), offsetx: 200, offsety: 0 }], + }; + const view = [170, -40]; + const ref = reference(scene, ...view, W, H); + expect(drawn(ref)).toBeGreaterThan(0); + const layers = boxed(scene); + app.viewport.moveTo(...view); + for (const mode of ["perTile", "shader"]) { + const { frame } = await drawIn(app, layers, mode); + const d = diff(ref, frame); + expect(d.different, `${mode}: ${d.first}`).toBe(0); + } + }); + + it("an infinite map in a container: the tiles left of and above its origin", async (ctx) => { + need(ctx); + const chunk = (x, y) => { + return { x, y, width: 4, height: 4, data: all(4, 4) }; + }; + const scene = { + orientation: "orthogonal", + cols: 4, + rows: 4, + tw: 32, + th: 32, + tilesets: [makeTileset({ tw: 32, th: 32 })], + layers: [ + { + startx: -4, + starty: -8, + width: 8, + height: 12, + data: undefined, + chunks: [chunk(-3, -5), chunk(0, 0)], + }, + ], + extra: { infinite: true }, + }; + // left of and above the map's own rectangle + const view = [-W - 4, -H - 4]; + const ref = reference(scene, ...view, W, H); + expect(drawn(ref)).toBeGreaterThan(0); + const layers = boxed(scene); + app.viewport.moveTo(...view); + for (const mode of ["perTile", "shader"]) { + const { frame } = await drawIn(app, layers, mode); + const d = diff(ref, frame); + expect(d.different, `${mode}: ${d.first}`).toBe(0); + } + }); + for (const mode of ["perTile", "shader", "prerender"]) { it(`a zoomed camera with an offset, over a moved world, drawn "${mode}"`, async (ctx) => { need(ctx); @@ -217,7 +383,7 @@ export function edgeCases(renderer, type) { }); describe("grids of odd sizes, laid out as Tiled lays them out", () => { - it("a staggered map of odd tile size: on the even grid below, tile by tile and baked", async (ctx) => { + it("a staggered map of odd tile size: on cells a pixel smaller, every way it is drawn", async (ctx) => { need(ctx); // 63 x 31 tiles stand on 62 x 30 cells: one pixel above and // one to the right of each @@ -231,15 +397,13 @@ export function edgeCases(renderer, type) { layers: [{ data: all(4, 4) }], extra: { staggeraxis: "y", staggerindex: "odd" }, }; - await fallsBack(scene, /odd size/, [ + const views = [ [-20, -20], [40, 10], - ]); + ]; + expect(await comparePaths(app, scene, { views })).toBeGreaterThan(0); const baked = show(app, makeMap(scene), "prerender"); - for (const [x, y] of [ - [-20, -20], - [40, 10], - ]) { + for (const [x, y] of views) { app.viewport.moveTo(x, y); const { frame } = await drawIn(app, baked, "prerender"); const d = diff(reference(scene, x, y, W, H), frame); @@ -249,7 +413,10 @@ export function edgeCases(renderer, type) { for (const [axis, tw, th, side] of [ ["x", 28, 24, 11], + // on this axis the cell is a pixel shorter than the tile ["y", 28, 24, 11], + // an odd height: 7 a side, rows 18 apart + ["y", 28, 25, 11], ["x", 30, 24, 7], // longer than the tile: the half left of a cell is negative ["x", 28, 24, 33], @@ -278,6 +445,14 @@ export function edgeCases(renderer, type) { [35, 12], ]; expect(await comparePaths(app, scene, { views })).toBeGreaterThan(0); + // and baked: the canvas holds every tile, to its last pixel + const baked = show(app, makeMap(scene), "prerender"); + for (const [x, y] of views) { + app.viewport.moveTo(x, y); + const { frame } = await drawIn(app, baked, "prerender"); + const d = diff(reference(scene, x, y, W, H), frame); + expect(d.different, `baked: ${d.first}`).toBe(0); + } }); } }); @@ -475,6 +650,45 @@ export function edgeCases(renderer, type) { expect(diff(ref, gpu.frame).different, "on the GPU").toBe(0); }); + it("a tile the image does not hold, set on a baked layer: left undrawn", async (ctx) => { + need(ctx); + const scene = { + orientation: "orthogonal", + cols: 6, + rows: 5, + tw: 32, + th: 32, + tilesets: [ + makeTileset({ tw: 32, th: 32, count: 4, extra: { tilecount: 8 } }), + ], + layers: [ + { + data: fill(6, 5, (c, r) => { + return 1 + ((c + r) % 4); + }), + }, + ], + }; + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + const layers = show(app, makeMap(scene), "prerender"); + const layer = layers[0]; + // one the image holds, and one it does not + scene.layers[0].data[1 * 6 + 1] = 3; + layer.setTile(layer.getTileById(3, 1, 1), 1, 1); + scene.layers[0].data[2 * 6 + 2] = 0; + expect(() => { + layer.setTile(layer.getTileById(7, 2, 2), 2, 2); + }).not.toThrow(); + app.viewport.moveTo(0, 0); + const { frame } = await drawIn(app, layers, "prerender"); + const d = diff(reference(scene, 0, 0, W, H), frame); + expect(d.different, d.first).toBe(0); + } finally { + warn.mockRestore(); + } + }); + it("a layer taken out of the world and put back is drawn again", async (ctx) => { need(ctx); const scene = { diff --git a/packages/melonjs/tests/helpers/tile-layer-staggered-scenarios.js b/packages/melonjs/tests/helpers/tile-layer-staggered-scenarios.js index 58b15352e1..18d3d12399 100644 --- a/packages/melonjs/tests/helpers/tile-layer-staggered-scenarios.js +++ b/packages/melonjs/tests/helpers/tile-layer-staggered-scenarios.js @@ -221,6 +221,67 @@ export function staggeredScenarios(renderer, type) { } }); + it("tiles of odd size: on the cell Tiled lays out, a pixel smaller", async (ctx) => { + need(ctx); + // 63 x 31 tiles of a staggered map stand on 62 x 30 cells; + // a hexagon side of 11 on 28 x 25 leaves 7 a side, rows 18 + // apart + for (const [grid, tw, th] of [ + [{ orientation: "staggered", tw: 63, th: 31 }, 63, 31], + [{ orientation: "staggered", tw: 64, th: 33 }, 64, 66], + [ + { orientation: "hexagonal", tw: 28, th: 25, hexsidelength: 11 }, + 28, + 25, + ], + [ + { orientation: "hexagonal", tw: 27, th: 24, hexsidelength: 12 }, + 27, + 40, + ], + ]) { + for (const axis of ["y", "x"]) { + expect( + await same( + staggeredScene(grid, axis, "odd", makeTileset({ tw, th })), + ), + `${grid.orientation} ${grid.tw} x ${grid.th}, axis ${axis}`, + ).toBeGreaterThan(0); + } + } + }); + + it("tiles flipped across and down, on hexagons", async (ctx) => { + need(ctx); + // (a hexagonal map's third flag is a turn of 60 degrees in + // Tiled, which the engine does not draw: left out here) + const flips = [0, FLIP_H, FLIP_V, FLIP_H + FLIP_V]; + for (const axis of ["y", "x"]) { + const scene = staggeredScene( + HEXAGONAL, + axis, + "even", + makeTileset({ + tw: 28, + th: 40, + opaque: (x, y) => { + return x + y > 12; + }, + }), + { + layers: [ + { + data: fill(COLS, ROWS, (c, r) => { + return 1 + ((c + r) % 8) + flips[(c * 3 + r) % 4]; + }), + }, + ], + }, + ); + expect(await same(scene), `axis ${axis}`).toBeGreaterThan(0); + } + }); + it("tiles flipped, every way", async (ctx) => { need(ctx); const flips = [ @@ -354,6 +415,10 @@ export function staggeredScenarios(renderer, type) { chunk(0, -4), chunk(4, 0), chunk(0, 0), + // odd coordinates: the lines that are shifted + // are the map's, not the chunk's + chunk(-3, 5), + chunk(5, -9), ], }, ], @@ -461,17 +526,6 @@ export function staggeredScenarios(renderer, type) { expect(said).toMatch(/larger than the shader's limit/); }); - it("tiles of odd size, which stand a pixel past their cell", (ctx) => { - need(ctx); - // the map is laid on the even grid below: 62 x 30 cells - const grid = { orientation: "staggered", tw: 63, th: 31 }; - const [mode, said] = modeOf( - staggeredScene(grid, "y", "odd", makeTileset({ tw: 63, th: 31 })), - ); - expect(mode).toBe("perTile"); - expect(said).toMatch(/odd size/); - }); - it("a tile of another tileset set while the game runs", (ctx) => { need(ctx); const scene = staggeredScene(HEXAGONAL, "y", "odd", blocks(HEXAGONAL), { @@ -515,6 +569,7 @@ export function staggeredScenarios(renderer, type) { })) { const scene = build(); const layers = show(app, makeMap(scene), "prerender"); + let total = 0; for (const [x, y] of STAGGERED_VIEWS.slice(0, 4)) { app.viewport.moveTo(x, y); const { frame } = await drawIn(app, layers, "prerender"); @@ -522,8 +577,9 @@ export function staggeredScenarios(renderer, type) { expect(d.different, `${label}, view (${x}, ${y}): ${d.first}`).toBe( 0, ); - expect(drawn(frame)).toBeGreaterThanOrEqual(0); + total += drawn(frame); } + expect(total, label).toBeGreaterThan(0); } }); }); diff --git a/packages/melonjs/tests/tmxlayer-offset.spec.js b/packages/melonjs/tests/tmxlayer-offset.spec.js index 82e6e1c737..aba505bccf 100644 --- a/packages/melonjs/tests/tmxlayer-offset.spec.js +++ b/packages/melonjs/tests/tmxlayer-offset.spec.js @@ -227,6 +227,84 @@ describe("where a tile layer is (Canvas renderer)", () => { }); }); + describe("getTile, on every kind of map, with the layer moved", () => { + const grids = [ + ["orthogonal", 32, 32, {}], + ["isometric", 64, 32, {}], + ["staggered", 64, 32, { staggeraxis: "y", staggerindex: "odd" }], + ["staggered", 64, 32, { staggeraxis: "x", staggerindex: "even" }], + [ + "hexagonal", + 28, + 24, + { staggeraxis: "y", staggerindex: "odd", hexsidelength: 12 }, + ], + [ + "hexagonal", + 28, + 24, + { staggeraxis: "x", staggerindex: "even", hexsidelength: 11 }, + ], + ]; + for (const [orientation, tw, th, extra] of grids) { + it(`${orientation}${extra.staggeraxis ? `, axis ${extra.staggeraxis}` : ""}: the middle of every cell is that cell`, () => { + const cols = 7; + const rows = 6; + const scene = { + orientation, + cols, + rows, + tw, + th, + tilesets: [makeTileset({ tw, th })], + layers: [{ data: filled(cols, rows), offsetx: 37, offsety: -21 }], + extra, + }; + const [layer] = show(app, makeMap(scene)); + const map = layer.getRenderer(); + let found = 0; + for (const [dx, dy] of [ + [0, 0], + [55, -140], + ]) { + layer.pos.x += dx; + layer.pos.y += dy; + const movedX = 37 + dx; + const movedY = -21 + dy; + for (let row = 0; row < rows; row++) { + for (let col = 0; col < cols; col++) { + // the middle of the cell, where the map's renderer + // puts it, moved as the layer is + const at = + orientation === "isometric" + ? map.tileToPixelCoords(col + 0.5, row + 0.5) + : map.tileToPixelCoords(col, row); + if (orientation !== "isometric") { + at.x += map.tilewidth / 2; + at.y += map.tileheight / 2; + } + const tile = layer.getTile(at.x + movedX, at.y + movedY); + const gid = scene.layers[0].data[row * cols + col]; + if (gid === 0) { + expect(tile, `empty cell (${col}, ${row})`).toBeNull(); + } else { + expect( + [tile?.col, tile?.row], + `cell (${col}, ${row}), layer moved by (${movedX}, ${movedY})`, + ).toEqual([col, row]); + expect(tile.tileId).toBe(gid); + found++; + } + } + } + } + expect(found).toBeGreaterThan(40); + // and far from the layer, nothing + expect(layer.getTile(-5000, -5000)).toBeNull(); + }); + } + }); + describe("moved in the game, by its pos", () => { for (const make of [orthogonal, isometric]) { it(`${make.name}: drawn, and found by getTile, where it was moved to`, async () => { From 11e7899c81597f3681f04905243418fc297492d3 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 05:07:03 +0000 Subject: [PATCH 10/51] Changelog: 20.17.0 rewritten for readers GPU rendering of isometric, staggered and hexagonal maps under Added; its gain in percent under Performance, with the orthogonal figures for reference; the opacity change under Fixed; the tile layer fixes merged into six entries, those a game cannot see left out. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- packages/melonjs/CHANGELOG.md | 35 +++++++++++------------------------ 1 file changed, 11 insertions(+), 24 deletions(-) diff --git a/packages/melonjs/CHANGELOG.md b/packages/melonjs/CHANGELOG.md index ac85585d49..eb1795ce54 100644 --- a/packages/melonjs/CHANGELOG.md +++ b/packages/melonjs/CHANGELOG.md @@ -4,32 +4,19 @@ ### Added - Transitions: a mask transition can be shaped like an image or a `Sprite`, close on the player with `center`, and fill the shape with `invert`, on `state.transition`, `MaskEffect` and `Trigger` ([#1399](https://github.com/melonjs/melonJS/issues/1399)) - -### Changed -- Tiled: an isometric, staggered or hexagonal tile layer with an `opacity` below 1 fades as one flat picture on WebGL and WebGPU, where each tile was faded over the ones behind it and showed through the one in front. Set the layer's `renderMode` to `"perTile"` for the look it had +- Tiled: isometric maps are rendered by the GPU on WebGL and WebGPU, as orthogonal ones are, and so are staggered and hexagonal maps. Nothing to enable: a tile layer whose tiles come from one tileset takes it by itself, and any other is drawn as before, the console saying why ([#1897](https://github.com/melonjs/melonJS/issues/1897)) ### Performance -- Tiled: isometric, staggered and hexagonal tile layers are drawn by the GPU on WebGL and WebGPU, as orthogonal ones are: one quad for the layer, its tiles found by the fragment shader, in place of a quad per tile in view found and placed in JavaScript every frame. On a 100 × 100 isometric map with about 4000 tiles in view, drawing the layer takes under **0.1 ms** of main-thread time a frame, down from about **2 ms**, and no longer grows with the number of tiles shown. A layer takes this path by itself when all its tiles come from one tileset, up to 4 cells wide and 8 tall (a `tileoffset`, flipped and animated tiles, and `setTile` are all fine); any other is drawn as before, and the console says why ([#1897](https://github.com/melonjs/melonJS/issues/1897)) -- Tiled: a reminder that orthogonal tile layers have been drawn this way since 19.4, with the same gain (about 1.9 ms down to under 0.1 ms for 3600 tiles in view). A layer that is not says why in the console when it is activated: most often a tileset with a `tileoffset`, a collection of images, or the Canvas renderer. - -### Fixed -- Tiled, GPU tile layers: the soft edge of a tile larger than the grid shows the tile behind it; it was drawn over the background instead, a thin outline round such tiles -- Tiled, GPU tile layers: tiles larger than the grid are drawn whole above the map's first row and right of its last column, where they were cut off -- Tiled, GPU tile layers: a tileset with a `margin` whose image stops at its last tiles, with no margin after them, draws the right tiles; they were counted a column or a row short -- Tiled, GPU tile layers: an orthogonal layer whose tiles are larger than the grid and come from more than one tileset, or whose map has a render order other than "right-down", is drawn tile by tile; on the GPU such tiles lay over each other in the wrong order -- Tiled, GPU tile layers: a layer with more columns or rows than the largest texture the GPU takes is drawn tile by tile; it drew nothing -- Tiled, GPU tile layers: a layer with a tile that is not square, flipped diagonally, is drawn tile by tile; the shader drew such a tile wrong -- Tiled, GPU tile layers: the shader runs at full precision whatever `highPrecisionShader` says; at a lower one a phone could misplace the tiles of a large map -- Tiled: a tile layer follows its offset in Tiled (`offsetx`, `offsety`), and its own `pos` when the game moves it: its tiles are drawn there and `getTile()` finds them there, on every renderer and map orientation. Both were ignored, and the layer drawn at the map's origin; only image layers followed their offset. A map whose tile layers have an offset now looks as it does in Tiled -- Tiled: tiles that reach past their layer's grid (taller or wider than a cell, or moved by a `tileoffset`) are drawn when they are in view and the grid is not; the whole layer was skipped, so the tops of tall tiles vanished once the map scrolled out of view. The layer's bounds are still its grid's -- Tiled: a map centred in the view because it is smaller (as `level.load` centres it), and a tile layer in a container that was moved, are drawn whole. The layer read the camera's view as if it stood at the world's origin: on WebGL, WebGPU and a pre-rendered layer the tiles reaching above or left of the grid were cut, and tile by tile a layer far from the origin lost tiles -- Tiled, staggered and hexagonal maps: a tile larger than its cell stands on the cell, and a tileset's `tileoffset` moves its tiles, as in Tiled and on every other map. Drawn tile by tile, such a tile hung down from the top of its cell and the offset was ignored, so the map sat lower than its objects (and than a tile redrawn in a baked layer); tiles of a large tileset also went missing along the edges of the view -- Tiled, staggered and hexagonal maps of odd sizes are laid out in whole numbers, as Tiled 1.10 lays them out: a tile of odd size stands on a cell a pixel smaller, and a hexagon side that leaves an odd number of pixels of a tile drops the half pixel. Every other column or row drifted half a pixel further, and a pre-rendered layer lost a row and a column of pixels -- Tiled: a level loaded into a container of its own is in view as far as its tile layers draw: their tiles' reach, a layer's offset, and an infinite map's chunks left of and above its origin were cut off once the map's own rectangle left the view -- Tiled: a tile layer taken out of its container and added again is drawn; it threw. A tile its tileset's image does not hold (an image cropped since the map was saved) is not drawn; drawing it threw every frame -- Tiled, isometric maps drawn tile by tile: tiles narrower than half a cell are no longer left out at the right edge of the view -- Tiled, isometric maps drawn tile by tile: tiles of a tileset larger than the map's first one, or moved by a `tileoffset`, went missing along the edges of the view -- Tiled, orthogonal maps drawn tile by tile: tiles more than two cells tall went missing along the bottom of the view +- Tiled: thanks to the GPU renderer, drawing an isometric tile layer takes about **90%** less of the main thread's time with 1200 tiles in view (0.68 to 0.07 ms a frame) and about **98%** less with 4000 (2.0 to 0.04 ms), and no longer grows with the number of tiles shown. Staggered and hexagonal maps gain the same +- Tiled: for reference, orthogonal tile layers, on the GPU since 19.4, measure about **85%** less with 1000 tiles in view (0.62 to 0.09 ms) and about **97%** less with 3600 (1.9 to 0.06 ms) + +### Fixed +- Tiled: a tile layer follows its offset in Tiled, and its own `pos` when the game moves it: its tiles are drawn there, and `getTile()` finds them there. Both were ignored; a map whose tile layers have an offset now looks as it does in Tiled +- Tiled: tiles larger than a cell are drawn wherever they are in view. They were cut off or left out along the edges of the view, above and right of the map, on a map centred in the screen, and once the map itself had scrolled out of view +- Tiled: staggered and hexagonal maps are drawn where Tiled draws them: a tile larger than its cell stands on it, a tileset's `tileoffset` moves its tiles, and maps of odd sizes stay on whole pixels +- Tiled: orthogonal layers drawn by the GPU show the soft edges of large tiles over the tiles behind them, lay large tiles over each other in the map's order, and read a tileset with a `margin` right +- Tiled: an isometric, staggered or hexagonal layer with an `opacity` below 1 fades as one picture on WebGL and WebGPU; each tile showed through the one in front of it +- Tiled: a tile layer removed from its container and added again, and a tile missing from its tileset's image, no longer throw - `NineSliceSprite` blinks with `flicker()`, as a `Sprite` does; it ignored it - glTF: a model compressed with Draco or meshopt, which the loader cannot decode, says so in the console, naming the extension, instead of failing on an accessor error that did not mention it From 33c1d20f1f9eca13376c9873e37186d51430e922 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 05:25:14 +0000 Subject: [PATCH 11/51] README: GPU tile rendering covers isometric, staggered and hexagonal maps The Tiled feature line said orthogonal maps only, and that the others fell back to the CPU renderer. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5734408cc2..07a8f3da58 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ melonJS is designed so you can **focus on making games, not on graphics plumbing - **Complete engine, minimal footprint** — Physics, tilemaps, audio, input, cameras, tweens, particles, UI — a full game stack in a single tree-shakeable ES module. No dependency sprawl, no library stitching. -- **Scenes, loaded in one call** — `level.load(name)` brings an authored scene straight into your world. [Tiled](https://www.mapeditor.org) is a first-class citizen for **2D** — orthogonal, isometric, hexagonal & staggered maps, animated tilesets, collision shapes, object properties, compressed formats, with GPU-accelerated tile rendering on the GPU backends — and **glTF / GLB** is the equivalent for **3D scenes**: author in Blender (or any DCC tool), export a `.glb`, and the whole scene — meshes, materials, cameras, lights, and node animation — loads under a `Camera3d`, no per-mesh wiring. Animated models play back through the same animation API as a 2D `Sprite`. +- **Scenes, loaded in one call** — `level.load(name)` brings an authored scene straight into your world. [Tiled](https://www.mapeditor.org) is a first-class citizen for **2D** — orthogonal, isometric, hexagonal & staggered maps, all four rendered on the GPU (a whole tile layer in a single draw, on WebGPU and WebGL 2), animated tilesets, collision shapes, object properties, compressed formats — and **glTF / GLB** is the equivalent for **3D scenes**: author in Blender (or any DCC tool), export a `.glb`, and the whole scene — meshes, materials, cameras, lights, and node animation — loads under a `Camera3d`, no per-mesh wiring. Animated models play back through the same animation API as a 2D `Sprite`. - **Batteries included, hackable by design** — Get started in minutes with minimal setup. When you need to go deeper: modern class-based architecture, a plugin system for engine extensions, and a clean architecture that's easy to extend without fighting the framework. @@ -117,7 +117,7 @@ UI Scenes - Load a scene in one call with `level.load(name)` — 2D Tiled maps and 3D glTF scenes alike, auto-registered on preload - [Tiled](https://www.mapeditor.org) map format [up to 1.12](https://doc.mapeditor.org/en/stable/reference/tmx-changelog/) built-in support for easy level design - - **GPU-accelerated tile rendering** for orthogonal maps on the GPU backends (WebGL 2 and WebGPU) — each layer draws as a single quad with no per-tile loop, ~5–8× faster than the legacy CPU renderer on dense maps. Honors animated tiles, flip bits, per-layer opacity/tint/blend, and oversized bottom-aligned tiles; falls back transparently to the CPU renderer on isometric/staggered/hexagonal layers or under the Canvas renderer + - **GPU-accelerated tile rendering** for orthogonal, isometric, staggered and hexagonal maps on the GPU backends (WebGL 2 and WebGPU) — each layer draws as a single quad with no per-tile loop, so its cost on the main thread stays flat however many tiles are in view: 85% to 98% less than the CPU renderer on a dense map. Honors animated and flipped tiles, per-layer opacity and tint, tiles larger than the grid and tileset offsets, and `setTile` at run time; falls back transparently to the CPU renderer for a layer it cannot draw (the console says why), on oblique maps and under the Canvas renderer - Uncompressed and [compressed](https://github.com/melonjs/melonJS/tree/master/packages/tiled-inflate-plugin) Plain, Base64, CSV and JSON encoded XML tilemap loading - Orthogonal, Isometric, Hexagonal (both normal and staggered) and Oblique maps - Multiple layers with per-layer alpha, tinting and blend modes (multiple background/foreground, collision and Image layers) From a4647d05e72cd43394c25322a2e4bad99b0cf207 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 07:16:24 +0000 Subject: [PATCH 12/51] Test: a sprite mask transition set for one change, then set back at once MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit state.transition("mask", …, sprite), state.change(), then the usual transition set back on the next line: that change hides and reveals with the sprite's silhouette, and the next change is the usual fade. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- .../tests/mask-transition-sprite.spec.js | 90 +++++++++++++++++++ 1 file changed, 90 insertions(+) diff --git a/packages/melonjs/tests/mask-transition-sprite.spec.js b/packages/melonjs/tests/mask-transition-sprite.spec.js index f66506fee8..d4e6b564ef 100644 --- a/packages/melonjs/tests/mask-transition-sprite.spec.js +++ b/packages/melonjs/tests/mask-transition-sprite.spec.js @@ -2,6 +2,7 @@ import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; import { Application, boot, + FadeEffect, MaskEffect, Sprite, Stage, @@ -15,6 +16,9 @@ import { readPixel } from "./helpers/pixels.js"; * hide closes on the player with the player's own silhouette, and the reveal * opens from the same place with the same silhouette, though the state * change has destroyed the player in between. + * + * And the way to use one for a single change: set it, call `state.change()`, + * set the usual transition back on the next line. */ const DURATION = 60; @@ -59,6 +63,13 @@ const leftHalf = () => { return canvas; }; +/** what is on the camera now, as `Class:direction` */ +const effectsOn = (app) => { + return app.viewport.cameraEffects.map((fx) => { + return `${fx.constructor.name}:${fx.direction}`; + }); +}; + describe("a mask transition shaped like, and closing on, a sprite", () => { let app; beforeAll(async () => { @@ -179,4 +190,83 @@ describe("a mask transition shaped like, and closing on, a sprite", () => { expect(app.viewport.cameraEffects).toHaveLength(0); }); }); + + it("set for one change, then set back at once: that change is the mask, the next one the usual fade", async () => { + let player; + const start = state.USER + 92; + const next = state.USER + 93; + const last = state.USER + 94; + state.set( + start, + new Stage({ + onResetEvent(game) { + player = new Sprite(200, 50, { image: leftHalf() }); + game.world.addChild(player); + }, + }), + ); + state.set(next, new Stage()); + state.set(last, new Stage()); + state.setTransition(start, false); + state.change(start, true); + await runUntil(() => { + expect(state.isCurrent(start)).toBe(true); + expect(player?.ancestor).toBeDefined(); + }); + + // the game's usual transition + state.transition("fade", "#000", DURATION); + + // the player's silhouette, for this change only: the usual one is + // set back before a single frame of the mask has run + state.transition("mask", "#000", DURATION, player); + state.change(next); + state.transition("fade", "#000", DURATION); + + // the hide was built when the change was asked for, from the mask + expect(effectsOn(app)).toEqual(["MaskEffect:hide"]); + const hide = app.viewport.getCameraEffect(MaskEffect); + expect(hide._silhouette).toBeDefined(); + const silhouette = hide._silhouette.target.canvas; + + // the reveal comes from the hide, not from the settings, which are + // the fade's by now: the same mask, the same silhouette + const seen = new Set(); + let reveal; + await runUntil(() => { + for (const name of effectsOn(app)) { + seen.add(name); + } + expect(state.isCurrent(next)).toBe(true); + reveal = app.viewport.cameraEffects.find((fx) => { + return fx instanceof MaskEffect && fx.direction === "reveal"; + }); + expect(reveal).toBeDefined(); + }); + expect(reveal._silhouette.target.canvas).toBe(silhouette); + await runUntil(() => { + for (const name of effectsOn(app)) { + seen.add(name); + } + expect(app.viewport.cameraEffects).toHaveLength(0); + }); + // on no frame of that transition was a fade on the camera + expect([...seen].sort()).toEqual(["MaskEffect:hide", "MaskEffect:reveal"]); + + // the next change is the usual fade, both ways, and never a mask + state.change(last); + expect(app.viewport.getCameraEffect(FadeEffect)).toBeDefined(); + const seenNext = new Set(); + await runUntil(() => { + for (const name of effectsOn(app)) { + seenNext.add(name); + } + expect(state.isCurrent(last)).toBe(true); + expect(app.viewport.cameraEffects).toHaveLength(0); + }); + expect(seenNext.size).toBeGreaterThan(0); + for (const name of seenNext) { + expect(name.startsWith("FadeEffect")).toBe(true); + } + }); }); From 2bb1fcc042e3f5b38de14c4671e3c8de6862a0ab Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 07:28:04 +0000 Subject: [PATCH 13/51] Transitions: a sprite the game keeps for itself shapes every mask transition MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit state.transition("mask", …, sprite) let go of any sprite after one transition, because a level's player is destroyed by the change. A sprite that is in no level (atlas.createSpriteFromName(), kept by the game) or a persistent one is not, and was dropped all the same: the first change wore it, every later one was a plain iris, with nothing said. A sprite shape, and a renderable center, are now let go only when the change takes them: in the world, and not under a persistent child of it. Anything else is kept with the transition and read again at each change. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- .../skills/melonjs-scenes-and-state/SKILL.md | 27 +- packages/melonjs/src/state/state.ts | 61 +++- .../tests/mask-transition-sprite.spec.js | 269 +++++++++++++++++- 3 files changed, 338 insertions(+), 19 deletions(-) diff --git a/packages/melonjs/skills/melonjs-scenes-and-state/SKILL.md b/packages/melonjs/skills/melonjs-scenes-and-state/SKILL.md index 00662de9d6..66f387f54d 100644 --- a/packages/melonjs/skills/melonjs-scenes-and-state/SKILL.md +++ b/packages/melonjs/skills/melonjs-scenes-and-state/SKILL.md @@ -162,11 +162,26 @@ scene uncovered. A sprite or renderable given here is read when the transition starts, and the reveal reuses what the hide read, so the old stage destroying the player -in between is fine. It is then let go: the transition is sticky, but one -level's player is not the next one's, so later changes are an iris on the -centre of the screen until you set it again. Give it this level's player -right before each `state.change`. The -`"pixelate"` form breaks the screen up into blocks (its fourth argument is the +in between is fine. Whether it is kept depends on whose it is: + +- **a sprite the game keeps for itself** (never added to a level, such as + `atlas.createSpriteFromName("logo")`, or a persistent one in the world): set + it once, it shapes every change, with the frame it shows by then. +- **a sprite that is part of the level** (the player): the change destroys it, + so it is let go after that one transition, and later changes are an iris on + the centre of the screen until you set it again. Give it this level's + player right before each `state.change`. + +```js +// once, at startup: every change wears the logo +state.transition("mask", "#000", 500, atlas.createSpriteFromName("logo")); + +// before each change: this level's player +state.transition("mask", "#000", 500, player, { center: player }); +state.change(state.GAME_END); +``` + +The `"pixelate"` form breaks the screen up into blocks (its fourth argument is the largest block size in pixels; the color is not used). It is a shader effect, so on Canvas it does nothing and the state changes directly. @@ -596,7 +611,7 @@ When `setStorage()` switches storage: | `Undefined Stage for state 'N'` thrown | no `state.set` for that id first | | `state.change(state.PLAY)` from `PLAY` does nothing ("Retry" ignored) | a change to the current state is a no-op — `state.reload()` (20.16), `level.reload()` for the map alone | | a mask transition closes on the middle of the screen, not on the player | pass `{ center: player }` as the fifth argument; on a `Trigger`, `center: "touching"` | -| the first mask transition is the player's shape, later ones a plain iris on the middle of the screen | a sprite or renderable given to `state.transition` is used by one transition, then let go: set it again, with this level's player, right before each `state.change` | +| the first mask transition is the player's shape, later ones a plain iris on the middle of the screen | a sprite that is part of the level is destroyed by the change, so `state.transition` lets it go after one transition: set it again, with this level's player, right before each `state.change`. A sprite kept outside any level (or a persistent one) is set once and shapes every change | | a level change through a `Trigger` ignores `state.transition` | it is a level change, not a state change: set `color` and `duration` (and `transition`) on the trigger | | the game stops updating for good after one very slow update, such as a heavy first frame (20.12 and 20.13) | the loop could no longer save enough time to step the world: update | | the game resumes under its own pause menu after a tab switch (before 20.9) | focus undid any pause; update, only the blur pause is undone | diff --git a/packages/melonjs/src/state/state.ts b/packages/melonjs/src/state/state.ts index 70da3747b1..5280ec701b 100644 --- a/packages/melonjs/src/state/state.ts +++ b/packages/melonjs/src/state/state.ts @@ -10,6 +10,7 @@ import MaskEffect, { } from "../camera/effects/mask_effect.ts"; import PixelateTransitionEffect from "../camera/effects/pixelate_transition_effect.ts"; import DefaultLoadingScreen from "./../loader/loadingscreen.js"; +import type Renderable from "./../renderable/renderable.js"; import Stage from "./../state/stage.ts"; import { BLUR, @@ -56,8 +57,8 @@ const _transitionConfig: { // where a mask transition closes and opens, and whether it is inverted center?: MaskCenter | undefined; invert?: boolean | undefined; - // a sprite shape or a renderable center was used, and let go: later - // changes are an iris on the centre of the screen until it is set again + // a sprite shape the change took with its level was used, and let go: + // later changes are an iris until it is set again released?: boolean | undefined; // the largest blocks of a pixelate transition, in screen pixels size?: number | undefined; @@ -66,6 +67,33 @@ const _transitionConfig: { duration: 0, }; +/** + * Whether a state change takes this away: a renderable in the world, unless + * the child of the world it is, or is under, is persistent. The world is + * reset with its stage, and spares its persistent children with all they + * hold; a renderable in no world (one the game made and keeps for itself) is + * not its to destroy. + * @param value - the shape or the center of a mask transition + * @returns true for a renderable the next state change takes away + */ +function goesWithTheStage(value: unknown): boolean { + if (!isRenderable(value)) { + return false; + } + let node: Renderable = value; + let kept = false; + // `ancestor` is undefined on a renderable that is in no container + let parent = node.ancestor as Renderable | undefined; + while (parent !== undefined) { + // persistent is a word to the container a renderable is a child of: + // only the world's own children are asked + kept = node.isPersistent; + node = parent; + parent = node.ancestor; + } + return node === _app.world && !kept; +} + // callback when state switch is done /** * @ignore @@ -725,14 +753,18 @@ const state = { * @param [shape] - for "mask" (required) the mask shape: an `Ellipse` or * `Polygon` (unit-sized, centred on the origin), an image or the name of a * preloaded one (its silhouette), or a `Sprite` (the silhouette of the - * frame it shows when the transition starts); see {@link MaskEffect}. For - * "pixelate", the size of the largest blocks, in screen pixels (32 by - * default) + * frame it shows when the transition starts); see {@link MaskEffect}. A + * sprite the game keeps for itself (in no level, or persistent) is kept + * with the transition, and shapes every change. One that is part of the + * level shapes the next change, which destroys it, and is then let go: + * later changes are an iris until it is set again. For "pixelate", the + * size of the largest blocks, in screen pixels (32 by default) * @param [options] - for "mask" only * @param [options.center] - where the shape closes and opens: a * renderable, such as the player, at the place it is drawn when the * transition starts, or a point on screen. The centre of the screen by - * default. The reveal opens from the same place + * default. The reveal opens from the same place. A renderable is kept or + * let go as a sprite `shape` is * @param [options.invert=false] - make the shape the cover rather than * the window: filled with the color, it grows out of `center` until it * covers the screen, and shrinks away to reveal it @@ -757,6 +789,10 @@ const state = { * state.transition("mask", "#000", 500, player, { center: player }); * state.change(state.GAME_END); * @example + * // a sprite of the game's own, in no level: set once, for every change + * const logo = atlas.createSpriteFromName("logo"); + * state.transition("mask", "#000", 500, logo); + * @example * // a black circle growing out of the player until it covers the screen * state.transition("mask", "#000", 400, new Ellipse(0, 0, 1, 1), { * center: player, @@ -940,15 +976,16 @@ const state = { invert: _transitionConfig.invert, onComplete, }); - // The transition is set once and kept, but a sprite or a - // renderable is one level's player: read now, it is let - // go, rather than held (and read again, destroyed or - // recycled into something else) by every later change - if (isRenderable(_transitionConfig.shape)) { + // The transition is set once and kept, and so is a sprite + // the game keeps for itself. One this change destroys, + // one level's player, is read now and let go, rather + // than held (and read again, destroyed or recycled into + // something else) by every later change + if (goesWithTheStage(_transitionConfig.shape)) { _transitionConfig.shape = undefined; _transitionConfig.released = true; } - if (isRenderable(_transitionConfig.center)) { + if (goesWithTheStage(_transitionConfig.center)) { _transitionConfig.center = undefined; } // see the note in the fade case: persistent is what diff --git a/packages/melonjs/tests/mask-transition-sprite.spec.js b/packages/melonjs/tests/mask-transition-sprite.spec.js index d4e6b564ef..b8fd3c04c2 100644 --- a/packages/melonjs/tests/mask-transition-sprite.spec.js +++ b/packages/melonjs/tests/mask-transition-sprite.spec.js @@ -1,12 +1,23 @@ -import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + describe, + expect, + it, + vi, +} from "vitest"; import { Application, boot, + Container, FadeEffect, MaskEffect, Sprite, Stage, state, + TextureAtlas, video, } from "../src/index.js"; import { readPixel } from "./helpers/pixels.js"; @@ -19,6 +30,10 @@ import { readPixel } from "./helpers/pixels.js"; * * And the way to use one for a single change: set it, call `state.change()`, * set the usual transition back on the next line. + * + * A sprite is let go after one transition only when the change takes it: one + * the game keeps for itself, outside any level, or a persistent one, is set + * once and shapes every change. */ const DURATION = 60; @@ -70,6 +85,51 @@ const effectsOn = (app) => { }); }; +/** the side of a silhouette that holds more of the shape, "left" or "right" */ +const heavierSide = (silhouette) => { + const canvas = silhouette.target.canvas; + const { width, height } = canvas; + const { data } = canvas.getContext("2d").getImageData(0, 0, width, height); + let left = 0; + let right = 0; + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + const alpha = data[(y * width + x) * 4 + 3]; + if (x < width / 2) { + left += alpha; + } else { + right += alpha; + } + } + } + return left > right ? "left" : "right"; +}; + +/** a sprite from an atlas, as `atlas.createSpriteFromName()` makes one */ +const atlasSprite = () => { + const atlas = new TextureAtlas( + { + frames: [ + { + filename: "eat_0000", + frame: { x: 0, y: 0, w: 20, h: 30 }, + rotated: false, + trimmed: false, + spriteSourceSize: { x: 0, y: 0, w: 20, h: 30 }, + sourceSize: { w: 20, h: 30 }, + }, + ], + meta: { + app: "texturepacker", + image: "eat-sheet.png", + size: { w: 20, h: 30 }, + }, + }, + leftHalf(), + ); + return atlas.createSpriteFromName("eat_0000"); +}; + describe("a mask transition shaped like, and closing on, a sprite", () => { let app; beforeAll(async () => { @@ -269,4 +329,211 @@ describe("a mask transition shaped like, and closing on, a sprite", () => { expect(name.startsWith("FadeEffect")).toBe(true); } }); + + describe("set once, for every change", () => { + // two empty stages to go back and forth between + const here = state.USER + 95; + const there = state.USER + 96; + let warn; + let current; + + /** change to the other stage, and hand back the hide it starts */ + const change = () => { + current = current === here ? there : here; + state.change(current); + return app.viewport.getCameraEffect(MaskEffect); + }; + /** let the change land and its reveal end */ + const settle = async () => { + await runUntil(() => { + expect(state.isCurrent(current)).toBe(true); + expect(app.viewport.cameraEffects).toHaveLength(0); + }); + }; + const isIris = (effect) => { + return ( + effect._silhouette === undefined && + effect._maskShape?.type === "Ellipse" + ); + }; + + beforeAll(async () => { + state.set(here, new Stage()); + state.set(there, new Stage()); + state.transition("fade", "#000", 0); + current = here; + state.change(here, true); + await runUntil(() => { + expect(state.isCurrent(here)).toBe(true); + }); + }); + beforeEach(() => { + warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + }); + afterEach(async () => { + warn.mockRestore(); + await settle(); + }); + + it("a sprite the game keeps for itself, never in a level, shapes every change", async () => { + // what `atlas.createSpriteFromName()` gives, set once at startup + const sprite = atlasSprite(); + state.transition("mask", "#000", DURATION, sprite); + + for (let i = 0; i < 4; i++) { + const hide = change(); + expect(hide.direction).toBe("hide"); + expect(hide._silhouette, `change ${i + 1}`).toBeDefined(); + await settle(); + // no change destroyed it + expect(sprite.offset).toBeDefined(); + } + expect(warn).not.toHaveBeenCalled(); + }); + + it("each change draws the frame the sprite shows by then", async () => { + const sprite = atlasSprite(); + state.transition("mask", "#000", DURATION, sprite); + + // the image's left half is the opaque one + expect(heavierSide(change()._silhouette)).toBe("left"); + await settle(); + + // the game turns its sprite around: the next change is not the + // picture of the first one, kept, but the sprite read again + sprite.flipX(true); + expect(heavierSide(change()._silhouette)).toBe("right"); + await settle(); + + sprite.flipX(false); + expect(heavierSide(change()._silhouette)).toBe("left"); + }); + + it("a persistent sprite in the world, and one in a persistent container, are kept", async () => { + const lone = new Sprite(40, 40, { image: leftHalf() }); + lone.isPersistent = true; + app.world.addChild(lone); + + const hud = new Container(0, 0, 320, 240); + hud.isPersistent = true; + const inHud = new Sprite(100, 100, { image: leftHalf() }); + hud.addChild(inHud); + app.world.addChild(hud); + + for (const sprite of [lone, inHud]) { + state.transition("mask", "#000", DURATION, sprite, { center: sprite }); + for (let i = 0; i < 3; i++) { + const hide = change(); + expect(hide._silhouette, `change ${i + 1}`).toBeDefined(); + expect(hide.center, `change ${i + 1}`).toBeDefined(); + await settle(); + // the change left it in the world + expect(sprite.ancestor).toBeDefined(); + } + } + expect(warn).not.toHaveBeenCalled(); + + app.world.removeChildNow(lone); + app.world.removeChildNow(hud); + }); + + it("a sprite inside a container of the level goes with it, and is let go", async () => { + const room = new Container(0, 0, 320, 240); + const inRoom = new Sprite(100, 100, { image: leftHalf() }); + room.addChild(inRoom); + app.world.addChild(room); + state.transition("mask", "#000", DURATION, inRoom, { center: inRoom }); + + const first = change(); + expect(first._silhouette).toBeDefined(); + expect(first.center).toBeDefined(); + await settle(); + // the change destroyed it + expect(inRoom.offset).toBeUndefined(); + + const second = change(); + expect(isIris(second)).toBe(true); + expect(second.center).toBeUndefined(); + expect(warn).not.toHaveBeenCalled(); + }); + + it("a persistent sprite inside a container of the level is let go with it", async () => { + // Persistent is a word to the container a renderable is a child + // of, and the world only asks its own children: the room goes, + // and what it held is left in a container that is no more. + // Nothing to keep reading a place on screen from + const room = new Container(0, 0, 320, 240); + const inRoom = new Sprite(100, 100, { image: leftHalf() }); + inRoom.isPersistent = true; + room.addChild(inRoom); + app.world.addChild(room); + state.transition("mask", "#000", DURATION, inRoom, { center: inRoom }); + + const first = change(); + expect(first._silhouette).toBeDefined(); + expect(first.center).toBeDefined(); + await settle(); + expect(room.ancestor).toBeUndefined(); + + const second = change(); + expect(isIris(second)).toBe(true); + expect(second.center).toBeUndefined(); + expect(warn).not.toHaveBeenCalled(); + }); + + it("kept while it is the game's own, let go by the change that finds it in a level", async () => { + const sprite = atlasSprite(); + state.transition("mask", "#000", DURATION, sprite); + expect(change()._silhouette).toBeDefined(); + await settle(); + expect(change()._silhouette).toBeDefined(); + await settle(); + + // now it joins a level: this change still wears it, and takes it + app.world.addChild(sprite); + expect(change()._silhouette).toBeDefined(); + await settle(); + expect(sprite.offset).toBeUndefined(); + + expect(isIris(change())).toBe(true); + expect(warn).not.toHaveBeenCalled(); + }); + + it("a sprite in a container that is in no world is kept", async () => { + const shelf = new Container(0, 0, 100, 100); + const sprite = new Sprite(10, 10, { image: leftHalf() }); + shelf.addChild(sprite); + state.transition("mask", "#000", DURATION, sprite); + for (let i = 0; i < 3; i++) { + expect(change()._silhouette, `change ${i + 1}`).toBeDefined(); + await settle(); + } + expect(warn).not.toHaveBeenCalled(); + }); + + it("a kept sprite the game destroys later: an iris from then on, not an error", async () => { + const sprite = atlasSprite(); + state.transition("mask", "#000", DURATION, sprite, { center: sprite }); + expect(change()._silhouette).toBeDefined(); + await settle(); + + sprite.destroy(); + const hide = change(); + expect(isIris(hide)).toBe(true); + await settle(); + expect(isIris(change())).toBe(true); + }); + + it("setting another transition forgets a kept sprite", async () => { + const sprite = atlasSprite(); + state.transition("mask", "#000", DURATION, sprite); + expect(change()._silhouette).toBeDefined(); + await settle(); + + state.transition("fade", "#000", DURATION); + state.change((current = current === here ? there : here)); + expect(app.viewport.getCameraEffect(MaskEffect)).toBeUndefined(); + expect(app.viewport.getCameraEffect(FadeEffect)).toBeDefined(); + }); + }); }); From 60bf7467b5ab491bbc6e706a4a6aed7494a59bde Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 08:06:56 +0000 Subject: [PATCH 14/51] Tiled: object layers and group layers follow their offset An offset given to a layer in Tiled moved a tile layer (since this release) and an image layer, and nothing else. An object layer's objects are now created that far from where they were drawn, collision shapes with them, and a group layer's offset moves the tile layers inside it, on top of their own. The objects are moved once they stand where their map puts them, so an isometric map's are moved on the screen, as Tiled does. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- packages/melonjs/CHANGELOG.md | 2 +- .../melonjs/skills/melonjs-tilemaps/SKILL.md | 12 +- packages/melonjs/src/level/tiled/TMXGroup.js | 23 +- .../melonjs/tests/tiled-layer-offsets.spec.js | 390 ++++++++++++++++++ 4 files changed, 423 insertions(+), 4 deletions(-) create mode 100644 packages/melonjs/tests/tiled-layer-offsets.spec.js diff --git a/packages/melonjs/CHANGELOG.md b/packages/melonjs/CHANGELOG.md index d2a722b83c..44d3bd2935 100644 --- a/packages/melonjs/CHANGELOG.md +++ b/packages/melonjs/CHANGELOG.md @@ -11,7 +11,7 @@ - Tiled: for reference, orthogonal tile layers, on the GPU since 19.4, measure about **85%** less with 1000 tiles in view (0.62 to 0.09 ms) and about **97%** less with 3600 (1.9 to 0.06 ms) ### Fixed -- Tiled: a tile layer follows its offset in Tiled, and its own `pos` when the game moves it: its tiles are drawn there, and `getTile()` finds them there. Both were ignored; a map whose tile layers have an offset now looks as it does in Tiled +- Tiled: layers follow their offset in Tiled. A tile layer is drawn there, and where its own `pos` moves it, and `getTile()` finds its tiles there; an object layer's objects are created there; a group layer's offset moves the tile layers inside it. All were ignored, so a map with layer offsets now looks as it does in Tiled - Tiled: tiles larger than a cell are drawn wherever they are in view. They were cut off or left out along the edges of the view, above and right of the map, on a map centred in the screen, and once the map itself had scrolled out of view - Tiled: staggered and hexagonal maps are drawn where Tiled draws them: a tile larger than its cell stands on it, a tileset's `tileoffset` moves its tiles, and maps of odd sizes stay on whole pixels - Tiled: orthogonal layers drawn by the GPU show the soft edges of large tiles over the tiles behind them, lay large tiles over each other in the map's order, and read a tileset with a `margin` right diff --git a/packages/melonjs/skills/melonjs-tilemaps/SKILL.md b/packages/melonjs/skills/melonjs-tilemaps/SKILL.md index 3ea557a668..d0db8aedc7 100644 --- a/packages/melonjs/skills/melonjs-tilemaps/SKILL.md +++ b/packages/melonjs/skills/melonjs-tilemaps/SKILL.md @@ -312,6 +312,13 @@ board.pos.y -= 8; // the whole layer, 8 pixels up board.getTile(pointer.x, pointer.y); // still the tile under the pointer ``` +The other layers follow their offset in Tiled too: an image layer is placed by +it, an object layer's objects are created that far from where they were drawn +(collision shapes with them), and a group layer's offset moves the tile layers +inside it, on top of their own. A group can only hold tile layers: with an +object layer, an image layer or another group inside a group, the map fails +to load. + The map's own custom properties (Map → Map Properties in Tiled) are set on the map object, which `level.getCurrentLevel()` returns once it is loaded: a `theme` string property is `level.getCurrentLevel().theme`. They are set @@ -540,8 +547,9 @@ layer into the offscreen-bake path instead. | the level's `name` is not its id after loading | a map custom property named `name` replaced it: map properties are set over the map's own fields | | changing tiles at runtime is slow on a pre-rendered layer | outside an orthogonal map whose tiles fit their cells, a changed tile re-bakes the whole layer before it next draws: keep layers you edit often off `preRender` | | thin lines between tiles on the Canvas renderer, with smoothing on | filtering blends in the next tile of the tileset or its spacing, which a canvas cannot prevent: set `antiAlias: false`, or `preRender` the layer. WebGL and WebGPU keep each tile to itself | -| a tile layer given an offset in Tiled (a roof nudged up, a shadow shifted) is drawn where the others are | before 20.17 a tile layer ignored its offset, and its `pos`; only image layers followed theirs: update | -| after updating to 20.17 a tile layer sits away from where it did | it has an offset in Tiled that was ignored until then, and now moves it as in the editor: clear the layer's Offset in Tiled if it was not meant | +| a tile layer given an offset in Tiled (a roof nudged up, a shadow shifted) is drawn where the others are, or the objects of an object layer with an offset are not where Tiled shows them | before 20.17 only image layers followed their offset; tile layers (and their `pos`), object layers and group layers ignored it: update | +| after updating to 20.17 a tile layer, or the objects of an object layer, sit away from where they did | the layer (or the group it is in) has an offset in Tiled that was ignored until then, and now moves it as in the editor: clear the layer's Offset in Tiled if it was not meant | +| the map fails to load with a group layer in it | the group holds an object layer, an image layer or another group: a group can only hold tile layers. Move those layers out of the group | | a map smaller than the screen (centred by `level.load`) had the tops of its tall tiles cut on WebGL or WebGPU | before 20.17 a layer read the camera's view as if it stood at the world's origin, and so did a layer in a container the game had moved: update | | the tops of tall tiles vanish when the map itself scrolls out of view | before 20.17 a layer was skipped once its grid left the view, though tiles larger than a cell (or moved by a `tileoffset`) still reached in: update | | an orthogonal layer warns `tiles larger than the grid, of more than one tileset in a layer` | tiles larger than a cell overlap, and the shader path keeps their order within one tileset: put each tileset's large tiles on a layer of their own (trees apart from the ground they stand on) | diff --git a/packages/melonjs/src/level/tiled/TMXGroup.js b/packages/melonjs/src/level/tiled/TMXGroup.js index 92dc62d09f..ab8d8364ea 100644 --- a/packages/melonjs/src/level/tiled/TMXGroup.js +++ b/packages/melonjs/src/level/tiled/TMXGroup.js @@ -63,6 +63,19 @@ export default class TMXGroup { */ this.blendMode = tiledBlendMode(data.mode); + /** + * the layer's horizontal offset in Tiled, in pixels: an object layer + * moves its objects by it, a group layer the tile layers inside it + * @type {number} + */ + this.offsetx = +data.offsetx || 0; + + /** + * the layer's vertical offset in Tiled, in pixels + * @type {number} + */ + this.offsety = +data.offsety || 0; + // check if we have any user-defined properties applyTMXProperties(this, data); @@ -71,7 +84,12 @@ export default class TMXGroup { const objects = data.objects; for (let i = 0, len = objects.length; i < len; i++) { objects[i].tintcolor = this.tintcolor; - this.objects.push(new TMXObject(map, objects[i], z)); + const object = new TMXObject(map, objects[i], z); + // Moved on the screen, so once the object stands where its + // map puts it (an isometric map projects it) + object.x += this.offsetx; + object.y += this.offsety; + this.objects.push(object); } } @@ -88,6 +106,9 @@ export default class TMXGroup { z, ); z++; + // the group's offset, on top of the layer's own + layer.pos.x += this.offsetx; + layer.pos.y += this.offsety; // set a renderer layer.setRenderer(map.getRenderer()); // resize container accordingly diff --git a/packages/melonjs/tests/tiled-layer-offsets.spec.js b/packages/melonjs/tests/tiled-layer-offsets.spec.js new file mode 100644 index 0000000000..fdd111705d --- /dev/null +++ b/packages/melonjs/tests/tiled-layer-offsets.spec.js @@ -0,0 +1,390 @@ +/** + * The offset Tiled gives a layer (`offsetx`, `offsety`), on the layers that + * are not tile layers: an object layer moves its objects, and a group layer + * moves the tile layers inside it, on top of their own offset. + * + * Objects are compared with the same map loaded with no offset, so that how + * an orientation places an object (an isometric map projects it) is not + * worked out twice. Tile layers in a group are held to the picture painted + * with no engine (see `helpers/tile-layer-compare.js`) of the same layers, + * out of the group, carrying the sum of the offsets themselves. + */ +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { TMXLayer, video } from "../src/index.js"; +import { + diff, + drawIn, + drawn, + fill, + inBlock, + makeApp, + makeMap, + makeTileset, + reference, + show, +} from "./helpers/tile-layer-compare.js"; + +const WIDTH = 320; +const HEIGHT = 240; + +const filled = (cols, rows, seed = 0) => { + return fill(cols, rows, (c, r) => { + return (c * 3 + r + seed) % 5 === 0 ? 0 : 1 + ((c + r * 2 + seed) % 8); + }); +}; + +const GEOMETRY = { + orthogonal: { cols: 10, rows: 8, tw: 32, th: 32, tall: 32 }, + isometric: { cols: 8, rows: 6, tw: 64, th: 32, tall: 64 }, +}; + +/** + * One tileset for each orientation, made once: two scenes are compared, and + * every tileset made has pictures of its own + */ +const TILESETS = {}; +const tilesetOf = (orientation) => { + const { tw, th, tall } = GEOMETRY[orientation]; + TILESETS[orientation] ??= makeTileset({ + tw, + th: tall, + opaque: (x, y) => { + return inBlock(x, y, tw, tall, tw, th); + }, + }); + return TILESETS[orientation]; +}; + +/** a map of one orientation, with the given layers after a plain tile layer */ +const scene = (orientation, layers) => { + const { cols, rows, tw, th } = GEOMETRY[orientation]; + return { + orientation, + cols, + rows, + tw, + th, + tilesets: [tilesetOf(orientation)], + layers: [{ data: filled(cols, rows) }, ...layers], + }; +}; + +/** a tile layer as a group holds one: all that `makeMap` fills in itself */ +const inner = (orientation, name, seed, more = {}) => { + const { cols, rows } = GEOMETRY[orientation]; + return { + type: "tilelayer", + name, + width: cols, + height: rows, + visible: true, + opacity: 1, + data: filled(cols, rows, seed), + ...more, + }; +}; + +/** an object layer with one object of each kind */ +const objectLayer = (more = {}) => { + const object = (id, name, rest) => { + return { id, name, type: "", rotation: 0, visible: true, ...rest }; + }; + return { + type: "objectgroup", + name: "things", + draworder: "topdown", + objects: [ + object(1, "box", { x: 40, y: 50, width: 20, height: 10 }), + object(2, "spot", { x: 100, y: 60, width: 0, height: 0, point: true }), + object(3, "tri", { + x: 120, + y: 80, + width: 0, + height: 0, + polygon: [ + { x: 0, y: 0 }, + { x: 20, y: 0 }, + { x: 10, y: 15 }, + ], + }), + object(4, "round", { + x: 30, + y: 90, + width: 24, + height: 24, + ellipse: true, + }), + object(5, "crate", { x: 64, y: 96, width: 32, height: 32, gid: 1 }), + ], + ...more, + }; +}; + +const NAMES = ["box", "spot", "tri", "round", "crate"]; + +describe("the offset of an object layer and of a group layer in Tiled", () => { + let app; + beforeAll(async () => { + app = await makeApp(video.CANVAS, "CANVAS", WIDTH, HEIGHT); + }); + afterAll(() => { + app?.destroy(); + vi.restoreAllMocks(); + }); + + /** load a map, and say where each named object stands in the world */ + const whereObjectsAre = (map, flatten) => { + app.world.reset(); + app.world.pos.set(0, 0, app.world.pos.z); + map.addTo(app.world, flatten, false); + const places = {}; + for (const name of NAMES) { + const found = app.world.getChildByName(name); + expect(found, name).toHaveLength(1); + const at = found[0].getAbsolutePosition(); + places[name] = { x: at.x, y: at.y }; + } + return places; + }; + + /** the tile layers a group holds, as the map read them */ + const groupLayers = (map) => { + map.getLayers(); + return map.objectGroups.flatMap((group) => { + return group.objects.filter((object) => { + return object instanceof TMXLayer; + }); + }); + }; + + describe("an object layer moves its objects", () => { + for (const orientation of ["orthogonal", "isometric"]) { + for (const flatten of [true, false]) { + for (const [ox, oy] of [ + [37, -21], + [-130, 75], + ]) { + it(`${orientation}, ${flatten ? "flattened" : "in its container"}, by (${ox}, ${oy})`, () => { + const unmoved = whereObjectsAre( + makeMap(scene(orientation, [objectLayer()])), + flatten, + ); + const moved = whereObjectsAre( + makeMap( + scene(orientation, [objectLayer({ offsetx: ox, offsety: oy })]), + ), + flatten, + ); + for (const name of NAMES) { + expect(moved[name].x - unmoved[name].x, `${name} x`).toBeCloseTo( + ox, + 6, + ); + expect(moved[name].y - unmoved[name].y, `${name} y`).toBeCloseTo( + oy, + 6, + ); + } + }); + } + } + } + + it("its collision shapes move with the objects", () => { + const shapeOf = (map) => { + app.world.reset(); + map.addTo(app.world, true, false); + const box = app.world.getChildByName("box")[0]; + const bounds = box.getBounds(); + return { left: bounds.left, top: bounds.top, width: bounds.width }; + }; + const unmoved = shapeOf(makeMap(scene("orthogonal", [objectLayer()]))); + const moved = shapeOf( + makeMap( + scene("orthogonal", [objectLayer({ offsetx: 37, offsety: -21 })]), + ), + ); + expect(moved.left - unmoved.left).toBeCloseTo(37, 6); + expect(moved.top - unmoved.top).toBeCloseTo(-21, 6); + expect(moved.width).toBeCloseTo(unmoved.width, 6); + }); + + it("an offset written as text, as an XML map gives it, counts the same", () => { + const unmoved = whereObjectsAre( + makeMap(scene("orthogonal", [objectLayer()])), + true, + ); + const moved = whereObjectsAre( + makeMap( + scene("orthogonal", [ + objectLayer({ offsetx: "12.5", offsety: "-4" }), + ]), + ), + true, + ); + expect(moved.box.x - unmoved.box.x).toBeCloseTo(12.5, 6); + expect(moved.box.y - unmoved.box.y).toBeCloseTo(-4, 6); + }); + + it("the objects are made twice from one map: moved once each time", () => { + const map = makeMap( + scene("orthogonal", [objectLayer({ offsetx: 37, offsety: -21 })]), + ); + const places = () => { + return map.getObjects(true).map((object) => { + return [object.name, object.pos.x, object.pos.y]; + }); + }; + const first = places(); + expect(first).toHaveLength(NAMES.length); + expect(places()).toEqual(first); + }); + + it("the map's data is left as it was read", () => { + const data = scene("orthogonal", [ + objectLayer({ offsetx: 37, offsety: -21 }), + ]); + const before = JSON.stringify(data.layers[1].objects); + whereObjectsAre(makeMap(data), true); + expect(JSON.stringify(data.layers[1].objects)).toBe(before); + }); + }); + + describe("a group layer moves the tile layers inside it", () => { + const VIEWS = [ + [0, 0], + [70, 20], + [-40, -80], + [230, 110], + ]; + + /** + * Draw a map with a group, tile by tile and baked, and expect the + * picture of the flat map that says the same thing. + */ + const asTiled = async (grouped, flat) => { + let total = 0; + for (const mode of ["perTile", "prerender"]) { + const map = makeMap(grouped); + for (const layer of groupLayers(map)) { + layer.renderMode = mode; + } + show(app, map, mode); + const layers = app.world.getChildByType(TMXLayer); + expect(layers).toHaveLength(flat.layers.length); + for (const [x, y] of VIEWS) { + app.viewport.moveTo(x, y); + const { frame } = await drawIn(app, layers, mode); + const d = diff(reference(flat, x, y, WIDTH, HEIGHT), frame); + expect(d.different, `${mode}, view (${x}, ${y}): ${d.first}`).toBe(0); + total += drawn(frame); + } + } + return total; + }; + + for (const orientation of ["orthogonal", "isometric"]) { + it(`${orientation}: by the group's offset, and by their own on top`, async () => { + const grouped = scene(orientation, [ + { + type: "group", + name: "upstairs", + offsetx: 48, + offsety: -16, + layers: [ + inner(orientation, "floor", 1, { offsetx: 5, offsety: 7 }), + inner(orientation, "walls", 3), + ], + }, + ]); + const { cols, rows } = GEOMETRY[orientation]; + const flat = scene(orientation, [ + { data: filled(cols, rows, 1), offsetx: 53, offsety: -9 }, + { data: filled(cols, rows, 3), offsetx: 48, offsety: -16 }, + ]); + expect(await asTiled(grouped, flat)).toBeGreaterThan(0); + }); + } + + it("a group with no offset leaves its layers where they are", async () => { + const grouped = scene("orthogonal", [ + { + type: "group", + name: "upstairs", + layers: [ + inner("orthogonal", "floor", 1, { offsetx: 5, offsety: 7 }), + inner("orthogonal", "walls", 3), + ], + }, + ]); + const flat = scene("orthogonal", [ + { data: filled(10, 8, 1), offsetx: 5, offsety: 7 }, + { data: filled(10, 8, 3) }, + ]); + expect(await asTiled(grouped, flat)).toBeGreaterThan(0); + }); + + it("`pos` and `getTile()` follow: a tile is found where it is drawn", () => { + const map = makeMap( + scene("orthogonal", [ + { + type: "group", + name: "upstairs", + offsetx: 48, + offsety: -16, + layers: [ + inner("orthogonal", "floor", 1, { offsetx: 5, offsety: 7 }), + ], + }, + ]), + ); + const [floor] = groupLayers(map); + expect(floor.pos.x).toBe(53); + expect(floor.pos.y).toBe(-9); + // the first cell of the layer that holds a tile + const data = filled(10, 8, 1); + const index = data.findIndex((gid) => { + return gid > 0; + }); + const col = index % 10; + const row = Math.floor(index / 10); + const x = col * 32 + 16; + const y = row * 32 + 16; + // found where it is drawn + expect(floor.getTile(x + 53, y - 9)?.tileId).toBe(data[index]); + // the layer is 320 wide: a point 300 to the left of that tile is + // in it only if the group's 48 pixels were left out + expect(floor.getTile(x + 53 - 300, y - 9)).toBeNull(); + expect(floor.getTile(-10, y - 9)).toBeNull(); + }); + + it("kept in its container (not flattened), the layers stand in the same place", async () => { + const grouped = scene("orthogonal", [ + { + type: "group", + name: "upstairs", + offsetx: 48, + offsety: -16, + layers: [inner("orthogonal", "walls", 3)], + }, + ]); + const flat = scene("orthogonal", [ + { data: filled(10, 8, 3), offsetx: 48, offsety: -16 }, + ]); + const map = makeMap(grouped); + app.world.reset(); + app.world.pos.set(0, 0, app.world.pos.z); + app.renderer.backgroundColor.setColor(16, 24, 48); + map.addTo(app.world, false, false); + app.world.sortNow(true); + app.viewport.setBounds(-100000, -100000, 200000, 200000); + const layers = [...map.getLayers(), ...groupLayers(map)]; + for (const [x, y] of VIEWS) { + app.viewport.moveTo(x, y); + const { frame } = await drawIn(app, layers, "perTile"); + const d = diff(reference(flat, x, y, WIDTH, HEIGHT), frame); + expect(d.different, `view (${x}, ${y}): ${d.first}`).toBe(0); + } + }); + }); +}); From 539613254cd273a46b3123f38ab6d5385934ce60 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 08:16:15 +0000 Subject: [PATCH 15/51] Platformer example: clear a stray offset on the flies layer of the second level The object layer carried an offset of (35, 1), one tile and a pixel, from a drag in the editor. The engine ignored object layer offsets until now, so the level was always played without it: cleared, the flies stay where they have always been. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- packages/examples/public/assets/platformer/map/map2.json | 2 -- 1 file changed, 2 deletions(-) diff --git a/packages/examples/public/assets/platformer/map/map2.json b/packages/examples/public/assets/platformer/map/map2.json index 7588cd8872..6720476d76 100644 --- a/packages/examples/public/assets/platformer/map/map2.json +++ b/packages/examples/public/assets/platformer/map/map2.json @@ -475,8 +475,6 @@ "x":980, "y":385 }], - "offsetx":35, - "offsety":1, "opacity":1, "type":"objectgroup", "visible":true, From 8e90cbd1bf2cf3c0fe37dba7176224a292975582 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 08:17:20 +0000 Subject: [PATCH 16/51] Platformer examples: the same stray offset cleared in the source copies of the second level Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- .../src/examples/platformer-matter/assets/map/map2.json | 2 -- packages/examples/src/examples/platformer/assets/map/map2.json | 2 -- 2 files changed, 4 deletions(-) diff --git a/packages/examples/src/examples/platformer-matter/assets/map/map2.json b/packages/examples/src/examples/platformer-matter/assets/map/map2.json index 7588cd8872..6720476d76 100644 --- a/packages/examples/src/examples/platformer-matter/assets/map/map2.json +++ b/packages/examples/src/examples/platformer-matter/assets/map/map2.json @@ -475,8 +475,6 @@ "x":980, "y":385 }], - "offsetx":35, - "offsety":1, "opacity":1, "type":"objectgroup", "visible":true, diff --git a/packages/examples/src/examples/platformer/assets/map/map2.json b/packages/examples/src/examples/platformer/assets/map/map2.json index 7588cd8872..6720476d76 100644 --- a/packages/examples/src/examples/platformer/assets/map/map2.json +++ b/packages/examples/src/examples/platformer/assets/map/map2.json @@ -475,8 +475,6 @@ "x":980, "y":385 }], - "offsetx":35, - "offsety":1, "opacity":1, "type":"objectgroup", "visible":true, From f60ed871f965e48620a801302693342b3bcf4a7a Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 08:25:21 +0000 Subject: [PATCH 17/51] Platformer example: slimes leave a trail of slime A ParticleEmitter in world space follows each slime and drops flat blobs of its own purple along the base of the sprite, behind it. They stay where they fell, shrink and fade; under the slime they fill the strip between its body and the tile it walks on. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- .../examples/platformer/entities/enemies.ts | 115 ++++++++++++++++++ 1 file changed, 115 insertions(+) diff --git a/packages/examples/src/examples/platformer/entities/enemies.ts b/packages/examples/src/examples/platformer/entities/enemies.ts index 314b3fd7e7..0fd1df3271 100644 --- a/packages/examples/src/examples/platformer/entities/enemies.ts +++ b/packages/examples/src/examples/platformer/entities/enemies.ts @@ -151,11 +151,105 @@ class PathEnemyEntity extends Sprite { } } +// the purple of the slime's body, as it is in the texture atlas +const SLIME_COLOR = "#E98AF4"; + +// a drop of slime, in pixels: wider than tall, as a drop lies on the ground +const DROP_WIDTH = 16; +const DROP_HEIGHT = 6; + +let dropImage: HTMLCanvasElement | undefined; + +/** + * A drop of slime: a white blob, made once and tinted by the emitter that + * draws it. + */ +function dropTexture() { + if (dropImage === undefined) { + dropImage = document.createElement("canvas"); + dropImage.width = DROP_WIDTH; + dropImage.height = DROP_HEIGHT; + const context = dropImage.getContext("2d"); + if (context) { + context.fillStyle = "#fff"; + context.beginPath(); + context.ellipse( + DROP_WIDTH / 2, + DROP_HEIGHT / 2, + DROP_WIDTH / 2, + DROP_HEIGHT / 2, + 0, + 0, + Math.PI * 2, + ); + context.fill(); + } + } + return dropImage; +} + +/** + * The trail a slime leaves on the ground: drops that stay where they fell + * (`referenceSpace: "world"`) while the slime moves on, and shrink away. + * + * They are dropped along the base of the sprite, on one line, and drawn + * behind it. The slime's body stands a couple of pixels above the tile it + * walks on (and its walk frame is shorter still): a drop is tall enough to + * fill that strip, so the slime sits in its own slime rather than over it. + */ +class SlimeTrail extends ParticleEmitter { + slime: SlimeEnemyEntity; + + constructor(slime: SlimeEnemyEntity) { + // the emitter centres its spawn area on the point it is given: the + // middle of the slime's base + super(slime.centerX, slime.pos.y + slime.height, { + image: dropTexture(), + // a drop is born whole inside the base, not hanging off its ends + width: slime.width - DROP_WIDTH, + height: 1, + referenceSpace: "world", + tint: SLIME_COLOR, + totalParticles: 80, + // one drop at a time, over thirty a second: they run into each + // other under the slime, and break up as they dry behind it + maxParticles: 1, + frequency: 30, + // they do not move: a drop settles where it fell + speed: 0, + speedVariation: 0, + minLife: 1200, + maxLife: 2200, + minStartScale: 0.8, + maxStartScale: 1.1, + minEndScale: 0, + maxEndScale: 0.2, + // gone by itself once the stream is stopped and the last drop + // has dried + autoDestroyOnComplete: true, + }); + this.slime = slime; + } + + override update(dt: number) { + // follow the slime: `pos` is the top left of the spawn area + if (this.slime.alive) { + this.setPosition( + this.slime.centerX - this.width / 2, + this.slime.pos.y + this.slime.height - this.height / 2, + ); + } + return super.update(dt); + } +} + /** * A Slime enemy entity * follow a horizontal path defined by the box size in Tiled */ export class SlimeEnemyEntity extends PathEnemyEntity { + trail: SlimeTrail | undefined; + /** * constructor */ @@ -183,6 +277,27 @@ export class SlimeEnemyEntity extends PathEnemyEntity { // particle tint matching the sprite color this.particleTint = "#FF35B8"; } + + /** + * In the level: start leaving a trail, drawn just behind the slime + */ + onActivateEvent() { + this.trail = new SlimeTrail(this); + this.ancestor.addChild(this.trail, this.pos.z - 0.5); + this.trail.streamParticles(); + } + + /** + * Out of the level (squashed, or the level is over): no new drops. The + * ones on the ground dry up, and the emitter goes with the last of them + */ + onDeactivateEvent() { + // unless the level took the emitter away first + if (this.trail?.ancestor) { + this.trail.stopStream(); + } + this.trail = undefined; + } } /** From 5737798862a562a3ffdaa80c8672cbf51cd6ae89 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 08:35:32 +0000 Subject: [PATCH 18/51] Platformer example: a pool of slime under the whole slime The drops of the trail land where chance puts them, so the strip between the slime's body and the tile stayed open under its front. A bar of slime, as wide as the sprite and drawn behind it, now fills that strip from one end to the other; the drops are the trail it leaves behind. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- .../examples/platformer/entities/enemies.ts | 77 +++++++++++++++++-- 1 file changed, 70 insertions(+), 7 deletions(-) diff --git a/packages/examples/src/examples/platformer/entities/enemies.ts b/packages/examples/src/examples/platformer/entities/enemies.ts index 0fd1df3271..a7c19b060f 100644 --- a/packages/examples/src/examples/platformer/entities/enemies.ts +++ b/packages/examples/src/examples/platformer/entities/enemies.ts @@ -188,14 +188,41 @@ function dropTexture() { return dropImage; } +// the slime pooled under the body: how thick, and how far it reaches past +// each end of the sprite +const POOL_HEIGHT = 6; +const POOL_MARGIN = 2; + +const poolImages = new Map(); + +/** + * The pool of slime a slime stands in: a bar with round ends, in its colour, + * made once for each width. + */ +function poolTexture(width: number) { + let image = poolImages.get(width); + if (image === undefined) { + image = document.createElement("canvas"); + image.width = width; + image.height = POOL_HEIGHT; + const context = image.getContext("2d"); + if (context) { + context.fillStyle = SLIME_COLOR; + context.beginPath(); + context.roundRect(0, 0, width, POOL_HEIGHT, POOL_HEIGHT / 2); + context.fill(); + } + poolImages.set(width, image); + } + return image; +} + /** * The trail a slime leaves on the ground: drops that stay where they fell * (`referenceSpace: "world"`) while the slime moves on, and shrink away. * * They are dropped along the base of the sprite, on one line, and drawn - * behind it. The slime's body stands a couple of pixels above the tile it - * walks on (and its walk frame is shorter still): a drop is tall enough to - * fill that strip, so the slime sits in its own slime rather than over it. + * behind it, where the pool the slime stands in ends. */ class SlimeTrail extends ParticleEmitter { slime: SlimeEnemyEntity; @@ -249,6 +276,7 @@ class SlimeTrail extends ParticleEmitter { */ export class SlimeEnemyEntity extends PathEnemyEntity { trail: SlimeTrail | undefined; + pool: Sprite | undefined; /** * constructor @@ -279,23 +307,58 @@ export class SlimeEnemyEntity extends PathEnemyEntity { } /** - * In the level: start leaving a trail, drawn just behind the slime + * Where the pool of slime under the body is: along the base of the + * sprite, half behind it and half below. The body stands a couple of + * pixels above the tile it walks on (its walk frame is shorter still), + * and the pool fills that strip from one end of the sprite to the other + */ + placePool() { + this.pool?.setPosition( + this.pos.x - POOL_MARGIN, + this.pos.y + this.height - POOL_HEIGHT / 2, + ); + } + + /** + * In the level: a pool of slime under the body and a trail behind it, + * both drawn just behind the slime */ onActivateEvent() { + this.pool = new Sprite(0, 0, { + image: poolTexture(this.width + POOL_MARGIN * 2), + anchorPoint: { x: 0, y: 0 }, + }); + this.placePool(); + this.ancestor.addChild(this.pool, this.pos.z - 0.5); + this.trail = new SlimeTrail(this); this.ancestor.addChild(this.trail, this.pos.z - 0.5); this.trail.streamParticles(); } /** - * Out of the level (squashed, or the level is over): no new drops. The - * ones on the ground dry up, and the emitter goes with the last of them + * the pool follows the slime + */ + update(dt) { + const updated = super.update(dt); + this.placePool(); + return updated; + } + + /** + * Out of the level (squashed, or the level is over): the pool goes with + * the slime, and no new drops fall. The ones on the ground dry up, and + * the emitter goes with the last of them */ onDeactivateEvent() { - // unless the level took the emitter away first + // unless the level took them away first + if (this.pool?.ancestor) { + this.pool.ancestor.removeChild(this.pool); + } if (this.trail?.ancestor) { this.trail.stopStream(); } + this.pool = undefined; this.trail = undefined; } } From 66d0db2d9174105a56982175761e8fef66353532 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 09:22:06 +0000 Subject: [PATCH 19/51] Platformer (Matter) example: slimes stand in a pool of slime and leave a trail The same as the built-in physics platformer: a bar of the slime's own purple under the whole sprite, filling the strip above the tile, and drops left behind that shrink and fade. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- .../platformer-matter/entities/enemies.ts | 179 ++++++++++++++++++ 1 file changed, 179 insertions(+) diff --git a/packages/examples/src/examples/platformer-matter/entities/enemies.ts b/packages/examples/src/examples/platformer-matter/entities/enemies.ts index 385a279cad..ef7265816d 100644 --- a/packages/examples/src/examples/platformer-matter/entities/enemies.ts +++ b/packages/examples/src/examples/platformer-matter/entities/enemies.ts @@ -175,11 +175,133 @@ class PathEnemyEntity extends Sprite { } } +// the purple of the slime's body, as it is in the texture atlas +const SLIME_COLOR = "#E98AF4"; + +// a drop of slime, in pixels: wider than tall, as a drop lies on the ground +const DROP_WIDTH = 16; +const DROP_HEIGHT = 6; + +let dropImage: HTMLCanvasElement | undefined; + +/** + * A drop of slime: a white blob, made once and tinted by the emitter that + * draws it. + */ +function dropTexture() { + if (dropImage === undefined) { + dropImage = document.createElement("canvas"); + dropImage.width = DROP_WIDTH; + dropImage.height = DROP_HEIGHT; + const context = dropImage.getContext("2d"); + if (context) { + context.fillStyle = "#fff"; + context.beginPath(); + context.ellipse( + DROP_WIDTH / 2, + DROP_HEIGHT / 2, + DROP_WIDTH / 2, + DROP_HEIGHT / 2, + 0, + 0, + Math.PI * 2, + ); + context.fill(); + } + } + return dropImage; +} + +// the slime pooled under the body: how thick, and how far it reaches past +// each end of the sprite +const POOL_HEIGHT = 6; +const POOL_MARGIN = 2; + +const poolImages = new Map(); + +/** + * The pool of slime a slime stands in: a bar with round ends, in its colour, + * made once for each width. + */ +function poolTexture(width: number) { + let image = poolImages.get(width); + if (image === undefined) { + image = document.createElement("canvas"); + image.width = width; + image.height = POOL_HEIGHT; + const context = image.getContext("2d"); + if (context) { + context.fillStyle = SLIME_COLOR; + context.beginPath(); + context.roundRect(0, 0, width, POOL_HEIGHT, POOL_HEIGHT / 2); + context.fill(); + } + poolImages.set(width, image); + } + return image; +} + +/** + * The trail a slime leaves on the ground: drops that stay where they fell + * (`referenceSpace: "world"`) while the slime moves on, and shrink away. + * + * They are dropped along the base of the sprite, on one line, and drawn + * behind it, where the pool the slime stands in ends. + */ +class SlimeTrail extends ParticleEmitter { + slime: SlimeEnemyEntity; + + constructor(slime: SlimeEnemyEntity) { + // the emitter centres its spawn area on the point it is given: the + // middle of the slime's base + super(slime.centerX, slime.pos.y + slime.height, { + image: dropTexture(), + // a drop is born whole inside the base, not hanging off its ends + width: slime.width - DROP_WIDTH, + height: 1, + referenceSpace: "world", + tint: SLIME_COLOR, + totalParticles: 80, + // one drop at a time, over thirty a second: they run into each + // other under the slime, and break up as they dry behind it + maxParticles: 1, + frequency: 30, + // they do not move: a drop settles where it fell + speed: 0, + speedVariation: 0, + minLife: 1200, + maxLife: 2200, + minStartScale: 0.8, + maxStartScale: 1.1, + minEndScale: 0, + maxEndScale: 0.2, + // gone by itself once the stream is stopped and the last drop + // has dried + autoDestroyOnComplete: true, + }); + this.slime = slime; + } + + override update(dt: number) { + // follow the slime: `pos` is the top left of the spawn area + if (this.slime.alive) { + this.setPosition( + this.slime.centerX - this.width / 2, + this.slime.pos.y + this.slime.height - this.height / 2, + ); + } + return super.update(dt); + } +} + /** * A Slime enemy entity * follow a horizontal path defined by the box size in Tiled */ export class SlimeEnemyEntity extends PathEnemyEntity { + trail: SlimeTrail | undefined; + pool: Sprite | undefined; + constructor(x, y, settings) { super(x, y, settings, [ "slime_normal.png", @@ -196,6 +318,63 @@ export class SlimeEnemyEntity extends PathEnemyEntity { this.setCurrentAnimation("walk"); this.particleTint = "#FF35B8"; } + + /** + * Where the pool of slime under the body is: along the base of the + * sprite, half behind it and half below. The body stands a couple of + * pixels above the tile it walks on (its walk frame is shorter still), + * and the pool fills that strip from one end of the sprite to the other + */ + placePool() { + this.pool?.setPosition( + this.pos.x - POOL_MARGIN, + this.pos.y + this.height - POOL_HEIGHT / 2, + ); + } + + /** + * In the level: a pool of slime under the body and a trail behind it, + * both drawn just behind the slime + */ + override onActivateEvent() { + super.onActivateEvent(); + this.pool = new Sprite(0, 0, { + image: poolTexture(this.width + POOL_MARGIN * 2), + anchorPoint: { x: 0, y: 0 }, + }); + this.placePool(); + this.ancestor.addChild(this.pool, this.pos.z - 0.5); + + this.trail = new SlimeTrail(this); + this.ancestor.addChild(this.trail, this.pos.z - 0.5); + this.trail.streamParticles(); + } + + /** + * the pool follows the slime + */ + update(dt) { + const updated = super.update(dt); + this.placePool(); + return updated; + } + + /** + * Out of the level (squashed, or the level is over): the pool goes with + * the slime, and no new drops fall. The ones on the ground dry up, and + * the emitter goes with the last of them + */ + onDeactivateEvent() { + // unless the level took them away first + if (this.pool?.ancestor) { + this.pool.ancestor.removeChild(this.pool); + } + if (this.trail?.ancestor) { + this.trail.stopStream(); + } + this.pool = undefined; + this.trail = undefined; + } } /** From 4219d5c9c6688a87122ad3051c84eccd3ca8a1b1 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 22:53:23 +0000 Subject: [PATCH 20/51] Build: shader comments are no longer published A shader is bundled as text, and no minifier reads inside a string: every comment of every .vert, .frag and .wgsl file was in the published build and in every game made with it. They were two thirds of the shader text. stripShaderComments takes them out, keeping every line break so that a line of the result is the same line of the source file. The build uses it in an esbuild plugin, and the tests through vite-plugin-glsl's onComplete, so the tests compile the text that ships. The engine minifies to 1,073 kB from 1,159 kB, and to 323 kB gzipped from 350 kB. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- packages/melonjs/CHANGELOG.md | 1 + packages/melonjs/scripts/build.ts | 19 ++- .../melonjs/scripts/strip-shader-comments.ts | 36 ++++++ .../melonjs/tests/shader-comments.spec.js | 109 ++++++++++++++++++ packages/melonjs/vitest.config.ts | 9 +- 5 files changed, 172 insertions(+), 2 deletions(-) create mode 100644 packages/melonjs/scripts/strip-shader-comments.ts create mode 100644 packages/melonjs/tests/shader-comments.spec.js diff --git a/packages/melonjs/CHANGELOG.md b/packages/melonjs/CHANGELOG.md index 44d3bd2935..92bd09da52 100644 --- a/packages/melonjs/CHANGELOG.md +++ b/packages/melonjs/CHANGELOG.md @@ -9,6 +9,7 @@ ### Performance - Tiled: thanks to the GPU renderer, drawing an isometric tile layer takes about **90%** less of the main thread's time with 1200 tiles in view (0.68 to 0.07 ms a frame) and about **98%** less with 4000 (2.0 to 0.04 ms), and no longer grows with the number of tiles shown. Staggered and hexagonal maps gain the same - Tiled: for reference, orthogonal tile layers, on the GPU since 19.4, measure about **85%** less with 1000 tiles in view (0.62 to 0.09 ms) and about **97%** less with 3600 (1.9 to 0.06 ms) +- Size: the engine is about **8%** smaller to download: 323 kB minified and gzipped, from 350 kB (1,073 kB minified, from 1,159 kB). The comments in its shaders are no longer published; a shader is bundled as text, which a game's minifier does not touch, so they reached every game. Nothing to change in a game ### Fixed - Tiled: layers follow their offset in Tiled. A tile layer is drawn there, and where its own `pos` moves it, and `getTile()` finds its tiles there; an object layer's objects are created there; a group layer's offset moves the tile layers inside it. All were ignored, so a map with layer offsets now looks as it does in Tiled diff --git a/packages/melonjs/scripts/build.ts b/packages/melonjs/scripts/build.ts index 09841ee1af..df0065eac0 100644 --- a/packages/melonjs/scripts/build.ts +++ b/packages/melonjs/scripts/build.ts @@ -1,5 +1,7 @@ -import esbuild, { BuildOptions } from "esbuild"; +import { readFile } from "node:fs/promises"; +import esbuild, { BuildOptions, Plugin } from "esbuild"; import packageJson from "../package.json" with { type: "json" }; +import { stripShaderComments } from "./strip-shader-comments.ts"; const banner = [ "/*!", @@ -11,6 +13,20 @@ const banner = [ " */", ].join("\n"); +// Shaders are bundled as text, which no minifier reads: their comments are +// taken out here, or they are shipped to every game +const shaders: Plugin = { + name: "strip-shader-comments", + setup(build) { + build.onLoad({ filter: /\.(vert|frag|wgsl)$/ }, async (args) => { + return { + contents: stripShaderComments(await readFile(args.path, "utf8")), + loader: "text", + }; + }); + }, +}; + const buildOptions = { entryPoints: ["src/index.ts"], loader: { @@ -26,6 +42,7 @@ const buildOptions = { target: "es2022", bundle: true, define: { __VERSION__: JSON.stringify(packageJson.version) }, + plugins: [shaders], banner: { js: banner, }, diff --git a/packages/melonjs/scripts/strip-shader-comments.ts b/packages/melonjs/scripts/strip-shader-comments.ts new file mode 100644 index 0000000000..ad4feab8b8 --- /dev/null +++ b/packages/melonjs/scripts/strip-shader-comments.ts @@ -0,0 +1,36 @@ +/** + * Shader source without its comments. + * + * A minifier never looks inside a string, and a shader is one: without this, + * every comment of every `.vert`, `.frag` and `.wgsl` file is in the published + * build, and in every game made with it. They were two thirds of the shader + * text. + * + * Used by the build (`scripts/build.ts`) and by the tests (`vitest.config.ts`), + * so that the tests compile the text that ships. + * + * Line breaks are kept, those inside a block comment too: a line of the result + * is the same line of the source file, which is what a shader compiler's error + * message points at. Nothing else is touched: no line is joined to the next (a + * preprocessor directive stays on its own), and no spacing is squeezed. + * @param source - the shader source, GLSL or WGSL + * @returns the source with its `//` and block comments removed + */ +export function stripShaderComments(source: string): string { + // One pass, whichever comment starts first: a `/*` written inside a `//` + // comment opens nothing, and a `//` inside a block comment ends nothing. + // The spaces before a comment go with it. + return source.replace( + /[ \t]*(?:\/\*[\s\S]*?\*\/|\/\/[^\n]*)/g, + (comment: string, offset: number) => { + const lineBreaks = comment.replace(/[^\n]/g, ""); + if (lineBreaks !== "" || !comment.trimStart().startsWith("/*")) { + return lineBreaks; + } + // a block comment on one line: with code after it, the words + // either side of it stay apart + const next = source[offset + comment.length] as string | undefined; + return next === undefined || next === "\n" || next === "\r" ? "" : " "; + }, + ); +} diff --git a/packages/melonjs/tests/shader-comments.spec.js b/packages/melonjs/tests/shader-comments.spec.js new file mode 100644 index 0000000000..bf0db15e0c --- /dev/null +++ b/packages/melonjs/tests/shader-comments.spec.js @@ -0,0 +1,109 @@ +/** + * The shaders are bundled as text, which no minifier reads: their comments + * are taken out when the engine is built (`scripts/build.ts`), by + * `stripShaderComments`. The tests load them through the same function + * (`vitest.config.ts`), so what is compiled here is what ships. + */ +import { describe, expect, it } from "vitest"; +import { stripShaderComments } from "../scripts/strip-shader-comments.ts"; +import meshLitFragment from "../src/video/webgl/shaders/mesh-lit.frag"; +import quadVertex from "../src/video/webgl/shaders/quad.vert"; +import tileLayerFragment from "../src/video/webgl/shaders/tmxlayer-common.frag"; +import meshLitWGSL from "../src/video/webgpu/shaders/mesh-lit.wgsl"; +import quadWGSL from "../src/video/webgpu/shaders/quad.wgsl"; +import tileLayerWGSL from "../src/video/webgpu/shaders/tmxlayer-common.wgsl"; + +describe("stripShaderComments", () => { + it("takes out a line comment, with the spaces before it", () => { + expect(stripShaderComments("float a = 1.0; // one\nfloat b;")).toBe( + "float a = 1.0;\nfloat b;", + ); + }); + + it("takes out a comment that is the whole line, and keeps the line", () => { + expect(stripShaderComments("a;\n\t// note\nb;")).toBe("a;\n\nb;"); + }); + + it("takes out a block comment, and keeps its line breaks", () => { + const source = "a;\n/**\n * two\n * lines\n */\nb;"; + const stripped = stripShaderComments(source); + expect(stripped).toBe("a;\n\n\n\n\nb;"); + // every line of the result is the same line of the source + expect(stripped.split("\n")).toHaveLength(source.split("\n").length); + expect(stripped.split("\n")[5]).toBe("b;"); + }); + + it("does not glue the words either side of a block comment together", () => { + expect(stripShaderComments("int/* count */n;")).toBe("int n;"); + expect(stripShaderComments("int /* count */ n;")).toBe("int n;"); + }); + + it("a `/*` inside a line comment opens nothing", () => { + // taken as a block comment, it would run on to the next `*/` and eat + // the code in between + expect(stripShaderComments("a; // see x/*y\nb;\nc; /* d */\ne;")).toBe( + "a;\nb;\nc;\ne;", + ); + }); + + it("a `//` inside a block comment ends nothing", () => { + expect(stripShaderComments("a; /* http://x // y */ b;\nc;")).toBe( + "a; b;\nc;", + ); + }); + + it("keeps every preprocessor directive on its own line", () => { + const source = [ + "#version 300 es // the version", + "/* precision */", + "precision highp float;", + "#ifdef LIT // optional", + "#define COUNT 4", + "#endif", + ].join("\n"); + expect(stripShaderComments(source).split("\n")).toEqual([ + "#version 300 es", + "", + "precision highp float;", + "#ifdef LIT", + "#define COUNT 4", + "#endif", + ]); + }); + + it("leaves a division, and source with no comment, as they are", () => { + const source = "float h = a / b / 2.0;\nfloat k = a /b;\n"; + expect(stripShaderComments(source)).toBe(source); + expect(stripShaderComments("")).toBe(""); + }); + + it("an unfinished block comment is left, for the compiler to refuse", () => { + expect(stripShaderComments("a; /* never closed\nb;")).toBe( + "a; /* never closed\nb;", + ); + }); +}); + +describe("the shaders the tests compile", () => { + const shaders = { + "quad.vert": quadVertex, + "mesh-lit.frag": meshLitFragment, + "tmxlayer-common.frag": tileLayerFragment, + "quad.wgsl": quadWGSL, + "mesh-lit.wgsl": meshLitWGSL, + "tmxlayer-common.wgsl": tileLayerWGSL, + }; + + for (const [name, source] of Object.entries(shaders)) { + it(`${name} carries no comment`, () => { + expect(typeof source).toBe("string"); + expect(source.length).toBeGreaterThan(100); + expect(source).not.toMatch(/\/\/|\/\*|\*\//); + }); + } + + it("mesh-lit.frag still has the token its batcher fills in", () => { + // the comment that explains `__MAX_LIGHTS__` is gone, its uses are not + expect(meshLitFragment.match(/__MAX_LIGHTS__/g)).toHaveLength(2); + }); +}); diff --git a/packages/melonjs/vitest.config.ts b/packages/melonjs/vitest.config.ts index 2aab41d419..9459ff8022 100644 --- a/packages/melonjs/vitest.config.ts +++ b/packages/melonjs/vitest.config.ts @@ -6,6 +6,7 @@ import { playwright } from "@vitest/browser-playwright"; import { PackageJson } from "type-fest"; import { default as glsl } from "vite-plugin-glsl"; import { defineConfig } from "vitest/config"; +import { stripShaderComments } from "./scripts/strip-shader-comments.ts"; const __dirname = dirname(fileURLToPath(import.meta.url)); @@ -110,7 +111,13 @@ export default defineConfig(() => }, publicDir: resolve(__dirname, "tests/public"), plugins: [ - glsl(), + // the shaders as the build ships them, without their comments + // (see `scripts/build.ts`): the tests compile the same text + glsl({ + onComplete: (shader) => { + return stripShaderComments(shader); + }, + }), { name: "transform-file", transform(src) { From c3cfbd067902eca1a3231e5bb83a2ffdc3b15027 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 23:04:34 +0000 Subject: [PATCH 21/51] Docs: what a normal map needs, and where it is lit The Sprite and TextureAtlas docs said a normal map was "silently ignored" by the Canvas renderer and used by "the WebGL renderer". It is lit on WebGL and WebGPU, and Canvas draws the sprite unlit with a console warning, once, when lights are on. A video is refused with a TypeError; an animated sprite takes its normals from one static sheet laid out like its colour sheet. The alpha of a normal map masks the sprite's shininess, and a matte texel is still shaded by the direction under that alpha. Tests now draw it: from an image file, and from an ImageBitmap made with premultiplyAlpha "none", the highlight follows the alpha and the direction is kept at an alpha of 0. The lighting skill says which sources lose it (a canvas, an ImageBitmap made with the default options, a file whose transparent pixels a tool has cleared). Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- .../melonjs/skills/melonjs-lighting/SKILL.md | 42 +++++- packages/melonjs/src/renderable/sprite.js | 32 ++++- packages/melonjs/src/video/texture/atlas.js | 4 +- packages/melonjs/tests/helpers/png.js | 87 +++++++++++++ .../melonjs/tests/lit_quad_specular.spec.js | 123 ++++++++++++++++++ 5 files changed, 280 insertions(+), 8 deletions(-) create mode 100644 packages/melonjs/tests/helpers/png.js diff --git a/packages/melonjs/skills/melonjs-lighting/SKILL.md b/packages/melonjs/skills/melonjs-lighting/SKILL.md index fe46ba498f..863b12ae50 100644 --- a/packages/melonjs/skills/melonjs-lighting/SKILL.md +++ b/packages/melonjs/skills/melonjs-lighting/SKILL.md @@ -110,6 +110,14 @@ const hero = new Sprite(x, y, { canvas, `ImageBitmap`, a `Texture2d`). Assigning anything else — including an `HTMLVideoElement`, which would freeze on frame 0 — throws a `TypeError`. +It is lit on the GPU renderers, **WebGL and WebGPU**. On Canvas the sprite is +drawn unlit and a warning says so once (see "What needs a GPU backend" below). + +A normal map is a still image, uploaded once. A sprite that **animates** takes +its normals from one static sheet laid out exactly like its colour sheet: the +animation picks the frame, and the same region of both is sampled. There is no +video or per-frame normal source to set up. + How grazing the light is comes from `light.lightHeight`, its height above the sprite plane in the same units as its radius (default `max(radiusX, radiusY) * 0.075`). Lower it for light raking across the surface, which shows the relief @@ -154,7 +162,9 @@ Three things worth knowing: reflective, 0 is dead matte, so one sprite can be a shiny blade with a matte leather grip. A normal map with no alpha detail (the usual case) shines uniformly. Note the corollary: if your normal map already uses alpha for - something, that channel now also decides gloss. + something, that channel now also decides gloss. The mask is in the **normal + map's** alpha, never the colour image's: making the grip transparent there + would hide it, not dull it. - **It accumulates per light.** Each light contributes its own highlight in its own colour, so a sprite between a warm lamp and a cool one carries two distinct glints that move independently. @@ -163,6 +173,32 @@ The highlight takes the light's own colour and is *added* on top of the lit result rather than multiplied into it, which is why a glint blows out toward white on a dark sprite instead of tinting with it. +### A matte texel still needs its direction + +In a normal map the alpha is a material, not a hole. A texel with an alpha of 0 +is matte, and is still shaded by the direction in its RGB. That direction has to +survive all the way to the GPU, and image tools are built to assume the opposite +(that nothing matters under a transparent pixel): + +| the normal map comes from | directions under a low alpha | +|---|---| +| an image file through the loader (a PNG) | **kept**: the engine uploads normal maps with premultiplied alpha off | +| `createImageBitmap(source, { premultiplyAlpha: "none" })` | **kept**: the way to build a masked normal map in code | +| `createImageBitmap(source)`, default options | **wrong** as soon as the alpha is below 255: WebGL uploads a bitmap as it was made, so the directions arrive multiplied by the mask | +| a canvas you drew or `putImageData` into | **lost** at an alpha of 0, and rounded at a low one: a canvas stores its pixels multiplied by their alpha | + +```js +// a masked normal map made in code: from pixels, never through a canvas +const pixels = new ImageData(width, height); +// ... rgb = the direction, a = how much it shines ... +sprite.normalMap = await createImageBitmap(pixels, { premultiplyAlpha: "none" }); +``` + +Before the file reaches the game, the same goes for the pipeline: an optimiser +or a packer that "cleans" or "bleeds" the colour of fully transparent pixels, or +that premultiplies, erases the directions of every matte texel. Export the +normal sheet with those options off, and with the same layout as the colour one. + See it running: [Normal Map example](https://melonjs.github.io/melonJS/examples/#/normal-map). Unlit areas of a normal-mapped sprite render pure black unless you raise @@ -222,6 +258,10 @@ See the `melonjs-3d` skill. | changing `radiusX` / `radiusY` does nothing | everything is sized from the bounds, which `setRadii()` updates and a bare field write does not | | normal-mapped relief looks flat under a light | `lightHeight` is high relative to the radius; lower it for a grazing light | | `TypeError` assigning `normalMap` | not an image-like value (a video element is rejected outright) | +| the whole sprite glints, not just the metal | the normal map is opaque, which is a full mask: paint the matte parts with a lower alpha in the **normal map** | +| `shininess` is set and nothing glints | no `normalMap`, an alpha of 0 over the whole normal map, the light behind the surface, or the Canvas backend | +| the matte part of a sprite (normal alpha 0) is black, or lit from the wrong side | its directions were erased: an optimiser cleared the colour of transparent pixels, or the map came from a canvas or from `createImageBitmap` with its default options. Load the file as it was exported, or build it with `premultiplyAlpha: "none"` | +| an animated sprite's shading does not follow its pose | the normal sheet is not laid out like the colour sheet: same size, same frames in the same places | | lighting misaligned under a 3D camera | the 2D light pass is not projection-aware — use `Light3d` | ## Related skills diff --git a/packages/melonjs/src/renderable/sprite.js b/packages/melonjs/src/renderable/sprite.js index 4cb8ebf631..1b87bbfaf8 100644 --- a/packages/melonjs/src/renderable/sprite.js +++ b/packages/melonjs/src/renderable/sprite.js @@ -46,7 +46,7 @@ export default class Sprite extends Renderable { * @param {number} [settings.flipX] - flip the sprite on the horizontal axis * @param {number} [settings.flipY] - flip the sprite on the vertical axis * @param {string|Vector2d|{x:number,y:number}} [settings.anchorPoint={x:0.5, y:0.5}] - Anchor point to draw the frame at (defaults to the center of the frame). Also accepts the named presets `"center"`, `"top"`, `"bottom"`, `"left"`, `"right"`, `"top-left"`, `"top-right"`, `"bottom-left"`, `"bottom-right"`. For spritesheet atlases the anchor also becomes the cached atlas's per-frame pivot (see {@link TextureAtlas}). - * @param {HTMLImageElement|HTMLCanvasElement|OffscreenCanvas|ImageBitmap|Texture2d|string} [settings.normalMap] - optional normal-map texture used for per-pixel lighting (SpriteIlluminator-style). Same layout/UVs as `settings.image`. When omitted (default), the sprite renders unlit and pays no extra cost. Ignored by the Canvas renderer. Note: `HTMLVideoElement` is intentionally not supported — normal maps encode static surface directions in RGB, and the engine caches the GL texture per image reference (a video would freeze on frame 0). + * @param {HTMLImageElement|HTMLCanvasElement|OffscreenCanvas|ImageBitmap|Texture2d|string} [settings.normalMap] - optional normal-map texture used for per-pixel lighting (SpriteIlluminator-style). Same layout/UVs as `settings.image`. When omitted (default), the sprite renders unlit and pays no extra cost. Lit on the GPU renderers, WebGL and WebGPU. The Canvas renderer cannot light a sprite per pixel: it draws the sprite unlit, and logs one console warning when lights are on (see {@link Sprite#normalMap}). An `HTMLVideoElement` is refused with a `TypeError`: a normal map is uploaded to the GPU once, so a video would stay on its first frame. For animated artwork, use one static normal atlas laid out like the color atlas (see {@link TextureAtlas}). * @param {object} [settings.bodyDef] - declarative, adapter-portable body definition, applied when this sprite is added to a container. Its `shapes` may name a collision shape file preloaded as JSON, paired with `id`. See {@link Renderable#bodyDef} and {@link BodyDefinitionInit} * @param {number} [settings.shininess=0] - specular exponent: how tight this sprite's highlight is, or 0 for none. Needs a `normalMap` — see {@link Sprite#shininess} * @example @@ -162,7 +162,16 @@ export default class Sprite extends Renderable { * have a shiny blade and a matte leather grip; a normal map with no * alpha detail (the usual case) shines uniformly. * - * Ignored by the Canvas renderer. + * That alpha is a material, not coverage: a matte texel (alpha 0) is + * still shaded by the direction in its RGB, which has to reach the + * GPU. It does from an image file, and from an `ImageBitmap` made + * with `premultiplyAlpha: "none"`. It does not from a canvas (which + * stores nothing under an alpha of 0) nor from an `ImageBitmap` made + * with the default options (whose directions arrive multiplied by the + * mask), nor from a file whose transparent pixels a tool has cleared. + * + * Needs a GPU renderer (WebGL or WebGPU), as the normal map does: the + * Canvas renderer draws the sprite unlit (see {@link Sprite#normalMap}). * @type {number} * @default 0 * @see [Normal Map example](https://melonjs.github.io/melonJS/examples/#/normal-map) — three orbs across the @@ -360,7 +369,8 @@ export default class Sprite extends Renderable { } // resolve the optional normal-map paired with this sprite (used by - // the GPU backends' lit pipeline; silently ignored by Canvas). + // the GPU backends' lit pipeline; Canvas draws the sprite unlit, and + // says so once when lights are on). // When the source is a TextureAtlas, prefer its paired normal-map // over an explicit `settings.normalMap` (the atlas drove the layout). if ( @@ -533,9 +543,21 @@ export default class Sprite extends Renderable { * lit pipeline samples this texture for per-pixel lighting using * `Stage._activeLights`. `null` when unlit. * Setting any non-image value (or anything without numeric - * `width`/`height`) throws — assign `null` to clear. + * `width`/`height`) throws — assign `null` to clear. So does a video + * element: a normal map is uploaded to the GPU once, and a video would + * stay on its first frame. A sprite whose animation changes pose takes + * its normals from one static atlas laid out like the color one. + * + * The alpha of a normal map is the mask of the sprite's + * {@link Sprite#shininess}, and the RGB under a low alpha still shades + * the sprite: see there for the sources that keep it. * - * Silently ignored by the Canvas renderer. + * Lit on the GPU renderers, WebGL and WebGPU. The Canvas renderer cannot + * light a sprite per pixel: the sprite is drawn there as it would be + * with no normal map, and the first one drawn while lights are on logs + * a console warning, once. `Light2d` glows and the stage's ambient light + * still draw. For a presentation of your own on Canvas, test + * `renderer.shaderLanguage === null`. * @type {HTMLImageElement|HTMLCanvasElement|OffscreenCanvas|ImageBitmap|null} * @see {@link Sprite#shininess} to add a specular highlight on top * @see [Normal Map example](https://melonjs.github.io/melonJS/examples/#/normal-map) diff --git a/packages/melonjs/src/video/texture/atlas.js b/packages/melonjs/src/video/texture/atlas.js index 136b5a9259..87d0ebe2bb 100644 --- a/packages/melonjs/src/video/texture/atlas.js +++ b/packages/melonjs/src/video/texture/atlas.js @@ -123,7 +123,7 @@ export class TextureAtlas extends Texture2d { /** * @param {object|object[]} atlases - atlas information. See {@link loader.getJSON} * @param {HTMLImageElement|HTMLCanvasElement|OffscreenCanvas|CompressedImage|string|OffscreenCanvas[]|HTMLImageElement[]|HTMLCanvasElement[]|string[]} [src=atlas.meta.image] - Image source - * @param {boolean|object} [options] - either a boolean (legacy `cache` flag — `false` disables `TextureCache` registration; default behavior is to cache) or an options object `{ cache?: boolean, normalMap?: HTMLImageElement|HTMLCanvasElement|OffscreenCanvas|ImageBitmap|string }`. When `normalMap` is provided, the atlas exposes a paired normal-map texture sharing the same UVs as the color texture (used by the WebGL renderer's lit pipeline). `HTMLVideoElement` is intentionally not supported as a normal map (would freeze on frame 0 due to per-image GL texture caching). + * @param {boolean|object} [options] - either a boolean (legacy `cache` flag — `false` disables `TextureCache` registration; default behavior is to cache) or an options object `{ cache?: boolean, normalMap?: HTMLImageElement|HTMLCanvasElement|OffscreenCanvas|ImageBitmap|string }`. When `normalMap` is provided, the atlas exposes a paired normal-map texture sharing the same UVs as the color texture, used for per-pixel lighting by the GPU renderers, WebGL and WebGPU (the Canvas renderer draws its sprites unlit; see {@link Sprite#normalMap}). An `HTMLVideoElement` is refused with a `TypeError`: a normal map is uploaded to the GPU once, so a video would stay on its first frame. * @example * // create a texture atlas from a JSON Object * game.texture = new me.TextureAtlas( @@ -179,7 +179,7 @@ export class TextureAtlas extends Texture2d { /** * paired normal-map source(s), keyed identically to `sources`. * Populated from the constructor's `options.normalMap`. Used by - * the WebGL renderer's lit pipeline for per-pixel lighting. + * the GPU renderers' lit pipeline for per-pixel lighting. * @type {Map} * @ignore * @internal diff --git a/packages/melonjs/tests/helpers/png.js b/packages/melonjs/tests/helpers/png.js new file mode 100644 index 0000000000..727c9f5506 --- /dev/null +++ b/packages/melonjs/tests/helpers/png.js @@ -0,0 +1,87 @@ +/** + * A PNG made from pixels, with no canvas in between. + * + * A 2D canvas stores its pixels multiplied by their alpha: what is drawn into + * one with an alpha of 0 comes back black, and with a low alpha comes back + * rounded. An image whose alpha is not coverage (a normal map carries a gloss + * mask there) cannot be built through one. This writes the bytes of a PNG + * file directly, as an artist's tool would, and decodes it the way the loader + * does: into an `HTMLImageElement`. + */ + +const CRC_TABLE = (() => { + 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 crc32 = (bytes) => { + let c = 0xffffffff; + for (const byte of bytes) { + c = CRC_TABLE[(c ^ byte) & 0xff] ^ (c >>> 8); + } + return (c ^ 0xffffffff) >>> 0; +}; + +const chunk = (type, body) => { + const out = new Uint8Array(12 + body.length); + const view = new DataView(out.buffer); + view.setUint32(0, body.length); + for (let i = 0; i < 4; i++) { + out[4 + i] = type.charCodeAt(i); + } + out.set(body, 8); + view.setUint32(8 + body.length, crc32(out.subarray(4, 8 + body.length))); + return out; +}; + +/** + * Encode pixels as an 8-bit RGBA PNG, straight alpha, and decode it. + * @param {ImageData} imageData - the pixels, as they are to be in the file + * @returns {Promise} the decoded image + */ +export async function pngImage(imageData) { + const { width, height, data } = imageData; + const stride = 1 + width * 4; + // each row: a filter byte (0, none), then its pixels + const raw = new Uint8Array(height * stride); + for (let y = 0; y < height; y++) { + raw.set(data.subarray(y * width * 4, (y + 1) * width * 4), y * stride + 1); + } + const deflated = new Uint8Array( + await new Response( + new Blob([raw]).stream().pipeThrough(new CompressionStream("deflate")), + ).arrayBuffer(), + ); + const header = new Uint8Array(13); + const view = new DataView(header.buffer); + view.setUint32(0, width); + view.setUint32(4, height); + // 8 bits a channel, color type 6 (RGBA), default compression and filter, + // not interlaced + header.set([8, 6, 0, 0, 0], 8); + const blob = new Blob( + [ + new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]), + chunk("IHDR", header), + chunk("IDAT", deflated), + chunk("IEND", new Uint8Array(0)), + ], + { type: "image/png" }, + ); + const url = URL.createObjectURL(blob); + const image = new Image(); + image.src = url; + try { + await image.decode(); + } finally { + URL.revokeObjectURL(url); + } + return image; +} diff --git a/packages/melonjs/tests/lit_quad_specular.spec.js b/packages/melonjs/tests/lit_quad_specular.spec.js index e7a85c0e4b..8e0847aa94 100644 --- a/packages/melonjs/tests/lit_quad_specular.spec.js +++ b/packages/melonjs/tests/lit_quad_specular.spec.js @@ -2,6 +2,7 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { boot, Sprite } from "../src/index.js"; import { buildLitMultiTextureFragment } from "../src/video/webgl/shaders/multitexture-lit.js"; import litQuadVertex from "../src/video/webgl/shaders/quad-multi-lit.vert?raw"; +import { pngImage } from "./helpers/png.js"; import { getWebGLRenderer, releaseWebGLRenderer, @@ -216,4 +217,126 @@ describe("2D specular", () => { expect(fragment).toContain("in float vShininess;"); }); }); + + /** + * The mask, drawn: one grey sprite, 16 pixels across, whose normal map + * tilts every texel toward the right, lit by one light, and the red of + * its middle read back. The light on the right is on the side the + * surface faces; on the left, behind it. + */ + describe("the normal map's alpha, in pixels", () => { + const SPRITE = 16; + // n = normalize(0.7, 0, 0.7), encoded + const TILT = [217, 128, 217]; + let diffuse; + + const pixels = (alpha) => { + const data = new ImageData(SPRITE, SPRITE); + for (let i = 0; i < SPRITE * SPRITE; i++) { + data.data.set([...TILT, alpha], i * 4); + } + return data; + }; + + /** the red of the sprite's middle, lit from `lightX` */ + const lit = (normalMap, lightX, shininess = 0) => { + const gl = renderer.gl; + const litQuad = renderer.batchers.get("litQuad"); + const lights = renderer.activeLightCount; + try { + renderer.activeLightCount = 1; + renderer.currentNormalMap = normalMap; + renderer.currentShininess = shininess; + litQuad.setLightUniforms({ + positions: new Float32Array([lightX, 32, 80, 1]), + colors: new Float32Array([1, 1, 1]), + heights: new Float32Array([12]), + count: 1, + ambient: [0, 0, 0], + }); + renderer.clearColor("#000000ff"); + renderer.drawImage(diffuse, 24, 24); + renderer.flush(); + const out = new Uint8Array(4); + gl.readPixels(32, 64 - 1 - 32, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, out); + return out[0]; + } finally { + renderer.activeLightCount = lights; + renderer.currentNormalMap = null; + renderer.currentShininess = 0; + litQuad.setLightUniforms({ + positions: new Float32Array(4), + colors: new Float32Array(3), + count: 0, + ambient: [0, 0, 0], + }); + } + }; + const RIGHT = 70; + const LEFT = -6; + + beforeAll(() => { + diffuse = document.createElement("canvas"); + diffuse.width = diffuse.height = SPRITE; + const context = diffuse.getContext("2d"); + context.fillStyle = "#808080"; + context.fillRect(0, 0, SPRITE, SPRITE); + }); + + it("a normal map from an image file: the alpha scales the highlight, and nothing else", async (ctx) => { + requireWebGL(ctx, renderer); + const shiny = await pngImage(pixels(255)); + const half = await pngImage(pixels(128)); + const matte = await pngImage(pixels(0)); + + // with no shininess the alpha changes nothing: the diffuse + // shading is the surface's direction, the same in all three + const flat = lit(shiny, RIGHT); + expect(flat).toBeGreaterThan(10); + expect(lit(half, RIGHT)).toBe(flat); + expect(lit(matte, RIGHT)).toBe(flat); + + // with it, the highlight is added in proportion to the alpha + const full = lit(shiny, RIGHT, 8); + const partly = lit(half, RIGHT, 8); + expect(full).toBeGreaterThan(flat + 20); + expect(partly).toBeGreaterThan(flat + 10); + expect(partly).toBeLessThan(full - 10); + // half the mask, half the highlight + expect((partly - flat) / (full - flat)).toBeCloseTo(128 / 255, 1); + // and a matte texel has none at all + expect(lit(matte, RIGHT, 8)).toBe(flat); + }); + + it("a matte texel keeps the direction it faces", async (ctx) => { + requireWebGL(ctx, renderer); + // Alpha 0 here is a material, not a hole: the direction under it + // still has to reach the shader, or the matte part of a sprite is + // lit from the wrong side. Normal maps are uploaded with + // premultiplied alpha off for that. + const matte = await pngImage(pixels(0)); + expect(lit(matte, RIGHT)).toBeGreaterThan(10); + expect(lit(matte, LEFT)).toBe(0); + // as the same surface does with a full mask + const shiny = await pngImage(pixels(255)); + expect(lit(matte, RIGHT)).toBe(lit(shiny, RIGHT)); + expect(lit(shiny, LEFT)).toBe(0); + }); + + it('an ImageBitmap made with `premultiplyAlpha: "none"` does the same', async (ctx) => { + requireWebGL(ctx, renderer); + // the way to make a masked normal map in code: a canvas cannot + // hold a direction under an alpha of 0, and a bitmap made with + // the default options has its directions multiplied by the mask + const options = { premultiplyAlpha: "none" }; + const shiny = await createImageBitmap(pixels(255), options); + const matte = await createImageBitmap(pixels(0), options); + const flat = lit(shiny, RIGHT); + expect(flat).toBeGreaterThan(10); + expect(lit(matte, RIGHT)).toBe(flat); + expect(lit(matte, LEFT)).toBe(0); + expect(lit(shiny, RIGHT, 8)).toBeGreaterThan(flat + 20); + expect(lit(matte, RIGHT, 8)).toBe(flat); + }); + }); }); From 43bd0f18096309c00f7cd2c5cc5839343e06679a Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 00:06:29 +0000 Subject: [PATCH 22/51] Dependencies: update the development tools flagged by the security audit pnpm audit reported 46 known vulnerabilities (1 critical, 24 high), all in development tools or in the private examples app; none in a dependency of a published package. It now reports none. Raised: vite 8.1.5 to 8.3.8, vitest and @vitest/browser 4.1.11 to 4.1.12, serve to 14.2.8, react-router-dom to 7.18.6. Overrides raised for shell-quote (the critical one, through concurrently), markdown-it and react-router, and added for minimatch, brace-expansion and fast-uri, which their parents have not picked up yet. eslint and typescript-eslint stay where they were: their newer versions add rules that flag 25 places in the engine, which is a change of its own. Only their minimatch is moved, by override. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- package.json | 25 +- packages/capacitor-plugin/package.json | 2 +- packages/debug-plugin/package.json | 2 +- packages/examples/package.json | 4 +- packages/gamepad-plugin/package.json | 4 +- packages/matter-adapter/package.json | 2 +- packages/melonjs/package.json | 4 +- packages/pathfinding-plugin/package.json | 4 +- packages/planck-adapter/package.json | 2 +- packages/rapier2d-adapter/package.json | 2 +- packages/rapier3d-adapter/package.json | 2 +- packages/spine-plugin/package.json | 2 +- packages/tiled-inflate-plugin/package.json | 2 +- pnpm-lock.yaml | 727 ++++++++++----------- 14 files changed, 362 insertions(+), 422 deletions(-) diff --git a/package.json b/package.json index e9e5159e54..56279f7b3c 100644 --- a/package.json +++ b/package.json @@ -33,8 +33,8 @@ "@biomejs/biome": "2.5.9", "@eslint/js": "^10.0.1", "@types/node": "^25.6.0", - "@vitest/browser": "^4.1.11", - "@vitest/browser-playwright": "^4.1.11", + "@vitest/browser": "^4.1.12", + "@vitest/browser-playwright": "^4.1.12", "eslint": "^10.8.1", "eslint-plugin-jsdoc": "^63.2.2", "globals": "^17.11.0", @@ -44,7 +44,7 @@ "turbo": "^2.10.11", "typescript": "^6.0.2", "typescript-eslint": "^8.67.0", - "vitest": "^4.1.11" + "vitest": "^4.1.12" }, "devDependencies": { "eslint-plugin-react-refresh": "^0.5.4", @@ -58,17 +58,20 @@ ], "overrides": { "minimatch@<4.0.0": "3.1.4", - "minimatch@>=9.0.0 <9.0.7": "9.0.7", + "minimatch@>=7.0.0 <11.0.1": "^11.0.9", + "brace-expansion@<1.1.21": "^1.1.22", + "brace-expansion@>=4.0.0 <5.0.12": "^5.0.13", + "fast-uri@<3.1.9": "^3.1.9", "ajv@<6.14.0": "6.14.0", - "vite": "8.1.5", + "vite": "8.3.8", "esbuild": "0.28.1", "ws": "^8.21.0", - "shell-quote": "^1.9.0", - "markdown-it": "^14.2.0", - "react-router": "^7.15.1", - "vitest": "^4.1.11", - "@vitest/browser": "^4.1.11", - "@vitest/browser-playwright": "^4.1.11" + "shell-quote": "^1.11.0", + "markdown-it": "^14.3.3", + "react-router": "^7.18.2", + "vitest": "^4.1.12", + "@vitest/browser": "^4.1.12", + "@vitest/browser-playwright": "^4.1.12" } } } diff --git a/packages/capacitor-plugin/package.json b/packages/capacitor-plugin/package.json index 1928f4bdfc..63d0706815 100644 --- a/packages/capacitor-plugin/package.json +++ b/packages/capacitor-plugin/package.json @@ -69,7 +69,7 @@ "tsconfig": "workspace:*", "tsx": "^4.23.1", "typescript": "^6.0.2", - "vitest": "^4.1.11" + "vitest": "^4.1.12" }, "scripts": { "dev": "concurrently --raw \"pnpm build:watch\" \"pnpm tsc:watch\"", diff --git a/packages/debug-plugin/package.json b/packages/debug-plugin/package.json index 07db208ff6..b647bbc04e 100644 --- a/packages/debug-plugin/package.json +++ b/packages/debug-plugin/package.json @@ -49,7 +49,7 @@ "tsconfig": "workspace:*", "tsx": "^4.23.1", "typescript": "^6.0.2", - "vitest": "^4.1.10" + "vitest": "^4.1.12" }, "scripts": { "dev": "concurrently --raw \"pnpm build:watch\" \"pnpm tsc:watch\"", diff --git a/packages/examples/package.json b/packages/examples/package.json index 0458378086..7036971f18 100644 --- a/packages/examples/package.json +++ b/packages/examples/package.json @@ -27,9 +27,9 @@ "melonjs": "workspace:^", "react": "^19.2.8", "react-dom": "^19.2.8", - "react-router-dom": "^7.18.1", + "react-router-dom": "^7.18.6", "tsconfig": "workspace:^", "typescript": "^6.0.2", - "vite": "8.1.5" + "vite": "8.3.8" } } diff --git a/packages/gamepad-plugin/package.json b/packages/gamepad-plugin/package.json index c2c20f26a3..67368c81c2 100644 --- a/packages/gamepad-plugin/package.json +++ b/packages/gamepad-plugin/package.json @@ -56,8 +56,8 @@ "tsconfig": "workspace:*", "tsx": "^4.23.1", "typescript": "^6.0.2", - "vite": "8.1.5", - "vitest": "^4.1.11" + "vite": "8.3.8", + "vitest": "^4.1.12" }, "scripts": { "dev": "concurrently --raw \"pnpm build:watch\" \"pnpm tsc:watch\"", diff --git a/packages/matter-adapter/package.json b/packages/matter-adapter/package.json index 84545c19d2..fa191d6b8e 100644 --- a/packages/matter-adapter/package.json +++ b/packages/matter-adapter/package.json @@ -55,7 +55,7 @@ "tsconfig": "workspace:*", "tsx": "^4.23.1", "typescript": "^6.0.2", - "vitest": "^4.1.10" + "vitest": "^4.1.12" }, "scripts": { "dev": "concurrently --raw \"pnpm build:watch\" \"pnpm tsc:watch\"", diff --git a/packages/melonjs/package.json b/packages/melonjs/package.json index bf0109f0b9..5f66798de6 100644 --- a/packages/melonjs/package.json +++ b/packages/melonjs/package.json @@ -59,13 +59,13 @@ "concurrently": "^9.2.1", "del-cli": "^7.0.0", "esbuild": "^0.27.3", - "serve": "^14.2.6", + "serve": "^14.2.8", "tsconfig": "workspace:^", "tsx": "^4.23.1", "type-fest": "^5.8.0", "typedoc": "^0.28.20", "typescript": "^6.0.2", - "vite": "8.1.5", + "vite": "8.3.8", "vite-plugin-glsl": "^1.6.1" }, "scripts": { diff --git a/packages/pathfinding-plugin/package.json b/packages/pathfinding-plugin/package.json index 9b894c5672..52ff03231c 100644 --- a/packages/pathfinding-plugin/package.json +++ b/packages/pathfinding-plugin/package.json @@ -54,8 +54,8 @@ "tsconfig": "workspace:*", "tsx": "^4.23.1", "typescript": "^6.0.2", - "vite": "8.1.5", - "vitest": "^4.1.11" + "vite": "8.3.8", + "vitest": "^4.1.12" }, "scripts": { "dev": "concurrently --raw \"pnpm build:watch\" \"pnpm tsc:watch\"", diff --git a/packages/planck-adapter/package.json b/packages/planck-adapter/package.json index a4a61cdcf9..cc029e8a44 100644 --- a/packages/planck-adapter/package.json +++ b/packages/planck-adapter/package.json @@ -57,7 +57,7 @@ "tsconfig": "workspace:*", "tsx": "^4.23.1", "typescript": "^6.0.2", - "vitest": "^4.1.10" + "vitest": "^4.1.12" }, "scripts": { "dev": "concurrently --raw \"pnpm build:watch\" \"pnpm tsc:watch\"", diff --git a/packages/rapier2d-adapter/package.json b/packages/rapier2d-adapter/package.json index df588dfdd2..561d1b5b1f 100644 --- a/packages/rapier2d-adapter/package.json +++ b/packages/rapier2d-adapter/package.json @@ -56,7 +56,7 @@ "tsconfig": "workspace:*", "tsx": "^4.23.1", "typescript": "^6.0.2", - "vitest": "^4.1.10" + "vitest": "^4.1.12" }, "scripts": { "dev": "concurrently --raw \"pnpm build:watch\" \"pnpm tsc:watch\"", diff --git a/packages/rapier3d-adapter/package.json b/packages/rapier3d-adapter/package.json index fe4e11dcae..a096239c4a 100644 --- a/packages/rapier3d-adapter/package.json +++ b/packages/rapier3d-adapter/package.json @@ -56,7 +56,7 @@ "tsconfig": "workspace:*", "tsx": "^4.23.1", "typescript": "^6.0.2", - "vitest": "^4.1.10" + "vitest": "^4.1.12" }, "scripts": { "dev": "concurrently --raw \"pnpm build:watch\" \"pnpm tsc:watch\"", diff --git a/packages/spine-plugin/package.json b/packages/spine-plugin/package.json index 891fd2fac7..cfea3b9097 100644 --- a/packages/spine-plugin/package.json +++ b/packages/spine-plugin/package.json @@ -58,7 +58,7 @@ "tsconfig": "workspace:*", "tsx": "^4.23.1", "typescript": "^6.0.3", - "vitest": "^4.1.11" + "vitest": "^4.1.12" }, "scripts": { "dev": "concurrently --raw \"pnpm build:watch\" \"pnpm tsc:watch\"", diff --git a/packages/tiled-inflate-plugin/package.json b/packages/tiled-inflate-plugin/package.json index b833a20f22..6a1496d7a4 100644 --- a/packages/tiled-inflate-plugin/package.json +++ b/packages/tiled-inflate-plugin/package.json @@ -51,7 +51,7 @@ "tsconfig": "workspace:*", "tsx": "^4.23.1", "typescript": "^6.0.2", - "vitest": "^4.1.11" + "vitest": "^4.1.12" }, "scripts": { "build": "tsx scripts/build.ts && pnpm types", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 2a8c8a9fb7..d87b25743f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -6,17 +6,20 @@ settings: overrides: minimatch@<4.0.0: 3.1.4 - minimatch@>=9.0.0 <9.0.7: 9.0.7 + minimatch@>=7.0.0 <11.0.1: ^11.0.9 + brace-expansion@<1.1.21: ^1.1.22 + brace-expansion@>=4.0.0 <5.0.12: ^5.0.13 + fast-uri@<3.1.9: ^3.1.9 ajv@<6.14.0: 6.14.0 - vite: 8.1.5 + vite: 8.3.8 esbuild: 0.28.1 ws: ^8.21.0 - shell-quote: ^1.9.0 - markdown-it: ^14.2.0 - react-router: ^7.15.1 - vitest: ^4.1.11 - '@vitest/browser': ^4.1.11 - '@vitest/browser-playwright': ^4.1.11 + shell-quote: ^1.11.0 + markdown-it: ^14.3.3 + react-router: ^7.18.2 + vitest: ^4.1.12 + '@vitest/browser': ^4.1.12 + '@vitest/browser-playwright': ^4.1.12 importers: @@ -32,11 +35,11 @@ importers: specifier: ^25.6.0 version: 25.6.2 '@vitest/browser': - specifier: ^4.1.11 - version: 4.1.11(vite@8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0))(vitest@4.1.11) + specifier: ^4.1.12 + version: 4.1.12(vite@8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0))(vitest@4.1.12) '@vitest/browser-playwright': - specifier: ^4.1.11 - version: 4.1.11(playwright@1.62.1)(vite@8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0))(vitest@4.1.11) + specifier: ^4.1.12 + version: 4.1.12(playwright@1.62.1)(vite@8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0))(vitest@4.1.12) eslint: specifier: ^10.8.1 version: 10.8.1 @@ -65,8 +68,8 @@ importers: specifier: ^8.67.0 version: 8.67.0(eslint@10.8.1)(typescript@6.0.3) vitest: - specifier: ^4.1.11 - version: 4.1.11(@types/node@25.6.2)(@vitest/browser-playwright@4.1.11)(vite@8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0)) + specifier: ^4.1.12 + version: 4.1.12(@types/node@25.6.2)(@vitest/browser-playwright@4.1.12)(vite@8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0)) devDependencies: eslint-plugin-react-refresh: specifier: ^0.5.4 @@ -105,8 +108,8 @@ importers: specifier: ^6.0.2 version: 6.0.3 vitest: - specifier: ^4.1.11 - version: 4.1.11(@types/node@25.6.2)(@vitest/browser-playwright@4.1.11)(vite@8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0)) + specifier: ^4.1.12 + version: 4.1.12(@types/node@25.6.2)(@vitest/browser-playwright@4.1.12)(vite@8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0)) packages/create-melonjs: {} @@ -131,8 +134,8 @@ importers: specifier: ^6.0.2 version: 6.0.3 vitest: - specifier: ^4.1.11 - version: 4.1.11(@types/node@25.6.2)(@vitest/browser-playwright@4.1.11)(vite@8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0)) + specifier: ^4.1.12 + version: 4.1.12(@types/node@25.6.2)(@vitest/browser-playwright@4.1.12)(vite@8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0)) packages/examples: dependencies: @@ -171,7 +174,7 @@ importers: version: 19.2.3(@types/react@19.2.17) '@vitejs/plugin-react': specifier: ^6.0.4 - version: 6.0.4(vite@8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0)) + version: 6.0.4(vite@8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0)) ace-builds: specifier: ^1.44.0 version: 1.44.0 @@ -185,8 +188,8 @@ importers: specifier: ^19.2.8 version: 19.2.8(react@19.2.8) react-router-dom: - specifier: ^7.18.1 - version: 7.18.1(react-dom@19.2.8(react@19.2.8))(react@19.2.8) + specifier: ^7.18.6 + version: 7.18.6(react-dom@19.2.8(react@19.2.8))(react@19.2.8) tsconfig: specifier: workspace:^ version: link:../tsconfig @@ -194,8 +197,8 @@ importers: specifier: ^6.0.2 version: 6.0.3 vite: - specifier: 8.1.5 - version: 8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0) + specifier: 8.3.8 + version: 8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0) packages/gamepad-plugin: devDependencies: @@ -221,11 +224,11 @@ importers: specifier: ^6.0.2 version: 6.0.3 vite: - specifier: 8.1.5 - version: 8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0) + specifier: 8.3.8 + version: 8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0) vitest: - specifier: ^4.1.11 - version: 4.1.11(@types/node@25.6.2)(@vitest/browser-playwright@4.1.11)(vite@8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0)) + specifier: ^4.1.12 + version: 4.1.12(@types/node@25.6.2)(@vitest/browser-playwright@4.1.12)(vite@8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0)) packages/matter-adapter: dependencies: @@ -258,8 +261,8 @@ importers: specifier: ^6.0.2 version: 6.0.3 vitest: - specifier: ^4.1.11 - version: 4.1.11(@types/node@25.6.2)(@vitest/browser-playwright@4.1.11)(vite@8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0)) + specifier: ^4.1.12 + version: 4.1.12(@types/node@25.6.2)(@vitest/browser-playwright@4.1.12)(vite@8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0)) packages/melonjs: devDependencies: @@ -276,8 +279,8 @@ importers: specifier: 0.28.1 version: 0.28.1 serve: - specifier: ^14.2.6 - version: 14.2.6 + specifier: ^14.2.8 + version: 14.2.8 tsconfig: specifier: workspace:^ version: link:../tsconfig @@ -294,11 +297,11 @@ importers: specifier: ^6.0.2 version: 6.0.3 vite: - specifier: 8.1.5 - version: 8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0) + specifier: 8.3.8 + version: 8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0) vite-plugin-glsl: specifier: ^1.6.1 - version: 1.6.1(esbuild@0.28.1)(vite@8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0)) + version: 1.6.1(esbuild@0.28.1)(vite@8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0)) packages/pathfinding-plugin: devDependencies: @@ -324,11 +327,11 @@ importers: specifier: ^6.0.2 version: 6.0.3 vite: - specifier: 8.1.5 - version: 8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0) + specifier: 8.3.8 + version: 8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0) vitest: - specifier: ^4.1.11 - version: 4.1.11(@types/node@25.6.2)(@vitest/browser-playwright@4.1.11)(vite@8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0)) + specifier: ^4.1.12 + version: 4.1.12(@types/node@25.6.2)(@vitest/browser-playwright@4.1.12)(vite@8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0)) packages/planck-adapter: dependencies: @@ -361,8 +364,8 @@ importers: specifier: ^6.0.2 version: 6.0.3 vitest: - specifier: ^4.1.11 - version: 4.1.11(@types/node@25.6.2)(@vitest/browser-playwright@4.1.11)(vite@8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0)) + specifier: ^4.1.12 + version: 4.1.12(@types/node@25.6.2)(@vitest/browser-playwright@4.1.12)(vite@8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0)) packages/rapier2d-adapter: dependencies: @@ -389,8 +392,8 @@ importers: specifier: ^6.0.2 version: 6.0.3 vitest: - specifier: ^4.1.11 - version: 4.1.11(@types/node@25.6.2)(@vitest/browser-playwright@4.1.11)(vite@8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0)) + specifier: ^4.1.12 + version: 4.1.12(@types/node@25.6.2)(@vitest/browser-playwright@4.1.12)(vite@8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0)) packages/rapier3d-adapter: dependencies: @@ -417,8 +420,8 @@ importers: specifier: ^6.0.2 version: 6.0.3 vitest: - specifier: ^4.1.11 - version: 4.1.11(@types/node@25.6.2)(@vitest/browser-playwright@4.1.11)(vite@8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0)) + specifier: ^4.1.12 + version: 4.1.12(@types/node@25.6.2)(@vitest/browser-playwright@4.1.12)(vite@8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0)) packages/spine-plugin: dependencies: @@ -451,8 +454,8 @@ importers: specifier: ^6.0.3 version: 6.0.3 vitest: - specifier: ^4.1.11 - version: 4.1.11(@types/node@25.6.2)(@vitest/browser-playwright@4.1.11)(vite@8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0)) + specifier: ^4.1.12 + version: 4.1.12(@types/node@25.6.2)(@vitest/browser-playwright@4.1.12)(vite@8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0)) packages/tiled-inflate-plugin: dependencies: @@ -479,8 +482,8 @@ importers: specifier: ^6.0.2 version: 6.0.3 vitest: - specifier: ^4.1.11 - version: 4.1.11(@types/node@25.6.2)(@vitest/browser-playwright@4.1.11)(vite@8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0)) + specifier: ^4.1.12 + version: 4.1.12(@types/node@25.6.2)(@vitest/browser-playwright@4.1.12)(vite@8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0)) packages/tsconfig: {} @@ -570,14 +573,14 @@ packages: '@dimforge/rapier3d-compat@0.21.0': resolution: {integrity: sha512-tCl1HPGwOhn5aCQbgqWbOH+Nx/5fnr3IPAnzQuR7zIhC/raqi2yxC6LhvZqjdI2El5hQgY5RDAwDrAjAi2FdPA==} - '@emnapi/core@1.11.1': - resolution: {integrity: sha512-RSvbQmHzdKzNsLYa/wHrbc3KN4sYLKAdPZxqiM2HATqv/SBk2/ENSHpvXGaLOMcsAyz0poEGqkmmKYG3OWiJEQ==} + '@emnapi/core@2.0.0-beta.2': + resolution: {integrity: sha512-MzCVoWtcg4Pm2B3je5mMvYMvj3MmBKw+fU7vbsJc9/iT8ip6/eYIHo/Dsm/mr+wsHB6SEyJDuxB09Yy6r/8+4A==} - '@emnapi/runtime@1.11.1': - resolution: {integrity: sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw==} + '@emnapi/runtime@2.0.0-beta.2': + resolution: {integrity: sha512-JcrSPzPvZuNZvJqPTF9Fw25LbOJ8avzFVlaf2grmH4Cku0oGP47tRgqPZadcfj3YoZMHkFVnCYFbQM8I+i5QEw==} - '@emnapi/wasi-threads@1.2.2': - resolution: {integrity: sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA==} + '@emnapi/wasi-threads@2.2.0': + resolution: {integrity: sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==} '@es-joy/jsdoccomment@0.90.0': resolution: {integrity: sha512-51x9KxyTAN6guZOCd+lmcDdkhgdMdP/6iMMtg9dyhCWDc3+iSUyoB7f/9WAM/yGHmGFq25Vd6bXRR7CZcB+tog==} @@ -814,14 +817,18 @@ packages: resolution: {integrity: sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==} engines: {node: '>=18.18'} + '@isaacs/nonrecursive-glob-match@1.1.0': + resolution: {integrity: sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==} + '@jridgewell/sourcemap-codec@1.5.5': resolution: {integrity: sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==} - '@napi-rs/wasm-runtime@1.1.6': - resolution: {integrity: sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg==} + '@napi-rs/wasm-runtime@1.2.6': + resolution: {integrity: sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==} + engines: {node: ^20.19.0 || ^22.13.0 || >=23.5.0} peerDependencies: - '@emnapi/core': ^1.7.1 - '@emnapi/runtime': ^1.7.1 + '@emnapi/core': ^1.7.1 || 2.0.0-beta.2 + '@emnapi/runtime': ^1.7.1 || 2.0.0-beta.2 '@nodelib/fs.scandir@2.1.5': resolution: {integrity: sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==} @@ -835,103 +842,109 @@ packages: resolution: {integrity: sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==} engines: {node: '>= 8'} - '@oxc-project/types@0.139.0': - resolution: {integrity: sha512-r9gHphtCs+1M7J0pw6Sn/hh/Wpa/iQrOOkrNAlVLF/gHq+/CJmHIWKKUUhdWjcD6CIa8idarspCsASiXCXvFUw==} + '@oxc-project/types@0.156.0': + resolution: {integrity: sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==} '@polka/url@1.0.0-next.29': resolution: {integrity: sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww==} - '@rolldown/binding-android-arm64@1.1.5': - resolution: {integrity: sha512-lZg8fqIv2v7FF237bwMgzGZEJvGL79/s5knJ/i6FmsGF4XXlzccZ4jb+TrFIxtSSxFtIpdsgrPZeMk1I9AFcyQ==} + '@rolldown/binding-android-arm-eabi@1.2.19': + resolution: {integrity: sha512-e+Ebe0WT+9tbXmNKPIiC8YrWAHYwug3m6i4p3rZGGulfZri1jtI4HslT+OZnFf/OIHowWF71DTlHwXBP2SiA7A==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [android] + + '@rolldown/binding-android-arm64@1.2.19': + resolution: {integrity: sha512-hOombrTJ+szt2ciEzS7oCA78lMPBgF5UMQWCJIyNfnrI7GLl8HYoFqCnpL2gcPOaXMqryGCU5ExdQKyDDcC+yA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [android] - '@rolldown/binding-darwin-arm64@1.1.5': - resolution: {integrity: sha512-51Bnx9pNiMRKSUNtBfySkNJ9vMU9Hh3I1ozDd6gyPPYzaXCfnptUcEZxXGYFn+ul2dtcMUiqGR1Yai2K10uoTw==} + '@rolldown/binding-darwin-arm64@1.2.19': + resolution: {integrity: sha512-XoMA2pwCKGTQzUjPgtRwkedH4WmXhdIPKT6l6oOxd1PUbNodGI6DcBekgN7EC//+x3pfBYX/qL1gNmZAqivw5g==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [darwin] - '@rolldown/binding-darwin-x64@1.1.5': - resolution: {integrity: sha512-Tm+gbfC0aHu1tBA/JvKQh32S0K6YgCHkiAF4/W6xX0K0RmNuc94VeK419dJoE65R5aRxmo+noZQSWrAMF6yb6g==} + '@rolldown/binding-darwin-x64@1.2.19': + resolution: {integrity: sha512-zo8EsSSwMZCY/e+fRnGaX02YGgvJD0yvhNi/9hpGPA2MJ9ZF8dPCw75UGfpI6OpQ/myR/dIYmogRvqiZD0TrXg==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [darwin] - '@rolldown/binding-freebsd-x64@1.1.5': - resolution: {integrity: sha512-JMzDKCCXq93YccG5gz3hvOs1oXRKAf0XYpfOS88e+wZrC8Iugj6j68867vrYZkvpDDpKn/KoKORThmchMpF6TA==} + '@rolldown/binding-freebsd-x64@1.2.19': + resolution: {integrity: sha512-O8ISAOfI1nj7AuBPd30FSF47z7f7lzlk5poQVGgiikvQuGEBFYvW8ki+UEnT+YJPnNGjQzn304klt4O9FUE7mA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [freebsd] - '@rolldown/binding-linux-arm-gnueabihf@1.1.5': - resolution: {integrity: sha512-uML21j2K5TfPGutKxub+M+nLjZIrWjXQ5Grx4lCe/nimTj9B4L63zHpjXLl4y0L3mcm2htEQIb06oCG/szerNw==} + '@rolldown/binding-linux-arm-gnueabihf@1.2.19': + resolution: {integrity: sha512-/lYCba5NO0yq4S0jGMH8QTBtkvQxoXjoQWzF5BcWp9MjB9jxVRD1GQDNofkVjcOj30DWyhLIN/4Oe60JKzaONw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm] os: [linux] - '@rolldown/binding-linux-arm64-gnu@1.1.5': - resolution: {integrity: sha512-navSiuTMogvnQoZoM/v+l3ZWo50/NTwSHSzheABx/RCnmUPaKwq9qSo4Br2OYRs21+Fz8uFqITZM3H4opOB0/Q==} + '@rolldown/binding-linux-arm64-gnu@1.2.19': + resolution: {integrity: sha512-pm/apFMBnSbFb3O6nG5pHO1iqHhZrjGDFEjSm+ot9J17XXPvH9L90y5h+jgfHCE+Qdlsvy8qKEcU4VKxgjD+vA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [linux] libc: [glibc] - '@rolldown/binding-linux-arm64-musl@1.1.5': - resolution: {integrity: sha512-lAryqH7IteztmCXQXk0etKj4wBQ7Gx5S6LjKhsgp9zb8I5bsuvU/2llH1hDQcjsFeqIsovMVN339/8pUDDBXxA==} + '@rolldown/binding-linux-arm64-musl@1.2.19': + resolution: {integrity: sha512-K1SmQp3FFichn8oqrNIwvFoZ5wcvjC7goBzpaMNvLf9FZc+QB/QvLmnpJZgAAGHiD980tP8FZZnXk2K94rvlxg==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [linux] libc: [musl] - '@rolldown/binding-linux-ppc64-gnu@1.1.5': - resolution: {integrity: sha512-fsK/sNBnxzBlL4O1JNrZakVQxPspqpED5dLtNsZS9oOKmtSpdNIzxH2kkol5HYTWJN47sE20ztMJPxfZ89qGOg==} + '@rolldown/binding-linux-ppc64-gnu@1.2.19': + resolution: {integrity: sha512-I0xwD57jP/3A7+5UPZin2w8Y7XHEmEM5zqpYZOcQ45MlNW6tUJUziymV3yRr7rL4vwyfEcRsRksC4a7Kc08p5Q==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [ppc64] os: [linux] libc: [glibc] - '@rolldown/binding-linux-s390x-gnu@1.1.5': - resolution: {integrity: sha512-gLYb4BIadlfTOYT5gO503n8zQjXflgzpD0FcyKh0Mzx3rqCZKnHoJWV9xe1KXUJ5lx2JfcSHr/mhzS0PC/McAA==} + '@rolldown/binding-linux-s390x-gnu@1.2.19': + resolution: {integrity: sha512-BrtEHT24SNXj9HiXqy+s/kXiSiQGt6EKCPUlRirAoIioVxKGnbXBUEkbZASAei7iZJB0/Ynm+0JP00Ipx7AnSw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [s390x] os: [linux] libc: [glibc] - '@rolldown/binding-linux-x64-gnu@1.1.5': - resolution: {integrity: sha512-FjcpEKUyJygHgs1o50VYNvkt5+7Le/VEdYt0AkRpkL33MnyQfwr8l5mXwMmfmTbyMPr5vJLC+8/Gd9gXnwU1QQ==} + '@rolldown/binding-linux-x64-gnu@1.2.19': + resolution: {integrity: sha512-rm75/9DkHKeU2WnA8w4X94WGYgLlDCFCfkQC+4bguVJmC/jvDRv2B+2wLOYhyE0fVuv7//Ckk39OoOufyCu76Q==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [linux] libc: [glibc] - '@rolldown/binding-linux-x64-musl@1.1.5': - resolution: {integrity: sha512-Me+PfPI2TMeOQk0gYWfLQZtTktrmzbr8cDboqX83XKc7UrgAi55gF+2dUkWdxd19n55Essp2yeca+O9N5rBxHg==} + '@rolldown/binding-linux-x64-musl@1.2.19': + resolution: {integrity: sha512-irh/4+iYFM4GAzpluDErgjz89bj6NDtqqMAG/6O1LG38Ed3NpyebzCpcVNkFW8uhy+/3/BocUvnXDR33CXWe9A==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [linux] libc: [musl] - '@rolldown/binding-openharmony-arm64@1.1.5': - resolution: {integrity: sha512-yc5WrLzXks6zCQfn9Oxr8pORKyl/pF+QjHmW/Qx3qu0oyrrNC+y2JLTU1E2rcWYAmzlnqngWXHQjy51VzW70Vw==} + '@rolldown/binding-openharmony-arm64@1.2.19': + resolution: {integrity: sha512-+KWTWNoPt+CfSq94CiceWu3yPE+QzkaG+phPyz9G60tmZLwfQkcA4AeksafzvJAw4pvg1mcd5a1TkUqVv0s4JA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [openharmony] - '@rolldown/binding-wasm32-wasi@1.1.5': - resolution: {integrity: sha512-VbQGPX2b4r48TAMIM2cjgluIM1HYutm4pcTEJsle7iEP7sB1dFqtPLBVbdLAZCxy1txCcPxf4QFf4v8uvltPqA==} - engines: {node: ^20.19.0 || >=22.12.0} + '@rolldown/binding-wasm32-wasi@1.2.19': + resolution: {integrity: sha512-7EH+skOsl5qpWnK0vzamgJFhOv1cwxQpsxm8tI883K9fur5c27p8q87fzEO6BbBPabA2/+s/zR63/pLc137iOg==} + engines: {node: ^20.19.0 || ^22.13.0 || >=23.5.0} cpu: [wasm32] - '@rolldown/binding-win32-arm64-msvc@1.1.5': - resolution: {integrity: sha512-gHv82k63z4qpV5+Q1y/12KrK0ltWBukVDI8nZcbT7Tt/ZlOIVwppazneq0F93oDxTo3IgAMEDIoQh3E2n6mVsw==} + '@rolldown/binding-win32-arm64-msvc@1.2.19': + resolution: {integrity: sha512-3Q1Yg1Q7tEvBWoZf5rFvG/GKZQPgwfru+p4wBajDfJFBs0SHCpL++dfTjW9gyAKd1T7ZpIYvdaUax7Pa/IhFVQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [win32] - '@rolldown/binding-win32-x64-msvc@1.1.5': - resolution: {integrity: sha512-tTZuDBPw85tEN5PQi1pnEBzDy0Z49HtScLAbD5t6hyeU92A95pRWaSMw1GZZi/RwgSgUIl0xrSlXIT/9QzvYSA==} + '@rolldown/binding-win32-x64-msvc@1.2.19': + resolution: {integrity: sha512-y/sqRRc6d7hECzOFc5n3LSeqctmIp9mMjY1Kq4s14uLPd/LZ4z7i1zrW6fMtp2mPeuQIC4e6ULMcwQzMomqQag==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [win32] @@ -1102,52 +1115,52 @@ packages: peerDependencies: '@rolldown/plugin-babel': ^0.1.7 || ^0.2.0 babel-plugin-react-compiler: ^1.0.0 - vite: 8.1.5 + vite: 8.3.8 peerDependenciesMeta: '@rolldown/plugin-babel': optional: true babel-plugin-react-compiler: optional: true - '@vitest/browser-playwright@4.1.11': - resolution: {integrity: sha512-riLBxPqwnJ0lWs2DN2WeUfYeKLoAjbP2Xx8cLQdSddzMi20sksIa6K2mPz79DyMZKKVKH2ksOC2yJvtNcZg8cg==} + '@vitest/browser-playwright@4.1.12': + resolution: {integrity: sha512-bU/TcyiBwFUijaIltxKXxgpQmLu9njO/t6G9wiD2LjSFX6SfmyUOf+pOJ8N26KsvhFOHWfVdzNS6P62ab/ONlA==} peerDependencies: playwright: '*' - vitest: ^4.1.11 + vitest: ^4.1.12 - '@vitest/browser@4.1.11': - resolution: {integrity: sha512-bwMovvAeuTFOK5kIFevw4VEf+1gVEICv4SYK4k3knJOxl6b1zEWud8mYKD73e1B0odAn174h1MofURy2TPWf3w==} + '@vitest/browser@4.1.12': + resolution: {integrity: sha512-Yl/6JIxJrcMlWMqKPoRkMhZy9sDpaAXdSJ+90hMVEJVE94tVysjp34SXTwCXJSIXjAtW2ha33qEjMeGG0G/Z0Q==} peerDependencies: - vitest: ^4.1.11 + vitest: ^4.1.12 - '@vitest/expect@4.1.11': - resolution: {integrity: sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw==} + '@vitest/expect@4.1.12': + resolution: {integrity: sha512-vFlTt+YEu9WBpNjdGayNmlMVzrWPi1+sv853/7t2FU7hpO5gAFBKHzQmkCq5Xjpr+evegF2994LQT3hF3mRlqQ==} - '@vitest/mocker@4.1.11': - resolution: {integrity: sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==} + '@vitest/mocker@4.1.12': + resolution: {integrity: sha512-fKShNpKZzupWZuY0z7egydvL0sqW4INEZBEExMBMAa6izlENEVHwoXgdaTCaBZ5fwlr4xf2o1wXC83n9RpO+NA==} peerDependencies: msw: ^2.4.9 - vite: 8.1.5 + vite: 8.3.8 peerDependenciesMeta: msw: optional: true vite: optional: true - '@vitest/pretty-format@4.1.11': - resolution: {integrity: sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw==} + '@vitest/pretty-format@4.1.12': + resolution: {integrity: sha512-XW9O8+Mxx4VpCtkYdMJLZQQwsVryP9wk7cPKDxtXFfwSak6yRh5+2fep/Y0XF/ElBvJHq8bcYdi6aeuai0opZA==} - '@vitest/runner@4.1.11': - resolution: {integrity: sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw==} + '@vitest/runner@4.1.12': + resolution: {integrity: sha512-NKlVKCr5QnCe8jijdMnmkpHHU+WTqiLFR6G0pHji9uRjXK9xJl1k1nTw6F3pOOj2PDcsDt2GKQMI7wIsaT491w==} - '@vitest/snapshot@4.1.11': - resolution: {integrity: sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog==} + '@vitest/snapshot@4.1.12': + resolution: {integrity: sha512-ko1y1Qgb/slzQ9mr+b89Cuqud8WG1TKtsPD8r7ZUBdvVOGt85Af2HwCqHujrhwJq95hs/9RM7fcAPg57o1vlzw==} - '@vitest/spy@4.1.11': - resolution: {integrity: sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA==} + '@vitest/spy@4.1.12': + resolution: {integrity: sha512-RGq9x4JNGNTZHEJxvN0oSiJjeSCExm0n2gZKKJZHY9cX5AVA6M7VJILBT3ZJ/tJ/0J9uWT7fETV9/btoi//vSg==} - '@vitest/utils@4.1.11': - resolution: {integrity: sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==} + '@vitest/utils@4.1.12': + resolution: {integrity: sha512-Q3awXrwOfEV+qc3WmO5ONyE0yO7Q1gQ9/oyHxGLZ/pl7N3NO/ZztqQwKLuwMkV+CA1JYSIeO3gkHnRDIo4AVaA==} '@zeit/schemas@2.36.0': resolution: {integrity: sha512-7kjMwcChYEzMKjeex9ZFXkt1AyNov9R5HZtjBKVsmVpw7pa7ZtlCGvCBC2vnnXctaYN+aRI61HjIqeetZW5ROg==} @@ -1190,9 +1203,6 @@ packages: resolution: {integrity: sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==} engines: {node: '>=12'} - arch@2.2.0: - resolution: {integrity: sha512-Of/R0wqp83cgHozfIYLbBMnej79U/SVGOOyuB3VVFv1NRM/PSFMK12x9KVtiYzJqmnU5WR2qp0Z5rHb7sWGnFQ==} - are-docs-informative@0.0.2: resolution: {integrity: sha512-ixiS0nLNNG5jNQzgZJNoUpBKdo9yTYZMGJ+QgT2jmjR7G7+QHRCc4v6LQ3NgE7EBJq+o0ams3waJwkrlBom8Ig==} engines: {node: '>=14'} @@ -1218,12 +1228,12 @@ packages: resolution: {integrity: sha512-j//dBVuyacJbvW+tvZ9HuH03fZ46QcaKvvhZickZqtB271DxJ7SNRSNxrV/dZX0085m7hISRZWbzWlJvx/rHSg==} engines: {node: '>=14.16'} - brace-expansion@1.1.14: - resolution: {integrity: sha512-MWPGfDxnyzKU7rNOW9SP/c50vi3xrmrua/+6hfPbCS2ABNWfx24vPidzvC7krjU/RTo235sV776ymlsMtGKj8g==} + brace-expansion@1.1.22: + resolution: {integrity: sha512-CKLDTuSsN0+r1ThM0WkzzBI7dnPI6xEGfa/JnVYIK9JNBA1N1NyPwXVHor//NKD/y3sDxp764sZdLhFK7pH8XQ==} - brace-expansion@5.0.7: - resolution: {integrity: sha512-7oFy703dxfY3/NLxC1fh2SUCQ0H9rmAY+5EpDVfXjUTTs+HEwR2nYaqLv+GWcTsumwxPfiz6CzCNkwXwBUwqCA==} - engines: {node: 18 || 20 || >=22} + brace-expansion@5.0.13: + resolution: {integrity: sha512-Vh3dmFbc4wZeox7M9I/0L9GfFd83Su4+yCck/OF9Gi/P/dAHn0RT7X4K9R7gMNMhDck3DvhR6QXsnQdjjgwNvQ==} + engines: {node: 20 || >=22} braces@3.0.3: resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==} @@ -1261,10 +1271,6 @@ packages: resolution: {integrity: sha512-/lzGpEWL/8PfI0BmBOPRwp0c/wFNX1RdUML3jK/RcSBA9T8mZDdQpqYBKtCFTOfQbwPqWEOpjqW+Fnayc0969g==} engines: {node: '>=10'} - clipboardy@3.0.0: - resolution: {integrity: sha512-Su+uU5sr1jkUy1sGRpLKjKrvEOVXgSgiSInwa/qeID6aJ07yh+5NWc3h2QfjHjBnfX4LhtFcuAWKUsJ3r+fjbg==} - engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} - cliui@8.0.1: resolution: {integrity: sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==} engines: {node: '>=12'} @@ -1284,8 +1290,8 @@ packages: resolution: {integrity: sha512-AF3r7P5dWxL8MxyITRMlORQNaOA2IkAFaTr4k7BUumjPtRpGDTZpl0Pb1XCO6JeDCBdp126Cgs9sMxqSjgYyRg==} engines: {node: '>= 0.6'} - compression@1.8.1: - resolution: {integrity: sha512-9mAqGPHLakhCLeNyxPkK4xVo746zQ/czLH1Ky+vkitMnWfWZps8r0qXuwhwizagCRttsL4lfG4pIOvaWLpAP0w==} + compression@1.8.2: + resolution: {integrity: sha512-o8vI5RE5A6EVVOd9o41jKp41aJom+QTEO/Bx8MYNjexMo/Bv2WOjUfZr+aL0WnYSgymUy6zeguqLTsIhV0gMvQ==} engines: {node: '>= 0.8.0'} concat-map@0.0.1: @@ -1347,6 +1353,10 @@ packages: resolution: {integrity: sha512-gPqh0mKTPvaUZGAuHbrBUYKZWBNAeHG7TU3QH5EhVwPMyKvmfJaNXhcD2jTcXsJRRcffuho4vaYweu80dRrMGA==} engines: {node: '>=18'} + destroy@1.2.0: + resolution: {integrity: sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==} + engines: {node: '>= 0.8', npm: 1.2.8000 || >= 1.4.16} + detect-libc@2.1.2: resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} engines: {node: '>=8'} @@ -1436,10 +1446,6 @@ packages: resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==} engines: {node: '>=0.10.0'} - execa@5.1.1: - resolution: {integrity: sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==} - engines: {node: '>=10'} - expect-type@1.4.0: resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==} engines: {node: '>=12.0.0'} @@ -1457,8 +1463,8 @@ packages: fast-levenshtein@2.0.6: resolution: {integrity: sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==} - fast-uri@3.1.2: - resolution: {integrity: sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ==} + fast-uri@3.1.9: + resolution: {integrity: sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==} fastq@1.20.1: resolution: {integrity: sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==} @@ -1511,10 +1517,6 @@ packages: resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==} engines: {node: 6.* || 8.* || >= 10.*} - get-stream@6.0.1: - resolution: {integrity: sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==} - engines: {node: '>=10'} - glob-parent@5.1.2: resolution: {integrity: sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==} engines: {node: '>= 6'} @@ -1538,10 +1540,6 @@ packages: html-entities@2.6.0: resolution: {integrity: sha512-kig+rMn/QOVRvr7c86gQ8lWXq+Hkv6CbAH1hLu+RG338StTpE8Z0b44SDVaqVu7HGKf27frdmUYEs9hTUX/cLQ==} - human-signals@2.1.0: - resolution: {integrity: sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==} - engines: {node: '>=10.17.0'} - ignore@5.3.2: resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==} engines: {node: '>= 4'} @@ -1561,11 +1559,6 @@ packages: ini@1.3.8: resolution: {integrity: sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==} - is-docker@2.2.1: - resolution: {integrity: sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ==} - engines: {node: '>=8'} - hasBin: true - is-extglob@2.1.1: resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==} engines: {node: '>=0.10.0'} @@ -1594,14 +1587,6 @@ packages: resolution: {integrity: sha512-9UoipoxYmSk6Xy7QFgRv2HDyaysmgSG75TFQs6S+3pDM7ZhKTF/bskZV+0UlABHzKjNVhPjYCLfeZUEg1wXxig==} engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} - is-stream@2.0.1: - resolution: {integrity: sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==} - engines: {node: '>=8'} - - is-wsl@2.2.0: - resolution: {integrity: sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==} - engines: {node: '>=8'} - isexe@2.0.0: resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} @@ -1769,8 +1754,8 @@ packages: magic-string@0.30.21: resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} - markdown-it@14.3.0: - resolution: {integrity: sha512-RCEsPjR+sr0x+AuYp601tKTkgFG4YEPLCzHST3cQ/fhlJkqAkz1L2/Qbp1j9qw5SBwQHFBoW8+hoN5xssOF0Tw==} + markdown-it@14.3.3: + resolution: {integrity: sha512-L//tDAkjTjJCU6pBUSBTgs3Kg4InVaZuUZog/b6V12UKhcDQ7S78877ibbCanRExwPuYP1CZD7Gd2dxSy1GXRg==} hasBin: true matter-js@0.20.0: @@ -1783,9 +1768,6 @@ packages: resolution: {integrity: sha512-EDYo6VlmtnumlcBCbh1gLJ//9jvM/ndXHfVXIFrZVr6fGcwTUyCTFNTLCKuY3ffbK8L/+3Mzqnd58RojiZqHVw==} engines: {node: '>=20'} - merge-stream@2.0.0: - resolution: {integrity: sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==} - merge2@1.4.1: resolution: {integrity: sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==} engines: {node: '>= 8'} @@ -1806,13 +1788,9 @@ packages: resolution: {integrity: sha512-lc/aahn+t4/SWV/qcmumYjymLsWfN3ELhpmVuUFjgsORruuZPVSwAQryq+HHGvO/SI2KVX26bx+En+zhM8g8hQ==} engines: {node: '>= 0.6'} - mimic-fn@2.1.0: - resolution: {integrity: sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==} - engines: {node: '>=6'} - - minimatch@10.2.5: - resolution: {integrity: sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==} - engines: {node: 18 || 20 || >=22} + minimatch@11.0.9: + resolution: {integrity: sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q==} + engines: {node: 20 || >=22} minimatch@3.1.4: resolution: {integrity: sha512-twmL+S8+7yIsE9wsqgzU3E8/LumN3M3QELrBZ20OdmQ9jB2JvW5oZtBEmft84k/Gs5CG9mqtWc6Y9vW+JEzGxw==} @@ -1830,8 +1808,8 @@ packages: ms@2.1.3: resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} - nanoid@3.3.16: - resolution: {integrity: sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==} + nanoid@3.3.20: + resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==} engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} hasBin: true @@ -1842,10 +1820,6 @@ packages: resolution: {integrity: sha512-myRT3DiWPHqho5PrJaIRyaMv2kgYf0mUVgBNOYMuCH5Ki1yEiQaf/ZJuQ62nvpc44wL5WDbTX7yGJi1Neevw8w==} engines: {node: '>= 0.6'} - npm-run-path@4.0.1: - resolution: {integrity: sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==} - engines: {node: '>=8'} - object-deep-merge@2.0.1: resolution: {integrity: sha512-aKttDKcU3pyZqKcCkDhsMn70WmZFG2JGDQLP9EcLyTSIFQRCPWLAmBZRLJnrVUrhPG1jETEEbfdgbNtJf1LyMg==} @@ -1857,10 +1831,6 @@ packages: resolution: {integrity: sha512-737ZY3yNnXy37FHkQxPzt4UZ2UWPWiCZWLvFZ4fu5cueciegX0zGPnrlY6bwRg4FdQOe9YU8MkmJwGhoMybl8A==} engines: {node: '>= 0.8'} - onetime@5.1.2: - resolution: {integrity: sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==} - engines: {node: '>=6'} - optionator@0.9.4: resolution: {integrity: sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==} engines: {node: '>= 0.8.0'} @@ -1915,6 +1885,10 @@ packages: resolution: {integrity: sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==} engines: {node: '>=12'} + picomatch@4.0.7: + resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} + engines: {node: '>=12'} + planck@1.5.1: resolution: {integrity: sha512-x3nHPSyoNTAxN0v8UXrSwP0XVTG0e7JCENBVZljZ8PZOjbOo7aRHq2+fy+DOREDhfW52aq5GiwgIm+m8kIErKQ==} engines: {node: '>=24.0'} @@ -1938,8 +1912,8 @@ packages: poly-decomp@0.3.0: resolution: {integrity: sha512-hWeBxGzPYiybmI4548Fca7Up/0k1qS5+79cVHI9+H33dKya5YNb9hxl0ZnDaDgvrZSuYFBhkCK/HOnqN7gefkQ==} - postcss@8.5.23: - resolution: {integrity: sha512-g50586zr4bZmwFiTlflMu8E0bDTb5I5gertgwAKmsdUlTQIhZtunzUlD1WSzwcVWPoAVpsrA6vlfCD7oXvRwgg==} + postcss@8.5.33: + resolution: {integrity: sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ==} engines: {node: ^10 || ^12 || >=14} prelude-ls@1.2.1: @@ -1974,15 +1948,15 @@ packages: peerDependencies: react: ^19.2.8 - react-router-dom@7.18.1: - resolution: {integrity: sha512-KaZh+X/6UtEp28x51AUYZDMg9NGoz2ja3dNHa+ta/tk40vCzKhQ/RypCWBMLbmDr6//E24Vv5uPsrqXFozdkAg==} + react-router-dom@7.18.6: + resolution: {integrity: sha512-a8JzFsKEY3EY9QL7t4T1b1OhuY0ngEfwMzXQNgBO/2cuIW9028JbVq3uk2rKnjLredzcIoDKLzUkguIq6fnkFA==} engines: {node: '>=20.0.0'} peerDependencies: react: '>=18' react-dom: '>=18' - react-router@7.18.1: - resolution: {integrity: sha512-GDLgg3i3uM0aeJO3Fm+TCS+sDQ7gu12T6x0qdTEzcwqEfleci7JwugVNIF3U//0FWKnJT7ptG+20B2jfDqnZAg==} + react-router@7.18.6: + resolution: {integrity: sha512-SP8KqKfRLlJzqzPseC+r6yYFsqPEavtQCC4BKV810tBGijjESLtwVPam+gPOO+wYeXrYN/TNy2CAykQVcNg4iQ==} engines: {node: '>=20.0.0'} peerDependencies: react: '>=18' @@ -2018,8 +1992,8 @@ packages: resolution: {integrity: sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==} engines: {iojs: '>=1.0.0', node: '>=0.10.0'} - rolldown@1.1.5: - resolution: {integrity: sha512-t9z29cJjXf/vxQ8dyhCSpt6H6aSwHTk8cT5I3iy6SMXuFpk5mB6PL6XfC8PCwrPTx93udwKUm9HRteAlTGBLiA==} + rolldown@1.2.19: + resolution: {integrity: sha512-QIiV1J9d0pzN4jeeTH4sjPy0AZ6cAy2cG0ExeoE1+U8Rvj+hR3gYkokx0YbeUNGlZqiQJJ2utcETe0oKXwzsuA==} engines: {node: ^20.19.0 || >=22.12.0} hasBin: true @@ -2043,8 +2017,8 @@ packages: serve-handler@6.1.7: resolution: {integrity: sha512-CinAq1xWb0vR3twAv9evEU8cNWkXCb9kd5ePAHUKJBkOsUpR1wt/CvGdeca7vqumL1U5cSaeVQ6zZMxiJ3yWsg==} - serve@14.2.6: - resolution: {integrity: sha512-QEjUSA+sD4Rotm1znR8s50YqA3kYpRGPmtd5GlFxbaL9n/FdUNbqMhxClqdditSk0LlZyA/dhud6XNRTOC9x2Q==} + serve@14.2.8: + resolution: {integrity: sha512-7or7YqR3zXwHhiBGj40l9yODyQY146O+hXKaEAfQYQkcvHtMDdX95K96xr50qL9EjXScyYVJb1NIgVE8F0i5cA==} engines: {node: '>= 14'} hasBin: true @@ -2059,16 +2033,13 @@ packages: resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} engines: {node: '>=8'} - shell-quote@1.10.0: - resolution: {integrity: sha512-w1aiOKwKuRgtwAReIIj89puqg+I7GvX4IbLrvmhXbzQsj1+Zwi4VO3+fa6ZF91TWSjIxoEkKnMeHcLEODK5ZXA==} + shell-quote@1.12.0: + resolution: {integrity: sha512-PcByqNyT/38F2kDNi006HAMRJaULuBzq/FOsw3qdZvX/GA9W/jamDaRskgHjubHiftXK5sIFxLNkvrXUwcof6Q==} engines: {node: '>= 0.4'} siginfo@2.0.0: resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} - signal-exit@3.0.7: - resolution: {integrity: sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==} - sirv@3.0.2: resolution: {integrity: sha512-2wcC/oGxHis/BoHkkPwldgiPSYcpZK3JU28WoMVv55yHJgcZ8rlXvuG9iZggz+sU1d4bRgIGASwyWqjxu3FM0g==} engines: {node: '>=18'} @@ -2077,9 +2048,9 @@ packages: resolution: {integrity: sha512-ZA6oR3T/pEyuqwMgAKT0/hAv8oAXckzbkmR0UkUosQ+Mc4RxGoJkRmwHgHufaenlyAgE1Mxgpdcrf75y6XcnDg==} engines: {node: '>=14.16'} - source-map-js@1.2.1: - resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} - engines: {node: '>=0.10.0'} + source-map-js@1.2.4: + resolution: {integrity: sha512-J7ZjMvHd9O1fcT/5V09QWaaSl2BbWx3F6O08spde82Namf9UB0GxRVIPiNbVsdKkoizHiSpTodo3vp2bAy91MA==} + engines: {node: '>=6.0.0'} spdx-exceptions@2.5.0: resolution: {integrity: sha512-PiU42r+xO4UbUS1buo3LPJkjlO7430Xn5SVAhdpzzsPHsjbYVflnnFdATgabnLude+Cqu25p6N+g2lw/PFsa4w==} @@ -2116,10 +2087,6 @@ packages: resolution: {integrity: sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==} engines: {node: '>=12'} - strip-final-newline@2.0.0: - resolution: {integrity: sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==} - engines: {node: '>=6'} - strip-json-comments@2.0.1: resolution: {integrity: sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==} engines: {node: '>=0.10.0'} @@ -2139,6 +2106,10 @@ packages: tinybench@2.9.0: resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} + tinyclip@0.1.15: + resolution: {integrity: sha512-uo33abH+Ays0xYaDysoBt494Hb3hsEczMpcC0MwFl773pazORx4fmvKhclhR1wonUbB6vvpRsvVMwnhfqeMc+A==} + engines: {node: ^16.14.0 || >= 17.3.0} + tinyexec@1.2.4: resolution: {integrity: sha512-SHf/r48b7vOrjve9PxJo3MN5v5yuyjHvdUcrQffT3WXMUfnGmHDVbC4k3sHJaJTgZCwpUplIaAo5ANtMyp3YHg==} engines: {node: '>=18'} @@ -2247,20 +2218,20 @@ packages: peerDependencies: '@rollup/pluginutils': ^5.x esbuild: 0.28.1 - vite: 8.1.5 + vite: 8.3.8 peerDependenciesMeta: '@rollup/pluginutils': optional: true esbuild: optional: true - vite@8.1.5: - resolution: {integrity: sha512-7ULLwsCdYx/nRyrpiEwvqb5TFHrMVZyBt+rg/OAXT7rgj/z+DtTDyKFeLAdDkubDVDKD8jOsndmy7m55XcfUsw==} + vite@8.3.8: + resolution: {integrity: sha512-LzOn3h9rG/0vhLdXrV4yJ4QFA9eEoqCl+Yx+kGJd7aB9w6nfNgVHKSYwLPZUHrz4ZGa+t+kXjV9itvcHDLQouA==} engines: {node: ^20.19.0 || >=22.12.0} hasBin: true peerDependencies: '@types/node': ^20.19.0 || >=22.12.0 - '@vitejs/devtools': ^0.3.0 + '@vitejs/devtools': ^0.7.1 || ^0.8.0 esbuild: 0.28.1 jiti: '>=1.21.0' less: ^4.0.0 @@ -2297,23 +2268,23 @@ packages: yaml: optional: true - vitest@4.1.11: - resolution: {integrity: sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw==} + vitest@4.1.12: + resolution: {integrity: sha512-5eWdz2yb3ajxWF3C8C4TjkXl7FGm3n2E/VlazALrQHzK7nYMSGFnCZto0bbPNl77AwkOZVLk0YnBAejUu0NiWA==} engines: {node: ^20.0.0 || ^22.0.0 || >=24.0.0} hasBin: true peerDependencies: '@edge-runtime/vm': '*' '@opentelemetry/api': ^1.9.0 '@types/node': ^20.0.0 || ^22.0.0 || >=24.0.0 - '@vitest/browser-playwright': ^4.1.11 - '@vitest/browser-preview': 4.1.11 - '@vitest/browser-webdriverio': 4.1.11 - '@vitest/coverage-istanbul': 4.1.11 - '@vitest/coverage-v8': 4.1.11 - '@vitest/ui': 4.1.11 + '@vitest/browser-playwright': ^4.1.12 + '@vitest/browser-preview': 4.1.12 + '@vitest/browser-webdriverio': ^4.1.11 + '@vitest/coverage-istanbul': 4.1.12 + '@vitest/coverage-v8': 4.1.12 + '@vitest/ui': 4.1.12 happy-dom: '*' jsdom: '*' - vite: 8.1.5 + vite: 8.3.8 peerDependenciesMeta: '@edge-runtime/vm': optional: true @@ -2456,18 +2427,18 @@ snapshots: '@dimforge/rapier3d-compat@0.21.0': {} - '@emnapi/core@1.11.1': + '@emnapi/core@2.0.0-beta.2': dependencies: - '@emnapi/wasi-threads': 1.2.2 + '@emnapi/wasi-threads': 2.2.0 tslib: 2.8.1 optional: true - '@emnapi/runtime@1.11.1': + '@emnapi/runtime@2.0.0-beta.2': dependencies: tslib: 2.8.1 optional: true - '@emnapi/wasi-threads@1.2.2': + '@emnapi/wasi-threads@2.2.0': dependencies: tslib: 2.8.1 optional: true @@ -2571,7 +2542,7 @@ snapshots: dependencies: '@eslint/object-schema': 3.0.5 debug: 4.4.3 - minimatch: 10.2.5 + minimatch: 11.0.9 transitivePeerDependencies: - supports-color @@ -2628,12 +2599,14 @@ snapshots: '@humanwhocodes/retry@0.4.3': {} + '@isaacs/nonrecursive-glob-match@1.1.0': {} + '@jridgewell/sourcemap-codec@1.5.5': {} - '@napi-rs/wasm-runtime@1.1.6(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.1)': + '@napi-rs/wasm-runtime@1.2.6(@emnapi/core@2.0.0-beta.2)(@emnapi/runtime@2.0.0-beta.2)': dependencies: - '@emnapi/core': 1.11.1 - '@emnapi/runtime': 1.11.1 + '@emnapi/core': 2.0.0-beta.2 + '@emnapi/runtime': 2.0.0-beta.2 '@tybys/wasm-util': 0.10.3 optional: true @@ -2649,57 +2622,60 @@ snapshots: '@nodelib/fs.scandir': 2.1.5 fastq: 1.20.1 - '@oxc-project/types@0.139.0': {} + '@oxc-project/types@0.156.0': {} '@polka/url@1.0.0-next.29': {} - '@rolldown/binding-android-arm64@1.1.5': + '@rolldown/binding-android-arm-eabi@1.2.19': optional: true - '@rolldown/binding-darwin-arm64@1.1.5': + '@rolldown/binding-android-arm64@1.2.19': optional: true - '@rolldown/binding-darwin-x64@1.1.5': + '@rolldown/binding-darwin-arm64@1.2.19': optional: true - '@rolldown/binding-freebsd-x64@1.1.5': + '@rolldown/binding-darwin-x64@1.2.19': optional: true - '@rolldown/binding-linux-arm-gnueabihf@1.1.5': + '@rolldown/binding-freebsd-x64@1.2.19': optional: true - '@rolldown/binding-linux-arm64-gnu@1.1.5': + '@rolldown/binding-linux-arm-gnueabihf@1.2.19': optional: true - '@rolldown/binding-linux-arm64-musl@1.1.5': + '@rolldown/binding-linux-arm64-gnu@1.2.19': optional: true - '@rolldown/binding-linux-ppc64-gnu@1.1.5': + '@rolldown/binding-linux-arm64-musl@1.2.19': optional: true - '@rolldown/binding-linux-s390x-gnu@1.1.5': + '@rolldown/binding-linux-ppc64-gnu@1.2.19': optional: true - '@rolldown/binding-linux-x64-gnu@1.1.5': + '@rolldown/binding-linux-s390x-gnu@1.2.19': optional: true - '@rolldown/binding-linux-x64-musl@1.1.5': + '@rolldown/binding-linux-x64-gnu@1.2.19': optional: true - '@rolldown/binding-openharmony-arm64@1.1.5': + '@rolldown/binding-linux-x64-musl@1.2.19': optional: true - '@rolldown/binding-wasm32-wasi@1.1.5': + '@rolldown/binding-openharmony-arm64@1.2.19': + optional: true + + '@rolldown/binding-wasm32-wasi@1.2.19': dependencies: - '@emnapi/core': 1.11.1 - '@emnapi/runtime': 1.11.1 - '@napi-rs/wasm-runtime': 1.1.6(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.1) + '@emnapi/core': 2.0.0-beta.2 + '@emnapi/runtime': 2.0.0-beta.2 + '@napi-rs/wasm-runtime': 1.2.6(@emnapi/core@2.0.0-beta.2)(@emnapi/runtime@2.0.0-beta.2) optional: true - '@rolldown/binding-win32-arm64-msvc@1.1.5': + '@rolldown/binding-win32-arm64-msvc@1.2.19': optional: true - '@rolldown/binding-win32-x64-msvc@1.1.5': + '@rolldown/binding-win32-x64-msvc@1.2.19': optional: true '@rolldown/pluginutils@1.0.1': {} @@ -2855,7 +2831,7 @@ snapshots: '@typescript-eslint/types': 8.67.0 '@typescript-eslint/visitor-keys': 8.67.0 debug: 4.4.3 - minimatch: 10.2.5 + minimatch: 11.0.9 semver: 7.8.5 tinyglobby: 0.2.17 ts-api-utils: 2.5.0(typescript@6.0.3) @@ -2879,18 +2855,18 @@ snapshots: '@typescript-eslint/types': 8.67.0 eslint-visitor-keys: 5.0.1 - '@vitejs/plugin-react@6.0.4(vite@8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0))': + '@vitejs/plugin-react@6.0.4(vite@8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0))': dependencies: '@rolldown/pluginutils': 1.0.1 - vite: 8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0) + vite: 8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0) - '@vitest/browser-playwright@4.1.11(playwright@1.62.1)(vite@8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0))(vitest@4.1.11)': + '@vitest/browser-playwright@4.1.12(playwright@1.62.1)(vite@8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0))(vitest@4.1.12)': dependencies: - '@vitest/browser': 4.1.11(vite@8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0))(vitest@4.1.11) - '@vitest/mocker': 4.1.11(vite@8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0)) + '@vitest/browser': 4.1.12(vite@8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0))(vitest@4.1.12) + '@vitest/mocker': 4.1.12(vite@8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0)) playwright: 1.62.1 tinyrainbow: 3.1.0 - vitest: 4.1.11(@types/node@25.6.2)(@vitest/browser-playwright@4.1.11)(vite@8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0)) + vitest: 4.1.12(@types/node@25.6.2)(@vitest/browser-playwright@4.1.12)(vite@8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0)) transitivePeerDependencies: - bufferutil - msw @@ -2898,29 +2874,29 @@ snapshots: - vite optional: true - '@vitest/browser-playwright@4.1.11(playwright@1.62.1)(vite@8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0))(vitest@4.1.11)': + '@vitest/browser-playwright@4.1.12(playwright@1.62.1)(vite@8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0))(vitest@4.1.12)': dependencies: - '@vitest/browser': 4.1.11(vite@8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0))(vitest@4.1.11) - '@vitest/mocker': 4.1.11(vite@8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0)) + '@vitest/browser': 4.1.12(vite@8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0))(vitest@4.1.12) + '@vitest/mocker': 4.1.12(vite@8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0)) playwright: 1.62.1 tinyrainbow: 3.1.0 - vitest: 4.1.11(@types/node@25.6.2)(@vitest/browser-playwright@4.1.11)(vite@8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0)) + vitest: 4.1.12(@types/node@25.6.2)(@vitest/browser-playwright@4.1.12)(vite@8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0)) transitivePeerDependencies: - bufferutil - msw - utf-8-validate - vite - '@vitest/browser@4.1.11(vite@8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0))(vitest@4.1.11)': + '@vitest/browser@4.1.12(vite@8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0))(vitest@4.1.12)': dependencies: '@blazediff/core': 1.9.1 - '@vitest/mocker': 4.1.11(vite@8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0)) - '@vitest/utils': 4.1.11 + '@vitest/mocker': 4.1.12(vite@8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0)) + '@vitest/utils': 4.1.12 magic-string: 0.30.21 pngjs: 7.0.0 sirv: 3.0.2 tinyrainbow: 3.1.0 - vitest: 4.1.11(@types/node@25.6.2)(@vitest/browser-playwright@4.1.11)(vite@8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0)) + vitest: 4.1.12(@types/node@25.6.2)(@vitest/browser-playwright@4.1.12)(vite@8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0)) ws: 8.21.0 transitivePeerDependencies: - bufferutil @@ -2929,16 +2905,16 @@ snapshots: - vite optional: true - '@vitest/browser@4.1.11(vite@8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0))(vitest@4.1.11)': + '@vitest/browser@4.1.12(vite@8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0))(vitest@4.1.12)': dependencies: '@blazediff/core': 1.9.1 - '@vitest/mocker': 4.1.11(vite@8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0)) - '@vitest/utils': 4.1.11 + '@vitest/mocker': 4.1.12(vite@8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0)) + '@vitest/utils': 4.1.12 magic-string: 0.30.21 pngjs: 7.0.0 sirv: 3.0.2 tinyrainbow: 3.1.0 - vitest: 4.1.11(@types/node@25.6.2)(@vitest/browser-playwright@4.1.11)(vite@8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0)) + vitest: 4.1.12(@types/node@25.6.2)(@vitest/browser-playwright@4.1.12)(vite@8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0)) ws: 8.21.0 transitivePeerDependencies: - bufferutil @@ -2946,52 +2922,52 @@ snapshots: - utf-8-validate - vite - '@vitest/expect@4.1.11': + '@vitest/expect@4.1.12': dependencies: '@standard-schema/spec': 1.1.0 '@types/chai': 5.2.3 - '@vitest/spy': 4.1.11 - '@vitest/utils': 4.1.11 + '@vitest/spy': 4.1.12 + '@vitest/utils': 4.1.12 chai: 6.2.2 tinyrainbow: 3.1.0 - '@vitest/mocker@4.1.11(vite@8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0))': + '@vitest/mocker@4.1.12(vite@8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0))': dependencies: - '@vitest/spy': 4.1.11 + '@vitest/spy': 4.1.12 estree-walker: 3.0.3 magic-string: 0.30.21 optionalDependencies: - vite: 8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0) + vite: 8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0) - '@vitest/mocker@4.1.11(vite@8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0))': + '@vitest/mocker@4.1.12(vite@8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0))': dependencies: - '@vitest/spy': 4.1.11 + '@vitest/spy': 4.1.12 estree-walker: 3.0.3 magic-string: 0.30.21 optionalDependencies: - vite: 8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0) + vite: 8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0) - '@vitest/pretty-format@4.1.11': + '@vitest/pretty-format@4.1.12': dependencies: tinyrainbow: 3.1.0 - '@vitest/runner@4.1.11': + '@vitest/runner@4.1.12': dependencies: - '@vitest/utils': 4.1.11 + '@vitest/utils': 4.1.12 pathe: 2.0.3 - '@vitest/snapshot@4.1.11': + '@vitest/snapshot@4.1.12': dependencies: - '@vitest/pretty-format': 4.1.11 - '@vitest/utils': 4.1.11 + '@vitest/pretty-format': 4.1.12 + '@vitest/utils': 4.1.12 magic-string: 0.30.21 pathe: 2.0.3 - '@vitest/spy@4.1.11': {} + '@vitest/spy@4.1.12': {} - '@vitest/utils@4.1.11': + '@vitest/utils@4.1.12': dependencies: - '@vitest/pretty-format': 4.1.11 + '@vitest/pretty-format': 4.1.12 convert-source-map: 2.0.0 tinyrainbow: 3.1.0 @@ -3015,7 +2991,7 @@ snapshots: ajv@8.18.0: dependencies: fast-deep-equal: 3.1.3 - fast-uri: 3.1.2 + fast-uri: 3.1.9 json-schema-traverse: 1.0.0 require-from-string: 2.0.2 @@ -3033,8 +3009,6 @@ snapshots: ansi-styles@6.2.3: {} - arch@2.2.0: {} - are-docs-informative@0.0.2: {} arg@5.0.2: {} @@ -3058,12 +3032,12 @@ snapshots: widest-line: 4.0.1 wrap-ansi: 8.1.0 - brace-expansion@1.1.14: + brace-expansion@1.1.22: dependencies: balanced-match: 1.0.2 concat-map: 0.0.1 - brace-expansion@5.0.7: + brace-expansion@5.0.13: dependencies: balanced-match: 4.0.4 @@ -3092,12 +3066,6 @@ snapshots: cli-boxes@3.0.0: {} - clipboardy@3.0.0: - dependencies: - arch: 2.2.0 - execa: 5.1.1 - is-wsl: 2.2.0 - cliui@8.0.1: dependencies: string-width: 4.2.3 @@ -3116,11 +3084,12 @@ snapshots: dependencies: mime-db: 1.54.0 - compression@1.8.1: + compression@1.8.2: dependencies: bytes: 3.1.2 compressible: 2.0.18 debug: 2.6.9 + destroy: 1.2.0 negotiator: 0.6.4 on-headers: 1.1.0 safe-buffer: 5.2.1 @@ -3134,7 +3103,7 @@ snapshots: dependencies: chalk: 4.1.2 rxjs: 7.8.2 - shell-quote: 1.10.0 + shell-quote: 1.12.0 supports-color: 8.1.1 tree-kill: 1.2.2 yargs: 17.7.2 @@ -3181,6 +3150,8 @@ snapshots: presentable-error: 0.0.1 slash: 5.1.0 + destroy@1.2.0: {} + detect-libc@2.1.2: {} eastasianwidth@0.2.0: {} @@ -3290,7 +3261,7 @@ snapshots: imurmurhash: 0.1.4 is-glob: 4.0.3 json-stable-stringify-without-jsonify: 1.0.1 - minimatch: 10.2.5 + minimatch: 11.0.9 natural-compare: 1.4.0 optionator: 0.9.4 transitivePeerDependencies: @@ -3318,18 +3289,6 @@ snapshots: esutils@2.0.3: {} - execa@5.1.1: - dependencies: - cross-spawn: 7.0.6 - get-stream: 6.0.1 - human-signals: 2.1.0 - is-stream: 2.0.1 - merge-stream: 2.0.0 - npm-run-path: 4.0.1 - onetime: 5.1.2 - signal-exit: 3.0.7 - strip-final-newline: 2.0.0 - expect-type@1.4.0: {} fast-deep-equal@3.1.3: {} @@ -3346,7 +3305,7 @@ snapshots: fast-levenshtein@2.0.6: {} - fast-uri@3.1.2: {} + fast-uri@3.1.9: {} fastq@1.20.1: dependencies: @@ -3388,8 +3347,6 @@ snapshots: get-caller-file@2.0.5: {} - get-stream@6.0.1: {} - glob-parent@5.1.2: dependencies: is-glob: 4.0.3 @@ -3413,8 +3370,6 @@ snapshots: html-entities@2.6.0: {} - human-signals@2.1.0: {} - ignore@5.3.2: {} ignore@7.0.5: {} @@ -3425,8 +3380,6 @@ snapshots: ini@1.3.8: {} - is-docker@2.2.1: {} - is-extglob@2.1.1: {} is-fullwidth-code-point@3.0.0: {} @@ -3443,12 +3396,6 @@ snapshots: is-port-reachable@4.0.0: {} - is-stream@2.0.1: {} - - is-wsl@2.2.0: - dependencies: - is-docker: 2.2.1 - isexe@2.0.0: {} jsdoc-type-pratt-parser@7.3.0: {} @@ -3576,7 +3523,7 @@ snapshots: dependencies: '@jridgewell/sourcemap-codec': 1.5.5 - markdown-it@14.3.0: + markdown-it@14.3.3: dependencies: argparse: 2.0.1 entities: 4.5.0 @@ -3591,8 +3538,6 @@ snapshots: meow@14.1.0: {} - merge-stream@2.0.0: {} - merge2@1.4.1: {} micromatch@4.0.8: @@ -3608,15 +3553,14 @@ snapshots: dependencies: mime-db: 1.33.0 - mimic-fn@2.1.0: {} - - minimatch@10.2.5: + minimatch@11.0.9: dependencies: - brace-expansion: 5.0.7 + '@isaacs/nonrecursive-glob-match': 1.1.0 + brace-expansion: 5.0.13 minimatch@3.1.4: dependencies: - brace-expansion: 1.1.14 + brace-expansion: 1.1.22 minimist@1.2.8: {} @@ -3626,26 +3570,18 @@ snapshots: ms@2.1.3: {} - nanoid@3.3.16: {} + nanoid@3.3.20: {} natural-compare@1.4.0: {} negotiator@0.6.4: {} - npm-run-path@4.0.1: - dependencies: - path-key: 3.1.1 - object-deep-merge@2.0.1: {} obug@2.1.3: {} on-headers@1.1.0: {} - onetime@5.1.2: - dependencies: - mimic-fn: 2.1.0 - optionator@0.9.4: dependencies: deep-is: 0.1.4 @@ -3689,6 +3625,8 @@ snapshots: picomatch@4.0.5: {} + picomatch@4.0.7: {} + planck@1.5.1(stage-js@1.0.2): dependencies: stage-js: 1.0.2 @@ -3705,11 +3643,11 @@ snapshots: poly-decomp@0.3.0: {} - postcss@8.5.23: + postcss@8.5.33: dependencies: - nanoid: 3.3.16 + nanoid: 3.3.20 picocolors: 1.1.1 - source-map-js: 1.2.1 + source-map-js: 1.2.4 prelude-ls@1.2.1: {} @@ -3735,13 +3673,13 @@ snapshots: react: 19.2.8 scheduler: 0.27.0 - react-router-dom@7.18.1(react-dom@19.2.8(react@19.2.8))(react@19.2.8): + react-router-dom@7.18.6(react-dom@19.2.8(react@19.2.8))(react@19.2.8): dependencies: react: 19.2.8 react-dom: 19.2.8(react@19.2.8) - react-router: 7.18.1(react-dom@19.2.8(react@19.2.8))(react@19.2.8) + react-router: 7.18.6(react-dom@19.2.8(react@19.2.8))(react@19.2.8) - react-router@7.18.1(react-dom@19.2.8(react@19.2.8))(react@19.2.8): + react-router@7.18.6(react-dom@19.2.8(react@19.2.8))(react@19.2.8): dependencies: cookie: 1.1.1 react: 19.2.8 @@ -3768,26 +3706,27 @@ snapshots: reusify@1.1.0: {} - rolldown@1.1.5: + rolldown@1.2.19: dependencies: - '@oxc-project/types': 0.139.0 + '@oxc-project/types': 0.156.0 '@rolldown/pluginutils': 1.0.1 optionalDependencies: - '@rolldown/binding-android-arm64': 1.1.5 - '@rolldown/binding-darwin-arm64': 1.1.5 - '@rolldown/binding-darwin-x64': 1.1.5 - '@rolldown/binding-freebsd-x64': 1.1.5 - '@rolldown/binding-linux-arm-gnueabihf': 1.1.5 - '@rolldown/binding-linux-arm64-gnu': 1.1.5 - '@rolldown/binding-linux-arm64-musl': 1.1.5 - '@rolldown/binding-linux-ppc64-gnu': 1.1.5 - '@rolldown/binding-linux-s390x-gnu': 1.1.5 - '@rolldown/binding-linux-x64-gnu': 1.1.5 - '@rolldown/binding-linux-x64-musl': 1.1.5 - '@rolldown/binding-openharmony-arm64': 1.1.5 - '@rolldown/binding-wasm32-wasi': 1.1.5 - '@rolldown/binding-win32-arm64-msvc': 1.1.5 - '@rolldown/binding-win32-x64-msvc': 1.1.5 + '@rolldown/binding-android-arm-eabi': 1.2.19 + '@rolldown/binding-android-arm64': 1.2.19 + '@rolldown/binding-darwin-arm64': 1.2.19 + '@rolldown/binding-darwin-x64': 1.2.19 + '@rolldown/binding-freebsd-x64': 1.2.19 + '@rolldown/binding-linux-arm-gnueabihf': 1.2.19 + '@rolldown/binding-linux-arm64-gnu': 1.2.19 + '@rolldown/binding-linux-arm64-musl': 1.2.19 + '@rolldown/binding-linux-ppc64-gnu': 1.2.19 + '@rolldown/binding-linux-s390x-gnu': 1.2.19 + '@rolldown/binding-linux-x64-gnu': 1.2.19 + '@rolldown/binding-linux-x64-musl': 1.2.19 + '@rolldown/binding-openharmony-arm64': 1.2.19 + '@rolldown/binding-wasm32-wasi': 1.2.19 + '@rolldown/binding-win32-arm64-msvc': 1.2.19 + '@rolldown/binding-win32-x64-msvc': 1.2.19 run-parallel@1.2.0: dependencies: @@ -3813,7 +3752,7 @@ snapshots: path-to-regexp: 3.3.0 range-parser: 1.2.0 - serve@14.2.6: + serve@14.2.8: dependencies: '@zeit/schemas': 2.36.0 ajv: 8.18.0 @@ -3821,10 +3760,10 @@ snapshots: boxen: 7.0.0 chalk: 5.0.1 chalk-template: 0.4.0 - clipboardy: 3.0.0 - compression: 1.8.1 + compression: 1.8.2 is-port-reachable: 4.0.0 serve-handler: 6.1.7 + tinyclip: 0.1.15 update-check: 1.5.4 transitivePeerDependencies: - supports-color @@ -3837,12 +3776,10 @@ snapshots: shebang-regex@3.0.0: {} - shell-quote@1.10.0: {} + shell-quote@1.12.0: {} siginfo@2.0.0: {} - signal-exit@3.0.7: {} - sirv@3.0.2: dependencies: '@polka/url': 1.0.0-next.29 @@ -3851,7 +3788,7 @@ snapshots: slash@5.1.0: {} - source-map-js@1.2.1: {} + source-map-js@1.2.4: {} spdx-exceptions@2.5.0: {} @@ -3888,8 +3825,6 @@ snapshots: dependencies: ansi-regex: 6.2.2 - strip-final-newline@2.0.0: {} - strip-json-comments@2.0.1: {} supports-color@7.2.0: @@ -3904,6 +3839,8 @@ snapshots: tinybench@2.9.0: {} + tinyclip@0.1.15: {} + tinyexec@1.2.4: {} tinyglobby@0.2.17: @@ -3967,8 +3904,8 @@ snapshots: dependencies: '@gerrit0/mini-shiki': 3.23.0 lunr: 2.3.9 - markdown-it: 14.3.0 - minimatch: 10.2.5 + markdown-it: 14.3.3 + minimatch: 11.0.9 typescript: 6.0.3 yaml: 2.9.0 @@ -4002,18 +3939,18 @@ snapshots: vary@1.1.2: {} - vite-plugin-glsl@1.6.1(esbuild@0.28.1)(vite@8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0)): + vite-plugin-glsl@1.6.1(esbuild@0.28.1)(vite@8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0)): dependencies: - vite: 8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0) + vite: 8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0) optionalDependencies: esbuild: 0.28.1 - vite@8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0): + vite@8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0): dependencies: lightningcss: 1.33.0 - picomatch: 4.0.5 - postcss: 8.5.23 - rolldown: 1.1.5 + picomatch: 4.0.7 + postcss: 8.5.33 + rolldown: 1.2.19 tinyglobby: 0.2.17 optionalDependencies: '@types/node': 25.6.2 @@ -4022,12 +3959,12 @@ snapshots: tsx: 4.23.1 yaml: 2.9.0 - vite@8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0): + vite@8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0): dependencies: lightningcss: 1.33.0 - picomatch: 4.0.5 - postcss: 8.5.23 - rolldown: 1.1.5 + picomatch: 4.0.7 + postcss: 8.5.33 + rolldown: 1.2.19 tinyglobby: 0.2.17 optionalDependencies: '@types/node': 25.6.2 @@ -4036,15 +3973,15 @@ snapshots: tsx: 4.23.12 yaml: 2.9.0 - vitest@4.1.11(@types/node@25.6.2)(@vitest/browser-playwright@4.1.11)(vite@8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0)): + vitest@4.1.12(@types/node@25.6.2)(@vitest/browser-playwright@4.1.12)(vite@8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0)): dependencies: - '@vitest/expect': 4.1.11 - '@vitest/mocker': 4.1.11(vite@8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0)) - '@vitest/pretty-format': 4.1.11 - '@vitest/runner': 4.1.11 - '@vitest/snapshot': 4.1.11 - '@vitest/spy': 4.1.11 - '@vitest/utils': 4.1.11 + '@vitest/expect': 4.1.12 + '@vitest/mocker': 4.1.12(vite@8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0)) + '@vitest/pretty-format': 4.1.12 + '@vitest/runner': 4.1.12 + '@vitest/snapshot': 4.1.12 + '@vitest/spy': 4.1.12 + '@vitest/utils': 4.1.12 es-module-lexer: 2.3.0 expect-type: 1.4.0 magic-string: 0.30.21 @@ -4056,23 +3993,23 @@ snapshots: tinyexec: 1.2.4 tinyglobby: 0.2.17 tinyrainbow: 3.1.0 - vite: 8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0) + vite: 8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0) why-is-node-running: 2.3.0 optionalDependencies: '@types/node': 25.6.2 - '@vitest/browser-playwright': 4.1.11(playwright@1.62.1)(vite@8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0))(vitest@4.1.11) + '@vitest/browser-playwright': 4.1.12(playwright@1.62.1)(vite@8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.1)(yaml@2.9.0))(vitest@4.1.12) transitivePeerDependencies: - msw - vitest@4.1.11(@types/node@25.6.2)(@vitest/browser-playwright@4.1.11)(vite@8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0)): + vitest@4.1.12(@types/node@25.6.2)(@vitest/browser-playwright@4.1.12)(vite@8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0)): dependencies: - '@vitest/expect': 4.1.11 - '@vitest/mocker': 4.1.11(vite@8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0)) - '@vitest/pretty-format': 4.1.11 - '@vitest/runner': 4.1.11 - '@vitest/snapshot': 4.1.11 - '@vitest/spy': 4.1.11 - '@vitest/utils': 4.1.11 + '@vitest/expect': 4.1.12 + '@vitest/mocker': 4.1.12(vite@8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0)) + '@vitest/pretty-format': 4.1.12 + '@vitest/runner': 4.1.12 + '@vitest/snapshot': 4.1.12 + '@vitest/spy': 4.1.12 + '@vitest/utils': 4.1.12 es-module-lexer: 2.3.0 expect-type: 1.4.0 magic-string: 0.30.21 @@ -4084,11 +4021,11 @@ snapshots: tinyexec: 1.2.4 tinyglobby: 0.2.17 tinyrainbow: 3.1.0 - vite: 8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0) + vite: 8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0) why-is-node-running: 2.3.0 optionalDependencies: '@types/node': 25.6.2 - '@vitest/browser-playwright': 4.1.11(playwright@1.62.1)(vite@8.1.5(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0))(vitest@4.1.11) + '@vitest/browser-playwright': 4.1.12(playwright@1.62.1)(vite@8.3.8(@types/node@25.6.2)(esbuild@0.28.1)(tsx@4.23.12)(yaml@2.9.0))(vitest@4.1.12) transitivePeerDependencies: - msw From c3ecf317f17ac9a1e89bc20b3a72faebcc4c2719 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 02:08:29 +0000 Subject: [PATCH 23/51] Engine: check a type where it was asserted, in the places a stricter linter points at Six places told TypeScript what a value was with a cast. They now find out, or no longer need to: - the built-in adapter looks for its own Body through one helper, and says so when a renderable has none; its 3D queries and the raycast check for the octree and for the body they walk, and pass over anything else - the audio listener asks its target whether it can say which way it faces - a mesh reverses its winding in one helper, on a copy the index array makes of itself, so of the same kind - the keyboard handlers take the key, and the browser's event when there is one: the browser's keyCode is read in one place - the particle setting that does nothing has no default any more These pass the current linter and the next one (typescript-eslint 8.73), which is not installed by this change. 55 tests added: 22 pin what is new, 33 guard what must not move. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- packages/melonjs/CHANGELOG.md | 1 + packages/melonjs/src/audio/spatial.ts | 18 +- packages/melonjs/src/input/keyboard.ts | 77 ++-- packages/melonjs/src/particles/settings.ts | 4 +- .../src/physics/builtin/builtin-adapter.ts | 63 ++-- .../melonjs/src/physics/builtin/raycast.ts | 16 +- packages/melonjs/src/renderable/mesh.js | 42 +-- .../tests/builtin-adapter-body-guard.spec.js | 338 ++++++++++++++++++ .../melonjs/tests/keyboard-events.spec.js | 191 ++++++++++ .../tests/mesh-reversed-winding.spec.js | 86 +++++ 10 files changed, 748 insertions(+), 88 deletions(-) create mode 100644 packages/melonjs/tests/builtin-adapter-body-guard.spec.js create mode 100644 packages/melonjs/tests/keyboard-events.spec.js create mode 100644 packages/melonjs/tests/mesh-reversed-winding.spec.js diff --git a/packages/melonjs/CHANGELOG.md b/packages/melonjs/CHANGELOG.md index 92bd09da52..c20591f74e 100644 --- a/packages/melonjs/CHANGELOG.md +++ b/packages/melonjs/CHANGELOG.md @@ -21,6 +21,7 @@ - `NineSliceSprite` blinks with `flicker()`, as a `Sprite` does; it ignored it - Text: a stroked multi-line label with `textBaseline: "hanging"` keeps the top of its outline on macOS, where Helvetica's hanging metrics made the ink padding exactly as tall as the ink, shearing its first row off the canvas ([#1870](https://github.com/melonjs/melonJS/issues/1870)) - glTF: a model compressed with Draco or meshopt, which the loader cannot decode, says so in the console, naming the extension, instead of failing on an accessor error that did not mention it +- Physics: a method of the built-in adapter (`setVelocity`, `applyForce`, `setStatic` and the like) called on a renderable with no body says so, `this renderable has no built-in body`, where it failed on a property of `undefined`; and a raycast passes over an object whose body is not one of the adapter's, where it threw ## [20.16.0] (melonJS 2) - _2026-11-17_ diff --git a/packages/melonjs/src/audio/spatial.ts b/packages/melonjs/src/audio/spatial.ts index 5eb1910e8c..632a712d4d 100644 --- a/packages/melonjs/src/audio/spatial.ts +++ b/packages/melonjs/src/audio/spatial.ts @@ -183,6 +183,19 @@ function stopTickingIfIdle() { } } +/** + * Whether a listener can say which way it faces, as a `Camera3d` does: the + * listener then turns with it. Asked of the object and not of its class, so + * that this module does not have to load the 3D camera to play a sound. + * @param target - the renderable the listener follows + * @returns true when it has a `getBasis` + */ +function facesSomewhere( + target: Renderable, +): target is Renderable & Pick { + return "getBasis" in target && typeof target.getBasis === "function"; +} + /** * Re-read the listener and every followed sound. * @@ -204,9 +217,8 @@ function tick() { } else { const p = listenerPositionOf(listenerTarget); listener(p.x, p.y, p.z); - const camera = listenerTarget as Camera3d; - if (typeof camera.getBasis === "function") { - camera.getBasis(_right, _up, _forward); + if (facesSomewhere(listenerTarget)) { + listenerTarget.getBasis(_right, _up, _forward); listenerOrientation( _forward.x, _forward.y, diff --git a/packages/melonjs/src/input/keyboard.ts b/packages/melonjs/src/input/keyboard.ts index 13f1bb4487..180fe05f28 100644 --- a/packages/melonjs/src/input/keyboard.ts +++ b/packages/melonjs/src/input/keyboard.ts @@ -23,22 +23,32 @@ const _keyBindings: Record = {}; // run: one of them that uses the key can stop its default action let _unboundKeyDown: KeyboardEvent | undefined; -type KeyEventHandler = ( - options: - | { keyCode: number; mouseButton?: number | undefined } - | KeyboardEvent, -) => void; +/** + * The code of the key of a browser event. The engine's key codes (`input.KEY`, + * the bindings) are the ones browsers have always given in `keyCode`: this is + * the one place that field is read. + * @param event - a keyboard event from the browser + * @returns the code of its key + */ +function keyCodeOf(event: KeyboardEvent): number { + // eslint-disable-next-line @typescript-eslint/no-deprecated -- the codes the engine's API is in + return event.keyCode; +} -const keyDownEvent: KeyEventHandler = (options) => { - // eslint-disable-next-line @typescript-eslint/no-deprecated - const { keyCode } = options; +/** + * A key goes down: pressed on the keyboard (with the browser's event), or + * triggered by the engine for a pointer button or from `triggerKeyEvent`. + * @param keyCode - the key + * @param [mouseButton] - the pointer button standing in for the key + * @param [event] - the browser's event, when a keyboard sent it + */ +function keyDown(keyCode: number, mouseButton?: number, event?: KeyboardEvent) { const action = _keyBindings[keyCode]; // a bound key follows its binding's preventDefault; an unbound one is left // to the listener that uses it, through preventKeyDefault() const outer = _unboundKeyDown; - _unboundKeyDown = - !action && "preventDefault" in options ? options : undefined; + _unboundKeyDown = action ? undefined : event; try { emit(KEYDOWN, action, keyCode, action ? !_keyLocked[action] : true); } finally { @@ -47,29 +57,31 @@ const keyDownEvent: KeyEventHandler = (options) => { if (action) { if (!_keyLocked[action]) { - const trigger = - ("mouseButton" in options ? options.mouseButton : undefined) ?? keyCode; + const trigger = mouseButton ?? keyCode; if (!_keyRefs[action][trigger]) { _keyStatus[action]++; _keyRefs[action][trigger] = true; } } - if ("preventDefault" in options && _preventDefaultForKeys[keyCode]) { - options.preventDefault(); + if (_preventDefaultForKeys[keyCode]) { + event?.preventDefault(); } } -}; +} -const keyUpEvent: KeyEventHandler = (options) => { - // eslint-disable-next-line @typescript-eslint/no-deprecated - const { keyCode } = options; +/** + * A key goes up: see {@link keyDown}. + * @param keyCode - the key + * @param [mouseButton] - the pointer button standing in for the key + * @param [event] - the browser's event, when a keyboard sent it + */ +function keyUp(keyCode: number, mouseButton?: number, event?: KeyboardEvent) { const action = _keyBindings[keyCode]; emit(KEYUP, action, keyCode); if (action) { - const trigger = - ("mouseButton" in options ? options.mouseButton : undefined) ?? keyCode; + const trigger = mouseButton ?? keyCode; delete _keyRefs[action][trigger]; if (_keyStatus[action] > 0) { @@ -78,11 +90,11 @@ const keyUpEvent: KeyEventHandler = (options) => { _keyLocked[action] = false; - if ("preventDefault" in options && _preventDefaultForKeys[keyCode]) { - options.preventDefault(); + if (_preventDefaultForKeys[keyCode]) { + event?.preventDefault(); } } -}; +} // gamepads press keys with a source of 256 and up (keys and mouse buttons // use their own codes, below that) @@ -125,12 +137,18 @@ export function initKeyboardEvent() { if (typeof globalThis.addEventListener === "function") { globalThis.addEventListener( "keydown", - (e) => { - keyDownEvent(e); + (event) => { + keyDown(keyCodeOf(event), undefined, event); + }, + false, + ); + globalThis.addEventListener( + "keyup", + (event) => { + keyUp(keyCodeOf(event), undefined, event); }, false, ); - globalThis.addEventListener("keyup", keyUpEvent, false); } // emitted on the window's blur and when the page is hidden on(BLUR, releaseHeldKeys); @@ -198,8 +216,11 @@ export function triggerKeyEvent( status: boolean, mouseButton?: number, ) { - const handler = status ? keyDownEvent : keyUpEvent; - handler({ keyCode, mouseButton }); + if (status) { + keyDown(keyCode, mouseButton); + } else { + keyUp(keyCode, mouseButton); + } } /** diff --git a/packages/melonjs/src/particles/settings.ts b/packages/melonjs/src/particles/settings.ts index ac3f00a18a..d49087e197 100644 --- a/packages/melonjs/src/particles/settings.ts +++ b/packages/melonjs/src/particles/settings.ts @@ -403,10 +403,9 @@ export interface ParticleEmitterSettings { * frame, from a transform that had not been rebuilt yet. Particles now * invalidate on write and recompute once on read, so the bounds a reader * gets are always current. - * @default false * @deprecated since 20.2.0 — bounds are always up to date; remove it */ - accurateBounds: boolean; + accurateBounds?: boolean; /** * When `true`, the emitter automatically removes itself from its parent @@ -473,7 +472,6 @@ const defaultParticleEmitterSettings: ParticleEmitterSettings = { frequency: 100, duration: Infinity, framesToSkip: 0, - accurateBounds: false, autoDestroyOnComplete: false, onComplete: undefined, }; diff --git a/packages/melonjs/src/physics/builtin/builtin-adapter.ts b/packages/melonjs/src/physics/builtin/builtin-adapter.ts index ef882f366d..3ca8ea031a 100644 --- a/packages/melonjs/src/physics/builtin/builtin-adapter.ts +++ b/packages/melonjs/src/physics/builtin/builtin-adapter.ts @@ -17,12 +17,27 @@ import type { RaycastHit3d, } from "../adapter.ts"; import type { Bounds } from "../bounds.ts"; -import type Octree from "../broadphase/octree.ts"; +import Octree from "../broadphase/octree.ts"; import type World from "../world.js"; import Body from "./body.js"; import Detector from "./detector.js"; import { raycastQuery } from "./raycast.ts"; +/** + * The body of a renderable this adapter manages. `Renderable#body` is the + * portable `PhysicsBody`, as another adapter puts a body of its own there: + * here it is the built-in `Body`, and this is where that is checked. + * @param renderable - a renderable with a body of this adapter + * @returns its body + */ +function bodyOf(renderable: Renderable): Body { + const body = renderable.body; + if (body instanceof Body) { + return body; + } + throw new TypeError("BuiltinAdapter: this renderable has no built-in body"); +} + // the axis the built-in bodies turn about, and a scratch for setRotation const _AXIS_Z = new Vector3d(0, 0, 1); @@ -643,7 +658,7 @@ export default class BuiltinAdapter implements PhysicsAdapter { setVelocity(renderable: Renderable, v: Vector2d | Vector3d): void { // a Vector3d also sets the velocity along the depth axis; a Vector2d // has no `z`, which leaves it as it was - (renderable.body as Body).setVelocity(v.x, v.y, (v as Vector3d).z); + bodyOf(renderable).setVelocity(v.x, v.y, (v as Vector3d).z); } getVelocity3d(renderable: Renderable, out?: Vector3d): Vector3d { const body = renderable.body as Body | undefined; @@ -665,7 +680,7 @@ export default class BuiltinAdapter implements PhysicsAdapter { // arm (`τ = r × F`). The 2-arg call (no point) preserves the // pre-angular behavior exactly: just accumulate into the linear // force vector. - const body = renderable.body as Body; + const body = bodyOf(renderable); if (point) { body.applyForce(force.x, force.y, point.x, point.y); } else { @@ -682,7 +697,7 @@ export default class BuiltinAdapter implements PhysicsAdapter { applyImpulse(renderable: Renderable, impulse: Vector2d | Vector3d): void { // impulse = mass * dv → dv = impulse / mass. A Vector3d also kicks // along the depth axis; a Vector2d has no `z`, which leaves it alone - (renderable.body as Body).applyImpulse( + bodyOf(renderable).applyImpulse( impulse.x, impulse.y, (impulse as Vector3d).z, @@ -714,11 +729,11 @@ export default class BuiltinAdapter implements PhysicsAdapter { // collisions remain axis-aligned against the original shapes — // but the renderable's `currentTransform` is updated so the // sprite rotates correctly. - (renderable.body as Body).setAngle(angle); + bodyOf(renderable).setAngle(angle); } getAngle(renderable: Renderable): number { - return (renderable.body as Body).angle; + return bodyOf(renderable).angle; } /** * The body's orientation: its turn about Z, the only one the built-in @@ -753,9 +768,7 @@ export default class BuiltinAdapter implements PhysicsAdapter { if (!(planar >= 1e-12) || !Number.isFinite(planar)) { return; } - (renderable.body as Body).setAngle( - Math.atan2(_rotScratch.y, _rotScratch.x), - ); + bodyOf(renderable).setAngle(Math.atan2(_rotScratch.y, _rotScratch.x)); } /** * The body's angular velocity about each axis: about Z only, as the @@ -780,32 +793,32 @@ export default class BuiltinAdapter implements PhysicsAdapter { ); } // a Vector3d's turn about Z, the only one the built-in bodies have - (renderable.body as Body).setAngularVelocity( + bodyOf(renderable).setAngularVelocity( typeof omega === "number" ? omega : omega.z, ); } getAngularVelocity(renderable: Renderable): number { - return (renderable.body as Body).angularVelocity; + return bodyOf(renderable).angularVelocity; } applyTorque(renderable: Renderable, torque: number): void { - (renderable.body as Body).applyTorque(torque); + bodyOf(renderable).applyTorque(torque); } setStatic(renderable: Renderable, isStatic: boolean): void { - (renderable.body as Body).setStatic(isStatic); + bodyOf(renderable).setStatic(isStatic); } setGravityScale(renderable: Renderable, scale: number): void { - (renderable.body as Body).gravityScale = scale; + bodyOf(renderable).gravityScale = scale; } setFrictionAir( renderable: Renderable, friction: number | { x: number; y: number }, ): void { - const body = renderable.body as Body; + const body = bodyOf(renderable); if (typeof friction === "number") { body.setFriction(friction, friction); } else { @@ -817,20 +830,20 @@ export default class BuiltinAdapter implements PhysicsAdapter { renderable: Renderable, limit: { x: number; y: number }, ): void { - (renderable.body as Body).setMaxVelocity(limit.x, limit.y); + bodyOf(renderable).setMaxVelocity(limit.x, limit.y); } getMaxVelocity(renderable: Renderable): { x: number; y: number } { - const v = (renderable.body as Body).maxVel; + const v = bodyOf(renderable).maxVel; return { x: v.x, y: v.y }; } setCollisionType(renderable: Renderable, type: number): void { - (renderable.body as Body).collisionType = type; + bodyOf(renderable).collisionType = type; } setCollisionMask(renderable: Renderable, mask: number): void { - (renderable.body as Body).setCollisionMask(mask); + bodyOf(renderable).setCollisionMask(mask); } setSensor(renderable: Renderable, isSensor: boolean): void { @@ -839,7 +852,7 @@ export default class BuiltinAdapter implements PhysicsAdapter { // only the positional push-out (`respondToCollision`). Same // semantics as Matter's `isSensor`, so adapter-agnostic trigger / // one-way-platform code behaves identically on both adapters. - (renderable.body as Body).isSensor = isSensor; + bodyOf(renderable).isSensor = isSensor; } getBodyAABB(renderable: Renderable, out: Bounds): Bounds | undefined { @@ -911,7 +924,7 @@ export default class BuiltinAdapter implements PhysicsAdapter { // airborne), but alone they called a body grounded whenever it was // not moving down: one never stepped, or held still in the air with // no gravity. - const body = renderable.body as Body; + const body = bodyOf(renderable); return body.onSurface && !body.falling && !body.jumping; } @@ -945,10 +958,10 @@ export default class BuiltinAdapter implements PhysicsAdapter { // to walk, so we return null. User code can guard via // `world.adapter.capabilities.raycasts3d` AND // `world.sortOn === "depth"` to skip a no-op call. - if (this.world.sortOn !== "depth") { + const octree = this.world.broadphase; + if (this.world.sortOn !== "depth" || !(octree instanceof Octree)) { return null; } - const octree = this.world.broadphase as Octree; const dx = to.x - from.x; const dy = to.y - from.y; @@ -1102,7 +1115,8 @@ export default class BuiltinAdapter implements PhysicsAdapter { // so user code can call this unconditionally without a // `sortOn === "depth"` guard sprinkled at every call site. const result: Renderable[] = []; - if (this.world.sortOn !== "depth") { + const octree = this.world.broadphase; + if (this.world.sortOn !== "depth" || !(octree instanceof Octree)) { return result; } // Unpack the two call shapes. We resolve to the loose (cx, @@ -1114,7 +1128,6 @@ export default class BuiltinAdapter implements PhysicsAdapter { const cy = isSphere ? centerOrSphere.pos.y : centerOrSphere.y; const cz = isSphere ? centerOrSphere.pos.z : centerOrSphere.z; const r = isSphere ? centerOrSphere.radius : radius!; - const octree = this.world.broadphase as Octree; // Broadphase walk: octree returns candidates whose octant the // sphere overlaps. Then narrow-phase by actual centre distance // so callers don't have to repeat the test (matches how diff --git a/packages/melonjs/src/physics/builtin/raycast.ts b/packages/melonjs/src/physics/builtin/raycast.ts index 6085667c68..29c8d086f0 100644 --- a/packages/melonjs/src/physics/builtin/raycast.ts +++ b/packages/melonjs/src/physics/builtin/raycast.ts @@ -8,7 +8,7 @@ import { Vector2d } from "../../math/vector2d.ts"; import type Renderable from "../../renderable/renderable.js"; import type { RaycastHit } from "../adapter.ts"; import type World from "../world.js"; -import type Body from "./body.js"; +import Body from "./body.js"; import { anchorOffsetX, anchorOffsetY } from "./sat.js"; /** @@ -400,19 +400,17 @@ export function raycastQuery( for (let i = candidates.length - 1; i >= 0; i--) { const objB = candidates[i]; - if (!objB.body) { + // This raycast walks the BuiltinAdapter's broadphase, whose bodies + // are the built-in `Body`: the portable `PhysicsBody` a renderable + // is typed with does not have the `shapes` read below. Anything + // else found there (no body, or one of another kind) is not hit. + const bodyB = objB.body; + if (!(bodyB instanceof Body)) { continue; } if (!line.getBounds().overlaps(objB.getBounds())) { continue; } - - // This raycast walks the BuiltinAdapter's broadphase, so every - // `objB.body` here is a concrete builtin `Body` — narrow from - // the portable `PhysicsBody` interface (which doesn't expose - // `shapes` / `getShape` since those are adapter-specific) to - // the concrete type. - const bodyB = objB.body as Body; const shapeCount = bodyB.shapes.length; if (shapeCount === 0) { continue; diff --git a/packages/melonjs/src/renderable/mesh.js b/packages/melonjs/src/renderable/mesh.js index 6ae4875890..c7ed416bb6 100644 --- a/packages/melonjs/src/renderable/mesh.js +++ b/packages/melonjs/src/renderable/mesh.js @@ -204,6 +204,26 @@ const _combinedMatrix = new Matrix3d(); // Resolve any acceptable texture input (TextureAtlas, image / canvas // object, or asset name) to a cached `TextureAtlas`. Throws if nothing // resolves — Mesh requires a texture binding for its GL pipeline. +/** + * The same triangles, wound the other way round: a copy of an index array + * with the last two corners of each triangle swapped. + * + * The copy is made by the array itself, so it is of the same kind: a mesh of + * more than 65535 vertices keeps its 32-bit indices, which a `Uint16Array` + * would cut short. + * @param {Uint16Array|Uint32Array|number[]} indices - three indices a triangle + * @returns {Uint16Array|Uint32Array|number[]} the reversed copy + * @ignore + */ +function reversedWinding(indices) { + const reversed = indices.slice(); + for (let i = 0; i + 2 < indices.length; i += 3) { + reversed[i + 1] = indices[i + 2]; + reversed[i + 2] = indices[i + 1]; + } + return reversed; +} + /** * Normalize a `vertexColors` setting to the packed form both batchers read. * @@ -2123,22 +2143,11 @@ export default class Mesh extends Renderable { // duplicate the whole index array for nothing (megabytes on a dense // mesh). if (needsReversedIndices === true && this.rightHanded !== true) { - const src = this._indicesOriginal; - // match the source index type (Uint16Array OR Uint32Array): a copy - // into a hard-coded Uint16Array would truncate indices for meshes - // with > 65535 vertices. - const Ctor = src.constructor; - const dst = new Ctor(src.length); - for (let i = 0; i < src.length; i += 3) { - dst[i] = src[i]; - dst[i + 1] = src[i + 2]; - dst[i + 2] = src[i + 1]; - } /** * @ignore * @internal */ - this._indicesReversed = dst; + this._indicesReversed = reversedWinding(this._indicesOriginal); } /** * @ignore @@ -3121,14 +3130,7 @@ export default class Mesh extends Renderable { } groups[i] = g; } - // the same triangles, wound the other way round - const src = this._indicesOriginal; - const reversed = new src.constructor(src.length); - for (let i = 0; i + 2 < src.length; i += 3) { - reversed[i] = src[i]; - reversed[i + 1] = src[i + 2]; - reversed[i + 2] = src[i + 1]; - } + const reversed = reversedWinding(this._indicesOriginal); hull = new Mesh(0, 0, { vertices: new Float32Array(count * 3), uvs: new Float32Array(count * 2), diff --git a/packages/melonjs/tests/builtin-adapter-body-guard.spec.js b/packages/melonjs/tests/builtin-adapter-body-guard.spec.js new file mode 100644 index 0000000000..37f4cd8c93 --- /dev/null +++ b/packages/melonjs/tests/builtin-adapter-body-guard.spec.js @@ -0,0 +1,338 @@ +/** + * What the built-in adapter makes of the body it is handed. + * + * `Renderable#body` is typed as the portable `PhysicsBody`, since another + * adapter puts a body of its own kind there. The built-in adapter needs its + * own `Body`, and checks for it where it used to take it on trust: a method + * that cannot do without one says so in a `TypeError` of its own, the 3D + * queries answer nothing where there is no octree to walk, and a raycast + * passes over what is not one of its bodies. + */ +import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; +import { + Application, + Body, + BuiltinAdapter, + boot, + collision, + Quaternion, + Rect, + Renderable, + Vector2d, + Vector3d, + video, + World, +} from "../src/index.js"; + +/** every adapter method that cannot do its work without a body */ +const NEEDS_A_BODY = { + setVelocity: (adapter, r) => { + adapter.setVelocity(r, new Vector2d(1, 2)); + }, + applyForce: (adapter, r) => { + adapter.applyForce(r, new Vector2d(1, 0)); + }, + applyImpulse: (adapter, r) => { + adapter.applyImpulse(r, new Vector2d(1, 0)); + }, + setAngle: (adapter, r) => { + adapter.setAngle(r, 0.5); + }, + getAngle: (adapter, r) => { + return adapter.getAngle(r); + }, + setRotation: (adapter, r) => { + adapter.setRotation(r, new Quaternion()); + }, + setAngularVelocity: (adapter, r) => { + adapter.setAngularVelocity(r, 1); + }, + getAngularVelocity: (adapter, r) => { + return adapter.getAngularVelocity(r); + }, + applyTorque: (adapter, r) => { + adapter.applyTorque(r, 1); + }, + setStatic: (adapter, r) => { + adapter.setStatic(r, false); + }, + setGravityScale: (adapter, r) => { + adapter.setGravityScale(r, 0.5); + }, + setFrictionAir: (adapter, r) => { + adapter.setFrictionAir(r, 0.1); + }, + setMaxVelocity: (adapter, r) => { + adapter.setMaxVelocity(r, { x: 3, y: 4 }); + }, + getMaxVelocity: (adapter, r) => { + return adapter.getMaxVelocity(r); + }, + setCollisionType: (adapter, r) => { + adapter.setCollisionType(r, collision.types.ENEMY_OBJECT); + }, + setCollisionMask: (adapter, r) => { + adapter.setCollisionMask(r, collision.types.PLAYER_OBJECT); + }, + setSensor: (adapter, r) => { + adapter.setSensor(r, true); + }, + isGrounded: (adapter, r) => { + return adapter.isGrounded(r); + }, +}; + +/** the methods that answer for a renderable with no body, as they always did */ +const DOES_WITHOUT = { + getVelocity: (adapter, r) => { + return adapter.getVelocity(r); + }, + getVelocity3d: (adapter, r) => { + return adapter.getVelocity3d(r); + }, + setPosition: (adapter, r) => { + adapter.setPosition(r, new Vector2d(5, 6)); + }, + getRotation: (adapter, r) => { + return adapter.getRotation(r); + }, + getAngularVelocity3d: (adapter, r) => { + return adapter.getAngularVelocity3d(r); + }, + getBodyAABB: (adapter, r) => { + return adapter.getBodyAABB(r, r.getBounds().clone()); + }, + getBodyShapes: (adapter, r) => { + return adapter.getBodyShapes(r); + }, +}; + +describe("BuiltinAdapter: the body it is handed", () => { + let app; + let adapter; + let world; + + beforeAll(async () => { + boot(); + app = new Application(800, 600, { + parent: "screen", + scale: "auto", + renderer: video.CANVAS, + }); + await app.init(); + }); + + afterAll(() => { + app?.destroy(); + }); + + beforeEach(() => { + adapter = new BuiltinAdapter(); + world = new World(0, 0, 800, 600, adapter); + }); + + const plain = () => { + return new Renderable(0, 0, 32, 32); + }; + const registered = () => { + const r = plain(); + adapter.addBody(r, { type: "dynamic", shapes: [new Rect(0, 0, 32, 32)] }); + return r; + }; + + describe("a method that needs a body", () => { + for (const [name, call] of Object.entries(NEEDS_A_BODY)) { + it(`${name}: says a renderable with no body has none`, () => { + const r = plain(); + expect(r.body).toBeUndefined(); + expect(() => { + call(adapter, r); + }).toThrow(TypeError); + expect(() => { + call(adapter, r); + }).toThrow(/no built-in body/); + }); + } + + it("says the same of a body of another kind, however alike", () => { + // what another adapter would leave on a renderable: the method + // names of a `Body`, and none of its state + const r = plain(); + r.body = Object.fromEntries( + Object.keys(NEEDS_A_BODY).map((name) => { + return [name, () => {}]; + }), + ); + for (const [name, call] of Object.entries(NEEDS_A_BODY)) { + expect(() => { + call(adapter, r); + }, name).toThrow(/no built-in body/); + } + }); + + it("works on a body the adapter made", () => { + for (const [name, call] of Object.entries(NEEDS_A_BODY)) { + const r = registered(); + expect(() => { + call(adapter, r); + }, name).not.toThrow(); + } + }); + + it("does what it did: the body takes what it was given", () => { + const r = registered(); + adapter.setVelocity(r, new Vector2d(1, 2)); + expect([r.body.vel.x, r.body.vel.y]).toEqual([1, 2]); + adapter.setAngle(r, 0.5); + expect(adapter.getAngle(r)).toBeCloseTo(0.5, 6); + adapter.setAngularVelocity(r, 2); + expect(adapter.getAngularVelocity(r)).toBe(2); + adapter.setStatic(r, true); + expect(r.body.isStatic).toBe(true); + adapter.setGravityScale(r, 0.25); + expect(r.body.gravityScale).toBe(0.25); + adapter.setMaxVelocity(r, { x: 3, y: 4 }); + expect(adapter.getMaxVelocity(r)).toEqual({ x: 3, y: 4 }); + adapter.setCollisionType(r, collision.types.ENEMY_OBJECT); + expect(r.body.collisionType).toBe(collision.types.ENEMY_OBJECT); + adapter.setCollisionMask(r, collision.types.PLAYER_OBJECT); + expect(r.body.collisionMask).toBe(collision.types.PLAYER_OBJECT); + adapter.setSensor(r, true); + expect(r.body.isSensor).toBe(true); + }); + + it("works on a body made by hand and never registered, the old way", () => { + // `this.body = new Body(this, shape)` in a constructor, with the + // adapter's methods called before the renderable is in a world + for (const [name, call] of Object.entries(NEEDS_A_BODY)) { + const r = plain(); + r.body = new Body(r, [new Rect(0, 0, 32, 32)]); + expect(adapter.bodies.has(r.body)).toBe(false); + expect(() => { + call(adapter, r); + }, name).not.toThrow(); + } + const r = plain(); + r.body = new Body(r, [new Rect(0, 0, 32, 32)]); + adapter.setVelocity(r, new Vector2d(7, 8)); + expect([r.body.vel.x, r.body.vel.y]).toEqual([7, 8]); + }); + + it("works on a class of the game's own that extends Body", () => { + class HeavyBody extends Body {} + for (const [name, call] of Object.entries(NEEDS_A_BODY)) { + const r = plain(); + r.body = new HeavyBody(r, [new Rect(0, 0, 32, 32)]); + expect(() => { + call(adapter, r); + }, name).not.toThrow(); + } + }); + }); + + describe("a method that does without a body", () => { + for (const [name, call] of Object.entries(DOES_WITHOUT)) { + it(`${name}: answers for a renderable with none`, () => { + const r = plain(); + expect(() => { + call(adapter, r); + }).not.toThrow(); + }); + } + + it("answers with nothing moving, and no shape", () => { + const r = plain(); + const v = adapter.getVelocity(r); + expect([v.x, v.y]).toEqual([0, 0]); + const v3 = adapter.getVelocity3d(r); + expect([v3.x, v3.y, v3.z]).toEqual([0, 0, 0]); + expect(adapter.getBodyShapes(r)).toHaveLength(0); + expect(adapter.getBodyAABB(r, r.getBounds().clone())).toBeUndefined(); + }); + }); + + describe("a raycast", () => { + const wall = (x) => { + const r = new Renderable(x, 100, 20, 100); + r.anchorPoint.set(0, 0); + r.isKinematic = false; + r.body = new Body(r, [new Rect(0, 0, 20, 100)]); + world.addChild(r); + return r; + }; + const rebuild = () => { + world.broadphase.clear(); + world.broadphase.insertContainer(world); + }; + + it("passes over what is in the broadphase with a body of another kind", () => { + const target = wall(300); + rebuild(); + // in the ray's way, nearer than the wall: one with a body that is + // not the adapter's, one with none + const foreign = new Renderable(150, 100, 20, 100); + foreign.anchorPoint.set(0, 0); + foreign.body = { collisionType: collision.types.ALL_OBJECT }; + const bare = new Renderable(200, 100, 20, 100); + bare.anchorPoint.set(0, 0); + world.broadphase.insert(foreign); + world.broadphase.insert(bare); + + let hit; + expect(() => { + hit = adapter.raycast(new Vector2d(0, 150), new Vector2d(600, 150)); + }).not.toThrow(); + expect(hit).not.toBeNull(); + expect(hit.renderable).toBe(target); + expect(hit.point.x).toBeCloseTo(300, 3); + }); + + it("still stops at the nearest of its own bodies", () => { + const near = wall(120); + wall(300); + rebuild(); + const hit = adapter.raycast(new Vector2d(0, 150), new Vector2d(600, 150)); + expect(hit.renderable).toBe(near); + }); + }); + + describe("the 3D queries", () => { + it("answer nothing in a 2D world", () => { + expect(world.sortOn).toBe("z"); + expect( + adapter.raycast3d(new Vector3d(0, 0, 0), new Vector3d(1, 1, 1)), + ).toBeNull(); + expect(adapter.querySphere(new Vector3d(0, 0, 0), 100)).toEqual([]); + }); + + it("answer in a world sorted by depth", () => { + world.sortOn = "depth"; + expect(() => { + adapter.raycast3d(new Vector3d(0, 0, 0), new Vector3d(1, 1, 1)); + adapter.querySphere(new Vector3d(0, 0, 0), 100); + }).not.toThrow(); + expect(adapter.querySphere(new Vector3d(0, 0, 0), 100)).toEqual([]); + }); + + it("answer nothing, and do not fail, where there is no octree to walk", () => { + // a world sorted by depth whose broadphase is something else: no + // octant to walk, so nothing found, as in a 2D world + world.sortOn = "depth"; + const octree = world.broadphase; + world.broadphase = { + retrieve: () => { + return []; + }, + clear: () => {}, + }; + try { + expect( + adapter.raycast3d(new Vector3d(0, 0, 0), new Vector3d(1, 1, 1)), + ).toBeNull(); + expect(adapter.querySphere(new Vector3d(0, 0, 0), 100)).toEqual([]); + } finally { + world.broadphase = octree; + } + }); + }); +}); diff --git a/packages/melonjs/tests/keyboard-events.spec.js b/packages/melonjs/tests/keyboard-events.spec.js new file mode 100644 index 0000000000..59e91f247b --- /dev/null +++ b/packages/melonjs/tests/keyboard-events.spec.js @@ -0,0 +1,191 @@ +/** + * Keys as the browser sends them, and as the engine triggers them itself. + * + * A key comes down two ways: pressed on the keyboard, with the browser's + * event, or triggered by the engine (`input.triggerKeyEvent`, a pointer + * button bound to a key) with no event at all. Both press the same action; + * only the first has a default action of the browser to stop. + */ +import { afterEach, beforeAll, describe, expect, it } from "vitest"; +import { boot, event, input } from "../src/index.js"; + +const KEYS = [input.KEY.LEFT, input.KEY.RIGHT, input.KEY.X, input.KEY.Z]; + +describe("keyboard events", () => { + beforeAll(() => { + // registers the keyboard listeners + boot(); + }); + + afterEach(() => { + for (const keyCode of KEYS) { + globalThis.dispatchEvent(new KeyboardEvent("keyup", { keyCode })); + input.triggerKeyEvent(keyCode, false); + input.triggerKeyEvent(keyCode, false, 1); + input.unbindKey(keyCode); + } + }); + + /** send a key event as the browser does, and hand it back */ + const press = (type, keyCode) => { + const sent = new KeyboardEvent(type, { keyCode, cancelable: true }); + globalThis.dispatchEvent(sent); + return sent; + }; + + describe("a key pressed on the keyboard", () => { + it("presses its action, and lets go of it", () => { + input.bindKey(input.KEY.LEFT, "left"); + expect(input.keyStatus("left")).toBe(false); + press("keydown", input.KEY.LEFT); + expect(input.keyStatus("left")).toBe(true); + expect(input.isKeyPressed("left")).toBe(true); + press("keyup", input.KEY.LEFT); + expect(input.keyStatus("left")).toBe(false); + }); + + it("is told from another key by its code", () => { + input.bindKey(input.KEY.LEFT, "left"); + input.bindKey(input.KEY.RIGHT, "right"); + press("keydown", input.KEY.RIGHT); + expect(input.keyStatus("right")).toBe(true); + expect(input.keyStatus("left")).toBe(false); + }); + + it("held down, counts once however often the browser repeats it", () => { + input.bindKey(input.KEY.LEFT, "left"); + press("keydown", input.KEY.LEFT); + press("keydown", input.KEY.LEFT); + press("keydown", input.KEY.LEFT); + press("keyup", input.KEY.LEFT); + expect(input.keyStatus("left")).toBe(false); + }); + + it("tells the KEYDOWN and KEYUP listeners the action and the key", () => { + input.bindKey(input.KEY.X, "fire"); + const heard = []; + const down = (action, keyCode) => { + heard.push(["down", action, keyCode]); + }; + const up = (action, keyCode) => { + heard.push(["up", action, keyCode]); + }; + event.on(event.KEYDOWN, down); + event.on(event.KEYUP, up); + try { + press("keydown", input.KEY.X); + press("keyup", input.KEY.X); + // a key with no binding is heard too, with no action + press("keydown", input.KEY.Z); + } finally { + event.off(event.KEYDOWN, down); + event.off(event.KEYUP, up); + } + expect(heard).toEqual([ + ["down", "fire", input.KEY.X], + ["up", "fire", input.KEY.X], + ["down", undefined, input.KEY.Z], + ]); + }); + }); + + describe("the browser's own action for the key", () => { + it("is stopped for a key bound with preventDefault, down and up", () => { + input.bindKey(input.KEY.LEFT, "left", false, true); + expect(press("keydown", input.KEY.LEFT).defaultPrevented).toBe(true); + expect(press("keyup", input.KEY.LEFT).defaultPrevented).toBe(true); + }); + + it("is left alone for a key bound without it", () => { + input.bindKey(input.KEY.RIGHT, "right", false, false); + expect(press("keydown", input.KEY.RIGHT).defaultPrevented).toBe(false); + expect(press("keyup", input.KEY.RIGHT).defaultPrevented).toBe(false); + // and the action is pressed all the same + press("keydown", input.KEY.RIGHT); + expect(input.keyStatus("right")).toBe(true); + }); + + it("is left alone for a key with no binding", () => { + expect(press("keydown", input.KEY.Z).defaultPrevented).toBe(false); + expect(press("keyup", input.KEY.Z).defaultPrevented).toBe(false); + }); + + it("is stopped for a key with no binding when the listener that uses it says so", () => { + // what a focused text field or button does with a key it takes + const uses = () => { + input.preventKeyDefault(); + }; + event.on(event.KEYDOWN, uses); + try { + expect(press("keydown", input.KEY.Z).defaultPrevented).toBe(true); + } finally { + event.off(event.KEYDOWN, uses); + } + // once the key event is over there is nothing left to stop + expect(() => { + input.preventKeyDefault(); + }).not.toThrow(); + expect(press("keydown", input.KEY.Z).defaultPrevented).toBe(false); + }); + + it("is not stopped by that for a key the engine triggered: it has no event", () => { + const uses = () => { + input.preventKeyDefault(); + }; + event.on(event.KEYDOWN, uses); + try { + expect(() => { + input.triggerKeyEvent(input.KEY.Z, true); + input.triggerKeyEvent(input.KEY.Z, false); + }).not.toThrow(); + } finally { + event.off(event.KEYDOWN, uses); + } + }); + }); + + describe("a key the engine triggers itself", () => { + it("presses its action with no browser event, bound with preventDefault or not", () => { + input.bindKey(input.KEY.X, "fire", false, true); + expect(() => { + input.triggerKeyEvent(input.KEY.X, true); + }).not.toThrow(); + expect(input.keyStatus("fire")).toBe(true); + expect(() => { + input.triggerKeyEvent(input.KEY.X, false); + }).not.toThrow(); + expect(input.keyStatus("fire")).toBe(false); + }); + + it("held by the key and by a pointer button, stays pressed until both let go", () => { + input.bindKey(input.KEY.X, "fire"); + // the key itself, then a pointer button standing in for it + press("keydown", input.KEY.X); + input.triggerKeyEvent(input.KEY.X, true, 1); + expect(input.keyStatus("fire")).toBe(true); + press("keyup", input.KEY.X); + expect(input.keyStatus("fire")).toBe(true); + input.triggerKeyEvent(input.KEY.X, false, 1); + expect(input.keyStatus("fire")).toBe(false); + }); + + it("the same button pressed twice counts once", () => { + input.bindKey(input.KEY.X, "fire"); + input.triggerKeyEvent(input.KEY.X, true, 1); + input.triggerKeyEvent(input.KEY.X, true, 1); + input.triggerKeyEvent(input.KEY.X, false, 1); + expect(input.keyStatus("fire")).toBe(false); + }); + + it("a locked key reads as pressed once, from the keyboard or triggered", () => { + input.bindKey(input.KEY.X, "fire", true); + press("keydown", input.KEY.X); + expect(input.isKeyPressed("fire")).toBe(true); + expect(input.isKeyPressed("fire")).toBe(false); + press("keyup", input.KEY.X); + input.triggerKeyEvent(input.KEY.X, true); + expect(input.isKeyPressed("fire")).toBe(true); + expect(input.isKeyPressed("fire")).toBe(false); + }); + }); +}); diff --git a/packages/melonjs/tests/mesh-reversed-winding.spec.js b/packages/melonjs/tests/mesh-reversed-winding.spec.js new file mode 100644 index 0000000000..2140e9ff56 --- /dev/null +++ b/packages/melonjs/tests/mesh-reversed-winding.spec.js @@ -0,0 +1,86 @@ +/** + * A mesh keeps a second copy of its indices with every triangle wound the + * other way round: one to draw with when its winding has to be flipped, one + * for the hull drawn as its outline. Both copies are of the same kind of + * array as the indices they were made from, so a mesh of more than 65535 + * vertices keeps 32-bit indices, and the indices given are left as they were. + */ +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { Application, boot, Mesh, video } from "../src/index.js"; + +/** two triangles sharing an edge: a quad, with the indices in a given array */ +const quad = (indices) => { + return { + vertices: new Float32Array([-1, -1, 0, 1, -1, 0, 1, 1, 0, -1, 1, 0]), + normals: new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]), + uvs: new Float32Array(8), + indices, + width: 2, + height: 2, + scale: 1, + normalize: false, + cullBackFaces: false, + castGroundShadow: false, + }; +}; + +const GIVEN = [0, 1, 2, 0, 2, 3]; +const REVERSED = [0, 2, 1, 0, 3, 2]; + +describe("a mesh's indices, wound the other way round", () => { + let app; + beforeAll(async () => { + boot(); + app = new Application(64, 64, { parent: "screen", renderer: video.CANVAS }); + await app.init(); + }); + afterAll(() => { + app?.destroy(); + }); + + for (const [kind, IndexArray] of [ + ["16-bit", Uint16Array], + ["32-bit", Uint32Array], + ]) { + describe(`${kind} indices`, () => { + it("the copy drawn when the winding is flipped is of the same kind", () => { + const given = new IndexArray(GIVEN); + const mesh = new Mesh(0, 0, quad(given)); + mesh._setupWorldSpace(true); + expect(mesh._indicesReversed).toBeInstanceOf(IndexArray); + expect(Array.from(mesh._indicesReversed)).toEqual(REVERSED); + // a copy: the indices given are as they were + expect(mesh._indicesReversed).not.toBe(given); + expect(Array.from(given)).toEqual(GIVEN); + expect(Array.from(mesh._indicesOriginal)).toEqual(GIVEN); + }); + + it("the outline's hull is wound the other way, in the same kind of array", () => { + const given = new IndexArray(GIVEN); + const mesh = new Mesh(0, 0, quad(given)); + const hull = mesh._outlineHull(0.1); + expect(hull.indices).toBeInstanceOf(IndexArray); + expect(Array.from(hull._indicesOriginal)).toEqual(REVERSED); + expect(Array.from(given)).toEqual(GIVEN); + }); + }); + } + + it("32-bit indices past 65535 are kept whole", () => { + // what a 16-bit copy would cut short: 70000 would come back as 4464 + const count = 70001; + const settings = quad(new Uint32Array([0, 69999, 70000])); + settings.vertices = new Float32Array(count * 3); + settings.normals = new Float32Array(count * 3); + settings.uvs = new Float32Array(count * 2); + const mesh = new Mesh(0, 0, settings); + mesh._setupWorldSpace(true); + expect(Array.from(mesh._indicesReversed)).toEqual([0, 70000, 69999]); + }); + + it("indices that do not end on a whole triangle: the odd ones are kept as given", () => { + const mesh = new Mesh(0, 0, quad(new Uint16Array([0, 1, 2, 0, 2]))); + mesh._setupWorldSpace(true); + expect(Array.from(mesh._indicesReversed)).toEqual([0, 2, 1, 0, 2]); + }); +}); From 5654feefe2949e18fa1ec6c41a956b0cfb1d39fd Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 05:00:34 +0000 Subject: [PATCH 24/51] Build: the engine is no longer linted by its own build The engine's build script began with its own lint, and the workspace lint builds first, then lints every package: the engine was linted twice by pnpm lint, and a third time in CI by the test job's build. The build now only builds. The lint stays where it guards something: pnpm lint, and the release scripts and the publish workflow, which call it by name. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- packages/melonjs/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/melonjs/package.json b/packages/melonjs/package.json index 5f66798de6..98ce0849ed 100644 --- a/packages/melonjs/package.json +++ b/packages/melonjs/package.json @@ -73,7 +73,7 @@ "tsc:watch": "tsc --project tsconfig.build.json --watch --noUnusedParameters false --noUnusedLocals false --preserveWatchOutput", "build:watch": "tsx scripts/build.js watch", "lint": "eslint src tests", - "build": "pnpm lint && tsx scripts/build.js && pnpm types", + "build": "tsx scripts/build.js && pnpm types", "dist": "pnpm clean && pnpm lint && pnpm vitest run && pnpm build && pnpm doc && cp ../../README.md .", "dist:publish": "pnpm clean && pnpm lint && pnpm build && pnpm doc && cp ../../README.md .", "doc": "tsx scripts/check-doc-readme.ts && pnpm doc:css && typedoc && tsx scripts/generate-llms-txt.ts", From df8797134e21904fae9836f645568bad825b228d Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 05:46:32 +0000 Subject: [PATCH 25/51] Lint: one package at a time, cached by Turborepo pnpm lint ran ESLint once over the whole workspace, in one process that loads every package's types together. Each package now has a lint script (eslint .) and turbo runs them: a package that has not changed, and whose dependencies have not, is skipped, and a change to the lint configuration re-lints them all. The files at the root and the scaffolder, which have no package script, are linted by lint:root. The same 1003 files are linted as before, with the same result. Unchanged, the ESLint part of pnpm lint takes no time at all where it took about a minute; after editing one plugin it takes 6 seconds. It also keeps each process small: the next typescript-eslint needs about 3 GB to lint the whole workspace in one process, and no more than the engine alone needs today when each package has its own. Changelog: a Chore section for this and for the dependency update. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- AGENTS.md | 5 +++++ CONTRIBUTING.md | 2 +- package.json | 3 ++- packages/capacitor-plugin/package.json | 1 + packages/debug-plugin/package.json | 2 +- packages/gamepad-plugin/package.json | 2 +- packages/matter-adapter/package.json | 2 +- packages/melonjs/CHANGELOG.md | 4 ++++ packages/melonjs/package.json | 2 +- packages/pathfinding-plugin/package.json | 2 +- packages/planck-adapter/package.json | 2 +- packages/rapier2d-adapter/package.json | 2 +- packages/rapier3d-adapter/package.json | 2 +- packages/spine-plugin/package.json | 1 + packages/tiled-inflate-plugin/package.json | 2 +- turbo.json | 5 +++++ 16 files changed, 28 insertions(+), 11 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index a795e85f4c..597b049461 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -52,6 +52,7 @@ pnpm dev # engine in watch mode + the examples sit pnpm test # the engine's browser tests (Vitest + Playwright) pnpm -F @melonjs/gamepad-plugin test # one package's tests (those that have them) pnpm lint # build, ESLint, Biome and the type checks +pnpm -F melonjs lint # ESLint on one package alone pnpm -F melonjs test:types # the engine's type check alone pnpm doc # the API docs, into packages/melonjs/docs/ ``` @@ -59,6 +60,10 @@ pnpm doc # the API docs, into packages/melonjs/doc Tests run in Chromium through Playwright: a renderer, a pointer and a canvas are real, so test through them rather than mocking them. +`pnpm lint` runs ESLint one package at a time through Turborepo, which caches +each result: a package that has not changed, and whose dependencies have not, +is skipped. A change to the engine re-lints the packages built on it. + ## Conventions - Tabs, strict equality, and the patterns of the code around the change; Biome diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 91ea4134d9..ea40f609f3 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -109,7 +109,7 @@ The output is written to `packages/melonjs/docs/` and can be viewed by opening ` ## Code style -melonJS uses [ESLint](https://eslint.org) and [Biome](https://biomejs.dev) to enforce consistent code style. Running `pnpm lint` will check your code against the project's rules. Key conventions: +melonJS uses [ESLint](https://eslint.org) and [Biome](https://biomejs.dev) to enforce consistent code style. Running `pnpm lint` will check your code against the project's rules. ESLint runs one package at a time and its results are cached, so a second run only looks at the packages that changed; `pnpm -F lint` checks one package alone. Key conventions: - Use tabs for indentation - Use strict equality (`===`) diff --git a/package.json b/package.json index 56279f7b3c..77aea74d04 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,8 @@ "scripts": { "build": "turbo build", "dev": "turbo dev", - "lint": "turbo build && eslint && biome check && turbo test:types", + "lint": "turbo build && turbo lint && pnpm lint:root && biome check && turbo test:types", + "lint:root": "eslint eslint.config.mjs vitest.workspace.ts scripts packages/create-melonjs", "test": "turbo build && vitest --config packages/melonjs/vitest.config.ts", "doc": "pnpm -F melonjs doc", "publish-melonjs": "gh workflow run publish.yml -f package=melonjs", diff --git a/packages/capacitor-plugin/package.json b/packages/capacitor-plugin/package.json index 63d0706815..73b5c185bd 100644 --- a/packages/capacitor-plugin/package.json +++ b/packages/capacitor-plugin/package.json @@ -74,6 +74,7 @@ "scripts": { "dev": "concurrently --raw \"pnpm build:watch\" \"pnpm tsc:watch\"", "build": "tsx scripts/build.ts && pnpm types", + "lint": "eslint .", "build:watch": "tsx scripts/build.ts watch", "prepublishOnly": "pnpm clean && pnpm build", "clean": "tsx scripts/clean.ts", diff --git a/packages/debug-plugin/package.json b/packages/debug-plugin/package.json index b647bbc04e..bb01473a1c 100644 --- a/packages/debug-plugin/package.json +++ b/packages/debug-plugin/package.json @@ -55,7 +55,7 @@ "dev": "concurrently --raw \"pnpm build:watch\" \"pnpm tsc:watch\"", "build": "tsx scripts/build.ts && pnpm types", "build:watch": "tsx scripts/build.ts watch", - "lint": "eslint src/**.js", + "lint": "eslint .", "prepublishOnly": "pnpm clean && pnpm build", "clean": "tsx scripts/clean.ts", "types": "tsc --project tsconfig.build.json", diff --git a/packages/gamepad-plugin/package.json b/packages/gamepad-plugin/package.json index 67368c81c2..3fb52c3c22 100644 --- a/packages/gamepad-plugin/package.json +++ b/packages/gamepad-plugin/package.json @@ -69,7 +69,7 @@ "tsc:watch": "tsc --project tsconfig.build.json --watch --noUnusedParameters false --noUnusedLocals false --preserveWatchOutput", "test": "vitest run", "test:types": "tsc", - "lint": "eslint src tests", + "lint": "eslint .", "visual": "vite --config visual/vite.config.ts" } } diff --git a/packages/matter-adapter/package.json b/packages/matter-adapter/package.json index fa191d6b8e..170447fe5f 100644 --- a/packages/matter-adapter/package.json +++ b/packages/matter-adapter/package.json @@ -61,7 +61,7 @@ "dev": "concurrently --raw \"pnpm build:watch\" \"pnpm tsc:watch\"", "build": "tsx scripts/build.ts && pnpm types", "build:watch": "tsx scripts/build.ts watch", - "lint": "eslint src/**.ts", + "lint": "eslint .", "prepublishOnly": "pnpm clean && pnpm build", "clean": "tsx scripts/clean.ts", "types": "tsc --project tsconfig.build.json", diff --git a/packages/melonjs/CHANGELOG.md b/packages/melonjs/CHANGELOG.md index c20591f74e..dcfa66a165 100644 --- a/packages/melonjs/CHANGELOG.md +++ b/packages/melonjs/CHANGELOG.md @@ -23,6 +23,10 @@ - glTF: a model compressed with Draco or meshopt, which the loader cannot decode, says so in the console, naming the extension, instead of failing on an accessor error that did not mention it - Physics: a method of the built-in adapter (`setVelocity`, `applyForce`, `setStatic` and the like) called on a renderable with no body says so, `this renderable has no built-in body`, where it failed on a property of `undefined`; and a raycast passes over an object whose body is not one of the adapter's, where it threw +### Chore +- Dependencies: the 46 known vulnerabilities the security audit reported in the development tools are cleared (vite 8.3.8, vitest 4.1.12, serve 14.2.8, and overrides for what they depend on). None was in a dependency of a published package +- Lint: each package is linted on its own and Turborepo caches the result, so `pnpm lint` skips the packages that have not changed; and the engine is no longer linted a second time by its own build + ## [20.16.0] (melonJS 2) - _2026-11-17_ **Highlights:** a faster `Camera3d`, its work per frame up to **72%** faster with no change to your game, and real 3D physics: with the new `@melonjs/rapier3d-adapter`, bodies tumble, stack and topple in 3D, with collision shapes built straight from your models. Also new: skinned glTF characters with crossfades, mesh picking, an orthographic `Camera3d` for isometric views, and toon shading with outlines. The new features are opt-in: a game that sets none of them renders as before. diff --git a/packages/melonjs/package.json b/packages/melonjs/package.json index 98ce0849ed..c38c4fc497 100644 --- a/packages/melonjs/package.json +++ b/packages/melonjs/package.json @@ -72,7 +72,7 @@ "dev": "concurrently --raw \"pnpm build:watch\" \"pnpm tsc:watch\" \"pnpm doc:watch\"", "tsc:watch": "tsc --project tsconfig.build.json --watch --noUnusedParameters false --noUnusedLocals false --preserveWatchOutput", "build:watch": "tsx scripts/build.js watch", - "lint": "eslint src tests", + "lint": "eslint .", "build": "tsx scripts/build.js && pnpm types", "dist": "pnpm clean && pnpm lint && pnpm vitest run && pnpm build && pnpm doc && cp ../../README.md .", "dist:publish": "pnpm clean && pnpm lint && pnpm build && pnpm doc && cp ../../README.md .", diff --git a/packages/pathfinding-plugin/package.json b/packages/pathfinding-plugin/package.json index 52ff03231c..1209e87c00 100644 --- a/packages/pathfinding-plugin/package.json +++ b/packages/pathfinding-plugin/package.json @@ -67,7 +67,7 @@ "tsc:watch": "tsc --project tsconfig.build.json --watch --noUnusedParameters false --noUnusedLocals false --preserveWatchOutput", "test": "vitest run", "test:types": "tsc", - "lint": "eslint src tests", + "lint": "eslint .", "visual": "vite --config visual/vite.config.ts" } } diff --git a/packages/planck-adapter/package.json b/packages/planck-adapter/package.json index cc029e8a44..d4d9991745 100644 --- a/packages/planck-adapter/package.json +++ b/packages/planck-adapter/package.json @@ -63,7 +63,7 @@ "dev": "concurrently --raw \"pnpm build:watch\" \"pnpm tsc:watch\"", "build": "tsx scripts/build.ts && pnpm types", "build:watch": "tsx scripts/build.ts watch", - "lint": "eslint src/**.ts", + "lint": "eslint .", "prepublishOnly": "pnpm clean && pnpm build", "clean": "tsx scripts/clean.ts", "types": "tsc --project tsconfig.build.json", diff --git a/packages/rapier2d-adapter/package.json b/packages/rapier2d-adapter/package.json index 561d1b5b1f..aa5a522619 100644 --- a/packages/rapier2d-adapter/package.json +++ b/packages/rapier2d-adapter/package.json @@ -62,7 +62,7 @@ "dev": "concurrently --raw \"pnpm build:watch\" \"pnpm tsc:watch\"", "build": "tsx scripts/build.ts && pnpm types", "build:watch": "tsx scripts/build.ts watch", - "lint": "eslint src/**.ts", + "lint": "eslint .", "prepublishOnly": "pnpm clean && pnpm build", "clean": "tsx scripts/clean.ts", "types": "tsc --project tsconfig.build.json", diff --git a/packages/rapier3d-adapter/package.json b/packages/rapier3d-adapter/package.json index a096239c4a..444bd2afb5 100644 --- a/packages/rapier3d-adapter/package.json +++ b/packages/rapier3d-adapter/package.json @@ -62,7 +62,7 @@ "dev": "concurrently --raw \"pnpm build:watch\" \"pnpm tsc:watch\"", "build": "tsx scripts/build.ts && pnpm types", "build:watch": "tsx scripts/build.ts watch", - "lint": "eslint src/**.ts", + "lint": "eslint .", "prepublishOnly": "pnpm clean && pnpm build", "clean": "tsx scripts/clean.ts", "types": "tsc --project tsconfig.build.json", diff --git a/packages/spine-plugin/package.json b/packages/spine-plugin/package.json index cfea3b9097..ace96e02e6 100644 --- a/packages/spine-plugin/package.json +++ b/packages/spine-plugin/package.json @@ -63,6 +63,7 @@ "scripts": { "dev": "concurrently --raw \"pnpm build:watch\" \"pnpm tsc:watch\"", "build": "tsx scripts/build.ts && pnpm types", + "lint": "eslint .", "build:watch": "tsx scripts/build.ts watch", "prepublishOnly": "pnpm clean && pnpm build", "clean": "tsx scripts/clean.ts", diff --git a/packages/tiled-inflate-plugin/package.json b/packages/tiled-inflate-plugin/package.json index 6a1496d7a4..183a7de491 100644 --- a/packages/tiled-inflate-plugin/package.json +++ b/packages/tiled-inflate-plugin/package.json @@ -60,6 +60,6 @@ "types": "tsc --project tsconfig.build.json", "test": "vitest run", "test:types": "tsc", - "lint": "eslint src tests" + "lint": "eslint ." } } diff --git a/turbo.json b/turbo.json index b9db02d520..331a496132 100644 --- a/turbo.json +++ b/turbo.json @@ -9,6 +9,11 @@ "persistent": true, "cache": false }, + "lint": { + "dependsOn": ["^build"], + "inputs": ["$TURBO_DEFAULT$", "$TURBO_ROOT$/eslint.config.mjs"], + "outputs": [] + }, "test:types": {} } } From 1d212994abdc761607fcdd7aa320e70e37b31a4f Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 07:20:50 +0000 Subject: [PATCH 26/51] CI: keep Turborepo's cache between runs Each CI job started with an empty cache, so every package was built, linted and type-checked on every run, and the test job built again what the lint job had just built. The lint, test and Windows jobs now restore .turbo from the latest run and save it at the end. A task is skipped only when the fingerprint of its files and dependencies is unchanged, so a stale cache is not used, not trusted. The lockfile is part of the key, so the cache starts afresh when dependencies change. One run's cache is about 48 MB. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- .github/workflows/main.yml | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 133521f4c1..f01a7eb340 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -37,6 +37,19 @@ jobs: path: ${{ env.STORE_PATH }} key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} restore-keys: ${{ runner.os }}-pnpm-store- + # Turborepo's cache: what each package's build, lint and type check gave, + # by a fingerprint of its files and of what it depends on. Restored from + # the latest run, a task whose fingerprint is unchanged is skipped, so a + # change that leaves a package alone does not build or lint it again, and + # the test job reuses what the lint job built. An entry that no longer + # matches is simply not used: a stale cache cannot give a wrong result. + # The lockfile is in the key so the cache starts afresh when dependencies + # change, which is when most of it stops matching anyway. + - uses: actions/cache@v5 + with: + path: .turbo + key: ${{ runner.os }}-turbo-${{ hashFiles('pnpm-lock.yaml') }}-${{ github.sha }} + restore-keys: ${{ runner.os }}-turbo-${{ hashFiles('pnpm-lock.yaml') }}- - run: pnpm i - run: pnpm lint - run: pnpm biome check @@ -62,6 +75,12 @@ jobs: path: ${{ env.STORE_PATH }} key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} restore-keys: ${{ runner.os }}-pnpm-store- + # Turborepo's cache (see the lint job) + - uses: actions/cache@v5 + with: + path: .turbo + key: ${{ runner.os }}-turbo-${{ hashFiles('pnpm-lock.yaml') }}-${{ github.sha }} + restore-keys: ${{ runner.os }}-turbo-${{ hashFiles('pnpm-lock.yaml') }}- - run: pnpm i # Vitest 4.1.11 runs each worker as one long-lived orchestrator page and # dispatches every spec file over a single websocket. Its ws close handler @@ -129,6 +148,12 @@ jobs: path: ${{ env.STORE_PATH }} key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} restore-keys: ${{ runner.os }}-pnpm-store- + # Turborepo's cache (see the lint job) + - uses: actions/cache@v5 + with: + path: .turbo + key: ${{ runner.os }}-turbo-${{ hashFiles('pnpm-lock.yaml') }}-${{ github.sha }} + restore-keys: ${{ runner.os }}-turbo-${{ hashFiles('pnpm-lock.yaml') }}- - run: pnpm i - run: pnpm lint - run: pnpm build From fe2ab5e00db0dde8ebc659ea2a82e452f07955b0 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 07:33:44 +0000 Subject: [PATCH 27/51] Lint: a package is re-linted for another's published types, not for its source The lint task depended on the build of what a package depends on, so any change in the engine, a comment included, re-linted every plugin and adapter. What their lint actually reads from another package is its published types: the lint task now takes those (packages/*/build/**/*.d.ts) and the shared TypeScript settings as inputs, and no longer depends on the build task. A change inside the engine that leaves its types as they were re-lints the engine alone; one that changes them re-lints everything, as does a change to the lint configuration or to the shared settings. pnpm lint builds first, as before, so the types read are current. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- AGENTS.md | 6 ++++-- turbo.json | 8 ++++++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 597b049461..3a0cb67f6b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -61,8 +61,10 @@ Tests run in Chromium through Playwright: a renderer, a pointer and a canvas are real, so test through them rather than mocking them. `pnpm lint` runs ESLint one package at a time through Turborepo, which caches -each result: a package that has not changed, and whose dependencies have not, -is skipped. A change to the engine re-lints the packages built on it. +each result: a package that has not changed is skipped. A package is linted +against the published types of the others (`build/**/*.d.ts`), so a change +inside the engine re-lints the plugins and adapters only when it changes those +types. ## Conventions diff --git a/turbo.json b/turbo.json index 331a496132..c8e34de93c 100644 --- a/turbo.json +++ b/turbo.json @@ -10,8 +10,12 @@ "cache": false }, "lint": { - "dependsOn": ["^build"], - "inputs": ["$TURBO_DEFAULT$", "$TURBO_ROOT$/eslint.config.mjs"], + "inputs": [ + "$TURBO_DEFAULT$", + "$TURBO_ROOT$/eslint.config.mjs", + "$TURBO_ROOT$/packages/tsconfig/**", + "$TURBO_ROOT$/packages/*/build/**/*.d.ts" + ], "outputs": [] }, "test:types": {} From 50dd8f6db9e447e1aecd24caf739da231bf843a5 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 08:38:48 +0000 Subject: [PATCH 28/51] CI: Biome runs once in the lint job The lint job ran pnpm lint, which ends with biome check, and then biome check again as a step of its own. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- .github/workflows/main.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index f01a7eb340..83ea4aaca1 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -51,8 +51,8 @@ jobs: key: ${{ runner.os }}-turbo-${{ hashFiles('pnpm-lock.yaml') }}-${{ github.sha }} restore-keys: ${{ runner.os }}-turbo-${{ hashFiles('pnpm-lock.yaml') }}- - run: pnpm i + # ESLint for each package, Biome and the type checks, after a build - run: pnpm lint - - run: pnpm biome check - run: pnpm build test: From 0db9590d039a5da0cfdacdaaa4ca6fce1e16df3d Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 08:39:51 +0000 Subject: [PATCH 29/51] CI: the test job shares the lint job's caches The cache action compresses with zstd where it is installed and with gzip where it is not, and looks only for caches saved the same way. The test job runs in the Playwright image, which has no zstd, so it kept caches of its own and never found what the lint job had saved: it built every package again. With zstd installed there, it restores the lint job's cache. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- .github/workflows/main.yml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 83ea4aaca1..fb8383f38f 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -67,6 +67,12 @@ jobs: uses: actions/setup-node@v6 with: node-version: 24 + # The cache steps below compress with zstd where it is installed and with + # gzip where it is not, and a cache saved one way is not found the other. + # This image has no zstd: with it, the job reads the caches the lint job + # saved, and so the build it has just made. + - name: Install zstd, to share caches with the lint job + run: apt-get update -qq && apt-get install -y -qq zstd - uses: pnpm/action-setup@v5 - name: Get pnpm store directory run: echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV From 65e8a26e93f58077f1957a1ef24d9fe1446f3075 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 14:31:10 +0000 Subject: [PATCH 30/51] Tests: the browser keeps a module for the length of a one-shot run Vite serves every source module as no-cache, and Vitest does the same for its own, so in every spec file the browser asked again for each of them: some 450 requests a file, all answered "not modified". Chromium keeps a 2 MiB shared-memory buffer, a file in the temporary folder, and an open handle on it for every module script re-validated that way, until its garbage collector next runs. Vitest runs every spec file in an iframe of one long-lived page and nothing makes the collector run, so they pile up: a page reached 11,467 handles and 22.6 GB of temporary files in an ordinary passing run. A page limited to 8,192 handles stops loading modules when it gets there and the run hangs; a full temporary folder fails the module loads instead. A page that loads 400 modules in an iframe twice shows the same buffers with no engine and no Vitest involved, and none once the modules are served with max-age. In a one-shot run nothing changes on disk, so the test server now answers max-age and the browser does not ask. Measured over the 502 spec files: - handles held by a page, at most: 11,467 -> 328 - temporary files at most: about 24 GB -> 143 MB - the suite: 338 s -> 201 s Watch mode is unchanged, since a module edited between two runs has to be asked for again. A spec file that mocks a module still gets its mock, and the next one the real module. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- packages/melonjs/vitest.config.ts | 77 ++++++++++++++++++++++++++++++- 1 file changed, 76 insertions(+), 1 deletion(-) diff --git a/packages/melonjs/vitest.config.ts b/packages/melonjs/vitest.config.ts index 9459ff8022..5f35c7e793 100644 --- a/packages/melonjs/vitest.config.ts +++ b/packages/melonjs/vitest.config.ts @@ -1,11 +1,12 @@ /// /// +import { ServerResponse } from "node:http"; import { dirname, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { playwright } from "@vitest/browser-playwright"; import { PackageJson } from "type-fest"; import { default as glsl } from "vite-plugin-glsl"; -import { defineConfig } from "vitest/config"; +import { defineConfig, type Plugin } from "vitest/config"; import { stripShaderComments } from "./scripts/strip-shader-comments.ts"; const __dirname = dirname(fileURLToPath(import.meta.url)); @@ -21,6 +22,79 @@ if (!version) { throw new Error("Version missing from package.json"); } +// Set by the plugin below once Vitest says the run is a one-shot one. An +// environment variable, because Vitest evaluates this file once per server it +// starts, and the server that feeds the browser is not the one it configures. +const ONE_SHOT = "MELONJS_TESTS_ONE_SHOT"; + +// a day: longer than any run +const KEPT_FOR_THE_RUN = "max-age=86400"; + +/** + * In a one-shot run, lets the browser keep a module for the rest of the run. + * + * Vite serves every source module as `no-cache`, and Vitest does the same for + * its own. So the browser asks again for each of them in every spec file, some + * 450 requests a file, and all the server answers is "not modified". Two things + * follow. + * + * It is slow: asking was 40% of the suite's time. + * + * And Chromium keeps a 2 MiB shared-memory buffer, a file in the temporary + * folder, and an open handle on it for every module script re-validated that + * way, until its garbage collector next runs. A page that loads 400 modules in + * an iframe twice shows it, with no engine and no Vitest involved. Vitest runs + * every spec file in an iframe of one long-lived page, and nothing makes the + * collector run: measured on this suite, a page reached 11,000 handles and + * 22 GB of temporary files. A page that runs out of handles stops loading + * modules, and the run hangs on whichever spec file is next; a full temporary + * folder fails the module loads instead. + * + * Nothing changes on disk during a one-shot run, so there the answer can be + * `max-age`, and the browser does not ask: a page then stays at a few hundred + * handles. + * A spec file that mocks a module still gets its mock, and the next one the + * real module (checked both ways round). + * + * Watch mode is left alone: a module edited between two runs has to be asked + * for again. + * @returns the plugin + */ +function keepModulesForTheRun(): Plugin { + return { + name: "melonjs:keep-modules-for-the-run", + configureVitest({ vitest }) { + // not `=== false`: without a terminal Vitest leaves it unset + if (!vitest.config.watch) { + process.env[ONE_SHOT] = "1"; + } + }, + configureServer(server) { + server.middlewares.use((req, res, next) => { + if ( + process.env[ONE_SHOT] !== undefined && + req.headers["sec-fetch-dest"] === "script" + ) { + // the prototype's, because Vitest replaces the response's own + // with one that ignores this header, for its own modules + const setHeader = ServerResponse.prototype.setHeader.bind(res); + // set by a middleware that ran before this one + if (res.getHeader("Cache-Control") === "no-cache") { + setHeader("Cache-Control", KEPT_FOR_THE_RUN); + } + // and by the ones that run after it + res.setHeader = (name, value) => { + const kept = + name.toLowerCase() === "cache-control" && value === "no-cache"; + return setHeader(name, kept ? KEPT_FOR_THE_RUN : value); + }; + } + next(); + }); + }, + }; +} + export default defineConfig(() => defineConfig({ // Anchor to this package. `pnpm test` invokes this config from the repo @@ -111,6 +185,7 @@ export default defineConfig(() => }, publicDir: resolve(__dirname, "tests/public"), plugins: [ + keepModulesForTheRun(), // the shaders as the build ships them, without their comments // (see `scripts/build.ts`): the tests compile the same text glsl({ From 62dde2e2246211d868c273eba96883026d8822cc Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 14:52:14 +0000 Subject: [PATCH 31/51] Tests: the tile-layer benchmark runs when asked for, and watch mode releases its buffers The tile-layer benchmark ran in every run, twenty seconds of it, though benchmarks are meant to run only with BENCH=1 as the mesh one does. It is now skipped, visibly, unless asked for. It tests nothing the tile-layer specs do not. A one-shot run no longer makes the browser re-validate its modules, which watch mode cannot do: an edited module has to be asked for again. So in watch mode a page still gathered a 2 MiB buffer and a file handle per module and per spec file, 11,467 handles at the most measured. It now collects garbage at the end of every spec file, in watch mode only: a page then held 468 handles at most over the whole suite. A one-shot run is not given the collection, because it also empties the browser's own store of modules and takes back what keeping them gained (344 s with both, 201 s with the modules kept alone). The whole suite, one-shot: 338 s before these changes, 177 s now. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- .../melonjs/tests/helpers/collect-garbage.js | 19 +++++++++++++++++ packages/melonjs/tests/tmxlayer_bench.spec.js | 11 ++++++++++ packages/melonjs/vitest.config.ts | 21 ++++++++++++++++--- 3 files changed, 48 insertions(+), 3 deletions(-) create mode 100644 packages/melonjs/tests/helpers/collect-garbage.js diff --git a/packages/melonjs/tests/helpers/collect-garbage.js b/packages/melonjs/tests/helpers/collect-garbage.js new file mode 100644 index 0000000000..ebd5d37482 --- /dev/null +++ b/packages/melonjs/tests/helpers/collect-garbage.js @@ -0,0 +1,19 @@ +import { afterAll, inject } from "vitest"; + +/** + * In watch mode, collects garbage once at the end of every spec file. + * + * Chromium keeps a 2 MiB shared-memory buffer and a file handle for every + * module a spec file re-validated with the server, until its garbage + * collector next runs, and nothing makes it run: see `keepModulesForTheRun` + * in `vitest.config.ts`, which is also where a one-shot run avoids the + * buffers altogether and so has no use for this. With a collection per file, + * a page holds one spec file's buffers at most. + * + * `gc` exists because the config starts the browser with `--expose-gc`. + */ +if (inject("collectGarbage") === true) { + afterAll(() => { + globalThis.gc?.(); + }); +} diff --git a/packages/melonjs/tests/tmxlayer_bench.spec.js b/packages/melonjs/tests/tmxlayer_bench.spec.js index bd8f38f9ec..7a64059d33 100644 --- a/packages/melonjs/tests/tmxlayer_bench.spec.js +++ b/packages/melonjs/tests/tmxlayer_bench.spec.js @@ -29,6 +29,10 @@ import { * The canvas is a quarter of the view's size each way, and the camera * zoomed out to match: as many tiles are in view, and walked, as in the * view named, with a sixteenth of the pixels for the software rasterizer. + * + * It runs only when asked for: `BENCH=1 pnpm vitest run --config + * packages/melonjs/vitest.config.ts tests/tmxlayer_bench.spec.js`, from the + * repository's root. */ const SCALE = 4; @@ -113,6 +117,13 @@ describe("tile layer benchmark: tile by tile against the GPU path", () => { ctx.skip("WebGL not available: nothing to measure"); return; } + // Skipped unless asked for, and visibly so: it measures and tests + // nothing the tile layer specs do not, and it is twenty seconds of + // every run otherwise. + if (import.meta.env.VITE_BENCH === "") { + ctx.skip("benchmark: run it with BENCH=1"); + return; + } const gl = app.renderer.gl; const pixel = new Uint8Array(4); const frame = () => { diff --git a/packages/melonjs/vitest.config.ts b/packages/melonjs/vitest.config.ts index 5f35c7e793..91d729c248 100644 --- a/packages/melonjs/vitest.config.ts +++ b/packages/melonjs/vitest.config.ts @@ -22,6 +22,13 @@ if (!version) { throw new Error("Version missing from package.json"); } +declare module "vitest" { + interface ProvidedContext { + /** true in watch mode: see `keepModulesForTheRun` below */ + collectGarbage: boolean; + } +} + // Set by the plugin below once Vitest says the run is a one-shot one. An // environment variable, because Vitest evaluates this file once per server it // starts, and the server that feeds the browser is not the one it configures. @@ -56,17 +63,23 @@ const KEPT_FOR_THE_RUN = "max-age=86400"; * A spec file that mocks a module still gets its mock, and the next one the * real module (checked both ways round). * - * Watch mode is left alone: a module edited between two runs has to be asked - * for again. + * Watch mode cannot do that: a module edited between two runs has to be asked + * for again. There the buffers are released instead, by a garbage collection + * at the end of every spec file (`tests/helpers/collect-garbage.js`). It costs + * a sixth more time, and is no use in a one-shot run: a collection also + * empties the browser's own store of modules, which undoes the gain above. * @returns the plugin */ function keepModulesForTheRun(): Plugin { return { name: "melonjs:keep-modules-for-the-run", - configureVitest({ vitest }) { + configureVitest({ vitest, project }) { // not `=== false`: without a terminal Vitest leaves it unset if (!vitest.config.watch) { process.env[ONE_SHOT] = "1"; + } else { + // read by tests/helpers/collect-garbage.js + project.provide("collectGarbage", true); } }, configureServer(server) { @@ -115,6 +128,8 @@ export default defineConfig(() => include: ["tests/**/*.{test,spec}.[jt]s?(x)"], // servers on other origins, for the loader's cross-origin tests globalSetup: ["tests/helpers/cors-servers.js"], + // in watch mode, a garbage collection at the end of every spec file + setupFiles: ["tests/helpers/collect-garbage.js"], // Several specs create a WebGL context in `beforeAll`. On a CI // container with no GPU that runs through a software rasterizer and // can genuinely take tens of seconds under load, so the default hook From 432693cd74c44a152fddfecfdbf8795952fd9edb Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 14:52:16 +0000 Subject: [PATCH 32/51] TEMPORARY: CI compares a run that re-validates its modules with one that keeps them To be removed before this pull request is merged. The test job runs twice, once as it is meant to and once with the test server making the browser re-validate every module as it did before, and a sampler prints what the test pages held in each: file handles, shared-memory buffers, free space in the temporary folder, the limits, and any browser process that went away, with what it held a second before. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- .github/page-resources.mjs | 101 ++++++++++++++++++++++++++++++ .github/workflows/main.yml | 16 +++++ packages/melonjs/vitest.config.ts | 5 ++ 3 files changed, 122 insertions(+) create mode 100644 .github/page-resources.mjs diff --git a/.github/page-resources.mjs b/.github/page-resources.mjs new file mode 100644 index 0000000000..b4f571b85b --- /dev/null +++ b/.github/page-resources.mjs @@ -0,0 +1,101 @@ +// TEMPORARY, for one pull request: records what the test pages hold while the +// engine's tests run, to compare a run that re-validates its modules with one +// that keeps them. Removed before the pull request is merged. +import { readdirSync, readFileSync, statfsSync } from "node:fs"; + +const started = Date.now(); +const seconds = () => { + return `${String(Math.round((Date.now() - started) / 1000)).padStart(4)}s`; +}; +const free = () => { + const s = statfsSync(process.env.TMPDIR ?? "/tmp"); + return Math.round((s.bavail * s.bsize) / 2 ** 20); +}; +const peak = { + handles: 0, + buffersMB: 0, + lowestFreeMB: free(), + firstFreeMB: free(), +}; +const seen = new Map(); +let limits = ""; + +function sample() { + peak.lowestFreeMB = Math.min(peak.lowestFreeMB, free()); + const alive = new Set(); + for (const pid of readdirSync("/proc")) { + if (!/^\d+$/.test(pid)) { + continue; + } + try { + const cmd = readFileSync(`/proc/${pid}/cmdline`, "utf8"); + if (!/chrome|headless/.test(cmd)) { + continue; + } + const type = /--type=([a-z-]+)/.exec(cmd)?.[1] ?? "browser"; + const handles = readdirSync(`/proc/${pid}/fd`).length; + let buffers = 0; + if (type === "renderer") { + for (const line of readFileSync(`/proc/${pid}/maps`, "utf8").split( + "\n", + )) { + if (line.includes("(deleted)")) { + const [from, to] = line.split(" ")[0].split("-"); + buffers += parseInt(to, 16) - parseInt(from, 16); + } + } + if (limits === "") { + limits = readFileSync(`/proc/${pid}/limits`, "utf8") + .split("\n") + .find((line) => { + return line.startsWith("Max open files"); + }) + .replace(/\s+/g, " "); + console.log(`${seconds()} a page's own limit: ${limits}`); + } + } + const buffersMB = Math.round(buffers / 2 ** 20); + alive.add(pid); + seen.set(pid, { type, handles, buffersMB }); + if (type === "renderer") { + peak.handles = Math.max(peak.handles, handles); + peak.buffersMB = Math.max(peak.buffersMB, buffersMB); + } + } catch { + // the process went away between the listing and the read + } + } + for (const [pid, last] of seen) { + if (!alive.has(pid)) { + seen.delete(pid); + console.log( + `${seconds()} ${last.type} ${pid} is gone: it held ${last.handles} handles and ${last.buffersMB} MB of buffers a second before, temp free ${free()} MB`, + ); + } + } +} + +let ticks = 0; +const timer = setInterval(() => { + sample(); + if (++ticks % 15 === 0) { + const pages = [...seen.values()].filter((p) => { + return p.type === "renderer"; + }); + console.log( + `${seconds()} pages: ${pages + .map((p) => { + return `${p.handles} handles / ${p.buffersMB} MB`; + }) + .join(", ")} | temp free ${free()} MB`, + ); + } +}, 1000); + +process.on("SIGTERM", () => { + clearInterval(timer); + console.log( + `SUMMARY most handles held by one page: ${peak.handles} | most buffers held by one page: ${peak.buffersMB} MB | temp free: ${peak.firstFreeMB} MB at the start, ${peak.lowestFreeMB} MB at the lowest`, + ); + process.exit(0); +}); diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index fb8383f38f..66456481dc 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -58,6 +58,14 @@ jobs: test: needs: lint runs-on: ubuntu-latest + # TEMPORARY, for this pull request only: the job runs twice, once as it is + # meant to and once with the test server making the browser re-validate + # every module, as it did before, to compare what the pages hold. + strategy: + fail-fast: false + matrix: + modules: [kept, revalidated] + continue-on-error: ${{ matrix.modules == 'revalidated' }} container: # must match the workspace's playwright version (root devDependencies) image: mcr.microsoft.com/playwright:v1.62.1-noble @@ -111,8 +119,16 @@ jobs: # dash, which has no `pipefail` — and without it the exit status of # `pnpm test` is masked by `tee` shell: bash + env: + MELONJS_TESTS_REVALIDATE: ${{ matrix.modules == 'revalidated' && '1' || '' }} run: | set -o pipefail + # TEMPORARY: see the comment on the job + echo "handle limit of this shell (soft/hard): $(ulimit -Sn)/$(ulimit -Hn)" + df -h /tmp + node .github/page-resources.mjs > page-resources.log 2>&1 & + sampler=$! + trap 'kill -TERM "$sampler" 2>/dev/null; sleep 2; echo "--- page resources ---"; cat page-resources.log' EXIT for attempt in 1 2; do if pnpm test 2>&1 | tee "test-$attempt.log"; then exit 0 diff --git a/packages/melonjs/vitest.config.ts b/packages/melonjs/vitest.config.ts index 91d729c248..42071d786e 100644 --- a/packages/melonjs/vitest.config.ts +++ b/packages/melonjs/vitest.config.ts @@ -74,6 +74,11 @@ function keepModulesForTheRun(): Plugin { return { name: "melonjs:keep-modules-for-the-run", configureVitest({ vitest, project }) { + // TEMPORARY, for one pull request: the CI job that compares a run + // re-validating its modules with one that keeps them + if (process.env.MELONJS_TESTS_REVALIDATE) { + return; + } // not `=== false`: without a terminal Vitest leaves it unset if (!vitest.config.watch) { process.env[ONE_SHOT] = "1"; From cd2e86d8f2a32b7988e72ec848af5d961f3e03c4 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 15:02:38 +0000 Subject: [PATCH 33/51] Changelog: the faster test suite, under Chore Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- packages/melonjs/CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/melonjs/CHANGELOG.md b/packages/melonjs/CHANGELOG.md index dcfa66a165..64a07b4057 100644 --- a/packages/melonjs/CHANGELOG.md +++ b/packages/melonjs/CHANGELOG.md @@ -26,6 +26,7 @@ ### Chore - Dependencies: the 46 known vulnerabilities the security audit reported in the development tools are cleared (vite 8.3.8, vitest 4.1.12, serve 14.2.8, and overrides for what they depend on). None was in a dependency of a published package - Lint: each package is linted on its own and Turborepo caches the result, so `pnpm lint` skips the packages that have not changed; and the engine is no longer linted a second time by its own build +- Tests: the engine's suite runs in about half the time (338 s to 177 s on a four-core machine), and its test pages no longer pile up temporary files and open file handles (up to 24 GB and 11,000 handles in one run before). In a one-shot run the browser keeps each module instead of asking the test server for it again in every spec file; watch mode releases what it gathers after each spec file; and the tile-layer benchmark runs only with `BENCH=1` ## [20.16.0] (melonJS 2) - _2026-11-17_ From 48f011b2f768ddf2352b02d1a48d0c69f8451faf Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 15:06:52 +0000 Subject: [PATCH 34/51] TEMPORARY: CI runs the test job twelve times and logs what a lost page was doing To be removed before this pull request is merged. The first comparison showed the buffers pile up on CI as they do locally (12,739 handles and 25 GB in one page when re-validating, 200 handles when not) but with room to spare there: a page may hold 65,536 handles and 85 GB were free. So it does not explain the page lost on master. This runs six copies each way, and has the test runner log a page that crashes, closes or loses its websocket, with the close code, and the sampler the memory available. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- .github/instrument-test-runner.mjs | 95 ++++++++++++++++++++++++++++++ .github/page-resources.mjs | 23 ++++++-- .github/workflows/main.yml | 13 ++-- 3 files changed, 121 insertions(+), 10 deletions(-) create mode 100644 .github/instrument-test-runner.mjs diff --git a/.github/instrument-test-runner.mjs b/.github/instrument-test-runner.mjs new file mode 100644 index 0000000000..1ec0933958 --- /dev/null +++ b/.github/instrument-test-runner.mjs @@ -0,0 +1,95 @@ +// TEMPORARY, for one pull request: makes the installed test runner write to +// the file named by WSLOG when a test page crashes, closes or loses a +// websocket, and with which close code. Removed before the pull request is +// merged. +import { readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; + +const pnpm = "node_modules/.pnpm"; +const find = (prefix, rest) => { + return readdirSync(pnpm) + .filter((dir) => { + return dir.startsWith(prefix); + }) + .map((dir) => { + return join(pnpm, dir, "node_modules", rest); + }); +}; +// the file is replaced, never written in place: pnpm hard-links it from its +// store, which the workflow caches +const patch = (file, edits, prefix = "") => { + let source = readFileSync(file, "utf8"); + for (const [from, to] of edits) { + if (!source.includes(from)) { + console.log(`skipped ${file}: not the version this was written for`); + return; + } + source = source.replace(from, to); + } + rmSync(file); + writeFileSync(file, prefix + source); + console.log(`patched ${file}`); +}; + +const LOG = `((m) => { try { require("node:fs").appendFileSync(process.env.WSLOG || "/dev/null", new Date().toISOString() + " " + m + "\\n"); } catch {} })`; + +for (const file of find("@vitest+browser@", "@vitest/browser/dist/index.js")) { + patch( + file, + [ + [ + 'debug?.("[%s] Browser API connected to %s", rpcId, type);\n\t\t\tws.on("close", () => {', + 'ws.on("close", (__code, __reason) => {\n\t\t\t\tif (type === "orchestrator") globalThis.__wslog?.(`server: the ${type} websocket of page ${sessionId.slice(0, 8)} closed, code=${__code} reason=${String(__reason)}`);', + ], + ], + `import { createRequire as __cr } from 'node:module'; const require = globalThis.require ?? __cr(import.meta.url); globalThis.__wslog = ${LOG};\n`, + ); +} + +for (const file of find( + "@vitest+browser-playwright@", + "@vitest/browser-playwright/dist/index.js", +)) { + patch(file, [ + [ + "this.browser = await playwright[this.browserName].launch(launchOptions);", + 'this.browser = await playwright[this.browserName].launch(launchOptions);\n\t\t\t\tthis.browser.on("disconnected", () => globalThis.__wslog?.("the browser disconnected"));', + ], + [ + "this.pages.set(sessionId, page);\n\t\tif (process.env.VITEST_PW_DEBUG) {", + `this.pages.set(sessionId, page); + { + const L = (m) => globalThis.__wslog?.(\`page \${sessionId.slice(0, 8)}: \${m}\`); + L("created"); + page.on("crash", () => L("CRASHED")); + page.on("close", () => L("closed")); + page.on("framenavigated", (f) => { if (f === page.mainFrame()) L("main frame navigated to " + f.url().replace(/\\?.*/, "")); }); + page.on("websocket", (w) => { + const kind = w.url().includes("type=orchestrator") ? "orchestrator" : w.url().includes("type=tester") ? "tester" : "vite"; + w.on("socketerror", (e) => L(kind + " websocket error: " + e)); + if (kind === "orchestrator") w.on("close", () => L("orchestrator websocket closed, seen from the page")); + }); + page.on("console", (m) => { const t = m.text(); if (/server connection lost|WebSocket connection to/i.test(t)) L("console: " + t.slice(0, 200)); }); + page.on("requestfailed", (r) => { const f = r.failure()?.errorText ?? ""; if (/INSUFFICIENT|NETWORK_CHANGED|CONNECTION_RESET|CONNECTION_CLOSED|EMPTY_RESPONSE|OUT_OF_MEMORY/.test(f)) L("request failed: " + f + " " + r.url().slice(0, 120)); }); + } + if (process.env.VITEST_PW_DEBUG) {`, + ], + ]); +} + +for (const file of find("vitest@", "vitest/dist/chunks").flatMap((dir) => { + return readdirSync(dir) + .filter((name) => { + return name.startsWith("cli-api."); + }) + .map((name) => { + return join(dir, name); + }); +})) { + patch(file, [ + [ + 'debug?.("[%s] run test %s", sessionId, file);', + 'debug?.("[%s] run test %s", sessionId, file);\n\t\tglobalThis.__wslog?.("page " + sessionId.slice(0, 8) + ": starts " + String(file.filepath).replace(/.*\\/tests\\//, ""));', + ], + ]); +} diff --git a/.github/page-resources.mjs b/.github/page-resources.mjs index b4f571b85b..0542d55de9 100644 --- a/.github/page-resources.mjs +++ b/.github/page-resources.mjs @@ -5,7 +5,13 @@ import { readdirSync, readFileSync, statfsSync } from "node:fs"; const started = Date.now(); const seconds = () => { - return `${String(Math.round((Date.now() - started) / 1000)).padStart(4)}s`; + return `${new Date().toISOString()} ${String(Math.round((Date.now() - started) / 1000)).padStart(4)}s`; +}; +const memory = () => { + const kb = /MemAvailable:\s+(\d+)/.exec( + readFileSync("/proc/meminfo", "utf8"), + ); + return kb === null ? -1 : Math.round(Number(kb[1]) / 1024); }; const free = () => { const s = statfsSync(process.env.TMPDIR ?? "/tmp"); @@ -16,12 +22,15 @@ const peak = { buffersMB: 0, lowestFreeMB: free(), firstFreeMB: free(), + lowestMemoryMB: memory(), + firstMemoryMB: memory(), }; const seen = new Map(); let limits = ""; function sample() { peak.lowestFreeMB = Math.min(peak.lowestFreeMB, free()); + peak.lowestMemoryMB = Math.min(peak.lowestMemoryMB, memory()); const alive = new Set(); for (const pid of readdirSync("/proc")) { if (!/^\d+$/.test(pid)) { @@ -69,7 +78,7 @@ function sample() { if (!alive.has(pid)) { seen.delete(pid); console.log( - `${seconds()} ${last.type} ${pid} is gone: it held ${last.handles} handles and ${last.buffersMB} MB of buffers a second before, temp free ${free()} MB`, + `${seconds()} ${last.type} ${pid} is gone: it held ${last.handles} handles and ${last.buffersMB} MB of buffers just before, temp free ${free()} MB, memory available ${memory()} MB`, ); } } @@ -78,7 +87,7 @@ function sample() { let ticks = 0; const timer = setInterval(() => { sample(); - if (++ticks % 15 === 0) { + if (++ticks % 60 === 0) { const pages = [...seen.values()].filter((p) => { return p.type === "renderer"; }); @@ -87,15 +96,17 @@ const timer = setInterval(() => { .map((p) => { return `${p.handles} handles / ${p.buffersMB} MB`; }) - .join(", ")} | temp free ${free()} MB`, + .join( + ", ", + )} | temp free ${free()} MB | memory available ${memory()} MB`, ); } -}, 1000); +}, 250); process.on("SIGTERM", () => { clearInterval(timer); console.log( - `SUMMARY most handles held by one page: ${peak.handles} | most buffers held by one page: ${peak.buffersMB} MB | temp free: ${peak.firstFreeMB} MB at the start, ${peak.lowestFreeMB} MB at the lowest`, + `SUMMARY most handles held by one page: ${peak.handles} | most buffers held by one page: ${peak.buffersMB} MB | temp free: ${peak.firstFreeMB} MB at the start, ${peak.lowestFreeMB} MB at the lowest | memory available: ${peak.firstMemoryMB} MB at the start, ${peak.lowestMemoryMB} MB at the lowest`, ); process.exit(0); }); diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 66456481dc..c47b0d3ec0 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -58,13 +58,15 @@ jobs: test: needs: lint runs-on: ubuntu-latest - # TEMPORARY, for this pull request only: the job runs twice, once as it is - # meant to and once with the test server making the browser re-validate - # every module, as it did before, to compare what the pages hold. + # TEMPORARY, for this pull request only: the job runs twelve times, six as + # it is meant to and six with the test server making the browser + # re-validate every module, as it did before. Each prints what its pages + # held, and what a page that was lost was doing when it went. strategy: fail-fast: false matrix: modules: [kept, revalidated] + copy: [1, 2, 3, 4, 5, 6] continue-on-error: ${{ matrix.modules == 'revalidated' }} container: # must match the workspace's playwright version (root devDependencies) @@ -96,6 +98,8 @@ jobs: key: ${{ runner.os }}-turbo-${{ hashFiles('pnpm-lock.yaml') }}-${{ github.sha }} restore-keys: ${{ runner.os }}-turbo-${{ hashFiles('pnpm-lock.yaml') }}- - run: pnpm i + # TEMPORARY: see the comment on the job + - run: node .github/instrument-test-runner.mjs # Vitest 4.1.11 runs each worker as one long-lived orchestrator page and # dispatches every spec file over a single websocket. Its ws close handler # destroys the session and rejects the pending `createTesters`, so if that @@ -121,6 +125,7 @@ jobs: shell: bash env: MELONJS_TESTS_REVALIDATE: ${{ matrix.modules == 'revalidated' && '1' || '' }} + WSLOG: ${{ github.workspace }}/page-events.log run: | set -o pipefail # TEMPORARY: see the comment on the job @@ -128,7 +133,7 @@ jobs: df -h /tmp node .github/page-resources.mjs > page-resources.log 2>&1 & sampler=$! - trap 'kill -TERM "$sampler" 2>/dev/null; sleep 2; echo "--- page resources ---"; cat page-resources.log' EXIT + trap 'kill -TERM "$sampler" 2>/dev/null; sleep 2; echo "--- attempts made: $attempt ---"; echo "--- page events ---"; grep -v ": starts " "$WSLOG"; echo "--- last spec files started ---"; grep ": starts " "$WSLOG" | tail -6; echo "--- page resources ---"; cat page-resources.log' EXIT for attempt in 1 2; do if pnpm test 2>&1 | tee "test-$attempt.log"; then exit 0 From 3a633b175b2488b1033ef80e91f3519b5875e483 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 15:20:44 +0000 Subject: [PATCH 35/51] Remove the temporary CI comparison, and record what it showed CI ran the engine's suite six times each way. Re-validating its modules, five runs peaked between 9,733 and 16,295 handles in one page and passed; the sixth lost every websocket of a page at once, with no process crashing, as that page reached 16,448 handles and 32.5 GB of buffers, 81 seconds in. That is the lost page seen on master. Keeping its modules, no page held more than 327 handles and none was lost; the suite took 115 to 194 s, against 182 to 287 s. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- .github/instrument-test-runner.mjs | 95 ------------------------ .github/page-resources.mjs | 112 ----------------------------- .github/workflows/main.yml | 21 ------ packages/melonjs/vitest.config.ts | 19 ++--- 4 files changed, 10 insertions(+), 237 deletions(-) delete mode 100644 .github/instrument-test-runner.mjs delete mode 100644 .github/page-resources.mjs diff --git a/.github/instrument-test-runner.mjs b/.github/instrument-test-runner.mjs deleted file mode 100644 index 1ec0933958..0000000000 --- a/.github/instrument-test-runner.mjs +++ /dev/null @@ -1,95 +0,0 @@ -// TEMPORARY, for one pull request: makes the installed test runner write to -// the file named by WSLOG when a test page crashes, closes or loses a -// websocket, and with which close code. Removed before the pull request is -// merged. -import { readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; -import { join } from "node:path"; - -const pnpm = "node_modules/.pnpm"; -const find = (prefix, rest) => { - return readdirSync(pnpm) - .filter((dir) => { - return dir.startsWith(prefix); - }) - .map((dir) => { - return join(pnpm, dir, "node_modules", rest); - }); -}; -// the file is replaced, never written in place: pnpm hard-links it from its -// store, which the workflow caches -const patch = (file, edits, prefix = "") => { - let source = readFileSync(file, "utf8"); - for (const [from, to] of edits) { - if (!source.includes(from)) { - console.log(`skipped ${file}: not the version this was written for`); - return; - } - source = source.replace(from, to); - } - rmSync(file); - writeFileSync(file, prefix + source); - console.log(`patched ${file}`); -}; - -const LOG = `((m) => { try { require("node:fs").appendFileSync(process.env.WSLOG || "/dev/null", new Date().toISOString() + " " + m + "\\n"); } catch {} })`; - -for (const file of find("@vitest+browser@", "@vitest/browser/dist/index.js")) { - patch( - file, - [ - [ - 'debug?.("[%s] Browser API connected to %s", rpcId, type);\n\t\t\tws.on("close", () => {', - 'ws.on("close", (__code, __reason) => {\n\t\t\t\tif (type === "orchestrator") globalThis.__wslog?.(`server: the ${type} websocket of page ${sessionId.slice(0, 8)} closed, code=${__code} reason=${String(__reason)}`);', - ], - ], - `import { createRequire as __cr } from 'node:module'; const require = globalThis.require ?? __cr(import.meta.url); globalThis.__wslog = ${LOG};\n`, - ); -} - -for (const file of find( - "@vitest+browser-playwright@", - "@vitest/browser-playwright/dist/index.js", -)) { - patch(file, [ - [ - "this.browser = await playwright[this.browserName].launch(launchOptions);", - 'this.browser = await playwright[this.browserName].launch(launchOptions);\n\t\t\t\tthis.browser.on("disconnected", () => globalThis.__wslog?.("the browser disconnected"));', - ], - [ - "this.pages.set(sessionId, page);\n\t\tif (process.env.VITEST_PW_DEBUG) {", - `this.pages.set(sessionId, page); - { - const L = (m) => globalThis.__wslog?.(\`page \${sessionId.slice(0, 8)}: \${m}\`); - L("created"); - page.on("crash", () => L("CRASHED")); - page.on("close", () => L("closed")); - page.on("framenavigated", (f) => { if (f === page.mainFrame()) L("main frame navigated to " + f.url().replace(/\\?.*/, "")); }); - page.on("websocket", (w) => { - const kind = w.url().includes("type=orchestrator") ? "orchestrator" : w.url().includes("type=tester") ? "tester" : "vite"; - w.on("socketerror", (e) => L(kind + " websocket error: " + e)); - if (kind === "orchestrator") w.on("close", () => L("orchestrator websocket closed, seen from the page")); - }); - page.on("console", (m) => { const t = m.text(); if (/server connection lost|WebSocket connection to/i.test(t)) L("console: " + t.slice(0, 200)); }); - page.on("requestfailed", (r) => { const f = r.failure()?.errorText ?? ""; if (/INSUFFICIENT|NETWORK_CHANGED|CONNECTION_RESET|CONNECTION_CLOSED|EMPTY_RESPONSE|OUT_OF_MEMORY/.test(f)) L("request failed: " + f + " " + r.url().slice(0, 120)); }); - } - if (process.env.VITEST_PW_DEBUG) {`, - ], - ]); -} - -for (const file of find("vitest@", "vitest/dist/chunks").flatMap((dir) => { - return readdirSync(dir) - .filter((name) => { - return name.startsWith("cli-api."); - }) - .map((name) => { - return join(dir, name); - }); -})) { - patch(file, [ - [ - 'debug?.("[%s] run test %s", sessionId, file);', - 'debug?.("[%s] run test %s", sessionId, file);\n\t\tglobalThis.__wslog?.("page " + sessionId.slice(0, 8) + ": starts " + String(file.filepath).replace(/.*\\/tests\\//, ""));', - ], - ]); -} diff --git a/.github/page-resources.mjs b/.github/page-resources.mjs deleted file mode 100644 index 0542d55de9..0000000000 --- a/.github/page-resources.mjs +++ /dev/null @@ -1,112 +0,0 @@ -// TEMPORARY, for one pull request: records what the test pages hold while the -// engine's tests run, to compare a run that re-validates its modules with one -// that keeps them. Removed before the pull request is merged. -import { readdirSync, readFileSync, statfsSync } from "node:fs"; - -const started = Date.now(); -const seconds = () => { - return `${new Date().toISOString()} ${String(Math.round((Date.now() - started) / 1000)).padStart(4)}s`; -}; -const memory = () => { - const kb = /MemAvailable:\s+(\d+)/.exec( - readFileSync("/proc/meminfo", "utf8"), - ); - return kb === null ? -1 : Math.round(Number(kb[1]) / 1024); -}; -const free = () => { - const s = statfsSync(process.env.TMPDIR ?? "/tmp"); - return Math.round((s.bavail * s.bsize) / 2 ** 20); -}; -const peak = { - handles: 0, - buffersMB: 0, - lowestFreeMB: free(), - firstFreeMB: free(), - lowestMemoryMB: memory(), - firstMemoryMB: memory(), -}; -const seen = new Map(); -let limits = ""; - -function sample() { - peak.lowestFreeMB = Math.min(peak.lowestFreeMB, free()); - peak.lowestMemoryMB = Math.min(peak.lowestMemoryMB, memory()); - const alive = new Set(); - for (const pid of readdirSync("/proc")) { - if (!/^\d+$/.test(pid)) { - continue; - } - try { - const cmd = readFileSync(`/proc/${pid}/cmdline`, "utf8"); - if (!/chrome|headless/.test(cmd)) { - continue; - } - const type = /--type=([a-z-]+)/.exec(cmd)?.[1] ?? "browser"; - const handles = readdirSync(`/proc/${pid}/fd`).length; - let buffers = 0; - if (type === "renderer") { - for (const line of readFileSync(`/proc/${pid}/maps`, "utf8").split( - "\n", - )) { - if (line.includes("(deleted)")) { - const [from, to] = line.split(" ")[0].split("-"); - buffers += parseInt(to, 16) - parseInt(from, 16); - } - } - if (limits === "") { - limits = readFileSync(`/proc/${pid}/limits`, "utf8") - .split("\n") - .find((line) => { - return line.startsWith("Max open files"); - }) - .replace(/\s+/g, " "); - console.log(`${seconds()} a page's own limit: ${limits}`); - } - } - const buffersMB = Math.round(buffers / 2 ** 20); - alive.add(pid); - seen.set(pid, { type, handles, buffersMB }); - if (type === "renderer") { - peak.handles = Math.max(peak.handles, handles); - peak.buffersMB = Math.max(peak.buffersMB, buffersMB); - } - } catch { - // the process went away between the listing and the read - } - } - for (const [pid, last] of seen) { - if (!alive.has(pid)) { - seen.delete(pid); - console.log( - `${seconds()} ${last.type} ${pid} is gone: it held ${last.handles} handles and ${last.buffersMB} MB of buffers just before, temp free ${free()} MB, memory available ${memory()} MB`, - ); - } - } -} - -let ticks = 0; -const timer = setInterval(() => { - sample(); - if (++ticks % 60 === 0) { - const pages = [...seen.values()].filter((p) => { - return p.type === "renderer"; - }); - console.log( - `${seconds()} pages: ${pages - .map((p) => { - return `${p.handles} handles / ${p.buffersMB} MB`; - }) - .join( - ", ", - )} | temp free ${free()} MB | memory available ${memory()} MB`, - ); - } -}, 250); - -process.on("SIGTERM", () => { - clearInterval(timer); - console.log( - `SUMMARY most handles held by one page: ${peak.handles} | most buffers held by one page: ${peak.buffersMB} MB | temp free: ${peak.firstFreeMB} MB at the start, ${peak.lowestFreeMB} MB at the lowest | memory available: ${peak.firstMemoryMB} MB at the start, ${peak.lowestMemoryMB} MB at the lowest`, - ); - process.exit(0); -}); diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index c47b0d3ec0..fb8383f38f 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -58,16 +58,6 @@ jobs: test: needs: lint runs-on: ubuntu-latest - # TEMPORARY, for this pull request only: the job runs twelve times, six as - # it is meant to and six with the test server making the browser - # re-validate every module, as it did before. Each prints what its pages - # held, and what a page that was lost was doing when it went. - strategy: - fail-fast: false - matrix: - modules: [kept, revalidated] - copy: [1, 2, 3, 4, 5, 6] - continue-on-error: ${{ matrix.modules == 'revalidated' }} container: # must match the workspace's playwright version (root devDependencies) image: mcr.microsoft.com/playwright:v1.62.1-noble @@ -98,8 +88,6 @@ jobs: key: ${{ runner.os }}-turbo-${{ hashFiles('pnpm-lock.yaml') }}-${{ github.sha }} restore-keys: ${{ runner.os }}-turbo-${{ hashFiles('pnpm-lock.yaml') }}- - run: pnpm i - # TEMPORARY: see the comment on the job - - run: node .github/instrument-test-runner.mjs # Vitest 4.1.11 runs each worker as one long-lived orchestrator page and # dispatches every spec file over a single websocket. Its ws close handler # destroys the session and rejects the pending `createTesters`, so if that @@ -123,17 +111,8 @@ jobs: # dash, which has no `pipefail` — and without it the exit status of # `pnpm test` is masked by `tee` shell: bash - env: - MELONJS_TESTS_REVALIDATE: ${{ matrix.modules == 'revalidated' && '1' || '' }} - WSLOG: ${{ github.workspace }}/page-events.log run: | set -o pipefail - # TEMPORARY: see the comment on the job - echo "handle limit of this shell (soft/hard): $(ulimit -Sn)/$(ulimit -Hn)" - df -h /tmp - node .github/page-resources.mjs > page-resources.log 2>&1 & - sampler=$! - trap 'kill -TERM "$sampler" 2>/dev/null; sleep 2; echo "--- attempts made: $attempt ---"; echo "--- page events ---"; grep -v ": starts " "$WSLOG"; echo "--- last spec files started ---"; grep ": starts " "$WSLOG" | tail -6; echo "--- page resources ---"; cat page-resources.log' EXIT for attempt in 1 2; do if pnpm test 2>&1 | tee "test-$attempt.log"; then exit 0 diff --git a/packages/melonjs/vitest.config.ts b/packages/melonjs/vitest.config.ts index 42071d786e..cc3947a43b 100644 --- a/packages/melonjs/vitest.config.ts +++ b/packages/melonjs/vitest.config.ts @@ -52,10 +52,16 @@ const KEPT_FOR_THE_RUN = "max-age=86400"; * way, until its garbage collector next runs. A page that loads 400 modules in * an iframe twice shows it, with no engine and no Vitest involved. Vitest runs * every spec file in an iframe of one long-lived page, and nothing makes the - * collector run: measured on this suite, a page reached 11,000 handles and - * 22 GB of temporary files. A page that runs out of handles stops loading - * modules, and the run hangs on whichever spec file is next; a full temporary - * folder fails the module loads instead. + * collector run, so the buffers pile up, by the thousand. + * + * That is what "Browser connection was closed while running tests" was, on + * whichever spec file came next and with no test failing. CI ran the suite six + * times each way (#1907): re-validating, five runs peaked between 9,700 and + * 16,300 handles in one page and passed, and the sixth lost every websocket of + * a page at once, with no process crashing, as that page reached 16,448 handles + * and 32 GB of buffers. Kept, no page held more than 330 handles and none was + * lost. Other ways it ends: a page limited to 8,192 handles stops loading + * modules and the run hangs, and a full temporary folder fails the loads. * * Nothing changes on disk during a one-shot run, so there the answer can be * `max-age`, and the browser does not ask: a page then stays at a few hundred @@ -74,11 +80,6 @@ function keepModulesForTheRun(): Plugin { return { name: "melonjs:keep-modules-for-the-run", configureVitest({ vitest, project }) { - // TEMPORARY, for one pull request: the CI job that compares a run - // re-validating its modules with one that keeps them - if (process.env.MELONJS_TESTS_REVALIDATE) { - return; - } // not `=== false`: without a terminal Vitest leaves it unset if (!vitest.config.watch) { process.env[ONE_SHOT] = "1"; From 7bbce4efa00f682b79e201531d5fa907cf76fca4 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 23:05:57 +0000 Subject: [PATCH 36/51] CI: the test step no longer retries It ran the engine's suite a second time when a run lost its browser page with no test failing, and its comment put that down to the browser. The cause is known and removed (the buffers a page gathered by re-validating its modules), so a lost page is now a failure to look into, not one to run past. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- .github/workflows/main.yml | 43 +++++--------------------------------- 1 file changed, 5 insertions(+), 38 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index fb8383f38f..c92fb4211c 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -88,44 +88,11 @@ jobs: key: ${{ runner.os }}-turbo-${{ hashFiles('pnpm-lock.yaml') }}-${{ github.sha }} restore-keys: ${{ runner.os }}-turbo-${{ hashFiles('pnpm-lock.yaml') }}- - run: pnpm i - # Vitest 4.1.11 runs each worker as one long-lived orchestrator page and - # dispatches every spec file over a single websocket. Its ws close handler - # destroys the session and rejects the pending `createTesters`, so if that - # socket drops the whole run dies — the in-page client does try to - # reconnect, but the session is already gone. Underneath, the browser - # intermittently severs a renderer's network-service channels: every - # websocket for that page dies at once, the server sees a graceful 1001 - # while the page sees 1006, and no process crashes. - # - # Measured at 4 deaths in 21 local runs, and it cost three attempts to - # land a PR that changed nothing but Markdown. Not our code: no test ever - # fails, and the spec it names is just whichever was in flight. Launching - # the full Chromium build fixes it locally (20 runs clean) but does - # nothing here (0 of 4), so this retries instead. - # - # The condition is deliberately narrow — the page must have been lost AND - # no test may have failed. A real failure prints "N failed" in the summary - # and exits without a retry. - - name: Test (retries once if vitest loses its browser page) - # the container has no default bash, so GitHub would run this under - # dash, which has no `pipefail` — and without it the exit status of - # `pnpm test` is masked by `tee` - shell: bash - run: | - set -o pipefail - for attempt in 1 2; do - if pnpm test 2>&1 | tee "test-$attempt.log"; then - exit 0 - fi - if ! grep -q "Browser connection was closed" "test-$attempt.log" \ - || grep -qE "Test Files.*[0-9]+ failed" "test-$attempt.log"; then - echo "::error::test failed for a real reason, not the known browser flake" - exit 1 - fi - echo "::warning::vitest lost its browser page (upstream flake) — attempt $attempt" - done - echo "::error::vitest lost its browser page on both attempts" - exit 1 + # No retry here. A run used to lose its browser page now and then, with no + # test failing, and this step ran the suite a second time when it did. The + # cause is known and removed: see `keepModulesForTheRun` in + # packages/melonjs/vitest.config.ts. A lost page is a failure to look into. + - run: pnpm test - run: pnpm -F @melonjs/matter-adapter test - run: pnpm -F @melonjs/planck-adapter test - run: pnpm -F @melonjs/rapier2d-adapter test From 1f60d1c16287c2470fb5aa662a768715c6ed03ae Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 00:04:54 +0000 Subject: [PATCH 37/51] Effects: GradientMapEffect and DitherEffect, and a Dithering example GradientMapEffect recolors a sprite or a scene from its brightness, through a list of two to eight colors: the darkest pixels take the first, the brightest the last. With smooth off each color takes a band of its own, a palette swap for art drawn in flat shades. A color's alpha is how opaque the pixels that take it are drawn. DitherEffect draws in a few colors with a 4 x 4 ordered dither between them, in pixels several pixels wide. It is made for a whole scene, on the camera: so many levels of each channel, so everything keeps its own hue, or a palette of two to sixteen colors, each pixel taking one of its two nearest. Only a color that falls between two allowed ones is patterned (shading, soft shadows, gradients): one that is itself a level, or in the palette, stays flat. Both ship a GLSL and a WGSL body, and the same drawing checks run on WebGL and on WebGPU (the latter skipped where there is no adapter). Examples: a new Dithering example, a lit 3D scene of plain meshes with the effect on the camera, and both effects in the Shader Effects one, which now attaches its effects with addPostEffect in place of the deprecated shader setter. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- .../examples/dithering/ExampleDithering.tsx | 349 ++++++++++ .../shaderEffects/ExampleShaderEffects.tsx | 123 ++-- packages/examples/src/main.tsx | 13 + packages/melonjs/CHANGELOG.md | 2 + .../melonjs-effects-and-shaders/SKILL.md | 74 ++- packages/melonjs/src/index.ts | 4 + packages/melonjs/src/video/effects/dither.js | 298 +++++++++ .../melonjs/src/video/effects/gradientMap.js | 190 ++++++ .../tests/helpers/palette-effect-checks.js | 606 ++++++++++++++++++ .../tests/palette-effects-webgpu.spec.js | 59 ++ .../melonjs/tests/palette-effects.spec.js | 207 ++++++ .../tests/webgpu_effects_validate.spec.js | 4 + 12 files changed, 1882 insertions(+), 47 deletions(-) create mode 100644 packages/examples/src/examples/dithering/ExampleDithering.tsx create mode 100644 packages/melonjs/src/video/effects/dither.js create mode 100644 packages/melonjs/src/video/effects/gradientMap.js create mode 100644 packages/melonjs/tests/helpers/palette-effect-checks.js create mode 100644 packages/melonjs/tests/palette-effects-webgpu.spec.js create mode 100644 packages/melonjs/tests/palette-effects.spec.js diff --git a/packages/examples/src/examples/dithering/ExampleDithering.tsx b/packages/examples/src/examples/dithering/ExampleDithering.tsx new file mode 100644 index 0000000000..621b1b5cec --- /dev/null +++ b/packages/examples/src/examples/dithering/ExampleDithering.tsx @@ -0,0 +1,349 @@ +/** + * melonJS — a dithered scene. + * + * One `DitherEffect` on the camera draws the whole scene in a few levels of + * each color channel, in pixels several screen pixels wide, with an ordered + * dither wherever a color falls between two levels. Nothing in the scene + * knows about it: the shapes are plain lit meshes. + * + * What gets patterned is what lies between two levels, which is the shading: + * the turn of a lit surface from light to dark, the soft edge of a shadow. + * A flat color that is itself a level is left alone, so the sky and the + * ground, which are given such colors, stay clean (at 6 and 16 levels: try + * 3). Each shape keeps its own hue. + * + * The checkboxes switch the effect, the number of levels and the pixel size. + * They are drawn by the same camera, so they are dithered with the rest. + * + * Copyright (C) 2011 - 2026 AltByte Pte Ltd — MIT License. + * See `packages/examples/LICENSE.md` for full license + asset credits. + */ +import { + Application, + Camera3d, + type CanvasRenderer, + DitherEffect, + Light3d, + Mesh, + Renderable, + Stage, + state, + UICheckbox, + Vector3d, + video, + type WebGLRenderer, +} from "melonjs"; +import { createExampleComponent } from "../utils"; + +// render space is Y-DOWN: the floor is at y = 0 and up is negative +const GROUND_Y = 0; +const UP = new Vector3d(0, 1, 0); +// The sky and the ground are made of fifths of 255, which are levels of a +// channel at 6 levels and at 16: there they are left alone. At 3 levels they +// fall between two, and are patterned like everything else. +const SKY = "#0066cc"; +const GROUND = [102, 204, 51] as const; + +/** a flat sky behind the scene, in screen space */ +class Backdrop extends Renderable { + constructor() { + super(0, 0, 1, 1); + this.floating = true; + this.anchorPoint.set(0, 0); + } + + override draw(renderer: CanvasRenderer | WebGLRenderer) { + renderer.setColor(SKY); + renderer.fillRect(0, 0, renderer.width, renderer.height); + } +} + +type Geometry = { + vertices: number[]; + normals: number[]; + indices: number[]; + width: number; + height: number; +}; + +/** a mesh of one flat color from a geometry authored Y-UP */ +const createShape = ( + geometry: Geometry, + color: readonly [number, number, number], + settings: { lit: boolean; castGroundShadow: boolean }, +) => { + const mesh = new Mesh(0, GROUND_Y, { + vertices: new Float32Array(geometry.vertices), + normals: new Float32Array(geometry.normals), + uvs: new Float32Array((geometry.vertices.length / 3) * 2), + indices: new Uint16Array(geometry.indices), + normalize: false, + scale: 1, + width: geometry.width, + height: geometry.height, + cullBackFaces: false, + shadowGroundY: GROUND_Y, + shadowOpacity: 0.6, + shadowScale: 1.3, + ...settings, + }); + mesh.tint.setColor(color[0], color[1], color[2]); + return mesh; +}; + +/** a round floor */ +const disc = (radius: number): Geometry => { + const segments = 64; + const vertices = [0, 0, 0]; + const normals = [0, 1, 0]; + const indices: number[] = []; + for (let i = 0; i <= segments; i++) { + const a = (i / segments) * Math.PI * 2; + vertices.push(Math.cos(a) * radius, 0, Math.sin(a) * radius); + normals.push(0, 1, 0); + if (i > 0) { + indices.push(0, i + 1, i); + } + } + return { vertices, normals, indices, width: radius * 2, height: radius * 2 }; +}; + +/** a sphere stretched to three radii, with smooth normals */ +const ellipsoid = (rx: number, ry: number, rz: number): Geometry => { + const rings = 28; + const segments = 44; + const vertices: number[] = []; + const normals: number[] = []; + const indices: number[] = []; + for (let r = 0; r <= rings; r++) { + const phi = (r / rings) * Math.PI; + for (let s = 0; s <= segments; s++) { + const theta = (s / segments) * Math.PI * 2; + const x = Math.sin(phi) * Math.cos(theta); + const y = Math.cos(phi); + const z = Math.sin(phi) * Math.sin(theta); + vertices.push(x * rx, y * ry, z * rz); + // the normal of a stretched sphere leans away from its long axes + const n = new Vector3d(x / rx, y / ry, z / rz).normalize(); + normals.push(n.x, n.y, n.z); + if (r < rings && s < segments) { + const a = r * (segments + 1) + s; + const b = a + segments + 1; + indices.push(a, b, a + 1, b, b + 1, a + 1); + } + } + } + return { vertices, normals, indices, width: rx * 2, height: ry * 2 }; +}; + +/** a ring standing upright, facing the camera */ +const torus = (ring: number, tube: number): Geometry => { + const around = 56; + const across = 28; + const vertices: number[] = []; + const normals: number[] = []; + const indices: number[] = []; + for (let i = 0; i <= around; i++) { + const u = (i / around) * Math.PI * 2; + for (let j = 0; j <= across; j++) { + const v = (j / across) * Math.PI * 2; + const out = ring + tube * Math.cos(v); + vertices.push(out * Math.cos(u), out * Math.sin(u), tube * Math.sin(v)); + normals.push( + Math.cos(v) * Math.cos(u), + Math.cos(v) * Math.sin(u), + Math.sin(v), + ); + if (i < around && j < across) { + const a = i * (across + 1) + j; + const b = a + across + 1; + indices.push(a, b, a + 1, b, b + 1, a + 1); + } + } + } + const size = (ring + tube) * 2; + return { vertices, normals, indices, width: size, height: size }; +}; + +const createGame = async () => { + let app: Application; + try { + app = new Application(1024, 576, { + parent: "screen", + renderer: video.AUTO, + scale: "auto", + cameraClass: Camera3d, + antiAlias: true, + }); + await app.init(); + if (!app.renderer.supportsDepthBuffer) { + throw new Error("no GPU backend available (Canvas fallback)"); + } + } catch (err) { + const reason = err instanceof Error ? err.message : String(err); + globalThis.alert( + "This example couldn't start: it needs WebGL 2 or WebGPU.\n\n" + + `Details: ${reason}`, + ); + throw err; + } + + const buildScene = (app: Application) => { + const world = app.world; + world.addChild(new Backdrop(), -10000); + + // a key light from the upper left, and a fill so the dark side of a + // shape keeps some of its color + world.addChild( + new Light3d({ + type: "directional", + direction: [0.5, 0.6, 0.65], + color: [1, 1, 1], + intensity: 1, + }), + ); + world.addChild( + new Light3d({ type: "ambient", color: [1, 1, 1], intensity: 0.35 }), + ); + + // the ground is not lit: it keeps the one color it is given + world.addChild( + createShape(disc(2400), GROUND, { lit: false, castGroundShadow: false }), + 0, + ); + + // the shapes: each of one color, lit, with a soft shadow on the ground + const place = (mesh: Mesh, x: number, y: number, z: number) => { + mesh.pos.set(x, GROUND_Y - y); + mesh.depth = z; + world.addChild(mesh, z); + return mesh; + }; + const solid = { lit: true, castGroundShadow: true }; + place( + createShape(ellipsoid(150, 100, 110), [235, 60, 70], solid), + -300, + 100, + -40, + ); + const ball = place( + createShape(ellipsoid(95, 95, 95), [170, 110, 80], solid), + -95, + 250, + 120, + ); + const ring = place( + createShape(torus(92, 40), [245, 150, 40], solid), + 150, + 255, + 110, + ); + place( + createShape(ellipsoid(125, 70, 105), [175, 195, 220], solid), + 370, + 95, + -70, + ); + + // ── the effect: on the camera, so on the whole scene ───────────── + const dither = new DitherEffect(app.renderer as WebGLRenderer, { + levels: 6, + size: 3, + }); + const camera = app.viewport as Camera3d; + camera.addPostEffect(dither); + + // ── controls ───────────────────────────────────────────────────── + const label = { + font: "sans-serif", + fontSize: 26, + labelFillStyle: "#ffffff", + }; + world.addChild( + new UICheckbox(24, 20, { + ...label, + label: "dither", + checked: true, + onChange: (on) => { + // switched off rather than removed: it keeps its program + dither.enabled = on; + }, + }), + 100, + ); + [3, 6, 16].forEach((levels, i) => { + world.addChild( + new UICheckbox(24, 76 + i * 40, { + ...label, + group: "levels", + label: `${levels} levels`, + checked: levels === 6, + onChange: (on) => { + if (on) { + dither.setLevels(levels); + } + }, + }), + 100, + ); + }); + [2, 3, 5].forEach((size, i) => { + world.addChild( + new UICheckbox(24, 212 + i * 40, { + ...label, + group: "size", + label: `${size} px`, + checked: size === 3, + onChange: (on) => { + if (on) { + dither.setSize(size); + } + }, + }), + 100, + ); + }); + + // ── camera: a low view, drifting from side to side ─────────────── + camera.setClipPlanes(10, 8000); + const target = { x: 20, y: GROUND_Y - 140, z: 40 }; + let time = 0; + const tick = (dt: number) => { + time += dt / 1000; + const turn = Math.sin(time * 0.25) * 0.22; + camera.setPosition( + target.x + Math.sin(turn) * 730, + target.y - 150, + target.z - Math.cos(turn) * 730, + ); + camera.lookAt(target.x, target.y, target.z); + // the ring turns and the ball bobs, so their shading moves + ring.rotate((dt / 1000) * 0.6, UP); + ball.pos.y = GROUND_Y - 250 - Math.sin(time * 1.3) * 22; + }; + tick(0); + return tick; + }; + + class DitheringStage extends Stage { + #tick: ((dt: number) => void) | null = null; + + override onResetEvent(app: Application) { + this.#tick = buildScene(app); + } + + override update(dt: number) { + this.#tick?.(dt); + return super.update(dt); + } + + override onDestroyEvent() { + this.#tick = null; + } + } + + state.set(state.PLAY, new DitheringStage()); + state.change(state.PLAY); +}; + +export const ExampleDithering = createExampleComponent(createGame); diff --git a/packages/examples/src/examples/shaderEffects/ExampleShaderEffects.tsx b/packages/examples/src/examples/shaderEffects/ExampleShaderEffects.tsx index 4ba973676c..7e2acc6a93 100644 --- a/packages/examples/src/examples/shaderEffects/ExampleShaderEffects.tsx +++ b/packages/examples/src/examples/shaderEffects/ExampleShaderEffects.tsx @@ -11,10 +11,12 @@ import { ColorMatrixEffect, DesaturateEffect, DissolveEffect, + DitherEffect, DropShadowEffect, event, FlashEffect, GlowEffect, + GradientMapEffect, HologramEffect, InvertEffect, loader, @@ -36,9 +38,9 @@ import { import { createExampleComponent } from "../utils"; import monsterImg from "./assets/monster.png"; -// five rows of four +// six rows of four const WIDTH = 1218; -const HEIGHT = 702; +const HEIGHT = 842; const SPRITE_SCALE = 0.25; const createGame = async () => { @@ -50,7 +52,7 @@ const createGame = async () => { await app.init(); // apply subtle vignette post-process effect on the camera - app.viewport.shader = new VignetteEffect(app.renderer as WebGLRenderer); + app.viewport.addPostEffect(new VignetteEffect(app.renderer as WebGLRenderer)); await loader.preload([{ name: "monster", type: "image", src: monsterImg }]); @@ -85,6 +87,8 @@ const createGame = async () => { "Squish", "Color Matrix", "Bloom", + "Gradient Map", + "Dither", ]; const cols = 4; @@ -116,13 +120,15 @@ const createGame = async () => { switch (i) { case 1: flashEffect = new FlashEffect(r, { intensity: 0 }); - sprite.shader = flashEffect; + sprite.addPostEffect(flashEffect); break; case 2: - sprite.shader = new OutlineEffect(r, { - color: [1, 1, 0], - width: 2, - }); + sprite.addPostEffect( + new OutlineEffect(r, { + color: [1, 1, 0], + width: 2, + }), + ); break; case 3: glowEffect = new GlowEffect(r, { @@ -130,43 +136,53 @@ const createGame = async () => { width: 10, intensity: 2.5, }); - sprite.shader = glowEffect; + sprite.addPostEffect(glowEffect); break; case 4: - sprite.shader = new DesaturateEffect(r); + sprite.addPostEffect(new DesaturateEffect(r)); break; case 5: - sprite.shader = new PixelateEffect(r, { - size: 6, - }); + sprite.addPostEffect( + new PixelateEffect(r, { + size: 6, + }), + ); break; case 6: - sprite.shader = new BlurEffect(r, { - strength: 5, - }); + sprite.addPostEffect( + new BlurEffect(r, { + strength: 5, + }), + ); break; case 7: - sprite.shader = new ChromaticAberrationEffect(r, { - offset: 5, - }); + sprite.addPostEffect( + new ChromaticAberrationEffect(r, { + offset: 5, + }), + ); break; case 8: dissolveEffect = new DissolveEffect(r, { progress: 0 }); - sprite.shader = dissolveEffect; + sprite.addPostEffect(dissolveEffect); break; case 9: - sprite.shader = new DropShadowEffect(r, { - offsetX: 6, - offsetY: 6, - opacity: 0.7, - }); + sprite.addPostEffect( + new DropShadowEffect(r, { + offsetX: 6, + offsetY: 6, + opacity: 0.7, + }), + ); break; case 10: - sprite.shader = new ScanlineEffect(r, { - opacity: 0.4, - curvature: 0.03, - vignetteStrength: 0.3, - }); + sprite.addPostEffect( + new ScanlineEffect(r, { + opacity: 0.4, + curvature: 0.03, + vignetteStrength: 0.3, + }), + ); break; case 11: pulseEffect = new TintPulseEffect(r, { @@ -174,7 +190,7 @@ const createGame = async () => { speed: 2, intensity: 0.4, }); - sprite.shader = pulseEffect; + sprite.addPostEffect(pulseEffect); break; case 12: waveEffect = new WaveEffect(r, { @@ -182,17 +198,17 @@ const createGame = async () => { frequency: 15.0, speed: 3.0, }); - sprite.shader = waveEffect; + sprite.addPostEffect(waveEffect); break; case 13: - sprite.shader = new InvertEffect(r); + sprite.addPostEffect(new InvertEffect(r)); break; case 14: - sprite.shader = new SepiaEffect(r); + sprite.addPostEffect(new SepiaEffect(r)); break; case 15: hologramEffect = new HologramEffect(r); - sprite.shader = hologramEffect; + sprite.addPostEffect(hologramEffect); break; case 16: shineEffect = new ShineEffect(r, { @@ -200,23 +216,44 @@ const createGame = async () => { width: 0.18, intensity: 0.7, }); - sprite.shader = shineEffect; + sprite.addPostEffect(shineEffect); break; case 17: squishEffect = new SquishEffect(r); squishSprite = sprite; - sprite.shader = squishEffect; + sprite.addPostEffect(squishEffect); break; case 18: matrixEffect = new ColorMatrixEffect(r); - sprite.shader = matrixEffect; + sprite.addPostEffect(matrixEffect); break; case 19: - sprite.shader = new BloomEffect(r, { - threshold: 0.3, - intensity: 2.2, - radius: 6, - }); + sprite.addPostEffect( + new BloomEffect(r, { + threshold: 0.3, + intensity: 2.2, + radius: 6, + }), + ); + break; + case 20: + // recolored from its brightness: dusk, from the darkest + // shade to the brightest + sprite.addPostEffect( + new GradientMapEffect(r, { + colors: [ + [0.1, 0.05, 0.3], + [0.55, 0.1, 0.5], + [0.98, 0.5, 0.3], + [1.0, 0.93, 0.7], + ], + }), + ); + break; + case 21: + // its own colors in three levels of each channel, with a dither + // between two, in pixels twelve texels wide + sprite.addPostEffect(new DitherEffect(r, { levels: 3, size: 12 })); break; } diff --git a/packages/examples/src/main.tsx b/packages/examples/src/main.tsx index 58a2ee0ef4..06b31242c7 100644 --- a/packages/examples/src/main.tsx +++ b/packages/examples/src/main.tsx @@ -163,6 +163,11 @@ const ExampleGroundShadows = lazy(() => default: m.ExampleGroundShadows, })), ); +const ExampleDithering = lazy(() => + import("./examples/dithering/ExampleDithering").then((m) => ({ + default: m.ExampleDithering, + })), +); const ExampleToon = lazy(() => import("./examples/toon/ExampleToon").then((m) => ({ default: m.ExampleToon, @@ -555,6 +560,14 @@ const examples: { description: "A rigged blocky character (Kenney, CC0) loaded from GLB, using node-TRS animation over a rigid hierarchy.", }, + { + component: , + label: "Dithering", + path: "dithering", + sourceDir: "dithering", + description: + "A lit 3D scene drawn in a few color levels with an ordered dither, by one DitherEffect on the camera: the shading is patterned, the flat colors are not.", + }, { component: , label: "Toon Shading", diff --git a/packages/melonjs/CHANGELOG.md b/packages/melonjs/CHANGELOG.md index 64a07b4057..2948883ea9 100644 --- a/packages/melonjs/CHANGELOG.md +++ b/packages/melonjs/CHANGELOG.md @@ -5,6 +5,8 @@ ### Added - Transitions: a mask transition can be shaped like an image or a `Sprite`, close on the player with `center`, and fill the shape with `invert`, on `state.transition`, `MaskEffect` and `Trigger` ([#1399](https://github.com/melonjs/melonJS/issues/1399)) - Tiled: isometric maps are rendered by the GPU on WebGL and WebGPU, as orthogonal ones are, and so are staggered and hexagonal maps. Nothing to enable: a tile layer whose tiles come from one tileset takes it by itself, and any other is drawn as before, the console saying why ([#1897](https://github.com/melonjs/melonJS/issues/1897)) +- Effects: `GradientMapEffect` recolors a sprite or a whole scene from its brightness, through a list of two to eight colors, the darkest pixels taking the first and the brightest the last: one sprite in a palette per team, a duotone, a night scene. With `smooth: false` each color takes a band of its own, a palette swap for art drawn in flat shades +- Effects: `DitherEffect` draws a scene in a few colors with an ordered dither between them, as early consoles did: on the camera, so many `levels` of each channel, so everything keeps its own hue, or a `palette` of two to sixteen colors of your own, in pixels `size` pixels wide. Only what falls between two colors is patterned (shading, soft shadows, gradients); a flat color that is one of them stays flat. See the new Dithering example ### Performance - Tiled: thanks to the GPU renderer, drawing an isometric tile layer takes about **90%** less of the main thread's time with 1200 tiles in view (0.68 to 0.07 ms a frame) and about **98%** less with 4000 (2.0 to 0.04 ms), and no longer grows with the number of tiles shown. Staggered and hexagonal maps gain the same diff --git a/packages/melonjs/skills/melonjs-effects-and-shaders/SKILL.md b/packages/melonjs/skills/melonjs-effects-and-shaders/SKILL.md index e9a960bcb9..398f1a8d4b 100644 --- a/packages/melonjs/skills/melonjs-effects-and-shaders/SKILL.md +++ b/packages/melonjs/skills/melonjs-effects-and-shaders/SKILL.md @@ -1,6 +1,6 @@ --- name: melonjs-effects-and-shaders -description: "Use this skill for post-processing effects, custom shaders, blend modes and colour grading in melonJS. Covers the built-in ShaderEffect presets, addPostEffect on renderables and cameras, writing a custom dual-language GLSL/WGSL effect, the screen_texture builtins, and why effects silently do nothing on the Canvas fallback. Triggers on: Tween, easing, animate an effect, ShaderEffect, addPostEffect, removePostEffect, getPostEffect, postEffectNeedsCapture, VignetteEffect, GlowEffect, BlurEffect, PixelateEffect, ScanlineEffect, OutlineEffect, BloomEffect, ToneMappingEffect, SwayEffect, SquishEffect, hdr, tone mapping, shader, GLSL, WGSL, uniform, setUniform, setTexture, setTime, getShader, prewarm, blendMode, colorMatrix, screen_texture, screen_uv, noise_uv, toFrameTexture, pixelate transition, post effect, filter." +description: "Use this skill for post-processing effects, custom shaders, blend modes and colour grading in melonJS. Covers the built-in ShaderEffect presets, addPostEffect on renderables and cameras, writing a custom dual-language GLSL/WGSL effect, the screen_texture builtins, and why effects silently do nothing on the Canvas fallback. Triggers on: Tween, easing, animate an effect, ShaderEffect, addPostEffect, removePostEffect, getPostEffect, postEffectNeedsCapture, VignetteEffect, GlowEffect, BlurEffect, PixelateEffect, ScanlineEffect, OutlineEffect, BloomEffect, ToneMappingEffect, SwayEffect, SquishEffect, GradientMapEffect, DitherEffect, palette swap, dither, hdr, tone mapping, shader, GLSL, WGSL, uniform, setUniform, setTexture, setTime, getShader, prewarm, blendMode, colorMatrix, screen_texture, screen_uv, noise_uv, toFrameTexture, pixelate transition, post effect, filter." license: MIT --- @@ -111,7 +111,7 @@ reused across renderables. ## Built-in effects -Twenty-three presets, every one constructed as `new XEffect(renderer, options)` +Twenty-five presets, every one constructed as `new XEffect(renderer, options)` and every one shipping both a GLSL and a WGSL body, so they all run on either GPU backend: `VignetteEffect`, `ScanlineEffect` (optional CRT curvature), `BloomEffect`, `GlowEffect`, `BlurEffect`, `PixelateEffect`, @@ -119,7 +119,7 @@ GPU backend: `VignetteEffect`, `ScanlineEffect` (optional CRT curvature), `OutlineEffect`, `ColorMatrixEffect`, `DesaturateEffect`, `DissolveEffect`, `TintPulseEffect`, `WaveEffect`, `SwayEffect`, `InvertEffect`, `SepiaEffect`, `HologramEffect`, `ShineEffect`, `RadialGradientEffect`, `SquishEffect`, -`ToneMappingEffect`. +`ToneMappingEffect`, `GradientMapEffect`, `DitherEffect`. **Colors take an alpha.** Every color option and `setColor` takes `[r, g, b]` or `[r, g, b, a]`, each 0.0 to 1.0, and the alpha is the color's own opacity: a @@ -134,7 +134,7 @@ sprite.addPostEffect(new OutlineEffect(app.renderer, { color: [1, 1, 1, 0.5] })) **On a sprite cut from an atlas or a tileset, the effects that read around a pixel keep to the sprite's own frame.** `GlowEffect`, `OutlineEffect`, `BlurEffect`, `DropShadowEffect`, `ChromaticAberrationEffect`, `WaveEffect`, -`SwayEffect`, `PixelateEffect` and `BloomEffect` read the neighbouring frames +`SwayEffect`, `PixelateEffect`, `DitherEffect` and `BloomEffect` read the neighbouring frames as transparent, as if the sprite were drawn on its own, so they never show along its edges and the atlas needs no padding for them. Past the texture's own edge (a standalone image, or the outside of an atlas) nothing changes. @@ -199,6 +199,69 @@ like the same art with a texture of its own. `WaveEffect`'s `anchor` is a row of the sprite too, but its amplitude and frequency are measured across the texture, so on an atlas sprite they are fractions of the atlas. +### Recoloring: `GradientMapEffect` and `DitherEffect` + +`GradientMapEffect` recolors a sprite from its **brightness**: the darkest +pixels take the first color of a list of two to eight, the brightest the last, +and the rest the colors in between. The sprite keeps its shading and loses its +own hues: one enemy drawn in a palette per team, a duotone, a night scene. +With `smooth: false` each color takes a band of brightness of its own, which is +a palette swap for art drawn in a few flat shades. + +```js +// the same sprite as a second team, in four flat reds +enemy.addPostEffect(new GradientMapEffect(app.renderer, { + colors: [[0.2, 0, 0.05], [0.55, 0.05, 0.1], [0.9, 0.25, 0.2], [1, 0.8, 0.7]], + smooth: false, +})); +``` + +It reads brightness and nothing else, so two colors as bright as each other +come out the same: a red and a green of equal brightness cannot be told apart +afterwards. To swap particular colors for particular others, the art has to +separate them by brightness first. A sprite's black outline takes the first +color, like any other dark pixel; give that color an alpha of 0 to drop it. +`setIntensity()` fades between the sprite's own colors and the list. + +`DitherEffect` draws in a few colors with an ordered dither between them, the +pattern that made a handful of colors read as many on early hardware. It is +made for a **whole scene, on the camera**: the colors are `levels` of each +channel, so everything keeps its own hue, in pixels `size` screen pixels wide. + +```js +// a lit scene in six levels a channel, in pixels three screen pixels wide +app.viewport.addPostEffect(new DitherEffect(app.renderer, { levels: 6, size: 3 })); +``` + +Only a color that falls **between two levels** is patterned: the turn of a lit +surface from light to dark, the soft edge of a shadow, a gradient. A flat color +that is itself a level is left alone. So a flat sky or ground that comes out +speckled all over is a color between two levels: give it one made of levels (at +6 levels, channels that are fifths of 255: 0, 51, 102, 153, 204, 255), and +remember that a **lit** surface's color is its tint times the light, which is +rarely a level; leave a flat ground unlit to keep it clean. + +A `palette` of two to sixteen colors of your own takes the place of the +levels: each pixel takes one of the two nearest, the nearer more often, and a +color that is in the palette stays flat. Everything then takes the palette's +hues, the scene's own are gone: + +```js +// the whole scene in four greens +app.viewport.addPostEffect(new DitherEffect(app.renderer, { + palette: [[0.06, 0.22, 0.06], [0.19, 0.38, 0.19], [0.55, 0.67, 0.06], [0.61, 0.74, 0.06]], + size: 2, +})); +``` + +`size` is the width of a drawn pixel **in pixels of the texture it draws**, as +`PixelateEffect`'s is: the screen's for a camera's effect, the art's for a +sprite's. On a sprite drawn smaller than its art, a `size` of 1 makes a pattern +finer than the screen can show, which reads as noise: for art drawn at a +quarter of its size, start at 8. `strength: 0` drops the pattern and leaves +flat bands (a posterize). On the camera it covers the HUD too, like any +camera effect (see above). + `RadialGradientEffect` is a procedural soft spot: solid at the centre of the renderable it draws, fading linearly to transparent at the edge, and elliptical for free on a non-square one. It is the one to reach for instead of baking a @@ -803,6 +866,9 @@ same question after construction. | squash and stretch only bulges, the height never changes, under matter, planck or Rapier (or a rotating built-in body) | the adapter rewrites `currentTransform` every step; set the scale from the sprite's `update()` | | `SquishEffect` squishes the whole screen instead of the sprite | it is chained with another effect, or on the camera; give the sprite it alone | | syntax error in a file whose shader you just edited, pointing at a line of GLSL | a backtick in the shader body ended the template literal — most often one wrapped around an identifier in a comment | +| a `GradientMapEffect` gives two different colors the same one | it maps brightness only: colors as bright as each other cannot come out different. Separate them by brightness in the art | +| a `DitherEffect` speckles a flat sky, floor or background all over | that color lies between two levels, so it is mixed from the two: give the area a color made of levels (fifths of 255 at 6 levels), unlit if it is a mesh, or add its color to the `palette` | +| a `DitherEffect` on a sprite looks like noise, or shows no pattern | its `size` is in texels of the sprite's texture, and the sprite is drawn smaller than its art: raise `size` until a drawn pixel covers two screen pixels or more | ## Related skills - `melonjs-scenes-and-state` — `Tween` and the easing families, for animating any of this diff --git a/packages/melonjs/src/index.ts b/packages/melonjs/src/index.ts index fd7d78dcc4..923bee9ba7 100644 --- a/packages/melonjs/src/index.ts +++ b/packages/melonjs/src/index.ts @@ -75,9 +75,11 @@ import ChromaticAberrationEffect from "./video/effects/chromaticAberration.js"; import ColorMatrixEffect from "./video/effects/colorMatrix.js"; import DesaturateEffect from "./video/effects/desaturate.js"; import DissolveEffect from "./video/effects/dissolve.js"; +import DitherEffect from "./video/effects/dither.js"; import DropShadowEffect from "./video/effects/dropShadow.js"; import FlashEffect from "./video/effects/flash.js"; import GlowEffect from "./video/effects/glow.js"; +import GradientMapEffect from "./video/effects/gradientMap.js"; import HologramEffect from "./video/effects/hologram.js"; import InvertEffect from "./video/effects/invert.js"; import OutlineEffect from "./video/effects/outline.js"; @@ -287,6 +289,7 @@ export { Container, DesaturateEffect, DissolveEffect, + DitherEffect, Draggable, DropShadowEffect, DropTarget, @@ -299,6 +302,7 @@ export { GLTFModel, GlowEffect, Gradient, + GradientMapEffect, HologramEffect, ImageLayer, InstancedMesh, diff --git a/packages/melonjs/src/video/effects/dither.js b/packages/melonjs/src/video/effects/dither.js new file mode 100644 index 0000000000..eea906011a --- /dev/null +++ b/packages/melonjs/src/video/effects/dither.js @@ -0,0 +1,298 @@ +import { FRAME_GLSL, FRAME_WGSL, FRAME_WGSL_MEMBERS } from "./frame.js"; +import { rgba } from "./rgba.js"; +import ShaderEffect from "./shadereffect.js"; + +/** + * additional import for TypeScript + * @import CanvasRenderer from "../canvas/canvas_renderer.js"; + * @import WebGLRenderer from "../webgl/webgl_renderer.js"; + * @import WebGPURenderer from "../webgpu/webgpu_renderer.js"; + * @import Renderer from "../renderer.js"; + */ + +/** + * the most colors a palette takes + * @ignore + */ +const MAX_COLORS = 16; + +// Both bodies read one color per cell of uPixelSize texels and find the two +// allowed colors it lies between: two levels of each channel, or the two +// nearest colors of the palette. A 4 x 4 ordered (Bayer) pattern then picks +// one of the two for the cell, the nearer one more often, in proportion. A +// color that is itself allowed is so left alone: only what lies between two +// is patterned, which is the shading of a scene and not its flat colors. +// +// The pattern is built from the cell's two lowest bits rather than read from +// a table, and the bits are taken before any arithmetic: on a large texture +// the usual one-line form of it runs out of float precision. + +// the WGSL twin of the GLSL body below: same logic, same uniform names, +// picked by the ShaderEffect base per renderer.shaderLanguage +const wgslFragment = ` +struct DitherUniforms { + uPalette : array, + uCount : f32, + uLevels : f32, + uStrength : f32, + uPixelSize : f32, + uTextureSize : vec2f,${FRAME_WGSL_MEMBERS} +}; +@group(3) @binding(0) var fx : DitherUniforms; +${FRAME_WGSL} +fn ditherBayer2(p : vec2f) -> f32 { + let a = floor(p) - 2.0 * floor(floor(p) / 2.0); + return fract(a.x / 2.0 + a.y * a.y * 0.75); +} +fn apply(color : vec4f, uv : vec2f) -> vec4f { + let texel = fx.uPixelSize / fx.uTextureSize; + let cell = floor(uv / texel); + let src = frameTexel((cell + 0.5) * texel) * vColor; + // the pixel's own color, out of its premultiplied form + let rgb = src.rgb / max(src.a, 0.0001); + let threshold = ditherBayer2(cell * 0.5) * 0.25 + ditherBayer2(cell) + 0.03125 - 0.5; + var alpha = src.a; + var result = rgb; + if (fx.uCount < 0.5) { + let steps = fx.uLevels - 1.0; + result = clamp(floor(rgb * steps + 0.5 + threshold * fx.uStrength) / steps, vec3f(0.0), vec3f(1.0)); + } else { + // the two nearest colors of the palette + var first = fx.uPalette[0]; + var second = fx.uPalette[0]; + var firstDistance = 1000.0; + var secondDistance = 1000.0; + for (var i = 0; i < ${MAX_COLORS}; i++) { + if (f32(i) >= fx.uCount) { + break; + } + let d = rgb - fx.uPalette[i].rgb; + let dist = dot(d, d); + if (dist < firstDistance) { + secondDistance = firstDistance; + second = first; + firstDistance = dist; + first = fx.uPalette[i]; + } else if (dist < secondDistance) { + secondDistance = dist; + second = fx.uPalette[i]; + } + } + // how far the pixel is from the nearest towards the other, 0 to 0.5 + let axis = second.rgb - first.rgb; + let along = clamp(dot(rgb - first.rgb, axis) / max(dot(axis, axis), 0.000001), 0.0, 1.0); + var chosen = first; + if (along > mix(0.5, threshold + 0.5, fx.uStrength)) { + chosen = second; + } + result = chosen.rgb; + alpha = alpha * chosen.a; + } + return vec4f(result * alpha, alpha); +} +`; + +/** + * A shader effect that draws in a few colors, with an ordered dither between + * them: the checkerboard-like patterns of early consoles and home computers, + * which make a handful of colors read as many. + * + * It is made for a whole scene, as an effect on the camera. The colors are + * so many levels of each channel (`levels`), so everything keeps its own hue, + * or a palette of your own (`palette`). `size` makes each drawn pixel several + * pixels wide, for a low-resolution look. + * + * Only a color that falls between two of the allowed ones is patterned: the + * shading of a lit surface, the soft edge of a shadow, a gradient. A flat + * color that is itself allowed is left as it is. So for clean flat areas, + * give them such colors: at 6 levels, channels that are fifths of 255 (0, 51, + * 102, 153, 204, 255), or with a palette, colors of the palette. + * @category Effects + * @see {@link Renderable#addPostEffect} for usage, on a camera or on a renderable + * @example + * // the whole scene in six levels a channel, in pixels three screen pixels wide + * app.viewport.addPostEffect(new DitherEffect(renderer, { levels: 6, size: 3 })); + * @example + * // the whole scene in four shades of green + * app.viewport.addPostEffect(new DitherEffect(renderer, { + * palette: [ + * [0.06, 0.22, 0.06], + * [0.19, 0.38, 0.19], + * [0.55, 0.67, 0.06], + * [0.61, 0.74, 0.06], + * ], + * size: 2, + * })); + * @example + * // one sprite, in pixels eight texels of its art wide + * mySprite.addPostEffect(new DitherEffect(renderer, { levels: 3, size: 8 })); + * @example + * // flat bands, with no pattern between them + * mySprite.addPostEffect(new DitherEffect(renderer, { levels: 3, strength: 0 })); + */ +export default class DitherEffect extends ShaderEffect { + /** + * @param {Renderer} renderer - the current renderer instance + * @param {object} [options] - effect options + * @param {number} [options.levels=4] - how many levels of each color channel are kept (2 or more), when no palette is given: 2 leaves eight colors, 4 leaves sixty-four + * @param {number[][]} [options.palette] - two to sixteen colors to draw in, each as [r, g, b] or [r, g, b, a] (0.0–1.0), instead of levels: every pixel takes one of the two nearest, the nearer more often. A color's alpha is how opaque the pixels that take it are drawn + * @param {number} [options.size=1.0] - the size of a drawn pixel (1 or more), in pixels of the texture it draws: screen pixels for a camera's effect, texels of its art for a sprite's + * @param {number} [options.strength=1.0] - how much of the dither pattern is applied (0.0 = flat bands, every pixel taking the nearest color; 1.0 = a full pattern between two colors) + * @param {number[]} [options.textureSize] - the size, `[width, height]`, of the texture its pixel size is measured in; by default the texture it draws: a sprite's own, alone or with other effects and at any scale or zoom, the screen for a camera's effect + */ + constructor(renderer, options = {}) { + super(renderer, { + glsl: ` + uniform vec4 uPalette[${MAX_COLORS}]; + uniform float uCount; + uniform float uLevels; + uniform float uStrength; + uniform float uPixelSize; + uniform vec2 uTextureSize; + ${FRAME_GLSL} + float ditherBayer2(vec2 p) { + vec2 a = mod(floor(p), 2.0); + return fract(a.x / 2.0 + a.y * a.y * 0.75); + } + vec4 apply(vec4 color, vec2 uv) { + vec2 texel = uPixelSize / uTextureSize; + vec2 cell = floor(uv / texel); + vec4 src = frameTexel((cell + 0.5) * texel) * vColor; + // the pixel's own color, out of its premultiplied form + vec3 rgb = src.rgb / max(src.a, 0.0001); + float threshold = ditherBayer2(cell * 0.5) * 0.25 + ditherBayer2(cell) + 0.03125 - 0.5; + float alpha = src.a; + vec3 result = rgb; + if (uCount < 0.5) { + float steps = uLevels - 1.0; + result = clamp(floor(rgb * steps + 0.5 + threshold * uStrength) / steps, 0.0, 1.0); + } else { + // the two nearest colors of the palette + vec4 first = uPalette[0]; + vec4 second = uPalette[0]; + float firstDistance = 1000.0; + float secondDistance = 1000.0; + for (int i = 0; i < ${MAX_COLORS}; i++) { + if (float(i) >= uCount) { + break; + } + vec3 d = rgb - uPalette[i].rgb; + float dist = dot(d, d); + if (dist < firstDistance) { + secondDistance = firstDistance; + second = first; + firstDistance = dist; + first = uPalette[i]; + } else if (dist < secondDistance) { + secondDistance = dist; + second = uPalette[i]; + } + } + // how far the pixel is from the nearest towards the other, 0 to 0.5 + vec3 axis = second.rgb - first.rgb; + float along = clamp(dot(rgb - first.rgb, axis) / max(dot(axis, axis), 0.000001), 0.0, 1.0); + vec4 chosen = along > mix(0.5, threshold + 0.5, uStrength) ? second : first; + result = chosen.rgb; + alpha *= chosen.a; + } + return vec4(result * alpha, alpha); + } + `, + wgsl: wgslFragment, + }); + + /** + * the palette, four floats a color, as the shader reads it + * @ignore + * @internal + */ + this._palette = new Float32Array(MAX_COLORS * 4); + + /** + * how many levels of each color channel are kept, when there is no + * palette + * @type {number} + */ + this.levels = 4; + + /** + * the size of a drawn pixel, in texels + * @type {number} + */ + this.size = 1; + + /** + * how much of the dither pattern is applied (0.0–1.0) + * @type {number} + */ + this.strength = 1; + + this.setLevels(options.levels ?? 4); + this.setSize(options.size ?? 1); + this.setStrength(options.strength ?? 1); + this.setPalette(options.palette ?? null); + // its pixel size is in texels: of the texture it draws, unless given one + this._initTextureSize(options.textureSize, [256, 256]); + } + + /** + * set how many levels of each color channel are kept. A palette, while + * one is set, is drawn in instead: see {@link DitherEffect#setPalette} + * @param {number} levels - 2 or more + */ + setLevels(levels) { + this.levels = Math.max(2, Math.round(levels)); + this.setUniform("uLevels", this.levels); + } + + /** + * set the colors to draw in, or go back to levels of each channel + * @param {number[][]|null} palette - two to sixteen colors, each as [r, g, b] or [r, g, b, a] (0.0–1.0); null to draw in levels again + */ + setPalette(palette) { + this._palette.fill(0); + if (palette === null) { + this.setUniform("uPalette", this._palette); + this.setUniform("uCount", 0); + return; + } + if (palette.length < 2 || palette.length > MAX_COLORS) { + throw new RangeError( + `a dither palette takes 2 to ${MAX_COLORS} colors, not ${palette.length}`, + ); + } + for (let i = 0; i < palette.length; i++) { + this._palette.set(rgba(palette[i]), i * 4); + } + this.setUniform("uPalette", this._palette); + this.setUniform("uCount", palette.length); + } + + /** + * set the size of a drawn pixel + * @param {number} size - in texels, 1 or more + */ + setSize(size) { + this.size = Math.max(1, size); + this.setUniform("uPixelSize", this.size); + } + + /** + * set how much of the dither pattern is applied + * @param {number} value - 0.0 = flat bands, 1.0 = a full pattern between two colors + */ + setStrength(value) { + this.strength = Math.max(0, Math.min(1, value)); + this.setUniform("uStrength", this.strength); + } + + /** + * Measure the effect's pixel size in the texels of a texture of this size, + * rather than of the texture it draws (the default) + * @param {number} width - texture width in pixels + * @param {number} height - texture height in pixels + */ + setTextureSize(width, height) { + this.setUniform("uTextureSize", new Float32Array([width, height])); + } +} diff --git a/packages/melonjs/src/video/effects/gradientMap.js b/packages/melonjs/src/video/effects/gradientMap.js new file mode 100644 index 0000000000..3d099ea0fd --- /dev/null +++ b/packages/melonjs/src/video/effects/gradientMap.js @@ -0,0 +1,190 @@ +import { rgba } from "./rgba.js"; +import ShaderEffect from "./shadereffect.js"; + +/** + * additional import for TypeScript + * @import CanvasRenderer from "../canvas/canvas_renderer.js"; + * @import WebGLRenderer from "../webgl/webgl_renderer.js"; + * @import WebGPURenderer from "../webgpu/webgpu_renderer.js"; + * @import Renderer from "../renderer.js"; + */ + +/** + * the most colors a gradient map takes + * @ignore + */ +const MAX_COLORS = 8; + +// Both bodies walk the colors with a loop over a constant bound: a uniform +// array indexed by a value computed per pixel is not something every GLSL +// compiler takes. Each color is mixed over the one before it, by how far +// the pixel's brightness is past it: a ramp when smooth, a step when not. + +// the WGSL twin of the GLSL body below: same logic, same uniform names, +// picked by the ShaderEffect base per renderer.shaderLanguage +const wgslFragment = ` +struct GradientMapUniforms { + uColors : array, + uCount : f32, + uSmooth : f32, + uIntensity : f32, +}; +@group(3) @binding(0) var fx : GradientMapUniforms; + +fn apply(color : vec4f, uv : vec2f) -> vec4f { + // the pixel's own color, out of its premultiplied form + let rgb = color.rgb / max(color.a, 0.0001); + let luma = clamp(dot(rgb, vec3f(0.2126, 0.7152, 0.0722)), 0.0, 1.0); + let pos = luma * (fx.uCount - 1.0); + let band = min(floor(luma * fx.uCount), fx.uCount - 1.0); + var mapped = fx.uColors[0]; + for (var i = 1; i < ${MAX_COLORS}; i++) { + if (f32(i) >= fx.uCount) { + break; + } + var f = step(f32(i), band); + if (fx.uSmooth > 0.5) { + f = clamp(pos - f32(i - 1), 0.0, 1.0); + } + mapped = mix(mapped, fx.uColors[i], f); + } + let alpha = color.a * mix(1.0, mapped.a, fx.uIntensity); + return vec4f(mix(rgb, mapped.rgb, fx.uIntensity) * alpha, alpha); +} +`; + +/** + * A shader effect that recolors the sprite from its brightness: the darkest + * pixels take the first color of a list, the brightest the last, and the + * ones in between the colors in between. The sprite keeps its shading and + * loses its own hues. + * + * Commonly used to draw one sprite as several (the same enemy in a palette + * per team or per level), for duotone and night scenes, and to give art from + * different sources one palette. + * + * With `smooth` off each color takes a band of brightness of its own, with a + * hard edge between two: a palette swap, for art drawn in a few flat shades. + * @category Effects + * @see {@link Renderable#addPostEffect} for usage + * @example + * // a duotone: shadows in navy, lights in cream + * mySprite.addPostEffect(new GradientMapEffect(renderer, { + * colors: [[0.05, 0.08, 0.25], [1.0, 0.93, 0.78]], + * })); + * @example + * // the same sprite as a second team: four flat shades of red + * enemy.addPostEffect(new GradientMapEffect(renderer, { + * colors: [[0.2, 0, 0.05], [0.55, 0.05, 0.1], [0.9, 0.25, 0.2], [1, 0.8, 0.7]], + * smooth: false, + * })); + * @example + * // fade a scene to its night palette, as an effect on the camera + * const night = new GradientMapEffect(renderer, { colors: nightColors, intensity: 0 }); + * app.viewport.addPostEffect(night); + * // then, over time + * night.setIntensity(night.intensity + dt / 2000); + */ +export default class GradientMapEffect extends ShaderEffect { + /** + * @param {Renderer} renderer - the current renderer instance + * @param {object} [options] - effect options + * @param {number[][]} [options.colors=[[0, 0, 0], [1, 1, 1]]] - two to eight colors, from the one the darkest pixels take to the one the brightest take, each as [r, g, b] or [r, g, b, a] (0.0–1.0); a color's alpha is how opaque the pixels that take it are drawn. The default draws the sprite in grays + * @param {boolean} [options.smooth=true] - blend from each color to the next; when false, each color takes a band of brightness of its own + * @param {number} [options.intensity=1.0] - how far the sprite is recolored (0.0 = its own colors, 1.0 = the colors of the list) + */ + constructor(renderer, options = {}) { + super(renderer, { + glsl: ` + uniform vec4 uColors[${MAX_COLORS}]; + uniform float uCount; + uniform float uSmooth; + uniform float uIntensity; + vec4 apply(vec4 color, vec2 uv) { + // the pixel's own color, out of its premultiplied form + vec3 rgb = color.rgb / max(color.a, 0.0001); + float luma = clamp(dot(rgb, vec3(0.2126, 0.7152, 0.0722)), 0.0, 1.0); + float pos = luma * (uCount - 1.0); + float band = min(floor(luma * uCount), uCount - 1.0); + vec4 mapped = uColors[0]; + for (int i = 1; i < ${MAX_COLORS}; i++) { + if (float(i) >= uCount) { + break; + } + float f = uSmooth > 0.5 + ? clamp(pos - float(i - 1), 0.0, 1.0) + : step(float(i), band); + mapped = mix(mapped, uColors[i], f); + } + float alpha = color.a * mix(1.0, mapped.a, uIntensity); + return vec4(mix(rgb, mapped.rgb, uIntensity) * alpha, alpha); + } + `, + wgsl: wgslFragment, + }); + + /** + * the colors, four floats each, as the shader reads them + * @ignore + * @internal + */ + this._colors = new Float32Array(MAX_COLORS * 4); + + /** + * how far the sprite is recolored (0.0–1.0) + * @type {number} + */ + this.intensity = options.intensity ?? 1.0; + + /** + * whether each color blends into the next + * @type {boolean} + */ + this.smooth = options.smooth ?? true; + + this.setColors( + options.colors ?? [ + [0, 0, 0], + [1, 1, 1], + ], + ); + this.setUniform("uSmooth", this.smooth ? 1 : 0); + this.setUniform("uIntensity", this.intensity); + } + + /** + * set the colors the sprite is drawn in + * @param {number[][]} colors - two to eight colors, from the one the darkest pixels take to the one the brightest take, each as [r, g, b] or [r, g, b, a] (0.0–1.0) + */ + setColors(colors) { + if (colors.length < 2 || colors.length > MAX_COLORS) { + throw new RangeError( + `a gradient map takes 2 to ${MAX_COLORS} colors, not ${colors.length}`, + ); + } + this._colors.fill(0); + for (let i = 0; i < colors.length; i++) { + this._colors.set(rgba(colors[i]), i * 4); + } + this.setUniform("uColors", this._colors); + this.setUniform("uCount", colors.length); + } + + /** + * set how far the sprite is recolored + * @param {number} value - 0.0 = its own colors, 1.0 = the colors of the list + */ + setIntensity(value) { + this.intensity = Math.max(0, Math.min(1, value)); + this.setUniform("uIntensity", this.intensity); + } + + /** + * blend from each color to the next, or give each a band of its own + * @param {boolean} smooth - false for hard bands + */ + setSmooth(smooth) { + this.smooth = smooth === true; + this.setUniform("uSmooth", this.smooth ? 1 : 0); + } +} diff --git a/packages/melonjs/tests/helpers/palette-effect-checks.js b/packages/melonjs/tests/helpers/palette-effect-checks.js new file mode 100644 index 0000000000..f596003253 --- /dev/null +++ b/packages/melonjs/tests/helpers/palette-effect-checks.js @@ -0,0 +1,606 @@ +/** + * What `GradientMapEffect` and `DitherEffect` draw, read in pixels, for any + * renderer with shaders: the same checks run on WebGL + * (`palette-effects.spec.js`) and on WebGPU + * (`palette-effects-webgpu.spec.js`). + * + * Each check draws a 32 x 32 sprite of known colors in the middle of a + * 64 x 64 frame, through the effect, and reads the frame back. + */ +import { expect, it } from "vitest"; +import { DitherEffect, GradientMapEffect, Sprite } from "../../src/index.js"; +import Renderer from "../../src/video/renderer.js"; +import { grabFrame } from "./pixels.js"; + +export const SIZE = 64; +const ART = 32; +// the sprite covers these pixels of the frame +const FROM = (SIZE - ART) / 2; + +/** a square texture of one CSS color */ +function flat(css) { + const canvas = Renderer.createCanvas(ART, ART); + const context = canvas.getContext("2d"); + context.fillStyle = css; + context.fillRect(0, 0, ART, ART); + return canvas; +} + +/** a gray, 0 to 1, as a CSS color */ +function gray(value) { + const v = Math.round(value * 255); + return `rgb(${v}, ${v}, ${v})`; +} + +/** a texture whose columns go from black to nearly white, left to right */ +function columns() { + const canvas = Renderer.createCanvas(ART, ART); + const context = canvas.getContext("2d"); + for (let x = 0; x < ART; x++) { + context.fillStyle = gray(x / ART); + context.fillRect(x, 0, 1, ART); + } + return canvas; +} + +/** draw `image` through `effect` over `background`, and return the frame */ +async function draw(renderer, image, effect, background = "#000000") { + const sprite = new Sprite(SIZE / 2, SIZE / 2, { image }); + sprite.addPostEffect(effect); + renderer.backgroundColor.parseCSS(background); + renderer.clear(); + renderer.save(); + renderer.resetTransform(); + sprite.preDraw(renderer); + sprite.draw(renderer); + sprite.postDraw(renderer); + renderer.restore(); + const frame = await grabFrame(renderer); + sprite.removePostEffect(effect); + effect.destroy(); + return frame; +} + +/** the pixel at x, y of a frame, as [r, g, b] */ +function at(frame, x, y) { + const o = (y * frame.width + x) * 4; + return [frame.data[o], frame.data[o + 1], frame.data[o + 2]]; +} + +/** the middle pixel of a frame */ +function middle(frame) { + return at(frame, SIZE / 2, SIZE / 2); +} + +/** every pixel the sprite covers, as [r, g, b] */ +function covered(frame) { + const pixels = []; + for (let y = FROM; y < FROM + ART; y++) { + for (let x = FROM; x < FROM + ART; x++) { + pixels.push(at(frame, x, y)); + } + } + return pixels; +} + +function expectClose(actual, expected, tolerance = 2) { + for (let i = 0; i < 3; i++) { + expect( + Math.abs(actual[i] - expected[i]), + `[${actual}] against [${expected}]`, + ).toBeLessThanOrEqual(tolerance); + } +} + +const RED = [1, 0, 0]; +const GREEN = [0, 1, 0]; +const BLUE = [0, 0, 1]; + +/** + * @param {(ctx: object) => object} getRenderer - gives the renderer, or skips the test + */ +export function gradientMapChecks(getRenderer) { + it("draws in grays by default, from each pixel's brightness", async (ctx) => { + const renderer = getRenderer(ctx); + expectClose( + middle( + await draw(renderer, flat(gray(0.5)), new GradientMapEffect(renderer)), + ), + [128, 128, 128], + ); + // pure red is 21% bright + expectClose( + middle( + await draw(renderer, flat("#ff0000"), new GradientMapEffect(renderer)), + ), + [54, 54, 54], + ); + }); + + it("gives the darkest pixels the first color and the brightest the last", async (ctx) => { + const renderer = getRenderer(ctx); + const duotone = () => { + return new GradientMapEffect(renderer, { colors: [BLUE, RED] }); + }; + expectClose( + middle(await draw(renderer, flat("#000000"), duotone())), + [0, 0, 255], + ); + expectClose( + middle(await draw(renderer, flat("#ffffff"), duotone())), + [255, 0, 0], + ); + expectClose( + middle(await draw(renderer, flat(gray(0.5)), duotone())), + [128, 0, 127], + ); + }); + + it("blends through every color in between, in order", async (ctx) => { + const renderer = getRenderer(ctx); + const three = () => { + return new GradientMapEffect(renderer, { colors: [RED, GREEN, BLUE] }); + }; + expectClose( + middle(await draw(renderer, flat("#000000"), three())), + [255, 0, 0], + ); + expectClose( + middle(await draw(renderer, flat(gray(0.25)), three())), + [127, 128, 0], + 3, + ); + expectClose( + middle(await draw(renderer, flat(gray(0.5)), three())), + [0, 254, 1], + 3, + ); + expectClose( + middle(await draw(renderer, flat(gray(0.75)), three())), + [0, 127, 128], + 3, + ); + expectClose( + middle(await draw(renderer, flat("#ffffff"), three())), + [0, 0, 255], + ); + }); + + it("takes eight colors", async (ctx) => { + const renderer = getRenderer(ctx); + const colors = []; + for (let i = 0; i < 8; i++) { + colors.push([i / 7, 0, 1 - i / 7]); + } + // a ramp from blue to red in eight equal steps is one straight ramp + expectClose( + middle( + await draw( + renderer, + flat(gray(0.3)), + new GradientMapEffect(renderer, { colors }), + ), + ), + [77, 0, 178], + 3, + ); + expectClose( + middle( + await draw( + renderer, + flat("#ffffff"), + new GradientMapEffect(renderer, { colors }), + ), + ), + [255, 0, 0], + ); + }); + + it("gives each color a band of its own when not smooth", async (ctx) => { + const renderer = getRenderer(ctx); + const WHITE = [1, 1, 1]; + const bands = () => { + return new GradientMapEffect(renderer, { + colors: [RED, GREEN, BLUE, WHITE], + smooth: false, + }); + }; + // four bands: below a quarter, a half, three quarters, and above + expectClose( + middle(await draw(renderer, flat("#000000"), bands())), + [255, 0, 0], + ); + expectClose( + middle(await draw(renderer, flat(gray(0.2)), bands())), + [255, 0, 0], + ); + expectClose( + middle(await draw(renderer, flat(gray(0.3)), bands())), + [0, 255, 0], + ); + expectClose( + middle(await draw(renderer, flat(gray(0.45)), bands())), + [0, 255, 0], + ); + expectClose( + middle(await draw(renderer, flat(gray(0.6)), bands())), + [0, 0, 255], + ); + expectClose( + middle(await draw(renderer, flat(gray(0.8)), bands())), + [255, 255, 255], + ); + expectClose( + middle(await draw(renderer, flat("#ffffff"), bands())), + [255, 255, 255], + ); + }); + + it("setSmooth switches between the two", async (ctx) => { + const renderer = getRenderer(ctx); + const effect = new GradientMapEffect(renderer, { colors: [BLUE, RED] }); + effect.setSmooth(false); + expect(effect.smooth).toBe(false); + // two bands: the dark half blue, the bright half red + expectClose( + middle(await draw(renderer, flat(gray(0.4)), effect)), + [0, 0, 255], + ); + }); + + it("recolors as far as its intensity", async (ctx) => { + const renderer = getRenderer(ctx); + const at = (intensity) => { + return new GradientMapEffect(renderer, { + colors: [BLUE, BLUE], + intensity, + }); + }; + expectClose( + middle(await draw(renderer, flat("#ff0000"), at(0))), + [255, 0, 0], + ); + expectClose( + middle(await draw(renderer, flat("#ff0000"), at(0.5))), + [128, 0, 128], + ); + expectClose( + middle(await draw(renderer, flat("#ff0000"), at(1))), + [0, 0, 255], + ); + }); + + it("draws the pixels that take a color as opaque as that color", async (ctx) => { + const renderer = getRenderer(ctx); + // the dark pixels take a transparent color: what is behind shows + const knockout = () => { + return new GradientMapEffect(renderer, { + colors: [ + [0, 0, 0, 0], + [1, 1, 1, 1], + ], + smooth: false, + }); + }; + expectClose( + middle(await draw(renderer, flat("#000000"), knockout(), "#ff0000")), + [255, 0, 0], + ); + expectClose( + middle(await draw(renderer, flat("#ffffff"), knockout(), "#ff0000")), + [255, 255, 255], + ); + // and a half-opaque color lets half of it through + const half = new GradientMapEffect(renderer, { + colors: [ + [0, 0, 1, 0.5], + [0, 0, 1, 0.5], + ], + }); + expectClose( + middle(await draw(renderer, flat("#ffffff"), half, "#ff0000")), + [128, 0, 128], + ); + }); + + it("keeps a translucent pixel as translucent as it was", async (ctx) => { + const renderer = getRenderer(ctx); + // half-opaque white over black: white at half + expectClose( + middle( + await draw( + renderer, + flat("rgba(255, 255, 255, 0.5)"), + new GradientMapEffect(renderer), + ), + ), + [128, 128, 128], + 3, + ); + // and it is mapped from its own color, not from its premultiplied one: + // half-opaque white is bright, so it takes the last color + expectClose( + middle( + await draw( + renderer, + flat("rgba(255, 255, 255, 0.5)"), + new GradientMapEffect(renderer, { + colors: [BLUE, RED], + smooth: false, + }), + ), + ), + [128, 0, 0], + 3, + ); + }); +} + +/** + * @param {(ctx: object) => object} getRenderer - gives the renderer, or skips the test + */ +export function ditherChecks(getRenderer) { + const count = (pixels, color) => { + return pixels.filter((p) => { + return ( + Math.abs(p[0] - color[0]) <= 2 && + Math.abs(p[1] - color[1]) <= 2 && + Math.abs(p[2] - color[2]) <= 2 + ); + }).length; + }; + + it("with no pattern, rounds each channel to its nearest level", async (ctx) => { + const renderer = getRenderer(ctx); + const flatBands = (levels) => { + return new DitherEffect(renderer, { levels, strength: 0 }); + }; + expectClose( + middle(await draw(renderer, flat(gray(0.3)), flatBands(2))), + [0, 0, 0], + ); + expectClose( + middle(await draw(renderer, flat(gray(0.7)), flatBands(2))), + [255, 255, 255], + ); + // each channel on its own + expectClose( + middle(await draw(renderer, flat("rgb(204, 51, 153)"), flatBands(2))), + [255, 0, 255], + ); + // four levels: 0, a third, two thirds, 1 + expectClose( + middle(await draw(renderer, flat(gray(0.4)), flatBands(4))), + [85, 85, 85], + ); + expectClose( + middle(await draw(renderer, flat(gray(0.6)), flatBands(4))), + [170, 170, 170], + ); + }); + + it("draws a gray between two levels as a mix of the two, in proportion", async (ctx) => { + const renderer = getRenderer(ctx); + const twoLevels = () => { + return new DitherEffect(renderer, { levels: 2 }); + }; + // half gray: half the pixels white, the others black, and nothing else + let pixels = covered(await draw(renderer, flat(gray(0.5)), twoLevels())); + expect(count(pixels, [255, 255, 255])).toBe(ART * ART * 0.5); + expect(count(pixels, [0, 0, 0])).toBe(ART * ART * 0.5); + // a quarter gray: a quarter of them white + pixels = covered(await draw(renderer, flat(gray(0.25)), twoLevels())); + expect(count(pixels, [255, 255, 255])).toBe(ART * ART * 0.25); + expect(count(pixels, [0, 0, 0])).toBe(ART * ART * 0.75); + // three quarters: three quarters of them + pixels = covered(await draw(renderer, flat(gray(0.75)), twoLevels())); + expect(count(pixels, [255, 255, 255])).toBe(ART * ART * 0.75); + }); + + it("spreads the mix evenly: every 4 x 4 block of a half gray is half white", async (ctx) => { + const renderer = getRenderer(ctx); + const frame = await draw( + renderer, + flat(gray(0.5)), + new DitherEffect(renderer, { levels: 2 }), + ); + for (let by = FROM; by < FROM + ART; by += 4) { + for (let bx = FROM; bx < FROM + ART; bx += 4) { + let white = 0; + for (let y = by; y < by + 4; y++) { + for (let x = bx; x < bx + 4; x++) { + white += at(frame, x, y)[0] > 128 ? 1 : 0; + } + } + expect(white, `block at ${bx}, ${by}`).toBe(8); + } + } + }); + + it("leaves a color that is a level as it is, with or without the pattern", async (ctx) => { + const renderer = getRenderer(ctx); + const pixels = covered( + await draw( + renderer, + flat("#ffffff"), + new DitherEffect(renderer, { levels: 2 }), + ), + ); + expect(count(pixels, [255, 255, 255])).toBe(ART * ART); + }); + + it("draws pixels of several texels with size", async (ctx) => { + const renderer = getRenderer(ctx); + const frame = await draw( + renderer, + columns(), + new DitherEffect(renderer, { levels: 256, strength: 0, size: 4 }), + ); + // the columns of the texture differ, the pixels of one cell do not + const y = SIZE / 2; + for (let cell = 0; cell < ART / 4; cell++) { + const x = FROM + cell * 4; + const first = at(frame, x, y); + for (let i = 1; i < 4; i++) { + expectClose(at(frame, x + i, y), first, 0); + } + } + // and one cell differs from the next + expect(at(frame, FROM + 4, y)[0]).toBeGreaterThan(at(frame, FROM, y)[0]); + expect(at(frame, FROM + 28, y)[0]).toBeGreaterThan( + at(frame, FROM + 4, y)[0] + 100, + ); + }); + + it("draws in the nearest color of a palette", async (ctx) => { + const renderer = getRenderer(ctx); + const palette = () => { + return new DitherEffect(renderer, { + palette: [RED, GREEN, BLUE], + strength: 0, + }); + }; + expectClose( + middle(await draw(renderer, flat("rgb(230, 50, 25)"), palette())), + [255, 0, 0], + ); + expectClose( + middle(await draw(renderer, flat("rgb(50, 180, 60)"), palette())), + [0, 255, 0], + ); + expectClose( + middle(await draw(renderer, flat("rgb(50, 75, 230)"), palette())), + [0, 0, 255], + ); + }); + + it("takes sixteen colors, and reaches the last", async (ctx) => { + const renderer = getRenderer(ctx); + const palette = []; + for (let i = 0; i < 16; i++) { + palette.push([i / 15, i / 15, i / 15]); + } + expectClose( + middle( + await draw( + renderer, + flat("#ffffff"), + new DitherEffect(renderer, { palette, strength: 0 }), + ), + ), + [255, 255, 255], + ); + // 0.4 is the palette's seventh gray, 6 / 15 + expectClose( + middle( + await draw( + renderer, + flat(gray(0.4)), + new DitherEffect(renderer, { palette, strength: 0 }), + ), + ), + [102, 102, 102], + ); + }); + + it("mixes the two colors of a palette a pixel lies between", async (ctx) => { + const renderer = getRenderer(ctx); + const pixels = covered( + await draw( + renderer, + flat(gray(0.5)), + new DitherEffect(renderer, { + palette: [ + [0, 0, 0], + [1, 1, 1], + ], + }), + ), + ); + expect(count(pixels, [255, 255, 255])).toBe(ART * ART * 0.5); + expect(count(pixels, [0, 0, 0])).toBe(ART * ART * 0.5); + }); + + it("mixes them in proportion: a quarter of the way is a quarter of the pixels", async (ctx) => { + const renderer = getRenderer(ctx); + const pixels = covered( + await draw( + renderer, + flat(gray(0.25)), + new DitherEffect(renderer, { + palette: [ + [0, 0, 0], + [1, 1, 1], + ], + }), + ), + ); + expect(count(pixels, [255, 255, 255])).toBe(ART * ART * 0.25); + expect(count(pixels, [0, 0, 0])).toBe(ART * ART * 0.75); + }); + + it("leaves a color that is in the palette flat, however close its neighbours", async (ctx) => { + const renderer = getRenderer(ctx); + // two close greens and two far colors: the pattern must not reach + // from one green to the other + const palette = [ + [0.2, 0.6, 0.2], + [0.25, 0.65, 0.2], + [1, 1, 1], + [0, 0, 0], + ]; + const pixels = covered( + await draw( + renderer, + flat("rgb(51, 153, 51)"), + new DitherEffect(renderer, { palette }), + ), + ); + expect(count(pixels, [51, 153, 51])).toBe(ART * ART); + }); + + it("draws the pixels that take a palette color as opaque as that color", async (ctx) => { + const renderer = getRenderer(ctx); + const effect = new DitherEffect(renderer, { + palette: [ + [1, 1, 1, 0.5], + [0, 0, 0, 1], + ], + strength: 0, + }); + expectClose( + middle(await draw(renderer, flat("#ffffff"), effect, "#ff0000")), + [255, 128, 128], + ); + }); + + it("setPalette(null) goes back to levels", async (ctx) => { + const renderer = getRenderer(ctx); + const effect = new DitherEffect(renderer, { + palette: [RED, BLUE], + levels: 2, + strength: 0, + }); + effect.setPalette(null); + // green is in neither color of the palette it had + expectClose( + middle(await draw(renderer, flat("#00ff00"), effect)), + [0, 255, 0], + ); + }); + + it("keeps a translucent pixel as translucent as it was", async (ctx) => { + const renderer = getRenderer(ctx); + expectClose( + middle( + await draw( + renderer, + flat("rgba(255, 255, 255, 0.5)"), + new DitherEffect(renderer, { levels: 2, strength: 0 }), + ), + ), + [128, 128, 128], + 3, + ); + }); +} diff --git a/packages/melonjs/tests/palette-effects-webgpu.spec.js b/packages/melonjs/tests/palette-effects-webgpu.spec.js new file mode 100644 index 0000000000..30c8838e59 --- /dev/null +++ b/packages/melonjs/tests/palette-effects-webgpu.spec.js @@ -0,0 +1,59 @@ +/** + * The `GradientMapEffect` and `DitherEffect` drawing checks on WebGPU, in a + * spec file of its own: an application with a GPU device takes the place of + * the shared WebGL renderer `palette-effects.spec.js` draws with. + * + * Skipped, visibly, where the browser has no WebGPU adapter. + */ +import { afterAll, beforeAll, describe } from "vitest"; +import { Application, boot, video } from "../src/index.js"; +import { + ditherChecks, + gradientMapChecks, + SIZE, +} from "./helpers/palette-effect-checks.js"; +import { drawOffscreen } from "./helpers/pixels.js"; + +describe("palette effects, on WebGPU", () => { + let app; + let available = false; + beforeAll(async () => { + boot(); + try { + app = new Application(SIZE, SIZE, { + parent: "screen", + renderer: video.WEBGPU, + consoleHeader: false, + }); + await app.init(); + available = app.renderer.type === "WebGPU"; + if (available) { + const renderer = drawOffscreen(app.renderer); + // the checks draw without a camera, which is what sets the + // projection in a game + renderer.projectionMatrix.ortho(0, SIZE, SIZE, 0, -1000, 1000); + renderer.setProjection(renderer.projectionMatrix); + } + } catch { + available = false; + } + }); + afterAll(() => { + app?.destroy(); + }); + + const getRenderer = (ctx) => { + if (!available) { + ctx.skip("WebGPU not available in this environment"); + } + return app.renderer; + }; + + describe("GradientMapEffect", () => { + gradientMapChecks(getRenderer); + }); + + describe("DitherEffect", () => { + ditherChecks(getRenderer); + }); +}); diff --git a/packages/melonjs/tests/palette-effects.spec.js b/packages/melonjs/tests/palette-effects.spec.js new file mode 100644 index 0000000000..f13313258e --- /dev/null +++ b/packages/melonjs/tests/palette-effects.spec.js @@ -0,0 +1,207 @@ +/** + * `GradientMapEffect` (a sprite recolored from its brightness) and + * `DitherEffect` (a sprite drawn in a few colors, with an ordered dither + * between them): what they draw on WebGL, what they refuse, and that their + * WGSL twins read the same values. + * + * The drawing checks are in `helpers/palette-effect-checks.js`, which + * `palette-effects-webgpu.spec.js` runs on WebGPU. + */ +import "./helpers/webgpu-globals.js"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { boot, DitherEffect, GradientMapEffect } from "../src/index.js"; +import WebGLRenderer from "../src/video/webgl/webgl_renderer.js"; +import { + ditherChecks, + gradientMapChecks, + SIZE, +} from "./helpers/palette-effect-checks.js"; +import { + getWebGLRenderer, + releaseWebGLRenderer, +} from "./helpers/webgl-context.js"; + +// enough of a renderer for an effect to build its WGSL twin +const wgslRenderer = { shaderLanguage: "wgsl", width: 64, height: 64 }; + +/** build an effect for WGSL, without the warning that no device is there */ +function forWGSL(Effect, options) { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const effect = new Effect(wgslRenderer, options); + warn.mockRestore(); + return effect; +} + +/** `count` floats of a member of an effect's WGSL uniform block */ +function block(effect, member, count) { + const { layout, f32 } = effect.wgslRealization; + const from = layout.get(member).offset >> 2; + return Array.from(f32.subarray(from, from + count)); +} + +describe("palette effects", () => { + let renderer; + + beforeAll(async () => { + boot(); + renderer = await getWebGLRenderer(SIZE, SIZE); + if (renderer instanceof WebGLRenderer) { + renderer.projectionMatrix.ortho(0, SIZE, SIZE, 0, -1000, 1000); + renderer.currentBatcher.setProjection(renderer.projectionMatrix); + } else { + renderer = undefined; + } + }); + + afterAll(() => { + releaseWebGLRenderer(); + }); + + const getRenderer = (ctx) => { + if (renderer === undefined) { + ctx.skip("WebGL renderer not available in this environment"); + } + return renderer; + }; + + describe("GradientMapEffect, drawn on WebGL", () => { + gradientMapChecks(getRenderer); + }); + + describe("DitherEffect, drawn on WebGL", () => { + ditherChecks(getRenderer); + }); + + describe("GradientMapEffect", () => { + it("takes two to eight colors, and nothing else", () => { + const make = (colors) => { + return forWGSL(GradientMapEffect, { colors }); + }; + expect(() => { + return make([[1, 0, 0]]); + }).toThrow(RangeError); + expect(() => { + return make(new Array(9).fill([1, 0, 0])); + }).toThrow(RangeError); + expect(() => { + return make([ + [1, 0, 0], + [0, 1], + ]); + }).toThrow(TypeError); + expect(() => { + return make(new Array(8).fill([1, 0, 0])); + }).not.toThrow(); + }); + + it("setColors refuses a bad list and keeps the one it had", () => { + const effect = forWGSL(GradientMapEffect, { + colors: [ + [0, 0, 1], + [1, 0, 0], + ], + }); + expect(() => { + effect.setColors([[1, 1, 1]]); + }).toThrow(RangeError); + expect(block(effect, "uColors", 8)).toEqual([0, 0, 1, 1, 1, 0, 0, 1]); + expect(block(effect, "uCount", 1)).toEqual([2]); + }); + + it("keeps its intensity between 0 and 1", () => { + const effect = forWGSL(GradientMapEffect); + expect(effect.intensity).toBe(1); + effect.setIntensity(4); + expect(effect.intensity).toBe(1); + effect.setIntensity(-1); + expect(effect.intensity).toBe(0); + expect(block(effect, "uIntensity", 1)).toEqual([0]); + }); + + it("gives its WGSL twin the same values", () => { + const effect = forWGSL(GradientMapEffect, { + colors: [ + [0.25, 0.5, 0.75], + [1, 0, 0, 0.5], + [0, 1, 0], + ], + smooth: false, + intensity: 0.5, + }); + expect(effect.wgslRealization.valid).toBe(true); + expect(block(effect, "uColors", 12)).toEqual([ + 0.25, 0.5, 0.75, 1, 1, 0, 0, 0.5, 0, 1, 0, 1, + ]); + expect(block(effect, "uCount", 1)).toEqual([3]); + expect(block(effect, "uSmooth", 1)).toEqual([0]); + expect(block(effect, "uIntensity", 1)).toEqual([0.5]); + // a shorter list leaves none of the longer one behind + effect.setColors([ + [1, 1, 1], + [0, 0, 0], + ]); + expect(block(effect, "uColors", 12)).toEqual([ + 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, + ]); + }); + }); + + describe("DitherEffect", () => { + it("takes a palette of two to sixteen colors, and nothing else", () => { + const make = (palette) => { + return forWGSL(DitherEffect, { palette }); + }; + expect(() => { + return make([[1, 0, 0]]); + }).toThrow(RangeError); + expect(() => { + return make(new Array(17).fill([1, 0, 0])); + }).toThrow(RangeError); + expect(() => { + return make([ + [1, 0, 0], + [0, 1, 0, 1, 1], + ]); + }).toThrow(TypeError); + expect(() => { + return make(new Array(16).fill([1, 0, 0])); + }).not.toThrow(); + }); + + it("keeps its levels, size and strength in range", () => { + const effect = forWGSL(DitherEffect); + expect([effect.levels, effect.size, effect.strength]).toEqual([4, 1, 1]); + effect.setLevels(1); + expect(effect.levels).toBe(2); + effect.setLevels(3.6); + expect(effect.levels).toBe(4); + effect.setSize(0); + expect(effect.size).toBe(1); + effect.setStrength(2); + expect(effect.strength).toBe(1); + effect.setStrength(-2); + expect(effect.strength).toBe(0); + }); + + it("gives its WGSL twin the same values", () => { + const effect = forWGSL(DitherEffect, { + palette: [ + [0, 0, 0], + [1, 1, 1, 0.5], + ], + levels: 3, + size: 2, + strength: 0.25, + }); + expect(effect.wgslRealization.valid).toBe(true); + expect(block(effect, "uPalette", 8)).toEqual([0, 0, 0, 1, 1, 1, 1, 0.5]); + expect(block(effect, "uCount", 1)).toEqual([2]); + expect(block(effect, "uLevels", 1)).toEqual([3]); + expect(block(effect, "uPixelSize", 1)).toEqual([2]); + expect(block(effect, "uStrength", 1)).toEqual([0.25]); + effect.setPalette(null); + expect(block(effect, "uCount", 1)).toEqual([0]); + expect(block(effect, "uPalette", 8)).toEqual([0, 0, 0, 0, 0, 0, 0, 0]); + }); + }); +}); diff --git a/packages/melonjs/tests/webgpu_effects_validate.spec.js b/packages/melonjs/tests/webgpu_effects_validate.spec.js index 298ba2b641..d9ea8f365e 100644 --- a/packages/melonjs/tests/webgpu_effects_validate.spec.js +++ b/packages/melonjs/tests/webgpu_effects_validate.spec.js @@ -6,9 +6,11 @@ import { ColorMatrixEffect, DesaturateEffect, DissolveEffect, + DitherEffect, DropShadowEffect, FlashEffect, GlowEffect, + GradientMapEffect, HologramEffect, InvertEffect, OutlineEffect, @@ -39,9 +41,11 @@ describe("built-in effect WGSL twins compile on the device", () => { ColorMatrixEffect, DesaturateEffect, DissolveEffect, + DitherEffect, DropShadowEffect, FlashEffect, GlowEffect, + GradientMapEffect, HologramEffect, InvertEffect, OutlineEffect, From fdb87e409a20e9ec5920f627d515c1d6e2f48321 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 00:07:03 +0000 Subject: [PATCH 38/51] Remove the Dithering example; the two effects in the README and the skills The Dithering example was a scene to look at the effect with, not one to keep. The README's list of built-in effects names the two new ones, the skills' router says where palette swaps and a dithered look are covered, and the sprite skill says what a tint cannot do (it multiplies, so it only darkens) and what to use instead: a GradientMapEffect to recolor a sprite, a FlashEffect to flash it. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- README.md | 2 +- .../examples/dithering/ExampleDithering.tsx | 349 ------------------ packages/examples/src/main.tsx | 13 - packages/melonjs/CHANGELOG.md | 2 +- .../melonjs-sprites-and-animation/SKILL.md | 14 + packages/melonjs/skills/melonjs/SKILL.md | 2 +- 6 files changed, 17 insertions(+), 365 deletions(-) delete mode 100644 packages/examples/src/examples/dithering/ExampleDithering.tsx diff --git a/README.md b/README.md index 07a8f3da58..3ad465a068 100644 --- a/README.md +++ b/README.md @@ -63,7 +63,7 @@ Graphics - **3D** — `Light3d` directional, point, spot and ambient lights, added to the world like `Light2d` (half-Lambert diffuse + ambient fill, quadratic falloff and cone angles on the punctual types, runtime-manipulable for day/night), auto-loaded from a glTF scene's authored suns and lamps - up to **32 simultaneous lights** on either path, with light data travelling in a uniform buffer — a static light rig costs zero GPU state changes per frame - Ground ("blob") shadows for 3D objects — **on by default** — so characters and props read as standing on the floor instead of hovering. An ellipse matching the caster's own footprint and rotation, shrinking and fading with height above the ground; one extra draw per object, and **one for an entire `InstancedMesh` scatter regardless of instance count**. Shaped by the light rather than always straight down: `shadowLight` points a blob at a `Light3d` and is re-read every draw, so a day/night cycle carries every shadow with it, while `shadowOffset` slides it out from the caster's feet, `shadowStretch` lengthens it for a low sun, `shadowScale` sizes it independently of the object, `shadowGroundNormal` lays it on a floor that is not level, and `shadowGroundPoint` on ground that is not flat at all, such as a planet. All of them work on an `InstancedMesh` too, as one value for the whole set. Controllable per object, per glTF scene (`level.load(name, { castGroundShadow, shadowLight, … })`) or application-wide. Deliberately not shadow mapping: it answers "where is this standing", which is what a 2.5D scene needs -- Built-in shader effects (Flash, Outline, Glow, Bloom, ToneMapping, Dissolve, CRT, Hologram, Shine, Vignette, Squish, Sway, etc.) with multi-pass chaining via `addPostEffect()`, on sprites, cameras and meshes alike, plus custom shader support on both GPU backends: `ShaderEffect` for per-sprite fragment effects (GLSL and/or WGSL bodies) and complete custom mesh shader programs via `mesh.shader` (a dual-language `GLShader`: GLSL pair and/or WGSL module) +- Built-in shader effects (Flash, Outline, Glow, Bloom, ToneMapping, Dissolve, CRT, Hologram, Shine, Vignette, Squish, Sway, Gradient Map for palette swaps, Dither for a retro limited-color look, etc.) with multi-pass chaining via `addPostEffect()`, on sprites, cameras and meshes alike, plus custom shader support on both GPU backends: `ShaderEffect` for per-sprite fragment effects (GLSL and/or WGSL bodies) and complete custom mesh shader programs via `mesh.shader` (a dual-language `GLShader`: GLSL pair and/or WGSL module) - Optional HDR rendering (`hdr: true`) — the camera's render targets become half-float, so additive light stops saturating on every write and `BloomEffect` thresholds on genuinely over-bright pixels instead of merely bright ones, with `ToneMappingEffect` and a `toneMapping` setting to compress the result back into display range when your art calls for it. Off by default and additive: nothing is inserted into your effect chain, so turning it on does not restyle a game whose look is built on clipped whites. On WebGPU it goes one step further — `hdrOutput: true` presents the frame in the display's own dynamic range rather than clamping it to SDR at the last step - Screen-space effects (refraction, heat haze, water): `renderer.toFrameTexture()` captures the frame for a `ShaderEffect` to sample, through the `screen_texture` / `screen_uv` built-ins - Shaders preloaded like any other asset, and the built-in shader programs compiled behind the loading screen (`prewarm`), so the first frame of an effect does not stall diff --git a/packages/examples/src/examples/dithering/ExampleDithering.tsx b/packages/examples/src/examples/dithering/ExampleDithering.tsx deleted file mode 100644 index 621b1b5cec..0000000000 --- a/packages/examples/src/examples/dithering/ExampleDithering.tsx +++ /dev/null @@ -1,349 +0,0 @@ -/** - * melonJS — a dithered scene. - * - * One `DitherEffect` on the camera draws the whole scene in a few levels of - * each color channel, in pixels several screen pixels wide, with an ordered - * dither wherever a color falls between two levels. Nothing in the scene - * knows about it: the shapes are plain lit meshes. - * - * What gets patterned is what lies between two levels, which is the shading: - * the turn of a lit surface from light to dark, the soft edge of a shadow. - * A flat color that is itself a level is left alone, so the sky and the - * ground, which are given such colors, stay clean (at 6 and 16 levels: try - * 3). Each shape keeps its own hue. - * - * The checkboxes switch the effect, the number of levels and the pixel size. - * They are drawn by the same camera, so they are dithered with the rest. - * - * Copyright (C) 2011 - 2026 AltByte Pte Ltd — MIT License. - * See `packages/examples/LICENSE.md` for full license + asset credits. - */ -import { - Application, - Camera3d, - type CanvasRenderer, - DitherEffect, - Light3d, - Mesh, - Renderable, - Stage, - state, - UICheckbox, - Vector3d, - video, - type WebGLRenderer, -} from "melonjs"; -import { createExampleComponent } from "../utils"; - -// render space is Y-DOWN: the floor is at y = 0 and up is negative -const GROUND_Y = 0; -const UP = new Vector3d(0, 1, 0); -// The sky and the ground are made of fifths of 255, which are levels of a -// channel at 6 levels and at 16: there they are left alone. At 3 levels they -// fall between two, and are patterned like everything else. -const SKY = "#0066cc"; -const GROUND = [102, 204, 51] as const; - -/** a flat sky behind the scene, in screen space */ -class Backdrop extends Renderable { - constructor() { - super(0, 0, 1, 1); - this.floating = true; - this.anchorPoint.set(0, 0); - } - - override draw(renderer: CanvasRenderer | WebGLRenderer) { - renderer.setColor(SKY); - renderer.fillRect(0, 0, renderer.width, renderer.height); - } -} - -type Geometry = { - vertices: number[]; - normals: number[]; - indices: number[]; - width: number; - height: number; -}; - -/** a mesh of one flat color from a geometry authored Y-UP */ -const createShape = ( - geometry: Geometry, - color: readonly [number, number, number], - settings: { lit: boolean; castGroundShadow: boolean }, -) => { - const mesh = new Mesh(0, GROUND_Y, { - vertices: new Float32Array(geometry.vertices), - normals: new Float32Array(geometry.normals), - uvs: new Float32Array((geometry.vertices.length / 3) * 2), - indices: new Uint16Array(geometry.indices), - normalize: false, - scale: 1, - width: geometry.width, - height: geometry.height, - cullBackFaces: false, - shadowGroundY: GROUND_Y, - shadowOpacity: 0.6, - shadowScale: 1.3, - ...settings, - }); - mesh.tint.setColor(color[0], color[1], color[2]); - return mesh; -}; - -/** a round floor */ -const disc = (radius: number): Geometry => { - const segments = 64; - const vertices = [0, 0, 0]; - const normals = [0, 1, 0]; - const indices: number[] = []; - for (let i = 0; i <= segments; i++) { - const a = (i / segments) * Math.PI * 2; - vertices.push(Math.cos(a) * radius, 0, Math.sin(a) * radius); - normals.push(0, 1, 0); - if (i > 0) { - indices.push(0, i + 1, i); - } - } - return { vertices, normals, indices, width: radius * 2, height: radius * 2 }; -}; - -/** a sphere stretched to three radii, with smooth normals */ -const ellipsoid = (rx: number, ry: number, rz: number): Geometry => { - const rings = 28; - const segments = 44; - const vertices: number[] = []; - const normals: number[] = []; - const indices: number[] = []; - for (let r = 0; r <= rings; r++) { - const phi = (r / rings) * Math.PI; - for (let s = 0; s <= segments; s++) { - const theta = (s / segments) * Math.PI * 2; - const x = Math.sin(phi) * Math.cos(theta); - const y = Math.cos(phi); - const z = Math.sin(phi) * Math.sin(theta); - vertices.push(x * rx, y * ry, z * rz); - // the normal of a stretched sphere leans away from its long axes - const n = new Vector3d(x / rx, y / ry, z / rz).normalize(); - normals.push(n.x, n.y, n.z); - if (r < rings && s < segments) { - const a = r * (segments + 1) + s; - const b = a + segments + 1; - indices.push(a, b, a + 1, b, b + 1, a + 1); - } - } - } - return { vertices, normals, indices, width: rx * 2, height: ry * 2 }; -}; - -/** a ring standing upright, facing the camera */ -const torus = (ring: number, tube: number): Geometry => { - const around = 56; - const across = 28; - const vertices: number[] = []; - const normals: number[] = []; - const indices: number[] = []; - for (let i = 0; i <= around; i++) { - const u = (i / around) * Math.PI * 2; - for (let j = 0; j <= across; j++) { - const v = (j / across) * Math.PI * 2; - const out = ring + tube * Math.cos(v); - vertices.push(out * Math.cos(u), out * Math.sin(u), tube * Math.sin(v)); - normals.push( - Math.cos(v) * Math.cos(u), - Math.cos(v) * Math.sin(u), - Math.sin(v), - ); - if (i < around && j < across) { - const a = i * (across + 1) + j; - const b = a + across + 1; - indices.push(a, b, a + 1, b, b + 1, a + 1); - } - } - } - const size = (ring + tube) * 2; - return { vertices, normals, indices, width: size, height: size }; -}; - -const createGame = async () => { - let app: Application; - try { - app = new Application(1024, 576, { - parent: "screen", - renderer: video.AUTO, - scale: "auto", - cameraClass: Camera3d, - antiAlias: true, - }); - await app.init(); - if (!app.renderer.supportsDepthBuffer) { - throw new Error("no GPU backend available (Canvas fallback)"); - } - } catch (err) { - const reason = err instanceof Error ? err.message : String(err); - globalThis.alert( - "This example couldn't start: it needs WebGL 2 or WebGPU.\n\n" + - `Details: ${reason}`, - ); - throw err; - } - - const buildScene = (app: Application) => { - const world = app.world; - world.addChild(new Backdrop(), -10000); - - // a key light from the upper left, and a fill so the dark side of a - // shape keeps some of its color - world.addChild( - new Light3d({ - type: "directional", - direction: [0.5, 0.6, 0.65], - color: [1, 1, 1], - intensity: 1, - }), - ); - world.addChild( - new Light3d({ type: "ambient", color: [1, 1, 1], intensity: 0.35 }), - ); - - // the ground is not lit: it keeps the one color it is given - world.addChild( - createShape(disc(2400), GROUND, { lit: false, castGroundShadow: false }), - 0, - ); - - // the shapes: each of one color, lit, with a soft shadow on the ground - const place = (mesh: Mesh, x: number, y: number, z: number) => { - mesh.pos.set(x, GROUND_Y - y); - mesh.depth = z; - world.addChild(mesh, z); - return mesh; - }; - const solid = { lit: true, castGroundShadow: true }; - place( - createShape(ellipsoid(150, 100, 110), [235, 60, 70], solid), - -300, - 100, - -40, - ); - const ball = place( - createShape(ellipsoid(95, 95, 95), [170, 110, 80], solid), - -95, - 250, - 120, - ); - const ring = place( - createShape(torus(92, 40), [245, 150, 40], solid), - 150, - 255, - 110, - ); - place( - createShape(ellipsoid(125, 70, 105), [175, 195, 220], solid), - 370, - 95, - -70, - ); - - // ── the effect: on the camera, so on the whole scene ───────────── - const dither = new DitherEffect(app.renderer as WebGLRenderer, { - levels: 6, - size: 3, - }); - const camera = app.viewport as Camera3d; - camera.addPostEffect(dither); - - // ── controls ───────────────────────────────────────────────────── - const label = { - font: "sans-serif", - fontSize: 26, - labelFillStyle: "#ffffff", - }; - world.addChild( - new UICheckbox(24, 20, { - ...label, - label: "dither", - checked: true, - onChange: (on) => { - // switched off rather than removed: it keeps its program - dither.enabled = on; - }, - }), - 100, - ); - [3, 6, 16].forEach((levels, i) => { - world.addChild( - new UICheckbox(24, 76 + i * 40, { - ...label, - group: "levels", - label: `${levels} levels`, - checked: levels === 6, - onChange: (on) => { - if (on) { - dither.setLevels(levels); - } - }, - }), - 100, - ); - }); - [2, 3, 5].forEach((size, i) => { - world.addChild( - new UICheckbox(24, 212 + i * 40, { - ...label, - group: "size", - label: `${size} px`, - checked: size === 3, - onChange: (on) => { - if (on) { - dither.setSize(size); - } - }, - }), - 100, - ); - }); - - // ── camera: a low view, drifting from side to side ─────────────── - camera.setClipPlanes(10, 8000); - const target = { x: 20, y: GROUND_Y - 140, z: 40 }; - let time = 0; - const tick = (dt: number) => { - time += dt / 1000; - const turn = Math.sin(time * 0.25) * 0.22; - camera.setPosition( - target.x + Math.sin(turn) * 730, - target.y - 150, - target.z - Math.cos(turn) * 730, - ); - camera.lookAt(target.x, target.y, target.z); - // the ring turns and the ball bobs, so their shading moves - ring.rotate((dt / 1000) * 0.6, UP); - ball.pos.y = GROUND_Y - 250 - Math.sin(time * 1.3) * 22; - }; - tick(0); - return tick; - }; - - class DitheringStage extends Stage { - #tick: ((dt: number) => void) | null = null; - - override onResetEvent(app: Application) { - this.#tick = buildScene(app); - } - - override update(dt: number) { - this.#tick?.(dt); - return super.update(dt); - } - - override onDestroyEvent() { - this.#tick = null; - } - } - - state.set(state.PLAY, new DitheringStage()); - state.change(state.PLAY); -}; - -export const ExampleDithering = createExampleComponent(createGame); diff --git a/packages/examples/src/main.tsx b/packages/examples/src/main.tsx index 06b31242c7..58a2ee0ef4 100644 --- a/packages/examples/src/main.tsx +++ b/packages/examples/src/main.tsx @@ -163,11 +163,6 @@ const ExampleGroundShadows = lazy(() => default: m.ExampleGroundShadows, })), ); -const ExampleDithering = lazy(() => - import("./examples/dithering/ExampleDithering").then((m) => ({ - default: m.ExampleDithering, - })), -); const ExampleToon = lazy(() => import("./examples/toon/ExampleToon").then((m) => ({ default: m.ExampleToon, @@ -560,14 +555,6 @@ const examples: { description: "A rigged blocky character (Kenney, CC0) loaded from GLB, using node-TRS animation over a rigid hierarchy.", }, - { - component: , - label: "Dithering", - path: "dithering", - sourceDir: "dithering", - description: - "A lit 3D scene drawn in a few color levels with an ordered dither, by one DitherEffect on the camera: the shading is patterned, the flat colors are not.", - }, { component: , label: "Toon Shading", diff --git a/packages/melonjs/CHANGELOG.md b/packages/melonjs/CHANGELOG.md index 2948883ea9..f5e6e743c9 100644 --- a/packages/melonjs/CHANGELOG.md +++ b/packages/melonjs/CHANGELOG.md @@ -6,7 +6,7 @@ - Transitions: a mask transition can be shaped like an image or a `Sprite`, close on the player with `center`, and fill the shape with `invert`, on `state.transition`, `MaskEffect` and `Trigger` ([#1399](https://github.com/melonjs/melonJS/issues/1399)) - Tiled: isometric maps are rendered by the GPU on WebGL and WebGPU, as orthogonal ones are, and so are staggered and hexagonal maps. Nothing to enable: a tile layer whose tiles come from one tileset takes it by itself, and any other is drawn as before, the console saying why ([#1897](https://github.com/melonjs/melonJS/issues/1897)) - Effects: `GradientMapEffect` recolors a sprite or a whole scene from its brightness, through a list of two to eight colors, the darkest pixels taking the first and the brightest the last: one sprite in a palette per team, a duotone, a night scene. With `smooth: false` each color takes a band of its own, a palette swap for art drawn in flat shades -- Effects: `DitherEffect` draws a scene in a few colors with an ordered dither between them, as early consoles did: on the camera, so many `levels` of each channel, so everything keeps its own hue, or a `palette` of two to sixteen colors of your own, in pixels `size` pixels wide. Only what falls between two colors is patterned (shading, soft shadows, gradients); a flat color that is one of them stays flat. See the new Dithering example +- Effects: `DitherEffect` draws a scene in a few colors with an ordered dither between them, as early consoles did: on the camera, so many `levels` of each channel, so everything keeps its own hue, or a `palette` of two to sixteen colors of your own, in pixels `size` pixels wide. Only what falls between two colors is patterned (shading, soft shadows, gradients); a flat color that is one of them stays flat ### Performance - Tiled: thanks to the GPU renderer, drawing an isometric tile layer takes about **90%** less of the main thread's time with 1200 tiles in view (0.68 to 0.07 ms a frame) and about **98%** less with 4000 (2.0 to 0.04 ms), and no longer grows with the number of tiles shown. Staggered and hexagonal maps gain the same diff --git a/packages/melonjs/skills/melonjs-sprites-and-animation/SKILL.md b/packages/melonjs/skills/melonjs-sprites-and-animation/SKILL.md index 72c0fb4dfb..121701dbc1 100644 --- a/packages/melonjs/skills/melonjs-sprites-and-animation/SKILL.md +++ b/packages/melonjs/skills/melonjs-sprites-and-animation/SKILL.md @@ -158,6 +158,19 @@ sprite.flicker(1000, function () { // blink for a second, then… }); ``` +**A tint multiplies, so it can only darken.** It cannot turn a red sprite blue, +or flash it white. For one sprite drawn in several palettes (a team colour, an +elite enemy, a frozen one) use a `GradientMapEffect`, which redraws it from its +brightness in the colours you list; for a white hit flash, a `FlashEffect`. Both +are in `melonjs-effects-and-shaders`. + +```js +// the same art as a second team +enemy.addPostEffect(new GradientMapEffect(app.renderer, { + colors: [[0.1, 0.05, 0.3], [0.3, 0.4, 0.9], [0.8, 0.9, 1]], +})); +``` + **`scale()` is multiplicative, not absolute.** Calling it every frame compounds. For absolute scaling reset first: @@ -223,6 +236,7 @@ Two consequences: | `this` is wrong in a `flicker(ms, callback)` callback, or a flicker started from it stops at once | before 20.13.0 the callback ran on an internal object and the flicker was stopped after it; now `this` is the sprite and the flicker has already ended | | sprites do not batch | more distinct textures in one frame than `renderer.maxTextures` | | nine-slice corners stretch anyway | `insetX`/`insetY` instead of `insetx`/`insety` | +| a tint will not turn the sprite the colour asked for, only a darker one | a tint multiplies the art's own colours: recolour with a `GradientMapEffect`, flash with a `FlashEffect` | ## Related skills diff --git a/packages/melonjs/skills/melonjs/SKILL.md b/packages/melonjs/skills/melonjs/SKILL.md index 80a00f1e7c..6bb6c20c48 100644 --- a/packages/melonjs/skills/melonjs/SKILL.md +++ b/packages/melonjs/skills/melonjs/SKILL.md @@ -39,7 +39,7 @@ dependencies. | [melonjs-math](../melonjs-math/SKILL.md) | Vectors and matrices: what mutates, what allocates, and interpolating with lerp, slerp, damp or moveTowards. | | [melonjs-tilemaps](../melonjs-tilemaps/SKILL.md) | Tiled maps — TMX/TSX loading, spawning entities from objects, collision layers, isometric maps, reading and changing tiles at run time (a tile layer as the game board). | | [melonjs-audio](../melonjs-audio/SKILL.md) | Sound effects, music, audio sprites, spatial audio, procedural tone and noise. | -| [melonjs-effects-and-shaders](../melonjs-effects-and-shaders/SKILL.md) | Post effects, custom GLSL/WGSL shaders, blend modes, colour grading, screen capture. | +| [melonjs-effects-and-shaders](../melonjs-effects-and-shaders/SKILL.md) | Post effects, custom GLSL/WGSL shaders, blend modes, colour grading, palette swaps, a dithered retro look, screen capture. | | [melonjs-3d](../melonjs-3d/SKILL.md) | Anything 3D or 2.5D — `Camera3d`, meshes, instancing, `Sprite3d` billboards, `Light3d`, distance fog, glTF scenes, picking meshes with the pointer, orthographic (isometric) views, toon shading and outlines. | | [melonjs-3d-assets](../melonjs-3d-assets/SKILL.md) | Loading glTF/GLB or OBJ models — materials, imported lights, instancing, and what is not supported. | | [melonjs-camera-and-drawing](../melonjs-camera-and-drawing/SKILL.md) | Camera follow, bounds, shake and fade, coordinate conversion, and immediate-mode shape drawing. | From 506c0ae1abd340cd8e1effee6cccbbfff662237c Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 00:58:43 +0000 Subject: [PATCH 39/51] Changelog: a shorter Chore section for 20.17.0 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- packages/melonjs/CHANGELOG.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/melonjs/CHANGELOG.md b/packages/melonjs/CHANGELOG.md index 65ee677550..f4ef54de43 100644 --- a/packages/melonjs/CHANGELOG.md +++ b/packages/melonjs/CHANGELOG.md @@ -29,9 +29,9 @@ - Skills: the deployment skill gave the engine's size as 250 KB; it is about 320 kB minified and gzipped ### Chore -- Dependencies: the 46 known vulnerabilities the security audit reported in the development tools are cleared (vite 8.3.8, vitest 4.1.12, serve 14.2.8, and overrides for what they depend on). None was in a dependency of a published package -- Lint: each package is linted on its own and Turborepo caches the result, so `pnpm lint` skips the packages that have not changed; and the engine is no longer linted a second time by its own build -- Tests: the engine's suite runs in about half the time (338 s to 177 s on a four-core machine), and its test pages no longer pile up temporary files and open file handles (up to 24 GB and 11,000 handles in one run before). In a one-shot run the browser keeps each module instead of asking the test server for it again in every spec file; watch mode releases what it gathers after each spec file; and the tile-layer benchmark runs only with `BENCH=1` +- Dependencies: update the development tools, clearing the 46 vulnerabilities reported by the security audit +- Lint: lint each package on its own and cache the result, so `pnpm lint` skips what has not changed +- CI: fix the test job losing its browser page at random, and run the test suite in about half the time ## [20.16.0] (melonJS 2) - _2026-11-17_ From f9a00ac35679227d8ed351f7b43182bae039bf71 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 01:32:19 +0000 Subject: [PATCH 40/51] Small fixes for 20.17.0: package contents, mask transition warning, examples - Package: publish CHANGELOG.md (the files entry matched nothing) and the license, copied in with the README; sideEffects names the published bundle instead of a source folder that is not shipped - Transitions: a mask transition whose sprite went with its level says so once when a later change closes a plain iris instead; the 'requires a shape' warning is printed once rather than on every change - README: the engine is about 320 KB minified and gzipped, not 250 - Claude plugin manifest: 20.17.0, as the release script requires - Examples: addPostEffect in place of the deprecated shader setter (five examples), an explicit z for the two HUDs that set a z property that does not exist, and the WebGPU example's comment about video.AUTO - Skills: the migration guide's list of stale example calls now matches the examples, and says why the platformer's overlapV is not the deprecated one Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- .claude-plugin/plugin.json | 2 +- README.md | 2 +- .../src/examples/aquarium/ExampleAquarium.tsx | 2 +- .../src/examples/heatHaze/ExampleHeatHaze.tsx | 2 +- .../src/examples/masking/ExampleMasking.tsx | 2 +- .../platformer-matter/entities/HUD.ts | 3 - .../src/examples/platformer-matter/play.ts | 6 +- .../src/examples/plinko-planck/createGame.ts | 10 +-- .../src/examples/pool-matter/createGame.ts | 10 +-- .../src/examples/pool-matter/entities/hud.ts | 3 - .../examples/src/examples/pool-matter/play.ts | 7 ++- .../src/examples/webgpu/ExampleWebGPU.tsx | 2 +- packages/melonjs/.gitignore | 1 + packages/melonjs/CHANGELOG.md | 4 +- packages/melonjs/package.json | 9 +-- .../skills/melonjs-20-migration/SKILL.md | 32 +++++----- .../skills/melonjs-renderables/SKILL.md | 10 +-- .../skills/melonjs-scenes-and-state/SKILL.md | 2 +- .../skills/melonjs-ui-and-text/SKILL.md | 7 +-- packages/melonjs/src/state/state.ts | 11 +++- .../tests/mask-transition-sprite.spec.js | 62 +++++++++++++++++-- 21 files changed, 130 insertions(+), 59 deletions(-) diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index f6d3c2bee4..0200da150a 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "melonjs", - "version": "20.16.0", + "version": "20.17.0", "description": "Build games with melonJS — 27 guides to the 2D, 2.5D and 3D HTML5 game engine, its conventions and idioms, so generated code runs the first time.", "author": { "name": "melonJS", diff --git a/README.md b/README.md index b283bf690c..da93279de6 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ melonJS 2 A modern & fully featured HTML5 game engine ------------------------------------------------------------------------------- -[melonJS](https://melonjs.org/) is an open-source 2D & 3D game engine designed for indie developers — perspective and orthogonal cameras, GPU-accelerated tilemap rendering, post-processing effects, custom shaders, 3D mesh support, polygon-accurate physics, modern Tiled workflows, and high performance. Runs on WebGPU, WebGL 2 or Canvas2D with automatic fallback. The whole engine is ~250 KB minzipped of vanilla JS/TS, with no dependencies and no toolchain lock-in. Built with modern class syntax and bundled with [esbuild](https://esbuild.github.io). +[melonJS](https://melonjs.org/) is an open-source 2D & 3D game engine designed for indie developers — perspective and orthogonal cameras, GPU-accelerated tilemap rendering, post-processing effects, custom shaders, 3D mesh support, polygon-accurate physics, modern Tiled workflows, and high performance. Runs on WebGPU, WebGL 2 or Canvas2D with automatic fallback. The whole engine is ~320 KB minzipped of vanilla JS/TS, with no dependencies and no toolchain lock-in. Built with modern class syntax and bundled with [esbuild](https://esbuild.github.io). [melonJS](https://melonjs.org/) is licensed under the [MIT License](LICENSE.md) and actively maintained by the team at AltByte in Singapore. diff --git a/packages/examples/src/examples/aquarium/ExampleAquarium.tsx b/packages/examples/src/examples/aquarium/ExampleAquarium.tsx index 56c95448e7..3da1ee2359 100644 --- a/packages/examples/src/examples/aquarium/ExampleAquarium.tsx +++ b/packages/examples/src/examples/aquarium/ExampleAquarium.tsx @@ -202,7 +202,7 @@ class WaterSurface extends Sprite { anchorPoint: { x: 0.5, y: 0.5 }, }); this.effect = effect; - this.shader = effect; + this.addPostEffect(effect); } draw(renderer: Parameters[0], viewport?: object) { diff --git a/packages/examples/src/examples/heatHaze/ExampleHeatHaze.tsx b/packages/examples/src/examples/heatHaze/ExampleHeatHaze.tsx index 50520373dd..8287d3e334 100644 --- a/packages/examples/src/examples/heatHaze/ExampleHeatHaze.tsx +++ b/packages/examples/src/examples/heatHaze/ExampleHeatHaze.tsx @@ -114,7 +114,7 @@ class HazeSurface extends Sprite { anchorPoint: { x: 0.5, y: 0.5 }, }); this.effect = effect; - this.shader = effect; + this.addPostEffect(effect); } draw(renderer: Parameters[0], viewport?: object) { diff --git a/packages/examples/src/examples/masking/ExampleMasking.tsx b/packages/examples/src/examples/masking/ExampleMasking.tsx index 5986a34a07..eff1433877 100644 --- a/packages/examples/src/examples/masking/ExampleMasking.tsx +++ b/packages/examples/src/examples/masking/ExampleMasking.tsx @@ -34,7 +34,7 @@ const createGame = async () => { loader.load({ name: "background", type: "image", src: bgImage }, () => { // apply subtle vignette post-process effect on the camera - game.viewport.shader = new VignetteEffect(game.renderer); + game.viewport.addPostEffect(new VignetteEffect(game.renderer)); const bg_sprite1 = new Sprite( game.viewport.width / 2, game.viewport.height / 2, diff --git a/packages/examples/src/examples/platformer-matter/entities/HUD.ts b/packages/examples/src/examples/platformer-matter/entities/HUD.ts index 86ff5e9b02..0d8a22fd0b 100644 --- a/packages/examples/src/examples/platformer-matter/entities/HUD.ts +++ b/packages/examples/src/examples/platformer-matter/entities/HUD.ts @@ -165,9 +165,6 @@ class UIContainer extends Container { // Use screen coordinates this.floating = true; - // draw the HUD on top of everything else (highest z renders last) - this.z = Number.POSITIVE_INFINITY; - // give a name this.name = "HUD"; diff --git a/packages/examples/src/examples/platformer-matter/play.ts b/packages/examples/src/examples/platformer-matter/play.ts index 19d12b0cad..1f0708c7d6 100644 --- a/packages/examples/src/examples/platformer-matter/play.ts +++ b/packages/examples/src/examples/platformer-matter/play.ts @@ -22,6 +22,9 @@ import { gameState } from "./gameState"; // identity color matrix used to reset the viewport between state changes const IDENTITY_COLOR_MATRIX = new ColorMatrix(); +/** draw order for the screen-space overlays — above every level layer */ +const HUD_Z = 100; + export class PlayScreen extends Stage { private HUD?: UIContainer; private vignette?: ShaderEffect; @@ -45,7 +48,8 @@ export class PlayScreen extends Stage { if (typeof this.HUD === "undefined") { this.HUD = new UIContainer(); } - app.world.addChild(this.HUD); + // explicit z: the HUD draws over the level + app.world.addChild(this.HUD, HUD_Z); // the touch controls, also shown on a desktop with the debug panel open const gamepad = plugin.cache.gamepad as GamepadPlugin | undefined; diff --git a/packages/examples/src/examples/plinko-planck/createGame.ts b/packages/examples/src/examples/plinko-planck/createGame.ts index 68615a04c0..f3f7f562a9 100644 --- a/packages/examples/src/examples/plinko-planck/createGame.ts +++ b/packages/examples/src/examples/plinko-planck/createGame.ts @@ -64,10 +64,12 @@ export const createGame = async () => { // "old arcade screen" vibe; subtle vignette to focus the eye // on the play field. Kept light — anything higher than ~0.1 // noticeably dims the neon palette below it. - _app.viewport.shader = new ScanlineEffect(game.renderer, { - opacity: 0.09, - vignetteStrength: 0.18, - }); + _app.viewport.addPostEffect( + new ScanlineEffect(game.renderer, { + opacity: 0.09, + vignetteStrength: 0.18, + }), + ); // register the debug plugin — press 'S' in-game to toggle the panel // (collision bodies, FPS, draw-call counts, etc.). Useful when diff --git a/packages/examples/src/examples/pool-matter/createGame.ts b/packages/examples/src/examples/pool-matter/createGame.ts index 3095d389f7..095e09d543 100644 --- a/packages/examples/src/examples/pool-matter/createGame.ts +++ b/packages/examples/src/examples/pool-matter/createGame.ts @@ -56,10 +56,12 @@ export const createGame = async () => { // renderable and resolution-independent. `strength=0.18` is subtle // enough that the corner pockets stay readable; `size=22` keeps the // dark falloff confined to the outer ~25% of the viewport. - _app.viewport.shader = new VignetteEffect(game.renderer, { - strength: 0.18, - size: 22.0, - }); + _app.viewport.addPostEffect( + new VignetteEffect(game.renderer, { + strength: 0.18, + size: 22.0, + }), + ); // register the debug plugin — press 'S' in-game to toggle the panel // (collision bodies, FPS, draw-call counts, etc.) diff --git a/packages/examples/src/examples/pool-matter/entities/hud.ts b/packages/examples/src/examples/pool-matter/entities/hud.ts index b04688f764..eeeaabbfc6 100644 --- a/packages/examples/src/examples/pool-matter/entities/hud.ts +++ b/packages/examples/src/examples/pool-matter/entities/hud.ts @@ -62,9 +62,6 @@ export class HUDContainer extends Container { this.isPersistent = true; this.floating = true; this.name = "HUD"; - // `Renderable.z` is the typed accessor for the underlying - // ObservableVector3d.z (declared as Vector2d in some signatures). - this.z = Number.POSITIVE_INFINITY; // Y=16 keeps the text in the brown rail strip above the felt — the // previous Y=50 placed it level with the corner pockets, where the // numbers overlapped the pocket "holes" on the table sprite. diff --git a/packages/examples/src/examples/pool-matter/play.ts b/packages/examples/src/examples/pool-matter/play.ts index fdc9008e10..158d400edc 100644 --- a/packages/examples/src/examples/pool-matter/play.ts +++ b/packages/examples/src/examples/pool-matter/play.ts @@ -12,6 +12,9 @@ import { buildPockets } from "./entities/pocket"; import { buildTable } from "./entities/table"; import { gameState } from "./gameState"; +/** draw order of the HUD — above the table and every ball */ +const HUD_Z = 100; + /** * Build the 15-ball triangle rack. Apex points toward the cue (left * side of the table); foot row is on the right. The 8-ball sits at @@ -76,7 +79,7 @@ export class PlayScreen extends Stage { app.world.addChild(b); } app.world.addChild(new CueBall(CUE_SPAWN_X, CUE_SPAWN_Y)); - // HUD on top - app.world.addChild(new HUDContainer()); + // HUD on top: an explicit z, above the table and every ball + app.world.addChild(new HUDContainer(), HUD_Z); } } diff --git a/packages/examples/src/examples/webgpu/ExampleWebGPU.tsx b/packages/examples/src/examples/webgpu/ExampleWebGPU.tsx index 33b81d07c8..9e7779d17a 100644 --- a/packages/examples/src/examples/webgpu/ExampleWebGPU.tsx +++ b/packages/examples/src/examples/webgpu/ExampleWebGPU.tsx @@ -168,7 +168,7 @@ export const ExampleWebGPU = createExampleComponent(async () => { const app = new Application(1024, 576, { parent: "screen", scale: "auto", - // opt-in only — `video.AUTO` never selects the WebGPU backend + // AUTO tries WebGPU first, then WebGL 2, then Canvas renderer: video.AUTO, backgroundColor: "#10212f", }); diff --git a/packages/melonjs/.gitignore b/packages/melonjs/.gitignore index 50a61f6541..530d632868 100644 --- a/packages/melonjs/.gitignore +++ b/packages/melonjs/.gitignore @@ -1,3 +1,4 @@ # copied from repo root during dist/publish README.md +LICENSE.md .docs.css diff --git a/packages/melonjs/CHANGELOG.md b/packages/melonjs/CHANGELOG.md index f4ef54de43..0310732f2a 100644 --- a/packages/melonjs/CHANGELOG.md +++ b/packages/melonjs/CHANGELOG.md @@ -26,7 +26,9 @@ - Text: a stroked multi-line label with `textBaseline: "hanging"` keeps the top of its outline on macOS, where Helvetica's hanging metrics made the ink padding exactly as tall as the ink, shearing its first row off the canvas ([#1870](https://github.com/melonjs/melonJS/issues/1870)) - glTF: a model compressed with Draco or meshopt, which the loader cannot decode, says so in the console, naming the extension, instead of failing on an accessor error that did not mention it - Physics: a method of the built-in adapter (`setVelocity`, `applyForce`, `setStatic` and the like) called on a renderable with no body says so, `this renderable has no built-in body`, where it failed on a property of `undefined`; and a raycast passes over an object whose body is not one of the adapter's, where it threw -- Skills: the deployment skill gave the engine's size as 250 KB; it is about 320 kB minified and gzipped +- Transitions: a mask transition shaped like a sprite of the level says so in the console, once, when a later change finds that sprite gone with its level and closes a plain iris instead; nothing was said. A mask transition given no shape also says so once, not on every change +- Package: the npm package includes `CHANGELOG.md` and the license, which were left out, and its `sideEffects` field names the published bundle rather than a source folder that is not published +- Skills and README: the engine's size was given as 250 KB; it is about 320 kB minified and gzipped ### Chore - Dependencies: update the development tools, clearing the 46 vulnerabilities reported by the security audit diff --git a/packages/melonjs/package.json b/packages/melonjs/package.json index c38c4fc497..66472d80ec 100644 --- a/packages/melonjs/package.json +++ b/packages/melonjs/package.json @@ -5,7 +5,7 @@ "homepage": "https://www.melonjs.org/", "type": "module", "sideEffects": [ - "./src/polyfill/**" + "./build/index.js" ], "keywords": [ "game-engine", @@ -51,7 +51,8 @@ "build", "skills", "README.md", - "CHANGELOG", + "LICENSE.md", + "CHANGELOG.md", "package.json" ], "devDependencies": { @@ -74,8 +75,8 @@ "build:watch": "tsx scripts/build.js watch", "lint": "eslint .", "build": "tsx scripts/build.js && pnpm types", - "dist": "pnpm clean && pnpm lint && pnpm vitest run && pnpm build && pnpm doc && cp ../../README.md .", - "dist:publish": "pnpm clean && pnpm lint && pnpm build && pnpm doc && cp ../../README.md .", + "dist": "pnpm clean && pnpm lint && pnpm vitest run && pnpm build && pnpm doc && cp ../../README.md ../../LICENSE.md .", + "dist:publish": "pnpm clean && pnpm lint && pnpm build && pnpm doc && cp ../../README.md ../../LICENSE.md .", "doc": "tsx scripts/check-doc-readme.ts && pnpm doc:css && typedoc && tsx scripts/generate-llms-txt.ts", "doc:watch": "typedoc --watch --skipErrorChecking --preserveWatchOutput --logLevel Error", "serve": "serve docs", diff --git a/packages/melonjs/skills/melonjs-20-migration/SKILL.md b/packages/melonjs/skills/melonjs-20-migration/SKILL.md index 1caa0b7a74..4fdb28f58e 100644 --- a/packages/melonjs/skills/melonjs-20-migration/SKILL.md +++ b/packages/melonjs/skills/melonjs-20-migration/SKILL.md @@ -169,24 +169,26 @@ Code written against an early 20.x release can still trip on these: (20.11, `autoSort` on by default). Turn `autoSort` off to keep an order set by hand. A `"z"` sort is unchanged. -## The shipped examples are not all current +## What the shipped examples still show of the old API The examples in this repository are the best reference for how melonJS is -assembled, but a few contain stale comments or legacy calls. Do not learn these -from them: - -- `webgpu/` has a comment claiming *"`video.AUTO` never selects the WebGPU - backend"*. That is pre-20 leftover — AUTO tries WebGPU **first**. The code is - right; the comment is wrong. -- Several examples assign `viewport.shader = …` / `sprite.shader = …`, which is - deprecated. `addPostEffect()` is current. -- Three files (in `platformer-matter/` and `pool-matter/`) set - `this.z = Number.POSITIVE_INFINITY` on a HUD or a virtual joypad. That - property does not exist; they draw on top only because they are added last. -- `platformer/entities/player.ts` and `enemies.ts` read `response.overlapV`, - the deprecated field. Use `response.depth` / `response.normal`. +assembled. Two things in them are easy to misread: + +- `platformer/entities/player.ts` and `enemies.ts` read and change + `response.overlapV` in a legacy `onCollision`. On the built-in world that is + not the deprecated field: the legacy handler gets the solver's own response, + which has no `normal` or `depth`, and changing `overlapV` there is how a + one-way platform or a slope changes the push-out. In a new handler + (`onCollisionStart` / `onCollisionActive`), and on every adapter, read + `response.depth` / `response.normal`. - Particle speeds tuned before 20.2 look wrong now: the particle transform fix - changed how far a burst travels, and emitters were retuned upward to match. + changed how far a burst travels, and the examples' emitters were retuned + upward to match. An emitter copied from an older version of an example needs + the same. + +Older copies of the examples (before 20.17) also assigned `viewport.shader = …` +/ `sprite.shader = …` and set `this.z = Number.POSITIVE_INFINITY` on a HUD. +Neither is current: use `addPostEffect()`, and `addChild(hud, z)`. ## Checklist when code "should work" but doesn't diff --git a/packages/melonjs/skills/melonjs-renderables/SKILL.md b/packages/melonjs/skills/melonjs-renderables/SKILL.md index a47223037a..cfd062b272 100644 --- a/packages/melonjs/skills/melonjs-renderables/SKILL.md +++ b/packages/melonjs/skills/melonjs-renderables/SKILL.md @@ -93,11 +93,11 @@ world.addChild(sprite, 10); // ✓ the only reliable form 1. **`renderable.z` does not exist.** There is no `z` accessor anywhere on `Renderable` (nor on `Rect`/`Polygon` above it) — only `depth`, which proxies `pos.z`, and the container's default `sortOn: "z"` comparator reads `pos.z`. - Writing `sprite.z = 100` creates an inert property that nothing reads. - Several shipped examples still contain `this.z = Number.POSITIVE_INFINITY`; - those HUDs draw on top only because they happen to be added last. (A `z` key - in a `Sprite`/`ImageLayer` *settings* object is a different thing and is real - — it assigns `pos.z` in the constructor — but trap 2 then overwrites it.) + Writing `sprite.z = 100` creates an inert property that nothing reads: a + HUD that sets `this.z = Number.POSITIVE_INFINITY` draws on top only if it + happens to be added last. (A `z` key in a `Sprite`/`ImageLayer` *settings* + object is a different thing and is real — it assigns `pos.z` in the + constructor — but trap 2 then overwrites it.) 2. **Setting `depth` *before* `addChild` is overwritten.** With `autoDepth` on (the default), `addChild` without an explicit `z` assigns `child.pos.z = children.length` after the push, discarding whatever you set. diff --git a/packages/melonjs/skills/melonjs-scenes-and-state/SKILL.md b/packages/melonjs/skills/melonjs-scenes-and-state/SKILL.md index 66f387f54d..beeb2e6a1a 100644 --- a/packages/melonjs/skills/melonjs-scenes-and-state/SKILL.md +++ b/packages/melonjs/skills/melonjs-scenes-and-state/SKILL.md @@ -611,7 +611,7 @@ When `setStorage()` switches storage: | `Undefined Stage for state 'N'` thrown | no `state.set` for that id first | | `state.change(state.PLAY)` from `PLAY` does nothing ("Retry" ignored) | a change to the current state is a no-op — `state.reload()` (20.16), `level.reload()` for the map alone | | a mask transition closes on the middle of the screen, not on the player | pass `{ center: player }` as the fifth argument; on a `Trigger`, `center: "touching"` | -| the first mask transition is the player's shape, later ones a plain iris on the middle of the screen | a sprite that is part of the level is destroyed by the change, so `state.transition` lets it go after one transition: set it again, with this level's player, right before each `state.change`. A sprite kept outside any level (or a persistent one) is set once and shapes every change | +| the first mask transition is the player's shape, later ones a plain iris on the middle of the screen, the console saying `the sprite shaping the mask transition went with its level` (20.17) | a sprite that is part of the level is destroyed by the change, so `state.transition` lets it go after one transition: set it again, with this level's player, right before each `state.change`. A sprite kept outside any level (or a persistent one) is set once and shapes every change | | a level change through a `Trigger` ignores `state.transition` | it is a level change, not a state change: set `color` and `duration` (and `transition`) on the trigger | | the game stops updating for good after one very slow update, such as a heavy first frame (20.12 and 20.13) | the loop could no longer save enough time to step the world: update | | the game resumes under its own pause menu after a tab switch (before 20.9) | focus undid any pause; update, only the blur pause is undone | diff --git a/packages/melonjs/skills/melonjs-ui-and-text/SKILL.md b/packages/melonjs/skills/melonjs-ui-and-text/SKILL.md index ef6fc58b14..fb3a7cc150 100644 --- a/packages/melonjs/skills/melonjs-ui-and-text/SKILL.md +++ b/packages/melonjs/skills/melonjs-ui-and-text/SKILL.md @@ -462,10 +462,9 @@ Three things matter here: - **Only the parent container needs `floating`.** `addChild` forces `child.floating = false` under a floating parent, and the container applies one projection swap for the whole subtree. -- **Pass an explicit z.** `this.z = Number.POSITIVE_INFINITY` appears in several - shipped examples and does nothing — `renderable.z` is not a real property. The - real accessor is `depth` (an alias for `pos.z`); `addChild(child, z)` sets it - for you. +- **Pass an explicit z.** `this.z = Number.POSITIVE_INFINITY` does nothing — + `renderable.z` is not a real property. The real accessor is `depth` (an + alias for `pos.z`); `addChild(child, z)` sets it for you. ### Bars and gauges: `ProgressBar` diff --git a/packages/melonjs/src/state/state.ts b/packages/melonjs/src/state/state.ts index 5280ec701b..de6a231139 100644 --- a/packages/melonjs/src/state/state.ts +++ b/packages/melonjs/src/state/state.ts @@ -9,6 +9,7 @@ import MaskEffect, { type MaskShape, } from "../camera/effects/mask_effect.ts"; import PixelateTransitionEffect from "../camera/effects/pixelate_transition_effect.ts"; +import { warnOnce } from "../lang/console.js"; import DefaultLoadingScreen from "./../loader/loadingscreen.js"; import type Renderable from "./../renderable/renderable.js"; import Stage from "./../state/stage.ts"; @@ -961,12 +962,20 @@ const state = { } case "mask": { if (!_transitionConfig.shape && !_transitionConfig.released) { - console.warn( + warnOnce( "melonJS: mask transition requires a shape, falling back to direct switch", ); onComplete(); break; } + if (!_transitionConfig.shape) { + // said here and not where the sprite is let go: a + // game that sets it again before each change is + // doing the right thing, and never gets this far + warnOnce( + "melonJS: the sprite shaping the mask transition went with its level, an iris is used instead: set state.transition() again, with a sprite of the new level, before each state.change()", + ); + } const maskEffect = new MaskEffect(_app.viewport, { shape: _transitionConfig.shape, color: _transitionConfig.color, diff --git a/packages/melonjs/tests/mask-transition-sprite.spec.js b/packages/melonjs/tests/mask-transition-sprite.spec.js index b8fd3c04c2..dd4ce58b76 100644 --- a/packages/melonjs/tests/mask-transition-sprite.spec.js +++ b/packages/melonjs/tests/mask-transition-sprite.spec.js @@ -20,8 +20,12 @@ import { TextureAtlas, video, } from "../src/index.js"; +import { resetWarnOnce } from "../src/lang/console.js"; import { readPixel } from "./helpers/pixels.js"; +/** what the console says, once, when a change finds its sprite gone with a level */ +const LET_GO = /went with its level, an iris is used instead/; + /** * `state.transition("mask", …, sprite, { center: sprite })` (#1399): the * hide closes on the player with the player's own silhouette, and the reveal @@ -235,7 +239,8 @@ describe("a mask transition shaped like, and closing on, a sprite", () => { // The player it was given is gone: a later change does not read it // again (destroyed, or recycled into something else), but closes an - // iris on the centre of the screen, with nothing to warn about + // iris on the centre of the screen, and says so + resetWarnOnce(); const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); state.setTransition(start, true); state.change(start); @@ -243,7 +248,8 @@ describe("a mask transition shaped like, and closing on, a sprite", () => { expect(again._maskShape?.type).toBe("Ellipse"); expect(again.center).toBeUndefined(); expect(again.invert).toBe(true); - expect(warn).not.toHaveBeenCalled(); + expect(warn).toHaveBeenCalledTimes(1); + expect(warn.mock.calls[0][0]).toMatch(LET_GO); warn.mockRestore(); await runUntil(() => { expect(state.isCurrent(start)).toBe(true); @@ -368,12 +374,19 @@ describe("a mask transition shaped like, and closing on, a sprite", () => { }); }); beforeEach(() => { + // each test hears what a page hears the first time + resetWarnOnce(); warn = vi.spyOn(console, "warn").mockImplementation(() => {}); }); afterEach(async () => { warn.mockRestore(); await settle(); }); + /** the one thing said: the sprite went with its level */ + const expectLetGoWarning = () => { + expect(warn).toHaveBeenCalledTimes(1); + expect(warn.mock.calls[0][0]).toMatch(LET_GO); + }; it("a sprite the game keeps for itself, never in a level, shapes every change", async () => { // what `atlas.createSpriteFromName()` gives, set once at startup @@ -451,10 +464,12 @@ describe("a mask transition shaped like, and closing on, a sprite", () => { // the change destroyed it expect(inRoom.offset).toBeUndefined(); + // nothing is said while it is let go, only once a change misses it + expect(warn).not.toHaveBeenCalled(); const second = change(); expect(isIris(second)).toBe(true); expect(second.center).toBeUndefined(); - expect(warn).not.toHaveBeenCalled(); + expectLetGoWarning(); }); it("a persistent sprite inside a container of the level is let go with it", async () => { @@ -475,10 +490,12 @@ describe("a mask transition shaped like, and closing on, a sprite", () => { await settle(); expect(room.ancestor).toBeUndefined(); + // nothing is said while it is let go, only once a change misses it + expect(warn).not.toHaveBeenCalled(); const second = change(); expect(isIris(second)).toBe(true); expect(second.center).toBeUndefined(); - expect(warn).not.toHaveBeenCalled(); + expectLetGoWarning(); }); it("kept while it is the game's own, let go by the change that finds it in a level", async () => { @@ -494,9 +511,10 @@ describe("a mask transition shaped like, and closing on, a sprite", () => { expect(change()._silhouette).toBeDefined(); await settle(); expect(sprite.offset).toBeUndefined(); + expect(warn).not.toHaveBeenCalled(); expect(isIris(change())).toBe(true); - expect(warn).not.toHaveBeenCalled(); + expectLetGoWarning(); }); it("a sprite in a container that is in no world is kept", async () => { @@ -524,6 +542,40 @@ describe("a mask transition shaped like, and closing on, a sprite", () => { expect(isIris(change())).toBe(true); }); + it("a level's sprite set again before each change is never warned about", async () => { + for (let i = 0; i < 3; i++) { + const player = new Sprite(100, 100, { image: leftHalf() }); + app.world.addChild(player); + state.transition("mask", "#000", DURATION, player); + expect(change()._silhouette, `change ${i + 1}`).toBeDefined(); + await settle(); + } + expect(warn).not.toHaveBeenCalled(); + }); + + it("the sprite gone with its level is said once, however many changes follow", async () => { + const player = new Sprite(100, 100, { image: leftHalf() }); + app.world.addChild(player); + state.transition("mask", "#000", DURATION, player); + expect(change()._silhouette).toBeDefined(); + await settle(); + for (let i = 0; i < 3; i++) { + expect(isIris(change()), `change ${i + 2}`).toBe(true); + await settle(); + } + expectLetGoWarning(); + }); + + it("a mask transition given no shape says so once, and switches directly", async () => { + state.transition("mask", "#000", DURATION); + for (let i = 0; i < 3; i++) { + expect(change(), `change ${i + 1}`).toBeUndefined(); + await settle(); + } + expect(warn).toHaveBeenCalledTimes(1); + expect(warn.mock.calls[0][0]).toMatch(/requires a shape/); + }); + it("setting another transition forgets a kept sprite", async () => { const sprite = atlasSprite(); state.transition("mask", "#000", DURATION, sprite); From a44c618cb7d61d92fc6ac5d51729c763aa58a634 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 02:40:51 +0000 Subject: [PATCH 41/51] Fix rotated atlas frames and black frames after a capture; examples off deprecated APIs Engine - Sprite: an atlas frame the packer stored rotated was turned back about the world's origin rather than the frame's own corner, so it was drawn off screen unless the sprite stood at (0, 0), as the renderable of an Entity does. NineSliceSprite had the same fault and also stretched a rotated frame along the wrong axes. Both are drawn as the same art stored plainly is, on WebGL and Canvas (32 new tests; one existing test pinned the old nine-slice layout and is corrected) - WebGL: a frame that captured an anti-aliased canvas and then drew over it was sometimes shown black by Chromium, more often on a slow frame. The renderer now closes such a frame with one more read of the canvas, a single pixel, which is what was measured to cure it (Aquarium example, recorded on the software renderer: 114 black frames in 125 before, none in 375 after; flush and finish after the capture do not help) - package.json: sideEffects keeps the source polyfill entry, which the engine's own build reads, beside the published bundle. With the bundle alone the build dropped the polyfills Examples - Aseprite and Texture Packer draw a Sprite instead of the deprecated Entity; the benchmark uses the application's fullscreen methods - README: ~300 KB Skills and changelog updated to match. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- README.md | 2 +- .../src/examples/aseprite/ExampleAseprite.tsx | 6 +- .../src/examples/aseprite/entities.ts | 35 +-- .../examples/src/examples/aseprite/play.ts | 6 +- .../examples/benchmark/ExampleBenchmark.tsx | 7 +- .../texturePacker/ExampleTexturePacker.tsx | 42 +-- packages/melonjs/CHANGELOG.md | 6 +- packages/melonjs/package.json | 1 + .../skills/melonjs-20-migration/SKILL.md | 6 +- .../melonjs-effects-and-shaders/SKILL.md | 1 + .../melonjs-sprites-and-animation/SKILL.md | 1 + .../melonjs/src/application/application.ts | 1 + .../melonjs/src/renderable/nineslicesprite.js | 33 ++- packages/melonjs/src/renderable/sprite.js | 7 +- packages/melonjs/src/video/renderer.js | 7 + .../melonjs/src/video/webgl/webgl_renderer.js | 70 +++++ .../melonjs/tests/nineslicesprite.spec.js | 11 +- .../tests/sprite-rotated-frame.spec.js | 258 ++++++++++++++++++ .../tests/toframetexture-antialias.spec.js | 205 ++++++++++++++ 19 files changed, 635 insertions(+), 70 deletions(-) create mode 100644 packages/melonjs/tests/sprite-rotated-frame.spec.js create mode 100644 packages/melonjs/tests/toframetexture-antialias.spec.js diff --git a/README.md b/README.md index da93279de6..9e67979690 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ melonJS 2 A modern & fully featured HTML5 game engine ------------------------------------------------------------------------------- -[melonJS](https://melonjs.org/) is an open-source 2D & 3D game engine designed for indie developers — perspective and orthogonal cameras, GPU-accelerated tilemap rendering, post-processing effects, custom shaders, 3D mesh support, polygon-accurate physics, modern Tiled workflows, and high performance. Runs on WebGPU, WebGL 2 or Canvas2D with automatic fallback. The whole engine is ~320 KB minzipped of vanilla JS/TS, with no dependencies and no toolchain lock-in. Built with modern class syntax and bundled with [esbuild](https://esbuild.github.io). +[melonJS](https://melonjs.org/) is an open-source 2D & 3D game engine designed for indie developers — perspective and orthogonal cameras, GPU-accelerated tilemap rendering, post-processing effects, custom shaders, 3D mesh support, polygon-accurate physics, modern Tiled workflows, and high performance. Runs on WebGPU, WebGL 2 or Canvas2D with automatic fallback. The whole engine is ~300 KB minzipped of vanilla JS/TS, with no dependencies and no toolchain lock-in. Built with modern class syntax and bundled with [esbuild](https://esbuild.github.io). [melonJS](https://melonjs.org/) is licensed under the [MIT License](LICENSE.md) and actively maintained by the team at AltByte in Singapore. diff --git a/packages/examples/src/examples/aseprite/ExampleAseprite.tsx b/packages/examples/src/examples/aseprite/ExampleAseprite.tsx index 5cc36649a0..f223d3a1d3 100644 --- a/packages/examples/src/examples/aseprite/ExampleAseprite.tsx +++ b/packages/examples/src/examples/aseprite/ExampleAseprite.tsx @@ -3,7 +3,6 @@ * Copyright (C) 2011 - 2026 AltByte Pte Ltd — MIT License. * See `packages/examples/LICENSE.md` for full license + asset credits. */ -import type * as me from "melonjs"; import { createExampleComponent } from "../utils"; import { createGame } from "./game"; import { paladin } from "./play"; @@ -42,10 +41,7 @@ export const ExampleAseprite = () => { borderRadius: 4, }} onChange={(event) => { - // eslint-disable-next-line @typescript-eslint/no-unsafe-call - (paladin.renderable as me.Sprite).setCurrentAnimation( - event.target.value, - ); + paladin.setCurrentAnimation(event.target.value); }} > diff --git a/packages/examples/src/examples/aseprite/entities.ts b/packages/examples/src/examples/aseprite/entities.ts index c03d0717ce..7c099b33c0 100644 --- a/packages/examples/src/examples/aseprite/entities.ts +++ b/packages/examples/src/examples/aseprite/entities.ts @@ -5,25 +5,20 @@ */ import * as me from "melonjs"; -export class Paladin extends me.Entity { - constructor() { - // call the super constructor - super(160, 250, { width: 100, height: 100 }); - - // just manually change the guy position - this.body.setStatic(); - - const textureAtlas = new me.TextureAtlas( - me.loader.getJSON("paladin"), - me.loader.getImage("paladin"), - ); - - // create a new sprite with all animations from the paladin atlas - this.renderable = textureAtlas.createAnimationFromName(); - // eslint-disable-next-line @typescript-eslint/no-unsafe-call - (this.renderable as me.Sprite).setCurrentAnimation("run front"); +/** + * The paladin: one sprite holding every animation of its Aseprite atlas. + */ +export function createPaladin(): me.Sprite { + const textureAtlas = new me.TextureAtlas( + me.loader.getJSON("paladin"), + me.loader.getImage("paladin"), + ); - this.anchorPoint.set(0.5, 0.0); - this.renderable.scale(4); - } + // with no list of names: every frame of the atlas, and an animation for + // each tag set in Aseprite + const paladin = textureAtlas.createAnimationFromName(); + paladin.setCurrentAnimation("run front"); + paladin.scale(4); + paladin.pos.set(210, 250); + return paladin; } diff --git a/packages/examples/src/examples/aseprite/play.ts b/packages/examples/src/examples/aseprite/play.ts index e1fc4efe66..ec4baab68f 100644 --- a/packages/examples/src/examples/aseprite/play.ts +++ b/packages/examples/src/examples/aseprite/play.ts @@ -4,13 +4,13 @@ * See `packages/examples/LICENSE.md` for full license + asset credits. */ import * as me from "melonjs"; -import { Paladin } from "./entities"; +import { createPaladin } from "./entities"; -export let paladin: me.Entity; +export let paladin: me.Sprite; export class PlayScreen extends me.Stage { override onResetEvent() { - paladin = new Paladin(); + paladin = createPaladin(); me.game.world.addChild(paladin, 2); } } diff --git a/packages/examples/src/examples/benchmark/ExampleBenchmark.tsx b/packages/examples/src/examples/benchmark/ExampleBenchmark.tsx index ee008dadd9..0d7424b184 100644 --- a/packages/examples/src/examples/benchmark/ExampleBenchmark.tsx +++ b/packages/examples/src/examples/benchmark/ExampleBenchmark.tsx @@ -6,7 +6,6 @@ import { DebugPanelPlugin } from "@melonjs/debug-plugin"; import { Application, - device, event, game, input, @@ -71,10 +70,10 @@ const createGame = async () => { event.on(event.KEYDOWN, (_, keyCode) => { // toggle fullscreen on/off if (keyCode === input.KEY.F) { - if (!device.isFullscreen()) { - device.requestFullscreen(); + if (!game.isFullscreen()) { + game.requestFullscreen(); } else { - device.exitFullscreen(); + game.exitFullscreen(); } } diff --git a/packages/examples/src/examples/texturePacker/ExampleTexturePacker.tsx b/packages/examples/src/examples/texturePacker/ExampleTexturePacker.tsx index 9494520151..c982c4d6a3 100644 --- a/packages/examples/src/examples/texturePacker/ExampleTexturePacker.tsx +++ b/packages/examples/src/examples/texturePacker/ExampleTexturePacker.tsx @@ -6,11 +6,10 @@ import { DebugPanelPlugin } from "@melonjs/debug-plugin"; import { Application, - Entity, game, loader, plugin, - type Sprite, + Sprite, Stage, state, TextureAtlas, @@ -21,26 +20,33 @@ const base = `${import.meta.env.BASE_URL}assets/texturePacker/img/`; let texture: TextureAtlas; -class CapGuyEntity extends Entity { +/** the walking character: a sprite animated from eight frames of the atlas */ +class CapGuy extends Sprite { constructor() { - super(0, 50, { width: 100, height: 300 }); - this.body.setStatic(); - this.renderable = texture.createAnimationFromName([ - "capguy/walk/0001", - "capguy/walk/0002", - "capguy/walk/0003", - "capguy/walk/0004", - "capguy/walk/0005", - "capguy/walk/0006", - "capguy/walk/0007", - "capguy/walk/0008", - ]); + super( + 50, + 200, + texture.getAnimationSettings([ + "capguy/walk/0001", + "capguy/walk/0002", + "capguy/walk/0003", + "capguy/walk/0004", + "capguy/walk/0005", + "capguy/walk/0006", + "capguy/walk/0007", + "capguy/walk/0008", + ]), + ); + // it walks off one side and back in from the other: keep it + // updating while it is out of view, or it would stay there + this.alwaysUpdate = true; } override update(dt: number) { this.pos.x += 0.3 * dt; - if (this.pos.x >= game.viewport.width) { - this.pos.x = 0; + // its position is its centre: gone once half its width past the edge + if (this.pos.x - this.width / 2 >= game.viewport.width) { + this.pos.x = -this.width / 2; } super.update(dt); return true; @@ -55,7 +61,7 @@ class PlayScreen extends Stage { const background = texture.createSpriteFromName("background") as Sprite; background.pos.set(w / 2, h / 2, 1); game.world.addChild(background, 1); - game.world.addChild(new CapGuyEntity(), 2); + game.world.addChild(new CapGuy(), 2); } } diff --git a/packages/melonjs/CHANGELOG.md b/packages/melonjs/CHANGELOG.md index 0310732f2a..f266fe42fd 100644 --- a/packages/melonjs/CHANGELOG.md +++ b/packages/melonjs/CHANGELOG.md @@ -26,9 +26,11 @@ - Text: a stroked multi-line label with `textBaseline: "hanging"` keeps the top of its outline on macOS, where Helvetica's hanging metrics made the ink padding exactly as tall as the ink, shearing its first row off the canvas ([#1870](https://github.com/melonjs/melonJS/issues/1870)) - glTF: a model compressed with Draco or meshopt, which the loader cannot decode, says so in the console, naming the extension, instead of failing on an accessor error that did not mention it - Physics: a method of the built-in adapter (`setVelocity`, `applyForce`, `setStatic` and the like) called on a renderable with no body says so, `this renderable has no built-in body`, where it failed on a property of `undefined`; and a raycast passes over an object whose body is not one of the adapter's, where it threw +- Sprites: an atlas frame the packer stored rotated is drawn where the sprite is. It was drawn off the screen unless the sprite stood at (0, 0), so an animation with such frames blinked, on every renderer. A `NineSliceSprite` made from a rotated frame is stretched along the right axes, with its corners the right way round +- WebGL: with `antiAlias` on, a frame that captures the canvas and then draws over it (`renderer.toFrameTexture()`, a `screen_texture` effect, an advanced blend mode) is no longer shown black. Chromium loses such a frame, more often the longer it takes: the Aquarium example showed 114 black frames in 125 on its software renderer, none now - Transitions: a mask transition shaped like a sprite of the level says so in the console, once, when a later change finds that sprite gone with its level and closes a plain iris instead; nothing was said. A mask transition given no shape also says so once, not on every change -- Package: the npm package includes `CHANGELOG.md` and the license, which were left out, and its `sideEffects` field names the published bundle rather than a source folder that is not published -- Skills and README: the engine's size was given as 250 KB; it is about 320 kB minified and gzipped +- Package: the npm package includes `CHANGELOG.md` and the license, which were left out, and its `sideEffects` field names the published bundle too, so a bundler keeps a `melonjs` imported only for its polyfills +- Skills and README: the engine's size was given as 250 KB; it is about 320 kB minified and gzipped (the README now says ~300 KB) ### Chore - Dependencies: update the development tools, clearing the 46 vulnerabilities reported by the security audit diff --git a/packages/melonjs/package.json b/packages/melonjs/package.json index 66472d80ec..ba088f8b2b 100644 --- a/packages/melonjs/package.json +++ b/packages/melonjs/package.json @@ -5,6 +5,7 @@ "homepage": "https://www.melonjs.org/", "type": "module", "sideEffects": [ + "./src/polyfill/**", "./build/index.js" ], "keywords": [ diff --git a/packages/melonjs/skills/melonjs-20-migration/SKILL.md b/packages/melonjs/skills/melonjs-20-migration/SKILL.md index 4fdb28f58e..9485b0ebbd 100644 --- a/packages/melonjs/skills/melonjs-20-migration/SKILL.md +++ b/packages/melonjs/skills/melonjs-20-migration/SKILL.md @@ -187,8 +187,10 @@ assembled. Two things in them are easy to misread: the same. Older copies of the examples (before 20.17) also assigned `viewport.shader = …` -/ `sprite.shader = …` and set `this.z = Number.POSITIVE_INFINITY` on a HUD. -Neither is current: use `addPostEffect()`, and `addChild(hud, z)`. +/ `sprite.shader = …`, set `this.z = Number.POSITIVE_INFINITY` on a HUD, +extended `Entity` and called `device.requestFullscreen()`. None is current: use +`addPostEffect()`, `addChild(hud, z)`, a `Sprite` (with a `bodyDef` when it +needs a body) and `app.requestFullscreen()`. ## Checklist when code "should work" but doesn't diff --git a/packages/melonjs/skills/melonjs-effects-and-shaders/SKILL.md b/packages/melonjs/skills/melonjs-effects-and-shaders/SKILL.md index 398f1a8d4b..1efd988f5a 100644 --- a/packages/melonjs/skills/melonjs-effects-and-shaders/SKILL.md +++ b/packages/melonjs/skills/melonjs-effects-and-shaders/SKILL.md @@ -856,6 +856,7 @@ same question after construction. | a white or solid box where the effect should be | carrier renderable drawn while the effect is disabled | | ONE effect does nothing but two of them work | the renderable draws with primitives — set `postEffectNeedsCapture` | | effect cannot be re-enabled | `removePostEffect()` destroyed it — use `enabled` | +| on WebGL with `antiAlias` on, the screen flickers to black once something captures the frame: `toFrameTexture()`, a `screen_texture` effect, an advanced blend mode (before 20.17) | the browser lost a frame of an anti-aliased canvas that was read and then drawn over, more often on a slow frame: update | | ported shader renders upside down | a hand-bound `toFrameTexture()` capture — GL is bottom-up, WebGPU top-down | | shadow/smear offset flips on some draws | vertical UV offset not multiplied by `uUVYDir` | | frame rate collapses with many blended sprites | an *advanced* mode (overlay, darken, …) — each draw is a capture plus a composite | diff --git a/packages/melonjs/skills/melonjs-sprites-and-animation/SKILL.md b/packages/melonjs/skills/melonjs-sprites-and-animation/SKILL.md index 121701dbc1..a108297d16 100644 --- a/packages/melonjs/skills/melonjs-sprites-and-animation/SKILL.md +++ b/packages/melonjs/skills/melonjs-sprites-and-animation/SKILL.md @@ -236,6 +236,7 @@ Two consequences: | `this` is wrong in a `flicker(ms, callback)` callback, or a flicker started from it stops at once | before 20.13.0 the callback ran on an internal object and the flicker was stopped after it; now `this` is the sprite and the flicker has already ended | | sprites do not batch | more distinct textures in one frame than `renderer.maxTextures` | | nine-slice corners stretch anyway | `insetX`/`insetY` instead of `insetx`/`insety` | +| an atlas animation blinks: the sprite vanishes on some of its frames (before 20.17) | the frames the packer stored rotated were drawn off the screen unless the sprite was at (0, 0); a nine-slice sprite from a rotated frame was stretched along the wrong axis. Update; on an older version, turn rotation off in the packer | | a tint will not turn the sprite the colour asked for, only a darker one | a tint multiplies the art's own colours: recolour with a `GradientMapEffect`, flash with a `FlashEffect` | ## Related skills diff --git a/packages/melonjs/src/application/application.ts b/packages/melonjs/src/application/application.ts index 20b33d23f9..1d3f18ee9a 100644 --- a/packages/melonjs/src/application/application.ts +++ b/packages/melonjs/src/application/application.ts @@ -1332,6 +1332,7 @@ export default class Application { // flush/render our frame this.renderer.flush(); + this.renderer.endFrame(); // publish notification emit(GAME_AFTER_DRAW, globalThis.performance.now()); diff --git a/packages/melonjs/src/renderable/nineslicesprite.js b/packages/melonjs/src/renderable/nineslicesprite.js index e5c82d372c..5c8d734da5 100644 --- a/packages/melonjs/src/renderable/nineslicesprite.js +++ b/packages/melonjs/src/renderable/nineslicesprite.js @@ -138,30 +138,45 @@ export default class NineSliceSprite extends Sprite { // cache the current position and size let dx = x; - const dy = y; + let dy = y; let w = frame.width; let h = frame.height; + // the size to cover and the corners to keep, along the same axes + let target_width = this.nss_width; + let target_height = this.nss_height; + let insetx = this.insetx; + let insety = this.insety; + // frame offset in the texture/atlas const frame_offset = frame.offset; const g_offset = this.offset; // remove image's TexturePacker/ShoeBox rotation if (frame.angle !== 0) { - renderer.translate(-dx, -dy); + // The slices are laid out as the frame is stored, a quarter turn + // from how it looks, about the sprite's own corner: there the + // sprite's height runs along x and its width along y, and so do + // its corners + renderer.translate(dx, dy); renderer.rotate(frame.angle); - dx -= h; w = frame.height; h = frame.width; + target_width = this.nss_height; + target_height = this.nss_width; + insetx = this.insety; + insety = this.insetx; + dx = -target_width; + dy = 0; } const sx = g_offset.x + frame_offset.x; const sy = g_offset.y + frame_offset.y; // should this be configurable ? - const corner_width = this.insetx || w / 4; - const corner_height = this.insety || h / 4; + const corner_width = insetx || w / 4; + const corner_height = insety || h / 4; // `* 2`, not `<< 1`: corners default to w/4 which is fractional for // widths not divisible by 4, and the bit-shift truncates to int32 — @@ -170,8 +185,8 @@ export default class NineSliceSprite extends Sprite { const image_center_width = w - corner_width * 2; const image_center_height = h - corner_height * 2; - const target_center_width = this.nss_width - corner_width * 2; - const target_center_height = this.nss_height - corner_height * 2; + const target_center_width = target_width - corner_width * 2; + const target_center_height = target_height - corner_height * 2; // The 9-slice grid is separable per axis: each column/row is an unscaled // corner, a stretched center, then an unscaled corner. Fill the shared @@ -181,13 +196,13 @@ export default class NineSliceSprite extends Sprite { sColX[2] = sx + w - corner_width; dColX[0] = dx; dColX[1] = dx + corner_width; - dColX[2] = dx + this.nss_width - corner_width; + dColX[2] = dx + target_width - corner_width; sRowY[0] = sy; sRowY[1] = sy + corner_height; sRowY[2] = sy + h - corner_height; dRowY[0] = dy; dRowY[1] = dy + corner_height; - dRowY[2] = dy + this.nss_height - corner_height; + dRowY[2] = dy + target_height - corner_height; // blit the 9 slices: corners keep their size, the center column/row stretch. for (let r = 0; r < 3; r++) { diff --git a/packages/melonjs/src/renderable/sprite.js b/packages/melonjs/src/renderable/sprite.js index 1b87bbfaf8..f9e5e654bb 100644 --- a/packages/melonjs/src/renderable/sprite.js +++ b/packages/melonjs/src/renderable/sprite.js @@ -1063,9 +1063,12 @@ export default class Sprite extends Renderable { // remove image's TexturePacker/ShoeBox rotation if (frame.angle !== 0) { - target.translate(-xpos, -ypos); + // turned back about the frame's own corner, wherever that is: the + // rest is then laid out from (0, 0) + target.translate(xpos, ypos); target.rotate(frame.angle); - xpos -= h; + xpos = -h; + ypos = 0; w = frame.height; h = frame.width; // apply trim in rotated space: (tx, ty) → (-ty, tx) for -π/2 diff --git a/packages/melonjs/src/video/renderer.js b/packages/melonjs/src/video/renderer.js index c4a1b8f5a9..c6ddcf6a52 100644 --- a/packages/melonjs/src/video/renderer.js +++ b/packages/melonjs/src/video/renderer.js @@ -592,6 +592,13 @@ export default class Renderer { this._screenSpaceDepth = (this._screenSpaceDepth ?? 0) + 1; } + /** + * Close the frame, once everything in it is drawn and flushed. Called by + * the application; a renderer with something to do then overrides it. + * @ignore + */ + endFrame() {} + /** * Put per-frame renderer state back to a known-good baseline. * diff --git a/packages/melonjs/src/video/webgl/webgl_renderer.js b/packages/melonjs/src/video/webgl/webgl_renderer.js index 6afeb19b87..e7f92e937a 100644 --- a/packages/melonjs/src/video/webgl/webgl_renderer.js +++ b/packages/melonjs/src/video/webgl/webgl_renderer.js @@ -71,6 +71,9 @@ import { GLSamplerCache } from "./utils/samplercache.js"; * @import {Sphere} from "../../geometries/sphere.ts"; */ +// the one pixel `endFrame` reads off the canvas +const ONE_PIXEL = { x: 0, y: 0, width: 1, height: 1 }; + // reusable constants for 2D→3D matrix operations const _tempMatrix = new Matrix3d(); @@ -719,6 +722,16 @@ export default class WebGLRenderer extends Renderer { * @internal */ _deriveCapabilities() { + /** + * Whether the canvas itself is multisampled: `antiAlias` was asked + * for and the browser gave it. See {@link WebGLRenderer#endFrame}. + * @type {boolean} + * @ignore + * @internal + */ + this._canvasMultisampled = + this.gl.getContextAttributes()?.antialias === true; + /** * Whether this backend CAN render into a half-float color buffer, * which is a property of the driver alone. What the chain is @@ -1421,6 +1434,16 @@ export default class WebGLRenderer extends Renderer { */ this._frameTexture = undefined; } + // and the one pixel `endFrame` reads, for the same reason + if (typeof this._canvasResolve !== "undefined") { + this._canvasResolve.destroy(); + /** + * @ignore + * @internal + */ + this._canvasResolve = undefined; + } + this._canvasCaptured = false; // Context-loss-only cleanup for the TMX GPU renderer: the cached // `GLShader` and per-layer GL textures reference the OLD context @@ -1665,6 +1688,43 @@ export default class WebGLRenderer extends Renderer { return texture; } + /** + * Close a frame that captured the canvas while it was being drawn. + * + * A multisampled canvas (`antiAlias`) is resolved by the browser each + * time it is read, so by `toFrameTexture`, and once more when the frame is + * shown. Chromium loses a frame that was resolved in the middle and drawn + * to afterwards: it shows black instead, more often the longer the frame + * took. Measured on its software renderer, in plain WebGL as well as + * here, where the Aquarium example showed 114 black frames in 125; with + * anti-aliasing off, or with nothing drawn after the capture, none. + * + * Reading the canvas again once everything is drawn has the browser + * resolve the finished frame itself, and the frame is then shown as + * drawn: none black in 125. One pixel is enough, copied into a texture + * (no read back to the CPU, which would stall the frame). Flushing or + * finishing after the capture does not help. + * + * Called by the application once a frame is drawn; does nothing unless + * the frame captured a multisampled canvas. + * @ignore + */ + endFrame() { + if (this._canvasCaptured !== true) { + return; + } + /** + * @ignore + * @internal + */ + this._canvasResolve = this.toFrameTexture({ + target: this._canvasResolve ?? null, + region: ONE_PIXEL, + }); + // after the read: it is a capture of the canvas too + this._canvasCaptured = false; + } + /** * Flush the batcher to the frame buffer */ @@ -2091,6 +2151,16 @@ export default class WebGLRenderer extends Renderer { msaaActive.bind(); } + // read straight off a multisampled canvas: the frame has to be closed + // by another read, see `endFrame` + if (activeTarget === null && this._canvasMultisampled === true) { + /** + * @ignore + * @internal + */ + this._canvasCaptured = true; + } + // the scratch bind clobbered GL `unit` OUTSIDE the shared texture-cache // accounting (bound directly, not via allocateTextureUnit), so other // batchers' unit caches don't know it changed — invalidate it on all of diff --git a/packages/melonjs/tests/nineslicesprite.spec.js b/packages/melonjs/tests/nineslicesprite.spec.js index f32a720b71..9929dbfe29 100644 --- a/packages/melonjs/tests/nineslicesprite.spec.js +++ b/packages/melonjs/tests/nineslicesprite.spec.js @@ -358,7 +358,10 @@ describe("NineSliceSprite", () => { it("ADVERSARIAL: a TexturePacker-rotated frame swaps source dims and still tiles", () => { // a 64×48 frame packed at 90° — draw() must rotate the ctx and treat the - // frame as 48×64 for slicing, while the dest still spans the expanded panel + // frame as 48×64 for slicing, while the dest still spans the expanded + // panel: in the turned space it draws in, the panel's height runs + // along x and its width along y (sprite-rotated-frame.spec.js checks + // the picture this gives against the same art stored plainly) const nss = new NineSliceSprite(0, 0, { image: makeImage(64, 48), width: 200, @@ -374,9 +377,9 @@ describe("NineSliceSprite", () => { // source dims are swapped: width sourced as the frame's 48px height expectTiles(axis(r.calls, "sx", "sw"), 48); expectTiles(axis(r.calls, "sy", "sh"), 64); - // destination still tiles the full expanded panel - expectTiles(axis(r.calls, "dx", "dw"), 200); - expectTiles(axis(r.calls, "dy", "dh"), 120); + // destination still tiles the full expanded panel, turned + expectTiles(axis(r.calls, "dx", "dw"), 120); + expectTiles(axis(r.calls, "dy", "dh"), 200); }); it("ADVERSARIAL: non-square frame into non-square target tiles each axis independently", () => { diff --git a/packages/melonjs/tests/sprite-rotated-frame.spec.js b/packages/melonjs/tests/sprite-rotated-frame.spec.js new file mode 100644 index 0000000000..113e55a604 --- /dev/null +++ b/packages/melonjs/tests/sprite-rotated-frame.spec.js @@ -0,0 +1,258 @@ +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { + Application, + boot, + Entity, + TextureAtlas, + video, +} from "../src/index.js"; +import { grabFrame } from "./helpers/pixels.js"; + +/** + * A texture packer stores some frames turned a quarter, to pack them tighter, + * and a sprite turns them back when it draws. + * + * It turned them about the top left of the WORLD rather than of the frame, so + * a turned frame was right only for a sprite at (0, 0): the renderable of an + * `Entity`, which is how the engine's own example drew its atlas for years. + * A sprite of its own anywhere else drew its turned frames somewhere off the + * screen: in the Texture Packer example, rewritten as a plain `Sprite`, the + * walking character vanished on three frames of its eight. + * + * Checked by drawing: a frame stored turned has to give, pixel for pixel, the + * picture the same art stored plainly gives, wherever the sprite is. + */ +const SIZE = 96; + +describe.each([ + { name: "WebGL", renderer: video.WEBGL }, + { name: "Canvas", renderer: video.CANVAS }, +])("a sprite drawing an atlas frame stored turned, on $name", (backend) => { + let app; + let renderer; + let atlas; + + beforeAll(async () => { + boot(); + app = new Application(SIZE, SIZE, { + parent: "screen", + renderer: backend.renderer, + failIfMajorPerformanceCaveat: false, + antiAlias: false, + backgroundColor: "#000000", + }); + await app.init(); + renderer = app.renderer; + + // the art: a 12 × 20 Γ, which looks different turned or mirrored + const art = document.createElement("canvas"); + art.width = 12; + art.height = 20; + const a = art.getContext("2d"); + a.fillStyle = "#ff0000"; + a.fillRect(0, 0, 12, 6); + a.fillStyle = "#00ff00"; + a.fillRect(0, 6, 4, 14); + // one sheet: plain at (0, 0), turned a quarter clockwise at (20, 0) + // (20 wide, 12 tall), and the same two again at (0, 30) and (20, 30) + // for the frames trimmed out of a larger one + const sheet = document.createElement("canvas"); + sheet.width = sheet.height = 64; + const s = sheet.getContext("2d"); + const turned = (x, y) => { + s.save(); + s.translate(x + 20, y); + s.rotate(Math.PI / 2); + s.drawImage(art, 0, 0); + s.restore(); + }; + s.drawImage(art, 0, 0); + turned(20, 0); + s.drawImage(art, 0, 30); + turned(20, 30); + const frame = (filename, x, y, extra = {}) => { + return { + filename, + frame: { x, y, w: 12, h: 20 }, + rotated: false, + trimmed: false, + spriteSourceSize: { x: 0, y: 0, w: 12, h: 20 }, + sourceSize: { w: 12, h: 20 }, + ...extra, + }; + }; + const trimmed = { + trimmed: true, + spriteSourceSize: { x: 5, y: 3, w: 12, h: 20 }, + sourceSize: { w: 20, h: 28 }, + }; + atlas = new TextureAtlas( + { + frames: [ + frame("plain", 0, 0), + frame("turned", 20, 0, { rotated: true }), + frame("plain-trimmed", 0, 30, trimmed), + frame("turned-trimmed", 20, 30, { ...trimmed, rotated: true }), + ], + meta: { + app: "texturepacker", + image: "turned-sheet.png", + size: { w: 64, h: 64 }, + scale: "1", + }, + }, + sheet, + ); + }); + + afterAll(() => { + app.destroy(); + }); + + /** one frame of the world holding only this renderable */ + const picture = async (renderable) => { + app.world.addChild(renderable); + // drawn without waiting for an update to find it in view + renderable.inViewport = true; + app.isDirty = true; + app.draw(); + // read in the task that drew it, then taken out + const frame = grabFrame(renderer); + app.world.removeChildNow(renderable, true); + return Array.from((await frame).data); + }; + + /** the picture of a named frame, as a sprite set up by `place` */ + const spritePicture = async (name, place) => { + const sprite = atlas.createSpriteFromName(name); + place(sprite); + // not destroyed: the sprites share the sheet, which goes with the app + return picture(sprite); + }; + + /** how many pixels are lit: a frame drawn off the screen leaves none */ + const lit = (data) => { + let count = 0; + for (let i = 0; i < data.length; i += 4) { + if (data[i] + data[i + 1] > 100) { + count++; + } + } + return count; + }; + + const placements = [ + { + where: "at the origin", + place: (sprite) => { + sprite.anchorPoint.set(0, 0); + sprite.pos.set(0, 0); + }, + }, + { + where: "away from the origin", + place: (sprite) => { + sprite.anchorPoint.set(0, 0); + sprite.pos.set(40, 30); + }, + }, + { + where: "away from the origin, on its centre", + place: (sprite) => { + sprite.pos.set(50, 44); + }, + }, + { + where: "away from the origin, scaled and flipped", + place: (sprite) => { + sprite.pos.set(48, 48); + sprite.scale(2); + sprite.flipX(true); + }, + }, + { + where: "away from the origin, turned itself", + place: (sprite) => { + sprite.pos.set(48, 48); + sprite.rotate(Math.PI / 6); + }, + }, + ]; + + for (const { where, place } of placements) { + it(`${where}: the picture of the same art stored plainly`, async () => { + const plain = await spritePicture("plain", place); + // the art is on the screen at all: 12 × 6 and 4 × 14 pixels of it + expect(lit(plain)).toBeGreaterThan(100); + expect(await spritePicture("turned", place)).toEqual(plain); + }); + + it(`${where}, trimmed: the picture of the same art stored plainly`, async () => { + const plain = await spritePicture("plain-trimmed", place); + expect(lit(plain)).toBeGreaterThan(100); + expect(await spritePicture("turned-trimmed", place)).toEqual(plain); + }); + } + + it("an animation of plain and turned frames stays where the sprite is", async () => { + const sprite = atlas.createAnimationFromName(["plain", "turned"]); + sprite.anchorPoint.set(0, 0); + sprite.pos.set(40, 30); + sprite.setAnimationFrame(0); + const first = await picture(sprite); + sprite.setAnimationFrame(1); + const second = await picture(sprite); + expect(lit(first)).toBeGreaterThan(100); + expect(second).toEqual(first); + }); + + // a nine-slice sprite stretches the frame over its own size, corners + // kept: turned, its width is laid out along the stored frame's height + const nineSlices = [ + { + what: "at the frame's own size, at the origin", + settings: { width: 12, height: 20 }, + at: [0, 0], + }, + { + what: "stretched, at the origin", + settings: { width: 40, height: 30 }, + at: [0, 0], + }, + { + what: "stretched, away from the origin", + settings: { width: 40, height: 30 }, + at: [30, 40], + }, + { + what: "stretched, with corners of its own, away from the origin", + settings: { width: 44, height: 36, insetx: 3, insety: 5 }, + at: [28, 32], + }, + ]; + for (const { what, settings, at } of nineSlices) { + it(`a nine-slice sprite ${what}: the picture of the same art stored plainly`, async () => { + const nineSlicePicture = (name) => { + const sprite = atlas.createSpriteFromName(name, { ...settings }, true); + sprite.anchorPoint.set(0, 0); + sprite.pos.set(at[0], at[1]); + return picture(sprite); + }; + const plain = await nineSlicePicture("plain"); + expect(lit(plain)).toBeGreaterThan(100); + expect(await nineSlicePicture("turned")).toEqual(plain); + }); + } + + it("as the renderable of an Entity, where it was right: unchanged", async () => { + const pictureIn = async (name) => { + const entity = new Entity(30, 20, { width: 12, height: 20 }); + entity.renderable = atlas.createSpriteFromName(name); + const data = await picture(entity); + return data; + }; + const plain = await pictureIn("plain"); + expect(lit(plain)).toBeGreaterThan(100); + expect(await pictureIn("turned")).toEqual(plain); + }); +}); diff --git a/packages/melonjs/tests/toframetexture-antialias.spec.js b/packages/melonjs/tests/toframetexture-antialias.spec.js new file mode 100644 index 0000000000..8a8ebbf316 --- /dev/null +++ b/packages/melonjs/tests/toframetexture-antialias.spec.js @@ -0,0 +1,205 @@ +import { + afterAll, + beforeAll, + beforeEach, + describe, + expect, + it, + vi, +} from "vitest"; +import { + Application, + boot, + Renderable, + video, + WebGLRenderer, +} from "../src/index.js"; + +/** + * A frame that captures an anti-aliased canvas (`renderer.toFrameTexture()`, + * a `screen_texture` effect, an advanced blend mode) and then draws over it. + * + * The browser resolves a multisampled canvas each time it is read, and once + * more when the frame is shown. Chromium loses a frame resolved in the middle + * and drawn to afterwards: the page shows black instead, more often the + * longer the frame took. Measured on its software renderer by recording the + * page: the Aquarium example showed 114 black frames in 125 (9 in 125 in the + * headless shell); plain WebGL doing the same, 6 screenshots in 40; with + * anti-aliasing off, or nothing drawn after the capture, none. + * + * What the page shows cannot be read from inside it, so this checks the + * remedy rather than the symptom: a frame that captured the canvas is closed + * by one more read of it, a single pixel, which is what was measured to give + * no black frame in 375. + */ +const SIZE = 32; + +/** every copy off the framebuffer since the spies were last cleared: [width, height] */ +const copies = (image, sub) => { + return [ + ...image.mock.calls.map((c) => { + return [c[5], c[6]]; + }), + ...sub.mock.calls.map((c) => { + return [c[6], c[7]]; + }), + ]; +}; + +describe.each([ + { antiAlias: true, name: "an anti-aliased canvas" }, + { antiAlias: false, name: "a canvas that is not anti-aliased" }, +])("capturing $name", ({ antiAlias }) => { + let app; + let renderer; + let gl; + let image; + let sub; + // the test browser has to grant the multisampling it is asked for + let multisampled; + + beforeAll(async () => { + boot(); + app = new Application(SIZE, SIZE, { + parent: "screen", + renderer: video.WEBGL, + failIfMajorPerformanceCaveat: false, + antiAlias, + }); + await app.init(); + renderer = app.renderer; + if (renderer instanceof WebGLRenderer) { + gl = renderer.gl; + multisampled = gl.getContextAttributes().antialias === true; + image = vi.spyOn(gl, "copyTexImage2D"); + sub = vi.spyOn(gl, "copyTexSubImage2D"); + } + }); + + afterAll(() => { + image?.mockRestore(); + sub?.mockRestore(); + app.destroy(); + }); + + beforeEach(() => { + image?.mockClear(); + sub?.mockClear(); + }); + + it("gets the canvas it asked for", (ctx) => { + if (gl === undefined) { + ctx.skip("WebGL is not available"); + } + if (antiAlias && !multisampled) { + ctx.skip("the browser gave no multisampled canvas"); + } + expect(multisampled).toBe(antiAlias); + expect(renderer._canvasMultisampled).toBe(antiAlias); + }); + + it("a frame that captured nothing is closed with no read", (ctx) => { + if (gl === undefined) { + ctx.skip("WebGL is not available"); + } + renderer.clear(); + renderer.flush(); + renderer.endFrame(); + expect(copies(image, sub)).toEqual([]); + }); + + it("a frame that captured the canvas is closed by a read of one pixel, when anti-aliased", (ctx) => { + if (gl === undefined || multisampled !== antiAlias) { + ctx.skip("WebGL, or the canvas asked for, is not available"); + } + renderer.clear(); + const capture = renderer.toFrameTexture(); + expect(copies(image, sub)).toEqual([[SIZE, SIZE]]); + image.mockClear(); + sub.mockClear(); + + renderer.flush(); + renderer.endFrame(); + expect(copies(image, sub)).toEqual(antiAlias ? [[1, 1]] : []); + expect(gl.getError()).toBe(gl.NO_ERROR); + + // the capture the game holds is not what the read went into + expect(renderer.getSharedFrameTexture()).toBe(capture); + expect(capture.width).toBe(SIZE); + expect(capture.height).toBe(SIZE); + + // said once: closing the frame again reads nothing + image.mockClear(); + sub.mockClear(); + renderer.endFrame(); + expect(copies(image, sub)).toEqual([]); + }); + + it("every such frame is closed, into the same one-pixel texture", (ctx) => { + if (gl === undefined || multisampled !== antiAlias || !antiAlias) { + ctx.skip("needs an anti-aliased WebGL canvas"); + } + const created = vi.spyOn(gl, "createTexture"); + for (let frame = 0; frame < 3; frame++) { + renderer.clear(); + renderer.toFrameTexture(); + renderer.flush(); + image.mockClear(); + sub.mockClear(); + renderer.endFrame(); + expect(copies(image, sub), `frame ${frame + 1}`).toEqual([[1, 1]]); + } + // allocated by the earlier test, and kept + expect(created).not.toHaveBeenCalled(); + created.mockRestore(); + expect(gl.getError()).toBe(gl.NO_ERROR); + }); + + it("the application closes the frame a renderable captured in its draw", (ctx) => { + if (gl === undefined || multisampled !== antiAlias) { + ctx.skip("WebGL, or the canvas asked for, is not available"); + } + class Capturing extends Renderable { + constructor() { + super(0, 0, SIZE, SIZE); + this.anchorPoint.set(0, 0); + } + draw(target) { + target.toFrameTexture(); + } + } + const capturing = new Capturing(); + app.world.addChild(capturing); + // drawn without waiting for an update to find it in view + capturing.inViewport = true; + app.isDirty = true; + app.draw(); + expect(copies(image, sub)).toEqual( + antiAlias + ? [ + [SIZE, SIZE], + [1, 1], + ] + : [[SIZE, SIZE]], + ); + app.world.removeChildNow(capturing); + }); + + it("a reset lets the one-pixel texture go, and the next frame makes another", (ctx) => { + if (gl === undefined || multisampled !== antiAlias || !antiAlias) { + ctx.skip("needs an anti-aliased WebGL canvas"); + } + expect(renderer._canvasResolve).toBeDefined(); + renderer.reset(); + expect(renderer._canvasResolve).toBeUndefined(); + + renderer.clear(); + renderer.toFrameTexture(); + renderer.flush(); + image.mockClear(); + sub.mockClear(); + renderer.endFrame(); + expect(copies(image, sub)).toEqual([[1, 1]]); + expect(gl.getError()).toBe(gl.NO_ERROR); + }); +}); From 45a7a2304fd23f5f06477379011f7427760a1a7e Mon Sep 17 00:00:00 2001 From: Swastik Tripathi Date: Sat, 21 Nov 2026 08:24:08 +0530 Subject: [PATCH 42/51] Path2D: keep half-circle SVG arcs from turning into straight lines vec2Angle() passed the normalized dot product of the two radius vectors straight to Math.acos. For a half circle the vectors are opposite and rounding can put the cosine just below -1, so the sweep angle was NaN, no arc points were generated and only the closing lineTo was drawn. Clamp the cosine to [-1, 1]. --- packages/melonjs/CHANGELOG.md | 1 + .../melonjs/src/geometries/toarccanvas.ts | 5 ++++- packages/melonjs/tests/path2d.spec.js | 22 +++++++++++++++++++ 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/packages/melonjs/CHANGELOG.md b/packages/melonjs/CHANGELOG.md index 65ee677550..a9909a79cd 100644 --- a/packages/melonjs/CHANGELOG.md +++ b/packages/melonjs/CHANGELOG.md @@ -27,6 +27,7 @@ - glTF: a model compressed with Draco or meshopt, which the loader cannot decode, says so in the console, naming the extension, instead of failing on an accessor error that did not mention it - Physics: a method of the built-in adapter (`setVelocity`, `applyForce`, `setStatic` and the like) called on a renderable with no body says so, `this renderable has no built-in body`, where it failed on a property of `undefined`; and a raycast passes over an object whose body is not one of the adapter's, where it threw - Skills: the deployment skill gave the engine's size as 250 KB; it is about 320 kB minified and gzipped +- Path2D: an SVG `A` arc that is exactly a half circle, as when its radius is too small and is scaled up to fit, is drawn as an arc. Rounding could push the cosine of its sweep angle just past -1, `Math.acos` returned `NaN`, and the arc became a straight line between its endpoints ### Chore - Dependencies: the 46 known vulnerabilities the security audit reported in the development tools are cleared (vite 8.3.8, vitest 4.1.12, serve 14.2.8, and overrides for what they depend on). None was in a dependency of a published package diff --git a/packages/melonjs/src/geometries/toarccanvas.ts b/packages/melonjs/src/geometries/toarccanvas.ts index 0fd2ddc592..6fd1103351 100644 --- a/packages/melonjs/src/geometries/toarccanvas.ts +++ b/packages/melonjs/src/geometries/toarccanvas.ts @@ -72,7 +72,10 @@ function vec2Angle(u: [number, number], v: [number, number]) { const [ux, uy] = u; const [vx, vy] = v; const sign = ux * vy - uy * vx >= 0 ? 1 : -1; - return sign * Math.acos(vec2Dot(u, v) / (vec2Mag(u) * vec2Mag(v))); + // rounding can push the cosine just past -1 or 1 (e.g. the opposite + // vectors of a half circle), where Math.acos returns NaN + const cos = vec2Dot(u, v) / (vec2Mag(u) * vec2Mag(v)); + return sign * Math.acos(Math.min(1, Math.max(-1, cos))); } // From https://svgwg.org/svg2-draft/implnote.html#ArcConversionEndpointToCenter diff --git a/packages/melonjs/tests/path2d.spec.js b/packages/melonjs/tests/path2d.spec.js index c2d03c48fe..a3dbaea298 100644 --- a/packages/melonjs/tests/path2d.spec.js +++ b/packages/melonjs/tests/path2d.spec.js @@ -125,6 +125,28 @@ describe("Path2D", () => { } }); + it("should draw a semicircle whose endpoints are not axis-aligned", () => { + // (0, 0) and (24, 10) are 26 apart, so a radius of 13 is exactly a + // half circle around (12, 5). The two radius vectors are opposite, + // and their normalized dot product rounds just below -1. + path.parseSVGPath("M 0 0 A 13 13 0 0 1 24 10"); + expect(path.points.length).toBeGreaterThan(10); + for (const point of path.points) { + expect(Math.hypot(point.x - 12, point.y - 5)).toBeCloseTo(13, 6); + } + }); + + it("should draw a semicircle when the radius is scaled up to fit", () => { + // radius 1 is too small for endpoints 12.04 apart, so it is scaled + // up to half that distance and the arc becomes a half circle + path.parseSVGPath("M 0 0 A 1 1 0 0 1 1 12"); + expect(path.points.length).toBeGreaterThan(10); + const r = Math.hypot(1, 12) / 2; + for (const point of path.points) { + expect(Math.hypot(point.x - 0.5, point.y - 6)).toBeCloseTo(r, 6); + } + }); + it("should handle the heart path from ticket #1198", () => { path.parseSVGPath( "M 10 30 A 20 20 0 0 1 50 30 A 20 20 0 0 1 90 30 Q 90 60 50 90 Q 10 60 10 30 Z", From 16fab41d360a015c75073c910c41f0a6da40bc18 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 03:15:07 +0000 Subject: [PATCH 43/51] SVG Shapes example: a row of half-circle arcs Six shapes whose arcs are exactly half a circle with their ends on a slant, or ask for a radius too small to reach between them: the cases in which an SVG arc is drawn as the straight line between its ends (melonjs/melonJS#1910). Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- .../examples/svgShapes/ExampleSVGShapes.tsx | 71 ++++++++++++++++++- 1 file changed, 70 insertions(+), 1 deletion(-) diff --git a/packages/examples/src/examples/svgShapes/ExampleSVGShapes.tsx b/packages/examples/src/examples/svgShapes/ExampleSVGShapes.tsx index b750b809dc..62554c3009 100644 --- a/packages/examples/src/examples/svgShapes/ExampleSVGShapes.tsx +++ b/packages/examples/src/examples/svgShapes/ExampleSVGShapes.tsx @@ -16,7 +16,7 @@ import { createExampleComponent } from "../utils"; const createGame = async () => { // Initialize the video. try { - const app = new Application(1024, 840, { + const app = new Application(1024, 1005, { parent: "screen", renderer: video.AUTO, blendMode: "normal", @@ -394,6 +394,73 @@ const createGame = async () => { "#B0BEC5", ); + // --- Row 6: half-circle arcs --- + // + // An arc is exactly half a circle when its two ends are a diameter + // apart, and also when its radius is too small to reach between + // them: it is then made large enough, which is half that distance. + // Each arc below is one, with its ends on a slant; drawn as the + // chord between its ends, it is a straight line. + + // Half disc: one arc and its chord + this.drawSVGShape( + renderer, + "M 2 30 A 52 52 0 0 1 98 70 Z", + 60, + 868, + "#0277BD", + "#4FC3F7", + ); + + // Disc: two half circles, as the donut above, on a slanted diameter + this.drawSVGShape( + renderer, + "M 2 30 A 52 52 0 0 1 98 70 A 52 52 0 0 1 2 30 Z", + 215, + 868, + "#AD1457", + "#F06292", + ); + + // Capsule on a slant: two half-circle ends + this.drawSVGShape( + renderer, + "M 30 2 L 78 22 A 26 26 0 0 1 58 70 L 10 50 A 26 26 0 0 1 30 2 Z", + 385, + 883, + "#2E7D32", + "#81C784", + ); + + // Wave: four half circles end to end, left unfilled + this.drawSVGShape( + renderer, + "M 2 60 A 13 13 0 0 1 26 50 A 13 13 0 0 0 50 40 A 13 13 0 0 1 74 30 A 13 13 0 0 0 98 20", + 525, + 878, + "#FFB300", + ); + + // Awning: every arc asks for a radius of 1, too small to reach + this.drawSVGShape( + renderer, + "M 0 50 A 1 1 0 0 1 25 45 A 1 1 0 0 1 50 50 A 1 1 0 0 1 75 45 A 1 1 0 0 1 100 50 L 100 90 L 0 90 Z", + 685, + 858, + "#6A1B9A", + "#BA68C8", + ); + + // Half moon: a half circle outside, a shallower arc inside + this.drawSVGShape( + renderer, + "M 14 70 A 39 39 0 0 1 86 40 A 60 60 0 0 0 14 70 Z", + 845, + 863, + "#F9A825", + "#FFF176", + ); + // --- Row dividers (evenly spaced between row centres) --- renderer.setColor("#333355"); renderer.beginPath(); @@ -405,6 +472,8 @@ const createGame = async () => { renderer.lineTo(1004, 502); renderer.moveTo(20, 667); renderer.lineTo(1004, 667); + renderer.moveTo(20, 832); + renderer.lineTo(1004, 832); renderer.stroke(); } } From 64bac5cb68ea274b741162a2b153e16876befb24 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 04:02:24 +0000 Subject: [PATCH 44/51] Changelog: credit the contributor of the half-circle arc fix Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- packages/melonjs/CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/melonjs/CHANGELOG.md b/packages/melonjs/CHANGELOG.md index 02fc4e3f35..27237bb442 100644 --- a/packages/melonjs/CHANGELOG.md +++ b/packages/melonjs/CHANGELOG.md @@ -31,7 +31,7 @@ - Transitions: a mask transition shaped like a sprite of the level says so in the console, once, when a later change finds that sprite gone with its level and closes a plain iris instead; nothing was said. A mask transition given no shape also says so once, not on every change - Package: the npm package includes `CHANGELOG.md` and the license, which were left out, and its `sideEffects` field names the published bundle too, so a bundler keeps a `melonjs` imported only for its polyfills - Skills and README: the engine's size was given as 250 KB; it is about 320 kB minified and gzipped (the README now says ~300 KB) -- Path2D: an SVG `A` arc that is exactly a half circle, as when its radius is too small and is scaled up to fit, is drawn as an arc. Rounding could push the cosine of its sweep angle just past -1, `Math.acos` returned `NaN`, and the arc became a straight line between its endpoints +- Path2D: an SVG `A` arc that is exactly a half circle, as when its radius is too small and is scaled up to fit, is drawn as an arc. Rounding could push the cosine of its sweep angle just past -1, `Math.acos` returned `NaN`, and the arc became a straight line between its endpoints (thanks @SwastikTripathi) ### Chore - Dependencies: update the development tools, clearing the 46 vulnerabilities reported by the security audit From 748ecaa3bb2153256b25ae5234f70a8f501c5b36 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 22:39:25 +0000 Subject: [PATCH 45/51] Changelog: trim 20.17.0 and credit a contributor - The two Skills entries and the engine-size correction are removed - The Package entry moves from Fixed to Chore - The hanging-baseline Text fix credits its contributor Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- packages/melonjs/CHANGELOG.md | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/packages/melonjs/CHANGELOG.md b/packages/melonjs/CHANGELOG.md index 27237bb442..56bc12be40 100644 --- a/packages/melonjs/CHANGELOG.md +++ b/packages/melonjs/CHANGELOG.md @@ -7,8 +7,6 @@ - Tiled: isometric maps are rendered by the GPU on WebGL and WebGPU, as orthogonal ones are, and so are staggered and hexagonal maps. Nothing to enable: a tile layer whose tiles come from one tileset takes it by itself, and any other is drawn as before, the console saying why ([#1897](https://github.com/melonjs/melonJS/issues/1897)) - Effects: `GradientMapEffect` recolors a sprite or a whole scene from its brightness, through a list of two to eight colors, the darkest pixels taking the first and the brightest the last: one sprite in a palette per team, a duotone, a night scene. With `smooth: false` each color takes a band of its own, a palette swap for art drawn in flat shades - Effects: `DitherEffect` draws a scene in a few colors with an ordered dither between them, as early consoles did: on the camera, so many `levels` of each channel, so everything keeps its own hue, or a `palette` of two to sixteen colors of your own, in pixels `size` pixels wide. Only what falls between two colors is patterned (shading, soft shadows, gradients); a flat color that is one of them stays flat -- Skills: the entry skill now says what melonJS is the right engine for and what it is not, turns a kind of game (a platformer, a puzzle, a shooter) into the skills to read and the example to start from, and maps the usual engine vocabulary to the names used here. It also answers a request for a browser game that names no engine -- Skills: a new `melonjs-testing` skill is how an agent checks its own work: the game run in a headless browser, every console line read (the header names the renderer the run got), the controls driven, the game's state read from outside, a frame looked at ### Performance - Tiled: thanks to the GPU renderer, drawing an isometric tile layer takes about **90%** less of the main thread's time with 1200 tiles in view (0.68 to 0.07 ms a frame) and about **98%** less with 4000 (2.0 to 0.04 ms), and no longer grows with the number of tiles shown. Staggered and hexagonal maps gain the same @@ -23,20 +21,19 @@ - Tiled: an isometric, staggered or hexagonal layer with an `opacity` below 1 fades as one picture on WebGL and WebGPU; each tile showed through the one in front of it - Tiled: a tile layer removed from its container and added again, and a tile missing from its tileset's image, no longer throw - `NineSliceSprite` blinks with `flicker()`, as a `Sprite` does; it ignored it -- Text: a stroked multi-line label with `textBaseline: "hanging"` keeps the top of its outline on macOS, where Helvetica's hanging metrics made the ink padding exactly as tall as the ink, shearing its first row off the canvas ([#1870](https://github.com/melonjs/melonJS/issues/1870)) +- Text: a stroked multi-line label with `textBaseline: "hanging"` keeps the top of its outline on macOS, where Helvetica's hanging metrics made the ink padding exactly as tall as the ink, shearing its first row off the canvas ([#1870](https://github.com/melonjs/melonJS/issues/1870)) (thanks @Goldloli) - glTF: a model compressed with Draco or meshopt, which the loader cannot decode, says so in the console, naming the extension, instead of failing on an accessor error that did not mention it - Physics: a method of the built-in adapter (`setVelocity`, `applyForce`, `setStatic` and the like) called on a renderable with no body says so, `this renderable has no built-in body`, where it failed on a property of `undefined`; and a raycast passes over an object whose body is not one of the adapter's, where it threw - Sprites: an atlas frame the packer stored rotated is drawn where the sprite is. It was drawn off the screen unless the sprite stood at (0, 0), so an animation with such frames blinked, on every renderer. A `NineSliceSprite` made from a rotated frame is stretched along the right axes, with its corners the right way round - WebGL: with `antiAlias` on, a frame that captures the canvas and then draws over it (`renderer.toFrameTexture()`, a `screen_texture` effect, an advanced blend mode) is no longer shown black. Chromium loses such a frame, more often the longer it takes: the Aquarium example showed 114 black frames in 125 on its software renderer, none now - Transitions: a mask transition shaped like a sprite of the level says so in the console, once, when a later change finds that sprite gone with its level and closes a plain iris instead; nothing was said. A mask transition given no shape also says so once, not on every change -- Package: the npm package includes `CHANGELOG.md` and the license, which were left out, and its `sideEffects` field names the published bundle too, so a bundler keeps a `melonjs` imported only for its polyfills -- Skills and README: the engine's size was given as 250 KB; it is about 320 kB minified and gzipped (the README now says ~300 KB) - Path2D: an SVG `A` arc that is exactly a half circle, as when its radius is too small and is scaled up to fit, is drawn as an arc. Rounding could push the cosine of its sweep angle just past -1, `Math.acos` returned `NaN`, and the arc became a straight line between its endpoints (thanks @SwastikTripathi) ### Chore - Dependencies: update the development tools, clearing the 46 vulnerabilities reported by the security audit - Lint: lint each package on its own and cache the result, so `pnpm lint` skips what has not changed - CI: fix the test job losing its browser page at random, and run the test suite in about half the time +- Package: the npm package includes `CHANGELOG.md` and the license, which were left out, and its `sideEffects` field names the published bundle too, so a bundler keeps a `melonjs` imported only for its polyfills ## [20.16.0] (melonJS 2) - _2026-11-17_ From b35dd09b12bdec3edc17063e95f7bb0c87b776eb Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 22:46:00 +0000 Subject: [PATCH 46/51] Changelog: the engine size entry, shorter, under Chore Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- packages/melonjs/CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/melonjs/CHANGELOG.md b/packages/melonjs/CHANGELOG.md index 56bc12be40..5b91a91f21 100644 --- a/packages/melonjs/CHANGELOG.md +++ b/packages/melonjs/CHANGELOG.md @@ -11,7 +11,6 @@ ### Performance - Tiled: thanks to the GPU renderer, drawing an isometric tile layer takes about **90%** less of the main thread's time with 1200 tiles in view (0.68 to 0.07 ms a frame) and about **98%** less with 4000 (2.0 to 0.04 ms), and no longer grows with the number of tiles shown. Staggered and hexagonal maps gain the same - Tiled: for reference, orthogonal tile layers, on the GPU since 19.4, measure about **85%** less with 1000 tiles in view (0.62 to 0.09 ms) and about **97%** less with 3600 (1.9 to 0.06 ms) -- Size: the engine is about **8%** smaller to download: 323 kB minified and gzipped, from 350 kB (1,073 kB minified, from 1,159 kB). The comments in its shaders are no longer published; a shader is bundled as text, which a game's minifier does not touch, so they reached every game. Nothing to change in a game ### Fixed - Tiled: layers follow their offset in Tiled. A tile layer is drawn there, and where its own `pos` moves it, and `getTile()` finds its tiles there; an object layer's objects are created there; a group layer's offset moves the tile layers inside it. All were ignored, so a map with layer offsets now looks as it does in Tiled @@ -34,6 +33,7 @@ - Lint: lint each package on its own and cache the result, so `pnpm lint` skips what has not changed - CI: fix the test job losing its browser page at random, and run the test suite in about half the time - Package: the npm package includes `CHANGELOG.md` and the license, which were left out, and its `sideEffects` field names the published bundle too, so a bundler keeps a `melonjs` imported only for its polyfills +- Size: the engine is about 8% smaller to download (323 kB minified and gzipped, from 350 kB), as the comments in its shaders are no longer published ## [20.16.0] (melonJS 2) - _2026-11-17_ From 68d4603d6562f9e3419e1ce70ec364b91a9788ca Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 22:46:42 +0000 Subject: [PATCH 47/51] Changelog: shorter entries for 20.17.0 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- packages/melonjs/CHANGELOG.md | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/packages/melonjs/CHANGELOG.md b/packages/melonjs/CHANGELOG.md index 5b91a91f21..003afe49b5 100644 --- a/packages/melonjs/CHANGELOG.md +++ b/packages/melonjs/CHANGELOG.md @@ -3,36 +3,36 @@ ## [20.17.0] (melonJS 2) - _unreleased_ ### Added -- Transitions: a mask transition can be shaped like an image or a `Sprite`, close on the player with `center`, and fill the shape with `invert`, on `state.transition`, `MaskEffect` and `Trigger` ([#1399](https://github.com/melonjs/melonJS/issues/1399)) -- Tiled: isometric maps are rendered by the GPU on WebGL and WebGPU, as orthogonal ones are, and so are staggered and hexagonal maps. Nothing to enable: a tile layer whose tiles come from one tileset takes it by itself, and any other is drawn as before, the console saying why ([#1897](https://github.com/melonjs/melonJS/issues/1897)) -- Effects: `GradientMapEffect` recolors a sprite or a whole scene from its brightness, through a list of two to eight colors, the darkest pixels taking the first and the brightest the last: one sprite in a palette per team, a duotone, a night scene. With `smooth: false` each color takes a band of its own, a palette swap for art drawn in flat shades -- Effects: `DitherEffect` draws a scene in a few colors with an ordered dither between them, as early consoles did: on the camera, so many `levels` of each channel, so everything keeps its own hue, or a `palette` of two to sixteen colors of your own, in pixels `size` pixels wide. Only what falls between two colors is patterned (shading, soft shadows, gradients); a flat color that is one of them stays flat +- Transitions: a mask transition can take the shape of an image or a `Sprite`, close on the player (`center`) and fill the shape (`invert`), on `state.transition`, `MaskEffect` and `Trigger` ([#1399](https://github.com/melonjs/melonJS/issues/1399)) +- Tiled: isometric, staggered and hexagonal maps are rendered by the GPU on WebGL and WebGPU, as orthogonal ones are. Nothing to enable: a tile layer drawn from a single tileset uses it by itself ([#1897](https://github.com/melonjs/melonJS/issues/1897)) +- Effects: `GradientMapEffect` recolors a sprite or a scene from its brightness, through two to eight colors: a palette per team, a duotone, a night scene, or a hard palette swap with `smooth: false` +- Effects: `DitherEffect` draws a scene in a few colors with an ordered dither between them, as early consoles did: `levels` of each channel or a `palette` of two to sixteen colors, in pixels `size` pixels wide ### Performance -- Tiled: thanks to the GPU renderer, drawing an isometric tile layer takes about **90%** less of the main thread's time with 1200 tiles in view (0.68 to 0.07 ms a frame) and about **98%** less with 4000 (2.0 to 0.04 ms), and no longer grows with the number of tiles shown. Staggered and hexagonal maps gain the same +- Tiled: on the GPU, drawing an isometric tile layer takes about **90%** less of the main thread's time with 1200 tiles in view (0.68 to 0.07 ms a frame) and about **98%** less with 4000 (2.0 to 0.04 ms). Staggered and hexagonal maps gain the same - Tiled: for reference, orthogonal tile layers, on the GPU since 19.4, measure about **85%** less with 1000 tiles in view (0.62 to 0.09 ms) and about **97%** less with 3600 (1.9 to 0.06 ms) ### Fixed -- Tiled: layers follow their offset in Tiled. A tile layer is drawn there, and where its own `pos` moves it, and `getTile()` finds its tiles there; an object layer's objects are created there; a group layer's offset moves the tile layers inside it. All were ignored, so a map with layer offsets now looks as it does in Tiled -- Tiled: tiles larger than a cell are drawn wherever they are in view. They were cut off or left out along the edges of the view, above and right of the map, on a map centred in the screen, and once the map itself had scrolled out of view +- Tiled: a layer's offset in Tiled is applied: to a tile layer (where it is drawn and where `getTile()` looks), to the objects of an object layer, and to the tile layers inside a group. It was ignored +- Tiled: tiles larger than a cell are drawn wherever they are in view; they were cut off or left out along the edges of the view and of the map - Tiled: staggered and hexagonal maps are drawn where Tiled draws them: a tile larger than its cell stands on it, a tileset's `tileoffset` moves its tiles, and maps of odd sizes stay on whole pixels - Tiled: orthogonal layers drawn by the GPU show the soft edges of large tiles over the tiles behind them, lay large tiles over each other in the map's order, and read a tileset with a `margin` right - Tiled: an isometric, staggered or hexagonal layer with an `opacity` below 1 fades as one picture on WebGL and WebGPU; each tile showed through the one in front of it - Tiled: a tile layer removed from its container and added again, and a tile missing from its tileset's image, no longer throw - `NineSliceSprite` blinks with `flicker()`, as a `Sprite` does; it ignored it -- Text: a stroked multi-line label with `textBaseline: "hanging"` keeps the top of its outline on macOS, where Helvetica's hanging metrics made the ink padding exactly as tall as the ink, shearing its first row off the canvas ([#1870](https://github.com/melonjs/melonJS/issues/1870)) (thanks @Goldloli) -- glTF: a model compressed with Draco or meshopt, which the loader cannot decode, says so in the console, naming the extension, instead of failing on an accessor error that did not mention it -- Physics: a method of the built-in adapter (`setVelocity`, `applyForce`, `setStatic` and the like) called on a renderable with no body says so, `this renderable has no built-in body`, where it failed on a property of `undefined`; and a raycast passes over an object whose body is not one of the adapter's, where it threw -- Sprites: an atlas frame the packer stored rotated is drawn where the sprite is. It was drawn off the screen unless the sprite stood at (0, 0), so an animation with such frames blinked, on every renderer. A `NineSliceSprite` made from a rotated frame is stretched along the right axes, with its corners the right way round -- WebGL: with `antiAlias` on, a frame that captures the canvas and then draws over it (`renderer.toFrameTexture()`, a `screen_texture` effect, an advanced blend mode) is no longer shown black. Chromium loses such a frame, more often the longer it takes: the Aquarium example showed 114 black frames in 125 on its software renderer, none now -- Transitions: a mask transition shaped like a sprite of the level says so in the console, once, when a later change finds that sprite gone with its level and closes a plain iris instead; nothing was said. A mask transition given no shape also says so once, not on every change -- Path2D: an SVG `A` arc that is exactly a half circle, as when its radius is too small and is scaled up to fit, is drawn as an arc. Rounding could push the cosine of its sweep angle just past -1, `Math.acos` returned `NaN`, and the arc became a straight line between its endpoints (thanks @SwastikTripathi) +- Text: a stroked multi-line label with `textBaseline: "hanging"` keeps the top of its outline on macOS, where its first row was cut off ([#1870](https://github.com/melonjs/melonJS/issues/1870)) (thanks @Goldloli) +- glTF: a model compressed with Draco or meshopt, which the loader cannot decode, says so in the console, naming the extension, instead of failing on an unrelated accessor error +- Physics: a method of the built-in adapter (`setVelocity`, `applyForce`, `setStatic` and the like) called on a renderable with no body says so, and a raycast passes over an object whose body is not the adapter's; both threw +- Sprites: an atlas frame the packer stored rotated is drawn where the sprite is; it was drawn off the screen unless the sprite stood at (0, 0), so its animation blinked. A `NineSliceSprite` made from such a frame is no longer stretched along the wrong axes +- WebGL: with `antiAlias` on, a frame that captures the canvas and then draws over it (`renderer.toFrameTexture()`, a `screen_texture` effect, an advanced blend mode) is no longer shown black at times in Chromium +- Transitions: a mask transition shaped like a sprite of the level says so in the console, once, when that sprite is gone with its level and a plain iris is used instead. A mask transition given no shape also says so once, not on every change +- Path2D: an SVG `A` arc that is exactly a half circle, as when its radius is too small and is scaled up to fit, is drawn as an arc; rounding could turn it into a straight line between its endpoints (thanks @SwastikTripathi) ### Chore - Dependencies: update the development tools, clearing the 46 vulnerabilities reported by the security audit - Lint: lint each package on its own and cache the result, so `pnpm lint` skips what has not changed - CI: fix the test job losing its browser page at random, and run the test suite in about half the time -- Package: the npm package includes `CHANGELOG.md` and the license, which were left out, and its `sideEffects` field names the published bundle too, so a bundler keeps a `melonjs` imported only for its polyfills +- Package: the npm package includes `CHANGELOG.md` and the license, which were left out, and its `sideEffects` field names the published bundle - Size: the engine is about 8% smaller to download (323 kB minified and gzipped, from 350 kB), as the comments in its shaders are no longer published ## [20.16.0] (melonJS 2) - _2026-11-17_ From 4dc6845ce0a238ce9a935dbc7c35703cc256e8c0 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 23:15:30 +0000 Subject: [PATCH 48/51] Effects: FlashEffect and TintPulseEffect are color matrices Both blend every pixel toward one color, which on the premultiplied colors an effect is given is a color matrix. They now extend ColorMatrixEffect and are drawn by its shader, where each had one of its own: two fewer programs to compile, and the pulse's sine is computed once a frame in setTime() rather than for every pixel. - Same options, setters and result: a new spec draws each against the shader it had, over opaque, gradient and half-transparent pixels, and the frames differ by one 8-bit step at most - The uniforms the old shaders had (uFlashColor, uFlashIntensity, uPulseColor, uPulseSpeed, uPulseIntensity, uTime) still set the effect by name - TintPulseEffect gains the speed and intensity properties - AfterBurner example: the death flash uses setIntensity() - Effects skill: the five presets that are color matrices Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- .../examples/src/examples/afterBurner/HUD.ts | 9 +- .../melonjs-effects-and-shaders/SKILL.md | 5 + .../melonjs/src/video/effects/colorMatrix.js | 38 ++ packages/melonjs/src/video/effects/flash.js | 74 ++-- .../melonjs/src/video/effects/tintPulse.js | 120 ++++-- .../melonjs/tests/effect-color-blend.spec.js | 388 ++++++++++++++++++ packages/melonjs/tests/effect-colors.spec.js | 4 +- 7 files changed, 557 insertions(+), 81 deletions(-) create mode 100644 packages/melonjs/tests/effect-color-blend.spec.js diff --git a/packages/examples/src/examples/afterBurner/HUD.ts b/packages/examples/src/examples/afterBurner/HUD.ts index 9ff7ed7ea0..84db42d7a8 100644 --- a/packages/examples/src/examples/afterBurner/HUD.ts +++ b/packages/examples/src/examples/afterBurner/HUD.ts @@ -345,7 +345,7 @@ export class HUD { this.flashTween?.stop(); this.flashTween = undefined; this.flashDriver.k = 0; - this.deathFlash.setUniform("uFlashIntensity", 0); + this.deathFlash.setIntensity(0); } /** @@ -360,7 +360,7 @@ export class HUD { flashDeath(): void { this.flashTween?.stop(); this.flashDriver.k = 1; - this.deathFlash.setUniform("uFlashIntensity", DEATH_FLASH_ALPHA); + this.deathFlash.setIntensity(DEATH_FLASH_ALPHA); const tween = new Tween(this.flashDriver); // the wash has to finish even though the run is over tween.updateWhenPaused = true; @@ -368,10 +368,7 @@ export class HUD { .to({ k: 0 }, { duration: DEATH_FLASH_FADE_MS }) .easing(Tween.Easing.Quadratic.Out) .onUpdate(() => { - this.deathFlash.setUniform( - "uFlashIntensity", - this.flashDriver.k * DEATH_FLASH_ALPHA, - ); + this.deathFlash.setIntensity(this.flashDriver.k * DEATH_FLASH_ALPHA); }) .onComplete(() => { this.flashTween = undefined; diff --git a/packages/melonjs/skills/melonjs-effects-and-shaders/SKILL.md b/packages/melonjs/skills/melonjs-effects-and-shaders/SKILL.md index 1efd988f5a..00149fb560 100644 --- a/packages/melonjs/skills/melonjs-effects-and-shaders/SKILL.md +++ b/packages/melonjs/skills/melonjs-effects-and-shaders/SKILL.md @@ -121,6 +121,11 @@ GPU backend: `VignetteEffect`, `ScanlineEffect` (optional CRT curvature), `HologramEffect`, `ShineEffect`, `RadialGradientEffect`, `SquishEffect`, `ToneMappingEffect`, `GradientMapEffect`, `DitherEffect`. +Five of them are a `ColorMatrixEffect` with a matrix set for you, and share +its one shader: `SepiaEffect`, `DesaturateEffect`, `InvertEffect`, +`FlashEffect` and `TintPulseEffect` (the last two since 20.17). Drive them +through their own setters (`setIntensity`, `setColor`, `setTime`). + **Colors take an alpha.** Every color option and `setColor` takes `[r, g, b]` or `[r, g, b, a]`, each 0.0 to 1.0, and the alpha is the color's own opacity: a half-transparent outline, a glow at half strength, a flash that only half diff --git a/packages/melonjs/src/video/effects/colorMatrix.js b/packages/melonjs/src/video/effects/colorMatrix.js index 2b666b8f5e..bf44003379 100644 --- a/packages/melonjs/src/video/effects/colorMatrix.js +++ b/packages/melonjs/src/video/effects/colorMatrix.js @@ -71,6 +71,44 @@ export default class ColorMatrixEffect extends ShaderEffect { this.setUniform("uColorMatrix", this._matrix.val); } + /** + * Set the matrix to a blend of every pixel toward one color: `amount` of + * the way, scaled by the color's own alpha. What a flash or a tint is. + * + * Colors reach an effect premultiplied, so "this color, as opaque as the + * pixel" is the color times the pixel's alpha: the matrix's alpha column. + * @param {ArrayLike} color - the color to blend toward, as [r, g, b, a] (0.0–1.0) + * @param {number} amount - how far (0.0 = the pixel's own color, 1.0 = the color) + * @ignore + * @internal + */ + _blendToward(color, amount) { + const k = amount * color[3]; + const keep = 1 - k; + // column-major: what red, green, blue and alpha each add to the result + this._matrix + .identity() + .transform( + keep, + 0, + 0, + 0, + 0, + keep, + 0, + 0, + 0, + 0, + keep, + 0, + k * color[0], + k * color[1], + k * color[2], + 1, + ); + this._syncUniform(); + } + /** * Reset the color matrix to identity (no color change). * @returns {this} this instance for chaining diff --git a/packages/melonjs/src/video/effects/flash.js b/packages/melonjs/src/video/effects/flash.js index 40dccc8530..9ee8ff647e 100644 --- a/packages/melonjs/src/video/effects/flash.js +++ b/packages/melonjs/src/video/effects/flash.js @@ -1,5 +1,5 @@ +import ColorMatrixEffect from "./colorMatrix.js"; import { rgba } from "./rgba.js"; -import ShaderEffect from "./shadereffect.js"; /** * additional import for TypeScript @@ -8,26 +8,15 @@ import ShaderEffect from "./shadereffect.js"; * @import WebGPURenderer from "../webgpu/webgpu_renderer.js"; * @import Renderer from "../renderer.js"; */ -// the WGSL twin of the GLSL body below — same logic, same uniform -// names, picked by the ShaderEffect base per renderer.shaderLanguage -const wgslFragment = ` -struct FlashUniforms { - uFlashColor : vec4f, - uFlashIntensity : f32, -}; -@group(3) @binding(0) var fx : FlashUniforms; - -fn apply(color : vec4f, uv : vec2f) -> vec4f { - // the color's alpha scales how far the flash covers the sprite - return vec4f(mix(color.rgb, fx.uFlashColor.rgb * color.a, fx.uFlashIntensity * fx.uFlashColor.a), color.a); -} -`; /** * A shader effect that flashes the sprite with a solid color. * Commonly used for hit feedback — flash white when the player takes damage. - * The `intensity` uniform controls how much of the flash color is mixed in + * The `intensity` controls how much of the flash color is mixed in * (0.0 = original sprite, 1.0 = fully colored). + * + * A flash is a color matrix: it is drawn by the shader of + * {@link ColorMatrixEffect}, which every flash shares. * @category Effects * @see {@link Renderable#addPostEffect} for usage * @example @@ -48,7 +37,7 @@ fn apply(color : vec4f, uv : vec2f) -> vec4f { * const hit = new FlashEffect(renderer, { color: [1.0, 1.0, 1.0, 0.5] }); * hit.setIntensity(1.0); */ -export default class FlashEffect extends ShaderEffect { +export default class FlashEffect extends ColorMatrixEffect { /** * @param {Renderer} renderer - the current renderer instance * @param {object} [options] - effect options @@ -56,23 +45,22 @@ export default class FlashEffect extends ShaderEffect { * @param {number} [options.intensity=0.0] - initial flash intensity (0.0–1.0) */ constructor(renderer, options = {}) { - super(renderer, { - glsl: ` - uniform vec4 uFlashColor; - uniform float uFlashIntensity; - vec4 apply(vec4 color, vec2 uv) { - // the color's alpha scales how far the flash covers the sprite - return vec4(mix(color.rgb, uFlashColor.rgb * color.a, uFlashIntensity * uFlashColor.a), color.a); - } - `, - wgsl: wgslFragment, - }); + super(renderer); + + /** + * the flash color, as [r, g, b, a] + * @ignore + * @internal + */ + this._color = rgba(options.color ?? [1.0, 1.0, 1.0]); - const color = options.color ?? [1.0, 1.0, 1.0]; + /** + * how much of the flash color is mixed in (0.0–1.0) + * @type {number} + */ this.intensity = options.intensity ?? 0.0; - this.setUniform("uFlashColor", rgba(color)); - this.setUniform("uFlashIntensity", this.intensity); + this._blendToward(this._color, this.intensity); } /** @@ -81,7 +69,7 @@ export default class FlashEffect extends ShaderEffect { */ setIntensity(value) { this.intensity = Math.max(0, Math.min(1, value)); - this.setUniform("uFlashIntensity", this.intensity); + this._blendToward(this._color, this.intensity); } /** @@ -89,6 +77,26 @@ export default class FlashEffect extends ShaderEffect { * @param {number[]} color - flash color as [r, g, b] or [r, g, b, a] (0.0–1.0); the alpha scales the intensity */ setColor(color) { - this.setUniform("uFlashColor", rgba(color)); + this._color = rgba(color); + this._blendToward(this._color, this.intensity); + } + + /** + * The flash had a shader of its own, with these two uniforms: a game that + * set them by name keeps working. + * @param {string} name - the uniform's name + * @param {*} value - its value + * @ignore + */ + setUniform(name, value) { + if (name === "uFlashIntensity") { + // as given, not clamped: that is what the uniform did + this.intensity = value; + this._blendToward(this._color, this.intensity); + } else if (name === "uFlashColor") { + this.setColor(value); + } else { + super.setUniform(name, value); + } } } diff --git a/packages/melonjs/src/video/effects/tintPulse.js b/packages/melonjs/src/video/effects/tintPulse.js index 9d67ed3b54..e329031ed3 100644 --- a/packages/melonjs/src/video/effects/tintPulse.js +++ b/packages/melonjs/src/video/effects/tintPulse.js @@ -1,5 +1,5 @@ +import ColorMatrixEffect from "./colorMatrix.js"; import { rgba } from "./rgba.js"; -import ShaderEffect from "./shadereffect.js"; /** * additional import for TypeScript @@ -8,28 +8,15 @@ import ShaderEffect from "./shadereffect.js"; * @import WebGPURenderer from "../webgpu/webgpu_renderer.js"; * @import Renderer from "../renderer.js"; */ -// the WGSL twin of the GLSL body below — same logic, same uniform -// names, picked by the ShaderEffect base per renderer.shaderLanguage -const wgslFragment = ` -struct TintPulseUniforms { - uPulseColor : vec4f, - uPulseSpeed : f32, - uPulseIntensity : f32, - uTime : f32, -}; -@group(3) @binding(0) var fx : TintPulseUniforms; - -fn apply(color : vec4f, uv : vec2f) -> vec4f { - let pulse = (sin(fx.uTime * fx.uPulseSpeed * 6.2832) * 0.5 + 0.5) * fx.uPulseIntensity; - // the color's alpha scales how far the pulse tints the sprite - return vec4f(mix(color.rgb, fx.uPulseColor.rgb * color.a, pulse * fx.uPulseColor.a), color.a); -} -`; /** * A shader effect that pulses a color overlay on the sprite. * Commonly used for status effects — poison green, freeze blue, fire red. - * The `time` uniform should be updated each frame for the pulse animation. + * The time should be updated each frame, with `setTime()`, for the pulse + * animation. + * + * A tint is a color matrix, here one that follows the time: it is drawn by + * the shader of {@link ColorMatrixEffect}, which every pulse shares. * @category Effects * @see {@link Renderable#addPostEffect} for usage * @example @@ -46,7 +33,7 @@ fn apply(color : vec4f, uv : vec2f) -> vec4f { * // a subtle pulse: the color's alpha caps how far it tints * mySprite.addPostEffect(new TintPulseEffect(renderer, { color: [1.0, 0.8, 0.0, 0.35] })); */ -export default class TintPulseEffect extends ShaderEffect { +export default class TintPulseEffect extends ColorMatrixEffect { /** * @param {Renderer} renderer - the current renderer instance * @param {object} [options] - effect options @@ -55,26 +42,35 @@ export default class TintPulseEffect extends ShaderEffect { * @param {number} [options.intensity=0.3] - maximum tint strength (0.0–1.0) */ constructor(renderer, options = {}) { - super(renderer, { - glsl: ` - uniform vec4 uPulseColor; - uniform float uPulseSpeed; - uniform float uPulseIntensity; - uniform float uTime; - vec4 apply(vec4 color, vec2 uv) { - float pulse = (sin(uTime * uPulseSpeed * 6.2832) * 0.5 + 0.5) * uPulseIntensity; - // the color's alpha scales how far the pulse tints the sprite - return vec4(mix(color.rgb, uPulseColor.rgb * color.a, pulse * uPulseColor.a), color.a); - } - `, - wgsl: wgslFragment, - }); + super(renderer); + + /** + * the pulse color, as [r, g, b, a] + * @ignore + * @internal + */ + this._color = rgba(options.color ?? [1.0, 0.0, 0.0]); + + /** + * pulse speed, in oscillations per second + * @type {number} + */ + this.speed = options.speed ?? 2.0; - const color = options.color ?? [1.0, 0.0, 0.0]; - this.setUniform("uPulseColor", rgba(color)); - this.setUniform("uPulseSpeed", options.speed ?? 2.0); - this.setUniform("uPulseIntensity", options.intensity ?? 0.3); - this.setUniform("uTime", 0.0); + /** + * maximum tint strength (0.0–1.0) + * @type {number} + */ + this.intensity = options.intensity ?? 0.3; + + /** + * the time the pulse is drawn at, in seconds + * @ignore + * @internal + */ + this._time = 0; + + this._pulse(); } /** @@ -82,6 +78,50 @@ export default class TintPulseEffect extends ShaderEffect { * @param {number[]} color - pulse color as [r, g, b] or [r, g, b, a] (0.0–1.0); the alpha scales the intensity */ setColor(color) { - this.setUniform("uPulseColor", rgba(color)); + this._color = rgba(color); + this._pulse(); + } + + /** + * Set the time the pulse is drawn at: call it once per frame. + * @param {number} seconds - elapsed time, in seconds + */ + setTime(seconds) { + this._time = seconds; + this._pulse(); + } + + /** + * The pulse had a shader of its own, with these four uniforms: a game + * that set them by name keeps working. + * @param {string} name - the uniform's name + * @param {*} value - its value + * @ignore + */ + setUniform(name, value) { + if (name === "uTime") { + this.setTime(value); + } else if (name === "uPulseColor") { + this.setColor(value); + } else if (name === "uPulseSpeed") { + this.speed = value; + this._pulse(); + } else if (name === "uPulseIntensity") { + this.intensity = value; + this._pulse(); + } else { + super.setUniform(name, value); + } + } + + /** + * the matrix of the tint at the current time: from none to `intensity` + * and back, `speed` times a second + * @ignore + * @internal + */ + _pulse() { + const wave = Math.sin(this._time * this.speed * Math.PI * 2) * 0.5 + 0.5; + this._blendToward(this._color, wave * this.intensity); } } diff --git a/packages/melonjs/tests/effect-color-blend.spec.js b/packages/melonjs/tests/effect-color-blend.spec.js new file mode 100644 index 0000000000..03eb81a30d --- /dev/null +++ b/packages/melonjs/tests/effect-color-blend.spec.js @@ -0,0 +1,388 @@ +import "./helpers/webgpu-globals.js"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { + boot, + ColorMatrixEffect, + FlashEffect, + ShaderEffect, + TintPulseEffect, +} from "../src/index.js"; +import Renderer from "../src/video/renderer.js"; +import { + getWebGLRenderer, + releaseWebGLRenderer, +} from "./helpers/webgl-context.js"; + +/** + * A flash and a tint pulse blend every pixel toward one color. On the + * premultiplied colors an effect is given, that is a color matrix, so both + * are a `ColorMatrixEffect` and share its shader, where each had one of its + * own. + * + * What has to hold: the picture is the one the old shaders drew, the colors + * and options mean what they did, and a game that set the old uniforms by + * name still works. + */ + +/** the sixteen floats of an effect's matrix, column-major */ +const matrixOf = (effect) => { + return Array.from(effect._matrix.val).map((v) => { + return Math.round(v * 1e6) / 1e6; + }); +}; + +/** the matrix of a blend toward [r, g, b], `k` of the way */ +const blend = ([r, g, b], k) => { + const keep = Math.round((1 - k) * 1e6) / 1e6; + const part = (v) => { + return Math.round(v * k * 1e6) / 1e6; + }; + return [ + keep, + 0, + 0, + 0, + 0, + keep, + 0, + 0, + 0, + 0, + keep, + 0, + part(r), + part(g), + part(b), + 1, + ]; +}; + +const IDENTITY = blend([0, 0, 0], 0); + +const wgslRenderer = { shaderLanguage: "wgsl", width: 64, height: 64 }; + +/** an effect on a WGSL renderer, with no device needed to check its matrix */ +const make = (Effect, options) => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const effect = new Effect(wgslRenderer, options); + warn.mockRestore(); + return effect; +}; + +describe("a flash and a tint pulse, as color matrices", () => { + describe("FlashEffect", () => { + it("is a ColorMatrixEffect, and still a ShaderEffect", () => { + const flash = make(FlashEffect); + expect(flash).toBeInstanceOf(ColorMatrixEffect); + expect(flash).toBeInstanceOf(ShaderEffect); + expect(flash.wgslRealization.valid).toBe(true); + flash.destroy(); + }); + + it("shares the color matrix shader, with a matrix as its only uniform", () => { + const flash = make(FlashEffect); + const matrix = make(ColorMatrixEffect); + expect([...flash.wgslRealization.layout.keys()]).toEqual([ + ...matrix.wgslRealization.layout.keys(), + ]); + expect([...flash.wgslRealization.layout.keys()]).toEqual([ + "uColorMatrix", + ]); + flash.destroy(); + matrix.destroy(); + }); + + it("leaves the sprite as it is by default: white, at no intensity", () => { + const flash = make(FlashEffect); + expect(flash.intensity).toBe(0); + expect(matrixOf(flash)).toEqual(IDENTITY); + flash.destroy(); + }); + + it("blends toward its color by its intensity", () => { + const flash = make(FlashEffect, { color: [1, 0.5, 0], intensity: 0.25 }); + expect(matrixOf(flash)).toEqual(blend([1, 0.5, 0], 0.25)); + flash.setIntensity(1); + expect(flash.intensity).toBe(1); + expect(matrixOf(flash)).toEqual(blend([1, 0.5, 0], 1)); + flash.destroy(); + }); + + it("scales the intensity by the color's alpha", () => { + const flash = make(FlashEffect, { color: [1, 1, 1, 0.5], intensity: 1 }); + expect(matrixOf(flash)).toEqual(blend([1, 1, 1], 0.5)); + flash.destroy(); + }); + + it("setIntensity keeps the intensity between 0 and 1", () => { + const flash = make(FlashEffect, { color: [1, 0, 0] }); + flash.setIntensity(3); + expect(flash.intensity).toBe(1); + flash.setIntensity(-1); + expect(flash.intensity).toBe(0); + expect(matrixOf(flash)).toEqual(IDENTITY); + flash.destroy(); + }); + + it("setColor changes the color, at the intensity it had", () => { + const flash = make(FlashEffect, { intensity: 0.5 }); + flash.setColor([0, 0, 1]); + expect(matrixOf(flash)).toEqual(blend([0, 0, 1], 0.5)); + flash.setColor([0, 0, 1, 0.5]); + expect(matrixOf(flash)).toEqual(blend([0, 0, 1], 0.25)); + expect(() => { + flash.setColor([1, 0]); + }).toThrow(TypeError); + flash.destroy(); + }); + + it("the uniforms its own shader had still set it, by name", () => { + const flash = make(FlashEffect); + flash.setUniform("uFlashIntensity", 0.75); + expect(flash.intensity).toBe(0.75); + expect(matrixOf(flash)).toEqual(blend([1, 1, 1], 0.75)); + flash.setUniform("uFlashColor", [1, 0, 0, 1]); + expect(matrixOf(flash)).toEqual(blend([1, 0, 0], 0.75)); + flash.setUniform("uFlashIntensity", 0); + expect(matrixOf(flash)).toEqual(IDENTITY); + flash.destroy(); + }); + }); + + describe("TintPulseEffect", () => { + it("is a ColorMatrixEffect, sharing its shader", () => { + const pulse = make(TintPulseEffect); + expect(pulse).toBeInstanceOf(ColorMatrixEffect); + expect(pulse.wgslRealization.valid).toBe(true); + expect([...pulse.wgslRealization.layout.keys()]).toEqual([ + "uColorMatrix", + ]); + pulse.destroy(); + }); + + it("takes its defaults: red, twice a second, up to 0.3", () => { + const pulse = make(TintPulseEffect); + expect(pulse.speed).toBe(2); + expect(pulse.intensity).toBe(0.3); + // at time 0 the wave is half way up + expect(matrixOf(pulse)).toEqual(blend([1, 0, 0], 0.15)); + pulse.destroy(); + }); + + it("goes from none to its intensity and back, `speed` times a second", () => { + const pulse = make(TintPulseEffect, { + color: [0, 1, 0], + speed: 1, + intensity: 0.8, + }); + // a quarter of a cycle in: the peak + pulse.setTime(0.25); + expect(matrixOf(pulse)).toEqual(blend([0, 1, 0], 0.8)); + // three quarters in: none + pulse.setTime(0.75); + expect(matrixOf(pulse)).toEqual(IDENTITY); + // a whole cycle later, the same as at the start + pulse.setTime(1); + expect(matrixOf(pulse)).toEqual(blend([0, 1, 0], 0.4)); + // twice as fast, the peak comes at an eighth of a second + const fast = make(TintPulseEffect, { + color: [0, 1, 0], + speed: 2, + intensity: 0.8, + }); + fast.setTime(0.125); + expect(matrixOf(fast)).toEqual(blend([0, 1, 0], 0.8)); + pulse.destroy(); + fast.destroy(); + }); + + it("scales the tint by the color's alpha, and takes a new color", () => { + const pulse = make(TintPulseEffect, { + color: [0, 1, 0, 0.5], + speed: 1, + intensity: 1, + }); + pulse.setTime(0.25); + expect(matrixOf(pulse)).toEqual(blend([0, 1, 0], 0.5)); + pulse.setColor([0, 0, 1]); + expect(matrixOf(pulse)).toEqual(blend([0, 0, 1], 1)); + expect(() => { + pulse.setColor([1, 0, 0, 1, 1]); + }).toThrow(TypeError); + pulse.destroy(); + }); + + it("the uniforms its own shader had still set it, by name", () => { + const pulse = make(TintPulseEffect, { color: [1, 0, 0], intensity: 1 }); + pulse.setUniform("uPulseSpeed", 1); + pulse.setUniform("uTime", 0.25); + expect(pulse.speed).toBe(1); + expect(matrixOf(pulse)).toEqual(blend([1, 0, 0], 1)); + pulse.setUniform("uPulseIntensity", 0.5); + expect(pulse.intensity).toBe(0.5); + expect(matrixOf(pulse)).toEqual(blend([1, 0, 0], 0.5)); + pulse.setUniform("uPulseColor", [0, 0, 1, 1]); + expect(matrixOf(pulse)).toEqual(blend([0, 0, 1], 0.5)); + pulse.destroy(); + }); + }); + + describe("on WebGL, against the shaders they had", () => { + const SIZE = 64; + let renderer; + let sprite; + + // the bodies the two effects were drawn with, before + const OLD_FLASH = ` + uniform vec4 uFlashColor; + uniform float uFlashIntensity; + vec4 apply(vec4 color, vec2 uv) { + return vec4(mix(color.rgb, uFlashColor.rgb * color.a, uFlashIntensity * uFlashColor.a), color.a); + } + `; + const OLD_PULSE = ` + uniform vec4 uPulseColor; + uniform float uPulseSpeed; + uniform float uPulseIntensity; + uniform float uTime; + vec4 apply(vec4 color, vec2 uv) { + float pulse = (sin(uTime * uPulseSpeed * 6.2832) * 0.5 + 0.5) * uPulseIntensity; + return vec4(mix(color.rgb, uPulseColor.rgb * color.a, pulse * uPulseColor.a), color.a); + } + `; + + beforeAll(async () => { + await boot(); + try { + renderer = await getWebGLRenderer(SIZE, SIZE); + } catch { + // WebGL genuinely unavailable: the tests skip below + } + if (renderer) { + renderer.projectionMatrix.ortho(0, SIZE, SIZE, 0, -1000, 1000); + renderer.currentBatcher.setProjection(renderer.projectionMatrix); + } + // 32x32, every kind of pixel a sprite has: opaque colors, a + // gradient, and half and quarter transparent ones over nothing + sprite = Renderer.createCanvas(32, 32); + const ctx = sprite.getContext("2d"); + const ramp = ctx.createLinearGradient(0, 0, 32, 0); + ramp.addColorStop(0, "#102080"); + ramp.addColorStop(1, "#f0c020"); + ctx.fillStyle = ramp; + ctx.fillRect(0, 0, 32, 12); + ctx.fillStyle = "rgba(255, 0, 0, 0.5)"; + ctx.fillRect(0, 12, 16, 10); + ctx.fillStyle = "rgba(0, 255, 64, 0.25)"; + ctx.fillRect(16, 12, 16, 10); + ctx.fillStyle = "#ffffff"; + ctx.fillRect(4, 24, 24, 6); + }); + + afterAll(() => { + releaseWebGLRenderer(); + }); + + const requireWebGL = (ctx) => { + if (renderer === undefined) { + ctx.skip("WebGL renderer not available in this environment"); + } + }; + + /** the sprite drawn with an effect over a mid grey, as its pixels */ + const drawn = (effect) => { + renderer.clearColor("#404040ff"); + renderer.save(); + renderer.customShader = effect; + renderer.drawImage(sprite, 0, 0, 32, 32, 16, 16, 32, 32); + renderer.flush(); + renderer.customShader = undefined; + renderer.restore(); + effect.destroy(); + const gl = renderer.gl; + const out = new Uint8Array(SIZE * SIZE * 4); + gl.readPixels(0, 0, SIZE, SIZE, gl.RGBA, gl.UNSIGNED_BYTE, out); + return out; + }; + + /** the largest difference between two frames, in 8-bit steps */ + const furthest = (a, b) => { + let most = 0; + for (let i = 0; i < a.length; i++) { + most = Math.max(most, Math.abs(a[i] - b[i])); + } + return most; + }; + + const oldFlash = (color, intensity) => { + const effect = new ShaderEffect(renderer, OLD_FLASH); + effect.setUniform("uFlashColor", new Float32Array(color)); + effect.setUniform("uFlashIntensity", intensity); + return effect; + }; + + const oldPulse = (color, speed, intensity, time) => { + const effect = new ShaderEffect(renderer, OLD_PULSE); + effect.setUniform("uPulseColor", new Float32Array(color)); + effect.setUniform("uPulseSpeed", speed); + effect.setUniform("uPulseIntensity", intensity); + effect.setUniform("uTime", time); + return effect; + }; + + it("the test sprite is drawn, and a flash changes it", (ctx) => { + requireWebGL(ctx); + const plain = drawn(new FlashEffect(renderer, { intensity: 0 })); + const white = drawn(new FlashEffect(renderer, { intensity: 1 })); + expect(furthest(plain, white)).toBeGreaterThan(100); + }); + + it.for([ + { color: [1, 1, 1, 1], intensity: 0 }, + { color: [1, 1, 1, 1], intensity: 0.3 }, + { color: [1, 1, 1, 1], intensity: 1 }, + { color: [1, 0, 0, 1], intensity: 0.6 }, + { color: [0.2, 0.9, 0.4, 0.5], intensity: 1 }, + { color: [0, 0, 0, 1], intensity: 0.8 }, + { color: [1, 1, 1, 0], intensity: 1 }, + ])( + "a flash of $color at $intensity is the picture its own shader drew", + (flash, ctx) => { + requireWebGL(ctx); + const now = drawn( + new FlashEffect(renderer, { + color: flash.color, + intensity: flash.intensity, + }), + ); + const before = drawn(oldFlash(flash.color, flash.intensity)); + // the same arithmetic in another order: a rounding step at most + expect(furthest(now, before)).toBeLessThanOrEqual(1); + }, + ); + + it.for([ + { color: [1, 0, 0, 1], speed: 2, intensity: 0.3, time: 0 }, + { color: [0, 1, 0, 1], speed: 1, intensity: 1, time: 0.25 }, + { color: [0, 1, 0, 1], speed: 1, intensity: 1, time: 0.75 }, + { color: [0.1, 0.4, 1, 0.5], speed: 3, intensity: 0.8, time: 1.37 }, + { color: [1, 0.8, 0, 0.35], speed: 2, intensity: 0.3, time: 12.4 }, + ])( + "a pulse of $color at $time s is the picture its own shader drew", + (pulse, ctx) => { + requireWebGL(ctx); + const effect = new TintPulseEffect(renderer, { + color: pulse.color, + speed: pulse.speed, + intensity: pulse.intensity, + }); + effect.setTime(pulse.time); + const now = drawn(effect); + const before = drawn( + oldPulse(pulse.color, pulse.speed, pulse.intensity, pulse.time), + ); + expect(furthest(now, before)).toBeLessThanOrEqual(1); + }, + ); + }); +}); diff --git a/packages/melonjs/tests/effect-colors.spec.js b/packages/melonjs/tests/effect-colors.spec.js index 00c2ed77c9..9a0fc04f66 100644 --- a/packages/melonjs/tests/effect-colors.spec.js +++ b/packages/melonjs/tests/effect-colors.spec.js @@ -32,12 +32,12 @@ import { */ // [effect, its color uniform, the constructor option, the setter] +// (a flash and a tint pulse take a color too, in a color matrix rather than a +// uniform of their own: effect-color-blend.spec.js) const COLORED = [ [OutlineEffect, "uOutlineColor", "color", "setColor"], [GlowEffect, "uGlowColor", "color", "setColor"], [DropShadowEffect, "uShadowColor", "color", "setColor"], - [FlashEffect, "uFlashColor", "color", "setColor"], - [TintPulseEffect, "uPulseColor", "color", "setColor"], [HologramEffect, "uHoloColor", "color", "setColor"], [ShineEffect, "uShineColor", "color", "setColor"], [DissolveEffect, "uEdgeColor", "edgeColor", "setEdgeColor"], From 74deda7bc4d5c154a0605044f911510adfdad377 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 23:19:11 +0000 Subject: [PATCH 49/51] Release: melonJS 20.17.0 The changelog dated 2026-11-22, its highlights leading with GPU tile layers for isometric, staggered and hexagonal maps. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- packages/melonjs/CHANGELOG.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/melonjs/CHANGELOG.md b/packages/melonjs/CHANGELOG.md index 003afe49b5..889a33365b 100644 --- a/packages/melonjs/CHANGELOG.md +++ b/packages/melonjs/CHANGELOG.md @@ -1,6 +1,8 @@ # Changelog -## [20.17.0] (melonJS 2) - _unreleased_ +## [20.17.0] (melonJS 2) - _2026-11-22_ + +**Highlights:** isometric, staggered and hexagonal Tiled maps are now drawn by the GPU, as orthogonal ones are: up to **98%** less of the main thread's time per tile layer, with nothing to enable. Also new: mask transitions shaped like an image or a sprite that close on the player, and two effects, `GradientMapEffect` (palette swaps, duotones) and `DitherEffect` (a retro limited-color look). A map with layer offsets now looks as it does in Tiled: the offsets were ignored before. ### Added - Transitions: a mask transition can take the shape of an image or a `Sprite`, close on the player (`center`) and fill the shape (`invert`), on `state.transition`, `MaskEffect` and `Trigger` ([#1399](https://github.com/melonjs/melonJS/issues/1399)) From 0f29993b559f94c56520f2c041acedba854700e1 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 23:22:11 +0000 Subject: [PATCH 50/51] Changelog: FlashEffect and TintPulseEffect on the color matrix shader, under Chore Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- packages/melonjs/CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/melonjs/CHANGELOG.md b/packages/melonjs/CHANGELOG.md index 889a33365b..1d4e0dfb68 100644 --- a/packages/melonjs/CHANGELOG.md +++ b/packages/melonjs/CHANGELOG.md @@ -36,6 +36,7 @@ - CI: fix the test job losing its browser page at random, and run the test suite in about half the time - Package: the npm package includes `CHANGELOG.md` and the license, which were left out, and its `sideEffects` field names the published bundle - Size: the engine is about 8% smaller to download (323 kB minified and gzipped, from 350 kB), as the comments in its shaders are no longer published +- Effects: `FlashEffect` and `TintPulseEffect` are drawn by the `ColorMatrixEffect` shader, as `SepiaEffect`, `DesaturateEffect` and `InvertEffect` are, where each had one of its own; nothing to change in a game ## [20.16.0] (melonJS 2) - _2026-11-17_ From de2f8e85dcccf961c2aecd501c44d9ea2975bd5d Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 23:23:05 +0000 Subject: [PATCH 51/51] Changelog: the FlashEffect and TintPulseEffect entry, under Performance Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA4a7ZyjLBpbeEpFLu6 --- packages/melonjs/CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/melonjs/CHANGELOG.md b/packages/melonjs/CHANGELOG.md index 1d4e0dfb68..403c5e6d8e 100644 --- a/packages/melonjs/CHANGELOG.md +++ b/packages/melonjs/CHANGELOG.md @@ -13,6 +13,7 @@ ### Performance - Tiled: on the GPU, drawing an isometric tile layer takes about **90%** less of the main thread's time with 1200 tiles in view (0.68 to 0.07 ms a frame) and about **98%** less with 4000 (2.0 to 0.04 ms). Staggered and hexagonal maps gain the same - Tiled: for reference, orthogonal tile layers, on the GPU since 19.4, measure about **85%** less with 1000 tiles in view (0.62 to 0.09 ms) and about **97%** less with 3600 (1.9 to 0.06 ms) +- Effects: `FlashEffect` and `TintPulseEffect` are drawn by the `ColorMatrixEffect` shader, as `SepiaEffect`, `DesaturateEffect` and `InvertEffect` are: two fewer shaders to compile, and the pulse is computed once a frame rather than for every pixel. Nothing to change in a game ### Fixed - Tiled: a layer's offset in Tiled is applied: to a tile layer (where it is drawn and where `getTile()` looks), to the objects of an object layer, and to the tile layers inside a group. It was ignored @@ -36,7 +37,6 @@ - CI: fix the test job losing its browser page at random, and run the test suite in about half the time - Package: the npm package includes `CHANGELOG.md` and the license, which were left out, and its `sideEffects` field names the published bundle - Size: the engine is about 8% smaller to download (323 kB minified and gzipped, from 350 kB), as the comments in its shaders are no longer published -- Effects: `FlashEffect` and `TintPulseEffect` are drawn by the `ColorMatrixEffect` shader, as `SepiaEffect`, `DesaturateEffect` and `InvertEffect` are, where each had one of its own; nothing to change in a game ## [20.16.0] (melonJS 2) - _2026-11-17_