diff --git a/packages/melonjs/CHANGELOG.md b/packages/melonjs/CHANGELOG.md index 975c26cae3..d6ccc7d55e 100644 --- a/packages/melonjs/CHANGELOG.md +++ b/packages/melonjs/CHANGELOG.md @@ -32,6 +32,10 @@ - Tiled: a frame drawn right after a level loaded could show its layers back to front - Tiled: a `renderMode` property on a tile layer was ignored - Tiled: each level load leaked a viewport-resize handler +- Tiled: a map with an object layer, an image layer or another group inside a group layer failed to load +- Tiled: the layers of a group of three or more were drawn over the map layers that follow the group; a layer after a group now takes the depth that follows the group's last layer +- Tiled: a group layer's tint is applied to the tile layers inside it +- `ImageLayer`: a layer that does not repeat on an axis smeared its edge pixels across the view on WebGL, and a picture larger than the view was cut off as the camera moved over it ## [20.17.0] (melonJS 2) - _2026-11-22_ diff --git a/packages/melonjs/skills/melonjs-tilemaps/SKILL.md b/packages/melonjs/skills/melonjs-tilemaps/SKILL.md index 2884289637..c0cfa1def8 100644 --- a/packages/melonjs/skills/melonjs-tilemaps/SKILL.md +++ b/packages/melonjs/skills/melonjs-tilemaps/SKILL.md @@ -95,7 +95,7 @@ option and resolve the same value they return — so `if (level.next())` becomes `if (await level.next({ async: true }))`. Running out of levels reports `false` either way rather than throwing. `level.getCurrentLevelId()` and `level.levelCount()` round out the namespace. `flatten: false` wraps each Tiled -object group in its own `Container` named after the group. +object layer and group layer in its own `Container` named after it. ## Spawning entities from Tiled objects @@ -371,10 +371,18 @@ board.getTile(pointer.x, pointer.y); // still the tile under the pointer The other layers follow their offset in Tiled too: an image layer is placed by it, an object layer's objects are created that far from where they were drawn -(collision shapes with them), and a group layer's offset moves the tile layers -inside it, on top of their own. A group can only hold tile layers: with an -object layer, an image layer or another group inside a group, the map fails -to load. +(collision shapes with them), and a group layer's offset moves the layers +inside it, on top of their own. + +A group layer holds layers of any kind: tile layers, object layers, image +layers and other groups (object layers, image layers and nested groups since +20.18). As in Tiled, the group gives the layers inside it its offset, its +opacity, its parallax factor, its blend mode, and its tint where a layer has +none of its own. Every layer takes a depth (`pos.z`) of its own in Tiled's +order, the ones inside a group included, so the layer that follows a group +draws over everything in the group. With `flatten: false`, a group is a +`Container` named after it, holding its tile and image layers, and a +container for each object layer or group inside it. The map's own custom properties (Map → Map Properties in Tiled) are set on the map object, which `level.getCurrentLevel()` returns once it is loaded: a @@ -568,7 +576,9 @@ the point it belongs with, such as `door.pos.y - dust.pos.y`. ## Image layers `ImageLayer` gives parallax backgrounds with a ratio per axis, set in Tiled or in -code. Repeat behaviour matches Tiled's. +code. Repeat behaviour matches Tiled's: `repeat` (the default in code), +`repeat-x`, `repeat-y`, or `no-repeat` for a picture drawn once, where the +layer is. ## Compressed maps need a plugin @@ -962,7 +972,9 @@ layer into the offscreen-bake path instead. | thin lines between tiles on the Canvas renderer, with smoothing on | filtering blends in the next tile of the tileset or its spacing, which a canvas cannot prevent: set `antiAlias: false`, or `preRender` the layer. WebGL and WebGPU keep each tile to itself | | a tile layer given an offset in Tiled (a roof nudged up, a shadow shifted) is drawn where the others are, or the objects of an object layer with an offset are not where Tiled shows them | before 20.17 only image layers followed their offset; tile layers (and their `pos`), object layers and group layers ignored it: update | | after updating to 20.17 a tile layer, or the objects of an object layer, sit away from where they did | the layer (or the group it is in) has an offset in Tiled that was ignored until then, and now moves it as in the editor: clear the layer's Offset in Tiled if it was not meant | -| the map fails to load with a group layer in it | the group holds an object layer, an image layer or another group: a group can only hold tile layers. Move those layers out of the group | +| the map fails to load with a group layer in it (`Cannot read properties of undefined (reading 'length')`) | before 20.18 a group could only hold tile layers: an object layer, an image layer or another group inside it broke the load. Update, or move those layers out of the group | +| a layer of the map is hidden under the layers of the group before it | before 20.18 a group of three or more layers took depths the next layers of the map took too: update. Layers after a group now have a higher `pos.z` than they had | +| an image layer set not to repeat fills the view with streaks of its edge colors on WebGL, or a backdrop larger than the screen is cut off as the camera moves | before 20.18 an axis that does not repeat was drawn over the view's size, not the picture's: update | | a map smaller than the screen (centred by `level.load`) had the tops of its tall tiles cut on WebGL or WebGPU | before 20.17 a layer read the camera's view as if it stood at the world's origin, and so did a layer in a container the game had moved: update | | the tops of tall tiles vanish when the map itself scrolls out of view | before 20.17 a layer was skipped once its grid left the view, though tiles larger than a cell (or moved by a `tileoffset`) still reached in: update | | an orthogonal layer warns `tiles larger than the grid, of more than one tileset in a layer` | tiles larger than a cell overlap, and the shader path keeps their order within one tileset: put each tileset's large tiles on a layer of their own (trees apart from the ground they stand on) | diff --git a/packages/melonjs/src/level/tiled/TMXGroup.js b/packages/melonjs/src/level/tiled/TMXGroup.js index 5bb742863c..38853172d9 100644 --- a/packages/melonjs/src/level/tiled/TMXGroup.js +++ b/packages/melonjs/src/level/tiled/TMXGroup.js @@ -1,5 +1,6 @@ import { clamp } from "../../math/math.ts"; import { setLayerScrolling } from "../tilemap/layer.js"; +import { readImageLayer } from "./TMXImageLayer.js"; import TMXLayer from "./TMXLayer.js"; import TMXObject from "./TMXObject.js"; import { @@ -10,13 +11,23 @@ import { } from "./TMXUtils.js"; /** - * object group definition as defined in Tiled. + * An object layer or a group layer of a Tiled map: the objects of the first, + * and for the second the layers it holds, each read as what it is: tile + * layers, image layers, object layers and other groups. A group gives the + * layers inside it its offset, its opacity, its tint, its blend mode and its + * parallax factor, on top of their own, as in Tiled. * (group definition is translated into the virtual `app.world` using `me.Container`) * @ignore * @internal */ export default class TMXGroup { - constructor(map, data, z) { + /** + * @param {object} map - the map + * @param {object} data - the layer, as Tiled saves it + * @param {number} z - the layer's depth: its objects', or its first layer's + * @param {TMXGroup} [parent] - the group layer this one is in + */ + constructor(map, data, z, parent) { /** * group name * @type {string} @@ -36,10 +47,10 @@ export default class TMXGroup { this.height = data.height || 0; /** - * tint color + * tint color: the layer's own, or else the one of the group it is in * @type {string} */ - this.tintcolor = data.tintcolor; + this.tintcolor = data.tintcolor ?? parent?.tintcolor; /** * the group class @@ -54,8 +65,10 @@ export default class TMXGroup { this.z = z; /** - * group objects list definition - * @see {@link TMXObject} + * what the layer holds, in Tiled's order: the objects of an object + * layer ({@link TMXObject}), and for a group layer its tile layers + * and image layers, built, and a `TMXGroup` for each object layer or + * group inside it * @type {object[]} */ this.objects = []; @@ -64,14 +77,18 @@ export default class TMXGroup { this.opacity = visible === true ? clamp(+data.opacity || 1.0, 0.0, 1.0) : 0; /** - * group blend mode (Tiled 1.12+) + * group blend mode (Tiled 1.12+): the layer's own, or else the one + * of the group it is in * @type {string} */ this.blendMode = tiledBlendMode(data.mode); + if (this.blendMode === "normal" && parent !== undefined) { + this.blendMode = parent.blendMode; + } /** * the layer's horizontal offset in Tiled, in pixels: an object layer - * moves its objects by it, a group layer the tile layers inside it + * moves its objects by it, a group layer the layers inside it * @type {number} */ this.offsetx = +data.offsetx || 0; @@ -82,9 +99,28 @@ export default class TMXGroup { */ this.offsety = +data.offsety || 0; + /** + * how far the layer is moved in all, across and down: its own + * offset and those of the groups it is in + * @type {number} + */ + this.shiftx = this.offsetx + (parent?.shiftx ?? 0); + this.shifty = this.offsety + (parent?.shifty ?? 0); + + /** + * the layer's parallax factor, across and down: its own, times + * those of the groups it is in + * @type {number} + */ + this.factorx = tiledParallaxFactor(data.parallaxx) * (parent?.factorx ?? 1); + this.factory = tiledParallaxFactor(data.parallaxy) * (parent?.factory ?? 1); + // check if we have any user-defined properties applyTMXProperties(this, data); + // the depth of the next layer read: each takes one, in Tiled's order + let next = z; + // parse all child objects/layers if (data.objects) { const objects = data.objects; @@ -93,50 +129,123 @@ export default class TMXGroup { const object = new TMXObject(map, objects[i], z); // Moved on the screen, so once the object stands where its // map puts it (an isometric map projects it) - object.x += this.offsetx; - object.y += this.offsety; + object.x += this.shiftx; + object.y += this.shifty; this.objects.push(object); } + next = z + 1; } if (data.layers) { const layers = data.layers; for (let i = 0, len = layers.length; i < len; i++) { - const layer = new TMXLayer( - map, - layers[i], - map.tilewidth, - map.tileheight, - map.orientation, - map.tilesets, - z, - ); - z++; - // the group's offset, on top of the layer's own - layer.pos.x += this.offsetx; - layer.pos.y += this.offsety; - // and its parallax factor, times the layer's own (Tiled's - // factor, or the layer's `ratio` property); the origin - // follows, unless the layer gave its own - const scrolling = tiledParallax( - map, - tiledParallaxFactor(data.parallaxx) * layer.ratio.x, - tiledParallaxFactor(data.parallaxy) * layer.ratio.y, - ); - setLayerScrolling( - layer, - layer._parallaxOriginGiven === true - ? { ratio: scrolling.ratio } - : scrolling, - ); - // set a renderer - layer.setRenderer(map.getRenderer()); - // resize container accordingly - this.width = Math.max(this.width, layer.width); - this.height = Math.max(this.height, layer.height); - this.objects.push(layer); + const child = layers[i]; + switch (child.type) { + case "tilelayer": + this.objects.push(this.readTileLayer(map, child, next++)); + break; + + case "imagelayer": + this.objects.push(this.readImageLayer(map, child, next++)); + break; + + case "objectgroup": + case "group": { + const group = new TMXGroup(map, child, next, this); + next = group.zEnd; + // resize container accordingly + this.width = Math.max(this.width, group.width); + this.height = Math.max(this.height, group.height); + this.objects.push(group); + break; + } + + default: + break; + } } } + + /** + * the depth that follows the layer: past its last layer's, for a + * group layer + * @type {number} + */ + this.zEnd = Math.max(next, z + 1); + } + + /** + * a tile layer of the group, with what the group gives it + * @param {object} map - the map + * @param {object} data - the tile layer, as Tiled saves it + * @param {number} z - its depth + * @returns {TMXLayer} the layer + * @ignore + */ + readTileLayer(map, data, z) { + const layer = new TMXLayer( + map, + data, + map.tilewidth, + map.tileheight, + map.orientation, + map.tilesets, + z, + ); + // the group's offset, on top of the layer's own + layer.pos.x += this.shiftx; + layer.pos.y += this.shifty; + // its parallax factor, times the layer's own (Tiled's factor, or + // the layer's `ratio` property); the origin follows, unless the + // layer gave its own + const scrolling = tiledParallax( + map, + this.factorx * layer.ratio.x, + this.factory * layer.ratio.y, + ); + setLayerScrolling( + layer, + layer._parallaxOriginGiven === true + ? { ratio: scrolling.ratio } + : scrolling, + ); + // and its tint, when the layer has none of its own + if ( + typeof data.tintcolor !== "string" && + typeof this.tintcolor === "string" + ) { + layer.tint.parseHex(this.tintcolor, true); + } + // set a renderer + layer.setRenderer(map.getRenderer()); + // resize container accordingly + this.width = Math.max(this.width, layer.width); + this.height = Math.max(this.height, layer.height); + return layer; + } + + /** + * an image layer of the group, with what the group gives it + * @param {object} map - the map + * @param {object} data - the image layer, as Tiled saves it + * @param {number} z - its depth + * @returns {object} the layer + * @ignore + */ + readImageLayer(map, data, z) { + // (a copy: the map's data is left as it is, to be read again) + return readImageLayer( + map, + { + ...data, + offsetx: +(data.offsetx ?? data.x ?? 0) + this.shiftx, + offsety: +(data.offsety ?? data.y ?? 0) + this.shifty, + parallaxx: this.factorx * tiledParallaxFactor(data.parallaxx), + parallaxy: this.factory * tiledParallaxFactor(data.parallaxy), + tintcolor: data.tintcolor ?? this.tintcolor, + }, + z, + ); } /** diff --git a/packages/melonjs/src/level/tiled/TMXImageLayer.js b/packages/melonjs/src/level/tiled/TMXImageLayer.js new file mode 100644 index 0000000000..f7aa67acf7 --- /dev/null +++ b/packages/melonjs/src/level/tiled/TMXImageLayer.js @@ -0,0 +1,92 @@ +import { getImage } from "../../loader/loader.js"; +import { vector2dPool } from "../../math/vector2d.ts"; +import ImageLayer from "../../renderable/imagelayer.js"; +import { + applyTMXProperties, + applyTransparentColor, + parseTintColor, + resolveEmbeddedImage, + tiledBlendMode, + tiledParallaxFactor, +} from "./TMXUtils.js"; + +/** + * @import TileMap from "./TileMap.js"; + */ + +/** + * Build the image layer a Tiled map describes: at the map's top level, or + * inside a group layer (which then gives it its own offset, parallax factor + * and tint on top: see TMXGroup). + * @param {TileMap} map - the map + * @param {object} data - the layer, as Tiled saves it + * @param {number} z - the layer's depth + * @returns {ImageLayer} the layer + * @ignore + * @internal + */ +export function readImageLayer(map, data, z) { + // resolve embedded JSON image data if present + resolveEmbeddedImage(data); + + // the layer's custom values, read into an object of their own: the + // map's data is left as it is, to be read again on the next load + const properties = {}; + applyTMXProperties(properties, data); + + // derive repeat mode: legacy custom "repeat" property takes precedence + // (for backward compatibility), then Tiled 1.8+ native repeatx/repeaty + const repX = data.repeatx === true || data.repeatx === "1"; + const repY = data.repeaty === true || data.repeaty === "1"; + let repeat = properties.repeat; + if (typeof repeat === "undefined" && (repX || repY)) { + if (repX && repY) { + repeat = "repeat"; + } else if (repX) { + repeat = "repeat-x"; + } else { + repeat = "repeat-y"; + } + } + + // Tiled 1.8+ parallax origin (map-level, baked into layer offset) + const pox = +(map.data.parallaxoriginx ?? 0); + const poy = +(map.data.parallaxoriginy ?? 0); + const ratioX = tiledParallaxFactor(data.parallaxx); + const ratioY = tiledParallaxFactor(data.parallaxy); + const ox = +(data.offsetx ?? data.x ?? 0) + pox * ratioX; + const oy = +(data.offsety ?? data.y ?? 0) + poy * ratioY; + + // create the layer + const imageLayer = new ImageLayer( + ox, + oy, + Object.assign( + { + name: data.name, + // its transparent color applied, when Tiled gives one + image: + typeof data.transparentcolor === "string" + ? (applyTransparentColor( + getImage(data.image), + data.transparentcolor, + ) ?? data.image) + : data.image, + ratio: vector2dPool.get(ratioX, ratioY), + tint: parseTintColor(data.tintcolor), + z: z, + repeat: repeat, + }, + properties, + ), + ); + + // set some additional flags + const visible = data.visible ?? true; + imageLayer.setOpacity(visible ? +data.opacity : 0); + + // layer blend mode (Tiled 1.12+) + imageLayer.blendMode = tiledBlendMode(data.mode); + + return imageLayer; +} diff --git a/packages/melonjs/src/level/tiled/TileMap.js b/packages/melonjs/src/level/tiled/TileMap.js index 4ec9fd4d9c..806637c0af 100644 --- a/packages/melonjs/src/level/tiled/TileMap.js +++ b/packages/melonjs/src/level/tiled/TileMap.js @@ -23,6 +23,7 @@ import { usesSpritesheet, } from "./spritefusion.ts"; import TMXGroup from "./TMXGroup.js"; +import { readImageLayer } from "./TMXImageLayer.js"; import TMXLayer from "./TMXLayer.js"; import TMXTileset from "./TMXTileset.js"; @@ -35,12 +36,8 @@ import TMXTileset from "./TMXTileset.js"; import { applyObjectOpacity, applyTMXProperties, - applyTransparentColor, parseTintColor, propagateBlendMode, - resolveEmbeddedImage, - tiledBlendMode, - tiledParallaxFactor, } from "./TMXUtils.js"; /** @@ -102,77 +99,6 @@ function readLayer(map, data, z) { ); } -/** - * read the Image Layer Data - * @ignore - * @internal - */ -function readImageLayer(map, data, z) { - // resolve embedded JSON image data if present - resolveEmbeddedImage(data); - - // the layer's custom values, read into an object of their own: the - // map's data is left as it is, to be read again on the next load - const properties = {}; - applyTMXProperties(properties, data); - - // derive repeat mode: legacy custom "repeat" property takes precedence - // (for backward compatibility), then Tiled 1.8+ native repeatx/repeaty - const repX = data.repeatx === true || data.repeatx === "1"; - const repY = data.repeaty === true || data.repeaty === "1"; - let repeat = properties.repeat; - if (typeof repeat === "undefined" && (repX || repY)) { - if (repX && repY) { - repeat = "repeat"; - } else if (repX) { - repeat = "repeat-x"; - } else { - repeat = "repeat-y"; - } - } - - // Tiled 1.8+ parallax origin (map-level, baked into layer offset) - const pox = +(map.data.parallaxoriginx ?? 0); - const poy = +(map.data.parallaxoriginy ?? 0); - const ratioX = tiledParallaxFactor(data.parallaxx); - const ratioY = tiledParallaxFactor(data.parallaxy); - const ox = +(data.offsetx ?? data.x ?? 0) + pox * ratioX; - const oy = +(data.offsety ?? data.y ?? 0) + poy * ratioY; - - // create the layer - const imageLayer = new ImageLayer( - ox, - oy, - Object.assign( - { - name: data.name, - // its transparent color applied, when Tiled gives one - image: - typeof data.transparentcolor === "string" - ? (applyTransparentColor( - getImage(data.image), - data.transparentcolor, - ) ?? data.image) - : data.image, - ratio: vector2dPool.get(ratioX, ratioY), - tint: parseTintColor(data.tintcolor), - z: z, - repeat: repeat, - }, - properties, - ), - ); - - // set some additional flags - const visible = data.visible ?? true; - imageLayer.setOpacity(visible ? +data.opacity : 0); - - // layer blend mode (Tiled 1.12+) - imageLayer.blendMode = tiledBlendMode(data.mode); - - return imageLayer; -} - /** * read the tileset Data * @ignore @@ -207,6 +133,139 @@ function colliderWalls(map, layer) { return tileLayerWalls(layer, map); } +/** + * Build what an object layer or a group layer of the map holds: the objects + * of an object layer, and for a group layer its tile layers, its image + * layers, and the object layers and groups inside it, each built the same + * way. + * @param {TileMap} map - the map + * @param {TMXGroup} group - the object layer or group layer + * @param {boolean} [flatten=true] - hand everything to `add` as it is built; + * when false, a `Container` is made for the layer, and for each layer of + * objects and each group inside it + * @param {boolean|Function} [wanted=true] - the objects to build + * @param {number} opacity - what the groups around this one fade it by, for + * when no container of theirs does it + * @param {(object: Renderable) => void} add - takes what is built + * @ignore + * @internal + */ +function buildGroup(map, group, flatten, wanted, opacity, add) { + // check if this is the collision shape group + const isCollisionGroup = isCollisionLayerName(group.name); + // with no container to carry the group's opacity, what it holds does + const faded = opacity * group.opacity; + let targetContainer; + let put = add; + + if (flatten === false) { + // create a new container + targetContainer = new Container(0, 0, map.width, map.height); + + // tiled uses 0,0 by default + targetContainer.anchorPoint.set(0, 0); + + // set additional properties + targetContainer.name = group.name; + targetContainer.pos.z = group.z; + targetContainer.setOpacity(group.opacity); + targetContainer.blendMode = group.blendMode; + + // disable auto-sort and auto-depth + targetContainer.autoSort = false; + targetContainer.autoDepth = false; + + put = (object) => { + targetContainer.addChild(object); + }; + } + + // iterate through the group and add all objects into their + // corresponding target Container + for (let o = 0; o < group.objects.length; o++) { + const settings = group.objects[o]; + + // a layer of objects, or a group, inside a group layer + if (settings instanceof TMXGroup) { + buildGroup(map, settings, flatten, wanted, faded, put); + continue; + } + + // A tile layer or an image layer of a group layer is listed with + // the group's objects: it is a layer, already built, and is added + // whatever the choice of objects + const isLayer = + settings instanceof TMXLayer || settings instanceof ImageLayer; + + // An object the game does not want is left out + if (!isLayer && !isObjectWanted(wanted, settings)) { + continue; + } + + // Tiled uses 0,0 by default + if (typeof settings.anchorPoint === "undefined") { + settings.anchorPoint = { x: 0, y: 0 }; + } + // convert to melonJS renderable argument name + if (!isLayer && typeof settings.tintcolor !== "undefined") { + settings.tint = parseTintColor(settings.tintcolor); + } + + // instantiate the object based on its type + const obj = isLayer ? settings : createLevelObject(settings, map); + + // an unnamed object of a collision group is a wall of the world + if (isCollisionGroup && !isLayer && !settings.name) { + markWorldShape(obj); + } + + // apply per-object opacity and visibility (a layer has its own) + if (obj.isRenderable === true && !isLayer) { + if (!settings.visible) { + obj.setOpacity(0); + if ( + typeof obj.renderable !== "undefined" && + obj.renderable.isRenderable === true + ) { + obj.renderable.setOpacity(0); + } + } else if (settings.opacity < 1) { + applyObjectOpacity(obj, settings.opacity); + } + } + + // the layers the cameras draw it on, from a custom property + if (typeof settings.visibilityLayer === "number") { + obj.visibilityLayer = settings.visibilityLayer; + } + + // propagate group blend mode to child objects + propagateBlendMode(obj, group.blendMode); + + // apply group opacity when flattened + if (flatten !== false && obj.isRenderable === true) { + applyObjectOpacity(obj, faded); + } + put(obj); + + // a solid tile layer of a group layer comes with its walls + for (const wall of colliderWalls(map, settings)) { + put(wall); + } + } + + // if we created a new container with children + if (flatten === false && targetContainer.getChildren().length > 0) { + // re-enable auto-sort and auto-depth + targetContainer.autoSort = true; + targetContainer.autoDepth = true; + + // add our container where its layer is: the world, or the + // container of the group it is in + add(targetContainer); + } +} + /** * read the object group Data * @ignore @@ -592,9 +651,13 @@ export default class TileMap { break; case "objectgroup": - case "group": - this.objectGroups.push(readObjectGroup(this, layer, zOrder++)); + case "group": { + // a group layer takes a depth for each layer inside it + const group = readObjectGroup(this, layer, zOrder); + zOrder = group.zEnd; + this.objectGroups.push(group); break; + } default: break; @@ -709,119 +772,14 @@ export default class TileMap { */ getObjects(flatten, wanted) { const objects = []; - let targetContainer; // parse the map for objects this.readMapObjects(this.data); for (let g = 0; g < this.objectGroups.length; g++) { - const group = this.objectGroups[g]; - - // check if this is the collision shape group - const isCollisionGroup = isCollisionLayerName(group.name); - - if (flatten === false) { - // create a new container - targetContainer = new Container(0, 0, this.width, this.height); - - // tiled uses 0,0 by default - targetContainer.anchorPoint.set(0, 0); - - // set additional properties - targetContainer.name = group.name; - targetContainer.pos.z = group.z; - targetContainer.setOpacity(group.opacity); - targetContainer.blendMode = group.blendMode; - - // disable auto-sort and auto-depth - targetContainer.autoSort = false; - targetContainer.autoDepth = false; - } - - // iterate through the group and add all objects into their - // corresponding target Container - for (let o = 0; o < group.objects.length; o++) { - const settings = group.objects[o]; - - // An object the game does not want is left out. A tile layer - // of a group layer is listed with the group's objects: it is - // a layer, and is added whatever the choice of objects - if ( - !(settings instanceof TMXLayer) && - !isObjectWanted(wanted, settings) - ) { - continue; - } - - // Tiled uses 0,0 by default - if (typeof settings.anchorPoint === "undefined") { - settings.anchorPoint = { x: 0, y: 0 }; - } - // convert to melonJS renderable argument name - if (typeof settings.tintcolor !== "undefined") { - settings.tint = parseTintColor(settings.tintcolor); - } - - // instantiate the object based on its type - const obj = createLevelObject(settings, this); - - // an unnamed object of a collision group is a wall of the world - if (isCollisionGroup && !settings.name) { - markWorldShape(obj); - } - - // apply per-object opacity and visibility (skip TMXLayer) - if (obj.isRenderable === true && !(settings instanceof TMXLayer)) { - if (!settings.visible) { - obj.setOpacity(0); - if ( - typeof obj.renderable !== "undefined" && - obj.renderable.isRenderable === true - ) { - obj.renderable.setOpacity(0); - } - } else if (settings.opacity < 1) { - applyObjectOpacity(obj, settings.opacity); - } - } - - // the layers the cameras draw it on, from a custom property - if (typeof settings.visibilityLayer === "number") { - obj.visibilityLayer = settings.visibilityLayer; - } - - // propagate group blend mode to child objects - propagateBlendMode(obj, group.blendMode); - - if (flatten !== false) { - // apply group opacity when flattened - if (obj.isRenderable === true) { - applyObjectOpacity(obj, group.opacity); - } - objects.push(obj); - } else { - targetContainer.addChild(obj); - } - - // a solid tile layer of a group layer comes with its walls - for (const wall of colliderWalls(this, settings)) { - if (flatten !== false) { - objects.push(wall); - } else { - targetContainer.addChild(wall); - } - } - } - - // if we created a new container with children - if (flatten === false && targetContainer.getChildren().length > 0) { - // re-enable auto-sort and auto-depth - targetContainer.autoSort = true; - targetContainer.autoDepth = true; - - // add our container to the world - objects.push(targetContainer); - } + buildGroup(this, this.objectGroups[g], flatten, wanted, 1, (object) => { + objects.push(object); + }); } return objects; } diff --git a/packages/melonjs/src/renderable/imagelayer.js b/packages/melonjs/src/renderable/imagelayer.js index 80082c64ca..637242773f 100644 --- a/packages/melonjs/src/renderable/imagelayer.js +++ b/packages/melonjs/src/renderable/imagelayer.js @@ -361,25 +361,25 @@ export default class ImageLayer extends Sprite { renderer.translate(x * vZoom, y * vZoom); renderer.scale(vZoom, vZoom); - // Clamp the draw extent to the source dimensions on any axis we - // are NOT tiling. Asking the renderer to fill past the source on - // a non-tiling axis is what makes Canvas (transparent fill per - // HTML spec) and WebGL (GL_CLAMP_TO_EDGE stretches the edge - // pixel) diverge — Canvas leaves the overflow transparent while - // WebGL stretches the bottom row (repeat-x) or right column - // (repeat-y) to fill it. By drawing exactly the source extent on - // the non-tiling axis, neither renderer enters its overflow path - // and the two outputs converge (issue #1290). + // On an axis that is not tiling, the pattern is drawn over the + // picture's own extent, no more and no less. More, and the two + // renderers part: Canvas leaves what is past the picture + // transparent, as the HTML spec says, while WebGL and WebGPU repeat + // its last row or column over it (GL_CLAMP_TO_EDGE; issue #1290). + // Less, and a picture larger than the view is cut where the view + // ends, though the camera scrolls over the rest of it. (The layer's + // own size on such an axis is the view's: it is what the layer is + // anchored by, not what it draws.) // On a tiling axis the offset is wrapped into (-imageSize, 0], so // the pattern must reach at least `viewport + imageSize` to cover // the viewport, also when the image is larger than the viewport // (and never less than the historical `viewport * 2`). const drawW = this.repeatX ? viewport.width + Math.max(viewport.width, this.image.width) - : width; + : this.image.width; const drawH = this.repeatY ? viewport.height + Math.max(viewport.height, this.image.height) - : height; + : this.image.height; // apply flip — pivot at the centre of the drawn pattern in the // post-zoom local frame, so the mirror lands in the visible viewport diff --git a/packages/melonjs/tests/helpers/tiled-parallax-checks.ts b/packages/melonjs/tests/helpers/tiled-parallax-checks.ts index 0e341a6d9a..d0f68b80f8 100644 --- a/packages/melonjs/tests/helpers/tiled-parallax-checks.ts +++ b/packages/melonjs/tests/helpers/tiled-parallax-checks.ts @@ -202,9 +202,7 @@ export function tiledParallaxChecks( // A tile layer is where an image layer of the same picture, offset // and factor is, at every view: by the image layers' rule, painted - // here, and against an image layer itself where one draws its - // picture once (on WebGL it spreads the picture's edges over the - // view, which is not this test's to tell). + // here, and against an image layer itself, drawing its picture once. const expectAsAnImageLayer = ( tiles: TileMap, placing: Placing, @@ -219,15 +217,13 @@ export function tiledParallaxChecks( `${what}, from ${String(x)}, ${String(y)}: ${result.first}`, ).toBe(0); } - if (renderer === video.CANVAS) { - const picture = frames(tiledMap([imageLayer({ ...placing })], origin)); - for (const [i, [x, y]] of VIEWS.entries()) { - const result = diff(got[i], picture[i], tolerance); - expect( - result.different, - `${what}, against an image layer, from ${String(x)}, ${String(y)}: ${result.first}`, - ).toBe(0); - } + const picture = frames(tiledMap([imageLayer({ ...placing })], origin)); + for (const [i, [x, y]] of VIEWS.entries()) { + const result = diff(got[i], picture[i], tolerance); + expect( + result.different, + `${what}, against an image layer, from ${String(x)}, ${String(y)}: ${result.first}`, + ).toBe(0); } return got; }; diff --git a/packages/melonjs/tests/imagelayer-repeat.spec.js b/packages/melonjs/tests/imagelayer-repeat.spec.js new file mode 100644 index 0000000000..bf378ef581 --- /dev/null +++ b/packages/melonjs/tests/imagelayer-repeat.spec.js @@ -0,0 +1,313 @@ +import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; +import { + Application, + boot, + ImageLayer, + loader, + state, + TileMap, + video, +} from "../src/index.js"; +import { copyFrame } from "./helpers/pixels.js"; + +/** + * An image layer draws its picture as its `repeat` says: over the whole view, + * along one axis only, or once. The frames are compared, pixel by pixel, with + * the same picture painted with a 2D canvas: where the picture is not, the + * background shows, on every renderer. + */ + +const WIDTH = 320; +const HEIGHT = 240; +const BACKGROUND = "#101830"; + +/** a picture where no two neighbours are of one color, edges included */ +const picture = (width, height) => { + const canvas = document.createElement("canvas"); + canvas.width = width; + canvas.height = height; + const c = canvas.getContext("2d"); + const data = c.createImageData(width, height); + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + const at = (y * width + x) * 4; + data.data[at] = 60 + ((x * 37) % 180); + data.data[at + 1] = 60 + ((y * 53) % 180); + data.data[at + 2] = 60 + (((x + y) * 29) % 180); + data.data[at + 3] = 255; + } + } + c.putImageData(data, 0, 0); + return canvas; +}; + +const SMALL = picture(64, 32); +// larger than the view, both ways +const LARGE = picture(400, 300); + +/** + * what the frame has to be: the picture at a place of the view, repeated as + * asked, over the background + */ +const reference = (image, repeat, x, y) => { + const canvas = document.createElement("canvas"); + canvas.width = WIDTH; + canvas.height = HEIGHT; + const c = canvas.getContext("2d", { willReadFrequently: true }); + c.fillStyle = BACKGROUND; + c.fillRect(0, 0, WIDTH, HEIGHT); + const repeatX = repeat === "repeat" || repeat === "repeat-x"; + const repeatY = repeat === "repeat" || repeat === "repeat-y"; + const along = (start, size, span, repeated) => { + if (!repeated) { + return [start]; + } + const places = []; + for ( + let at = start - Math.ceil(start / size) * size - size; + at < span; + at += size + ) { + places.push(at); + } + return places; + }; + for (const py of along(y, image.height, HEIGHT, repeatY)) { + for (const px of along(x, image.width, WIDTH, repeatX)) { + c.drawImage(image, px, py); + } + } + return c.getImageData(0, 0, WIDTH, HEIGHT).data; +}; + +/** how two frames differ: the count of pixels, and the first of them */ +const difference = (got, expected) => { + let count = 0; + let first = ""; + for (let at = 0; at < expected.length; at += 4) { + if ( + Math.abs(got[at] - expected[at]) > 2 || + Math.abs(got[at + 1] - expected[at + 1]) > 2 || + Math.abs(got[at + 2] - expected[at + 2]) > 2 + ) { + if (count === 0) { + const p = at / 4; + first = `at ${p % WIDTH}, ${Math.floor(p / WIDTH)}: drawn ${[got[at], got[at + 1], got[at + 2]]}, expected ${[expected[at], expected[at + 1], expected[at + 2]]}`; + } + count += 1; + } + } + return count === 0 + ? "the same" + : `${count} pixels differ, the first ${first}`; +}; + +const REPEATS = ["no-repeat", "repeat-x", "repeat-y", "repeat"]; + +describe.each([ + ["Canvas", video.CANVAS], + ["WebGL", video.WEBGL], +])("an image layer's repeat (%s)", (label, renderer) => { + let app; + + const draw = () => { + app.world.update(16); + app.viewport.update(16); + app.repaint(); + app.draw(); + return copyFrame(app.renderer).data; + }; + + beforeAll(async () => { + boot(); + app = new Application(WIDTH, HEIGHT, { + parent: "screen", + renderer, + consoleHeader: false, + antiAlias: false, + }); + await app.init(); + state.change(state.DEFAULT, true); + app.reset(); + await loader.load({ + name: "picture-small", + type: "image", + src: SMALL.toDataURL("image/png"), + }); + await loader.load({ + name: "picture-large", + type: "image", + src: LARGE.toDataURL("image/png"), + }); + }); + + afterAll(() => { + loader.unloadAll(); + app?.destroy(); + }); + + /** an empty world, its background shown, the camera free to go anywhere */ + const clear = () => { + app.world.reset(); + app.world.pos.set(0, 0); + app.world.backgroundColor.parseCSS(BACKGROUND); + app.viewport.setBounds(-4000, -4000, 8000, 8000); + app.viewport.moveTo(0, 0); + }; + + beforeEach(clear); + + /** an image layer in the world */ + const show = (image, repeat, x = 0, y = 0, extra = {}) => { + const layer = new ImageLayer(x, y, { image, repeat, z: 1, ...extra }); + app.world.addChild(layer, 1); + return layer; + }; + + it("uses the renderer asked for", () => { + expect(app.renderer.type.toLowerCase()).toContain( + label === "Canvas" ? "canvas" : "webgl", + ); + }); + + describe.each(REPEATS)("%s", (repeat) => { + it("draws the picture at the view's corner, and the background elsewhere", () => { + show("picture-small", repeat); + expect(difference(draw(), reference(SMALL, repeat, 0, 0))).toBe( + "the same", + ); + }); + + it("draws it where the layer is put", () => { + show("picture-small", repeat, 24, 16); + expect(difference(draw(), reference(SMALL, repeat, 24, 16))).toBe( + "the same", + ); + }); + + it("draws it partly out of the view, on any side", () => { + for (const [x, y] of [ + [-20, -10], + [WIDTH - 30, HEIGHT - 12], + [-40, HEIGHT - 20], + ]) { + clear(); + show("picture-small", repeat, x, y); + expect( + difference(draw(), reference(SMALL, repeat, x, y)), + `at ${x}, ${y}`, + ).toBe("the same"); + } + }); + + it("follows the camera, at the layer's ratio", () => { + for (const [ratio, view] of [ + [1, [10, 6]], + [0.5, [40, 20]], + [0.25, [-80, 120]], + [1, [-33, -17]], + ]) { + clear(); + show("picture-small", repeat, 24, 16, { ratio }); + app.viewport.moveTo(view[0], view[1]); + expect( + difference( + draw(), + reference( + SMALL, + repeat, + 24 - ratio * view[0], + 16 - ratio * view[1], + ), + ), + `ratio ${ratio}, camera at ${view}`, + ).toBe("the same"); + } + }); + + it("draws all of a picture larger than the view, as the camera goes over it", () => { + for (const view of [ + [0, 0], + [60, 40], + [80, 60], + [-50, -30], + ]) { + clear(); + show("picture-large", repeat); + app.viewport.moveTo(view[0], view[1]); + expect( + difference(draw(), reference(LARGE, repeat, -view[0], -view[1])), + `camera at ${view}`, + ).toBe("the same"); + } + }); + }); + + it("covers only the picture's own pixels when it is not repeated", () => { + show("picture-small", "no-repeat", 24, 16); + const frame = draw(); + const clear = reference(SMALL, "no-repeat", -1000, -1000); + let drawn = 0; + for (let at = 0; at < frame.length; at += 4) { + if ( + frame[at] !== clear[at] || + frame[at + 1] !== clear[at + 1] || + frame[at + 2] !== clear[at + 2] + ) { + drawn += 1; + } + } + expect(drawn).toBe(SMALL.width * SMALL.height); + }); + + describe("read from a Tiled map", () => { + let serial = 0; + const mapOf = (layer) => { + return new TileMap(`image-layer-map-${serial++}`, { + type: "map", + version: "1.10", + tiledversion: "1.10.2", + orientation: "orthogonal", + renderorder: "right-down", + infinite: false, + width: 4, + height: 2, + tilewidth: 16, + tileheight: 16, + tilesets: [], + layers: [ + { + type: "imagelayer", + name: "picture", + image: "picture-small", + visible: true, + opacity: 1, + ...layer, + }, + ], + }); + }; + + it.each([ + [ + "the `repeat` property set to no-repeat", + { properties: { repeat: "no-repeat" } }, + "no-repeat", + ], + ["Tiled's repeat x alone", { repeatx: true }, "repeat-x"], + ["Tiled's repeat y alone", { repeaty: true }, "repeat-y"], + ["Tiled's repeat x and y", { repeatx: true, repeaty: true }, "repeat"], + ])("%s", (name, settings, repeat) => { + mapOf({ offsetx: 24, offsety: 16, ...settings }).addTo( + app.world, + true, + false, + ); + app.viewport.setBounds(-4000, -4000, 8000, 8000); + app.viewport.moveTo(10, 6); + expect(difference(draw(), reference(SMALL, repeat, 14, 10))).toBe( + "the same", + ); + }); + }); +}); diff --git a/packages/melonjs/tests/imagelayer.spec.js b/packages/melonjs/tests/imagelayer.spec.js index 964194e4ce..55a080fd36 100644 --- a/packages/melonjs/tests/imagelayer.spec.js +++ b/packages/melonjs/tests/imagelayer.spec.js @@ -653,8 +653,9 @@ describe("ImageLayer", () => { expect(rect.x).toBeLessThanOrEqual(0); // and the drawn pattern reaches the right edge expect(rect.x + rect.w).toBeGreaterThanOrEqual(VW); - // non-tiling axis still draws exactly the source extent (#1290) - expect(rect.h).toEqual(layer.height); + // the non-tiling axis draws exactly the source extent + // (#1290): the picture's height, not the view's + expect(rect.h).toEqual(image.height); }); } } @@ -678,7 +679,7 @@ describe("ImageLayer", () => { expect(rect.y).toBeGreaterThan(-image.height); expect(rect.y).toBeLessThanOrEqual(0); expect(rect.y + rect.h).toBeGreaterThanOrEqual(VH); - expect(rect.w).toEqual(layer.width); + expect(rect.w).toEqual(image.width); }); } diff --git a/packages/melonjs/tests/tiled-group-layers.spec.js b/packages/melonjs/tests/tiled-group-layers.spec.js new file mode 100644 index 0000000000..23228fbb77 --- /dev/null +++ b/packages/melonjs/tests/tiled-group-layers.spec.js @@ -0,0 +1,824 @@ +import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; +import { + Application, + boot, + Container, + collision, + ImageLayer, + loader, + Renderable, + registerObjectClass, + state, + TileMap, + TMXLayer, + video, +} from "../src/index.js"; +import * as TMXUtils from "../src/level/tiled/TMXUtils.js"; +import { copyFrame } from "./helpers/pixels.js"; + +/** + * A Tiled group layer holds layers of any kind: tile layers, object layers, + * image layers and other groups. Each is read as what it is, in Tiled's + * order, with what the group gives the layers inside it (its offset, its + * opacity, its tint, its blend mode, its parallax factor) on top of their + * own. + */ + +const WIDTH = 96; +const HEIGHT = 64; +const TILE = 16; + +// the tiles of the test's tileset, each of one color: gid 1 is the first +const TILE_COLORS = [ + [200, 40, 40], + [40, 200, 40], + [40, 40, 200], + [200, 200, 40], + [40, 200, 200], + [200, 40, 200], + [120, 120, 120], + [240, 240, 240], +]; +const PICTURE_COLOR = [255, 128, 0]; +const BLACK = [0, 0, 0]; + +const flat = (width, height, paint) => { + const canvas = document.createElement("canvas"); + canvas.width = width; + canvas.height = height; + paint(canvas.getContext("2d")); + return canvas.toDataURL("image/png"); +}; + +const tilesImage = () => { + return flat(TILE * 4, TILE * 2, (c) => { + TILE_COLORS.forEach((color, id) => { + c.fillStyle = `rgb(${color.join(",")})`; + c.fillRect((id % 4) * TILE, Math.floor(id / 4) * TILE, TILE, TILE); + }); + }); +}; + +const pictureImage = () => { + return flat(32, 16, (c) => { + c.fillStyle = `rgb(${PICTURE_COLOR.join(",")})`; + c.fillRect(0, 0, 32, 16); + }); +}; + +/** an object of the game's: a box of one color, which keeps what it was given */ +class Gem extends Renderable { + constructor(x, y, settings) { + super(x, y, settings.width, settings.height); + this.anchorPoint.set(0, 0); + this.name = settings.name; + this.color = settings.color ?? "#00ff00"; + this.given = settings; + } + + draw(renderer) { + renderer.setColor(this.color); + renderer.fillRect(this.pos.x, this.pos.y, this.width, this.height); + } +} + +/** an object as Tiled saves it */ +const object = (id, name, x, y, extra = {}) => { + return { + id, + name, + type: "GroupGem", + x, + y, + width: 16, + height: 16, + rotation: 0, + visible: true, + ...extra, + }; +}; + +const objectLayer = (name, objects, extra = {}) => { + return { + type: "objectgroup", + name, + visible: true, + opacity: 1, + x: 0, + y: 0, + objects, + ...extra, + }; +}; + +/** a tile layer of 4 x 2 cells: the gid of each, 0 for none */ +const tileLayer = (name, data, extra = {}) => { + return { + type: "tilelayer", + name, + visible: true, + opacity: 1, + x: 0, + y: 0, + width: 4, + height: 2, + data, + ...extra, + }; +}; + +const imageLayer = (name, extra = {}) => { + return { + type: "imagelayer", + name, + image: "group-picture", + visible: true, + opacity: 1, + properties: { repeat: "no-repeat" }, + ...extra, + }; +}; + +const group = (name, layers, extra = {}) => { + return { + type: "group", + name, + visible: true, + opacity: 1, + layers, + ...extra, + }; +}; + +let serial = 0; +/** a map of 4 x 2 tiles, as Tiled saves it in JSON */ +const mapOf = (layers) => { + return new TileMap(`group-map-${serial++}`, { + type: "map", + version: "1.10", + tiledversion: "1.12.0", + orientation: "orthogonal", + renderorder: "right-down", + infinite: false, + width: 4, + height: 2, + tilewidth: TILE, + tileheight: TILE, + nextobjectid: 100, + tilesets: [ + { + firstgid: 1, + name: "tiles", + image: "group-tiles.png", + imagewidth: 64, + imageheight: 32, + tilewidth: TILE, + tileheight: TILE, + tilecount: 8, + columns: 4, + margin: 0, + spacing: 0, + }, + ], + layers, + }); +}; + +/** the names of what was built, each with its kind */ +const kinds = (built) => { + return built.map((child) => { + const kind = + child instanceof TMXLayer + ? "tiles" + : child instanceof ImageLayer + ? "image" + : child instanceof Container + ? "container" + : child instanceof Gem + ? "gem" + : "other"; + return `${kind}:${child.name}`; + }); +}; + +describe.each([ + ["Canvas", video.CANVAS], + ["WebGL", video.WEBGL], +])("a Tiled group layer (%s)", (label, renderer) => { + let app; + + beforeAll(async () => { + boot(); + app = new Application(WIDTH, HEIGHT, { + parent: "screen", + renderer, + consoleHeader: false, + antiAlias: false, + }); + await app.init(); + state.change(state.DEFAULT, true); + app.reset(); + await loader.load({ + name: "group-tiles", + type: "image", + src: tilesImage(), + }); + await loader.load({ + name: "group-picture", + type: "image", + src: pictureImage(), + }); + registerObjectClass("GroupGem", Gem); + }); + + afterAll(() => { + loader.unloadAll(); + app?.destroy(); + }); + + beforeEach(() => { + app.world.reset(); + app.world.pos.set(0, 0); + app.world.backgroundColor.parseCSS("#000000"); + app.viewport.setBounds(-4000, -4000, 8000, 8000); + app.viewport.moveTo(0, 0); + }); + + /** add a map to the world, draw a frame, and read the color at the middle of cells */ + const colors = async (map, flatten, ...cells) => { + map.addTo(app.world, flatten, false); + // (a container sorts its children once what added them is done) + await new Promise((resolve) => { + setTimeout(resolve, 0); + }); + app.world.sortNow?.(true); + app.viewport.setBounds(-4000, -4000, 8000, 8000); + app.viewport.moveTo(0, 0); + app.world.update(16); + app.viewport.update(16); + app.repaint(); + app.draw(); + const frame = copyFrame(app.renderer); + return cells.map(([col, row]) => { + const at = + ((row * TILE + TILE / 2) * frame.width + col * TILE + TILE / 2) * 4; + return [frame.data[at], frame.data[at + 1], frame.data[at + 2]]; + }); + }; + + describe("holding an object layer", () => { + const withObjects = ( + groupExtra = {}, + layerExtra = {}, + objectExtra = {}, + ) => { + return mapOf([ + group( + "upstairs", + [ + objectLayer( + "more", + [object(21, "gem", 32, 16, objectExtra)], + layerExtra, + ), + ], + groupExtra, + ), + ]); + }; + + it("loads, and builds the layer's objects", () => { + const built = withObjects().getObjects(true); + expect(kinds(built)).toEqual(["gem:gem"]); + expect([built[0].pos.x, built[0].pos.y]).toEqual([32, 16]); + }); + + it("moves them by the group's offset, on top of their layer's", () => { + const [gem] = withObjects( + { offsetx: 8, offsety: 4 }, + { offsetx: 2, offsety: 1 }, + ).getObjects(true); + expect([gem.pos.x, gem.pos.y]).toEqual([42, 21]); + }); + + it("fades them by the group's opacity, times their layer's", () => { + const [gem] = withObjects({ opacity: 0.5 }, { opacity: 0.5 }).getObjects( + true, + ); + expect(gem.getOpacity()).toBeCloseTo(0.25, 6); + // and times the object's own + const [faint] = withObjects( + { opacity: 0.5 }, + { opacity: 0.5 }, + { opacity: 0.4 }, + ).getObjects(true); + expect(faint.getOpacity()).toBeCloseTo(0.1, 6); + }); + + it("hides them with the group, or with their layer", () => { + const [inHiddenGroup] = withObjects({ visible: false }).getObjects(true); + expect(inHiddenGroup.getOpacity()).toBe(0); + const [inHiddenLayer] = withObjects({}, { visible: false }).getObjects( + true, + ); + expect(inHiddenLayer.getOpacity()).toBe(0); + }); + + it("tints them with the group's tint, unless their layer has its own", () => { + const [tinted] = withObjects({ tintcolor: "#ff0000" }).getObjects(true); + expect(tinted.given.tint?.toHex().toLowerCase()).toBe("#ff0000"); + const [own] = withObjects( + { tintcolor: "#ff0000" }, + { tintcolor: "#0000ff" }, + ).getObjects(true); + expect(own.given.tint?.toHex().toLowerCase()).toBe("#0000ff"); + const [none] = withObjects().getObjects(true); + expect(none.given.tint).toBeUndefined(); + }); + + it("blends them as the group says, unless their layer says otherwise", () => { + const [blended] = withObjects({ mode: "multiply" }).getObjects(true); + expect(blended.blendMode).toBe("multiply"); + const [own] = withObjects( + { mode: "multiply" }, + { mode: "screen" }, + ).getObjects(true); + expect(own.blendMode).toBe("screen"); + }); + + it("keeps a container for the group and one for the layer, when not flattened", () => { + const built = withObjects({ opacity: 0.5 }, { opacity: 0.25 }).getObjects( + false, + ); + expect(kinds(built)).toEqual(["container:upstairs"]); + const upstairs = built[0]; + expect(upstairs.getOpacity()).toBe(0.5); + expect(kinds(upstairs.getChildren())).toEqual(["container:more"]); + const more = upstairs.getChildren()[0]; + expect(more.getOpacity()).toBe(0.25); + expect(kinds(more.getChildren())).toEqual(["gem:gem"]); + // each fades what is in it: the object keeps its own opacity + expect(more.getChildren()[0].getOpacity()).toBe(1); + }); + + it("leaves the objects out when the game asks for none, and asks about each", () => { + expect(withObjects().getObjects(true, false)).toEqual([]); + const asked = []; + withObjects().getObjects(true, (settings) => { + asked.push(settings.name); + return true; + }); + expect(asked).toEqual(["gem"]); + }); + + it("makes walls of the unnamed shapes of a layer named collision", () => { + const map = mapOf([ + group("physics", [ + objectLayer("collision", [ + { + id: 30, + name: "", + type: "", + x: 0, + y: 16, + width: 64, + height: 16, + rotation: 0, + visible: true, + }, + ]), + ]), + ]); + const [wall] = map.getObjects(true); + expect(wall.bodyDef.collisionType).toBe(collision.types.WORLD_SHAPE); + expect(wall.bodyDef.type).toBe("static"); + // and not of a layer of any other name + const [thing] = mapOf([ + group("physics", [ + objectLayer("things", [ + { + id: 31, + name: "", + type: "", + x: 0, + y: 16, + width: 64, + height: 16, + rotation: 0, + visible: true, + }, + ]), + ]), + ]).getObjects(true); + expect(thing.bodyDef.collisionType).not.toBe(collision.types.WORLD_SHAPE); + }); + }); + + describe("holding an image layer", () => { + const withImage = (groupExtra = {}, layerExtra = {}) => { + return mapOf([ + group("backdrop", [imageLayer("sky", layerExtra)], groupExtra), + ]); + }; + + it("loads, and builds the image layer", () => { + const built = withImage().getObjects(true); + expect(kinds(built)).toEqual(["image:sky"]); + expect(built[0].repeat).toBe("no-repeat"); + }); + + it("builds it whatever objects the game asks for: it is a layer", () => { + expect(kinds(withImage().getObjects(true, false))).toEqual(["image:sky"]); + const asked = []; + withImage().getObjects(true, (settings) => { + asked.push(settings.name); + return false; + }); + expect(asked).toEqual([]); + }); + + it("places it by the group's offset, on top of its own", () => { + const [sky] = withImage( + { offsetx: 8, offsety: 4 }, + { offsetx: 16, offsety: 2 }, + ).getObjects(true); + expect([sky.offset.x, sky.offset.y]).toEqual([24, 6]); + }); + + it("scrolls it at the group's parallax factor, times its own", () => { + const [sky] = withImage( + { parallaxx: 0.5, parallaxy: 0.5 }, + { parallaxx: 0.5, parallaxy: 1 }, + ).getObjects(true); + expect([sky.ratio.x, sky.ratio.y]).toEqual([0.25, 0.5]); + }); + + it("fades it by the group's opacity, times its own", () => { + const [sky] = withImage({ opacity: 0.5 }, { opacity: 0.5 }).getObjects( + true, + ); + expect(sky.getOpacity()).toBeCloseTo(0.25, 6); + const [hidden] = withImage({ visible: false }).getObjects(true); + expect(hidden.getOpacity()).toBe(0); + }); + + it("tints it with the group's tint, unless it has its own", () => { + const [tinted] = withImage({ tintcolor: "#ff0000" }).getObjects(true); + expect(tinted.tint.toHex().toLowerCase()).toBe("#ff0000"); + const [own] = withImage( + { tintcolor: "#ff0000" }, + { tintcolor: "#0000ff" }, + ).getObjects(true); + expect(own.tint.toHex().toLowerCase()).toBe("#0000ff"); + }); + + it("is in the group's container when not flattened", () => { + const built = withImage().getObjects(false); + expect(kinds(built)).toEqual(["container:backdrop"]); + expect(kinds(built[0].getChildren())).toEqual(["image:sky"]); + }); + + it("is drawn where it is, once", async () => { + // the picture is 32 x 16: at 16, 16 it covers two cells of the second row + for (const flatten of [true, false]) { + app.world.reset(); + app.world.backgroundColor.parseCSS("#000000"); + expect( + await colors( + withImage({ offsetx: 16 }, { offsety: 16 }), + flatten, + [0, 1], + [1, 1], + [2, 1], + [3, 1], + [1, 0], + ), + `flatten ${flatten}`, + ).toEqual([BLACK, PICTURE_COLOR, PICTURE_COLOR, BLACK, BLACK]); + } + }); + }); + + describe("holding another group", () => { + const nested = (outer = {}, inner = {}, layerExtra = {}) => { + return mapOf([ + group( + "outer", + [ + group( + "inner", + [ + tileLayer("deep", [2, 0, 0, 0, 0, 0, 0, 0], layerExtra), + objectLayer("things", [object(41, "gem", 0, 16)], layerExtra), + imageLayer("far", layerExtra), + ], + inner, + ), + ], + outer, + ), + ]); + }; + + it("loads, and builds what the inner group holds, in Tiled's order", () => { + expect(kinds(nested().getObjects(true))).toEqual([ + "tiles:deep", + "gem:gem", + "image:far", + ]); + }); + + it("adds up the offsets of both groups and of the layer", () => { + const [deep, gem, far] = nested( + { offsetx: 8, offsety: 4 }, + { offsetx: 16, offsety: 0 }, + { offsetx: 2, offsety: 1 }, + ).getObjects(true); + expect([deep.pos.x, deep.pos.y]).toEqual([26, 5]); + expect([gem.pos.x, gem.pos.y]).toEqual([26, 21]); + expect([far.offset.x, far.offset.y]).toEqual([26, 5]); + }); + + it("multiplies their opacities", () => { + const [deep, gem, far] = nested( + { opacity: 0.5 }, + { opacity: 0.5 }, + { opacity: 0.5 }, + ).getObjects(true); + expect(deep.getOpacity()).toBeCloseTo(0.125, 6); + expect(gem.getOpacity()).toBeCloseTo(0.125, 6); + expect(far.getOpacity()).toBeCloseTo(0.125, 6); + }); + + it("multiplies their parallax factors", () => { + const [deep, , far] = nested( + { parallaxx: 0.5, parallaxy: 0.5 }, + { parallaxx: 0.5, parallaxy: 1 }, + { parallaxx: 0.5, parallaxy: 0.5 }, + ).getObjects(true); + expect([deep.ratio.x, deep.ratio.y]).toEqual([0.125, 0.25]); + expect([far.ratio.x, far.ratio.y]).toEqual([0.125, 0.25]); + }); + + it("tints a tile layer with the nearest group's tint, unless it has its own", () => { + const [outer] = nested({ tintcolor: "#ff0000" }).getObjects(true); + expect(outer.tint.toHex().toLowerCase()).toBe("#ff0000"); + const [inner] = nested( + { tintcolor: "#ff0000" }, + { tintcolor: "#00ff00" }, + ).getObjects(true); + expect(inner.tint.toHex().toLowerCase()).toBe("#00ff00"); + const [own] = nested( + { tintcolor: "#ff0000" }, + { tintcolor: "#00ff00" }, + { tintcolor: "#0000ff" }, + ).getObjects(true); + expect(own.tint.toHex().toLowerCase()).toBe("#0000ff"); + const [none] = nested().getObjects(true); + expect(none.tint.toHex().toLowerCase()).toBe("#ffffff"); + }); + + it("takes the blend mode of the nearest group that has one", () => { + const [, outerOnly] = nested({ mode: "multiply" }).getObjects(true); + expect(outerOnly.blendMode).toBe("multiply"); + const [, innerWins] = nested( + { mode: "multiply" }, + { mode: "screen" }, + ).getObjects(true); + expect(innerWins.blendMode).toBe("screen"); + }); + + it("keeps a container for each group and each object layer, when not flattened", () => { + const built = nested({ opacity: 0.5 }, { opacity: 0.25 }).getObjects( + false, + ); + expect(kinds(built)).toEqual(["container:outer"]); + expect(built[0].getOpacity()).toBe(0.5); + expect(kinds(built[0].getChildren())).toEqual(["container:inner"]); + const inner = built[0].getChildren()[0]; + expect(inner.getOpacity()).toBe(0.25); + expect(kinds(inner.getChildren()).sort()).toEqual([ + "container:things", + "image:far", + "tiles:deep", + ]); + }); + + it("builds nothing for a group that holds nothing, or only empty layers", () => { + const map = mapOf([ + group("empty", []), + group("hollow", [group("inner", []), objectLayer("none", [])]), + // (as the XML reader gives a group with no child: no `layers` at all) + { type: "group", name: "bare", visible: true, opacity: 1 }, + ]); + expect(map.getObjects(true)).toEqual([]); + expect(map.getObjects(false)).toEqual([]); + }); + + it("ignores a layer of a kind it does not know", () => { + const map = mapOf([ + group("odd", [ + { type: "somethingelse", name: "what" }, + objectLayer("things", [object(51, "gem", 0, 0)]), + ]), + ]); + expect(kinds(map.getObjects(true))).toEqual(["gem:gem"]); + }); + }); + + describe("draw order", () => { + // along the first row: each layer covers the cell of the one before + // and one more, so each cell shows which of two is on top + const stacked = () => { + return mapOf([ + tileLayer("below", [1, 1, 1, 1, 1, 1, 1, 1]), + group("g", [ + tileLayer("a", [2, 2, 0, 0, 0, 0, 0, 0]), + objectLayer("objs", [ + object(61, "gem", 16, 0, { + width: 32, + height: 16, + properties: { color: "#ff00ff" }, + }), + ]), + imageLayer("pic", { offsetx: 32 }), + group("h", [tileLayer("b", [0, 0, 0, 3, 3, 0, 0, 0])]), + ]), + tileLayer("above", [0, 0, 0, 0, 4, 0, 0, 0]), + ]); + }; + + it.each([ + ["flattened", true], + ["in containers", false], + ])("follows Tiled's layer order, %s", async (name, flatten) => { + expect( + await colors( + stacked(), + flatten, + [0, 0], + [1, 0], + [2, 0], + [3, 0], + [0, 1], + [1, 1], + ), + ).toEqual([ + // the group's first tile layer, over the layer below the group + TILE_COLORS[1], + // the object, over that tile layer + [255, 0, 255], + // the image layer, over the object + PICTURE_COLOR, + // the nested group's tile layer, over the image layer + TILE_COLORS[2], + // the layer after the group, over the group's last layer + TILE_COLORS[3], + // and the layer below the group, where nothing covers it + TILE_COLORS[0], + ]); + }); + + it("draws a layer that follows a group over the group's layers, however many", async () => { + // tile layers only: three in a group, each covering one cell less + // than the one before, then a layer of the map over the first cell + for (const flatten of [true, false]) { + app.world.reset(); + app.world.backgroundColor.parseCSS("#000000"); + const map = mapOf([ + group("g", [ + tileLayer("a", [2, 2, 2, 2, 0, 0, 0, 0]), + tileLayer("b", [3, 3, 3, 0, 0, 0, 0, 0]), + tileLayer("c", [4, 4, 0, 0, 0, 0, 0, 0]), + ]), + tileLayer("above", [5, 0, 0, 0, 0, 0, 0, 0]), + ]); + expect( + await colors(map, flatten, [0, 0], [1, 0], [2, 0], [3, 0]), + `flatten ${flatten}`, + ).toEqual([ + TILE_COLORS[4], + TILE_COLORS[3], + TILE_COLORS[2], + TILE_COLORS[1], + ]); + } + }); + + it("gives each layer a depth of its own, in Tiled's order", () => { + const map = mapOf([ + tileLayer("below", [1, 0, 0, 0, 0, 0, 0, 0]), + group("g", [ + tileLayer("a", [2, 0, 0, 0, 0, 0, 0, 0]), + objectLayer("objs", [ + object(91, "gem", 0, 0), + object(92, "gem", 16, 0), + ]), + imageLayer("pic"), + group("h", [tileLayer("b", [3, 0, 0, 0, 0, 0, 0, 0])]), + ]), + tileLayer("above", [4, 0, 0, 0, 0, 0, 0, 0]), + objectLayer("last", [object(93, "gem", 0, 0)]), + ]); + const depth = Object.fromEntries( + [...map.getLayers(), ...map.getObjects(true)].map((child) => { + return [ + child.name === "gem" ? `gem ${child.id}` : child.name, + child.pos.z, + ]; + }), + ); + expect(depth).toEqual({ + below: 0, + a: 1, + // the objects of one layer share its depth + "gem 91": 2, + "gem 92": 2, + pic: 3, + b: 4, + above: 5, + "gem 93": 6, + }); + }); + }); + + describe("read from a TMX file", () => { + const TMX = ` + + + + + + + +2,0,0,0, +0,0,0,0 + + + + + + + + + + + + + + +`; + + const fromXML = () => { + return new TileMap( + `group-xml-${serial++}`, + TMXUtils.parse(new DOMParser().parseFromString(TMX, "text/xml")).map, + ); + }; + + it("loads, and builds each layer as what it is", () => { + const built = fromXML().getObjects(true); + expect(kinds(built)).toEqual([ + "tiles:deep", + "gem:gem", + "image:far", + "gem:jewel", + ]); + const [deep, gem, far, jewel] = built; + expect([deep.pos.x, deep.pos.y]).toEqual([8, 4]); + expect([gem.pos.x, gem.pos.y]).toEqual([10, 21]); + expect([far.offset.x, far.offset.y]).toEqual([24, 6]); + expect(far.repeat).toBe("repeat-x"); + expect([jewel.pos.x, jewel.pos.y]).toEqual([24, 4]); + for (const child of built) { + expect(child.getOpacity()).toBeCloseTo(0.5, 6); + } + }); + + it("keeps the groups as containers when not flattened", () => { + const built = fromXML().getObjects(false); + expect(kinds(built)).toEqual(["container:outer"]); + expect(kinds(built[0].getChildren()).sort()).toEqual([ + "container:inner", + "container:things", + "image:far", + "tiles:deep", + ]); + }); + }); + + it("finds an object of a nested group by the id the map gives it", async () => { + const map = mapOf([ + group("outer", [ + group("inner", [objectLayer("things", [object(81, "gem", 0, 0)])]), + ]), + ]); + for (const flatten of [true, false]) { + app.world.reset(); + map.addTo(app.world, flatten, false); + const found = app.world.getChildByProp("id", 81); + expect(found.length, `flatten ${flatten}`).toBe(1); + expect(found[0]).toBeInstanceOf(Gem); + } + }); +});