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.

40.3 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
 * @file  The 3D world drives Transform, in the units a scene is authored in.
 *
 * check-physics3d proves the solver; this proves the wiring around it, which is
 * where the units live. A scene is authored in world units and the solver works
 * in metres, so a body that arrives unscaled is a character 180 metres tall
 * falling through a floor 0.1m thick — every number still "works", and nothing
 * behaves.
 */
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { Parent, Transform } from '../src/ecs/component';
import type { TransformData } from '../src/ecs/component.generated';
import {
    RigidBody3D, BoxCollider3D, SphereCollider3D, CapsuleCollider3D, CharacterController3D,
    MeshCollider3D, ConvexCollider3D,
} from '../src/physics3d/Physics3DComponents';
import {
    registerMeshCollision, releaseMeshCollision, extractPositions,
} from '../src/asset/meshCollision';
import { stepPhysics3D, DEFAULT_PHYSICS3D_CONFIG } from '../src/physics3d/Physics3DSystem';
import {
    PointJoint3D, HingeJoint3D, SliderJoint3D, FixedJoint3D, SwingTwistJoint3D, SixDOFJoint3D, DistanceJoint3D,
    type Joint3DMap, type HingeJoint3DData, type SliderJoint3DData, type SixDOFJoint3DData, type SwingTwistJoint3DData,
} from '../src/physics3d/Physics3DJoints';
import { drainPhysics3DEvents, type Physics3DEventsData, type Physics3DWasmModule } from '../src/physics3d/Physics3DModule';
import type { App } from '../src/app/app';
import type { Entity } from '../src/types';
import { sceneUses3DPhysics, sceneUsesPhysics } from '../src/runtime/runtimeLoader';
import { Physics3DQueries } from '../src/physics3d/Physics3DQueries';

/** A module that records what it was told, and can be made to answer a readback.
 *  The two readbacks are separate buffers, as they are in the module: sharing one
 *  let the body sweep overwrite what a character had just published. */
function fakeModule(): Physics3DWasmModule & {
    calls: { name: string; args: number[] }[];
    publish(records: number[]): void;
    publishQuery(records: number[]): void;
    publishContacts(records: number[]): void;
} {
    const calls: { name: string; args: number[] }[] = [];
    // One heap the module's two pointers index into, as wasm has.
    const combined = new Float32Array(4096);
    const heap = combined.subarray(0, 1024);
    const record = (name: string) => (...args: number[]): number => {
        calls.push({ name, args });
        return calls.length;  // a non-zero body id
    };
    const query = combined.subarray(1024);
    const eventArea = combined.subarray(2048);
    let published = 0;
    let publishedQuery = 0;
    let publishedEvents = 0;
    let scratchTop = 4096;
    return {
        calls,
        publish(records: number[]) {
            heap.set(records, 0);
            published = records.length * 4;
        },
        publishQuery(records: number[]) {
            query.set(records, 0);
            publishedQuery = records.length * 4;
        },
        publishContacts(records: number[]) {
            eventArea.set(records, 0);
            publishedEvents = records.length * 4;
        },
        HEAPF32: combined,
        HEAPU32: new Uint32Array(combined.buffer),
        _physics3d_init: record('init'),
        _physics3d_shutdown: record('shutdown'),
        _physics3d_isReady: () => 1,
        _physics3d_step: record('step'),
        _physics3d_optimize: record('optimize'),
        _physics3d_addBox: record('addBox'),
        _physics3d_addSphere: record('addSphere'),
        _physics3d_addCapsule: record('addCapsule'),
        _physics3d_removeBody: record('removeBody'),
        _physics3d_setTransform: record('setTransform'),
        _physics3d_setLinearVelocity: record('setLinearVelocity'),
        _physics3d_getBodyState: record('getBodyState'),
        _physics3d_raycast: record('raycast'),
        _physics3d_addCharacter: record('addCharacter'),
        _physics3d_removeCharacter: record('removeCharacter'),
        _physics3d_moveCharacter: record('moveCharacter'),
        _physics3d_setCharacterPosition: record('setCharacterPosition'),
        _physics3d_addMeshBody: record('addMeshBody'),
        _physics3d_addConvexBody: record('addConvexBody'),
        _physics3d_setLayerMask: record('setLayerMask'),
        _physics3d_addPointJoint: record('addPointJoint'),
        _physics3d_addHingeJoint: record('addHingeJoint'),
        _physics3d_addSliderJoint: record('addSliderJoint'),
        _physics3d_addDistanceJoint: record('addDistanceJoint'),
        _physics3d_addFixedJoint: record('addFixedJoint'),
        _physics3d_addSwingTwistJoint: record('addSwingTwistJoint'),
        _physics3d_addSixDOFJoint: record('addSixDOFJoint'),
        _physics3d_setAdvancedJointMotor: record('setAdvancedJointMotor'),
        _physics3d_removeJoint: record('removeJoint'),
        _physics3d_setJointMotor: record('setJointMotor'),
        _physics3d_setJointLimits: record('setJointLimits'),
        _physics3d_setJointMotorLimit: record('setJointMotorLimit'),
        _physics3d_setDistanceJoint: record('setDistanceJoint'),
        _physics3d_setMass: record('setMass'),
        _physics3d_jointValue: (entity: number) => { calls.push({ name: 'jointValue', args: [entity] }); return 0.25; },
        // Distinct allocations, as a real heap gives: one address for everything
        // let the index write land on top of the vertex write.
        _malloc: (bytes: number) => { const at = scratchTop; scratchTop += bytes; return at; },
        _free: () => {},
        _physics3d_contactEnters: () => 2048 * 4,
        _physics3d_contactEntersBytes: () => publishedEvents,
        _physics3d_contactExits: () => 0,
        _physics3d_contactExitsBytes: () => 0,
        _physics3d_sensorEnters: () => 0,
        _physics3d_sensorEntersBytes: () => 0,
        _physics3d_sensorExits: () => 0,
        _physics3d_sensorExitsBytes: () => 0,
        _physics3d_transforms: () => 0,
        _physics3d_transformsBytes: () => published,
        // A byte offset past the transform buffer, so the two never alias.
        _physics3d_queryResult: () => 1024 * 4,
        _physics3d_queryResultBytes: () => publishedQuery,
    } as unknown as Physics3DWasmModule & {
        calls: { name: string; args: number[] }[];
        publish(records: number[]): void;
        publishQuery(records: number[]): void;
        publishContacts(records: number[]): void;
    };
}

