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.

55.1 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
 * @file    Physics3DModuleEntry.cpp
 * @brief   The 3D physics side module's entry points.
 * @details One world, built on demand and stepped by the SDK — the same shape as
 *          the 2D module beside it, because the SDK drives both the same way. What
 *          differs is only what a body is: a shape in space with an orientation,
 *          rather than a shape in a plane with an angle.
 *
 * @author  ESEngine Team
 * @date    2026
 *
 * @copyright Copyright (c) 2026 ESEngine Team
 *            Licensed under the Apache License, Version 2.0.
 */
#include "./Physics3DContext.hpp"

#include <Jolt/Physics/Body/BodyCreationSettings.h>
#include <Jolt/Physics/Collision/CastResult.h>
#include <Jolt/Physics/Collision/RayCast.h>
#include <Jolt/Physics/Collision/Shape/BoxShape.h>
#include <Jolt/Physics/Collision/Shape/CapsuleShape.h>
#include <Jolt/Physics/Collision/Shape/ConvexHullShape.h>
#include <Jolt/Physics/Collision/Shape/MeshShape.h>
#include <Jolt/Physics/Collision/Shape/RotatedTranslatedShape.h>
#include <Jolt/Physics/Collision/Shape/SphereShape.h>
#include <Jolt/Physics/Collision/Shape/StaticCompoundShape.h>
#include <Jolt/Physics/Character/CharacterVirtual.h>
#include <Jolt/Physics/Collision/CollideShape.h>
#include <Jolt/Physics/Collision/CollisionCollectorImpl.h>
#include <Jolt/Physics/Collision/CollisionDispatch.h>
#include <Jolt/Physics/Collision/ContactListener.h>
#include <limits>
#include <Jolt/Physics/Collision/ShapeCast.h>
#include <Jolt/RegisterTypes.h>

#include <cstddef>
#include <algorithm>
#include <cmath>
#include <vector>

using namespace JPH;
using esengine::physics3d::Context;
namespace Layers = esengine::physics3d::Layers;

namespace esengine::physics3d {
Context& ctx() {
    static Context instance;
    return instance;
}
LayerMatrix& layerMatrix() {
    static LayerMatrix instance;
    return instance;
}
}  // namespace esengine::physics3d

namespace {

Context& g() { return esengine::physics3d::ctx(); }

/// The temp allocator's arena. A step borrows from it and gives it all back, so
/// this is a ceiling on one step's working set rather than a running cost.
constexpr JPH::uint TEMP_ARENA_BYTES = 8 * 1024 * 1024;

/// Character ids and body ids are both small integers and share one owner map, so
/// a character's key is tagged apart. Bodies never reach this bit: Jolt packs a
/// BodyID's index into the low 23.
constexpr uint32_t CHARACTER_ID_TAG = 0x80000000u;

EMotionType motionTypeOf(int value) {
    switch (value) {
        case 1: return EMotionType::Kinematic;
        case 2: return EMotionType::Dynamic;
        default: return EMotionType::Static;
    }
}

ObjectLayer layerOf(EMotionType motion, uint32_t layer) {
    return esengine::physics3d::Layers::of(layer, motion != EMotionType::Static);
}

/// What a body is beyond its shape: how it answers to gravity, how it slows, and
/// whether the solver may turn it. Passed as one record because every add takes
/// the same set and a fourth positional float each would be unreadable.
struct BodyMotion {
    int motion = 0;
    float gravityScale = 1.0f;
    float linearDamping = 0.0f;
    float angularDamping = 0.0f;
    int fixedRotation = 0;
    uint32_t layer = 0;
    int continuous = 0;
};

/// The entity a body speaks for, or 0 when nothing claims it.
uint32_t entityOfBody(const BodyID& id) {
    auto found = g().entityOf.find(id.GetIndexAndSequenceNumber());
    return found == g().entityOf.end() ? 0u : found->second;
}

/**
 * Records what touched what. Jolt calls this with every body locked, so it reads
 * only its own tables and the geometry it is handed — never the world.
 */
class ContactRecorder final : public ContactListener {
public:
    void OnContactAdded(const Body& body1, const Body& body2, const ContactManifold& manifold,
                        ContactSettings&) override {
        const uint32_t a = body1.GetID().GetIndexAndSequenceNumber();
        const uint32_t b = body2.GetID().GetIndexAndSequenceNumber();
        const uint32_t entityA = entityOfBody(body1.GetID());
        const uint32_t entityB = entityOfBody(body2.GetID());
        if (entityA == 0 && entityB == 0) return;

        const bool aIsSensor = g().sensorBodies.count(a) != 0;
        const bool bIsSensor = g().sensorBodies.count(b) != 0;
        if (aIsSensor || bIsSensor) {
            // The sensor is named first, so a listener never has to work out
            // which of the two it subscribed to.
            g().sensorEnterBuffer.push_back(static_cast<float>(aIsSensor ? entityA : entityB));
            g().sensorEnterBuffer.push_back(static_cast<float>(aIsSensor ? entityB : entityA));
            return;
        }
        const RVec3 point = manifold.GetWorldSpaceContactPointOn1(0);
        const Vec3 normal = manifold.mWorldSpaceNormal;
        g().contactEnterBuffer.insert(g().contactEnterBuffer.end(), {
            static_cast<float>(entityA), static_cast<float>(entityB),
            normal.GetX(), normal.GetY(), normal.GetZ(),
            static_cast<float>(point.GetX()), static_cast<float>(point.GetY()),
            static_cast<float>(point.GetZ()),
        });
        // Read before the solver has answered the contact: what the two were doing as they met. The normal points from
        // the first into the second, so the first closing on the second is a positive speed.
        const Vec3 closing = body1.GetPointVelocity(point) - body2.GetPointVelocity(point);
        g().contactEnterSpeedBuffer.push_back(closing.Dot(normal));
        // A static or kinematic body is pushed by nothing: it gives no inverse mass to the meeting.
        const auto inverse = [](const Body& body) { return body.IsDynamic() ? body.GetMotionProperties()->GetInverseMass() : 0.0f; };
        const float both = inverse(body1) + inverse(body2);
        g().contactEnterMassBuffer.push_back(both > 0.0f ? 1.0f / both : std::numeric_limits<float>::infinity());
    }

