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): thread the full world config from Project Settings
esengine544535dc213d
diff --git a/desktop/src/engine/PlayRealm.ts b/desktop/src/engine/PlayRealm.tsindex edef468ff..753b86a5e 100644--- a/desktop/src/engine/PlayRealm.ts+++ b/desktop/src/engine/PlayRealm.ts@@ -12,14 +12,15 @@* touched, so there is nothing to restore.*/import { createStore } from 'zustand/vanilla';-import type { SceneData } from 'esengine';+import type { SceneData, PhysicsPluginConfig } from 'esengine';export interface PlayPayload {sceneData: SceneData;assetManifest: Record<string, string>;/** Project-declared physics enable (features.physics) — forwarded to the realm. */physicsEnabled?: boolean;- physicsGravity?: { x: number; y: number };+ /** Project physics world config (gravity, solver, collision matrix) — forwarded to the realm. */+ physicsConfig?: PhysicsPluginConfig;}export interface PlayRealmSnapshot {diff --git a/desktop/src/playHost.ts b/desktop/src/playHost.tsindex 48d8340f5..a0b646edd 100644--- a/desktop/src/playHost.ts+++ b/desktop/src/playHost.ts@@ -15,7 +15,7 @@* sidestepping the custom-scheme cross-fetch ban.*/import { createWebApp, setEditorMode, setPlayMode, initPlayRealmRuntime, getComponent, clearUserComponents } from 'esengine';-import type { App, ESEngineModule, SceneData } from 'esengine';+import type { App, ESEngineModule, SceneData, PhysicsPluginConfig } from 'esengine';type LiveEntity = SceneData['entities'][number];@@ -80,7 +80,7 @@ interface InitMessage {sceneData: SceneData;assetManifest: Record<string, string>;physicsEnabled?: boolean;- physicsGravity?: { x: number; y: number };+ physicsConfig?: PhysicsPluginConfig;}const canvas = document.getElementById('canvas') as HTMLCanvasElement;@@ -157,7 +157,7 @@ async function buildAppAndRun(msg: InitMessage): Promise<void> {// physics.wasm is served next to esengine.wasm; load it on demand.wasmBaseUrl: wasmBase.replace(/\/$/, ''),physicsEnabled: msg.physicsEnabled,- physicsGravity: msg.physicsGravity,+ physicsConfig: msg.physicsConfig,enableStats: true, // editor profiler: per-phase / per-system frame timing});}diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.tsindex 40a0e3fad..20c48cdb7 100644--- a/desktop/src/project/ProjectStore.ts+++ b/desktop/src/project/ProjectStore.ts@@ -2,7 +2,7 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport { createStore } from 'zustand/vanilla';import { getComponent, Assets, migratePrefabData, extractPrefab } from 'esengine';-import type { SceneData, PrefabData, ExtractEntity } from 'esengine';+import type { SceneData, PrefabData, ExtractEntity, PhysicsPluginConfig } from 'esengine';import { EngineHost } from '@/engine/EngineHost';import { SceneModel } from '@/engine/SceneModel';import { Reconciler } from '@/engine/Reconciler';@@ -22,6 +22,11 @@ function normalizeLayers(layers?: string[]): string[] {return Array.from({ length: 16 }, (_, i) => layers?.[i] ?? (i === 0 ? 'Default' : ''));}+/** Pad/truncate the collision matrix to 16 rows; absent rows default to all-collide. */+function normalizeLayerMasks(masks?: number[]): number[] {+ return Array.from({ length: 16 }, (_, i) => (typeof masks?.[i] === 'number' ? masks[i] & 0xffff : 0xffff));+}+/** Whether an asset of the editor `type` is a valid pick for a `fieldType` slot. */function assetMatchesSlot(type: AssetType, fieldType?: string): boolean {if (!fieldType) return true;@@ -508,7 +513,7 @@ class ProjectStoreImpl {sceneData: SceneData;assetManifest: Record<string, string>;physicsEnabled?: boolean;- physicsGravity?: { x: number; y: number };+ physicsConfig?: PhysicsPluginConfig;} | null {const sceneData = SceneModel.serialize();if (!sceneData) return null;@@ -516,19 +521,48 @@ class ProjectStoreImpl {// same-origin estella:// — no cross-scheme dance needed.const assetManifest: Record<string, string> = {};for (const [uuid, path] of this.uuidToPath) assetManifest[uuid] = `estella://project/${path}`;- // Carry the project's declared physics enable so the realm installs physics- // even for runtime-spawned bodies the static scene doesn't show.- const physics = this.state?.features?.physics;- return { sceneData, assetManifest, physicsEnabled: physics?.enabled, physicsGravity: physics?.gravity };- }-- /** The project's declared physics feature, with defaults (for Project Settings). */- physicsFeature(): { enabled: boolean; gravity: { x: number; y: number }; collisionLayers: string[] } {+ // Carry the project's physics world config so the realm installs physics (even for+ // runtime-spawned bodies the static scene doesn't show) and matches the editor's+ // Project Settings. The collision matrix is sent ONLY when configured — otherwise+ // a layer's mask would override each collider's own maskBits (the two are exclusive).+ const f = this.physicsFeature();+ const raw = this.state?.features?.physics;+ const physicsConfig: PhysicsPluginConfig = {+ gravity: f.gravity,+ fixedTimestep: f.fixedTimestep,+ subStepCount: f.subStepCount,+ contactHertz: f.contactHertz,+ contactDampingRatio: f.contactDampingRatio,+ contactSpeed: f.contactSpeed,+ enableSleep: f.enableSleep,+ enableContinuous: f.enableContinuous,+ };+ if (raw?.collisionLayerMasks) physicsConfig.collisionLayerMasks = f.collisionLayerMasks;+ return { sceneData, assetManifest, physicsEnabled: f.enabled, physicsConfig };+ }++ /** The project's declared physics feature, with defaults (for Project Settings). The+ * solver defaults mirror the runtime fallbacks so the UI shows the effective values. */+ physicsFeature(): {+ enabled: boolean; gravity: { x: number; y: number }; collisionLayers: string[];+ collisionLayerMasks: number[];+ fixedTimestep: number; subStepCount: number; contactHertz: number;+ contactDampingRatio: number; contactSpeed: number;+ enableSleep: boolean; enableContinuous: boolean;+ } {const p = this.state?.features?.physics;return {enabled: p?.enabled ?? false,gravity: p?.gravity ?? { x: 0, y: -9.81 },collisionLayers: normalizeLayers(p?.collisionLayers),+ collisionLayerMasks: normalizeLayerMasks(p?.collisionLayerMasks),+ fixedTimestep: p?.fixedTimestep ?? 1 / 60,+ subStepCount: p?.subStepCount ?? 4,+ contactHertz: p?.contactHertz ?? 120,+ contactDampingRatio: p?.contactDampingRatio ?? 10,+ contactSpeed: p?.contactSpeed ?? 10,+ enableSleep: p?.enableSleep ?? true,+ enableContinuous: p?.enableContinuous ?? true,};}@@ -628,7 +662,7 @@ class ProjectStoreImpl {* parser doesn't model survive; in-memory state updates first so the toggle* reflects immediately.*/- async setPhysics(patch: { enabled?: boolean; gravity?: { x: number; y: number }; collisionLayers?: string[] }): Promise<void> {+ async setPhysics(patch: Partial<NonNullable<ProjectFeatures['physics']>>): Promise<void> {const st = this.state;if (!st) return;const physics: NonNullable<ProjectFeatures['physics']> = { ...st.features?.physics, ...patch };diff --git a/desktop/src/project/format.ts b/desktop/src/project/format.tsindex 40b12dcde..e079d772a 100644--- a/desktop/src/project/format.ts+++ b/desktop/src/project/format.ts@@ -69,6 +69,17 @@ export interface ProjectFeatures {gravity?: { x: number; y: number };/** Names for the 16 Box2D collision-filter layers (the inspector's layer masks). */collisionLayers?: string[];+ /** Per-layer collision masks (the UE/Unity collision matrix): masks[i] bit j set ⇒+ * layer i collides with layer j. 16 entries; absent ⇒ all-collide. */+ collisionLayerMasks?: number[];+ /** World solver tuning (Project Settings → Physics); absent ⇒ engine defaults. */+ fixedTimestep?: number;+ subStepCount?: number;+ contactHertz?: number;+ contactDampingRatio?: number;+ contactSpeed?: number;+ enableSleep?: boolean;+ enableContinuous?: boolean;};rendering?: {/** Named render sorting layers (the inspector's `layer` dropdown); index = z-order. */@@ -219,6 +230,15 @@ export function parseManifest(raw: unknown): ProjectManifest {if (Array.isArray(p.collisionLayers)) {physics.collisionLayers = p.collisionLayers.slice(0, 16).map((n) => (typeof n === 'string' ? n : ''));}+ if (Array.isArray(p.collisionLayerMasks)) {+ physics.collisionLayerMasks = p.collisionLayerMasks.slice(0, 16)+ .map((n) => (typeof n === 'number' && Number.isFinite(n) ? n & 0xffff : 0xffff));+ }+ for (const k of ['fixedTimestep', 'subStepCount', 'contactHertz', 'contactDampingRatio', 'contactSpeed'] as const) {+ if (typeof p[k] === 'number' && Number.isFinite(p[k] as number)) physics[k] = p[k] as number;+ }+ if (typeof p.enableSleep === 'boolean') physics.enableSleep = p.enableSleep;+ if (typeof p.enableContinuous === 'boolean') physics.enableContinuous = p.enableContinuous;features.physics = physics;}if (f.rendering && typeof f.rendering === 'object') {diff --git a/desktop/src/settings/projectSettings.ts b/desktop/src/settings/projectSettings.tsindex d28dd75df..9c8388548 100644--- a/desktop/src/settings/projectSettings.ts+++ b/desktop/src/settings/projectSettings.ts@@ -156,3 +156,82 @@ settingsRegistry.register({set: (v) => void ProjectStore.setPhysics({ gravity: { ...ProjectStore.physicsFeature().gravity, y: v } }),},});++// ── Solver (world simulation tuning; absent ⇒ engine defaults) ──+settingsRegistry.register({+ id: 'project.physics.fixedTimestep',+ type: 'number', scope: 'project', section: 'physics', group: 'Solver',+ label: 'Fixed timestep', suffix: 's',+ description: 'Simulation step size; smaller is more accurate but costlier. Default 1/60.',+ default: 1 / 60, min: 0.001, step: 0.001,+ bind: {+ get: () => ProjectStore.physicsFeature().fixedTimestep,+ set: (v) => void ProjectStore.setPhysics({ fixedTimestep: v }),+ },+});+settingsRegistry.register({+ id: 'project.physics.subStepCount',+ type: 'number', scope: 'project', section: 'physics', group: 'Solver',+ label: 'Sub-steps',+ description: 'Solver sub-steps per step — higher firms up stacks/joints at more cost. Default 4.',+ default: 4, min: 1, max: 8, step: 1,+ bind: {+ get: () => ProjectStore.physicsFeature().subStepCount,+ set: (v) => void ProjectStore.setPhysics({ subStepCount: Math.round(v) }),+ },+});+settingsRegistry.register({+ id: 'project.physics.contactHertz',+ type: 'number', scope: 'project', section: 'physics', group: 'Solver',+ label: 'Contact Hz',+ description: 'Contact stiffness frequency. Default 120.',+ default: 120, min: 1, step: 1,+ bind: {+ get: () => ProjectStore.physicsFeature().contactHertz,+ set: (v) => void ProjectStore.setPhysics({ contactHertz: v }),+ },+});+settingsRegistry.register({+ id: 'project.physics.contactDampingRatio',+ type: 'number', scope: 'project', section: 'physics', group: 'Solver',+ label: 'Contact damping',+ description: 'Contact damping ratio. Default 10.',+ default: 10, min: 0, step: 0.5,+ bind: {+ get: () => ProjectStore.physicsFeature().contactDampingRatio,+ set: (v) => void ProjectStore.setPhysics({ contactDampingRatio: v }),+ },+});+settingsRegistry.register({+ id: 'project.physics.contactSpeed',+ type: 'number', scope: 'project', section: 'physics', group: 'Solver',+ label: 'Contact push speed', suffix: 'm/s',+ description: 'Max speed used to resolve overlap. Default 10.',+ default: 10, min: 0, step: 0.5,+ bind: {+ get: () => ProjectStore.physicsFeature().contactSpeed,+ set: (v) => void ProjectStore.setPhysics({ contactSpeed: v }),+ },+});+settingsRegistry.register({+ id: 'project.physics.enableSleep',+ type: 'boolean', scope: 'project', section: 'physics', group: 'Solver',+ label: 'Allow sleeping',+ description: 'Let resting bodies sleep to save CPU (Box2D default on).',+ default: true,+ bind: {+ get: () => ProjectStore.physicsFeature().enableSleep,+ set: (v) => void ProjectStore.setPhysics({ enableSleep: v }),+ },+});+settingsRegistry.register({+ id: 'project.physics.enableContinuous',+ type: 'boolean', scope: 'project', section: 'physics', group: 'Solver',+ label: 'Continuous collision',+ description: 'Anti-tunneling for fast bodies (Box2D default on).',+ default: true,+ bind: {+ get: () => ProjectStore.physicsFeature().enableContinuous,+ set: (v) => void ProjectStore.setPhysics({ enableContinuous: v }),+ },+});diff --git a/desktop/tests/project-physics.test.ts b/desktop/tests/project-physics.test.tsnew file mode 100644index 000000000..57079f584--- /dev/null+++ b/desktop/tests/project-physics.test.ts@@ -0,0 +1,60 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file parseManifest — physics world config (Project Settings → Physics). Guards that+ * the solver tuning + collision matrix round-trip through project.esproject and+ * that invalid values are dropped/clamped.+ */+import { describe, it, expect } from 'vitest';+import { parseManifest } from '../src/project/format';++describe('parseManifest — physics', () => {+ it('parses the full physics world config', () => {+ const m = parseManifest({+ name: 'X',+ features: {+ physics: {+ enabled: true,+ gravity: { x: 0, y: -20 },+ collisionLayers: ['Default', 'Player'],+ collisionLayerMasks: [0xffff, 0x0005],+ fixedTimestep: 0.02,+ subStepCount: 6,+ contactHertz: 60,+ contactDampingRatio: 5,+ contactSpeed: 8,+ enableSleep: false,+ enableContinuous: false,+ },+ },+ });+ expect(m.features?.physics).toMatchObject({+ enabled: true,+ gravity: { x: 0, y: -20 },+ collisionLayerMasks: [0xffff, 0x0005],+ fixedTimestep: 0.02,+ subStepCount: 6,+ contactHertz: 60,+ contactDampingRatio: 5,+ contactSpeed: 8,+ enableSleep: false,+ enableContinuous: false,+ });+ expect(m.features?.physics?.collisionLayers?.slice(0, 2)).toEqual(['Default', 'Player']);+ });++ it('drops non-numeric solver values and masks bad matrix rows to all-collide', () => {+ const m = parseManifest({+ name: 'X',+ features: { physics: { fixedTimestep: 'fast', contactHertz: 90, collisionLayerMasks: [3, 'x', 7] } },+ });+ const p = m.features?.physics;+ expect(p?.fixedTimestep).toBeUndefined(); // invalid → dropped (runtime default applies)+ expect(p?.contactHertz).toBe(90);+ expect(p?.collisionLayerMasks).toEqual([3, 0xffff, 7]); // bad row → all-collide+ });++ it('omits physics when absent', () => {+ expect(parseManifest({ name: 'X' }).features?.physics).toBeUndefined();+ });+});diff --git a/sdk/src/playRealmRuntime.ts b/sdk/src/playRealmRuntime.tsindex 7f2d332cc..d2dacaa83 100644--- a/sdk/src/playRealmRuntime.ts+++ b/sdk/src/playRealmRuntime.ts@@ -21,7 +21,7 @@ import { initRuntime } from './runtimeLoader';import type { RuntimeAssetProvider } from './runtimeLoader';import type { AddressableManifest } from './asset/AddressableManifest';import type { SceneData } from './scene';-import type { Vec2 } from './types';+import type { PhysicsPluginConfig } from './physics/PhysicsPlugin';import { decodeImagePixels } from './asset/imageDecode';const UUID_PREFIX = '@uuid:';@@ -41,8 +41,9 @@ export interface PlayRealmRuntimeConfig {/** Project-declared physics enable (`.uproject` features analog) — installs* physics even for runtime-spawned bodies the static scene doesn't show. */physicsEnabled?: boolean;- /** Optional physics world overrides (e.g. project-declared gravity). */- physicsGravity?: Vec2;+ /** Project-declared physics world config (gravity, solver tuning, collision-layer+ * masks, sleep/continuous) from the editor's Project Settings. */+ physicsConfig?: PhysicsPluginConfig;/** Turn on per-phase / per-system frame timing (editor profiler; off in shipped games). */enableStats?: boolean;}@@ -98,7 +99,7 @@ export async function initPlayRealmRuntime(config: PlayRealmRuntimeConfig): Prommanifest: manifest ?? null,aspectRatio: canvas.width / canvas.height,physicsEnabled: config.physicsEnabled,- physicsConfig: config.physicsGravity ? { gravity: config.physicsGravity } : undefined,+ physicsConfig: config.physicsConfig,// Physics (and spine) are acquired from app.sideModules — the fetch host// createWebApp built from this realm's wasmBaseUrl.});diff --git a/sdk/src/runtimeLoader.ts b/sdk/src/runtimeLoader.tsindex 30b52cc61..8c43b31dd 100644--- a/sdk/src/runtimeLoader.ts+++ b/sdk/src/runtimeLoader.ts@@ -16,7 +16,6 @@ import type { PhysicsWasmModule } from './physics/PhysicsModuleLoader';import { PhysicsPlugin, type PhysicsPluginConfig } from './physics/PhysicsPlugin';import { SpinePlugin } from './spine/SpinePlugin';import type { App } from './app';-import type { Vec2 } from './types';import type { AddressableManifest } from './asset/AddressableManifest';import { Assets } from './asset/AssetPlugin';import { getAssetTypeEntry } from './assetTypes';@@ -320,7 +319,9 @@ export interface LoadRuntimeSceneOptions {spineModule?: SpineWasmModule | null;spineManager?: SpineManager | null;physicsModule?: PhysicsWasmModule | null;- physicsConfig?: { gravity?: Vec2; fixedTimestep?: number; subStepCount?: number; contactHertz?: number; contactDampingRatio?: number; contactSpeed?: number };+ /** Project-declared physics world config (gravity, solver tuning, collision-layer+ * masks, sleep/continuous toggles) — threaded from the editor's Project Settings. */+ physicsConfig?: PhysicsPluginConfig;/** Project-declared physics enable (`.uproject` features analog) — installs* physics even for runtime-spawned bodies the static scene doesn't show.* OR-combined with a content scan. */@@ -391,6 +392,11 @@ export async function loadRuntimeScene(options: LoadRuntimeSceneOptions): PromiscontactDampingRatio: physicsConfig?.contactDampingRatio ?? 10,contactSpeed: physicsConfig?.contactSpeed ?? 10,};+ // Pass through the remaining world config only when the project set it, so+ // the plugin's own defaults still apply otherwise.+ if (physicsConfig?.collisionLayerMasks) config.collisionLayerMasks = physicsConfig.collisionLayerMasks;+ if (physicsConfig?.enableSleep !== undefined) config.enableSleep = physicsConfig.enableSleep;+ if (physicsConfig?.enableContinuous !== undefined) config.enableContinuous = physicsConfig.enableContinuous;const mod = physicsModule;app.addPlugin(new PhysicsPlugin('', config, () => Promise.resolve(mod)));log.info('physics', `installed (gravity ${gravity.x}, ${gravity.y})`);@@ -449,7 +455,9 @@ export interface RuntimeInitConfig {spineModule?: SpineWasmModule | null;spineManager?: SpineManager | null;physicsModule?: PhysicsWasmModule | null;- physicsConfig?: { gravity?: Vec2; fixedTimestep?: number; subStepCount?: number; contactHertz?: number; contactDampingRatio?: number; contactSpeed?: number };+ /** Project-declared physics world config (gravity, solver tuning, collision-layer+ * masks, sleep/continuous toggles) — threaded from the editor's Project Settings. */+ physicsConfig?: PhysicsPluginConfig;/** Project-declared physics enable; see {@link LoadRuntimeSceneOptions.physicsEnabled}. */physicsEnabled?: boolean;manifest?: AddressableManifest | null;