/** The slice of a World that stepPhysics3D touches. Real components, plain
 *  storage: what is under test is the sync, and a World needs a C++ registry. */
function fakeWorld() {
    const store = new Map<Entity, Map<unknown, Record<string, unknown>>>();
    let next = 1;
    return {
        spawn(): Entity {
            const e = next++ as Entity;
            store.set(e, new Map());
            return e;
        },
        insert<T>(e: Entity, def: unknown, data?: Partial<T>): T {
            const defaults = (def as { _default?: object })._default ?? {};
            const value = structuredClone({ ...defaults, ...(data ?? {}) });
            store.get(e)!.set(def, value as Record<string, unknown>);
            return value as T;
        },
        remove(e: Entity, def: unknown): void { store.get(e)?.delete(def); },
        get(e: Entity, def: unknown): unknown { return store.get(e)?.get(def); },
        set(e: Entity, def: unknown, value: unknown): void {
            store.get(e)?.set(def, value as Record<string, unknown>);
        },
        has(e: Entity, def: unknown): boolean { return store.get(e)?.has(def) ?? false; },
        // Modelled, not stubbed: the real one edits the stored value in place and
        // reports it. A fake missing a write path sends its tests down another.
        update<T>(e: Entity, def: unknown, edit: (draft: T) => void): void {
            const value = store.get(e)?.get(def);
            if (!value) throw new Error('update: the entity does not carry it.');
            edit(value as T);
        },
        valid(e: Entity): boolean { return store.has(e); },
        // Nothing composes here, so this is the honest answer for a store with no
        // composer: what the solver's world pose becomes under a PARENT is
        // checked against the real one in physics3d-transform-space.
        ensureTransformsComposed(): void {},
        queryEntities(defs: unknown[]): Entity[] {
            return [...store.entries()]
                .filter(([, comps]) => defs.every((d) => comps.has(d)))
                .map(([e]) => e);
        },
    };
}

