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(editor): scene-camera gizmos + Output Log wired to real logs

esengine816c5e7edfe1
diff --git a/desktop/src/engine/ViewportController.ts b/desktop/src/engine/ViewportController.ts
index f6f239d84..f3bfa8837 100644
--- a/desktop/src/engine/ViewportController.ts
+++ b/desktop/src/engine/ViewportController.ts
@@ -1,4 +1,4 @@
-import { CameraView, EditorView, Sprite, Transform } from 'esengine';
+import { Camera, CameraView, EditorView, Sprite, Transform } from 'esengine';
import type { EntityId } from '@/types';
import { EngineHost } from './EngineHost';
@@ -156,4 +156,51 @@ export const ViewportController = {
view.x = pos.x;
view.y = pos.y;
},
+
+ /** Ids of the scene's camera entities — the camera-gizmo set (structural). */
+ cameraIds(): EntityId[] {
+ const world = EngineHost.world;
+ if (!world) return [];
+ const out: EntityId[] = [];
+ for (const e of world.getAllEntities()) {
+ if (world.has(e, Camera) && world.has(e, Transform)) out.push(e);
+ }
+ return out;
+ },
+
+ /**
+ * Screen-space icon position + authored view rect (CSS px) of a scene camera,
+ * for drawing its gizmo. The rect is the camera's authored framing (orthoSize
+ * half-height × the viewport aspect) — what that game camera is set to see.
+ */
+ getCameraGizmo(
+ id: EntityId,
+ ): { cx: number; cy: number; rect: { x: number; y: number; w: number; h: number } } | null {
+ const world = EngineHost.world;
+ const canvas = EngineHost.canvas;
+ if (!world || !canvas || !world.valid(id) || !world.has(id, Camera) || !world.has(id, Transform)) {
+ return null;
+ }
+ const t = world.get(id, Transform);
+ const c = world.get(id, Camera) as { orthoSize?: number };
+ const halfH = c.orthoSize ?? 360;
+ const aspect = canvas.height > 0 ? canvas.width / canvas.height : 1;
+ const halfW = halfH * aspect;
+ const x = t.position.x;
+ const y = t.position.y;
+ const center = this.worldToClient(x, y);
+ if (!center) return null;
+ const corners = [
+ [x - halfW, y - halfH],
+ [x + halfW, y - halfH],
+ [x + halfW, y + halfH],
+ [x - halfW, y + halfH],
+ ].map(([wx, wy]) => this.worldToClient(wx, wy));
+ if (corners.some((p) => !p)) return null;
+ const xs = corners.map((p) => p!.x);
+ const ys = corners.map((p) => p!.y);
+ const minX = Math.min(...xs);
+ const minY = Math.min(...ys);
+ return { cx: center.x, cy: center.y, rect: { x: minX, y: minY, w: Math.max(...xs) - minX, h: Math.max(...ys) - minY } };
+ },
};
diff --git a/desktop/src/main.tsx b/desktop/src/main.tsx
index 05be5cdbb..f08633216 100644
--- a/desktop/src/main.tsx
+++ b/desktop/src/main.tsx
@@ -16,6 +16,10 @@ import './theme/dockview-theme.css';
import './theme/app.css';
import './theme/launcher.css';
import { App } from './App';
+import { LogStore } from './store/LogStore';
+
+// Capture console (editor + SDK + wasm) into the Output Log panel from startup.
+LogStore.install();
createRoot(document.getElementById('root')!).render(
<StrictMode>
diff --git a/desktop/src/mock/sceneData.ts b/desktop/src/mock/sceneData.ts
deleted file mode 100644
index e66617612..000000000
--- a/desktop/src/mock/sceneData.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import type { AssetItem, LogEntry } from '@/types';
-
-// Placeholder content for panels not yet wired to live data (Content Browser,
-// Output Log). The scene tree and inspector now read the real engine — see
-// EngineHost.readSceneTree / readInspector.
-
-export const MOCK_ASSETS: AssetItem[] = [
- { id: 'a1', name: 'scenes', type: 'folder' },
- { id: 'a2', name: 'sprites', type: 'folder' },
- { id: 'a3', name: 'audio', type: 'folder' },
- { id: 'a4', name: 'scripts', type: 'folder' },
- { id: 'a5', name: 'Level_01', type: 'scene' },
- { id: 'a6', name: 'hero', type: 'spine' },
- { id: 'a7', name: 'slime', type: 'sprite' },
- { id: 'a8', name: 'tileset', type: 'texture' },
- { id: 'a9', name: 'jump', type: 'audio' },
- { id: 'a10', name: 'Coin', type: 'prefab' },
- { id: 'a11', name: 'water', type: 'material' },
- { id: 'a12', name: 'PlayerController', type: 'script' },
- { id: 'a13', name: 'Bullet', type: 'prefab' },
- { id: 'a14', name: 'explosion', type: 'texture' },
-];
-
-export const MOCK_LOG: LogEntry[] = [
- { id: 1, level: 'info', time: '12:04:01', source: 'Engine', message: 'esengine.wasm instantiated (1.34 MB) in 38ms' },
- { id: 2, level: 'info', time: '12:04:01', source: 'Assets', message: 'Loaded project "platformer" — 14 assets indexed' },
- { id: 3, level: 'success', time: '12:04:02', source: 'Scene', message: 'Opened Level_01.scene — 15 entities, 38 components' },
- { id: 4, level: 'warn', time: '12:04:05', source: 'Spine', message: 'Player: animation "dash" referenced but not found in skeleton' },
- { id: 5, level: 'info', time: '12:04:06', source: 'Physics', message: 'Box2D world stepped at fixed 60Hz' },
- { id: 6, level: 'error', time: '12:04:09', source: 'Script', message: 'PlayerController.ts:42 — Cannot read "velocity" of undefined' },
- { id: 7, level: 'info', time: '12:04:12', source: 'Render', message: 'Draw calls: 23 · batches: 6 · triangles: 4.1k' },
-];
diff --git a/desktop/src/panels/OutputLog.tsx b/desktop/src/panels/OutputLog.tsx
index 4e87b1f9d..68a0a3fd9 100644
--- a/desktop/src/panels/OutputLog.tsx
+++ b/desktop/src/panels/OutputLog.tsx
@@ -1,31 +1,106 @@
-import { Trash2, Filter, ArrowDownToLine } from 'lucide-react';
-import { MOCK_LOG } from '@/mock/sceneData';
+import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
+import { Trash2, ArrowDownToLine, Search } from 'lucide-react';
+import { LogStore, type LogLevel } from '@/store/LogStore';
+
+type Filter = 'all' | LogLevel;
export function OutputLog() {
+ const entries = useSyncExternalStore(LogStore.subscribe, LogStore.getSnapshot);
+ const [filter, setFilter] = useState<Filter>('all');
+ const [query, setQuery] = useState('');
+ const bodyRef = useRef<HTMLDivElement>(null);
+ const stick = useRef(true); // stay pinned to the bottom unless the user scrolls up
+
+ const counts = useMemo(() => {
+ let warn = 0;
+ let error = 0;
+ for (const e of entries) {
+ if (e.level === 'warn') warn++;
+ else if (e.level === 'error') error++;
+ }
+ return { warn, error };
+ }, [entries]);
+
+ const visible = useMemo(() => {
+ const q = query.trim().toLowerCase();
+ return entries.filter(
+ (e) =>
+ (filter === 'all' || e.level === filter) &&
+ (!q || e.message.toLowerCase().includes(q) || e.source.toLowerCase().includes(q)),
+ );
+ }, [entries, filter, query]);
+
+ // Auto-scroll to the newest line while pinned to the bottom.
+ useEffect(() => {
+ const el = bodyRef.current;
+ if (el && stick.current) el.scrollTop = el.scrollHeight;
+ }, [visible]);
+
+ const onScroll = () => {
+ const el = bodyRef.current;
+ if (el) stick.current = el.scrollHeight - el.scrollTop - el.clientHeight < 24;
+ };
+ const scrollToBottom = () => {
+ const el = bodyRef.current;
+ if (el) {
+ el.scrollTop = el.scrollHeight;
+ stick.current = true;
+ }
+ };
+
+ const Pill = ({ id, label, badge }: { id: Filter; label: string; badge?: number }) => (
+ <button
+ type="button"
+ className={`pill${filter === id ? ' is-active' : ''}`}
+ onClick={() => setFilter(id)}
+ >
+ {id !== 'all' && <i className={`dot dot--${id}`} />}
+ {label}
+ {badge ? <span className="pill__badge">{badge}</span> : null}
+ </button>
+ );
+
return (
<div className="panel log">
<div className="panel__toolbar">
<div className="log__filters">
- <button type="button" className="pill is-active">All</button>
- <button type="button" className="pill"><i className="dot dot--info" />Info</button>
- <button type="button" className="pill"><i className="dot dot--warn" />Warnings</button>
- <button type="button" className="pill"><i className="dot dot--error" />Errors</button>
+ <Pill id="all" label="All" />
+ <Pill id="info" label="Info" />
+ <Pill id="warn" label="Warnings" badge={counts.warn} />
+ <Pill id="error" label="Errors" badge={counts.error} />
</div>
<div className="log__tools">
- <button type="button" className="iconbtn" title="Filter source"><Filter size={14} strokeWidth={1.85} /></button>
- <button type="button" className="iconbtn" title="Scroll to bottom"><ArrowDownToLine size={14} strokeWidth={1.85} /></button>
- <button type="button" className="iconbtn" title="Clear log"><Trash2 size={14} strokeWidth={1.85} /></button>
+ <div className="log__search">
+ <Search size={12} strokeWidth={1.9} />
+ <input
+ value={query}
+ spellCheck={false}
+ placeholder="Filter"
+ onChange={(e) => setQuery(e.target.value)}
+ />
+ </div>
+ <button type="button" className="iconbtn" title="Scroll to bottom" onClick={scrollToBottom}>
+ <ArrowDownToLine size={14} strokeWidth={1.85} />
+ </button>
+ <button type="button" className="iconbtn" title="Clear log" onClick={() => LogStore.clear()}>
+ <Trash2 size={14} strokeWidth={1.85} />
+ </button>
</div>
</div>
- <div className="panel__body log__body mono">
- {MOCK_LOG.map((e) => (
+ <div ref={bodyRef} className="panel__body log__body mono" onScroll={onScroll}>
+ {visible.map((e) => (
<div key={e.id} className={`logline logline--${e.level}`}>
<span className="logline__time">{e.time}</span>
<span className="logline__source">{e.source}</span>
<span className="logline__msg">{e.message}</span>
</div>
))}
+ {visible.length === 0 && (
+ <div className="log__empty">
+ {entries.length === 0 ? 'No log output yet.' : 'No entries match the filter.'}
+ </div>
+ )}
</div>
</div>
);
diff --git a/desktop/src/panels/Viewport.tsx b/desktop/src/panels/Viewport.tsx
index 3e607af47..e8329094a 100644
--- a/desktop/src/panels/Viewport.tsx
+++ b/desktop/src/panels/Viewport.tsx
@@ -1,8 +1,8 @@
-import { useEffect, useRef, useState, useSyncExternalStore } from 'react';
+import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
import type { PointerEvent as ReactPointerEvent } from 'react';
import {
MousePointer2, Move, RotateCw, Scale3d, Grid3x3, Eye, Magnet, Frame,
- Loader2, TriangleAlert, type LucideIcon,
+ Camera, Loader2, TriangleAlert, type LucideIcon,
} from 'lucide-react';
import { useEditorStore } from '@/store/editorStore';
import { useSelection } from '@/store/selectionStore';
@@ -11,6 +11,7 @@ import { EngineHost } from '@/engine/EngineHost';
import { ViewportController } from '@/engine/ViewportController';
import { SceneCommands } from '@/engine/SceneCommands';
import { SceneQuery } from '@/engine/SceneQuery';
+import { SceneStore } from '@/engine/SceneStore';
import { StatsStore } from '@/engine/StatsStore';
import type { ToolMode } from '@/types';
@@ -110,6 +111,16 @@ export function Viewport() {
const [zoomPct, setZoomPct] = useState(100);
const engine = useSyncExternalStore(EngineHost.subscribe, EngineHost.getSnapshot);
+ // Scene cameras don't render in edit mode (the viewport is the editor camera),
+ // so draw each as a gizmo (icon + authored view rect). The id set updates on
+ // structural change; the rAF below positions them every frame.
+ const structRev = useSyncExternalStore(SceneStore.subscribe, SceneStore.getStructureRevision);
+ const camRefs = useRef(new Map<number, HTMLDivElement | null>());
+ const camIds = useMemo(
+ () => (engine.status === 'ready' ? ViewportController.cameraIds() : []),
+ [structRev, engine.status],
+ );
+
// Mount the live engine canvas into the stage; it survives panel re-docking.
useEffect(() => {
const stage = stageRef.current;
@@ -163,6 +174,27 @@ export function Viewport() {
} else {
sel.style.opacity = '0';
}
+
+ // Scene-camera gizmos — only in edit mode (in play the viewport IS the
+ // game camera), and only when gizmos are on.
+ const camsOn = ready && showG && !useEditorStore.getState().isPlaying;
+ for (const [cid, wrap] of camRefs.current) {
+ if (!wrap) continue;
+ const cg = camsOn ? ViewportController.getCameraGizmo(cid) : null;
+ if (cg) {
+ wrap.style.opacity = '1';
+ const icon = wrap.firstElementChild as HTMLElement | null;
+ const rectEl = wrap.lastElementChild as HTMLElement | null;
+ if (icon) icon.style.transform = `translate(${cg.cx}px, ${cg.cy}px)`;
+ if (rectEl) {
+ rectEl.style.transform = `translate(${cg.rect.x}px, ${cg.rect.y}px)`;
+ rectEl.style.width = `${cg.rect.w}px`;
+ rectEl.style.height = `${cg.rect.h}px`;
+ }
+ } else {
+ wrap.style.opacity = '0';
+ }
+ }
};
raf = requestAnimationFrame(tick);
return () => cancelAnimationFrame(raf);
@@ -287,6 +319,22 @@ export function Viewport() {
onContextMenu={(e) => e.preventDefault()}
/>
+ {/* Scene-camera gizmos (icon + authored view rect); positioned by the rAF. */}
+ {camIds.map((id) => (
+ <div
+ key={id}
+ ref={(el) => {
+ if (el) camRefs.current.set(id, el);
+ else camRefs.current.delete(id);
+ }}
+ className="viewport__cam-gizmo"
+ aria-hidden="true"
+ >
+ <Camera className="viewport__cam-icon" size={15} strokeWidth={1.75} />
+ <div className="viewport__cam-rect" />
+ </div>
+ ))}
+
<div ref={selectionRef} className="viewport__selection" aria-hidden="true" />
<div ref={gizmoRef} className="viewport__gizmo" aria-hidden="true">
diff --git a/desktop/src/store/LogStore.ts b/desktop/src/store/LogStore.ts
new file mode 100644
index 000000000..c2731cc3b
--- /dev/null
+++ b/desktop/src/store/LogStore.ts
@@ -0,0 +1,103 @@
+/**
+ * @file LogStore.ts
+ * @brief The editor's Output Log feed. Everything the editor, the SDK, and the
+ * wasm engine emit ultimately goes through `console.*` (EngineHost routes
+ * wasm print/printErr there; the SDK logger's ConsoleLogHandler too), so
+ * intercepting console in one place captures the whole stream. Entries
+ * are kept in a capped ring buffer; the OutputLog panel renders them.
+ */
+import { createStore } from 'zustand/vanilla';
+
+export type LogLevel = 'info' | 'warn' | 'error';
+
+export interface LogEntry {
+ id: number;
+ level: LogLevel;
+ time: string;
+ source: string;
+ message: string;
+}
+
+const CAP = 2000; // ring-buffer cap — long sessions can't grow the log unbounded
+
+const pad = (n: number) => (n < 10 ? `0${n}` : `${n}`);
+function stamp(): string {
+ const d = new Date();
+ return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
+}
+
+function fmtArg(a: unknown): string {
+ if (typeof a === 'string') return a;
+ if (a instanceof Error) return a.stack || a.message;
+ if (a === null) return 'null';
+ if (a === undefined) return 'undefined';
+ if (typeof a === 'object') {
+ try {
+ return JSON.stringify(a);
+ } catch {
+ return String(a);
+ }
+ }
+ return String(a);
+}
+
+/** Pull a source tag out of a formatted line, handling both log shapes. */
+export function parseSource(raw: string): { source: string; message: string } {
+ // SDK logger: "[12:00:00.000] [WARN ] [scene] message"
+ let m = /^\[[\d:.]+\]\s*\[[A-Za-z]+\s*\]\s*\[([^\]]+)\]\s*([\s\S]*)$/.exec(raw);
+ if (m) return { source: m[1].trim(), message: m[2] };
+ // EngineHost / editor: "[source] message" (skip if the tag looks like a time)
+ m = /^\[([^\]]+)\]\s*([\s\S]*)$/.exec(raw);
+ if (m && !/[:.]/.test(m[1])) return { source: m[1].trim(), message: m[2] };
+ return { source: '', message: raw };
+}
+
+class LogStoreImpl {
+ private readonly store = createStore<{ entries: LogEntry[] }>(() => ({ entries: [] }));
+ private seq = 0;
+ private installed = false;
+ private capturing = false;
+
+ subscribe = (fn: () => void): (() => void) => this.store.subscribe(fn);
+ getSnapshot = (): LogEntry[] => this.store.getState().entries;
+
+ push(level: LogLevel, source: string, message: string): void {
+ const entry: LogEntry = { id: ++this.seq, level, time: stamp(), source, message };
+ const cur = this.store.getState().entries;
+ const next = cur.length >= CAP ? [...cur.slice(cur.length - CAP + 1), entry] : [...cur, entry];
+ this.store.setState({ entries: next });
+ }
+
+ clear(): void {
+ this.store.setState({ entries: [] });
+ }
+
+ /** Patch console.* once so every log (editor + SDK + wasm) flows into the panel. */
+ install(): void {
+ if (this.installed) return;
+ this.installed = true;
+ const wrap = (method: 'log' | 'info' | 'debug' | 'warn' | 'error', level: LogLevel) => {
+ const orig = console[method].bind(console);
+ console[method] = (...args: unknown[]) => {
+ orig(...args);
+ if (this.capturing) return; // guard against logs emitted while capturing
+ this.capturing = true;
+ try {
+ const { source, message } = parseSource(args.map(fmtArg).join(' '));
+ this.push(level, source, message);
+ } catch {
+ /* never let logging break the app */
+ } finally {
+ this.capturing = false;
+ }
+ };
+ };
+ wrap('log', 'info');
+ wrap('info', 'info');
+ wrap('debug', 'info');
+ wrap('warn', 'warn');
+ wrap('error', 'error');
+ }
+}
+
+export const LogStore = new LogStoreImpl();
diff --git a/desktop/src/theme/app.css b/desktop/src/theme/app.css
index ec142037a..6af61219e 100644
--- a/desktop/src/theme/app.css
+++ b/desktop/src/theme/app.css
@@ -579,6 +579,30 @@
filter: drop-shadow(0 0 6px rgba(0, 0, 0, 0.6));
}
+/* Scene-camera gizmo: a camera icon at the camera + its authored view rect. */
+.viewport__cam-gizmo {
+ position: absolute;
+ inset: 0;
+ z-index: 2;
+ pointer-events: none;
+}
+.viewport__cam-icon {
+ position: absolute;
+ left: 0;
+ top: 0;
+ margin: -8px 0 0 -8px;
+ color: var(--star-hi);
+ filter: drop-shadow(0 0 2px rgba(0, 0, 0, 0.75));
+}
+.viewport__cam-rect {
+ position: absolute;
+ left: 0;
+ top: 0;
+ border: 1px dashed var(--star-line);
+ border-radius: 2px;
+ background: rgba(76, 143, 214, 0.04);
+}
+
.viewport__overlay {
position: absolute;
display: flex;
@@ -1417,6 +1441,45 @@
.logline--success .logline__msg {
color: var(--run);
}
+.log__search {
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ height: 24px;
+ padding: 0 7px;
+ background: var(--input);
+ border: 1px solid var(--line);
+ border-radius: var(--r-sm);
+ color: var(--text-faint);
+}
+.log__search:focus-within {
+ border-color: var(--star-line);
+}
+.log__search input {
+ width: 110px;
+ background: none;
+ border: none;
+ outline: none;
+ color: var(--text-hi);
+ font-size: var(--fs-xs);
+}
+.log__search input::placeholder {
+ color: var(--text-faint);
+}
+.pill__badge {
+ margin-left: 5px;
+ padding: 0 4px;
+ border-radius: 999px;
+ background: var(--line-strong);
+ color: var(--text);
+ font-size: var(--fs-2xs);
+ font-variant-numeric: tabular-nums;
+}
+.log__empty {
+ padding: 16px 12px;
+ color: var(--text-faint);
+ font-size: var(--fs-xs);
+}
/* ----------------------------------------------------------------- toasts --- */
.toaster {
diff --git a/desktop/tests/log-store.test.ts b/desktop/tests/log-store.test.ts
new file mode 100644
index 000000000..844720d44
--- /dev/null
+++ b/desktop/tests/log-store.test.ts
@@ -0,0 +1,34 @@
+/**
+ * @file LogStore source parsing — the two log line shapes that flow through
+ * console into the Output Log: the SDK logger's "[time] [LEVEL] [cat] msg"
+ * and EngineHost's "[source] msg".
+ */
+import { describe, it, expect } from 'vitest';
+import { parseSource } from '@/store/LogStore';
+
+describe('parseSource', () => {
+ it('extracts the category from the SDK logger format', () => {
+ expect(parseSource('[12:00:00.088] [WARN ] [scene] Unknown component type: X')).toEqual({
+ source: 'scene',
+ message: 'Unknown component type: X',
+ });
+ });
+
+ it('extracts the source from the EngineHost / editor format', () => {
+ expect(parseSource('[wasm] esengine.wasm instantiated')).toEqual({
+ source: 'wasm',
+ message: 'esengine.wasm instantiated',
+ });
+ expect(parseSource('[engine] boot ok')).toEqual({ source: 'engine', message: 'boot ok' });
+ });
+
+ it('leaves a plain line untouched', () => {
+ expect(parseSource('just a message')).toEqual({ source: '', message: 'just a message' });
+ });
+
+ it('does not mistake a leading timestamp tag for a source', () => {
+ const r = parseSource('[12:00:00] hello');
+ expect(r.source).toBe('');
+ expect(r.message).toBe('[12:00:00] hello');
+ });
+});