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(scene): publication says where it went, phase by phase, and names what had no timer

esengine076f515155ee
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index b4c83718d..8941673b5 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -7345,7 +7345,7 @@ assets: Assets | undefined
collectAssets: LoadedSceneAssets | undefined
externalEntities: ReadonlyMap<number, number> | undefined
onMissingAssets: MissingAssetCallback | undefined
-onPhase: ((phase: string, ms: number) => void) | undefined
+onPhase: ScenePhaseSink | undefined
onProgress: SceneLoadProgressCallback | undefined
```
@@ -11929,7 +11929,7 @@ LifecyclePlugin
## loadSceneData — function @experimental
```
-(world: World, sceneData: SceneData, external?: ReadonlyMap<number, Entity>): Map<number, Entity>
+(world: World, sceneData: SceneData, external?: ReadonlyMap<number, Entity>, onPhase?: ScenePhaseSink): Map<number, Entity>
```
## loadSceneWithAssets — function @experimental
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 97bde0c8b..4fc007042 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -7538,7 +7538,7 @@ assets: Assets | undefined
collectAssets: LoadedSceneAssets | undefined
externalEntities: ReadonlyMap<number, number> | undefined
onMissingAssets: MissingAssetCallback | undefined
-onPhase: ((phase: string, ms: number) => void) | undefined
+onPhase: ScenePhaseSink | undefined
onProgress: SceneLoadProgressCallback | undefined
```
@@ -12172,7 +12172,7 @@ LifecyclePlugin
## loadSceneData — function @experimental
```
-(world: World, sceneData: SceneData, external?: ReadonlyMap<number, Entity>): Map<number, Entity>
+(world: World, sceneData: SceneData, external?: ReadonlyMap<number, Entity>, onPhase?: ScenePhaseSink): Map<number, Entity>
```
## loadSceneWithAssets — function @experimental
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 42bb2aaeb..9c3b529fc 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -7340,7 +7340,7 @@ assets: Assets | undefined
collectAssets: LoadedSceneAssets | undefined
externalEntities: ReadonlyMap<number, number> | undefined
onMissingAssets: MissingAssetCallback | undefined
-onPhase: ((phase: string, ms: number) => void) | undefined
+onPhase: ScenePhaseSink | undefined
onProgress: SceneLoadProgressCallback | undefined
```
@@ -11929,7 +11929,7 @@ LifecyclePlugin
## loadSceneData — function @experimental
```
-(world: World, sceneData: SceneData, external?: ReadonlyMap<number, Entity>): Map<number, Entity>
+(world: World, sceneData: SceneData, external?: ReadonlyMap<number, Entity>, onPhase?: ScenePhaseSink): Map<number, Entity>
```
## loadSceneWithAssets — function @experimental
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 67bd4e1db..7dff7c0a8 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -7586,7 +7586,7 @@ assets: Assets | undefined
collectAssets: LoadedSceneAssets | undefined
externalEntities: ReadonlyMap<number, number> | undefined
onMissingAssets: MissingAssetCallback | undefined
-onPhase: ((phase: string, ms: number) => void) | undefined
+onPhase: ScenePhaseSink | undefined
onProgress: SceneLoadProgressCallback | undefined
```
@@ -12191,7 +12191,7 @@ LifecyclePlugin
## loadSceneData — function @experimental
```
-(world: World, sceneData: SceneData, external?: ReadonlyMap<number, Entity>): Map<number, Entity>
+(world: World, sceneData: SceneData, external?: ReadonlyMap<number, Entity>, onPhase?: ScenePhaseSink): Map<number, Entity>
```
## loadSceneWithAssets — function @experimental
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 74c6eb422..adfaafad4 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -7347,7 +7347,7 @@ assets: Assets | undefined
collectAssets: LoadedSceneAssets | undefined
externalEntities: ReadonlyMap<number, number> | undefined
onMissingAssets: MissingAssetCallback | undefined
-onPhase: ((phase: string, ms: number) => void) | undefined
+onPhase: ScenePhaseSink | undefined
onProgress: SceneLoadProgressCallback | undefined
```
@@ -11957,7 +11957,7 @@ LifecyclePlugin
## loadSceneData — function @experimental
```
-(world: World, sceneData: SceneData, external?: ReadonlyMap<number, Entity>): Map<number, Entity>
+(world: World, sceneData: SceneData, external?: ReadonlyMap<number, Entity>, onPhase?: ScenePhaseSink): Map<number, Entity>
```
## loadSceneWithAssets — function @experimental
diff --git a/sdk/src/runtime/runtimeLoader.ts b/sdk/src/runtime/runtimeLoader.ts
index cdf2530f8..833dfce1b 100644
--- a/sdk/src/runtime/runtimeLoader.ts
+++ b/sdk/src/runtime/runtimeLoader.ts
@@ -372,6 +372,7 @@ export async function prepareRuntimeScene(
// Spine pairs (raw refs) for the two-phase spine load+apply below; every
// other asset type loads through the single canonical Assets channel.
+ const discoverBegan = onPhase ? performance.now() : 0;
const discovered = discoverSceneAssets(sceneData);
// Eager scene assets (textures / fonts / materials / anim-clips / tilemaps /
@@ -394,6 +395,10 @@ export async function prepareRuntimeScene(
app.getResource(VideoPlayer).setRefResolver((ref) => backend.resolveUrl(resolveRef(ref)));
}
mergeSceneTextureImportSettings(sceneAssets, sceneData, source.resolveRef ?? ((r) => r));
+ // Two full walks of the document before a byte is fetched. Named because
+ // they scale with the cell and not with what it references, which is not
+ // what "asset discovery" sounds like it costs.
+ if (onPhase) onPhase('discover', performance.now() - discoverBegan);
const assetResult = await timed('assets',
() => sceneAssets.preloadSceneAssets(sceneData, undefined, { skipSpine: true }));
sceneAssets.resolveSceneAssetPaths(sceneData, assetResult);
@@ -415,6 +420,7 @@ export async function prepareRuntimeScene(
const mod = await host.acquire('basis');
return mod ? transcoderFromModule(mod as unknown as BasisWasmModule) : null;
};
+ const subsystemsBegan = onPhase ? performance.now() : 0;
// Prepared by the realm, owned by the scene: the receipts join the scope
// this scene gives back, and a second scene of one spine asset joins its era
// instead of uploading its pages again.
@@ -531,6 +537,11 @@ export async function prepareRuntimeScene(
}
}
+ // Loading the runtimes a cell's content needs, and the tables it binds. All
+ // of it self-gating and installed once, so the first cell of a world pays
+ // for the world and the ones after it pay for their own content only.
+ if (onPhase) onPhase('subsystems', performance.now() - subsystemsBegan);
+
// The one place a packaged scene's entities come into being. `externalEntities`
// is what lets a streamed cell name the persistent world: without it a cross
// document reference resolves to nothing, quietly.
@@ -570,51 +581,66 @@ export async function publishRuntimeScene(
const began = performance.now();
try { return await run(); } finally { onPhase(phase, performance.now() - began); }
};
+ /**
+ * The synchronous sibling of `timed`, for the steps that ARE synchronous.
+ *
+ * `timed` is `async`, so measuring these with it opens a microtask gap per
+ * step through which another cell's publication could interleave — an
+ * instrument that changed the thing it measures.
+ */
+ const mark = <T>(phase: string, run: () => T): T => {
+ if (!onPhase) return run();
+ const began = performance.now();
+ try { return run(); } finally { onPhase(phase, performance.now() - began); }
+ };
void discovered;
const entityMap = await timed('spawn',
- () => loadSceneData(app.world, sceneData, options.externalEntities));
+ () => loadSceneData(app.world, sceneData, options.externalEntities, onPhase));
// Which document row each entity came from, when someone is keeping track
// (an editor inspecting its own running game). No-op otherwise.
- recordSceneOrigins(app, entityMap);
+ mark('origins', () => recordSceneOrigins(app, entityMap));
// Apply the project theme over the freshly instantiated scene: prefabs bake
// the default dark palette, so a light base or any token override re-resolves
// every ThemeStyle tag.
if (uiTheme === 'light' || uiThemeOverrides) {
- switchTheme(app.world, resolveThemeTokens(uiTheme ?? 'dark', uiThemeOverrides));
+ mark('theme', () => switchTheme(app.world, resolveThemeTokens(uiTheme ?? 'dark', uiThemeOverrides)));
}
const cppRegistry = app.world.getCppRegistry();
// Fold the loaded transforms into world matrices once, before the first frame.
// Native hosts run their own TransformSystem each frame instead.
if (cppRegistry && module) {
- module.transform_update(cppRegistry);
+ mark('transform', () => module.transform_update(cppRegistry));
}
if (spineManager && cppRegistry) {
- await applySpineEntities({ spineManager, sceneData, entityMap, registry: cppRegistry, assetInfo: spineAssetInfo });
+ await timed('spine', () => applySpineEntities({ spineManager, sceneData, entityMap, registry: cppRegistry, assetInfo: spineAssetInfo }));
}
if (dragonBonesManager) {
- applyDragonBonesEntities({
+ mark('dragonbones', () => applyDragonBonesEntities({
manager: dragonBonesManager, sceneData, entityMap, assetInfo: dragonBonesAssetInfo,
- });
+ }));
}
if (sceneName && app.hasResource(SceneManager)) {
// Adopt into the SceneManager's instance set so unload/switchTo actually
// despawns these entities — SceneOwner alone is only the persistence tag.
const ctx = app.getResource(SceneManager).getScene(sceneName);
- for (const entity of entityMap.values()) {
- if (ctx) ctx.adopt(entity);
- else app.world.insert(entity, SceneOwner, { scene: sceneName, persistent: false });
- }
- // The RECEIPTS, not the paths: after a hot update a path-addressed
- // release gives back the oldest era, which belongs to whoever loaded
- // before the update.
- ctx?.trackAssetScope(assetResult.scope);
+ mark('adopt', () => {
+ for (const entity of entityMap.values()) {
+ if (ctx) ctx.adopt(entity);
+ else app.world.insert(entity, SceneOwner, { scene: sceneName, persistent: false });
+ }
+ // The RECEIPTS, not the paths: after a hot update a path-addressed
+ // release gives back the oldest era, which belongs to whoever loaded
+ // before the update.
+ ctx?.trackAssetScope(assetResult.scope);
+ });
}
+
}
/**
diff --git a/sdk/src/scene/scene.ts b/sdk/src/scene/scene.ts
index a3c0ff400..f41756967 100644
--- a/sdk/src/scene/scene.ts
+++ b/sdk/src/scene/scene.ts
@@ -118,10 +118,20 @@ export interface SceneLoadOptions {
* Where a load's time went, phase by phase. Most of it runs between frames —
* off every system timer there is — so a profiler watching the frame loop
* sees the cost and cannot say what it was.
+ *
+ * A name may be dotted, and a dot means containment: `spawn.components` is
+ * part of `spawn`, so a reader sums the roots and never the whole list.
*/
- onPhase?: (phase: string, ms: number) => void;
+ onPhase?: ScenePhaseSink;
}
+/**
+ * Where a load's time went. Dotted names nest; see {@link SceneLoadOptions.onPhase}.
+ *
+ * @experimental
+ */
+export type ScenePhaseSink = (phase: string, ms: number) => void;
+
export class MissingAssetsError extends Error {
readonly missing: import('../asset/Assets').MissingAsset[];
constructor(missing: import('../asset/Assets').MissingAsset[]) {
@@ -456,8 +466,19 @@ function checkLoadable(sceneData: SceneData): void {
function spawnAndLoadEntities(
world: World, sceneData: SceneData, external?: ReadonlyMap<number, Entity>,
+ onPhase?: ScenePhaseSink,
): Map<number, Entity> {
+ // One clock reading per component rather than two: the end of one write is
+ // the start of the next, so attribution costs a call and not a pair.
+ let mark = onPhase ? performance.now() : 0;
+ const since = (): number => {
+ const now = performance.now();
+ const elapsed = now - mark;
+ mark = now;
+ return elapsed;
+ };
checkLoadable(sceneData);
+ if (onPhase) onPhase('spawn.validate', since());
const entityMap = new Map<number, Entity>();
for (const entityData of sceneData.entities) {
@@ -473,8 +494,13 @@ function spawnAndLoadEntities(
entityMap.set(entityData.id, entity);
world.insert(entity, Name, { value: entityData.name });
}
+ if (onPhase) onPhase('spawn.entities', since());
try {
+ // By component TYPE, because "component writes" is a rename of the total
+ // and not an answer: which writes reach a subsystem, and which are field
+ // validation, is the difference between a mechanism and a number.
+ const byType = onPhase ? new Map<string, number>() : null;
for (const entityData of sceneData.entities) {
if (entityData.visible === false) continue;
if (isPrefabEntry(entityData)) continue;
@@ -482,7 +508,16 @@ function spawnAndLoadEntities(
for (const compData of entityData.components) {
remapEntityFields(compData, entityMap, external);
loadComponent(world, entity, compData, entityData.name);
+ if (byType) byType.set(compData.type, (byType.get(compData.type) ?? 0) + since());
+ }
+ }
+ if (onPhase && byType) {
+ let total = 0;
+ for (const [type, ms] of byType) {
+ total += ms;
+ onPhase(`spawn.components.${type}`, ms);
}
+ onPhase('spawn.components', total);
}
for (const entityData of sceneData.entities) {
@@ -494,6 +529,7 @@ function spawnAndLoadEntities(
}
}
}
+ if (onPhase) onPhase('spawn.hierarchy', since());
} catch (e) {
for (const entity of entityMap.values()) {
try { world.despawn(entity); } catch { /* ignore cleanup errors */ }
@@ -506,9 +542,15 @@ function spawnAndLoadEntities(
export function loadSceneData(
world: World, sceneData: SceneData, external?: ReadonlyMap<number, Entity>,
+ onPhase?: ScenePhaseSink,
): Map<number, Entity> {
+ const began = onPhase ? performance.now() : 0;
const { data } = migrateSceneData(sceneData);
- return spawnAndLoadEntities(world, data, external);
+ // Named because it is a surprise: migration deep-clones the whole document
+ // so the caller's data is never mutated, and on a streamed cell that clone
+ // is paid at the door — after preparation already had the bytes in hand.
+ if (onPhase) onPhase('spawn.migrate', performance.now() - began);
+ return spawnAndLoadEntities(world, data, external, onPhase);
}
/**
@@ -580,7 +622,7 @@ export async function loadSceneWithAssets(
}
}
}
- return timed('spawn', () => spawnAndLoadEntities(world, data, options?.externalEntities));
+ return timed('spawn', () => spawnAndLoadEntities(world, data, options?.externalEntities, onPhase));
}
function applyTextureMetadata(sceneData: SceneData, textureHandles: Map<string, number>): void {