    void OnContactRemoved(const SubShapeIDPair& pair) override {
        const uint32_t a = pair.GetBody1ID().GetIndexAndSequenceNumber();
        const uint32_t b = pair.GetBody2ID().GetIndexAndSequenceNumber();
        const uint32_t entityA = entityOfBody(pair.GetBody1ID());
        const uint32_t entityB = entityOfBody(pair.GetBody2ID());
        if (entityA == 0 && entityB == 0) return;

        const bool aIsSensor = g().sensorBodies.count(a) != 0;
        const bool bIsSensor = g().sensorBodies.count(b) != 0;
        std::vector<float>& out = (aIsSensor || bIsSensor) ? g().sensorExitBuffer
                                                           : g().contactExitBuffer;
        if (aIsSensor || bIsSensor) {
            out.push_back(static_cast<float>(aIsSensor ? entityA : entityB));
            out.push_back(static_cast<float>(aIsSensor ? entityB : entityA));
        } else {
            out.push_back(static_cast<float>(entityA));
            out.push_back(static_cast<float>(entityB));
        }
    }
};

ContactRecorder& recorder() {
    static ContactRecorder instance;
    return instance;
}

/// Register a shape as a body, and remember which entity it speaks for.
uint32_t addBody(uint32_t entity, const Ref<Shape>& shape, float px, float py, float pz,
                 float qx, float qy, float qz, float qw, const BodyMotion& how,
                 float friction, float restitution, int isSensor,
                 float cx = 0.0f, float cy = 0.0f, float cz = 0.0f, float mass = 0.0f) {
    if (!g().isValid()) return 0;
    // A collider off the entity's origin: the shape is carried by a translated wrapper, so the body (and what a dynamic one rotates about)
    // stays at the entity.
    Ref<Shape> placed = shape;
    // `> 0` is false for NaN too, so a caller that leaves the offset off gets a body at the origin.
    if (cx * cx + cy * cy + cz * cz > 0.0f) {
        const ShapeSettings::ShapeResult r = RotatedTranslatedShapeSettings(Vec3(cx, cy, cz), Quat::sIdentity(), shape).Create();
        if (r.IsValid()) placed = r.Get();
    }
    const EMotionType motionType = motionTypeOf(how.motion);
    BodyCreationSettings settings(placed, RVec3(px, py, pz), Quat(qx, qy, qz, qw).Normalized(),
                                  motionType, layerOf(motionType, how.layer));
    settings.mFriction = friction;
    settings.mRestitution = restitution;
    settings.mIsSensor = isSensor != 0;
    settings.mGravityFactor = how.gravityScale;
    settings.mLinearDamping = how.linearDamping;
    settings.mAngularDamping = how.angularDamping;
    if (mass > 0.0f && std::isfinite(mass) && motionType != EMotionType::Static) {
        settings.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
        settings.mMassPropertiesOverride.mMass = mass;
    }
    // What keeps a character upright: the solver may move it and never turn it.
    if (how.fixedRotation != 0) {
        settings.mAllowedDOFs = EAllowedDOFs::TranslationX | EAllowedDOFs::TranslationY
                              | EAllowedDOFs::TranslationZ;
    }
    // Discrete collision only asks where a body IS at the end of a step, so
    // anything that crosses more than its own thickness in one step arrives on the
    // far side of a wall having never touched it.
    if (how.continuous != 0) settings.mMotionQuality = EMotionQuality::LinearCast;
    BodyInterface& bodies = g().system->GetBodyInterface();
    const BodyID id = bodies.CreateAndAddBody(
        settings, motionType == EMotionType::Static ? EActivation::DontActivate
                                                    : EActivation::Activate);
    if (id.IsInvalid()) return 0;
    g().entityOf[id.GetIndexAndSequenceNumber()] = entity;
    if (isSensor != 0) g().sensorBodies.insert(id.GetIndexAndSequenceNumber());
    return id.GetIndexAndSequenceNumber();
}

}  // namespace

