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.

refactor: SDK app/system lifecycle, editor panel and renderer updates

esengine016a1c96f7cc
diff --git a/editor/src/panels/profiler/ProfilerPanel.ts b/editor/src/panels/profiler/ProfilerPanel.ts
index 587c5ffaa..2dd2150c1 100644
--- a/editor/src/panels/profiler/ProfilerPanel.ts
+++ b/editor/src/panels/profiler/ProfilerPanel.ts
@@ -6,6 +6,7 @@ import type { PanelInstance } from '../PanelRegistry';
import { FrameTimeline } from './FrameTimeline';
import { PhaseWaterfall } from './PhaseWaterfall';
import { SystemTable } from './SystemTable';
+import { icons } from '../../utils/icons';
const enum Mode {
Live,
@@ -57,13 +58,13 @@ export class ProfilerPanel implements PanelInstance {
this.container_.innerHTML = `
<div class="es-profiler-panel">
<div class="es-profiler-toolbar">
- <button class="es-profiler-btn es-profiler-btn-pause" title="Pause/Resume">▮▮</button>
- <button class="es-profiler-btn es-profiler-btn-clear" title="Clear">Clear</button>
+ <button class="es-profiler-btn es-profiler-btn-pause" title="Pause/Resume">${icons.pause(14)}</button>
+ <button class="es-profiler-btn es-profiler-btn-clear" title="Clear">${icons.eraser(14)} Clear</button>
<span class="es-profiler-fps-display">-- FPS / --ms</span>
<span class="es-profiler-toolbar-sep"></span>
- <button class="es-profiler-btn es-profiler-btn-prev" title="Previous frame" disabled>◀</button>
+ <button class="es-profiler-btn es-profiler-btn-prev" title="Previous frame" disabled>${icons.chevronLeft(14)}</button>
<span class="es-profiler-frame-display">--</span>
- <button class="es-profiler-btn es-profiler-btn-next" title="Next frame" disabled>▶</button>
+ <button class="es-profiler-btn es-profiler-btn-next" title="Next frame" disabled>${icons.chevronRight(14)}</button>
</div>
<div class="es-profiler-top">
<div class="es-profiler-timeline-wrap"></div>
@@ -177,7 +178,7 @@ export class ProfilerPanel implements PanelInstance {
this.frozenSnapshots_ = this.frameHistory_.getAll();
this.selectedIndex_ = Math.min(selectIndex, this.frozenSnapshots_.length - 1);
this.mode_ = Mode.Paused;
- this.btnPause_.textContent = '▶';
+ this.btnPause_.innerHTML = icons.play(14);
this.btnPause_.classList.add('es-profiler-btn-active');
this.scheduleRender();
}
@@ -186,7 +187,7 @@ export class ProfilerPanel implements PanelInstance {
this.mode_ = Mode.Live;
this.selectedIndex_ = -1;
this.frozenSnapshots_ = [];
- this.btnPause_.textContent = '▮▮';
+ this.btnPause_.innerHTML = icons.pause(14);
this.btnPause_.classList.remove('es-profiler-btn-active');
this.scheduleRender();
}
@@ -205,7 +206,7 @@ export class ProfilerPanel implements PanelInstance {
this.frozenSnapshots_ = [];
this.selectedIndex_ = -1;
this.mode_ = Mode.Live;
- this.btnPause_.textContent = '▮▮';
+ this.btnPause_.innerHTML = icons.pause(14);
this.btnPause_.classList.remove('es-profiler-btn-active');
this.fpsDisplay_.textContent = '-- FPS / --ms';
this.frameDisplay_.textContent = '--';
diff --git a/editor/src/panels/scene-view/SceneViewPanel.ts b/editor/src/panels/scene-view/SceneViewPanel.ts
index e2ee9b153..db598f57d 100644
--- a/editor/src/panels/scene-view/SceneViewPanel.ts
+++ b/editor/src/panels/scene-view/SceneViewPanel.ts
@@ -405,7 +405,10 @@ export class SceneViewPanel {
this.webglInitPending_ = true;
const sharedCtx = getSharedRenderContext();
- const success = sharedCtx.initialized || await sharedCtx.init(this.app_.wasmModule);
+ if (!sharedCtx.initialized) {
+ await new Promise<void>(resolve => sharedCtx.onceInitialized(resolve));
+ }
+ const success = sharedCtx.initialized;
if (success) {
this.sceneRenderer_ = new EditorSceneRenderer(sharedCtx);
@@ -591,30 +594,35 @@ export class SceneViewPanel {
}
private render(): void {
+ const sharedCtx = getSharedRenderContext();
+ sharedCtx.resetFrameTick();
+
if (this.useWebGL_ && this.sceneRenderer_) {
const w = this.sceneViewportW_;
const h = this.sceneViewportH_;
- if (w === 0 || h === 0) return;
- this.sceneRenderer_.camera.panX = this.camera_.panX;
- this.sceneRenderer_.camera.panY = this.camera_.panY;
- this.sceneRenderer_.camera.zoom = this.camera_.zoom;
-
- this.sceneRenderer_.render(w, h);
- this.camera_.orthoHalfHeight = this.sceneRenderer_.camera.orthoHalfHeight;
-
- const sharedCtx = getSharedRenderContext();
- const webglCanvas = sharedCtx.webglCanvas_;
- if (this.displayCanvas_ && webglCanvas) {
- const dCtx = this.displayCanvas_.getContext('2d');
- if (dCtx) {
- const srcY = webglCanvas.height - h;
- dCtx.clearRect(0, 0, this.displayCanvas_.width, this.displayCanvas_.height);
- dCtx.drawImage(webglCanvas, 0, srcY, w, h, 0, 0, w, h);
+ this.sceneRenderer_.tickAndRenderGameView(w, h);
+
+ if (w > 0 && h > 0) {
+ this.sceneRenderer_.camera.panX = this.camera_.panX;
+ this.sceneRenderer_.camera.panY = this.camera_.panY;
+ this.sceneRenderer_.camera.zoom = this.camera_.zoom;
+
+ this.sceneRenderer_.renderSceneView(w, h);
+ this.camera_.orthoHalfHeight = this.sceneRenderer_.camera.orthoHalfHeight;
+
+ const webglCanvas = sharedCtx.webglCanvas_;
+ if (this.displayCanvas_ && webglCanvas) {
+ const dCtx = this.displayCanvas_.getContext('2d');
+ if (dCtx) {
+ const srcY = webglCanvas.height - h;
+ dCtx.clearRect(0, 0, this.displayCanvas_.width, this.displayCanvas_.height);
+ dCtx.drawImage(webglCanvas, 0, srcY, w, h, 0, 0, w, h);
+ }
}
- }
- this.renderOverlay();
+ this.renderOverlay();
+ }
} else if (this.bridge_) {
const w = this.canvas_.width;
const h = this.canvas_.height;
@@ -625,7 +633,7 @@ export class SceneViewPanel {
this.renderPreview();
}
- getSharedRenderContext().firePostRenderCallback();
+ sharedCtx.firePostRenderCallback();
}
// =========================================================================
diff --git a/editor/src/renderer/EditorSceneRenderer.ts b/editor/src/renderer/EditorSceneRenderer.ts
index 3dd1df952..56967be48 100644
--- a/editor/src/renderer/EditorSceneRenderer.ts
+++ b/editor/src/renderer/EditorSceneRenderer.ts
@@ -335,16 +335,37 @@ export class EditorSceneRenderer {
}
}
- render(width: number, height: number): void {
+ tickAndRenderGameView(sceneW: number, sceneH: number): void {
+ if (!this.context_.initialized || !this.sceneManager_) return;
+
+ if (sceneW > 0 && sceneH > 0) {
+ this.sceneManager_.setViewportSize(sceneW, sceneH);
+ }
+
+ if (!this.context_.isPlayMode && this.app_) {
+ const canvasRect = this.sceneManager_.getCanvasRect();
+ const uiCamera = this.app_.getResource(UICameraInfo);
+ if (canvasRect) {
+ uiCamera.worldLeft = canvasRect.left;
+ uiCamera.worldBottom = canvasRect.bottom;
+ uiCamera.worldRight = canvasRect.right;
+ uiCamera.worldTop = canvasRect.top;
+ uiCamera.valid = true;
+ } else {
+ uiCamera.valid = false;
+ }
+ }
+
+ this.context_.runFrame();
+ this.syncDerivedTransforms();
+ }
+
+ renderSceneView(width: number, height: number): void {
if (!this.pipeline_ || !this.sceneManager_ || !this.context_.initialized) return;
if (width <= 0 || height <= 0) return;
if (this.sceneManager_.isBusy) return;
- this.sceneManager_.setViewportSize(width, height);
-
const bg = this.findCanvasBackgroundColor();
- Renderer.setClearColor(bg.r, bg.g, bg.b, bg.a);
-
const canvasRect = this.sceneManager_.getCanvasRect();
if (canvasRect) {
this.camera_.orthoHalfHeight = (canvasRect.top - canvasRect.bottom) / 2;
@@ -354,39 +375,10 @@ export class EditorSceneRenderer {
const matrix = this.camera_.getViewProjection(width, height);
const elapsed = this.context_.elapsed;
-
const cppReg = this.sceneManager_.registry;
const registry = { _cpp: cppReg };
try {
- if (this.app_) {
- if (this.context_.isPlayMode) {
- const gameRenderer = this.context_.gameViewRenderer;
- if (gameRenderer && gameRenderer.visible) {
- gameRenderer.updateUICameraInfo(this.context_);
- }
- } else {
- const uiCamera = this.app_.getResource(UICameraInfo);
- if (canvasRect) {
- uiCamera.worldLeft = canvasRect.left;
- uiCamera.worldBottom = canvasRect.bottom;
- uiCamera.worldRight = canvasRect.right;
- uiCamera.worldTop = canvasRect.top;
- uiCamera.valid = true;
- } else {
- uiCamera.valid = false;
- }
- }
-
- this.context_.tickApp();
- this.syncDerivedTransforms();
- }
-
- const gameRenderer = this.context_.gameViewRenderer;
- if (gameRenderer && gameRenderer.visible) {
- gameRenderer.renderAndCapture(this.context_);
- }
-
const ppCamera = this.findFirstPPCamera();
if (ppCamera >= 0) {
PostProcess._applyForCamera(ppCamera);
@@ -409,13 +401,18 @@ export class EditorSceneRenderer {
}
} catch (e) {
if (e instanceof WebAssembly.RuntimeError) {
- console.warn('[EditorSceneRenderer] WASM error during render:', (e as Error).message);
+ console.warn('[EditorSceneRenderer] WASM error during scene render:', (e as Error).message);
} else {
throw e;
}
}
}
+ render(width: number, height: number): void {
+ this.tickAndRenderGameView(width, height);
+ this.renderSceneView(width, height);
+ }
+
renderGameCamera(width: number, height: number, vpMatrix: Float32Array): void {
if (!this.pipeline_ || !this.sceneManager_ || !this.context_.initialized) return;
if (width <= 0 || height <= 0) return;
diff --git a/editor/src/renderer/SharedRenderContext.ts b/editor/src/renderer/SharedRenderContext.ts
index 25218f03e..b2a2020a0 100644
--- a/editor/src/renderer/SharedRenderContext.ts
+++ b/editor/src/renderer/SharedRenderContext.ts
@@ -97,9 +97,16 @@ export class SharedRenderContext {
return mod._tl_getTime(result.handle);
}
+ private initPromise_: Promise<boolean> | null = null;
+
async init(module: ESEngineModule): Promise<boolean> {
if (this.initialized_) return true;
+ if (this.initPromise_) return this.initPromise_;
+ this.initPromise_ = this.doInit_(module);
+ return this.initPromise_;
+ }
+ private async doInit_(module: ESEngineModule): Promise<boolean> {
this.module_ = module;
const canvas = document.createElement('canvas');
@@ -218,6 +225,12 @@ export class SharedRenderContext {
setRenderCallback(callback: (() => void) | null): void {
this.renderCallback_ = callback;
+ if (callback && this.standaloneRafId_) {
+ cancelAnimationFrame(this.standaloneRafId_);
+ this.standaloneRafId_ = null;
+ } else if (!callback && this.continuousRender_) {
+ this.scheduleStandaloneRender_();
+ }
}
setGameViewRenderer(renderer: GameViewRenderer | null): void {
@@ -289,15 +302,83 @@ export class SharedRenderContext {
requestRender(): void {
this.isDirty_ = true;
- this.renderCallback_?.();
+ if (this.renderCallback_) {
+ this.renderCallback_();
+ } else if (this.continuousRender_) {
+ this.scheduleStandaloneRender_();
+ }
}
startContinuousRender(): void {
this.continuousRender_ = true;
+ if (!this.renderCallback_) {
+ this.scheduleStandaloneRender_();
+ }
}
stopContinuousRender(): void {
this.continuousRender_ = false;
+ if (this.standaloneRafId_) {
+ cancelAnimationFrame(this.standaloneRafId_);
+ this.standaloneRafId_ = null;
+ }
+ }
+
+ private standaloneRafId_: number | null = null;
+
+ private scheduleStandaloneRender_(): void {
+ if (this.standaloneRafId_ || this.renderCallback_) return;
+ this.standaloneRafId_ = requestAnimationFrame(() => {
+ this.standaloneRafId_ = null;
+ this.runStandaloneFrame_();
+ if (this.continuousRender_ && !this.renderCallback_) {
+ this.scheduleStandaloneRender_();
+ }
+ });
+ }
+
+ private frameTicked_ = false;
+
+ runFrame(): void {
+ if (this.frameTicked_) return;
+ this.frameTicked_ = true;
+
+ if (!this.initialized_ || !this.sceneManager_) return;
+ if (this.sceneManager_.isBusy) return;
+
+ try {
+ if (this.app_) {
+ if (this.playMode_) {
+ const gr = this.gameViewRenderer_;
+ if (gr && gr.visible) {
+ gr.updateUICameraInfo(this);
+ }
+ }
+
+ this.tickApp();
+ }
+
+ const gr = this.gameViewRenderer_;
+ if (gr && gr.visible) {
+ gr.renderAndCapture(this);
+ }
+ } catch (e) {
+ if (e instanceof WebAssembly.RuntimeError) {
+ console.warn('[SharedRenderContext] WASM error during frame:', (e as Error).message);
+ } else {
+ throw e;
+ }
+ }
+ }
+
+ resetFrameTick(): void {
+ this.frameTicked_ = false;
+ }
+
+ private runStandaloneFrame_(): void {
+ this.resetFrameTick();
+ this.runFrame();
+ this.firePostRenderCallback();
}
get isContinuousRender(): boolean {
diff --git a/editor/src/services/RuntimeService.ts b/editor/src/services/RuntimeService.ts
index 29bbd02c3..799e58214 100644
--- a/editor/src/services/RuntimeService.ts
+++ b/editor/src/services/RuntimeService.ts
@@ -37,6 +37,12 @@ export class RuntimeService {
setApp(app: App): void {
this.app_ = app;
this.bridge_ = new EditorBridge(app, this.store_);
+
+ const ctx = getSharedRenderContext();
+ if (!ctx.initialized && app.wasmModule) {
+ ctx.init(app.wasmModule);
+ }
+
for (const listener of this.appListeners_) {
listener(app, this.bridge_!);
}
diff --git a/editor/src/services/ScriptInjector.ts b/editor/src/services/ScriptInjector.ts
index 292250573..fd37a7eac 100644
--- a/editor/src/services/ScriptInjector.ts
+++ b/editor/src/services/ScriptInjector.ts
@@ -14,7 +14,6 @@ export class ScriptInjector {
this.app_ = app;
const ctx = getDefaultContext();
- const pendingBefore = ctx.pendingSystems.length;
(window as any).__esengine_shim__ = { esengine };
@@ -34,14 +33,11 @@ export class ScriptInjector {
console.error('[ScriptInjector] Failed to load user scripts:', e);
}
- const pending = ctx.pendingSystems;
- if (pending.length > pendingBefore) {
- for (let i = pendingBefore; i < pending.length; i++) {
- const entry = pending[i];
- app.addSystemToSchedule(entry.schedule as any, entry.system as any);
- this.injectedSystemIds_.push((entry.system as any)._id);
- }
- pending.length = 0;
+ const drained = ctx.drainPendingSystems();
+ for (const entry of drained) {
+ const templateId = (entry.system as any)._id;
+ app.addSystemToSchedule(entry.schedule as any, entry.system as any);
+ this.injectedSystemIds_.push(templateId);
}
}
diff --git a/editor/src/styles/content-browser.css b/editor/src/styles/content-browser.css
index ab12325a7..7ccbef452 100644
--- a/editor/src/styles/content-browser.css
+++ b/editor/src/styles/content-browser.css
@@ -47,6 +47,7 @@
padding: 4px 8px;
background: var(--es-bg-secondary);
border-bottom: 1px solid var(--es-border);
+ flex-wrap: wrap;
}
.es-content-browser-toolbar .es-content-search {
diff --git a/editor/src/styles/frame-debugger.css b/editor/src/styles/frame-debugger.css
index b9753552c..8f8dcda9e 100644
--- a/editor/src/styles/frame-debugger.css
+++ b/editor/src/styles/frame-debugger.css
@@ -15,6 +15,7 @@
background: var(--es-bg-secondary);
border-bottom: 1px solid var(--es-border);
flex-shrink: 0;
+ flex-wrap: wrap;
}
.es-fd-btn {
diff --git a/editor/src/styles/game-view.css b/editor/src/styles/game-view.css
index 25bd42dee..c3c3439dd 100644
--- a/editor/src/styles/game-view.css
+++ b/editor/src/styles/game-view.css
@@ -7,12 +7,15 @@
.es-gameview-tools {
display: flex;
align-items: center;
+ flex-wrap: wrap;
}
.es-gameview-toolbar {
display: flex;
align-items: center;
gap: 8px;
+ flex-wrap: wrap;
+ padding: 4px 8px;
}
.es-gameview-controls {
diff --git a/editor/src/styles/profiler.css b/editor/src/styles/profiler.css
index f940dec4c..0a52d291e 100644
--- a/editor/src/styles/profiler.css
+++ b/editor/src/styles/profiler.css
@@ -32,6 +32,7 @@
background: var(--es-bg-secondary);
border-bottom: 1px solid var(--es-border);
flex-shrink: 0;
+ flex-wrap: wrap;
}
.es-profiler-btn {
diff --git a/editor/src/styles/timeline.css b/editor/src/styles/timeline.css
index bf25544c7..f6f185bae 100644
--- a/editor/src/styles/timeline.css
+++ b/editor/src/styles/timeline.css
@@ -41,6 +41,7 @@
background: var(--es-bg-secondary);
border-bottom: 1px solid var(--es-border);
flex-shrink: 0;
+ flex-wrap: wrap;
}
.es-timeline-transport {
diff --git a/sdk/src/app.ts b/sdk/src/app.ts
index 343ad1937..676fa9264 100644
--- a/sdk/src/app.ts
+++ b/sdk/src/app.ts
@@ -58,6 +58,8 @@ export class App {
private readonly resources_: ResourceStorage;
private readonly systems_ = new Map<Schedule, SystemEntry[]>();
private runner_: SystemRunner | null = null;
+ private systemCounter_ = 0;
+ private readonly templateToRuntime_ = new Map<symbol, symbol>();
private running_ = false;
private lastTime_ = 0;
@@ -168,8 +170,17 @@ export class App {
system: SystemDef,
options?: { runBefore?: string[]; runAfter?: string[]; runIf?: RunCondition }
): this {
+ const name = system._name || `System_${++this.systemCounter_}`;
+ const scoped: SystemDef = {
+ _id: Symbol(`System_${name}`),
+ _params: system._params,
+ _fn: system._fn,
+ _name: name,
+ };
+ this.templateToRuntime_.set(system._id, scoped._id);
+
this.systems_.get(schedule)!.push({
- system,
+ system: scoped,
runBefore: options?.runBefore,
runAfter: options?.runAfter,
runIf: options?.runIf,
@@ -187,15 +198,20 @@ export class App {
}
removeSystem(systemId: symbol): boolean {
+ const runtimeId = this.templateToRuntime_.get(systemId) ?? systemId;
let removed = false;
for (const [schedule, entries] of this.systems_) {
- const filtered = entries.filter(e => e.system._id !== systemId);
+ const filtered = entries.filter(e => e.system._id !== runtimeId);
if (filtered.length !== entries.length) {
this.systems_.set(schedule, filtered);
this.sortedSystemsCache_.delete(schedule);
removed = true;
}
}
+ if (removed) {
+ this.runner_?.evict(runtimeId);
+ this.templateToRuntime_.delete(systemId);
+ }
return removed;
}
@@ -466,6 +482,13 @@ export class App {
}
this.world_.disconnectCpp();
+ for (const [, entries] of this.systems_) {
+ entries.length = 0;
+ }
+ this.sortedSystemsCache_.clear();
+ this.templateToRuntime_.clear();
+ this.systemCounter_ = 0;
+
this.pipeline_ = null;
this.runner_ = null;
this.module_ = null;
@@ -476,6 +499,8 @@ export class App {
// =========================================================================
private async runFrame_(delta: number): Promise<void> {
+ this.runner_?.clearTimings();
+ this.phaseTimings_?.clear();
this.eventRegistry_.swapAll();
this.world_.advanceTick();
this.updateTime(delta);
@@ -736,11 +761,8 @@ export function createWebApp(module: ESEngineModule, options?: WebAppOptions): A
}
export function flushPendingSystems(app: App): void {
- const pending = getDefaultContext().pendingSystems;
- if (pending.length === 0) return;
-
- for (const entry of pending) {
+ const drained = getDefaultContext().drainPendingSystems();
+ for (const entry of drained) {
app.addSystemToSchedule(entry.schedule as Schedule, entry.system as SystemDef);
}
- pending.length = 0;
}
diff --git a/sdk/src/context.ts b/sdk/src/context.ts
index bbaaf94bf..f16aa142a 100644
--- a/sdk/src/context.ts
+++ b/sdk/src/context.ts
@@ -16,6 +16,19 @@ export class AppContext {
readonly componentRegistry = new Map<string, any>();
readonly pendingSystems: PendingSystemEntry[] = [];
editorBridge: EditorBridge | null = null;
+
+ /** @brief Drain all pending systems and clear the queue */
+ drainPendingSystems(): PendingSystemEntry[] {
+ const drained = this.pendingSystems.splice(0);
+ return drained;
+ }
+
+ /** @brief Reset all mutable state for a new session */
+ reset(): void {
+ this.pendingSystems.length = 0;
+ this.componentRegistry.clear();
+ this.editorBridge = null;
+ }
}
let defaultContext_: AppContext | null = null;
diff --git a/sdk/src/system.ts b/sdk/src/system.ts
index c420b528a..f7c92f39e 100644
--- a/sdk/src/system.ts
+++ b/sdk/src/system.ts
@@ -89,7 +89,7 @@ export interface SystemDef {
readonly _name: string;
}
-let systemCounter = 0;
+let templateCounter_ = 0;
export interface SystemOptions {
name?: string;
@@ -102,13 +102,13 @@ export function defineSystem<P extends readonly SystemParam[]>(
fn: (...args: InferParams<P>) => void | Promise<void>,
options?: SystemOptions
): SystemDef {
- const id = ++systemCounter;
+ const tid = ++templateCounter_;
return {
- _id: Symbol(`System_${id}_${options?.name ?? ''}`),
+ _id: Symbol(`SystemTemplate_${tid}`),
_params: params,
_fn: fn as (...args: never[]) => void,
- _name: options?.name ?? `System_${id}`
+ _name: options?.name ?? ''
};
}
@@ -161,6 +161,27 @@ export class SystemRunner {
return this.timings_;
}
+ /** @brief Clear timing data for the current frame */
+ clearTimings(): void {
+ this.timings_?.clear();
+ }
+
+ /** @brief Remove cached state for a single system */
+ evict(systemId: symbol): void {
+ this.argsCache_.delete(systemId);
+ this.systemTicks_.delete(systemId);
+ this.queryCache_.delete(systemId);
+ this.removedCache_.delete(systemId);
+ }
+
+ /** @brief Clear all cached state */
+ reset(): void {
+ this.argsCache_.clear();
+ this.systemTicks_.clear();
+ this.queryCache_.clear();
+ this.removedCache_.clear();
+ }
+
run(system: SystemDef): void | Promise<void> {
let args = this.argsCache_.get(system._id);
if (!args) {
diff --git a/sdk/tests/system.test.ts b/sdk/tests/system.test.ts
index eb14fab99..35c8d4882 100644
--- a/sdk/tests/system.test.ts
+++ b/sdk/tests/system.test.ts
@@ -116,9 +116,9 @@ describe('defineSystem', () => {
expect(sys._name).toBe('MovementSystem');
});
- it('should auto-generate name when not provided', () => {
+ it('should default to empty name when not provided', () => {
const sys = defineSystem([], () => {});
- expect(sys._name).toMatch(/^System_\d+$/);
+ expect(sys._name).toBe('');
});
it('should create unique ids for different systems', () => {
@@ -157,6 +157,18 @@ describe('Global system registration', () => {
const pending = getDefaultContext().pendingSystems;
expect(pending).toContainEqual({ schedule: Schedule.Last, system: sys });
});
+
+ it('drainPendingSystems should return entries and clear queue', () => {
+ const sys = defineSystem([], () => {});
+ addSystem(sys);
+ const ctx = getDefaultContext();
+ expect(ctx.pendingSystems.length).toBe(1);
+
+ const drained = ctx.drainPendingSystems();
+ expect(drained).toHaveLength(1);
+ expect(drained[0].system).toBe(sys);
+ expect(ctx.pendingSystems.length).toBe(0);
+ });
});
// =============================================================================
@@ -351,4 +363,32 @@ describe('SystemRunner', () => {
expect(() => runner.run(sys)).toThrow('Unknown system parameter type');
});
});
+
+ describe('evict and reset', () => {
+ it('evict should clear cached state for a system', () => {
+ const fn = vi.fn();
+ const sys = defineSystem([], fn);
+ runner.run(sys);
+ expect(fn).toHaveBeenCalledOnce();
+
+ runner.evict(sys._id);
+ runner.run(sys);
+ expect(fn).toHaveBeenCalledTimes(2);
+ });
+
+ it('reset should clear all cached state', () => {
+ const fn1 = vi.fn();
+ const fn2 = vi.fn();
+ const sys1 = defineSystem([], fn1);
+ const sys2 = defineSystem([], fn2);
+ runner.run(sys1);
+ runner.run(sys2);
+
+ runner.reset();
+ runner.run(sys1);
+ runner.run(sys2);
+ expect(fn1).toHaveBeenCalledTimes(2);
+ expect(fn2).toHaveBeenCalledTimes(2);
+ });
+ });
});