diff --git a/README.md b/README.md index cbb9d217ef..bcca51e7de 100644 --- a/README.md +++ b/README.md @@ -179,6 +179,10 @@ 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/). + +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 diff --git a/packages/melonjs/CHANGELOG.md b/packages/melonjs/CHANGELOG.md index dd6ff25de0..6f142b6e78 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) @@ -22,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/skills/melonjs-sprites-and-animation/SKILL.md b/packages/melonjs/skills/melonjs-sprites-and-animation/SKILL.md index a108297d16..7db557098f 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))` | @@ -237,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 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/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..45e45cbfb5 100644 --- a/packages/melonjs/src/video/texture/atlas.js +++ b/packages/melonjs/src/video/texture/atlas.js @@ -81,31 +81,72 @@ 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")) { + } else if (app.toLowerCase().includes("shoebox")) { + // the melonJS exporter for ShoeBox writes "ShoeBox" return "shoebox"; } else if (app.includes("aseprite")) { return "aseprite"; } else if (app.includes("melonJS")) { return "melonJS"; - } else { - throw new Error("Unknown texture atlas format: " + app); } + + // 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" && + frames !== null && + typeof meta.size?.w === "number" && + typeof meta.size?.h === "number" + ) { + 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 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"; + } + } + + 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 @@ -125,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") * ); @@ -244,74 +287,42 @@ 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": - 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 b74547192c..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,55 +10,21 @@ import { Vector2d } from "../../../math/vector2d.ts"; */ export function parseTexturePacker(data, textureAtlas) { const atlas = {}; + const frames = data.frames; - data.frames.forEach((frame) => { - // fix wrongly formatted JSON (e.g. last dummy object in ShoeBox) - if (frame.hasOwnProperty("filename")) { - // 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, - }; - } - - 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); + 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); } - - atlas[frame.filename] = { - name: frame.filename, // 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, - frame.filename, - 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 new file mode 100644 index 0000000000..424dbd11f5 --- /dev/null +++ b/packages/melonjs/tests/texture-atlas-formats.spec.js @@ -0,0 +1,515 @@ +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"; + +/** + * 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, + 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 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", + format: "shoebox", + meta: { exporter: "melonJS" }, + }, + { app: "melonJS", parser: "texturepacker", format: "melonJS" }, + { app: "https://spritesheet.dev/" }, + { app: "https://example.com/my-packer" }, + { app: "" }, + { app: undefined }, + // not a string + { app: 42 }, +]; + +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.byStructure; + // 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 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/" }; + 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); + 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", + ); + }); +}); + +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" }; + + 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: "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) => { + 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) => { + 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("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]), + 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..0d69458644 100644 --- a/packages/melonjs/tests/texture-atlas-parsers.spec.js +++ b/packages/melonjs/tests/texture-atlas-parsers.spec.js @@ -231,3 +231,49 @@ describe("spritesheet parser on a non-divisible (padded) sheet", () => { expect(frame1.uvs[0]).toBeCloseTo(32 / 70); }); }); + +// 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, + 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, 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"); + + // 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 }); + // 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); + }); +});