extern "C" {

// World lifecycle

EMSCRIPTEN_KEEPALIVE
void physics3d_init(float gx, float gy, float gz, uint32_t maxBodies) {
    if (g().isValid()) return;
    RegisterDefaultAllocator();
    // Factory and type registry are process-wide, so a world built after a
    // shutdown must not register them twice.
    if (Factory::sInstance == nullptr) {
        Factory::sInstance = new Factory();
        RegisterTypes();
    }
    g().factory = Factory::sInstance;
    g().temp = new TempAllocatorImpl(TEMP_ARENA_BYTES);
    g().jobs = new JobSystemSingleThreaded(cMaxPhysicsJobs);
    g().system = new PhysicsSystem();
    const uint32_t bodies = maxBodies > 0 ? maxBodies : 1024;
    g().system->Init(bodies, 0, bodies * 2, bodies * 2, g().broadPhaseLayers,
                     g().objectVsBroadPhase, g().objectPairs);
    g().system->SetGravity(Vec3(gx, gy, gz));
    g().system->SetContactListener(&recorder());
}

EMSCRIPTEN_KEEPALIVE
void physics3d_shutdown() {
    if (!g().isValid()) return;
    delete g().system;
    delete g().jobs;
    delete g().temp;
    g().system = nullptr;
    g().jobs = nullptr;
    g().temp = nullptr;
    g().characterVsCharacter.mCharacters.clear();
    g().characters.clear();
    g().sensorBodies.clear();
    g().contactEnterBuffer.clear();
    g().contactEnterSpeedBuffer.clear();
    g().contactEnterMassBuffer.clear();
    g().contactExitBuffer.clear();
    g().sensorEnterBuffer.clear();
    g().sensorExitBuffer.clear();
    g().entityOf.clear();
    g().transformBuffer.clear();
    g().queryBuffer.clear();
    // Factory/RegisterTypes are deliberately left standing: they are process-wide
    // and a second world would only re-register the same types.
}

EMSCRIPTEN_KEEPALIVE
int physics3d_isReady() { return g().isValid() ? 1 : 0; }

/**
 * @brief Declares which layers layer `layer` collides with.
 * @details Both sides must agree, so a body only meets another when each names
 *          the other — one of them saying no is enough to keep them apart. Set
 *          before bodies are registered: an ObjectLayer is fixed at creation.
 */
EMSCRIPTEN_KEEPALIVE
void physics3d_setLayerMask(uint32_t layer, uint32_t mask) {
    if (layer < esengine::physics3d::Layers::COUNT) {
        esengine::physics3d::layerMatrix().masks[layer] = mask;
    }
}

EMSCRIPTEN_KEEPALIVE
void physics3d_setSolver(int velocityIterations, int positionIterations, int allowSleep,
                         float bounceThreshold) {
    if (!g().isValid()) return;
    // From Jolt's own defaults, not from what is set now: 0 means "Jolt's value", so a
    // setting cleared after being changed goes back rather than staying where it was.
    const PhysicsSettings jolt;
    PhysicsSettings settings = g().system->GetPhysicsSettings();
    settings.mNumVelocitySteps = velocityIterations > 0 ? static_cast<JPH::uint>(velocityIterations) : jolt.mNumVelocitySteps;
    settings.mNumPositionSteps = positionIterations > 0 ? static_cast<JPH::uint>(positionIterations) : jolt.mNumPositionSteps;
    settings.mAllowSleeping = allowSleep != 0;
    settings.mMinVelocityForRestitution = bounceThreshold > 0.0f ? bounceThreshold : jolt.mMinVelocityForRestitution;
    g().system->SetPhysicsSettings(settings);
}

/// Advance the world, then refill the transform buffer with every active body.
EMSCRIPTEN_KEEPALIVE
void physics3d_step(float dt, int collisionSteps) {
    if (!g().isValid() || dt <= 0.0f) return;
    // No character moved this step: what the last one met has been read, and is not told again.
    if (g().characterHitsStale) g().characterHitBuffer.clear();
    g().solverStep = dt / static_cast<float>(std::max(collisionSteps, 1));
    // Cleared before the step, not after: the listener fires DURING Update, and a
    // buffer emptied afterwards would publish nothing.
    g().contactEnterBuffer.clear();
    g().contactEnterSpeedBuffer.clear();
    g().contactEnterMassBuffer.clear();
    g().contactExitBuffer.clear();
    g().sensorEnterBuffer.clear();
    g().sensorExitBuffer.clear();
    g().system->Update(dt, collisionSteps > 0 ? collisionSteps : 1, g().temp, g().jobs);

    BodyIDVector active;
    g().system->GetActiveBodies(EBodyType::RigidBody, active);
    const BodyInterface& bodies = g().system->GetBodyInterfaceNoLock();
    std::vector<float>& out = g().transformBuffer;
    out.clear();
    out.reserve(active.size() * 8);
    for (const BodyID& id : active) {
        auto owner = g().entityOf.find(id.GetIndexAndSequenceNumber());
        if (owner == g().entityOf.end()) continue;
        RVec3 position;
        Quat rotation;
        bodies.GetPositionAndRotation(id, position, rotation);
        out.push_back(static_cast<float>(owner->second));
        out.push_back(static_cast<float>(position.GetX()));
        out.push_back(static_cast<float>(position.GetY()));
        out.push_back(static_cast<float>(position.GetZ()));
        out.push_back(rotation.GetX());
        out.push_back(rotation.GetY());
        out.push_back(rotation.GetZ());
        out.push_back(rotation.GetW());
    }
    g().characterHitsStale = true;
}

/// Rebuild the broad-phase tree. Worth calling once after the static geometry of a
/// level is in, and never per frame.
EMSCRIPTEN_KEEPALIVE
void physics3d_optimize() {
    if (g().isValid()) g().system->OptimizeBroadPhase();
}

// Bodies

/// Each primitive is 11 floats: kind, dimensions.xyz, offset.xyz, rotation.xyzw.
/// The compound remains ONE body, so children cannot separate under gravity.
EMSCRIPTEN_KEEPALIVE
uint32_t physics3d_addCompound(uint32_t entity, uintptr_t partsPtr, uint32_t count,
                               float px, float py, float pz, float qx, float qy, float qz, float qw,
                               int motion, float gravityScale, float linearDamping, float angularDamping,
                               int fixedRotation, uint32_t layer, int continuous,
                               float friction, float restitution, int isSensor, float mass) {
    if (!g().isValid() || partsPtr == 0 || count == 0 || count > 16384) return 0;
    const float* parts = reinterpret_cast<const float*>(partsPtr);
    StaticCompoundShapeSettings settings;
    for (uint32_t i = 0; i < count; ++i) {
        const float* p = parts + i * 11;
        for (uint32_t j = 0; j < 11; ++j) if (!std::isfinite(p[j])) return 0;
        Ref<Shape> shape;
        if (p[0] == 0 && p[1] > 0 && p[2] > 0 && p[3] > 0) {
            const float convex = std::min(0.05f, std::min(p[1], std::min(p[2], p[3])) * 0.1f);
            shape = new BoxShape(Vec3(p[1], p[2], p[3]), convex);
        } else if (p[0] == 1 && p[1] > 0) shape = new SphereShape(p[1]);
        else if (p[0] == 2 && p[1] > 0 && p[2] >= 0) {
            if (p[2] == 0) shape = new SphereShape(p[1]);
            else shape = new CapsuleShape(p[2], p[1]);
        } else return 0;
        Quat rotation(p[7], p[8], p[9], p[10]);
        if (rotation.LengthSq() < 1.0e-12f) return 0;
        settings.AddShape(Vec3(p[4], p[5], p[6]), rotation.Normalized(), shape);
    }
    const auto result = settings.Create();
    if (result.HasError()) return 0;
    return addBody(entity, result.Get(), px, py, pz, qx, qy, qz, qw,
        {motion, gravityScale, linearDamping, angularDamping, fixedRotation, layer, continuous},
        friction, restitution, isSensor, 0, 0, 0, mass);
}

EMSCRIPTEN_KEEPALIVE
uint32_t physics3d_addBox(uint32_t entity, float hx, float hy, float hz,
                          float px, float py, float pz,
                          float qx, float qy, float qz, float qw,
                          int motion, float gravityScale, float linearDamping,
                          float angularDamping, int fixedRotation, uint32_t layer,
                          int continuous, float friction, float restitution, int isSensor,
                          float cx, float cy, float cz) {
    return addBody(entity, new BoxShape(Vec3(hx, hy, hz)), px, py, pz, qx, qy, qz, qw,
                   {motion, gravityScale, linearDamping, angularDamping, fixedRotation, layer,
                    continuous},
                   friction, restitution, isSensor, cx, cy, cz);
}

EMSCRIPTEN_KEEPALIVE
uint32_t physics3d_addSphere(uint32_t entity, float radius,
                             float px, float py, float pz,
                             float qx, float qy, float qz, float qw,
                             int motion, float gravityScale, float linearDamping,
                             float angularDamping, int fixedRotation, uint32_t layer,
                             int continuous, float friction, float restitution, int isSensor,
                          float cx, float cy, float cz) {
    return addBody(entity, new SphereShape(radius), px, py, pz, qx, qy, qz, qw,
                   {motion, gravityScale, linearDamping, angularDamping, fixedRotation, layer,
                    continuous},
                   friction, restitution, isSensor, cx, cy, cz);
}

/// `halfHeight` is the cylinder half-height, so the capsule is `2*halfHeight + 2*radius`
/// tall — the same convention CapsuleCollider2D uses in 2D.
EMSCRIPTEN_KEEPALIVE
uint32_t physics3d_addCapsule(uint32_t entity, float radius, float halfHeight,
                              float px, float py, float pz,
                              float qx, float qy, float qz, float qw,
                              int motion, float gravityScale, float linearDamping,
                              float angularDamping, int fixedRotation, uint32_t layer,
                              int continuous, float friction, float restitution, int isSensor,
                          float cx, float cy, float cz) {
    return addBody(entity, new CapsuleShape(halfHeight, radius), px, py, pz, qx, qy, qz, qw,
                   {motion, gravityScale, linearDamping, angularDamping, fixedRotation, layer,
                    continuous},
                   friction, restitution, isSensor, cx, cy, cz);
}

/**
 * @brief Registers imported geometry as a collider.
 * @details Triangles rather than a shape: the `.esmesh` format belongs to the
 *          asset layer, which hands over positions it has already extracted and
 *          scaled. A mesh collider is always STATIC — Jolt cannot give a triangle
 *          soup an inertia tensor, so there is nothing for a solver to push.
 * @param vertexPtr `vertexCount * 3` floats, in metres, in the body's own space.
 * @param indexPtr `indexCount` uint32 indices; must be a triangle list.
 */
EMSCRIPTEN_KEEPALIVE
uint32_t physics3d_addMeshBody(uint32_t entity, uintptr_t vertexPtr, uint32_t vertexCount,
                               uintptr_t indexPtr, uint32_t indexCount,
                               float px, float py, float pz,
                               float qx, float qy, float qz, float qw,
                               uint32_t layer, float friction, float restitution) {
    if (!g().isValid() || vertexCount == 0 || indexCount < 3 || indexCount % 3 != 0) return 0;
    const float* positions = reinterpret_cast<const float*>(vertexPtr);
    const uint32_t* indices = reinterpret_cast<const uint32_t*>(indexPtr);
    if (positions == nullptr || indices == nullptr) return 0;

    VertexList vertices;
    vertices.reserve(vertexCount);
    for (uint32_t i = 0; i < vertexCount; ++i) {
        vertices.push_back(Float3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]));
    }
    IndexedTriangleList triangles;
    triangles.reserve(indexCount / 3);
    for (uint32_t i = 0; i + 2 < indexCount; i += 3) {
        if (indices[i] >= vertexCount || indices[i + 1] >= vertexCount
            || indices[i + 2] >= vertexCount) {
            return 0;  // an index past the vertices would read whatever follows them
        }
        triangles.push_back(IndexedTriangle(indices[i], indices[i + 1], indices[i + 2], 0));
    }

    MeshShapeSettings settings(std::move(vertices), std::move(triangles));
    settings.SetEmbedded();
    ShapeSettings::ShapeResult shape = settings.Create();
    if (shape.HasError()) return 0;
    return addBody(entity, shape.Get(), px, py, pz, qx, qy, qz, qw,
                   {0, 1.0f, 0.0f, 0.0f, 0, layer}, friction, restitution, 0);
}

