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(physics): imported geometry can be collided against

esengineff795549a36b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 34022d0d3..a2ee2e26f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,17 @@ published separately; it ships inside the editor.
### Added
+- **Imported geometry can be collided against.** A `MeshCollider3D` uses a
+ mesh's own triangles — a terrain, a staircase, the inside of a room, none of
+ which a box or a capsule can express. Always static: a triangle soup has no
+ inertia tensor, so there is nothing for a solver to push.
+
+ The triangles are the ones the mesh decode already produced. Geometry went to
+ the GPU and its bytes were let go, which is right for drawing and useless for
+ colliding, so the asset layer now keeps the positions and indices under the
+ handle everything already references the mesh by — nothing else, since a
+ collider does not care what colour a vertex is.
+
- **The 3D world says what touched what.** Contacts and sensor overlaps reach
the ECS through a `Physics3DEvents` resource, drained per fixed step: an enter
carries both entities, the normal and the point; a sensor names itself first,
diff --git a/desktop/src/engine/componentDocs.generated.ts b/desktop/src/engine/componentDocs.generated.ts
index 6ad910a63..85445dc9f 100644
--- a/desktop/src/engine/componentDocs.generated.ts
+++ b/desktop/src/engine/componentDocs.generated.ts
@@ -35,6 +35,7 @@ export const COMPONENT_DOC_PATHS: Readonly<Record<string, string>> = {
Light2D: 'reference/components/graphics/#light2d',
Marker: 'reference/components/world/#marker',
Mesh2D: 'reference/components/graphics/#mesh2d',
+ MeshCollider3D: 'reference/components/physics/#meshcollider3d',
MeshSkin: 'reference/components/graphics/#meshskin',
MotorJoint: 'reference/components/physics/#motorjoint',
Name: 'reference/components/core/#name',
diff --git a/docs/astro/src/content/docs/gameplay/physics-3d.mdx b/docs/astro/src/content/docs/gameplay/physics-3d.mdx
index 809dc3437..3cfd2a27f 100644
--- a/docs/astro/src/content/docs/gameplay/physics-3d.mdx
+++ b/docs/astro/src/content/docs/gameplay/physics-3d.mdx
@@ -48,6 +48,26 @@ cmds.spawn()
is not optional — it is why a capsule 60 units wide falls the way a person does.
</Aside>
+### Colliding against imported geometry
+
+A `MeshCollider3D` collides against a mesh's own triangles — a terrain, a
+staircase, the inside of a room. It is what a box and a capsule cannot say.
+
+```typescript
+cmds.spawn()
+ .insert(Transform, {})
+ .insert(RigidBody3D, { bodyType: BodyType.Static })
+ .insert(MeshCollider3D, { mesh: 'assets/models/level.esmesh' });
+```
+
+<Aside>
+ Always static, whatever its `RigidBody3D` says: a triangle soup has no inertia
+ tensor, so there is nothing for a solver to push. And the triangles are
+ ONE-SIDED — a floor whose winding faces down is one that rays still report and
+ bodies fall straight through. That is the failure to expect if imported geometry
+ stops nothing.
+</Aside>
+
## Characters
A `CharacterController3D` replaces a `RigidBody3D` rather than accompanying one: a
diff --git a/docs/astro/src/content/docs/zh-cn/gameplay/physics-3d.mdx b/docs/astro/src/content/docs/zh-cn/gameplay/physics-3d.mdx
index 78194dbaa..6aacfef46 100644
--- a/docs/astro/src/content/docs/zh-cn/gameplay/physics-3d.mdx
+++ b/docs/astro/src/content/docs/zh-cn/gameplay/physics-3d.mdx
@@ -44,6 +44,24 @@ cmds.spawn()
不是可选项——它正是一个 60 单位宽的胶囊会像人一样倒下的原因。
</Aside>
+### 用导入的几何做碰撞
+
+`MeshCollider3D` 直接拿网格自己的三角形做碰撞——地形、楼梯、房间内部,
+这些正是盒子和胶囊说不出来的东西。
+
+```typescript
+cmds.spawn()
+ .insert(Transform, {})
+ .insert(RigidBody3D, { bodyType: BodyType.Static })
+ .insert(MeshCollider3D, { mesh: 'assets/models/level.esmesh' });
+```
+
+<Aside>
+ 它永远是静态的,不管 `RigidBody3D` 怎么写:三角汤没有惯性张量,求解器没有东西可推。
+ 而且三角形是**单面的**——一块绕序朝下的地板,射线照样报命中,刚体却会直接穿过去。
+ 导入的几何拦不住任何东西时,先怀疑这个。
+</Aside>
+
## 角色
`CharacterController3D` **取代** `RigidBody3D` 而不是与它并存:被求解器推的刚体
diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.ts
index e719cbca7..41cad0fe1 100644
--- a/docs/astro/src/data/componentDocs.ts
+++ b/docs/astro/src/data/componentDocs.ts
@@ -111,6 +111,7 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {
BoxCollider3D: { category: 'physics', summary: 'A box collision shape in 3D. Half-extents are in world units.', doc: 'gameplay/physics-3d', anchor: 'shapes', anchorZh: 'shapes' },
SphereCollider3D: { category: 'physics', summary: 'A sphere collision shape in 3D.', doc: 'gameplay/physics-3d', anchor: 'shapes', anchorZh: 'shapes' },
CapsuleCollider3D: { category: 'physics', summary: 'An upright capsule — what a 3D character is. Total height is 2*(halfHeight + radius).', doc: 'gameplay/physics-3d', anchor: 'shapes', anchorZh: 'shapes' },
+ MeshCollider3D: { category: 'physics', summary: 'Collides against an imported mesh\u2019s own triangles — terrain, stairs, a room. Always static, and one-sided.', doc: 'gameplay/physics-3d', anchor: 'colliding-against-imported-geometry', anchorZh: '用导入的几何做碰撞' },
CharacterController3D: { category: 'physics', summary: 'A kinematic 3D mover: swept against the world, climbs steps, stays glued to slopes, and reports the ground it is on.', doc: 'gameplay/physics-3d', anchor: 'characters', anchorZh: 'characters' },
CharacterController: { category: 'physics', summary: 'Kinematic character movement that slides along walls, climbs slopes and reports ground contact.', doc: 'gameplay/physics', anchor: 'character-controller', anchorZh: '角色控制器' },
OneWayPlatform: { category: 'physics', summary: 'Makes a collider solid from one side only, so a body passes up through it and lands on top.', doc: 'gameplay/physics', anchor: 'one-way-platforms', anchorZh: '单向平台' },
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index c8ec28902..b756d254f 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -1527,6 +1527,35 @@
"color.a"
]
},
+ {
+ "name": "MeshCollider3D",
+ "source": "cpp",
+ "fields": [
+ {
+ "key": "mesh",
+ "type": "Asset<mesh>",
+ "default": "none",
+ "doc": "Geometry (.esmesh) to collide against."
+ },
+ {
+ "key": "friction",
+ "type": "number",
+ "default": "0.3",
+ "range": "≥ 0"
+ },
+ {
+ "key": "restitution",
+ "type": "number",
+ "default": "0",
+ "range": "0–1"
+ },
+ {
+ "key": "enabled",
+ "type": "boolean",
+ "default": "true"
+ }
+ ]
+ },
{
"name": "MeshSkin",
"source": "cpp",
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 6588bafe8..a07583977 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -5,7 +5,7 @@ Symbols: 113 public · 58 beta · 1418 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
-"95e303bc2d7c9fab"
+"f3c3c0443ccbd99d"
```
## ANCHOR_AXES — const @experimental
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 4fa922e0e..35770a307 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -5,7 +5,7 @@ Symbols: 113 public · 63 beta · 1437 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
-"95e303bc2d7c9fab"
+"f3c3c0443ccbd99d"
```
## ANCHOR_AXES — const @experimental
diff --git a/sdk/etc/wasm.api.md b/sdk/etc/wasm.api.md
index b5e6baf79..6634a33c7 100644
--- a/sdk/etc/wasm.api.md
+++ b/sdk/etc/wasm.api.md
@@ -28,6 +28,7 @@ addFlexContainer: (entity: Entity, component: FlexContainer) => void
addInteractable: (entity: Entity, component: Interactable) => void
addLight2D: (entity: Entity, component: Light2D) => void
addMesh2D: (entity: Entity, component: Mesh2D) => void
+addMeshCollider3D: (entity: Entity, component: MeshCollider3D) => void
addMeshSkin: (entity: Entity, component: MeshSkin) => void
addParent: (entity: Entity, component: Parent) => void
addParticleEmitter: (entity: Entity, component: ParticleEmitter) => void
@@ -68,6 +69,7 @@ getFlexContainer: (entity: Entity) => FlexContainer
getInteractable: (entity: Entity) => Interactable
getLight2D: (entity: Entity) => Light2D
getMesh2D: (entity: Entity) => Mesh2D
+getMeshCollider3D: (entity: Entity) => MeshCollider3D
getMeshSkin: (entity: Entity) => MeshSkin
getParent: (entity: Entity) => Parent
getParticleEmitter: (entity: Entity) => ParticleEmitter
@@ -104,6 +106,7 @@ hasFlexContainer: (entity: Entity) => boolean
hasInteractable: (entity: Entity) => boolean
hasLight2D: (entity: Entity) => boolean
hasMesh2D: (entity: Entity) => boolean
+hasMeshCollider3D: (entity: Entity) => boolean
hasMeshSkin: (entity: Entity) => boolean
hasParent: (entity: Entity) => boolean
hasParticleEmitter: (entity: Entity) => boolean
@@ -140,6 +143,7 @@ removeFlexContainer: (entity: Entity) => void
removeInteractable: (entity: Entity) => void
removeLight2D: (entity: Entity) => void
removeMesh2D: (entity: Entity) => void
+removeMeshCollider3D: (entity: Entity) => void
removeMeshSkin: (entity: Entity) => void
removeParent: (entity: Entity) => void
removeParticleEmitter: (entity: Entity) => void
diff --git a/sdk/src/asset/loaders/MeshAssetLoader.ts b/sdk/src/asset/loaders/MeshAssetLoader.ts
index ee0b5ca34..ee758b974 100644
--- a/sdk/src/asset/loaders/MeshAssetLoader.ts
+++ b/sdk/src/asset/loaders/MeshAssetLoader.ts
@@ -4,6 +4,7 @@ import type { AssetLoader, LoadContext } from '../AssetLoader';
import type { ESEngineModule } from '../../wasm';
import { withScratch } from '../../wasm/wasmScratch';
import { decodeMesh, encodeChannelTable } from '../meshFormat';
+import { extractPositions, registerMeshCollision, releaseMeshCollision } from '../meshCollision';
/** A mesh uploaded to the GPU, named by the handle everything else references. */
export interface MeshResult {
@@ -59,10 +60,16 @@ export class MeshAssetLoader implements AssetLoader<MeshResult> {
});
if (!handle) throw new Error(`the engine rejected the geometry in ${path}`);
+ // The triangles the decode already produced, kept for whoever needs shape
+ // rather than pixels — a collider cannot ask the GPU what it uploaded.
+ const positions = extractPositions(mesh.vertices, mesh.vertexCount,
+ mesh.vertexStride, mesh.channels);
+ if (positions) registerMeshCollision(handle, { positions, indices: mesh.indices });
return { handle };
}
unload(asset: MeshResult): void {
+ releaseMeshCollision(asset.handle);
this.module_()?.mesh_release?.(asset.handle);
}
}
diff --git a/sdk/src/asset/meshCollision.ts b/sdk/src/asset/meshCollision.ts
new file mode 100644
index 000000000..7fb373d17
--- /dev/null
+++ b/sdk/src/asset/meshCollision.ts
@@ -0,0 +1,69 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file meshCollision.ts
+ * @brief The CPU-side triangles of a loaded mesh, kept for whoever needs shape
+ * rather than pixels.
+ * @details Geometry goes to the GPU and the bytes are let go, which is right for
+ * drawing and useless for colliding: a physics world, a navmesh bake and
+ * a precise pick all need the triangles themselves. The decode already
+ * produces them, so this keeps the positions and the indices — nothing
+ * else — under the handle everything references the mesh by.
+ *
+ * Positions only: a collider does not care what colour a vertex is, and
+ * keeping the full interleaved buffer would hold several times as much
+ * for no reader.
+ */
+
+/** One mesh's triangles, in the model space its vertices were authored in. */
+export interface MeshCollisionData {
+ /** `vertexCount * 3` floats. */
+ positions: Float32Array;
+ indices: Uint32Array;
+}
+
+const byHandle = new Map<number, MeshCollisionData>();
+
+/** Remember `handle`'s triangles. Called by the loader that decoded them. */
+export function registerMeshCollision(handle: number, data: MeshCollisionData): void {
+ if (handle !== 0) byHandle.set(handle, data);
+}
+
+/** The triangles behind a mesh handle, or null when nothing loaded it. */
+export function getMeshCollision(handle: number): MeshCollisionData | null {
+ return byHandle.get(handle) ?? null;
+}
+
+export function releaseMeshCollision(handle: number): void {
+ byHandle.delete(handle);
+}
+
+/** How many meshes are holding triangles — for a leak check, not for gameplay. */
+export function meshCollisionCount(): number {
+ return byHandle.size;
+}
+
+/**
+ * Pull the Position channel out of an interleaved vertex buffer.
+ *
+ * @param channels The file's channel table; Position is semantic 0.
+ * @returns null when the mesh carries no positions, which nothing can collide with.
+ */
+export function extractPositions(
+ vertices: Uint8Array, vertexCount: number, vertexStride: number,
+ channels: ReadonlyArray<{ semantic: number; offset: number; type: number }>,
+): Float32Array | null {
+ const position = channels.find((c) => c.semantic === 0);
+ // Float32 is type 0 in the format's own enum. A packed position would need
+ // its own decode, and no exporter this engine reads writes one.
+ if (!position || position.type !== 0) return null;
+ const view = new DataView(vertices.buffer, vertices.byteOffset, vertices.byteLength);
+ const out = new Float32Array(vertexCount * 3);
+ for (let i = 0; i < vertexCount; i++) {
+ const at = i * vertexStride + position.offset;
+ out[i * 3] = view.getFloat32(at, true);
+ out[i * 3 + 1] = view.getFloat32(at + 4, true);
+ out[i * 3 + 2] = view.getFloat32(at + 8, true);
+ }
+ return out;
+}
diff --git a/sdk/src/ecs/bridge/ptrAccessors.generated.ts b/sdk/src/ecs/bridge/ptrAccessors.generated.ts
index 03a45cdc1..dd8f2892d 100644
--- a/sdk/src/ecs/bridge/ptrAccessors.generated.ts
+++ b/sdk/src/ecs/bridge/ptrAccessors.generated.ts
@@ -773,6 +773,42 @@ export function createMesh2DData(): Mesh2DPtrData {
};
}
+export interface MeshCollider3DPtrData {
+ mesh: number;
+ friction: number;
+ restitution: number;
+ enabled: boolean;
+}
+
+export function fillMeshCollider3D(
+ f32: Float32Array, u32: Uint32Array, u8: Uint8Array,
+ ptr: number, out: MeshCollider3DPtrData,
+): void {
+ out.mesh = u32[ptr >> 2];
+ out.friction = f32[(ptr + 4) >> 2];
+ out.restitution = f32[(ptr + 8) >> 2];
+ out.enabled = u8[ptr + 12] !== 0;
+}
+
+export function writeMeshCollider3D(
+ f32: Float32Array, u32: Uint32Array, u8: Uint8Array,
+ ptr: number, data: MeshCollider3DPtrData,
+): void {
+ u32[ptr >> 2] = data.mesh;
+ f32[(ptr + 4) >> 2] = data.friction;
+ f32[(ptr + 8) >> 2] = data.restitution;
+ u8[ptr + 12] = data.enabled ? 1 : 0;
+}
+
+export function createMeshCollider3DData(): MeshCollider3DPtrData {
+ return {
+ mesh: 0,
+ friction: 0,
+ restitution: 0,
+ enabled: false,
+ };
+}
+
export interface ParticleEmitterPtrData {
rate: number;
burstCount: number;
@@ -2006,6 +2042,7 @@ export const PTR_ACCESSORS: Record<string, PtrAccessor<any>> = {
Interactable: { fill: fillInteractable, write: writeInteractable, create: createInteractableData },
Light2D: { fill: fillLight2D, write: writeLight2D, create: createLight2DData },
Mesh2D: { fill: fillMesh2D, write: writeMesh2D, create: createMesh2DData },
+ MeshCollider3D: { fill: fillMeshCollider3D, write: writeMeshCollider3D, create: createMeshCollider3DData },
ParticleEmitter: { fill: fillParticleEmitter, write: writeParticleEmitter, create: createParticleEmitterData },
ParticleForceField: { fill: fillParticleForceField, write: writeParticleForceField, create: createParticleForceFieldData },
RigidBody: { fill: fillRigidBody, write: writeRigidBody, create: createRigidBodyData },
diff --git a/sdk/src/ecs/component.generated.ts b/sdk/src/ecs/component.generated.ts
index a3e4fea27..b31b38d44 100644
--- a/sdk/src/ecs/component.generated.ts
+++ b/sdk/src/ecs/component.generated.ts
@@ -15,7 +15,7 @@ import type { Dimension, Padding } from '../wasm/wasm.generated';
* getAbiLayoutHash(); BuiltinBridge.connect() compares them and refuses to
* run on mismatch, because mismatched offsets read the wrong heap bytes.
*/
-export const ABI_LAYOUT_HASH = '95e303bc2d7c9fab';
+export const ABI_LAYOUT_HASH = 'f3c3c0443ccbd99d';
/**
* One asset-valued field of a component: which field, and what kind of
@@ -429,6 +429,23 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
material: { advanced: true },
},
},
+ MeshCollider3D: {
+ defaults: {
+ mesh: 0,
+ friction: 0.3,
+ restitution: 0,
+ enabled: true,
+ },
+ assetFields: [{ field: 'mesh', type: 'mesh' as AssetFieldType }],
+ entityFields: [],
+ colorFields: [],
+ animatableFields: [],
+ fields: {
+ mesh: { tooltip: "Geometry (.esmesh) to collide against." },
+ friction: { min: 0 },
+ restitution: { min: 0, max: 1 },
+ },
+ },
MeshSkin: {
defaults: {
joints: [],
@@ -1172,6 +1189,13 @@ export interface Mesh2DData {
mesh: number;
}
+export interface MeshCollider3DData {
+ mesh: number;
+ friction: number;
+ restitution: number;
+ enabled: boolean;
+}
+
export interface MeshSkinData {
joints: Entity[];
}
diff --git a/sdk/src/physics3d/Physics3DComponents.ts b/sdk/src/physics3d/Physics3DComponents.ts
index 6f812d8a7..bdf0e0e8d 100644
--- a/sdk/src/physics3d/Physics3DComponents.ts
+++ b/sdk/src/physics3d/Physics3DComponents.ts
@@ -10,12 +10,12 @@
import { defineBuiltin } from '../ecs/component';
import type {
RigidBody3DData, BoxCollider3DData, SphereCollider3DData, CapsuleCollider3DData,
- CharacterController3DData,
+ CharacterController3DData, MeshCollider3DData,
} from '../ecs/component.generated';
export type {
RigidBody3DData, BoxCollider3DData, SphereCollider3DData, CapsuleCollider3DData,
- CharacterController3DData,
+ CharacterController3DData, MeshCollider3DData,
};
export const RigidBody3D = defineBuiltin<RigidBody3DData>('RigidBody3D', {
@@ -58,6 +58,19 @@ export const CapsuleCollider3D = defineBuiltin<CapsuleCollider3DData>('CapsuleCo
enabled: true,
});
+/**
+ * Imported geometry used as it is, for a level to collide against. Always static:
+ * a triangle soup has no inertia tensor, so there is nothing for a solver to push.
+ *
+ * @beta
+ */
+export const MeshCollider3D = defineBuiltin<MeshCollider3DData>('MeshCollider3D', {
+ mesh: 0,
+ friction: 0.3,
+ restitution: 0.0,
+ enabled: true,
+});
+
/**
* A kinematic mover for a 3D player or NPC: swept against the world rather than
* solved in it. Set `velocity` each step and read `isOnFloor` back; the vertical
diff --git a/sdk/src/physics3d/Physics3DModule.ts b/sdk/src/physics3d/Physics3DModule.ts
index 0d8525d4c..a111a1b0a 100644
--- a/sdk/src/physics3d/Physics3DModule.ts
+++ b/sdk/src/physics3d/Physics3DModule.ts
@@ -37,7 +37,15 @@ export interface Physics3DWasmModule {
motion: number, gravityScale: number, linearDamping: number,
angularDamping: number, fixedRotation: number,
friction: number, restitution: number, isSensor: number): number;
+ _physics3d_addMeshBody(entity: number, vertexPtr: number, vertexCount: number,
+ indexPtr: number, indexCount: number,
+ px: number, py: number, pz: number,
+ qx: number, qy: number, qz: number, qw: number,
+ friction: number, restitution: number): number;
_physics3d_removeBody(bodyId: number): void;
+
+ _malloc(bytes: number): number;
+ _free(ptr: number): void;
_physics3d_setTransform(bodyId: number, px: number, py: number, pz: number,
qx: number, qy: number, qz: number, qw: number): void;
_physics3d_setLinearVelocity(bodyId: number, vx: number, vy: number, vz: number): void;
diff --git a/sdk/src/physics3d/Physics3DSystem.ts b/sdk/src/physics3d/Physics3DSystem.ts
index 36b59867c..f88a6ceea 100644
--- a/sdk/src/physics3d/Physics3DSystem.ts
+++ b/sdk/src/physics3d/Physics3DSystem.ts
@@ -16,9 +16,11 @@ import { Transform } from '../ecs/component';
import type { TransformData } from '../ecs/component.generated';
import {
RigidBody3D, BoxCollider3D, SphereCollider3D, CapsuleCollider3D, CharacterController3D,
+ MeshCollider3D,
type RigidBody3DData, type BoxCollider3DData, type SphereCollider3DData,
- type CapsuleCollider3DData, type CharacterController3DData,
+ type CapsuleCollider3DData, type CharacterController3DData, type MeshCollider3DData,
} from './Physics3DComponents';
+import { getMeshCollision } from '../asset/meshCollision';
import type { Entity } from '../types';
import type { Physics3DWasmModule, Physics3DEventsData } from './Physics3DModule';
import { PHYSICS3D_TRANSFORM_STRIDE, drainPhysics3DEvents } from './Physics3DModule';
@@ -140,6 +142,10 @@ function createBody(app: App, module: Physics3DWasmModule, entity: Entity,
entity as number, sphere.radius / ppu, px, py, pz, r.x, r.y, r.z, r.w,
...how, sphere.friction, sphere.restitution, sphere.isSensor ? 1 : 0);
}
+ const meshCollider = app.world.get(entity, MeshCollider3D) as MeshCollider3DData | undefined;
+ if (meshCollider?.enabled && meshCollider.mesh !== 0) {
+ return addMeshBody(module, entity, meshCollider, px, py, pz, r, ppu);
+ }
const capsule = app.world.get(entity, CapsuleCollider3D) as CapsuleCollider3DData | undefined;
if (capsule?.enabled) {
return module._physics3d_addCapsule(
@@ -152,6 +158,34 @@ function createBody(app: App, module: Physics3DWasmModule, entity: Entity,
return 0;
}
+/**
+ * Hand a loaded mesh's triangles to the module, scaled into metres.
+ *
+ * They cross through the module's own heap: the positions have to be scaled
+ * anyway, so a copy is made either way and this is the one the module can read.
+ */
+function addMeshBody(module: Physics3DWasmModule, entity: Entity,
+ collider: MeshCollider3DData,
+ px: number, py: number, pz: number,
+ r: { x: number; y: number; z: number; w: number }, ppu: number): number {
+ const geometry = getMeshCollision(collider.mesh);
+ if (!geometry) return 0;
+ const { positions, indices } = geometry;
+ const vertexPtr = module._malloc(positions.length * 4);
+ const indexPtr = module._malloc(indices.length * 4);
+ try {
+ const heapF32 = module.HEAPF32;
+ for (let i = 0; i < positions.length; i++) heapF32[(vertexPtr >> 2) + i] = positions[i]! / ppu;
+ module.HEAPU32.set(indices, indexPtr >> 2);
+ return module._physics3d_addMeshBody(
+ entity as number, vertexPtr, positions.length / 3, indexPtr, indices.length,
+ px, py, pz, r.x, r.y, r.z, r.w, collider.friction, collider.restitution);
+ } finally {
+ module._free(vertexPtr);
+ module._free(indexPtr);
+ }
+}
+
/** Bring the world's population in line with the ECS, then step and read back. */
export function stepPhysics3D(app: App, module: Physics3DWasmModule,
bodies: BodyMap, config: Physics3DConfig,
diff --git a/sdk/src/wasm/ptrLayouts.generated.ts b/sdk/src/wasm/ptrLayouts.generated.ts
index 3940258ee..fc684068f 100644
--- a/sdk/src/wasm/ptrLayouts.generated.ts
+++ b/sdk/src/wasm/ptrLayouts.generated.ts
@@ -218,6 +218,15 @@ export const PTR_LAYOUTS: Record<string, PtrLayout> = {
{ name: 'mesh', type: 'u32', offset: 48 },
],
},
+ MeshCollider3D: {
+ ptrFn: 'getMeshCollider3DPtr',
+ fields: [
+ { name: 'mesh', type: 'u32', offset: 0 },
+ { name: 'friction', type: 'f32', offset: 4 },
+ { name: 'restitution', type: 'f32', offset: 8 },
+ { name: 'enabled', type: 'bool', offset: 12 },
+ ],
+ },
ParticleEmitter: {
ptrFn: 'getParticleEmitterPtr',
fields: [
diff --git a/sdk/src/wasm/wasm.generated.ts b/sdk/src/wasm/wasm.generated.ts
index 07b10ca59..adf7ba53e 100644
--- a/sdk/src/wasm/wasm.generated.ts
+++ b/sdk/src/wasm/wasm.generated.ts
@@ -390,6 +390,13 @@ export interface Mesh2D {
mesh: number;
}
+export interface MeshCollider3D {
+ mesh: number;
+ friction: number;
+ restitution: number;
+ enabled: boolean;
+}
+
export interface MeshSkin {
joints: VectorEntity;
}
@@ -734,6 +741,10 @@ export interface Registry {
getMesh2D(entity: Entity): Mesh2D;
addMesh2D(entity: Entity, component: Mesh2D): void;
removeMesh2D(entity: Entity): void;
+ hasMeshCollider3D(entity: Entity): boolean;
+ getMeshCollider3D(entity: Entity): MeshCollider3D;
+ addMeshCollider3D(entity: Entity, component: MeshCollider3D): void;
+ removeMeshCollider3D(entity: Entity): void;
hasMeshSkin(entity: Entity): boolean;
getMeshSkin(entity: Entity): MeshSkin;
addMeshSkin(entity: Entity, component: MeshSkin): void;
@@ -847,6 +858,7 @@ export interface ESEngineModule {
Interactable: new () => Interactable;
Light2D: new () => Light2D;
Mesh2D: new () => Mesh2D;
+ MeshCollider3D: new () => MeshCollider3D;
MeshSkin: new () => MeshSkin;
Parent: new () => Parent;
ParticleEmitter: new () => ParticleEmitter;
diff --git a/sdk/tests/physics3d-ecs.test.ts b/sdk/tests/physics3d-ecs.test.ts
index 953be0752..92763c4f0 100644
--- a/sdk/tests/physics3d-ecs.test.ts
+++ b/sdk/tests/physics3d-ecs.test.ts
@@ -14,7 +14,11 @@ import { Transform } from '../src/ecs/component';
import type { TransformData } from '../src/ecs/component.generated';
import {
RigidBody3D, BoxCollider3D, SphereCollider3D, CapsuleCollider3D, CharacterController3D,
+ MeshCollider3D,
} from '../src/physics3d/Physics3DComponents';
+import {
+ registerMeshCollision, releaseMeshCollision, extractPositions,
+} from '../src/asset/meshCollision';
import { stepPhysics3D, DEFAULT_PHYSICS3D_CONFIG } from '../src/physics3d/Physics3DSystem';
import type { Physics3DWasmModule } from '../src/physics3d/Physics3DModule';
import type { App } from '../src/app/app';
@@ -31,7 +35,7 @@ function fakeModule(): Physics3DWasmModule & {
} {
const calls: { name: string; args: number[] }[] = [];
// One heap the module's two pointers index into, as wasm has.
- const combined = new Float32Array(2176);
+ const combined = new Float32Array(4096);
const heap = combined.subarray(0, 1024);
const record = (name: string) => (...args: number[]): number => {
calls.push({ name, args });
@@ -42,6 +46,7 @@ function fakeModule(): Physics3DWasmModule & {
let published = 0;
let publishedQuery = 0;
let publishedEvents = 0;
+ let scratchTop = 4096;
return {
calls,
publish(records: number[]) {
@@ -75,6 +80,11 @@ function fakeModule(): Physics3DWasmModule & {
_physics3d_removeCharacter: record('removeCharacter'),
_physics3d_moveCharacter: record('moveCharacter'),
_physics3d_setCharacterPosition: record('setCharacterPosition'),
+ _physics3d_addMeshBody: record('addMeshBody'),
+ // Distinct allocations, as a real heap gives: one address for everything
+ // let the index write land on top of the vertex write.
+ _malloc: (bytes: number) => { const at = scratchTop; scratchTop += bytes; return at; },
+ _free: () => {},
_physics3d_contactEnters: () => 2048 * 4,
_physics3d_contactEntersBytes: () => publishedEvents,
_physics3d_contactExits: () => 0,
@@ -280,6 +290,36 @@ describe('the 3D world and the ECS', () => {
expect(hit!.pointY).toBeCloseTo(1, 6);
});
+ it('collides against a loaded mesh\u2019s own triangles', () => {
+ // Two triangles a metre across, as the loader would have kept them.
+ registerMeshCollision(77, {
+ positions: new Float32Array([0, 0, 0, 100, 0, 0, 0, 0, 100, 100, 0, 100]),
+ indices: new Uint32Array([0, 2, 1, 2, 3, 1]),
+ });
+ const e = spawn();
+ world.insert(e, MeshCollider3D, { mesh: 77 });
+
+ stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG);
+
+ const [call] = called('addMeshBody');
+ expect(call).toBeDefined();
+ expect(call!.args[2]).toBe(4); // four vertices
+ expect(call!.args[4]).toBe(6); // six indices
+ // A 100-unit triangle is a metre in the solver.
+ expect(module.HEAPF32[(call!.args[1] >> 2) + 3]).toBeCloseTo(1, 6);
+ releaseMeshCollision(77);
+ });
+
+ it('registers nothing for a mesh collider whose geometry never loaded', () => {
+ const e = spawn();
+ world.insert(e, MeshCollider3D, { mesh: 999 });
+ stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG);
+ // Handle 999 named a mesh nothing kept triangles for. Registering a body
+ // with no shape would put an invisible point in the world.
+ expect(called('addMeshBody')).toHaveLength(0);
+ expect(bodies.size).toBe(0);
+ });
+
it('leaves a disabled body out of the world', () => {
const e = spawn();
world.insert(e, BoxCollider3D);
@@ -309,3 +349,24 @@ describe('a scene asks for the world it needs', () => {
expect(sceneUsesPhysics(sceneWith('RigidBody3D', 'BoxCollider3D') as never)).toBe(false);
});
});
+
+describe('mesh collision geometry', () => {
+ it('pulls positions out of an interleaved buffer', () => {
+ // Two vertices, each 20 bytes: position (12) then a colour (8) it ignores.
+ const bytes = new Uint8Array(40);
+ const view = new DataView(bytes.buffer);
+ view.setFloat32(0, 1, true); view.setFloat32(4, 2, true); view.setFloat32(8, 3, true);
+ view.setFloat32(20, 4, true); view.setFloat32(24, 5, true); view.setFloat32(28, 6, true);
+ const out = extractPositions(bytes, 2, 20, [
+ { semantic: 0, offset: 0, type: 0 }, { semantic: 1, offset: 12, type: 0 },
+ ]);
+ expect(Array.from(out!)).toEqual([1, 2, 3, 4, 5, 6]);
+ });
+
+ it('answers null for geometry with no positions', () => {
+ // Nothing can collide against a mesh that never said where its vertices are.
+ expect(extractPositions(new Uint8Array(8), 1, 8, [
+ { semantic: 3, offset: 0, type: 0 },
+ ])).toBeNull();
+ });
+});
diff --git a/sdk/tests/physics3d-smoke.mjs b/sdk/tests/physics3d-smoke.mjs
index c78a954da..04d6ba7b9 100644
--- a/sdk/tests/physics3d-smoke.mjs
+++ b/sdk/tests/physics3d-smoke.mjs
@@ -277,7 +277,58 @@ check('and does not stop it', near(bodyState(visitorId).y, 0.5, 0.1),
check('and reports when it leaves', sensorLeft != null && sensorLeft[1] === VISITOR,
JSON.stringify(sensorLeft));
-// ── 8) A removed body is gone from both the sweep and the getter ────────────
+// ── 8) Imported geometry as a collider ─────────────────────────────────────
+// A shallow ramp from two triangles, 4 wide and rising 1, at y=3 well clear of
+// the floor. Shallow on purpose: a steep one only proves that things slide.
+const alloc = (values, Ctor) => {
+ const ptr = m._malloc(values.length * 4);
+ new Ctor(m.HEAPU8.buffer, ptr, values.length).set(values);
+ return ptr;
+};
+const RAMP = 30;
+const rampVerts = alloc(new Float32Array([
+ 0, 0, -2, 4, 1, -2, 0, 0, 2, 4, 1, 2,
+]), Float32Array);
+// Counter-clockwise from above, so the normals point UP. A mesh shape is
+// ONE-SIDED: reversed, a body falls through while a ray still reports a hit.
+const rampIndices = alloc(new Uint32Array([0, 2, 1, 2, 3, 1]), Uint32Array);
+const rampId = m._physics3d_addMeshBody(RAMP, rampVerts, 4, rampIndices, 6,
+ 30, 3, 0, ...IDENTITY, 0.5, 0);
+m._free(rampVerts);
+m._free(rampIndices);
+check('imported geometry becomes a body', rampId !== 0, `id=${rampId}`);
+m._physics3d_optimize();
+
+// A ray finds it at the height the slope predicts: over x=31 the surface is at
+// 3.25, so the hit is 6.75 of the ray's 20 units.
+const onRamp = raycast(31, 10, 0, 0, -20, 0);
+check('a ray meets the ramp where it slopes', onRamp != null && onRamp.entity === RAMP
+ && near(onRamp.fraction, 0.3375, 0.02),
+ `entity=${onRamp?.entity} fraction=${onRamp?.fraction?.toFixed(4)} want 0.3375`);
+
+// Over x=32 the surface is at 3.5, so a half-metre box settles near 4; the floor
+// is at 0. A BOX, not a sphere — a sphere rolls off any slope, however shallow.
+const CRATE = 31;
+const crateId = m._physics3d_addBox(CRATE, 0.5, 0.5, 0.5, 32, 8, 0, ...IDENTITY,
+ ...FREE(DYNAMIC), 0.9, 0, 0);
+step(240);
+const crate = bodyState(crateId);
+check('and a body rests on its triangles', crate && crate.y > 3.4,
+ `y=${crate?.y?.toFixed(4)} want about 4 (ramp surface 3.5 + half-extent)`);
+
+// Degenerate input is REFUSED, not quietly trimmed — an out-of-range index would
+// read past the vertices. One good triangle and one bad, so silently dropping the
+// bad one would still build a body.
+const badVerts = alloc(new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]), Float32Array);
+const badIndices = alloc(new Uint32Array([0, 1, 2, 0, 1, 99]), Uint32Array);
+check('an index past the vertices is refused',
+ m._physics3d_addMeshBody(32, badVerts, 3, badIndices, 6, 0, 0, 0, ...IDENTITY, 0.5, 0) === 0);
+check('and so is a non-triangle count',
+ m._physics3d_addMeshBody(32, badVerts, 3, badIndices, 5, 0, 0, 0, ...IDENTITY, 0.5, 0) === 0);
+m._free(badVerts);
+m._free(badIndices);
+
+// ── 9) A removed body is gone from both the sweep and the getter ────────────
m._physics3d_removeBody(capId);
step(1);
check('a removed body leaves the readback', bodyPos(CAP) === null);
diff --git a/src/esengine/bindings/EditorAPI.generated.cpp b/src/esengine/bindings/EditorAPI.generated.cpp
index 544868a6a..740e20457 100644
--- a/src/esengine/bindings/EditorAPI.generated.cpp
+++ b/src/esengine/bindings/EditorAPI.generated.cpp
@@ -2,10 +2,10 @@
* @file EditorAPI.generated.cpp
* @brief Auto-generated editor API with string-dispatched component access
* @details Generated by EHT - DO NOT EDIT
- * @schema_hash 79309dcbf27e8e60
+ * @schema_hash 1caddb3e87fa4b7c
*/
-#define ES_EDITOR_API_SCHEMA_HASH "79309dcbf27e8e60"
+#define ES_EDITOR_API_SCHEMA_HASH "1caddb3e87fa4b7c"
#include <emscripten/bind.h>
#include <string>
@@ -73,6 +73,7 @@ std::vector<std::string> editor_getComponentNames() {
"Interactable",
"Light2D",
"Mesh2D",
+ "MeshCollider3D",
"MeshSkin",
"Parent",
"ParticleEmitter",
@@ -310,6 +311,13 @@ std::string editor_getComponentSchema(const std::string& name) {
{"key":"enabled","type":"bool","group":"Mesh2D"},
{"key":"mesh","type":"asset","group":"Mesh2D"}
])JSON";
+ } else if (name == "MeshCollider3D") {
+ return R"JSON([
+ {"key":"mesh","type":"asset","group":"MeshCollider3D"},
+ {"key":"friction","type":"float","group":"MeshCollider3D"},
+ {"key":"restitution","type":"float","group":"MeshCollider3D"},
+ {"key":"enabled","type":"bool","group":"MeshCollider3D"}
+ ])JSON";
} else if (name == "MeshSkin") {
return R"JSON([
{"key":"joints","type":"entity","group":"MeshSkin"}
@@ -713,6 +721,9 @@ bool editor_addComponent(Registry& reg, u32 e, const std::string& name) {
} else if (name == "Mesh2D") {
if (!reg.has<esengine::ecs::Mesh2D>(entity)) reg.emplace<esengine::ecs::Mesh2D>(entity);
return true;
+ } else if (name == "MeshCollider3D") {
+ if (!reg.has<esengine::ecs::MeshCollider3D>(entity)) reg.emplace<esengine::ecs::MeshCollider3D>(entity);
+ return true;
} else if (name == "MeshSkin") {
if (!reg.has<esengine::ecs::MeshSkin>(entity)) reg.emplace<esengine::ecs::MeshSkin>(entity);
return true;
@@ -816,6 +827,8 @@ bool editor_removeComponent(Registry& reg, u32 e, const std::string& name) {
if (reg.has<esengine::ecs::Light2D>(entity)) { reg.remove<esengine::ecs::Light2D>(entity); return true; }
} else if (name == "Mesh2D") {
if (reg.has<esengine::ecs::Mesh2D>(entity)) { reg.remove<esengine::ecs::Mesh2D>(entity); return true; }
+ } else if (name == "MeshCollider3D") {
+ if (reg.has<esengine::ecs::MeshCollider3D>(entity)) { reg.remove<esengine::ecs::MeshCollider3D>(entity); return true; }
} else if (name == "MeshSkin") {
if (reg.has<esengine::ecs::MeshSkin>(entity)) { reg.remove<esengine::ecs::MeshSkin>(entity); return true; }
} else if (name == "Parent") {
@@ -880,6 +893,7 @@ bool editor_hasComponent(Registry& reg, u32 e, const std::string& name) {
if (name == "Interactable") return reg.has<esengine::ecs::Interactable>(entity);
if (name == "Light2D") return reg.has<esengine::ecs::Light2D>(entity);
if (name == "Mesh2D") return reg.has<esengine::ecs::Mesh2D>(entity);
+ if (name == "MeshCollider3D") return reg.has<esengine::ecs::MeshCollider3D>(entity);
if (name == "MeshSkin") return reg.has<esengine::ecs::MeshSkin>(entity);
if (name == "Parent") return reg.has<esengine::ecs::Parent>(entity);
if (name == "ParticleEmitter") return reg.has<esengine::ecs::ParticleEmitter>(entity);
@@ -925,6 +939,7 @@ std::vector<std::string> editor_getComponents(Registry& reg, u32 e) {
if (reg.has<esengine::ecs::Interactable>(entity)) result.push_back("Interactable");
if (reg.has<esengine::ecs::Light2D>(entity)) result.push_back("Light2D");
if (reg.has<esengine::ecs::Mesh2D>(entity)) result.push_back("Mesh2D");
+ if (reg.has<esengine::ecs::MeshCollider3D>(entity)) result.push_back("MeshCollider3D");
if (reg.has<esengine::ecs::MeshSkin>(entity)) result.push_back("MeshSkin");
if (reg.has<esengine::ecs::Parent>(entity)) result.push_back("Parent");
if (reg.has<esengine::ecs::ParticleEmitter>(entity)) result.push_back("ParticleEmitter");
@@ -1118,6 +1133,13 @@ bool editor_setFloat(Registry& reg, u32 e, const std::string& comp, const std::s
else if (field == "parallax.y") { c.parallax.y = value; }
else { return false; }
return true;
+ } else if (comp == "MeshCollider3D") {
+ if (!reg.has<esengine::ecs::MeshCollider3D>(entity)) return false;
+ auto& c = reg.get<esengine::ecs::MeshCollider3D>(entity);
+ if (field == "friction") { c.friction = value; }
+ else if (field == "restitution") { c.restitution = value; }
+ else { return false; }
+ return true;
} else if (comp == "ParticleEmitter") {
if (!reg.has<esengine::ecs::ParticleEmitter>(entity)) return false;
auto& c = reg.get<esengine::ecs::ParticleEmitter>(entity);
@@ -1556,6 +1578,11 @@ f32 editor_getFloat(Registry& reg, u32 e, const std::string& comp, const std::st
else if (field == "color.a") { return c.color.a; }
else if (field == "parallax.x") { return c.parallax.x; }
else if (field == "parallax.y") { return c.parallax.y; }
+ } else if (comp == "MeshCollider3D") {
+ if (!reg.has<esengine::ecs::MeshCollider3D>(entity)) return 0.0f;
+ const auto& c = reg.get<esengine::ecs::MeshCollider3D>(entity);
+ if (field == "friction") { return c.friction; }
+ else if (field == "restitution") { return c.restitution; }
} else if (comp == "ParticleEmitter") {
if (!reg.has<esengine::ecs::ParticleEmitter>(entity)) return 0.0f;
const auto& c = reg.get<esengine::ecs::ParticleEmitter>(entity);
@@ -1887,6 +1914,12 @@ bool editor_setInt(Registry& reg, u32 e, const std::string& comp, const std::str
else if (field == "mesh") { c.mesh = resource::MeshHandle(static_cast<u32>(value)); }
else { return false; }
return true;
+ } else if (comp == "MeshCollider3D") {
+ if (!reg.has<esengine::ecs::MeshCollider3D>(entity)) return false;
+ auto& c = reg.get<esengine::ecs::MeshCollider3D>(entity);
+ if (field == "mesh") { c.mesh = resource::MeshHandle(static_cast<u32>(value)); }
+ else { return false; }
+ return true;
} else if (comp == "Parent") {
if (field != "entity") return false;
esengine::ecs::setParent(reg, entity, static_cast<Entity>(value));
@@ -2080,6 +2113,10 @@ i32 editor_getInt(Registry& reg, u32 e, const std::string& comp, const std::stri
else if (field == "layer") { return static_cast<i32>(c.layer); }
else if (field == "material") { return static_cast<i32>(c.material); }
else if (field == "mesh") { return static_cast<i32>(c.mesh.id()); }
+ } else if (comp == "MeshCollider3D") {
+ if (!reg.has<esengine::ecs::MeshCollider3D>(entity)) return 0;
+ const auto& c = reg.get<esengine::ecs::MeshCollider3D>(entity);
+ if (field == "mesh") { return static_cast<i32>(c.mesh.id()); }
} else if (comp == "Parent") {
if (!reg.has<esengine::ecs::Parent>(entity)) return 0;
const auto& c = reg.get<esengine::ecs::Parent>(entity);
@@ -2275,6 +2312,12 @@ bool editor_setBool(Registry& reg, u32 e, const std::string& comp, const std::st
else if (field == "enabled") { c.enabled = value; }
else { return false; }
return true;
+ } else if (comp == "MeshCollider3D") {
+ if (!reg.has<esengine::ecs::MeshCollider3D>(entity)) return false;
+ auto& c = reg.get<esengine::ecs::MeshCollider3D>(entity);
+ if (field == "enabled") { c.enabled = value; }
+ else { return false; }
+ return true;
} else if (comp == "ParticleEmitter") {
if (!reg.has<esengine::ecs::ParticleEmitter>(entity)) return false;
auto& c = reg.get<esengine::ecs::ParticleEmitter>(entity);
@@ -2470,6 +2513,10 @@ bool editor_getBool(Registry& reg, u32 e, const std::string& comp, const std::st
else if (field == "cullBackfaces") { return c.cullBackfaces; }
else if (field == "lit") { return c.lit; }
else if (field == "enabled") { return c.enabled; }
+ } else if (comp == "MeshCollider3D") {
+ if (!reg.has<esengine::ecs::MeshCollider3D>(entity)) return false;
+ const auto& c = reg.get<esengine::ecs::MeshCollider3D>(entity);
+ if (field == "enabled") { return c.enabled; }
} else if (comp == "ParticleEmitter") {
if (!reg.has<esengine::ecs::ParticleEmitter>(entity)) return false;
const auto& c = reg.get<esengine::ecs::ParticleEmitter>(entity);
diff --git a/src/esengine/bindings/WebBindings.generated.cpp b/src/esengine/bindings/WebBindings.generated.cpp
index d2deb0dcb..7dc97081b 100644
--- a/src/esengine/bindings/WebBindings.generated.cpp
+++ b/src/esengine/bindings/WebBindings.generated.cpp
@@ -545,6 +545,35 @@ Mesh2DJS mesh2dToJS(const esengine::ecs::Mesh2D& c) {
return js;
}
+struct MeshCollider3DJS {
+ u32 mesh;
+ f32 friction;
+ f32 restitution;
+ bool enabled;
+};
+
+void meshcollider3dApplyJS(esengine::ecs::MeshCollider3D& c, const MeshCollider3DJS& js) {
+ c.mesh = resource::MeshHandle(js.mesh);
+ c.friction = js.friction;
+ c.restitution = js.restitution;
+ c.enabled = js.enabled;
+}
+
+esengine::ecs::MeshCollider3D meshcollider3dFromJS(const MeshCollider3DJS& js) {
+ esengine::ecs::MeshCollider3D c;
+ meshcollider3dApplyJS(c, js);
+ return c;
+}
+
+MeshCollider3DJS meshcollider3dToJS(const esengine::ecs::MeshCollider3D& c) {
+ MeshCollider3DJS js;
+ js.mesh = c.mesh.id();
+ js.friction = c.friction;
+ js.restitution = c.restitution;
+ js.enabled = c.enabled;
+ return js;
+}
+
struct MeshSkinJS {
std::vector<u32> joints;
};
@@ -1378,6 +1407,12 @@ EMSCRIPTEN_BINDINGS(esengine_components) {
.field("enabled", &Mesh2DJS::enabled)
.field("mesh", &Mesh2DJS::mesh);
+ value_object<MeshCollider3DJS>("MeshCollider3D")
+ .field("mesh", &MeshCollider3DJS::mesh)
+ .field("friction", &MeshCollider3DJS::friction)
+ .field("restitution", &MeshCollider3DJS::restitution)
+ .field("enabled", &MeshCollider3DJS::enabled);
+
value_object<MeshSkinJS>("MeshSkin")
.field("joints", &MeshSkinJS::joints);
@@ -1991,6 +2026,30 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {
r.remove<esengine::ecs::Mesh2D>(entity);
}))
+ // MeshCollider3D
+ .function("hasMeshCollider3D", optional_override([](Registry& r, u32 e) {
+ return r.has<esengine::ecs::MeshCollider3D>(static_cast<Entity>(e));
+ }))
+ .function("getMeshCollider3D", optional_override([](Registry& r, u32 e) {
+ auto entity = static_cast<Entity>(e);
+ if (!r.valid(entity) || !r.has<esengine::ecs::MeshCollider3D>(entity)) return MeshCollider3DJS{};
+ return meshcollider3dToJS(r.get<esengine::ecs::MeshCollider3D>(entity));
+ }))
+ .function("addMeshCollider3D", optional_override([](Registry& r, u32 e, const MeshCollider3DJS& js) {
+ auto entity = static_cast<Entity>(e);
+ if (!r.valid(entity)) return;
+ if (auto* existing = r.tryGet<esengine::ecs::MeshCollider3D>(entity)) {
+ meshcollider3dApplyJS(*existing, js);
+ return;
+ }
+ r.emplaceOrReplace<esengine::ecs::MeshCollider3D>(entity, meshcollider3dFromJS(js));
+ }))
+ .function("removeMeshCollider3D", optional_override([](Registry& r, u32 e) {
+ auto entity = static_cast<Entity>(e);
+ if (!r.valid(entity) || !r.has<esengine::ecs::MeshCollider3D>(entity)) return;
+ r.remove<esengine::ecs::MeshCollider3D>(entity);
+ }))
+
// MeshSkin
.function("hasMeshSkin", optional_override([](Registry& r, u32 e) {
return r.has<esengine::ecs::MeshSkin>(static_cast<Entity>(e));
@@ -2497,6 +2556,7 @@ emscripten::val esengineGetBuiltinComponentNames() {
arr.set(i++, val(std::string("Interactable")));
arr.set(i++, val(std::string("Light2D")));
arr.set(i++, val(std::string("Mesh2D")));
+ arr.set(i++, val(std::string("MeshCollider3D")));
arr.set(i++, val(std::string("MeshSkin")));
arr.set(i++, val(std::string("Parent")));
arr.set(i++, val(std::string("ParticleEmitter")));
@@ -2653,6 +2713,10 @@ static_assert(offsetof(esengine::ecs::Mesh2D, parallax) == 32, "ABI offset drift
static_assert(offsetof(esengine::ecs::Mesh2D, material) == 40, "ABI offset drift: esengine::ecs::Mesh2D.material (EHT expected 40)");
static_assert(offsetof(esengine::ecs::Mesh2D, enabled) == 44, "ABI offset drift: esengine::ecs::Mesh2D.enabled (EHT expected 44)");
static_assert(offsetof(esengine::ecs::Mesh2D, mesh) == 48, "ABI offset drift: esengine::ecs::Mesh2D.mesh (EHT expected 48)");
+static_assert(offsetof(esengine::ecs::MeshCollider3D, mesh) == 0, "ABI offset drift: esengine::ecs::MeshCollider3D.mesh (EHT expected 0)");
+static_assert(offsetof(esengine::ecs::MeshCollider3D, friction) == 4, "ABI offset drift: esengine::ecs::MeshCollider3D.friction (EHT expected 4)");
+static_assert(offsetof(esengine::ecs::MeshCollider3D, restitution) == 8, "ABI offset drift: esengine::ecs::MeshCollider3D.restitution (EHT expected 8)");
+static_assert(offsetof(esengine::ecs::MeshCollider3D, enabled) == 12, "ABI offset drift: esengine::ecs::MeshCollider3D.enabled (EHT expected 12)");
static_assert(offsetof(esengine::ecs::ParticleEmitter, rate) == 0, "ABI offset drift: esengine::ecs::ParticleEmitter.rate (EHT expected 0)");
static_assert(offsetof(esengine::ecs::ParticleEmitter, burstCount) == 4, "ABI offset drift: esengine::ecs::ParticleEmitter.burstCount (EHT expected 4)");
static_assert(offsetof(esengine::ecs::ParticleEmitter, burstInterval) == 8, "ABI offset drift: esengine::ecs::ParticleEmitter.burstInterval (EHT expected 8)");
@@ -2867,7 +2931,7 @@ static_assert(offsetof(esengine::ecs::Velocity, angular) == 12, "ABI offset drif
// ABI Hash -- runtime handshake against the SDK bundle
// =============================================================================
-static const char* kEsAbiLayoutHash = "95e303bc2d7c9fab";
+static const char* kEsAbiLayoutHash = "f3c3c0443ccbd99d";
std::string esengineGetAbiLayoutHash() {
return std::string(kEsAbiLayoutHash);
diff --git a/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp b/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp
index 1f7b6e129..740e59b28 100644
--- a/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp
+++ b/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp
@@ -21,6 +21,7 @@
#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/MeshShape.h>
#include <Jolt/Physics/Collision/Shape/SphereShape.h>
#include <Jolt/Physics/Character/CharacterVirtual.h>
#include <Jolt/Physics/Collision/ContactListener.h>
@@ -141,7 +142,7 @@ ContactRecorder& recorder() {
}
/// Register a shape as a body, and remember which entity it speaks for.
-uint32_t addBody(uint32_t entity, Shape* shape, float px, float py, float pz,
+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) {
if (!g().isValid()) return 0;
@@ -303,6 +304,49 @@ uint32_t physics3d_addCapsule(uint32_t entity, float radius, float halfHeight,
friction, restitution, isSensor);
}
+/**
+ * @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,
+ 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}, friction, restitution, 0);
+}
+
EMSCRIPTEN_KEEPALIVE
void physics3d_removeBody(uint32_t bodyId) {
if (!g().isValid() || bodyId == 0) return;
diff --git a/src/esengine/ecs/components/RigidBody3D.hpp b/src/esengine/ecs/components/RigidBody3D.hpp
index 19398672b..06b1f5d0e 100644
--- a/src/esengine/ecs/components/RigidBody3D.hpp
+++ b/src/esengine/ecs/components/RigidBody3D.hpp
@@ -124,6 +124,30 @@ struct CapsuleCollider3D {
bool enabled{true};
};
+/**
+ * @brief Imported geometry, used as it is, for a level to collide against.
+ *
+ * @details What a box or a capsule cannot say: a terrain, a staircase, a room.
+ * ALWAYS STATIC whatever the RigidBody3D says — a triangle soup has no
+ * inertia tensor, so there is nothing for a solver to push. Its triangles
+ * are also ONE-SIDED: reversed winding stops nothing.
+ */
+ES_COMPONENT()
+struct MeshCollider3D {
+ /** @brief The geometry to collide against. Its triangles are used directly. */
+ ES_PROPERTY(asset = mesh, tooltip="Geometry (.esmesh) to collide against.")
+ resource::MeshHandle mesh;
+
+ ES_PROPERTY(min=0)
+ f32 friction{0.3f};
+
+ ES_PROPERTY(min=0, max=1)
+ f32 restitution{0.0f};
+
+ ES_PROPERTY()
+ bool enabled{true};
+};
+
/**
* @brief A kinematic mover for a 3D player or NPC.
*