Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions packages/melonjs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 6 additions & 2 deletions packages/melonjs/src/level/tiled/TMXObject.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
32 changes: 18 additions & 14 deletions packages/melonjs/src/level/tiled/TMXTile.js
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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);

Expand Down
65 changes: 65 additions & 0 deletions packages/melonjs/src/level/tiled/TMXTileset.js
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -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}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
47 changes: 44 additions & 3 deletions packages/melonjs/src/level/tiled/renderer/TMXRenderer.js
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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);
}
}

Expand Down
84 changes: 84 additions & 0 deletions packages/melonjs/tests/tmxrenderer.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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]);
});
});
});

Expand Down Expand Up @@ -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", () => {
Expand Down
Loading
Loading