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): 3D bodies choose who they meet

esengine32c49cbc504f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a2ee2e26f..bbd64dd2d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,16 @@ published separately; it ships inside the editor.
### Added
+- **3D collision layers.** Every body is in one of sixteen layers, and a project
+ says which layers hear from which — bullets that pass through their own team
+ and stop on the world, which two layers could not express. Both sides must
+ agree, so one of them refusing keeps two bodies apart and a rule only has to be
+ written once.
+
+ ONE layer per body rather than the 2D world's category bits: Jolt classifies a
+ body by a single id. A body's layer is fixed when it enters the world, so the
+ matrix is installed as the world is built.
+
- **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
diff --git a/docs/astro/src/content/docs/gameplay/physics-3d.mdx b/docs/astro/src/content/docs/gameplay/physics-3d.mdx
index 3cfd2a27f..c790be64b 100644
--- a/docs/astro/src/content/docs/gameplay/physics-3d.mdx
+++ b/docs/astro/src/content/docs/gameplay/physics-3d.mdx
@@ -95,6 +95,30 @@ if (input.justPressed('jump') && c.isOnFloor) c.velocity.y = 500;
leaving every caller to rediscover it.
</Aside>
+## Collision layers
+
+Every body is in one of sixteen layers, and a project says which layers hear from
+which. Both sides must agree — one of them refusing is enough to keep two bodies
+apart, so a rule only has to be written once to hold.
+
+```typescript
+app.addPlugin(physics3dPlugin(url, {
+ layerMasks: [
+ 0xFFFF, // 0: everything
+ 0xFFFF, // 1: the world
+ ~(1 << 3), // 2: bullets — not their own team
+ 0xFFFF, // 3: that team
+ ],
+}));
+```
+
+<Aside>
+ ONE layer per body, not a set of category bits like the 2D world uses: Jolt
+ classifies a body by a single id. And a body's layer is fixed when it enters the
+ world, so the matrix has to be in place before anything is registered — the
+ plugin installs it as the world is built.
+</Aside>
+
## Collision events
Each step publishes what touched what into the `Physics3DEvents` resource. It is
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 6aacfef46..44a913958 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
@@ -87,6 +87,28 @@ if (input.justPressed('jump') && c.isOnFloor) c.velocity.y = 500;
而不是让每个调用者各自重新发现这件事。
</Aside>
+## 碰撞层
+
+每个刚体属于十六层中的一层,由项目声明哪些层之间能互相听见。**两边都得同意**——
+其中一边拒绝就足以让两个刚体互不相碰,所以一条规则只需要写一次就成立。
+
+```typescript
+app.addPlugin(physics3dPlugin(url, {
+ layerMasks: [
+ 0xFFFF, // 0: 全部
+ 0xFFFF, // 1: 世界
+ ~(1 << 3), // 2: 子弹 —— 不打自己人
+ 0xFFFF, // 3: 那支队伍
+ ],
+}));
+```
+
+<Aside>
+ 一个刚体**只属于一层**,不像 2D 世界那样用一组类别位:Jolt 用单个 id 给刚体分类。
+ 另外,刚体的层在它进入世界的那一刻就固定了,所以矩阵必须在任何刚体注册之前就位——
+ 插件在建世界时装它。
+</Aside>
+
## 碰撞事件
每一步都会把「谁碰到了谁」发布到 `Physics3DEvents` 资源里。它按固定步长排空,
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index b756d254f..9891d484a 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -773,6 +773,13 @@
"doc": "Steepest ground it can stand on",
"range": "0–1.5708, step 0.01"
},
+ {
+ "key": "layer",
+ "type": "number",
+ "default": "0",
+ "range": "0–15, step 1",
+ "advanced": true
+ },
{
"key": "stepHeight",
"type": "number",
@@ -1537,6 +1544,13 @@
"default": "none",
"doc": "Geometry (.esmesh) to collide against."
},
+ {
+ "key": "layer",
+ "type": "number",
+ "default": "0",
+ "range": "0–15",
+ "advanced": true
+ },
{
"key": "friction",
"type": "number",
@@ -2613,6 +2627,13 @@
"Dynamic"
]
},
+ {
+ "key": "layer",
+ "type": "number",
+ "default": "0",
+ "range": "0–15",
+ "advanced": true
+ },
{
"key": "gravityScale",
"type": "number",
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index a07583977..2df504f65 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
```
-"f3c3c0443ccbd99d"
+"efd9284ec11052f6"
```
## ANCHOR_AXES — const @experimental
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 35770a307..ed9284726 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
```
-"f3c3c0443ccbd99d"
+"efd9284ec11052f6"
```
## ANCHOR_AXES — const @experimental
diff --git a/sdk/src/ecs/bridge/ptrAccessors.generated.ts b/sdk/src/ecs/bridge/ptrAccessors.generated.ts
index dd8f2892d..6c45e2cb6 100644
--- a/sdk/src/ecs/bridge/ptrAccessors.generated.ts
+++ b/sdk/src/ecs/bridge/ptrAccessors.generated.ts
@@ -382,6 +382,7 @@ export interface CharacterController3DPtrData {
snapDown: number;
mass: number;
enabled: boolean;
+ layer: number;
isOnFloor: boolean;
floorNormal: Vec3;
realVelocity: Vec3;
@@ -399,9 +400,10 @@ export function fillCharacterController3D(
out.snapDown = f32[(ptr + 28) >> 2];
out.mass = f32[(ptr + 32) >> 2];
out.enabled = u8[ptr + 36] !== 0;
- out.isOnFloor = u8[ptr + 37] !== 0;
- const floorNormal_ = out.floorNormal; floorNormal_.x = f32[(ptr + 40) >> 2]; floorNormal_.y = f32[((ptr + 40) >> 2) + 1]; floorNormal_.z = f32[((ptr + 40) >> 2) + 2];
- const realVelocity_ = out.realVelocity; realVelocity_.x = f32[(ptr + 52) >> 2]; realVelocity_.y = f32[((ptr + 52) >> 2) + 1]; realVelocity_.z = f32[((ptr + 52) >> 2) + 2];
+ out.layer = u32[(ptr + 40) >> 2];
+ out.isOnFloor = u8[ptr + 44] !== 0;
+ const floorNormal_ = out.floorNormal; floorNormal_.x = f32[(ptr + 48) >> 2]; floorNormal_.y = f32[((ptr + 48) >> 2) + 1]; floorNormal_.z = f32[((ptr + 48) >> 2) + 2];
+ const realVelocity_ = out.realVelocity; realVelocity_.x = f32[(ptr + 60) >> 2]; realVelocity_.y = f32[((ptr + 60) >> 2) + 1]; realVelocity_.z = f32[((ptr + 60) >> 2) + 2];
}
export function writeCharacterController3D(
@@ -416,9 +418,10 @@ export function writeCharacterController3D(
f32[(ptr + 28) >> 2] = data.snapDown;
f32[(ptr + 32) >> 2] = data.mass;
u8[ptr + 36] = data.enabled ? 1 : 0;
- u8[ptr + 37] = data.isOnFloor ? 1 : 0;
- f32[(ptr + 40) >> 2] = data.floorNormal.x; f32[((ptr + 40) >> 2) + 1] = data.floorNormal.y; f32[((ptr + 40) >> 2) + 2] = data.floorNormal.z;
- f32[(ptr + 52) >> 2] = data.realVelocity.x; f32[((ptr + 52) >> 2) + 1] = data.realVelocity.y; f32[((ptr + 52) >> 2) + 2] = data.realVelocity.z;
+ u32[(ptr + 40) >> 2] = data.layer;
+ u8[ptr + 44] = data.isOnFloor ? 1 : 0;
+ f32[(ptr + 48) >> 2] = data.floorNormal.x; f32[((ptr + 48) >> 2) + 1] = data.floorNormal.y; f32[((ptr + 48) >> 2) + 2] = data.floorNormal.z;
+ f32[(ptr + 60) >> 2] = data.realVelocity.x; f32[((ptr + 60) >> 2) + 1] = data.realVelocity.y; f32[((ptr + 60) >> 2) + 2] = data.realVelocity.z;
}
export function createCharacterController3DData(): CharacterController3DPtrData {
@@ -431,6 +434,7 @@ export function createCharacterController3DData(): CharacterController3DPtrData
snapDown: 0,
mass: 0,
enabled: false,
+ layer: 0,
isOnFloor: false,
floorNormal: { x: 0, y: 0, z: 0 },
realVelocity: { x: 0, y: 0, z: 0 },
@@ -777,6 +781,7 @@ export interface MeshCollider3DPtrData {
mesh: number;
friction: number;
restitution: number;
+ layer: number;
enabled: boolean;
}
@@ -787,7 +792,8 @@ export function fillMeshCollider3D(
out.mesh = u32[ptr >> 2];
out.friction = f32[(ptr + 4) >> 2];
out.restitution = f32[(ptr + 8) >> 2];
- out.enabled = u8[ptr + 12] !== 0;
+ out.layer = u32[(ptr + 12) >> 2];
+ out.enabled = u8[ptr + 16] !== 0;
}
export function writeMeshCollider3D(
@@ -797,7 +803,8 @@ export function writeMeshCollider3D(
u32[ptr >> 2] = data.mesh;
f32[(ptr + 4) >> 2] = data.friction;
f32[(ptr + 8) >> 2] = data.restitution;
- u8[ptr + 12] = data.enabled ? 1 : 0;
+ u32[(ptr + 12) >> 2] = data.layer;
+ u8[ptr + 16] = data.enabled ? 1 : 0;
}
export function createMeshCollider3DData(): MeshCollider3DPtrData {
@@ -805,6 +812,7 @@ export function createMeshCollider3DData(): MeshCollider3DPtrData {
mesh: 0,
friction: 0,
restitution: 0,
+ layer: 0,
enabled: false,
};
}
@@ -1159,6 +1167,7 @@ export interface RigidBody3DPtrData {
linearDamping: number;
angularDamping: number;
fixedRotation: boolean;
+ layer: number;
enabled: boolean;
}
@@ -1171,7 +1180,8 @@ export function fillRigidBody3D(
out.linearDamping = f32[(ptr + 8) >> 2];
out.angularDamping = f32[(ptr + 12) >> 2];
out.fixedRotation = u8[ptr + 16] !== 0;
- out.enabled = u8[ptr + 17] !== 0;
+ out.layer = u32[(ptr + 20) >> 2];
+ out.enabled = u8[ptr + 24] !== 0;
}
export function writeRigidBody3D(
@@ -1183,7 +1193,8 @@ export function writeRigidBody3D(
f32[(ptr + 8) >> 2] = data.linearDamping;
f32[(ptr + 12) >> 2] = data.angularDamping;
u8[ptr + 16] = data.fixedRotation ? 1 : 0;
- u8[ptr + 17] = data.enabled ? 1 : 0;
+ u32[(ptr + 20) >> 2] = data.layer;
+ u8[ptr + 24] = data.enabled ? 1 : 0;
}
export function createRigidBody3DData(): RigidBody3DPtrData {
@@ -1193,6 +1204,7 @@ export function createRigidBody3DData(): RigidBody3DPtrData {
linearDamping: 0,
angularDamping: 0,
fixedRotation: false,
+ layer: 0,
enabled: false,
};
}
diff --git a/sdk/src/ecs/component.generated.ts b/sdk/src/ecs/component.generated.ts
index b31b38d44..715a63ea1 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 = 'f3c3c0443ccbd99d';
+export const ABI_LAYOUT_HASH = 'efd9284ec11052f6';
/**
* One asset-valued field of a component: which field, and what kind of
@@ -252,6 +252,7 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
snapDown: 0.5,
mass: 70,
enabled: true,
+ layer: 0,
isOnFloor: false,
floorNormal: { x: 0, y: 0, z: 0 },
realVelocity: { x: 0, y: 0, z: 0 },
@@ -267,6 +268,7 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
stepHeight: { min: 0, advanced: true },
snapDown: { min: 0, advanced: true },
mass: { min: 0, advanced: true },
+ layer: { min: 0, max: 15, advanced: true },
isOnFloor: { advanced: true },
floorNormal: { advanced: true },
realVelocity: { advanced: true },
@@ -434,6 +436,7 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
mesh: 0,
friction: 0.3,
restitution: 0,
+ layer: 0,
enabled: true,
},
assetFields: [{ field: 'mesh', type: 'mesh' as AssetFieldType }],
@@ -444,6 +447,7 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
mesh: { tooltip: "Geometry (.esmesh) to collide against." },
friction: { min: 0 },
restitution: { min: 0, max: 1 },
+ layer: { min: 0, max: 15, advanced: true },
},
},
MeshSkin: {
@@ -639,6 +643,7 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
linearDamping: 0.05,
angularDamping: 0.05,
fixedRotation: false,
+ layer: 0,
enabled: true,
},
assetFields: [],
@@ -650,6 +655,7 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
gravityScale: { min: 0 },
linearDamping: { min: 0 },
angularDamping: { min: 0 },
+ layer: { min: 0, max: 15, advanced: true },
},
},
SegmentCollider: {
@@ -1098,6 +1104,7 @@ export interface CharacterController3DData {
snapDown: number;
mass: number;
enabled: boolean;
+ layer: number;
isOnFloor: boolean;
floorNormal: Vec3;
realVelocity: Vec3;
@@ -1193,6 +1200,7 @@ export interface MeshCollider3DData {
mesh: number;
friction: number;
restitution: number;
+ layer: number;
enabled: boolean;
}
@@ -1296,6 +1304,7 @@ export interface RigidBody3DData {
linearDamping: number;
angularDamping: number;
fixedRotation: boolean;
+ layer: number;
enabled: boolean;
}
diff --git a/sdk/src/physics3d/Physics3DComponents.ts b/sdk/src/physics3d/Physics3DComponents.ts
index bdf0e0e8d..1d71d75a1 100644
--- a/sdk/src/physics3d/Physics3DComponents.ts
+++ b/sdk/src/physics3d/Physics3DComponents.ts
@@ -20,6 +20,7 @@ export type {
export const RigidBody3D = defineBuiltin<RigidBody3DData>('RigidBody3D', {
bodyType: 2,
+ layer: 0,
gravityScale: 1.0,
linearDamping: 0.05,
angularDamping: 0.05,
@@ -66,6 +67,7 @@ export const CapsuleCollider3D = defineBuiltin<CapsuleCollider3DData>('CapsuleCo
*/
export const MeshCollider3D = defineBuiltin<MeshCollider3DData>('MeshCollider3D', {
mesh: 0,
+ layer: 0,
friction: 0.3,
restitution: 0.0,
enabled: true,
@@ -84,6 +86,7 @@ export const CharacterController3D = defineBuiltin<CharacterController3DData>(
radius: 0.3,
halfHeight: 0.5,
maxSlope: 0.87,
+ layer: 0,
stepHeight: 0.4,
snapDown: 0.5,
mass: 70,
@@ -98,6 +101,7 @@ export const CharacterController3D = defineBuiltin<CharacterController3DData>(
stepHeight: { min: 0, step: 0.05, advanced: true },
snapDown: { min: 0, step: 0.05, advanced: true },
mass: { min: 0, advanced: true },
+ layer: { min: 0, max: 15, step: 1, advanced: true },
isOnFloor: { advanced: true },
floorNormal: { advanced: true },
realVelocity: { advanced: true },
diff --git a/sdk/src/physics3d/Physics3DModule.ts b/sdk/src/physics3d/Physics3DModule.ts
index a111a1b0a..9e7e30a25 100644
--- a/sdk/src/physics3d/Physics3DModule.ts
+++ b/sdk/src/physics3d/Physics3DModule.ts
@@ -18,30 +18,31 @@ export interface Physics3DWasmModule {
_physics3d_isReady(): number;
_physics3d_step(dt: number, collisionSteps: number): void;
_physics3d_optimize(): void;
+ _physics3d_setLayerMask(layer: number, mask: number): void;
_physics3d_addBox(entity: number, hx: number, hy: number, hz: number,
px: number, py: number, pz: number,
qx: number, qy: number, qz: number, qw: number,
motion: number, gravityScale: number, linearDamping: number,
- angularDamping: number, fixedRotation: number,
+ angularDamping: number, fixedRotation: number, layer: number,
friction: number, restitution: number, isSensor: number): number;
_physics3d_addSphere(entity: number, radius: number,
px: number, py: number, pz: number,
qx: number, qy: number, qz: number, qw: number,
motion: number, gravityScale: number, linearDamping: number,
- angularDamping: number, fixedRotation: number,
+ angularDamping: number, fixedRotation: number, layer: number,
friction: number, restitution: number, isSensor: number): number;
_physics3d_addCapsule(entity: number, radius: number, halfHeight: number,
px: number, py: number, pz: number,
qx: number, qy: number, qz: number, qw: number,
motion: number, gravityScale: number, linearDamping: number,
- angularDamping: number, fixedRotation: number,
+ angularDamping: number, fixedRotation: number, layer: 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;
+ layer: number, friction: number, restitution: number): number;
_physics3d_removeBody(bodyId: number): void;
_malloc(bytes: number): number;
@@ -53,7 +54,7 @@ export interface Physics3DWasmModule {
_physics3d_addCharacter(entity: number, radius: number, halfHeight: number,
px: number, py: number, pz: number,
- maxSlope: number, mass: number): number;
+ maxSlope: number, mass: number, layer: number): number;
_physics3d_removeCharacter(characterId: number): void;
_physics3d_moveCharacter(characterId: number, vx: number, vy: number, vz: number,
dt: number, stepUp: number, stepDown: number): void;
diff --git a/sdk/src/physics3d/Physics3DPlugin.ts b/sdk/src/physics3d/Physics3DPlugin.ts
index 68d9c28f4..3537a0578 100644
--- a/sdk/src/physics3d/Physics3DPlugin.ts
+++ b/sdk/src/physics3d/Physics3DPlugin.ts
@@ -60,6 +60,11 @@ export class Physics3DPlugin implements Plugin {
this.module_ = module;
const { gravity, maxBodies } = this.config_;
module._physics3d_init(gravity.x, gravity.y, gravity.z, maxBodies);
+ // Before any body: an ObjectLayer is fixed when a body is created, so a
+ // matrix installed later would not reach what is already in the world.
+ this.config_.layerMasks?.forEach((mask, layer) => {
+ module._physics3d_setLayerMask(layer, mask);
+ });
runtime.module = module;
app.addSystemToSchedule(Schedule.FixedUpdate, defineSystem([], () => {
stepPhysics3D(app, module, runtime.bodies, this.config_,
diff --git a/sdk/src/physics3d/Physics3DSystem.ts b/sdk/src/physics3d/Physics3DSystem.ts
index f88a6ceea..77e5f7b7e 100644
--- a/sdk/src/physics3d/Physics3DSystem.ts
+++ b/sdk/src/physics3d/Physics3DSystem.ts
@@ -29,6 +29,9 @@ import { PHYSICS3D_TRANSFORM_STRIDE, drainPhysics3DEvents } from './Physics3DMod
const MOTION = { Static: 0, Kinematic: 1, Dynamic: 2 } as const;
export interface Physics3DConfig {
+ /** Layer i collides with layer j when bit j of `layerMasks[i]` is set AND bit
+ * i of `layerMasks[j]` is. Absent leaves every layer colliding with all. */
+ layerMasks?: number[];
gravity: { x: number; y: number; z: number };
fixedTimestep: number;
collisionSteps: number;
@@ -72,7 +75,8 @@ function moveCharacters(app: App, module: Physics3DWasmModule, characters: BodyM
const p = t?.worldPosition ?? { x: 0, y: 0, z: 0 };
id = module._physics3d_addCharacter(
entity as number, character.radius / ppu, character.halfHeight / ppu,
- p.x / ppu, p.y / ppu, p.z / ppu, character.maxSlope, character.mass);
+ p.x / ppu, p.y / ppu, p.z / ppu, character.maxSlope, character.mass,
+ character.layer);
if (id === 0) continue;
characters.set(entity, id);
}
@@ -127,7 +131,7 @@ function createBody(app: App, module: Physics3DWasmModule, entity: Entity,
const px = p.x / ppu, py = p.y / ppu, pz = p.z / ppu;
// How the body answers to the world, in the order the module reads it.
const how = [motionOf(body), body.gravityScale, body.linearDamping,
- body.angularDamping, body.fixedRotation ? 1 : 0] as const;
+ body.angularDamping, body.fixedRotation ? 1 : 0, body.layer] as const;
const box = app.world.get(entity, BoxCollider3D) as BoxCollider3DData | undefined;
if (box?.enabled) {
@@ -144,7 +148,7 @@ function createBody(app: App, module: Physics3DWasmModule, entity: Entity,
}
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);
+ return addMeshBody(module, entity, meshCollider, px, py, pz, r, ppu, body.layer);
}
const capsule = app.world.get(entity, CapsuleCollider3D) as CapsuleCollider3DData | undefined;
if (capsule?.enabled) {
@@ -167,7 +171,8 @@ function createBody(app: App, module: Physics3DWasmModule, entity: Entity,
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 {
+ r: { x: number; y: number; z: number; w: number },
+ ppu: number, layer: number): number {
const geometry = getMeshCollision(collider.mesh);
if (!geometry) return 0;
const { positions, indices } = geometry;
@@ -179,7 +184,8 @@ function addMeshBody(module: Physics3DWasmModule, entity: Entity,
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);
+ px, py, pz, r.x, r.y, r.z, r.w, layer,
+ collider.friction, collider.restitution);
} finally {
module._free(vertexPtr);
module._free(indexPtr);
diff --git a/sdk/src/wasm/ptrLayouts.generated.ts b/sdk/src/wasm/ptrLayouts.generated.ts
index fc684068f..09e6d112a 100644
--- a/sdk/src/wasm/ptrLayouts.generated.ts
+++ b/sdk/src/wasm/ptrLayouts.generated.ts
@@ -129,9 +129,10 @@ export const PTR_LAYOUTS: Record<string, PtrLayout> = {
{ name: 'snapDown', type: 'f32', offset: 28 },
{ name: 'mass', type: 'f32', offset: 32 },
{ name: 'enabled', type: 'bool', offset: 36 },
- { name: 'isOnFloor', type: 'bool', offset: 37 },
- { name: 'floorNormal', type: 'vec3', offset: 40 },
- { name: 'realVelocity', type: 'vec3', offset: 52 },
+ { name: 'layer', type: 'u32', offset: 40 },
+ { name: 'isOnFloor', type: 'bool', offset: 44 },
+ { name: 'floorNormal', type: 'vec3', offset: 48 },
+ { name: 'realVelocity', type: 'vec3', offset: 60 },
],
},
CircleCollider: {
@@ -224,7 +225,8 @@ export const PTR_LAYOUTS: Record<string, PtrLayout> = {
{ name: 'mesh', type: 'u32', offset: 0 },
{ name: 'friction', type: 'f32', offset: 4 },
{ name: 'restitution', type: 'f32', offset: 8 },
- { name: 'enabled', type: 'bool', offset: 12 },
+ { name: 'layer', type: 'u32', offset: 12 },
+ { name: 'enabled', type: 'bool', offset: 16 },
],
},
ParticleEmitter: {
@@ -321,7 +323,8 @@ export const PTR_LAYOUTS: Record<string, PtrLayout> = {
{ name: 'linearDamping', type: 'f32', offset: 8 },
{ name: 'angularDamping', type: 'f32', offset: 12 },
{ name: 'fixedRotation', type: 'bool', offset: 16 },
- { name: 'enabled', type: 'bool', offset: 17 },
+ { name: 'layer', type: 'u32', offset: 20 },
+ { name: 'enabled', type: 'bool', offset: 24 },
],
},
SegmentCollider: {
diff --git a/sdk/src/wasm/wasm.generated.ts b/sdk/src/wasm/wasm.generated.ts
index adf7ba53e..8dfacd341 100644
--- a/sdk/src/wasm/wasm.generated.ts
+++ b/sdk/src/wasm/wasm.generated.ts
@@ -305,6 +305,7 @@ export interface CharacterController3D {
snapDown: number;
mass: number;
enabled: boolean;
+ layer: number;
isOnFloor: boolean;
floorNormal: Vec3;
realVelocity: Vec3;
@@ -394,6 +395,7 @@ export interface MeshCollider3D {
mesh: number;
friction: number;
restitution: number;
+ layer: number;
enabled: boolean;
}
@@ -491,6 +493,7 @@ export interface RigidBody3D {
linearDamping: number;
angularDamping: number;
fixedRotation: boolean;
+ layer: number;
enabled: boolean;
}
diff --git a/sdk/tests/physics3d-ecs.test.ts b/sdk/tests/physics3d-ecs.test.ts
index 92763c4f0..e6517f5d2 100644
--- a/sdk/tests/physics3d-ecs.test.ts
+++ b/sdk/tests/physics3d-ecs.test.ts
@@ -81,6 +81,7 @@ function fakeModule(): Physics3DWasmModule & {
_physics3d_moveCharacter: record('moveCharacter'),
_physics3d_setCharacterPosition: record('setCharacterPosition'),
_physics3d_addMeshBody: record('addMeshBody'),
+ _physics3d_setLayerMask: record('setLayerMask'),
// 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; },
@@ -320,6 +321,19 @@ describe('the 3D world and the ECS', () => {
expect(bodies.size).toBe(0);
});
+ it('sends a body\u2019s layer to the world', () => {
+ const e = spawn();
+ world.insert(e, SphereCollider3D);
+ (world.get(e, RigidBody3D) as { layer: number }).layer = 5;
+
+ stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG);
+
+ // entity, radius, position(3), rotation(4), motion, gravity, damping(2),
+ // fixedRotation, then LAYER — a knob nothing forwards does nothing.
+ const [call] = called('addSphere');
+ expect(call!.args[14]).toBe(5);
+ });
+
it('leaves a disabled body out of the world', () => {
const e = spawn();
world.insert(e, BoxCollider3D);
diff --git a/sdk/tests/physics3d-smoke.mjs b/sdk/tests/physics3d-smoke.mjs
index 04d6ba7b9..61589391c 100644
--- a/sdk/tests/physics3d-smoke.mjs
+++ b/sdk/tests/physics3d-smoke.mjs
@@ -20,9 +20,9 @@ const near = (a, b, tol = 1e-3) => Math.abs(a - b) <= tol;
const STATIC = 0, KINEMATIC = 1, DYNAMIC = 2;
const IDENTITY = [0, 0, 0, 1];
-// motion, gravityScale, linearDamping, angularDamping, fixedRotation — what a body
-// is beyond its shape.
-const FREE = (motion) => [motion, 1, 0, 0, 0];
+// motion, gravityScale, linearDamping, angularDamping, fixedRotation, layer —
+// what a body is beyond its shape.
+const FREE = (motion, layer = 0) => [motion, 1, 0, 0, 0, layer];
/** The position of `entity` in the step's transform readback, or null. */
function bodyPos(entity) {
@@ -127,7 +127,7 @@ check('and on its own radius', side && side.entity === CAP && near(side.fraction
// drops 4.9m in the same second.
const FLOAT = 5;
const floatId = m._physics3d_addSphere(FLOAT, 0.5, -3, 5, 0, ...IDENTITY,
- DYNAMIC, 0, 0, 0, 0, 0.5, 0, 0);
+ DYNAMIC, 0, 0, 0, 0, 0, 0.5, 0, 0);
step(60);
check('gravityScale 0 leaves a body where it was', near(bodyState(floatId).y, 5, 0.01),
`y=${bodyState(floatId).y.toFixed(4)} want 5`);
@@ -137,7 +137,7 @@ check('gravityScale 0 leaves a body where it was', near(bodyState(floatId).y, 5,
// flat, so the tilt it KEEPS is what says the solver may not turn it.
const UPRIGHT = 6;
const uprightId = m._physics3d_addCapsule(UPRIGHT, 0.3, 0.5, -6, 3, 0,
- 0.3, 0, 0, 0.954, DYNAMIC, 1, 0, 0, 1, 0.5, 0, 0);
+ 0.3, 0, 0, 0.954, DYNAMIC, 1, 0, 0, 1, 0, 0.5, 0, 0);
step(180);
const uprightBase = m._physics3d_getBodyState(uprightId) ? m._physics3d_queryResult() >> 2 : 0;
const qx = m.HEAPF32[uprightBase + 3];
@@ -157,7 +157,7 @@ function moveCharacter(id, vx, vy, vz, steps = 1, stepUp = 0.4, stepDown = 0.5)
// Dropped from 3m onto the floor: a capsule of radius 0.3 + half-height 0.5
// stands with its centre 0.8 up, and reports the ground it is on.
-const hero = m._physics3d_addCharacter(9, 0.3, 0.5, -20, 3, 0, 0.87, 70);
+const hero = m._physics3d_addCharacter(9, 0.3, 0.5, -20, 3, 0, 0.87, 70, 0);
check('a character is handed back', hero !== 0, `id=${hero}`);
const airborne = moveCharacter(hero, 0, 0, 0, 1);
check('and starts in the air', airborne.ground === IN_AIR, `state=${airborne.ground}`);
@@ -293,7 +293,7 @@ const rampVerts = alloc(new Float32Array([
// 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);
+ 30, 3, 0, ...IDENTITY, 0, 0.5, 0);
m._free(rampVerts);
m._free(rampIndices);
check('imported geometry becomes a body', rampId !== 0, `id=${rampId}`);
@@ -322,13 +322,45 @@ check('and a body rests on its triangles', crate && crate.y > 3.4,
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);
+ m._physics3d_addMeshBody(32, badVerts, 3, badIndices, 6, 0, 0, 0, ...IDENTITY, 0, 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._physics3d_addMeshBody(32, badVerts, 3, badIndices, 5, 0, 0, 0, ...IDENTITY, 0, 0.5, 0) === 0);
m._free(badVerts);
m._free(badIndices);
-// ── 9) A removed body is gone from both the sweep and the getter ────────────
+// ── 9) Layers decide who meets whom ────────────────────────────────────────
+// Layer 1 is the world, 2 is bullets, 3 is the team firing them: bullets pass
+// through their own team and stop on the world.
+m._physics3d_setLayerMask(2, ~(1 << 3) >>> 0); // bullets ignore their team
+m._physics3d_setLayerMask(3, ~(1 << 2) >>> 0); // and the team ignores bullets
+
+const TEAMMATE = 40, BULLET = 41, WALL = 42;
+m._physics3d_addBox(WALL, 5, 0.5, 5, 60, -0.5, 0, ...IDENTITY, ...FREE(STATIC, 1), 0.5, 0, 0);
+// Wide enough to cover both drop points: the second bullet has to fall past the
+// teammate too, and landing on the FIRST bullet would prove nothing about layers.
+m._physics3d_addBox(TEAMMATE, 5, 1, 5, 60, 1, 0, ...IDENTITY, ...FREE(STATIC, 3), 0.5, 0, 0);
+const bulletId = m._physics3d_addSphere(BULLET, 0.2, 60, 6, 0, ...IDENTITY,
+ ...FREE(DYNAMIC, 2), 0.5, 0, 0);
+m._physics3d_optimize();
+step(240);
+const bullet = bodyState(bulletId);
+// It fell past the teammate (whose top is at 2) and landed on the world at 0.2.
+check('a body passes through a layer it ignores', bullet && bullet.y < 1.5,
+ `y=${bullet?.y?.toFixed(4)} — it stopped on the teammate it should ignore`);
+check('and still lands on one it does not', bullet && near(bullet.y, 0.2, 0.1),
+ `y=${bullet?.y?.toFixed(4)} want 0.2 (resting on the world)`);
+
+// One side saying no is enough: the team never stopped naming bullets, but
+// bullets stopped naming the team, and they still pass.
+m._physics3d_setLayerMask(3, 0xFFFFFFFF);
+const SECOND = 43;
+const secondId = m._physics3d_addSphere(SECOND, 0.2, 63, 6, 0, ...IDENTITY,
+ ...FREE(DYNAMIC, 2), 0.5, 0, 0);
+step(240);
+check('one side refusing is enough', near(bodyState(secondId).y, 0.2, 0.1),
+ `y=${bodyState(secondId)?.y?.toFixed(4)} want 0.2`);
+
+// ── 10) 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 740e20457..934d3bef3 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 1caddb3e87fa4b7c
+ * @schema_hash 82e78d440d228f27
*/
-#define ES_EDITOR_API_SCHEMA_HASH "1caddb3e87fa4b7c"
+#define ES_EDITOR_API_SCHEMA_HASH "82e78d440d228f27"
#include <emscripten/bind.h>
#include <string>
@@ -207,6 +207,7 @@ std::string editor_getComponentSchema(const std::string& name) {
{"key":"snapDown","type":"float","group":"CharacterController3D"},
{"key":"mass","type":"float","group":"CharacterController3D"},
{"key":"enabled","type":"bool","group":"CharacterController3D"},
+ {"key":"layer","type":"int","group":"CharacterController3D"},
{"key":"isOnFloor","type":"bool","group":"CharacterController3D"},
{"key":"floorNormal.x","type":"float","group":"CharacterController3D"},
{"key":"floorNormal.y","type":"float","group":"CharacterController3D"},
@@ -316,6 +317,7 @@ std::string editor_getComponentSchema(const std::string& name) {
{"key":"mesh","type":"asset","group":"MeshCollider3D"},
{"key":"friction","type":"float","group":"MeshCollider3D"},
{"key":"restitution","type":"float","group":"MeshCollider3D"},
+ {"key":"layer","type":"int","group":"MeshCollider3D"},
{"key":"enabled","type":"bool","group":"MeshCollider3D"}
])JSON";
} else if (name == "MeshSkin") {
@@ -422,6 +424,7 @@ std::string editor_getComponentSchema(const std::string& name) {
{"key":"linearDamping","type":"float","group":"RigidBody3D"},
{"key":"angularDamping","type":"float","group":"RigidBody3D"},
{"key":"fixedRotation","type":"bool","group":"RigidBody3D"},
+ {"key":"layer","type":"int","group":"RigidBody3D"},
{"key":"enabled","type":"bool","group":"RigidBody3D"}
])JSON";
} else if (name == "SegmentCollider") {
@@ -1873,6 +1876,12 @@ bool editor_setInt(Registry& reg, u32 e, const std::string& comp, const std::str
else if (field == "maskBits") { c.maskBits = static_cast<u32>(value); }
else { return false; }
return true;
+ } else if (comp == "CharacterController3D") {
+ if (!reg.has<esengine::ecs::CharacterController3D>(entity)) return false;
+ auto& c = reg.get<esengine::ecs::CharacterController3D>(entity);
+ if (field == "layer") { c.layer = static_cast<u32>(value); }
+ else { return false; }
+ return true;
} else if (comp == "CircleCollider") {
if (!reg.has<esengine::ecs::CircleCollider>(entity)) return false;
auto& c = reg.get<esengine::ecs::CircleCollider>(entity);
@@ -1918,6 +1927,7 @@ bool editor_setInt(Registry& reg, u32 e, const std::string& comp, const std::str
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 if (field == "layer") { c.layer = static_cast<u32>(value); }
else { return false; }
return true;
} else if (comp == "Parent") {
@@ -1961,6 +1971,7 @@ bool editor_setInt(Registry& reg, u32 e, const std::string& comp, const std::str
if (!reg.has<esengine::ecs::RigidBody3D>(entity)) return false;
auto& c = reg.get<esengine::ecs::RigidBody3D>(entity);
if (field == "bodyType") { c.bodyType = static_cast<BodyType>(value); }
+ else if (field == "layer") { c.layer = static_cast<u32>(value); }
else { return false; }
return true;
} else if (comp == "SegmentCollider") {
@@ -2082,6 +2093,10 @@ i32 editor_getInt(Registry& reg, u32 e, const std::string& comp, const std::stri
const auto& c = reg.get<esengine::ecs::CapsuleCollider>(entity);
if (field == "categoryBits") { return static_cast<i32>(c.categoryBits); }
else if (field == "maskBits") { return static_cast<i32>(c.maskBits); }
+ } else if (comp == "CharacterController3D") {
+ if (!reg.has<esengine::ecs::CharacterController3D>(entity)) return 0;
+ const auto& c = reg.get<esengine::ecs::CharacterController3D>(entity);
+ if (field == "layer") { return static_cast<i32>(c.layer); }
} else if (comp == "CircleCollider") {
if (!reg.has<esengine::ecs::CircleCollider>(entity)) return 0;
const auto& c = reg.get<esengine::ecs::CircleCollider>(entity);
@@ -2117,6 +2132,7 @@ i32 editor_getInt(Registry& reg, u32 e, const std::string& comp, const std::stri
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 (field == "layer") { return static_cast<i32>(c.layer); }
} else if (comp == "Parent") {
if (!reg.has<esengine::ecs::Parent>(entity)) return 0;
const auto& c = reg.get<esengine::ecs::Parent>(entity);
@@ -2152,6 +2168,7 @@ i32 editor_getInt(Registry& reg, u32 e, const std::string& comp, const std::stri
if (!reg.has<esengine::ecs::RigidBody3D>(entity)) return 0;
const auto& c = reg.get<esengine::ecs::RigidBody3D>(entity);
if (field == "bodyType") { return static_cast<i32>(c.bodyType); }
+ else if (field == "layer") { return static_cast<i32>(c.layer); }
} else if (comp == "SegmentCollider") {
if (!reg.has<esengine::ecs::SegmentCollider>(entity)) return 0;
const auto& c = reg.get<esengine::ecs::SegmentCollider>(entity);
diff --git a/src/esengine/bindings/WebBindings.generated.cpp b/src/esengine/bindings/WebBindings.generated.cpp
index 7dc97081b..1bdab0de1 100644
--- a/src/esengine/bindings/WebBindings.generated.cpp
+++ b/src/esengine/bindings/WebBindings.generated.cpp
@@ -549,6 +549,7 @@ struct MeshCollider3DJS {
u32 mesh;
f32 friction;
f32 restitution;
+ u32 layer;
bool enabled;
};
@@ -556,6 +557,7 @@ void meshcollider3dApplyJS(esengine::ecs::MeshCollider3D& c, const MeshCollider3
c.mesh = resource::MeshHandle(js.mesh);
c.friction = js.friction;
c.restitution = js.restitution;
+ c.layer = js.layer;
c.enabled = js.enabled;
}
@@ -570,6 +572,7 @@ MeshCollider3DJS meshcollider3dToJS(const esengine::ecs::MeshCollider3D& c) {
js.mesh = c.mesh.id();
js.friction = c.friction;
js.restitution = c.restitution;
+ js.layer = c.layer;
js.enabled = c.enabled;
return js;
}
@@ -841,6 +844,7 @@ struct RigidBody3DJS {
f32 linearDamping;
f32 angularDamping;
bool fixedRotation;
+ u32 layer;
bool enabled;
};
@@ -850,6 +854,7 @@ void rigidbody3dApplyJS(esengine::ecs::RigidBody3D& c, const RigidBody3DJS& js)
c.linearDamping = js.linearDamping;
c.angularDamping = js.angularDamping;
c.fixedRotation = js.fixedRotation;
+ c.layer = js.layer;
c.enabled = js.enabled;
}
@@ -866,6 +871,7 @@ RigidBody3DJS rigidbody3dToJS(const esengine::ecs::RigidBody3D& c) {
js.linearDamping = c.linearDamping;
js.angularDamping = c.angularDamping;
js.fixedRotation = c.fixedRotation;
+ js.layer = c.layer;
js.enabled = c.enabled;
return js;
}
@@ -1330,6 +1336,7 @@ EMSCRIPTEN_BINDINGS(esengine_components) {
.field("snapDown", &esengine::ecs::CharacterController3D::snapDown)
.field("mass", &esengine::ecs::CharacterController3D::mass)
.field("enabled", &esengine::ecs::CharacterController3D::enabled)
+ .field("layer", &esengine::ecs::CharacterController3D::layer)
.field("isOnFloor", &esengine::ecs::CharacterController3D::isOnFloor)
.field("floorNormal", &esengine::ecs::CharacterController3D::floorNormal)
.field("realVelocity", &esengine::ecs::CharacterController3D::realVelocity);
@@ -1411,6 +1418,7 @@ EMSCRIPTEN_BINDINGS(esengine_components) {
.field("mesh", &MeshCollider3DJS::mesh)
.field("friction", &MeshCollider3DJS::friction)
.field("restitution", &MeshCollider3DJS::restitution)
+ .field("layer", &MeshCollider3DJS::layer)
.field("enabled", &MeshCollider3DJS::enabled);
value_object<MeshSkinJS>("MeshSkin")
@@ -1502,6 +1510,7 @@ EMSCRIPTEN_BINDINGS(esengine_components) {
.field("linearDamping", &RigidBody3DJS::linearDamping)
.field("angularDamping", &RigidBody3DJS::angularDamping)
.field("fixedRotation", &RigidBody3DJS::fixedRotation)
+ .field("layer", &RigidBody3DJS::layer)
.field("enabled", &RigidBody3DJS::enabled);
value_object<esengine::ecs::SegmentCollider>("SegmentCollider")
@@ -2656,9 +2665,10 @@ static_assert(offsetof(esengine::ecs::CharacterController3D, stepHeight) == 24,
static_assert(offsetof(esengine::ecs::CharacterController3D, snapDown) == 28, "ABI offset drift: esengine::ecs::CharacterController3D.snapDown (EHT expected 28)");
static_assert(offsetof(esengine::ecs::CharacterController3D, mass) == 32, "ABI offset drift: esengine::ecs::CharacterController3D.mass (EHT expected 32)");
static_assert(offsetof(esengine::ecs::CharacterController3D, enabled) == 36, "ABI offset drift: esengine::ecs::CharacterController3D.enabled (EHT expected 36)");
-static_assert(offsetof(esengine::ecs::CharacterController3D, isOnFloor) == 37, "ABI offset drift: esengine::ecs::CharacterController3D.isOnFloor (EHT expected 37)");
-static_assert(offsetof(esengine::ecs::CharacterController3D, floorNormal) == 40, "ABI offset drift: esengine::ecs::CharacterController3D.floorNormal (EHT expected 40)");
-static_assert(offsetof(esengine::ecs::CharacterController3D, realVelocity) == 52, "ABI offset drift: esengine::ecs::CharacterController3D.realVelocity (EHT expected 52)");
+static_assert(offsetof(esengine::ecs::CharacterController3D, layer) == 40, "ABI offset drift: esengine::ecs::CharacterController3D.layer (EHT expected 40)");
+static_assert(offsetof(esengine::ecs::CharacterController3D, isOnFloor) == 44, "ABI offset drift: esengine::ecs::CharacterController3D.isOnFloor (EHT expected 44)");
+static_assert(offsetof(esengine::ecs::CharacterController3D, floorNormal) == 48, "ABI offset drift: esengine::ecs::CharacterController3D.floorNormal (EHT expected 48)");
+static_assert(offsetof(esengine::ecs::CharacterController3D, realVelocity) == 60, "ABI offset drift: esengine::ecs::CharacterController3D.realVelocity (EHT expected 60)");
static_assert(offsetof(esengine::ecs::CircleCollider, radius) == 0, "ABI offset drift: esengine::ecs::CircleCollider.radius (EHT expected 0)");
static_assert(offsetof(esengine::ecs::CircleCollider, offset) == 4, "ABI offset drift: esengine::ecs::CircleCollider.offset (EHT expected 4)");
static_assert(offsetof(esengine::ecs::CircleCollider, density) == 12, "ABI offset drift: esengine::ecs::CircleCollider.density (EHT expected 12)");
@@ -2716,7 +2726,8 @@ static_assert(offsetof(esengine::ecs::Mesh2D, mesh) == 48, "ABI offset drift: es
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::MeshCollider3D, layer) == 12, "ABI offset drift: esengine::ecs::MeshCollider3D.layer (EHT expected 12)");
+static_assert(offsetof(esengine::ecs::MeshCollider3D, enabled) == 16, "ABI offset drift: esengine::ecs::MeshCollider3D.enabled (EHT expected 16)");
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)");
@@ -2793,7 +2804,8 @@ static_assert(offsetof(esengine::ecs::RigidBody3D, gravityScale) == 4, "ABI offs
static_assert(offsetof(esengine::ecs::RigidBody3D, linearDamping) == 8, "ABI offset drift: esengine::ecs::RigidBody3D.linearDamping (EHT expected 8)");
static_assert(offsetof(esengine::ecs::RigidBody3D, angularDamping) == 12, "ABI offset drift: esengine::ecs::RigidBody3D.angularDamping (EHT expected 12)");
static_assert(offsetof(esengine::ecs::RigidBody3D, fixedRotation) == 16, "ABI offset drift: esengine::ecs::RigidBody3D.fixedRotation (EHT expected 16)");
-static_assert(offsetof(esengine::ecs::RigidBody3D, enabled) == 17, "ABI offset drift: esengine::ecs::RigidBody3D.enabled (EHT expected 17)");
+static_assert(offsetof(esengine::ecs::RigidBody3D, layer) == 20, "ABI offset drift: esengine::ecs::RigidBody3D.layer (EHT expected 20)");
+static_assert(offsetof(esengine::ecs::RigidBody3D, enabled) == 24, "ABI offset drift: esengine::ecs::RigidBody3D.enabled (EHT expected 24)");
static_assert(offsetof(esengine::ecs::SegmentCollider, point1) == 0, "ABI offset drift: esengine::ecs::SegmentCollider.point1 (EHT expected 0)");
static_assert(offsetof(esengine::ecs::SegmentCollider, point2) == 8, "ABI offset drift: esengine::ecs::SegmentCollider.point2 (EHT expected 8)");
static_assert(offsetof(esengine::ecs::SegmentCollider, density) == 16, "ABI offset drift: esengine::ecs::SegmentCollider.density (EHT expected 16)");
@@ -2931,7 +2943,7 @@ static_assert(offsetof(esengine::ecs::Velocity, angular) == 12, "ABI offset drif
// ABI Hash -- runtime handshake against the SDK bundle
// =============================================================================
-static const char* kEsAbiLayoutHash = "f3c3c0443ccbd99d";
+static const char* kEsAbiLayoutHash = "efd9284ec11052f6";
std::string esengineGetAbiLayoutHash() {
return std::string(kEsAbiLayoutHash);
diff --git a/src/esengine/bindings/modules/physics3d/Physics3DContext.hpp b/src/esengine/bindings/modules/physics3d/Physics3DContext.hpp
index acbc50469..5beeedc55 100644
--- a/src/esengine/bindings/modules/physics3d/Physics3DContext.hpp
+++ b/src/esengine/bindings/modules/physics3d/Physics3DContext.hpp
@@ -42,9 +42,17 @@ namespace JPH { class CharacterVirtual; }
namespace esengine::physics3d {
namespace Layers {
-static constexpr JPH::ObjectLayer STATIC = 0;
-static constexpr JPH::ObjectLayer MOVING = 1;
-static constexpr JPH::ObjectLayer COUNT = 2;
+/// How many collision layers a project can name. Sixteen, like the 2D world's
+/// mask bits, so a project describes its layers once for both.
+static constexpr JPH::uint COUNT = 16;
+/// An ObjectLayer packs the layer index with whether the body moves: Jolt asks
+/// which broad-phase tree a layer belongs to, and a bare index cannot say.
+static constexpr JPH::ObjectLayer of(JPH::uint layer, bool moving) {
+ return static_cast<JPH::ObjectLayer>((layer << 1) | (moving ? 1u : 0u));
+}
+static constexpr JPH::uint indexOf(JPH::ObjectLayer layer) { return layer >> 1; }
+static constexpr bool isMoving(JPH::ObjectLayer layer) { return (layer & 1u) != 0; }
+static constexpr JPH::ObjectLayer OBJECT_LAYER_COUNT = COUNT * 2;
} // namespace Layers
namespace BroadPhase {
@@ -53,37 +61,48 @@ static constexpr JPH::BroadPhaseLayer MOVING(1);
static constexpr JPH::uint COUNT(2);
} // namespace BroadPhase
-/// Static bodies never test against each other; everything else tests everything.
+/// Per-layer masks: bit i of `masks[l]` means layer l wants to hear from layer i.
+/// Both sides must agree, so one of them saying no is enough — the same rule the
+/// 2D world's category/mask pair follows.
+struct LayerMatrix {
+ JPH::uint32 masks[Layers::COUNT];
+ LayerMatrix() { for (JPH::uint32& m : masks) m = 0xFFFFFFFFu; }
+ bool collide(JPH::uint a, JPH::uint b) const {
+ if (a >= Layers::COUNT || b >= Layers::COUNT) return false;
+ return (masks[a] & (1u << b)) != 0 && (masks[b] & (1u << a)) != 0;
+ }
+};
+
+LayerMatrix& layerMatrix();
+
+/// Two static bodies never test against each other whatever their layers say —
+/// neither can move, so a contact between them can never do anything.
class ObjectLayerPairFilterImpl final : public JPH::ObjectLayerPairFilter {
public:
bool ShouldCollide(JPH::ObjectLayer a, JPH::ObjectLayer b) const override {
- return a == Layers::STATIC ? b == Layers::MOVING : true;
+ if (!Layers::isMoving(a) && !Layers::isMoving(b)) return false;
+ return layerMatrix().collide(Layers::indexOf(a), Layers::indexOf(b));
}
};
class BroadPhaseLayerInterfaceImpl final : public JPH::BroadPhaseLayerInterface {
public:
- BroadPhaseLayerInterfaceImpl() {
- objectToBroadPhase_[Layers::STATIC] = BroadPhase::STATIC;
- objectToBroadPhase_[Layers::MOVING] = BroadPhase::MOVING;
- }
JPH::uint GetNumBroadPhaseLayers() const override { return BroadPhase::COUNT; }
JPH::BroadPhaseLayer GetBroadPhaseLayer(JPH::ObjectLayer layer) const override {
- return objectToBroadPhase_[layer];
+ return Layers::isMoving(layer) ? BroadPhase::MOVING : BroadPhase::STATIC;
}
#if defined(JPH_EXTERNAL_PROFILE) || defined(JPH_PROFILE_ENABLED)
const char* GetBroadPhaseLayerName(JPH::BroadPhaseLayer layer) const override {
return layer == BroadPhase::STATIC ? "static" : "moving";
}
#endif
-private:
- JPH::BroadPhaseLayer objectToBroadPhase_[Layers::COUNT];
};
class ObjectVsBroadPhaseLayerFilterImpl final : public JPH::ObjectVsBroadPhaseLayerFilter {
public:
bool ShouldCollide(JPH::ObjectLayer a, JPH::BroadPhaseLayer b) const override {
- return a == Layers::STATIC ? b == BroadPhase::MOVING : true;
+ // A static body only ever needs the moving tree; a moving one needs both.
+ return Layers::isMoving(a) || b == BroadPhase::MOVING;
}
};
@@ -122,6 +141,8 @@ struct Context {
/// rather than solved in it, which is what lets it climb stairs and stay
/// glued to a slope without inheriting momentum from whatever it stands on.
std::unordered_map<uint32_t, std::unique_ptr<JPH::CharacterVirtual>> characters;
+ /// A character is not a body, so its layer is not stored in one.
+ std::unordered_map<uint32_t, uint32_t> characterLayers;
uint32_t nextCharacterId = 1;
bool isValid() const { return system != nullptr; }
diff --git a/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp b/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp
index 740e59b28..7eabac9e3 100644
--- a/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp
+++ b/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp
@@ -38,6 +38,10 @@ Context& ctx() {
static Context instance;
return instance;
}
+LayerMatrix& layerMatrix() {
+ static LayerMatrix instance;
+ return instance;
+}
} // namespace esengine::physics3d
namespace {
@@ -61,8 +65,8 @@ EMotionType motionTypeOf(int value) {
}
}
-ObjectLayer layerOf(EMotionType motion) {
- return motion == EMotionType::Static ? Layers::STATIC : Layers::MOVING;
+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
@@ -74,6 +78,7 @@ struct BodyMotion {
float linearDamping = 0.0f;
float angularDamping = 0.0f;
int fixedRotation = 0;
+ uint32_t layer = 0;
};
/// The entity a body speaks for, or 0 when nothing claims it.
@@ -148,7 +153,7 @@ uint32_t addBody(uint32_t entity, const Ref<Shape>& shape, float px, float py, f
if (!g().isValid()) return 0;
const EMotionType motionType = motionTypeOf(how.motion);
BodyCreationSettings settings(shape, RVec3(px, py, pz), Quat(qx, qy, qz, qw).Normalized(),
- motionType, layerOf(motionType));
+ motionType, layerOf(motionType, how.layer));
settings.mFriction = friction;
settings.mRestitution = restitution;
settings.mIsSensor = isSensor != 0;
@@ -222,6 +227,19 @@ void physics3d_shutdown() {
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;
+ }
+}
+
/// Advance the world, then refill the transform buffer with every active body.
EMSCRIPTEN_KEEPALIVE
void physics3d_step(float dt, int collisionSteps) {
@@ -271,10 +289,10 @@ 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,
+ float angularDamping, int fixedRotation, uint32_t layer,
float friction, float restitution, int isSensor) {
return addBody(entity, new BoxShape(Vec3(hx, hy, hz)), px, py, pz, qx, qy, qz, qw,
- {motion, gravityScale, linearDamping, angularDamping, fixedRotation},
+ {motion, gravityScale, linearDamping, angularDamping, fixedRotation, layer},
friction, restitution, isSensor);
}
@@ -283,10 +301,10 @@ 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,
+ float angularDamping, int fixedRotation, uint32_t layer,
float friction, float restitution, int isSensor) {
return addBody(entity, new SphereShape(radius), px, py, pz, qx, qy, qz, qw,
- {motion, gravityScale, linearDamping, angularDamping, fixedRotation},
+ {motion, gravityScale, linearDamping, angularDamping, fixedRotation, layer},
friction, restitution, isSensor);
}
@@ -297,10 +315,10 @@ 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,
+ float angularDamping, int fixedRotation, uint32_t layer,
float friction, float restitution, int isSensor) {
return addBody(entity, new CapsuleShape(halfHeight, radius), px, py, pz, qx, qy, qz, qw,
- {motion, gravityScale, linearDamping, angularDamping, fixedRotation},
+ {motion, gravityScale, linearDamping, angularDamping, fixedRotation, layer},
friction, restitution, isSensor);
}
@@ -318,7 +336,7 @@ uint32_t physics3d_addMeshBody(uint32_t entity, uintptr_t vertexPtr, uint32_t ve
uintptr_t indexPtr, uint32_t indexCount,
float px, float py, float pz,
float qx, float qy, float qz, float qw,
- float friction, float restitution) {
+ 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);
@@ -344,7 +362,7 @@ uint32_t physics3d_addMeshBody(uint32_t entity, uintptr_t vertexPtr, uint32_t ve
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);
+ {0, 1.0f, 0.0f, 0.0f, 0, layer}, friction, restitution, 0);
}
EMSCRIPTEN_KEEPALIVE
@@ -402,7 +420,8 @@ int physics3d_getBodyState(uint32_t bodyId) {
*/
EMSCRIPTEN_KEEPALIVE
uint32_t physics3d_addCharacter(uint32_t entity, float radius, float halfHeight,
- float px, float py, float pz, float maxSlope, float mass) {
+ float px, float py, float pz, float maxSlope, float mass,
+ uint32_t layer) {
if (!g().isValid()) return 0;
Ref<CharacterVirtualSettings> settings = new CharacterVirtualSettings();
settings->mShape = new CapsuleShape(halfHeight, radius);
@@ -414,6 +433,7 @@ uint32_t physics3d_addCharacter(uint32_t entity, float radius, float halfHeight,
auto character = std::make_unique<CharacterVirtual>(
settings, RVec3(px, py, pz), Quat::sIdentity(), g().system);
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;
@@ -422,6 +442,7 @@ uint32_t physics3d_addCharacter(uint32_t entity, float radius, float halfHeight,
EMSCRIPTEN_KEEPALIVE
void physics3d_removeCharacter(uint32_t characterId) {
g().characters.erase(characterId);
+ g().characterLayers.erase(characterId);
g().entityOf.erase(characterId | CHARACTER_ID_TAG);
}
@@ -455,9 +476,11 @@ void physics3d_moveCharacter(uint32_t characterId, float vx, float vy, float vz,
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(Layers::MOVING),
- g().system->GetDefaultLayerFilter(Layers::MOVING),
+ g().system->GetDefaultBroadPhaseLayerFilter(objectLayer),
+ g().system->GetDefaultLayerFilter(objectLayer),
{}, {}, *g().temp);
const RVec3 position = character.GetPosition();
diff --git a/src/esengine/ecs/components/RigidBody3D.hpp b/src/esengine/ecs/components/RigidBody3D.hpp
index 06b1f5d0e..5a1bf58b0 100644
--- a/src/esengine/ecs/components/RigidBody3D.hpp
+++ b/src/esengine/ecs/components/RigidBody3D.hpp
@@ -53,6 +53,11 @@ struct RigidBody3D {
ES_PROPERTY()
bool fixedRotation{false};
+ /** @brief Which collision layer this body is in (0..15). ONE layer, unlike the
+ * 2D world's category bits: Jolt classifies a body by a single id. */
+ ES_PROPERTY(min=0, max=15, advanced)
+ u32 layer{0};
+
/** @brief Disabled bodies are left out of the world entirely. */
ES_PROPERTY()
bool enabled{true};
@@ -144,6 +149,10 @@ struct MeshCollider3D {
ES_PROPERTY(min=0, max=1)
f32 restitution{0.0f};
+ /** @brief Which collision layer the geometry is in (0..15). */
+ ES_PROPERTY(min=0, max=15, advanced)
+ u32 layer{0};
+
ES_PROPERTY()
bool enabled{true};
};
@@ -188,6 +197,10 @@ struct CharacterController3D {
ES_PROPERTY()
bool enabled{true};
+ /** @brief Which collision layer it is in (0..15). */
+ ES_PROPERTY(min=0, max=15, advanced)
+ u32 layer{0};
+
/** @brief Output: standing on ground it can walk on. */
ES_PROPERTY(advanced)
bool isOnFloor{false};