/**
 * @brief Registers the convex hull of imported geometry as a collider.
 * @details The hull is what makes imported geometry usable as a DYNAMIC body:
 *          Jolt cannot give a triangle soup an inertia tensor, so a mesh collider
 *          is scenery whatever its RigidBody3D says.
 * @param vertexPtr `vertexCount * 3` floats, in metres, in the body's own space.
 */
EMSCRIPTEN_KEEPALIVE
uint32_t physics3d_addConvexBody(uint32_t entity, uintptr_t vertexPtr, uint32_t vertexCount,
                                 float px, float py, float pz,
                                 float qx, float qy, float qz, float qw,
                                 int motion, float gravityScale, float linearDamping,
                                 float angularDamping, int fixedRotation, uint32_t layer,
                                 int continuous, float friction, float restitution,
                                 int isSensor) {
    // Three points are a triangle and enclose nothing; a hull needs a volume.
    if (!g().isValid() || vertexCount < 4) return 0;
    const float* positions = reinterpret_cast<const float*>(vertexPtr);
    if (positions == nullptr) return 0;

    Array<Vec3> points;
    points.reserve(vertexCount);
    for (uint32_t i = 0; i < vertexCount; ++i) {
        points.push_back(Vec3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]));
    }
    ConvexHullShapeSettings settings(points);
    settings.SetEmbedded();
    ShapeSettings::ShapeResult shape = settings.Create();
    // Degenerate input — every point on a plane, or all of them the same — has no
    // hull, and a body with no shape is an invisible point that falls forever.
    if (shape.HasError()) return 0;
    return addBody(entity, shape.Get(), px, py, pz, qx, qy, qz, qw,
                   {motion, gravityScale, linearDamping, angularDamping, fixedRotation, layer,
                    continuous},
                   friction, restitution, isSensor);
}

EMSCRIPTEN_KEEPALIVE
void physics3d_removeBody(uint32_t bodyId) {
    if (!g().isValid() || bodyId == 0) return;
    const BodyID id(bodyId);
    BodyInterface& bodies = g().system->GetBodyInterface();
    bodies.RemoveBody(id);
    bodies.DestroyBody(id);
    g().entityOf.erase(bodyId);
    g().sensorBodies.erase(bodyId);
}

EMSCRIPTEN_KEEPALIVE
void physics3d_setTransform(uint32_t bodyId, float px, float py, float pz,
                            float qx, float qy, float qz, float qw) {
    if (!g().isValid() || bodyId == 0) return;
    g().system->GetBodyInterface().SetPositionAndRotation(
        BodyID(bodyId), RVec3(px, py, pz), Quat(qx, qy, qz, qw).Normalized(),
        EActivation::Activate);
}

EMSCRIPTEN_KEEPALIVE
void physics3d_setLinearVelocity(uint32_t bodyId, float vx, float vy, float vz) {
    if (!g().isValid() || bodyId == 0) return;
    g().system->GetBodyInterface().SetLinearVelocity(BodyID(bodyId), Vec3(vx, vy, vz));
}

EMSCRIPTEN_KEEPALIVE
void physics3d_setMass(uint32_t bodyId, float mass) {
    if (!g().isValid() || bodyId == 0 || !(mass > 0.0f) || !std::isfinite(mass)) return;
    const BodyLockWrite lock(g().system->GetBodyLockInterface(), BodyID(bodyId));
    if (!lock.Succeeded() || !lock.GetBody().IsDynamic()) return;
    Body& body = lock.GetBody();
    // The shape's own mass properties, as the density gave them, brought to the mass asked: its inertia comes along.
    MassProperties props = body.GetShape()->GetMassProperties();
    props.ScaleToMass(mass);
    MotionProperties* motion = body.GetMotionProperties();
    motion->SetMassProperties(motion->GetAllowedDOFs(), props);
}

/// Writes (px,py,pz, qx,qy,qz,qw, vx,vy,vz) into the query buffer; 0 when the body
/// is gone. One body's state, for a caller that wants it outside the step readback.
EMSCRIPTEN_KEEPALIVE
int physics3d_getBodyState(uint32_t bodyId) {
    if (!g().isValid() || bodyId == 0) return 0;
    const BodyInterface& bodies = g().system->GetBodyInterface();
    const BodyID id(bodyId);
    if (!bodies.IsAdded(id)) return 0;
    RVec3 position;
    Quat rotation;
    bodies.GetPositionAndRotation(id, position, rotation);
    const Vec3 velocity = bodies.GetLinearVelocity(id);
    g().queryBuffer = {
        static_cast<float>(position.GetX()), static_cast<float>(position.GetY()),
        static_cast<float>(position.GetZ()), rotation.GetX(), rotation.GetY(),
        rotation.GetZ(), rotation.GetW(), velocity.GetX(), velocity.GetY(), velocity.GetZ(),
    };
    return 1;
}

/// Writes (mass, wx,wy,wz) into the query buffer: the body's mass in kilograms and its angular velocity in radians a
/// second, world space. 0 when the body is gone or does not move (a static or kinematic body has no mass to push).
EMSCRIPTEN_KEEPALIVE
int physics3d_getBodyDynamics(uint32_t bodyId) {
    if (!g().isValid() || bodyId == 0) return 0;
    const BodyLockRead lock(g().system->GetBodyLockInterface(), BodyID(bodyId));
    if (!lock.Succeeded() || !lock.GetBody().IsDynamic()) return 0;
    const Body& body = lock.GetBody();
    const float inverseMass = body.GetMotionProperties()->GetInverseMass();
    if (!(inverseMass > 0.0f)) return 0;
    const Vec3 spin = body.GetAngularVelocity();
    g().queryBuffer = { 1.0f / inverseMass, spin.GetX(), spin.GetY(), spin.GetZ() };
    return 1;
}

/// A force of (fx, fy, fz) newtons at the world point (px, py, pz), over the next step. It turns the body as well as pushing it,
/// by as much as the point is off the centre of mass; and it wakes a body that has gone to sleep.
EMSCRIPTEN_KEEPALIVE
void physics3d_addForce(uint32_t bodyId, float fx, float fy, float fz, float px, float py, float pz) {
    if (!g().isValid() || bodyId == 0) return;
    // A point that is not a number is its centre of mass: pushed there, it turns nothing.
    if (std::isfinite(px) && std::isfinite(py) && std::isfinite(pz)) g().system->GetBodyInterface().AddForce(BodyID(bodyId), Vec3(fx, fy, fz), RVec3(px, py, pz));
    else g().system->GetBodyInterface().AddForce(BodyID(bodyId), Vec3(fx, fy, fz));
}

EMSCRIPTEN_KEEPALIVE
void physics3d_addImpulse(uint32_t bodyId, float ix, float iy, float iz, float px, float py, float pz) {
    if (!g().isValid() || bodyId == 0) return;
    BodyInterface& bodies = g().system->GetBodyInterface();
    if (bodies.GetMotionType(BodyID(bodyId)) != EMotionType::Dynamic) return;
    if (std::isfinite(px) && std::isfinite(py) && std::isfinite(pz)) bodies.AddImpulse(BodyID(bodyId), Vec3(ix, iy, iz), RVec3(px, py, pz));
    else bodies.AddImpulse(BodyID(bodyId), Vec3(ix, iy, iz));
}

EMSCRIPTEN_KEEPALIVE
void physics3d_addAngularImpulse(uint32_t bodyId, float ix, float iy, float iz) {
    if (!g().isValid() || bodyId == 0) return;
    BodyInterface& bodies = g().system->GetBodyInterface();
    if (bodies.GetMotionType(BodyID(bodyId)) != EMotionType::Dynamic) return;
    bodies.AddAngularImpulse(BodyID(bodyId), Vec3(ix, iy, iz));
}

