A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
test(sdk): cover the undo/redo, input-router, mat4 and UI-helper gaps
yhh42f79434a5a5
diff --git a/sdk/tests/input-router.test.ts b/sdk/tests/input-router.test.tsnew file mode 100644index 000000000..284140984--- /dev/null+++ b/sdk/tests/input-router.test.ts@@ -0,0 +1,146 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The chain-of-responsibility input router (editor → UI → game). Its job+ * is entirely about ORDER and CONSUMPTION — editor sees an event first,+ * a `true` return stops propagation, a throw must not — and the subtle+ * key-up modifier timing (a handler sees the modifier as still-held on the+ * edge that releases it). None of that was asserted.+ */+import { describe, it, expect, vi } from 'vitest';+import { InputRouter, type InputHandler, type Modifiers } from '../src/inputRouter';++describe('InputRouter tier ordering & consumption', () => {+ it('dispatches editor before UI and stops when the editor consumes', () => {+ const order: string[] = [];+ const editor: InputHandler = { onKeyDown: () => { order.push('editor'); return true; } };+ const ui: InputHandler = { onKeyDown: () => { order.push('ui'); return true; } };+ const r = new InputRouter();+ r.setEditorHandler(editor);+ r.setUIHandler(ui);+ expect(r.dispatchKeyDown('KeyA')).toBe(true);+ expect(order).toEqual(['editor']); // UI never reached+ });++ it('falls through to UI when the editor returns void/false', () => {+ const order: string[] = [];+ const editor: InputHandler = { onKeyDown: () => { order.push('editor'); /* void */ } };+ const ui: InputHandler = { onKeyDown: () => { order.push('ui'); return true; } };+ const r = new InputRouter();+ r.setEditorHandler(editor);+ r.setUIHandler(ui);+ expect(r.dispatchKeyDown('KeyA')).toBe(true);+ expect(order).toEqual(['editor', 'ui']);+ });++ it('returns false to gameplay when no tier consumes', () => {+ const r = new InputRouter();+ r.setEditorHandler({ onKeyDown: () => false });+ r.setUIHandler({ onKeyDown: () => undefined });+ expect(r.dispatchKeyDown('KeyA')).toBe(false);+ });++ it('treats a throwing handler as non-consuming and keeps dispatching', () => {+ const ui = vi.fn(() => true);+ const r = new InputRouter();+ r.setEditorHandler({ onPointerDown: () => { throw new Error('bad tool'); } });+ r.setUIHandler({ onPointerDown: ui });+ expect(() => r.dispatchPointerDown(0, 5, 6)).not.toThrow();+ expect(r.dispatchPointerDown(0, 5, 6)).toBe(true); // fell through to UI+ expect(ui).toHaveBeenCalledWith(0, 5, 6, expect.any(Object));+ });++ it('only-a-partial handler (missing method) is skipped, not an error', () => {+ const r = new InputRouter();+ r.setEditorHandler({}); // no callbacks at all+ r.setUIHandler({ onWheel: () => true });+ expect(r.dispatchWheel(0, -120)).toBe(true);+ });+});++describe('InputRouter handler registration', () => {+ it('unregister thunk clears the handler', () => {+ const r = new InputRouter();+ const off = r.setEditorHandler({ onKeyDown: () => true });+ expect(r.dispatchKeyDown('KeyA')).toBe(true);+ off();+ expect(r.dispatchKeyDown('KeyA')).toBe(false); // handler gone+ });++ it('a stale unregister thunk does not clobber a replacement handler', () => {+ const r = new InputRouter();+ const off1 = r.setEditorHandler({ onKeyDown: () => false });+ r.setEditorHandler({ onKeyDown: () => true }); // replace+ off1(); // stale: must NOT remove the new handler+ expect(r.dispatchKeyDown('KeyA')).toBe(true);+ });+});++describe('InputRouter modifier tracking', () => {+ it('tracks shift/ctrl/alt/meta across key down and up', () => {+ const r = new InputRouter();+ r.dispatchKeyDown('ShiftLeft');+ r.dispatchKeyDown('ControlRight');+ r.dispatchKeyDown('AltLeft');+ r.dispatchKeyDown('OSLeft'); // meta alias+ expect(r.currentMods).toMatchObject({ shift: true, ctrl: true, alt: true, meta: true });+ r.dispatchKeyUp('ShiftLeft');+ expect(r.currentMods.shift).toBe(false);+ expect(r.currentMods.ctrl).toBe(true); // others untouched+ });++ it('non-modifier keys leave the modifier state (and its identity) unchanged', () => {+ const r = new InputRouter();+ const before = r.currentMods;+ r.dispatchKeyDown('KeyA');+ expect(r.currentMods).toBe(before); // no new object allocated+ expect(r.currentMods).toMatchObject({ shift: false, ctrl: false, alt: false, meta: false });+ });++ it('passes the CURRENT modifiers to handlers on key-down', () => {+ const r = new InputRouter();+ r.dispatchKeyDown('ShiftLeft');+ let seen: Modifiers | null = null;+ r.setEditorHandler({ onKeyDown: (_c, mods) => { seen = mods; } });+ r.dispatchKeyDown('KeyA');+ expect(seen).toMatchObject({ shift: true });+ });++ it('key-up updates modifiers AFTER dispatch: the handler sees it still held', () => {+ const r = new InputRouter();+ r.dispatchKeyDown('ShiftLeft');+ let shiftDuringRelease: boolean | null = null;+ r.setEditorHandler({ onKeyUp: (_c, mods) => { shiftDuringRelease = mods.shift; } });+ r.dispatchKeyUp('ShiftLeft');+ expect(shiftDuringRelease).toBe(true); // still held on the releasing edge (DOM semantics)+ expect(r.currentMods.shift).toBe(false); // cleared once dispatch returns+ });+});++describe('InputRouter dispatch coverage (args reach the right tier)', () => {+ it('routes pointer, wheel, and touch events with their arguments', () => {+ const calls: Record<string, unknown[]> = {};+ const record = (k: string) => (...a: unknown[]) => { calls[k] = a; return false; };+ const r = new InputRouter();+ r.setUIHandler({+ onPointerMove: record('move'),+ onPointerUp: record('up'),+ onTouchStart: record('tstart'),+ onTouchMove: record('tmove'),+ onTouchEnd: record('tend'),+ onTouchCancel: record('tcancel'),+ });+ r.dispatchPointerMove(3, 4);+ r.dispatchPointerUp(2);+ r.dispatchTouchStart(7, 10, 20);+ r.dispatchTouchMove(7, 11, 21);+ r.dispatchTouchEnd(7);+ r.dispatchTouchCancel(7);+ expect(calls.move.slice(0, 2)).toEqual([3, 4]);+ expect(calls.up[0]).toBe(2);+ expect(calls.tstart).toEqual([7, 10, 20]);+ expect(calls.tmove).toEqual([7, 11, 21]);+ expect(calls.tend).toEqual([7]);+ expect(calls.tcancel).toEqual([7]);+ });+});diff --git a/sdk/tests/mat4.test.ts b/sdk/tests/mat4.test.tsnew file mode 100644index 000000000..ea4429d14--- /dev/null+++ b/sdk/tests/mat4.test.ts@@ -0,0 +1,148 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Correctness of the camera/projection matrix math. These functions are+ * exercised indirectly whenever CameraPlugin builds a view/projection,+ * but nothing asserted the numbers were right — a sign flip in ortho or a+ * transposed multiply would render "fine" and be silently wrong. Column+ * major throughout: element (row r, col c) lives at m[c * 4 + r], and a+ * point transforms as out[r] = Σ_c m[c*4+r] · v[c].+ */+import { describe, it, expect } from 'vitest';+import { ortho, perspective, invertTranslation, invertViewZ, multiply, IDENTITY } from '../src/math/mat4';++const close = (a: number, b: number, eps = 1e-6) => expect(Math.abs(a - b)).toBeLessThanOrEqual(eps);++/** Column-major matrix · (x,y,z,w) → [x',y',z',w']. */+function apply(m: Float32Array, x: number, y: number, z: number, w = 1): [number, number, number, number] {+ const out: [number, number, number, number] = [0, 0, 0, 0];+ for (let r = 0; r < 4; r++) {+ out[r] = m[0 * 4 + r] * x + m[1 * 4 + r] * y + m[2 * 4 + r] * z + m[3 * 4 + r] * w;+ }+ return out;+}++// Every builder returns a shared module-level scratch array, so a second call+// clobbers the first. Snapshot before comparing — this mirrors how callers must+// treat the results and guards the shared-buffer contract itself.+const snap = (m: Float32Array): Float32Array => Float32Array.from(m);++describe('mat4.ortho', () => {+ it('maps the box corners to the NDC cube and the center to the origin', () => {+ const m = snap(ortho(-10, 10, -5, 5, 1, 100));+ // x: [-10,10] → [-1,1]; y: [-5,5] → [-1,1] (z picked in-range, does not affect x/y).+ expect(apply(m, 10, 5, -1)[0]).toBeCloseTo(1, 6);+ expect(apply(m, -10, -5, -1)[0]).toBeCloseTo(-1, 6);+ expect(apply(m, 10, 5, -1)[1]).toBeCloseTo(1, 6);+ expect(apply(m, -10, -5, -1)[1]).toBeCloseTo(-1, 6);+ const c = apply(m, 0, 0, -50.5); // (center x, center y, mid eye-depth)+ close(c[0], 0); close(c[1], 0); close(c[2], 0);+ });++ it('uses the OpenGL depth convention: near plane → -1, far plane → +1', () => {+ const m = snap(ortho(-1, 1, -1, 1, 1, 100));+ // Eye space looks down -Z, so the near plane sits at z = -near, far at z = -far.+ close(apply(m, 0, 0, -1)[2], -1);+ close(apply(m, 0, 0, -100)[2], 1);+ });++ it('is affine in w and leaves the perspective row untouched (w stays 1)', () => {+ const m = snap(ortho(-3, 7, -2, 8, 0.5, 20));+ expect(apply(m, 4, 4, -4)[3]).toBe(1);+ });+});++describe('mat4.perspective', () => {+ it('emits w = -z (the perspective divide) and keeps the optical axis centered', () => {+ const m = snap(perspective(Math.PI / 2, 16 / 9, 0.1, 1000));+ const p = apply(m, 0, 0, -5);+ close(p[0], 0);+ close(p[1], 0);+ close(p[3], 5); // w = -z = -(-5)+ });++ it('scales x by 1/aspect and y by the focal length at fov=90°', () => {+ // fov = 90° → f = 1/tan(45°) = 1, so m[0] = 1/aspect, m[5] = 1.+ const aspect = 2;+ const m = snap(perspective(Math.PI / 2, aspect, 1, 100));+ close(m[0], 1 / aspect);+ close(m[5], 1);+ close(m[11], -1);+ });+});++describe('mat4.invertTranslation', () => {+ it('sends the camera position to the origin', () => {+ const m = snap(invertTranslation(3, -4, 5));+ const o = apply(m, 3, -4, 5);+ close(o[0], 0); close(o[1], 0); close(o[2], 0); close(o[3], 1);+ });+});++describe('mat4.invertViewZ', () => {+ it('equals invertTranslation when the camera is unrotated (θ=0)', () => {+ const t = snap(invertTranslation(7, -2, 3));+ const v = snap(invertViewZ(7, -2, 3, 1, 0)); // cosθ=1, sinθ=0+ for (let i = 0; i < 16; i++) close(v[i], t[i]);+ });++ it('sends the camera position to the origin under rotation', () => {+ const th = Math.PI / 3;+ const m = snap(invertViewZ(5, 8, -2, Math.cos(th), Math.sin(th)));+ const o = apply(m, 5, 8, -2);+ close(o[0], 0); close(o[1], 0); close(o[2], 0);+ });++ it('rotates world into view space: a +90° camera turns +X into -Y', () => {+ // Camera at origin rotated +90° (cos=0, sin=1). A world point on +X should+ // land on the view-space -Y axis (the world rotates by -θ into the view).+ const m = snap(invertViewZ(0, 0, 0, 0, 1));+ const o = apply(m, 1, 0, 0);+ close(o[0], 0); close(o[1], -1);+ });+});++describe('mat4.multiply', () => {+ it('IDENTITY is the two-sided identity', () => {+ const a = snap(invertTranslation(2, 3, 4));+ const left = snap(multiply(IDENTITY, a));+ const right = snap(multiply(a, IDENTITY));+ for (let i = 0; i < 16; i++) { close(left[i], a[i]); close(right[i], a[i]); }+ });++ it('composes transforms in column-major order (M·v applies the right operand first)', () => {+ // ortho ∘ view: projecting the camera-space origin of a translated camera+ // must equal projecting (0,0,0) directly — the camera sits at its own origin.+ const proj = snap(ortho(-10, 10, -10, 10, 1, 100));+ const view = snap(invertTranslation(4, -6, -50));+ const vp = snap(multiply(proj, view));+ const throughCombined = apply(vp, 4, -6, -50);+ const throughSeparate = apply(proj, ...(apply(view, 4, -6, -50).slice(0, 3) as [number, number, number]));+ for (let i = 0; i < 4; i++) close(throughCombined[i], throughSeparate[i]);+ });++ it('matches a hand-computed product on a non-symmetric pair', () => {+ // Two distinct translations compose additively: T(a)·T(b) = T(a+b).+ const A = snap(invertTranslation(-1, -2, -3)); // translate(+1,+2,+3)+ const B = snap(invertTranslation(-4, -5, -6)); // translate(+4,+5,+6)+ const AB = snap(multiply(A, B));+ // Combined translation column (m[12..14]) must be the sum (+5,+7,+9).+ close(AB[12], 5); close(AB[13], 7); close(AB[14], 9); close(AB[15], 1);+ });+});++describe('mat4 shared scratch buffers (footgun contract)', () => {+ it('reuses one array per builder — callers must snapshot before the next call', () => {+ const first = ortho(-1, 1, -1, 1, 1, 10);+ const second = ortho(-2, 2, -2, 2, 1, 20);+ expect(first).toBe(second); // same reference: the first result was overwritten+ expect(first[0]).toBeCloseTo(2 / 4, 6); // now holds the SECOND box's 2/(r-l)+ });++ it('IDENTITY is a genuine identity matrix and is not a scratch target', () => {+ expect(Array.from(IDENTITY)).toEqual([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);+ multiply(IDENTITY, IDENTITY); // multiply writes its own buffer, never IDENTITY+ expect(IDENTITY[0]).toBe(1);+ expect(IDENTITY[5]).toBe(1);+ });+});diff --git a/sdk/tests/transaction.test.ts b/sdk/tests/transaction.test.tsnew file mode 100644index 000000000..a6b5f7f87--- /dev/null+++ b/sdk/tests/transaction.test.ts@@ -0,0 +1,188 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The editor's undo/redo primitive. Every gesture the editor makes rides+ * on this: LIFO reversal within a transaction, redo invalidation on a new+ * edit, the single-active-transaction invariant, history trimming, and+ * error-resilient replay. It had zero coverage — a broken reverse order+ * or a leaked active transaction would corrupt undo with no test to catch+ * it.+ */+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { Transaction, TransactionManager } from '../src/transaction';+import { log } from '../src/logger';++/** A recording op: pushes a marker on forward/reverse so ordering is observable. */+function recordingOp(trace: string[], tag: string) {+ return {+ forward: () => trace.push(`+${tag}`),+ reverse: () => trace.push(`-${tag}`),+ };+}++describe('Transaction', () => {+ it('add() runs forward immediately; addDeferred() does not', () => {+ const trace: string[] = [];+ const tx = new Transaction('edit');+ tx.add(recordingOp(trace, 'a'));+ expect(trace).toEqual(['+a']); // add applied forward+ tx.addDeferred(recordingOp(trace, 'b'));+ expect(trace).toEqual(['+a']); // deferred did not+ expect(tx.opCount).toBe(2);+ });++ it('undo reverses in LIFO order, redo replays in FIFO order', () => {+ const trace: string[] = [];+ const tx = new Transaction('multi');+ tx.add(recordingOp(trace, 'a'));+ tx.add(recordingOp(trace, 'b'));+ tx.add(recordingOp(trace, 'c'));+ expect(trace).toEqual(['+a', '+b', '+c']);+ trace.length = 0;+ tx.undo();+ expect(trace).toEqual(['-c', '-b', '-a']); // LIFO+ trace.length = 0;+ tx.redo();+ expect(trace).toEqual(['+a', '+b', '+c']); // FIFO+ });++ it('a throwing op is caught and logged; siblings still run', () => {+ const warn = vi.spyOn(log, 'warn').mockImplementation(() => {});+ const trace: string[] = [];+ const tx = new Transaction('resilient');+ tx.addDeferred(recordingOp(trace, 'a'));+ tx.addDeferred({ forward: () => {}, reverse: () => { throw new Error('boom'); } });+ tx.addDeferred(recordingOp(trace, 'c'));+ expect(() => tx.undo()).not.toThrow();+ // LIFO: c reverses, the middle throws (caught), a still reverses.+ expect(trace).toEqual(['-c', '-a']);+ expect(warn).toHaveBeenCalledTimes(1);+ warn.mockRestore();+ });++ it('assigns a unique id and a label; ids do not collide across instances', () => {+ const a = new Transaction('one');+ const b = new Transaction('two');+ expect(a.label).toBe('one');+ expect(a.id).not.toBe(b.id);+ expect(new Transaction('x', 'fixed-id').id).toBe('fixed-id');+ });+});++describe('TransactionManager', () => {+ let mgr: TransactionManager;+ beforeEach(() => { mgr = new TransactionManager(); });++ const commit = (label: string, ops: Array<{ forward(): void; reverse(): void }>) => {+ const tx = mgr.begin(label);+ for (const op of ops) tx.add(op);+ mgr.commit(tx);+ return tx;+ };++ it('commits a non-empty transaction and enables undo', () => {+ expect(mgr.canUndo()).toBe(false);+ const trace: string[] = [];+ commit('edit', [recordingOp(trace, 'a')]);+ expect(mgr.canUndo()).toBe(true);+ expect(mgr.canRedo()).toBe(false);+ expect(mgr.peekUndo()?.label).toBe('edit');+ });++ it('drops an empty transaction silently', () => {+ const tx = mgr.begin('noop');+ mgr.commit(tx);+ expect(mgr.canUndo()).toBe(false);+ expect(mgr.peekUndo()).toBeNull();+ });++ it('begin() rejects a nested transaction', () => {+ mgr.begin('outer');+ expect(() => mgr.begin('inner')).toThrow(/already open/);+ });++ it('commit()/rollback() reject a transaction that is not the active one', () => {+ const active = mgr.begin('active');+ const stranger = new Transaction('stranger');+ expect(() => mgr.commit(stranger)).toThrow(/not the active one/);+ expect(() => mgr.rollback(stranger)).toThrow(/not the active one/);+ mgr.commit(active); // clean up the active slot+ });++ it('rollback reverses applied ops and does not enter the undo stack', () => {+ const trace: string[] = [];+ const tx = mgr.begin('cancelled');+ tx.add(recordingOp(trace, 'a'));+ tx.add(recordingOp(trace, 'b'));+ trace.length = 0;+ mgr.rollback(tx);+ expect(trace).toEqual(['-b', '-a']); // LIFO undo of applied ops+ expect(mgr.canUndo()).toBe(false); // never committed+ });++ it('undo moves a transaction to the redo stack; redo moves it back', () => {+ const trace: string[] = [];+ commit('edit', [recordingOp(trace, 'a')]);+ trace.length = 0;++ const undone = mgr.undo();+ expect(undone?.label).toBe('edit');+ expect(trace).toEqual(['-a']);+ expect(mgr.canUndo()).toBe(false);+ expect(mgr.canRedo()).toBe(true);++ trace.length = 0;+ const redone = mgr.redo();+ expect(redone?.label).toBe('edit');+ expect(trace).toEqual(['+a']);+ expect(mgr.canUndo()).toBe(true);+ expect(mgr.canRedo()).toBe(false);+ });++ it('a new commit invalidates the redo path', () => {+ commit('first', [{ forward() {}, reverse() {} }]);+ mgr.undo();+ expect(mgr.canRedo()).toBe(true);+ commit('second', [{ forward() {}, reverse() {} }]);+ expect(mgr.canRedo()).toBe(false); // redo stack cleared+ expect(mgr.peekRedo()).toBeNull();+ });++ it('undo/redo return null on empty stacks', () => {+ expect(mgr.undo()).toBeNull();+ expect(mgr.redo()).toBeNull();+ });++ it('refuses undo/redo while a transaction is open', () => {+ const warn = vi.spyOn(log, 'warn').mockImplementation(() => {});+ commit('done', [{ forward() {}, reverse() {} }]);+ mgr.begin('open');+ expect(mgr.undo()).toBeNull();+ expect(mgr.redo()).toBeNull();+ expect(mgr.canUndo()).toBe(false); // gated while open+ expect(mgr.canRedo()).toBe(false);+ expect(warn).toHaveBeenCalled();+ warn.mockRestore();+ });++ it('enforces the history limit, dropping the oldest entry', () => {+ const m = new TransactionManager({ historyLimit: 2 });+ const mk = (label: string) => { const tx = m.begin(label); tx.add({ forward() {}, reverse() {} }); m.commit(tx); };+ mk('a'); mk('b'); mk('c'); // 'a' should have been evicted+ expect(m.peekUndo()?.label).toBe('c');+ m.undo(); // c+ m.undo(); // b+ expect(m.canUndo()).toBe(false); // only 2 retained; 'a' is gone+ });++ it('clear() empties both stacks and the active slot', () => {+ commit('edit', [{ forward() {}, reverse() {} }]);+ mgr.undo();+ expect(mgr.canRedo()).toBe(true);+ mgr.begin('dangling'); // leave a transaction open+ mgr.clear();+ expect(mgr.canUndo()).toBe(false);+ expect(mgr.canRedo()).toBe(false);+ expect(() => mgr.begin('fresh')).not.toThrow(); // active slot was cleared+ });+});diff --git a/sdk/tests/ui-util-helpers.test.ts b/sdk/tests/ui-util-helpers.test.tsnew file mode 100644index 000000000..a2647e72b--- /dev/null+++ b/sdk/tests/ui-util-helpers.test.ts@@ -0,0 +1,122 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The pure, world-free helpers in ui/util/helpers: word-aware text+ * wrapping, power-of-two rounding, colour math, and the entity/state map+ * cleanup. wrapText in particular carries real branching (word boundary+ * vs. hard break vs. paragraph split) that nothing exercised directly.+ */+import { describe, it, expect } from 'vitest';+import {+ isWordChar,+ wrapText,+ nextPowerOf2,+ colorScale,+ colorWithAlpha,+ colorToRgba,+ EntityStateMap,+} from '../src/ui/util/helpers';+import type { Color, Entity } from '../src/types';++// A deterministic text metric: every glyph is 10 units wide, so a maxWidth of N+// means "at most N/10 characters per line" — no real font or canvas required.+const ctx = { measureText: (s: string) => ({ width: s.length * 10 }) } as unknown as CanvasRenderingContext2D;++describe('isWordChar', () => {+ it('accepts letters, digits and underscore; rejects space and punctuation', () => {+ expect(isWordChar('A'.charCodeAt(0))).toBe(true);+ expect(isWordChar('z'.charCodeAt(0))).toBe(true);+ expect(isWordChar('7'.charCodeAt(0))).toBe(true);+ expect(isWordChar('_'.charCodeAt(0))).toBe(true);+ expect(isWordChar(' '.charCodeAt(0))).toBe(false);+ expect(isWordChar('-'.charCodeAt(0))).toBe(false);+ expect(isWordChar('.'.charCodeAt(0))).toBe(false);+ });+});++describe('wrapText', () => {+ it('returns a single empty line for empty input', () => {+ expect(wrapText(ctx, '', 100)).toEqual(['']);+ });++ it('does not wrap when everything fits', () => {+ expect(wrapText(ctx, 'abc', 100)).toEqual(['abc']); // 30 < 100+ });++ it('splits on hard newlines, preserving blank paragraphs', () => {+ expect(wrapText(ctx, 'ab\ncd', 100)).toEqual(['ab', 'cd']);+ expect(wrapText(ctx, 'ab\n\ncd', 100)).toEqual(['ab', '', 'cd']);+ });++ it('treats maxWidth <= 0 as "newlines only", never measuring', () => {+ expect(wrapText(ctx, 'abcdef', 0)).toEqual(['abcdef']);+ expect(wrapText(ctx, 'ab\ncd', -5)).toEqual(['ab', 'cd']);+ });++ it('hard-breaks a single word with no break opportunity', () => {+ // 8 glyphs, 3 per line → 3/3/2.+ expect(wrapText(ctx, 'aaaaaaaa', 30)).toEqual(['aaa', 'aaa', 'aa']);+ });++ it('breaks at a word boundary and keeps every character', () => {+ const lines = wrapText(ctx, 'alpha beta', 50); // 5 glyphs/line+ expect(lines.length).toBeGreaterThan(1);+ expect(lines.join('').replace(/\s/g, '')).toBe('alphabeta'); // no glyph lost+ expect(lines[0]).toBe('alpha'); // the first word survives intact on line 1+ });+});++describe('nextPowerOf2', () => {+ it('rounds up to the next power of two (and is idempotent on exact powers)', () => {+ expect(nextPowerOf2(1)).toBe(1);+ expect(nextPowerOf2(3)).toBe(4);+ expect(nextPowerOf2(5)).toBe(8);+ expect(nextPowerOf2(16)).toBe(16);+ expect(nextPowerOf2(17)).toBe(32);+ expect(nextPowerOf2(0)).toBe(1); // p starts at 1, loop never runs+ });+});++describe('colour helpers', () => {+ const c: Color = { r: 0.4, g: 0.5, b: 0.6, a: 0.8 };++ it('colorScale multiplies rgb, clamps to 1, and preserves alpha', () => {+ expect(colorScale(c, 0.5)).toEqual({ r: 0.2, g: 0.25, b: 0.3, a: 0.8 });+ const bright = colorScale({ r: 0.8, g: 0.9, b: 1, a: 0.5 }, 2);+ expect(bright).toEqual({ r: 1, g: 1, b: 1, a: 0.5 }); // clamped, alpha untouched+ });++ it('colorWithAlpha replaces only alpha', () => {+ expect(colorWithAlpha(c, 0.1)).toEqual({ r: 0.4, g: 0.5, b: 0.6, a: 0.1 });+ });++ it('colorToRgba rounds rgb to 0..255 and passes alpha through raw', () => {+ expect(colorToRgba({ r: 1, g: 0, b: 0.5, a: 0.25 })).toBe('rgba(255, 0, 128, 0.25)');+ });+});++describe('EntityStateMap', () => {+ it('stores and retrieves per-entity state', () => {+ const m = new EntityStateMap<string>();+ const e = 1 as Entity;+ expect(m.has(e)).toBe(false);+ m.set(e, 'hovered');+ expect(m.get(e)).toBe('hovered');+ expect(m.has(e)).toBe(true);+ m.delete(e);+ expect(m.get(e)).toBeUndefined();+ });++ it('cleanup() drops entries whose entity is no longer valid', () => {+ const m = new EntityStateMap<number>();+ m.set(1 as Entity, 10);+ m.set(2 as Entity, 20);+ m.set(3 as Entity, 30);+ const alive = new Set([1, 3]);+ const world = { valid: (e: Entity) => alive.has(e as unknown as number) };+ m.cleanup(world as never);+ expect(m.has(1 as Entity)).toBe(true);+ expect(m.has(2 as Entity)).toBe(false); // pruned+ expect(m.has(3 as Entity)).toBe(true);+ });+});