From 6e063101ccee7a6fdc18d734a056add58f83a251 Mon Sep 17 00:00:00 2001 From: nvms Date: Thu, 27 Mar 2025 17:48:01 -0400 Subject: [PATCH] feat(input): improve safety check of button assignment feat(time scale): adjust time scale logic, add rawDelta fix(migrateEntityId): update $ceMap on entity id change chore(tests): update tests chore(README): update readme to reflect these new changes --- packages/ngn/README.md | 70 ++++--- packages/ngn/bun.lockb | Bin 89785 -> 89785 bytes packages/ngn/package.json | 1 - packages/ngn/public/demo.js | 47 ++--- packages/ngn/public/demo.js.map | 4 +- packages/ngn/public/index.html | 11 + packages/ngn/src/demo.ts | 12 +- packages/ngn/src/ngn.ts | 44 +++- packages/ngn/src/packages/emitter/index.ts | 189 +++++++++++++++--- .../src/packages/input/devices/keyboard.ts | 11 +- .../ngn/src/packages/input/devices/mouse.ts | 7 +- packages/ngn/src/tests/ngn/index.ts | 4 + packages/ngn/src/tests/ngn/keyboard.test.ts | 25 +++ packages/ngn/src/tests/ngn/time.test.ts | 58 ++++++ packages/ngn/src/tests/ngn/world.test.ts | 4 +- 15 files changed, 382 insertions(+), 105 deletions(-) create mode 100644 packages/ngn/src/tests/ngn/time.test.ts diff --git a/packages/ngn/README.md b/packages/ngn/README.md index e9ceea2..f658b12 100644 --- a/packages/ngn/README.md +++ b/packages/ngn/README.md @@ -4,25 +4,25 @@ An ECS framework (and robust input system) for the web. -- [Comprehensive sample](#comprehensive-sample) -- [Installation](#installation) -- [API overview](#api-overview) - - [createWorld](#createworld) - - [Entities](#entities) - - [Components](#components) - - [Extending components](#extending-components) - - [Extras](#extras) - - [Keyboard, mouse and gamepad input](#keyboard-mouse-and-gamepad-input) - - [Input system](#input-system) - - [ButtonState](#buttonstate) - - [Mouse](#mouse) - - [Keyboard](#keyboard) - - [Gamepad](#gamepad) - - [Input usage examples](#input-usage-examples) - - [Gamepad](#gamepad-1) - - [Keyboard](#keyboard-1) - - [Mouse](#mouse-1) - - [Expiring log system](#expiring-log-system) +* [Comprehensive sample](#comprehensive-sample) +* [Installation](#installation) +* [API overview](#api-overview) + * [createWorld](#createworld) + * [Entities](#entities) + * [Components](#components) + * [Extending components](#extending-components) + * [Extras](#extras) + * [Keyboard, mouse and gamepad input](#keyboard-mouse-and-gamepad-input) + * [Input system](#input-system) + * [ButtonState](#buttonstate) + * [Mouse](#mouse) + * [Keyboard](#keyboard) + * [Gamepad](#gamepad) + * [Input usage examples](#input-usage-examples) + * [Gamepad](#gamepad-1) + * [Keyboard](#keyboard-1) + * [Mouse](#mouse-1) + * [Expiring log system](#expiring-log-system) @@ -83,6 +83,7 @@ const player = .addComponent(Alive) .addTag("player"); +// Create a bunch of monsters Array .from(Array(50)) .forEach((i) => @@ -181,20 +182,31 @@ const { state, createEntity, getEntity, onEntityCreated, query, addSystem, remov - Is passed to all systems (if you use ngn's system mechanics, which is optional). - Contains a useful `time` object that looks like: - * `state.time.delta` - time since last frame in ms, unaffected by scale. - * `state.time.loopDelta` - time since last call to main game loop, affected by sclae. useful for calculations involving time and scale. - * `state.time.scale` - time scale. (default: `1`, valid: `0.1 - 1`). - - Does not affect framerate at all. The scale determines how often to call the main game loop (if you use choose to use ngn's ticker). On a 60hz display, at a scale of 1, the main game loop is called every 16~ms, and every 33~ms at a scale of 0.5. + * `state.time.delta` - time since last frame in ms, scaled by time.scale. Use this value for all physics and movement calculations to ensure they respect the time scale. + * `state.time.rawDelta` - raw, unscaled time since last frame in ms. This is the actual time between render frames and doesn't change with time scale. + * `state.time.loopDelta` - time since last call to main game loop, affected by scale. + * `state.time.scale` - time scale. (default: `1`). + - Does not affect framerate at all. The scale affects both how often the main game loop is called and the delta time used for physics/movement calculations. At a scale of 1, the main loop is called every frame and delta equals rawDelta. At a scale of 0.5, the main loop is called approximately every other frame and delta is half of rawDelta. + + > **Important:** Time scaling separates rendering framerate from simulation speed. The game will always render at the device's refresh rate (e.g., 60fps), but the simulation speed (how fast objects move, animations play, etc.) is controlled by the time scale. Always use `delta` in your movement and physics calculations to ensure they respect the time scale: + > ```typescript + > // This will move at half speed when time.scale is 0.5 + > position.x += velocity.x * state.time.delta; + > ``` * `state.time.elapsed` - time since `start` was called in ms. * `state.time.fps` - frames per second. -This table may help provide clarity to the behavior of `time.scale`. + > **Note:** The "last frame" and "last call to main game loop" are different concepts. The engine always runs at the device's refresh rate (e.g. 60fps), so `rawDelta` and `delta` update every frame. However, the main game loop (where your game logic runs) may be called less frequently based on the time scale. For example, at scale 0.5, the main game loop runs every other frame, resulting in a `loopDelta` that's approximately twice the `delta`. -| scale | fps | delta | loopDelta | -| ----- | --- | ----- | --------- | -| 1 | 120 | 8.33 | 8.33 | -| 0.5 | 120 | 8.33 | 16.66 | -| 0.1 | 120 | 8.33 | 83.33 | +This table may help provide clarity to the behavior of `time.scale`: + +| scale | fps | rawDelta | delta | loopDelta | Description | +| ----- | --- | -------- | ----- | --------- | ----------- | +| 1 | 60 | 16.67 | 16.67 | 16.67 | Normal speed - main loop called exactly once per frame | +| 0.5 | 60 | 16.67 | 8.33 | 33.34 | Half speed - main loop called every ~2 frames | +| 2.0 | 60 | 16.67 | 33.34 | 8.33 | Double speed - main loop called ~twice per frame | + +The engine always renders at the device's refresh rate (fps), but the frequency of main loop calls and the simulation time (delta) are affected by the time scale. ### Entities diff --git a/packages/ngn/bun.lockb b/packages/ngn/bun.lockb index b15b49c6ca270040d30cb16aa721eeda02899661..234225602dd421ce93f97c6f8295c507eaa15dbf 100755 GIT binary patch delta 24 gcmdnFmv!e})(x9~ax%sl=o#o4nwoFk^Yd>C0EP?--2eap delta 24 bcmdnFmv!e})(x9~axyVM!R9?b|E2%{byo=| diff --git a/packages/ngn/package.json b/packages/ngn/package.json index 8c86f06..e16a4ee 100644 --- a/packages/ngn/package.json +++ b/packages/ngn/package.json @@ -11,7 +11,6 @@ "build:packages:input": "tsup src/packages/input/index.ts --format cjs,esm --dts --minify --clean --out-dir dist/packages/input", "build:packages:2d": "tsup src/packages/2d/index.ts --format cjs,esm --dts --minify --clean --out-dir dist/packages/2d", "test": "bun src/tests/index.ts", - "test:watch": "nodemon --watch src --watch tests --exec \"clear && pnpm run test\" --ext ts", "release": "bumpp package.json --commit 'Release %s' --push --tag && pnpm publish --access public --no-git-checks", "serve": "esr --serve src/demo.ts" }, diff --git a/packages/ngn/public/demo.js b/packages/ngn/public/demo.js index abbb234..dc019fc 100755 --- a/packages/ngn/public/demo.js +++ b/packages/ngn/public/demo.js @@ -29,8 +29,7 @@ function getCreateId(opts) { if (!str || num === 256) { str = ""; num = (1 + len) / 2 | 0; - while (num--) - str += HEX[256 * Math.random() | 0]; + while (num--) str += HEX[256 * Math.random() | 0]; str = str.substring(num = 0, len); } const date = Date.now().toString(36); @@ -113,8 +112,7 @@ var createWorld = () => { let xfps = 1; const xtimes = []; function handler(now) { - if (!state[$running]) - return craf(loopHandler); + if (!state[$running]) return craf(loopHandler); while (xtimes.length > 0 && xtimes[0] <= now - 1e3) { xtimes.shift(); } @@ -142,7 +140,9 @@ var createWorld = () => { }; function step2() { for (const system of state[$systems]) { - system(state); + if (system(state) === null) { + break; + } } } function addSystem2(...systems) { @@ -192,8 +192,7 @@ var createWorld = () => { }; const query = ({ and = [], or = [], not = [], tag = [] }) => { const validQuery = (c) => Object.prototype.hasOwnProperty.call(c, "name"); - if (![...and, ...or, ...not].every(validQuery)) - throw new Error("Invalid query"); + if (![...and, ...or, ...not].every(validQuery)) throw new Error("Invalid query"); const queryName = ["and", ...and.map((c) => c.name), "or", ...or.map((c) => c.name), "not", ...not.map((c) => c.name), "tag", ...tag].join(""); [...and, ...or, ...not].forEach((c) => { const dependencies = state[$queryDependencies].get(c.name) || /* @__PURE__ */ new Set(); @@ -210,8 +209,7 @@ var createWorld = () => { }; function destroyEntity(e) { const exists = state[$eMap][e.id]; - if (!exists) - return false; + if (!exists) return false; const componentsToRemove = Object.keys(state[$eciMap][e.id]); componentsToRemove.forEach((componentName) => { state[$ceMap][componentName] = state[$ceMap][componentName].filter((id) => id !== e.id); @@ -227,16 +225,14 @@ var createWorld = () => { return true; } function onEntityCreated(fn) { - if (typeof fn !== "function") - return; + if (typeof fn !== "function") return; state[$onEntityCreated].push(fn); return () => { state[$onEntityCreated] = state[$onEntityCreated].filter((f) => f !== fn); }; } function createComponent(entity, component, defaults = {}) { - if (state[$eciMap]?.[entity.id]?.[component.name] !== void 0) - return entity; + if (state[$eciMap]?.[entity.id]?.[component.name] !== void 0) return entity; const affectedQueries = state[$queryDependencies].get(component.name); if (affectedQueries) { affectedQueries.forEach(markQueryDirty); @@ -348,8 +344,7 @@ var createWorld = () => { } function migrateEntityId(oldId, newId) { const entity = state[$eMap][oldId]; - if (!entity) - return; + if (!entity) return; entity.id = newId; state[$eMap][newId] = entity; delete state[$eMap][oldId]; @@ -582,8 +577,7 @@ var createParticleEmitter = (opts) => { let dead = false; let paused = false; const update = (state) => { - if (dead) - return; + if (dead) return; context.globalCompositeOperation = opts.blendMode ?? "source-over"; const { loopDelta } = state.time; for (let i = particles.length - 1; i >= 0; i--) { @@ -683,7 +677,6 @@ var createParticleEmitter = (opts) => { if (opts.burst && particles.length === 0) { destroy(); } - context.globalCompositeOperation = "source-over"; }; const destroy = () => { dead = true; @@ -798,7 +791,7 @@ var particleSystem = createParticleSystem({ var emitter = particleSystem.createEmitter({ x: canvas.width / 2, y: canvas.height / 2, - maxParticles: 100, + maxParticles: 120, rate: 0.1, lifetime: 1e3, lifetimeVariation: 0.2, @@ -829,8 +822,8 @@ var emitter = particleSystem.createEmitter({ particleSystem.createEmitter({ x: particle.x, y: particle.y, - maxParticles: 3, - lifetimeVariation: 0.2, + maxParticles: 4, + lifetimeVariation: 0.5, size: 3, sizeVariation: 2, colorStart: ["#FF0000", "#ff5100"], @@ -851,8 +844,6 @@ var emitter = particleSystem.createEmitter({ }, onUpdate: (particle, state) => { particle.size = Math.max(0, particle.size - 0.35); - const v = pulse(state.time.elapsed, 0.25, -1, 1); - particle.x += v * 1; }, onRemove: (particle, state) => { } @@ -868,14 +859,20 @@ var fpsDrawSystem = (state) => { draw.text({ x: 10, y: 20 }, `FPS: ${state.time.fps.toFixed(2)}`, "white"); }; var particleCountSystem = (state) => { - draw.text({ x: 10, y: 40 }, `Particle count: ${particleSystem.numParticles}`, "white"); + draw.text({ x: 10, y: 40 }, `Particle count: ${particleSystem.numParticles}. Emitter count: ${emitter.particles.length}`, "white"); }; var particlePositionSystem = (state) => { const { time } = state; const xPos = pulse(time.elapsed, 0.25, canvas.width / 2 - 100, canvas.width / 2 + 100); emitter.x = xPos; }; -addSystem(clearCanvasSystem, fpsDrawSystem, particleCountSystem, particlePositionSystem, particleSystem); +addSystem( + clearCanvasSystem, + fpsDrawSystem, + particleCountSystem, + particlePositionSystem, + particleSystem +); defineMain(() => { step(); }); diff --git a/packages/ngn/public/demo.js.map b/packages/ngn/public/demo.js.map index 4a40c1d..255801a 100755 --- a/packages/ngn/public/demo.js.map +++ b/packages/ngn/public/demo.js.map @@ -1,7 +1,7 @@ { "version": 3, "sources": ["../src/misc.ts", "../src/ids.ts", "../src/ngn.ts", "../src/packages/2d/canvas.ts", "../src/packages/2d/draw.ts", "../src/packages/2d/create2d.ts", "../src/packages/emitter/index.ts", "../src/demo.ts"], - "sourcesContent": ["/**\n * Generates a sinusoidal pulse between a minimum and maximum value at a specified frequency.\n *\n * @param time - The time variable, typically representing elapsed time.\n * @param freq - The frequency of the pulse in cycles per unit time (default is 1).\n * @param min - The minimum value of the pulse (default is 0).\n * @param max - The maximum value of the pulse (default is 1).\n * @returns The calculated pulse value at the given time.\n */\nexport function pulse(time: number, freq: number = 1, min: number = 0, max: number = 1): number {\n const halfRange = (max - min) / 2;\n return min + halfRange * (1 + Math.sin(2 * Math.PI * freq * time));\n}\n\n/**\n * Performs a linear interpolation between two numbers.\n * @param a The start value.\n * @param b The end value.\n * @param t The interpolation factor (0-1).\n * @returns The interpolated value.\n */\nexport function lerp(a: number, b: number, t: number): number {\n return (1 - t) * a + t * b;\n}\n\n/**\n * Performs spherical linear interpolation between two numbers.\n * @param a The start value.\n * @param b The end value.\n * @param t The interpolation factor, between 0 and 1.\n * @returns The interpolated value.\n */\nexport function slerp(a: number, b: number, t: number): number {\n const theta = Math.acos(Math.min(Math.max(a / b, -1), 1)) * t;\n return a * Math.cos(theta) + b * Math.sin(theta);\n}\n\nexport function extend(component: () => T) {\n return (overrides: Partial): (() => T) => {\n const extendedCompponent = () => ({ ...component(), ...overrides });\n Object.defineProperty(extendedCompponent, \"name\", {\n value: component.name,\n });\n return extendedCompponent;\n };\n}\n", "/*\n This is a mashup of github.com/lukeed/hexoid and github.com/paralleldrive/cuid\n Both are MIT licensed.\n\n ~ https://github.com/paralleldrive/cuid/blob/f507d971a70da224d3eb447ed87ddbeb1b9fd097/LICENSE\n --\n MIT License\n Copyright (c) 2012 Eric Elliott\n Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n ~ https://github.com/lukeed/hexoid/blob/1070447cdc62d1780d2a657b0df64348fc1e5ec5/license\n --\n MIT License\n Copyright (c) Luke Edwards (lukeed.com)\n Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*/\n\nconst HEX: string[] = [];\n\nfor (let i = 0; i < 256; i++) {\n HEX[i] = (i + 256).toString(16).substring(1);\n}\n\nfunction pad(str: string, size: number) {\n const s = \"000000\" + str;\n return s.substring(s.length - size);\n}\n\nconst SHARD_COUNT = 32;\n\nexport function getCreateId(opts: { init: number; len: number }) {\n const len = opts.len || 16;\n let str = \"\";\n let num = 0;\n const discreteValues = 1_679_616; // Math.pow(36, 4)\n let current = opts.init + Math.ceil(discreteValues / 2);\n\n function counter() {\n current = current <= discreteValues ? current : 0;\n current++;\n return (current - 1).toString(16);\n }\n\n return () => {\n if (!str || num === 256) {\n str = \"\";\n num = ((1 + len) / 2) | 0;\n while (num--) str += HEX[(256 * Math.random()) | 0];\n str = str.substring((num = 0), len);\n }\n\n const date = Date.now().toString(36);\n const paddedCounter = pad(counter(), 6);\n const hex = HEX[num++];\n\n const shardKey = parseInt(hex, 16) % SHARD_COUNT;\n\n return `ngn${date}${paddedCounter}${hex}${str}${shardKey}`;\n };\n}\n", "import { getCreateId } from \"./ids\";\n\nconst createId = getCreateId({ init: 0, len: 4 });\n\n/**\n * entity.id -> component.name -> index of component in entity.components\n *\n * This map stores indices of components in the entity component array.\n * The purpose of this map is to allow for fast lookups of components in the\n * entity.components array (e.g. entity.getComponent()).\n */\nexport const $eciMap = Symbol();\n\n/**\n * component.name -> array of entity.ids that have this component\n */\nexport const $ceMap = Symbol();\nexport const $eMap = Symbol();\nexport const $queryResults = Symbol();\nexport const $dirtyQueries = Symbol();\nexport const $queryDependencies = Symbol();\nexport const $systems = Symbol();\nexport const $running = Symbol();\nexport const $onEntityCreated = Symbol();\nexport const $mainLoop = Symbol();\n\nexport type Component = () => {};\nexport type ComponentInstance = () => {\n __ngn__?: {\n parent: string;\n name: string;\n };\n} & {\n [key: string]: any;\n};\n\nexport type QueryConfig = Readonly<\n Partial<{\n /** Matches entities as long as the entity has all of the components in the provided array. */\n and: Component[];\n /** Matches entities as long as the entity has at least one of the components in the provided array. */\n or: Component[];\n /** Matches entities as long as the entity has none of the components in the provided array. */\n not: Component[];\n /** Matches entities that have any of these tag strings. */\n tag: string[];\n }>\n>;\n\nexport type Entity = Readonly<{\n id: string;\n components: ReturnType[];\n addTag: (tag: string) => Entity;\n removeTag: () => Entity;\n getTag: () => string;\n addComponent: (component: Component, defaults?: object) => Entity;\n removeComponent: (component: Component) => Entity;\n getComponent: (arg: T) => ReturnType;\n hasComponent: (component: Component) => boolean;\n destroy: () => void;\n}>;\n\nexport type QueryResults = {\n results: {\n entity: Entity;\n [componentName: string]: any;\n }[];\n};\n\nexport type SystemFn = (w: WorldState) => void;\nexport type SystemCls = { update: (w: WorldState) => void };\nexport type System = SystemCls | SystemFn;\n\nexport type WorldState = {\n [$eciMap]: { [key: number]: { [componentName: string]: number } };\n [$ceMap]: { [key: string]: string[] };\n [$eMap]: { [key: number]: any };\n [$dirtyQueries]: Set;\n [$queryDependencies]: Map>;\n [$queryResults]: { [key: string]: QueryResults };\n [$systems]: ((w: WorldState) => void)[];\n [$mainLoop]: (w: WorldState) => void;\n time: {\n /** The total elapsed time in seconds since the game loop started. */\n elapsed: number;\n /** The time in milliseconds since the last frame. */\n delta: number;\n /** The time in milliseconds since the last time the main loop was called. */\n loopDelta: number;\n /** The time in milliseconds of the last call to the main loop. */\n lastLoopDelta: number;\n /** The time scale of the game loop. */\n scale: number;\n /** The current frames per second. */\n fps: number;\n };\n [$running]: boolean;\n [$onEntityCreated]: ((e: Entity) => void)[];\n};\n\nexport const createWorld = () => {\n const state: WorldState = {\n [$eciMap]: {},\n [$ceMap]: {},\n [$eMap]: {},\n [$dirtyQueries]: new Set(),\n [$queryDependencies]: new Map(),\n [$queryResults]: {},\n [$systems]: [],\n [$mainLoop]: null,\n time: {\n elapsed: 0,\n delta: 0,\n loopDelta: 0,\n lastLoopDelta: 0,\n scale: 1,\n fps: 0,\n },\n [$running]: false,\n [$onEntityCreated]: [],\n };\n\n const defineMain = (callback: (w?: WorldState) => void) => {\n state[$mainLoop] = callback;\n };\n\n /**\n * start - starts the game loop.\n * @returns - a function to stop the loop.\n */\n const start = () => {\n let then = 0;\n let accumulator = 0;\n const boundLoop = handler.bind(start);\n let loopHandler = -1;\n const { time } = state;\n time.delta = 0;\n time.elapsed = 0;\n time.fps = 0;\n state[$running] = true;\n\n let raf: ((cb: FrameRequestCallback) => number) | null = null;\n let craf: ((handle: number) => void) | null = null;\n\n /**\n * Fake requestAnimationFrame and cancelAnimationFrame\n * so that we can run tests for this in node.\n */\n if (typeof window !== \"undefined\") {\n let now = performance.now();\n raf = (cb: FrameRequestCallback): number => {\n return requestAnimationFrame((timestamp) => {\n now = timestamp;\n cb(now);\n });\n };\n craf = cancelAnimationFrame;\n } else {\n let now = 0;\n raf = (cb: FrameRequestCallback): number => {\n return setTimeout(() => {\n now += 16.67;\n cb(now);\n }, 16.67) as unknown as number;\n };\n\n craf = (id: number) => {\n clearTimeout(id);\n };\n }\n\n let xfps = 1;\n const xtimes = [];\n\n function handler(now: number) {\n if (!state[$running]) return craf(loopHandler);\n\n while (xtimes.length > 0 && xtimes[0] <= now - 1000) {\n xtimes.shift();\n }\n\n xtimes.push(now);\n xfps = xtimes.length;\n time.fps = xfps;\n\n time.delta = now - then;\n then = now;\n\n accumulator += time.delta * time.scale;\n\n // Calculate the threshold for stepping the world based on the current frame rate\n const stepThreshold = 1000 / (time.fps || 60);\n\n // Step the world only when the accumulated scaled time exceeds the threshold\n while (accumulator >= stepThreshold) {\n time.loopDelta = now - time.lastLoopDelta;\n time.lastLoopDelta = now;\n\n state[$mainLoop](state);\n accumulator -= stepThreshold;\n }\n\n time.elapsed += time.delta * 0.001;\n\n loopHandler = raf(boundLoop);\n }\n\n loopHandler = raf(boundLoop);\n\n return () => (state[$running] = false);\n };\n\n const stop = () => {\n state[$running] = false;\n };\n\n function step() {\n for (const system of state[$systems]) {\n system(state);\n }\n }\n\n /**\n * Adds one or more systems to the ECS world.\n * A system can be either a @see SystemFn or a @see SystemCls.\n * @param systems An array of system classes or functions.\n * @throws {Error} If a system is not a valid system class or function.\n */\n function addSystem(...systems: (SystemCls | SystemFn)[]) {\n for (const system of systems) {\n // If the system is a function, add it to the world systems array\n if (typeof system === \"function\") {\n state[$systems].push(system);\n // If the system has an `update` method, add that method to the world systems array\n } else if (system.update && typeof system.update === \"function\") {\n state[$systems].push(system.update);\n // If the system is not a valid system class or function, throw an error\n } else {\n throw new Error(`Not a valid system: ${JSON.stringify(system)}`);\n }\n }\n }\n\n /**\n * Removes one or more systems from the world.\n *\n * @param {...(SystemCls | SystemFn)[]} systems - The system or systems to remove.\n * @throws {TypeError} Throws an error if the system parameter is not a function or an object with an update function.\n * @returns {void}\n */\n function removeSystem(...systems: (SystemCls | SystemFn)[]): void {\n for (const system of systems) {\n if (typeof system === \"function\") {\n state[$systems] = state[$systems].filter((s) => s !== system);\n } else if (system.update && typeof system.update === \"function\") {\n state[$systems] = state[$systems].filter((s) => s !== system.update);\n } else {\n throw new TypeError(\"Parameter must be a function or an object with an update function.\");\n }\n }\n }\n\n /**\n * Retrieves query results based on the given configuration and query name.\n * If non-dirty query results exist for this queryName, returns them. Otherwise, filters entities based on the queryConfig\n * and updates the state with the new query results before returning them.\n *\n * @param {QueryConfig} queryConfig - The configuration object containing 'and', 'or', 'not' and 'tag' arrays of component names.\n * @param {string} queryName - The name of the query to retrieve or update results for.\n * @returns {any[]} An array of result objects, each containing an entity and its components as properties.\n */\n const getQuery = (queryConfig: QueryConfig, queryName: string) => {\n // If we have non-dirty query results for this queryName, return them\n if (!state[$dirtyQueries].has(queryName) && state[$queryResults][queryName]) {\n return state[$queryResults][queryName].results;\n }\n\n const { and = [], or = [], not = [], tag = [] } = queryConfig;\n const entities: Entity[] = Object.values(state[$eMap]).filter((entity) => {\n return (\n (!not.length || !not.some((component) => entity.hasComponent(component))) &&\n (!and.length || and.every((component) => entity.hasComponent(component))) &&\n (!or.length || or.some((component) => entity.hasComponent(component))) &&\n (!tag.length || tag.some((t) => entity.tag === t))\n );\n });\n\n state[$queryResults][queryName] = {\n results: entities.map((entity) => {\n const result: any = { entity };\n\n entity.components.forEach((component) => {\n result[component.__ngn__.name] = component;\n });\n\n return result;\n }),\n };\n\n state[$dirtyQueries].delete(queryName);\n\n return state[$queryResults][queryName].results;\n };\n\n const markQueryDirty = (queryName: string) => {\n state[$dirtyQueries].add(queryName);\n };\n\n /**\n * Defines a query for filtering entities based on a combination of criteria.\n * @param queryConfig The configuration for the query. Contains and, or, not and tag criteria.\n * @throws {Error} Invalid query if any criteria in the query config does not have a 'name' property.\n * @returns A function that takes a query implementation and returns the results of the query.\n */\n const query = ({ and = [], or = [], not = [], tag = [] }: QueryConfig) => {\n // Checks if a criteria object has a 'name' property\n const validQuery = (c: Component) => Object.prototype.hasOwnProperty.call(c, \"name\");\n\n // Throws an error if any criteria object in the query config does not have a 'name' property\n if (![...and, ...or, ...not].every(validQuery)) throw new Error(\"Invalid query\");\n\n // Constructs a string representing the query name based on the criteria in the query config\n const queryName = [\"and\", ...and.map((c) => c.name), \"or\", ...or.map((c) => c.name), \"not\", ...not.map((c) => c.name), \"tag\", ...tag].join(\"\");\n\n // Component dependencies\n [...and, ...or, ...not].forEach((c) => {\n const dependencies = state[$queryDependencies].get(c.name) || new Set();\n dependencies.add(queryName);\n state[$queryDependencies].set(c.name, dependencies);\n });\n\n // Tag dependencies\n tag.forEach((t) => {\n const tagKey = `tag:${t}`;\n const dependencies = state[$queryDependencies].get(tagKey) || new Set();\n dependencies.add(queryName);\n state[$queryDependencies].set(tagKey, dependencies);\n });\n\n return (queryImpl: (results: { entity: Entity }[]) => void) => queryImpl(getQuery({ and, or, not, tag }, queryName));\n };\n\n function destroyEntity(e: Entity) {\n const exists = state[$eMap][e.id];\n\n if (!exists) return false;\n\n const componentsToRemove: string[] = Object.keys(state[$eciMap][e.id]);\n\n componentsToRemove.forEach((componentName) => {\n state[$ceMap][componentName] = state[$ceMap][componentName].filter((id) => id !== e.id);\n });\n\n delete state[$eciMap][e.id];\n delete state[$eMap][e.id];\n\n componentsToRemove.forEach((componentName) => {\n const affectedQueries = state[$queryDependencies].get(componentName);\n\n if (affectedQueries) {\n affectedQueries.forEach(markQueryDirty);\n }\n });\n\n return true;\n }\n\n function onEntityCreated(fn: any) {\n if (typeof fn !== \"function\") return;\n\n state[$onEntityCreated].push(fn);\n\n return () => {\n state[$onEntityCreated] = state[$onEntityCreated].filter((f) => f !== fn);\n };\n }\n\n /**\n * Creates a new component for the given entity and adds it to the world.\n * @param entity The entity to add the component to.\n * @param component The component function to add.\n * @param defaults (optional) Default values to apply to the component.\n * @returns The modified entity with the new component added.\n */\n function createComponent(entity: Entity, component: Function, defaults: object = {}): Entity {\n // If the entity already has this component, return the unmodified entity.\n if (state[$eciMap]?.[entity.id]?.[component.name] !== undefined) return entity;\n\n const affectedQueries = state[$queryDependencies].get(component.name);\n\n if (affectedQueries) {\n affectedQueries.forEach(markQueryDirty);\n }\n\n const componentInstance = component();\n\n if (componentInstance.onAttach && typeof componentInstance.onAttach === \"function\") {\n componentInstance.onAttach(entity);\n }\n\n // Create the component, assigning defaults and a reference to the parent entity.\n entity.components.push(\n Object.assign(\n {},\n {\n ...componentInstance,\n ...defaults,\n __ngn__: {\n parent: entity.id,\n name: component.name,\n },\n },\n ) as ComponentInstance,\n );\n\n // Add the component index to the entity's index map.\n state[$eciMap][entity.id] = state[$eciMap][entity.id] || {};\n state[$eciMap][entity.id][component.name] = entity.components.length - 1;\n\n // Add the entity to the component's entity map.\n state[$ceMap][component.name] = state[$ceMap][component.name] || [];\n state[$ceMap][component.name].push(entity.id);\n\n return entity;\n }\n\n /**\n * Creates an entity with the given specification object.\n * @param {object} spec - Optional data to be stored on the entity.\n * @returns {any} - Returns the created entity.\n */\n function createEntity(spec: T & { id?: string } = {} as T): T & Entity {\n const id = spec.id ?? createId();\n const components: any[] = [];\n\n const tagKey = (t: string) => `tag:${t}`;\n\n function updateTagQueries(tagKey: string) {\n const affectedQueries = state[$queryDependencies].get(tagKey);\n\n if (affectedQueries) {\n affectedQueries.forEach(markQueryDirty);\n }\n }\n\n function addTag(t: string): Entity {\n const previousTagKey = tagKey(this.tag);\n\n this.tag = t;\n\n updateTagQueries(tagKey(t));\n updateTagQueries(previousTagKey);\n\n return this;\n }\n\n function removeTag(): Entity {\n const previousTagKey = tagKey(this.tag);\n this.tag = \"\";\n\n updateTagQueries(previousTagKey);\n\n return this;\n }\n\n function getTag() {\n return this.tag;\n }\n\n function addComponent(c: Component, defaults = {}) {\n return createComponent(this, c, defaults);\n }\n\n function hasComponent(component: Component) {\n return state[$eciMap]?.[id]?.[component.name] !== undefined;\n }\n\n function getComponent(arg: T): ReturnType {\n const index = state[$eciMap][id][arg.name];\n return components[index];\n }\n\n /**\n * Removes the specified component from the entity and updates the world state accordingly.\n *\n * @param component The component to remove from the entity.\n * @returns The modified entity.\n */\n function removeComponent(component: Component | string): Entity {\n const name = typeof component === \"string\" ? component : component.name;\n\n const componentInstance = getComponent(typeof component === \"string\" ? ({ name } as any) : component);\n\n if (componentInstance && componentInstance.onDetach && typeof componentInstance.onDetach === \"function\") {\n componentInstance.onDetach(this);\n }\n\n const affectedQueries = state[$queryDependencies].get(name);\n\n if (affectedQueries) {\n affectedQueries.forEach(markQueryDirty);\n }\n\n // Set the entity's component index for the specified component to undefined.\n state[$eciMap][id][name] = undefined;\n\n // Remove the entity's ID from the component's entity list.\n state[$ceMap][name] = state[$ceMap][name].filter((e) => e !== id);\n\n // Remove the component from the entity's component list.\n const index = state[$eciMap][id][name];\n components.splice(index, 1);\n\n // Update the entity's component indices for all components after the removed component.\n Object.keys(state[$eciMap][id]).forEach((componentName) => {\n if (state[$eciMap][id][componentName] > components.findIndex((c) => c.name === componentName)) {\n state[$eciMap][id][componentName]--;\n }\n });\n\n // Return the modified entity.\n return this;\n }\n\n function destroy() {\n return destroyEntity(this);\n }\n\n const entity = Object.assign({}, spec, {\n id,\n components,\n addTag,\n removeTag,\n getTag,\n addComponent,\n hasComponent,\n getComponent,\n removeComponent,\n destroy,\n });\n\n // If we are focing a specific entity id, we need to migrate any\n // entity that might already occupy this space.\n if (spec.id !== undefined && state[$eMap][spec.id]) {\n migrateEntityId(spec.id, createId());\n }\n\n state[$eMap][id] = entity;\n state[$eciMap][id] = {};\n\n state[$onEntityCreated].forEach((fn) => {\n fn(entity);\n });\n\n return entity as unknown as T & Entity;\n }\n\n /**\n * migrateEntityId updates the id of an entity in the world, and all\n * associated world maps.\n * @param oldId The id of the entity to migrate.\n * @param newId The id to migrate the entity to.\n */\n function migrateEntityId(oldId: string, newId: string) {\n const entity = state[$eMap][oldId];\n\n if (!entity) return;\n\n entity.id = newId;\n\n state[$eMap][newId] = entity;\n delete state[$eMap][oldId];\n\n state[$eciMap][newId] = state[$eciMap][oldId];\n delete state[$eciMap][oldId];\n }\n\n function getEntity(id: string): Entity {\n return state[$eMap][id];\n }\n\n return {\n state,\n query,\n createEntity,\n getEntity,\n onEntityCreated,\n addSystem,\n removeSystem,\n start,\n stop,\n step,\n defineMain,\n };\n};\n", "export type CreateCanvasOptions = Partial<{\n width: number;\n height: number;\n fullscreen: boolean;\n target: HTMLElement;\n}>;\n\nexport const createCanvas = (options: CreateCanvasOptions) => {\n const canvas = document.createElement(\"canvas\");\n const { target, fullscreen } = options;\n const { body } = window.document;\n\n if (target && fullscreen) {\n options.target = null;\n } else if (!target && !fullscreen) {\n options.fullscreen = true;\n }\n\n if (fullscreen) {\n Object.assign(canvas.style, {\n position: \"absolute\",\n top: \"0\",\n left: \"0\",\n });\n canvas.width = window.innerWidth;\n canvas.height = window.innerHeight;\n body.appendChild(canvas);\n Object.assign(body.style, {\n margin: \"0\",\n padding: \"0\",\n width: \"100%\",\n height: \"100%\",\n overflow: \"hidden\",\n });\n }\n\n if (target) {\n target.appendChild(canvas);\n target.style.overflow = \"hidden\";\n canvas.width = canvas.offsetWidth;\n canvas.height = canvas.offsetHeight;\n }\n\n canvas.width = canvas.offsetWidth;\n canvas.height = canvas.offsetHeight;\n canvas.style.width = \"100%\";\n canvas.style.height = \"100%\";\n\n const existingMeta = window.document.querySelector(`meta[name=\"viewport\"]`);\n if (existingMeta) {\n Object.assign(existingMeta, {\n content: \"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0\",\n });\n } else {\n const meta = Object.assign(window.document.createElement(\"meta\"), {\n name: \"viewport\",\n content: \"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0\",\n });\n window.document.head.appendChild(meta);\n }\n\n return canvas;\n};\n", "export type Vector2 = {\n x: number;\n y: number;\n};\n\nconst fastRound = (num: number): number => ~~(0.5 + num);\n\nconst fastRoundVector2 = (v: Vector2): Vector2 => ({\n x: fastRound(v.x),\n y: fastRound(v.y),\n});\n\nexport const createDraw = (context: CanvasRenderingContext2D) => {\n const text = (v: Vector2, text: string, color: string = \"black\", size: number = 16) => {\n v = fastRoundVector2(v);\n context.save();\n context.fillStyle = color;\n context.font = `${size}px sans-serif`;\n context.fillText(text, v.x, v.y);\n context.restore();\n };\n\n const line = (from: Vector2, to: Vector2, color: string = \"black\", lineWidth: number = 1) => {\n from = fastRoundVector2(from);\n to = fastRoundVector2(to);\n context.save();\n context.beginPath();\n context.moveTo(from.x, from.y);\n context.lineTo(to.x, to.y);\n context.strokeStyle = color; // Use the color parameter\n context.lineWidth = lineWidth;\n context.stroke();\n context.closePath();\n context.restore();\n };\n\n const rectangle = (pos: Vector2, dimensions: Vector2, color: string = \"black\", lineWidth: number = 1) => {\n pos = fastRoundVector2(pos);\n dimensions = fastRoundVector2(dimensions);\n context.save();\n context.beginPath();\n context.rect(pos.x, pos.y, dimensions.x, dimensions.y);\n context.lineWidth = lineWidth;\n context.strokeStyle = color;\n context.stroke();\n context.closePath();\n context.restore();\n };\n\n const circle = (pos: Vector2, radius: number = 25, color: string = \"black\", lineWidth: number = 1) => {\n pos = fastRoundVector2(pos);\n context.save();\n context.beginPath();\n context.strokeStyle = color;\n context.lineWidth = lineWidth;\n context.arc(pos.x, pos.y, radius, 0, Math.PI * 2, true);\n context.stroke();\n context.closePath();\n context.restore();\n };\n\n return {\n text,\n line,\n rectangle,\n circle,\n };\n};\n", "import { createCanvas, CreateCanvasOptions } from \"./canvas\";\nimport { createDraw } from \"./draw\";\n\ntype Create2DOptions = Partial<{\n canvas: CreateCanvasOptions;\n}>;\n\nexport const create2D = (options: Create2DOptions) => {\n const { width = 800, height = 600, fullscreen = false, target = null } = options.canvas;\n const canvas = createCanvas({ width, height, fullscreen, target });\n const context = canvas.getContext(\"2d\");\n const draw = createDraw(context);\n\n const onWindowResize = () => {\n if (fullscreen) {\n canvas.style.width = \"100%\";\n canvas.style.height = \"100%\";\n canvas.width = window.innerWidth;\n canvas.height = window.innerHeight;\n return;\n }\n\n canvas.width = canvas.offsetWidth;\n canvas.height = canvas.offsetHeight;\n };\n\n window.addEventListener(\"resize\", onWindowResize);\n\n const destroy = () => {\n window.removeEventListener(\"resize\", onWindowResize);\n canvas.parentElement.removeChild(canvas);\n };\n\n return { canvas, context, draw, destroy };\n};\n", "import { WorldState } from \"../../ngn\";\n\nexport type Particle = {\n x: number;\n y: number;\n size: number;\n color: string;\n colorStart: string;\n colorEnd: string;\n lifetime: number;\n speedX: number;\n speedY: number;\n scaleX: number;\n scaleY: number;\n onInit?: (particle: Particle, state: WorldState) => void;\n onRemove?: (particle: Particle, state: WorldState) => void;\n onUpdate?: (particle: Particle, state: WorldState) => void;\n};\n\nexport enum ColorEasing {\n LINEAR = \"linear\",\n EASE_IN = \"easeIn\",\n EASE_OUT = \"easeOut\",\n EASE_IN_OUT = \"easeInOut\",\n}\n\nexport type FadeEasing = ColorEasing;\n\ntype BlendMode =\n | \"color\"\n | \"color-burn\"\n | \"color-dodge\"\n | \"copy\"\n | \"darken\"\n | \"destination-atop\"\n | \"destination-in\"\n | \"destination-out\"\n | \"destination-over\"\n | \"difference\"\n | \"exclusion\"\n | \"hard-light\"\n | \"hue\"\n | \"lighten\"\n | \"lighter\"\n | \"luminosity\"\n | \"multiply\"\n | \"overlay\"\n | \"saturation\"\n | \"screen\"\n | \"soft-light\"\n | \"source-atop\"\n | \"source-in\"\n | \"source-out\"\n | \"source-over\"\n | \"xor\";\n\nexport type ParticleEmitterOptions = {\n x?: number; // X position\n y?: number; // Y position\n maxParticles?: number; // Max number of particles\n rate?: number; // Particles per second\n lifetime?: number; // Lifetime of each particle\n lifetimeVariation?: number; // Variation in lifetime\n size?: number; // Size of each particle\n sizeVariation?: number; // Variation in size\n colorStart?: string | string[]; // Start color\n colorEnd?: string | string[]; // End color\n colorEasing?: ColorEasing; // Easing function for color\n fadeOutEasing?: FadeEasing;\n speed?: number; // Speed of each particle\n speedVariation?: number; // Variation in speed\n angle?: number; // Angle of emission\n spread?: number; // Spread of emission\n gravity?: { x: number; y: number }; // Gravity affecting the particles\n blendMode?: BlendMode; // Blend mode\n canvas: HTMLCanvasElement; // Canvas to draw on\n burst?: boolean; // If true, emit all particles at once and then stop\n /** Per-particle initialization callback. */\n onInit?: (particle: Particle, state: WorldState) => void; // Callback for particle initialization\n /** Per-particle update callback. */\n onUpdate?: (particle: Particle, state: WorldState) => void; // Callback for particle update\n /** Per-particle removal callback. */\n onRemove?: (particle: Particle, state: WorldState) => void; // Callback for particle removal\n};\n\nconst getDefaultParticleEmitterOptions = (opts: Partial): ParticleEmitterOptions => ({\n ...opts,\n x: opts.x ?? 0,\n y: opts.y ?? 0,\n maxParticles: opts.maxParticles ?? 100,\n rate: opts.rate ?? 1,\n lifetime: opts.lifetime ?? 1000,\n lifetimeVariation: opts.lifetimeVariation ?? 0,\n size: opts.size ?? 5,\n sizeVariation: opts.sizeVariation ?? 0,\n colorStart: opts.colorStart ?? \"#000000\",\n colorEnd: opts.colorEnd ?? \"#000000\",\n colorEasing: opts.colorEasing ?? ColorEasing.LINEAR,\n angle: opts.angle ?? 0,\n spread: opts.spread ?? 0,\n gravity: opts.gravity ?? { x: 0, y: 0 },\n speed: opts.speed ?? 0.1,\n speedVariation: opts.speedVariation ?? 0,\n canvas: opts.canvas,\n burst: opts.burst ?? false,\n});\n\nexport type ParticleEmitter = {\n particles: Particle[];\n update: (state: WorldState) => void;\n destroy: () => void;\n pause: () => void;\n resume: () => void;\n x: number;\n y: number;\n};\n\nexport type ParticleSystemOptions = {\n x: number;\n y: number;\n canvas: HTMLCanvasElement;\n // A property to determine whether or not it starts immediately\n start?: boolean;\n};\n\nconst interpolateColor = (colorStart: string, colorEnd: string, factor: number, easing: ColorEasing): string => {\n switch (easing) {\n case ColorEasing.EASE_IN:\n factor = Math.pow(factor, 2);\n break;\n case ColorEasing.EASE_OUT:\n factor = 1 - Math.pow(1 - factor, 2);\n break;\n case ColorEasing.EASE_IN_OUT:\n if (factor < 0.5) {\n factor = 2 * Math.pow(factor, 2);\n } else {\n factor = 1 - 2 * Math.pow(1 - factor, 2);\n }\n break;\n case ColorEasing.LINEAR:\n default:\n // No adjustment needed for linear\n break;\n }\n\n // Assuming colorStart and colorEnd are in the format \"#RRGGBB\"\n const color1 = parseInt(colorStart.slice(1), 16);\n const color2 = parseInt(colorEnd.slice(1), 16);\n\n const r1 = (color1 >> 16) & 0xff;\n const g1 = (color1 >> 8) & 0xff;\n const b1 = color1 & 0xff;\n\n const r2 = (color2 >> 16) & 0xff;\n const g2 = (color2 >> 8) & 0xff;\n const b2 = color2 & 0xff;\n\n const r = Math.round(r1 + factor * (r2 - r1));\n const g = Math.round(g1 + factor * (g2 - g1));\n const b = Math.round(b1 + factor * (b2 - b1));\n\n return `#${((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)}`;\n};\n\nconst hexToRgb = (hex: string): string => {\n const color = parseInt(hex.slice(1), 16);\n const r = (color >> 16) & 0xff;\n const g = (color >> 8) & 0xff;\n const b = color & 0xff;\n return `${r}, ${g}, ${b}`;\n};\n\nexport const createParticleEmitter = (opts: ParticleEmitterOptions): ParticleEmitter => {\n opts = getDefaultParticleEmitterOptions(opts);\n const particles = [];\n let timeSinceLastEmission = 0;\n const emissionInterval = 1 / opts.rate;\n const lifetimeVariation = opts.lifetimeVariation ?? 0;\n const context = opts.canvas.getContext(\"2d\");\n const angleInRadians = opts.angle * (Math.PI / 180);\n let dead = false;\n let paused = false;\n\n const update = (state: WorldState) => {\n if (dead) return;\n\n context.globalCompositeOperation = opts.blendMode ?? \"source-over\";\n\n const { loopDelta } = state.time;\n\n for (let i = particles.length - 1; i >= 0; i--) {\n const particle = particles[i];\n const lifeFactor = particle.lifetime / opts.lifetime;\n let opacity = 1;\n\n particle.color = interpolateColor(particle.colorStart, particle.colorEnd, 1 - lifeFactor, opts.colorEasing);\n\n if (opts.fadeOutEasing) {\n switch (opts.fadeOutEasing) {\n case ColorEasing.EASE_IN:\n opacity = Math.pow(lifeFactor, 2);\n break;\n case ColorEasing.EASE_OUT:\n opacity = 1 - Math.pow(1 - lifeFactor, 2);\n break;\n case ColorEasing.EASE_IN_OUT:\n if (lifeFactor < 0.5) {\n opacity = 2 * Math.pow(lifeFactor, 2);\n } else {\n opacity = 1 - 2 * Math.pow(1 - lifeFactor, 2);\n }\n break;\n case ColorEasing.LINEAR:\n default:\n opacity = lifeFactor;\n break;\n }\n }\n\n if (!paused) {\n particle.x += particle.speedX * loopDelta;\n particle.y += particle.speedY * loopDelta;\n\n particle.speedX += (opts.gravity.x * loopDelta) / 1000;\n particle.speedY += (opts.gravity.y * loopDelta) / 1000;\n\n particle.lifetime -= state.time.loopDelta;\n\n if (opts.onUpdate) {\n opts.onUpdate(particle, state);\n }\n\n if (particle.onUpdate) {\n particle.onUpdate(particle, state);\n }\n }\n\n if (particle.lifetime <= 0) {\n if (opts.onRemove) {\n opts.onRemove(particle, state);\n }\n\n if (particle.onRemove) {\n particle.onRemove(particle, state);\n }\n\n particles.splice(i, 1);\n } else {\n context.fillStyle = `rgba(${hexToRgb(particle.color)}, ${opacity})`;\n context.beginPath();\n // context.arc(particle.x * particle.scaleX, particle.y * particle.scaleY, particle.size, 0, Math.PI * 2);\n // draw a rectangel instead:\n context.rect(particle.x * particle.scaleX, particle.y * particle.scaleY, particle.size, particle.size);\n context.closePath();\n context.fill();\n }\n }\n\n const emitParticle = () => {\n const lifetimeVariationAmount = lifetimeVariation ? opts.lifetime * lifetimeVariation * Math.random() : 0;\n const particleLifetime = opts.lifetime + lifetimeVariationAmount * (Math.random() < 0.5 ? -1 : 1);\n const colorStart = Array.isArray(opts.colorStart) ? opts.colorStart[Math.floor(Math.random() * opts.colorStart.length)] : opts.colorStart;\n const colorEnd = Array.isArray(opts.colorEnd) ? opts.colorEnd[Math.floor(Math.random() * opts.colorEnd.length)] : opts.colorEnd;\n const particle = spawnParticle({\n x: opts.x,\n y: opts.y,\n colorStart: colorStart,\n colorEnd: colorEnd,\n color: colorStart,\n lifetime: particleLifetime,\n size: Math.max(0, opts.size + (Math.random() - 0.5) * opts.sizeVariation),\n speedX: opts.speed * (Math.sin(angleInRadians) + (Math.random() - 0.5) * opts.spread),\n speedY: -opts.speed * (Math.cos(angleInRadians) + (Math.random() - 0.5) * opts.spread),\n scaleX: 1,\n scaleY: 1,\n });\n\n if (opts.onInit) {\n opts.onInit(particle, state);\n }\n\n if (particle.onInit) {\n particle.onInit(particle, state);\n }\n };\n\n if (!paused) {\n if (opts.burst && timeSinceLastEmission === 0) {\n for (let i = 0; i < opts.maxParticles; i++) {\n emitParticle();\n }\n\n timeSinceLastEmission = -1;\n } else if (!opts.burst) {\n timeSinceLastEmission += loopDelta;\n\n while (timeSinceLastEmission >= emissionInterval && particles.length < opts.maxParticles) {\n emitParticle();\n timeSinceLastEmission -= emissionInterval;\n }\n }\n }\n\n if (opts.burst && particles.length === 0) {\n destroy();\n }\n\n context.globalCompositeOperation = \"source-over\";\n };\n\n const destroy = () => {\n dead = true;\n particles.length = 0;\n return;\n };\n\n const spawnParticle = (p: Particle): Particle => {\n particles.push(p);\n return p;\n };\n\n const pause = () => {\n paused = true;\n };\n\n const resume = () => {\n paused = false;\n };\n\n document.addEventListener(\"visibilitychange\", () => {\n if (document.visibilityState === \"visible\") {\n resume();\n } else {\n pause();\n }\n });\n\n return {\n particles,\n update,\n destroy,\n pause,\n resume,\n set x(value: number) {\n opts.x = value;\n },\n get x() {\n return opts.x;\n },\n set y(value: number) {\n opts.y = value;\n },\n get y() {\n return opts.y;\n },\n };\n};\n\nexport const createParticleSystem = (opts: ParticleSystemOptions) => {\n let _x = opts.x;\n let _y = opts.y;\n const emitters: ParticleEmitter[] = [];\n const startImmediately = opts.start ?? true;\n\n const update = (state: WorldState) => {\n emitters.forEach((emitter) => {\n emitter.update(state);\n });\n };\n\n const destroy = () => {\n emitters.forEach((emitter) => {\n emitter.destroy();\n });\n };\n\n const createEmitter = (opts: ParticleEmitterOptions): ParticleEmitter => {\n const emitter = createParticleEmitter({\n ...opts,\n /* x: _x, */\n /* y: _y, */\n });\n emitters.push(emitter);\n\n if (!startImmediately) {\n emitter.pause();\n }\n\n return emitter;\n };\n\n const pause = () => {\n emitters.forEach((emitter) => {\n emitter.pause();\n });\n };\n\n const start = () => {\n emitters.forEach((emitter) => {\n emitter.resume();\n });\n };\n\n return {\n update,\n destroy,\n createEmitter,\n pause,\n start,\n set x(value: number) {\n _x = value;\n },\n get x() {\n return _x;\n },\n set y(value: number) {\n _y = value;\n },\n get y() {\n return _y;\n },\n get numParticles() {\n return emitters.reduce((acc, emitter) => acc + emitter.particles.length, 0);\n },\n };\n};\n", "import { pulse } from \"./misc\";\nimport { createWorld, type WorldState } from \"./ngn\";\nimport { create2D } from \"./packages/2d\";\nimport { ColorEasing, createParticleSystem, Particle } from \"./packages/emitter\";\n\nconst { canvas, draw } = create2D({ canvas: { fullscreen: true } });\n\nconst particleSystem = createParticleSystem({\n x: canvas.width / 2,\n y: canvas.height / 2,\n canvas,\n});\n\nconst emitter = particleSystem.createEmitter({\n x: canvas.width / 2,\n y: canvas.height / 2,\n maxParticles: 100,\n rate: 0.1,\n lifetime: 1000,\n lifetimeVariation: 0.2,\n size: 20,\n sizeVariation: 10,\n colorStart: [\"#FF0000\", \"#ff5100\"],\n colorEnd: \"#222222\",\n colorEasing: ColorEasing.EASE_IN,\n fadeOutEasing: ColorEasing.EASE_OUT,\n speed: 0.1,\n speedVariation: 1,\n angle: 0,\n spread: 0.75,\n gravity: { x: 0, y: 0 },\n canvas,\n burst: false,\n\n onInit: (particle: Particle, state: WorldState) => {\n particle.x += Math.random() < 0.5 ? -6 : 6;\n particle.y += Math.random() < 0.5 ? -6 : 6;\n\n if (!(Math.random() < 0.02)) {\n return;\n }\n\n particle.size = 15;\n particle.speedY = -0.3;\n particle.lifetime = 1000;\n particle.colorEnd = \"#ff0000\";\n\n particle.onRemove = () => {\n particleSystem.createEmitter({\n x: particle.x,\n y: particle.y,\n maxParticles: 3,\n lifetimeVariation: 0.2,\n size: 3,\n sizeVariation: 2,\n colorStart: [\"#FF0000\", \"#ff5100\"],\n colorEnd: \"#222222\",\n colorEasing: ColorEasing.EASE_IN,\n fadeOutEasing: ColorEasing.EASE_OUT,\n speed: 0.02,\n speedVariation: 1,\n spread: 6,\n angle: 180,\n canvas,\n burst: true,\n });\n };\n\n particle.onUpdate = () => {\n particle.size = Math.max(0, particle.size + 0.25);\n };\n },\n onUpdate: (particle: Particle, state: WorldState) => {\n particle.size = Math.max(0, particle.size - 0.35);\n const v = pulse(state.time.elapsed, 0.25, -1, 1);\n particle.x += v * 1;\n },\n onRemove: (particle: Particle, state: WorldState) => {},\n});\n\nconst { addSystem, start, step, defineMain } = createWorld();\n\nconst clearCanvasSystem = () => {\n const context = canvas.getContext(\"2d\");\n context.clearRect(0, 0, canvas.width, canvas.height);\n\n context.fillStyle = \"#111\";\n context.fillRect(0, 0, canvas.width, canvas.height);\n};\n\nconst fpsDrawSystem = (state: WorldState) => {\n draw.text({ x: 10, y: 20 }, `FPS: ${state.time.fps.toFixed(2)}`, \"white\");\n};\n\nconst particleCountSystem = (state: WorldState) => {\n draw.text({ x: 10, y: 40 }, `Particle count: ${particleSystem.numParticles}`, \"white\");\n};\n\nconst particlePositionSystem = (state: WorldState) => {\n const { time } = state;\n const xPos = pulse(time.elapsed, 0.25, canvas.width / 2 - 100, canvas.width / 2 + 100);\n // const yPos = pulse(time.elapsed, 0.25, canvas.height / 2 - 100, canvas.height / 2 + 100);\n emitter.x = xPos;\n // emitter.y = yPos;\n};\n\naddSystem(clearCanvasSystem, fpsDrawSystem, particleCountSystem, particlePositionSystem, particleSystem);\n\ndefineMain(() => {\n step();\n});\n\nstart();\n\nconst container = document.createElement(\"div\");\ncontainer.style.position = \"fixed\";\ncontainer.style.bottom = \"0\";\ncontainer.style.left = \"0\";\ncontainer.style.padding = \"10px\";\ncontainer.style.display = \"flex\";\ncontainer.style.justifyContent = \"space-between\";\ncontainer.style.alignItems = \"center\";\ndocument.body.appendChild(container);\n\nconst pauseButton = document.createElement(\"button\");\npauseButton.innerText = \"Pause\";\npauseButton.onclick = () => {\n particleSystem.pause();\n};\ncontainer.appendChild(pauseButton);\n\nconst startButton = document.createElement(\"button\");\nstartButton.innerText = \"Start\";\nstartButton.style.marginLeft = \"5px\";\nstartButton.onclick = () => {\n particleSystem.start();\n};\ncontainer.appendChild(startButton);\n\nconst destroyButton = document.createElement(\"button\");\ndestroyButton.innerText = \"Destroy\";\ndestroyButton.style.marginLeft = \"5px\";\ndestroyButton.onclick = () => {\n particleSystem.destroy();\n};\ncontainer.appendChild(destroyButton);\n"], - "mapp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c,MAAM,aAAa;AACjC,cAAc,UAAU,MAAM;AAC5B,iBAAe,QAAQ;AACzB;AACA,UAAU,YAAY,aAAa;", + "sourcesContent": ["/**\n * Generates a sinusoidal pulse between a minimum and maximum value at a specified frequency.\n *\n * @param time - The time variable, typically representing elapsed time.\n * @param freq - The frequency of the pulse in cycles per unit time (default is 1).\n * @param min - The minimum value of the pulse (default is 0).\n * @param max - The maximum value of the pulse (default is 1).\n * @returns The calculated pulse value at the given time.\n */\nexport function pulse(time: number, freq: number = 1, min: number = 0, max: number = 1): number {\n const halfRange = (max - min) / 2;\n return min + halfRange * (1 + Math.sin(2 * Math.PI * freq * time));\n}\n\n/**\n * Performs a linear interpolation between two numbers.\n * @param a The start value.\n * @param b The end value.\n * @param t The interpolation factor (0-1).\n * @returns The interpolated value.\n */\nexport function lerp(a: number, b: number, t: number): number {\n return (1 - t) * a + t * b;\n}\n\n/**\n * Performs spherical linear interpolation between two numbers.\n * @param a The start value.\n * @param b The end value.\n * @param t The interpolation factor, between 0 and 1.\n * @returns The interpolated value.\n */\nexport function slerp(a: number, b: number, t: number): number {\n const theta = Math.acos(Math.min(Math.max(a / b, -1), 1)) * t;\n return a * Math.cos(theta) + b * Math.sin(theta);\n}\n\nexport function extend(component: () => T) {\n return (overrides: Partial): (() => T) => {\n const extendedCompponent = () => ({ ...component(), ...overrides });\n Object.defineProperty(extendedCompponent, \"name\", {\n value: component.name,\n });\n return extendedCompponent;\n };\n}\n", "/*\n This is a mashup of github.com/lukeed/hexoid and github.com/paralleldrive/cuid\n Both are MIT licensed.\n\n ~ https://github.com/paralleldrive/cuid/blob/f507d971a70da224d3eb447ed87ddbeb1b9fd097/LICENSE\n --\n MIT License\n Copyright (c) 2012 Eric Elliott\n Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n ~ https://github.com/lukeed/hexoid/blob/1070447cdc62d1780d2a657b0df64348fc1e5ec5/license\n --\n MIT License\n Copyright (c) Luke Edwards (lukeed.com)\n Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*/\n\nconst HEX: string[] = [];\n\nfor (let i = 0; i < 256; i++) {\n HEX[i] = (i + 256).toString(16).substring(1);\n}\n\nfunction pad(str: string, size: number) {\n const s = \"000000\" + str;\n return s.substring(s.length - size);\n}\n\nconst SHARD_COUNT = 32;\n\nexport function getCreateId(opts: { init: number; len: number }) {\n const len = opts.len || 16;\n let str = \"\";\n let num = 0;\n const discreteValues = 1_679_616; // Math.pow(36, 4)\n let current = opts.init + Math.ceil(discreteValues / 2);\n\n function counter() {\n current = current <= discreteValues ? current : 0;\n current++;\n return (current - 1).toString(16);\n }\n\n return () => {\n if (!str || num === 256) {\n str = \"\";\n num = ((1 + len) / 2) | 0;\n while (num--) str += HEX[(256 * Math.random()) | 0];\n str = str.substring((num = 0), len);\n }\n\n const date = Date.now().toString(36);\n const paddedCounter = pad(counter(), 6);\n const hex = HEX[num++];\n\n const shardKey = parseInt(hex, 16) % SHARD_COUNT;\n\n return `ngn${date}${paddedCounter}${hex}${str}${shardKey}`;\n };\n}\n", "import { getCreateId } from \"./ids\";\n\nconst createId = getCreateId({ init: 0, len: 4 });\n\n/**\n * entity.id -> component.name -> index of component in entity.components\n *\n * This map stores indices of components in the entity component array.\n * The purpose of this map is to allow for fast lookups of components in the\n * entity.components array (e.g. entity.getComponent()).\n */\nexport const $eciMap = Symbol();\n\n/**\n * component.name -> array of entity.ids that have this component\n */\nexport const $ceMap = Symbol();\nexport const $eMap = Symbol();\nexport const $queryResults = Symbol();\nexport const $dirtyQueries = Symbol();\nexport const $queryDependencies = Symbol();\nexport const $systems = Symbol();\nexport const $running = Symbol();\nexport const $onEntityCreated = Symbol();\nexport const $mainLoop = Symbol();\n\nexport type Component = () => {};\nexport type ComponentInstance = () => {\n __ngn__?: {\n parent: string;\n name: string;\n };\n} & {\n [key: string]: any;\n};\n\nexport type QueryConfig = Readonly<\n Partial<{\n /** Matches entities as long as the entity has all of the components in the provided array. */\n and: Component[];\n /** Matches entities as long as the entity has at least one of the components in the provided array. */\n or: Component[];\n /** Matches entities as long as the entity has none of the components in the provided array. */\n not: Component[];\n /** Matches entities that have any of these tag strings. */\n tag: string[];\n }>\n>;\n\nexport type Entity = Readonly<{\n id: string;\n components: ReturnType[];\n addTag: (tag: string) => Entity;\n removeTag: () => Entity;\n getTag: () => string;\n addComponent: (component: Component, defaults?: object) => Entity;\n removeComponent: (component: Component) => Entity;\n getComponent: (arg: T) => ReturnType;\n hasComponent: (component: Component) => boolean;\n destroy: () => void;\n}>;\n\nexport type QueryResults = {\n results: {\n entity: Entity;\n [componentName: string]: any;\n }[];\n};\n\nexport type SystemFn = (w: WorldState) => void;\nexport type SystemCls = { update: (w: WorldState) => void };\nexport type System = SystemCls | SystemFn;\n\nexport type WorldState = {\n [$eciMap]: { [key: number]: { [componentName: string]: number } };\n [$ceMap]: { [key: string]: string[] };\n [$eMap]: { [key: number]: any };\n [$dirtyQueries]: Set;\n [$queryDependencies]: Map>;\n [$queryResults]: { [key: string]: QueryResults };\n [$systems]: ((w: WorldState) => void)[];\n [$mainLoop]: (w: WorldState) => void;\n time: {\n /** The total elapsed time in seconds since the game loop started. */\n elapsed: number;\n /** The time in milliseconds since the last frame. */\n delta: number;\n /** The time in milliseconds since the last time the main loop was called. */\n loopDelta: number;\n /** The time in milliseconds of the last call to the main loop. */\n lastLoopDelta: number;\n /** The time scale of the game loop. */\n scale: number;\n /** The current frames per second. */\n fps: number;\n };\n [$running]: boolean;\n [$onEntityCreated]: ((e: Entity) => void)[];\n};\n\nexport const createWorld = () => {\n const state: WorldState = {\n [$eciMap]: {},\n [$ceMap]: {},\n [$eMap]: {},\n [$dirtyQueries]: new Set(),\n [$queryDependencies]: new Map(),\n [$queryResults]: {},\n [$systems]: [],\n [$mainLoop]: null,\n time: {\n elapsed: 0,\n delta: 0,\n loopDelta: 0,\n lastLoopDelta: 0,\n scale: 1,\n fps: 0,\n },\n [$running]: false,\n [$onEntityCreated]: [],\n };\n\n const defineMain = (callback: (w?: WorldState) => void) => {\n state[$mainLoop] = callback;\n };\n\n /**\n * start - starts the game loop.\n * @returns - a function to stop the loop.\n */\n const start = () => {\n let then = 0;\n let accumulator = 0;\n const boundLoop = handler.bind(start);\n let loopHandler = -1;\n const { time } = state;\n time.delta = 0;\n time.elapsed = 0;\n time.fps = 0;\n state[$running] = true;\n\n let raf: ((cb: FrameRequestCallback) => number) | null = null;\n let craf: ((handle: number) => void) | null = null;\n\n /**\n * Fake requestAnimationFrame and cancelAnimationFrame\n * so that we can run tests for this in node.\n */\n if (typeof window !== \"undefined\") {\n let now = performance.now();\n raf = (cb: FrameRequestCallback): number => {\n return requestAnimationFrame((timestamp: number) => {\n now = timestamp;\n cb(now);\n });\n };\n craf = cancelAnimationFrame;\n } else {\n let now = 0;\n raf = (cb: FrameRequestCallback): number => {\n return setTimeout(() => {\n now += 16.67;\n cb(now);\n }, 16.67) as unknown as number;\n };\n\n craf = (id: number) => {\n clearTimeout(id);\n };\n }\n\n let xfps = 1;\n const xtimes = [];\n\n function handler(now: number) {\n if (!state[$running]) return craf(loopHandler);\n\n while (xtimes.length > 0 && xtimes[0] <= now - 1000) {\n xtimes.shift();\n }\n\n xtimes.push(now);\n xfps = xtimes.length;\n time.fps = xfps;\n\n time.delta = now - then;\n then = now;\n\n accumulator += time.delta * time.scale;\n\n // Calculate the threshold for stepping the world based on the current frame rate\n const stepThreshold = 1000 / (time.fps || 60);\n\n // Step the world only when the accumulated scaled time exceeds the threshold\n while (accumulator >= stepThreshold) {\n time.loopDelta = now - time.lastLoopDelta;\n time.lastLoopDelta = now;\n\n state[$mainLoop](state);\n accumulator -= stepThreshold;\n }\n\n time.elapsed += time.delta * 0.001;\n\n loopHandler = raf(boundLoop);\n }\n\n loopHandler = raf(boundLoop);\n\n return () => (state[$running] = false);\n };\n\n const stop = () => {\n state[$running] = false;\n };\n\n function step() {\n for (const system of state[$systems]) {\n if (system(state) === null) {\n break;\n }\n }\n }\n\n /**\n * Adds one or more systems to the ECS world.\n * A system can be either a @see SystemFn or a @see SystemCls.\n * @param systems An array of system classes or functions.\n * @throws {Error} If a system is not a valid system class or function.\n */\n function addSystem(...systems: (SystemCls | SystemFn)[]) {\n for (const system of systems) {\n // If the system is a function, add it to the world systems array\n if (typeof system === \"function\") {\n state[$systems].push(system);\n // If the system has an `update` method, add that method to the world systems array\n } else if (system.update && typeof system.update === \"function\") {\n state[$systems].push(system.update);\n // If the system is not a valid system class or function, throw an error\n } else {\n throw new Error(`Not a valid system: ${JSON.stringify(system)}`);\n }\n }\n }\n\n /**\n * Removes one or more systems from the world.\n *\n * @param {...(SystemCls | SystemFn)[]} systems - The system or systems to remove.\n * @throws {TypeError} Throws an error if the system parameter is not a function or an object with an update function.\n * @returns {void}\n */\n function removeSystem(...systems: (SystemCls | SystemFn)[]): void {\n for (const system of systems) {\n if (typeof system === \"function\") {\n state[$systems] = state[$systems].filter((s) => s !== system);\n } else if (system.update && typeof system.update === \"function\") {\n state[$systems] = state[$systems].filter((s) => s !== system.update);\n } else {\n throw new TypeError(\"Parameter must be a function or an object with an update function.\");\n }\n }\n }\n\n /**\n * Retrieves query results based on the given configuration and query name.\n * If non-dirty query results exist for this queryName, returns them. Otherwise, filters entities based on the queryConfig\n * and updates the state with the new query results before returning them.\n *\n * @param {QueryConfig} queryConfig - The configuration object containing 'and', 'or', 'not' and 'tag' arrays of component names.\n * @param {string} queryName - The name of the query to retrieve or update results for.\n * @returns {any[]} An array of result objects, each containing an entity and its components as properties.\n */\n const getQuery = (queryConfig: QueryConfig, queryName: string): any[] => {\n // If we have non-dirty query results for this queryName, return them\n if (!state[$dirtyQueries].has(queryName) && state[$queryResults][queryName]) {\n return state[$queryResults][queryName].results;\n }\n\n const { and = [], or = [], not = [], tag = [] } = queryConfig;\n const entities: Entity[] = Object.values(state[$eMap]).filter((entity) => {\n return (\n (!not.length || !not.some((component) => entity.hasComponent(component))) &&\n (!and.length || and.every((component) => entity.hasComponent(component))) &&\n (!or.length || or.some((component) => entity.hasComponent(component))) &&\n (!tag.length || tag.some((t) => entity.tag === t))\n );\n });\n\n state[$queryResults][queryName] = {\n results: entities.map((entity) => {\n const result: any = { entity };\n\n entity.components.forEach((component) => {\n result[component.__ngn__.name] = component;\n });\n\n return result;\n }),\n };\n\n state[$dirtyQueries].delete(queryName);\n\n return state[$queryResults][queryName].results;\n };\n\n const markQueryDirty = (queryName: string) => {\n state[$dirtyQueries].add(queryName);\n };\n\n /**\n * Defines a query for filtering entities based on a combination of criteria.\n * @param queryConfig The configuration for the query. Contains and, or, not and tag criteria.\n * @throws {Error} Invalid query if any criteria in the query config does not have a 'name' property.\n * @returns A function that takes a query implementation and returns the results of the query.\n */\n const query = ({ and = [], or = [], not = [], tag = [] }: QueryConfig) => {\n // Checks if a criteria object has a 'name' property\n const validQuery = (c: Component) => Object.prototype.hasOwnProperty.call(c, \"name\");\n\n // Throws an error if any criteria object in the query config does not have a 'name' property\n if (![...and, ...or, ...not].every(validQuery)) throw new Error(\"Invalid query\");\n\n // Constructs a string representing the query name based on the criteria in the query config\n const queryName = [\"and\", ...and.map((c) => c.name), \"or\", ...or.map((c) => c.name), \"not\", ...not.map((c) => c.name), \"tag\", ...tag].join(\"\");\n\n // Component dependencies\n [...and, ...or, ...not].forEach((c) => {\n const dependencies = state[$queryDependencies].get(c.name) || new Set();\n dependencies.add(queryName);\n state[$queryDependencies].set(c.name, dependencies);\n });\n\n // Tag dependencies\n tag.forEach((t) => {\n const tagKey = `tag:${t}`;\n const dependencies = state[$queryDependencies].get(tagKey) || new Set();\n dependencies.add(queryName);\n state[$queryDependencies].set(tagKey, dependencies);\n });\n\n return (queryImpl: (results: { entity: Entity }[]) => void) => queryImpl(getQuery({ and, or, not, tag }, queryName));\n };\n\n function destroyEntity(e: Entity) {\n const exists = state[$eMap][e.id];\n\n if (!exists) return false;\n\n const componentsToRemove: string[] = Object.keys(state[$eciMap][e.id]);\n\n componentsToRemove.forEach((componentName) => {\n state[$ceMap][componentName] = state[$ceMap][componentName].filter((id) => id !== e.id);\n });\n\n delete state[$eciMap][e.id];\n delete state[$eMap][e.id];\n\n componentsToRemove.forEach((componentName) => {\n const affectedQueries = state[$queryDependencies].get(componentName);\n\n if (affectedQueries) {\n affectedQueries.forEach(markQueryDirty);\n }\n });\n\n return true;\n }\n\n function onEntityCreated(fn: any) {\n if (typeof fn !== \"function\") return;\n\n state[$onEntityCreated].push(fn);\n\n return () => {\n state[$onEntityCreated] = state[$onEntityCreated].filter((f) => f !== fn);\n };\n }\n\n /**\n * Creates a new component for the given entity and adds it to the world.\n * @param entity The entity to add the component to.\n * @param component The component function to add.\n * @param defaults (optional) Default values to apply to the component.\n * @returns The modified entity with the new component added.\n */\n function createComponent(entity: Entity, component: Function, defaults: object = {}): Entity {\n // If the entity already has this component, return the unmodified entity.\n if (state[$eciMap]?.[entity.id]?.[component.name] !== undefined) return entity;\n\n const affectedQueries = state[$queryDependencies].get(component.name);\n\n if (affectedQueries) {\n affectedQueries.forEach(markQueryDirty);\n }\n\n const componentInstance = component();\n\n if (componentInstance.onAttach && typeof componentInstance.onAttach === \"function\") {\n componentInstance.onAttach(entity);\n }\n\n // Create the component, assigning defaults and a reference to the parent entity.\n entity.components.push(\n Object.assign(\n {},\n {\n ...componentInstance,\n ...defaults,\n __ngn__: {\n parent: entity.id,\n name: component.name,\n },\n },\n ) as ComponentInstance,\n );\n\n // Add the component index to the entity's index map.\n state[$eciMap][entity.id] = state[$eciMap][entity.id] || {};\n state[$eciMap][entity.id][component.name] = entity.components.length - 1;\n\n // Add the entity to the component's entity map.\n state[$ceMap][component.name] = state[$ceMap][component.name] || [];\n state[$ceMap][component.name].push(entity.id);\n\n return entity;\n }\n\n /**\n * Creates an entity with the given specification object.\n * @param {object} spec - Optional data to be stored on the entity.\n * @returns {any} - Returns the created entity.\n */\n function createEntity(spec: T & { id?: string } = {} as T): T & Entity {\n const id = spec.id ?? createId();\n const components: any[] = [];\n\n const tagKey = (t: string) => `tag:${t}`;\n\n function updateTagQueries(tagKey: string) {\n const affectedQueries = state[$queryDependencies].get(tagKey);\n\n if (affectedQueries) {\n affectedQueries.forEach(markQueryDirty);\n }\n }\n\n function addTag(t: string): Entity {\n const previousTagKey = tagKey(this.tag);\n\n this.tag = t;\n\n updateTagQueries(tagKey(t));\n updateTagQueries(previousTagKey);\n\n return this;\n }\n\n function removeTag(): Entity {\n const previousTagKey = tagKey(this.tag);\n this.tag = \"\";\n\n updateTagQueries(previousTagKey);\n\n return this;\n }\n\n function getTag() {\n return this.tag;\n }\n\n function addComponent(c: Component, defaults = {}) {\n return createComponent(this, c, defaults);\n }\n\n function hasComponent(component: Component) {\n return state[$eciMap]?.[id]?.[component.name] !== undefined;\n }\n\n function getComponent(arg: T): ReturnType {\n const index = state[$eciMap][id][arg.name];\n return components[index];\n }\n\n /**\n * Removes the specified component from the entity and updates the world state accordingly.\n *\n * @param component The component to remove from the entity.\n * @returns The modified entity.\n */\n function removeComponent(component: Component | string): Entity {\n const name = typeof component === \"string\" ? component : component.name;\n\n const componentInstance = getComponent(typeof component === \"string\" ? ({ name } as any) : component);\n\n if (componentInstance && componentInstance.onDetach && typeof componentInstance.onDetach === \"function\") {\n componentInstance.onDetach(this);\n }\n\n const affectedQueries = state[$queryDependencies].get(name);\n\n if (affectedQueries) {\n affectedQueries.forEach(markQueryDirty);\n }\n\n // Set the entity's component index for the specified component to undefined.\n state[$eciMap][id][name] = undefined;\n\n // Remove the entity's ID from the component's entity list.\n state[$ceMap][name] = state[$ceMap][name].filter((e) => e !== id);\n\n // Remove the component from the entity's component list.\n const index = state[$eciMap][id][name];\n components.splice(index, 1);\n\n // Update the entity's component indices for all components after the removed component.\n Object.keys(state[$eciMap][id]).forEach((componentName) => {\n if (state[$eciMap][id][componentName] > components.findIndex((c) => c.name === componentName)) {\n state[$eciMap][id][componentName]--;\n }\n });\n\n // Return the modified entity.\n return this;\n }\n\n function destroy() {\n return destroyEntity(this);\n }\n\n const entity = Object.assign({}, spec, {\n id,\n components,\n addTag,\n removeTag,\n getTag,\n addComponent,\n hasComponent,\n getComponent,\n removeComponent,\n destroy,\n });\n\n // If we are focing a specific entity id, we need to migrate any\n // entity that might already occupy this space.\n if (spec.id !== undefined && state[$eMap][spec.id]) {\n migrateEntityId(spec.id, createId());\n }\n\n state[$eMap][id] = entity;\n state[$eciMap][id] = {};\n\n state[$onEntityCreated].forEach((fn) => {\n fn(entity);\n });\n\n return entity as unknown as T & Entity;\n }\n\n /**\n * migrateEntityId updates the id of an entity in the world, and all\n * associated world maps.\n * @param oldId The id of the entity to migrate.\n * @param newId The id to migrate the entity to.\n */\n function migrateEntityId(oldId: string, newId: string) {\n const entity = state[$eMap][oldId];\n\n if (!entity) return;\n\n entity.id = newId;\n\n state[$eMap][newId] = entity;\n delete state[$eMap][oldId];\n\n state[$eciMap][newId] = state[$eciMap][oldId];\n delete state[$eciMap][oldId];\n }\n\n function getEntity(id: string): Entity {\n return state[$eMap][id];\n }\n\n return {\n state,\n query,\n createEntity,\n getEntity,\n onEntityCreated,\n addSystem,\n removeSystem,\n start,\n stop,\n step,\n defineMain,\n };\n};\n", "export type CreateCanvasOptions = Partial<{\n width: number;\n height: number;\n fullscreen: boolean;\n target: HTMLElement;\n}>;\n\nexport const createCanvas = (options: CreateCanvasOptions) => {\n const canvas = document.createElement(\"canvas\");\n const { target, fullscreen } = options;\n const { body } = window.document;\n\n if (target && fullscreen) {\n options.target = null;\n } else if (!target && !fullscreen) {\n options.fullscreen = true;\n }\n\n if (fullscreen) {\n Object.assign(canvas.style, {\n position: \"absolute\",\n top: \"0\",\n left: \"0\",\n });\n canvas.width = window.innerWidth;\n canvas.height = window.innerHeight;\n body.appendChild(canvas);\n Object.assign(body.style, {\n margin: \"0\",\n padding: \"0\",\n width: \"100%\",\n height: \"100%\",\n overflow: \"hidden\",\n });\n }\n\n if (target) {\n target.appendChild(canvas);\n target.style.overflow = \"hidden\";\n canvas.width = canvas.offsetWidth;\n canvas.height = canvas.offsetHeight;\n }\n\n canvas.width = canvas.offsetWidth;\n canvas.height = canvas.offsetHeight;\n canvas.style.width = \"100%\";\n canvas.style.height = \"100%\";\n\n const existingMeta = window.document.querySelector(`meta[name=\"viewport\"]`);\n if (existingMeta) {\n Object.assign(existingMeta, {\n content: \"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0\",\n });\n } else {\n const meta = Object.assign(window.document.createElement(\"meta\"), {\n name: \"viewport\",\n content: \"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0\",\n });\n window.document.head.appendChild(meta);\n }\n\n return canvas;\n};\n", "export type Vector2 = {\n x: number;\n y: number;\n};\n\nconst fastRound = (num: number): number => ~~(0.5 + num);\n\nconst fastRoundVector2 = (v: Vector2): Vector2 => ({\n x: fastRound(v.x),\n y: fastRound(v.y),\n});\n\nexport const createDraw = (context: CanvasRenderingContext2D) => {\n const text = (v: Vector2, text: string, color: string = \"black\", size: number = 16) => {\n v = fastRoundVector2(v);\n context.save();\n context.fillStyle = color;\n context.font = `${size}px sans-serif`;\n context.fillText(text, v.x, v.y);\n context.restore();\n };\n\n const line = (from: Vector2, to: Vector2, color: string = \"black\", lineWidth: number = 1) => {\n from = fastRoundVector2(from);\n to = fastRoundVector2(to);\n context.save();\n context.beginPath();\n context.moveTo(from.x, from.y);\n context.lineTo(to.x, to.y);\n context.strokeStyle = color; // Use the color parameter\n context.lineWidth = lineWidth;\n context.stroke();\n context.closePath();\n context.restore();\n };\n\n const rectangle = (pos: Vector2, dimensions: Vector2, color: string = \"black\", lineWidth: number = 1) => {\n pos = fastRoundVector2(pos);\n dimensions = fastRoundVector2(dimensions);\n context.save();\n context.beginPath();\n context.rect(pos.x, pos.y, dimensions.x, dimensions.y);\n context.lineWidth = lineWidth;\n context.strokeStyle = color;\n context.stroke();\n context.closePath();\n context.restore();\n };\n\n const circle = (pos: Vector2, radius: number = 25, color: string = \"black\", lineWidth: number = 1) => {\n pos = fastRoundVector2(pos);\n context.save();\n context.beginPath();\n context.strokeStyle = color;\n context.lineWidth = lineWidth;\n context.arc(pos.x, pos.y, radius, 0, Math.PI * 2, true);\n context.stroke();\n context.closePath();\n context.restore();\n };\n\n return {\n text,\n line,\n rectangle,\n circle,\n };\n};\n", "import { createCanvas, CreateCanvasOptions } from \"./canvas\";\nimport { createDraw } from \"./draw\";\n\ntype Create2DOptions = Partial<{\n canvas: CreateCanvasOptions;\n}>;\n\nexport const create2D = (options: Create2DOptions) => {\n const { width = 800, height = 600, fullscreen = false, target = null } = options.canvas;\n const canvas = createCanvas({ width, height, fullscreen, target });\n const context = canvas.getContext(\"2d\");\n const draw = createDraw(context);\n\n const onWindowResize = () => {\n if (fullscreen) {\n canvas.style.width = \"100%\";\n canvas.style.height = \"100%\";\n canvas.width = window.innerWidth;\n canvas.height = window.innerHeight;\n return;\n }\n\n canvas.width = canvas.offsetWidth;\n canvas.height = canvas.offsetHeight;\n };\n\n window.addEventListener(\"resize\", onWindowResize);\n\n const destroy = () => {\n window.removeEventListener(\"resize\", onWindowResize);\n canvas.parentElement.removeChild(canvas);\n };\n\n return { canvas, context, draw, destroy };\n};\n", "import { WorldState } from \"../../ngn\";\n\nexport type Particle = {\n x: number;\n y: number;\n size: number;\n color: string;\n colorStart: string;\n colorEnd: string;\n lifetime: number;\n speedX: number;\n speedY: number;\n scaleX: number;\n scaleY: number;\n onInit?: (particle: Particle, state: WorldState) => void;\n onRemove?: (particle: Particle, state: WorldState) => void;\n onUpdate?: (particle: Particle, state: WorldState) => void;\n};\n\nexport enum ColorEasing {\n LINEAR = \"linear\",\n EASE_IN = \"easeIn\",\n EASE_OUT = \"easeOut\",\n EASE_IN_OUT = \"easeInOut\",\n}\n\nexport type FadeEasing = ColorEasing;\n\ntype BlendMode =\n | \"color\"\n | \"color-burn\"\n | \"color-dodge\"\n | \"copy\"\n | \"darken\"\n | \"destination-atop\"\n | \"destination-in\"\n | \"destination-out\"\n | \"destination-over\"\n | \"difference\"\n | \"exclusion\"\n | \"hard-light\"\n | \"hue\"\n | \"lighten\"\n | \"lighter\"\n | \"luminosity\"\n | \"multiply\"\n | \"overlay\"\n | \"saturation\"\n | \"screen\"\n | \"soft-light\"\n | \"source-atop\"\n | \"source-in\"\n | \"source-out\"\n | \"source-over\"\n | \"xor\";\n\nexport type ParticleEmitterOptions = {\n /** \n * The x coordinate for new particles. \n * Default is 0. \n * Determines the horizontal start position of particle emission. Can be changed at any time.\n */\n x?: number;\n \n /** \n * The y coordinate for new particles. \n * Default is 0. \n * Determines the vertical start position of particle emission. Can be changed at any time.\n */\n y?: number;\n \n /** \n * Maximum number of particles that can exist at one time. \n * Default is 100. \n * Helps manage performance by capping particle count.\n */\n maxParticles?: number;\n \n /** \n * Number of particles emitted per millisecond interval.\n * Default is 1. \n * Controls the frequency of particle emission in relation to time.\n */\n rate?: number;\n \n /** \n * Lifetime of each particle in milliseconds. \n * Default is 1000 (1 second). \n * Determines how long a particle will exist before disappearing.\n */\n lifetime?: number;\n \n /** \n * Variation in particle lifetime as a fraction of `lifetime`. \n * Provide a value between 0 and 1. \n * Default is 0. \n * Allows particles to have different lifetimes, adding randomness.\n */\n lifetimeVariation?: number;\n \n /** \n * Base size of each particle. \n * Default is 5. \n * Represents the default size/scale factor for particles.\n */\n size?: number;\n \n /** \n * Variation in size as a fraction of `size`. \n * Provide a value between 0 and 1. \n * Default is 0.\n * Introduces variability to particle sizes.\n */\n sizeVariation?: number;\n \n /** \n * Initial color or array of possible initial colors for particles in hexadecimal format. \n * Default is \"#000000\". \n * Specifies the starting color of particles.\n */\n colorStart?: string | string[];\n \n /** \n * Final color or array of possible end colors for particles in hexadecimal format. \n * Default is \"#000000\". \n * Specifies the color particles will transition to over their lifetime.\n */\n colorEnd?: string | string[];\n \n /** \n * Easing function to interpolate between `colorStart` and `colorEnd`. \n * Default is `ColorEasing.LINEAR`.\n * Determines how the color changes over the particle's lifetime.\n */\n colorEasing?: ColorEasing;\n \n /** \n * Easing function for fade out effect.\n * Default is `ColorEasing.LINEAR`.\n * Controls opacity transition as particles disappear.\n */\n fadeOutEasing?: FadeEasing;\n \n /** \n * Base speed of particle movement in pixels per millisecond. \n * Default is 0.1. \n * Determines how fast particles move from their origin.\n */\n speed?: number;\n \n /** \n * Variation in speed as a fraction of `speed`. \n * Provide a value between 0 and 1. \n * Default is 0. \n * Introduces speed variability amongst particles.\n */\n speedVariation?: number;\n \n /** \n * Emission angle in degrees. \n * Default is 0. \n * Sets the direction of initial particle movement.\n */\n angle?: number;\n \n /** \n * Spread angle in degrees around the emission angle for particle dispersion. \n * Default is 0. \n * Widens the field of initial particle directions.\n */\n spread?: number;\n \n /** \n * Gravity effect on particles as x and y components. \n * Default is {x: 0, y: 0}. \n * It simulates gravitational forces affecting particle trajectories.\n */\n gravity?: { x: number; y: number };\n \n /** \n * Blend mode used for particle rendering. \n * Default is the canvas context\u2019s \"source-over\". \n * Determines how particles blend with the background/canvas.\n */\n blendMode?: BlendMode;\n \n /** \n * HTMLCanvasElement on which particles are drawn. \n * Required parameter.\n * Represents the rendering surface for the particle system.\n */\n canvas: HTMLCanvasElement;\n \n /** \n * If true, emit all particles at once and then stop. \n * Default is false. \n * Changes emitter behavior from continuous to singular burst.\n */\n burst?: boolean;\n \n /** \n * Callback invoked on each particle initialization. \n * Default is undefined. \n * Useful for setting initial particle properties dynamically.\n */\n onInit?: (particle: Particle, state: WorldState) => void;\n \n /** \n * Callback for code execution every frame as each particle updates. \n * Default is undefined. \n * Allows interaction or modification of particles per update loop.\n */\n onUpdate?: (particle: Particle, state: WorldState) => void;\n \n /** \n * Callback invoked when a particle is removed. \n * Default is undefined. \n * Useful for cleanup or concluding actions when particles disappear.\n */\n onRemove?: (particle: Particle, state: WorldState) => void;\n};\n\nconst getDefaultParticleEmitterOptions = (opts: Partial): ParticleEmitterOptions => ({\n ...opts,\n x: opts.x ?? 0,\n y: opts.y ?? 0,\n maxParticles: opts.maxParticles ?? 100,\n rate: opts.rate ?? 1,\n lifetime: opts.lifetime ?? 1000,\n lifetimeVariation: opts.lifetimeVariation ?? 0,\n size: opts.size ?? 5,\n sizeVariation: opts.sizeVariation ?? 0,\n colorStart: opts.colorStart ?? \"#000000\",\n colorEnd: opts.colorEnd ?? \"#000000\",\n colorEasing: opts.colorEasing ?? ColorEasing.LINEAR,\n angle: opts.angle ?? 0,\n spread: opts.spread ?? 0,\n gravity: opts.gravity ?? { x: 0, y: 0 },\n speed: opts.speed ?? 0.1,\n speedVariation: opts.speedVariation ?? 0,\n canvas: opts.canvas,\n burst: opts.burst ?? false,\n});\n\nexport type ParticleEmitter = {\n particles: Particle[];\n update: (state: WorldState) => void;\n destroy: () => void;\n pause: () => void;\n resume: () => void;\n x: number;\n y: number;\n};\n\nexport type ParticleSystemOptions = {\n x: number;\n y: number;\n canvas: HTMLCanvasElement;\n // A property to determine whether or not it starts immediately\n start?: boolean;\n};\n\nconst interpolateColor = (colorStart: string, colorEnd: string, factor: number, easing: ColorEasing): string => {\n switch (easing) {\n case ColorEasing.EASE_IN:\n factor = Math.pow(factor, 2);\n break;\n case ColorEasing.EASE_OUT:\n factor = 1 - Math.pow(1 - factor, 2);\n break;\n case ColorEasing.EASE_IN_OUT:\n if (factor < 0.5) {\n factor = 2 * Math.pow(factor, 2);\n } else {\n factor = 1 - 2 * Math.pow(1 - factor, 2);\n }\n break;\n case ColorEasing.LINEAR:\n default:\n // No adjustment needed for linear\n break;\n }\n\n // Assuming colorStart and colorEnd are in the format \"#RRGGBB\"\n const color1 = parseInt(colorStart.slice(1), 16);\n const color2 = parseInt(colorEnd.slice(1), 16);\n\n const r1 = (color1 >> 16) & 0xff;\n const g1 = (color1 >> 8) & 0xff;\n const b1 = color1 & 0xff;\n\n const r2 = (color2 >> 16) & 0xff;\n const g2 = (color2 >> 8) & 0xff;\n const b2 = color2 & 0xff;\n\n const r = Math.round(r1 + factor * (r2 - r1));\n const g = Math.round(g1 + factor * (g2 - g1));\n const b = Math.round(b1 + factor * (b2 - b1));\n\n return `#${((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)}`;\n};\n\nconst hexToRgb = (hex: string): string => {\n const color = parseInt(hex.slice(1), 16);\n const r = (color >> 16) & 0xff;\n const g = (color >> 8) & 0xff;\n const b = color & 0xff;\n return `${r}, ${g}, ${b}`;\n};\n\nexport const createParticleEmitter = (opts: ParticleEmitterOptions): ParticleEmitter => {\n opts = getDefaultParticleEmitterOptions(opts);\n const particles = [];\n let timeSinceLastEmission = 0;\n const emissionInterval = 1 / opts.rate;\n const lifetimeVariation = opts.lifetimeVariation ?? 0;\n const context = opts.canvas.getContext(\"2d\");\n const angleInRadians = opts.angle * (Math.PI / 180);\n let dead = false;\n let paused = false;\n\n const update = (state: WorldState) => {\n if (dead) return;\n\n context.globalCompositeOperation = opts.blendMode ?? \"source-over\";\n\n const { loopDelta } = state.time;\n\n for (let i = particles.length - 1; i >= 0; i--) {\n const particle = particles[i];\n const lifeFactor = particle.lifetime / opts.lifetime;\n let opacity = 1;\n\n particle.color = interpolateColor(particle.colorStart, particle.colorEnd, 1 - lifeFactor, opts.colorEasing);\n\n if (opts.fadeOutEasing) {\n switch (opts.fadeOutEasing) {\n case ColorEasing.EASE_IN:\n opacity = Math.pow(lifeFactor, 2);\n break;\n case ColorEasing.EASE_OUT:\n opacity = 1 - Math.pow(1 - lifeFactor, 2);\n break;\n case ColorEasing.EASE_IN_OUT:\n if (lifeFactor < 0.5) {\n opacity = 2 * Math.pow(lifeFactor, 2);\n } else {\n opacity = 1 - 2 * Math.pow(1 - lifeFactor, 2);\n }\n break;\n case ColorEasing.LINEAR:\n default:\n opacity = lifeFactor;\n break;\n }\n }\n\n if (!paused) {\n particle.x += particle.speedX * loopDelta;\n particle.y += particle.speedY * loopDelta;\n\n particle.speedX += (opts.gravity.x * loopDelta) / 1000;\n particle.speedY += (opts.gravity.y * loopDelta) / 1000;\n\n particle.lifetime -= state.time.loopDelta;\n\n if (opts.onUpdate) {\n opts.onUpdate(particle, state);\n }\n\n if (particle.onUpdate) {\n particle.onUpdate(particle, state);\n }\n }\n\n if (particle.lifetime <= 0) {\n if (opts.onRemove) {\n opts.onRemove(particle, state);\n }\n\n if (particle.onRemove) {\n particle.onRemove(particle, state);\n }\n\n particles.splice(i, 1);\n } else {\n context.fillStyle = `rgba(${hexToRgb(particle.color)}, ${opacity})`;\n context.beginPath();\n // context.arc(particle.x * particle.scaleX, particle.y * particle.scaleY, particle.size, 0, Math.PI * 2);\n // draw a rectangel instead:\n context.rect(particle.x * particle.scaleX, particle.y * particle.scaleY, particle.size, particle.size);\n context.closePath();\n context.fill();\n }\n }\n\n const emitParticle = () => {\n const lifetimeVariationAmount = lifetimeVariation ? opts.lifetime * lifetimeVariation * Math.random() : 0;\n const particleLifetime = opts.lifetime + lifetimeVariationAmount * (Math.random() < 0.5 ? -1 : 1);\n const colorStart = Array.isArray(opts.colorStart) ? opts.colorStart[Math.floor(Math.random() * opts.colorStart.length)] : opts.colorStart;\n const colorEnd = Array.isArray(opts.colorEnd) ? opts.colorEnd[Math.floor(Math.random() * opts.colorEnd.length)] : opts.colorEnd;\n const particle = spawnParticle({\n x: opts.x,\n y: opts.y,\n colorStart: colorStart,\n colorEnd: colorEnd,\n color: colorStart,\n lifetime: particleLifetime,\n size: Math.max(0, opts.size + (Math.random() - 0.5) * opts.sizeVariation),\n speedX: opts.speed * (Math.sin(angleInRadians) + (Math.random() - 0.5) * opts.spread),\n speedY: -opts.speed * (Math.cos(angleInRadians) + (Math.random() - 0.5) * opts.spread),\n scaleX: 1,\n scaleY: 1,\n });\n\n if (opts.onInit) {\n opts.onInit(particle, state);\n }\n\n if (particle.onInit) {\n particle.onInit(particle, state);\n }\n };\n\n if (!paused) {\n if (opts.burst && timeSinceLastEmission === 0) {\n for (let i = 0; i < opts.maxParticles; i++) {\n emitParticle();\n }\n\n timeSinceLastEmission = -1;\n } else if (!opts.burst) {\n timeSinceLastEmission += loopDelta;\n\n while (timeSinceLastEmission >= emissionInterval && particles.length < opts.maxParticles) {\n emitParticle();\n timeSinceLastEmission -= emissionInterval;\n }\n }\n }\n\n if (opts.burst && particles.length === 0) {\n destroy();\n }\n\n // context.globalCompositeOperation = \"source-over\";\n };\n\n const destroy = () => {\n dead = true;\n particles.length = 0;\n return;\n };\n\n const spawnParticle = (p: Particle): Particle => {\n particles.push(p);\n return p;\n };\n\n const pause = () => {\n paused = true;\n };\n\n const resume = () => {\n paused = false;\n };\n\n document.addEventListener(\"visibilitychange\", () => {\n if (document.visibilityState === \"visible\") {\n resume();\n } else {\n pause();\n }\n });\n\n return {\n particles,\n update,\n destroy,\n pause,\n resume,\n set x(value: number) {\n opts.x = value;\n },\n get x() {\n return opts.x;\n },\n set y(value: number) {\n opts.y = value;\n },\n get y() {\n return opts.y;\n },\n };\n};\n\nexport const createParticleSystem = (opts: ParticleSystemOptions) => {\n let _x = opts.x;\n let _y = opts.y;\n const emitters: ParticleEmitter[] = [];\n const startImmediately = opts.start ?? true;\n\n const update = (state: WorldState) => {\n emitters.forEach((emitter) => {\n emitter.update(state);\n });\n };\n\n const destroy = () => {\n emitters.forEach((emitter) => {\n emitter.destroy();\n });\n };\n\n const createEmitter = (opts: ParticleEmitterOptions): ParticleEmitter => {\n const emitter = createParticleEmitter({\n ...opts,\n /* x: _x, */\n /* y: _y, */\n });\n emitters.push(emitter);\n\n if (!startImmediately) {\n emitter.pause();\n }\n\n return emitter;\n };\n\n const pause = () => {\n emitters.forEach((emitter) => {\n emitter.pause();\n });\n };\n\n const start = () => {\n emitters.forEach((emitter) => {\n emitter.resume();\n });\n };\n\n return {\n update,\n destroy,\n createEmitter,\n pause,\n start,\n set x(value: number) {\n _x = value;\n },\n get x() {\n return _x;\n },\n set y(value: number) {\n _y = value;\n },\n get y() {\n return _y;\n },\n get numParticles() {\n return emitters.reduce((acc, emitter) => acc + emitter.particles.length, 0);\n },\n };\n};\n", "import { pulse } from \"./misc\";\nimport { createWorld, type WorldState } from \"./ngn\";\nimport { create2D } from \"./packages/2d\";\nimport { ColorEasing, createParticleSystem, Particle } from \"./packages/emitter\";\n\nconst { canvas, draw } = create2D({ canvas: { fullscreen: true } });\n\nconst particleSystem = createParticleSystem({\n x: canvas.width / 2,\n y: canvas.height / 2,\n canvas,\n});\n\nconst emitter = particleSystem.createEmitter({\n x: canvas.width / 2,\n y: canvas.height / 2,\n maxParticles: 120,\n rate: 0.1,\n lifetime: 1000,\n lifetimeVariation: 0.2,\n size: 20,\n sizeVariation: 10,\n colorStart: [\"#FF0000\", \"#ff5100\"],\n colorEnd: \"#222222\",\n colorEasing: ColorEasing.EASE_IN,\n fadeOutEasing: ColorEasing.EASE_OUT,\n speed: 0.1,\n speedVariation: 1,\n angle: 0,\n spread: 0.75,\n gravity: { x: 0, y: 0 },\n canvas,\n burst: false,\n\n onInit: (particle: Particle, state: WorldState) => {\n particle.x += Math.random() < 0.5 ? -6 : 6;\n particle.y += Math.random() < 0.5 ? -6 : 6;\n\n if (!(Math.random() < 0.02)) {\n return;\n }\n\n particle.size = 15;\n particle.speedY = -0.3;\n particle.lifetime = 1000;\n particle.colorEnd = \"#ff0000\";\n\n particle.onRemove = () => {\n particleSystem.createEmitter({\n x: particle.x,\n y: particle.y,\n maxParticles: 4,\n lifetimeVariation: 0.5,\n size: 3,\n sizeVariation: 2,\n colorStart: [\"#FF0000\", \"#ff5100\"],\n colorEnd: \"#222222\",\n colorEasing: ColorEasing.EASE_IN,\n fadeOutEasing: ColorEasing.EASE_OUT,\n speed: 0.02,\n speedVariation: 1,\n spread: 6,\n angle: 180,\n canvas,\n burst: true,\n });\n };\n\n particle.onUpdate = () => {\n particle.size = Math.max(0, particle.size + 0.25);\n };\n },\n onUpdate: (particle: Particle, state: WorldState) => {\n particle.size = Math.max(0, particle.size - 0.35);\n // const v = pulse(state.time.elapsed, 0.25, -1, 1);\n // particle.x += v * 1;\n },\n onRemove: (particle: Particle, state: WorldState) => {},\n});\n\nconst { addSystem, start, step, defineMain } = createWorld();\n\nconst clearCanvasSystem = () => {\n const context = canvas.getContext(\"2d\");\n context.clearRect(0, 0, canvas.width, canvas.height);\n\n context.fillStyle = \"#111\";\n context.fillRect(0, 0, canvas.width, canvas.height);\n};\n\nconst fpsDrawSystem = (state: WorldState) => {\n draw.text({ x: 10, y: 20 }, `FPS: ${state.time.fps.toFixed(2)}`, \"white\");\n};\n\nconst particleCountSystem = (state: WorldState) => {\n draw.text({ x: 10, y: 40 }, `Particle count: ${particleSystem.numParticles}. Emitter count: ${emitter.particles.length}`, \"white\");\n};\n\nconst particlePositionSystem = (state: WorldState) => {\n const { time } = state;\n const xPos = pulse(time.elapsed, 0.25, canvas.width / 2 - 100, canvas.width / 2 + 100);\n // const yPos = pulse(time.elapsed, 0.25, canvas.height / 2 - 100, canvas.height / 2 + 100);\n emitter.x = xPos;\n // emitter.y = yPos;\n};\n\naddSystem(\n clearCanvasSystem,\n fpsDrawSystem,\n particleCountSystem,\n particlePositionSystem,\n particleSystem,\n);\n\ndefineMain(() => {\n step();\n});\n\nstart();\n\nconst container = document.createElement(\"div\");\ncontainer.style.position = \"fixed\";\ncontainer.style.bottom = \"0\";\ncontainer.style.left = \"0\";\ncontainer.style.padding = \"10px\";\ncontainer.style.display = \"flex\";\ncontainer.style.justifyContent = \"space-between\";\ncontainer.style.alignItems = \"center\";\ndocument.body.appendChild(container);\n\nconst pauseButton = document.createElement(\"button\");\npauseButton.innerText = \"Pause\";\npauseButton.onclick = () => {\n particleSystem.pause();\n};\ncontainer.appendChild(pauseButton);\n\nconst startButton = document.createElement(\"button\");\nstartButton.innerText = \"Start\";\nstartButton.style.marginLeft = \"5px\";\nstartButton.onclick = () => {\n particleSystem.start();\n};\ncontainer.appendChild(startButton);\n\nconst destroyButton = document.createElement(\"button\");\ndestroyButton.innerText = \"Destroy\";\ndestroyButton.style.marginLeft = \"5px\";\ndestroyButton.onclick = () => {\n particleSystem.destroy();\n};\ncontainer.appendChild(destroyButton);\n"], + "mappings": ";AASO,SAAS,MAAM,MAAc,OAAe,GAAG,MAAc,GAAG,MAAc,GAAW;AAC9F,QAAM,aAAa,MAAM,OAAO;AAChC,SAAO,MAAM,aAAa,IAAI,KAAK,IAAI,IAAI,KAAK,KAAK,OAAO,IAAI;AAClE;;;ACSA,IAAM,MAAgB,CAAC;AAEvB,SAAS,IAAI,GAAG,IAAI,KAAK,KAAK;AAC5B,MAAI,CAAC,KAAK,IAAI,KAAK,SAAS,EAAE,EAAE,UAAU,CA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ACnI;AAEA,IAAM,yBAAyB,CAAC,UAAsB;AACpD,QAAM,EAAE,KAAK,IAAI;AACjB,QAAM,OAAO,MAAM,KAAK,SAAS,MAAM,OAAO,QAAQ,IAAI,KAAK,OAAO,QAAQ,IAAI,GAAG;AAErF,UAAQ,IAAI;AAEd;AAEA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,WAAW,MAAM;AACf,OAAK;AACP,CAAC;AAED,MAAM;AAEN,IAAM,YAAY,SAAS,cAAc,KAAK;AAC9C,UAAU,MAAM,WAAW;AAC3B,UAAU,MAAM,SAAS;AACzB,UAAU,MAAM,OAAO;AACvB,UAAU,MAAM,UAAU;AAC1B,UAAU,MAAM,UAAU;AAC1B,UAAU,MAAM,iBAAiB;AACjC,UAAU,MAAM,aAAa;AAC7B,SAAS,KAAK,YAAY,SAAS;AAEnC,IAAM,cAAc,SAAS,cAAc,QAAQ;AACnD,YAAY,YAAY;AACxB,YAAY,UAAU,MAAM;AAC1B,iBAAe,MAAM;AACvB;AACA,UAAU,YAAY,WAAW;AAEjC,IAAM,cAAc,SAAS,cAAc,QAAQ;AACnD,YAAY,YAAY;AACxB,YAAY,MAAM,aAAa;AAC/B,YAAY,UAAU,MAAM;AAC1B,iBAAe,MAAM;AACvB;AACA,UAAU,YAAY,WAAW;AAEjC,IAAM,gBAAgB,SAAS,cAAc,QAAQ;AACrD,cAAc,YAAY;AAC1B,cAAc,MAAM,aAAa;AACjC,cAAc,UAAU,MAAM;AAC5B,iBAAe,QAAQ;AACzB;AACA,UAAU,YAAY,aAAa;", "names": ["defineMain", "start", "step", "addSystem", "tagKey", "canvas", "text", "canvas", "draw", "emitter", "opts", "start"] } diff --git a/packages/ngn/public/index.html b/packages/ngn/public/index.html index ceedc82..4751b73 100644 --- a/packages/ngn/public/index.html +++ b/packages/ngn/public/index.html @@ -4,10 +4,21 @@ esr +
+
{{ livereload }} + diff --git a/packages/ngn/src/demo.ts b/packages/ngn/src/demo.ts index 279ccbd..cf49a02 100644 --- a/packages/ngn/src/demo.ts +++ b/packages/ngn/src/demo.ts @@ -14,7 +14,7 @@ const particleSystem = createParticleSystem({ const emitter = particleSystem.createEmitter({ x: canvas.width / 2, y: canvas.height / 2, - maxParticles: 100, + maxParticles: 120, rate: 0.1, lifetime: 1000, lifetimeVariation: 0.2, @@ -49,8 +49,8 @@ const emitter = particleSystem.createEmitter({ particleSystem.createEmitter({ x: particle.x, y: particle.y, - maxParticles: 3, - lifetimeVariation: 0.2, + maxParticles: 4, + lifetimeVariation: 0.5, size: 3, sizeVariation: 2, colorStart: ["#FF0000", "#ff5100"], @@ -72,8 +72,8 @@ const emitter = particleSystem.createEmitter({ }, onUpdate: (particle: Particle, state: WorldState) => { particle.size = Math.max(0, particle.size - 0.35); - const v = pulse(state.time.elapsed, 0.25, -1, 1); - particle.x += v * 1; + // const v = pulse(state.time.elapsed, 0.25, -1, 1); + // particle.x += v * 1; }, onRemove: (particle: Particle, state: WorldState) => {}, }); @@ -93,7 +93,7 @@ const fpsDrawSystem = (state: WorldState) => { }; const particleCountSystem = (state: WorldState) => { - draw.text({ x: 10, y: 40 }, `Particle count: ${particleSystem.numParticles}`, "white"); + draw.text({ x: 10, y: 40 }, `Particle count: ${particleSystem.numParticles}. Emitter count: ${emitter.particles.length}`, "white"); }; const particlePositionSystem = (state: WorldState) => { diff --git a/packages/ngn/src/ngn.ts b/packages/ngn/src/ngn.ts index d24117e..459992c 100644 --- a/packages/ngn/src/ngn.ts +++ b/packages/ngn/src/ngn.ts @@ -36,7 +36,7 @@ export type ComponentInstance = () => { export type QueryConfig = Readonly< Partial<{ - /** Matches entities as long as the entity has all of the components in the provided array. */ + /** Matches entities as long as the entity has all the components in the provided array. */ and: Component[]; /** Matches entities as long as the entity has at least one of the components in the provided array. */ or: Component[]; @@ -83,13 +83,15 @@ export type WorldState = { time: { /** The total elapsed time in seconds since the game loop started. */ elapsed: number; - /** The time in milliseconds since the last frame. */ + /** The time in milliseconds since the last frame, scaled by time.scale. */ delta: number; + /** The raw, unscaled time in milliseconds since the last frame. */ + rawDelta: number; /** The time in milliseconds since the last time the main loop was called. */ loopDelta: number; /** The time in milliseconds of the last call to the main loop. */ lastLoopDelta: number; - /** The time scale of the game loop. */ + /** The timescale of the game loop. */ scale: number; /** The current frames per second. */ fps: number; @@ -111,6 +113,7 @@ export const createWorld = () => { time: { elapsed: 0, delta: 0, + rawDelta: 0, loopDelta: 0, lastLoopDelta: 0, scale: 1, @@ -135,6 +138,7 @@ export const createWorld = () => { let loopHandler = -1; const { time } = state; time.delta = 0; + time.rawDelta = 0; time.elapsed = 0; time.fps = 0; state[$running] = true; @@ -183,23 +187,39 @@ export const createWorld = () => { xfps = xtimes.length; time.fps = xfps; - time.delta = now - then; + // Store the raw, unscaled delta time + time.rawDelta = now - then; then = now; - accumulator += time.delta * time.scale; + // Apply time scale to delta - this represents the simulation time that has passed + time.delta = time.rawDelta * time.scale; + + // Use the raw delta for accumulation (behavior remains the same) + accumulator += time.rawDelta * time.scale; // Calculate the threshold for stepping the world based on the current frame rate const stepThreshold = 1000 / (time.fps || 60); + // Add a maximum number of iterations to prevent spiral of death + const maxSteps = 5; // Limit the catch-up to prevent freezing + let steps = 0; + // Step the world only when the accumulated scaled time exceeds the threshold - while (accumulator >= stepThreshold) { + while (accumulator >= stepThreshold && steps < maxSteps) { time.loopDelta = now - time.lastLoopDelta; time.lastLoopDelta = now; state[$mainLoop](state); accumulator -= stepThreshold; + steps++; } + // If we hit the max steps, discard remaining accumulator time + if (steps >= maxSteps) { + accumulator = 0; + } + + // Use the scaled delta for elapsed time calculation time.elapsed += time.delta * 0.001; loopHandler = raf(boundLoop); @@ -541,7 +561,7 @@ export const createWorld = () => { destroy, }); - // If we are focing a specific entity id, we need to migrate any + // If we are forcing a specific entity id, we need to migrate any // entity that might already occupy this space. if (spec.id !== undefined && state[$eMap][spec.id]) { migrateEntityId(spec.id, createId()); @@ -575,6 +595,16 @@ export const createWorld = () => { state[$eciMap][newId] = state[$eciMap][oldId]; delete state[$eciMap][oldId]; + + // Update component-to-entity mappings, because otherwise queries that + // rely on state[$ceMap] would still reference the old entity ID, + // causing inconsistencies when trying to find entities with specific + // components after ID migration. + Object.keys(state[$ceMap]).forEach((componentName) => { + if (state[$ceMap][componentName].includes(oldId)) { + state[$ceMap][componentName] = state[$ceMap][componentName].map((id) => (id === oldId ? newId : id)); + } + }); } function getEntity(id: string): Entity { diff --git a/packages/ngn/src/packages/emitter/index.ts b/packages/ngn/src/packages/emitter/index.ts index cae99cf..827bbde 100644 --- a/packages/ngn/src/packages/emitter/index.ts +++ b/packages/ngn/src/packages/emitter/index.ts @@ -55,32 +55,169 @@ type BlendMode = | "xor"; export type ParticleEmitterOptions = { - x?: number; // X position - y?: number; // Y position - maxParticles?: number; // Max number of particles - rate?: number; // Particles per second - lifetime?: number; // Lifetime of each particle - lifetimeVariation?: number; // Variation in lifetime - size?: number; // Size of each particle - sizeVariation?: number; // Variation in size - colorStart?: string | string[]; // Start color - colorEnd?: string | string[]; // End color - colorEasing?: ColorEasing; // Easing function for color + /** + * The x coordinate for new particles. + * Default is 0. + * Determines the horizontal start position of particle emission. Can be changed at any time. + */ + x?: number; + + /** + * The y coordinate for new particles. + * Default is 0. + * Determines the vertical start position of particle emission. Can be changed at any time. + */ + y?: number; + + /** + * Maximum number of particles that can exist at one time. + * Default is 100. + * Helps manage performance by capping particle count. + */ + maxParticles?: number; + + /** + * Number of particles emitted per millisecond interval. + * Default is 1. + * Controls the frequency of particle emission in relation to time. + */ + rate?: number; + + /** + * Lifetime of each particle in milliseconds. + * Default is 1000 (1 second). + * Determines how long a particle will exist before disappearing. + */ + lifetime?: number; + + /** + * Variation in particle lifetime as a fraction of `lifetime`. + * Provide a value between 0 and 1. + * Default is 0. + * Allows particles to have different lifetimes, adding randomness. + */ + lifetimeVariation?: number; + + /** + * Base size of each particle. + * Default is 5. + * Represents the default size/scale factor for particles. + */ + size?: number; + + /** + * Variation in size as a fraction of `size`. + * Provide a value between 0 and 1. + * Default is 0. + * Introduces variability to particle sizes. + */ + sizeVariation?: number; + + /** + * Initial color or array of possible initial colors for particles in hexadecimal format. + * Default is "#000000". + * Specifies the starting color of particles. + */ + colorStart?: string | string[]; + + /** + * Final color or array of possible end colors for particles in hexadecimal format. + * Default is "#000000". + * Specifies the color particles will transition to over their lifetime. + */ + colorEnd?: string | string[]; + + /** + * Easing function to interpolate between `colorStart` and `colorEnd`. + * Default is `ColorEasing.LINEAR`. + * Determines how the color changes over the particle's lifetime. + */ + colorEasing?: ColorEasing; + + /** + * Easing function for fade out effect. + * Default is `ColorEasing.LINEAR`. + * Controls opacity transition as particles disappear. + */ fadeOutEasing?: FadeEasing; - speed?: number; // Speed of each particle - speedVariation?: number; // Variation in speed - angle?: number; // Angle of emission - spread?: number; // Spread of emission - gravity?: { x: number; y: number }; // Gravity affecting the particles - blendMode?: BlendMode; // Blend mode - canvas: HTMLCanvasElement; // Canvas to draw on - burst?: boolean; // If true, emit all particles at once and then stop - /** Per-particle initialization callback. */ - onInit?: (particle: Particle, state: WorldState) => void; // Callback for particle initialization - /** Per-particle update callback. */ - onUpdate?: (particle: Particle, state: WorldState) => void; // Callback for particle update - /** Per-particle removal callback. */ - onRemove?: (particle: Particle, state: WorldState) => void; // Callback for particle removal + + /** + * Base speed of particle movement in pixels per millisecond. + * Default is 0.1. + * Determines how fast particles move from their origin. + */ + speed?: number; + + /** + * Variation in speed as a fraction of `speed`. + * Provide a value between 0 and 1. + * Default is 0. + * Introduces speed variability amongst particles. + */ + speedVariation?: number; + + /** + * Emission angle in degrees. + * Default is 0. + * Sets the direction of initial particle movement. + */ + angle?: number; + + /** + * Spread angle in degrees around the emission angle for particle dispersion. + * Default is 0. + * Widens the field of initial particle directions. + */ + spread?: number; + + /** + * Gravity effect on particles as x and y components. + * Default is {x: 0, y: 0}. + * It simulates gravitational forces affecting particle trajectories. + */ + gravity?: { x: number; y: number }; + + /** + * Blend mode used for particle rendering. + * Default is the canvas context’s "source-over". + * Determines how particles blend with the background/canvas. + */ + blendMode?: BlendMode; + + /** + * HTMLCanvasElement on which particles are drawn. + * Required parameter. + * Represents the rendering surface for the particle system. + */ + canvas: HTMLCanvasElement; + + /** + * If true, emit all particles at once and then stop. + * Default is false. + * Changes emitter behavior from continuous to singular burst. + */ + burst?: boolean; + + /** + * Callback invoked on each particle initialization. + * Default is undefined. + * Useful for setting initial particle properties dynamically. + */ + onInit?: (particle: Particle, state: WorldState) => void; + + /** + * Callback for code execution every frame as each particle updates. + * Default is undefined. + * Allows interaction or modification of particles per update loop. + */ + onUpdate?: (particle: Particle, state: WorldState) => void; + + /** + * Callback invoked when a particle is removed. + * Default is undefined. + * Useful for cleanup or concluding actions when particles disappear. + */ + onRemove?: (particle: Particle, state: WorldState) => void; }; const getDefaultParticleEmitterOptions = (opts: Partial): ParticleEmitterOptions => ({ @@ -306,7 +443,7 @@ export const createParticleEmitter = (opts: ParticleEmitterOptions): ParticleEmi destroy(); } - context.globalCompositeOperation = "source-over"; + // context.globalCompositeOperation = "source-over"; }; const destroy = () => { diff --git a/packages/ngn/src/packages/input/devices/keyboard.ts b/packages/ngn/src/packages/input/devices/keyboard.ts index 1e1b654..b08c6c7 100644 --- a/packages/ngn/src/packages/input/devices/keyboard.ts +++ b/packages/ngn/src/packages/input/devices/keyboard.ts @@ -39,7 +39,7 @@ export const keyboard = () => ({ * If the key is not found or not pressed, the `pressed`, `justPressed`, and `justReleased` properties will be set to `false`. */ getKey(b: string): ButtonState { - const key = Object.keys(keyboardMapping)[Object.values(keyboardMapping).indexOf(b)]; + const key = Object.keys(keyboardMapping)[Object.values(keyboardMapping).indexOf(b)] || b; if (key) return keyboardState.keys[key]; if (keyboardState.keys[b]) return keyboardState.keys[b]; return { pressed: false, justPressed: false, justReleased: false }; @@ -54,12 +54,13 @@ export const keyboard = () => ({ */ export const keyboardUpdate = (): void => { for (const [key, value] of Object.entries(observedKeyboardState.keys)) { - keyboardState.keys[key] = { + const actualKey = Object.keys(keyboardMapping)[Object.values(keyboardMapping).indexOf(key)] || key; + keyboardState.keys[actualKey] = { ...value, - justReleased: !value.pressed && keysDownLastFrame.keys?.[key]?.pressed, + justReleased: !value.pressed && keysDownLastFrame.keys?.[actualKey]?.pressed, }; - keysDownLastFrame.keys[key] = { ...value, justPressed: false }; - observedKeyboardState.keys[key] = { ...value, justPressed: false }; + keysDownLastFrame.keys[actualKey] = { ...value, justPressed: false }; + observedKeyboardState.keys[actualKey] = { ...value, justPressed: false }; } }; diff --git a/packages/ngn/src/packages/input/devices/mouse.ts b/packages/ngn/src/packages/input/devices/mouse.ts index 2e8a08d..9945835 100644 --- a/packages/ngn/src/packages/input/devices/mouse.ts +++ b/packages/ngn/src/packages/input/devices/mouse.ts @@ -33,12 +33,13 @@ const buttonsDownLastFrame: ObservedMouseState = { buttons: {} }; */ export const mouseUpdate = (): void => { for (const [button, value] of Object.entries(observedMouseState.buttons)) { - mouseState.buttons[button] = { + const actualButton = Object.keys(mouseMapping)[Object.values(mouseMapping).indexOf(button)] || button; + mouseState.buttons[actualButton] = { ...value, justReleased: !value.pressed && buttonsDownLastFrame.buttons?.[button]?.pressed, }; - buttonsDownLastFrame.buttons[button] = { ...value, justPressed: false }; - observedMouseState.buttons[button] = { ...value, justPressed: false }; + buttonsDownLastFrame.buttons[actualButton] = { ...value, justPressed: false }; + observedMouseState.buttons[actualButton] = { ...value, justPressed: false }; } }; diff --git a/packages/ngn/src/tests/ngn/index.ts b/packages/ngn/src/tests/ngn/index.ts index de494e6..0b6db26 100644 --- a/packages/ngn/src/tests/ngn/index.ts +++ b/packages/ngn/src/tests/ngn/index.ts @@ -20,4 +20,8 @@ export default testSuite(async ({ describe }) => { describe("mouse input", async ({ runTestSuite }) => { runTestSuite(import("./mouse.test.js")); }); + + describe("time scaling", async ({ runTestSuite }) => { + runTestSuite(import("./time.test.js")); + }); }); diff --git a/packages/ngn/src/tests/ngn/keyboard.test.ts b/packages/ngn/src/tests/ngn/keyboard.test.ts index aeee2a8..8c3e9b5 100644 --- a/packages/ngn/src/tests/ngn/keyboard.test.ts +++ b/packages/ngn/src/tests/ngn/keyboard.test.ts @@ -4,6 +4,31 @@ import { KeyboardKey } from "../../packages/input/devices/mappings/keyboard"; export default testSuite(async ({ describe }) => { describe("keyboard", () => { + test("accepts a custom mapping", () => { + const customMapping = () => ({ + [KeyboardKey.KeyA]: "RotateLeft", + [KeyboardKey.KeyD]: "Right", + }); + + const kb = keyboard(); + kb.keyboard.useMapping(customMapping); + + expect(kb.keyboard.getKey("RotateLeft")).toEqual({ + pressed: false, + justPressed: false, + justReleased: false, + }); + + onKeyDown({ code: "RotateLeft", repeat: false } as KeyboardEvent); + keyboardUpdate(); + + expect(kb.keyboard.getKey("RotateLeft")).toEqual({ + pressed: true, + justPressed: true, + justReleased: false, + }); + }); + test("should return an object with a keyboard property containing methods", () => { const kb = keyboard(); expect(typeof kb.keyboard).toBe("object"); diff --git a/packages/ngn/src/tests/ngn/time.test.ts b/packages/ngn/src/tests/ngn/time.test.ts new file mode 100644 index 0000000..6cf10c8 --- /dev/null +++ b/packages/ngn/src/tests/ngn/time.test.ts @@ -0,0 +1,58 @@ +import { expect, test, testSuite } from "manten"; +import { createWorld, WorldState } from "../../ngn"; + +const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +export default testSuite(async () => { + test("time.delta should be scaled by time.scale", async () => { + const { state, start, stop, defineMain } = createWorld(); + let i = 0; + state.time.scale = 0.5; + + defineMain((state: WorldState) => { + if (i > 0) { + // Check that delta is scaled (approximately half of rawDelta) + expect(state.time.delta).toBeCloseTo(state.time.rawDelta * 0.5, 1); + + // The raw delta should be around 16.67ms (60fps) + expect(state.time.rawDelta).toBeGreaterThan(15); + expect(state.time.rawDelta).toBeLessThan(20); + + // The scaled delta should be around 8.33ms (at scale 0.5) + expect(state.time.delta).toBeGreaterThan(7); + expect(state.time.delta).toBeLessThan(10); + } + + if (++i === 3) stop(); + }); + + start(); + await sleep(500); + + expect(i).toBe(3); + }); + + test("time.delta should be doubled when time.scale is 2.0", async () => { + const { state, start, stop, defineMain } = createWorld(); + let i = 0; + state.time.scale = 2.0; + + defineMain((state: WorldState) => { + if (i > 0) { + // Check that delta is scaled (approximately double of rawDelta) + expect(state.time.delta).toBeCloseTo(state.time.rawDelta * 2.0, 1); + + // The scaled delta should be around 33.34ms (at scale 2.0) + expect(state.time.delta).toBeGreaterThan(30); + expect(state.time.delta).toBeLessThan(40); + } + + if (++i === 3) stop(); + }); + + start(); + await sleep(500); + + expect(i).toBe(3); + }); +}); diff --git a/packages/ngn/src/tests/ngn/world.test.ts b/packages/ngn/src/tests/ngn/world.test.ts index 31bef53..2335a31 100644 --- a/packages/ngn/src/tests/ngn/world.test.ts +++ b/packages/ngn/src/tests/ngn/world.test.ts @@ -494,7 +494,9 @@ export default testSuite(async () => { await sleep(500); expect(i).toBe(3); - expect(state.time.delta).toBe(16.670000000000016); + // delta is scaled, so it should be half of rawDelta + expect(state.time.delta).toBeCloseTo(state.time.rawDelta * 0.5, 1); + expect(state.time.rawDelta).toBeCloseTo(16.67, 1); }); test("step calls systems, passing world", async () => {