EMSCRIPTEN_KEEPALIVE
void physics3d_setAngularVelocity(uint32_t bodyId, float wx, float wy, float wz) {
    if (!g().isValid() || bodyId == 0) return;
    BodyInterface& bodies = g().system->GetBodyInterface();
    if (bodies.GetMotionType(BodyID(bodyId)) == EMotionType::Static) return;
    bodies.SetAngularVelocity(BodyID(bodyId), Vec3(wx, wy, wz));
    bodies.ActivateBody(BodyID(bodyId));
}

EMSCRIPTEN_KEEPALIVE
void physics3d_setGravity(float gx, float gy, float gz) {
    if (!g().isValid()) return;
    g().system->SetGravity(Vec3(gx, gy, gz));
}

EMSCRIPTEN_KEEPALIVE
void physics3d_setAwake(uint32_t bodyId, int awake) {
    if (!g().isValid() || bodyId == 0) return;
    BodyInterface& bodies = g().system->GetBodyInterface();
    if (bodies.GetMotionType(BodyID(bodyId)) == EMotionType::Static) return;
    if (awake) bodies.ActivateBody(BodyID(bodyId)); else bodies.DeactivateBody(BodyID(bodyId));
}

EMSCRIPTEN_KEEPALIVE
int physics3d_isAwake(uint32_t bodyId) {
    if (!g().isValid() || bodyId == 0) return 0;
    return g().system->GetBodyInterface().IsActive(BodyID(bodyId)) ? 1 : 0;
}

EMSCRIPTEN_KEEPALIVE
int physics3d_getBodyMassData(uint32_t bodyId) {
    if (!g().isValid() || bodyId == 0) return 0;
    const BodyLockRead lock(g().system->GetBodyLockInterface(), BodyID(bodyId));
    if (!lock.Succeeded() || !lock.GetBody().IsDynamic()) return 0;
    const Body& body = lock.GetBody();
    const MotionProperties* motion = body.GetMotionProperties();
    const float inverseMass = motion->GetInverseMass();
    if (!(inverseMass > 0.0f)) return 0;
    const RVec3 centre = body.GetCenterOfMassPosition();
    // About the body's own axes, not Jolt's principal ones, which it orders as it likes: a twist about an axis alone
    // turns it by inverse-inertia along that axis, and the moment is its inverse.
    const Mat44 inverse = motion->GetLocalSpaceInverseInertia();
    const auto moment = [](float i) { return i > 0.0f ? 1.0f / i : std::numeric_limits<float>::infinity(); };
    g().queryBuffer = { 1.0f / inverseMass,
                        static_cast<float>(centre.GetX()), static_cast<float>(centre.GetY()), static_cast<float>(centre.GetZ()),
                        moment(inverse(0, 0)), moment(inverse(1, 1)), moment(inverse(2, 2)) };
    return 1;
}

/// A torque of (tx, ty, tz) newton metres, over the next step.
EMSCRIPTEN_KEEPALIVE
void physics3d_addTorque(uint32_t bodyId, float tx, float ty, float tz) {
    if (!g().isValid() || bodyId == 0) return;
    g().system->GetBodyInterface().AddTorque(BodyID(bodyId), Vec3(tx, ty, tz));
}

// Characters

/**
 * @brief Registers a character: an upright capsule swept against the world.
 * @param maxSlope Steepest ground the character can stand on, in radians.
 * @return the character id, or 0 when there is no world.
 */
EMSCRIPTEN_KEEPALIVE
uint32_t physics3d_addCharacter(uint32_t entity, float radius, float halfHeight,
                                float px, float py, float pz, float maxSlope, float mass,
                                uint32_t layer, float pushForce) {
    if (!g().isValid()) return 0;
    Ref<CharacterVirtualSettings> settings = new CharacterVirtualSettings();
    settings->mShape = new CapsuleShape(halfHeight, radius);
    settings->mMaxSlopeAngle = maxSlope;
    settings->mMass = mass;
    // Nothing gets out of a swept character's way on its own: this is the force
    // it may spend shoving what it walks into.
    settings->mMaxStrength = pushForce;
    // The plane below which contacts do not hold the character up. Without it a
    // contact anywhere on the capsule — including the top — reads as ground.
    settings->mSupportingVolume = Plane(Vec3::sAxisY(), -radius);
    auto character = std::make_unique<CharacterVirtual>(
        settings, RVec3(px, py, pz), Quat::sIdentity(), g().system);
    // Every character checks against every other one. Brute force, which is what
    // Jolt offers and what a crowd of the size a scene authors costs nothing at.
    character->SetCharacterVsCharacterCollision(&g().characterVsCharacter);
    g().characterVsCharacter.Add(character.get());
    const uint32_t id = g().nextCharacterId++;
    g().characterLayers[id] = layer;
    g().characters[id] = std::move(character);
    g().entityOf[id | CHARACTER_ID_TAG] = entity;
    return id;
}

EMSCRIPTEN_KEEPALIVE
void physics3d_removeCharacter(uint32_t characterId) {
    auto found = g().characters.find(characterId);
    if (found != g().characters.end()) g().characterVsCharacter.Remove(found->second.get());
    g().characters.erase(characterId);
    g().characterLayers.erase(characterId);
    g().characterTouching.erase(characterId);
    g().entityOf.erase(characterId | CHARACTER_ID_TAG);
}

/**
 * @brief Moves a character by its velocity for one step.
 * @details ExtendedUpdate is Jolt's own combination of move, stick-to-floor and
 *          walk-stairs: without it a character stops dead at a 10cm step and
 *          launches off the top of every slope it walks down.
 *          Writes (px,py,pz, groundState, nx,ny,nz, vx,vy,vz) to the query buffer.
 */
/// What a character ran into on this move that it was not already touching: told once, with how fast it closed and the
/// mass it met with, as a contact between bodies is.
static void noteCharacterMeetings(uint32_t characterId, const CharacterVirtual& character, Vec3Arg velocity) {
    if (g().characterHitsStale) { g().characterHitBuffer.clear(); g().characterHitsStale = false; }
    std::vector<uint32_t>& touching = g().characterTouching[characterId];
    std::vector<uint32_t> now;
    const auto self = g().entityOf.find(characterId | CHARACTER_ID_TAG);
    const float own = character.GetMass() > 0.0f ? 1.0f / character.GetMass() : 0.0f;
    for (const auto& contact : character.GetActiveContacts()) {
        if (!contact.mHadCollision || contact.mWasDiscarded || contact.mBodyB.IsInvalid()) continue;
        const uint32_t key = contact.mBodyB.GetIndexAndSequenceNumber();
        if (std::find(now.begin(), now.end(), key) != now.end()) continue;
        now.push_back(key);
        if (std::find(touching.begin(), touching.end(), key) != touching.end()) continue;
        float other = 0.0f;
        {
            const BodyLockRead lock(g().system->GetBodyLockInterface(), contact.mBodyB);
            if (lock.Succeeded() && lock.GetBody().IsDynamic()) other = lock.GetBody().GetMotionProperties()->GetInverseMass();
        }
        const float both = own + other;
        const auto owner = g().entityOf.find(key);
        // The normal points toward the character: closing on what it met is moving against it.
        const float closing = -(velocity - contact.mLinearVelocity).Dot(contact.mContactNormal);
        g().characterHitBuffer.insert(g().characterHitBuffer.end(), {
            self == g().entityOf.end() ? 0.0f : static_cast<float>(self->second),
            owner == g().entityOf.end() ? 0.0f : static_cast<float>(owner->second),
            static_cast<float>(contact.mPosition.GetX()), static_cast<float>(contact.mPosition.GetY()), static_cast<float>(contact.mPosition.GetZ()),
            contact.mContactNormal.GetX(), contact.mContactNormal.GetY(), contact.mContactNormal.GetZ(),
            std::max(closing, 0.0f), both > 0.0f ? 1.0f / both : std::numeric_limits<float>::infinity(),
        });
    }
    touching.swap(now);
}

