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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(physics): the running game draws its own 3D shapes
esengine1e589eddb06d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 27abfec32..d7ed1b604 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,16 @@ published separately; it ships inside the editor.### Added+- **The running game can draw its own 3D shapes.** `Physics3DDebugDraw` outlines+ every collider the solver built, in the game rather than in the editor — which+ is the only place the question "why did the player get stuck there" can be+ asked. The editor hides its own overlays in play, so what you see is the engine+ answering.++ `Draw.line3D` is what made it possible: the immediate-mode vertex has always+ carried three components, and the ribbon is now widened across the view rather+ than in the plane, so a line reads as a line from wherever the camera is.+- **Imported geometry that moves.** A `ConvexCollider3D` collides against theconvex hull of a mesh's vertices — a rock, a chamfered crate, a barrel thatrolls. `MeshCollider3D` is scenery whatever its body says (Jolt cannot give adiff --git a/desktop/scripts/editor-checks/physics3d-debug-draw.mjs b/desktop/scripts/editor-checks/physics3d-debug-draw.mjsnew file mode 100644index 000000000..a01842a91--- /dev/null+++ b/desktop/scripts/editor-checks/physics3d-debug-draw.mjs@@ -0,0 +1,138 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file physics3d-debug-draw — the RUNNING game can show its own 3D shapes.+ *+ * The editor gizmo answers "is this box the size I meant"; this answers "why did+ * the player get stuck there", which only the running game can be asked. The+ * editor hides every one of its overlays in play, so a wireframe on screen here+ * can only have been drawn by the engine — which is what makes the picture worth+ * measuring rather than merely counting.+ */+import { makeProject, checker } from '../lib/editorDriver.mjs';++/** One static box seen through a PERSPECTIVE camera, which is what makes the+ * picture answer whether the lines carry depth: the near face draws wider than+ * the far one, so a scan across the middle crosses FOUR uprights. Drop the z+ * and the faces coincide, leaving every other measure unchanged. */+const SCENE = JSON.stringify({+ version: '1.0', name: 'Main',+ entities: [+ {+ id: 0, name: 'Camera', parent: null, children: [], visible: true,+ components: [+ { type: 'Transform', data: { position: { x: 0, y: 0, z: 600 } } },+ {+ type: 'Camera',+ data: {+ projectionType: 0, fov: 60, nearPlane: 10, farPlane: 2000,+ isActive: true, priority: 0,+ },+ },+ ],+ },+ {+ id: 1, name: 'Wall', parent: null, children: [], visible: true,+ components: [+ { type: 'Transform', data: { position: { x: 0, y: 0, z: 0 } } },+ { type: 'RigidBody3D', data: { bodyType: 0 } },+ { type: 'BoxCollider3D', data: { halfExtents: { x: 100, y: 25, z: 100 } } },+ ],+ },+ ],+}, null, 1);++export const name = 'physics3d-debug-draw';+export const describes = 'a running 3D game draws its own collider shapes when asked';++/** Pixels near the static-body colour (0.2, 0.4, 1.0) — blue, well above both+ * other channels. Nothing else in a play viewport of an empty scene is. */+function shapeBox(png) {+ let minX = Infinity, minY = Infinity, maxX = -1, maxY = -1, count = 0;+ // The viewport only: the content browser below it has blue folder icons, and a+ // window-wide sweep counts those as a wireframe.+ const x0 = Math.round(png.w * 0.04), x1 = Math.round(png.w * 0.72);+ const y0 = Math.round(png.h * 0.12), y1 = Math.round(png.h * 0.62);+ for (let y = y0; y < y1; y++) {+ for (let x = x0; x < x1; x++) {+ const p = png.px(x, y);+ if (p[2] < 140 || p[2] - p[0] < 90 || p[2] - p[1] < 60) continue;+ count++;+ if (x < minX) minX = x;+ if (x > maxX) maxX = x;+ if (y < minY) minY = y;+ if (y > maxY) maxY = y;+ }+ }+ return maxX < 0 ? null : { minX, minY, maxX, maxY, w: maxX - minX + 1, h: maxY - minY + 1, count };+}++/** Runs of shape-coloured pixels along one row — how many uprights it crosses. */+function runsAcross(png, y, x0, x1) {+ let runs = 0;+ let inside = false;+ for (let x = x0; x <= x1; x++) {+ const p = png.px(x, y);+ const lit = p[2] >= 140 && p[2] - p[0] >= 90 && p[2] - p[1] >= 60;+ if (lit && !inside) runs++;+ inside = lit;+ }+ return runs;+}++export async function run(ed) {+ const root = await makeProject({+ 'project.esproject': JSON.stringify({ name: 'DebugDraw3D', version: '1.0' }, null, 2),+ 'assets/scenes/main.esscene': SCENE,+ });+ const check = checker();++ await ed.open(root, 'assets/scenes/main.esscene');+ await ed.call('set_play', { state: 'playing' }, 120000);++ let ready = false;+ for (let i = 0; i < 40 && !ready; i++) {+ ready = (await ed.json('get_play_state', {}))?.ready === true;+ if (!ready) await ed.sleep(500);+ }+ if (!check(ready, 'the play realm never reported ready')) return check.failures;++ await ed.call('play_probe', { code: 'await step(3); return true;' }, 60000);+ await ed.sleep(600);+ const before = shapeBox(await ed.screenshot('debug3d-off'));+ if (!check((before?.count ?? 0) < 40,+ `${before?.count} shape-coloured pixels before anything asked for them — the overlay `+ + 'is drawing itself, or an editor gizmo is still on screen in play')) {+ return check.failures;+ }++ const on = await ed.json('play_probe', {+ code: 'setResource("Physics3DDebugDraw", { enabled: true });'+ + ' await step(3);'+ + ' return resource("Physics3DDebugDraw");',+ }, 60000);+ if (!check(on?.enabled === true, `the resource did not take the write: ${JSON.stringify(on)}`)) {+ return check.failures;+ }+ await ed.sleep(600);++ const shot = await ed.screenshot('debug3d-on');+ const box = shapeBox(shot);+ if (!check(box != null && box.count > 100,+ `only ${box?.count ?? 0} wireframe pixels after turning the overlay on`)) {+ return check.failures;+ }++ // ★ Four uprights across the middle: the near face and the far one, drawn at+ // the different sizes perspective gives them. Two would mean the lines reached+ // the GPU without their depth and the box collapsed into a rectangle.+ const uprights = runsAcross(shot, Math.round((box.minY + box.maxY) / 2),+ box.minX - 2, box.maxX + 2);+ check(+ uprights === 4,+ `a scan across the middle crossed ${uprights} uprights rather than 4 — the near and far `+ + 'faces are not being drawn at different sizes, so the lines carry no depth',+ );++ return check.failures;+}diff --git a/desktop/src/theme/viewport.css b/desktop/src/theme/viewport.cssindex 9ad6f6f7e..eb63ad775 100644--- a/desktop/src/theme/viewport.css+++ b/desktop/src/theme/viewport.css@@ -412,6 +412,9 @@.viewport--play .viewport__cam-gizmo,.viewport--play .viewport__light-gizmo,.viewport--play .viewport__collider-gizmo,+.viewport--play .viewport__collider3d-gizmo,+.viewport--play .viewport__joint3d-gizmo,+.viewport--play .viewport__joint-gizmo,.viewport--play .viewport__tilecol-gizmo,.viewport--play .viewport__particle-gizmo,.viewport--play .viewport__marker-gizmo,diff --git a/docs/astro/src/content/docs/gameplay/physics-3d.mdx b/docs/astro/src/content/docs/gameplay/physics-3d.mdxindex b161d65e6..a9a0b4257 100644--- a/docs/astro/src/content/docs/gameplay/physics-3d.mdx+++ b/docs/astro/src/content/docs/gameplay/physics-3d.mdx@@ -100,6 +100,31 @@ beside it, since a character is swept rather than solved.edges would bury it.</Aside>+### While the game runs++The editor's gizmos are hidden in play, so the running game draws its own. Turn+the `Physics3DDebugDraw` resource on when you need to see why something got+stuck where it did:++```typescript+app.getResource(Physics3DDebugDraw).enabled = true;+```++| Field | What it does |+|---|---|+| `enabled` | Off by default — an overlay costs a line per edge per frame. |+| `showColliders` | The shape of every body the solver built. |+| `showContacts` | A cross at each contact point reported this step. |++<Aside>+ Only what the solver actually built is drawn here. A disabled collider is+ authoring state, and the editor is where you see it — the running game showing+ it would be describing a collision that cannot happen.++ The overlay ignores the depth buffer, so a shape inside a wall is still+ visible. That is what a debug view is for.+</Aside>+## CharactersA `CharacterController3D` replaces a `RigidBody3D` rather than accompanying one: adiff --git a/docs/astro/src/content/docs/zh-cn/gameplay/physics-3d.mdx b/docs/astro/src/content/docs/zh-cn/gameplay/physics-3d.mdxindex b198f4df1..6e1d7c8f9 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@@ -90,6 +90,28 @@ cmds.spawn()这个网格,几千条投影出来的边只会把它埋掉。</Aside>+### 游戏跑起来的时候++编辑器的 gizmo 在 Play 时全部隐藏,所以由运行中的游戏画它自己的。+需要弄清「它为什么卡在那儿」时,把 `Physics3DDebugDraw` 资源打开:++```typescript+app.getResource(Physics3DDebugDraw).enabled = true;+```++| 字段 | 作用 |+|---|---|+| `enabled` | 默认关闭——每帧每条边一根线,这是有代价的。 |+| `showColliders` | 求解器真的建出来的每个刚体的形状。 |+| `showContacts` | 这一步报告的每个接触点上画一个十字。 |++<Aside>+ 这里只画**求解器真的建了的**那些。被禁用的碰撞体属于编辑态,该在编辑器里看——+ 运行中的游戏把它画出来就是在描述一场不可能发生的碰撞。++ 这层覆盖**不参与深度测试**,所以埋在墙里的形状照样看得见。调试视图就是要这样。+</Aside>+## 角色`CharacterController3D` **取代** `RigidBody3D` 而不是与它并存:被求解器推的刚体diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex 1c40a9ad7..5fc3e29f6 100644--- a/docs/astro/src/data/apiStability.generated.json+++ b/docs/astro/src/data/apiStability.generated.json@@ -3,10 +3,10 @@"counts": {"public": 113,"beta": 73,- "experimental": 1559,+ "experimental": 1562,"deprecated": 3},- "total": 1745,+ "total": 1748,"subsystems": [{"id": "ecs",diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 8dfa6bb0d..c54c0efbe 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,7 +1,7 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 113 public · 66 beta · 1444 experimental · 3 deprecated+Symbols: 113 public · 66 beta · 1447 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -2640,6 +2640,7 @@ drawMeshWithMaterial: (geometry: GeometryHandle, material: MaterialHandle, transend: () => voidgetDrawCallCount: () => numbergetPrimitiveCount: () => number+line3D: (from: Vec3, to: Vec3, color: Color, thickness?: number) => voidline: (from: Vec2, to: Vec2, color: Color, thickness?: number) => voidrect: (position: Vec2, size: Vec2, color: Color, filled?: boolean) => voidrectOutline: (position: Vec2, size: Vec2, color: Color, thickness?: number) => void@@ -4999,6 +5000,18 @@ ComponentDef<{}>ResourceDef<PhysicsAPI>```+## Physics3DDebugDraw — const @experimental+```+ResourceDef<Physics3DDebugDrawConfig>+```++## Physics3DDebugDrawConfig — interface @experimental+```+enabled: boolean+showColliders: boolean+showContacts: boolean+```+## PhysicsContactEventData — interface @experimental```approachSpeed: number | undefined@@ -9818,6 +9831,11 @@ DragPlugin() => DragonBonesPlugin```+## drawPhysics3DDebug — function @experimental+```+(app: App, contacts?: readonly Contact3D[]): void+```+## editorViewAxes — function @experimental```(view: EditorViewData): { x: ScreenAxis; y: ScreenAxis; z: ScreenAxis; }diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 802ff0c43..2261218ed 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.native<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 113 public · 71 beta · 1463 experimental · 3 deprecated+Symbols: 113 public · 71 beta · 1466 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -2648,6 +2648,7 @@ drawMeshWithMaterial: (geometry: GeometryHandle, material: MaterialHandle, transend: () => voidgetDrawCallCount: () => numbergetPrimitiveCount: () => number+line3D: (from: Vec3, to: Vec3, color: Color, thickness?: number) => voidline: (from: Vec2, to: Vec2, color: Color, thickness?: number) => voidrect: (position: Vec2, size: Vec2, color: Color, filled?: boolean) => voidrectOutline: (position: Vec2, size: Vec2, color: Color, thickness?: number) => void@@ -5182,6 +5183,18 @@ ComponentDef<{}>ResourceDef<PhysicsAPI>```+## Physics3DDebugDraw — const @experimental+```+ResourceDef<Physics3DDebugDrawConfig>+```++## Physics3DDebugDrawConfig — interface @experimental+```+enabled: boolean+showColliders: boolean+showContacts: boolean+```+## PhysicsContactEventData — interface @experimental```approachSpeed: number | undefined@@ -10051,6 +10064,11 @@ DragPlugin() => DragonBonesPlugin```+## drawPhysics3DDebug — function @experimental+```+(app: App, contacts?: readonly Contact3D[]): void+```+## editorViewAxes — function @experimental```(view: EditorViewData): { x: ScreenAxis; y: ScreenAxis; z: ScreenAxis; }diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 9a4a861aa..5e0dfed21 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.node<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 113 public · 68 beta · 1443 experimental · 3 deprecated+Symbols: 113 public · 68 beta · 1446 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -2635,6 +2635,7 @@ drawMeshWithMaterial: (geometry: GeometryHandle, material: MaterialHandle, transend: () => voidgetDrawCallCount: () => numbergetPrimitiveCount: () => number+line3D: (from: Vec3, to: Vec3, color: Color, thickness?: number) => voidline: (from: Vec2, to: Vec2, color: Color, thickness?: number) => voidrect: (position: Vec2, size: Vec2, color: Color, filled?: boolean) => voidrectOutline: (position: Vec2, size: Vec2, color: Color, thickness?: number) => void@@ -4994,6 +4995,18 @@ ComponentDef<{}>ResourceDef<PhysicsAPI>```+## Physics3DDebugDraw — const @experimental+```+ResourceDef<Physics3DDebugDrawConfig>+```++## Physics3DDebugDrawConfig — interface @experimental+```+enabled: boolean+showColliders: boolean+showContacts: boolean+```+## PhysicsContactEventData — interface @experimental```approachSpeed: number | undefined@@ -9813,6 +9826,11 @@ DragPlugin() => DragonBonesPlugin```+## drawPhysics3DDebug — function @experimental+```+(app: App, contacts?: readonly Contact3D[]): void+```+## editorViewAxes — function @experimental```(view: EditorViewData): { x: ScreenAxis; y: ScreenAxis; z: ScreenAxis; }diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 5d4664230..7bc09fc61 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -1,7 +1,7 @@# API surface — esengine/minigame<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 113 public · 66 beta · 1464 experimental · 3 deprecated+Symbols: 113 public · 66 beta · 1467 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -2635,6 +2635,7 @@ drawMeshWithMaterial: (geometry: GeometryHandle, material: MaterialHandle, transend: () => voidgetDrawCallCount: () => numbergetPrimitiveCount: () => number+line3D: (from: Vec3, to: Vec3, color: Color, thickness?: number) => voidline: (from: Vec2, to: Vec2, color: Color, thickness?: number) => voidrect: (position: Vec2, size: Vec2, color: Color, filled?: boolean) => voidrectOutline: (position: Vec2, size: Vec2, color: Color, thickness?: number) => void@@ -5239,6 +5240,18 @@ ComponentDef<{}>ResourceDef<PhysicsAPI>```+## Physics3DDebugDraw — const @experimental+```+ResourceDef<Physics3DDebugDrawConfig>+```++## Physics3DDebugDrawConfig — interface @experimental+```+enabled: boolean+showColliders: boolean+showContacts: boolean+```+## PhysicsContactEventData — interface @experimental```approachSpeed: number | undefined@@ -10063,6 +10076,11 @@ DragPlugin() => DragonBonesPlugin```+## drawPhysics3DDebug — function @experimental+```+(app: App, contacts?: readonly Contact3D[]): void+```+## editorViewAxes — function @experimental```(view: EditorViewData): { x: ScreenAxis; y: ScreenAxis; z: ScreenAxis; }diff --git a/sdk/etc/wasm.api.md b/sdk/etc/wasm.api.mdindex d60be155f..ecc356c5c 100644--- a/sdk/etc/wasm.api.md+++ b/sdk/etc/wasm.api.md@@ -238,6 +238,7 @@ draw_circleOutline: (centerX: number, centerY: number, radius: number, r: numberdraw_end: () => voiddraw_getDrawCallCount: () => numberdraw_getPrimitiveCount: () => number+draw_line3D: (fromX: number, fromY: number, fromZ: number, toX: number, toY: number, toZ: number, r: number, g: number, b: number, a: number, thickness: number) => voiddraw_line: (fromX: number, fromY: number, toX: number, toY: number, r: number, g: number, b: number, a: number, thickness: number) => voiddraw_mesh: (geometryHandle: number, shaderHandle: number, transformPtr: number) => voiddraw_meshWithMaterial: (geometryHandle: number, materialId: number) => booleandiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 15036da94..cf9221d77 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1,7 +1,7 @@# API surface — esengine/wechat<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 113 public · 66 beta · 1454 experimental · 3 deprecated+Symbols: 113 public · 66 beta · 1457 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -2635,6 +2635,7 @@ drawMeshWithMaterial: (geometry: GeometryHandle, material: MaterialHandle, transend: () => voidgetDrawCallCount: () => numbergetPrimitiveCount: () => number+line3D: (from: Vec3, to: Vec3, color: Color, thickness?: number) => voidline: (from: Vec2, to: Vec2, color: Color, thickness?: number) => voidrect: (position: Vec2, size: Vec2, color: Color, filled?: boolean) => voidrectOutline: (position: Vec2, size: Vec2, color: Color, thickness?: number) => void@@ -5001,6 +5002,18 @@ ComponentDef<{}>ResourceDef<PhysicsAPI>```+## Physics3DDebugDraw — const @experimental+```+ResourceDef<Physics3DDebugDrawConfig>+```++## Physics3DDebugDrawConfig — interface @experimental+```+enabled: boolean+showColliders: boolean+showContacts: boolean+```+## PhysicsContactEventData — interface @experimental```approachSpeed: number | undefined@@ -9840,6 +9853,11 @@ DragPlugin() => DragonBonesPlugin```+## drawPhysics3DDebug — function @experimental+```+(app: App, contacts?: readonly Contact3D[]): void+```+## editorViewAxes — function @experimental```(view: EditorViewData): { x: ScreenAxis; y: ScreenAxis; z: ScreenAxis; }diff --git a/sdk/src/core-runtime.ts b/sdk/src/core-runtime.tsindex 7b9d7d882..09948a244 100644--- a/sdk/src/core-runtime.ts+++ b/sdk/src/core-runtime.ts@@ -217,6 +217,12 @@ export {type Joint3DShape,} from './physics3d/Physics3DJoints';+export {+ Physics3DDebugDraw,+ drawPhysics3DDebug,+ type Physics3DDebugDrawConfig,+} from './physics3d/Physics3DDebugDraw';+export {readCollider3DShapes,collider3DWireframe,diff --git a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts b/sdk/src/ecs/bridge/nativeEngineApi.generated.tsindex 69b644a6c..805dd025f 100644--- a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts+++ b/sdk/src/ecs/bridge/nativeEngineApi.generated.ts@@ -30,6 +30,7 @@ export interface NativeEngineApi {draw_getDrawCallCount?(): number;draw_getPrimitiveCount?(): number;draw_line?(fromX: number, fromY: number, toX: number, toY: number, r: number, g: number, b: number, a: number, thickness: number): void;+ draw_line3D?(fromX: number, fromY: number, fromZ: number, toX: number, toY: number, toZ: number, r: number, g: number, b: number, a: number, thickness: number): void;draw_mesh?(geometryHandle: number, shaderHandle: number, transformPtr: number): void;draw_meshWithMaterial?(geometryHandle: number, materialId: number): boolean;draw_meshWithUniforms?(geometryHandle: number, shaderHandle: number, transformPtr: number, uniformsPtr: number, uniformCount: number): void;@@ -282,6 +283,7 @@ export function createNativeEngineApi(bind('draw_getDrawCallCount', 'es_draw_getDrawCallCount', false);bind('draw_getPrimitiveCount', 'es_draw_getPrimitiveCount', false);bind('draw_line', 'es_draw_line', false);+ bind('draw_line3D', 'es_draw_line3D', false);bind('draw_mesh', 'es_draw_mesh', false);bind('draw_meshWithMaterial', 'es_draw_meshWithMaterial', false);bind('draw_meshWithUniforms', 'es_draw_meshWithUniforms', false);diff --git a/sdk/src/physics3d/Physics3DDebugDraw.ts b/sdk/src/physics3d/Physics3DDebugDraw.tsnew file mode 100644index 000000000..52931e3ce--- /dev/null+++ b/sdk/src/physics3d/Physics3DDebugDraw.ts@@ -0,0 +1,117 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Physics3DDebugDraw.ts+ * @brief The 3D world's shapes, drawn by the running game.+ * @details The editor gizmo answers "is this box the size I meant" while a scene+ * is being authored. This answers the other question — "why did the+ * player get stuck there" — which only the running game can be asked,+ * and which the editor hides its own overlays for.+ *+ * Geometry comes from the same seam the gizmo projects+ * ({@link readCollider3DShapes}), so the two can never disagree about+ * which shape the solver built.+ */+import type { App } from '../app/app';+import type { Color } from '../types';+import { Transform } from '../ecs/component';+import type { TransformData } from '../ecs/component.generated';+import { Draw } from '../render/draw';+import { defineResource } from '../ecs/resource';+import { registerDrawCallback } from '../render/customDraw';+import { RigidBody3D, CharacterController3D } from './Physics3DComponents';+import type { RigidBody3DData } from './Physics3DComponents';+import {+ readCollider3DShapes, collider3DWireframe, placeCollider3DWireframe,+} from './ColliderShape3D';++export interface Physics3DDebugDrawConfig {+ enabled: boolean;+ showColliders: boolean;+ showContacts: boolean;+}++/** Off until a game turns it on: a debug overlay costs a line per edge per frame. */+export const Physics3DDebugDraw = defineResource<Physics3DDebugDrawConfig>({+ enabled: false,+ showColliders: true,+ showContacts: false,+}, 'Physics3DDebugDraw');++const STATIC_COLOR: Color = { r: 0.2, g: 0.4, b: 1.0, a: 0.8 };+const DYNAMIC_COLOR: Color = { r: 0.2, g: 1.0, b: 0.2, a: 0.8 };+const KINEMATIC_COLOR: Color = { r: 0.2, g: 1.0, b: 1.0, a: 0.8 };+const SENSOR_COLOR: Color = { r: 1.0, g: 1.0, b: 0.2, a: 0.6 };+const CHARACTER_COLOR: Color = { r: 1.0, g: 0.6, b: 0.1, a: 0.9 };+const CONTACT_COLOR: Color = { r: 1.0, g: 0.2, b: 0.2, a: 1.0 };+/** World units. The 3D world is authored at 100 units to the metre, so this is+ * about a centimetre — thin enough not to hide the shape it outlines. */+const LINE_THICKNESS = 2;+const CONTACT_CROSS = 8;++function bodyTypeColor(bodyType: number): Color {+ switch (bodyType) {+ case 0: return STATIC_COLOR;+ case 1: return KINEMATIC_COLOR;+ default: return DYNAMIC_COLOR;+ }+}++interface Contact3D { pointX: number; pointY: number; pointZ: number }++export function drawPhysics3DDebug(app: App, contacts?: readonly Contact3D[]): void {+ const config = app.getResource<Physics3DDebugDrawConfig>(Physics3DDebugDraw);+ if (!config || !config.enabled) return;++ if (config.showColliders) {+ const world = app.world as unknown as Parameters<typeof readCollider3DShapes>[0];+ for (const entity of app.world.getEntitiesWithComponents([Transform])) {+ const instances = readCollider3DShapes(world, entity as number);+ if (instances.length === 0) continue;+ const t = app.world.get(entity, Transform) as TransformData;+ const body = app.world.has(entity, RigidBody3D)+ ? app.world.get(entity, RigidBody3D) as RigidBody3DData : null;++ for (const inst of instances) {+ // What the solver did NOT build is not drawn here: the running+ // game is not the place to see geometry that collides with+ // nothing, and the editor already shows it while it is authored.+ if (!inst.active) continue;+ const color = inst.component === 'CharacterController3D' ? CHARACTER_COLOR+ : inst.isSensor ? SENSOR_COLOR+ : bodyTypeColor(body?.bodyType ?? 2);+ const lines = placeCollider3DWireframe(+ collider3DWireframe(inst.shape),+ t.worldPosition, t.worldRotation);+ for (const line of lines) {+ for (let i = 0; i + 1 < line.length; i++) {+ Draw.line3D(line[i]!, line[i + 1]!, color, LINE_THICKNESS);+ }+ }+ }+ }+ }++ if (config.showContacts && contacts) {+ for (const c of contacts) {+ const at = { x: c.pointX, y: c.pointY, z: c.pointZ };+ for (const axis of [{ x: CONTACT_CROSS, y: 0, z: 0 },+ { x: 0, y: CONTACT_CROSS, z: 0 },+ { x: 0, y: 0, z: CONTACT_CROSS }]) {+ Draw.line3D({ x: at.x - axis.x, y: at.y - axis.y, z: at.z - axis.z },+ { x: at.x + axis.x, y: at.y + axis.y, z: at.z + axis.z },+ CONTACT_COLOR, LINE_THICKNESS);+ }+ }+ }+}++/** Installed by the 3D physics plugin; the resource decides whether it draws. */+export function setupPhysics3DDebugDraw(app: App, contacts: () => readonly Contact3D[]): void {+ app.insertResource(Physics3DDebugDraw, {+ enabled: false, showColliders: true, showContacts: false,+ });+ registerDrawCallback('physics3d-debug-draw', () => {+ drawPhysics3DDebug(app, contacts());+ });+}diff --git a/sdk/src/physics3d/Physics3DPlugin.ts b/sdk/src/physics3d/Physics3DPlugin.tsindex bce917259..6b3c49d1b 100644--- a/sdk/src/physics3d/Physics3DPlugin.ts+++ b/sdk/src/physics3d/Physics3DPlugin.ts@@ -16,6 +16,7 @@ import {stepPhysics3D, DEFAULT_PHYSICS3D_CONFIG, type Physics3DConfig,} from './Physics3DSystem';import { Physics3DQueries } from './Physics3DQueries';+import { setupPhysics3DDebugDraw } from './Physics3DDebugDraw';import type { Joint3DMap } from './Physics3DJoints';/** Ask the 3D world what is where. Present once the module has loaded. */@@ -81,6 +82,9 @@ export class Physics3DPlugin implements Plugin {stepPhysics3D(app, module, runtime.bodies, this.config_,runtime.characters, events, runtime.joints);}));+ // Installed with the world, drawn only once a game turns the resource+ // on — a scene that never asks for it pays a resource and nothing else.+ setupPhysics3DDebugDraw(app, () => events.contactEnters);app.setFixedTimestep?.(this.config_.fixedTimestep);app.subsystems?.transition?.('physics3d', 'ready');});diff --git a/sdk/src/render/draw.ts b/sdk/src/render/draw.tsindex 48e2c28b7..a8f0ce36f 100644--- a/sdk/src/render/draw.ts+++ b/sdk/src/render/draw.ts@@ -8,7 +8,7 @@*/import type { ESEngineModule } from '../wasm';-import type { Vec2, Color } from '../types';+import type { Vec2, Vec3, Color } from '../types';import type { GeometryHandle } from './geometry';import type { ShaderHandle, MaterialHandle } from './material';import { Material, isTextureRef, classifyUniformArity, type UniformValue, type TextureRef } from './material';@@ -93,6 +93,15 @@ export interface DrawAPI {*/line(from: Vec2, to: Vec2, color: Color, thickness?: number): void;+ /**+ * Draws a line between two points in space.+ *+ * The ribbon is widened across the view, so it reads as a line from wherever+ * the camera is. Thickness is in WORLD units rather than pixels — a distant+ * line thins out the way the geometry beside it does.+ */+ line3D(from: Vec3, to: Vec3, color: Color, thickness?: number): void;+/*** Draws a filled or outlined rectangle.* @param position Center position@@ -254,6 +263,19 @@ export const Draw: DrawAPI = {}},+ line3D(from: Vec3, to: Vec3, color: Color, thickness = 1): void {+ try {+ getModule().draw_line3D(+ from.x, from.y, from.z,+ to.x, to.y, to.z,+ color.r, color.g, color.b, color.a,+ thickness+ );+ } catch (e) {+ handleWasmError(e, 'Draw.line3D');+ }+ },+rect(position: Vec2, size: Vec2, color: Color, filled = true): void {try {getModule().draw_rect(diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.tsindex 80ef7f990..235d060f3 100644--- a/sdk/src/wasm.ts+++ b/sdk/src/wasm.ts@@ -351,6 +351,9 @@ export interface ESEngineModule {draw_end(): void;draw_line(fromX: number, fromY: number, toX: number, toY: number,r: number, g: number, b: number, a: number, thickness: number): void;+ draw_line3D(fromX: number, fromY: number, fromZ: number,+ toX: number, toY: number, toZ: number,+ r: number, g: number, b: number, a: number, thickness: number): void;draw_rect(x: number, y: number, width: number, height: number,r: number, g: number, b: number, a: number, filled: boolean): void;draw_rectOutline(x: number, y: number, width: number, height: number,diff --git a/src/esengine/bindings/ImmediateDrawBindings.cpp b/src/esengine/bindings/ImmediateDrawBindings.cppindex edacc2621..5d93c5b53 100644--- a/src/esengine/bindings/ImmediateDrawBindings.cpp+++ b/src/esengine/bindings/ImmediateDrawBindings.cpp@@ -65,6 +65,18 @@ void draw_line(f32 fromX, f32 fromY, f32 toX, f32 toY,);}+void draw_line3D(f32 fromX, f32 fromY, f32 fromZ, f32 toX, f32 toY, f32 toZ,+ f32 r, f32 g, f32 b, f32 a, f32 thickness) {+ if (!g_immediateDraw || !g_immediateDrawActive) return;++ g_immediateDraw->line3D(+ glm::vec3(fromX, fromY, fromZ),+ glm::vec3(toX, toY, toZ),+ glm::vec4(r, g, b, a),+ thickness+ );+}+void draw_rect(f32 x, f32 y, f32 width, f32 height,f32 r, f32 g, f32 b, f32 a, bool filled) {if (!g_immediateDraw || !g_immediateDrawActive) return;diff --git a/src/esengine/bindings/ImmediateDrawBindings.hpp b/src/esengine/bindings/ImmediateDrawBindings.hppindex ab1c24e21..7aa1d3db3 100644--- a/src/esengine/bindings/ImmediateDrawBindings.hpp+++ b/src/esengine/bindings/ImmediateDrawBindings.hpp@@ -11,6 +11,8 @@ void draw_begin(uintptr_t matrixPtr);void draw_end();void draw_line(f32 fromX, f32 fromY, f32 toX, f32 toY,f32 r, f32 g, f32 b, f32 a, f32 thickness);+void draw_line3D(f32 fromX, f32 fromY, f32 fromZ, f32 toX, f32 toY, f32 toZ,+ f32 r, f32 g, f32 b, f32 a, f32 thickness);void draw_rect(f32 x, f32 y, f32 width, f32 height,f32 r, f32 g, f32 b, f32 a, bool filled);void draw_rectOutline(f32 x, f32 y, f32 width, f32 height,diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cppindex ead84c1ec..a5086b3a5 100644--- a/src/esengine/bindings/WebSDKEntry.cpp+++ b/src/esengine/bindings/WebSDKEntry.cpp@@ -546,6 +546,7 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {emscripten::function("draw_begin", &esengine::draw_begin);emscripten::function("draw_end", &esengine::draw_end);emscripten::function("draw_line", &esengine::draw_line);+ emscripten::function("draw_line3D", &esengine::draw_line3D);emscripten::function("draw_rect", &esengine::draw_rect);emscripten::function("draw_rectOutline", &esengine::draw_rectOutline);emscripten::function("draw_circle", &esengine::draw_circle);diff --git a/src/esengine/renderer/draw/ImmediateDraw.cpp b/src/esengine/renderer/draw/ImmediateDraw.cppindex d8ea7264a..43cb01a70 100644--- a/src/esengine/renderer/draw/ImmediateDraw.cpp+++ b/src/esengine/renderer/draw/ImmediateDraw.cpp@@ -133,6 +133,14 @@ void ImmediateDraw::begin(const glm::mat4& viewProjection) {// A prior phase may have left another pipeline bound; force our pipeline to re-apply.device_.invalidatePipelineCache();+ // Near-centre to far-centre through the inverse: one direction that works for+ // both projections, where a perspective camera's own position does not.+ const glm::mat4 inverseVP = glm::inverse(viewProjection);+ const glm::vec4 nearPoint = inverseVP * glm::vec4(0.0f, 0.0f, -1.0f, 1.0f);+ const glm::vec4 farPoint = inverseVP * glm::vec4(0.0f, 0.0f, 1.0f, 1.0f);+ const glm::vec3 forward = glm::vec3(farPoint) / farPoint.w - glm::vec3(nearPoint) / nearPoint.w;+ if (glm::length(forward) > 0.0001f) viewForward_ = glm::normalize(forward);+pool_.beginFrame();currentTexture_ = white_texture_id_;pendingGeometry_ = false;@@ -255,6 +263,42 @@ void ImmediateDraw::line(const glm::vec2& from, const glm::vec2& to,++primitiveCount_;}+void ImmediateDraw::line3D(const glm::vec3& from, const glm::vec3& to,+ const glm::vec4& color, f32 thickness) {+ if (!inFrame_) return;++ const glm::vec3 delta = to - from;+ const f32 length = glm::length(delta);+ if (length < 0.0001f) return;+ const glm::vec3 dir = delta / length;++ glm::vec3 side = glm::cross(dir, viewForward_);+ f32 sideLength = glm::length(side);+ if (sideLength < 0.0001f) {+ // Looking straight down the line: any perpendicular reads the same.+ side = glm::cross(dir, std::abs(dir.y) < 0.9f ? glm::vec3(0.0f, 1.0f, 0.0f)+ : glm::vec3(1.0f, 0.0f, 0.0f));+ sideLength = glm::length(side);+ if (sideLength < 0.0001f) return;+ }+ side *= (thickness * 0.5f) / sideLength;++ useTexture(white_texture_id_);+ const u32 packed = packColor(color);+ const std::array<BatchVertex, 4> verts{+ BatchVertex{ from - side, packed, {0.0f, 0.0f} },+ BatchVertex{ from + side, packed, {1.0f, 0.0f} },+ BatchVertex{ to + side, packed, {1.0f, 1.0f} },+ BatchVertex{ to - side, packed, {0.0f, 1.0f} },+ };+ const u32 base =+ pool_.appendVertices(LayoutId::Batch, verts.data(), sizeof(verts)) / sizeof(BatchVertex);+ const u32 idx[6] = { base + 0, base + 1, base + 2, base + 2, base + 3, base + 0 };+ pool_.appendIndices(LayoutId::Batch, idx, 6);+ pendingGeometry_ = true;+ ++primitiveCount_;+}+void ImmediateDraw::polyline(std::span<const glm::vec2> vertices,const glm::vec4& color, f32 thickness, bool closed) {if (!inFrame_ || vertices.size() < 2) return;diff --git a/src/esengine/renderer/draw/ImmediateDraw.hpp b/src/esengine/renderer/draw/ImmediateDraw.hppindex f916a140f..4832417b7 100644--- a/src/esengine/renderer/draw/ImmediateDraw.hpp+++ b/src/esengine/renderer/draw/ImmediateDraw.hpp@@ -105,6 +105,16 @@ public:void line(const glm::vec2& from, const glm::vec2& to,const glm::vec4& color, f32 thickness = 1.0f);+ /**+ * @brief A line between two points in SPACE, widened across the view.+ * @details Widened along `cross(direction, view forward)` rather than in a+ * plane, so it reads as a line from wherever the camera is.+ * Thickness is in WORLD units, so a distant line thins out with the+ * geometry beside it.+ */+ void line3D(const glm::vec3& from, const glm::vec3& to,+ const glm::vec4& color, f32 thickness = 1.0f);+void polyline(std::span<const glm::vec2> vertices, const glm::vec4& color,f32 thickness = 1.0f, bool closed = false);@@ -196,6 +206,10 @@ private:u32 currentTexture_ = 0;bool pendingGeometry_ = false;+ /// Where the camera looks, from the view-projection this frame began with —+ /// what a 3D line is widened across.+ glm::vec3 viewForward_{0.0f, 0.0f, -1.0f};+i32 currentLayer_ = 0;f32 currentDepth_ = 0.0f;u32 primitiveCount_ = 0;