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.

feat(native): physics on the device — Box2D in the host, not a side module

yhh4230cc5ce43f
diff --git a/CMakeLists.txt b/CMakeLists.txt
index aedf00ab4..05e88e8dd 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -489,6 +489,7 @@ html,body{width:100%;height:100%;overflow:hidden;background:#1a1a1a}
if(ES_ENABLE_BOX2D)
set(ES_PHYSICS_SOURCES
src/esengine/bindings/PhysicsModuleEntry.cpp
+ src/esengine/bindings/PhysicsReadback.cpp
src/esengine/bindings/PhysicsContext.cpp
src/esengine/bindings/PhysicsShapes.cpp
src/esengine/bindings/PhysicsJoints.cpp
diff --git a/build-tools/tasks/native.js b/build-tools/tasks/native.js
index a77323df6..24f984fda 100644
--- a/build-tools/tasks/native.js
+++ b/build-tools/tasks/native.js
@@ -47,6 +47,10 @@ export const NATIVE_BINDING_HEADERS = [
'GeometryBindings.hpp',
'ImmediateDrawBindings.hpp',
'AnimationBindings.hpp',
+ // Physics: a C module compiled into the host, not a wasm side module.
+ 'PhysicsBindings.hpp',
+ // The engine's own MPEG-1 decoder, likewise compiled in.
+ 'VideoBindings.hpp',
];
// Generate the QuickJS wrappers for the engine's binding ENTRY POINTS — the same
diff --git a/examples/physics-spinner/src/systems/spawn.ts b/examples/physics-spinner/src/systems/spawn.ts
index ea067f474..0fa7795b9 100644
--- a/examples/physics-spinner/src/systems/spawn.ts
+++ b/examples/physics-spinner/src/systems/spawn.ts
@@ -5,7 +5,11 @@ import {
} from 'esengine';
import { SpawnMarker } from '../components';
-const BODY_COUNT = 150;
+// A stress count, not a gameplay one: 5000 dynamic bodies is what makes this
+// example a measurement of the whole per-frame chain — Box2D's solver, the
+// transform readback across the boundary, and 5000 batched shape draws — on
+// whatever hardware it runs on.
+const BODY_COUNT = 5000;
const PPU = 100;
const GRID_LEFT = -23;
const GRID_RIGHT = 23;
diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt
index 3e6d625db..c424f4f2a 100644
--- a/native/CMakeLists.txt
+++ b/native/CMakeLists.txt
@@ -59,6 +59,34 @@ add_library(yogacore STATIC ${YOGA_SOURCES})
target_include_directories(yogacore PUBLIC "${TP}")
target_compile_options(yogacore PRIVATE -Wno-unused-parameter)
+# Box2D + the physics module's own TUs, compiled INTO the host. On the web physics
+# ships as a separate wasm side module (dynamic linking, its own emscripten runtime);
+# a native app has no such story and no reason for one — the same C sources link
+# straight in, and the SDK reaches them through the generated es_physics_* wrappers.
+# Vendored, so nothing extra to fetch.
+set(BOX2D_SAMPLES OFF CACHE BOOL "" FORCE)
+set(BOX2D_BENCHMARKS OFF CACHE BOOL "" FORCE)
+set(BOX2D_DOCS OFF CACHE BOOL "" FORCE)
+set(BOX2D_UNIT_TESTS OFF CACHE BOOL "" FORCE)
+set(BOX2D_VALIDATE OFF CACHE BOOL "" FORCE) # release: no heavy internal assertions
+add_subdirectory("${TP}/box2d" "${CMAKE_BINARY_DIR}/box2d" EXCLUDE_FROM_ALL)
+
+# The engine's own MPEG-1 decoder (pl_mpeg), the same TU the web links as the
+# "videodec" side module. Header-only dependency, so nothing to fetch.
+add_library(estella_video STATIC "${SRC}/esengine/bindings/VideoModuleEntry.cpp")
+target_include_directories(estella_video PUBLIC "${SRC}" "${TP}/pl_mpeg")
+
+set(ESTELLA_PHYSICS_SOURCES
+ "${SRC}/esengine/bindings/PhysicsModuleEntry.cpp"
+ "${SRC}/esengine/bindings/PhysicsContext.cpp"
+ "${SRC}/esengine/bindings/PhysicsShapes.cpp"
+ "${SRC}/esengine/bindings/PhysicsJoints.cpp"
+ "${SRC}/esengine/bindings/PhysicsQueries.cpp"
+ "${SRC}/esengine/bindings/PhysicsReadback.cpp")
+add_library(estella_physics STATIC ${ESTELLA_PHYSICS_SOURCES})
+target_include_directories(estella_physics PUBLIC "${SRC}" "${TP}/box2d/include")
+target_link_libraries(estella_physics PUBLIC box2d)
+
if(ANDROID)
add_library(native_app_glue STATIC
"${ANDROID_NDK}/sources/android/native_app_glue/android_native_app_glue.c")
@@ -165,7 +193,7 @@ if(ESTELLA_QUICKJS_DIR)
# archive, so these also live in native/ios/project.yml).
set_source_files_properties(host/media/native_audio.cpp PROPERTIES
COMPILE_OPTIONS "-x;objective-c++")
- target_link_libraries(estella_js_host esengine qjs
+ target_link_libraries(estella_js_host esengine estella_physics estella_video qjs
"-framework UIKit" "-framework QuartzCore" "-framework Foundation"
"-framework AVFoundation" "-framework CoreAudio" "-framework AudioToolbox"
"-framework CoreText" "-framework CoreGraphics")
@@ -174,13 +202,15 @@ if(ESTELLA_QUICKJS_DIR)
add_custom_command(TARGET estella_js_host POST_BUILD
COMMAND libtool -static -o "${CMAKE_BINARY_DIR}/libestella_ios.a"
$<TARGET_FILE:estella_js_host> $<TARGET_FILE:esengine>
+ $<TARGET_FILE:estella_physics> $<TARGET_FILE:box2d>
+ $<TARGET_FILE:estella_video>
$<TARGET_FILE:qjs> $<TARGET_FILE:yogacore> "${ESTELLA_DAWN_LIB}"
COMMENT "Merging the iOS host, engine and Dawn into libestella_ios.a")
else()
# Android: plain C++; miniaudio dlopens AAudio/OpenSL at runtime (no extra
# link libs). native_audio.cpp's Obj-C paths are __APPLE__-guarded out.
add_library(estella_js_host SHARED ${HOST_SOURCES} host/platform/android.cpp)
- target_link_libraries(estella_js_host esengine qjs native_app_glue android log)
+ target_link_libraries(estella_js_host esengine estella_physics estella_video qjs native_app_glue android log)
set_target_properties(estella_js_host PROPERTIES LINK_FLAGS "-u ANativeActivity_onCreate")
endif()
# host/ is the include root: every host TU spells its siblings from there
diff --git a/sdk/src/ecs/nativeRuntime.ts b/sdk/src/ecs/nativeRuntime.ts
index 476f6c785..6b76f55bc 100644
--- a/sdk/src/ecs/nativeRuntime.ts
+++ b/sdk/src/ecs/nativeRuntime.ts
@@ -27,6 +27,7 @@ import { createNativeRendererBackend, nativeSurfaceSize } from './nativeRenderer
import { createNativeEngineApi } from './nativeEngineApi.generated';
import { setNativeEngineApi, engineApi } from './engineApi';
import { createNativeHeap } from './nativeHeap';
+import { createNativeSideModules } from './nativeSideModules';
import { initPostProcessAPI } from '../postprocess';
import { log } from '../logger';
import { setRendererBackend } from '../renderer';
@@ -87,6 +88,10 @@ export function createNativeApp(
app.connectCpp(createNativeRegistry(scope), undefined, {
memory: new NativeMemoryProvider(scope),
});
+ // The optional subsystems (physics today) come from the host binary rather than
+ // a fetched wasm side module, through the same acquirer the web realms use — so
+ // the runtime's own self-gating installs them without knowing the difference.
+ app.setSideModules(createNativeSideModules(scope));
// The same order the web app builds in (see _createWebApp): the frame first,
// then assets, then the gameplay stack. assetPlugin is the one plugin that
// cannot be shared as-is — it wires the wasm heap — so installNativeAssets
diff --git a/sdk/src/ecs/nativeSideModules.ts b/sdk/src/ecs/nativeSideModules.ts
new file mode 100644
index 000000000..39642b6b5
--- /dev/null
+++ b/sdk/src/ecs/nativeSideModules.ts
@@ -0,0 +1,104 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ecs/nativeSideModules.ts
+ * @brief The optional subsystems, as a native host answers them.
+ *
+ * On the web, physics / spine / the KTX2 transcoder / the video decoder ship as
+ * standalone emscripten modules that a realm fetches, inlines or hands over
+ * (`SideModuleHost`). A native app has no dynamic-linking story and no reason for
+ * one: the same C sources are compiled into the host binary, and their entry points
+ * are registered on the JS global object by the generated wrappers.
+ *
+ * So the "module" here is a VIEW of those globals in the shape the SDK's consumers
+ * already expect — `_physics_step(…)` resolves to the host's `es_physics_step` —
+ * merged with the heap they marshal buffers through (see nativeHeap.ts). Nothing
+ * downstream changes: the runtime's own self-gating installs the physics plugin from
+ * `app.sideModules` exactly as it does in a browser.
+ *
+ * A host that did not compile a subsystem in simply does not answer its entry
+ * points, and this reports that as unavailability rather than handing back an object
+ * whose first call is a TypeError.
+ */
+
+import { createSideModuleHost, type SideModuleHost, type SideModule } from '../sideModules/host';
+import type { SideModuleId } from '../sideModules/registry';
+import { log } from '../logger';
+import { createNativeHeap, type NativeHeap } from './nativeHeap';
+
+/**
+ * One global per subsystem that proves the host compiled it in. Picked from the
+ * entry points a consumer calls first, so the probe cannot pass while the surface
+ * is half-registered.
+ */
+export const NATIVE_SIDE_MODULE_PROBES: Partial<Record<SideModuleId, string>> = {
+ physics: 'es_physics_init',
+ videodec: 'es_video_open',
+};
+
+/**
+ * The host global behind an emscripten C-export name: `_physics_step` →
+ * `es_physics_step`. `es_` marks the boundary surface, so a C name that already
+ * carries it keeps it (`_es_video_open` → `es_video_open`) — the same rule the
+ * generator applies when it registers the wrapper.
+ */
+function hostGlobal(exportName: string): string {
+ const name = exportName.slice(1);
+ return name.startsWith('es_') ? name : `es_${name}`;
+}
+
+/**
+ * A C module's entry points, spelled the way emscripten exports them (`_name`), over
+ * the host globals — plus the heap views, since a caller writes its buffers there
+ * before passing an offset.
+ */
+function nativeCModule(scope: Record<string, unknown>, heap: NativeHeap): SideModule {
+ const resolved: Record<string, unknown> = { ...heap };
+ return new Proxy(resolved, {
+ get(target, prop): unknown {
+ if (prop in target) return Reflect.get(target, prop);
+ if (typeof prop !== 'string' || !prop.startsWith('_')) return undefined;
+ const fn = scope[hostGlobal(prop)];
+ if (typeof fn !== 'function') return undefined;
+ // Remembered, so repeat calls are a plain property read (and the
+ // bridge's per-property guard wrapper keeps working).
+ target[prop] = fn;
+ return fn;
+ },
+ has(target, prop): boolean {
+ if (prop in target) return true;
+ return typeof prop === 'string' && prop.startsWith('_')
+ && typeof scope[hostGlobal(prop)] === 'function';
+ },
+ }) as SideModule;
+}
+
+/**
+ * The optional-module acquirer for a native host. Answers the subsystems this host
+ * compiled in and null for the rest, which is what the runtime's gating already
+ * treats as "not available in this realm".
+ */
+export function createNativeSideModules(
+ scope: Record<string, unknown> = globalThis as unknown as Record<string, unknown>,
+): SideModuleHost {
+ const heap = createNativeHeap(scope);
+ return createSideModuleHost(async (_descriptor, id): Promise<SideModule> => {
+ const probe = NATIVE_SIDE_MODULE_PROBES[id];
+ if (!probe) {
+ throw new Error(`[native] "${id}" is not compiled into this host`);
+ }
+ if (typeof scope[probe] !== 'function') {
+ throw new Error(
+ `[native] "${id}" is not compiled into this host (${probe} is not bound) — `
+ + 'rebuild it with that subsystem enabled',
+ );
+ }
+ if (!heap) {
+ throw new Error(
+ `[native] "${id}" needs the host heap to marshal buffers, and es_heap is not bound`,
+ );
+ }
+ log.info('sidemodule', `${id}: native (compiled into the host)`);
+ return nativeCModule(scope, heap);
+ });
+}
diff --git a/sdk/tests/binding-surface.test.ts b/sdk/tests/binding-surface.test.ts
index 91492bad8..85d9423ed 100644
--- a/sdk/tests/binding-surface.test.ts
+++ b/sdk/tests/binding-surface.test.ts
@@ -320,15 +320,37 @@ function expectMirrored(label: string, tsDeclared: Set<string>, cppExports: Set<
}
describe('WASM binding surface: side modules (C exports)', () => {
+ // The four TUs the SDK's own interface mirrors. PhysicsReadback.cpp is
+ // deliberately absent: its `*Bytes` helpers exist so a NATIVE wrapper can copy
+ // exactly what a getter published, and no SDK caller ever names them.
+ const PHYSICS_TUS = ['PhysicsModuleEntry.cpp', 'PhysicsShapes.cpp',
+ 'PhysicsJoints.cpp', 'PhysicsQueries.cpp'];
+
it('PhysicsWasmModule mirrors the physics module exports exactly', () => {
const cpp = new Set(
- ['PhysicsModuleEntry.cpp', 'PhysicsShapes.cpp', 'PhysicsJoints.cpp', 'PhysicsQueries.cpp']
- .flatMap((f) => [...parseKeepaliveExports(read(resolve(CPP, 'bindings', f)))]),
+ PHYSICS_TUS.flatMap((f) => [...parseKeepaliveExports(read(resolve(CPP, 'bindings', f)))]),
);
const ts = parseInterfaceMethods(read(resolve(SDK, 'physics/PhysicsModuleLoader.ts')), 'PhysicsWasmModule');
expectMirrored('physics', ts, cpp);
});
+ // The native half of the same surface. A device reaches physics through QuickJS
+ // wrappers EHT generates from PhysicsBindings.hpp, so a declaration missing there
+ // is an entry point the device silently does not answer — and one that exists
+ // there but nowhere else is a wrapper that will not link.
+ it('PhysicsBindings.hpp declares exactly what the module exports', () => {
+ const header = stripComments(read(resolve(CPP, 'bindings/PhysicsBindings.hpp')));
+ const declared = new Set([...header.matchAll(/\b(physics_\w+)\s*\(/g)].map((m) => m[1]!));
+ const exported = new Set([...PHYSICS_TUS, 'PhysicsReadback.cpp']
+ .flatMap((f) => [...parseKeepaliveExports(read(resolve(CPP, 'bindings', f)))]));
+ const undeclared = [...exported].filter((n) => !declared.has(n)).sort();
+ const phantom = [...declared].filter((n) => !exported.has(n)).sort();
+ expect(undeclared, `exported but not declared in PhysicsBindings.hpp (no native wrapper): ${undeclared.join(', ')}`)
+ .toEqual([]);
+ expect(phantom, `declared in PhysicsBindings.hpp but defined nowhere: ${phantom.join(', ')}`)
+ .toEqual([]);
+ });
+
it('SpineWasmModule + its cwrap table mirror the spine module exports exactly', () => {
const cpp = parseKeepaliveExports(read(resolve(CPP, 'bindings/SpineModuleEntry.cpp')));
const loaderTs = read(resolve(SDK, 'spine/SpineModuleLoader.ts'));
diff --git a/sdk/tests/native-side-modules.test.ts b/sdk/tests/native-side-modules.test.ts
new file mode 100644
index 000000000..48a4d5a43
--- /dev/null
+++ b/sdk/tests/native-side-modules.test.ts
@@ -0,0 +1,133 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+//
+// The optional subsystems on a device. On the web they are fetched wasm side
+// modules; in a native app the same C is compiled into the host binary and its entry
+// points sit on the JS global object. What must hold is that NOTHING downstream can
+// tell the difference: the SDK's `PhysicsWasmModule` shape is satisfied by the host
+// globals plus the heap, so the runtime's own gating installs physics either way.
+//
+// Driven against a mock host scope — the marshalling is what these check, not Box2D.
+import { describe, it, expect, vi } from 'vitest';
+import { createNativeSideModules, NATIVE_SIDE_MODULE_PROBES } from '../src/ecs/nativeSideModules';
+import { HEAP_BINDINGS } from '../src/ecs/nativeHeap';
+import type { PhysicsWasmModule } from '../src/physics/PhysicsModuleLoader';
+
+/** A host that compiled physics in: the heap plus a few es_physics_* globals. */
+function mockNativeHost(options: { physics?: boolean; heap?: boolean } = {}) {
+ const { physics = true, heap = true } = options;
+ const buffer = new ArrayBuffer(4096);
+ let next = 8;
+ const calls: { name: string; args: unknown[] }[] = [];
+ const scope: Record<string, unknown> = {};
+ if (heap) {
+ scope[HEAP_BINDINGS.heap] = () => buffer;
+ scope[HEAP_BINDINGS.malloc] = (bytes: number) => {
+ const at = next; next += Math.ceil(bytes / 8) * 8; return at;
+ };
+ scope[HEAP_BINDINGS.free] = () => {};
+ }
+ if (physics) {
+ const record = (name: string) => (...args: unknown[]) => { calls.push({ name, args }); return 0; };
+ for (const name of ['init', 'step', 'createBody', 'destroyBody', 'setGravity',
+ 'getDynamicBodyCount', 'collectEvents', 'addPolygonShape']) {
+ scope[`es_physics_${name}`] = record(name);
+ }
+ // The readback getters answer an OFFSET into the heap (the wrapper published
+ // the module's bytes there), exactly like a wasm pointer.
+ scope['es_physics_getDynamicBodyTransforms'] = () => 64;
+ }
+ return { scope, buffer, calls };
+}
+
+describe('createNativeSideModules', () => {
+ it('answers physics when the host compiled it in', async () => {
+ const { scope } = mockNativeHost();
+ const mod = await createNativeSideModules(scope).acquire('physics');
+ expect(mod).not.toBeNull();
+ });
+
+ it('answers null when the host did not — not an object that throws on first call', async () => {
+ const { scope } = mockNativeHost({ physics: false });
+ expect(await createNativeSideModules(scope).acquire('physics')).toBeNull();
+ });
+
+ it('answers null when the host bound no heap to marshal through', async () => {
+ const { scope } = mockNativeHost({ heap: false });
+ expect(await createNativeSideModules(scope).acquire('physics')).toBeNull();
+ });
+
+ it('answers null for a subsystem no native host compiles yet', async () => {
+ const { scope } = mockNativeHost();
+ expect(await createNativeSideModules(scope).acquire('spine:4.2')).toBeNull();
+ expect(NATIVE_SIDE_MODULE_PROBES['spine:4.2']).toBeUndefined();
+ });
+
+ it('caches, so two consumers share one view', async () => {
+ const host = createNativeSideModules(mockNativeHost().scope);
+ expect(await host.acquire('physics')).toBe(await host.acquire('physics'));
+ });
+});
+
+describe('the native physics module satisfies the SDK’s shape', () => {
+ it('resolves an emscripten C export name to the host global', async () => {
+ const { scope, calls } = mockNativeHost();
+ const mod = (await createNativeSideModules(scope).acquire('physics')) as unknown as PhysicsWasmModule;
+ mod._physics_init(0, -9.81, 1 / 60, 4, 120, 10, 10);
+ mod._physics_step(1 / 60);
+ expect(calls.map((c) => c.name)).toEqual(['init', 'step']);
+ expect(calls[0]!.args).toEqual([0, -9.81, 1 / 60, 4, 120, 10, 10]);
+ });
+
+ it('carries the heap, so a caller writes its buffer and passes an offset', async () => {
+ const { scope, buffer, calls } = mockNativeHost();
+ const mod = (await createNativeSideModules(scope).acquire('physics')) as unknown as PhysicsWasmModule;
+ // What PhysicsSystem does for a polygon collider.
+ const verts = new Float32Array([0, 0, 1, 0, 1, 1]);
+ const ptr = mod._malloc(verts.byteLength);
+ mod.HEAPF32.set(verts, ptr / 4);
+ mod._physics_addPolygonShape(1, ptr, 3, 0, 1, 0.3, 0, 0, 1, 0xffff);
+ mod._free(ptr);
+ // The bytes really landed in the host's arena, which is what the C side reads.
+ expect(Array.from(new Float32Array(buffer, ptr, 6))).toEqual([0, 0, 1, 0, 1, 1]);
+ expect(calls.at(-1)!.args[1]).toBe(ptr);
+ });
+
+ it('reads a readback getter as an offset into that same heap', async () => {
+ const { scope, buffer } = mockNativeHost();
+ const mod = (await createNativeSideModules(scope).acquire('physics')) as unknown as PhysicsWasmModule;
+ // The host published a body transform at offset 64: [entity, x, y, angle].
+ new Uint32Array(buffer, 64, 1)[0] = 7;
+ new Float32Array(buffer, 68, 3).set([12.5, -3, 1.5]);
+ const base = mod._physics_getDynamicBodyTransforms() >> 2;
+ expect(mod.HEAPU32[base]).toBe(7);
+ expect(Array.from(mod.HEAPF32.subarray(base + 1, base + 4))).toEqual([12.5, -3, 1.5]);
+ });
+
+ it('is honest about an entry point the host never bound', async () => {
+ const { scope } = mockNativeHost();
+ const mod = (await createNativeSideModules(scope).acquire('physics')) as unknown as
+ Record<string, unknown>;
+ expect(mod._physics_neverBound).toBeUndefined();
+ expect('_physics_step' in mod).toBe(true);
+ expect('_physics_neverBound' in mod).toBe(false);
+ });
+
+ it('does not invent a name that is not a C export', async () => {
+ const { scope } = mockNativeHost();
+ const mod = (await createNativeSideModules(scope).acquire('physics')) as unknown as
+ Record<string, unknown>;
+ // No leading underscore: not the export convention, so not forwarded.
+ expect(mod.physics_step).toBeUndefined();
+ });
+});
+
+describe('the runtime installs physics from a native host', () => {
+ it('goes through the same acquirer the web realms use', async () => {
+ const { scope } = mockNativeHost();
+ const host = createNativeSideModules(scope);
+ const acquire = vi.spyOn(host, 'acquire');
+ await host.acquire('physics');
+ expect(acquire).toHaveBeenCalledWith('physics');
+ });
+});
diff --git a/src/esengine/bindings/PhysicsBindings.hpp b/src/esengine/bindings/PhysicsBindings.hpp
new file mode 100644
index 000000000..82da278c7
--- /dev/null
+++ b/src/esengine/bindings/PhysicsBindings.hpp
@@ -0,0 +1,187 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file PhysicsBindings.hpp
+ * @brief The Box2D module's entry points, declared once for both platforms.
+ * @details The physics module is plain C: `extern "C"` functions over a Box2D world,
+ * which the web build links into its own wasm side module and exports by
+ * KEEPALIVE. There were no declarations anywhere — the SDK's
+ * `PhysicsWasmModule` interface was the only statement of this surface, and
+ * it could drift from the C++ silently.
+ *
+ * Declaring them here gives the surface one source: the same file the web
+ * module compiles from, and the file EHT reads to generate the QuickJS
+ * wrappers a native host binds (`eht --native-functions`). A native build
+ * compiles these TUs and Box2D into the host binary — no side module, since
+ * there is no dynamic-linking story to have on a device.
+ *
+ * Bulk data crosses as an offset into the caller's heap (wasm linear memory
+ * on the web, the host arena on a device), which is why the readback getters
+ * carry an `@heapreturn` annotation: they hand back memory the MODULE owns,
+ * so a native wrapper copies exactly that many bytes into the heap the SDK
+ * reads. The byte counts come from the module, never from a stride guessed
+ * on the far side — see the `*Bytes` helpers at the end.
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the Apache License, Version 2.0.
+ */
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+
+extern "C" {
+
+// — World, bodies, the step, events and body properties (PhysicsModuleEntry.cpp) —
+
+void physics_init(float gx, float gy, float timestep, int substeps, float contactHertz, float contactDampingRatio, float contactSpeed);
+void physics_setWorldConfig(int enableSleep, int enableContinuous, float restitutionThreshold, float maxLinearSpeed);
+void physics_shutdown();
+void physics_setOneWayPlatform(uint32_t entityId, float nx, float ny, int enable);
+void physics_createBody(uint32_t entityId, int bodyType, float x, float y, float angle, float gravityScale, float linearDamping, float angularDamping, int fixedRotation, int bullet);
+void physics_destroyBody(uint32_t entityId);
+int physics_hasBody(uint32_t entityId);
+void physics_setBodyEnabled(uint32_t entityId, int enabled);
+void physics_step(float dt);
+void physics_setBodyTransform(uint32_t entityId, float x, float y, float angle);
+void physics_setBodyTargetTransform(uint32_t entityId, float x, float y, float angle, float dt);
+int physics_getDynamicBodyCount();
+// @heapreturn physics_dynamicBodyTransformsBytes()
+uintptr_t physics_getDynamicBodyTransforms();
+void physics_collectEvents();
+int physics_getCollisionEnterCount();
+// @heapreturn physics_collisionEnterBytes()
+uintptr_t physics_getCollisionEnterBuffer();
+int physics_getHitEventCount();
+// @heapreturn physics_hitEventBytes()
+uintptr_t physics_getHitEventBuffer();
+int physics_getCollisionExitCount();
+// @heapreturn physics_collisionExitBytes()
+uintptr_t physics_getCollisionExitBuffer();
+int physics_getSensorEnterCount();
+// @heapreturn physics_sensorEnterBytes()
+uintptr_t physics_getSensorEnterBuffer();
+int physics_getSensorExitCount();
+// @heapreturn physics_sensorExitBytes()
+uintptr_t physics_getSensorExitBuffer();
+void physics_applyForce(uint32_t entityId, float forceX, float forceY);
+void physics_applyImpulse(uint32_t entityId, float impulseX, float impulseY);
+void physics_setLinearVelocity(uint32_t entityId, float vx, float vy);
+// @heapreturn 2 * sizeof(float)
+uintptr_t physics_getLinearVelocity(uint32_t entityId);
+void physics_setGravity(float gx, float gy);
+// @heapreturn 2 * sizeof(float)
+uintptr_t physics_getGravity();
+void physics_setAngularVelocity(uint32_t entityId, float omega);
+float physics_getAngularVelocity(uint32_t entityId);
+void physics_applyTorque(uint32_t entityId, float torque);
+void physics_applyAngularImpulse(uint32_t entityId, float impulse);
+void physics_updateBodyProperties(uint32_t entityId, int bodyType, float gravityScale, float linearDamping, float angularDamping, int fixedRotation, int bullet);
+void physics_setAwake(uint32_t entityId, int awake);
+int physics_isAwake(uint32_t entityId);
+float physics_getBodyMass(uint32_t entityId);
+float physics_getBodyInertia(uint32_t entityId);
+// @heapreturn 2 * sizeof(float)
+uintptr_t physics_getBodyCenterOfMass(uint32_t entityId);
+
+// — Shapes (PhysicsShapes.cpp) —
+
+void physics_addBoxShape(uint32_t entityId, float halfW, float halfH, float offX, float offY, float radius, float density, float friction, float restitution, int isSensor, uint32_t categoryBits, uint32_t maskBits);
+void physics_addCircleShape(uint32_t entityId, float radius, float offX, float offY, float density, float friction, float restitution, int isSensor, uint32_t categoryBits, uint32_t maskBits);
+void physics_addCapsuleShape(uint32_t entityId, float radius, float halfHeight, float offX, float offY, float density, float friction, float restitution, int isSensor, uint32_t categoryBits, uint32_t maskBits);
+void physics_addSegmentShape(uint32_t entityId, float x1, float y1, float x2, float y2, float density, float friction, float restitution, int isSensor, uint32_t categoryBits, uint32_t maskBits);
+void physics_addPolygonShape(uint32_t entityId, uintptr_t verticesPtr, int vertexCount, float radius, float density, float friction, float restitution, int isSensor, uint32_t categoryBits, uint32_t maskBits);
+void physics_addChainShape(uint32_t entityId, uintptr_t pointsPtr, int pointCount, int isLoop, float friction, float restitution, uint32_t categoryBits, uint32_t maskBits);
+void physics_clearShapes(uint32_t entityId);
+
+// — Joints (PhysicsJoints.cpp) —
+
+int physics_createRevoluteJoint(uint32_t entityIdA, uint32_t entityIdB, float anchorAx, float anchorAy, float anchorBx, float anchorBy, int enableMotor, float motorSpeed, float maxMotorTorque, int enableLimit, float lowerAngle, float upperAngle, int collideConnected);
+void physics_destroyJoint(uint32_t entityId);
+void physics_setRevoluteMotorSpeed(uint32_t entityId, float speed);
+void physics_setRevoluteMaxMotorTorque(uint32_t entityId, float torque);
+void physics_enableRevoluteMotor(uint32_t entityId, int enable);
+void physics_enableRevoluteLimit(uint32_t entityId, int enable);
+void physics_setRevoluteLimits(uint32_t entityId, float lower, float upper);
+float physics_getRevoluteAngle(uint32_t entityId);
+float physics_getRevoluteMotorTorque(uint32_t entityId);
+int physics_hasJoint(uint32_t entityId);
+int physics_createDistanceJoint(uint32_t entityIdA, uint32_t entityIdB, float anchorAx, float anchorAy, float anchorBx, float anchorBy, float length, int enableSpring, float hertz, float dampingRatio, int enableLimit, float minLength, float maxLength, int enableMotor, float maxMotorForce, float motorSpeed, int collideConnected);
+int physics_createPrismaticJoint(uint32_t entityIdA, uint32_t entityIdB, float anchorAx, float anchorAy, float anchorBx, float anchorBy, float axisX, float axisY, int enableSpring, float hertz, float dampingRatio, int enableLimit, float lowerTranslation, float upperTranslation, int enableMotor, float maxMotorForce, float motorSpeed, int collideConnected);
+int physics_createWeldJoint(uint32_t entityIdA, uint32_t entityIdB, float anchorAx, float anchorAy, float anchorBx, float anchorBy, float linearHertz, float angularHertz, float linearDampingRatio, float angularDampingRatio, int collideConnected);
+int physics_createWheelJoint(uint32_t entityIdA, uint32_t entityIdB, float anchorAx, float anchorAy, float anchorBx, float anchorBy, float axisX, float axisY, int enableSpring, float hertz, float dampingRatio, int enableLimit, float lowerTranslation, float upperTranslation, int enableMotor, float maxMotorTorque, float motorSpeed, int collideConnected);
+float physics_getDistanceJointLength(uint32_t entityId);
+float physics_getDistanceJointCurrentLength(uint32_t entityId);
+void physics_setDistanceJointLength(uint32_t entityId, float length);
+void physics_enableDistanceJointSpring(uint32_t entityId, int enable);
+void physics_enableDistanceJointLimit(uint32_t entityId, int enable);
+void physics_setDistanceJointLimits(uint32_t entityId, float minLength, float maxLength);
+void physics_enableDistanceJointMotor(uint32_t entityId, int enable);
+void physics_setDistanceJointMotorSpeed(uint32_t entityId, float speed);
+void physics_setDistanceJointMaxMotorForce(uint32_t entityId, float force);
+float physics_getDistanceJointMotorForce(uint32_t entityId);
+float physics_getPrismaticJointTranslation(uint32_t entityId);
+float physics_getPrismaticJointSpeed(uint32_t entityId);
+void physics_enablePrismaticJointSpring(uint32_t entityId, int enable);
+void physics_enablePrismaticJointLimit(uint32_t entityId, int enable);
+void physics_setPrismaticJointLimits(uint32_t entityId, float lower, float upper);
+void physics_enablePrismaticJointMotor(uint32_t entityId, int enable);
+void physics_setPrismaticJointMotorSpeed(uint32_t entityId, float speed);
+void physics_setPrismaticJointMaxMotorForce(uint32_t entityId, float force);
+float physics_getPrismaticJointMotorForce(uint32_t entityId);
+void physics_enableWheelJointSpring(uint32_t entityId, int enable);
+void physics_enableWheelJointLimit(uint32_t entityId, int enable);
+void physics_setWheelJointLimits(uint32_t entityId, float lower, float upper);
+void physics_enableWheelJointMotor(uint32_t entityId, int enable);
+void physics_setWheelJointMotorSpeed(uint32_t entityId, float speed);
+void physics_setWheelJointMaxMotorTorque(uint32_t entityId, float torque);
+float physics_getWheelJointMotorTorque(uint32_t entityId);
+int physics_createMotorJoint(uint32_t entityIdA, uint32_t entityIdB, float linearVelX, float linearVelY, float maxVelocityForce, float angularVelocity, float maxVelocityTorque, float linearHertz, float linearDampingRatio, float maxSpringForce, float angularHertz, float angularDampingRatio, float maxSpringTorque, int collideConnected);
+void physics_setMotorJointLinearVelocity(uint32_t entityId, float vx, float vy);
+void physics_setMotorJointAngularVelocity(uint32_t entityId, float omega);
+void physics_setMotorJointMaxVelocityForce(uint32_t entityId, float force);
+void physics_setMotorJointMaxVelocityTorque(uint32_t entityId, float torque);
+int physics_createMouseJoint(uint32_t entityId, float targetX, float targetY, float hertz, float dampingRatio, float maxForce);
+void physics_setMouseTarget(float targetX, float targetY);
+void physics_destroyMouseJoint();
+int physics_hasMouseJoint();
+
+// — Queries: raycast, overlap, shape cast, character movement (PhysicsQueries.cpp) —
+
+int physics_raycast(float originX, float originY, float dirX, float dirY, float maxDistance, uint32_t maskBits);
+// @heapreturn physics_raycastBytes()
+uintptr_t physics_getRaycastBuffer();
+int physics_overlapCircle(float centerX, float centerY, float radius, uint32_t maskBits);
+// @heapreturn physics_overlapBytes()
+uintptr_t physics_getOverlapBuffer();
+int physics_shapeCastCircle(float centerX, float centerY, float radius, float translationX, float translationY, uint32_t maskBits);
+int physics_shapeCastBox(float centerX, float centerY, float halfW, float halfH, float angle, float translationX, float translationY, uint32_t maskBits);
+int physics_shapeCastCapsule(float center1X, float center1Y, float center2X, float center2Y, float radius, float translationX, float translationY, uint32_t maskBits);
+// @heapreturn physics_shapeCastBytes()
+uintptr_t physics_getShapeCastBuffer();
+int physics_overlapAABB(float minX, float minY, float maxX, float maxY, uint32_t maskBits);
+int physics_moveCharacter(float px, float py, float c1x, float c1y, float c2x, float c2y, float radius, float velX, float velY, float dt, float upX, float upY, float floorCos, uint32_t maskBits, uint32_t selfEntity, float skinWidth, int maxSlides, float snapLength, int slideOnCeiling);
+// @heapreturn physics_moveCharacterBytes()
+uintptr_t physics_getMoveCharacterBuffer();
+
+// — Readback lengths —
+//
+// How many bytes each getter above actually published. The buffers are the module's
+// own (vectors it fills per step, fixed arrays a query writes), so only the module
+// can say how much is live: a count times an assumed stride would over-read the very
+// frame a body was disabled or a query found fewer hits than the last one.
+size_t physics_dynamicBodyTransformsBytes();
+size_t physics_collisionEnterBytes();
+size_t physics_collisionExitBytes();
+size_t physics_sensorEnterBytes();
+size_t physics_sensorExitBytes();
+size_t physics_hitEventBytes();
+size_t physics_raycastBytes();
+size_t physics_overlapBytes();
+size_t physics_shapeCastBytes();
+size_t physics_moveCharacterBytes();
+
+} // extern "C"
diff --git a/src/esengine/bindings/PhysicsContext.hpp b/src/esengine/bindings/PhysicsContext.hpp
index 69c5987c2..53ade5c4c 100644
--- a/src/esengine/bindings/PhysicsContext.hpp
+++ b/src/esengine/bindings/PhysicsContext.hpp
@@ -2,7 +2,14 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
#pragma once
+// The module's entry points are marked KEEPALIVE so the emscripten link keeps them
+// exported. A native build compiles the same TUs into the host binary, where the
+// attribute has no meaning and the header does not exist.
+#ifdef __EMSCRIPTEN__
#include <emscripten.h>
+#else
+#define EMSCRIPTEN_KEEPALIVE
+#endif
#include <box2d/box2d.h>
diff --git a/src/esengine/bindings/PhysicsReadback.cpp b/src/esengine/bindings/PhysicsReadback.cpp
new file mode 100644
index 000000000..05ba62789
--- /dev/null
+++ b/src/esengine/bindings/PhysicsReadback.cpp
@@ -0,0 +1,77 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file PhysicsReadback.cpp
+ * @brief How many bytes each readback getter published.
+ * @details The module's getters hand back a pointer to memory the module owns — a
+ * vector it refills each step, a fixed array a query writes into. On the web
+ * the caller reads that memory directly out of the shared heap, so nobody
+ * had to state its length; a native host has to COPY it into the heap the
+ * SDK reads, and copying a count times an assumed stride would over-read the
+ * very frame a body was disabled (the transform buffer skips those) or a
+ * query found fewer hits than the previous one left behind.
+ *
+ * So the module says. These are the `@heapreturn` expressions in
+ * PhysicsBindings.hpp, and they are the only reason a native wrapper needs
+ * no hand-written copy of its own.
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the Apache License, Version 2.0.
+ */
+#include "PhysicsContext.hpp"
+#include "PhysicsBindings.hpp"
+
+namespace {
+size_t floatBytes(const std::vector<float>& buffer) {
+ return buffer.size() * sizeof(float);
+}
+} // namespace
+
+extern "C" {
+
+EMSCRIPTEN_KEEPALIVE size_t physics_dynamicBodyTransformsBytes() {
+ return floatBytes(g_ctx.dynamicTransformBuffer);
+}
+
+EMSCRIPTEN_KEEPALIVE size_t physics_collisionEnterBytes() {
+ return floatBytes(g_ctx.collisionEnterBuffer);
+}
+
+EMSCRIPTEN_KEEPALIVE size_t physics_collisionExitBytes() {
+ return floatBytes(g_ctx.collisionExitBuffer);
+}
+
+EMSCRIPTEN_KEEPALIVE size_t physics_sensorEnterBytes() {
+ return floatBytes(g_ctx.sensorEnterBuffer);
+}
+
+EMSCRIPTEN_KEEPALIVE size_t physics_sensorExitBytes() {
+ return floatBytes(g_ctx.sensorExitBuffer);
+}
+
+EMSCRIPTEN_KEEPALIVE size_t physics_hitEventBytes() {
+ return floatBytes(g_ctx.hitEventBuffer);
+}
+
+EMSCRIPTEN_KEEPALIVE size_t physics_raycastBytes() {
+ return floatBytes(g_raycastBuffer);
+}
+
+EMSCRIPTEN_KEEPALIVE size_t physics_overlapBytes() {
+ return floatBytes(g_overlapBuffer);
+}
+
+EMSCRIPTEN_KEEPALIVE size_t physics_shapeCastBytes() {
+ return floatBytes(g_shapeCastBuffer);
+}
+
+// The character mover writes a fixed record (position delta, ground normal, flags),
+// so its whole extent is always live — see physics_moveCharacter.
+EMSCRIPTEN_KEEPALIVE size_t physics_moveCharacterBytes() {
+ return 9 * sizeof(float);
+}
+
+} // extern "C"