diff --git a/packages/melonjs/CHANGELOG.md b/packages/melonjs/CHANGELOG.md index 1d803581a3..27bcc54a13 100644 --- a/packages/melonjs/CHANGELOG.md +++ b/packages/melonjs/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## [20.17.0] (melonJS 2) - _unreleased_ + +### Added +- Transitions: a mask transition can be shaped like an image or a `Sprite`, close on the player with `center`, and fill the shape with `invert`, on `state.transition`, `MaskEffect` and `Trigger` ([#1399](https://github.com/melonjs/melonJS/issues/1399)) + +### Fixed +- `NineSliceSprite` blinks with `flicker()`, as a `Sprite` does; it ignored it + ## [20.16.0] (melonJS 2) - _2026-11-17_ **Highlights:** a faster `Camera3d`, its work per frame up to **72%** faster with no change to your game, and real 3D physics: with the new `@melonjs/rapier3d-adapter`, bodies tumble, stack and topple in 3D, with collision shapes built straight from your models. Also new: skinned glTF characters with crossfades, mesh picking, an orthographic `Camera3d` for isometric views, and toon shading with outlines. The new features are opt-in: a game that sets none of them renders as before. diff --git a/packages/melonjs/package.json b/packages/melonjs/package.json index e92480a1d5..bf0109f0b9 100644 --- a/packages/melonjs/package.json +++ b/packages/melonjs/package.json @@ -1,6 +1,6 @@ { "name": "melonjs", - "version": "20.16.0", + "version": "20.17.0", "description": "A modern & fully featured HTML5 game engine (2D & 3D) for JavaScript/TypeScript, with WebGL/WebGPU rendering, built-in physics, Tiled map & glTF support and WebAudio.", "homepage": "https://www.melonjs.org/", "type": "module", diff --git a/packages/melonjs/skills/melonjs-camera-and-drawing/SKILL.md b/packages/melonjs/skills/melonjs-camera-and-drawing/SKILL.md index 2084fdfd21..c89645885b 100644 --- a/packages/melonjs/skills/melonjs-camera-and-drawing/SKILL.md +++ b/packages/melonjs/skills/melonjs-camera-and-drawing/SKILL.md @@ -1,6 +1,6 @@ --- name: melonjs-camera-and-drawing -description: "Use this skill for camera control and immediate-mode drawing in melonJS — following a target, viewport bounds, shake and fade, secondary cameras and what each one draws, and drawing shapes, lines and gradients inside a custom draw(). Covers world versus screen coordinate conversion, clipping and masking, baking with CanvasRenderTarget, and reading pixels back. Triggers on: Camera2d, viewport, follow, offset, look ahead, setBounds, minimap, second camera, split screen, cullMask, visibilityLayer, hide from a camera, zoom, roll, shake, fadeIn, fadeOut, CameraEffect, addCameraEffect, MaskEffect, PixelateTransitionEffect, worldToLocal, localToWorld, worldToScreen, screenToRay, screenToWorld, colorMatrix, renderer.fill, renderer.stroke, setGlobalAlpha, fillArc, Rect, Ellipse, Polygon, Line, Path2D, SVG path, Gradient, clipRect, mask, CanvasRenderTarget, NoiseTexture2d, lookAt, setBasis, orbit, toImageData, getImageData, toBlob, toDataURL, screenshot, read pixels." +description: "Use this skill for camera control and immediate-mode drawing in melonJS — following a target, viewport bounds, shake and fade, secondary cameras and what each one draws, and drawing shapes, lines and gradients inside a custom draw(). Covers world versus screen coordinate conversion, clipping and masking, baking with CanvasRenderTarget, and reading pixels back. Triggers on: Camera2d, viewport, follow, offset, look ahead, setBounds, minimap, second camera, split screen, cullMask, visibilityLayer, hide from a camera, zoom, roll, shake, fadeIn, fadeOut, CameraEffect, addCameraEffect, MaskEffect, iris, image mask, PixelateTransitionEffect, worldToLocal, localToWorld, worldToScreen, screenToRay, screenToWorld, colorMatrix, renderer.fill, renderer.stroke, setGlobalAlpha, fillArc, Rect, Ellipse, Polygon, Line, Path2D, SVG path, Gradient, clipRect, mask, CanvasRenderTarget, NoiseTexture2d, lookAt, setBasis, orbit, toImageData, getImageData, toBlob, toDataURL, screenshot, read pixels." license: MIT --- @@ -153,13 +153,32 @@ returns it), found with `getCameraEffect(Class)` and taken off with |---|---|---| | `ShakeEffect` | `intensity`, `duration`, `axis`, `onComplete` | jitters `offset`; what `shake()` adds. Several can run at once this way | | `FadeEffect` | `color`, `duration` (1000), `direction: "in" \| "out"`, `onComplete` | what `fadeIn()` / `fadeOut()` add | -| `MaskEffect` | `shape`, `color`, `duration` (500), `direction: "hide" \| "reveal"`, `onComplete` | an iris or a wipe through a unit-sized `Ellipse` or `Polygon` centred on the origin | +| `MaskEffect` | `shape`, `color`, `duration` (500), `direction: "hide" \| "reveal"`, `center`, `invert`, `onComplete` | an iris (the default) or a wipe through a unit-sized `Ellipse` or `Polygon`, an image's silhouette (the image, or a preloaded one's name) or a `Sprite`'s current frame (a `NineSliceSprite` at its full size), closing on `center` (a renderable or a screen point; the screen's centre by default). `invert` fills the shape instead and grows it to cover. Plain images and fills: the same on Canvas, WebGL and WebGPU | | `PixelateTransitionEffect` | `renderer`, `size` (32), `duration` (500), `direction: "hide" \| "reveal"`, `onComplete` | the view breaks into blocks up to `size` screen pixels, or comes back from them. A shader: on Canvas it keeps its timing and draws nothing | +```js +// the player's own silhouette closing on the player, then a heart image +// growing out of it until it covers the screen +camera.addCameraEffect(new MaskEffect(camera, { + shape: player, center: player, color: "#000", duration: 500, +})); +camera.addCameraEffect(new MaskEffect(camera, { + shape: "heart_mask", center: player, invert: true, color: "#000", duration: 400, +})); +``` + +A sprite or renderable is read once, when the effect is made: its frame, its +facing and its place on screen (not its scale or rotation: the shape is grown +to the screen's size anyway). The shape grows about its thickest part, which +sits on `center`. An image is read through a canvas, so a compressed texture +or a cross-origin image without CORS cannot shape a mask (it warns and uses an +iris). + `state.transition("fade" | "mask" | "pixelate", …)` drives the last three for a state change (see `melonjs-scenes-and-state`). A `Trigger` that loads a level transitions only with both a `color` and a `duration`, and takes only -`transition: "fade"` (the default) or `"mask"` with a `shape`: anything else, +`transition: "fade"` (the default) or `"mask"` with a `shape` (and `center`, +`invert`; `"touching"` for either is whoever walked in): anything else, `"pixelate"` included, is a fade. For an effect of your own, extend `CameraEffect`: `update(dt)` runs every @@ -539,6 +558,8 @@ const data = await rt.toImageData(0, 0, w, h); | a second `shake()` does nothing | one is still running: pass `force` (the fifth argument) to replace it | | a `Trigger` with `transition: "pixelate"` fades instead | a trigger takes only `"fade"` or `"mask"`; add a `PixelateTransitionEffect` yourself | | a `Trigger` loads its level with no transition | it needs both `color` and `duration` | +| an image or sprite `MaskEffect` is a plain circle, with a console warning | the shape could not be used: an unknown image name, a compressed texture, a cross-origin image without CORS, a fully transparent image or frame, a destroyed sprite, a renderable that is not a `Sprite`, or a value that is not a shape at all | +| a `MaskEffect` closes on the middle of the screen | it closes on `center`, the screen's centre by default: pass the renderable or point | | a `rotate()` or `scale()` on the camera is lost | `roll` owns the camera's `currentTransform` and rebuilds it; use `roll` and `zoom` | | an SVG path from an editor comes out scrambled | `parseSVGPath` reads absolute commands only, and `H` / `V` as offsets | | a hole in a path fills in, on Canvas only | it is wound the same way as the outline; wind it the opposite way | diff --git a/packages/melonjs/skills/melonjs-scenes-and-state/SKILL.md b/packages/melonjs/skills/melonjs-scenes-and-state/SKILL.md index 3ad64a4a30..00662de9d6 100644 --- a/packages/melonjs/skills/melonjs-scenes-and-state/SKILL.md +++ b/packages/melonjs/skills/melonjs-scenes-and-state/SKILL.md @@ -1,6 +1,6 @@ --- name: melonjs-scenes-and-state -description: "Use this skill for scene structure and game flow in melonJS — Stage subclasses, the state manager, transitions, pausing, the update loop, timers and tweens. Covers onResetEvent versus the constructor, state.set before state.change, the camera and world lifecycle per stage, and pause-aware timing. Triggers on: Tween, easing, fade out, flash, pulse, punch, shrink back, ease in, ease out, animate over time, countdown in update, Stage, state, state.set, state.change, state.transition, pixelate, Trigger transition, retry level, play again, restart, state.reload, state.pause, pauseOnBlur, resumeOnFocus, onResetEvent, onDestroyEvent, onActivateEvent, onDeactivateEvent, PLAY, MENU, LOADING, update loop, GAME_UPDATE, timer, setTimeout, setInterval, Tween, freeze, setFocusEvents, focusEvents, host or portal pause, YouTube Playables onPause, save, save.add, setStorage, createCloudStorage, flush, localStorage, cloud save, high score persistence." +description: "Use this skill for scene structure and game flow in melonJS — Stage subclasses, the state manager, transitions, pausing, the update loop, timers and tweens. Covers onResetEvent versus the constructor, state.set before state.change, the camera and world lifecycle per stage, and pause-aware timing. Triggers on: Tween, easing, fade out, flash, pulse, punch, shrink back, ease in, ease out, animate over time, countdown in update, Stage, state, state.set, state.change, state.transition, pixelate, iris, star wipe, Trigger transition, retry level, play again, restart, state.reload, state.pause, pauseOnBlur, resumeOnFocus, onResetEvent, onDestroyEvent, onActivateEvent, onDeactivateEvent, PLAY, MENU, LOADING, update loop, GAME_UPDATE, timer, setTimeout, setInterval, Tween, freeze, setFocusEvents, focusEvents, host or portal pause, YouTube Playables onPause, save, save.add, setStorage, createCloudStorage, flush, localStorage, cloud save, high score persistence." license: MIT --- @@ -133,6 +133,9 @@ included (before 20.13 the children's bodies were dropped by the reset). ```js state.transition("fade", "#FFFFFF", 250); state.transition("mask", "#000", 500, new Ellipse(0, 0, 1, 1)); // shape required +state.transition("mask", "#000", 500, "star_mask"); // a preloaded image's silhouette +state.transition("mask", "#000", 500, player, { center: player }); // the player's shape, closing on it +state.transition("mask", "#000", 400, new Ellipse(0, 0, 1, 1), { center: player, invert: true }); state.transition("pixelate", "#000", 300); // blocks up to 32px; a 4th argument sets the size state.pause(); // freeze update, keep drawing state.resume(); @@ -143,8 +146,26 @@ app.freeze(150); // brief hit-stop (proxies state.fr `state.change`; `state.setTransition(id, false)` turns it off for changes into one state. The duration (1000 ms when omitted) is for each half: the cover, then the -reveal. The `"mask"` form needs its fourth argument, an `Ellipse` or -`Polygon`; without one it warns and falls back to a direct switch. The +reveal. The `"mask"` form needs its fourth argument, the shape: an `Ellipse` +or `Polygon` (unit-sized, centred on the origin), an image or the name of a +preloaded one (its silhouette: transparent pixels are covered, the rest shows +the scene; colours do not matter and gaps inside the outline are filled), or a +`Sprite` (the silhouette of the frame it shows, facing its way). Without a +shape it warns and falls back to a direct switch. Its fifth argument is +`{ center, invert }`: `center` is where the shape closes and the reveal opens, +a renderable (where it is drawn on screen as the transition starts) or a +screen point, the centre of the screen by default; `invert: true` makes the +shape the cover, filled with the colour and growing out of `center`. The +shape grows about its thickest part (a U or a sprite drawn off-centre in its +frame too), until the screen is wholly inside it, so the reveal ends with the +scene uncovered. + +A sprite or renderable given here is read when the transition starts, and +the reveal reuses what the hide read, so the old stage destroying the player +in between is fine. It is then let go: the transition is sticky, but one +level's player is not the next one's, so later changes are an iris on the +centre of the screen until you set it again. Give it this level's player +right before each `state.change`. The `"pixelate"` form breaks the screen up into blocks (its fourth argument is the largest block size in pixels; the color is not used). It is a shader effect, so on Canvas it does nothing and the state changes directly. @@ -152,9 +173,12 @@ so on Canvas it does nothing and the state changes directly. A level change is not a state change, so `state.transition` does not apply to it. A Tiled `Trigger` that loads a level has a transition of its own, set on the trigger: `color` and `duration` (both needed, or the level loads with -none), and `transition: "fade"` (the default) or `"mask"` with a `shape`. -A `"mask"` without a `shape` fades instead, without a warning, and there is -no pixelate form for a trigger. See `melonjs-tilemaps`. +none), and `transition: "fade"` (the default) or `"mask"` with a `shape`, +plus `center` and `invert` as above. On a trigger, `shape: "touching"` and +`center: "touching"` mean whoever walked in: the player's own silhouette +closing on the player, with no code to find it. A `"mask"` without a `shape` +fades instead, without a warning, and there is no pixelate form for a +trigger. See `melonjs-tilemaps`. A `state.change` asked for while a transition covers the screen (Enter pressed twice on a menu, a timer firing as the player skips a screen) needs no guard: @@ -571,6 +595,8 @@ When `setStorage()` switches storage: | a host's pause does nothing, after turning `pauseOnBlur` off so the tab would not pause the game | the flags apply to every `event.BLUR`, the host's included; keep them, and stop the window reporting with `device.setFocusEvents(false)` | | `Undefined Stage for state 'N'` thrown | no `state.set` for that id first | | `state.change(state.PLAY)` from `PLAY` does nothing ("Retry" ignored) | a change to the current state is a no-op — `state.reload()` (20.16), `level.reload()` for the map alone | +| a mask transition closes on the middle of the screen, not on the player | pass `{ center: player }` as the fifth argument; on a `Trigger`, `center: "touching"` | +| the first mask transition is the player's shape, later ones a plain iris on the middle of the screen | a sprite or renderable given to `state.transition` is used by one transition, then let go: set it again, with this level's player, right before each `state.change` | | a level change through a `Trigger` ignores `state.transition` | it is a level change, not a state change: set `color` and `duration` (and `transition`) on the trigger | | the game stops updating for good after one very slow update, such as a heavy first frame (20.12 and 20.13) | the loop could no longer save enough time to step the world: update | | the game resumes under its own pause menu after a tab switch (before 20.9) | focus undid any pause; update, only the blur pause is undone | diff --git a/packages/melonjs/skills/melonjs-tilemaps/SKILL.md b/packages/melonjs/skills/melonjs-tilemaps/SKILL.md index 574e526aab..51481cf2af 100644 --- a/packages/melonjs/skills/melonjs-tilemaps/SKILL.md +++ b/packages/melonjs/skills/melonjs-tilemaps/SKILL.md @@ -205,6 +205,16 @@ knowing before you spend an afternoon on a map that loads at the wrong scale. `async` is excluded deliberately — the trigger needs to sequence its own transition. +That transition is the trigger's own, and every part of it can be a property +of the trigger object in Tiled, with no code: `color` and `duration` (both, or +there is none), `transition` (`"fade"` or `"mask"`), and for a mask `shape`, +`center` and `invert`. A `shape` property is text, so it names a preloaded +image (its silhouette) or is `"touching"`; `center: "touching"` closes the +mask on whoever walked in. So a door that closes the player's own silhouette +onto the player is the properties `transition = mask`, `shape = touching`, +`center = touching`, `color = #000`, `duration = 400`. See +`melonjs-scenes-and-state` for the shapes and what `invert` does. + ## Reading and changing tiles at run time A tile layer is a live grid, not just a picture: read it as the game board, diff --git a/packages/melonjs/skills/melonjs/SKILL.md b/packages/melonjs/skills/melonjs/SKILL.md index d584fd0f5f..80a00f1e7c 100644 --- a/packages/melonjs/skills/melonjs/SKILL.md +++ b/packages/melonjs/skills/melonjs/SKILL.md @@ -176,7 +176,9 @@ check for: - **Art:** `TextureAtlas` (TexturePacker, ShoeBox, Aseprite), `CanvasRenderTarget` for bake-once drawing, `NoiseTexture2d`. - **Game flow:** `state.transition()` (`"fade"`, `"mask"` or `"pixelate"`) - between screens, `state.pause()` / `state.resume()` behind a pause menu, + between screens, with a mask shaped like an image or the player's own sprite + and closing on the player (`center`), and a `Trigger`'s own transition for a + level door (`shape: "touching"`, `center: "touching"`), `state.pause()` / `state.resume()` behind a pause menu, `save` for localStorage-backed persistence, `createPool` / `getPool` for recycling. - **Levels:** Tiled tile layers read and changed with `cellAt` / `setTile`, diff --git a/packages/melonjs/src/camera/effects/mask_effect.ts b/packages/melonjs/src/camera/effects/mask_effect.ts index fc444ed9b5..dd1edd28d7 100644 --- a/packages/melonjs/src/camera/effects/mask_effect.ts +++ b/packages/melonjs/src/camera/effects/mask_effect.ts @@ -1,20 +1,478 @@ import { Ellipse, ellipsePool } from "../../geometries/ellipse.ts"; import { Polygon, polygonPool } from "../../geometries/polygon.ts"; +import { warnOnce } from "../../lang/console.js"; +import { getImage } from "../../loader/cache.js"; import type { Color } from "../../math/color.ts"; import { colorPool } from "../../math/color.ts"; +import { Vector2d } from "../../math/vector2d.ts"; +import { Vector3d } from "../../math/vector3d.ts"; +import type Renderable from "../../renderable/renderable.js"; +import type Sprite from "../../renderable/sprite.js"; import type Tween from "../../tweens/tween.ts"; import { tweenPool } from "../../tweens/tween.ts"; import type Renderer from "../../video/renderer.js"; +import CanvasRenderTarget from "../../video/rendertarget/canvasrendertarget.js"; import type Camera2d from "../camera2d.ts"; import CameraEffect from "./camera_effect.ts"; -type MaskShape = Ellipse | Polygon; +/** + * An image whose silhouette shapes a {@link MaskEffect}: a loaded image + * (`loader.getImage()`), or a canvas drawn by the game. + * @category Camera + */ +export type MaskImage = + | HTMLImageElement + | HTMLCanvasElement + | OffscreenCanvas + | ImageBitmap; + +/** + * What a {@link MaskEffect} is shaped like: + * - an `Ellipse` (an iris) or a `Polygon`, unit-sized; + * - an image, or the name of a preloaded one: its silhouette; + * - a `Sprite`: the silhouette of the frame it shows when the effect starts. + * @category Camera + */ +export type MaskShape = Ellipse | Polygon | MaskImage | Sprite | string; + +/** + * Where a {@link MaskEffect} closes and opens: a renderable, at the place + * on screen it is drawn when the effect starts, or a point in the camera's + * screen coordinates. + * @category Camera + */ +export type MaskCenter = Renderable | { x: number; y: number }; + +/** + * The settings of a {@link MaskEffect}, as its constructor takes them. + * @category Camera + */ +export interface MaskEffectOptions { + /** + * an `Ellipse` or `Polygon` (unit-sized), an image or the name of a + * preloaded one, or a `Sprite`; an iris when omitted + */ + shape?: MaskShape | undefined; + /** CSS color value or Color instance for the transition fill */ + color: Color | string; + /** transition duration in milliseconds (500 by default) */ + duration?: number | undefined; + /** "hide" covers the scene (the default), "reveal" uncovers it */ + direction?: "hide" | "reveal" | undefined; + /** + * where the shape closes and opens: a renderable (where it is drawn when + * the effect starts) or a point in the camera's screen coordinates. The + * centre of the screen by default + */ + center?: MaskCenter | undefined; + /** + * make the shape the cover rather than the window: it grows out of + * `center` to hide the scene + */ + invert?: boolean | undefined; + /** callback when the transition finishes */ + onComplete?: (() => void) | undefined; +} + +/** the largest side a silhouette is kept at, in pixels */ +const MAX_SILHOUETTE = 512; +/** clear pixels kept round a silhouette, so its outside is one region */ +const PAD = 2; + +/** a world point to project with a 3D camera; never escapes `resolveCenter` */ +const _world3d = new Vector3d(); +/** where a 2D camera draws a world point; never escapes `resolveCenter` */ +const _local = new Vector2d(); + +/** + * A shape, settled for drawing: the point it grows about, in its own + * units, and the radius of the largest circle round that point inside it. + * Once that circle reaches the screen's farthest corner, the screen is + * wholly inside the shape. + * @ignore + */ +interface Anchor { + x: number; + y: number; + inner: number; +} + +/** + * A silhouette made from an image or a sprite: solid white where it is, + * clear around it, with a small clear margin, and the point it grows about. + * @ignore + */ +interface Silhouette extends Anchor { + target: CanvasRenderTarget; +} + +/** + * The silhouettes made so far, by their canvas: one handed back as a shape + * (the reveal of a transition, from its hide) is used as it is, not made + * again from itself. + * @ignore + */ +const baked = new WeakMap(); + +/** + * The point of a silhouette farthest from its edge (the middle of its + * thickest part), and the exact distance from there to the edge. + * + * A shape grown about its own centre would not do: the centre of a U, a + * crescent or a sprite drawn off-centre in its frame is outside it, and no + * size of it would ever hold the screen. A two-pass distance transform + * finds the thickest part; ties go to the one nearest the centre, so a + * symmetric shape still grows about its middle. + * @ignore + */ +function deepestPoint( + inside: Uint8Array, + cw: number, + ch: number, +): Anchor | null { + const count = cw * ch; + const far = cw + ch; + const dist = new Float32Array(count); + for (let i = 0; i < count; i++) { + dist[i] = inside[i] === 1 ? far : 0; + } + const D = Math.SQRT2; + for (let y = 0; y < ch; y++) { + for (let x = 0; x < cw; x++) { + const i = y * cw + x; + if (dist[i] === 0) continue; + let d = dist[i]; + if (x > 0) d = Math.min(d, dist[i - 1] + 1); + if (y > 0) { + d = Math.min(d, dist[i - cw] + 1); + if (x > 0) d = Math.min(d, dist[i - cw - 1] + D); + if (x < cw - 1) d = Math.min(d, dist[i - cw + 1] + D); + } + dist[i] = d; + } + } + let best = -1; + let bestD = 0; + let bestC = Infinity; + for (let y = ch - 1; y >= 0; y--) { + for (let x = cw - 1; x >= 0; x--) { + const i = y * cw + x; + if (dist[i] === 0) continue; + let d = dist[i]; + if (x < cw - 1) d = Math.min(d, dist[i + 1] + 1); + if (y < ch - 1) { + d = Math.min(d, dist[i + cw] + 1); + if (x < cw - 1) d = Math.min(d, dist[i + cw + 1] + D); + if (x > 0) d = Math.min(d, dist[i + cw - 1] + D); + } + dist[i] = d; + const c = (x + 0.5 - cw / 2) ** 2 + (y + 0.5 - ch / 2) ** 2; + if (d > bestD + 1e-6 || (Math.abs(d - bestD) <= 1e-6 && c < bestC)) { + best = i; + bestD = d; + bestC = c; + } + } + } + if (best < 0) { + return null; + } + // the exact distance to the edge from there (the transform is close, not + // exact): the nearest pixel outside, less half a pixel for its edge + const ax = (best % cw) + 0.5; + const ay = Math.floor(best / cw) + 0.5; + let nearest = Infinity; + for (let i = 0; i < count; i++) { + if (inside[i] === 0) { + const dx = (i % cw) + 0.5 - ax; + const dy = Math.floor(i / cw) + 0.5 - ay; + const d = dx * dx + dy * dy; + if (d < nearest) { + nearest = d; + } + } + } + return { x: ax, y: ay, inner: Math.max(0.5, Math.sqrt(nearest) - 0.5) }; +} + +/** + * Draw `draw` into a canvas `w` × `h` (plus the margin) and make a solid + * silhouette of it, or `null` when nothing was drawn. + * + * Solid twice over: a pixel more than faintly opaque counts in full, so a + * sprite's glass or soft shading leaves no see-through patches, and any + * clear area the outside cannot reach (an eye, the gap between a helmet and + * a head) is filled, so only the outline matters. + * @ignore + */ +function bakeSilhouette( + w: number, + h: number, + draw: (context: CanvasRenderingContext2D) => void, +): Silhouette | null { + const cw = w + PAD * 2; + const ch = h + PAD * 2; + const target = new CanvasRenderTarget(cw, ch, { + context: "2d", + willReadFrequently: true, + }); + const context = target.context as CanvasRenderingContext2D; + context.save(); + context.translate(PAD, PAD); + draw(context); + context.restore(); + + const image = target.getImageData(0, 0, cw, ch); + const data = image.data; + const count = cw * ch; + // opaque from a low threshold up: soft edges stay a little soft + for (let i = 0; i < count; i++) { + const a = data[i * 4 + 3]; + data[i * 4 + 3] = Math.min(255, Math.max(0, (a - 24) * 4)); + } + // flood the outside from the margin; whatever it cannot reach is inside + const inside = new Uint8Array(count).fill(1); + const stack: number[] = []; + const visit = (i: number) => { + if (inside[i] === 1 && data[i * 4 + 3] < 128) { + inside[i] = 0; + stack.push(i); + } + }; + for (let x = 0; x < cw; x++) { + visit(x); + visit((ch - 1) * cw + x); + } + for (let y = 0; y < ch; y++) { + visit(y * cw); + visit(y * cw + cw - 1); + } + while (stack.length > 0) { + const i = stack.pop()!; + const x = i % cw; + if (x > 0) visit(i - 1); + if (x < cw - 1) visit(i + 1); + if (i >= cw) visit(i - cw); + if (i < count - cw) visit(i + cw); + } + const anchor = deepestPoint(inside, cw, ch); + if (anchor === null) { + target.destroy(); + return null; + } + for (let i = 0; i < count; i++) { + const o = i * 4; + data[o] = 255; + data[o + 1] = 255; + data[o + 2] = 255; + if (inside[i] === 1) { + data[o + 3] = 255; + } + } + context.putImageData(image, 0, 0); + const silhouette = { target, ...anchor }; + baked.set(target.canvas, silhouette); + return silhouette; +} + +/** + * The silhouette of an image, at most {@link MAX_SILHOUETTE} on a side. + * @ignore + */ +function imageSilhouette(image: MaskImage): Silhouette | null { + const k = Math.min( + 1, + MAX_SILHOUETTE / Math.max(image.width, image.height, 1), + ); + const w = Math.max(1, Math.round(image.width * k)); + const h = Math.max(1, Math.round(image.height * k)); + return bakeSilhouette(w, h, (context) => { + context.drawImage(image, 0, 0, w, h); + }); +} + +/** + * The silhouette of the frame a sprite shows now, drawn by the sprite + * itself ({@link Sprite#drawFrame}: an atlas region trimmed or stored + * turned, the nine slices of a `NineSliceSprite`), and flipped the way it + * is. At most {@link MAX_SILHOUETTE} on a side. + * @ignore + */ +function spriteSilhouette(sprite: Sprite): Silhouette | null { + const sw = Math.max(1, sprite.width); + const sh = Math.max(1, sprite.height); + const k = Math.min(1, MAX_SILHOUETTE / Math.max(sw, sh)); + return bakeSilhouette( + Math.max(1, Math.round(sw * k)), + Math.max(1, Math.round(sh * k)), + (context) => { + context.scale(k, k); + if (sprite.isFlippedX || sprite.isFlippedY) { + context.translate( + sprite.isFlippedX ? sw : 0, + sprite.isFlippedY ? sh : 0, + ); + context.scale(sprite.isFlippedX ? -1 : 1, sprite.isFlippedY ? -1 : 1); + } + ( + sprite as Sprite & { + drawFrame: ( + target: CanvasRenderingContext2D, + x: number, + y: number, + ) => void; + } + ).drawFrame(context, 0, 0); + }, + ); +} + +/** + * The point a polygon grows about, in its own units: its origin when it + * surrounds it, as a unit-sized template is meant to, or else the inside + * point farthest from its edges. `null` for a polygon with no inside. + * @ignore + */ +function polygonAnchor(polygon: Polygon): Anchor | null { + const points = polygon.points; + const isInside = (x: number, y: number) => { + return polygon.contains(polygon.pos.x + x, polygon.pos.y + y); + }; + const toEdge = (x: number, y: number) => { + let nearest = Infinity; + for (let i = 0; i < points.length; i++) { + const a = points[i]; + const b = points[(i + 1) % points.length]; + const ex = b.x - a.x; + const ey = b.y - a.y; + const len2 = ex * ex + ey * ey; + const t = + len2 > 0 + ? Math.min(1, Math.max(0, ((x - a.x) * ex + (y - a.y) * ey) / len2)) + : 0; + nearest = Math.min( + nearest, + Math.hypot(a.x + ex * t - x, a.y + ey * t - y), + ); + } + return nearest; + }; + if (isInside(0, 0)) { + const inner = toEdge(0, 0); + if (inner > 1e-6) { + return { x: 0, y: 0, inner }; + } + } + // not about its origin: the deepest point of a grid over its bounds + let minX = Infinity; + let minY = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + for (const p of points) { + minX = Math.min(minX, p.x); + minY = Math.min(minY, p.y); + maxX = Math.max(maxX, p.x); + maxY = Math.max(maxY, p.y); + } + const STEPS = 32; + let best: Anchor | null = null; + for (let j = 0; j < STEPS; j++) { + for (let i = 0; i < STEPS; i++) { + const x = minX + ((i + 0.5) / STEPS) * (maxX - minX); + const y = minY + ((j + 0.5) / STEPS) * (maxY - minY); + if (isInside(x, y)) { + const inner = toEdge(x, y); + if (best === null || inner > best.inner) { + best = { x, y, inner }; + } + } + } + } + return best !== null && best.inner > 1e-6 ? best : null; +} + +/** + * true for a `Sprite`, told apart without importing the class + * @param shape - the value to test + * @returns whether `shape` is a sprite + */ +function isSprite(shape: unknown): shape is Sprite { + return ( + typeof shape === "object" && + shape !== null && + "current" in shape && + "image" in shape && + "offset" in shape && + typeof (shape as { drawFrame?: unknown }).drawFrame === "function" + ); +} + +/** + * true for a renderable, told apart without importing the class. Not by + * `getBounds`, which the geometry classes have too: a renderable is a + * `Rect`, and so a `Polygon`, but one that draws. + * @ignore + * @param value - the value to test + * @returns whether `value` is a renderable + */ +export function isRenderable(value: unknown): value is Renderable { + return ( + typeof value === "object" && + value !== null && + typeof (value as Renderable).preDraw === "function" && + typeof (value as Renderable).getBounds === "function" + ); +} + +/** + * true for an image or a canvas a silhouette can be read from + * @param value - the value to test + * @returns whether `value` is an image + */ +function isImage(value: unknown): value is MaskImage { + return ( + (typeof HTMLImageElement !== "undefined" && + value instanceof HTMLImageElement) || + (typeof HTMLCanvasElement !== "undefined" && + value instanceof HTMLCanvasElement) || + (typeof OffscreenCanvas !== "undefined" && + value instanceof OffscreenCanvas) || + (typeof ImageBitmap !== "undefined" && value instanceof ImageBitmap) || + // a canvas from another realm, or a host's own (a DOM-less runtime) + (typeof value === "object" && + value !== null && + typeof (value as HTMLCanvasElement).getContext === "function" && + typeof (value as HTMLCanvasElement).width === "number") + ); +} /** * A camera effect that performs a mask-based scene transition. - * A shape (ellipse, polygon) is scaled from full-screen to zero (hide) - * or from zero to full-screen (reveal), with the area outside the shape - * filled with a solid color. + * + * A shape closes on a point to hide the scene, filling the screen around + * it with a solid color, and opens from it again to reveal the scene. The + * shape can be: + * - an `Ellipse` (an iris, the default) or a `Polygon`, unit-sized and + * centred on its origin; + * - an image, or the name of a preloaded one: the shape is its silhouette, + * its transparent pixels outside and the others inside (colors do not + * matter, and gaps inside the outline are filled); + * - a `Sprite`: the silhouette of the frame it shows when the effect + * starts, facing the way it faces (not its scale or rotation: the shape + * is grown to the screen's size anyway). + * + * The shape grows and shrinks about its thickest part (the origin of a + * unit `Polygon` or `Ellipse`), and that point sits on the centre of the + * screen, or on `center`: a renderable, at the place it is drawn when the + * effect starts, such as the player. With `invert`, the shape is the cover + * instead of the window: filled with the color, it grows out of that point + * until it covers the screen, and shrinks away to reveal it. + * + * Whatever the shape and the point, the shape is grown until it holds the + * whole screen, so a reveal ends with the scene fully uncovered. It is + * drawn with plain images and fills, the same on every renderer. A shape + * that cannot be used (an unknown image name, an image that cannot be read, + * an empty one, a destroyed sprite) warns once and is an iris instead. * @category Camera * @example * // iris transition (circle shrinks to hide the scene) @@ -35,6 +493,30 @@ type MaskShape = Ellipse | Polygon; * duration: 500, * direction: "reveal", * })); + * @example + * // a star wipe from a preloaded silhouette image + * camera.addCameraEffect(new MaskEffect(camera, { + * shape: "star_mask", // or loader.getImage("star_mask") + * color: "#000", + * duration: 500, + * })); + * @example + * // the player's own silhouette closing on the player + * camera.addCameraEffect(new MaskEffect(camera, { + * shape: player, + * center: player, + * color: "#000", + * duration: 500, + * })); + * @example + * // a black heart growing out of the player until it covers the screen + * camera.addCameraEffect(new MaskEffect(camera, { + * shape: "heart_mask", + * center: player, + * invert: true, + * color: "#000", + * duration: 400, + * })); */ export default class MaskEffect extends CameraEffect { /** @@ -43,9 +525,29 @@ export default class MaskEffect extends CameraEffect { color: Color; /** - * the mask shape template (unit-sized, centered at origin) + * the shape as given: an `Ellipse` or `Polygon` template, an image, the + * name of one, or a sprite; `undefined` for the default iris */ - shape: MaskShape; + shape: MaskShape | undefined; + + /** + * the point the shape closes on and opens from, in the camera's screen + * coordinates, read when the effect started; `undefined` for the centre + * of the screen + */ + center: { x: number; y: number } | undefined; + + /** + * `true` when the shape is the cover rather than the window: it grows + * to hide the scene and shrinks to reveal it + * @default false + */ + invert: boolean; + + /** + * the transition duration, in milliseconds + */ + duration: number; /** * current progress value (0 = fully covered, 1 = fully visible) @@ -68,60 +570,291 @@ export default class MaskEffect extends CameraEffect { onComplete: (() => void) | undefined; /** - * pooled shape used for rendering (avoids per-frame allocation) + * pooled shape used for rendering a geometric mask (avoids per-frame + * allocation); `undefined` for an image or sprite mask + * @ignore + * @internal + */ + _maskShape: Ellipse | Polygon | undefined; + + /** + * the unit `Polygon` template the drawn polygon is scaled from + * @ignore + * @internal + */ + _template: Polygon | undefined; + + /** + * the silhouette of an image or sprite mask, white on clear + * @ignore + * @internal + */ + _silhouette: Silhouette | undefined; + + /** + * what is drawn of an image or sprite mask: the color round the + * silhouette (or, inverted, the silhouette in the color) + * @ignore + * @internal + */ + _cover: CanvasRenderTarget | undefined; + + /** + * the point the shape grows about, in its own units, and the radius of + * the largest circle round it inside the shape + * @ignore + * @internal + */ + _anchor: Anchor; + + /** + * the renderer that drew the cover, to free its copy on the GPU * @ignore * @internal */ - _maskShape: MaskShape; + _renderer: Renderer | undefined; /** * @param camera - the camera to apply the transition to - * @param options - transition parameters - * @param options.shape - an Ellipse or Polygon (unit-sized, centered at origin) defining the mask shape + * @param options - transition parameters, see {@link MaskEffectOptions} + * @param [options.shape] - an `Ellipse` or `Polygon` (unit-sized), an + * image or the name of a preloaded one, or a `Sprite`; an iris when omitted * @param options.color - CSS color value or Color instance for the transition fill * @param [options.duration=500] - transition duration in milliseconds - * @param [options.direction="hide"] - "hide" shrinks the visible area, "reveal" grows it + * @param [options.direction="hide"] - "hide" covers the scene, "reveal" uncovers it + * @param [options.center] - where the shape closes and opens: a + * renderable (where it is drawn when the effect starts) or a point in the + * camera's screen coordinates. The centre of the screen by default + * @param [options.invert=false] - make the shape the cover rather than + * the window: it grows out of `center` to hide the scene * @param [options.onComplete] - callback when the transition finishes */ - constructor( - camera: Camera2d, - options: { - shape: MaskShape; - color: Color | string; - duration?: number | undefined; - direction?: "hide" | "reveal" | undefined; - onComplete?: (() => void) | undefined; - }, - ) { + constructor(camera: Camera2d, options: MaskEffectOptions) { super(camera); this.color = colorPool.get(options.color); this.direction = options.direction ?? "hide"; this.onComplete = options.onComplete; - + this.invert = options.invert === true; + this.duration = options.duration ?? 500; this.shape = options.shape; + this._maskShape = undefined; + this._template = undefined; + this._silhouette = undefined; + this._cover = undefined; + this._renderer = undefined; + this._anchor = { x: 0, y: 0, inner: 1 }; - // clone the shape for rendering - this._maskShape = this.shape.clone(); + this._resolveShape(options.shape); + this.center = this._resolveCenter(options.center); // progress: 1 = fully visible, 0 = fully covered - const duration = options.duration ?? 500; if (this.direction === "hide") { this.progress = { value: 1.0 }; this.tween = tweenPool .get(this.progress) - .to({ value: 0.0 }, { duration }); + .to({ value: 0.0 }, { duration: this.duration }); } else { this.progress = { value: 0.0 }; this.tween = tweenPool .get(this.progress) - .to({ value: 1.0 }, { duration }); + .to({ value: 1.0 }, { duration: this.duration }); } this.tween.isPersistent = true; this.tween.start(); } + /** + * The settings of the effect that plays this one backwards: the other + * direction, with the same color, duration and `invert`, the shape this + * one settled when it started (the silhouette a sprite gave, though the + * sprite may be gone by then) and the point it closed on. Read them + * while this effect is still on its camera. Used by `state.transition` + * and `Trigger` for their reveal. + * @ignore + * @internal + * @param [onComplete] - a callback for the new effect + * @returns the settings for a new `MaskEffect` + */ + reverseOptions(onComplete?: () => void): MaskEffectOptions { + return { + shape: this._silhouette?.target.canvas ?? this._template ?? this.shape, + color: this.color.toRGBA(), + duration: this.duration, + direction: this.direction === "hide" ? "reveal" : "hide", + center: this.center, + invert: this.invert, + onComplete, + }; + } + + /** + * Settle the shape: a template to scale, or a silhouette to draw. + * @ignore + */ + _resolveShape(shape: MaskShape | undefined): void { + let source: unknown = shape; + const fallBack = (why: string) => { + warnOnce(`melonJS: MaskEffect: ${why}, an iris is used instead`); + source = undefined; + }; + if (typeof source === "string") { + source = getImage(source) ?? undefined; + if (source === undefined) { + fallBack(`no loaded image named "${shape as string}"`); + } + } + if ( + isRenderable(source) && + !isSprite(source) && + isSprite((source as Renderable & { renderable?: unknown }).renderable) + ) { + // an Entity: the sprite it draws + source = (source as Renderable & { renderable: Sprite }).renderable; + } + + if (source === undefined) { + // the default iris, or the fallback for a shape that cannot be used + } else if (source instanceof Ellipse) { + this._maskShape = source.clone(); + } else if (isSprite(source)) { + if (source.offset === undefined || source.image === undefined) { + fallBack("the sprite was destroyed before the transition started"); + } else { + const sprite = source; + this._silhouette = this._bake(() => { + return spriteSilhouette(sprite); + }); + } + } else if (isRenderable(source)) { + fallBack( + "of the renderables, only a Sprite can shape a mask (its current frame)", + ); + } else if (source instanceof Polygon) { + const anchor = polygonAnchor(source); + if (anchor === null) { + fallBack("the polygon has no inside"); + } else { + this._template = source; + this._maskShape = source.clone(); + this._anchor = anchor; + } + } else if (isImage(source)) { + const image = source; + this._silhouette = + baked.get(image) ?? + this._bake(() => { + return imageSilhouette(image); + }); + } else { + fallBack( + "the shape is not an Ellipse, a Polygon, an image or its name, or a Sprite", + ); + } + + if (this._silhouette !== undefined) { + const { x, y, inner } = this._silhouette; + this._anchor = { x, y, inner }; + this._cover = this._makeCover(this._silhouette); + } else if (this._maskShape === undefined) { + this._maskShape = ellipsePool.get(0, 0, 1, 1); + } + } + + /** + * Bake a silhouette, or `undefined` (and a warning) for an image the + * browser cannot read back (a compressed texture, a cross-origin image) + * or one with nothing in it. + * @ignore + */ + _bake(bake: () => Silhouette | null): Silhouette | undefined { + let silhouette: Silhouette | null; + try { + silhouette = bake(); + } catch { + warnOnce( + "melonJS: MaskEffect: the image could not be read (a compressed texture, or a cross-origin image), an iris is used instead", + ); + return undefined; + } + if (silhouette === null) { + warnOnce( + "melonJS: MaskEffect: the image or frame is fully transparent, an iris is used instead", + ); + return undefined; + } + return silhouette; + } + + /** + * What is drawn: the color everywhere but the silhouette, or inverted, + * the silhouette in the color. + * @ignore + */ + _makeCover(silhouette: Silhouette): CanvasRenderTarget { + const canvas = silhouette.target.canvas; + const cover = new CanvasRenderTarget(canvas.width, canvas.height, { + context: "2d", + }); + const context = cover.context as CanvasRenderingContext2D; + context.fillStyle = this.color.toRGBA(); + if (this.invert) { + context.drawImage(canvas, 0, 0); + context.globalCompositeOperation = "source-in"; + context.fillRect(0, 0, canvas.width, canvas.height); + } else { + context.fillRect(0, 0, canvas.width, canvas.height); + context.globalCompositeOperation = "destination-out"; + context.drawImage(canvas, 0, 0); + } + context.globalCompositeOperation = "source-over"; + return cover; + } + + /** + * Where the shape closes, in the camera's screen coordinates, read once. + * @ignore + */ + _resolveCenter( + center: MaskCenter | undefined, + ): { x: number; y: number } | undefined { + if (center === undefined) { + return undefined; + } + if (!isRenderable(center)) { + if (Number.isFinite(center.x) && Number.isFinite(center.y)) { + return { x: center.x, y: center.y }; + } + return undefined; + } + if (center.ancestor === undefined) { + warnOnce( + "melonJS: MaskEffect: the center renderable is not in the world, the centre of the screen is used instead", + ); + return undefined; + } + const bounds = center.getBounds(); + const x = bounds.centerX; + const y = bounds.centerY; + // in a floating container too (whose children are not `floating` + // themselves): its bounds are on the screen already + if (center.isFloating) { + return { x, y }; + } + const camera = this.camera as Camera2d & { + worldToScreen?: (world: Vector3d) => Vector2d | null; + }; + if (typeof camera.worldToScreen === "function") { + // the bounds are absolute, so the depth must be too + const depth = center.getAbsolutePosition().z; + const screen = camera.worldToScreen(_world3d.set(x, y, depth)); + return screen === null ? undefined : { x: screen.x, y: screen.y }; + } + camera.worldToLocal(x, y, _local); + return { x: _local.x - camera.screenX, y: _local.y - camera.screenY }; + } + override update(): void { // check if the transition has completed if ( @@ -141,27 +874,6 @@ export default class MaskEffect extends CameraEffect { this.onComplete(); } } - return; - } - - // update the mask shape based on current progress - const width = this.camera.width; - const height = this.camera.height; - const maxRadius = Math.sqrt(width * width + height * height) / 2; - const scale = this.progress.value * maxRadius; - const cx = width / 2; - const cy = height / 2; - - if (this._maskShape.type === "Ellipse") { - (this._maskShape as Ellipse).setShape(cx, cy, scale * 2, scale * 2); - } else { - // set scaled vertices directly - const mask = this._maskShape as Polygon; - const srcPoints = (this.shape as Polygon).points; - for (let i = 0; i < srcPoints.length; i++) { - mask.points[i].set(srcPoints[i].x * scale, srcPoints[i].y * scale); - } - mask.pos.set(cx, cy); } } @@ -170,23 +882,119 @@ export default class MaskEffect extends CameraEffect { return; } + const visible = this.progress.value; + const cx = this.center?.x ?? width / 2; + const cy = this.center?.y ?? height / 2; + // the corner farthest from the point: once the shape's inner circle + // reaches it, the shape holds the whole screen + const far = Math.max( + Math.hypot(cx, cy), + Math.hypot(width - cx, cy), + Math.hypot(cx, height - cy), + Math.hypot(width - cx, height - cy), + ); + // how far the shape is grown: the window shrinks as the scene is + // hidden, the cover grows + const grown = this.invert ? 1 - visible : visible; + const scale = (grown * far) / this._anchor.inner; + const r = renderer as any; r.save(); r.resetTransform(); + r.setColor(this.color); - if (this.progress.value <= 0.0) { - // fully covered — just fill with color - r.setColor(this.color); + if ((this.invert && grown >= 1) || (!this.invert && grown <= 0)) { + // fully covered r.fillRect(0, 0, width, height); + } else if (grown > 0 || !this.invert) { + if (this._cover !== undefined) { + this._renderer = renderer; + this._drawCover(r, cx, cy, scale, width, height); + } else { + this._drawShape(r, cx, cy, scale, width, height); + } + } + + r.restore(); + } + + /** + * Draw a geometric mask at `scale`, its anchor on (`cx`, `cy`). + * @ignore + */ + _drawShape( + r: any, + cx: number, + cy: number, + scale: number, + width: number, + height: number, + ): void { + const mask = this._maskShape!; + if (this._template === undefined) { + (mask as Ellipse).setShape(cx, cy, scale * 2, scale * 2); + } else { + const points = this._template.points; + const polygon = mask as Polygon; + const { x, y } = this._anchor; + for (let i = 0; i < points.length; i++) { + polygon.points[i].set( + (points[i].x - x) * scale, + (points[i].y - y) * scale, + ); + } + polygon.pos.set(cx, cy); + } + if (this.invert) { + r.fill(mask); } else { - // mask: only fill OUTSIDE the shape (invert = true) - r.setMask(this._maskShape, true); - r.setColor(this.color); + // only fill OUTSIDE the shape (invert = true) + r.setMask(mask, true); r.fillRect(0, 0, width, height); r.clearMask(); } + } - r.restore(); + /** + * Draw an image or sprite mask at `scale`, its anchor on (`cx`, `cy`): + * the cover image, and for a window the color round it. + * @ignore + */ + _drawCover( + r: any, + cx: number, + cy: number, + scale: number, + width: number, + height: number, + ): void { + const canvas = this._cover!.canvas; + // whole pixels, so the image and the bands round it meet with no seam + const w = Math.round(canvas.width * scale); + const h = Math.round(canvas.height * scale); + if (w < 1 || h < 1) { + if (!this.invert) { + r.fillRect(0, 0, width, height); + } + return; + } + const x = Math.round(cx - this._anchor.x * scale); + const y = Math.round(cy - this._anchor.y * scale); + r.drawImage(canvas, 0, 0, canvas.width, canvas.height, x, y, w, h); + if (!this.invert) { + if (y > 0) { + r.fillRect(0, 0, width, y); + } + if (y + h < height) { + r.fillRect(0, y + h, width, height - y - h); + } + if (x > 0) { + r.fillRect(0, y, x, h); + } + if (x + w < width) { + r.fillRect(x + w, y, width - x - w, h); + } + } } override destroy(): void { @@ -202,12 +1010,22 @@ export default class MaskEffect extends CameraEffect { this.color = undefined as unknown as typeof this.color; } if (this._maskShape !== undefined) { - if (this._maskShape.type === "Ellipse") { + if (this._template === undefined) { ellipsePool.release(this._maskShape as Ellipse); } else { polygonPool.release(this._maskShape as Polygon); } - this._maskShape = undefined as unknown as typeof this._maskShape; + this._maskShape = undefined; + } + if (this._cover !== undefined) { + // and the copy the renderer uploaded to the GPU + this._cover.destroy(this._renderer); + this._cover = undefined; } + // the silhouette is kept: a reverse effect may be using it, and it + // never went to the GPU, so the garbage collector frees it + this._silhouette = undefined; + this._template = undefined; + this._renderer = undefined; } } diff --git a/packages/melonjs/src/index.ts b/packages/melonjs/src/index.ts index 8ceb121fcd..fd7d78dcc4 100644 --- a/packages/melonjs/src/index.ts +++ b/packages/melonjs/src/index.ts @@ -131,6 +131,12 @@ export type { SoundEvents, TrackOptions, } from "./audio/types.ts"; +export type { + MaskCenter, + MaskEffectOptions, + MaskImage, + MaskShape, +} from "./camera/effects/mask_effect.ts"; export type { FrustumOptions, ProjectionMode } from "./camera/frustum.ts"; // export all public constants export * from "./const.ts"; diff --git a/packages/melonjs/src/renderable/nineslicesprite.js b/packages/melonjs/src/renderable/nineslicesprite.js index 7700525759..e5c82d372c 100644 --- a/packages/melonjs/src/renderable/nineslicesprite.js +++ b/packages/melonjs/src/renderable/nineslicesprite.js @@ -124,16 +124,21 @@ export default class NineSliceSprite extends Sprite { } /** + * The nine slices of the current frame, stretched over this sprite's + * size, with its top left corner at (`x`, `y`). See {@link Sprite#drawFrame}. * @ignore * @internal + * @param {Renderer|CanvasRenderingContext2D} renderer - where to draw + * @param {number} x - the left of the sprite + * @param {number} y - the top of the sprite */ - draw(renderer) { + drawFrame(renderer, x, y) { // the frame to draw const frame = this.current; // cache the current position and size - let dx = this.pos.x; - const dy = this.pos.y; + let dx = x; + const dy = y; let w = frame.width; let h = frame.height; diff --git a/packages/melonjs/src/renderable/sprite.js b/packages/melonjs/src/renderable/sprite.js index 5c918032be..4cb8ebf631 100644 --- a/packages/melonjs/src/renderable/sprite.js +++ b/packages/melonjs/src/renderable/sprite.js @@ -1011,13 +1011,26 @@ export default class Sprite extends Renderable { ) { return; } + this.drawFrame(renderer, this.pos.x, this.pos.y); + } + /** + * Draw the current frame with its top left corner at (`x`, `y`): the + * atlas region, trimmed or stored turned, put back as the frame is meant + * to look. `target` is the renderer, or anything with the same + * `translate`, `rotate` and `drawImage`, such as a 2D canvas context (a + * mask transition draws the frame into one to take its silhouette). + * @ignore + * @param {Renderer|CanvasRenderingContext2D} target - where to draw + * @param {number} x - the left of the frame + * @param {number} y - the top of the frame + */ + drawFrame(target, x, y) { // the frame to draw const frame = this.current; - // cache the current position and size - let xpos = this.pos.x; - let ypos = this.pos.y; + let xpos = x; + let ypos = y; let w = frame.width; let h = frame.height; @@ -1028,8 +1041,8 @@ export default class Sprite extends Renderable { // remove image's TexturePacker/ShoeBox rotation if (frame.angle !== 0) { - renderer.translate(-xpos, -ypos); - renderer.rotate(frame.angle); + target.translate(-xpos, -ypos); + target.rotate(frame.angle); xpos -= h; w = frame.height; h = frame.width; @@ -1044,7 +1057,7 @@ export default class Sprite extends Renderable { ypos += frame.trim.y; } - renderer.drawImage( + target.drawImage( this.image, g_offset.x + frame_offset.x, // sx g_offset.y + frame_offset.y, // sy diff --git a/packages/melonjs/src/renderable/trigger.js b/packages/melonjs/src/renderable/trigger.js index ddf221f4e3..5fe7bfcfde 100644 --- a/packages/melonjs/src/renderable/trigger.js +++ b/packages/melonjs/src/renderable/trigger.js @@ -13,7 +13,7 @@ import Renderable from "./renderable.js"; * @import ResponseObject from "./../physics/response.js"; * @import {Color} from "../math/color.ts"; * @import Container from "./container.js"; - * @import {Ellipse} from "../geometries/ellipse.ts"; + * @import {MaskCenter, MaskShape} from "../camera/effects/mask_effect.ts"; * @import {Line} from "../geometries/line.ts"; * @import {Vector3d} from "../math/vector3d.ts"; * @import {Polygon} from "../geometries/polygon.ts"; @@ -75,7 +75,9 @@ export default class Trigger extends Renderable { * @param {number} [settings.duration] - Transition duration (in ms) * @param {string|Color} [settings.color] - Transition color (also accepts legacy `fade` property) * @param {string} [settings.transition="fade"] - Transition type: "fade" for a color fade, "mask" for a shape-based mask transition - * @param {Ellipse|Polygon} [settings.shape] - Mask shape for "mask" transition type (e.g. an Ellipse for iris, a Polygon for diamond/star) + * @param {MaskShape|"touching"} [settings.shape] - Mask shape for the "mask" transition type: an `Ellipse` (an iris) or a `Polygon`, an image or the name of a preloaded one (its silhouette), a `Sprite`, or `"touching"` for the silhouette of the object that set the trigger off. See {@link MaskEffect} + * @param {MaskCenter|"touching"} [settings.center] - Where the mask closes and opens: a renderable, a point on screen, or `"touching"` for the object that set the trigger off. The centre of the screen by default + * @param {boolean} [settings.invert=false] - Make the mask the cover rather than the window: filled with the color, it grows out of `center` until it covers the screen * @param {string} [settings.event="level"] - the type of event to trigger (only "level" supported for now) * @param {string} [settings.to] - level to load if level trigger * @param {string|Container} [settings.container] - Target container. See {@link level.load} @@ -115,6 +117,31 @@ export default class Trigger extends Renderable { * to: "mymap2", * })); * @example + * // the player's own silhouette, closing on the player as it walks in + * world.addChild(new Trigger(x, y, { + * shapes: [new Rect(0, 0, 100, 100)], + * transition: "mask", + * shape: "touching", + * center: "touching", + * color: "#000", + * duration: 300, + * to: "mymap2", + * })); + * @example + * // a preloaded star image, growing out of the player until it covers + * // the screen. In Tiled, the same as properties of the trigger object: + * // transition "mask", shape "star_mask", center "touching", invert true + * world.addChild(new Trigger(x, y, { + * shapes: [new Rect(0, 0, 100, 100)], + * transition: "mask", + * shape: "star_mask", + * center: "touching", + * invert: true, + * color: "#000", + * duration: 400, + * to: "mymap2", + * })); + * @example * // mask transition with diamond polygon * world.addChild(new Trigger(x, y, { * shapes: [new Rect(0, 0, 100, 100)], @@ -137,6 +164,8 @@ export default class Trigger extends Renderable { this.duration = settings.duration; this.transition = settings.transition || "fade"; this.transitionShape = settings.shape; + this.transitionCenter = settings.center; + this.transitionInvert = settings.invert === true; this.fading = false; // Tiled settings @@ -204,8 +233,10 @@ export default class Trigger extends Renderable { /** * Trigger this event. Override in subclasses to customize behavior. * @protected + * @param {Renderable} [other] - the object that set the trigger off, which + * a mask transition's `shape` and `center` of `"touching"` stand for */ - triggerEvent() { + triggerEvent(other) { const triggerSettings = this.getTriggerSettings(); const world = this.ancestor.getRootAncestor(); const app = world.app; @@ -221,13 +252,27 @@ export default class Trigger extends Renderable { const color = this.color; const duration = this.duration; const useMask = this.transition === "mask" && this.transitionShape; - const shape = this.transitionShape; + // "touching" is the object that walked in; with none (an + // event fired by hand), the mask's own default, an iris on + // the centre of the screen + const shape = + this.transitionShape === "touching" ? other : this.transitionShape; + const center = + this.transitionCenter === "touching" + ? other + : this.transitionCenter; + // the reveal, read from the hide as it completes: the shape + // and the point it settled when it started, from an object + // the level change destroys + let hide; + let reveal; // Await the load rather than intercepting the caller's // `onLoaded`: the reveal used to be injected by wrapping // `settings.onLoaded` and calling the user's through it, // which meant rewriting an option the caller passed in. const onComplete = () => { + reveal = hide?.reverseOptions(); level .load(gotolevel, { ...settings, async: true }) .then(() => { @@ -237,14 +282,7 @@ export default class Trigger extends Renderable { const vp = app.viewport; // reveal effect (same type as hide) if (useMask) { - vp.addCameraEffect( - new MaskEffect(vp, { - shape, - color, - duration, - direction: "reveal", - }), - ); + vp.addCameraEffect(new MaskEffect(vp, reveal)); } else { vp.addCameraEffect( new FadeEffect(vp, { @@ -267,15 +305,16 @@ export default class Trigger extends Renderable { // hide effect, then load level + reveal if (useMask) { - viewport.addCameraEffect( - new MaskEffect(viewport, { - shape, - color, - duration, - direction: "hide", - onComplete, - }), - ); + hide = new MaskEffect(viewport, { + shape, + color, + duration, + direction: "hide", + center, + invert: this.transitionInvert, + onComplete, + }); + viewport.addCameraEffect(hide); } else { viewport.addCameraEffect( new FadeEffect(viewport, { @@ -301,9 +340,9 @@ export default class Trigger extends Renderable { * runs exactly once per entry — under the legacy alias this would * fire every frame the entity was inside the trigger. */ - onCollisionStart() { + onCollisionStart(_response, other) { if (this.name === "Trigger") { - this.triggerEvent(); + this.triggerEvent(other); } } } diff --git a/packages/melonjs/src/state/state.ts b/packages/melonjs/src/state/state.ts index a0c8eb1ce9..70da3747b1 100644 --- a/packages/melonjs/src/state/state.ts +++ b/packages/melonjs/src/state/state.ts @@ -3,7 +3,11 @@ import { pauseTrack, resumeTrack } from "./../audio/audio.ts"; import type Camera2d from "../camera/camera2d.ts"; import type CameraEffect from "../camera/effects/camera_effect.ts"; import FadeEffect from "../camera/effects/fade_effect.ts"; -import MaskEffect from "../camera/effects/mask_effect.ts"; +import MaskEffect, { + isRenderable, + type MaskCenter, + type MaskShape, +} from "../camera/effects/mask_effect.ts"; import PixelateTransitionEffect from "../camera/effects/pixelate_transition_effect.ts"; import DefaultLoadingScreen from "./../loader/loadingscreen.js"; import Stage from "./../state/stage.ts"; @@ -48,10 +52,13 @@ let _transitionType: "fade" | "mask" | "pixelate" = "fade"; const _transitionConfig: { color: string; duration: number; - shape?: - | import("../geometries/ellipse.ts").Ellipse - | import("../geometries/polygon.ts").Polygon - | undefined; + shape?: MaskShape | undefined; + // where a mask transition closes and opens, and whether it is inverted + center?: MaskCenter | undefined; + invert?: boolean | undefined; + // a sprite shape or a renderable center was used, and let go: later + // changes are an iris on the centre of the screen until it is set again + released?: boolean | undefined; // the largest blocks of a pixelate transition, in screen pixels size?: number | undefined; } = { @@ -715,9 +722,20 @@ const state = { * @param color - a CSS color value (not used by "pixelate") * @param [duration=1000] - expressed in milliseconds, for each half: the * cover, then the reveal - * @param [shape] - an Ellipse or Polygon defining the mask shape (required - * when effect is "mask"), or for "pixelate" the size of the largest - * blocks, in screen pixels (32 by default) + * @param [shape] - for "mask" (required) the mask shape: an `Ellipse` or + * `Polygon` (unit-sized, centred on the origin), an image or the name of a + * preloaded one (its silhouette), or a `Sprite` (the silhouette of the + * frame it shows when the transition starts); see {@link MaskEffect}. For + * "pixelate", the size of the largest blocks, in screen pixels (32 by + * default) + * @param [options] - for "mask" only + * @param [options.center] - where the shape closes and opens: a + * renderable, such as the player, at the place it is drawn when the + * transition starts, or a point on screen. The centre of the screen by + * default. The reveal opens from the same place + * @param [options.invert=false] - make the shape the cover rather than + * the window: filled with the color, it grows out of `center` until it + * covers the screen, and shrinks away to reveal it * @example * // classic fade to black * state.transition("fade", "#000", 500); @@ -731,6 +749,20 @@ const state = { * { x: 0, y: 1 }, { x: -1, y: 0 }, * ])); * @example + * // a star wipe, from a preloaded silhouette image + * state.transition("mask", "#000", 500, "star_mask"); + * @example + * // the player's own silhouette, closing on the player: set right before + * // the change, as the player of one level is not the next one's + * state.transition("mask", "#000", 500, player, { center: player }); + * state.change(state.GAME_END); + * @example + * // a black circle growing out of the player until it covers the screen + * state.transition("mask", "#000", 400, new Ellipse(0, 0, 1, 1), { + * center: player, + * invert: true, + * }); + * @example * // the screen breaks up into 32 pixel blocks, and comes back * state.transition("pixelate", "#000", 300); * // into 16 pixel blocks @@ -740,16 +772,17 @@ const state = { effect: "fade" | "mask" | "pixelate", color: string, duration: number = 1000, - shape?: - | import("../geometries/ellipse.ts").Ellipse - | import("../geometries/polygon.ts").Polygon - | number, + shape?: MaskShape | number, + options?: { center?: MaskCenter | undefined; invert?: boolean | undefined }, ): void { _transitionType = effect; _transitionConfig.color = color; _transitionConfig.duration = duration; _transitionConfig.shape = typeof shape === "number" ? undefined : shape; _transitionConfig.size = typeof shape === "number" ? shape : undefined; + _transitionConfig.center = options?.center; + _transitionConfig.invert = options?.invert; + _transitionConfig.released = false; }, /** @@ -891,39 +924,51 @@ const state = { break; } case "mask": { - if (!_transitionConfig.shape) { + if (!_transitionConfig.shape && !_transitionConfig.released) { console.warn( "melonJS: mask transition requires a shape, falling back to direct switch", ); onComplete(); break; } - const shape = _transitionConfig.shape; - const color = _transitionConfig.color; - const duration = _transitionConfig.duration; const maskEffect = new MaskEffect(_app.viewport, { - shape, - color, - duration, + shape: _transitionConfig.shape, + color: _transitionConfig.color, + duration: _transitionConfig.duration, direction: "hide", + center: _transitionConfig.center, + invert: _transitionConfig.invert, onComplete, }); + // The transition is set once and kept, but a sprite or a + // renderable is one level's player: read now, it is let + // go, rather than held (and read again, destroyed or + // recycled into something else) by every later change + if (isRenderable(_transitionConfig.shape)) { + _transitionConfig.shape = undefined; + _transitionConfig.released = true; + } + if (isRenderable(_transitionConfig.center)) { + _transitionConfig.center = undefined; + } // see the note in the fade case: persistent is what // keeps the closed iris on screen until the switch // lands, and the owner is what takes it away again maskEffect.isPersistent = true; const hidCamera = _app.viewport; _onSwitchComplete = () => { + // The reveal opens from where the hide closed, with + // the shape it closed with: both were settled when + // the hide started, from a sprite and a renderable + // the switch may well have destroyed since. Made + // before the hide is taken away, which frees them. + const reveal = new MaskEffect( + _app.viewport, + maskEffect.reverseOptions(), + ); hidCamera.removeCameraEffect(maskEffect); // create reveal with the post-switch viewport - _app.viewport.addCameraEffect( - new MaskEffect(_app.viewport, { - shape, - color, - duration, - direction: "reveal", - }), - ); + _app.viewport.addCameraEffect(reveal); }; _app.viewport.addCameraEffect(maskEffect); covering(maskEffect); diff --git a/packages/melonjs/tests/mask-effect-image.spec.js b/packages/melonjs/tests/mask-effect-image.spec.js new file mode 100644 index 0000000000..e1f8cafd6e --- /dev/null +++ b/packages/melonjs/tests/mask-effect-image.spec.js @@ -0,0 +1,966 @@ +/** + * `MaskEffect` with an image, a sprite or a preloaded image's name as its + * shape, a `center` to close on, and `invert` (#1399). + * + * The image used throughout is a disc with a hole in its middle, in a 32 px + * square: the hole is enclosed, so the silhouette fills it, and the disc's + * own radius is the circle that has to reach the screen's corners for a + * reveal to end with the scene fully uncovered. + * + * The pixel checks draw the effect over white, so a covered pixel reads + * black and a visible one white, on Canvas and on WebGL (WebGPU, where the + * browser has it). + */ +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { + Application, + boot, + Camera2d, + Camera3d, + Container, + Ellipse, + level, + loader, + MaskEffect, + NineSliceSprite, + Polygon, + Renderable, + Sprite, + TextureAtlas, + Trigger, + Vector3d, + video, +} from "../src/index.js"; +import GLTFScene from "../src/level/gltf/GLTFScene.js"; +import { readPixel } from "./helpers/pixels.js"; +import { + getWebGLRenderer, + releaseWebGLRenderer, +} from "./helpers/webgl-context.js"; + +const SIZE = 64; + +/** a 32 px disc, radius 14, with a hole of radius 4 at its centre */ +const discWithHole = () => { + const canvas = document.createElement("canvas"); + canvas.width = canvas.height = 32; + const ctx = canvas.getContext("2d"); + ctx.fillStyle = "#3a7"; + ctx.beginPath(); + ctx.arc(16, 16, 14, 0, Math.PI * 2); + ctx.fill(); + ctx.globalCompositeOperation = "destination-out"; + ctx.beginPath(); + ctx.arc(16, 16, 4, 0, Math.PI * 2); + ctx.fill(); + return canvas; +}; + +/** an image whose left half only is opaque */ +const leftHalf = (w = 20, h = 30) => { + const canvas = document.createElement("canvas"); + canvas.width = w; + canvas.height = h; + const ctx = canvas.getContext("2d"); + ctx.fillStyle = "#f00"; + ctx.fillRect(0, 0, w / 2, h); + return canvas; +}; + +/** a 32 px U: its middle is open to the outside, so not part of it */ +const uShape = () => { + const canvas = document.createElement("canvas"); + canvas.width = canvas.height = 32; + const ctx = canvas.getContext("2d"); + ctx.fillStyle = "#000"; + ctx.fillRect(2, 2, 8, 28); + ctx.fillRect(22, 2, 8, 28); + ctx.fillRect(2, 22, 28, 8); + return canvas; +}; + +/** an image whose top left quarter only is opaque */ +const topLeftQuarter = (w = 20, h = 30) => { + const canvas = document.createElement("canvas"); + canvas.width = w; + canvas.height = h; + const ctx = canvas.getContext("2d"); + ctx.fillStyle = "#0f0"; + ctx.fillRect(0, 0, w / 2, h / 2); + return canvas; +}; + +/** a unit square that does not surround its origin */ +const offOrigin = () => { + return new Polygon(0, 0, [ + { x: 0.2, y: 0.2 }, + { x: 1, y: 0.2 }, + { x: 1, y: 1 }, + { x: 0.2, y: 1 }, + ]); +}; + +/** an effect at a given progress (1 = all visible, 0 = all covered) */ +const at = (camera, progress, options) => { + const effect = new MaskEffect(camera, { + color: "#000", + duration: 1000, + direction: "hide", + ...options, + }); + effect.tween.stop(); + effect.progress.value = progress; + return effect; +}; + +/** draw an effect over a white screen */ +const drawOverWhite = (renderer, effect) => { + renderer.save(); + renderer.resetTransform(); + renderer.setColor("#ffffff"); + renderer.fillRect(0, 0, SIZE, SIZE); + renderer.restore(); + effect.draw(renderer, SIZE, SIZE); + renderer.flush(); +}; + +/** 1 where a pixel is covered (dark), 0 where it is visible (light) */ +const covered = async (renderer, x, y) => { + return (await readPixel(renderer, x, y))[0] < 128 ? 1 : 0; +}; + +const CORNERS = [ + [1, 1], + [SIZE - 2, 1], + [1, SIZE - 2], + [SIZE - 2, SIZE - 2], +]; + +/** the same drawing checks, on one renderer */ +const drawingChecks = (getRenderer) => { + const camera = new Camera2d(0, 0, SIZE, SIZE); + + it("an image: the scene shows through its silhouette, hole filled in", async (ctx) => { + const renderer = getRenderer(ctx); + const effect = at(camera, 0.3, { shape: discWithHole() }); + drawOverWhite(renderer, effect); + // the centre is the image's hole: part of the silhouette, so visible + expect(await covered(renderer, 32, 32)).toBe(0); + expect(await covered(renderer, 32, 26)).toBe(0); + for (const [x, y] of CORNERS) { + expect(await covered(renderer, x, y)).toBe(1); + } + effect.destroy(); + }); + + it("an image: covers everything once closed", async (ctx) => { + const renderer = getRenderer(ctx); + const effect = at(camera, 0, { shape: discWithHole() }); + drawOverWhite(renderer, effect); + expect(await covered(renderer, 32, 32)).toBe(1); + expect(await covered(renderer, 1, 1)).toBe(1); + effect.destroy(); + }); + + it("an image: just before the end, the whole screen is already uncovered", async (ctx) => { + const renderer = getRenderer(ctx); + const effect = at(camera, 0.995, { shape: discWithHole() }); + drawOverWhite(renderer, effect); + for (const [x, y] of CORNERS) { + expect(await covered(renderer, x, y)).toBe(0); + } + effect.destroy(); + }); + + it("a polygon: just before the end, the whole screen is already uncovered", async (ctx) => { + const renderer = getRenderer(ctx); + const diamond = new Polygon(0, 0, [ + { x: 0, y: -1 }, + { x: 1, y: 0 }, + { x: 0, y: 1 }, + { x: -1, y: 0 }, + ]); + const effect = at(camera, 0.995, { shape: diamond }); + drawOverWhite(renderer, effect); + for (const [x, y] of CORNERS) { + expect(await covered(renderer, x, y)).toBe(0); + } + effect.destroy(); + }); + + it("inverted: the silhouette is the cover, the scene shows round it", async (ctx) => { + const renderer = getRenderer(ctx); + const effect = at(camera, 0.7, { shape: discWithHole(), invert: true }); + drawOverWhite(renderer, effect); + expect(await covered(renderer, 32, 32)).toBe(1); + for (const [x, y] of CORNERS) { + expect(await covered(renderer, x, y)).toBe(0); + } + effect.destroy(); + }); + + it("inverted: covers everything once closed, nothing at the start", async (ctx) => { + const renderer = getRenderer(ctx); + const closed = at(camera, 0, { shape: discWithHole(), invert: true }); + drawOverWhite(renderer, closed); + expect(await covered(renderer, 1, 1)).toBe(1); + expect(await covered(renderer, 32, 32)).toBe(1); + closed.destroy(); + const open = at(camera, 1, { shape: discWithHole(), invert: true }); + drawOverWhite(renderer, open); + expect(await covered(renderer, 32, 32)).toBe(0); + open.destroy(); + }); + + it("inverted geometry: an iris filled, growing out of the centre", async (ctx) => { + const renderer = getRenderer(ctx); + const effect = at(camera, 0.7, { + shape: new Ellipse(0, 0, 1, 1), + invert: true, + }); + drawOverWhite(renderer, effect); + expect(await covered(renderer, 32, 32)).toBe(1); + expect(await covered(renderer, 1, 1)).toBe(0); + effect.destroy(); + }); + + it("an image open in its middle (a U): grows about its thickest part, and still uncovers everything", async (ctx) => { + const renderer = getRenderer(ctx); + // just after the hide starts, the middle of the screen is still seen + const start = at(camera, 0.99, { shape: uShape() }); + drawOverWhite(renderer, start); + expect(await covered(renderer, 32, 32)).toBe(0); + start.destroy(); + // and just before a reveal ends, nothing is covered + const end = at(camera, 0.995, { shape: uShape() }); + drawOverWhite(renderer, end); + for (const [x, y] of [...CORNERS, [32, 32], [32, 3]]) { + expect(await covered(renderer, x, y)).toBe(0); + } + end.destroy(); + }); + + it("a polygon off its origin: still uncovers everything, and inverted still covers it", async (ctx) => { + const renderer = getRenderer(ctx); + const open = at(camera, 0.995, { shape: offOrigin() }); + drawOverWhite(renderer, open); + for (const [x, y] of CORNERS) { + expect(await covered(renderer, x, y)).toBe(0); + } + open.destroy(); + // the cover nearly grown: the screen is covered by the polygon itself + const cover = at(camera, 0.005, { shape: offOrigin(), invert: true }); + drawOverWhite(renderer, cover); + for (const [x, y] of [...CORNERS, [32, 32]]) { + expect(await covered(renderer, x, y)).toBe(1); + } + cover.destroy(); + }); + + it("nearly closed, the image is still drawn, a sliver of the scene in the middle", async (ctx) => { + const renderer = getRenderer(ctx); + const effect = at(camera, 0.05, { shape: discWithHole() }); + const drawImage = vi.spyOn(renderer, "drawImage"); + drawOverWhite(renderer, effect); + expect(drawImage).toHaveBeenCalled(); + drawImage.mockRestore(); + expect(await covered(renderer, 32, 32)).toBe(0); + for (const [x, y] of [...CORNERS, [32, 20], [44, 32]]) { + expect(await covered(renderer, x, y)).toBe(1); + } + effect.destroy(); + }); + + it("center: closes on that point, not on the centre of the screen", async (ctx) => { + const renderer = getRenderer(ctx); + const effect = at(camera, 0.2, { + shape: discWithHole(), + center: { x: 12, y: 12 }, + }); + drawOverWhite(renderer, effect); + expect(await covered(renderer, 12, 12)).toBe(0); + expect(await covered(renderer, 52, 52)).toBe(1); + effect.destroy(); + }); +}; + +// One Canvas application for the whole file, made first: the engine gives a +// viewport only to the application live at the first `init()` +let app; +beforeAll(async () => { + boot(); + app = new Application(SIZE, SIZE, { + parent: "screen", + renderer: video.CANVAS, + consoleHeader: false, + }); + await app.init(); + const png = discWithHole().toDataURL("image/png"); + await loader.preload( + [{ name: "mask-disc", type: "image", src: png }], + undefined, + false, + ); +}); +afterAll(() => { + app?.destroy(); +}); + +describe("MaskEffect: image and sprite shapes", () => { + describe("Canvas", () => { + drawingChecks(() => { + return app.renderer; + }); + }); + + describe("WebGL", () => { + let renderer; + beforeAll(async () => { + boot(); + renderer = await getWebGLRenderer(SIZE, SIZE); + if (renderer !== undefined) { + renderer.projectionMatrix.ortho(0, SIZE, SIZE, 0, -1000, 1000); + renderer.currentBatcher.setProjection(renderer.projectionMatrix); + } + }); + afterAll(() => { + releaseWebGLRenderer(); + }); + drawingChecks((ctx) => { + if (renderer === undefined) { + ctx.skip("WebGL renderer not available in this environment"); + } + return renderer; + }); + + it("destroy frees the copy of the image uploaded to the GPU", (ctx) => { + if (renderer === undefined) { + ctx.skip("WebGL renderer not available in this environment"); + return; + } + const effect = at(new Camera2d(0, 0, SIZE, SIZE), 0.5, { + shape: discWithHole(), + }); + drawOverWhite(renderer, effect); + const canvas = effect._cover.canvas; + expect(renderer.cache.has(canvas)).toBe(true); + effect.destroy(); + expect(renderer.cache.has(canvas)).toBe(false); + }); + }); + + describe("WebGPU", () => { + let gpuApp; + let available = false; + beforeAll(async () => { + try { + gpuApp = new Application(SIZE, SIZE, { + parent: "screen", + renderer: video.WEBGPU, + consoleHeader: false, + }); + await gpuApp.init(); + available = gpuApp.renderer.type === "WebGPU"; + } catch { + available = false; + } + }); + afterAll(() => { + gpuApp?.destroy(); + }); + drawingChecks((ctx) => { + if (!available) { + ctx.skip("WebGPU not available in this environment"); + } + return gpuApp.renderer; + }); + }); +}); + +describe("MaskEffect: what a shape and a center resolve to", () => { + /** the alpha of a silhouette pixel, in the silhouette's own pixels */ + const alpha = (effect, x, y) => { + const canvas = effect._silhouette.target.canvas; + return canvas.getContext("2d").getImageData(x, y, 1, 1).data[3]; + }; + + it("a preloaded image's name is that image", () => { + const effect = new MaskEffect(app.viewport, { + shape: "mask-disc", + color: "#000", + }); + expect(effect._silhouette).toBeDefined(); + expect(effect._maskShape).toBeUndefined(); + // 32 px plus the clear margin on each side + expect(effect._silhouette.target.canvas.width).toBe(36); + // grown about its middle, by the disc's radius (less its soft edge) + expect(effect._anchor.x).toBe(18.5); + expect(effect._anchor.y).toBe(18.5); + expect(effect._anchor.inner).toBeGreaterThan(12.5); + expect(effect._anchor.inner).toBeLessThan(14.5); + effect.destroy(); + }); + + it("an unknown name warns, and an iris is used instead", () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const effect = new MaskEffect(app.viewport, { + shape: "no-such-mask-image", + color: "#000", + }); + expect(effect._maskShape).toBeInstanceOf(Ellipse); + expect(warn).toHaveBeenCalled(); + warn.mockRestore(); + effect.destroy(); + }); + + it("a sprite: the frame it shows, facing the way it faces", () => { + const sprite = new Sprite(0, 0, { image: leftHalf() }); + const facing = new MaskEffect(app.viewport, { + shape: sprite, + color: "#000", + }); + // opaque on the left, clear on the right (2 px margin) + expect(alpha(facing, 2 + 3, 15)).toBe(255); + expect(alpha(facing, 2 + 16, 15)).toBe(0); + facing.destroy(); + + sprite.flipX(true); + const flipped = new MaskEffect(app.viewport, { + shape: sprite, + color: "#000", + }); + expect(alpha(flipped, 2 + 3, 15)).toBe(0); + expect(alpha(flipped, 2 + 16, 15)).toBe(255); + flipped.destroy(); + sprite.destroy(); + }); + + it("a sprite's atlas frame: only that region of its image", () => { + // a 40 × 30 sheet of two 20 × 30 frames: opaque left half, then clear + const sheet = document.createElement("canvas"); + sheet.width = 40; + sheet.height = 30; + const ctx = sheet.getContext("2d"); + ctx.fillStyle = "#00f"; + ctx.fillRect(0, 0, 20, 30); + const sprite = new Sprite(0, 0, { + image: sheet, + framewidth: 20, + frameheight: 30, + }); + sprite.addAnimation("full", [0]); + sprite.addAnimation("empty", [1]); + sprite.setCurrentAnimation("full"); + const full = new MaskEffect(app.viewport, { shape: sprite, color: "#000" }); + expect(full._silhouette.target.canvas.width).toBe(24); + expect(alpha(full, 12, 15)).toBe(255); + full.destroy(); + // the clear frame has no silhouette at all: warned, and an iris + sprite.setCurrentAnimation("empty"); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const empty = new MaskEffect(app.viewport, { + shape: sprite, + color: "#000", + }); + expect(empty._silhouette).toBeUndefined(); + expect(empty._maskShape).toBeInstanceOf(Ellipse); + expect(warn.mock.calls.flat().join(" ")).toMatch(/fully transparent/); + warn.mockRestore(); + empty.destroy(); + sprite.destroy(); + }); + + it("a destroyed sprite warns, and an iris is used instead", () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const sprite = new Sprite(0, 0, { image: leftHalf() }); + sprite.destroy(); + const effect = new MaskEffect(app.viewport, { + shape: sprite, + color: "#000", + }); + expect(effect._maskShape).toBeInstanceOf(Ellipse); + expect(warn).toHaveBeenCalled(); + warn.mockRestore(); + effect.destroy(); + }); + + it("a renderable that is not a sprite warns, and an iris is used instead", () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const effect = new MaskEffect(app.viewport, { + shape: new Renderable(0, 0, 10, 10), + color: "#000", + }); + expect(effect._maskShape).toBeInstanceOf(Ellipse); + expect(warn).toHaveBeenCalled(); + warn.mockRestore(); + effect.destroy(); + }); + + it("an object holding a sprite (an Entity) is shaped by that sprite", () => { + const holder = new Renderable(0, 0, 20, 30); + holder.renderable = new Sprite(0, 0, { image: leftHalf() }); + const effect = new MaskEffect(app.viewport, { + shape: holder, + color: "#000", + }); + expect(effect._silhouette).toBeDefined(); + expect(alpha(effect, 5, 15)).toBe(255); + effect.destroy(); + holder.renderable.destroy(); + }); + + it("a renderable center is where it is drawn on screen, read once", () => { + const target = new Renderable(50, 30, 20, 20); + target.anchorPoint.set(0, 0); + app.world.addChild(target); + app.viewport.pos.set(40, 10); + const effect = new MaskEffect(app.viewport, { + shape: new Ellipse(0, 0, 1, 1), + color: "#000", + center: target, + }); + // its middle (60, 40), less the camera's position + expect(effect.center.x).toBeCloseTo(20, 5); + expect(effect.center.y).toBeCloseTo(30, 5); + // moving it afterwards changes nothing + target.pos.set(0, 0); + expect(effect.center.x).toBeCloseTo(20, 5); + effect.destroy(); + app.viewport.pos.set(0, 0); + app.world.removeChildNow(target); + }); + + it("a center not in the world warns, and the centre of the screen is used", () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const effect = new MaskEffect(app.viewport, { + shape: new Ellipse(0, 0, 1, 1), + color: "#000", + center: new Renderable(10, 10, 5, 5), + }); + expect(effect.center).toBeUndefined(); + expect(warn).toHaveBeenCalled(); + warn.mockRestore(); + effect.destroy(); + }); + + it("reverseOptions: the effect played back, with the shape after its sprite is gone", () => { + const sprite = new Sprite(0, 0, { image: leftHalf() }); + const hide = new MaskEffect(app.viewport, { + shape: sprite, + color: "#336699", + duration: 321, + center: { x: 30, y: 40 }, + invert: true, + }); + sprite.destroy(); + const options = hide.reverseOptions(); + const anchor = { ...hide._anchor }; + const reveal = new MaskEffect(app.viewport, options); + hide.destroy(); + expect(options.direction).toBe("reveal"); + expect(reveal.duration).toBe(321); + expect(reveal.invert).toBe(true); + expect(reveal.color.toHex()).toBe("#336699"); + // the same silhouette, not one made again from it + expect(reveal._silhouette.target.canvas).toBe(options.shape); + expect(reveal._anchor).toEqual(anchor); + expect(reveal.center).toEqual({ x: 30, y: 40 }); + // and back again + expect(reveal.reverseOptions().direction).toBe("hide"); + reveal.destroy(); + }); + + it("reverseOptions of a polygon or the default iris give the same shape", () => { + const poly = offOrigin(); + const a = new MaskEffect(app.viewport, { shape: poly, color: "#000" }); + const b = new MaskEffect(app.viewport, a.reverseOptions()); + expect(b._template).toBe(poly); + expect(b._anchor).toEqual(a._anchor); + a.destroy(); + b.destroy(); + const iris = new MaskEffect(app.viewport, { color: "#000" }); + expect(iris.reverseOptions().shape).toBeUndefined(); + iris.destroy(); + }); + + it("no shape is the default iris, without a warning", () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const effect = new MaskEffect(app.viewport, { color: "#000" }); + expect(effect._maskShape).toBeInstanceOf(Ellipse); + expect(warn).not.toHaveBeenCalled(); + warn.mockRestore(); + effect.destroy(); + }); + + it("a shape of the wrong kind warns that it is not supported, and is an iris", () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + for (const shape of [{}, 42]) { + const effect = new MaskEffect(app.viewport, { shape, color: "#000" }); + expect(effect._maskShape).toBeInstanceOf(Ellipse); + effect.destroy(); + } + expect(warn.mock.calls.flat().join(" ")).toMatch(/not an Ellipse/); + warn.mockRestore(); + }); + + it("a fully transparent image is an iris (the warning is shown once, above)", () => { + const blank = document.createElement("canvas"); + blank.width = blank.height = 16; + const effect = new MaskEffect(app.viewport, { + shape: blank, + color: "#000", + }); + expect(effect._silhouette).toBeUndefined(); + expect(effect._maskShape).toBeInstanceOf(Ellipse); + effect.destroy(); + }); + + it("an image that cannot be read back warns, and is an iris", () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const read = vi + .spyOn(CanvasRenderingContext2D.prototype, "getImageData") + .mockImplementation(() => { + throw new DOMException("tainted", "SecurityError"); + }); + try { + const effect = new MaskEffect(app.viewport, { + shape: discWithHole(), + color: "#000", + }); + expect(effect._maskShape).toBeInstanceOf(Ellipse); + effect.destroy(); + } finally { + read.mockRestore(); + } + expect(warn.mock.calls.flat().join(" ")).toMatch(/could not be read/); + warn.mockRestore(); + }); + + it("a polygon with no inside warns, and is an iris", () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const flat = new Polygon(0, 0, [ + { x: -1, y: 0 }, + { x: 0, y: 0 }, + { x: 1, y: 0 }, + ]); + const effect = new MaskEffect(app.viewport, { shape: flat, color: "#000" }); + expect(effect._template).toBeUndefined(); + expect(effect._maskShape).toBeInstanceOf(Ellipse); + warn.mockRestore(); + effect.destroy(); + }); + + it("a sprite flipped on either axis", () => { + const sprite = new Sprite(0, 0, { image: topLeftQuarter() }); + const flips = [ + [false, false, [5, 5]], + [true, false, [15, 5]], + [false, true, [5, 22]], + [true, true, [15, 22]], + ]; + for (const [fx, fy, [x, y]] of flips) { + sprite.flipX(fx); + sprite.flipY(fy); + const effect = new MaskEffect(app.viewport, { + shape: sprite, + color: "#000", + }); + // the opaque quarter is where the flips put it (2 px margin) + expect(alpha(effect, 2 + x, 2 + y)).toBe(255); + const others = [ + [5, 5], + [15, 5], + [5, 22], + [15, 22], + ].filter(([ox, oy]) => { + return ox !== x || oy !== y; + }); + for (const [ox, oy] of others) { + expect(alpha(effect, 2 + ox, 2 + oy)).toBe(0); + } + effect.destroy(); + } + sprite.destroy(); + }); + + it("an atlas frame stored turned, or trimmed, gives the same silhouette as a plain one", () => { + // the art: a 12 × 20 Γ + const art = document.createElement("canvas"); + art.width = 12; + art.height = 20; + const a = art.getContext("2d"); + a.fillStyle = "#c00"; + a.fillRect(0, 0, 12, 6); + a.fillRect(0, 0, 4, 20); + // one sheet: plain at (0, 0), turned a quarter clockwise at (20, 0) + // (20 wide, 12 tall), and trimmed out of a 16 × 24 frame at (0, 30) + const sheet = document.createElement("canvas"); + sheet.width = sheet.height = 64; + const s = sheet.getContext("2d"); + s.drawImage(art, 0, 0); + s.save(); + s.translate(40, 0); + s.rotate(Math.PI / 2); + s.drawImage(art, 0, 0); + s.restore(); + s.drawImage(art, 0, 30); + const frame = (filename, x, y, extra = {}) => { + return { + filename, + frame: { x, y, w: 12, h: 20 }, + rotated: false, + trimmed: false, + spriteSourceSize: { x: 0, y: 0, w: 12, h: 20 }, + sourceSize: { w: 12, h: 20 }, + ...extra, + }; + }; + const atlas = new TextureAtlas( + { + frames: [ + frame("plain", 0, 0), + frame("turned", 20, 0, { rotated: true }), + frame("trimmed", 0, 30, { + trimmed: true, + spriteSourceSize: { x: 2, y: 3, w: 12, h: 20 }, + sourceSize: { w: 16, h: 24 }, + }), + ], + meta: { + app: "texturepacker", + image: "mask-sheet.png", + size: { w: 64, h: 64 }, + scale: "1", + }, + }, + sheet, + ); + const silhouetteOf = (name) => { + const sprite = atlas.createSpriteFromName(name); + const effect = new MaskEffect(app.viewport, { + shape: sprite, + color: "#000", + }); + const canvas = effect._silhouette.target.canvas; + const data = canvas + .getContext("2d") + .getImageData(0, 0, canvas.width, canvas.height); + effect.destroy(); + sprite.destroy(); + return data; + }; + const plain = silhouetteOf("plain"); + const turned = silhouetteOf("turned"); + expect([turned.width, turned.height]).toEqual([plain.width, plain.height]); + expect(Array.from(turned.data)).toEqual(Array.from(plain.data)); + // trimmed: the same, 2 across and 3 down in its larger frame + const trimmed = silhouetteOf("trimmed"); + const at = (img, x, y) => { + return img.data[(y * img.width + x) * 4 + 3]; + }; + let same = 0; + for (let y = 0; y < plain.height; y++) { + for (let x = 0; x < plain.width; x++) { + if (at(plain, x, y) === at(trimmed, x + 2, y + 3)) { + same++; + } + } + } + expect(same).toBe(plain.width * plain.height); + }); + + it("a NineSliceSprite: its whole stretched size, not its source frame", () => { + const source = document.createElement("canvas"); + source.width = source.height = 30; + const s = source.getContext("2d"); + s.fillStyle = "#08f"; + s.fillRect(0, 0, 30, 30); + const panel = new NineSliceSprite(0, 0, { + image: source, + width: 90, + height: 60, + }); + const effect = new MaskEffect(app.viewport, { + shape: panel, + color: "#000", + }); + const canvas = effect._silhouette.target.canvas; + expect([canvas.width, canvas.height]).toEqual([94, 64]); + expect(alpha(effect, 85, 55)).toBe(255); + effect.destroy(); + panel.destroy(); + }); + + it("a center in a floating container is where it is on the screen", () => { + const hud = new Container(0, 0, SIZE, SIZE); + hud.floating = true; + app.world.addChild(hud); + const item = new Renderable(10, 10, 4, 4); + item.anchorPoint.set(0, 0); + hud.addChild(item); + // a child of a floating container is not floating itself + expect(item.floating).toBe(false); + app.viewport.pos.set(40, 10); + const effect = new MaskEffect(app.viewport, { + color: "#000", + center: item, + }); + expect(effect.center.x).toBeCloseTo(12, 5); + expect(effect.center.y).toBeCloseTo(12, 5); + effect.destroy(); + app.viewport.pos.set(0, 0); + app.world.removeChildNow(hud); + }); + + it("under a Camera3d, a center inside a container at a depth is projected at its full depth", () => { + const camera = new Camera3d(0, 0, SIZE, SIZE); + camera.setClipPlanes(1, 100000); + camera.orbit({ x: 0, y: 0, z: 0 }, 0, 0, 500); + const box = new Container(0, 0, 100, 100); + app.world.addChild(box); + // after addChild, which gives it a depth of its own + box.depth = 200; + const item = new Renderable(40, 0, 4, 4); + item.anchorPoint.set(0, 0); + box.addChild(item); + const effect = new MaskEffect(camera, { color: "#000", center: item }); + const b = item.getBounds(); + // the container's depth and the child's own (its place in the container) + const depth = item.getAbsolutePosition().z; + expect(depth).toBeGreaterThanOrEqual(200); + const atDepth = camera.worldToScreen( + new Vector3d(b.centerX, b.centerY, depth), + ); + const atZero = camera.worldToScreen( + new Vector3d(b.centerX, b.centerY, item.depth), + ); + expect(effect.center.x).toBeCloseTo(atDepth.x, 4); + expect(effect.center.y).toBeCloseTo(atDepth.y, 4); + // and that is not where its own (local) depth would put it + expect(Math.abs(atDepth.x - atZero.x)).toBeGreaterThan(1); + effect.destroy(); + app.world.removeChildNow(box); + }); +}); + +describe("Trigger: a mask that is whoever walked in", () => { + const clearEffects = () => { + while (app.viewport.cameraEffects.length > 0) { + app.viewport.removeCameraEffect(app.viewport.cameraEffects[0]); + } + }; + + it('"touching" is the sprite that set the trigger off, and where it is', () => { + const player = new Sprite(30, 20, { image: leftHalf() }); + player.anchorPoint.set(0, 0); + app.world.addChild(player); + const trigger = new Trigger(0, 0, { + width: 50, + height: 50, + transition: "mask", + shape: "touching", + center: "touching", + invert: true, + color: "#000", + duration: 300, + to: "map2", + }); + app.world.addChild(trigger); + trigger.onCollisionStart({}, player); + + const effect = app.viewport.getCameraEffect(MaskEffect); + expect(effect).toBeDefined(); + expect(effect._silhouette).toBeDefined(); + expect(effect.invert).toBe(true); + // the middle of the player's 20 × 30 frame + expect(effect.center.x).toBeCloseTo(40, 5); + expect(effect.center.y).toBeCloseTo(35, 5); + + clearEffects(); + app.world.removeChildNow(trigger); + app.world.removeChildNow(player); + }); + + it('"touching" with nothing that touched it: an iris on the centre', () => { + const trigger = new Trigger(0, 0, { + width: 50, + height: 50, + transition: "mask", + shape: "touching", + center: "touching", + color: "#000", + duration: 300, + to: "map2", + }); + app.world.addChild(trigger); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + trigger.onCollisionStart({}); + + const effect = app.viewport.getCameraEffect(MaskEffect); + expect(effect._maskShape).toBeInstanceOf(Ellipse); + expect(effect.center).toBeUndefined(); + expect(warn).not.toHaveBeenCalled(); + warn.mockRestore(); + + clearEffects(); + app.world.removeChildNow(trigger); + }); +}); + +describe("Trigger: the reveal opens where the hide closed", () => { + let originalAddTo; + beforeAll(() => { + // a level that loads without assets + originalAddTo = GLTFScene.prototype.addTo; + GLTFScene.prototype.addTo = () => {}; + level.add("gltf", "mask-trigger-target"); + }); + afterAll(() => { + GLTFScene.prototype.addTo = originalAddTo; + }); + + it("with the player's silhouette and place, though the level change destroyed the player", async () => { + const player = new Sprite(30, 20, { image: leftHalf() }); + player.anchorPoint.set(0, 0); + app.world.addChild(player); + const trigger = new Trigger(0, 0, { + width: 8, + height: 8, + transition: "mask", + shape: "touching", + center: "touching", + invert: true, + color: "#000", + duration: 300, + to: "mask-trigger-target", + }); + app.world.addChild(trigger); + trigger.onCollisionStart({}, player); + const hide = app.viewport.getCameraEffect(MaskEffect); + const silhouette = hide._silhouette.target.canvas; + const center = { ...hide.center }; + + // the hide ends: the level loads, then the reveal starts + hide.tween.stop(); + hide.progress.value = 0; + hide.update(); + let reveal; + for (let i = 0; i < 50 && reveal === undefined; i++) { + await new Promise((resolve) => { + setTimeout(resolve, 0); + }); + reveal = app.viewport.cameraEffects.find((fx) => { + return fx instanceof MaskEffect && fx.direction === "reveal"; + }); + } + expect(reveal).toBeDefined(); + expect(player.offset).toBeUndefined(); + expect(reveal._silhouette.target.canvas).toBe(silhouette); + expect(reveal.center).toEqual(center); + expect(reveal.invert).toBe(true); + expect(reveal.duration).toBe(300); + while (app.viewport.cameraEffects.length > 0) { + app.viewport.removeCameraEffect(app.viewport.cameraEffects[0]); + } + }); +}); diff --git a/packages/melonjs/tests/mask-transition-sprite.spec.js b/packages/melonjs/tests/mask-transition-sprite.spec.js new file mode 100644 index 0000000000..f66506fee8 --- /dev/null +++ b/packages/melonjs/tests/mask-transition-sprite.spec.js @@ -0,0 +1,182 @@ +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { + Application, + boot, + MaskEffect, + Sprite, + Stage, + state, + video, +} from "../src/index.js"; +import { readPixel } from "./helpers/pixels.js"; + +/** + * `state.transition("mask", …, sprite, { center: sprite })` (#1399): the + * hide closes on the player with the player's own silhouette, and the reveal + * opens from the same place with the same silhouette, though the state + * change has destroyed the player in between. + */ + +const DURATION = 60; +const FRAME = 1000 / 60; +const LIMIT = 20000; + +// the game loop, run here one frame at a time (see transition-second-change) +let nextFrame = null; +let clock = 0; +const frame = async () => { + const callback = nextFrame; + nextFrame = null; + if (callback !== null) { + clock += FRAME; + callback(clock); + } + await new Promise((resolve) => { + setTimeout(resolve, 0); + }); +}; +const runUntil = async (check) => { + const end = globalThis.performance.now() + LIMIT; + while (globalThis.performance.now() < end) { + try { + check(); + return; + } catch { + await frame(); + } + } + check(); +}; + +/** a 20 × 30 image, its left half opaque */ +const leftHalf = () => { + const canvas = document.createElement("canvas"); + canvas.width = 20; + canvas.height = 30; + const ctx = canvas.getContext("2d"); + ctx.fillStyle = "#f00"; + ctx.fillRect(0, 0, 10, 30); + return canvas; +}; + +describe("a mask transition shaped like, and closing on, a sprite", () => { + let app; + beforeAll(async () => { + clock = globalThis.performance.now(); + vi.spyOn(globalThis, "requestAnimationFrame").mockImplementation( + (callback) => { + nextFrame = callback; + return 1; + }, + ); + vi.spyOn(globalThis, "cancelAnimationFrame").mockImplementation(() => { + nextFrame = null; + }); + boot(); + app = new Application(320, 240, { + parent: "screen", + renderer: video.CANVAS, + }); + await app.init(); + }); + afterAll(() => { + state.transition("fade", "#000", 0); + app?.destroy(); + vi.restoreAllMocks(); + }); + + it("the reveal opens where the hide closed, after the player is gone", async () => { + let player; + const start = state.USER + 90; + const next = state.USER + 91; + state.set( + start, + new Stage({ + onResetEvent(game) { + player = new Sprite(200, 50, { image: leftHalf() }); + player.anchorPoint.set(0, 0); + game.world.addChild(player); + }, + }), + ); + state.set(next, new Stage()); + state.setTransition(start, false); + state.change(start, true); + await runUntil(() => { + expect(state.isCurrent(start)).toBe(true); + expect(player?.ancestor).toBeDefined(); + }); + + state.transition("mask", "#000", DURATION, player, { + center: player, + invert: true, + }); + state.change(next); + + const hide = app.viewport.getCameraEffect(MaskEffect); + expect(hide.direction).toBe("hide"); + expect(hide.invert).toBe(true); + expect(hide._silhouette).toBeDefined(); + // the middle of the player's frame + expect(hide.center).toEqual({ x: 210, y: 65 }); + const silhouette = hide._silhouette.target.canvas; + + // the switch lands, the player goes with the old stage + let reveal; + await runUntil(() => { + expect(state.isCurrent(next)).toBe(true); + reveal = app.viewport.cameraEffects.find((fx) => { + return fx instanceof MaskEffect && fx.direction === "reveal"; + }); + expect(reveal).toBeDefined(); + }); + expect(player.offset).toBeUndefined(); + expect(reveal.invert).toBe(true); + expect(reveal.center).toEqual({ x: 210, y: 65 }); + expect(reveal._silhouette.target.canvas).toBe(silhouette); + + // just before it ends, nothing is covered any more: drawn over white, + // every corner and the middle read white + reveal.tween.stop(); + reveal.progress.value = 0.995; + const renderer = app.renderer; + renderer.save(); + renderer.resetTransform(); + renderer.setColor("#ffffff"); + renderer.fillRect(0, 0, 320, 240); + renderer.restore(); + reveal.draw(renderer, 320, 240); + for (const [x, y] of [ + [1, 1], + [318, 1], + [1, 238], + [318, 238], + [160, 120], + ]) { + expect((await readPixel(renderer, x, y))[0]).toBeGreaterThan(200); + } + reveal.progress.value = 1; + + // and the screen ends uncovered + await runUntil(() => { + expect(app.viewport.cameraEffects).toHaveLength(0); + }); + + // The player it was given is gone: a later change does not read it + // again (destroyed, or recycled into something else), but closes an + // iris on the centre of the screen, with nothing to warn about + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + state.setTransition(start, true); + state.change(start); + const again = app.viewport.getCameraEffect(MaskEffect); + expect(again._maskShape?.type).toBe("Ellipse"); + expect(again.center).toBeUndefined(); + expect(again.invert).toBe(true); + expect(warn).not.toHaveBeenCalled(); + warn.mockRestore(); + await runUntil(() => { + expect(state.isCurrent(start)).toBe(true); + expect(app.viewport.cameraEffects).toHaveLength(0); + }); + }); +}); diff --git a/packages/melonjs/tests/nineslicesprite.spec.js b/packages/melonjs/tests/nineslicesprite.spec.js index 4a5dec4ab8..f32a720b71 100644 --- a/packages/melonjs/tests/nineslicesprite.spec.js +++ b/packages/melonjs/tests/nineslicesprite.spec.js @@ -437,4 +437,38 @@ describe("NineSliceSprite", () => { expect(nss.nss_width).toBe(200); expect(nss.nss_height).toBe(120); }); + it("draws its slices through drawFrame, and blinks with flicker() like a Sprite", () => { + const nss = new NineSliceSprite(10, 20, { + image: makeImage(32, 32), + width: 80, + height: 60, + }); + const target = { + calls: [], + translate() {}, + rotate() {}, + drawImage(...args) { + this.calls.push(args); + }, + }; + // drawn at the place it is given, not at its own position + nss.drawFrame(target, 0, 0); + expect(target.calls.length).toBe(9); + const right = Math.max( + ...target.calls.map((c) => { + return c[5] + c[7]; + }), + ); + expect(right).toBe(80); + // draw() is Sprite's, so a flickering panel skips its hidden beats + const drawFrame = vi.spyOn(nss, "drawFrame"); + nss.flicker(1000); + nss._flicker.elapsed = 33 * 1 + 1; + nss.draw(target); + expect(drawFrame).not.toHaveBeenCalled(); + nss._flicker.elapsed = 33 * 2 + 1; + nss.draw(target); + expect(drawFrame).toHaveBeenCalledWith(target, 10, 20); + drawFrame.mockRestore(); + }); });