diff --git a/packages/melonjs/CHANGELOG.md b/packages/melonjs/CHANGELOG.md index 5e1965ce9a..5693060b3d 100644 --- a/packages/melonjs/CHANGELOG.md +++ b/packages/melonjs/CHANGELOG.md @@ -6,6 +6,12 @@ - TextureAtlas: drawing part of an image, a bitmap font glyph or a repeating pattern no longer adds a region to the atlas for every new source rectangle. Those regions piled up for as long as the atlas lived, and turned up among the frames an animation is built from ([#1281](https://github.com/melonjs/melonJS/issues/1281), thanks @snowyukitty) - TextureAtlas: on an atlas with pages of different sizes, a source rectangle drawn from one page no longer reuses the UVs worked out for the same rectangle on another (thanks @snowyukitty) - Tiled: objects on isometric maps are placed where Tiled draws them. Positions are measured in tile heights on both axes, which changes maps whose tiles are not 2:1, and tile objects are anchored at their bottom center, so a game that offset them to compensate should drop that offset (thanks @vtxe02023274) +- Tiled: a tile object resized in Tiled is drawn at its own size, its tile stretched to fill it, and collides at that size. Unless its tile came from an image collection, it was drawn and collided at the size of the tile (thanks @vtxe02023274) +- Tiled: a tile object from an image collection is drawn on its own box when it is resized or flipped in Tiled. A resized one was drawn above and to the left of it, and a flipped one a whole tile width to the right +- Tiled: tile objects are placed by their tileset's object alignment, so a tileset that anchors its objects at the top left, the center or any other point places them there. They were always anchored at the bottom left, or the bottom center on isometric maps +- Tiled: a rotated tile object turns about the point its tileset aligns, as in Tiled, which is its bottom left (bottom center on isometric maps) unless the tileset sets another. It turned about another point, so it was drawn and collided away from where Tiled shows it +- Tiled: a map with an animated tile object loads, and the object plays its animation. One from a tileset image threw "string parameters for addAnimation are not allowed for standard spritesheet based Texture", and one from an image collection threw a TypeError +- Tiled: in a tile layer, tiles from an image collection whose images are not all the same height each sit on the bottom of their cell, as in Tiled. Every tile was placed as if it were as tall as the tallest image of the collection ### Performance - Rendering: drawing a sprite, a glyph or a pattern computes its UVs from the image size instead of looking them up, with no string built and nothing allocated or kept. On the platformer, text and Jungle Rabbit examples a lookup took 34 to 58 ns and now takes 6 to 10, in Chrome and WebKit: 1 to 2% of a frame's CPU time on the text example, and too little to measure on the platformer diff --git a/packages/melonjs/src/level/tiled/TMXObject.js b/packages/melonjs/src/level/tiled/TMXObject.js index 62a8eeed09..50ffe8d523 100644 --- a/packages/melonjs/src/level/tiled/TMXObject.js +++ b/packages/melonjs/src/level/tiled/TMXObject.js @@ -216,8 +216,12 @@ export default class TMXObject { const tileset = tilesets.getTilesetByGid(this.gid); if (tileset.isCollection === false) { - this.width = this.framewidth = tileset.tilewidth; - this.height = this.frameheight = tileset.tileheight; + this.framewidth = tileset.tilewidth; + this.frameheight = tileset.tileheight; + // an object resized in Tiled keeps its size, and its tile is + // stretched to fill it; one saved without a size is the tile's + this.width ||= tileset.tilewidth; + this.height ||= tileset.tileheight; } this.tile = new Tile(this.x, this.y, this.gid, tileset); diff --git a/packages/melonjs/src/level/tiled/TMXTile.js b/packages/melonjs/src/level/tiled/TMXTile.js index 44ad245911..0896e0bd98 100644 --- a/packages/melonjs/src/level/tiled/TMXTile.js +++ b/packages/melonjs/src/level/tiled/TMXTile.js @@ -196,30 +196,23 @@ export default class Tile extends Bounds { const frameId = []; for (const frame of tileset.animations.get(localId).frames) { frameId.push(frame.tileid); + // named by position: the sprite's atlas holds the frames in + // this order, and a spritesheet atlas refuses string names frames.push({ - name: "" + frame.tileid, + name: frames.length, delay: frame.duration, }); } - renderable = tileset.texture.createAnimationFromName(frameId, settings); + renderable = tileset + .getAnimationTexture() + .createAnimationFromName(frameId, settings); renderable.addAnimation(localId, frames); renderable.setCurrentAnimation(localId); } else if (tileset.isCollection) { // collection tile — create a sprite from the tile image const image = tileset.getTileImage(this.tileId); - renderable = new Sprite(0, 0, { image }); + renderable = new Sprite(0, 0, { image, rotation: settings?.rotation }); renderable.anchorPoint.set(0, 0); - renderable.scale( - settings.width / this.width, - settings.height / this.height, - ); - if (settings.rotation !== undefined) { - renderable.anchorPoint.set(0.5, 0.5); - renderable.rotate(settings.rotation); - renderable.translate(settings.width / 2, settings.height / 2); - // clear rotation to prevent double-application by the caller - settings.rotation = undefined; - } } else { // regular tile — create a sprite from the tileset atlas renderable = tileset.texture.createSpriteFromName( @@ -229,6 +222,17 @@ export default class Tile extends Bounds { renderable.anchorPoint.set(0, 0); } + // stretch the tile to the object's size, as Tiled draws a resized + // tile object: after the rotation, which turns the stretched box, + // and before the flip, which turns the tile around its own center + if (settings?.width > 0 && settings.height > 0) { + const scaleX = settings.width / this.width; + const scaleY = settings.height / this.height; + if (scaleX !== 1 || scaleY !== 1) { + renderable.scale(scaleX, scaleY); + } + } + // apply any H/V/AD flip transforms this.setTileTransform(renderable.currentTransform); diff --git a/packages/melonjs/src/level/tiled/TMXTileset.js b/packages/melonjs/src/level/tiled/TMXTileset.js index d4cbc85b71..42060e9689 100644 --- a/packages/melonjs/src/level/tiled/TMXTileset.js +++ b/packages/melonjs/src/level/tiled/TMXTileset.js @@ -4,6 +4,8 @@ import { Matrix2d } from "../../math/matrix2d.ts"; import { Vector2d } from "../../math/vector2d.ts"; import timer from "../../system/timer.ts"; import { getBasename, getExtension } from "../../utils/file.ts"; +import { createCanvas } from "../../video/canvas_factory.js"; +import { TextureAtlas } from "../../video/texture/atlas.js"; import { buildFlipTransform } from "./TMXTile.js"; import { resolveEmbeddedImage } from "./TMXUtils.js"; @@ -134,6 +136,16 @@ export default class TMXTileset { */ this.fillmode = tileset.fillmode ?? "stretch"; + /** + * the point of a tile object from this tileset that sits at its + * position: "topleft", "top", "topright", "left", "center", "right", + * "bottomleft", "bottom" or "bottomright". "unspecified" means the + * bottom left, or the bottom center on an isometric map + * @type {string} + * @default "unspecified" + */ + this.objectalignment = tileset.objectalignment ?? "unspecified"; + /** * the map's tile grid width (used for tilerendersize="grid") * @type {number} @@ -513,6 +525,53 @@ export default class TMXTileset { return this.imageCollection.get(gid); } + /** + * the texture the sprite of an animated tile object is cut from: the + * tileset image, or for an image collection the images its animations + * show, painted side by side once and named by their tile id + * @returns {TextureAtlas} + * @ignore + * @internal + */ + getAnimationTexture() { + if (!this.isCollection) { + return this.texture; + } + if (this._animationTexture === undefined) { + const ids = new Set(); + for (const animation of this.animations.values()) { + for (const frame of animation.frames) { + ids.add(+frame.tileid); + } + } + let width = 0; + let height = 0; + for (const id of ids) { + const image = this.getTileImage(id + this.firstgid); + width += image.width; + height = Math.max(height, image.height); + } + const canvas = createCanvas(width, height); + const context = canvas.getContext("2d"); + const frames = []; + let x = 0; + for (const id of ids) { + const image = this.getTileImage(id + this.firstgid); + context.drawImage(image, x, 0); + frames.push({ + filename: "" + id, + frame: { x, y: 0, w: image.width, h: image.height }, + }); + x += image.width; + } + this._animationTexture = new TextureAtlas( + { meta: { app: "melonJS", size: { w: width, h: height } }, frames }, + canvas, + ); + } + return this._animationTexture; + } + /** * set the tile properties * @param {number} gid - global tile ID @@ -626,6 +685,9 @@ export default class TMXTileset { } else { dw = tmxTile.width; dh = tmxTile.height; + // bottom-align against tileset baseline (renderer uses + // tileset.tileheight, the tallest image of the collection) + dy += this.tileheight - dh; } } else { // spritesheet: use precomputed values @@ -730,6 +792,9 @@ export default class TMXTileset { } else { dw = tileWidth; dh = tileHeight; + // bottom-align against tileset baseline (renderer uses + // tileset.tileheight, the tallest image of the collection) + dy += this.tileheight - dh; } } else { // spritesheet: use precomputed values diff --git a/packages/melonjs/src/level/tiled/renderer/TMXIsometricRenderer.js b/packages/melonjs/src/level/tiled/renderer/TMXIsometricRenderer.js index ce4ae16407..c857a61ad3 100644 --- a/packages/melonjs/src/level/tiled/renderer/TMXIsometricRenderer.js +++ b/packages/melonjs/src/level/tiled/renderer/TMXIsometricRenderer.js @@ -92,11 +92,10 @@ export default class TMXIsometricRenderer extends TMXRenderer { obj.x = isoPos.x; obj.y = isoPos.y; - // tile objects are aligned to their bottom center on isometric maps, - // while melonJS places renderables from their top left + // unless their tileset says otherwise, tile objects are aligned to + // their bottom center on isometric maps if (typeof obj.gid === "number") { - obj.x -= obj.width / 2; - obj.y -= obj.height; + this.alignTileObject(obj, "bottom"); } vector2dPool.release(isoPos); diff --git a/packages/melonjs/src/level/tiled/renderer/TMXRenderer.js b/packages/melonjs/src/level/tiled/renderer/TMXRenderer.js index fc37482114..e83d77bc4d 100644 --- a/packages/melonjs/src/level/tiled/renderer/TMXRenderer.js +++ b/packages/melonjs/src/level/tiled/renderer/TMXRenderer.js @@ -1,6 +1,21 @@ import { Bounds, boundsPool } from "./../../../physics/bounds.ts"; import TMXLayer from "./../TMXLayer.js"; +// where each Tiled `objectalignment` puts a tile object's position, as a +// fraction of its width and height from its top left ("unspecified" is +// not listed: the renderer picks the orientation's default) +const OBJECT_ALIGNMENT = new Map([ + ["topleft", [0, 0]], + ["top", [0.5, 0]], + ["topright", [1, 0]], + ["left", [0, 0.5]], + ["center", [0.5, 0.5]], + ["right", [1, 0.5]], + ["bottomleft", [0, 1]], + ["bottom", [0.5, 1]], + ["bottomright", [1, 1]], +]); + /** * additional import for TypeScript * @import CanvasRenderer from "../../../video/canvas/canvas_renderer.js"; @@ -94,9 +109,35 @@ export default class TMXRenderer { adjustPosition(obj) { // only adjust position if obj.gid is defined if (typeof obj.gid === "number") { - // Tiled objects origin point is "bottom-left" in Tiled, - // "top-left" in melonJS - obj.y -= obj.height; + this.alignTileObject(obj, "bottomleft"); + } + } + + /** + * move a tile object from the point Tiled anchors it at to its top left, + * where melonJS places renderables. The point is the tileset's + * `objectalignment`, or `fallback` when the tileset leaves it unspecified + * @param {object} obj - a TMX Object with x, y, width, height and rotation properties + * @param {string} fallback - the alignment Tiled uses for this orientation + * @ignore + * @internal + */ + alignTileObject(obj, fallback) { + const offset = + OBJECT_ALIGNMENT.get(obj.tile?.tileset.objectalignment) ?? + OBJECT_ALIGNMENT.get(fallback); + const ax = offset[0] !== 0 ? obj.width * offset[0] : 0; + const ay = offset[1] !== 0 ? obj.height * offset[1] : 0; + obj.x -= ax; + obj.y -= ay; + // Tiled turns a tile object about that point, while its sprite and + // body turn about their top left: move the top left to where turning + // about the point leaves it + if (obj.rotation) { + const cos = Math.cos(obj.rotation); + const sin = Math.sin(obj.rotation); + obj.x += ax - (ax * cos - ay * sin); + obj.y += ay - (ax * sin + ay * cos); } } diff --git a/packages/melonjs/tests/tmxrenderer.spec.js b/packages/melonjs/tests/tmxrenderer.spec.js index 737aca3819..af42434560 100644 --- a/packages/melonjs/tests/tmxrenderer.spec.js +++ b/packages/melonjs/tests/tmxrenderer.spec.js @@ -162,6 +162,57 @@ describe("TMX Renderers", () => { expect(obj.x).toBeCloseTo(445); expect(obj.y).toBeCloseTo(68); }); + + it("should align tile objects by their tileset's objectalignment", () => { + // the same object projects to (465, 108), the point its + // tileset's alignment puts on the map + const place = (objectalignment) => { + const obj = { + gid: 2, + x: 162, + y: 54, + width: 40, + height: 40, + tile: { tileset: { objectalignment } }, + }; + iso.adjustPosition(obj); + return [obj.x, obj.y]; + }; + expect(place("topleft")).toEqual([465, 108]); + expect(place("center")).toEqual([445, 88]); + expect(place("bottomright")).toEqual([425, 68]); + // unspecified, or a value Tiled does not know, is the bottom center + expect(place("unspecified")).toEqual([445, 68]); + expect(place("middle")).toEqual([445, 68]); + }); + + it("should turn a rotated tile object about the point its tileset aligns", () => { + // melonJS turns the sprite and body about their top left, so that + // corner must sit where Tiled's turn about (465, 108) leaves it + const place = (objectalignment, degrees) => { + const obj = { + gid: 2, + x: 162, + y: 54, + width: 40, + height: 40, + rotation: (degrees * Math.PI) / 180, + tile: { tileset: { objectalignment } }, + }; + iso.adjustPosition(obj); + return [obj.x, obj.y].map((v) => { + return Math.round(v * 1e6) / 1e6; + }); + }; + // the bottom center: (-20, -40) from the anchor turns to (40, -20) + expect(place("unspecified", 90)).toEqual([505, 88]); + // the center: (-20, -20) turns to (20, -20) + expect(place("center", 90)).toEqual([485, 88]); + // the top left is the anchor: it does not move + expect(place("topleft", 90)).toEqual([465, 108]); + // half a turn: (-20, -40) turns to (20, 40) + expect(place("unspecified", 180)).toEqual([485, 148]); + }); }); }); @@ -345,6 +396,39 @@ describe("TMX Renderers", () => { expect(spy.calls[0].dw).toBeCloseTo(16); expect(spy.calls[0].dh).toBeCloseTo(16); }); + + it("should sit collection tiles of different heights on the cell's bottom", () => { + // the tileset's tileheight is its tallest image (64): the short + // one must not be drawn as if it were that tall + fakeImage("short", 48, 32); + fakeImage("tall", 48, 64); + const ts = makeTileset( + { + tileheight: 64, + tilecount: 2, + columns: 0, + image: undefined, + tiles: [ + { id: 0, image: "short.png" }, + { id: 1, image: "tall.png" }, + ], + }, + 32, + 32, + ); + expect(ts.isCollection).toEqual(true); + const ortho = new TMXOrthogonalRenderer(mockMap()); + for (const gid of [1, 2]) { + const spy = spyRenderer(); + ortho.drawTile(spy, 0, 0, new Tile(0, 0, gid, ts)); + ortho.drawTileRaw(spy, 0, 0, gid, 0, ts); + for (const { dy, dh } of spy.calls) { + // the bottom of the first row of 32px cells + expect(dy + dh, `gid ${gid}`).toEqual(32); + } + expect(spy.calls.length).toEqual(2); + } + }); }); describe("TMXIsometricRenderer.drawTile", () => { diff --git a/packages/melonjs/tests/tmxtilemap.spec.js b/packages/melonjs/tests/tmxtilemap.spec.js index 607437ee0d..d3a871e92d 100644 --- a/packages/melonjs/tests/tmxtilemap.spec.js +++ b/packages/melonjs/tests/tmxtilemap.spec.js @@ -1318,6 +1318,232 @@ describe("TMXTileMap", () => { }); }); + describe("getObjects: tile object size and alignment, as Tiled draws them", () => { + // one tile object at (64, 96) over the 32x32 test tiles + function tileObject(object, tileset = {}) { + const map = new TMXTileMap("test", { + ...tileObjectMap, + tilesets: [{ ...tilesetData, ...tileset }], + layers: [ + { + type: "objectgroup", + name: "TileObjects", + opacity: 1, + visible: true, + objects: [ + { id: 300, name: "", type: "", gid: 1, x: 64, y: 96, ...object }, + ], + }, + ], + }); + return map.getObjects(true)[0]; + } + + it("draws a tile object resized in Tiled at its own size, with a body to match", () => { + const obj = tileObject({ width: 64, height: 48 }); + expect(obj.getBounds().width).toBeCloseTo(64); + expect(obj.getBounds().height).toBeCloseTo(48); + // anchored at its bottom left: Tiled's y is the bottom of the 48px box + expect([obj.pos.x, obj.pos.y]).toEqual([64, 48]); + const body = obj.bodyDef.shapes[0].getBounds(); + expect([body.width, body.height]).toEqual([64, 48]); + }); + + it("draws a tile object at the tile's size when it has that size or none", () => { + for (const size of [{ width: 32, height: 32 }, {}]) { + const obj = tileObject(size); + expect(obj.getBounds().width).toBeCloseTo(32); + expect(obj.getBounds().height).toBeCloseTo(32); + expect([obj.pos.x, obj.pos.y]).toEqual([64, 64]); + const body = obj.bodyDef.shapes[0].getBounds(); + expect([body.width, body.height]).toEqual([32, 32]); + } + }); + + it("stretches a flipped tile object without moving it off its box", () => { + // gid with the horizontal flip bit: flipped around the tile's own + // center, then stretched, it covers the same box as unflipped. + // Stretched first, then flipped, it would sit 32px to the left + const plain = tileObject({ width: 64, height: 48 }).getBounds(); + const flipped = tileObject({ + gid: (0x80000000 | 1) >>> 0, + width: 64, + height: 48, + }).getBounds(); + expect(flipped.left).toBeCloseTo(plain.left); + expect(flipped.top).toBeCloseTo(plain.top); + expect(flipped.width).toBeCloseTo(64); + expect(flipped.height).toBeCloseTo(48); + }); + + it("keeps a resized or flipped image-collection tile on its box", () => { + // a collection tile is its own 32x48 image. Scaled or flipped about + // a centered anchor, it would sit off the box: a quarter of the + // lost size up and left, or a whole width to the right + const image = fakeImage("tallblock", 32, 48); + const collection = { + name: "blocks", + tilewidth: 32, + tileheight: 48, + tilecount: 1, + columns: 0, + image: undefined, + tiles: [{ id: 0, image: "tallblock.png" }], + }; + for (const object of [ + { width: 16, height: 24 }, + { width: 48, height: 36 }, + { gid: (0x80000000 | 1) >>> 0, width: 32, height: 48 }, + { gid: (0x40000000 | 1) >>> 0, width: 16, height: 24 }, + ]) { + const obj = tileObject(object, collection); + expect(obj.image).toBe(image); + // the world does this on its first update + const bounds = obj.updateBounds(); + const box = [64, 96 - object.height, object.width, object.height]; + [bounds.left, bounds.top, bounds.width, bounds.height].forEach( + (value, i) => { + expect(value, JSON.stringify(object)).toBeCloseTo(box[i]); + }, + ); + } + }); + + it("turns a rotated tile object about its anchor, sprite and body alike", () => { + // [object, the box Tiled draws it in]: Tiled turns a tile object + // about the point its tileset aligns, here the bottom left (64, 96) + const tallblock = { + name: "blocks", + tilewidth: 32, + tileheight: 48, + tilecount: 1, + columns: 0, + image: undefined, + tiles: [{ id: 0, image: "tallblock.png" }], + }; + fakeImage("tallblock", 32, 48); + const cases = [ + // a quarter turn: the box hangs below and right of the corner + [{ width: 32, height: 32, rotation: 90 }, {}, [64, 96, 32, 32]], + // half a turn: it hangs below and left of it + [{ width: 64, height: 48, rotation: 180 }, {}, [0, 96, 64, 48]], + // a collection tile, stretched and turned + [{ width: 32, height: 48, rotation: 90 }, tallblock, [64, 96, 48, 32]], + // centered by its tileset: it turns about its own center + [ + { width: 64, height: 32, rotation: 90 }, + { objectalignment: "center" }, + [48, 64, 32, 64], + ], + ]; + for (const [object, tileset, box] of cases) { + const obj = tileObject(object, tileset); + // the world does this on its first update + const drawn = obj.updateBounds(); + const shape = obj.bodyDef.shapes[0].getBounds(); + const body = [ + obj.pos.x + shape.left, + obj.pos.y + shape.top, + shape.width, + shape.height, + ]; + const label = JSON.stringify(object); + [drawn.left, drawn.top, drawn.width, drawn.height].forEach((v, i) => { + expect(v, label + " drawn").toBeCloseTo(box[i]); + }); + body.forEach((v, i) => { + expect(v, label + " body").toBeCloseTo(box[i]); + }); + } + }); + + it("loads an animated tile object and shows its frames in order", () => { + // frames 0 then 3 of the 2x2 test tiles: by position, not by id + const obj = tileObject( + { width: 32, height: 32 }, + { + tiles: [ + { + id: 0, + animation: [ + { tileid: 0, duration: 100 }, + { tileid: 3, duration: 100 }, + ], + }, + ], + }, + ); + expect(obj.current.length).toEqual(2); + expect([obj.current.offset.x, obj.current.offset.y]).toEqual([0, 0]); + obj.setAnimationFrame(1); + expect([obj.current.offset.x, obj.current.offset.y]).toEqual([32, 32]); + }); + + it("loads an animated image-collection tile object and shows each image", () => { + // two 32x48 images, red then blue: the second frame must show blue + for (const [name, colour] of [ + ["redblock", "#ff0000"], + ["blueblock", "#0000ff"], + ]) { + const context = fakeImage(name, 32, 48).getContext("2d"); + context.fillStyle = colour; + context.fillRect(0, 0, 32, 48); + } + const obj = tileObject( + { width: 32, height: 48 }, + { + name: "animblocks", + tilewidth: 32, + tileheight: 48, + tilecount: 2, + columns: 0, + image: undefined, + tiles: [ + { + id: 0, + image: "redblock.png", + animation: [ + { tileid: 0, duration: 100 }, + { tileid: 1, duration: 100 }, + ], + }, + { id: 1, image: "blueblock.png" }, + ], + }, + ); + const pixel = () => { + const { x, y } = obj.current.offset; + return Array.from( + obj.image.getContext("2d").getImageData(x + 1, y + 1, 1, 1).data, + ); + }; + expect(obj.current.length).toEqual(2); + expect(pixel()).toEqual([255, 0, 0, 255]); + obj.setAnimationFrame(1); + expect(pixel()).toEqual([0, 0, 255, 255]); + }); + + it("places a tile object by its tileset's objectalignment", () => { + // [x, y] of the top left of a 64x48 object whose anchor is at (64, 96) + const expected = { + unspecified: [64, 48], + topleft: [64, 96], + top: [32, 96], + topright: [0, 96], + left: [64, 72], + center: [32, 72], + right: [0, 72], + bottomleft: [64, 48], + bottom: [32, 48], + bottomright: [0, 48], + }; + for (const [objectalignment, position] of Object.entries(expected)) { + const obj = tileObject({ width: 64, height: 48 }, { objectalignment }); + expect([obj.pos.x, obj.pos.y], objectalignment).toEqual(position); + } + }); + }); + // --------------------------------------------------------------- // TMXLayer passthrough // ---------------------------------------------------------------