From 888c6682b02e39e50e4ad1fda2471bf6a780cc34 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 23:24:16 +0000 Subject: [PATCH 1/6] TextureAtlas: recognise TexturePacker / Aseprite JSON from other exporters An atlas whose meta.app is not a tool known by name is now identified from the structure of the file (meta.frameTags reads as Aseprite, frames with a frame rectangle as TexturePacker) instead of throwing, and the TexturePacker parser accepts the "JSON (Hash)" variant, frames keyed by name. Adds spritesheet.dev to the supported tools. Fixes #1915 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA1sfRfGDyxaPSzYMnN --- README.md | 2 + packages/melonjs/CHANGELOG.md | 2 + .../melonjs-sprites-and-animation/SKILL.md | 3 +- .../melonjs/src/loader/parsers/aseprite.js | 2 +- packages/melonjs/src/video/texture/atlas.js | 40 ++- .../src/video/texture/parser/texturepacker.js | 22 +- .../tests/texture-atlas-formats.spec.js | 326 ++++++++++++++++++ .../tests/texture-atlas-parsers.spec.js | 149 ++++++++ 8 files changed, 528 insertions(+), 18 deletions(-) create mode 100644 packages/melonjs/tests/texture-atlas-formats.spec.js diff --git a/README.md b/README.md index cbb9d217ef..7a5ac6866d 100644 --- a/README.md +++ b/README.md @@ -179,6 +179,8 @@ melonJS is supporting the below tools and frameworks natively or through our off [![Spine](https://github.com/melonjs/melonJS/assets/4033090/7a8d81b8-bc80-47bd-80dc-d9a054c78c96 "Spine")](http://esotericsoftware.com) [![aseprite](https://github.com/melonjs/melonJS/assets/4033090/65d19fef-2eba-461a-b925-cc2ad3bb270c "aseprite")](https://www.aseprite.org) +Any other tool that exports the TexturePacker ("JSON (Array)" or "JSON (Hash)") or Aseprite JSON layout works as well, such as [spritesheet.dev](https://spritesheet.dev/). + Tools integration and usage with melonJS is documented in our [Wiki](https://github.com/melonjs/melonJS/wiki#third-party-tools-usage). Getting Started diff --git a/packages/melonjs/CHANGELOG.md b/packages/melonjs/CHANGELOG.md index dd6ff25de0..bfd1caa9b7 100644 --- a/packages/melonjs/CHANGELOG.md +++ b/packages/melonjs/CHANGELOG.md @@ -14,6 +14,8 @@ - Levels: `registerObjectClass` and `registerObjectFactory` register the classes a level builds, whatever editor it comes from - Levels: `level.load` takes `objects`, to choose which objects of a level are built - Levels: an object built from a level carries the level's `id`, so `getChildByProp("id", id)` finds it +- `TextureAtlas`: an atlas from a tool it does not know by name (such as [spritesheet.dev](https://spritesheet.dev/)) loads when it has the TexturePacker or Aseprite JSON layout, instead of throwing `Unknown texture atlas format` +- `TextureAtlas`: TexturePacker's "JSON (Hash)" export is supported, as "JSON (Array)" is ### Deprecated - Levels: `registerTiledObjectClass` and `registerTiledObjectFactory`, for `registerObjectClass` and `registerObjectFactory` (the same functions; the old names keep working) diff --git a/packages/melonjs/skills/melonjs-sprites-and-animation/SKILL.md b/packages/melonjs/skills/melonjs-sprites-and-animation/SKILL.md index a108297d16..5a43103d96 100644 --- a/packages/melonjs/skills/melonjs-sprites-and-animation/SKILL.md +++ b/packages/melonjs/skills/melonjs-sprites-and-animation/SKILL.md @@ -129,8 +129,9 @@ many it kept. | source | how | |---|---| -| TexturePacker / Free Texture Packer JSON | `new TextureAtlas(loader.getJSON(name), loader.getImage(name))` | +| TexturePacker / Free Texture Packer JSON, "JSON (Array)" or "JSON (Hash)" | `new TextureAtlas(loader.getJSON(name), loader.getImage(name))` | | Aseprite **JSON export** | same as TexturePacker — the format is detected from `meta.app` | +| another tool writing either layout (spritesheet.dev, your own exporter) | same call. Since 20.18 an unknown `meta.app` is recognised from the file's structure: `meta.frameTags` reads as Aseprite, frames with a `frame` rectangle as TexturePacker. Before, it threw `Unknown texture atlas format` | | Aseprite **`.aseprite` / `.ase` binary** | loader type `"aseprite"`, which stores the composited image *and* a JSON sidecar under the one asset name | | ShoeBox | JSON export using the melonJS exporter settings file; same call as TexturePacker | | fixed-cell spritesheet | `new TextureAtlas({ framewidth, frameheight, anchorPoint }, loader.getImage(name))` | diff --git a/packages/melonjs/src/loader/parsers/aseprite.js b/packages/melonjs/src/loader/parsers/aseprite.js index 494672a92f..e99ad2379e 100644 --- a/packages/melonjs/src/loader/parsers/aseprite.js +++ b/packages/melonjs/src/loader/parsers/aseprite.js @@ -480,7 +480,7 @@ function composite(parsed) { /** * Build the JSON sidecar in the shape expected by parseAseprite() - * in src/video/texture/parser/aseprite.js — meta.app must include + * in src/video/texture/parser/aseprite.js — meta.app includes * "aseprite" so identifyFormat() picks the right route. * @ignore * @internal diff --git a/packages/melonjs/src/video/texture/atlas.js b/packages/melonjs/src/video/texture/atlas.js index 87d0ebe2bb..edd91df6ba 100644 --- a/packages/melonjs/src/video/texture/atlas.js +++ b/packages/melonjs/src/video/texture/atlas.js @@ -81,11 +81,18 @@ export function createAtlas( } /** - * return a string that identifies the texture atlas type + * return a string that identifies the texture atlas type: from the name of + * the tool in `meta.app` when it is a known one, else from the structure of + * the file, so that any exporter writing the TexturePacker or Aseprite JSON + * layout is accepted under its own name + * @param {object} atlas - the atlas description (with a `meta` object) + * @returns {string} "texturepacker", "shoebox", "aseprite" or "melonJS" * @ignore * @internal */ -export function identifyFormat(app) { +export function identifyFormat(atlas) { + const meta = atlas.meta; + const app = typeof meta.app === "string" ? meta.app : ""; if (app.includes("texturepacker") || app.includes("free-tex-packer")) { return "texturepacker"; } else if (app.includes("shoebox")) { @@ -94,18 +101,39 @@ export function identifyFormat(app) { return "aseprite"; } else if (app.includes("melonJS")) { return "melonJS"; - } else { - throw new Error("Unknown texture atlas format: " + app); } + + // an unknown tool: both parsers need the frames and the sheet size + const frames = atlas.frames; + if ( + typeof frames === "object" && + frames !== null && + typeof meta.size?.w === "number" && + typeof meta.size?.h === "number" + ) { + if (Array.isArray(meta.frameTags)) { + // animation tags are Aseprite's + return "aseprite"; + } + // frames as a list ("JSON (Array)") or keyed by name ("JSON (Hash)") + const first = Array.isArray(frames) ? frames[0] : Object.values(frames)[0]; + if (typeof first?.frame === "object" && first.frame !== null) { + return "texturepacker"; + } + } + + throw new Error("Unknown texture atlas format: " + meta.app); } /** * A Texture atlas class, currently supports :
- * - [TexturePacker]{@link http://www.codeandweb.com/texturepacker/} : through JSON export (standard and multipack texture atlas)
+ * - [TexturePacker]{@link http://www.codeandweb.com/texturepacker/} : through JSON export, "JSON (Array)" or "JSON (Hash)" (standard and multipack texture atlas)
* - [Free Texture Packer]{@link http://free-tex-packer.com/app/} : through JSON export (standard and multipack texture atlas)
* - [aseprite]{@link https://www.aseprite.org/} : through JSON export (standard and multipack texture atlas)
* - [ShoeBox]{@link http://renderhjs.net/shoebox/} : through JSON export using the * melonJS setting [file]{@link https://github.com/melonjs/melonJS/raw/master/media/shoebox_JSON_export.sbx}
+ * - any other tool that writes the TexturePacker or Aseprite JSON layout, such as [spritesheet.dev]{@link https://spritesheet.dev/} : the format is + * recognised from the structure of the file when `meta.app` is not one of the names above
* - Standard (fixed cell size) spritesheet : through a {framewidth:xx, frameheight:xx, anchorPoint:me.Vector2d} object * ); * @category Game Objects @@ -244,7 +272,7 @@ export class TextureAtlas extends Texture2d { const atlas = atlases[i]; if (typeof atlas.meta !== "undefined") { - this.format = identifyFormat(atlas.meta.app); + this.format = identifyFormat(atlas); this.repeat = atlas.meta.repeat || "no-repeat"; switch (this.format) { case "texturepacker": diff --git a/packages/melonjs/src/video/texture/parser/texturepacker.js b/packages/melonjs/src/video/texture/parser/texturepacker.js index b74547192c..226479245d 100644 --- a/packages/melonjs/src/video/texture/parser/texturepacker.js +++ b/packages/melonjs/src/video/texture/parser/texturepacker.js @@ -12,9 +12,16 @@ import { Vector2d } from "../../../math/vector2d.ts"; export function parseTexturePacker(data, textureAtlas) { const atlas = {}; - data.frames.forEach((frame) => { + // "JSON (Array)" lists the frames, each with its `filename`; + // "JSON (Hash)" keys them by that name + const frames = data.frames; + const isArray = Array.isArray(frames); + + Object.keys(frames).forEach((key) => { + const frame = frames[key]; // fix wrongly formatted JSON (e.g. last dummy object in ShoeBox) - if (frame.hasOwnProperty("filename")) { + if (!isArray || frame.hasOwnProperty("filename")) { + const name = isArray ? frame.filename : key; // Source coordinates const s = frame.frame; const trimmed = !!frame.trimmed; @@ -39,8 +46,8 @@ export function parseTexturePacker(data, textureAtlas) { originY = frame.sourceSize.h * frame.pivot.y - (trimmed ? trim.y : 0); } - atlas[frame.filename] = { - name: frame.filename, // frame name + atlas[name] = { + name: name, // frame name texture: data.meta.image || "default", // the source texture offset: new Vector2d(s.x, s.y), anchorPoint: hasTextureAnchorPoint @@ -53,12 +60,7 @@ export function parseTexturePacker(data, textureAtlas) { sourceSize: frame.sourceSize || { w: s.w, h: s.h }, angle: frame.rotated === true ? -ETA : 0, }; - textureAtlas.addUVs( - atlas, - frame.filename, - data.meta.size.w, - data.meta.size.h, - ); + textureAtlas.addUVs(atlas, name, data.meta.size.w, data.meta.size.h); } }); return atlas; diff --git a/packages/melonjs/tests/texture-atlas-formats.spec.js b/packages/melonjs/tests/texture-atlas-formats.spec.js new file mode 100644 index 0000000000..34fe45fb6a --- /dev/null +++ b/packages/melonjs/tests/texture-atlas-formats.spec.js @@ -0,0 +1,326 @@ +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { Application, boot, TextureAtlas, video } from "../src/index.js"; +import { grabFrame } from "./helpers/pixels.js"; + +/** + * Which parser reads an atlas, for every combination of the tool named in + * `meta.app` and the layout of the file (issue #1915). + * + * A known name decides alone, as it always did. An unknown name, or none, + * falls back to the structure: `meta.frameTags` is Aseprite's, frames with a + * `frame` rectangle are TexturePacker's, as a list ("JSON (Array)") or keyed + * by name ("JSON (Hash)"). + */ + +// two 16 × 16 frames side by side on a 32 × 16 sheet +const NAMES = ["a.png", "b.png"]; + +const entry = (index) => { + return { + frame: { x: index * 16, y: 0, w: 16, h: 16 }, + rotated: false, + trimmed: false, + spriteSourceSize: { x: 0, y: 0, w: 16, h: 16 }, + sourceSize: { w: 16, h: 16 }, + duration: 100 + index * 50, + }; +}; + +const arrayFrames = () => { + return NAMES.map((filename, index) => { + return { filename, ...entry(index) }; + }); +}; + +const hashFrames = () => { + return Object.fromEntries( + NAMES.map((filename, index) => { + return [filename, entry(index)]; + }), + ); +}; + +const frameTags = () => { + return [{ name: "blink", from: 0, to: 1, direction: "forward" }]; +}; + +const layouts = [ + { layout: "TexturePacker JSON (Array)", frames: arrayFrames, tags: false }, + { layout: "TexturePacker JSON (Hash)", frames: hashFrames, tags: false }, + { layout: "Aseprite JSON (Array)", frames: arrayFrames, tags: true }, + { layout: "Aseprite JSON (Hash)", frames: hashFrames, tags: true }, +]; + +// `parser` is what a known name selects; undefined leaves it to the structure +const apps = [ + { app: "https://www.codeandweb.com/texturepacker", parser: "texturepacker" }, + { app: "http://free-tex-packer.com", parser: "texturepacker" }, + { app: "https://www.aseprite.org/", parser: "aseprite" }, + { + app: "shoebox", + parser: "texturepacker", + format: "shoebox", + meta: { exporter: "melonJS" }, + }, + { app: "melonJS", parser: "texturepacker", format: "melonJS" }, + { app: "https://spritesheet.dev/" }, + { app: "https://example.com/my-packer" }, + { app: "" }, + { app: undefined }, +]; + +const makeAtlas = (app, layout, image = "sheet.png") => { + const meta = { + version: "1.0", + image, + format: "RGBA8888", + size: { w: 32, h: 16 }, + scale: "1", + ...app.meta, + }; + if (app.app !== undefined) { + meta.app = app.app; + } + if (layout.tags) { + meta.frameTags = frameTags(); + } + return { frames: layout.frames(), meta }; +}; + +const fakeImage = { width: 32, height: 16, src: "sheet.png" }; + +describe.each(apps)("an atlas whose meta.app is $app", (app) => { + describe.each(layouts)("in the $layout layout", (layout) => { + // by name when the name is known, else by structure + const parser = app.parser ?? (layout.tags ? "aseprite" : "texturepacker"); + // the Aseprite parser names the frames of a list by their position + const names = + parser === "aseprite" && Array.isArray(layout.frames()) + ? ["0", "1"] + : NAMES; + + const load = () => { + return new TextureAtlas(makeAtlas(app, layout), fakeImage, false); + }; + + it(`is read as ${app.format ?? parser}`, () => { + expect(load().format).toBe(app.format ?? parser); + }); + + it("holds every frame, at its rectangle", () => { + const atlas = load(); + expect(Object.keys(atlas.getAnimationSettings().atlasIndices)).toEqual( + names, + ); + names.forEach((name, index) => { + const region = atlas.getRegion(name); + expect(region.name).toBe(name); + expect(region.offset.x).toBe(index * 16); + expect(region.offset.y).toBe(0); + expect(region.width).toBe(16); + expect(region.height).toBe(16); + expect(region.angle).toBe(0); + expect(region.trimmed).toBe(false); + expect(Array.from(region.uvs)).toEqual([ + index / 2, + 0, + (index + 1) / 2, + 1, + ]); + }); + }); + + // the Aseprite parser, on a file that has tags + const tagged = parser === "aseprite" && layout.tags; + + it( + tagged + ? "carries the tagged animations, with each frame's duration" + : "carries no animation", + () => { + const anims = load().getAtlas().anims; + if (tagged) { + const blink = Object.values(anims)[0]; + expect(blink.name).toBe("blink"); + expect(blink.index).toEqual([ + { name: 0, delay: 100 }, + { name: 1, delay: 150 }, + ]); + } else { + // none at all, or the Aseprite parser's empty list + expect(Object.keys(anims ?? {})).toEqual([]); + } + }, + ); + }); +}); + +describe("an Aseprite export without tags, from an unknown tool", () => { + it.each([ + { form: "Array", frames: arrayFrames }, + { form: "Hash", frames: hashFrames }, + ])("$form: is read through the TexturePacker parser", ({ frames }) => { + const atlas = new TextureAtlas( + makeAtlas({ app: "https://spritesheet.dev/" }, { frames, tags: false }), + fakeImage, + false, + ); + expect(atlas.format).toBe("texturepacker"); + expect(atlas.getRegion("b.png").offset.x).toBe(16); + }); +}); + +describe("a multipack atlas from an unknown tool", () => { + it("holds the frames of every page, whatever the layout of each", () => { + const app = { app: "https://spritesheet.dev/" }; + const second = makeAtlas(app, layouts[1], "sheet-1.png"); + second.frames = { "c.png": entry(0), "d.png": entry(1) }; + const atlas = new TextureAtlas( + [makeAtlas(app, layouts[0], "sheet-0.png"), second], + fakeImage, + false, + ); + expect(atlas.getRegion("b.png").texture).toBe("sheet-0.png"); + expect(atlas.getRegion("d.png").texture).toBe("sheet-1.png"); + expect(atlas.getRegion("d.png").offset.x).toBe(16); + }); +}); + +describe("an atlas that is in no layout it reads", () => { + const unknown = { app: "https://example.com/my-packer" }; + + it.each([ + { + what: "frames without a frame rectangle", + change: (json) => { + json.frames = [{ filename: "a.png", x: 0, y: 0, w: 16, h: 16 }]; + }, + }, + { + what: "no frames", + change: (json) => { + delete json.frames; + }, + }, + { + what: "an empty list of frames", + change: (json) => { + json.frames = []; + }, + }, + { + what: "no sheet size", + change: (json) => { + delete json.meta.size; + }, + }, + { + what: "tags but no sheet size", + change: (json) => { + json.meta.frameTags = frameTags(); + delete json.meta.size; + }, + }, + ])("$what: throws, naming the tool", ({ change }) => { + const json = makeAtlas(unknown, layouts[0]); + change(json); + expect(() => { + return new TextureAtlas(json, fakeImage, false); + }).toThrow("Unknown texture atlas format: " + unknown.app); + }); + + it("ShoeBox still requires the melonJS exporter", () => { + expect(() => { + return new TextureAtlas( + makeAtlas({ app: "shoebox" }, layouts[0]), + fakeImage, + false, + ); + }).toThrow(/ShoeBox requires the JSON exporter/); + }); +}); + +/** + * Checked by drawing: a file from an unknown tool has to give, pixel for + * pixel, the picture the same file gives under a name the engine knows. + */ +const SIZE = 32; + +describe.each([ + { name: "WebGL", renderer: video.WEBGL }, + { name: "Canvas", renderer: video.CANVAS }, +])("drawing a frame of an atlas from an unknown tool, on $name", (backend) => { + let app; + let sheet; + + beforeAll(async () => { + boot(); + app = new Application(SIZE, SIZE, { + parent: "screen", + renderer: backend.renderer, + failIfMajorPerformanceCaveat: false, + antiAlias: false, + backgroundColor: "#000000", + }); + await app.init(); + + // a.png is red, b.png is green over blue + sheet = document.createElement("canvas"); + sheet.width = 32; + sheet.height = 16; + const s = sheet.getContext("2d"); + s.fillStyle = "#ff0000"; + s.fillRect(0, 0, 16, 16); + s.fillStyle = "#00ff00"; + s.fillRect(16, 0, 16, 8); + s.fillStyle = "#0000ff"; + s.fillRect(16, 8, 16, 8); + }); + + afterAll(() => { + app.destroy(); + }); + + /** the frame of this name (or position), drawn at (8, 8) */ + const picture = async (json, name) => { + const atlas = new TextureAtlas(json, sheet, false); + const sprite = atlas.createSpriteFromName(name); + sprite.anchorPoint.set(0, 0); + sprite.pos.set(8, 8); + app.world.addChild(sprite); + sprite.inViewport = true; + app.isDirty = true; + app.draw(); + const frame = grabFrame(app.renderer); + app.world.removeChildNow(sprite, true); + return (await frame).data; + }; + + const pixel = (data, x, y) => { + const o = (y * SIZE + x) * 4; + return Array.from(data.subarray(o, o + 3)); + }; + + it.each([ + { ...layouts[0], known: apps[0], name: "b.png" }, + { ...layouts[1], known: apps[0], name: "b.png" }, + { ...layouts[2], known: apps[2], name: "1" }, + { ...layouts[3], known: apps[2], name: "b.png" }, + ])("$layout: the picture a known tool's file gives", async (testCase) => { + const data = await picture( + makeAtlas({ app: "https://spritesheet.dev/" }, testCase), + testCase.name, + ); + // the second frame, the right way up, and nothing around it + expect(pixel(data, 12, 10)).toEqual([0, 255, 0]); + expect(pixel(data, 20, 20)).toEqual([0, 0, 255]); + expect(pixel(data, 4, 12)).toEqual([0, 0, 0]); + expect(pixel(data, 28, 12)).toEqual([0, 0, 0]); + + const reference = await picture( + makeAtlas(testCase.known, testCase), + testCase.name, + ); + expect(Array.from(data)).toEqual(Array.from(reference)); + }); +}); diff --git a/packages/melonjs/tests/texture-atlas-parsers.spec.js b/packages/melonjs/tests/texture-atlas-parsers.spec.js index 72ed5254ee..f803412ab5 100644 --- a/packages/melonjs/tests/texture-atlas-parsers.spec.js +++ b/packages/melonjs/tests/texture-atlas-parsers.spec.js @@ -231,3 +231,152 @@ describe("spritesheet parser on a non-divisible (padded) sheet", () => { expect(frame1.uvs[0]).toBeCloseTo(32 / 70); }); }); + +// issue #1915: a tool that writes the TexturePacker or Aseprite JSON layout +// under its own `meta.app` is recognised from the structure of the file +describe("atlas from an exporter unknown by name", () => { + const UNKNOWN_APP = "https://example.com/my-packer"; + + const packedFrame = (x, extra = {}) => { + return { + frame: { x, y: 0, w: 16, h: 16 }, + rotated: false, + trimmed: false, + spriteSourceSize: { x: 0, y: 0, w: 16, h: 16 }, + sourceSize: { w: 16, h: 16 }, + ...extra, + }; + }; + + const meta = (extra = {}) => { + return { + app: UNKNOWN_APP, + version: "1.0", + image: "sheet.png", + format: "RGBA8888", + size: { w: 32, h: 16 }, + scale: "1", + ...extra, + }; + }; + + it("loads a TexturePacker JSON (Array) file", () => { + const atlas = new TextureAtlas( + { + frames: [ + packedFrame(0, { filename: "a" }), + packedFrame(16, { filename: "b" }), + ], + meta: meta(), + }, + fakeImage(32, 16), + false, + ); + expect(atlas.format).toBe("texturepacker"); + const b = atlas.getRegion("b"); + expect(b.offset.x).toBe(16); + expect(b.width).toBe(16); + expect(Array.from(b.uvs)).toEqual([0.5, 0, 1, 1]); + }); + + it("loads a TexturePacker JSON (Hash) file", () => { + const atlas = new TextureAtlas( + { + frames: { a: packedFrame(0), b: packedFrame(16) }, + meta: meta(), + }, + fakeImage(32, 16), + false, + ); + expect(atlas.format).toBe("texturepacker"); + expect(atlas.getRegion("a").name).toBe("a"); + expect(Array.from(atlas.getRegion("b").uvs)).toEqual([0.5, 0, 1, 1]); + }); + + it("loads an Aseprite JSON file, with its animations", () => { + const json = makeAsepriteJSON(); + json.meta.app = UNKNOWN_APP; + const atlas = new TextureAtlas(json, fakeImage(128, 64), false); + expect(atlas.format).toBe("aseprite"); + expect(atlas.getRegion("hero 1.png").width).toBe(32); + const walk = Object.values(atlas.getAtlas().anims)[0]; + expect(walk.name).toBe("walk"); + expect(walk.index.length).toBe(3); + }); + + it("loads a file that has no meta.app at all", () => { + const atlas = new TextureAtlas( + { + frames: [packedFrame(0, { filename: "a" })], + meta: meta({ app: undefined }), + }, + fakeImage(32, 16), + false, + ); + expect(atlas.format).toBe("texturepacker"); + }); + + it("still throws when the structure is not one it reads", () => { + // no frame rectangles + expect(() => { + return new TextureAtlas( + { frames: [{ filename: "a", x: 0, y: 0 }], meta: meta() }, + fakeImage(32, 16), + false, + ); + }).toThrow("Unknown texture atlas format: " + UNKNOWN_APP); + // no sheet size + expect(() => { + return new TextureAtlas( + { + frames: [packedFrame(0, { filename: "a" })], + meta: meta({ size: undefined }), + }, + fakeImage(32, 16), + false, + ); + }).toThrow(/Unknown texture atlas format/); + // no frames + expect(() => { + return new TextureAtlas({ meta: meta() }, fakeImage(32, 16), false); + }).toThrow(/Unknown texture atlas format/); + }); +}); + +describe("TexturePacker JSON (Hash)", () => { + it("reads frames keyed by name, as the array form does", () => { + const entry = { + frame: { x: 10, y: 20, w: 28, h: 30 }, + rotated: true, + trimmed: true, + spriteSourceSize: { x: 2, y: 1, w: 28, h: 30 }, + sourceSize: { w: 32, h: 32 }, + pivot: { x: 0.5, y: 0.5 }, + }; + const meta = { + app: "https://www.codeandweb.com/texturepacker", + image: "sheet.png", + size: { w: 64, h: 64 }, + }; + const hash = new TextureAtlas( + { frames: { "hero.png": entry }, meta }, + fakeImage(64, 64), + false, + ).getRegion("hero.png"); + const array = new TextureAtlas( + { frames: [{ filename: "hero.png", ...entry }], meta }, + fakeImage(64, 64), + false, + ).getRegion("hero.png"); + + expect(hash.name).toBe("hero.png"); + expect(hash.angle).toBe(-ETA); + expect(hash.trim).toEqual({ x: 2, y: 1, w: 28, h: 30 }); + expect(hash.sourceSize).toEqual({ w: 32, h: 32 }); + expect(hash.offset.x).toBe(array.offset.x); + expect(hash.offset.y).toBe(array.offset.y); + expect(hash.anchorPoint.x).toBeCloseTo(array.anchorPoint.x); + expect(hash.anchorPoint.y).toBeCloseTo(array.anchorPoint.y); + expect(Array.from(hash.uvs)).toEqual(Array.from(array.uvs)); + }); +}); From d31877f7d1db2e355978bd731f076fe5a7eb1850 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 23:36:51 +0000 Subject: [PATCH 2/6] TextureAtlas: tighten format detection, share the frame parsing Follow-up to the review of the #1915 change: - an unknown tool's file is accepted only when every frame has its rectangle (and, in a list, its filename), checked before its tags, so a malformed file throws "Unknown texture atlas format" rather than a TypeError or loading empty - ShoeBox is matched whatever its case: the melonJS exporter writes "ShoeBox", which was refused - the TexturePacker and Aseprite parsers share one addFrame helper, and the constructor picks the parser once - the missing-image error names the image - tests: expectations spelled out per layout, malformed inputs, ShoeBox as exported, mixed multipack; the duplicate block is removed Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA1sfRfGDyxaPSzYMnN --- packages/melonjs/CHANGELOG.md | 1 + packages/melonjs/src/video/texture/atlas.js | 119 ++++++-------- .../src/video/texture/parser/aseprite.js | 44 +---- .../melonjs/src/video/texture/parser/frame.js | 56 +++++++ .../src/video/texture/parser/texturepacker.js | 63 ++----- .../tests/texture-atlas-formats.spec.js | 154 ++++++++++++++++-- .../tests/texture-atlas-parsers.spec.js | 143 +++------------- 7 files changed, 279 insertions(+), 301 deletions(-) create mode 100644 packages/melonjs/src/video/texture/parser/frame.js diff --git a/packages/melonjs/CHANGELOG.md b/packages/melonjs/CHANGELOG.md index bfd1caa9b7..6f142b6e78 100644 --- a/packages/melonjs/CHANGELOG.md +++ b/packages/melonjs/CHANGELOG.md @@ -24,6 +24,7 @@ - Loader: `loader.getTMX`, for `loader.getTileMap` (the same function) ### Fixed +- `TextureAtlas`: a ShoeBox atlas made with the melonJS exporter was refused with `Unknown texture atlas format: ShoeBox` - TypeScript: an asset's `data` accepts a parsed map object - Tile maps: a floating tile layer disappeared once the camera moved - Tile maps: two tilesets cut from one image at different tile sizes drew the same tiles diff --git a/packages/melonjs/src/video/texture/atlas.js b/packages/melonjs/src/video/texture/atlas.js index edd91df6ba..8eb6598797 100644 --- a/packages/melonjs/src/video/texture/atlas.js +++ b/packages/melonjs/src/video/texture/atlas.js @@ -95,7 +95,8 @@ export function identifyFormat(atlas) { const app = typeof meta.app === "string" ? meta.app : ""; if (app.includes("texturepacker") || app.includes("free-tex-packer")) { return "texturepacker"; - } else if (app.includes("shoebox")) { + } else if (app.toLowerCase().includes("shoebox")) { + // the melonJS exporter for ShoeBox writes "ShoeBox" return "shoebox"; } else if (app.includes("aseprite")) { return "aseprite"; @@ -103,7 +104,8 @@ export function identifyFormat(atlas) { return "melonJS"; } - // an unknown tool: both parsers need the frames and the sheet size + // an unknown tool: the file has to be one a parser reads in full, that + // is the sheet size and, for every frame, its rectangle const frames = atlas.frames; if ( typeof frames === "object" && @@ -111,13 +113,24 @@ export function identifyFormat(atlas) { typeof meta.size?.w === "number" && typeof meta.size?.h === "number" ) { - if (Array.isArray(meta.frameTags)) { + const entries = Object.values(frames); + const hasFrames = + entries.length > 0 && + entries.every((entry) => { + return typeof entry?.frame === "object" && entry.frame !== null; + }); + if (hasFrames && Array.isArray(meta.frameTags)) { // animation tags are Aseprite's return "aseprite"; } - // frames as a list ("JSON (Array)") or keyed by name ("JSON (Hash)") - const first = Array.isArray(frames) ? frames[0] : Object.values(frames)[0]; - if (typeof first?.frame === "object" && first.frame !== null) { + // frames keyed by name ("JSON (Hash)"), or a list of them + // ("JSON (Array)") that each carry their name + const isNamed = + !Array.isArray(frames) || + frames.every((entry) => { + return typeof entry.filename === "string"; + }); + if (hasFrames && isNamed) { return "texturepacker"; } } @@ -274,72 +287,40 @@ export class TextureAtlas extends Texture2d { if (typeof atlas.meta !== "undefined") { this.format = identifyFormat(atlas); this.repeat = atlas.meta.repeat || "no-repeat"; - switch (this.format) { - case "texturepacker": - case "aseprite": - // set the texture - if (typeof src === "undefined") { - // get the texture name from the atlas meta data - const image = getImage(atlas.meta.image); - if (!image) { - throw new Error("Atlas texture '" + image + "' not found"); - } - this.sources.set(atlas.meta.image, image); - } else { - this.sources.set( - atlas.meta.image || "default", - typeof src === "string" ? getImage(src) : src, - ); - } - // initialize the atlas - if (this.format === "texturepacker") { - this.atlases.set( - atlas.meta.image || "default", - parseTexturePacker(atlas, this), - ); - } else { - this.atlases.set( - atlas.meta.image || "default", - parseAseprite(atlas, this), - ); - } - break; - case "shoebox": - if ( - !atlas.meta.exporter || - !atlas.meta.exporter.includes("melonJS") - ) { - throw new Error( - "ShoeBox requires the JSON exporter : " + - "https://github.com/melonjs/melonJS/tree/master/media/shoebox_JSON_export.sbx", - ); - } - this.sources.set( - "default", - typeof src === "string" ? getImage(src) : src, - ); - // initialize the atlas - this.atlases.set( - atlas.meta.image || "default", - parseTexturePacker(atlas, this), - ); - break; - case "melonJS": - this.sources.set( - "default", - typeof src === "string" ? getImage(src) : src, - ); - // initialize the atlas - this.atlases.set( - atlas.meta.image || "default", - parseTexturePacker(atlas, this), - ); - break; - default: + if ( + this.format === "shoebox" && + (!atlas.meta.exporter || !atlas.meta.exporter.includes("melonJS")) + ) { + throw new Error( + "ShoeBox requires the JSON exporter : " + + "https://github.com/melonjs/melonJS/tree/master/media/shoebox_JSON_export.sbx", + ); + } + // set the texture + if (this.format === "shoebox" || this.format === "melonJS") { + this.sources.set( + "default", + typeof src === "string" ? getImage(src) : src, + ); + } else if (typeof src === "undefined") { + // get the texture name from the atlas meta data + const image = getImage(atlas.meta.image); + if (!image) { throw new Error( - "Unknown texture atlas format: " + atlas.meta.app, + "Atlas texture '" + atlas.meta.image + "' not found", ); + } + this.sources.set(atlas.meta.image, image); + } else { + this.sources.set( + atlas.meta.image || "default", + typeof src === "string" ? getImage(src) : src, + ); } + // initialize the atlas + const parse = + this.format === "aseprite" ? parseAseprite : parseTexturePacker; + this.atlases.set(atlas.meta.image || "default", parse(atlas, this)); } else { // a regular spritesheet if ( diff --git a/packages/melonjs/src/video/texture/parser/aseprite.js b/packages/melonjs/src/video/texture/parser/aseprite.js index 2e154c2d8a..c0c6bd3b5d 100644 --- a/packages/melonjs/src/video/texture/parser/aseprite.js +++ b/packages/melonjs/src/video/texture/parser/aseprite.js @@ -1,5 +1,4 @@ -import { ETA } from "../../../math/math.ts"; -import { Vector2d } from "../../../math/vector2d.ts"; +import { addFrame } from "./frame.js"; /** * parse the given data and return a corresponding atlas @@ -21,47 +20,10 @@ export function parseAseprite(data, textureAtlas) { // in aseprite's JSON export (hash and array forms alike), `trimmed`, // `spriteSourceSize`, `sourceSize`, `rotated`, `pivot` and `duration` // are SIBLINGS of the `frame` rect on each entry — same layout as - // TexturePacker's (see texturepacker.js) + // TexturePacker's (see frame.js) const entry = frames[name]; - const frame = entry.frame; - const trimmed = !!entry.trimmed; - - let trim; - - if (trimmed) { - trim = { - x: entry.spriteSourceSize.x, - y: entry.spriteSourceSize.y, - w: entry.spriteSourceSize.w, - h: entry.spriteSourceSize.h, - }; - } - - let originX; - let originY; - // Pixel-based offset origin from the top-left of the source frame - const hasTextureAnchorPoint = entry.sourceSize && entry.pivot; - if (hasTextureAnchorPoint) { - originX = entry.sourceSize.w * entry.pivot.x - (trimmed ? trim.x : 0); - originY = entry.sourceSize.h * entry.pivot.y - (trimmed ? trim.y : 0); - } - - atlas[name] = { - name: name, // frame name - texture: data.meta.image || "default", // the source texture - offset: new Vector2d(frame.x, frame.y), - anchorPoint: hasTextureAnchorPoint - ? new Vector2d(originX / frame.w, originY / frame.h) - : null, - trimmed: trimmed, - trim: trim, - width: frame.w, - height: frame.h, - sourceSize: entry.sourceSize || { w: frame.w, h: frame.h }, - angle: entry.rotated === true ? -ETA : 0, - }; + addFrame(atlas, name, entry, data, textureAtlas); frameDurations.push(entry.duration); - textureAtlas.addUVs(atlas, name, data.meta.size.w, data.meta.size.h); } const anims = {}; diff --git a/packages/melonjs/src/video/texture/parser/frame.js b/packages/melonjs/src/video/texture/parser/frame.js new file mode 100644 index 0000000000..7623ca6a7d --- /dev/null +++ b/packages/melonjs/src/video/texture/parser/frame.js @@ -0,0 +1,56 @@ +import { ETA } from "../../../math/math.ts"; +import { Vector2d } from "../../../math/vector2d.ts"; + +/** + * Add one frame of a TexturePacker or Aseprite JSON file to an atlas page. + * Both tools describe a frame the same way: a `frame` rectangle, with + * `trimmed`, `spriteSourceSize`, `sourceSize`, `rotated` and `pivot` beside it. + * @param {Object} atlas - the atlas page being built + * @param {string} name - the name the frame is stored under + * @param {Object} entry - the frame, as the file describes it + * @param {Object} data - atlas data information. See {@link loader.getJSON} + * @param {TextureAtlas} textureAtlas - the texture atlas class calling the parser + * @ignore + * @internal + */ +export function addFrame(atlas, name, entry, data, textureAtlas) { + // Source coordinates + const s = entry.frame; + const trimmed = !!entry.trimmed; + + let trim; + + if (trimmed) { + trim = { + x: entry.spriteSourceSize.x, + y: entry.spriteSourceSize.y, + w: entry.spriteSourceSize.w, + h: entry.spriteSourceSize.h, + }; + } + + let originX; + let originY; + // Pixel-based offset origin from the top-left of the source frame + const hasTextureAnchorPoint = entry.sourceSize && entry.pivot; + if (hasTextureAnchorPoint) { + originX = entry.sourceSize.w * entry.pivot.x - (trimmed ? trim.x : 0); + originY = entry.sourceSize.h * entry.pivot.y - (trimmed ? trim.y : 0); + } + + atlas[name] = { + name: name, // frame name + texture: data.meta.image || "default", // the source texture + offset: new Vector2d(s.x, s.y), + anchorPoint: hasTextureAnchorPoint + ? new Vector2d(originX / s.w, originY / s.h) + : null, + trimmed: trimmed, + trim: trim, + width: s.w, + height: s.h, + sourceSize: entry.sourceSize || { w: s.w, h: s.h }, + angle: entry.rotated === true ? -ETA : 0, + }; + textureAtlas.addUVs(atlas, name, data.meta.size.w, data.meta.size.h); +} diff --git a/packages/melonjs/src/video/texture/parser/texturepacker.js b/packages/melonjs/src/video/texture/parser/texturepacker.js index 226479245d..944c754937 100644 --- a/packages/melonjs/src/video/texture/parser/texturepacker.js +++ b/packages/melonjs/src/video/texture/parser/texturepacker.js @@ -1,5 +1,4 @@ -import { ETA } from "./../../../math/math.ts"; -import { Vector2d } from "../../../math/vector2d.ts"; +import { addFrame } from "./frame.js"; /** * parse the given data and return a corresponding atlas @@ -11,57 +10,21 @@ import { Vector2d } from "../../../math/vector2d.ts"; */ export function parseTexturePacker(data, textureAtlas) { const atlas = {}; - - // "JSON (Array)" lists the frames, each with its `filename`; - // "JSON (Hash)" keys them by that name const frames = data.frames; - const isArray = Array.isArray(frames); - - Object.keys(frames).forEach((key) => { - const frame = frames[key]; - // fix wrongly formatted JSON (e.g. last dummy object in ShoeBox) - if (!isArray || frame.hasOwnProperty("filename")) { - const name = isArray ? frame.filename : key; - // Source coordinates - const s = frame.frame; - const trimmed = !!frame.trimmed; - let trim; - - if (trimmed) { - trim = { - x: frame.spriteSourceSize.x, - y: frame.spriteSourceSize.y, - w: frame.spriteSourceSize.w, - h: frame.spriteSourceSize.h, - }; + if (Array.isArray(frames)) { + // "JSON (Array)": a list of frames, each with its `filename` + for (const frame of frames) { + // fix wrongly formatted JSON (e.g. last dummy object in ShoeBox) + if (frame.hasOwnProperty("filename")) { + addFrame(atlas, frame.filename, frame, data, textureAtlas); } - - let originX; - let originY; - // Pixel-based offset origin from the top-left of the source frame - const hasTextureAnchorPoint = frame.sourceSize && frame.pivot; - if (hasTextureAnchorPoint) { - originX = frame.sourceSize.w * frame.pivot.x - (trimmed ? trim.x : 0); - originY = frame.sourceSize.h * frame.pivot.y - (trimmed ? trim.y : 0); - } - - atlas[name] = { - name: name, // frame name - texture: data.meta.image || "default", // the source texture - offset: new Vector2d(s.x, s.y), - anchorPoint: hasTextureAnchorPoint - ? new Vector2d(originX / s.w, originY / s.h) - : null, - trimmed: trimmed, - trim: trim, - width: s.w, - height: s.h, - sourceSize: frame.sourceSize || { w: s.w, h: s.h }, - angle: frame.rotated === true ? -ETA : 0, - }; - textureAtlas.addUVs(atlas, name, data.meta.size.w, data.meta.size.h); } - }); + } else { + // "JSON (Hash)": the frames keyed by that name + for (const name of Object.keys(frames)) { + addFrame(atlas, name, frames[name], data, textureAtlas); + } + } return atlas; } diff --git a/packages/melonjs/tests/texture-atlas-formats.spec.js b/packages/melonjs/tests/texture-atlas-formats.spec.js index 34fe45fb6a..95e0802155 100644 --- a/packages/melonjs/tests/texture-atlas-formats.spec.js +++ b/packages/melonjs/tests/texture-atlas-formats.spec.js @@ -45,17 +45,45 @@ const frameTags = () => { }; const layouts = [ - { layout: "TexturePacker JSON (Array)", frames: arrayFrames, tags: false }, - { layout: "TexturePacker JSON (Hash)", frames: hashFrames, tags: false }, - { layout: "Aseprite JSON (Array)", frames: arrayFrames, tags: true }, - { layout: "Aseprite JSON (Hash)", frames: hashFrames, tags: true }, + { + layout: "TexturePacker JSON (Array)", + frames: arrayFrames, + tags: false, + byStructure: "texturepacker", + }, + { + layout: "TexturePacker JSON (Hash)", + frames: hashFrames, + tags: false, + byStructure: "texturepacker", + }, + { + layout: "Aseprite JSON (Array)", + frames: arrayFrames, + tags: true, + byStructure: "aseprite", + }, + { + layout: "Aseprite JSON (Hash)", + frames: hashFrames, + tags: true, + byStructure: "aseprite", + }, ]; -// `parser` is what a known name selects; undefined leaves it to the structure +// `parser` is what a known name selects whatever the layout; an unknown name +// leaves it to the structure, spelled out per layout in `byStructure` const apps = [ { app: "https://www.codeandweb.com/texturepacker", parser: "texturepacker" }, { app: "http://free-tex-packer.com", parser: "texturepacker" }, { app: "https://www.aseprite.org/", parser: "aseprite" }, + { + // as the melonJS exporter for ShoeBox writes it + app: "ShoeBox", + parser: "texturepacker", + format: "shoebox", + meta: { exporter: "melonJS" }, + }, { app: "shoebox", parser: "texturepacker", @@ -67,6 +95,8 @@ const apps = [ { app: "https://example.com/my-packer" }, { app: "" }, { app: undefined }, + // not a string + { app: 42 }, ]; const makeAtlas = (app, layout, image = "sheet.png") => { @@ -92,7 +122,7 @@ const fakeImage = { width: 32, height: 16, src: "sheet.png" }; describe.each(apps)("an atlas whose meta.app is $app", (app) => { describe.each(layouts)("in the $layout layout", (layout) => { // by name when the name is known, else by structure - const parser = app.parser ?? (layout.tags ? "aseprite" : "texturepacker"); + const parser = app.parser ?? layout.byStructure; // the Aseprite parser names the frames of a list by their position const names = parser === "aseprite" && Array.isArray(layout.frames()) @@ -155,21 +185,32 @@ describe.each(apps)("an atlas whose meta.app is $app", (app) => { }); }); -describe("an Aseprite export without tags, from an unknown tool", () => { - it.each([ - { form: "Array", frames: arrayFrames }, - { form: "Hash", frames: hashFrames }, - ])("$form: is read through the TexturePacker parser", ({ frames }) => { - const atlas = new TextureAtlas( - makeAtlas({ app: "https://spritesheet.dev/" }, { frames, tags: false }), - fakeImage, - false, - ); - expect(atlas.format).toBe("texturepacker"); +describe("an Aseprite export with an empty list of tags, from an unknown tool", () => { + it("is read as Aseprite, with no animation", () => { + const json = makeAtlas({ app: "https://spritesheet.dev/" }, layouts[3]); + json.meta.frameTags = []; + const atlas = new TextureAtlas(json, fakeImage, false); + expect(atlas.format).toBe("aseprite"); + expect(atlas.getAtlas().anims).toEqual({}); expect(atlas.getRegion("b.png").offset.x).toBe(16); }); }); +describe("a ShoeBox export, as the melonJS exporter writes it", () => { + it("leaves out the entry that closes its list of frames", () => { + const json = makeAtlas( + { app: "ShoeBox", meta: { exporter: "melonJS" } }, + layouts[0], + ); + json.frames.push({ EOL: "true" }); + const atlas = new TextureAtlas(json, fakeImage, false); + expect(atlas.format).toBe("shoebox"); + expect(Object.keys(atlas.getAnimationSettings().atlasIndices)).toEqual( + NAMES, + ); + }); +}); + describe("a multipack atlas from an unknown tool", () => { it("holds the frames of every page, whatever the layout of each", () => { const app = { app: "https://spritesheet.dev/" }; @@ -183,6 +224,28 @@ describe("a multipack atlas from an unknown tool", () => { expect(atlas.getRegion("b.png").texture).toBe("sheet-0.png"); expect(atlas.getRegion("d.png").texture).toBe("sheet-1.png"); expect(atlas.getRegion("d.png").offset.x).toBe(16); + expect(Array.from(atlas.sources.keys())).toEqual([ + "sheet-0.png", + "sheet-1.png", + ]); + }); + + it("reads each page by its own structure", () => { + const app = { app: "https://spritesheet.dev/" }; + const tagged = makeAtlas(app, layouts[3], "sheet-1.png"); + tagged.frames = { "c.png": entry(0), "d.png": entry(1) }; + const atlas = new TextureAtlas( + [makeAtlas(app, layouts[1], "sheet-0.png"), tagged], + fakeImage, + false, + ); + expect(atlas.getRegion("a.png").texture).toBe("sheet-0.png"); + expect(atlas.getRegion("c.png").texture).toBe("sheet-1.png"); + // only the tagged page carries animations + expect(atlas.getAtlas("sheet-0.png").anims).toBeUndefined(); + expect(Object.values(atlas.getAtlas("sheet-1.png").anims)[0].name).toBe( + "blink", + ); }); }); @@ -214,6 +277,51 @@ describe("an atlas that is in no layout it reads", () => { delete json.meta.size; }, }, + { + what: "a frame further down the list without a rectangle", + change: (json) => { + delete json.frames[1].frame; + }, + }, + { + what: "a frame further down the hash without a rectangle", + change: (json) => { + json.frames = { "a.png": entry(0), "b.png": { x: 16, y: 0 } }; + }, + }, + { + what: "a null frame", + change: (json) => { + json.frames = { "a.png": entry(0), "b.png": null }; + }, + }, + { + what: "a list of frames that have no filename", + change: (json) => { + json.frames = [{ name: "a.png", ...entry(0) }]; + }, + }, + { + what: "tags, and frames without a rectangle", + change: (json) => { + json.meta.frameTags = []; + json.frames = [{ filename: "a.png", x: 0, y: 0 }]; + }, + }, + { + what: "tags, and an empty list of frames", + change: (json) => { + json.meta.frameTags = []; + json.frames = []; + }, + }, + { + what: "tags that are not a list, and frames without a filename", + change: (json) => { + json.meta.frameTags = "blink"; + json.frames = [entry(0)]; + }, + }, { what: "tags but no sheet size", change: (json) => { @@ -229,10 +337,20 @@ describe("an atlas that is in no layout it reads", () => { }).toThrow("Unknown texture atlas format: " + unknown.app); }); + it("names the image it did not find, when none is passed", () => { + expect(() => { + return new TextureAtlas( + makeAtlas(unknown, layouts[1], "not-loaded.png"), + undefined, + false, + ); + }).toThrow("Atlas texture 'not-loaded.png' not found"); + }); + it("ShoeBox still requires the melonJS exporter", () => { expect(() => { return new TextureAtlas( - makeAtlas({ app: "shoebox" }, layouts[0]), + makeAtlas({ app: "ShoeBox" }, layouts[0]), fakeImage, false, ); diff --git a/packages/melonjs/tests/texture-atlas-parsers.spec.js b/packages/melonjs/tests/texture-atlas-parsers.spec.js index f803412ab5..0d69458644 100644 --- a/packages/melonjs/tests/texture-atlas-parsers.spec.js +++ b/packages/melonjs/tests/texture-atlas-parsers.spec.js @@ -232,119 +232,13 @@ describe("spritesheet parser on a non-divisible (padded) sheet", () => { }); }); -// issue #1915: a tool that writes the TexturePacker or Aseprite JSON layout -// under its own `meta.app` is recognised from the structure of the file -describe("atlas from an exporter unknown by name", () => { - const UNKNOWN_APP = "https://example.com/my-packer"; - - const packedFrame = (x, extra = {}) => { - return { - frame: { x, y: 0, w: 16, h: 16 }, - rotated: false, - trimmed: false, - spriteSourceSize: { x: 0, y: 0, w: 16, h: 16 }, - sourceSize: { w: 16, h: 16 }, - ...extra, - }; - }; - - const meta = (extra = {}) => { - return { - app: UNKNOWN_APP, - version: "1.0", - image: "sheet.png", - format: "RGBA8888", - size: { w: 32, h: 16 }, - scale: "1", - ...extra, - }; - }; - - it("loads a TexturePacker JSON (Array) file", () => { - const atlas = new TextureAtlas( - { - frames: [ - packedFrame(0, { filename: "a" }), - packedFrame(16, { filename: "b" }), - ], - meta: meta(), - }, - fakeImage(32, 16), - false, - ); - expect(atlas.format).toBe("texturepacker"); - const b = atlas.getRegion("b"); - expect(b.offset.x).toBe(16); - expect(b.width).toBe(16); - expect(Array.from(b.uvs)).toEqual([0.5, 0, 1, 1]); - }); - - it("loads a TexturePacker JSON (Hash) file", () => { - const atlas = new TextureAtlas( - { - frames: { a: packedFrame(0), b: packedFrame(16) }, - meta: meta(), - }, - fakeImage(32, 16), - false, - ); - expect(atlas.format).toBe("texturepacker"); - expect(atlas.getRegion("a").name).toBe("a"); - expect(Array.from(atlas.getRegion("b").uvs)).toEqual([0.5, 0, 1, 1]); - }); - - it("loads an Aseprite JSON file, with its animations", () => { - const json = makeAsepriteJSON(); - json.meta.app = UNKNOWN_APP; - const atlas = new TextureAtlas(json, fakeImage(128, 64), false); - expect(atlas.format).toBe("aseprite"); - expect(atlas.getRegion("hero 1.png").width).toBe(32); - const walk = Object.values(atlas.getAtlas().anims)[0]; - expect(walk.name).toBe("walk"); - expect(walk.index.length).toBe(3); - }); - - it("loads a file that has no meta.app at all", () => { - const atlas = new TextureAtlas( - { - frames: [packedFrame(0, { filename: "a" })], - meta: meta({ app: undefined }), - }, - fakeImage(32, 16), - false, - ); - expect(atlas.format).toBe("texturepacker"); - }); - - it("still throws when the structure is not one it reads", () => { - // no frame rectangles - expect(() => { - return new TextureAtlas( - { frames: [{ filename: "a", x: 0, y: 0 }], meta: meta() }, - fakeImage(32, 16), - false, - ); - }).toThrow("Unknown texture atlas format: " + UNKNOWN_APP); - // no sheet size - expect(() => { - return new TextureAtlas( - { - frames: [packedFrame(0, { filename: "a" })], - meta: meta({ size: undefined }), - }, - fakeImage(32, 16), - false, - ); - }).toThrow(/Unknown texture atlas format/); - // no frames - expect(() => { - return new TextureAtlas({ meta: meta() }, fakeImage(32, 16), false); - }).toThrow(/Unknown texture atlas format/); - }); -}); - -describe("TexturePacker JSON (Hash)", () => { - it("reads frames keyed by name, as the array form does", () => { +// issue #1915: TexturePacker's "JSON (Hash)" keys the frames by name, under a +// known tool name and an unknown one alike +describe.each([ + "https://www.codeandweb.com/texturepacker", + "https://spritesheet.dev/", +])("TexturePacker JSON (Hash), meta.app %s", (app) => { + it("gives the region the array form gives", () => { const entry = { frame: { x: 10, y: 20, w: 28, h: 30 }, rotated: true, @@ -353,11 +247,7 @@ describe("TexturePacker JSON (Hash)", () => { sourceSize: { w: 32, h: 32 }, pivot: { x: 0.5, y: 0.5 }, }; - const meta = { - app: "https://www.codeandweb.com/texturepacker", - image: "sheet.png", - size: { w: 64, h: 64 }, - }; + const meta = { app, image: "sheet.png", size: { w: 64, h: 64 } }; const hash = new TextureAtlas( { frames: { "hero.png": entry }, meta }, fakeImage(64, 64), @@ -369,14 +259,21 @@ describe("TexturePacker JSON (Hash)", () => { false, ).getRegion("hero.png"); + // what the file says, not only what the other form gives expect(hash.name).toBe("hero.png"); + expect(hash.texture).toBe("sheet.png"); + expect(hash.width).toBe(28); + expect(hash.height).toBe(30); + expect(hash.offset.x).toBe(10); + expect(hash.offset.y).toBe(20); expect(hash.angle).toBe(-ETA); + expect(hash.trimmed).toBe(true); expect(hash.trim).toEqual({ x: 2, y: 1, w: 28, h: 30 }); expect(hash.sourceSize).toEqual({ w: 32, h: 32 }); - expect(hash.offset.x).toBe(array.offset.x); - expect(hash.offset.y).toBe(array.offset.y); - expect(hash.anchorPoint.x).toBeCloseTo(array.anchorPoint.x); - expect(hash.anchorPoint.y).toBeCloseTo(array.anchorPoint.y); - expect(Array.from(hash.uvs)).toEqual(Array.from(array.uvs)); + // pivot at the centre of the 32 × 32 source, less the trim + expect(hash.anchorPoint.x).toBeCloseTo(14 / 28); + expect(hash.anchorPoint.y).toBeCloseTo(15 / 30); + // and the whole region, as the array form gives it + expect(hash).toEqual(array); }); }); From 34118c17f4e1d2b17194bfc16a5444480bfe2224 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 23:46:32 +0000 Subject: [PATCH 3/6] TextureAtlas tests: the image of an unknown tool's atlas, more malformed files Covers the branches the format specs did not reach: the image named by meta.image when none is passed, an image passed by name, a file that names none, and frames or a sheet size of the wrong type. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA1sfRfGDyxaPSzYMnN --- .../tests/texture-atlas-formats.spec.js | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/packages/melonjs/tests/texture-atlas-formats.spec.js b/packages/melonjs/tests/texture-atlas-formats.spec.js index 95e0802155..424dbd11f5 100644 --- a/packages/melonjs/tests/texture-atlas-formats.spec.js +++ b/packages/melonjs/tests/texture-atlas-formats.spec.js @@ -1,5 +1,6 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { Application, boot, TextureAtlas, video } from "../src/index.js"; +import { imgList } from "../src/loader/cache.js"; import { grabFrame } from "./helpers/pixels.js"; /** @@ -249,6 +250,52 @@ describe("a multipack atlas from an unknown tool", () => { }); }); +describe("the image of an atlas from an unknown tool", () => { + const app = { app: "https://spritesheet.dev/" }; + const loaded = { width: 32, height: 16, src: "loaded-sheet.png" }; + + beforeAll(() => { + imgList["loaded-sheet"] = loaded; + }); + + afterAll(() => { + delete imgList["loaded-sheet"]; + }); + + it.each(layouts)( + "$layout: is the one meta.image names, when none is passed", + (layout) => { + const atlas = new TextureAtlas( + makeAtlas(app, layout, "loaded-sheet.png"), + undefined, + false, + ); + expect(atlas.sources.get("loaded-sheet.png")).toBe(loaded); + expect(atlas.getTexture()).toBe(loaded); + }, + ); + + it.each(layouts)( + "$layout: is the loaded image of the name passed", + (layout) => { + const atlas = new TextureAtlas( + makeAtlas(app, layout, "sheet.png"), + "loaded-sheet", + false, + ); + expect(atlas.sources.get("sheet.png")).toBe(loaded); + }, + ); + + it('is stored as "default" when the file names none', () => { + const json = makeAtlas(app, layouts[1]); + delete json.meta.image; + const atlas = new TextureAtlas(json, fakeImage, false); + expect(atlas.sources.get("default")).toBe(fakeImage); + expect(atlas.getRegion("b.png").texture).toBe("default"); + }); +}); + describe("an atlas that is in no layout it reads", () => { const unknown = { app: "https://example.com/my-packer" }; @@ -277,6 +324,30 @@ describe("an atlas that is in no layout it reads", () => { delete json.meta.size; }, }, + { + what: "a sheet width but no height", + change: (json) => { + delete json.meta.size.h; + }, + }, + { + what: "a sheet size written as text", + change: (json) => { + json.meta.size = { w: "32", h: "16" }; + }, + }, + { + what: "null for frames", + change: (json) => { + json.frames = null; + }, + }, + { + what: "text for frames", + change: (json) => { + json.frames = "a.png"; + }, + }, { what: "a frame further down the list without a rectangle", change: (json) => { From 391124387201fd9ccf637ac1a57f321e09d05592 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 00:05:08 +0000 Subject: [PATCH 4/6] Sprites skill: symptom rows for atlas format errors Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA1sfRfGDyxaPSzYMnN --- packages/melonjs/skills/melonjs-sprites-and-animation/SKILL.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/melonjs/skills/melonjs-sprites-and-animation/SKILL.md b/packages/melonjs/skills/melonjs-sprites-and-animation/SKILL.md index 5a43103d96..7db557098f 100644 --- a/packages/melonjs/skills/melonjs-sprites-and-animation/SKILL.md +++ b/packages/melonjs/skills/melonjs-sprites-and-animation/SKILL.md @@ -238,6 +238,9 @@ Two consequences: | 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 | +| `Unknown texture atlas format: ` from `new TextureAtlas` | before 20.18, an atlas whose `meta.app` named a tool the engine did not know, even in the TexturePacker or Aseprite layout (and `ShoeBox`, matched in lowercase only); since 20.18, a file that is in neither layout: no `meta.size`, a frame with no `frame` rectangle, or a list of frames with no `filename` | +| `frames.forEach is not a function` from `new TextureAtlas` | before 20.18, a TexturePacker "JSON (Hash)" export; re-export as "JSON (Array)" or update | +| a frame of an Aseprite JSON export is not found by its name | exported as "Array": the frames are then named by their position (`"0"`, `"1"`…); export as "Hash" to keep the names | | 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 From f9dab86a107f36ffd9e44db89445f0e26dc0d6aa Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 00:06:47 +0000 Subject: [PATCH 5/6] Router skill and TextureAtlas example: atlases from any tool in the TexturePacker or Aseprite layout Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA1sfRfGDyxaPSzYMnN --- packages/melonjs/skills/melonjs/SKILL.md | 5 +++-- packages/melonjs/src/video/texture/atlas.js | 4 +++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/packages/melonjs/skills/melonjs/SKILL.md b/packages/melonjs/skills/melonjs/SKILL.md index 9a249535ad..cf68560e4b 100644 --- a/packages/melonjs/skills/melonjs/SKILL.md +++ b/packages/melonjs/skills/melonjs/SKILL.md @@ -131,7 +131,7 @@ what it is called here: | [melonjs-20-migration](../melonjs-20-migration/SKILL.md) | Code based on melonJS 19.x or earlier, or an API that "should exist" but doesn't — `video.init`, `Entity`, `renderable.shader =`. | | [melonjs-scenes-and-state](../melonjs-scenes-and-state/SKILL.md) | `Stage` subclasses, the state manager, transitions, pausing, the update loop, timers, tweens, saved data. | | [melonjs-renderables](../melonjs-renderables/SKILL.md) | Subclassing `Renderable`, custom `draw()`, draw order, anchors, `floating`, post effects on an object. | -| [melonjs-sprites-and-animation](../melonjs-sprites-and-animation/SKILL.md) | `Sprite`, frame animation, texture atlases (TexturePacker / Aseprite / ShoeBox), tint, flip, pooling. | +| [melonjs-sprites-and-animation](../melonjs-sprites-and-animation/SKILL.md) | `Sprite`, frame animation, texture atlases (TexturePacker / Aseprite / ShoeBox, or any tool exporting their JSON layout), tint, flip, pooling. | | [melonjs-input](../melonjs-input/SKILL.md) | Keyboard actions, pointer and touch handling, drag, gamepad, virtual controls (fixed or floating sticks and buttons, tap to act). | | [melonjs-physics](../melonjs-physics/SKILL.md) | Collision, bodies, movement, spatial queries, and the planck / matter / Rapier / Rapier 3D adapters. | | [melonjs-math](../melonjs-math/SKILL.md) | Vectors and matrices: what mutates, what allocates, and interpolating with lerp, slerp, damp or moveTowards. | @@ -272,7 +272,8 @@ check for: `UICheckbox` (a radio button with a `group`), `UISlider`, `ProgressBar`, `UISpriteElement`, keyboard and gamepad navigation between widgets once one has `focus()`, `NineSliceSprite`, `Draggable` / `DropTarget`, `BitmapText`. -- **Art:** `TextureAtlas` (TexturePacker, ShoeBox, Aseprite), +- **Art:** `TextureAtlas` (TexturePacker, ShoeBox, Aseprite, and any tool that + exports the TexturePacker or Aseprite JSON layout), `CanvasRenderTarget` for bake-once drawing, `NoiseTexture2d`. - **Game flow:** `state.transition()` (`"fade"`, `"mask"` or `"pixelate"`) between screens, with a mask shaped like an image or the player's own sprite diff --git a/packages/melonjs/src/video/texture/atlas.js b/packages/melonjs/src/video/texture/atlas.js index 8eb6598797..45e45cbfb5 100644 --- a/packages/melonjs/src/video/texture/atlas.js +++ b/packages/melonjs/src/video/texture/atlas.js @@ -166,7 +166,9 @@ export class TextureAtlas extends Texture2d { * @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 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 + * // create a texture atlas from a JSON Object: a TexturePacker + * // ("JSON (Array)" or "JSON (Hash)") or Aseprite export, or the same + * // layout written by any other tool * game.texture = new me.TextureAtlas( * me.loader.getJSON("texture") * ); From 0b1da4302b4a0961137a050885e6a66c87fc6986 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 00:15:26 +0000 Subject: [PATCH 6/6] README: Blender and other glTF tools in the tools section Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01JnzwA1sfRfGDyxaPSzYMnN --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 7a5ac6866d..bcca51e7de 100644 --- a/README.md +++ b/README.md @@ -181,6 +181,8 @@ melonJS is supporting the below tools and frameworks natively or through our off Any other tool that exports the TexturePacker ("JSON (Array)" or "JSON (Hash)") or Aseprite JSON layout works as well, such as [spritesheet.dev](https://spritesheet.dev/). +3D scenes come from [Blender](https://www.blender.org) or any other tool that exports glTF (`.glb` or `.gltf`), such as Maya, 3ds Max or Cinema 4D. + Tools integration and usage with melonJS is documented in our [Wiki](https://github.com/melonjs/melonJS/wiki#third-party-tools-usage). Getting Started