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
perf(editor): O(1) entity lookup, gated pivot, cached ref-count; slider mixed
esenginec12bc9868056
diff --git a/desktop/src/engine/SceneModel.ts b/desktop/src/engine/SceneModel.tsindex 9dc050781..14655ed04 100644--- a/desktop/src/engine/SceneModel.ts+++ b/desktop/src/engine/SceneModel.ts@@ -68,6 +68,10 @@ export interface PrefabInstanceTag {*/export class SceneModelImpl {private data: SceneData | null = null;+ /** source id → entity record, kept in lockstep with `data.entities` so+ * {@link entityBySource} (a hot path — folder resolution, drag, spawn,+ * outliner) is O(1) instead of a linear scan that compounds to O(N²). */+ private entityIndex_ = new Map<number, SceneEntity>();/** runtime World entity → source entity id (Reconciler-maintained). */private readonly runtimeToSource = new Map<EntityId, number>();/** source entity id → runtime World entity (absent for unknown/unspawned). */@@ -107,6 +111,7 @@ export class SceneModelImpl {this.runtimeToSource.clear();this.sourceToRuntime.clear();this.prefabTags.clear();+ this.entityIndex_ = new Map(loaded.entities.map((e) => [e.id, e]));let maxId = 0;for (const e of loaded.entities) if (e.id > maxId) maxId = e.id;this.nextSourceId = maxId + 1;@@ -122,6 +127,7 @@ export class SceneModelImpl {this.runtimeToSource.clear();this.sourceToRuntime.clear();this.prefabTags.clear();+ this.entityIndex_.clear();this.nextSourceId = 1;this.emit({ kind: 'reset' });}@@ -202,9 +208,11 @@ export class SceneModelImpl {addEntity(name: string, components: SceneComponent[], parent: number | null = null): number {const id = this.nextSourceId++;if (this.data) {- this.data.entities.push({ id, name, parent, children: [], components });+ const entity = { id, name, parent, children: [], components };+ this.data.entities.push(entity);+ this.entityIndex_.set(id, entity);if (parent != null) {- const p = this.data.entities.find((e) => e.id === parent);+ const p = this.entityBySource(parent);if (p && !p.children.includes(id)) p.children.push(id);}}@@ -223,8 +231,9 @@ export class SceneModelImpl {const idx = this.data.entities.findIndex((e) => e.id === sourceId);if (idx < 0) return undefined;const [removed] = this.data.entities.splice(idx, 1);+ this.entityIndex_.delete(sourceId);if (removed.parent != null) {- const p = this.data.entities.find((e) => e.id === removed.parent);+ const p = this.entityBySource(removed.parent);if (p) p.children = p.children.filter((c) => c !== sourceId);}this.prefabTags.delete(sourceId);@@ -240,8 +249,9 @@ export class SceneModelImpl {restoreEntity(entity: SceneEntity): void {if (!this.data) return;this.data.entities.push(entity);+ this.entityIndex_.set(entity.id, entity);if (entity.parent != null) {- const p = this.data.entities.find((e) => e.id === entity.parent);+ const p = this.entityBySource(entity.parent);if (p && !p.children.includes(entity.id)) p.children.push(entity.id);}this.emit({ kind: 'entityAdded', sourceId: entity.id });@@ -258,12 +268,12 @@ export class SceneModelImpl {if (child.parent === parent) return;if (child.parent != null) {- const old = this.data.entities.find((e) => e.id === child.parent);+ const old = this.entityBySource(child.parent);if (old) old.children = old.children.filter((c) => c !== sourceId);}child.parent = parent;if (parent != null) {- const np = this.data.entities.find((e) => e.id === parent);+ const np = this.entityBySource(parent);if (np && !np.children.includes(sourceId)) np.children.push(sourceId);}this.emit({ kind: 'parentChanged', sourceId });@@ -423,9 +433,9 @@ export class SceneModelImpl {return this.data ? (JSON.parse(JSON.stringify(this.data)) as SceneData) : null;}- /** The source entity record for a source id. */+ /** The source entity record for a source id (O(1) via {@link entityIndex_}). */entityBySource(sourceId: number): SceneEntity | undefined {- return this.data?.entities.find((e) => e.id === sourceId);+ return this.entityIndex_.get(sourceId);}/** Every source entity record (live references, read-only by convention). */@@ -476,6 +486,7 @@ export class SceneModelImpl {for (const e of entities) {if (e.id >= this.nextSourceId) this.nextSourceId = e.id + 1;this.data.entities.push(e);+ this.entityIndex_.set(e.id, e);}// Attach batch roots (parent outside the batch) to their parent's children.for (const e of entities) {diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsxindex e3e46e15a..b229a2343 100644--- a/desktop/src/panels/Details.tsx+++ b/desktop/src/panels/Details.tsx@@ -339,6 +339,7 @@ export function SliderControl({max,step,unit,+ mixed,onBegin,onEnd,onChange,@@ -348,12 +349,15 @@ export function SliderControl({max: number;step?: number;unit?: string;+ mixed?: boolean;onChange: (n: number) => void;}) {const track = useRef<HTMLDivElement>(null);const dragging = useRef(false);const span = max - min;- const pct = span > 0 ? Math.max(0, Math.min(1, (value - min) / span)) : 0;+ // A mixed multi-selection has no single value to point the fill/thumb at; show+ // an empty track (and `—` in the field) until a drag commits one value to all.+ const pct = mixed ? 0 : span > 0 ? Math.max(0, Math.min(1, (value - min) / span)) : 0;const setFromX = (clientX: number) => {const el = track.current;if (!el) return;@@ -390,7 +394,7 @@ export function SliderControl({<span className="thumb" style={{ left: `${pct * 100}%` }} /></div><span className="snum">- <NumField value={value} suffix={unit} onBegin={onBegin} onEnd={onEnd} onCommit={onChange} />+ <NumField value={value} suffix={unit} mixed={mixed} onBegin={onBegin} onEnd={onEnd} onCommit={onChange} /></span></>);@@ -1092,6 +1096,7 @@ function FieldRow({ entities, comp, field, write }: { entities: EntityId[]; compmax={field.max}step={field.step}unit={field.unit}+ mixed={mixed}onBegin={begin}onEnd={end}onChange={apply}@@ -2463,9 +2468,10 @@ function GenericAssetInspector({ path }: { path: string }) {img.onload = () => alive && setDims(`${img.naturalWidth} × ${img.naturalHeight}`);img.src = `estella://project/${path}`;}- // Same collector as Find Usages (disk graph + unsaved scene), so the count- // always matches what the dialog lists.- void findAssetUsages(path)+ // Same collector as Find Usages, but off the cached asset index (this fires+ // on every selection — a full disk walk per click just for a badge is waste);+ // fsWatch keeps the cache fresh, and the dialog itself stays authoritative.+ void findAssetUsages(path, { preferCache: true }).then((u) => alive && setRefCount(u.length)).catch(() => {});return () => {diff --git a/desktop/src/panels/Viewport.tsx b/desktop/src/panels/Viewport.tsxindex cd36b3cc3..673368a8d 100644--- a/desktop/src/panels/Viewport.tsx+++ b/desktop/src/panels/Viewport.tsx@@ -1067,10 +1067,14 @@ export function Viewport() {// The transform gizmo sits at the selection pivot (centroid or active-entity// pivot per pivotMode), rotated to the active entity's axes in local space.- // Only for the move/rotate/scale tools — select shows just the outline.- const pivotWorld = ready && selIds.length ? selectionPivot(selIds) : null;+ // Only for the move/rotate/scale tools — select shows just the outline. Gate+ // the compute on the same condition as the draw so a big marquee selection+ // under the (default) Select tool doesn't run O(selection) wasm queries/frame+ // for a pivot that's never drawn.+ const drawPivot = ready && showG && toolMode !== 'select' && selIds.length > 0;+ const pivotWorld = drawPivot ? selectionPivot(selIds) : null;const pivot = pivotWorld ? ViewportController.worldToClient(pivotWorld.x, pivotWorld.y) : null;- if (pivot && showG && toolMode !== 'select') {+ if (pivot) {const angDeg = (gizmoScreenAngleRad(selIds) * 180) / Math.PI;g.style.transform = `translate(${pivot.x}px, ${pivot.y}px) rotate(${angDeg}deg)`;g.style.opacity = '1';diff --git a/desktop/src/project/assetUsages.ts b/desktop/src/project/assetUsages.tsindex 9ed2c6741..56a674e31 100644--- a/desktop/src/project/assetUsages.ts+++ b/desktop/src/project/assetUsages.ts@@ -12,12 +12,26 @@ import { collectAssetUsages, type AssetUsage } from './assetRefs';export type { AssetUsage };-/** Everything referencing the asset at `path` (disk graph + unsaved scene). */-export async function findAssetUsages(path: string): Promise<AssetUsage[]> {- const scan = await window.estella.project.scanAssets();+/**+ * Everything referencing the asset at `path` (disk graph + unsaved scene).+ *+ * `preferCache` reads the already-built asset index instead of walking the disk —+ * for the passive ref-count badge that fires on every asset selection, where a+ * full main-process scan per click is wasteful. The authoritative walk (the+ * default) stays for the delete confirm and Find Usages, which must not miss a+ * reference. Falls back to the walk when there is no cache yet.+ */+export async function findAssetUsages(+ path: string,+ opts?: { preferCache?: boolean },+): Promise<AssetUsage[]> {+ const index = opts?.preferCache+ ? (await window.estella.project.cachedAssetIndex().catch(() => null))+ ?? (await window.estella.project.scanAssets()).index+ : (await window.estella.project.scanAssets()).index;const data = SceneModel.current;return collectAssetUsages(- scan.index,+ index,path,data ? { path: ProjectStore.getSnapshot()?.currentScene ?? null, data } : null,);diff --git a/desktop/tests/scene-model.test.ts b/desktop/tests/scene-model.test.tsindex b7a67e155..6120b4212 100644--- a/desktop/tests/scene-model.test.ts+++ b/desktop/tests/scene-model.test.ts@@ -76,4 +76,30 @@ describe('SceneModel (JSON-first source of truth)', () => {expect(SceneModel.current).toBeNull();expect(SceneModel.sourceFor(100)).toBeUndefined();});++ it('entityBySource (O(1) index) stays in lockstep with the entities array across mutations', () => {+ SceneModel.adopt(fixture(), new Map([[1, 100], [2, 200]]));+ // The index must mirror the array exactly (same object references) and miss nothing.+ const agrees = () =>+ SceneModel.current!.entities.every((e) => SceneModel.entityBySource(e.id) === e)+ && SceneModel.entityBySource(99999) === undefined;+ const scan = (id: number) => SceneModel.current?.entities.find((e) => e.id === id);++ expect(agrees()).toBe(true);++ const added = SceneModel.addEntity('New', [], 1);+ expect(SceneModel.entityBySource(added)).toBe(scan(added));+ expect(agrees()).toBe(true);++ const removed = SceneModel.removeEntityBySource(1);+ expect(SceneModel.entityBySource(1)).toBeUndefined();+ expect(agrees()).toBe(true);++ SceneModel.restoreEntity(removed!);+ expect(SceneModel.entityBySource(1)).toBe(scan(1));+ expect(agrees()).toBe(true);++ SceneModel.clear();+ expect(SceneModel.entityBySource(1)).toBeUndefined();+ });});