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): a 3D character stands, walks and climbs a step

esengineeecf89bf6c66
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5dc9bcd3b..eec0ffb71 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,19 @@ published separately; it ships inside the editor.
### Added
+- **A 3D character stands, walks and climbs a step.** `CharacterController3D`
+ is swept against the world rather than solved in it, which is what lets it
+ climb a 20cm step and stay glued to a slope without inheriting the momentum of
+ whatever it stands on. Set `velocity` from gameplay each step and read
+ `isOnFloor`, `floorNormal` and `realVelocity` back — the same shape the 2D
+ character controller has.
+
+ The vertical component is carried for you: a Jolt character does not fall on
+ its own (its gravity parameter only pushes down on what it stands on, and the
+ vertical speed belongs to the caller), so the module integrates gravity rather
+ than leaving every caller to rediscover that `velocity.y = 0` otherwise means
+ "hang in the air".
+
- **A 3D physics world, beside the 2D one rather than over it.** Jolt Physics
ships as a second side module, so a project that never asks for a 3D world
never pays the 1.2MB it weighs — and a 2D scene keeps the solver, the units
diff --git a/desktop/src/engine/componentDocs.generated.ts b/desktop/src/engine/componentDocs.generated.ts
index 2344e494e..6ad910a63 100644
--- a/desktop/src/engine/componentDocs.generated.ts
+++ b/desktop/src/engine/componentDocs.generated.ts
@@ -19,6 +19,7 @@ export const COMPONENT_DOC_PATHS: Readonly<Record<string, string>> = {
CapsuleCollider3D: 'reference/components/physics/#capsulecollider3d',
ChainCollider: 'reference/components/physics/#chaincollider',
CharacterController: 'reference/components/physics/#charactercontroller',
+ CharacterController3D: 'reference/components/physics/#charactercontroller3d',
Children: 'reference/components/core/#children',
CircleCollider: 'reference/components/physics/#circlecollider',
Disabled: 'reference/components/core/#disabled',
diff --git a/docs/astro/src/content/docs/gameplay/physics-3d.mdx b/docs/astro/src/content/docs/gameplay/physics-3d.mdx
index 389f61096..74048c501 100644
--- a/docs/astro/src/content/docs/gameplay/physics-3d.mdx
+++ b/docs/astro/src/content/docs/gameplay/physics-3d.mdx
@@ -48,6 +48,33 @@ cmds.spawn()
is not optional — it is why a capsule 60 units wide falls the way a person does.
</Aside>
+## Characters
+
+A `CharacterController3D` replaces a `RigidBody3D` rather than accompanying one: a
+body the solver pushes and a character that sweeps are two answers to where an
+entity is. Set `velocity` from gameplay each step and read the result back.
+
+```typescript
+const c = world.get(player, CharacterController3D);
+c.velocity.x = input.axis('move') * 200;
+if (input.justPressed('jump') && c.isOnFloor) c.velocity.y = 500;
+```
+
+| Field | What it does |
+|---|---|
+| `velocity` | Desired velocity in world units/second. A positive `y` is a jump. |
+| `stepHeight` | Tallest step it climbs instead of stopping at. `0` climbs nothing. |
+| `snapDown` | How far it reaches down to stay on the floor over a crest. `0` is off. |
+| `maxSlope` | Steepest ground it can stand on; beyond this it slides. |
+| `isOnFloor` / `floorNormal` / `realVelocity` | Outputs, read after the step. |
+
+<Aside>
+ The vertical component is carried for you: `velocity.y = 0` means "walk", not
+ "hang in the air". A character does not fall on its own in Jolt — the vertical
+ speed belongs to the caller — so the module integrates gravity rather than
+ leaving every caller to rediscover it.
+</Aside>
+
## Which world a scene is in
Nothing stops an entity carrying both sets, but nothing merges them either: the two
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 927343cc0..67e26e1b2 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,31 @@ cmds.spawn()
不是可选项——它正是一个 60 单位宽的胶囊会像人一样倒下的原因。
</Aside>
+## 角色
+
+`CharacterController3D` **取代** `RigidBody3D` 而不是与它并存:被求解器推的刚体
+和自己扫掠的角色,是「这个实体在哪」的两个答案。每步从游戏逻辑设 `velocity`,再把结果读回来。
+
+```typescript
+const c = world.get(player, CharacterController3D);
+c.velocity.x = input.axis('move') * 200;
+if (input.justPressed('jump') && c.isOnFloor) c.velocity.y = 500;
+```
+
+| 字段 | 作用 |
+|---|---|
+| `velocity` | 期望速度,世界单位/秒。`y` 为正就是跳。 |
+| `stepHeight` | 能迈上去而不是被挡住的最高台阶。`0` 就什么都迈不上。 |
+| `snapDown` | 过坡顶时向下够多远以贴住地面。`0` 是关掉。 |
+| `maxSlope` | 能站住的最陡地面;比这更陡就会滑下去。 |
+| `isOnFloor` / `floorNormal` / `realVelocity` | 输出,步进之后读。 |
+
+<Aside>
+ 垂直分量由引擎替你维护:`velocity.y = 0` 的意思是「走」,不是「悬在空中」。
+ 在 Jolt 里角色**不会自己下落**——垂直速度属于调用者——所以这一层替你积分重力,
+ 而不是让每个调用者各自重新发现这件事。
+</Aside>
+
## 一个场景在哪个世界里
没有东西阻止一个实体同时带两套组件,但也没有东西会把它们合并:两个世界互相看不见,
diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.ts
index 74ba9e7f3..e719cbca7 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' },
+ 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: '单向平台' },
DistanceJoint: { category: 'physics', summary: 'Holds two bodies a fixed (or spring-limited) distance apart.', doc: 'gameplay/physics', anchor: 'joints', anchorZh: '关节' },
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index 70ede4eb6..daabb316b 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -745,6 +745,79 @@
"realVelocity.y"
]
},
+ {
+ "name": "CharacterController3D",
+ "source": "cpp",
+ "fields": [
+ {
+ "key": "velocity",
+ "type": "Vec3",
+ "default": "(0, 0, 0)"
+ },
+ {
+ "key": "radius",
+ "type": "number",
+ "default": "0.3",
+ "range": "≥ 0"
+ },
+ {
+ "key": "halfHeight",
+ "type": "number",
+ "default": "0.5",
+ "range": "≥ 0"
+ },
+ {
+ "key": "maxSlope",
+ "type": "number",
+ "default": "0.87",
+ "range": "0–1.5708"
+ },
+ {
+ "key": "stepHeight",
+ "type": "number",
+ "default": "0.4",
+ "range": "≥ 0",
+ "advanced": true
+ },
+ {
+ "key": "snapDown",
+ "type": "number",
+ "default": "0.5",
+ "range": "≥ 0",
+ "advanced": true
+ },
+ {
+ "key": "mass",
+ "type": "number",
+ "default": "70",
+ "range": "≥ 0",
+ "advanced": true
+ },
+ {
+ "key": "enabled",
+ "type": "boolean",
+ "default": "true"
+ },
+ {
+ "key": "isOnFloor",
+ "type": "boolean",
+ "default": "false",
+ "advanced": true
+ },
+ {
+ "key": "floorNormal",
+ "type": "Vec3",
+ "default": "(0, 0, 0)",
+ "advanced": true
+ },
+ {
+ "key": "realVelocity",
+ "type": "Vec3",
+ "default": "(0, 0, 0)",
+ "advanced": true
+ }
+ ]
+ },
{
"name": "Children",
"source": "cpp",
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 6e28da56e..6819fc8d5 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
```
-"fb8d63de6b3e9865"
+"95e303bc2d7c9fab"
```
## ANCHOR_AXES — const @experimental
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 02d53d206..21f52ecf8 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
```
-"fb8d63de6b3e9865"
+"95e303bc2d7c9fab"
```
## ANCHOR_AXES — const @experimental
diff --git a/sdk/etc/wasm.api.md b/sdk/etc/wasm.api.md
index a7519deb6..b5e6baf79 100644
--- a/sdk/etc/wasm.api.md
+++ b/sdk/etc/wasm.api.md
@@ -20,6 +20,7 @@ addCamera: (entity: Entity, component: Camera) => void
addCanvas: (entity: Entity, component: Canvas) => void
addCapsuleCollider3D: (entity: Entity, component: CapsuleCollider3D) => void
addCapsuleCollider: (entity: Entity, component: CapsuleCollider) => void
+addCharacterController3D: (entity: Entity, component: CharacterController3D) => void
addChildren: (entity: Entity, component: Children) => void
addCircleCollider: (entity: Entity, component: CircleCollider) => void
addDragonBonesAnimation: (entity: Entity, component: DragonBonesAnimation) => void
@@ -59,6 +60,7 @@ getCamera: (entity: Entity) => Camera
getCanvas: (entity: Entity) => Canvas
getCapsuleCollider3D: (entity: Entity) => CapsuleCollider3D
getCapsuleCollider: (entity: Entity) => CapsuleCollider
+getCharacterController3D: (entity: Entity) => CharacterController3D
getChildren: (entity: Entity) => Children
getCircleCollider: (entity: Entity) => CircleCollider
getDragonBonesAnimation: (entity: Entity) => DragonBonesAnimation
@@ -94,6 +96,7 @@ hasCamera: (entity: Entity) => boolean
hasCanvas: (entity: Entity) => boolean
hasCapsuleCollider3D: (entity: Entity) => boolean
hasCapsuleCollider: (entity: Entity) => boolean
+hasCharacterController3D: (entity: Entity) => boolean
hasChildren: (entity: Entity) => boolean
hasCircleCollider: (entity: Entity) => boolean
hasDragonBonesAnimation: (entity: Entity) => boolean
@@ -129,6 +132,7 @@ removeCamera: (entity: Entity) => void
removeCanvas: (entity: Entity) => void
removeCapsuleCollider3D: (entity: Entity) => void
removeCapsuleCollider: (entity: Entity) => void
+removeCharacterController3D: (entity: Entity) => void
removeChildren: (entity: Entity) => void
removeCircleCollider: (entity: Entity) => void
removeDragonBonesAnimation: (entity: Entity) => void
diff --git a/sdk/src/ecs/bridge/ptrAccessors.generated.ts b/sdk/src/ecs/bridge/ptrAccessors.generated.ts
index c10f0d0b9..03a45cdc1 100644
--- a/sdk/src/ecs/bridge/ptrAccessors.generated.ts
+++ b/sdk/src/ecs/bridge/ptrAccessors.generated.ts
@@ -373,6 +373,70 @@ export function createCapsuleCollider3DData(): CapsuleCollider3DPtrData {
};
}
+export interface CharacterController3DPtrData {
+ velocity: Vec3;
+ radius: number;
+ halfHeight: number;
+ maxSlope: number;
+ stepHeight: number;
+ snapDown: number;
+ mass: number;
+ enabled: boolean;
+ isOnFloor: boolean;
+ floorNormal: Vec3;
+ realVelocity: Vec3;
+}
+
+export function fillCharacterController3D(
+ f32: Float32Array, u32: Uint32Array, u8: Uint8Array,
+ ptr: number, out: CharacterController3DPtrData,
+): void {
+ const velocity_ = out.velocity; velocity_.x = f32[ptr >> 2]; velocity_.y = f32[(ptr >> 2) + 1]; velocity_.z = f32[(ptr >> 2) + 2];
+ out.radius = f32[(ptr + 12) >> 2];
+ out.halfHeight = f32[(ptr + 16) >> 2];
+ out.maxSlope = f32[(ptr + 20) >> 2];
+ out.stepHeight = f32[(ptr + 24) >> 2];
+ 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];
+}
+
+export function writeCharacterController3D(
+ f32: Float32Array, u32: Uint32Array, u8: Uint8Array,
+ ptr: number, data: CharacterController3DPtrData,
+): void {
+ f32[ptr >> 2] = data.velocity.x; f32[(ptr >> 2) + 1] = data.velocity.y; f32[(ptr >> 2) + 2] = data.velocity.z;
+ f32[(ptr + 12) >> 2] = data.radius;
+ f32[(ptr + 16) >> 2] = data.halfHeight;
+ f32[(ptr + 20) >> 2] = data.maxSlope;
+ f32[(ptr + 24) >> 2] = data.stepHeight;
+ 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;
+}
+
+export function createCharacterController3DData(): CharacterController3DPtrData {
+ return {
+ velocity: { x: 0, y: 0, z: 0 },
+ radius: 0,
+ halfHeight: 0,
+ maxSlope: 0,
+ stepHeight: 0,
+ snapDown: 0,
+ mass: 0,
+ enabled: false,
+ isOnFloor: false,
+ floorNormal: { x: 0, y: 0, z: 0 },
+ realVelocity: { x: 0, y: 0, z: 0 },
+ };
+}
+
export interface CircleColliderPtrData {
radius: number;
offset: Vec2;
@@ -1935,6 +1999,7 @@ export const PTR_ACCESSORS: Record<string, PtrAccessor<any>> = {
Canvas: { fill: fillCanvas, write: writeCanvas, create: createCanvasData },
CapsuleCollider: { fill: fillCapsuleCollider, write: writeCapsuleCollider, create: createCapsuleColliderData },
CapsuleCollider3D: { fill: fillCapsuleCollider3D, write: writeCapsuleCollider3D, create: createCapsuleCollider3DData },
+ CharacterController3D: { fill: fillCharacterController3D, write: writeCharacterController3D, create: createCharacterController3DData },
CircleCollider: { fill: fillCircleCollider, write: writeCircleCollider, create: createCircleColliderData },
DragonBonesAnimation: { fill: fillDragonBonesAnimation, write: writeDragonBonesAnimation, create: createDragonBonesAnimationData },
FlexContainer: { fill: fillFlexContainer, write: writeFlexContainer, create: createFlexContainerData },
diff --git a/sdk/src/ecs/component.generated.ts b/sdk/src/ecs/component.generated.ts
index 0fee4b433..a3e4fea27 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 = 'fb8d63de6b3e9865';
+export const ABI_LAYOUT_HASH = '95e303bc2d7c9fab';
/**
* One asset-valued field of a component: which field, and what kind of
@@ -242,6 +242,36 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
restitution: { min: 0, max: 1 },
},
},
+ CharacterController3D: {
+ defaults: {
+ velocity: { x: 0, y: 0, z: 0 },
+ radius: 0.3,
+ halfHeight: 0.5,
+ maxSlope: 0.87,
+ stepHeight: 0.4,
+ snapDown: 0.5,
+ mass: 70,
+ enabled: true,
+ isOnFloor: false,
+ floorNormal: { x: 0, y: 0, z: 0 },
+ realVelocity: { x: 0, y: 0, z: 0 },
+ },
+ assetFields: [],
+ entityFields: [],
+ colorFields: [],
+ animatableFields: [],
+ fields: {
+ radius: { min: 0 },
+ halfHeight: { min: 0 },
+ maxSlope: { min: 0, max: 1.5708, unit: "rad" },
+ stepHeight: { min: 0, advanced: true },
+ snapDown: { min: 0, advanced: true },
+ mass: { min: 0, advanced: true },
+ isOnFloor: { advanced: true },
+ floorNormal: { advanced: true },
+ realVelocity: { advanced: true },
+ },
+ },
Children: {
defaults: {
entities: [],
@@ -1042,6 +1072,20 @@ export interface CapsuleCollider3DData {
enabled: boolean;
}
+export interface CharacterController3DData {
+ velocity: Vec3;
+ radius: number;
+ halfHeight: number;
+ maxSlope: number;
+ stepHeight: number;
+ snapDown: number;
+ mass: number;
+ enabled: boolean;
+ isOnFloor: boolean;
+ floorNormal: Vec3;
+ realVelocity: Vec3;
+}
+
/**
* The fields of the engine's `Children` component, generated from
* the C++ struct so the two shapes cannot drift.
diff --git a/sdk/src/physics3d/Physics3DComponents.ts b/sdk/src/physics3d/Physics3DComponents.ts
index a1ef5dc1b..6f812d8a7 100644
--- a/sdk/src/physics3d/Physics3DComponents.ts
+++ b/sdk/src/physics3d/Physics3DComponents.ts
@@ -10,10 +10,12 @@
import { defineBuiltin } from '../ecs/component';
import type {
RigidBody3DData, BoxCollider3DData, SphereCollider3DData, CapsuleCollider3DData,
+ CharacterController3DData,
} from '../ecs/component.generated';
export type {
RigidBody3DData, BoxCollider3DData, SphereCollider3DData, CapsuleCollider3DData,
+ CharacterController3DData,
};
export const RigidBody3D = defineBuiltin<RigidBody3DData>('RigidBody3D', {
@@ -55,3 +57,36 @@ export const CapsuleCollider3D = defineBuiltin<CapsuleCollider3DData>('CapsuleCo
isSensor: false,
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
+ * component is carried for you, so a zero there means "walk", not "hang".
+ *
+ * @beta
+ */
+export const CharacterController3D = defineBuiltin<CharacterController3DData>(
+ 'CharacterController3D', {
+ velocity: { x: 0, y: 0, z: 0 },
+ radius: 0.3,
+ halfHeight: 0.5,
+ maxSlope: 0.87,
+ stepHeight: 0.4,
+ snapDown: 0.5,
+ mass: 70,
+ enabled: true,
+ isOnFloor: false,
+ floorNormal: { x: 0, y: 0, z: 0 },
+ realVelocity: { x: 0, y: 0, z: 0 },
+ }, {
+ fields: {
+ maxSlope: { min: 0, max: 1.5708, step: 0.01, unit: 'rad',
+ tooltip: 'Steepest ground it can stand on' },
+ stepHeight: { min: 0, step: 0.05, advanced: true },
+ snapDown: { min: 0, step: 0.05, advanced: true },
+ mass: { min: 0, 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 fbb588ea5..c65548918 100644
--- a/sdk/src/physics3d/Physics3DModule.ts
+++ b/sdk/src/physics3d/Physics3DModule.ts
@@ -40,6 +40,15 @@ export interface Physics3DWasmModule {
_physics3d_setLinearVelocity(bodyId: number, vx: number, vy: number, vz: number): void;
_physics3d_getBodyState(bodyId: number): number;
+ _physics3d_addCharacter(entity: number, radius: number, halfHeight: number,
+ px: number, py: number, pz: number,
+ maxSlope: number, mass: number): number;
+ _physics3d_removeCharacter(characterId: number): void;
+ _physics3d_moveCharacter(characterId: number, vx: number, vy: number, vz: number,
+ dt: number, stepUp: number, stepDown: number): void;
+ _physics3d_setCharacterPosition(characterId: number, px: number, py: number,
+ pz: number): void;
+
_physics3d_raycast(ox: number, oy: number, oz: number,
dx: number, dy: number, dz: number): number;
@@ -63,6 +72,7 @@ const REQUIRED_EXPORTS = [
'_physics3d_addBox', '_physics3d_addSphere', '_physics3d_addCapsule',
'_physics3d_removeBody', '_physics3d_setTransform', '_physics3d_raycast',
'_physics3d_transforms', '_physics3d_transformsBytes',
+ '_physics3d_addCharacter', '_physics3d_moveCharacter', '_physics3d_removeCharacter',
] as const;
/** Throws naming what is missing, rather than letting the first frame do it. */
diff --git a/sdk/src/physics3d/Physics3DPlugin.ts b/sdk/src/physics3d/Physics3DPlugin.ts
index 54e99d158..d58228974 100644
--- a/sdk/src/physics3d/Physics3DPlugin.ts
+++ b/sdk/src/physics3d/Physics3DPlugin.ts
@@ -21,10 +21,12 @@ export interface Physics3DRuntime {
initPromise: Promise<unknown> | null;
/** Entity -> body id, so a scene teardown can drop the world's population. */
bodies: Map<Entity, number>;
+ /** Entity -> character id. Characters are not bodies and are kept apart. */
+ characters: Map<Entity, number>;
}
export const Physics3DRuntime = defineResource<Physics3DRuntime>(
- { module: null, initPromise: null, bodies: new Map() },
+ { module: null, initPromise: null, bodies: new Map(), characters: new Map() },
'Physics3DRuntime',
);
@@ -43,7 +45,9 @@ export class Physics3DPlugin implements Plugin {
}
build(app: App): void {
- const runtime: Physics3DRuntime = { module: null, initPromise: null, bodies: new Map() };
+ const runtime: Physics3DRuntime = {
+ module: null, initPromise: null, bodies: new Map(), characters: new Map(),
+ };
app.insertResource(Physics3DRuntime, runtime);
app.subsystems?.transition?.('physics3d', 'initializing');
@@ -53,7 +57,7 @@ export class Physics3DPlugin implements Plugin {
module._physics3d_init(gravity.x, gravity.y, gravity.z, maxBodies);
runtime.module = module;
app.addSystemToSchedule(Schedule.FixedUpdate, defineSystem([], () => {
- stepPhysics3D(app, module, runtime.bodies, this.config_);
+ stepPhysics3D(app, module, runtime.bodies, this.config_, runtime.characters);
}));
app.setFixedTimestep?.(this.config_.fixedTimestep);
app.subsystems?.transition?.('physics3d', 'ready');
diff --git a/sdk/src/physics3d/Physics3DSystem.ts b/sdk/src/physics3d/Physics3DSystem.ts
index 260a50f66..66689b855 100644
--- a/sdk/src/physics3d/Physics3DSystem.ts
+++ b/sdk/src/physics3d/Physics3DSystem.ts
@@ -15,9 +15,9 @@ import type { App } from '../app/app';
import { Transform } from '../ecs/component';
import type { TransformData } from '../ecs/component.generated';
import {
- RigidBody3D, BoxCollider3D, SphereCollider3D, CapsuleCollider3D,
+ RigidBody3D, BoxCollider3D, SphereCollider3D, CapsuleCollider3D, CharacterController3D,
type RigidBody3DData, type BoxCollider3DData, type SphereCollider3DData,
- type CapsuleCollider3DData,
+ type CapsuleCollider3DData, type CharacterController3DData,
} from './Physics3DComponents';
import type { Entity } from '../types';
import type { Physics3DWasmModule } from './Physics3DModule';
@@ -45,6 +45,68 @@ export const DEFAULT_PHYSICS3D_CONFIG: Physics3DConfig = {
/** Which body an entity owns, so a removed component takes its body with it. */
type BodyMap = Map<Entity, number>;
+/** Ground states, as CharacterVirtual reports them. */
+const ON_GROUND = 0;
+
+/**
+ * Sweep every character, then write where each ended up.
+ *
+ * Characters are moved BEFORE the solver steps: a character reads the world as it
+ * stands and the bodies then react to where it went, which is the order that keeps
+ * a character from being pushed by the very body it just displaced.
+ */
+function moveCharacters(app: App, module: Physics3DWasmModule, characters: BodyMap,
+ config: Physics3DConfig): void {
+ const ppu = config.pixelsPerUnit;
+ const live = new Set<Entity>();
+ for (const entity of app.world.queryEntities([CharacterController3D])) {
+ const character = app.world.get(entity, CharacterController3D) as CharacterController3DData;
+ if (!character.enabled) continue;
+ live.add(entity);
+
+ let id = characters.get(entity);
+ if (id === undefined) {
+ const t = app.world.get(entity, Transform) as TransformData | undefined;
+ 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);
+ if (id === 0) continue;
+ characters.set(entity, id);
+ }
+
+ module._physics3d_moveCharacter(
+ id, character.velocity.x / ppu, character.velocity.y / ppu,
+ character.velocity.z / ppu, config.fixedTimestep,
+ character.stepHeight / ppu, character.snapDown / ppu);
+
+ const bytes = module._physics3d_queryResultBytes();
+ if (bytes === 0) continue;
+ const base = module._physics3d_queryResult() >> 2;
+ const f32 = module.HEAPF32;
+ character.isOnFloor = f32[base + 3] === ON_GROUND;
+ character.floorNormal.x = f32[base + 4]!;
+ character.floorNormal.y = f32[base + 5]!;
+ character.floorNormal.z = f32[base + 6]!;
+ character.realVelocity.x = f32[base + 7]! * ppu;
+ character.realVelocity.y = f32[base + 8]! * ppu;
+ character.realVelocity.z = f32[base + 9]! * ppu;
+ app.world.set(entity, CharacterController3D, character);
+
+ if (!app.world.has(entity, Transform)) continue;
+ const t = app.world.get(entity, Transform) as TransformData;
+ t.position.x = f32[base]! * ppu;
+ t.position.y = f32[base + 1]! * ppu;
+ t.position.z = f32[base + 2]! * ppu;
+ app.world.set(entity, Transform, t);
+ }
+ for (const [entity, id] of characters) {
+ if (live.has(entity) && app.world.valid(entity)) continue;
+ module._physics3d_removeCharacter(id);
+ characters.delete(entity);
+ }
+}
+
function motionOf(body: RigidBody3DData): number {
// BodyType is the 2D enum, reused: static/kinematic/dynamic mean the same here.
return body.bodyType === 0 ? MOTION.Static
@@ -92,8 +154,10 @@ function createBody(app: App, module: Physics3DWasmModule, entity: Entity,
/** 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): void {
+ bodies: BodyMap, config: Physics3DConfig,
+ characters: BodyMap = new Map()): void {
const ppu = config.pixelsPerUnit;
+ moveCharacters(app, module, characters, config);
const live = new Set<Entity>();
for (const entity of app.world.queryEntities([RigidBody3D])) {
diff --git a/sdk/src/wasm/ptrLayouts.generated.ts b/sdk/src/wasm/ptrLayouts.generated.ts
index bacc332f5..3940258ee 100644
--- a/sdk/src/wasm/ptrLayouts.generated.ts
+++ b/sdk/src/wasm/ptrLayouts.generated.ts
@@ -118,6 +118,22 @@ export const PTR_LAYOUTS: Record<string, PtrLayout> = {
{ name: 'enabled', type: 'bool', offset: 17 },
],
},
+ CharacterController3D: {
+ ptrFn: 'getCharacterController3DPtr',
+ fields: [
+ { name: 'velocity', type: 'vec3', offset: 0 },
+ { name: 'radius', type: 'f32', offset: 12 },
+ { name: 'halfHeight', type: 'f32', offset: 16 },
+ { name: 'maxSlope', type: 'f32', offset: 20 },
+ { name: 'stepHeight', type: 'f32', offset: 24 },
+ { 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 },
+ ],
+ },
CircleCollider: {
ptrFn: 'getCircleColliderPtr',
fields: [
diff --git a/sdk/src/wasm/wasm.generated.ts b/sdk/src/wasm/wasm.generated.ts
index 9ec1e4d58..07b10ca59 100644
--- a/sdk/src/wasm/wasm.generated.ts
+++ b/sdk/src/wasm/wasm.generated.ts
@@ -296,6 +296,20 @@ export interface CapsuleCollider3D {
enabled: boolean;
}
+export interface CharacterController3D {
+ velocity: Vec3;
+ radius: number;
+ halfHeight: number;
+ maxSlope: number;
+ stepHeight: number;
+ snapDown: number;
+ mass: number;
+ enabled: boolean;
+ isOnFloor: boolean;
+ floorNormal: Vec3;
+ realVelocity: Vec3;
+}
+
export interface Children {
entities: VectorEntity;
}
@@ -688,6 +702,10 @@ export interface Registry {
getCapsuleCollider3D(entity: Entity): CapsuleCollider3D;
addCapsuleCollider3D(entity: Entity, component: CapsuleCollider3D): void;
removeCapsuleCollider3D(entity: Entity): void;
+ hasCharacterController3D(entity: Entity): boolean;
+ getCharacterController3D(entity: Entity): CharacterController3D;
+ addCharacterController3D(entity: Entity, component: CharacterController3D): void;
+ removeCharacterController3D(entity: Entity): void;
hasChildren(entity: Entity): boolean;
getChildren(entity: Entity): Children;
addChildren(entity: Entity, component: Children): void;
@@ -821,6 +839,7 @@ export interface ESEngineModule {
Canvas: new () => Canvas;
CapsuleCollider: new () => CapsuleCollider;
CapsuleCollider3D: new () => CapsuleCollider3D;
+ CharacterController3D: new () => CharacterController3D;
Children: new () => Children;
CircleCollider: new () => CircleCollider;
DragonBonesAnimation: new () => DragonBonesAnimation;
diff --git a/sdk/tests/physics3d-ecs.test.ts b/sdk/tests/physics3d-ecs.test.ts
index ffe7fd256..3646cfc0e 100644
--- a/sdk/tests/physics3d-ecs.test.ts
+++ b/sdk/tests/physics3d-ecs.test.ts
@@ -13,33 +13,44 @@ import { describe, it, expect, beforeEach } from 'vitest';
import { Transform } from '../src/ecs/component';
import type { TransformData } from '../src/ecs/component.generated';
import {
- RigidBody3D, BoxCollider3D, SphereCollider3D, CapsuleCollider3D,
+ RigidBody3D, BoxCollider3D, SphereCollider3D, CapsuleCollider3D, CharacterController3D,
} from '../src/physics3d/Physics3DComponents';
import { stepPhysics3D, DEFAULT_PHYSICS3D_CONFIG } from '../src/physics3d/Physics3DSystem';
import type { Physics3DWasmModule } from '../src/physics3d/Physics3DModule';
import type { App } from '../src/app/app';
import type { Entity } from '../src/types';
-/** A module that records what it was told, and can be made to answer a readback. */
+/** A module that records what it was told, and can be made to answer a readback.
+ * The two readbacks are separate buffers, as they are in the module: sharing one
+ * let the body sweep overwrite what a character had just published. */
function fakeModule(): Physics3DWasmModule & {
calls: { name: string; args: number[] }[];
publish(records: number[]): void;
+ publishQuery(records: number[]): void;
} {
const calls: { name: string; args: number[] }[] = [];
- const heap = new Float32Array(1024);
+ // One heap the module's two pointers index into, as wasm has.
+ const combined = new Float32Array(1088);
+ const heap = combined.subarray(0, 1024);
const record = (name: string) => (...args: number[]): number => {
calls.push({ name, args });
return calls.length; // a non-zero body id
};
+ const query = combined.subarray(1024);
let published = 0;
+ let publishedQuery = 0;
return {
calls,
publish(records: number[]) {
heap.set(records, 0);
published = records.length * 4;
},
- HEAPF32: heap,
- HEAPU32: new Uint32Array(heap.buffer),
+ publishQuery(records: number[]) {
+ query.set(records, 0);
+ publishedQuery = records.length * 4;
+ },
+ HEAPF32: combined,
+ HEAPU32: new Uint32Array(combined.buffer),
_physics3d_init: record('init'),
_physics3d_shutdown: record('shutdown'),
_physics3d_isReady: () => 1,
@@ -53,13 +64,19 @@ function fakeModule(): Physics3DWasmModule & {
_physics3d_setLinearVelocity: record('setLinearVelocity'),
_physics3d_getBodyState: record('getBodyState'),
_physics3d_raycast: record('raycast'),
+ _physics3d_addCharacter: record('addCharacter'),
+ _physics3d_removeCharacter: record('removeCharacter'),
+ _physics3d_moveCharacter: record('moveCharacter'),
+ _physics3d_setCharacterPosition: record('setCharacterPosition'),
_physics3d_transforms: () => 0,
_physics3d_transformsBytes: () => published,
- _physics3d_queryResult: () => 0,
- _physics3d_queryResultBytes: () => 0,
+ // A byte offset past the transform buffer, so the two never alias.
+ _physics3d_queryResult: () => 1024 * 4,
+ _physics3d_queryResultBytes: () => publishedQuery,
} as unknown as Physics3DWasmModule & {
calls: { name: string; args: number[] }[];
publish(records: number[]): void;
+ publishQuery(records: number[]): void;
};
}
@@ -192,6 +209,43 @@ describe('the 3D world and the ECS', () => {
expect(bodies.size).toBe(0);
});
+ it('sweeps a character in metres and reads its ground state back', () => {
+ const e = world.spawn();
+ world.insert<TransformData>(e, Transform, {
+ position: { x: 0, y: 0, z: 0 },
+ rotation: { x: 0, y: 0, z: 0, w: 1 },
+ scale: { x: 1, y: 1, z: 1 },
+ worldPosition: { x: 0, y: 500, z: 0 },
+ worldRotation: { x: 0, y: 0, z: 0, w: 1 },
+ worldScale: { x: 1, y: 1, z: 1 },
+ });
+ world.insert(e, CharacterController3D, {
+ radius: 30, halfHeight: 50, velocity: { x: 200, y: 0, z: 0 },
+ });
+
+ const characters = new Map<Entity, number>();
+ stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG, characters);
+
+ const [added] = called('addCharacter');
+ expect(added!.args[1]).toBeCloseTo(0.3, 6); // 30 world units = 0.3m
+ expect(added!.args[2]).toBeCloseTo(0.5, 6);
+ expect(added!.args[4]).toBeCloseTo(5, 6); // standing 5m up
+ const [moved] = called('moveCharacter');
+ expect(moved!.args[1]).toBeCloseTo(2, 6); // 200 units/s = 2 m/s
+ expect(characters.size).toBe(1);
+
+ // Ground state 0 is OnGround; the normal and velocity come back beside it.
+ module.publishQuery([1, 2, 3, 0, 0, 1, 0, 2, 0, 0]);
+ stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG, characters);
+ const state = world.get(e, CharacterController3D) as {
+ isOnFloor: boolean; floorNormal: { y: number }; realVelocity: { x: number };
+ };
+ expect(state.isOnFloor).toBe(true);
+ expect(state.floorNormal.y).toBeCloseTo(1, 6);
+ expect(state.realVelocity.x).toBeCloseTo(200, 4);
+ expect((world.get(e, Transform) as TransformData).position.y).toBeCloseTo(200, 4);
+ });
+
it('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 784d589ee..a97368389 100644
--- a/sdk/tests/physics3d-smoke.mjs
+++ b/sdk/tests/physics3d-smoke.mjs
@@ -144,7 +144,62 @@ const qx = m.HEAPF32[uprightBase + 3];
check('fixedRotation keeps a body from turning', near(qx, 0.3, 0.01),
`qx=${qx?.toFixed(4)} want the 0.3 it was given`);
-// ── 6) A removed body is gone from both the sweep and the getter ────────────
+// ── 6) A character stands, walks, climbs a step and is stopped by a wall ────
+// The three things that make a character a character rather than a falling
+// capsule. Ground state: 0 = OnGround, 3 = InAir.
+const ON_GROUND = 0, IN_AIR = 3;
+function moveCharacter(id, vx, vy, vz, steps = 1, stepUp = 0.4, stepDown = 0.5) {
+ for (let i = 0; i < steps; i++) m._physics3d_moveCharacter(id, vx, vy, vz, 1 / 60, stepUp, stepDown);
+ const base = m._physics3d_queryResult() >> 2;
+ const f = (i) => m.HEAPF32[base + i];
+ return { x: f(0), y: f(1), z: f(2), ground: f(3), ny: f(5), vy: f(8) };
+}
+
+// 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);
+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}`);
+
+const landed = moveCharacter(hero, 0, 0, 0, 180);
+check('a character lands on the floor', near(landed.y, 0.8, 0.05),
+ `y=${landed.y.toFixed(4)} want 0.8`);
+check('and reports the ground it is on', landed.ground === ON_GROUND, `state=${landed.ground}`);
+check('with the floor normal pointing up', near(landed.ny, 1, 0.05), `ny=${landed.ny.toFixed(4)}`);
+
+// Walking: 2 m/s for half a second covers about a metre, and stays on the floor.
+const walked = moveCharacter(hero, 2, 0, 0, 30);
+check('a character walks where it is sent', walked.x > landed.x + 0.8,
+ `x=${walked.x.toFixed(4)} from ${landed.x.toFixed(4)}`);
+check('and stays on the ground while walking', walked.ground === ON_GROUND);
+
+// A 0.2m step is climbed rather than stopped at: without WalkStairs the character
+// stops dead against it, so the y AFTER is what tells the two apart.
+m._physics3d_addBox(10, 0.5, 0.1, 5, walked.x + 1.3, 0.1, 0, ...IDENTITY,
+ ...FREE(STATIC), 0.5, 0, 0);
+m._physics3d_optimize();
+const climbed = moveCharacter(hero, 2, 0, 0, 60);
+check('a character climbs a step', near(climbed.y, 1.0, 0.08),
+ `y=${climbed.y.toFixed(4)} want 1.0 (0.8 + a 0.2 step)`);
+
+// A wall taller than any step stops it. The character keeps its own height, so a
+// wall that was CLIMBED would show up as a rise rather than as a stop.
+const wallX = climbed.x + 1.0;
+m._physics3d_addBox(11, 0.2, 2, 5, wallX, 2, 0, ...IDENTITY, ...FREE(STATIC), 0.5, 0, 0);
+m._physics3d_optimize();
+const blocked = moveCharacter(hero, 3, 0, 0, 120);
+check('a wall stops a character', blocked.x < wallX - 0.2,
+ `x=${blocked.x.toFixed(4)} wall at ${wallX.toFixed(4)}`);
+check('and it did not climb the wall', blocked.y < climbed.y + 0.3,
+ `y=${blocked.y.toFixed(4)}`);
+
+m._physics3d_removeCharacter(hero);
+check('a removed character can no longer be moved',
+ (m._physics3d_moveCharacter(hero, 1, 0, 0, 1 / 60, 0.4, 0.5),
+ m._physics3d_queryResultBytes() === 0));
+
+// ── 7) 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 6435b86de..544868a6a 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 49337e5243bcd028
+ * @schema_hash 79309dcbf27e8e60
*/
-#define ES_EDITOR_API_SCHEMA_HASH "49337e5243bcd028"
+#define ES_EDITOR_API_SCHEMA_HASH "79309dcbf27e8e60"
#include <emscripten/bind.h>
#include <string>
@@ -65,6 +65,7 @@ std::vector<std::string> editor_getComponentNames() {
"Canvas",
"CapsuleCollider",
"CapsuleCollider3D",
+ "CharacterController3D",
"Children",
"CircleCollider",
"DragonBonesAnimation",
@@ -193,6 +194,26 @@ std::string editor_getComponentSchema(const std::string& name) {
{"key":"isSensor","type":"bool","group":"CapsuleCollider3D"},
{"key":"enabled","type":"bool","group":"CapsuleCollider3D"}
])JSON";
+ } else if (name == "CharacterController3D") {
+ return R"JSON([
+ {"key":"velocity.x","type":"float","group":"CharacterController3D"},
+ {"key":"velocity.y","type":"float","group":"CharacterController3D"},
+ {"key":"velocity.z","type":"float","group":"CharacterController3D"},
+ {"key":"radius","type":"float","group":"CharacterController3D"},
+ {"key":"halfHeight","type":"float","group":"CharacterController3D"},
+ {"key":"maxSlope","type":"float","group":"CharacterController3D"},
+ {"key":"stepHeight","type":"float","group":"CharacterController3D"},
+ {"key":"snapDown","type":"float","group":"CharacterController3D"},
+ {"key":"mass","type":"float","group":"CharacterController3D"},
+ {"key":"enabled","type":"bool","group":"CharacterController3D"},
+ {"key":"isOnFloor","type":"bool","group":"CharacterController3D"},
+ {"key":"floorNormal.x","type":"float","group":"CharacterController3D"},
+ {"key":"floorNormal.y","type":"float","group":"CharacterController3D"},
+ {"key":"floorNormal.z","type":"float","group":"CharacterController3D"},
+ {"key":"realVelocity.x","type":"float","group":"CharacterController3D"},
+ {"key":"realVelocity.y","type":"float","group":"CharacterController3D"},
+ {"key":"realVelocity.z","type":"float","group":"CharacterController3D"}
+ ])JSON";
} else if (name == "Children") {
return R"JSON([
{"key":"entities","type":"entity","group":"Children"}
@@ -669,6 +690,9 @@ bool editor_addComponent(Registry& reg, u32 e, const std::string& name) {
} else if (name == "CapsuleCollider3D") {
if (!reg.has<esengine::ecs::CapsuleCollider3D>(entity)) reg.emplace<esengine::ecs::CapsuleCollider3D>(entity);
return true;
+ } else if (name == "CharacterController3D") {
+ if (!reg.has<esengine::ecs::CharacterController3D>(entity)) reg.emplace<esengine::ecs::CharacterController3D>(entity);
+ return true;
} else if (name == "Children") {
return false;
} else if (name == "CircleCollider") {
@@ -772,6 +796,8 @@ bool editor_removeComponent(Registry& reg, u32 e, const std::string& name) {
if (reg.has<esengine::ecs::CapsuleCollider>(entity)) { reg.remove<esengine::ecs::CapsuleCollider>(entity); return true; }
} else if (name == "CapsuleCollider3D") {
if (reg.has<esengine::ecs::CapsuleCollider3D>(entity)) { reg.remove<esengine::ecs::CapsuleCollider3D>(entity); return true; }
+ } else if (name == "CharacterController3D") {
+ if (reg.has<esengine::ecs::CharacterController3D>(entity)) { reg.remove<esengine::ecs::CharacterController3D>(entity); return true; }
} else if (name == "Children") {
if (reg.has<esengine::ecs::Children>(entity)) {
const auto kids = reg.get<esengine::ecs::Children>(entity).entities;
@@ -846,6 +872,7 @@ bool editor_hasComponent(Registry& reg, u32 e, const std::string& name) {
if (name == "Canvas") return reg.has<esengine::ecs::Canvas>(entity);
if (name == "CapsuleCollider") return reg.has<esengine::ecs::CapsuleCollider>(entity);
if (name == "CapsuleCollider3D") return reg.has<esengine::ecs::CapsuleCollider3D>(entity);
+ if (name == "CharacterController3D") return reg.has<esengine::ecs::CharacterController3D>(entity);
if (name == "Children") return reg.has<esengine::ecs::Children>(entity);
if (name == "CircleCollider") return reg.has<esengine::ecs::CircleCollider>(entity);
if (name == "DragonBonesAnimation") return reg.has<esengine::ecs::DragonBonesAnimation>(entity);
@@ -890,6 +917,7 @@ std::vector<std::string> editor_getComponents(Registry& reg, u32 e) {
if (reg.has<esengine::ecs::Canvas>(entity)) result.push_back("Canvas");
if (reg.has<esengine::ecs::CapsuleCollider>(entity)) result.push_back("CapsuleCollider");
if (reg.has<esengine::ecs::CapsuleCollider3D>(entity)) result.push_back("CapsuleCollider3D");
+ if (reg.has<esengine::ecs::CharacterController3D>(entity)) result.push_back("CharacterController3D");
if (reg.has<esengine::ecs::Children>(entity)) result.push_back("Children");
if (reg.has<esengine::ecs::CircleCollider>(entity)) result.push_back("CircleCollider");
if (reg.has<esengine::ecs::DragonBonesAnimation>(entity)) result.push_back("DragonBonesAnimation");
@@ -1007,6 +1035,26 @@ bool editor_setFloat(Registry& reg, u32 e, const std::string& comp, const std::s
else if (field == "restitution") { c.restitution = 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 == "velocity.x") { c.velocity.x = value; }
+ else if (field == "velocity.y") { c.velocity.y = value; }
+ else if (field == "velocity.z") { c.velocity.z = value; }
+ else if (field == "radius") { c.radius = value; }
+ else if (field == "halfHeight") { c.halfHeight = value; }
+ else if (field == "maxSlope") { c.maxSlope = value; }
+ else if (field == "stepHeight") { c.stepHeight = value; }
+ else if (field == "snapDown") { c.snapDown = value; }
+ else if (field == "mass") { c.mass = value; }
+ else if (field == "floorNormal.x") { c.floorNormal.x = value; }
+ else if (field == "floorNormal.y") { c.floorNormal.y = value; }
+ else if (field == "floorNormal.z") { c.floorNormal.z = value; }
+ else if (field == "realVelocity.x") { c.realVelocity.x = value; }
+ else if (field == "realVelocity.y") { c.realVelocity.y = value; }
+ else if (field == "realVelocity.z") { c.realVelocity.z = 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);
@@ -1437,6 +1485,24 @@ f32 editor_getFloat(Registry& reg, u32 e, const std::string& comp, const std::st
else if (field == "halfHeight") { return c.halfHeight; }
else if (field == "friction") { return c.friction; }
else if (field == "restitution") { return c.restitution; }
+ } else if (comp == "CharacterController3D") {
+ if (!reg.has<esengine::ecs::CharacterController3D>(entity)) return 0.0f;
+ const auto& c = reg.get<esengine::ecs::CharacterController3D>(entity);
+ if (field == "velocity.x") { return c.velocity.x; }
+ else if (field == "velocity.y") { return c.velocity.y; }
+ else if (field == "velocity.z") { return c.velocity.z; }
+ else if (field == "radius") { return c.radius; }
+ else if (field == "halfHeight") { return c.halfHeight; }
+ else if (field == "maxSlope") { return c.maxSlope; }
+ else if (field == "stepHeight") { return c.stepHeight; }
+ else if (field == "snapDown") { return c.snapDown; }
+ else if (field == "mass") { return c.mass; }
+ else if (field == "floorNormal.x") { return c.floorNormal.x; }
+ else if (field == "floorNormal.y") { return c.floorNormal.y; }
+ else if (field == "floorNormal.z") { return c.floorNormal.z; }
+ else if (field == "realVelocity.x") { return c.realVelocity.x; }
+ else if (field == "realVelocity.y") { return c.realVelocity.y; }
+ else if (field == "realVelocity.z") { return c.realVelocity.z; }
} else if (comp == "CircleCollider") {
if (!reg.has<esengine::ecs::CircleCollider>(entity)) return 0.0f;
const auto& c = reg.get<esengine::ecs::CircleCollider>(entity);
@@ -2161,6 +2227,13 @@ 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 == "CharacterController3D") {
+ if (!reg.has<esengine::ecs::CharacterController3D>(entity)) return false;
+ auto& c = reg.get<esengine::ecs::CharacterController3D>(entity);
+ if (field == "enabled") { c.enabled = value; }
+ else if (field == "isOnFloor") { c.isOnFloor = 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);
@@ -2361,6 +2434,11 @@ bool editor_getBool(Registry& reg, u32 e, const std::string& comp, const std::st
const auto& c = reg.get<esengine::ecs::CapsuleCollider3D>(entity);
if (field == "isSensor") { return c.isSensor; }
else if (field == "enabled") { return c.enabled; }
+ } else if (comp == "CharacterController3D") {
+ if (!reg.has<esengine::ecs::CharacterController3D>(entity)) return false;
+ const auto& c = reg.get<esengine::ecs::CharacterController3D>(entity);
+ if (field == "enabled") { return c.enabled; }
+ else if (field == "isOnFloor") { return c.isOnFloor; }
} else if (comp == "CircleCollider") {
if (!reg.has<esengine::ecs::CircleCollider>(entity)) return false;
const auto& c = reg.get<esengine::ecs::CircleCollider>(entity);
diff --git a/src/esengine/bindings/WebBindings.generated.cpp b/src/esengine/bindings/WebBindings.generated.cpp
index 254906a69..d2deb0dcb 100644
--- a/src/esengine/bindings/WebBindings.generated.cpp
+++ b/src/esengine/bindings/WebBindings.generated.cpp
@@ -1292,6 +1292,19 @@ EMSCRIPTEN_BINDINGS(esengine_components) {
.field("isSensor", &esengine::ecs::CapsuleCollider3D::isSensor)
.field("enabled", &esengine::ecs::CapsuleCollider3D::enabled);
+ value_object<esengine::ecs::CharacterController3D>("CharacterController3D")
+ .field("velocity", &esengine::ecs::CharacterController3D::velocity)
+ .field("radius", &esengine::ecs::CharacterController3D::radius)
+ .field("halfHeight", &esengine::ecs::CharacterController3D::halfHeight)
+ .field("maxSlope", &esengine::ecs::CharacterController3D::maxSlope)
+ .field("stepHeight", &esengine::ecs::CharacterController3D::stepHeight)
+ .field("snapDown", &esengine::ecs::CharacterController3D::snapDown)
+ .field("mass", &esengine::ecs::CharacterController3D::mass)
+ .field("enabled", &esengine::ecs::CharacterController3D::enabled)
+ .field("isOnFloor", &esengine::ecs::CharacterController3D::isOnFloor)
+ .field("floorNormal", &esengine::ecs::CharacterController3D::floorNormal)
+ .field("realVelocity", &esengine::ecs::CharacterController3D::realVelocity);
+
value_object<ChildrenJS>("Children")
.field("entities", &ChildrenJS::entities);
@@ -1797,6 +1810,27 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {
r.remove<esengine::ecs::CapsuleCollider3D>(entity);
}))
+ // CharacterController3D
+ .function("hasCharacterController3D", optional_override([](Registry& r, u32 e) {
+ return r.has<esengine::ecs::CharacterController3D>(static_cast<Entity>(e));
+ }))
+ .function("getCharacterController3D", optional_override([](Registry& r, u32 e) -> esengine::ecs::CharacterController3D& {
+ auto entity = static_cast<Entity>(e);
+ static esengine::ecs::CharacterController3D s_dummy{};
+ if (!r.valid(entity) || !r.has<esengine::ecs::CharacterController3D>(entity)) return s_dummy;
+ return r.get<esengine::ecs::CharacterController3D>(entity);
+ }), allow_raw_pointers())
+ .function("addCharacterController3D", optional_override([](Registry& r, u32 e, const esengine::ecs::CharacterController3D& c) {
+ auto entity = static_cast<Entity>(e);
+ if (!r.valid(entity)) return;
+ r.emplaceOrReplace<esengine::ecs::CharacterController3D>(entity, c);
+ }))
+ .function("removeCharacterController3D", optional_override([](Registry& r, u32 e) {
+ auto entity = static_cast<Entity>(e);
+ if (!r.valid(entity) || !r.has<esengine::ecs::CharacterController3D>(entity)) return;
+ r.remove<esengine::ecs::CharacterController3D>(entity);
+ }))
+
// Children
.function("hasChildren", optional_override([](Registry& r, u32 e) {
return r.has<esengine::ecs::Children>(static_cast<Entity>(e));
@@ -2455,6 +2489,7 @@ emscripten::val esengineGetBuiltinComponentNames() {
arr.set(i++, val(std::string("Canvas")));
arr.set(i++, val(std::string("CapsuleCollider")));
arr.set(i++, val(std::string("CapsuleCollider3D")));
+ arr.set(i++, val(std::string("CharacterController3D")));
arr.set(i++, val(std::string("Children")));
arr.set(i++, val(std::string("CircleCollider")));
arr.set(i++, val(std::string("DragonBonesAnimation")));
@@ -2553,6 +2588,17 @@ static_assert(offsetof(esengine::ecs::CapsuleCollider3D, friction) == 8, "ABI of
static_assert(offsetof(esengine::ecs::CapsuleCollider3D, restitution) == 12, "ABI offset drift: esengine::ecs::CapsuleCollider3D.restitution (EHT expected 12)");
static_assert(offsetof(esengine::ecs::CapsuleCollider3D, isSensor) == 16, "ABI offset drift: esengine::ecs::CapsuleCollider3D.isSensor (EHT expected 16)");
static_assert(offsetof(esengine::ecs::CapsuleCollider3D, enabled) == 17, "ABI offset drift: esengine::ecs::CapsuleCollider3D.enabled (EHT expected 17)");
+static_assert(offsetof(esengine::ecs::CharacterController3D, velocity) == 0, "ABI offset drift: esengine::ecs::CharacterController3D.velocity (EHT expected 0)");
+static_assert(offsetof(esengine::ecs::CharacterController3D, radius) == 12, "ABI offset drift: esengine::ecs::CharacterController3D.radius (EHT expected 12)");
+static_assert(offsetof(esengine::ecs::CharacterController3D, halfHeight) == 16, "ABI offset drift: esengine::ecs::CharacterController3D.halfHeight (EHT expected 16)");
+static_assert(offsetof(esengine::ecs::CharacterController3D, maxSlope) == 20, "ABI offset drift: esengine::ecs::CharacterController3D.maxSlope (EHT expected 20)");
+static_assert(offsetof(esengine::ecs::CharacterController3D, stepHeight) == 24, "ABI offset drift: esengine::ecs::CharacterController3D.stepHeight (EHT expected 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::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)");
@@ -2821,7 +2867,7 @@ static_assert(offsetof(esengine::ecs::Velocity, angular) == 12, "ABI offset drif
// ABI Hash -- runtime handshake against the SDK bundle
// =============================================================================
-static const char* kEsAbiLayoutHash = "fb8d63de6b3e9865";
+static const char* kEsAbiLayoutHash = "95e303bc2d7c9fab";
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 29299fb55..2f6d14e69 100644
--- a/src/esengine/bindings/modules/physics3d/Physics3DContext.hpp
+++ b/src/esengine/bindings/modules/physics3d/Physics3DContext.hpp
@@ -26,9 +26,12 @@
#include <Jolt/Physics/PhysicsSystem.h>
#include <cstdint>
+#include <memory>
#include <unordered_map>
#include <vector>
+namespace JPH { class CharacterVirtual; }
+
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#else
@@ -101,6 +104,12 @@ struct Context {
/// The last query's hits, in the shape its getter documents.
std::vector<float> queryBuffer;
+ /// Characters are not bodies: a CharacterVirtual is swept against the world
+ /// 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;
+ 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 771d28f40..e20117317 100644
--- a/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp
+++ b/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp
@@ -22,6 +22,7 @@
#include <Jolt/Physics/Collision/Shape/BoxShape.h>
#include <Jolt/Physics/Collision/Shape/CapsuleShape.h>
#include <Jolt/Physics/Collision/Shape/SphereShape.h>
+#include <Jolt/Physics/Character/CharacterVirtual.h>
#include <Jolt/RegisterTypes.h>
#include <cstddef>
@@ -45,6 +46,11 @@ Context& g() { return esengine::physics3d::ctx(); }
/// this is a ceiling on one step's working set rather than a running cost.
constexpr JPH::uint TEMP_ARENA_BYTES = 8 * 1024 * 1024;
+/// Character ids and body ids are both small integers and share one owner map, so
+/// a character's key is tagged apart. Bodies never reach this bit: Jolt packs a
+/// BodyID's index into the low 23.
+constexpr uint32_t CHARACTER_ID_TAG = 0x80000000u;
+
EMotionType motionTypeOf(int value) {
switch (value) {
case 1: return EMotionType::Kinematic;
@@ -131,6 +137,7 @@ void physics3d_shutdown() {
g().system = nullptr;
g().jobs = nullptr;
g().temp = nullptr;
+ g().characters.clear();
g().entityOf.clear();
g().transformBuffer.clear();
g().queryBuffer.clear();
@@ -262,6 +269,91 @@ int physics3d_getBodyState(uint32_t bodyId) {
return 1;
}
+// Characters
+
+/**
+ * @brief Registers a character: an upright capsule swept against the world.
+ * @param maxSlope Steepest ground the character can stand on, in radians.
+ * @return the character id, or 0 when there is no world.
+ */
+EMSCRIPTEN_KEEPALIVE
+uint32_t physics3d_addCharacter(uint32_t entity, float radius, float halfHeight,
+ float px, float py, float pz, float maxSlope, float mass) {
+ if (!g().isValid()) return 0;
+ Ref<CharacterVirtualSettings> settings = new CharacterVirtualSettings();
+ settings->mShape = new CapsuleShape(halfHeight, radius);
+ settings->mMaxSlopeAngle = maxSlope;
+ settings->mMass = mass;
+ // The plane below which contacts do not hold the character up. Without it a
+ // contact anywhere on the capsule — including the top — reads as ground.
+ settings->mSupportingVolume = Plane(Vec3::sAxisY(), -radius);
+ auto character = std::make_unique<CharacterVirtual>(
+ settings, RVec3(px, py, pz), Quat::sIdentity(), g().system);
+ const uint32_t id = g().nextCharacterId++;
+ g().characters[id] = std::move(character);
+ g().entityOf[id | CHARACTER_ID_TAG] = entity;
+ return id;
+}
+
+EMSCRIPTEN_KEEPALIVE
+void physics3d_removeCharacter(uint32_t characterId) {
+ g().characters.erase(characterId);
+ g().entityOf.erase(characterId | CHARACTER_ID_TAG);
+}
+
+/**
+ * @brief Moves a character by its velocity for one step.
+ * @details ExtendedUpdate is Jolt's own combination of move, stick-to-floor and
+ * walk-stairs: without it a character stops dead at a 10cm step and
+ * launches off the top of every slope it walks down.
+ * Writes (px,py,pz, groundState, nx,ny,nz, vx,vy,vz) to the query buffer.
+ */
+EMSCRIPTEN_KEEPALIVE
+void physics3d_moveCharacter(uint32_t characterId, float vx, float vy, float vz,
+ float dt, float stepUp, float stepDown) {
+ g().queryBuffer.clear();
+ auto found = g().characters.find(characterId);
+ if (!g().isValid() || found == g().characters.end()) return;
+ CharacterVirtual& character = *found->second;
+
+ // A CharacterVirtual does not fall on its own — its gravity parameter only
+ // pushes down on what it stands on, and the vertical speed is the caller's.
+ // Carried here so `vy = 0` means "walk", not "hang in the air".
+ float vertical = character.GetLinearVelocity().GetY();
+ if (vy != 0.0f) {
+ vertical = vy; // a jump, or a deliberate dive
+ } else if (character.GetGroundState() == CharacterVirtual::EGroundState::OnGround) {
+ vertical = 0.0f;
+ } else {
+ vertical += g().system->GetGravity().GetY() * dt;
+ }
+ character.SetLinearVelocity(Vec3(vx, vertical, vz));
+ CharacterVirtual::ExtendedUpdateSettings settings;
+ settings.mWalkStairsStepUp = Vec3(0, stepUp, 0);
+ settings.mStickToFloorStepDown = Vec3(0, -stepDown, 0);
+ character.ExtendedUpdate(dt, g().system->GetGravity(), settings,
+ g().system->GetDefaultBroadPhaseLayerFilter(Layers::MOVING),
+ g().system->GetDefaultLayerFilter(Layers::MOVING),
+ {}, {}, *g().temp);
+
+ const RVec3 position = character.GetPosition();
+ const Vec3 normal = character.GetGroundNormal();
+ const Vec3 velocity = character.GetLinearVelocity();
+ g().queryBuffer = {
+ static_cast<float>(position.GetX()), static_cast<float>(position.GetY()),
+ static_cast<float>(position.GetZ()),
+ static_cast<float>(character.GetGroundState()),
+ normal.GetX(), normal.GetY(), normal.GetZ(),
+ velocity.GetX(), velocity.GetY(), velocity.GetZ(),
+ };
+}
+
+EMSCRIPTEN_KEEPALIVE
+void physics3d_setCharacterPosition(uint32_t characterId, float px, float py, float pz) {
+ auto found = g().characters.find(characterId);
+ if (found != g().characters.end()) found->second->SetPosition(RVec3(px, py, pz));
+}
+
// Queries
/// Nearest hit along the ray. Writes (entity, fraction, px,py,pz, nx,ny,nz) into the
diff --git a/src/esengine/ecs/components/RigidBody3D.hpp b/src/esengine/ecs/components/RigidBody3D.hpp
index 14a018cde..19398672b 100644
--- a/src/esengine/ecs/components/RigidBody3D.hpp
+++ b/src/esengine/ecs/components/RigidBody3D.hpp
@@ -124,4 +124,57 @@ struct CapsuleCollider3D {
bool enabled{true};
};
+/**
+ * @brief A kinematic mover for a 3D player or NPC.
+ *
+ * @details Swept against the world rather than solved in it, which is what lets it
+ * climb a step without inheriting the momentum of what it stands on. Set
+ * @ref velocity each step; the vertical component is carried for you, so a
+ * zero there means "walk". REPLACES a RigidBody3D rather than joining one.
+ */
+ES_COMPONENT()
+struct CharacterController3D {
+ /** @brief Desired velocity in world units/second. A positive y is a jump. */
+ ES_PROPERTY()
+ glm::vec3 velocity{0.0f, 0.0f, 0.0f};
+
+ ES_PROPERTY(min=0)
+ f32 radius{0.3f};
+
+ /** @brief Half the cylinder; total height is `2*(halfHeight + radius)`. */
+ ES_PROPERTY(min=0)
+ f32 halfHeight{0.5f};
+
+ /** @brief Steepest ground it can stand on. Beyond this it slides. */
+ ES_PROPERTY(min=0, max=1.5708, unit="rad")
+ f32 maxSlope{0.87f};
+
+ /** @brief Tallest step it climbs instead of stopping at. 0 = climbs nothing. */
+ ES_PROPERTY(min=0, advanced)
+ f32 stepHeight{0.4f};
+
+ /** @brief How far it reaches down to stay on the floor over a crest. 0 = off. */
+ ES_PROPERTY(min=0, advanced)
+ f32 snapDown{0.5f};
+
+ /** @brief Mass used when it pushes dynamic bodies. */
+ ES_PROPERTY(min=0, advanced)
+ f32 mass{70.0f};
+
+ ES_PROPERTY()
+ bool enabled{true};
+
+ /** @brief Output: standing on ground it can walk on. */
+ ES_PROPERTY(advanced)
+ bool isOnFloor{false};
+
+ /** @brief Output: the floor's normal; zero while airborne. */
+ ES_PROPERTY(advanced)
+ glm::vec3 floorNormal{0.0f, 0.0f, 0.0f};
+
+ /** @brief Output: what it actually moved, per second, after collisions. */
+ ES_PROPERTY(advanced)
+ glm::vec3 realVelocity{0.0f, 0.0f, 0.0f};
+};
+
} // namespace esengine::ecs