describe('the 3D world and the ECS', () => {
    let world: ReturnType<typeof fakeWorld>;
    let app: App;
    let module: ReturnType<typeof fakeModule>;
    let bodies: Map<Entity, number>;

    beforeEach(() => {
        world = fakeWorld();
        app = { world } as unknown as App;
        module = fakeModule();
        bodies = new Map();
    });

    const spawn = (position = { x: 0, y: 0, z: 0 }): Entity => {
        const e = world.spawn();
        world.insert<TransformData>(e, Transform, {
            position: { ...position },
            rotation: { x: 0, y: 0, z: 0, w: 1 },
            scale: { x: 1, y: 1, z: 1 },
            worldPosition: { ...position },
            worldRotation: { x: 0, y: 0, z: 0, w: 1 },
            worldScale: { x: 1, y: 1, z: 1 },
        });
        world.insert(e, RigidBody3D);
        return e;
    };

    const called = (name: string) => module.calls.filter((c) => c.name === name);

    it('syncs changed authored static and kinematic poses without writes on stable frames', () => {
        const e=spawn();world.insert(e,BoxCollider3D);world.insert(e,RigidBody3D,{bodyType:1});
        stepPhysics3D(app,module,bodies,DEFAULT_PHYSICS3D_CONFIG);
        stepPhysics3D(app,module,bodies,DEFAULT_PHYSICS3D_CONFIG);
        expect(called('setTransform')).toHaveLength(0);
        world.update(e,Transform,(t:TransformData)=>{t.worldPosition.x=250;});
        stepPhysics3D(app,module,bodies,DEFAULT_PHYSICS3D_CONFIG);
        expect(called('setTransform')[0].args.slice(1,4)).toEqual([2.5,0,0]);
        stepPhysics3D(app,module,bodies,DEFAULT_PHYSICS3D_CONFIG);
        expect(called('setTransform')).toHaveLength(1);
    });

    it('does not dirty the ECS for an unchanged native body readback', () => {
        const e=spawn();world.insert(e,BoxCollider3D);world.insert(e,RigidBody3D,{bodyType:2});
        module.publish([e,0,0,0,0,0,0,1]);
        const writes=vi.spyOn(world,'set');
        stepPhysics3D(app,module,bodies,DEFAULT_PHYSICS3D_CONFIG);
        stepPhysics3D(app,module,bodies,DEFAULT_PHYSICS3D_CONFIG);
        expect(writes.mock.calls.filter(c=>c[1]===Transform)).toHaveLength(0);
    });

    it('registers a body for each shape a scene authors', () => {
        const box = spawn();
        world.insert(box, BoxCollider3D);
        const ball = spawn();
        world.insert(ball, SphereCollider3D);
        const character = spawn();
        world.insert(character, CapsuleCollider3D);

        stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG);

        expect(called('addBox')).toHaveLength(1);
        expect(called('addSphere')).toHaveLength(1);
        expect(called('addCapsule')).toHaveLength(1);
        expect(bodies.size).toBe(3);
    });

    it('gives a moving body the mass it says, and a new one when it changes in play', () => {
        const light = spawn();
        world.insert(light, SphereCollider3D);
        world.insert(light, RigidBody3D, { bodyType: 2, mass: 0.05 });
        const plain = spawn();
        world.insert(plain, SphereCollider3D);
        const wall = spawn();
        world.insert(wall, BoxCollider3D);
        world.insert(wall, RigidBody3D, { bodyType: 0, mass: 900 });

        stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG);
        stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG);
        // Once, and only to the body that moves and says a mass; the others keep what their shape gives.
        expect(called('setMass').map((c) => c.args)).toEqual([[bodies.get(light)!, 0.05]]);

        world.update(light, RigidBody3D, (b: { mass: number }) => { b.mass = 3; });
        stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG);
        expect(called('setMass').map((c) => c.args)).toEqual([[bodies.get(light)!, 0.05], [bodies.get(light)!, 3]]);
    });

    it('reads how hard two bodies met: speed by the mass they met with', () => {
        const a = spawn(), b = spawn();
        module.publishContacts([a, b, 0, 1, 0, 0, 0, 0]);
        const speeds = new Float32Array([4]);
        const masses = new Float32Array([2.5]);
        const speedAt = 3000 * 4, massAt = 3008 * 4;
        module.HEAPF32.set(speeds, speedAt / 4);
        module.HEAPF32.set(masses, massAt / 4);
        Object.assign(module, {
            _physics3d_contactEnterSpeeds: () => speedAt, _physics3d_contactEnterSpeedsBytes: () => 4,
            _physics3d_contactEnterMasses: () => massAt, _physics3d_contactEnterMassesBytes: () => 4,
        });
        const events = { contactEnters: [], contactExits: [], sensorEnters: [], sensorExits: [] } as Physics3DEventsData;
        drainPhysics3DEvents(module, events, 100);
        // In world units a second, at 100 to the metre; the mass is kilograms whatever the units.
        expect(events.contactEnters[0]).toMatchObject({ speed: 400, mass: 2.5, impulse: 1000 });
    });

    it('registers nothing for a body with no shape', () => {
        spawn();
        stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG);
        // An extent-less body is a point that falls forever — and, worse, one the
        // readback would then try to write back to a Transform.
        expect(bodies.size).toBe(0);
        expect(called('step')).toHaveLength(1);
    });

    it('sends the solver metres, not world units', () => {
        const e = spawn({ x: 300, y: 150, z: 0 });
        world.insert(e, SphereCollider3D);
        world.update(e, SphereCollider3D, (c) => { (c as { radius: number }).radius = 50; });

        stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG);

        // 100 world units to the metre: a 50-unit ball is half a metre across and
        // stands 1.5m from the origin.
        const [call] = called('addSphere');
        expect(call!.args[1]).toBeCloseTo(0.5, 6);
        expect(call!.args[2]).toBeCloseTo(3, 6);
        expect(call!.args[3]).toBeCloseTo(1.5, 6);
    });

    it('hands the solver where a collider sits from its entity, in metres', () => {
        const e = spawn();
        world.insert(e, BoxCollider3D);
        world.update(e, BoxCollider3D, (c) => { (c as { center: { x: number; y: number; z: number } }).center = { x: 100, y: 250, z: -50 }; });
        const plain = spawn();
        world.insert(plain, BoxCollider3D);

        stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG);

        const [off, centred] = called('addBox');
        // The last three arguments are the offset: the shape moves, the body stays at the entity.
        expect(off!.args.slice(-3)).toEqual([1, 2.5, -0.5]);
        expect(centred!.args.slice(-3)).toEqual([0, 0, 0]);
    });

    it('writes the solver’s answer back in world units', () => {
        const e = spawn();
        world.insert(e, BoxCollider3D);
        stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG);

        // (entity, position, rotation) — a body at 2m up and a quarter turn about Y.
        const s = Math.SQRT1_2;
        module.publish([e as number, 0, 2, 0, 0, s, 0, s]);
        stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG);

        const t = world.get(e, Transform) as TransformData;
        expect(t.position.y).toBeCloseTo(200, 4);
        expect(t.rotation.y).toBeCloseTo(s, 6);
        expect(t.rotation.w).toBeCloseTo(s, 6);
    });

    it('gives a body back when its component goes', () => {
        const e = spawn();
        world.insert(e, BoxCollider3D);
        stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG);
        expect(bodies.size).toBe(1);

        // The collider stays, so the entity is a static body now: the dynamic one goes and a static one is made.
        world.remove(e, RigidBody3D);
        module.calls.length = 0;
        stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG);
        expect(called('removeBody')).toHaveLength(1);
        expect(called('addBox')).toHaveLength(1);
        expect(bodies.size).toBe(1);

        world.remove(e, BoxCollider3D);
        module.calls.length = 0;
        stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG);
        expect(called('removeBody')).toHaveLength(1);
        expect(bodies.size).toBe(0);
    });

    it('builds a collider under a rigid body as nothing of its own', () => {
        const parent = spawn();
        world.insert(parent, BoxCollider3D);
        const child = world.spawn();
        world.insert<TransformData>(child, Transform, {});
        world.insert(child, Parent, { entity: parent });
        world.insert(child, SphereCollider3D);
        stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG);
        expect(called('addSphere')).toHaveLength(0);
        expect(bodies.size).toBe(1);
    });

    it('sweeps a character in metres and reads its ground state back', () => {
        const e = world.spawn();
        world.insert<TransformData>(e, Transform, {
            position: { x: 0, y: 0, z: 0 },
            rotation: { x: 0, y: 0, z: 0, w: 1 },
            scale: { x: 1, y: 1, z: 1 },
            worldPosition: { x: 0, y: 500, z: 0 },
            worldRotation: { x: 0, y: 0, z: 0, w: 1 },
            worldScale: { x: 1, y: 1, z: 1 },
        });
        world.insert(e, CharacterController3D, {
            radius: 30, halfHeight: 50, velocity: { x: 200, y: 0, z: 0 },
        });

        const characters = new Map<Entity, number>();
        stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG, characters);

        const [added] = called('addCharacter');
        expect(added!.args[1]).toBeCloseTo(0.3, 6);   // 30 world units = 0.3m
        expect(added!.args[2]).toBeCloseTo(0.5, 6);
        expect(added!.args[4]).toBeCloseTo(5, 6);     // standing 5m up
        // Push force is a force, not a length: it crosses unscaled, and a character
        // that never forwarded it walks through crates without moving them.
        expect(added!.args[9]).toBe(5000);
        const [moved] = called('moveCharacter');
        expect(moved!.args[1]).toBeCloseTo(2, 6);     // 200 units/s = 2 m/s
        expect(characters.size).toBe(1);

        // Ground state 0 is OnGround; the normal and velocity come back beside it.
        module.publishQuery([1, 2, 3, 0, 0, 1, 0, 2, 0, 0]);
        stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG, characters);
        const state = world.get(e, CharacterController3D) as {
            isOnFloor: boolean; floorNormal: { y: number }; realVelocity: { x: number };
        };
        expect(state.isOnFloor).toBe(true);
        expect(state.floorNormal.y).toBeCloseTo(1, 6);
        expect(state.realVelocity.x).toBeCloseTo(200, 4);
        expect((world.get(e, Transform) as TransformData).position.y).toBeCloseTo(200, 4);
    });

    it('hands this step\u2019s contacts to the events resource', () => {
        const e = spawn();
        world.insert(e, BoxCollider3D);
        const events = {
            contactEnters: [], contactExits: [], sensorEnters: [], sensorExits: [],
        };
        // (entityA, entityB, normal, point) — two bodies met head-on at 1m up, which is 100 in Transform units.
        module.publishContacts([7, 9, 0, 1, 0, 0, 1, 0]);
        stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG, new Map(), events);

        expect(events.contactEnters).toHaveLength(1);
        const [hit] = events.contactEnters as Array<Record<string, number>>;
        expect(hit!.entityA).toBe(7);
        expect(hit!.entityB).toBe(9);
        expect(hit!.normalY).toBeCloseTo(1, 6);
        expect(hit!.pointY).toBeCloseTo(DEFAULT_PHYSICS3D_CONFIG.pixelsPerUnit, 6);
    });

    it('collides against a loaded mesh\u2019s own triangles', () => {
        // Two triangles a metre across, as the loader would have kept them.
        registerMeshCollision(77, {
            positions: new Float32Array([0, 0, 0, 100, 0, 0, 0, 0, 100, 100, 0, 100]),
            indices: new Uint32Array([0, 2, 1, 2, 3, 1]),
        });
        const e = spawn();
        world.insert(e, MeshCollider3D, { mesh: 77 });

        stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG);

        const [call] = called('addMeshBody');
        expect(call).toBeDefined();
        expect(call!.args[2]).toBe(4);   // four vertices
        expect(call!.args[4]).toBe(6);   // six indices
        // A 100-unit triangle is a metre in the solver.
        expect(module.HEAPF32[(call!.args[1] >> 2) + 3]).toBeCloseTo(1, 6);
        releaseMeshCollision(77);
    });

    it('hands a convex collider its mesh\u2019s points, scaled, and no triangles', () => {
        registerMeshCollision(78, {
            positions: new Float32Array([0, 0, 0, 100, 0, 0, 0, 100, 0, 0, 0, 100]),
            indices: new Uint32Array([0, 1, 2, 0, 2, 3, 0, 3, 1, 1, 3, 2]),
        });
        const e = spawn();
        world.insert(e, ConvexCollider3D, { mesh: 78 });

        stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG);

        const [call] = called('addConvexBody');
        expect(call).toBeDefined();
        expect(call!.args[2]).toBe(4);                                  // four points
        expect(module.HEAPF32[(call!.args[1] >> 2) + 3]).toBeCloseTo(1, 6);  // 100 units = 1m
        releaseMeshCollision(78);
    });

    it('lets a mesh collider win over a hull on the same entity', () => {
        registerMeshCollision(79, {
            positions: new Float32Array([0, 0, 0, 100, 0, 0, 0, 0, 100, 100, 0, 100]),
            indices: new Uint32Array([0, 2, 1, 2, 3, 1]),
        });
        const e = spawn();
        world.insert(e, ConvexCollider3D, { mesh: 79 });
        world.insert(e, MeshCollider3D, { mesh: 79 });

        stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG);

        // One body per entity, and the order is the one readCollider3DShapes draws.
        expect(called('addMeshBody')).toHaveLength(1);
        expect(called('addConvexBody')).toHaveLength(0);
        releaseMeshCollision(79);
    });

    it('registers nothing for a mesh collider whose geometry never loaded', () => {
        const e = spawn();
        world.insert(e, MeshCollider3D, { mesh: 999 });
        stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG);
        // Handle 999 named a mesh nothing kept triangles for. Registering a body
        // with no shape would put an invisible point in the world.
        expect(called('addMeshBody')).toHaveLength(0);
        expect(bodies.size).toBe(0);
    });

    it('sends the continuous-collision choice to the world', () => {
        const e = spawn();
        world.insert(e, SphereCollider3D);
        world.update(e, RigidBody3D, (b) => { (b as { continuousCollision: boolean }).continuousCollision = true; });

        stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG);

        // entity, radius, position(3), rotation(4), motion, gravity, damping(2),
        // fixedRotation, layer, then the motion quality \u2014 a flag nothing forwards
        // leaves every bullet passing through every wall.
        expect(called('addSphere')[0]!.args[15]).toBe(1);
    });

    it('sends a body\u2019s layer to the world', () => {
        const e = spawn();
        world.insert(e, SphereCollider3D);
        world.update(e, RigidBody3D, (b) => { (b as { layer: number }).layer = 5; });

        stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG);

        // entity, radius, position(3), rotation(4), motion, gravity, damping(2),
        // fixedRotation, then LAYER — a knob nothing forwards does nothing.
        const [call] = called('addSphere');
        expect(call!.args[14]).toBe(5);
    });

    it('leaves a disabled body out of the world', () => {
        const e = spawn();
        world.insert(e, BoxCollider3D);
        world.update(e, RigidBody3D, (b) => { (b as { enabled: boolean }).enabled = false; });

        stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG);
        expect(bodies.size).toBe(0);
    });

    describe('joints', () => {
        let joints: Joint3DMap;
        beforeEach(() => { joints = new Map(); });

        const stepJoints = () =>
            stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG, new Map(),
                          undefined, joints);

        /** A pair of bodies a joint can be hung between. */
        const pair = (aPos = { x: 0, y: 0, z: 0 }, bPos = { x: 100, y: 0, z: 0 }) => {
            const a = spawn(aPos);
            world.insert(a, BoxCollider3D);
            const b = spawn(bPos);
            world.insert(b, BoxCollider3D);
            return [a, b] as const;
        };

        it('scales six-axis limits and velocity without scaling angles or force', () => {
            const [a, b] = pair();
            world.insert(a, SixDOFJoint3D, { connectedEntity: b,
                translationMotion: { x: 1, y: 0, z: 2 },
                translationLower: { x: -200, y: 0, z: 0 }, translationUpper: { x: 300, y: 0, z: 0 },
                rotationMotion: { x: 1, y: 0, z: 0 },
                rotationLower: { x: -0.4, y: 0, z: 0 }, rotationUpper: { x: 0.6, y: 0, z: 0 },
                enableMotor: true, linearVelocity: { x: 150, y: 0, z: 0 },
                angularVelocity: { x: 2, y: 0, z: 0 }, maxMotorForce: 40, maxMotorTorque: 20 });
            stepJoints();
            const args = called('addSixDOFJoint')[0]!.args;
            expect(args.slice(12, 14)).toEqual([33, 1]);
            expect(args.slice(14, 20)).toEqual([-2, 0, 0, 3, 0, 0]);
            expect(args.slice(20, 26)).toEqual([-0.4, 0, 0, 0.6, 0, 0]);
            expect(called('setAdvancedJointMotor')[0]!.args).toEqual([a, 1, 1.5, 0, 0, 2, 0, 0, 40, 20]);
            stepJoints();
            expect(called('setAdvancedJointMotor')).toHaveLength(1);
            world.update(a, SixDOFJoint3D, (d) => { (d as SixDOFJoint3DData).linearVelocity = { x: -200, y: 0, z: 0 }; });
            stepJoints();
            expect(called('addSixDOFJoint')).toHaveLength(1);
            expect(called('setAdvancedJointMotor')[1]!.args[2]).toBe(-2);
        });

        it('rebuilds changed swing limits and removes an invalid frame before stepping', () => {
            const [a, b] = pair();
            world.insert(a, SwingTwistJoint3D, { connectedEntity: b });
            stepJoints();
            world.update(a, SwingTwistJoint3D, (d) => { (d as SwingTwistJoint3DData).normalHalfConeAngle = 0.2; });
            stepJoints();
            expect(called('addSwingTwistJoint')).toHaveLength(2);
            expect(called('removeJoint')).toHaveLength(1);
            world.update(a, SwingTwistJoint3D, (d) => { (d as SwingTwistJoint3DData).normalAxis = { x: 0, y: 1, z: 0 }; });
            stepJoints();
            expect(joints.size).toBe(0);
            expect(called('removeJoint')).toHaveLength(2);
            expect(called('addSwingTwistJoint')).toHaveLength(2);
        });

        it('hands the anchor over in metres, from where the entity is', () => {
            const [a, b] = pair({ x: 200, y: 100, z: 0 });
            world.insert(a, HingeJoint3D, { connectedEntity: b, anchor: { x: 50, y: 0, z: 0 } });

            stepJoints();

            const [call] = called('addHingeJoint');
            expect(call).toBeDefined();
            // (200 + 50, 100, 0) world units at 100 to the metre.
            expect(call!.args.slice(3, 6)).toEqual([2.5, 1, 0]);
        });

        it('turns the anchor and the axis with the entity', () => {
            const [a, b] = pair();
            // A quarter turn about Z: +x becomes +y, and so does the hinge axis.
            const half = Math.PI / 4;
            world.update(a, Transform, (t) => {
                (t as TransformData).worldRotation = { x: 0, y: 0, z: Math.sin(half), w: Math.cos(half) };
            });
            world.insert(a, HingeJoint3D, {
                connectedEntity: b, anchor: { x: 100, y: 0, z: 0 }, axis: { x: 1, y: 0, z: 0 },
            });

            stepJoints();

            const [call] = called('addHingeJoint');
            const [px, py, pz, ax, ay, az] = call!.args.slice(3, 9);
            expect(px).toBeCloseTo(0, 5);
            expect(py).toBeCloseTo(1, 5);
            expect(pz).toBeCloseTo(0, 5);
            expect(ax).toBeCloseTo(0, 5);
            expect(ay).toBeCloseTo(1, 5);
            expect(az).toBeCloseTo(0, 5);
        });

        it('scales travel but not force', () => {
            const [a, b] = pair();
            world.insert(a, SliderJoint3D, {
                connectedEntity: b, enableLimit: true,
                lowerTranslation: -200, upperTranslation: 300,
                enableMotor: true, motorSpeed: 150, maxMotorForce: 400,
            });

            stepJoints();

            const args = called('addSliderJoint')[0]!.args;
            expect(args.slice(10, 12)).toEqual([-2, 3]);   // world units → metres
            expect(args[13]).toBe(1.5);                    // speed is a length too
            expect(args[14]).toBe(400);                    // force is not
        });

        it('waits for the body at the other end', () => {
            const a = spawn();
            world.insert(a, BoxCollider3D);
            const b = world.spawn();   // no Transform, no body yet
            world.insert(a, PointJoint3D, { connectedEntity: b });

            stepJoints();
            expect(called('addPointJoint')).toHaveLength(0);
            expect(joints.size).toBe(0);

            world.insert<TransformData>(b, Transform, {
                position: { x: 100, y: 0, z: 0 }, rotation: { x: 0, y: 0, z: 0, w: 1 },
                scale: { x: 1, y: 1, z: 1 }, worldPosition: { x: 100, y: 0, z: 0 },
                worldRotation: { x: 0, y: 0, z: 0, w: 1 }, worldScale: { x: 1, y: 1, z: 1 },
            });
            world.insert(b, RigidBody3D);
            world.insert(b, BoxCollider3D);

            stepJoints();
            expect(called('addPointJoint')).toHaveLength(1);
        });

        it('builds one joint per entity, the one the module keys', () => {
            const [a, b] = pair();
            world.insert(a, FixedJoint3D, { connectedEntity: b });
            world.insert(a, PointJoint3D, { connectedEntity: b });

            stepJoints();

            expect(called('addPointJoint')).toHaveLength(1);
            expect(called('addFixedJoint')).toHaveLength(0);
        });

        it('makes each joint once, not once per step', () => {
            const [a, b] = pair();
            world.insert(a, PointJoint3D, { connectedEntity: b });
            stepJoints();
            stepJoints();
            stepJoints();
            expect(called('addPointJoint')).toHaveLength(1);
        });

        it('takes the joint back when its component goes', () => {
            const [a, b] = pair();
            world.insert(a, PointJoint3D, { connectedEntity: b });
            stepJoints();
            world.remove(a, PointJoint3D);
            stepJoints();

            expect(called('removeJoint')).toHaveLength(1);
            expect(joints.size).toBe(0);
        });

        it('takes the joint out BEFORE the body it hangs on', () => {
            // The module holds a constraint against two bodies. A body removed
            // while a joint still names it leaves the solver holding nothing, and
            // nothing in a later step can notice that.
            const [a, b] = pair();
            world.insert(a, PointJoint3D, { connectedEntity: b });
            stepJoints();
            module.calls.length = 0;
            world.remove(b, RigidBody3D);
            world.remove(b, BoxCollider3D);
            stepJoints();

            const removeJoint = module.calls.findIndex((c) => c.name === 'removeJoint');
            const removeBody = module.calls.findIndex((c) => c.name === 'removeBody');
            expect(removeJoint).toBeGreaterThanOrEqual(0);
            expect(removeBody).toBeGreaterThanOrEqual(0);
            expect(removeJoint).toBeLessThan(removeBody);
        });

        it('leaves a disabled joint out of the world', () => {
            const [a, b] = pair();
            world.insert(a, PointJoint3D, { connectedEntity: b, enabled: false });
            stepJoints();
            expect(called('addPointJoint')).toHaveLength(0);
        });

        it('carries a new motor speed into a joint that already exists', () => {
            // A joint is built once. Without this, writing motorSpeed from a script
            // would set a field nothing reads — the door never opens.
            const [a, b] = pair();
            const hinge = world.insert<HingeJoint3DData>(a, HingeJoint3D, {
                connectedEntity: b, enableMotor: true, motorSpeed: 1, maxMotorTorque: 100,
            });
            stepJoints();
            expect(called('setJointMotor')).toHaveLength(0);   // built with it already

            hinge.motorSpeed = 4;
            stepJoints();
            const [drive] = called('setJointMotor');
            expect(drive!.args).toEqual([a as number, 1, 4]);

            // ...and only when it changes: a call every step would fight the solver.
            stepJoints();
            expect(called('setJointMotor')).toHaveLength(1);
        });

        it('carries a new range and motor limit into a hinge or slider that already exists', () => {
            // Built once; without this, a door locked from a script by narrowing its range would swing on.
            const [a, b] = pair();
            const hinge = world.insert<HingeJoint3DData>(a, HingeJoint3D, { connectedEntity: b, maxMotorTorque: 10 });
            stepJoints();
            expect(called('setJointLimits')).toHaveLength(0);
            hinge.enableLimit = true;
            hinge.lowerAngle = -0.2;
            hinge.upperAngle = 0.4;
            hinge.maxMotorTorque = 50;
            stepJoints();
            expect(called('setJointLimits').map((c) => c.args)).toEqual([[a as number, 1, -0.2, 0.4]]);
            expect(called('setJointMotorLimit').map((c) => c.args)).toEqual([[a as number, 50]]);
            stepJoints();
            expect(called('setJointLimits')).toHaveLength(1);

            // A slider's travel is a length, and reaches the world in metres; its force does not.
            const [c, d] = pair({ x: 500, y: 0, z: 0 }, { x: 600, y: 0, z: 0 });
            const slider = world.insert<SliderJoint3DData>(c, SliderJoint3D, { connectedEntity: d });
            stepJoints();
            slider.enableLimit = true;
            slider.lowerTranslation = -50;
            slider.upperTranslation = 150;
            stepJoints();
            expect(called('setJointLimits').at(-1)!.args).toEqual([c as number, 1, -0.5, 1.5]);
        });

        it('carries a new length and spring into a distance joint that already exists', () => {
            const [a, b] = pair();
            const rope = world.insert<{ connectedEntity: Entity; maxLength: number; minLength: number; frequency: number; damping: number }>(a, DistanceJoint3D, { connectedEntity: b, maxLength: 300 });
            stepJoints();
            expect(called('setDistanceJoint')).toHaveLength(0);
            rope.maxLength = 100;
            rope.frequency = 2;
            stepJoints();
            expect(called('setDistanceJoint').map((c) => c.args)).toEqual([[a as number, 0, 1, 2, 0.5]]);
        });

        it('writes the joint state back where gameplay can read it', () => {
            const [a, b] = pair();
            world.insert(a, HingeJoint3D, { connectedEntity: b });
            stepJoints();
            expect((world.get(a, HingeJoint3D) as HingeJoint3DData).angle).toBe(0.25);

            const [c, d] = pair({ x: 500, y: 0, z: 0 }, { x: 600, y: 0, z: 0 });
            world.insert(c, SliderJoint3D, { connectedEntity: d });
            stepJoints();
            // An angle is an angle; travel is a length and comes back in world units.
            expect((world.get(c, SliderJoint3D) as SliderJoint3DData).translation).toBe(25);
        });
    });
});

