Skip to content

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.

test: add TDD tests for uiMath, uiLayout, renderTexture, sceneManager

esenginef082d3f24a62
diff --git a/sdk/tests/renderTexture.test.ts b/sdk/tests/renderTexture.test.ts
new file mode 100644
index 000000000..742270451
--- /dev/null
+++ b/sdk/tests/renderTexture.test.ts
@@ -0,0 +1,162 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+vi.mock('../src/renderer', () => ({
+ Renderer: {
+ createRenderTarget: vi.fn().mockReturnValue(1),
+ releaseRenderTarget: vi.fn(),
+ getTargetTexture: vi.fn().mockReturnValue(100),
+ getTargetDepthTexture: vi.fn().mockReturnValue(200),
+ begin: vi.fn(),
+ end: vi.fn(),
+ },
+}));
+
+import { RenderTexture } from '../src/renderTexture';
+import { Renderer } from '../src/renderer';
+
+describe('RenderTexture', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ (Renderer.createRenderTarget as ReturnType<typeof vi.fn>).mockReturnValue(1);
+ (Renderer.getTargetTexture as ReturnType<typeof vi.fn>).mockReturnValue(100);
+ (Renderer.getTargetDepthTexture as ReturnType<typeof vi.fn>).mockReturnValue(200);
+ });
+
+ describe('create', () => {
+ it('uses depth=true by default, producing flags=1', () => {
+ RenderTexture.create({ width: 256, height: 256 });
+ expect(Renderer.createRenderTarget).toHaveBeenCalledWith(256, 256, 1);
+ });
+
+ it('sets flags=0 when depth=false', () => {
+ RenderTexture.create({ width: 128, height: 128, depth: false });
+ expect(Renderer.createRenderTarget).toHaveBeenCalledWith(128, 128, 0);
+ });
+
+ it('sets flags=3 when depth=true and filter=linear', () => {
+ RenderTexture.create({ width: 64, height: 64, depth: true, filter: 'linear' });
+ expect(Renderer.createRenderTarget).toHaveBeenCalledWith(64, 64, 3);
+ });
+
+ it('sets flags=2 when depth=false and filter=linear', () => {
+ RenderTexture.create({ width: 64, height: 64, depth: false, filter: 'linear' });
+ expect(Renderer.createRenderTarget).toHaveBeenCalledWith(64, 64, 2);
+ });
+
+ it('sets flags=1 when filter=nearest (default depth)', () => {
+ RenderTexture.create({ width: 64, height: 64, filter: 'nearest' });
+ expect(Renderer.createRenderTarget).toHaveBeenCalledWith(64, 64, 1);
+ });
+
+ it('returns a RenderTextureHandle with correct fields', () => {
+ const rt = RenderTexture.create({ width: 512, height: 512 });
+ expect(rt).toEqual({
+ _handle: 1,
+ textureId: 100,
+ width: 512,
+ height: 512,
+ });
+ });
+
+ it('queries textureId from the created handle', () => {
+ (Renderer.createRenderTarget as ReturnType<typeof vi.fn>).mockReturnValue(42);
+ RenderTexture.create({ width: 256, height: 256 });
+ expect(Renderer.getTargetTexture).toHaveBeenCalledWith(42);
+ });
+ });
+
+ describe('release', () => {
+ it('calls releaseRenderTarget with the correct handle', () => {
+ const rt = RenderTexture.create({ width: 256, height: 256 });
+ RenderTexture.release(rt);
+ expect(Renderer.releaseRenderTarget).toHaveBeenCalledWith(rt._handle);
+ });
+
+ it('can be called on different handles', () => {
+ (Renderer.createRenderTarget as ReturnType<typeof vi.fn>).mockReturnValueOnce(10).mockReturnValueOnce(20);
+ const rt1 = RenderTexture.create({ width: 64, height: 64 });
+ const rt2 = RenderTexture.create({ width: 128, height: 128 });
+ RenderTexture.release(rt1);
+ RenderTexture.release(rt2);
+ expect(Renderer.releaseRenderTarget).toHaveBeenCalledWith(10);
+ expect(Renderer.releaseRenderTarget).toHaveBeenCalledWith(20);
+ });
+ });
+
+ describe('resize', () => {
+ it('releases old target then creates a new one', () => {
+ const callOrder: string[] = [];
+ (Renderer.releaseRenderTarget as ReturnType<typeof vi.fn>).mockImplementation(() => callOrder.push('release'));
+ (Renderer.createRenderTarget as ReturnType<typeof vi.fn>).mockImplementation(() => {
+ callOrder.push('create');
+ return 2;
+ });
+
+ const rt = { _handle: 1, textureId: 100, width: 256, height: 256 };
+ RenderTexture.resize(rt, 512, 512);
+
+ expect(callOrder).toEqual(['release', 'create']);
+ expect(Renderer.releaseRenderTarget).toHaveBeenCalledWith(1);
+ });
+
+ it('returns a new handle with updated dimensions', () => {
+ (Renderer.createRenderTarget as ReturnType<typeof vi.fn>).mockReturnValue(5);
+ (Renderer.getTargetTexture as ReturnType<typeof vi.fn>).mockReturnValue(500);
+
+ const rt = { _handle: 1, textureId: 100, width: 256, height: 256 };
+ const resized = RenderTexture.resize(rt, 1024, 768);
+
+ expect(resized).toEqual({
+ _handle: 5,
+ textureId: 500,
+ width: 1024,
+ height: 768,
+ });
+ });
+
+ it('hardcodes depth=true in resize (potential bug: loses original depth setting)', () => {
+ const rt = { _handle: 1, textureId: 100, width: 64, height: 64 };
+ RenderTexture.resize(rt, 128, 128);
+ expect(Renderer.createRenderTarget).toHaveBeenCalledWith(128, 128, 1);
+ });
+ });
+
+ describe('begin / end', () => {
+ it('calls Renderer.begin with viewProjection and handle', () => {
+ const vp = new Float32Array(16);
+ const rt = { _handle: 7, textureId: 100, width: 256, height: 256 };
+ RenderTexture.begin(rt, vp);
+ expect(Renderer.begin).toHaveBeenCalledWith(vp, 7);
+ });
+
+ it('calls Renderer.end', () => {
+ RenderTexture.end();
+ expect(Renderer.end).toHaveBeenCalled();
+ });
+
+ it('passes arguments in correct order (viewProjection first, handle second)', () => {
+ const vp = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
+ const rt = { _handle: 3, textureId: 100, width: 128, height: 128 };
+ RenderTexture.begin(rt, vp);
+
+ const call = (Renderer.begin as ReturnType<typeof vi.fn>).mock.calls[0];
+ expect(call[0]).toBe(vp);
+ expect(call[1]).toBe(3);
+ });
+ });
+
+ describe('getDepthTexture', () => {
+ it('proxies to Renderer.getTargetDepthTexture with correct handle', () => {
+ const rt = { _handle: 9, textureId: 100, width: 256, height: 256 };
+ RenderTexture.getDepthTexture(rt);
+ expect(Renderer.getTargetDepthTexture).toHaveBeenCalledWith(9);
+ });
+
+ it('returns the value from Renderer', () => {
+ (Renderer.getTargetDepthTexture as ReturnType<typeof vi.fn>).mockReturnValue(999);
+ const rt = { _handle: 9, textureId: 100, width: 256, height: 256 };
+ const result = RenderTexture.getDepthTexture(rt);
+ expect(result).toBe(999);
+ });
+ });
+});
diff --git a/sdk/tests/sceneManager.test.ts b/sdk/tests/sceneManager.test.ts
new file mode 100644
index 000000000..c7e7ab32b
--- /dev/null
+++ b/sdk/tests/sceneManager.test.ts
@@ -0,0 +1,901 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+vi.mock('../src/scene', () => ({
+ loadSceneWithAssets: vi.fn().mockResolvedValue(new Map()),
+}));
+
+vi.mock('../src/customDraw', () => ({
+ registerDrawCallback: vi.fn(),
+ unregisterDrawCallback: vi.fn(),
+}));
+
+vi.mock('../src/postprocess', () => ({
+ PostProcess: {
+ addPass: vi.fn().mockReturnValue(0),
+ removePass: vi.fn(),
+ setEnabled: vi.fn(),
+ },
+}));
+
+vi.mock('../src/material', () => ({
+ Material: {
+ release: vi.fn(),
+ createShader: vi.fn(),
+ },
+ defineResource: vi.fn(),
+}));
+
+vi.mock('../src/draw', () => ({
+ Draw: {
+ setLayer: vi.fn(),
+ setDepth: vi.fn(),
+ rect: vi.fn(),
+ },
+}));
+
+vi.mock('../src/resource', () => ({
+ defineResource: vi.fn((_init: unknown, name?: string) => ({
+ _id: Symbol(name ?? 'Resource'),
+ _name: name ?? 'Resource',
+ _default: _init,
+ })),
+}));
+
+vi.mock('../src/component', () => ({
+ SceneOwner: Symbol('SceneOwner'),
+ Sprite: Symbol('Sprite'),
+ SpineAnimation: Symbol('SpineAnimation'),
+ BitmapText: Symbol('BitmapText'),
+}));
+
+vi.mock('../src/asset/AssetPlugin', () => ({
+ Assets: Symbol('Assets'),
+}));
+
+vi.mock('../src/defaults', () => ({
+ RuntimeConfig: {
+ sceneTransitionDuration: 0.5,
+ sceneTransitionColor: { r: 0, g: 0, b: 0, a: 1 },
+ },
+}));
+
+import { SceneManagerState, wrapSceneSystem } from '../src/sceneManager';
+import { SceneOwner, Sprite, SpineAnimation, BitmapText } from '../src/component';
+import { loadSceneWithAssets } from '../src/scene';
+import { registerDrawCallback, unregisterDrawCallback } from '../src/customDraw';
+import { PostProcess } from '../src/postprocess';
+import { Material } from '../src/material';
+
+function createMockApp() {
+ const entities = new Map<number, Map<symbol, any>>();
+ let nextEntity = 1;
+ const resources = new Map<any, any>();
+
+ const world = {
+ spawn: vi.fn(() => {
+ const e = nextEntity++;
+ entities.set(e, new Map());
+ return e;
+ }),
+ despawn: vi.fn((e: number) => entities.delete(e)),
+ valid: vi.fn((e: number) => entities.has(e)),
+ has: vi.fn((e: number, comp: symbol) => entities.get(e)?.has(comp) ?? false),
+ get: vi.fn((e: number, comp: symbol) => entities.get(e)?.get(comp)),
+ insert: vi.fn((e: number, comp: symbol, data: any) => {
+ if (!entities.has(e)) entities.set(e, new Map());
+ entities.get(e)!.set(comp, data);
+ }),
+ };
+
+ return {
+ world,
+ hasResource: vi.fn((key: any) => resources.has(key)),
+ getResource: vi.fn((key: any) => resources.get(key)),
+ addSystemToSchedule: vi.fn(),
+ _entities: entities,
+ _resources: resources,
+ };
+}
+
+function makeSceneData() {
+ return {
+ version: '1.0',
+ name: 'TestScene',
+ entities: [],
+ };
+}
+
+describe('SceneManager', () => {
+ let app: ReturnType<typeof createMockApp>;
+ let manager: SceneManagerState;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ app = createMockApp();
+ manager = new SceneManagerState(app as any);
+ });
+
+ // =========================================================================
+ // Registration & initial scene
+ // =========================================================================
+ describe('registration & initial scene', () => {
+ it('register stores config by name', () => {
+ manager.register({ name: 'main' });
+ expect(manager.getScene('main')).toBeNull();
+ // Does not throw when loading a registered scene
+ expect(() => manager.register({ name: 'main' })).not.toThrow();
+ });
+
+ it('setInitial / getInitial', () => {
+ expect(manager.getInitial()).toBeNull();
+ manager.setInitial('main');
+ expect(manager.getInitial()).toBe('main');
+ });
+
+ it('load unregistered scene throws "not registered"', async () => {
+ await expect(manager.load('unknown')).rejects.toThrow('not registered');
+ });
+
+ it('loadAdditive unregistered scene throws "not registered"', async () => {
+ await expect(manager.loadAdditive('unknown')).rejects.toThrow('not registered');
+ });
+ });
+
+ // =========================================================================
+ // Scene loading
+ // =========================================================================
+ describe('scene loading', () => {
+ it('load() with inline data sets status=running and activeScene', async () => {
+ manager.register({ name: 'level1', data: makeSceneData() });
+ const ctx = await manager.load('level1');
+ expect(ctx.name).toBe('level1');
+ expect(manager.getActive()).toBe('level1');
+ expect(manager.getSceneStatus('level1')).toBe('running');
+ });
+
+ it('load() with already-loaded scene returns existing context', async () => {
+ manager.register({ name: 'level1', data: makeSceneData() });
+ const ctx1 = await manager.load('level1');
+ const ctx2 = await manager.load('level1');
+ expect(ctx2).toBe(ctx1);
+ });
+
+ it('load() adds entities via SceneOwner when loadSceneWithAssets returns entities', async () => {
+ const entityMap = new Map<number, number>();
+ entityMap.set(100, 1);
+ entityMap.set(200, 2);
+ vi.mocked(loadSceneWithAssets).mockResolvedValueOnce(entityMap);
+
+ // Pre-create the entities in the mock world so valid() returns true
+ app._entities.set(1, new Map());
+ app._entities.set(2, new Map());
+
+ manager.register({ name: 'level1', data: makeSceneData() });
+ const ctx = await manager.load('level1');
+ expect(ctx.entities.size).toBe(2);
+ expect(app.world.insert).toHaveBeenCalledWith(
+ 1, SceneOwner, { scene: 'level1', persistent: false }
+ );
+ });
+
+ it('loadAdditive() adds to additive scenes', async () => {
+ manager.register({ name: 'ui', data: makeSceneData() });
+ manager.register({ name: 'main', data: makeSceneData() });
+ await manager.load('main');
+ await manager.loadAdditive('ui');
+
+ expect(manager.isLoaded('ui')).toBe(true);
+ expect(manager.getLoaded()).toContain('ui');
+ });
+
+ it('loadAdditive() for already-loaded scene reuses instance', async () => {
+ manager.register({ name: 'ui', data: makeSceneData() });
+ const ctx1 = await manager.loadAdditive('ui');
+ const ctx2 = await manager.loadAdditive('ui');
+ expect(ctx2).toBe(ctx1);
+ });
+
+ it('duplicate load() while loading returns same promise', async () => {
+ let resolveLoad!: (val: Map<number, number>) => void;
+ vi.mocked(loadSceneWithAssets).mockReturnValueOnce(
+ new Promise(r => { resolveLoad = r; })
+ );
+
+ manager.register({ name: 'level1', data: makeSceneData() });
+ const p1 = manager.load('level1');
+ const p2 = manager.load('level1');
+
+ resolveLoad(new Map());
+ const [ctx1, ctx2] = await Promise.all([p1, p2]);
+ expect(ctx1).toBe(ctx2);
+ });
+
+ it('load() calls setup callback', async () => {
+ const setup = vi.fn();
+ manager.register({ name: 'level1', data: makeSceneData(), setup });
+ await manager.load('level1');
+ expect(setup).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ // =========================================================================
+ // Scene unloading
+ // =========================================================================
+ describe('scene unloading', () => {
+ it('unload() despawns entities', async () => {
+ const entityMap = new Map([[100, 1]]);
+ vi.mocked(loadSceneWithAssets).mockResolvedValueOnce(entityMap);
+ app._entities.set(1, new Map());
+
+ manager.register({ name: 'level1', data: makeSceneData() });
+ await manager.load('level1');
+
+ await manager.unload('level1');
+ expect(app.world.despawn).toHaveBeenCalledWith(1);
+ });
+
+ it('unload() keeps persistent entities by default', async () => {
+ const entityMap = new Map([[100, 1], [200, 2]]);
+ vi.mocked(loadSceneWithAssets).mockResolvedValueOnce(entityMap);
+ app._entities.set(1, new Map());
+ app._entities.set(2, new Map());
+
+ manager.register({ name: 'level1', data: makeSceneData() });
+ await manager.load('level1');
+
+ // Mark entity 1 as persistent
+ const ownerData1 = app._entities.get(1)!.get(SceneOwner);
+ ownerData1.persistent = true;
+ app._entities.get(1)!.set(SceneOwner, ownerData1);
+
+ await manager.unload('level1');
+ // Entity 1 should NOT be despawned (persistent)
+ expect(app.world.despawn).not.toHaveBeenCalledWith(1);
+ // Entity 2 should be despawned (not persistent)
+ expect(app.world.despawn).toHaveBeenCalledWith(2);
+ });
+
+ it('unload() with keepPersistent=false despawns all entities', async () => {
+ const entityMap = new Map([[100, 1]]);
+ vi.mocked(loadSceneWithAssets).mockResolvedValueOnce(entityMap);
+ app._entities.set(1, new Map());
+
+ manager.register({ name: 'level1', data: makeSceneData() });
+ await manager.load('level1');
+
+ // Mark as persistent
+ const ownerData = app._entities.get(1)!.get(SceneOwner);
+ ownerData.persistent = true;
+ app._entities.get(1)!.set(SceneOwner, ownerData);
+
+ await manager.unload('level1', { keepPersistent: false });
+ expect(app.world.despawn).toHaveBeenCalledWith(1);
+ });
+
+ it('unload() cleans up draw callbacks', async () => {
+ manager.register({ name: 'level1', data: makeSceneData() });
+ const ctx = await manager.load('level1');
+
+ ctx.registerDrawCallback('myDraw', () => {});
+ await manager.unload('level1');
+ expect(unregisterDrawCallback).toHaveBeenCalledWith('myDraw');
+ });
+
+ it('unload() removes postprocess passes', async () => {
+ manager.register({ name: 'level1', data: makeSceneData() });
+ const ctx = await manager.load('level1');
+
+ ctx.addPostProcessPass('bloom', 42 as any);
+ await manager.unload('level1');
+ expect(PostProcess.removePass).toHaveBeenCalledWith('bloom');
+ });
+
+ it('unload() releases material handles from loadedAssets', async () => {
+ vi.mocked(loadSceneWithAssets).mockImplementationOnce(
+ async (_world, _data, options) => {
+ if (options?.collectAssets) {
+ options.collectAssets.materialHandles.add(10);
+ options.collectAssets.materialHandles.add(20);
+ }
+ return new Map();
+ }
+ );
+
+ manager.register({ name: 'level1', data: makeSceneData() });
+ await manager.load('level1');
+ await manager.unload('level1');
+
+ expect(Material.release).toHaveBeenCalledWith(10);
+ expect(Material.release).toHaveBeenCalledWith(20);
+ });
+
+ it('unload() clears activeScene if unloaded scene was active', async () => {
+ manager.register({ name: 'level1', data: makeSceneData() });
+ await manager.load('level1');
+ expect(manager.getActive()).toBe('level1');
+
+ await manager.unload('level1');
+ expect(manager.getActive()).toBeNull();
+ });
+
+ it('unload() calls cleanup callback', async () => {
+ const cleanup = vi.fn();
+ manager.register({ name: 'level1', data: makeSceneData(), cleanup });
+ await manager.load('level1');
+ await manager.unload('level1');
+ expect(cleanup).toHaveBeenCalledTimes(1);
+ });
+
+ it('unload() non-existent scene is a no-op', async () => {
+ await expect(manager.unload('nonexistent')).resolves.toBeUndefined();
+ });
+ });
+
+ // =========================================================================
+ // Scene switching
+ // =========================================================================
+ describe('scene switching', () => {
+ it('switchTo() unloads old scene and loads new scene', async () => {
+ manager.register({ name: 'level1', data: makeSceneData() });
+ manager.register({ name: 'level2', data: makeSceneData() });
+
+ await manager.load('level1');
+ expect(manager.getActive()).toBe('level1');
+
+ await manager.switchTo('level2');
+ expect(manager.getActive()).toBe('level2');
+ expect(manager.isLoaded('level1')).toBe(false);
+ });
+
+ it('switchTo() during transition is ignored', async () => {
+ manager.register({ name: 'level1', data: makeSceneData() });
+ manager.register({ name: 'level2', data: makeSceneData() });
+ manager.register({ name: 'level3', data: makeSceneData() });
+
+ await manager.load('level1');
+
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+
+ // Start a switch that won't resolve immediately
+ let resolveLoad!: (val: Map<number, number>) => void;
+ vi.mocked(loadSceneWithAssets).mockReturnValueOnce(
+ new Promise(r => { resolveLoad = r; })
+ );
+ const p1 = manager.switchTo('level2');
+
+ // This should be ignored
+ await manager.switchTo('level3');
+ expect(warnSpy).toHaveBeenCalled();
+
+ resolveLoad(new Map());
+ await p1;
+ expect(manager.getActive()).toBe('level2');
+ warnSpy.mockRestore();
+ });
+
+ it('switchTo() with transition=none does direct switch', async () => {
+ manager.register({ name: 'level1', data: makeSceneData() });
+ manager.register({ name: 'level2', data: makeSceneData() });
+ await manager.load('level1');
+
+ await manager.switchTo('level2', { transition: 'none' });
+ expect(manager.getActive()).toBe('level2');
+ expect(registerDrawCallback).not.toHaveBeenCalledWith(
+ '__scene_transition_overlay__',
+ expect.any(Function)
+ );
+ });
+
+ it('switching_ is reset even if load fails', async () => {
+ manager.register({ name: 'level1', data: makeSceneData() });
+ await manager.load('level1');
+
+ // Attempt to switch to an unregistered scene (will throw)
+ await expect(manager.switchTo('nonexistent')).rejects.toThrow('not registered');
+
+ // switching_ should be reset, so another switch should work
+ manager.register({ name: 'level2', data: makeSceneData() });
+ await manager.switchTo('level2');
+ expect(manager.getActive()).toBe('level2');
+ });
+
+ it('switchTo() to same scene as active does not unload', async () => {
+ manager.register({ name: 'level1', data: makeSceneData() });
+ await manager.load('level1');
+
+ await manager.switchTo('level1');
+ expect(manager.getActive()).toBe('level1');
+ expect(manager.isLoaded('level1')).toBe(true);
+ });
+ });
+
+ // =========================================================================
+ // Pause / Resume
+ // =========================================================================
+ describe('pause / resume', () => {
+ it('pause() sets status=paused and adds to pausedScenes', async () => {
+ manager.register({ name: 'level1', data: makeSceneData() });
+ await manager.load('level1');
+
+ manager.pause('level1');
+ expect(manager.getSceneStatus('level1')).toBe('paused');
+ expect(manager.isPaused('level1')).toBe(true);
+ });
+
+ it('pause() on non-running scene is no-op', async () => {
+ manager.register({ name: 'level1', data: makeSceneData() });
+ await manager.load('level1');
+
+ manager.pause('level1');
+ expect(manager.isPaused('level1')).toBe(true);
+
+ // Pause again should be no-op (already paused, not 'running')
+ manager.pause('level1');
+ expect(manager.isPaused('level1')).toBe(true);
+ });
+
+ it('pause() on non-loaded scene is no-op', () => {
+ manager.pause('nonexistent');
+ expect(manager.isPaused('nonexistent')).toBe(false);
+ });
+
+ it('resume() sets status=running and removes from pausedScenes', async () => {
+ manager.register({ name: 'level1', data: makeSceneData() });
+ await manager.load('level1');
+
+ manager.pause('level1');
+ manager.resume('level1');
+ expect(manager.getSceneStatus('level1')).toBe('running');
+ expect(manager.isPaused('level1')).toBe(false);
+ });
+
+ it('resume() on non-paused scene is no-op', async () => {
+ manager.register({ name: 'level1', data: makeSceneData() });
+ await manager.load('level1');
+ // Already running, resume should be no-op
+ manager.resume('level1');
+ expect(manager.getSceneStatus('level1')).toBe('running');
+ });
+
+ it('pause() disables postprocess passes', async () => {
+ manager.register({ name: 'level1', data: makeSceneData() });
+ const ctx = await manager.load('level1');
+ ctx.addPostProcessPass('bloom', 1 as any);
+
+ manager.pause('level1');
+ expect(PostProcess.setEnabled).toHaveBeenCalledWith('bloom', false);
+ });
+
+ it('resume() re-enables postprocess passes', async () => {
+ manager.register({ name: 'level1', data: makeSceneData() });
+ const ctx = await manager.load('level1');
+ ctx.addPostProcessPass('bloom', 1 as any);
+
+ manager.pause('level1');
+ vi.mocked(PostProcess.setEnabled).mockClear();
+
+ manager.resume('level1');
+ expect(PostProcess.setEnabled).toHaveBeenCalledWith('bloom', true);
+ });
+ });
+
+ // =========================================================================
+ // Sleep / Wake
+ // =========================================================================
+ describe('sleep / wake', () => {
+ function setupEntityWithComponents(entityId: number) {
+ const entityComponents = new Map<symbol, any>();
+ entityComponents.set(Sprite, { color: { r: 1, g: 1, b: 1, a: 0.8 } });
+ entityComponents.set(SpineAnimation, { color: { r: 1, g: 1, b: 1, a: 0.6 } });
+ entityComponents.set(BitmapText, { color: { r: 1, g: 1, b: 1, a: 0.9 } });
+ app._entities.set(entityId, entityComponents);
+ }
+
+ it('sleep() sets status=sleeping and saves entity alphas', async () => {
+ const entityMap = new Map([[100, 1]]);
+ vi.mocked(loadSceneWithAssets).mockResolvedValueOnce(entityMap);
+ setupEntityWithComponents(1);
+
+ manager.register({ name: 'level1', data: makeSceneData() });
+ await manager.load('level1');
+
+ manager.sleep('level1');
+ expect(manager.getSceneStatus('level1')).toBe('sleeping');
+ expect(manager.isSleeping('level1')).toBe(true);
+
+ // Alpha should be set to 0
+ const sprite = app._entities.get(1)!.get(Sprite);
+ expect(sprite.color.a).toBe(0);
+ });
+
+ it('sleep() only on running scenes', async () => {
+ manager.register({ name: 'level1', data: makeSceneData() });
+ await manager.load('level1');
+ manager.pause('level1');
+
+ manager.sleep('level1');
+ // Should still be paused, not sleeping
+ expect(manager.getSceneStatus('level1')).toBe('paused');
+ expect(manager.isSleeping('level1')).toBe(false);
+ });
+
+ it('sleep() on non-loaded scene is no-op', () => {
+ manager.sleep('nonexistent');
+ expect(manager.isSleeping('nonexistent')).toBe(false);
+ });
+
+ it('wake() restores alphas from savedAlphas', async () => {
+ const entityMap = new Map([[100, 1]]);
+ vi.mocked(loadSceneWithAssets).mockResolvedValueOnce(entityMap);
+ setupEntityWithComponents(1);
+
+ manager.register({ name: 'level1', data: makeSceneData() });
+ await manager.load('level1');
+
+ manager.sleep('level1');
+ manager.wake('level1');
+
+ expect(manager.getSceneStatus('level1')).toBe('running');
+ expect(manager.isSleeping('level1')).toBe(false);
+
+ const sprite = app._entities.get(1)!.get(Sprite);
+ expect(sprite.color.a).toBe(0.8);
+
+ const spine = app._entities.get(1)!.get(SpineAnimation);
+ expect(spine.color.a).toBe(0.6);
+
+ const bt = app._entities.get(1)!.get(BitmapText);
+ expect(bt.color.a).toBe(0.9);
+ });
+
+ it('wake() only on sleeping scenes', async () => {
+ manager.register({ name: 'level1', data: makeSceneData() });
+ await manager.load('level1');
+ // Running scene, wake should be no-op
+ manager.wake('level1');
+ expect(manager.getSceneStatus('level1')).toBe('running');
+ });
+
+ it('wake() disables postprocess passes on sleep and re-enables on wake', async () => {
+ manager.register({ name: 'level1', data: makeSceneData() });
+ const ctx = await manager.load('level1');
+ ctx.addPostProcessPass('blur', 2 as any);
+
+ manager.sleep('level1');
+ expect(PostProcess.setEnabled).toHaveBeenCalledWith('blur', false);
+
+ vi.mocked(PostProcess.setEnabled).mockClear();
+ manager.wake('level1');
+ expect(PostProcess.setEnabled).toHaveBeenCalledWith('blur', true);
+ });
+ });
+
+ // =========================================================================
+ // Query methods
+ // =========================================================================
+ describe('query methods', () => {
+ it('getActive() returns active scene name', async () => {
+ expect(manager.getActive()).toBeNull();
+ manager.register({ name: 'level1', data: makeSceneData() });
+ await manager.load('level1');
+ expect(manager.getActive()).toBe('level1');
+ });
+
+ it('getActiveScenes() returns all running scenes', async () => {
+ manager.register({ name: 'main', data: makeSceneData() });
+ manager.register({ name: 'ui', data: makeSceneData() });
+
+ await manager.load('main');
+ await manager.loadAdditive('ui');
+
+ const active = manager.getActiveScenes();
+ expect(active).toContain('main');
+ expect(active).toContain('ui');
+ expect(active).toHaveLength(2);
+ });
+
+ it('getActiveScenes() excludes paused scenes', async () => {
+ manager.register({ name: 'main', data: makeSceneData() });
+ manager.register({ name: 'ui', data: makeSceneData() });
+
+ await manager.load('main');
+ await manager.loadAdditive('ui');
+
+ manager.pause('ui');
+ const active = manager.getActiveScenes();
+ expect(active).toContain('main');
+ expect(active).not.toContain('ui');
+ });
+
+ it('getLoaded() returns all loaded scene names', async () => {
+ manager.register({ name: 'level1', data: makeSceneData() });
+ manager.register({ name: 'level2', data: makeSceneData() });
+
+ await manager.load('level1');
+ await manager.loadAdditive('level2');
+
+ const loaded = manager.getLoaded();
+ expect(loaded).toContain('level1');
+ expect(loaded).toContain('level2');
+ });
+
+ it('getLoadOrder() returns load order', async () => {
+ manager.register({ name: 'level1', data: makeSceneData() });
+ manager.register({ name: 'level2', data: makeSceneData() });
+
+ await manager.load('level1');
+ await manager.loadAdditive('level2');
+
+ expect(manager.getLoadOrder()).toEqual(['level1', 'level2']);
+ });
+
+ it('bringToTop() moves scene to end of loadOrder', async () => {
+ manager.register({ name: 'level1', data: makeSceneData() });
+ manager.register({ name: 'level2', data: makeSceneData() });
+ manager.register({ name: 'level3', data: makeSceneData() });
+
+ await manager.load('level1');
+ await manager.loadAdditive('level2');
+ await manager.loadAdditive('level3');
+
+ manager.bringToTop('level1');
+ expect(manager.getLoadOrder()).toEqual(['level2', 'level3', 'level1']);
+ });
+
+ it('bringToTop() on non-loaded scene is no-op', () => {
+ manager.bringToTop('nonexistent');
+ expect(manager.getLoadOrder()).toEqual([]);
+ });
+
+ it('getScene() returns context or null', async () => {
+ expect(manager.getScene('nonexistent')).toBeNull();
+
+ manager.register({ name: 'level1', data: makeSceneData() });
+ await manager.load('level1');
+ expect(manager.getScene('level1')).not.toBeNull();
+ });
+
+ it('getSceneStatus() returns status or null', async () => {
+ expect(manager.getSceneStatus('nonexistent')).toBeNull();
+
+ manager.register({ name: 'level1', data: makeSceneData() });
+ await manager.load('level1');
+ expect(manager.getSceneStatus('level1')).toBe('running');
+ });
+
+ it('isActive() returns correct value', async () => {
+ manager.register({ name: 'level1', data: makeSceneData() });
+ expect(manager.isActive('level1')).toBe(false);
+ await manager.load('level1');
+ expect(manager.isActive('level1')).toBe(true);
+ });
+
+ it('isLoaded() returns correct value', async () => {
+ manager.register({ name: 'level1', data: makeSceneData() });
+ expect(manager.isLoaded('level1')).toBe(false);
+ await manager.load('level1');
+ expect(manager.isLoaded('level1')).toBe(true);
+ });
+ });
+
+ // =========================================================================
+ // wrapSceneSystem
+ // =========================================================================
+ describe('wrapSceneSystem', () => {
+ it('wrapped system only runs when scene status is running', async () => {
+ manager.register({ name: 'level1', data: makeSceneData() });
+ await manager.load('level1');
+
+ const innerFn = vi.fn();
+ const system = {
+ _id: Symbol('test'),
+ _name: 'testSystem',
+ _params: [],
+ _fn: innerFn,
+ };
+
+ // We need to set up getResource to return the manager
+ const { SceneManager } = await import('../src/sceneManager');
+ app.getResource.mockImplementation((key: any) => {
+ if (key === SceneManager || key?._name === 'SceneManager') return manager;
+ return undefined;
+ });
+
+ const wrapped = wrapSceneSystem(app as any, 'level1', system as any);
+ (wrapped._fn as Function)();
+ expect(innerFn).toHaveBeenCalledTimes(1);
+ });
+
+ it('wrapped system is skipped when scene is paused', async () => {
+ manager.register({ name: 'level1', data: makeSceneData() });
+ await manager.load('level1');
+ manager.pause('level1');
+
+ const innerFn = vi.fn();
+ const system = {
+ _id: Symbol('test'),
+ _name: 'testSystem',
+ _params: [],
+ _fn: innerFn,
+ };
+
+ const { SceneManager } = await import('../src/sceneManager');
+ app.getResource.mockImplementation((key: any) => {
+ if (key === SceneManager || key?._name === 'SceneManager') return manager;
+ return undefined;
+ });
+
+ const wrapped = wrapSceneSystem(app as any, 'level1', system as any);
+ (wrapped._fn as Function)();
+ expect(innerFn).not.toHaveBeenCalled();
+ });
+
+ it('wrapped system name includes scene name', () => {
+ const system = {
+ _id: Symbol('test'),
+ _name: 'movement',
+ _params: [],
+ _fn: vi.fn(),
+ };
+
+ const wrapped = wrapSceneSystem(app as any, 'level1', system as any);
+ expect(wrapped._name).toBe('movement@level1');
+ });
+ });
+
+ // =========================================================================
+ // Transition (fade)
+ // =========================================================================
+ describe('transition (fade)', () => {
+ it('isTransitioning() returns false initially', () => {
+ expect(manager.isTransitioning()).toBe(false);
+ });
+
+ it('switchTo with fade starts transition', async () => {
+ manager.register({ name: 'level1', data: makeSceneData() });
+ manager.register({ name: 'level2', data: makeSceneData() });
+ await manager.load('level1');
+
+ const onStart = vi.fn();
+ manager.switchTo('level2', { transition: 'fade', duration: 1.0, onStart });
+
+ // Allow microtask to run
+ await Promise.resolve();
+
+ expect(manager.isTransitioning()).toBe(true);
+ expect(onStart).toHaveBeenCalled();
+ expect(registerDrawCallback).toHaveBeenCalledWith(
+ '__scene_transition_overlay__',
+ expect.any(Function)
+ );
+ });
+
+ it('updateTransition with dt progresses elapsed', async () => {
+ manager.register({ name: 'level1', data: makeSceneData() });
+ manager.register({ name: 'level2', data: makeSceneData() });
+ await manager.load('level1');
+
+ manager.switchTo('level2', { transition: 'fade', duration: 1.0 });
+ await Promise.resolve();
+
+ expect(manager.isTransitioning()).toBe(true);
+
+ // Progress but not past half duration
+ manager.updateTransition(0.2);
+ expect(manager.isTransitioning()).toBe(true);
+ });
+
+ it('fade-out completes at half duration and switches to fade-in', async () => {
+ manager.register({ name: 'level1', data: makeSceneData() });
+ manager.register({ name: 'level2', data: makeSceneData() });
+ await manager.load('level1');
+
+ manager.switchTo('level2', { transition: 'fade', duration: 1.0 });
+ await Promise.resolve();
+
+ // Advance past half (0.5)
+ manager.updateTransition(0.6);
+
+ // Allow async scene switch to complete
+ await new Promise(r => setTimeout(r, 10));
+
+ // Should still be transitioning (in fade-in phase now)
+ // If the fade-in hasn't completed, it should still be transitioning
+ // The elapsed was reset to 0 for fade-in, then 0 < 0.5 so still transitioning
+ expect(manager.isTransitioning()).toBe(true);
+ });
+
+ it('fade-in completes and resolves transition', async () => {
+ manager.register({ name: 'level1', data: makeSceneData() });
+ manager.register({ name: 'level2', data: makeSceneData() });
+ await manager.load('level1');
+
+ const onComplete = vi.fn();
+ const promise = manager.switchTo('level2', {
+ transition: 'fade',
+ duration: 1.0,
+ onComplete,
+ });
+ await Promise.resolve();
+
+ // Complete fade-out (half = 0.5)
+ manager.updateTransition(0.6);
+ await new Promise(r => setTimeout(r, 10));
+
+ // Complete fade-in (half = 0.5)
+ manager.updateTransition(0.6);
+
+ expect(manager.isTransitioning()).toBe(false);
+ expect(onComplete).toHaveBeenCalled();
+ expect(unregisterDrawCallback).toHaveBeenCalledWith('__scene_transition_overlay__');
+
+ await promise;
+ });
+
+ it('switchTo with fade is ignored during active transition', async () => {
+ manager.register({ name: 'level1', data: makeSceneData() });
+ manager.register({ name: 'level2', data: makeSceneData() });
+ manager.register({ name: 'level3', data: makeSceneData() });
+ await manager.load('level1');
+
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+
+ manager.switchTo('level2', { transition: 'fade', duration: 1.0 });
+ await Promise.resolve();
+
+ // Second switch should be ignored
+ await manager.switchTo('level3');
+ expect(warnSpy).toHaveBeenCalled();
+ warnSpy.mockRestore();
+ });
+ });
+
+ // =========================================================================
+ // SceneContext methods
+ // =========================================================================
+ describe('SceneContext', () => {
+ it('spawn() creates entity with SceneOwner', async () => {
+ manager.register({ name: 'level1', data: makeSceneData() });
+ const ctx = await manager.load('level1');
+
+ const entity = ctx.spawn();
+ expect(app.world.spawn).toHaveBeenCalled();
+ expect(ctx.entities.has(entity)).toBe(true);
+ expect(app.world.insert).toHaveBeenCalledWith(
+ entity, SceneOwner, { scene: 'level1', persistent: false }
+ );
+ });
+
+ it('despawn() removes entity from context', async () => {
+ manager.register({ name: 'level1', data: makeSceneData() });
+ const ctx = await manager.load('level1');
+
+ const entity = ctx.spawn();
+ ctx.despawn(entity);
+ expect(app.world.despawn).toHaveBeenCalledWith(entity);
+ expect(ctx.entities.has(entity)).toBe(false);
+ });
+
+ it('setPersistent() updates SceneOwner data', async () => {
+ manager.register({ name: 'level1', data: makeSceneData() });
+ const ctx = await manager.load('level1');
+
+ const entity = ctx.spawn();
+ ctx.setPersistent(entity, true);
+
+ const lastInsertCall = app.world.insert.mock.calls[
+ app.world.insert.mock.calls.length - 1
+ ];
+ expect(lastInsertCall[2].persistent).toBe(true);
+ });
+
+ it('removePostProcessPass() removes pass from instance tracking', async () => {
+ manager.register({ name: 'level1', data: makeSceneData() });
+ const ctx = await manager.load('level1');
+
+ ctx.addPostProcessPass('bloom', 1 as any);
+ ctx.removePostProcessPass('bloom');
+ expect(PostProcess.removePass).toHaveBeenCalledWith('bloom');
+ });
+ });
+});
diff --git a/sdk/tests/uiLayout.test.ts b/sdk/tests/uiLayout.test.ts
new file mode 100644
index 000000000..05e0a6503
--- /dev/null
+++ b/sdk/tests/uiLayout.test.ts
@@ -0,0 +1,517 @@
+import { describe, it, expect } from 'vitest';
+import { computeUIRectLayout } from '../src/ui/uiLayout';
+import type { LayoutRect, LayoutResult } from '../src/ui/uiLayout';
+
+const PARENT: LayoutRect = { left: 0, bottom: 0, right: 800, top: 600 };
+
+function noOffset() {
+ return { x: 0, y: 0 };
+}
+
+describe('computeUIRectLayout', () => {
+ describe('point anchor (anchorMin === anchorMax)', () => {
+ it('centers element with default pivot at center anchor', () => {
+ const r = computeUIRectLayout(
+ { x: 0.5, y: 0.5 },
+ { x: 0.5, y: 0.5 },
+ noOffset(),
+ noOffset(),
+ { x: 100, y: 80 },
+ PARENT,
+ );
+ expect(r.width).toBe(100);
+ expect(r.height).toBe(80);
+ expect(r.originX).toBe(400);
+ expect(r.originY).toBe(300);
+ expect(r.rect.left).toBe(350);
+ expect(r.rect.right).toBe(450);
+ expect(r.rect.bottom).toBe(260);
+ expect(r.rect.top).toBe(340);
+ });
+
+ it('positions at top-left with anchor (0, 1)', () => {
+ const r = computeUIRectLayout(
+ { x: 0, y: 1 },
+ { x: 0, y: 1 },
+ noOffset(),
+ noOffset(),
+ { x: 100, y: 80 },
+ PARENT,
+ );
+ // aLeft=0, aBottom=600
+ // myLeft = 0 + 0 - 100*0.5 = -50, myRight = 50
+ // myBottom = 600 + 0 - 80*0.5 = 560, myTop = 640
+ expect(r.originX).toBe(0);
+ expect(r.originY).toBe(600);
+ expect(r.rect.left).toBe(-50);
+ expect(r.rect.right).toBe(50);
+ expect(r.rect.bottom).toBe(560);
+ expect(r.rect.top).toBe(640);
+ });
+
+ it('positions at bottom-right with anchor (1, 0)', () => {
+ const r = computeUIRectLayout(
+ { x: 1, y: 0 },
+ { x: 1, y: 0 },
+ noOffset(),
+ noOffset(),
+ { x: 100, y: 80 },
+ PARENT,
+ );
+ // aLeft=800, aBottom=0
+ // myLeft = 800 - 50 = 750, myRight = 850
+ // myBottom = 0 - 40 = -40, myTop = 40
+ expect(r.originX).toBe(800);
+ expect(r.originY).toBe(0);
+ expect(r.rect.left).toBe(750);
+ expect(r.rect.right).toBe(850);
+ });
+
+ it('shifts position with offset', () => {
+ const r = computeUIRectLayout(
+ { x: 0.5, y: 0.5 },
+ { x: 0.5, y: 0.5 },
+ { x: 20, y: -10 },
+ noOffset(),
+ { x: 100, y: 80 },
+ PARENT,
+ );
+ // aLeft=400, aBottom=300
+ // myLeft = 400 + 20 - 50 = 370, myRight = 470
+ // myBottom = 300 + (-10) - 40 = 250, myTop = 330
+ expect(r.rect.left).toBe(370);
+ expect(r.rect.right).toBe(470);
+ expect(r.rect.bottom).toBe(250);
+ expect(r.rect.top).toBe(330);
+ expect(r.originX).toBe(420);
+ expect(r.originY).toBe(290);
+ });
+
+ it('places origin at bottom-left with pivot (0, 0)', () => {
+ const r = computeUIRectLayout(
+ { x: 0.5, y: 0.5 },
+ { x: 0.5, y: 0.5 },
+ noOffset(),
+ noOffset(),
+ { x: 100, y: 80 },
+ PARENT,
+ { x: 0, y: 0 },
+ );
+ // myLeft = 400 + 0 - 100*0 = 400, myRight = 500
+ // myBottom = 300 + 0 - 80*0 = 300, myTop = 380
+ expect(r.rect.left).toBe(400);
+ expect(r.rect.right).toBe(500);
+ expect(r.rect.bottom).toBe(300);
+ expect(r.rect.top).toBe(380);
+ expect(r.originX).toBe(400);
+ expect(r.originY).toBe(300);
+ });
+
+ it('places origin at top-right with pivot (1, 1)', () => {
+ const r = computeUIRectLayout(
+ { x: 0.5, y: 0.5 },
+ { x: 0.5, y: 0.5 },
+ noOffset(),
+ noOffset(),
+ { x: 100, y: 80 },
+ PARENT,
+ { x: 1, y: 1 },
+ );
+ // myLeft = 400 - 100 = 300, myRight = 400
+ // myBottom = 300 - 80 = 220, myTop = 300
+ expect(r.rect.left).toBe(300);
+ expect(r.rect.right).toBe(400);
+ expect(r.originX).toBe(400);
+ expect(r.originY).toBe(300);
+ });
+
+ it('allows element to extend beyond parent with large size', () => {
+ const r = computeUIRectLayout(
+ { x: 0.5, y: 0.5 },
+ { x: 0.5, y: 0.5 },
+ noOffset(),
+ noOffset(),
+ { x: 1600, y: 1200 },
+ PARENT,
+ );
+ expect(r.width).toBe(1600);
+ expect(r.height).toBe(1200);
+ expect(r.rect.left).toBe(-400);
+ expect(r.rect.right).toBe(1200);
+ });
+
+ it('produces zero-size rect with size (0, 0)', () => {
+ const r = computeUIRectLayout(
+ { x: 0.5, y: 0.5 },
+ { x: 0.5, y: 0.5 },
+ noOffset(),
+ noOffset(),
+ { x: 0, y: 0 },
+ PARENT,
+ );
+ expect(r.width).toBe(0);
+ expect(r.height).toBe(0);
+ expect(r.originX).toBe(400);
+ expect(r.originY).toBe(300);
+ expect(r.rect.left).toBe(400);
+ expect(r.rect.right).toBe(400);
+ });
+ });
+
+ describe('stretch anchor (anchorMin !== anchorMax)', () => {
+ it('fills parent exactly with full stretch and zero offsets', () => {
+ const r = computeUIRectLayout(
+ { x: 0, y: 0 },
+ { x: 1, y: 1 },
+ noOffset(),
+ noOffset(),
+ { x: 0, y: 0 },
+ PARENT,
+ );
+ expect(r.width).toBe(800);
+ expect(r.height).toBe(600);
+ expect(r.rect.left).toBe(0);
+ expect(r.rect.right).toBe(800);
+ expect(r.rect.bottom).toBe(0);
+ expect(r.rect.top).toBe(600);
+ expect(r.originX).toBe(400);
+ expect(r.originY).toBe(300);
+ });
+
+ it('insets from parent edges with positive offsets', () => {
+ const r = computeUIRectLayout(
+ { x: 0, y: 0 },
+ { x: 1, y: 1 },
+ { x: 10, y: 20 },
+ { x: -10, y: -20 },
+ { x: 0, y: 0 },
+ PARENT,
+ );
+ // myLeft = 0 + 10 = 10, myRight = 800 + (-10) = 790
+ // myBottom = 0 + 20 = 20, myTop = 600 + (-20) = 580
+ expect(r.rect.left).toBe(10);
+ expect(r.rect.right).toBe(790);
+ expect(r.rect.bottom).toBe(20);
+ expect(r.rect.top).toBe(580);
+ expect(r.width).toBe(780);
+ expect(r.height).toBe(560);
+ });
+
+ it('extends beyond parent with negative offsetMin and positive offsetMax', () => {
+ const r = computeUIRectLayout(
+ { x: 0, y: 0 },
+ { x: 1, y: 1 },
+ { x: -10, y: -10 },
+ { x: 10, y: 10 },
+ { x: 0, y: 0 },
+ PARENT,
+ );
+ expect(r.rect.left).toBe(-10);
+ expect(r.rect.right).toBe(810);
+ expect(r.rect.bottom).toBe(-10);
+ expect(r.rect.top).toBe(610);
+ expect(r.width).toBe(820);
+ expect(r.height).toBe(620);
+ });
+
+ it('stretches horizontally only when Y anchors match', () => {
+ const r = computeUIRectLayout(
+ { x: 0, y: 0.5 },
+ { x: 1, y: 0.5 },
+ noOffset(),
+ noOffset(),
+ { x: 0, y: 80 },
+ PARENT,
+ );
+ // X: stretch => myLeft=0, myRight=800
+ // Y: point => myBottom = 300 - 40 = 260, myTop = 340
+ expect(r.width).toBe(800);
+ expect(r.height).toBe(80);
+ expect(r.rect.left).toBe(0);
+ expect(r.rect.right).toBe(800);
+ expect(r.rect.bottom).toBe(260);
+ expect(r.rect.top).toBe(340);
+ });
+
+ it('stretches vertically only when X anchors match', () => {
+ const r = computeUIRectLayout(
+ { x: 0.5, y: 0 },
+ { x: 0.5, y: 1 },
+ noOffset(),
+ noOffset(),
+ { x: 100, y: 0 },
+ PARENT,
+ );
+ // X: point => myLeft = 400 - 50 = 350, myRight = 450
+ // Y: stretch => myBottom=0, myTop=600
+ expect(r.width).toBe(100);
+ expect(r.height).toBe(600);
+ expect(r.rect.left).toBe(350);
+ expect(r.rect.right).toBe(450);
+ expect(r.rect.bottom).toBe(0);
+ expect(r.rect.top).toBe(600);
+ });
+
+ it('computes partial stretch proportionally', () => {
+ const r = computeUIRectLayout(
+ { x: 0.25, y: 0.25 },
+ { x: 0.75, y: 0.75 },
+ noOffset(),
+ noOffset(),
+ { x: 0, y: 0 },
+ PARENT,
+ );
+ // aLeft=200, aRight=600, aBottom=150, aTop=450
+ expect(r.rect.left).toBe(200);
+ expect(r.rect.right).toBe(600);
+ expect(r.rect.bottom).toBe(150);
+ expect(r.rect.top).toBe(450);
+ expect(r.width).toBe(400);
+ expect(r.height).toBe(300);
+ expect(r.originX).toBe(400);
+ expect(r.originY).toBe(300);
+ });
+
+ it('applies margins via offsets with stretch', () => {
+ const r = computeUIRectLayout(
+ { x: 0, y: 0 },
+ { x: 1, y: 1 },
+ { x: 50, y: 30 },
+ { x: -50, y: -30 },
+ { x: 0, y: 0 },
+ PARENT,
+ );
+ expect(r.rect.left).toBe(50);
+ expect(r.rect.right).toBe(750);
+ expect(r.rect.bottom).toBe(30);
+ expect(r.rect.top).toBe(570);
+ expect(r.width).toBe(700);
+ expect(r.height).toBe(540);
+ });
+
+ it('uses pivot for origin calculation in stretch mode', () => {
+ const r = computeUIRectLayout(
+ { x: 0, y: 0 },
+ { x: 1, y: 1 },
+ noOffset(),
+ noOffset(),
+ { x: 0, y: 0 },
+ PARENT,
+ { x: 0, y: 0 },
+ );
+ expect(r.originX).toBe(0);
+ expect(r.originY).toBe(0);
+ });
+ });
+
+ describe('edge cases', () => {
+ it('returns zero-size result for zero-size parent', () => {
+ const zeroParent: LayoutRect = { left: 0, bottom: 0, right: 0, top: 0 };
+ const r = computeUIRectLayout(
+ { x: 0, y: 0 },
+ { x: 1, y: 1 },
+ noOffset(),
+ noOffset(),
+ { x: 0, y: 0 },
+ zeroParent,
+ );
+ expect(r.width).toBe(0);
+ expect(r.height).toBe(0);
+ expect(r.originX).toBe(0);
+ expect(r.originY).toBe(0);
+ });
+
+ it('clamps negative width/height to zero', () => {
+ // Stretch with offsets that invert left/right
+ const r = computeUIRectLayout(
+ { x: 0, y: 0 },
+ { x: 1, y: 1 },
+ { x: 500, y: 400 },
+ { x: -500, y: -400 },
+ { x: 0, y: 0 },
+ PARENT,
+ );
+ // myLeft = 500, myRight = 800-500 = 300 => inverted
+ // myBottom = 400, myTop = 600-400 = 200 => inverted
+ expect(r.width).toBe(0);
+ expect(r.height).toBe(0);
+ });
+
+ it('handles inverted anchors (anchorMin > anchorMax)', () => {
+ const r = computeUIRectLayout(
+ { x: 0.75, y: 0.75 },
+ { x: 0.25, y: 0.25 },
+ noOffset(),
+ noOffset(),
+ { x: 0, y: 0 },
+ PARENT,
+ );
+ // aLeft = 600, aRight = 200 => myLeft=600, myRight=200 => width clamped to 0
+ expect(r.width).toBe(0);
+ expect(r.height).toBe(0);
+ });
+
+ it('handles pivot at extremes (0 and 1) in point mode', () => {
+ const r0 = computeUIRectLayout(
+ { x: 0.5, y: 0.5 },
+ { x: 0.5, y: 0.5 },
+ noOffset(),
+ noOffset(),
+ { x: 200, y: 100 },
+ PARENT,
+ { x: 0, y: 1 },
+ );
+ // X: myLeft = 400 - 200*0 = 400, myRight = 600
+ // Y: myBottom = 300 - 100*1 = 200, myTop = 300
+ expect(r0.rect.left).toBe(400);
+ expect(r0.rect.right).toBe(600);
+ expect(r0.rect.bottom).toBe(200);
+ expect(r0.rect.top).toBe(300);
+ expect(r0.originX).toBe(400);
+ expect(r0.originY).toBe(300);
+ });
+
+ it('works with parent rect not starting at origin', () => {
+ const offsetParent: LayoutRect = { left: 100, bottom: 50, right: 500, top: 350 };
+ const r = computeUIRectLayout(
+ { x: 0.5, y: 0.5 },
+ { x: 0.5, y: 0.5 },
+ noOffset(),
+ noOffset(),
+ { x: 100, y: 80 },
+ offsetParent,
+ );
+ // parentW = 400, parentH = 300
+ // aLeft = 100 + 0.5*400 = 300
+ // aBottom = 50 + 0.5*300 = 200
+ // myLeft = 300 - 50 = 250, myRight = 350
+ // myBottom = 200 - 40 = 160, myTop = 240
+ expect(r.originX).toBe(300);
+ expect(r.originY).toBe(200);
+ expect(r.rect.left).toBe(250);
+ expect(r.rect.right).toBe(350);
+ expect(r.rect.bottom).toBe(160);
+ expect(r.rect.top).toBe(240);
+ });
+ });
+
+ describe('nested layout', () => {
+ it('child fills parent when using full stretch', () => {
+ const parent = computeUIRectLayout(
+ { x: 0, y: 0 },
+ { x: 1, y: 1 },
+ noOffset(),
+ noOffset(),
+ { x: 0, y: 0 },
+ PARENT,
+ );
+ const child = computeUIRectLayout(
+ { x: 0, y: 0 },
+ { x: 1, y: 1 },
+ noOffset(),
+ noOffset(),
+ { x: 0, y: 0 },
+ parent.rect,
+ );
+ expect(child.rect).toEqual(parent.rect);
+ expect(child.width).toBe(parent.width);
+ expect(child.height).toBe(parent.height);
+ });
+
+ it('centers child at half parent size', () => {
+ const parent = computeUIRectLayout(
+ { x: 0, y: 0 },
+ { x: 1, y: 1 },
+ noOffset(),
+ noOffset(),
+ { x: 0, y: 0 },
+ PARENT,
+ );
+ const child = computeUIRectLayout(
+ { x: 0.5, y: 0.5 },
+ { x: 0.5, y: 0.5 },
+ noOffset(),
+ noOffset(),
+ { x: 400, y: 300 },
+ parent.rect,
+ );
+ expect(child.width).toBe(400);
+ expect(child.height).toBe(300);
+ expect(child.originX).toBe(400);
+ expect(child.originY).toBe(300);
+ expect(child.rect.left).toBe(200);
+ expect(child.rect.right).toBe(600);
+ expect(child.rect.bottom).toBe(150);
+ expect(child.rect.top).toBe(450);
+ });
+
+ it('chains layout results through multiple nesting levels', () => {
+ const level1 = computeUIRectLayout(
+ { x: 0, y: 0 },
+ { x: 1, y: 1 },
+ { x: 20, y: 20 },
+ { x: -20, y: -20 },
+ { x: 0, y: 0 },
+ PARENT,
+ );
+ // level1: left=20, right=780, bottom=20, top=580 => 760x560
+ expect(level1.width).toBe(760);
+ expect(level1.height).toBe(560);
+
+ const level2 = computeUIRectLayout(
+ { x: 0, y: 0 },
+ { x: 1, y: 1 },
+ { x: 10, y: 10 },
+ { x: -10, y: -10 },
+ { x: 0, y: 0 },
+ level1.rect,
+ );
+ // level2: left=30, right=770, bottom=30, top=570 => 740x540
+ expect(level2.width).toBe(740);
+ expect(level2.height).toBe(540);
+ expect(level2.rect.left).toBe(30);
+ expect(level2.rect.right).toBe(770);
+ });
+
+ it('produces consistent results across three nesting levels', () => {
+ const l1 = computeUIRectLayout(
+ { x: 0.25, y: 0.25 },
+ { x: 0.75, y: 0.75 },
+ noOffset(),
+ noOffset(),
+ { x: 0, y: 0 },
+ PARENT,
+ );
+ // l1: 200..600 x 150..450 => 400x300
+ const l2 = computeUIRectLayout(
+ { x: 0.25, y: 0.25 },
+ { x: 0.75, y: 0.75 },
+ noOffset(),
+ noOffset(),
+ { x: 0, y: 0 },
+ l1.rect,
+ );
+ // l2 parentW=400, parentH=300
+ // aLeft=200+0.25*400=300, aRight=200+0.75*400=500
+ // aBottom=150+0.25*300=225, aTop=150+0.75*300=375
+ // => 300..500 x 225..375 => 200x150
+ expect(l2.width).toBe(200);
+ expect(l2.height).toBe(150);
+
+ const l3 = computeUIRectLayout(
+ { x: 0.25, y: 0.25 },
+ { x: 0.75, y: 0.75 },
+ noOffset(),
+ noOffset(),
+ { x: 0, y: 0 },
+ l2.rect,
+ );
+ // l3 parentW=200, parentH=150
+ // => 100x75
+ expect(l3.width).toBe(100);
+ expect(l3.height).toBe(75);
+ expect(l3.originX).toBe(400);
+ expect(l3.originY).toBe(300);
+ });
+ });
+});
diff --git a/sdk/tests/uiMath.test.ts b/sdk/tests/uiMath.test.ts
new file mode 100644
index 000000000..eb60d0455
--- /dev/null
+++ b/sdk/tests/uiMath.test.ts
@@ -0,0 +1,479 @@
+import { describe, it, expect } from 'vitest';
+import {
+ intersectRects,
+ invertMatrix4,
+ screenToWorld,
+ pointInWorldRect,
+ quaternionToAngle2D,
+ worldToScreen,
+ createInvVPCache,
+ pointInOBB,
+} from '../src/ui/uiMath';
+import type { ScreenRect } from '../src/ui/uiMath';
+
+// =============================================================================
+// Helpers
+// =============================================================================
+
+function identity4(): Float32Array {
+ const m = new Float32Array(16);
+ m[0] = 1; m[5] = 1; m[10] = 1; m[15] = 1;
+ return m;
+}
+
+function translation4(tx: number, ty: number, tz: number): Float32Array {
+ const m = identity4();
+ m[12] = tx; m[13] = ty; m[14] = tz;
+ return m;
+}
+
+function scale4(sx: number, sy: number, sz: number): Float32Array {
+ const m = new Float32Array(16);
+ m[0] = sx; m[5] = sy; m[10] = sz; m[15] = 1;
+ return m;
+}
+
+function rotationZ4(radians: number): Float32Array {
+ const c = Math.cos(radians);
+ const s = Math.sin(radians);
+ const m = identity4();
+ m[0] = c; m[1] = s;
+ m[4] = -s; m[5] = c;
+ return m;
+}
+
+function mulMat4(a: Float32Array, b: Float32Array): Float32Array {
+ const out = new Float32Array(16);
+ for (let i = 0; i < 4; i++) {
+ for (let j = 0; j < 4; j++) {
+ let sum = 0;
+ for (let k = 0; k < 4; k++) {
+ sum += a[i + k * 4] * b[k + j * 4];
+ }
+ out[i + j * 4] = sum;
+ }
+ }
+ return out;
+}
+
+function expectMatClose(a: Float32Array, b: Float32Array, precision = 5) {
+ expect(a.length).toBe(b.length);
+ for (let i = 0; i < a.length; i++) {
+ expect(a[i]).toBeCloseTo(b[i], precision);
+ }
+}
+
+function quaternionFromAngle(angle: number): { rz: number; rw: number } {
+ return { rz: Math.sin(angle / 2), rw: Math.cos(angle / 2) };
+}
+
+// =============================================================================
+// Tests
+// =============================================================================
+
+describe('uiMath', () => {
+
+ // =========================================================================
+ // intersectRects
+ // =========================================================================
+
+ describe('intersectRects', () => {
+ it('should return correct intersection for two overlapping rects', () => {
+ const a: ScreenRect = { x: 0, y: 0, w: 10, h: 10 };
+ const b: ScreenRect = { x: 5, y: 5, w: 10, h: 10 };
+ const r = intersectRects(a, b);
+ expect(r).toEqual({ x: 5, y: 5, w: 5, h: 5 });
+ });
+
+ it('should return zero-sized rect for non-overlapping rects', () => {
+ const a: ScreenRect = { x: 0, y: 0, w: 5, h: 5 };
+ const b: ScreenRect = { x: 10, y: 10, w: 5, h: 5 };
+ const r = intersectRects(a, b);
+ expect(r.w).toBe(0);
+ expect(r.h).toBe(0);
+ });
+
+ it('should return inner rect when one is fully inside another', () => {
+ const outer: ScreenRect = { x: 0, y: 0, w: 20, h: 20 };
+ const inner: ScreenRect = { x: 5, y: 5, w: 5, h: 5 };
+ const r = intersectRects(outer, inner);
+ expect(r).toEqual({ x: 5, y: 5, w: 5, h: 5 });
+ });
+
+ it('should return same rect for identical rects', () => {
+ const a: ScreenRect = { x: 3, y: 4, w: 10, h: 8 };
+ const r = intersectRects(a, a);
+ expect(r).toEqual(a);
+ });
+
+ it('should return zero width/height for edge-touching rects', () => {
+ const a: ScreenRect = { x: 0, y: 0, w: 5, h: 5 };
+ const b: ScreenRect = { x: 5, y: 0, w: 5, h: 5 };
+ const r = intersectRects(a, b);
+ expect(r.w).toBe(0);
+ });
+
+ it('should handle partial overlap on one axis only', () => {
+ const a: ScreenRect = { x: 0, y: 0, w: 10, h: 5 };
+ const b: ScreenRect = { x: 5, y: 10, w: 10, h: 5 };
+ const r = intersectRects(a, b);
+ expect(r.h).toBe(0);
+ });
+ });
+
+ // =========================================================================
+ // invertMatrix4
+ // =========================================================================
+
+ describe('invertMatrix4', () => {
+ it('should invert identity to identity', () => {
+ const id = identity4();
+ const inv = invertMatrix4(id);
+ expectMatClose(inv, id);
+ });
+
+ it('should invert translation to negative translation', () => {
+ const t = translation4(3, -7, 5);
+ const inv = invertMatrix4(t);
+ expect(inv[12]).toBeCloseTo(-3);
+ expect(inv[13]).toBeCloseTo(7);
+ expect(inv[14]).toBeCloseTo(-5);
+ });
+
+ it('should invert scale to reciprocal scale', () => {
+ const s = scale4(2, 4, 0.5);
+ const inv = invertMatrix4(s);
+ expect(inv[0]).toBeCloseTo(0.5);
+ expect(inv[5]).toBeCloseTo(0.25);
+ expect(inv[10]).toBeCloseTo(2);
+ });
+
+ it('should satisfy M * M^-1 = Identity', () => {
+ const m = translation4(5, -3, 1);
+ m[0] = 2; m[5] = 3;
+ const inv = invertMatrix4(m);
+ const product = mulMat4(m, inv);
+ expectMatClose(product, identity4());
+ });
+
+ it('should return zero-filled output for singular matrix', () => {
+ const singular = new Float32Array(16);
+ const inv = invertMatrix4(singular);
+ for (let i = 0; i < 16; i++) {
+ expect(inv[i]).toBe(0);
+ }
+ });
+
+ it('should write to custom result buffer', () => {
+ const id = identity4();
+ const buf = new Float32Array(16);
+ const result = invertMatrix4(id, buf);
+ expect(result).toBe(buf);
+ expectMatClose(buf, id);
+ });
+
+ it('should correctly invert a 2D rotation matrix', () => {
+ const angle = Math.PI / 3;
+ const rot = rotationZ4(angle);
+ const inv = invertMatrix4(rot);
+ const product = mulMat4(rot, inv);
+ expectMatClose(product, identity4());
+ });
+
+ it('should invert an orthographic projection matrix', () => {
+ const ortho = new Float32Array(16);
+ const l = -10, r = 10, b = -5, t = 5, n = -1, f = 1;
+ ortho[0] = 2 / (r - l);
+ ortho[5] = 2 / (t - b);
+ ortho[10] = -2 / (f - n);
+ ortho[12] = -(r + l) / (r - l);
+ ortho[13] = -(t + b) / (t - b);
+ ortho[14] = -(f + n) / (f - n);
+ ortho[15] = 1;
+ const inv = invertMatrix4(ortho);
+ const product = mulMat4(ortho, inv);
+ expectMatClose(product, identity4());
+ });
+ });
+
+ // =========================================================================
+ // screenToWorld
+ // =========================================================================
+
+ describe('screenToWorld', () => {
+ it('should map viewport center to world origin with identity VP', () => {
+ const invVP = identity4();
+ const result = screenToWorld(400, 300, invVP, 0, 0, 800, 600);
+ expect(result.x).toBeCloseTo(0);
+ expect(result.y).toBeCloseTo(0);
+ });
+
+ it('should map viewport corners to NDC corners with identity VP', () => {
+ const invVP = identity4();
+ const topLeft = screenToWorld(0, 0, invVP, 0, 0, 800, 600);
+ expect(topLeft.x).toBeCloseTo(-1);
+ expect(topLeft.y).toBeCloseTo(-1);
+
+ const bottomRight = screenToWorld(800, 600, invVP, 0, 0, 800, 600);
+ expect(bottomRight.x).toBeCloseTo(1);
+ expect(bottomRight.y).toBeCloseTo(1);
+ });
+
+ it('should apply translation from VP inverse', () => {
+ const invVP = translation4(10, 20, 0);
+ const result = screenToWorld(400, 300, invVP, 0, 0, 800, 600);
+ expect(result.x).toBeCloseTo(10);
+ expect(result.y).toBeCloseTo(20);
+ });
+
+ it('should handle viewport offset (vpX, vpY non-zero)', () => {
+ const invVP = identity4();
+ const result = screenToWorld(200, 200, invVP, 100, 100, 200, 200);
+ expect(result.x).toBeCloseTo(0);
+ expect(result.y).toBeCloseTo(0);
+ });
+
+ it('should roundtrip with worldToScreen for identity VP', () => {
+ const vp = identity4();
+ const invVP = invertMatrix4(vp);
+ const sx = 250, sy = 180;
+ const vpX = 0, vpY = 0, vpW = 800, vpH = 600;
+ const world = screenToWorld(sx, sy, invVP, vpX, vpY, vpW, vpH);
+ const [backX, backY] = worldToScreen(world.x, world.y, vp, vpX, vpY, vpW, vpH);
+ expect(backX).toBeCloseTo(sx);
+ expect(backY).toBeCloseTo(sy);
+ });
+
+ it('should roundtrip with worldToScreen for scaled VP', () => {
+ const vp = scale4(0.5, 0.5, 1);
+ vp[15] = 1;
+ const invVP = invertMatrix4(vp);
+ const sx = 300, sy = 400;
+ const vpX = 0, vpY = 0, vpW = 800, vpH = 600;
+ const world = screenToWorld(sx, sy, invVP, vpX, vpY, vpW, vpH);
+ const [backX, backY] = worldToScreen(world.x, world.y, vp, vpX, vpY, vpW, vpH);
+ expect(backX).toBeCloseTo(sx);
+ expect(backY).toBeCloseTo(sy);
+ });
+ });
+
+ // =========================================================================
+ // worldToScreen
+ // =========================================================================
+
+ describe('worldToScreen', () => {
+ it('should map world origin to viewport center with identity VP', () => {
+ const vp = identity4();
+ const [sx, sy] = worldToScreen(0, 0, vp, 0, 0, 800, 600);
+ expect(sx).toBeCloseTo(400);
+ expect(sy).toBeCloseTo(300);
+ });
+
+ it('should map world (-1,-1) to viewport origin with identity VP', () => {
+ const vp = identity4();
+ const [sx, sy] = worldToScreen(-1, -1, vp, 0, 0, 800, 600);
+ expect(sx).toBeCloseTo(0);
+ expect(sy).toBeCloseTo(0);
+ });
+
+ it('should handle scaled VP matrix', () => {
+ const vp = scale4(2, 2, 1);
+ vp[15] = 1;
+ const [sx, sy] = worldToScreen(0.5, 0.5, vp, 0, 0, 800, 600);
+ expect(sx).toBeCloseTo(800);
+ expect(sy).toBeCloseTo(600);
+ });
+
+ it('should apply viewport offset', () => {
+ const vp = identity4();
+ const [sx, sy] = worldToScreen(0, 0, vp, 50, 100, 800, 600);
+ expect(sx).toBeCloseTo(450);
+ expect(sy).toBeCloseTo(400);
+ });
+
+ it('should be consistent with screenToWorld roundtrip', () => {
+ const vp = translation4(0.5, -0.3, 0);
+ const invVP = invertMatrix4(vp);
+ const vpX = 10, vpY = 20, vpW = 640, vpH = 480;
+ const wx = 3.5, wy = -2.1;
+ const [sx, sy] = worldToScreen(wx, wy, vp, vpX, vpY, vpW, vpH);
+ const back = screenToWorld(sx, sy, invVP, vpX, vpY, vpW, vpH);
+ expect(back.x).toBeCloseTo(wx);
+ expect(back.y).toBeCloseTo(wy);
+ });
+ });
+
+ // =========================================================================
+ // pointInWorldRect
+ // =========================================================================
+
+ describe('pointInWorldRect', () => {
+ it('should return true for point at center', () => {
+ expect(pointInWorldRect(5, 5, 5, 5, 10, 10, 0.5, 0.5)).toBe(true);
+ });
+
+ it('should return false for point outside', () => {
+ expect(pointInWorldRect(20, 20, 5, 5, 10, 10, 0.5, 0.5)).toBe(false);
+ });
+
+ it('should return true for point on edge (boundary inclusive)', () => {
+ expect(pointInWorldRect(0, 0, 5, 5, 10, 10, 0.5, 0.5)).toBe(true);
+ expect(pointInWorldRect(10, 10, 5, 5, 10, 10, 0.5, 0.5)).toBe(true);
+ });
+
+ it('should handle default pivot (0.5, 0.5) with symmetric bounds', () => {
+ expect(pointInWorldRect(-5, 0, 0, 0, 10, 10, 0.5, 0.5)).toBe(true);
+ expect(pointInWorldRect(5, 0, 0, 0, 10, 10, 0.5, 0.5)).toBe(true);
+ expect(pointInWorldRect(-5.01, 0, 0, 0, 10, 10, 0.5, 0.5)).toBe(false);
+ });
+
+ it('should handle pivot (0, 0) extending right and up', () => {
+ expect(pointInWorldRect(5, 5, 0, 0, 10, 10, 0, 0)).toBe(true);
+ expect(pointInWorldRect(-1, -1, 0, 0, 10, 10, 0, 0)).toBe(false);
+ });
+
+ it('should handle pivot (1, 1) extending left and down', () => {
+ expect(pointInWorldRect(-5, -5, 0, 0, 10, 10, 1, 1)).toBe(true);
+ expect(pointInWorldRect(1, 1, 0, 0, 10, 10, 1, 1)).toBe(false);
+ });
+
+ it('should handle zero-size rect (only exact center matches)', () => {
+ expect(pointInWorldRect(5, 5, 5, 5, 0, 0, 0.5, 0.5)).toBe(true);
+ expect(pointInWorldRect(5.001, 5, 5, 5, 0, 0, 0.5, 0.5)).toBe(false);
+ });
+ });
+
+ // =========================================================================
+ // quaternionToAngle2D
+ // =========================================================================
+
+ describe('quaternionToAngle2D', () => {
+ it('should return 0 for identity quaternion', () => {
+ expect(quaternionToAngle2D(0, 1)).toBeCloseTo(0);
+ });
+
+ it('should return PI/2 for 90 degree rotation', () => {
+ const q = quaternionFromAngle(Math.PI / 2);
+ expect(quaternionToAngle2D(q.rz, q.rw)).toBeCloseTo(Math.PI / 2);
+ });
+
+ it('should return PI for 180 degree rotation', () => {
+ const q = quaternionFromAngle(Math.PI);
+ expect(quaternionToAngle2D(q.rz, q.rw)).toBeCloseTo(Math.PI);
+ });
+
+ it('should return -PI/2 for -90 degree rotation', () => {
+ const q = quaternionFromAngle(-Math.PI / 2);
+ expect(quaternionToAngle2D(q.rz, q.rw)).toBeCloseTo(-Math.PI / 2);
+ });
+
+ it('should return 2*PI for 360 degree rotation (atan2 does not wrap)', () => {
+ const q = quaternionFromAngle(2 * Math.PI);
+ const angle = quaternionToAngle2D(q.rz, q.rw);
+ expect(angle).toBeCloseTo(2 * Math.PI, 4);
+ });
+ });
+
+ // =========================================================================
+ // pointInOBB
+ // =========================================================================
+
+ describe('pointInOBB', () => {
+ it('should behave like pointInWorldRect with no rotation', () => {
+ const q = quaternionFromAngle(0);
+ expect(pointInOBB(5, 5, 5, 5, 10, 10, 0.5, 0.5, q.rz, q.rw)).toBe(true);
+ expect(pointInOBB(20, 20, 5, 5, 10, 10, 0.5, 0.5, q.rz, q.rw)).toBe(false);
+ });
+
+ it('should detect point inside 45-degree rotated rect', () => {
+ const q = quaternionFromAngle(Math.PI / 4);
+ expect(pointInOBB(5, 5, 5, 5, 10, 10, 0.5, 0.5, q.rz, q.rw)).toBe(true);
+ });
+
+ it('should reject point outside rotated rect but inside AABB', () => {
+ const q = quaternionFromAngle(Math.PI / 4);
+ expect(pointInOBB(10, 5, 5, 5, 6, 6, 0.5, 0.5, q.rz, q.rw)).toBe(false);
+ });
+
+ it('should handle 90-degree rotation (swapped axes)', () => {
+ const q = quaternionFromAngle(Math.PI / 2);
+ expect(pointInOBB(5, 9, 5, 5, 10, 2, 0.5, 0.5, q.rz, q.rw)).toBe(true);
+ expect(pointInOBB(9, 5, 5, 5, 10, 2, 0.5, 0.5, q.rz, q.rw)).toBe(false);
+ });
+
+ it('should always contain center point at any rotation', () => {
+ for (const angle of [0, Math.PI / 6, Math.PI / 3, Math.PI / 2, Math.PI]) {
+ const q = quaternionFromAngle(angle);
+ expect(pointInOBB(5, 5, 5, 5, 10, 10, 0.5, 0.5, q.rz, q.rw)).toBe(true);
+ }
+ });
+
+ it('should handle custom pivot with rotation', () => {
+ const q = quaternionFromAngle(0);
+ expect(pointInOBB(5, 5, 0, 0, 10, 10, 0, 0, q.rz, q.rw)).toBe(true);
+ expect(pointInOBB(-1, -1, 0, 0, 10, 10, 0, 0, q.rz, q.rw)).toBe(false);
+ });
+
+ it('should handle zero-size OBB', () => {
+ const q = quaternionFromAngle(Math.PI / 4);
+ expect(pointInOBB(5, 5, 5, 5, 0, 0, 0.5, 0.5, q.rz, q.rw)).toBe(true);
+ expect(pointInOBB(5.1, 5, 5, 5, 0, 0, 0.5, 0.5, q.rz, q.rw)).toBe(false);
+ });
+ });
+
+ // =========================================================================
+ // createInvVPCache
+ // =========================================================================
+
+ describe('createInvVPCache', () => {
+ it('should compute inverse on first call', () => {
+ const cache = createInvVPCache();
+ const vp = identity4();
+ cache.update(vp);
+ const inv = cache.getInverse(vp);
+ expectMatClose(inv, identity4());
+ });
+
+ it('should return cached result for same VP', () => {
+ const cache = createInvVPCache();
+ const vp = translation4(3, 4, 0);
+ cache.update(vp);
+ const inv1 = cache.getInverse(vp);
+ const inv2 = cache.getInverse(vp);
+ expect(inv1).toBe(inv2);
+ });
+
+ it('should recompute when VP changes', () => {
+ const cache = createInvVPCache();
+ const vp1 = translation4(1, 0, 0);
+ cache.update(vp1);
+ const inv1Snapshot = new Float32Array(cache.getInverse(vp1));
+
+ const vp2 = translation4(2, 0, 0);
+ cache.update(vp2);
+ const inv2 = cache.getInverse(vp2);
+
+ expect(inv2[12]).toBeCloseTo(-2);
+ expect(inv1Snapshot[12]).toBeCloseTo(-1);
+ });
+
+ it('should return valid inverse (multiply original gives identity)', () => {
+ const cache = createInvVPCache();
+ const vp = scale4(3, 2, 1);
+ vp[15] = 1;
+ cache.update(vp);
+ const inv = cache.getInverse(vp);
+ const product = mulMat4(vp, inv);
+ expectMatClose(product, identity4());
+ });
+
+ it('should work with update then getInverse sequence', () => {
+ const cache = createInvVPCache();
+ const vp = translation4(5, -3, 0);
+ cache.update(vp);
+ const inv = cache.getInverse(vp);
+ expect(inv[12]).toBeCloseTo(-5);
+ expect(inv[13]).toBeCloseTo(3);
+ });
+ });
+});