EMSCRIPTEN_KEEPALIVE
void physics3d_moveCharacter(uint32_t characterId, float vx, float vy, float vz,
                             float dt, float stepUp, float stepDown) {
    g().queryBuffer.clear();
    auto found = g().characters.find(characterId);
    if (!g().isValid() || found == g().characters.end()) return;
    CharacterVirtual& character = *found->second;

    // A CharacterVirtual does not fall on its own — its gravity parameter only
    // pushes down on what it stands on, and the vertical speed is the caller's.
    // Carried here so `vy = 0` means "walk", not "hang in the air".
    float vertical = character.GetLinearVelocity().GetY();
    if (vy != 0.0f) {
        vertical = vy;  // a jump, or a deliberate dive
    } else if (character.GetGroundState() == CharacterVirtual::EGroundState::OnGround) {
        vertical = 0.0f;
    } else {
        vertical += g().system->GetGravity().GetY() * dt;
    }
    character.SetLinearVelocity(Vec3(vx, vertical, vz));
    // Where it stood before the sweep. GetLinearVelocity afterwards returns what
    // we PUT there — ExtendedUpdate moves the character without rewriting it — so
    // the only honest answer is the ground it covered over the time it had.
    const RVec3 startedAt = character.GetPosition();
    CharacterVirtual::ExtendedUpdateSettings settings;
    settings.mWalkStairsStepUp = Vec3(0, stepUp, 0);
    settings.mStickToFloorStepDown = Vec3(0, -stepDown, 0);
    const ObjectLayer objectLayer = esengine::physics3d::Layers::of(
        g().characterLayers.count(characterId) ? g().characterLayers[characterId] : 0, true);
    character.ExtendedUpdate(dt, g().system->GetGravity(), settings,
                             g().system->GetDefaultBroadPhaseLayerFilter(objectLayer),
                             g().system->GetDefaultLayerFilter(objectLayer),
                             {}, {}, *g().temp);

    noteCharacterMeetings(characterId, character, Vec3(vx, vertical, vz));

    const RVec3 position = character.GetPosition();
    const Vec3 normal = character.GetGroundNormal();
    // The velocity it REACHED, not the one it was given: a character shoving a
    // wall keeps the velocity it asked for and covers no ground, and gameplay
    // reading the request back would never know the difference.
    const Vec3 velocity = dt > 0.0f
        ? Vec3((position - startedAt) / dt)
        : Vec3::sZero();
    g().queryBuffer = {
        static_cast<float>(position.GetX()), static_cast<float>(position.GetY()),
        static_cast<float>(position.GetZ()),
        static_cast<float>(character.GetGroundState()),
        normal.GetX(), normal.GetY(), normal.GetZ(),
        velocity.GetX(), velocity.GetY(), velocity.GetZ(),
    };
}

/**
 * @brief Puts a character somewhere, rather than moving it there.
 * @details The velocity goes with it. A CharacterVirtual carries its own
 *          vertical speed between steps, so a character teleported mid-fall
 *          would arrive still falling and drive itself through the floor it
 *          was placed on.
 */
EMSCRIPTEN_KEEPALIVE
void physics3d_setCharacterPosition(uint32_t characterId, float px, float py, float pz) {
    auto found = g().characters.find(characterId);
    if (found == g().characters.end()) return;
    found->second->SetPosition(RVec3(px, py, pz));
    found->second->SetLinearVelocity(Vec3::sZero());
}

// Queries

namespace {

/// Restricts a query to the layers a caller named. A zero mask means EVERY layer
/// rather than none: a caller that did not ask to filter is asking for
/// everything, and the other reading would silently return nothing.
class MaskLayerFilter final : public ObjectLayerFilter {
public:
    explicit MaskLayerFilter(uint32_t mask) : mask_(mask == 0 ? 0xFFFFFFFFu : mask) {}
    bool ShouldCollide(ObjectLayer layer) const override {
        return (mask_ & (1u << esengine::physics3d::Layers::indexOf(layer))) != 0;
    }
private:
    uint32_t mask_;
};

/// Appends one hit's (entity, px,py,pz) to the query buffer.
void pushEntityHit(uint32_t entity, RVec3Arg point) {
    g().queryBuffer.push_back(static_cast<float>(entity));
    g().queryBuffer.push_back(static_cast<float>(point.GetX()));
    g().queryBuffer.push_back(static_cast<float>(point.GetY()));
    g().queryBuffer.push_back(static_cast<float>(point.GetZ()));
}

void pushHit(const BodyID& id, RVec3Arg point) {
    auto owner = g().entityOf.find(id.GetIndexAndSequenceNumber());
    pushEntityHit(owner == g().entityOf.end() ? 0u : owner->second, point);
}

/// Whether a layer index passes a mask, where 0 means every layer.
bool layerPasses(uint32_t mask, uint32_t layerIndex) {
    return ((mask == 0 ? 0xFFFFFFFFu : mask) & (1u << layerIndex)) != 0;
}

/**
 * @brief Characters overlapping `shape`, appended to the query buffer.
 * @details A CharacterVirtual is swept against the world and is not IN it, so the
 *          narrow phase has no body to find — and every player and every enemy is
 *          one. Overlap only: what a RAY meets is a separate question with its own
 *          consumers (line of sight, the camera's boom).
 */
int collideCharacters(const Shape* shape, RMat44Arg transform,
                      const CollideShapeSettings& settings, uint32_t layerMask) {
    int found = 0;
    for (const auto& entry : g().characters) {
        const auto layer = g().characterLayers.find(entry.first);
        if (!layerPasses(layerMask, layer == g().characterLayers.end() ? 0u : layer->second)) {
            continue;
        }
        const auto owner = g().entityOf.find(entry.first | CHARACTER_ID_TAG);
        if (owner == g().entityOf.end()) continue;

        ClosestHitCollisionCollector<CollideShapeCollector> collector;
        CollisionDispatch::sCollideShapeVsShape(
            shape, entry.second->GetShape(),
            Vec3::sReplicate(1.0f), Vec3::sReplicate(1.0f),
            transform, entry.second->GetCenterOfMassTransform(),
            SubShapeIDCreator(), SubShapeIDCreator(), settings, collector);
        if (!collector.HadHit()) continue;
        pushEntityHit(owner->second, collector.mHit.mContactPointOn2);
        found++;
    }
    return found;
}

/// Everything overlapping `shape` at `position`, into the query buffer.
int collideShape(const Shape* shape, float px, float py, float pz, uint32_t layerMask) {
    g().queryBuffer.clear();
    if (!g().isValid() || shape == nullptr) return 0;
    AllHitCollisionCollector<CollideShapeCollector> collector;
    const CollideShapeSettings settings;
    const RMat44 transform = RMat44::sTranslation(RVec3(px, py, pz));
    const MaskLayerFilter filter(layerMask);
    g().system->GetNarrowPhaseQuery().CollideShape(
        shape, Vec3::sReplicate(1.0f), transform, settings, RVec3::sZero(), collector,
        {}, filter);
    for (const CollideShapeResult& hit : collector.mHits) {
        pushHit(hit.mBodyID2, hit.mContactPointOn2);
    }
    return static_cast<int>(collector.mHits.size())
        + collideCharacters(shape, transform, settings, layerMask);
}

}  // namespace