describe('a scene asks for the world it needs', () => {
    const sceneWith = (...types: string[]) => ({
        entities: [{ components: types.map((type) => ({ type, data: {} })) }],
    });

    it('sees every 3D component as wanting the 3D world', () => {
        for (const type of ['RigidBody3D', 'BoxCollider3D', 'SphereCollider3D',
                            'CapsuleCollider3D', 'CharacterController3D']) {
            expect(sceneUses3DPhysics(sceneWith(type) as never)).toBe(true);
        }
    });

    it('does not confuse the two worlds', () => {
        // A 2D scene must not drag in a 1.2MB module it has no use for, and a 3D
        // scene must not be served the solver that cannot move it.
        expect(sceneUses3DPhysics(sceneWith('RigidBody2D', 'BoxCollider2D') as never)).toBe(false);
        expect(sceneUsesPhysics(sceneWith('RigidBody3D', 'BoxCollider3D') as never)).toBe(false);
    });
});

describe('mesh collision geometry', () => {
    it('pulls positions out of an interleaved buffer', () => {
        // Two vertices, each 20 bytes: position (12) then a colour (8) it ignores.
        const bytes = new Uint8Array(40);
        const view = new DataView(bytes.buffer);
        view.setFloat32(0, 1, true); view.setFloat32(4, 2, true); view.setFloat32(8, 3, true);
        view.setFloat32(20, 4, true); view.setFloat32(24, 5, true); view.setFloat32(28, 6, true);
        const out = extractPositions(bytes, 2, 20, [
            { semantic: 0, offset: 0, type: 0 }, { semantic: 1, offset: 12, type: 0 },
        ]);
        expect(Array.from(out!)).toEqual([1, 2, 3, 4, 5, 6]);
    });

    it('answers null for geometry with no positions', () => {
        // Nothing can collide against a mesh that never said where its vertices are.
        expect(extractPositions(new Uint8Array(8), 1, 8, [
            { semantic: 3, offset: 0, type: 0 },
        ])).toBeNull();
    });
});

