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: add event-driven entity tracking for shared play mode

esengine3d1bffad8eeb
diff --git a/editor/src/panels/InspectorPanel.ts b/editor/src/panels/InspectorPanel.ts
index b7129a4bb..9d79bb8ef 100644
--- a/editor/src/panels/InspectorPanel.ts
+++ b/editor/src/panels/InspectorPanel.ts
@@ -81,16 +81,14 @@ export class InspectorPanel {
const pms = getPlayModeService();
this.playModeCleanups_.push(
pms.onStateChange((state) => {
- const isPlaying = state === 'playing' && !pms.isSharedMode;
+ const isPlaying = state === 'playing';
this.playMode_ = isPlaying;
if (isPlaying) {
this.container_.classList.add('es-play-mode');
hideMaterialPreview(this.materialPreviewState_);
- if (pms.bridge) {
- this.runtimeProxy_ = new RuntimeStoreProxy(
- pms.bridge, this.store_
- );
- }
+ this.runtimeProxy_ = new RuntimeStoreProxy(
+ pms.bridge, this.store_
+ );
} else {
this.container_.classList.remove('es-play-mode');
this.stopRuntimeRefresh();
@@ -390,7 +388,10 @@ export class InspectorPanel {
const pms = getPlayModeService();
- if (this.runtimeProxy_) {
+ if (pms.isSharedMode) {
+ this.rebuildPlayModeEntity(runtimeEntityId as Entity);
+ this.startSharedRefreshLoop(runtimeEntityId);
+ } else if (this.runtimeProxy_) {
const freshData = await pms.queryEntityByRuntimeId(runtimeEntityId);
if (!freshData || this.runtimeEntityId_ !== runtimeEntityId) return;
@@ -508,6 +509,27 @@ export class InspectorPanel {
this.runtimeRefreshRafId_ = requestAnimationFrame(tick);
}
+ private startSharedRefreshLoop(entityId: number): void {
+ const pms = getPlayModeService();
+ const tick = () => {
+ if (this.runtimeEntityId_ !== entityId) return;
+ const fresh = pms.querySharedEntity(entityId);
+ if (!fresh) {
+ this.contentContainer_.innerHTML = '<div class="es-inspector-empty">Entity despawned</div>';
+ this.updateFooter('Live mode');
+ return;
+ }
+ if (this.runtimeProxy_) {
+ this.runtimeProxy_.applyRuntimeData(entityId, fresh);
+ this.updatePlayModeEditors(entityId);
+ }
+ if (this.runtimeEntityId_ === entityId) {
+ this.runtimeRefreshRafId_ = requestAnimationFrame(tick);
+ }
+ };
+ this.runtimeRefreshRafId_ = requestAnimationFrame(tick);
+ }
+
private stopRuntimeRefresh(): void {
if (this.runtimeRefreshRafId_) {
cancelAnimationFrame(this.runtimeRefreshRafId_);
diff --git a/editor/src/panels/hierarchy/HierarchyPanel.ts b/editor/src/panels/hierarchy/HierarchyPanel.ts
index 214b3168b..c21eb58b9 100644
--- a/editor/src/panels/hierarchy/HierarchyPanel.ts
+++ b/editor/src/panels/hierarchy/HierarchyPanel.ts
@@ -101,7 +101,7 @@ export class HierarchyPanel implements HierarchyState {
const pms = getPlayModeService();
this.playModeCleanups_.push(
pms.onStateChange((state) => {
- const isPlaying = state === 'playing' && !pms.isSharedMode;
+ const isPlaying = state === 'playing';
this.playMode = isPlaying;
if (isPlaying) {
this.container_.classList.add('es-play-mode');
diff --git a/editor/src/services/PlayModeService.ts b/editor/src/services/PlayModeService.ts
index 22dc6d58d..96e6c814d 100644
--- a/editor/src/services/PlayModeService.ts
+++ b/editor/src/services/PlayModeService.ts
@@ -1,7 +1,12 @@
import type { GameViewBridge, RuntimeEntityData } from '../panels/game-view/GameViewBridge';
import type { EntityData } from '../types/SceneTypes';
+import { Assets, Name, Parent, Children, getComponent } from 'esengine';
+import type { Entity, World } from 'esengine';
import { getEditorStore, type SceneSnapshot } from '../store/EditorStore';
import { getSharedRenderContext } from '../renderer/SharedRenderContext';
+import { ScriptInjector } from './ScriptInjector';
+import { getEditorInstance, getEditorContext } from '../context/EditorContext';
+import { getAssetDatabase, isUUID } from '../asset';
export type PlayState = 'stopped' | 'playing';
@@ -33,6 +38,10 @@ class PlayModeService {
private entityListListeners_ = new Set<EntityListCallback>();
private selectionListeners_ = new Set<SelectionCallback>();
private snapshot_: SceneSnapshot | null = null;
+ private scriptInjector_: ScriptInjector | null = null;
+ private sharedCleanups_: Array<() => void> = [];
+ private sharedWorld_: World | null = null;
+ private entityNameMap_: Map<number, string> | null = null;
get state(): PlayState { return this.state_; }
get bridge(): GameViewBridge | null { return this.bridge_; }
@@ -46,7 +55,12 @@ class PlayModeService {
return null;
}
- enterShared(): void {
+ querySharedEntity(entityId: number): RuntimeEntityData | null {
+ if (!this.sharedWorld_ || !this.sharedWorld_.valid(entityId as Entity)) return null;
+ return this.entityToRuntimeData(this.sharedWorld_, entityId as Entity);
+ }
+
+ async enterShared(): Promise<void> {
this.snapshot_ = getEditorStore().takeSnapshot();
this.sharedMode_ = true;
this.bridge_ = null;
@@ -54,20 +68,31 @@ class PlayModeService {
this.cachedEntities_ = [];
this.selectedEntityId_ = null;
- getSharedRenderContext().enterPlayMode();
+ const ctx = getSharedRenderContext();
+ this.configureAssetBaseUrl(ctx);
+ await this.injectUserScripts(ctx);
+ ctx.enterPlayMode();
+
+ this.startSharedEntityTracking(ctx);
this.emitStateChange();
}
async exitShared(): Promise<void> {
if (!this.sharedMode_) return;
+ for (const cleanup of this.sharedCleanups_) cleanup();
+ this.sharedCleanups_ = [];
+
const snapshot = this.snapshot_;
this.snapshot_ = null;
this.sharedMode_ = false;
this.state_ = 'stopped';
this.cachedEntities_ = [];
this.selectedEntityId_ = null;
+ this.sharedWorld_ = null;
+ this.entityNameMap_ = null;
+ this.ejectUserScripts();
await getSharedRenderContext().exitPlayMode(snapshot?.scene);
if (snapshot) {
@@ -239,6 +264,120 @@ class PlayModeService {
}
}
+ private configureAssetBaseUrl(ctx: ReturnType<typeof getSharedRenderContext>): void {
+ const app = ctx.app_;
+ if (!app || !app.hasResource(Assets)) return;
+
+ const projectDir = ctx.pathResolver_.getProjectDir();
+ if (!projectDir) return;
+
+ const fs = getEditorContext().fs;
+ if (!fs?.toAssetUrl) return;
+
+ const assetServer = app.getResource(Assets);
+ assetServer.baseUrl = fs.toAssetUrl(projectDir);
+
+ const db = getAssetDatabase();
+ assetServer.setAssetRefResolver((ref: string) => {
+ if (isUUID(ref)) {
+ return db.getPath(ref) ?? null;
+ }
+ return null;
+ });
+ }
+
+ private async injectUserScripts(ctx: ReturnType<typeof getSharedRenderContext>): Promise<void> {
+ const app = ctx.app_;
+ if (!app) return;
+
+ const editor = getEditorInstance();
+ if (!editor) return;
+
+ const compiledCode = editor.getCompiledScripts();
+ if (!compiledCode) return;
+
+ this.scriptInjector_ = new ScriptInjector();
+ await this.scriptInjector_.inject(app, compiledCode);
+ }
+
+ private ejectUserScripts(): void {
+ if (this.scriptInjector_) {
+ this.scriptInjector_.eject();
+ this.scriptInjector_ = null;
+ }
+ }
+
+ private buildRuntimeEntityData(world: import('esengine').World): RuntimeEntityData[] {
+ const entities = world.getAllEntities();
+ const result: RuntimeEntityData[] = [];
+ for (const entity of entities) {
+ result.push(this.entityToRuntimeData(world, entity));
+ }
+ return result;
+ }
+
+ private entityToRuntimeData(world: import('esengine').World, entity: Entity): RuntimeEntityData {
+ const nameData = world.tryGet(entity, Name);
+ const parentData = world.tryGet(entity, Parent);
+ const childrenData = world.tryGet(entity, Children);
+
+ const componentTypes = world.getComponentTypes(entity);
+ const components = componentTypes.map(type => {
+ const comp = getComponent(type);
+ if (!comp) return { type, data: {} };
+ const data = world.tryGet(entity, comp);
+ return { type, data: data ? { ...data } : {} };
+ });
+
+ return {
+ entityId: entity as number,
+ name: nameData?.value
+ ?? this.entityNameMap_?.get(entity as number)
+ ?? `Entity ${entity}`,
+ parentId: parentData?.entity ?? null,
+ children: childrenData?.entities ? [...childrenData.entities] : [],
+ components,
+ };
+ }
+
+ private startSharedEntityTracking(ctx: ReturnType<typeof getSharedRenderContext>): void {
+ const app = ctx.app_;
+ if (!app) return;
+
+ const world = app.world;
+ this.sharedWorld_ = world;
+
+ this.entityNameMap_ = new Map();
+ const sm = ctx.sceneManager_;
+ if (sm) {
+ const scene = getEditorStore().scene;
+ const entityMap = sm.getEntityMap();
+ for (const [editorId, ecsEntity] of entityMap) {
+ const ed = scene.entities.find(e => e.id === editorId);
+ if (ed) this.entityNameMap_.set(ecsEntity as number, ed.name);
+ }
+ }
+
+ this.cachedEntities_ = this.buildRuntimeEntityData(world);
+ this.emitEntityListUpdate();
+
+ const unsubSpawn = world.onSpawn((entity: Entity) => {
+ this.cachedEntities_ = this.buildRuntimeEntityData(world);
+ this.emitEntityListUpdate();
+ });
+
+ const unsubDespawn = world.onDespawn((entity: Entity) => {
+ if (this.selectedEntityId_ === (entity as number)) {
+ this.selectedEntityId_ = null;
+ this.emitSelectionChange();
+ }
+ this.cachedEntities_ = this.buildRuntimeEntityData(world);
+ this.emitEntityListUpdate();
+ });
+
+ this.sharedCleanups_.push(unsubSpawn, unsubDespawn);
+ }
+
private startPolling(): void {
this.stopPolling();
this.consecutiveFailures_ = 0;
diff --git a/editor/src/services/RuntimeStoreProxy.ts b/editor/src/services/RuntimeStoreProxy.ts
index 5976af1cd..e9c888227 100644
--- a/editor/src/services/RuntimeStoreProxy.ts
+++ b/editor/src/services/RuntimeStoreProxy.ts
@@ -5,12 +5,12 @@ import type { SceneData, EntityData, ComponentData } from '../types/SceneTypes';
import { getPlayModeService } from './PlayModeService';
export class RuntimeStoreProxy {
- private bridge_: GameViewBridge;
+ private bridge_: GameViewBridge | null;
private editorStore_: EditorStore;
private runtimeCache_ = new Map<number, Record<string, Record<string, unknown>>>();
private pendingWrites_ = new Map<string, { value: unknown; stale: boolean }>();
- constructor(bridge: GameViewBridge, editorStore: EditorStore) {
+ constructor(bridge: GameViewBridge | null, editorStore: EditorStore) {
this.bridge_ = bridge;
this.editorStore_ = editorStore;
}
@@ -105,7 +105,7 @@ export class RuntimeStoreProxy {
newValue: unknown,
): void {
this.recordPendingWrite(entity as number, componentType, propertyName, newValue);
- this.bridge_.setEntityProperty(entity as number, componentType, propertyName, newValue);
+ this.bridge_?.setEntityProperty(entity as number, componentType, propertyName, newValue);
}
updateProperties(
@@ -115,7 +115,7 @@ export class RuntimeStoreProxy {
): void {
for (const change of changes) {
this.recordPendingWrite(entity as number, componentType, change.property, change.newValue);
- this.bridge_.setEntityProperty(entity as number, componentType, change.property, change.newValue);
+ this.bridge_?.setEntityProperty(entity as number, componentType, change.property, change.newValue);
}
}
@@ -126,7 +126,7 @@ export class RuntimeStoreProxy {
newValue: unknown,
): void {
this.recordPendingWrite(entity as number, componentType, propertyName, newValue);
- this.bridge_.setEntityProperty(entity as number, componentType, propertyName, newValue);
+ this.bridge_?.setEntityProperty(entity as number, componentType, propertyName, newValue);
}
renameEntity(entity: Entity, name: string): void {
diff --git a/sdk/src/world.ts b/sdk/src/world.ts
index 98a990853..002732f7a 100644
--- a/sdk/src/world.ts
+++ b/sdk/src/world.ts
@@ -151,6 +151,7 @@ export class World {
private iterationDepth_ = 0;
private nextEntityId_ = 0;
private nextGeneration_ = 0;
+ private spawnCallbacks_: Array<(entity: Entity) => void> = [];
private despawnCallbacks_: Array<(entity: Entity) => void> = [];
private worldTick_ = 0;
@@ -213,6 +214,11 @@ export class World {
}
this.entities_.set(entity, generation);
this.worldVersion_++;
+
+ for (const cb of this.spawnCallbacks_) {
+ try { cb(entity); } catch {}
+ }
+
return entity;
}
@@ -255,6 +261,14 @@ export class World {
}
}
+ onSpawn(callback: (entity: Entity) => void): () => void {
+ this.spawnCallbacks_.push(callback);
+ return () => {
+ const idx = this.spawnCallbacks_.indexOf(callback);
+ if (idx !== -1) this.spawnCallbacks_.splice(idx, 1);
+ };
+ }
+
onDespawn(callback: (entity: Entity) => void): () => void {
this.despawnCallbacks_.push(callback);
return () => {