/**
 * @brief Everything a sphere at this position overlaps.
 * @details Writes (entity, px,py,pz) per hit into the query buffer and returns
 *          how many — the question a spawn point asks before it spawns.
 */
EMSCRIPTEN_KEEPALIVE
int physics3d_overlapSphere(float px, float py, float pz, float radius, uint32_t layerMask) {
    if (radius <= 0.0f) { g().queryBuffer.clear(); return 0; }
    const SphereShape shape(radius);
    return collideShape(&shape, px, py, pz, layerMask);
}

/** @brief The same for a box, given its half-extents. */
EMSCRIPTEN_KEEPALIVE
int physics3d_overlapBox(float px, float py, float pz, float hx, float hy, float hz,
                         uint32_t layerMask) {
    if (hx <= 0.0f || hy <= 0.0f || hz <= 0.0f) { g().queryBuffer.clear(); return 0; }
    const BoxShape shape(Vec3(hx, hy, hz));
    return collideShape(&shape, px, py, pz, layerMask);
}

/**
 * @brief Sweeps a sphere along a path and reports the first thing it meets.
 * @details What a ray cannot answer: a ray is infinitely thin, so it slips through
 *          the very gaps a moving body would not fit. Writes
 *          (entity, fraction, px,py,pz, nx,ny,nz); returns 0 for a clear path.
 */
static int castShapeQuery(const Shape& shape, RMat44Arg start, Vec3Arg direction, uint32_t layerMask);

EMSCRIPTEN_KEEPALIVE
int physics3d_sphereCast(float px, float py, float pz, float radius,
                         float dx, float dy, float dz, uint32_t layerMask) {
    g().queryBuffer.clear();
    if (!g().isValid() || radius <= 0.0f) return 0;
    const SphereShape shape(radius);
    return castShapeQuery(shape, RMat44::sTranslation(RVec3(px, py, pz)), Vec3(dx, dy, dz), layerMask);
}

/// A turn that is not one - zero, or not a number - is no turn.
static Quat turnOf(float qx, float qy, float qz, float qw) {
    const Quat q(qx, qy, qz, qw);
    const float length = q.Length();
    return std::isfinite(length) && length > 1e-6f ? q / length : Quat::sIdentity();
}

EMSCRIPTEN_KEEPALIVE
int physics3d_boxCast(float px, float py, float pz, float hx, float hy, float hz,
                      float qx, float qy, float qz, float qw, float dx, float dy, float dz, uint32_t layerMask) {
    g().queryBuffer.clear();
    if (!g().isValid() || !(hx > 0.0f) || !(hy > 0.0f) || !(hz > 0.0f)) return 0;
    // Rounded no more than its thinnest side allows: a box a centimetre thick is still a box.
    const BoxShape shape(Vec3(hx, hy, hz), std::min({0.05f, hx, hy, hz}));
    return castShapeQuery(shape, RMat44::sRotationTranslation(turnOf(qx, qy, qz, qw), RVec3(px, py, pz)), Vec3(dx, dy, dz), layerMask);
}

EMSCRIPTEN_KEEPALIVE
int physics3d_capsuleCast(float px, float py, float pz, float radius, float halfHeight,
                          float qx, float qy, float qz, float qw, float dx, float dy, float dz, uint32_t layerMask) {
    g().queryBuffer.clear();
    if (!g().isValid() || !(radius > 0.0f) || !(halfHeight >= 0.0f)) return 0;
    if (halfHeight == 0.0f) return physics3d_sphereCast(px, py, pz, radius, dx, dy, dz, layerMask);
    const CapsuleShape shape(halfHeight, radius);
    return castShapeQuery(shape, RMat44::sRotationTranslation(turnOf(qx, qy, qz, qw), RVec3(px, py, pz)), Vec3(dx, dy, dz), layerMask);
}

/// The first body a shape swept from `start` along `direction` meets, written to the query buffer as
/// (entity, fraction, px,py,pz, nx,ny,nz); 1 for a hit.
static int castShapeQuery(const Shape& shape, RMat44Arg start, Vec3Arg direction, uint32_t layerMask) {
    const RShapeCast cast(&shape, Vec3::sReplicate(1.0f), start, direction);
    ClosestHitCollisionCollector<CastShapeCollector> collector;
    const ShapeCastSettings settings;
    const MaskLayerFilter filter(layerMask);
    g().system->GetNarrowPhaseQuery().CastShape(cast, settings, RVec3::sZero(), collector,
                                                {}, filter);
    if (!collector.HadHit()) return 0;

    const ShapeCastResult& hit = collector.mHit;
    auto owner = g().entityOf.find(hit.mBodyID2.GetIndexAndSequenceNumber());
    const RVec3 point = hit.mContactPointOn2;
    const Vec3 normal = -hit.mPenetrationAxis.Normalized();
    g().queryBuffer = {
        owner == g().entityOf.end() ? 0.0f : static_cast<float>(owner->second),
        hit.mFraction,
        static_cast<float>(point.GetX()), static_cast<float>(point.GetY()),
        static_cast<float>(point.GetZ()),
        normal.GetX(), normal.GetY(), normal.GetZ(),
    };
    return 1;
}

/// Nearest hit along the ray. Writes (entity, fraction, px,py,pz, nx,ny,nz) into the
/// query buffer and returns 1; returns 0 and leaves it empty when nothing is hit.
EMSCRIPTEN_KEEPALIVE
int physics3d_raycast(float ox, float oy, float oz, float dx, float dy, float dz,
                      uint32_t layerMask) {
    g().queryBuffer.clear();
    if (!g().isValid()) return 0;
    const RRayCast ray{RVec3(ox, oy, oz), Vec3(dx, dy, dz)};
    RayCastResult hit;
    const MaskLayerFilter filter(layerMask);
    if (!g().system->GetNarrowPhaseQuery().CastRay(ray, hit, {}, filter)) return 0;

    const RVec3 point = ray.GetPointOnRay(hit.mFraction);
    const BodyLockRead lock(g().system->GetBodyLockInterface(), hit.mBodyID);
    Vec3 normal = Vec3::sZero();
    if (lock.Succeeded()) {
        normal = lock.GetBody().GetWorldSpaceSurfaceNormal(hit.mSubShapeID2, point);
    }
    auto owner = g().entityOf.find(hit.mBodyID.GetIndexAndSequenceNumber());
    g().queryBuffer = {
        owner == g().entityOf.end() ? 0.0f : static_cast<float>(owner->second),
        hit.mFraction,
        static_cast<float>(point.GetX()), static_cast<float>(point.GetY()),
        static_cast<float>(point.GetZ()),
        normal.GetX(), normal.GetY(), normal.GetZ(),
    };
    return 1;
}