describe('3D spatial queries', () => {
    /** A module that answers one canned result, so the units can be checked. */
    function queryModule(result: number[], hits = 1) {
        const heap = new Float32Array(64);
        heap.set(result, 0);
        const calls: number[][] = [];
        return {
            calls,
            HEAPF32: heap,
            _physics3d_queryResult: () => 0,
            _physics3d_raycast: (...args: number[]) => { calls.push(args); return hits; },
            _physics3d_sphereCast: (...args: number[]) => { calls.push(args); return hits; },
            _physics3d_overlapSphere: (...args: number[]) => { calls.push(args); return hits; },
            _physics3d_overlapBox: (...args: number[]) => { calls.push(args); return hits; },
        } as unknown as Parameters<typeof Physics3DQueries.prototype.raycast> extends never
            ? never : ConstructorParameters<typeof Physics3DQueries>[0] & { calls: number[][] };
    }

    it('asks in metres and answers in world units', () => {
        // A hit 3m along, at 2m up, with an upward normal.
        const module = queryModule([9, 0.5, 0, 2, 0, 0, 1, 0]);
        const q = new Physics3DQueries(module, 100);
        const hit = q.raycast({ x: 0, y: 500, z: 0 }, { x: 0, y: -600, z: 0 });

        expect(module.calls[0]![1]).toBeCloseTo(5, 6);     // 500 units = 5m
        expect(module.calls[0]![4]).toBeCloseTo(-6, 6);
        expect(hit!.y).toBeCloseTo(200, 4);                // 2m = 200 units
        // A normal is a direction: scaling it would leave a unit vector 100 long.
        expect(hit!.normalY).toBeCloseTo(1, 6);
        expect(hit!.entity).toBe(9);
    });

    it('scales a swept sphere’s radius too', () => {
        const module = queryModule([1, 0.25, 0, 0, 0, 0, 1, 0]);
        const q = new Physics3DQueries(module, 100);
        q.sphereCast({ x: 0, y: 0, z: 0 }, 30, { x: 400, y: 0, z: 0 });
        expect(module.calls[0]![3]).toBeCloseTo(0.3, 6);
        expect(module.calls[0]![4]).toBeCloseTo(4, 6);
    });

    it('reads every overlap the world reported', () => {
        const module = queryModule([7, 1, 2, 3, 8, 4, 5, 6], 2);
        const q = new Physics3DQueries(module, 100);
        const hits = q.overlapSphere({ x: 0, y: 0, z: 0 }, 50);
        expect(hits).toHaveLength(2);
        expect(hits[0]!.entity).toBe(7);
        expect(hits[1]!.entity).toBe(8);
        expect(hits[1]!.x).toBeCloseTo(400, 4);
    });

    it('answers an empty list rather than a phantom hit', () => {
        const module = queryModule([7, 1, 2, 3], 0);
        const q = new Physics3DQueries(module, 100);
        expect(q.overlapBox({ x: 0, y: 0, z: 0 }, { x: 10, y: 10, z: 10 })).toEqual([]);
    });
});