EMSCRIPTEN_KEEPALIVE
int physics3d_raycastAll(float ox, float oy, float oz, float dx, float dy, float dz, uint32_t layerMask, uint32_t maxHits) {
    g().queryBuffer.clear();
    if (!g().isValid() || maxHits == 0) return 0;
    const Vec3 direction(dx, dy, dz);
    if (!(direction.LengthSq() > 0.0f)) return 0;
    const MaskLayerFilter filter(layerMask);
    const RayCastSettings settings;
    // Where the line goes into each body, from its start; and where it comes out, by going in from its end.
    AllHitCollisionCollector<CastRayCollector> forward, backward;
    g().system->GetNarrowPhaseQuery().CastRay(RRayCast{RVec3(ox, oy, oz), direction}, settings, forward, {}, filter);
    g().system->GetNarrowPhaseQuery().CastRay(RRayCast{RVec3(ox, oy, oz) + direction, -direction}, settings, backward, {}, filter);
    struct Crossing { BodyID body; SubShapeID part; float entry; float exit; };
    std::vector<Crossing> crossings;
    for (const RayCastResult& hit : forward.mHits) {
        auto same = std::find_if(crossings.begin(), crossings.end(), [&](const Crossing& c) { return c.body == hit.mBodyID; });
        if (same == crossings.end()) crossings.push_back({hit.mBodyID, hit.mSubShapeID2, hit.mFraction, 1.0f});
        else if (hit.mFraction < same->entry) { same->entry = hit.mFraction; same->part = hit.mSubShapeID2; }
    }
    for (Crossing& c : crossings) {
        float exit = 1.0f;
        for (const RayCastResult& hit : backward.mHits) if (hit.mBodyID == c.body) exit = std::min(exit, 1.0f - hit.mFraction);
        // A body the line ends inside is met by the backward line at once: it comes out nowhere short of the end.
        c.exit = std::max(exit, c.entry);
    }
    std::sort(crossings.begin(), crossings.end(), [](const Crossing& a, const Crossing& b) { return a.entry < b.entry; });
    if (crossings.size() > maxHits) crossings.resize(maxHits);
    for (const Crossing& c : crossings) {
        const RVec3 point = RVec3(ox, oy, oz) + Vec3(direction * c.entry);
        Vec3 normal = Vec3::sZero();
        const BodyLockRead lock(g().system->GetBodyLockInterface(), c.body);
        if (lock.Succeeded()) normal = lock.GetBody().GetWorldSpaceSurfaceNormal(c.part, point);
        auto owner = g().entityOf.find(c.body.GetIndexAndSequenceNumber());
        g().queryBuffer.insert(g().queryBuffer.end(), {
            owner == g().entityOf.end() ? 0.0f : static_cast<float>(owner->second), c.entry, c.exit,
            static_cast<float>(point.GetX()), static_cast<float>(point.GetY()), static_cast<float>(point.GetZ()),
            normal.GetX(), normal.GetY(), normal.GetZ(),
        });
    }
    return static_cast<int>(crossings.size());
}

/**
 * @brief The world's nearest hit, or a character's when one is nearer and `flags` bit 0 asks for them.
 * @details A CharacterVirtual is not a body, so the narrow phase cannot meet it; each capsule is cast against in its
 *          own space instead, which is what Jolt's own CharacterVirtual queries do. A ray that starts inside a capsule
 *          meets it at 0 — a shooter's own character is left out by its layer.
 */
EMSCRIPTEN_KEEPALIVE
int physics3d_raycastWith(float ox, float oy, float oz, float dx, float dy, float dz,
                          uint32_t layerMask, uint32_t flags) {
    const int worldHit = physics3d_raycast(ox, oy, oz, dx, dy, dz, layerMask);
    if ((flags & 1u) == 0 || !g().isValid()) return worldHit;
    float best = worldHit ? g().queryBuffer[1] : 1.0f;
    const RRayCast ray{RVec3(ox, oy, oz), Vec3(dx, dy, dz)};
    uint32_t entity = 0;
    Vec3 normal = Vec3::sZero();
    bool found = false;
    for (const auto& entry : g().characters) {
        const auto layer = g().characterLayers.find(entry.first);
        if (!layerPasses(layerMask, layer == g().characterLayers.end() ? 0u : layer->second)) continue;
        const auto owner = g().entityOf.find(entry.first | CHARACTER_ID_TAG);
        if (owner == g().entityOf.end()) continue;
        const RMat44 com = entry.second->GetCenterOfMassTransform();
        const RayCast local(ray.Transformed(com.InversedRotationTranslation()));
        RayCastResult hit;
        hit.mFraction = best;
        const Shape* shape = entry.second->GetShape();
        if (!shape->CastRay(local, SubShapeIDCreator(), hit) || hit.mFraction >= best) continue;
        best = hit.mFraction;
        entity = owner->second;
        normal = com.Multiply3x3(shape->GetSurfaceNormal(hit.mSubShapeID2, local.GetPointOnRay(best))).NormalizedOr(Vec3::sAxisY());
        found = true;
    }
    if (!found) return worldHit;
    const RVec3 point = ray.GetPointOnRay(best);
    g().queryBuffer = {
        static_cast<float>(entity), best,
        static_cast<float>(point.GetX()), static_cast<float>(point.GetY()), static_cast<float>(point.GetZ()),
        normal.GetX(), normal.GetY(), normal.GetZ(),
    };
    return 1;
}

// Readback

EMSCRIPTEN_KEEPALIVE
uintptr_t physics3d_transforms() {
    return reinterpret_cast<uintptr_t>(g().transformBuffer.data());
}

EMSCRIPTEN_KEEPALIVE
size_t physics3d_transformsBytes() {
    return g().transformBuffer.size() * sizeof(float);
}

EMSCRIPTEN_KEEPALIVE
uintptr_t physics3d_characterHits() {
    return reinterpret_cast<uintptr_t>(g().characterHitBuffer.data());
}

EMSCRIPTEN_KEEPALIVE
size_t physics3d_characterHitsBytes() {
    return g().characterHitBuffer.size() * sizeof(float);
}

EMSCRIPTEN_KEEPALIVE
uintptr_t physics3d_contactEnterMasses() {
    return reinterpret_cast<uintptr_t>(g().contactEnterMassBuffer.data());
}

EMSCRIPTEN_KEEPALIVE
size_t physics3d_contactEnterMassesBytes() {
    return g().contactEnterMassBuffer.size() * sizeof(float);
}

EMSCRIPTEN_KEEPALIVE
uintptr_t physics3d_contactEnterSpeeds() {
    return reinterpret_cast<uintptr_t>(g().contactEnterSpeedBuffer.data());
}

EMSCRIPTEN_KEEPALIVE
size_t physics3d_contactEnterSpeedsBytes() {
    return g().contactEnterSpeedBuffer.size() * sizeof(float);
}

EMSCRIPTEN_KEEPALIVE
uintptr_t physics3d_contactEnters() {
    return reinterpret_cast<uintptr_t>(g().contactEnterBuffer.data());
}

EMSCRIPTEN_KEEPALIVE
size_t physics3d_contactEntersBytes() {
    return g().contactEnterBuffer.size() * sizeof(float);
}

EMSCRIPTEN_KEEPALIVE
uintptr_t physics3d_contactExits() {
    return reinterpret_cast<uintptr_t>(g().contactExitBuffer.data());
}

EMSCRIPTEN_KEEPALIVE
size_t physics3d_contactExitsBytes() {
    return g().contactExitBuffer.size() * sizeof(float);
}

EMSCRIPTEN_KEEPALIVE
uintptr_t physics3d_sensorEnters() {
    return reinterpret_cast<uintptr_t>(g().sensorEnterBuffer.data());
}

EMSCRIPTEN_KEEPALIVE
size_t physics3d_sensorEntersBytes() {
    return g().sensorEnterBuffer.size() * sizeof(float);
}

EMSCRIPTEN_KEEPALIVE
uintptr_t physics3d_sensorExits() {
    return reinterpret_cast<uintptr_t>(g().sensorExitBuffer.data());
}

EMSCRIPTEN_KEEPALIVE
size_t physics3d_sensorExitsBytes() {
    return g().sensorExitBuffer.size() * sizeof(float);
}

EMSCRIPTEN_KEEPALIVE
uintptr_t physics3d_queryResult() {
    return reinterpret_cast<uintptr_t>(g().queryBuffer.data());
}

EMSCRIPTEN_KEEPALIVE
size_t physics3d_queryResultBytes() {
    return g().queryBuffer.size() * sizeof(float);
}

}  // extern "C"