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
feat(editor): inspector, overlay, tool, asset-type and context-menu contributions
esenginef0e88d481b29
diff --git a/desktop/src/components/icons.tsx b/desktop/src/components/icons.tsxindex 1707ba0d3..b2b6718c6 100644--- a/desktop/src/components/icons.tsx+++ b/desktop/src/components/icons.tsx@@ -21,7 +21,7 @@ import {type LucideIcon,} from 'lucide-react';import type { NodeKind, AssetType } from '@/types';-import { ASSET_TYPES } from '@/project/assetTypes';+import { assetTypeDef } from '@/project/assetTypes';// Scene-node kind → glyph. Keeps the outliner legible at a glance.const NODE_ICON: Record<NodeKind, LucideIcon> = {@@ -42,12 +42,12 @@ export function NodeIcon({ kind, size = 14 }: { kind: NodeKind; size?: number })}export function AssetIcon({ type, size = 22 }: { type: AssetType; size?: number }) {- const { icon: Glyph, tint } = ASSET_TYPES[type];+ const { icon: Glyph, tint } = assetTypeDef(type);return <Glyph size={size} strokeWidth={1.5} color={tint} />;}export function assetTint(type: AssetType): string {- return ASSET_TYPES[type].tint;+ return assetTypeDef(type).tint;}// Component (by registry name) → glyph, for the Add-Component picker. Knowndiff --git a/desktop/src/engine/entitySources.ts b/desktop/src/engine/entitySources.tsindex 90e537dab..7947c55b7 100644--- a/desktop/src/engine/entitySources.ts+++ b/desktop/src/engine/entitySources.ts@@ -80,6 +80,19 @@ function preset(name: string, comps: CompSpec[]): PrefabData {};}+/**+ * Build a one-entity prefab from `{ type, data? }` specs, layering each `data` over+ * that component's registered defaults — the door contributed entity templates come+ * through, so a plugin never hand-writes PrefabData (version, prefabEntityId, parent+ * wiring) and cannot produce a malformed one.+ */+export function prefabFromSpecs(+ name: string,+ specs: readonly { type: string; data?: Record<string, unknown> }[],+): PrefabData {+ return preset(name, specs.map((s) => (s.data ? [s.type, s.data] : s.type) as CompSpec));+}+/*** A Transform + Sprite prefab referencing `textureRef`, sized to `size` (the model* side of "drag an image into the viewport"). Size is a plain vec2, so the presetdiff --git a/desktop/src/main.tsx b/desktop/src/main.tsxindex fffb9bead..ca2628efc 100644--- a/desktop/src/main.tsx+++ b/desktop/src/main.tsx@@ -61,7 +61,7 @@ import { PerfMonitor } from './engine/PerfMonitor';import { LogStore } from './store/LogStore';import { initFsWatch } from './project/fsWatch';import { initPlugins } from './plugins/init';-import { ASSET_OPEN } from './project/assetOpen';+import { openAssetOfType } from './project/assetOpen';import { assetTypeOf } from './project/assetTypes';import { initBackgroundThrottle } from './engine/backgroundThrottle';// Register the built-in settings (side effect) and replay persisted ones.@@ -222,7 +222,7 @@ if (new URLSearchParams(location.search).has('automation')) {/** Double-click-open an asset by project path (FSM/BT/tileset/clip editors…). */openAsset: (path: string) => {const name = path.split('/').pop() ?? path;- ASSET_OPEN[assetTypeOf(name)]?.(path, name);+ openAssetOfType(assetTypeOf(name), path, name);},reveal: (id: string) => dockApi.revealAndExpand(id),/** Open a registered panel by id, docking it where its def says (reveal onlydiff --git a/desktop/src/panels/ContentBrowser.tsx b/desktop/src/panels/ContentBrowser.tsxindex e85ac072c..45e831706 100644--- a/desktop/src/panels/ContentBrowser.tsx+++ b/desktop/src/panels/ContentBrowser.tsx@@ -14,7 +14,9 @@ import { ProjectStore } from '@/project/ProjectStore';import { Toasts } from '@/store/Toasts';import { useSelection } from '@/store/selectionStore';import { IMAGE_RE, assetTypeOf as assetType, baseName, TYPE_CODE } from '@/project/assetMeta';-import { ASSET_OPEN } from '@/project/assetOpen';+import { openAssetOfType } from '@/project/assetOpen';+import { assetTypeRegistry } from '@/project/assetTypes';+import { contributedContextRows } from '@/plugins/contextMenus';import { syncAssetPaths } from '@/project/assetPathSync';import { findAssetUsages, type AssetUsage } from '@/project/assetUsages';import { FindUsagesDialog } from '@/components/FindUsagesDialog';@@ -464,7 +466,7 @@ export function ContentBrowser() {go(path);return;}- ASSET_OPEN[assetType(name)]?.(path, name);+ openAssetOfType(assetType(name), path, name);};// After any fs mutation: re-read open directories + re-scan the asset registry@@ -736,11 +738,20 @@ export function ContentBrowser() {}};- const newAssetItems: MenuItem[] = NEW_ASSET_TYPES.map((a) =>- a.templates- ? { label: t(a.labelKey), children: a.templates().map((tpl) => ({ label: tpl.label, onClick: () => void runNew(tpl.create) })) }- : { label: t(a.labelKey), onClick: () => void runNew(a.create!, a.errorKey) },- );+ const newAssetItems: MenuItem[] = [+ ...NEW_ASSET_TYPES.map((a) =>+ a.templates+ ? { label: t(a.labelKey), children: a.templates().map((tpl) => ({ label: tpl.label, onClick: () => void runNew(tpl.create) })) }+ : { label: t(a.labelKey), onClick: () => void runNew(a.create!, a.errorKey) },+ ),+ // Contributed asset types that offer a creator, after the built-ins. They go+ // through the SAME runNew path, so a contributed asset is revealed and dropped+ // into rename exactly like a built-in one.+ ...assetTypeRegistry+ .all()+ .filter((type) => type.create)+ .map((type) => ({ label: type.create!.label, onClick: () => void runNew(type.create!.run) })),+ ];const showInExplorer = async (path: string) => {try {@@ -987,6 +998,7 @@ export function ContentBrowser() {...newAssetItems,{ sep: true },{ label: t('cb.menuShowInExplorer'), onClick: () => void showInExplorer(cwd) },+ ...contributedContextRows('content/background', { path: cwd }),];}const { path, entry } = ctx.target;@@ -1056,6 +1068,7 @@ export function ContentBrowser() {...(ref ? [{ label: t('cb.menuCopyReference'), onClick: () => copy(ref, t('cb.copiedReference')) }] : []),...(entry.isDir ? [] : [{ label: t('cb.menuFindUsages'), onClick: () => setUsagesPath(path) }]),{ label: t('cb.menuShowInExplorer'), onClick: () => void showInExplorer(path) },+ ...contributedContextRows('content/item', { path }),{ sep: true },{ label: t('ui.delete'), danger: true, onClick: () => void remove(selectedAssets.has(path) && selectedAssets.size > 1 ? [...selectedAssets] : [path]) },];diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsxindex f69696962..cac4a8dec 100644--- a/desktop/src/panels/Details.tsx+++ b/desktop/src/panels/Details.tsx@@ -76,6 +76,9 @@ import { PlayInspect } from '@/engine/PlayInspect';import { DimensionUnit, AnchorAxis, detectAnchorAxes, UIPositionType, FlexDirection, FlexWrap, JustifyContent, AlignItems, INTERACTION_CONTROLLER, INTERACTION_PAGES, parseLocaleTable, EasingType, BUILTIN_SHADER_TEMPLATES, INVALID_ENTITY } from 'esengine';import type { SceneData, InputMapAsset, ActionType, Binding, LocaleTableAsset, PluralCategory, GearValue, GearTween, MaterialAssetData } from 'esengine';import { modelAddableComponentEntries, subscribeSchemas, getSchemaRevision, prettyLabel, hexToRgba, dynamicEnumOptions, boxGroupsFor, isRequiredEmpty, type BoxGroupDef } from '@/engine/schema';+import { inspectorRegistry, buildContributedSection, isInfoRow } from '@/plugins/inspector';+import { localizePlugin } from '@/plugins/localize';+import type { AssetInspectorContribution, ComponentInspectorContribution } from '@/plugins/types';import * as imap from '@/project/inputMapDoc';import * as ldoc from '@/project/localeTableDoc';import { buildImporterComponent, applyImporterEdit, readTextureCookSettings } from '@/project/assetImporter';@@ -2191,6 +2194,70 @@ function BoxSidesControl({);}+/**+ * Sections a plugin contributed for one component type (or one asset type), rendered+ * through the SAME ComponentSection as everything else — so a contributed section is+ * native by construction rather than by imitation.+ *+ * Single-entity only for the component case: multi-selection has real semantics here+ * (mixed values, fan-out writes) that a plugin's `build(entity)` cannot express, and+ * inventing an answer would be worse than not offering one.+ */+function ContributedSections({ target }: { target: { entity: EntityId } | { component: string; path: string } }) {+ // Re-render when the section set changes (plugin load/unload) — and on the host's+ // own revision, since a section's rows are rebuilt from live data each render.+ useSyncExternalStore(inspectorRegistry.subscribe, inspectorRegistry.getRevision);+ const [collapsed, setCollapsed] = useState<Record<string, boolean>>({});++ const sections =+ 'entity' in target+ ? SceneModel.entityBySource(target.entity)?.components.flatMap((c) => inspectorRegistry.forComponent(c.type)) ?? []+ : inspectorRegistry.forAssetType(target.component);++ return (+ <>+ {sections.map((section) => {+ const built =+ section.kind === 'component' && 'entity' in target+ ? buildContributedSection(section, (v) => localizePlugin(v), (ui) => section.build(target.entity, ui))+ : section.kind === 'asset' && 'path' in target+ ? buildContributedSection(section, (v) => localizePlugin(v), (ui) => section.build(target.path, ui))+ : null;+ if (!built) return null;+ const action = section.action+ ? {+ label: localizePlugin(section.action.label),+ title: localizePlugin(section.action.label),+ run: () =>+ 'entity' in target+ ? (section as ComponentInspectorContribution).action!.run(target.entity)+ : (section as AssetInspectorContribution).action!.run(target.path),+ }+ : undefined;+ return (+ <ComponentSection+ key={section.id}+ entities={[]}+ comp={built}+ collapsed={collapsed[section.id] ?? false}+ onToggle={() => setCollapsed((s) => ({ ...s, [section.id]: !(s[section.id] ?? false) }))}+ action={action}+ write={+ section.write+ ? (key, _type, value) => {+ if (isInfoRow(key)) return; // a read-only row was never writable+ if ('entity' in target) (section as ComponentInspectorContribution).write!(target.entity, key, value as never);+ else (section as AssetInspectorContribution).write!(target.path, key, value as never);+ }+ : undefined+ }+ />+ );+ })}+ </>+ );+}+function ComponentSection({entities,comp,@@ -3391,6 +3458,8 @@ function GenericAssetInspector({ path }: { path: string }) {<TexturePlatformOverrides importer={importer} write={write} />)}+ <ContributedSections target={{ component: type, path }} />+<div className="cb-meta" style={{ padding: '8px 10px 0' }}><MetaRow k={t('det.metaPath')} v={path} mono />{dims && <MetaRow k={t('det.metaDimensions')} v={dims} />}@@ -3779,6 +3848,9 @@ function EditorDetails() {}/>))}+ {/* Contributed sections come after the entity's own components — a plugin+ adds to the inspector, it doesn't push the real properties down. */}+ {ids.length === 1 && <ContributedSections target={{ entity: ids[0]! }} />}{query && visible.length === 0 && (<div className="empty-line">{t('det.noComponentsMatch', { query })}</div>)}diff --git a/desktop/src/panels/Outliner.tsx b/desktop/src/panels/Outliner.tsxindex d7f6eba48..9164c3bad 100644--- a/desktop/src/panels/Outliner.tsx+++ b/desktop/src/panels/Outliner.tsx@@ -14,6 +14,7 @@ import { PlayInspect } from '@/engine/PlayInspect';import { ProjectStore } from '@/project/ProjectStore';import { ContextMenu, type MenuItem } from '@/components/Menu';import { formatKeybinding } from '@/commands/keybinding';+import { contributedContextRows } from '@/plugins/contextMenus';import { VirtualTree } from '@/components/VirtualTree';import { t } from '@/i18n';import { buildOutlinerItems, collectExpandableKeys, entityKey, folderKey, parseQuery, type OutlinerItem, type SortMode } from '@/outliner/OutlinerModel';@@ -565,6 +566,7 @@ export function Outliner() {{ sep: true },{ label: t('out.expandAll'), onClick: expandAll },{ label: t('out.collapseAll'), onClick: () => useOutliner.getState().setExpanded([]) },+ ...contributedContextRows('outliner/background', {}),];}if (ctx.item.kind === 'folder') {@@ -618,6 +620,7 @@ export function Outliner() {// old "Add Entity" which jumped to root.{ label: t('out.addChild'), onClick: () => addEntity(id) },{ label: t('out.createChild'), onClick: () => setCreateFor({ parent: id }) },+ ...contributedContextRows('outliner/item', { entity: id }),];// eslint-disable-next-line react-hooks/exhaustive-deps}, [ctx]);diff --git a/desktop/src/panels/Viewport.tsx b/desktop/src/panels/Viewport.tsxindex fdd0e81ac..452128e85 100644--- a/desktop/src/panels/Viewport.tsx+++ b/desktop/src/panels/Viewport.tsx@@ -38,6 +38,7 @@ import { SceneStore } from '@/engine/SceneStore';import { StatsStore } from '@/engine/StatsStore';import { PerfMonitor } from '@/engine/PerfMonitor';import { PerfOverlay } from '@/components/PerfOverlay';+import { PluginOverlays } from '@/plugins/PluginOverlays';import { Perf } from '@/components/Perf';import { Popover, usePopover } from '@/components/Popover';import { usePanelWindow, eventWindow } from '@/components/PanelWindow';@@ -2592,6 +2593,9 @@ export function Viewport() {paintHint={inTilePaint && paintTool ? TILE_HINT[paintTool] : null}/>{engine.status === 'ready' && showMinimap && <ViewportMinimap data={minimap} />}+ {/* Contributed gizmos. Gated on `showGizmos` with the built-in ones — a plugin+ overlay is a gizmo, so the same toggle has to silence it. */}+ {engine.status === 'ready' && showGizmos && !isPlaying && <PluginOverlays />}{perfVisible && <Perf id="viewport.perfhud"><PerfOverlay /></Perf>}{mode.id !== 'scene' && !isPlaying && (diff --git a/desktop/src/plugins/PluginHost.ts b/desktop/src/plugins/PluginHost.tsindex d82607d7f..039329e71 100644--- a/desktop/src/plugins/PluginHost.ts+++ b/desktop/src/plugins/PluginHost.ts@@ -29,6 +29,11 @@ import { settingsRegistry } from '@/settings/registry';import { dockApi } from '@/layout/dockApi';import { editorModeRegistry } from '@/mode/editorModes';import { entitySourceRegistry } from '@/engine/entitySources';+import { toolRegistry } from '@/tools/toolRegistry';+import { assetTypeRegistry } from '@/project/assetTypes';+import { overlayRegistry } from './overlays';+import { inspectorRegistry } from './inspector';+import { contextMenuRegistry } from './contextMenus';import { LogStore } from '@/store/LogStore';import { Toasts } from '@/store/Toasts';import { PerfMonitor } from '@/engine/PerfMonitor';@@ -88,6 +93,11 @@ const CONTRIBUTION_REGISTRIES = [{ disposeOwner: (o: Owner) => settingsRegistry.disposeOwner(o) },editorModeRegistry,entitySourceRegistry,+ toolRegistry,+ overlayRegistry,+ inspectorRegistry,+ assetTypeRegistry,+ contextMenuRegistry,];interface LoadedPlugin {@@ -127,6 +137,15 @@ class PluginHostImpl {* Timed through PerfMonitor so a slow plugin shows up in the profiler beside the* editor's own work, under `plugin.<id>.<what>`.*/+ /**+ * Run one overlay's per-frame draw. Exposed because the overlay renderer's rAF+ * calls plugin code directly, and a throw there must be attributed and counted+ * like any other — not swallowed anonymously inside a render loop.+ */+ guardOverlay(id: string, draw: () => void): void {+ this.guard(id, 'overlay render', draw, undefined);+ }+private guard<T>(id: string, what: string, fn: () => T, fallback: T): T {try {return PerfMonitor.measure(`plugin.${id}.${what}`, fn);diff --git a/desktop/src/plugins/PluginOverlays.tsx b/desktop/src/plugins/PluginOverlays.tsxnew file mode 100644index 000000000..5145e7b32--- /dev/null+++ b/desktop/src/plugins/PluginOverlays.tsx@@ -0,0 +1,141 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file PluginOverlays — draws every contributed viewport overlay into one SVG.+ *+ * Runs its OWN rAF rather than joining the Viewport's main tick (the same choice+ * ViewportMinimap makes): the main tick already positions every built-in gizmo, and+ * a plugin's draw cost must not be paid inside it or attributed to it.+ *+ * SVG children are POOLED across frames and reused by index. Rebuilding the subtree+ * each frame is the obvious implementation and the wrong one at 60fps — it churns+ * the DOM for a gizmo whose geometry barely changed.+ *+ * A throwing overlay is disarmed for the frame by the host's guard (which returns a+ * safe fallback), so one bad plugin cannot stop the others from drawing.+ */+import { useEffect, useRef, useSyncExternalStore } from 'react';+import { activeMode } from '@/mode/activeMode';+import { PluginHost } from './PluginHost';+import { overlayRegistry, createOverlayGraphics, type OverlayPrimitive } from './overlays';+import type { GizmoStyle } from './types';++const SVG_NS = 'http://www.w3.org/2000/svg';++/** Defaults chosen to read as an editor gizmo unless the plugin says otherwise. */+const applyStyle = (el: SVGElement, style: GizmoStyle | undefined, filled: boolean): void => {+ el.setAttribute('stroke', style?.color ?? 'var(--acc)');+ el.setAttribute('stroke-width', String(style?.width ?? 1.5));+ el.setAttribute('fill', style?.fill ?? (filled ? 'none' : 'none'));+ el.setAttribute('opacity', String(style?.opacity ?? 1));+ if (style?.dashed) el.setAttribute('stroke-dasharray', '4 3');+ else el.removeAttribute('stroke-dasharray');+};++export function PluginOverlays() {+ const svgRef = useRef<SVGSVGElement>(null);+ // Re-arm the tick when the overlay SET changes (a plugin loaded or unloaded).+ const revision = useSyncExternalStore(overlayRegistry.subscribe, overlayRegistry.getRevision);++ useEffect(() => {+ const svg = svgRef.current;+ if (!svg) return;+ // One pool per element kind: reused by index, hidden past the live count.+ const pools = new Map<string, SVGElement[]>();+ const primitives: OverlayPrimitive[] = [];+ let raf = 0;++ const take = (kind: string, index: number, tag: string): SVGElement => {+ let pool = pools.get(kind);+ if (!pool) pools.set(kind, (pool = []));+ let el = pool[index];+ if (!el) {+ el = document.createElementNS(SVG_NS, tag);+ pool[index] = el;+ svg.append(el);+ }+ el.style.display = '';+ return el;+ };++ const tick = () => {+ raf = requestAnimationFrame(tick);+ const overlays = overlayRegistry.all();+ if (overlays.length === 0 && primitives.length === 0) return;++ primitives.length = 0;+ const g = createOverlayGraphics(primitives);+ const mode = activeMode().id;+ for (const overlay of overlays) {+ if (overlay.modes && !overlay.modes.includes(mode)) continue;+ PluginHost.guardOverlay(overlay.id, () => overlay.render(g));+ }++ // Per-kind running index, so each kind draws from its own pool.+ const counts: Record<string, number> = {};+ const next = (kind: string): number => (counts[kind] = (counts[kind] ?? 0) + 1) - 1;++ for (const p of primitives) {+ switch (p.kind) {+ case 'line': {+ const el = take('line', next('line'), 'line');+ el.setAttribute('x1', String(p.points[0].x));+ el.setAttribute('y1', String(p.points[0].y));+ el.setAttribute('x2', String(p.points[1].x));+ el.setAttribute('y2', String(p.points[1].y));+ applyStyle(el, p.style, false);+ break;+ }+ case 'polyline': {+ const el = take('polyline', next('polyline'), 'polyline');+ el.setAttribute('points', p.points.map((q) => `${q.x},${q.y}`).join(' '));+ applyStyle(el, p.style, false);+ break;+ }+ case 'circle': {+ const el = take('circle', next('circle'), 'circle');+ el.setAttribute('cx', String(p.center.x));+ el.setAttribute('cy', String(p.center.y));+ el.setAttribute('r', String(p.radius));+ applyStyle(el, p.style, false);+ break;+ }+ case 'rect': {+ const el = take('rect', next('rect'), 'rect');+ el.setAttribute('x', String(p.x));+ el.setAttribute('y', String(p.y));+ el.setAttribute('width', String(p.w));+ el.setAttribute('height', String(p.h));+ applyStyle(el, p.style, true);+ break;+ }+ case 'text': {+ const el = take('text', next('text'), 'text');+ el.setAttribute('x', String(p.at.x));+ el.setAttribute('y', String(p.at.y));+ el.setAttribute('font-size', String(p.style?.fontSize ?? 11));+ el.setAttribute('fill', p.style?.color ?? 'var(--text-hi)');+ el.setAttribute('stroke', 'none');+ el.setAttribute('opacity', String(p.style?.opacity ?? 1));+ el.textContent = p.text;+ break;+ }+ }+ }++ // Hide the tail of every pool rather than removing it — the next frame very+ // likely wants those nodes back.+ for (const [kind, pool] of pools) {+ for (let i = counts[kind] ?? 0; i < pool.length; i++) pool[i].style.display = 'none';+ }+ };++ raf = requestAnimationFrame(tick);+ return () => {+ cancelAnimationFrame(raf);+ svg.replaceChildren();+ };+ }, [revision]);++ return <svg className="viewport__plugin-overlay" ref={svgRef} />;+}diff --git a/desktop/src/plugins/context.ts b/desktop/src/plugins/context.tsindex 003a267b4..f48db4ccc 100644--- a/desktop/src/plugins/context.ts+++ b/desktop/src/plugins/context.ts@@ -19,29 +19,33 @@ import { commands } from '@/commands/registry';import { registerPanel } from '@/layout/panels';import { registerMenuItem } from '@/layout/menus';import { dockApi } from '@/layout/dockApi';+import { toolRegistry } from '@/tools/toolRegistry';+import { assetTypeRegistry, CONTRIBUTED_ASSET_ICON } from '@/project/assetTypes';+import { entitySourceRegistry, prefabFromSpecs } from '@/engine/entitySources';+import { overlayRegistry, viewportProjection } from './overlays';+import { inspectorRegistry } from './inspector';+import { contextMenuRegistry } from './contextMenus';+import { localizePlugin as localize } from './localize';import { settingsRegistry } from '@/settings/registry';import { useSettings } from '@/store/settingsStore';import { useSelection } from '@/store/selectionStore';import { useEditorStore } from '@/store/editorStore';import { EditorControlSurface } from '@/engine/EditorSession';+import { EngineHost } from '@/engine/EngineHost';import { ProjectStore } from '@/project/ProjectStore';import { LogStore } from '@/store/LogStore';import { Toasts } from '@/store/Toasts';-import { editorLocale } from '@/i18n';import type { InspectorFieldValue } from '@/types';import type { Owner, Disposable as CoreDisposable } from '@/contrib/ContributionRegistry';+import type { PointerInput as CorePointerInput } from '@/tools/EditorTool';import type { PluginManifest, PluginCapability } from './manifest';import type {- CommandContribution, Disposable, EditorEvents, EditorPlugin, EditorProjectApi, EditorSceneApi,- FieldValue, LocalizedString, PanelContribution, PluginContext, PluginFs, SettingContribution,+ AssetTypeContribution, CommandContribution, ContextMenuContribution, Disposable, EditorEvents,+ EditorPlugin, EditorProjectApi, EditorSceneApi, EntityTemplateContribution, FieldValue,+ InspectorContribution, OverlayContribution, PanelContribution, PluginContext,+ PluginFs, SettingContribution, ToolContribution, PointerInput as PluginPointerInput,} from './types';-const localize = (value: LocalizedString | undefined): string => {- if (value === undefined) return '';- if (typeof value === 'string') return value;- return value[editorLocale] ?? value.en ?? Object.values(value)[0] ?? '';-};-/** Per-plugin persisted state, kept out of the project (it's a user preference). */const stateKey = (id: string): string => `estella.plugin.state.${id}`;@@ -107,6 +111,20 @@ function sceneApi(): EditorSceneApi {};}+/** Client-space pointer input → the viewport-space shape plugins are handed. */+function toPluginPointer(p: CorePointerInput): PluginPointerInput {+ const canvas = EngineHost.canvas;+ const r = canvas?.getBoundingClientRect();+ return {+ x: p.clientX - (r?.left ?? 0),+ y: p.clientY - (r?.top ?? 0),+ pointerId: p.pointerId,+ button: p.button,+ shift: p.shift,+ alt: p.alt,+ };+}+function projectApi(): EditorProjectApi {return {root: () => ProjectStore.getSnapshot()?.root ?? null,@@ -259,6 +277,80 @@ export function buildPluginContext(return adopt(settingsRegistry.register(descriptor, owner));};+ const registerTool = (tool: ToolContribution): Disposable =>+ adopt(+ toolRegistry.register(owner, {+ id: tool.id,+ title: localize(tool.title),+ modes: tool.modes,+ // Every stroke callback is guarded: a throw mid-drag must not wedge the+ // viewport's pointer routing. onPointerDown's fallback is `false` — "I did+ // not take the stroke" — so a broken tool degrades to no-op, not to a+ // captured pointer nothing releases.+ //+ // Pointer coordinates are converted from CLIENT space (what the DOM and the+ // built-in tools use) to VIEWPORT space here, so a plugin's input arrives in+ // the same space `ctx.viewport` and overlays project to — one conversion, at+ // the boundary, instead of every plugin repeating it.+ onPointerDown: (p, c) => guard(`tool ${tool.id} down`, () => tool.onPointerDown(toPluginPointer(p), c), false),+ onPointerMove: (p, c) => guard(`tool ${tool.id} move`, () => tool.onPointerMove(toPluginPointer(p), c), undefined),+ onPointerUp: (p, c) => guard(`tool ${tool.id} up`, () => tool.onPointerUp(toPluginPointer(p), c), undefined),+ cancel: tool.cancel ? (c) => guard(`tool ${tool.id} cancel`, () => tool.cancel!(c), undefined) : undefined,+ }),+ );++ const registerOverlay = (overlay: OverlayContribution): Disposable =>+ // Not guarded here: the overlay renderer's rAF calls PluginHost.guardOverlay+ // itself, so a per-frame throw is attributed once, at the frame boundary.+ adopt(overlayRegistry.register(owner, overlay));++ const registerInspector = (section: InspectorContribution): Disposable =>+ adopt(inspectorRegistry.register(owner, { ...section, id: `${id}.${section.id}` }));++ const registerAssetType = (type: AssetTypeContribution): Disposable =>+ adopt(+ assetTypeRegistry.register(owner, {+ id: type.id,+ extensions: type.extensions,+ badge: type.badge ?? '',+ icon: CONTRIBUTED_ASSET_ICON,+ tint: type.tint ?? 'var(--text-dim)',+ open: type.open ? (path) => guard(`asset open ${type.id}`, () => type.open!(path), undefined) : undefined,+ create: type.create+ ? {+ label: localize(type.create.label),+ run: (dir) => guard(`asset create ${type.id}`, () => type.create!.run(dir), undefined),+ }+ : undefined,+ }),+ );++ const registerTemplate = (template: EntityTemplateContribution): Disposable =>+ adopt(+ entitySourceRegistry.register(owner, {+ id: template.id,+ label: localize(template.label),+ category: template.category ?? 'Scripts',+ icon: CONTRIBUTED_ASSET_ICON,+ keywords: template.keywords ? [...template.keywords] : undefined,+ // The host builds the prefab from the component specs, so a plugin never+ // hand-writes PrefabData (version, prefabEntityId, parent wiring).+ build: () => prefabFromSpecs(localize(template.label), template.components),+ }),+ );++ const registerContextMenuItem = (item: ContextMenuContribution): Disposable =>+ adopt(+ contextMenuRegistry.register(owner, {+ ...item,+ // A plain string is itself a LocalizedString, so resolving it here means+ // every consumer reads one already-localized label.+ label: localize(item.label),+ when: item.when ? (target) => guard(`context ${item.id} when`, () => !!item.when!(target), false) : undefined,+ run: (target) => guard(`context ${item.id}`, () => item.run(target), undefined),+ }),+ );+const ctx: PluginContext = {id,version: manifest.version,@@ -275,8 +367,19 @@ export function buildPluginContext(register: registerSetting,get: <T extends boolean | number | string>(sid: string) => useSettings.getState().getValue(sid) as T | undefined,},+ tools: {+ register: registerTool,+ activate: (toolId) => toolRegistry.activate(toolId),+ activeId: () => toolRegistry.activeId(),+ },+ overlays: { register: registerOverlay },+ inspector: { register: registerInspector },+ assets: { registerType: registerAssetType },+ entities: { registerTemplate },+ contextMenus: { register: registerContextMenuItem },scene: sceneApi(),project: projectApi(),+ viewport: viewportProjection,fs: pluginFs(id, dir, capabilities),events: editorEvents(track),};diff --git a/desktop/src/plugins/contextMenus.ts b/desktop/src/plugins/contextMenus.tsnew file mode 100644index 000000000..2a1be5e23--- /dev/null+++ b/desktop/src/plugins/contextMenus.ts@@ -0,0 +1,43 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file contextMenus.ts+ * @brief Contributed right-click rows, kept separate from the menu-BAR registry+ * because they answer a different question: a menu-bar row is a command that+ * is always there, while a context row is evaluated against a TARGET (the+ * entity or asset that was clicked) each time the menu opens.+ *+ * That target is why these can't just be command references — `when(target)` and+ * `run(target)` need the click's subject, which a command id cannot carry.+ */+import { ContributionRegistry, type Disposable, type Owner } from '@/contrib/ContributionRegistry';+import { localizePlugin } from './localize';+import type { MenuItem } from '@/components/Menu';+import type { ContextMenuContribution, ContextMenuLocation, ContextMenuTarget } from './types';++const contrib = new ContributionRegistry<ContextMenuContribution>('context menu item');++export const contextMenuRegistry = {+ register: (owner: Owner, item: ContextMenuContribution): Disposable => contrib.register(owner, item),+ disposeOwner: (owner: Owner): void => contrib.disposeOwner(owner),+ all: (): readonly ContextMenuContribution[] => contrib.all(),++ /** Rows for a location that apply to `target`, in registration order. */+ forTarget(location: ContextMenuLocation, target: ContextMenuTarget): ContextMenuContribution[] {+ return contrib.all().filter((i) => i.location === location && (i.when?.(target) ?? true));+ },+};++/**+ * Contributed rows as menu items, with a leading separator when there are any — so a+ * host menu appends ONE spread and gets correct grouping whether or not a plugin is+ * loaded (and no dangling separator when none is).+ */+export function contributedContextRows(location: ContextMenuLocation, target: ContextMenuTarget): MenuItem[] {+ const rows = contextMenuRegistry.forTarget(location, target);+ if (rows.length === 0) return [];+ return [+ { sep: true },+ ...rows.map((row) => ({ label: localizePlugin(row.label), onClick: () => row.run(target) })),+ ];+}diff --git a/desktop/src/plugins/inspector.ts b/desktop/src/plugins/inspector.tsnew file mode 100644index 000000000..5ff336a1c--- /dev/null+++ b/desktop/src/plugins/inspector.ts@@ -0,0 +1,100 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file inspector.ts+ * @brief Contributed inspector sections, and the builder that turns a plugin's row+ * calls into the editor's own `InspectorComponent` shape.+ *+ * The builder exists so the plugin API never exposes `InspectorField` — a 20-case+ * union with presentation, prefab-override, and multi-select semantics that plugins+ * have no business reproducing. A plugin says `ui.number('gain', 'Gain', 0.5)`; the+ * host decides how a number row looks, and the section renders through the SAME+ * ComponentSection every built-in component uses, so it is native by construction+ * rather than by imitation.+ *+ * Section ids are prefixed with the plugin's own id, so two plugins can both add a+ * "Stats" section to Sprite without colliding in the collapse-state store.+ */+import { ContributionRegistry, type Disposable, type Owner } from '@/contrib/ContributionRegistry';+import type { InspectorComponent, InspectorField } from '@/types';+import type {+ AssetInspectorContribution, ComponentInspectorContribution, InspectorContribution,+ InspectorSectionBuilder, LocalizedString,+} from './types';++const contrib = new ContributionRegistry<InspectorContribution>('inspector section');++export const inspectorRegistry = {+ register: (owner: Owner, section: InspectorContribution): Disposable => contrib.register(owner, section),+ disposeOwner: (owner: Owner): void => contrib.disposeOwner(owner),+ all: (): readonly InspectorContribution[] => contrib.all(),+ subscribe: (fn: () => void): (() => void) => contrib.subscribe(fn),+ getRevision: (): number => contrib.getRevision(),++ /** Sections attached to a component type. */+ forComponent(component: string): ComponentInspectorContribution[] {+ return contrib.all().filter((s): s is ComponentInspectorContribution => s.kind === 'component' && s.component === component);+ },++ /** Sections attached to an asset type. */+ forAssetType(assetType: string): AssetInspectorContribution[] {+ return contrib.all().filter((s): s is AssetInspectorContribution => s.kind === 'asset' && s.assetType === assetType);+ },+};++/** Collects builder calls into inspector fields. */+export function createSectionBuilder(localize: (v: LocalizedString) => string): {+ ui: InspectorSectionBuilder;+ fields: InspectorField[];+} {+ const fields: InspectorField[] = [];+ let infoCount = 0;+ const ui: InspectorSectionBuilder = {+ info(label, value) {+ // A read-only row is a string field the write path never routes (no `key` the+ // contribution declared), so it needs a key that cannot collide with a real one.+ fields.push({ key: `__info${infoCount++}`, label: localize(label), type: 'string', value });+ },+ number(key, label, value, opts) {+ fields.push({+ key, label: localize(label), type: 'number', value,+ min: opts?.min, max: opts?.max, step: opts?.step, unit: opts?.unit,+ slider: opts?.min !== undefined && opts?.max !== undefined,+ });+ },+ bool(key, label, value) {+ fields.push({ key, label: localize(label), type: 'bool', value });+ },+ text(key, label, value) {+ fields.push({ key, label: localize(label), type: 'string', value });+ },+ vec2(key, label, value) {+ fields.push({ key, label: localize(label), type: 'vec2', value: [value.x, value.y] });+ },+ color(key, label, value) {+ fields.push({ key, label: localize(label), type: 'color', value });+ },+ select(key, label, value, options) {+ fields.push({ key, label: localize(label), type: 'select', value, selectOptions: [...options] });+ },+ };+ return { ui, fields };+}++/** True for a row produced by `ui.info` — read-only, never written back. */+export const isInfoRow = (key: string): boolean => key.startsWith('__info');++/**+ * Build the `InspectorComponent` for one contributed section. Returns null when the+ * section produced no rows, so an empty section doesn't render as a bare header.+ */+export function buildContributedSection(+ section: InspectorContribution,+ localize: (v: LocalizedString) => string,+ emit: (ui: InspectorSectionBuilder) => void,+): InspectorComponent | null {+ const { ui, fields } = createSectionBuilder(localize);+ emit(ui);+ if (fields.length === 0) return null;+ return { name: section.id, label: localize(section.title), fields };+}diff --git a/desktop/src/plugins/localize.ts b/desktop/src/plugins/localize.tsnew file mode 100644index 000000000..f8df04066--- /dev/null+++ b/desktop/src/plugins/localize.ts@@ -0,0 +1,20 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file localize.ts — resolves a plugin-supplied {@link LocalizedString} against the+ * editor's session locale.+ *+ * Plugins can't use `t()`: the editor's catalog is closed at compile time, so a+ * plugin string could never be a valid key. They carry their own per-locale text+ * instead, and this is the one place that rule is applied — the plugin host, the+ * inspector, and the menus all resolve identically.+ */+import { editorLocale } from '@/i18n';+import type { LocalizedString } from './types';++/** Resolve for the current editor locale, falling back to `en`, then any value. */+export function localizePlugin(value: LocalizedString | undefined): string {+ if (value === undefined) return '';+ if (typeof value === 'string') return value;+ return value[editorLocale] ?? value.en ?? Object.values(value)[0] ?? '';+}diff --git a/desktop/src/plugins/overlays.ts b/desktop/src/plugins/overlays.tsnew file mode 100644index 000000000..8aeb054bc--- /dev/null+++ b/desktop/src/plugins/overlays.ts@@ -0,0 +1,110 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file overlays.ts+ * @brief Contributed viewport overlays, and the projection + primitive collection+ * behind {@link OverlayGraphics}.+ *+ * Plugins draw in WORLD coordinates; the host projects. That is the whole reason+ * this layer exists: a gizmo then tracks the scene through pan/zoom with no camera+ * math in the plugin, and a radius given in world units scales the way a+ * scene-anchored circle should — while stroke widths and text stay in screen pixels+ * so a hairline stays a hairline when you zoom out.+ *+ * Collecting primitives into a flat list (rather than handing over an SVG element)+ * is what lets the renderer POOL its DOM nodes across frames, and it keeps a plugin+ * from retaining or mutating editor DOM.+ */+import { ViewportController } from '@/engine/ViewportController';+import { EngineHost } from '@/engine/EngineHost';+import { ContributionRegistry, type Disposable, type Owner } from '@/contrib/ContributionRegistry';+import type { GizmoStyle, OverlayContribution, OverlayGraphics, Vec2 } from './types';++/** A collected primitive, already projected to overlay CSS pixels. */+export type OverlayPrimitive =+ | { kind: 'line'; points: Vec2[]; style?: GizmoStyle }+ | { kind: 'polyline'; points: Vec2[]; style?: GizmoStyle }+ | { kind: 'circle'; center: Vec2; radius: number; style?: GizmoStyle }+ | { kind: 'rect'; x: number; y: number; w: number; h: number; style?: GizmoStyle }+ | { kind: 'text'; at: Vec2; text: string; style?: GizmoStyle };++const contrib = new ContributionRegistry<OverlayContribution>('viewport overlay');++export const overlayRegistry = {+ register: (owner: Owner, overlay: OverlayContribution): Disposable => contrib.register(owner, overlay),+ disposeOwner: (owner: Owner): void => contrib.disposeOwner(owner),+ all: (): readonly OverlayContribution[] => contrib.all(),+ subscribe: (fn: () => void): (() => void) => contrib.subscribe(fn),+ getRevision: (): number => contrib.getRevision(),+};++/**+ * The viewport camera projection, in VIEWPORT space (CSS pixels from the canvas+ * top-left). Shared by overlays and by `ctx.viewport`, so a tool's pointer input and+ * an overlay's drawing agree on one coordinate system.+ *+ * ViewportController's own pair is asymmetric — worldToClient returns+ * canvas-relative pixels while canvasToWorld expects CLIENT pixels — so the client+ * offset is added back here, in one place, rather than at each call site.+ */+export const viewportProjection = {+ worldToViewport: (x: number, y: number): Vec2 | null => ViewportController.worldToClient(x, y),+ viewportToWorld: (x: number, y: number): Vec2 | null => {+ const canvas = EngineHost.canvas;+ if (!canvas) return null;+ const r = canvas.getBoundingClientRect();+ return ViewportController.canvasToWorld(r.left + x, r.top + y);+ },+};++/**+ * Build a graphics surface that collects into `out`. Every projection failure+ * (no camera yet, no canvas) drops the primitive rather than drawing it at a wrong+ * place — a gizmo in the wrong spot is worse than a missing one.+ */+export function createOverlayGraphics(out: OverlayPrimitive[]): OverlayGraphics {+ const project = viewportProjection.worldToViewport;++ return {+ worldToViewport: project,+ viewportToWorld: viewportProjection.viewportToWorld,+ line(a, b, style) {+ const p0 = project(a.x, a.y);+ const p1 = project(b.x, b.y);+ if (p0 && p1) out.push({ kind: 'line', points: [p0, p1], style });+ },+ polyline(points, style) {+ const projected: Vec2[] = [];+ for (const p of points) {+ const q = project(p.x, p.y);+ if (!q) return; // a partially projected polyline would draw a false shape+ projected.push(q);+ }+ if (projected.length >= 2) out.push({ kind: 'polyline', points: projected, style });+ },+ circle(center, radius, style) {+ const c = project(center.x, center.y);+ // Project a point one radius away rather than reading a zoom factor: it stays+ // correct for any projection the camera applies, without assuming uniformity.+ const edge = project(center.x + radius, center.y);+ if (c && edge) out.push({ kind: 'circle', center: c, radius: Math.abs(edge.x - c.x), style });+ },+ rect(a, b, style) {+ const p0 = project(a.x, a.y);+ const p1 = project(b.x, b.y);+ if (!p0 || !p1) return;+ out.push({+ kind: 'rect',+ x: Math.min(p0.x, p1.x),+ y: Math.min(p0.y, p1.y),+ w: Math.abs(p1.x - p0.x),+ h: Math.abs(p1.y - p0.y),+ style,+ });+ },+ text(at, text, style) {+ const p = project(at.x, at.y);+ if (p) out.push({ kind: 'text', at: p, text, style });+ },+ };+}diff --git a/desktop/src/plugins/types.ts b/desktop/src/plugins/types.tsindex 2d6c3f0ad..e709ff67d 100644--- a/desktop/src/plugins/types.ts+++ b/desktop/src/plugins/types.ts@@ -123,6 +123,227 @@ export type SettingContribution =| StringSettingContribution| EnumSettingContribution;+/** A point in scene (world) space. */+export interface Vec2 {+ x: number;+ y: number;+}++// — Viewport tools ————————————————————————————————————————————————————————————++/**+ * A pointer event reduced to what a tool needs (no DOM coupling). `x`/`y` are in+ * VIEWPORT space — CSS pixels from the viewport canvas's top-left — the same space+ * {@link EditorViewportApi} and {@link OverlayGraphics} project to, so a tool can+ * hand its input straight to `viewportToWorld` with no conversion.+ */+export interface PointerInput {+ x: number;+ y: number;+ pointerId: number;+ button: number;+ shift: boolean;+ alt: boolean;+}++/** Host services during a stroke. */+export interface ToolContext {+ /** Keep receiving move/up even when the pointer leaves the viewport. */+ capture(pointerId: number): void;+ release(pointerId: number): void;+}++/**+ * A viewport tool. While ARMED (`ctx.tools.activate(id)`) it gets first refusal on+ * every pointer-down; returning true claims the stroke and its move/up. Return+ * false for a one-shot action or a click that shouldn't take over.+ *+ * Choosing any built-in tool (Select/Move/… or a tile brush) disarms it, so the+ * user is never stuck in a plugin's tool.+ */+export interface ToolContribution {+ /** Namespaced id, e.g. `acme.measure`. */+ id: string;+ title: LocalizedString;+ /** Restrict to these editor modes ('scene' | 'ui' | 'tilemap'); omitted ⇒ all. */+ modes?: readonly string[];+ onPointerDown(p: PointerInput, ctx: ToolContext): boolean;+ onPointerMove(p: PointerInput, ctx: ToolContext): void;+ onPointerUp(p: PointerInput, ctx: ToolContext): void;+ /** Roll back an in-progress stroke (Esc / tool switch). */+ cancel?(ctx: ToolContext): void;+}++// — Viewport overlays —————————————————————————————————————————————————————————++export interface GizmoStyle {+ /** Any CSS color — including a theme token, e.g. `var(--acc)`, which is the way+ * to stay consistent with the editor's own gizmos in both light and dark. */+ color?: string;+ /** Stroke width in SCREEN pixels, so it stays legible at any zoom. */+ width?: number;+ dashed?: boolean;+ fill?: string;+ opacity?: number;+ /** `text` only: font size in screen pixels. */+ fontSize?: number;+}++/**+ * Drawing surface for a viewport overlay, redrawn every frame.+ *+ * Every primitive takes WORLD coordinates and is projected by the host, so a gizmo+ * tracks the scene through pan and zoom without the plugin doing camera math — and+ * a radius in world units scales the way a scene-anchored circle should. Stroke+ * widths and font sizes are in SCREEN pixels, which is what keeps a hairline a+ * hairline when you zoom out.+ */+export interface OverlayGraphics {+ /** World → viewport CSS pixels, for plugins that need screen-space math. */+ worldToViewport(x: number, y: number): Vec2 | null;+ /** Viewport CSS pixels → world (the exact inverse). */+ viewportToWorld(x: number, y: number): Vec2 | null;+ line(a: Vec2, b: Vec2, style?: GizmoStyle): void;+ polyline(points: readonly Vec2[], style?: GizmoStyle): void;+ /** `radius` is in world units. */+ circle(center: Vec2, radius: number, style?: GizmoStyle): void;+ /** Axis-aligned world rect (corners in any order). */+ rect(a: Vec2, b: Vec2, style?: GizmoStyle): void;+ /** Label anchored at a world point, drawn at a fixed screen size. */+ text(at: Vec2, text: string, style?: GizmoStyle): void;+}++export interface OverlayContribution {+ /** Namespaced id, e.g. `acme.spawn-radius`. */+ id: string;+ /** Restrict to these editor modes; omitted ⇒ drawn in all of them. */+ modes?: readonly string[];+ /** Draw this frame. Called on every viewport frame — keep it cheap. */+ render(g: OverlayGraphics): void;+}++// — Inspector sections ————————————————————————————————————————————————————————++/**+ * Builds inspector rows. The host turns these calls into the same property UI the+ * editor renders for its own components, so a contributed section is visually+ * native and needs no styling — and the plugin never handles the editor's internal+ * field vocabulary.+ *+ * A row's `key` identifies it in the contribution's `write` callback.+ */+export interface InspectorSectionBuilder {+ /** A read-only labelled value. */+ info(label: LocalizedString, value: string): void;+ number(key: string, label: LocalizedString, value: number, opts?: { min?: number; max?: number; step?: number; unit?: string }): void;+ bool(key: string, label: LocalizedString, value: boolean): void;+ text(key: string, label: LocalizedString, value: string): void;+ vec2(key: string, label: LocalizedString, value: Vec2): void;+ /** `#rrggbb` / `#rrggbbaa`. */+ color(key: string, label: LocalizedString, value: string): void;+ select(key: string, label: LocalizedString, value: string, options: readonly string[]): void;+}++/** Extra section shown under a component, for entities that carry it. */+export interface ComponentInspectorContribution {+ kind: 'component';+ /** Namespaced id, e.g. `acme.sprite-audit`. */+ id: string;+ /** The component type this attaches to, e.g. `Sprite`. */+ component: string;+ title: LocalizedString;+ build(entity: EntityId, ui: InspectorSectionBuilder): void;+ /** A button in the section header. */+ action?: { label: LocalizedString; run(entity: EntityId): void };+ /** An edit to one of the rows `build` produced. Wrap scene writes in+ * `ctx.scene.transact` if one edit should be one undo step. */+ write?(entity: EntityId, key: string, value: FieldValue): void;+}++/** Section shown when an asset of `assetType` is selected in the Content Browser. */+export interface AssetInspectorContribution {+ kind: 'asset';+ id: string;+ /** Asset type id — a built-in one (`texture`, `scene`, …) or a contributed one. */+ assetType: string;+ title: LocalizedString;+ build(path: string, ui: InspectorSectionBuilder): void;+ action?: { label: LocalizedString; run(path: string): void };+ write?(path: string, key: string, value: FieldValue): void;+}++export type InspectorContribution = ComponentInspectorContribution | AssetInspectorContribution;++// — Asset types ———————————————————————————————————————————————————————————————++export interface AssetTypeContribution {+ /** Namespaced type id, e.g. `acme.dialogue`. */+ id: string;+ /** Extensions (lower-case, no dot) that resolve to this type. */+ extensions: readonly string[];+ /** Short uppercase badge on the Content Browser tile (e.g. `DLG`). */+ badge?: string;+ /** Tile tint — any CSS color. */+ tint?: string;+ /** Double-click action. */+ open?(path: string): void;+ /** A "New ▸ …" entry in the Content Browser's create menu. Returning the new+ * path makes the browser reveal it and drop into rename. */+ create?: { label: LocalizedString; run(dir: string): Promise<string | void> | string | void };+}++// — Entity templates ——————————————————————————————————————————————————————————++/** One component of a template: its type, and any non-default field values. */+export interface ComponentSpec {+ type: string;+ data?: Record<string, unknown>;+}++/** A ready-made entity offered by the Create picker (and drag-drop, and the menu). */+export interface EntityTemplateContribution {+ /** Namespaced id, e.g. `acme.turret`. */+ id: string;+ label: LocalizedString;+ /** Create-picker bucket; unknown categories fall under `Other`. */+ category?: string;+ /** Extra search terms for the picker. */+ keywords?: readonly string[];+ /** The entity's components, applied over their registered defaults. */+ components: readonly ComponentSpec[];+}++// — Context menus ——————————————————————————————————————————————————————————————++/**+ * Where a contributed row can appear. Deliberately only the menus that EXIST — the+ * viewport has no context menu to host rows, and declaring a location the editor+ * never opens would be a seam that silently does nothing.+ */+export type ContextMenuLocation =+ | 'outliner/item'+ | 'outliner/background'+ | 'content/item'+ | 'content/background';++/** What was right-clicked. Which fields are set depends on the location. */+export interface ContextMenuTarget {+ /** `outliner/item` — the entity whose row was clicked. */+ entity?: EntityId | null;+ /** `content/item` — the asset path; `content/background` — the current folder. */+ path?: string | null;+}++export interface ContextMenuContribution {+ /** Namespaced id, e.g. `acme.reveal-refs`. */+ id: string;+ location: ContextMenuLocation;+ label: LocalizedString;+ /** Hide the row entirely for this target (distinct from disabling it). */+ when?(target: ContextMenuTarget): boolean;+ run(target: ContextMenuTarget): void;+}+// =============================================================================// Editor APIs// =============================================================================@@ -190,6 +411,17 @@ export interface PluginFs {writeProject(relPath: string, contents: string): Promise<void>;}+/**+ * The viewport's camera projection. A tool needs this to turn its pointer input into+ * scene coordinates, so it lives on the context rather than only inside an overlay's+ * draw call — both use the same VIEWPORT space (CSS pixels from the canvas top-left).+ * Returns null before the viewport has a camera (no scene open yet).+ */+export interface EditorViewportApi {+ viewportToWorld(x: number, y: number): Vec2 | null;+ worldToViewport(x: number, y: number): Vec2 | null;+}+/** Editor events a plugin can observe. Handlers are dropped on unload. */export interface EditorEvents {on(event: 'selectionChanged' | 'sceneChanged' | 'playStateChanged', handler: () => void): Disposable;@@ -241,9 +473,32 @@ export interface PluginContext {/** Current value of one of YOUR settings. */get<T extends boolean | number | string>(id: string): T | undefined;};+ readonly tools: {+ register(tool: ToolContribution): Disposable;+ /** Arm one of your tools (null disarms). It then gets first refusal on strokes. */+ activate(id: string | null): void;+ /** The currently armed contributed tool, or null. */+ activeId(): string | null;+ };+ readonly overlays: {+ register(overlay: OverlayContribution): Disposable;+ };+ readonly inspector: {+ register(section: InspectorContribution): Disposable;+ };+ readonly assets: {+ registerType(type: AssetTypeContribution): Disposable;+ };+ readonly entities: {+ registerTemplate(template: EntityTemplateContribution): Disposable;+ };+ readonly contextMenus: {+ register(item: ContextMenuContribution): Disposable;+ };readonly scene: EditorSceneApi;readonly project: EditorProjectApi;+ readonly viewport: EditorViewportApi;readonly fs: PluginFs;readonly events: EditorEvents;}diff --git a/desktop/src/project/assetOpen.ts b/desktop/src/project/assetOpen.tsindex ee37263d7..3f7d43dcb 100644--- a/desktop/src/project/assetOpen.ts+++ b/desktop/src/project/assetOpen.ts@@ -8,6 +8,7 @@* openers); folding them into the registry would create import cycles.*/import type { AssetType } from '@/types';+import { assetTypeRegistry } from './assetTypes';import { ProjectStore } from './ProjectStore';import { confirmDiscard } from './discardGuard';import { t } from '@/i18n';@@ -21,7 +22,26 @@ import { openStateMachine } from '@/fsm/openStateMachine';import { openAnimatorController } from '@/animator/openAnimatorController';import { openBehaviorTree } from '@/bt/openBehaviorTree';-/** Open action per asset type; types absent here aren't double-click-openable. */+/**+ * Open an asset by type — built-ins from the table below, contributed types from+ * their own registration (a plugin carries its open action on the type itself, since+ * it has no import cycle to design around). Returns false when nothing can open it.+ */+export function openAssetOfType(type: AssetType, path: string, name: string): boolean {+ const builtin = ASSET_OPEN[type];+ if (builtin) {+ builtin(path, name);+ return true;+ }+ const contributed = assetTypeRegistry.get(type);+ if (contributed?.open) {+ contributed.open(path);+ return true;+ }+ return false;+}++/** Open action per built-in asset type; types absent here aren't double-click-openable. */export const ASSET_OPEN: Partial<Record<AssetType, (path: string, name: string) => void>> = {scene: async (path, name) => {if (!(await confirmDiscard(t('discard.openScene', { name })))) return;diff --git a/desktop/src/project/assetTypes.ts b/desktop/src/project/assetTypes.tsindex 6a83e58c2..089d220b0 100644--- a/desktop/src/project/assetTypes.ts+++ b/desktop/src/project/assetTypes.ts@@ -6,17 +6,23 @@* type carries its file extensions, content-browser badge, and icon/tint;* `assetTypeOf` (extension lookup), the `TYPE_CODE` badges, and the* `AssetIcon`/`assetTint` glyphs all derive from it. Adding an asset type- * is this table + the `AssetType` union in types.ts (the `Record` keeps+ * is this table + the `BuiltinAssetType` union in types.ts (the `Record` keeps* them in sync — a missing entry is a compile error). Double-click open* actions live in assetOpen.ts, co-located with their editors to avoid* import cycles.+ *+ * A CONTRIBUTED type is registered at runtime instead, and carries its open/create+ * actions on the same object (a plugin has no import-cycle problem to design+ * around). Lookups go through {@link assetTypeDef} / {@link assetTypeOf} so both+ * kinds resolve identically; the built-in table keeps its exhaustiveness guard.*/import {Folder, Film, Image, FileImage, PersonStanding, Music,- Component, Blend, FileCode2, Clapperboard, Grid3x3, File, Workflow, Gamepad2, GitBranch, ListTree, Languages, Images, Video, Waypoints, Sparkles,+ Component, Blend, FileCode2, Clapperboard, Grid3x3, File, Workflow, Gamepad2, GitBranch, ListTree, Languages, Images, Video, Waypoints, Sparkles, Plug,type LucideIcon,} from 'lucide-react';-import type { AssetType } from '@/types';+import { ContributionRegistry, type Disposable, type Owner } from '@/contrib/ContributionRegistry';+import type { AssetType, BuiltinAssetType } from '@/types';export interface AssetTypeDef {/** Extensions (lower-case, no dot) that resolve to this type. Omitted for the@@ -30,7 +36,7 @@ export interface AssetTypeDef {// Desaturated tints (vs candy colors) so the content browser stays scannable by// type but reads as a professional tool.-export const ASSET_TYPES: Record<AssetType, AssetTypeDef> = {+export const ASSET_TYPES: Record<BuiltinAssetType, AssetTypeDef> = {folder: { badge: '', icon: Folder, tint: 'var(--star)' },scene: { extensions: ['esscene'], badge: 'SCN', icon: Film, tint: '#c98a93' },texture: { extensions: ['png', 'webp'], badge: 'TEX', icon: FileImage, tint: '#7fa6c4' },@@ -66,8 +72,47 @@ for (const [type, def] of Object.entries(ASSET_TYPES) as [AssetType, AssetTypeDefor (const ext of def.extensions ?? []) byExt.set(ext, type);}-/** Asset type from a file name's extension; unknown extensions fall back to `file`. */+// — Contributed asset types ————————————————————————————————————————————————————++/** A plugin-registered asset type: display data plus its own open/create actions. */+export interface ContributedAssetType extends AssetTypeDef {+ id: string;+ open?: (path: string) => void;+ create?: { label: string; run: (dir: string) => Promise<string | void> | string | void };+}++const contributed = new ContributionRegistry<ContributedAssetType>('asset type');++export const assetTypeRegistry = {+ register(owner: Owner, type: ContributedAssetType): Disposable {+ return contributed.register(owner, type);+ },+ disposeOwner: (owner: Owner): void => contributed.disposeOwner(owner),+ all: (): readonly ContributedAssetType[] => contributed.all(),+ get: (id: string): ContributedAssetType | undefined => contributed.get(id),+ subscribe: (fn: () => void): (() => void) => contributed.subscribe(fn),+ getRevision: (): number => contributed.getRevision(),+};++/** Display data for any asset type — built-in or contributed. Unknown ⇒ the generic file look. */+export function assetTypeDef(type: AssetType): AssetTypeDef {+ return (ASSET_TYPES as Record<string, AssetTypeDef>)[type] ?? contributed.get(type) ?? ASSET_TYPES.file;+}++/**+ * Asset type from a file name's extension; unknown extensions fall back to `file`.+ * Built-ins are matched first, so a plugin cannot re-map `.png`.+ */export function assetTypeOf(name: string): AssetType {const ext = name.split('.').pop()?.toLowerCase() ?? '';- return byExt.get(ext) ?? 'file';+ const builtin = byExt.get(ext);+ if (builtin) return builtin;+ for (const type of contributed.all()) {+ if (type.extensions?.includes(ext)) return type.id;+ }+ return 'file';}++/** Icon assigned to a contributed type — one generic glyph, so a plugin needn't+ * ship an icon and the editor needn't bundle all of lucide to resolve a name. */+export const CONTRIBUTED_ASSET_ICON: LucideIcon = Plug;diff --git a/desktop/src/store/editorStore.ts b/desktop/src/store/editorStore.tsindex bd5b1bee1..9a17e6e02 100644--- a/desktop/src/store/editorStore.ts+++ b/desktop/src/store/editorStore.ts@@ -3,6 +3,7 @@import { create } from 'zustand';import type { ToolMode } from '@/types';import type { GizmoAxis } from '@/tools/gizmo';+import { toolRegistry } from '@/tools/toolRegistry';// Global editor UI state (tools, viewport toggles, play state, launcher gate).// Entity selection lives in its own engine-anchored store — see selectionStore.ts;@@ -121,7 +122,12 @@ interface EditorState {export const useEditorStore = create<EditorState>((set) => ({tool: 'move',- setTool: (tool) => set({ tool }),+ // Picking a built-in tool disarms any contributed one — otherwise choosing Move+ // would silently do nothing while a plugin tool held the strokes.+ setTool: (tool) => {+ toolRegistry.activate(null);+ set({ tool });+ },isPlaying: false,isPaused: false,diff --git a/desktop/src/store/tilemapPaintStore.ts b/desktop/src/store/tilemapPaintStore.tsindex e66ee3c0e..d54d562ae 100644--- a/desktop/src/store/tilemapPaintStore.ts+++ b/desktop/src/store/tilemapPaintStore.ts@@ -9,6 +9,7 @@* selecting. Editor-session state — never serialized.*/import { create } from 'zustand';+import { toolRegistry } from '@/tools/toolRegistry';import {type TileStamp, type TilesetAsset,singleStamp, flipStampH, flipStampV, rotateStampCW, encodeTile,@@ -132,6 +133,11 @@ export const useTilemapPaint = create<TilemapPaintState>((set) => ({flipH: () => set((s) => ({ stamp: flipStampH(s.stamp) })),flipV: () => set((s) => ({ stamp: flipStampV(s.stamp) })),rotateCW: () => set((s) => ({ stamp: rotateStampCW(s.stamp) })),- setTool: (tool) => set({ tool }),+ // Same exclusivity as the transform tools: choosing a paint tool disarms any+ // contributed tool holding the strokes.+ setTool: (tool) => {+ if (tool) toolRegistry.activate(null);+ set({ tool });+ },toggleRandomBrush: () => set((s) => ({ randomBrush: !s.randomBrush })),}));diff --git a/desktop/src/theme/plugins.css b/desktop/src/theme/plugins.cssindex c57f7a247..9d6594e72 100644--- a/desktop/src/theme/plugins.css+++ b/desktop/src/theme/plugins.css@@ -41,3 +41,16 @@only guarantees it fills the tab and scrolls, and that the theme tokens are inscope so a plugin styling against them matches the editor. */.plugin-panel { width: 100%; height: 100%; overflow: auto; }++/* Contributed viewport gizmos. Sits over the engine canvas in the same stacking+ context as the built-in gizmo layers, and never eats pointer events — a plugin+ that wants input contributes a TOOL, which goes through the viewport's router+ rather than intercepting clicks behind its back. */+.viewport__plugin-overlay {+ position: absolute;+ inset: 0;+ width: 100%;+ height: 100%;+ pointer-events: none;+ overflow: visible;+}diff --git a/desktop/src/tools/index.ts b/desktop/src/tools/index.tsindex 56ec4e99f..a8ea601f4 100644--- a/desktop/src/tools/index.ts+++ b/desktop/src/tools/index.ts@@ -2,20 +2,26 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/*** @file tools/index.ts- * @brief Resolves the active viewport tool from the active editor mode. Tilemap- * mode routes to a paint tool (when one is set — it must not re-pick/select);- * every other mode routes to the transform tool (select/move/rotate/scale).- * The Viewport calls this per pointer-down and routes the stroke to it.+ * @brief Resolves the active viewport tool from the active editor mode. An armed+ * CONTRIBUTED tool wins outright (arming one is an explicit act, so it must+ * beat the resting default); otherwise tilemap mode routes to a paint tool+ * (when one is set — it must not re-pick/select), and every other mode to the+ * transform tool (select/move/rotate/scale). The Viewport calls this per+ * pointer-down and routes the stroke to whatever comes back.*/import { useEditorStore } from '@/store/editorStore';import { useTilemapPaint } from '@/store/tilemapPaintStore';import { activeMode } from '@/mode/activeMode';import { TRANSFORM_TOOLS } from './transformTools';import { TILE_TOOLS } from './tileTools';+import { toolRegistry } from './toolRegistry';import type { EditorTool } from './EditorTool';export function resolveActiveTool(): EditorTool {- if (activeMode().toolset === 'tilemap') {+ const mode = activeMode();+ const contributed = toolRegistry.activeFor(mode.id);+ if (contributed) return contributed;+ if (mode.toolset === 'tilemap') {const tool = useTilemapPaint.getState().tool;if (tool) return TILE_TOOLS[tool];}@@ -24,3 +30,4 @@ export function resolveActiveTool(): EditorTool {export type { EditorTool, PointerInput, ToolContext } from './EditorTool';export { isTilemapSelected, isTilePaintMode } from './tileMode';+export { toolRegistry, type ToolContribution } from './toolRegistry';diff --git a/desktop/src/tools/toolRegistry.ts b/desktop/src/tools/toolRegistry.tsnew file mode 100644index 000000000..d287d4488--- /dev/null+++ b/desktop/src/tools/toolRegistry.ts@@ -0,0 +1,93 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file toolRegistry.ts+ * @brief Contributed viewport tools — the third tool family beside the built-in+ * transform and tile tools, and the only one that is open-ended.+ *+ * A contributed tool IS an {@link EditorTool}: it takes a stroke by returning true+ * from onPointerDown and owns the stroke's move/up, exactly like the built-ins, so+ * the Viewport stays a router with no idea a plugin is involved.+ *+ * Activation is EXCLUSIVE and lives here rather than in a store of its own: at most+ * one contributed tool is armed, and arming one is what makes it beat the built-in+ * resolution. Keeping the active id next to the registry means retracting a tool+ * (plugin unload) can disarm it in the same place — a dangling active id would send+ * strokes to a tool that no longer exists.+ */+import { ContributionRegistry, type Disposable, type Owner } from '@/contrib/ContributionRegistry';+import type { EditorTool } from './EditorTool';++export interface ToolContribution extends EditorTool {+ /** Namespaced id, e.g. `acme.measure`. Also the activation command's id. */+ readonly id: string;+ /** Shown in the viewport toolbar / palette row for the tool. */+ readonly title: string;+ /** Restrict to these editor modes (omitted ⇒ every mode). */+ readonly modes?: readonly string[];+}++const contrib = new ContributionRegistry<ToolContribution>('viewport tool');+const listeners = new Set<() => void>();+let activeId: string | null = null;++const changed = (): void => {+ for (const fn of listeners) fn();+};++export const toolRegistry = {+ register(owner: Owner, tool: ToolContribution): Disposable {+ const handle = contrib.register(owner, tool);+ changed();+ return {+ dispose: () => {+ // Disarm before retracting, so no stroke can route to a gone tool.+ if (activeId === tool.id) activeId = null;+ handle.dispose();+ changed();+ },+ };+ },++ disposeOwner(owner: Owner): void {+ for (const tool of contrib.byOwner(owner)) if (activeId === tool.id) activeId = null;+ contrib.disposeOwner(owner);+ changed();+ },++ all(): readonly ToolContribution[] {+ return contrib.all();+ },++ get(id: string): ToolContribution | undefined {+ return contrib.get(id);+ },++ /** Arm a contributed tool (null disarms). Unknown ids are ignored. */+ activate(id: string | null): void {+ if (id !== null && !contrib.get(id)) return;+ activeId = id;+ changed();+ },++ activeId(): string | null {+ return activeId;+ },++ /** The armed tool, if it's allowed in `mode`. */+ activeFor(mode: string): ToolContribution | undefined {+ if (activeId === null) return undefined;+ const tool = contrib.get(activeId);+ if (!tool) return undefined;+ return !tool.modes || tool.modes.includes(mode) ? tool : undefined;+ },++ subscribe(fn: () => void): () => void {+ listeners.add(fn);+ const off = contrib.subscribe(fn);+ return () => {+ listeners.delete(fn);+ off();+ };+ },+};diff --git a/desktop/src/types.ts b/desktop/src/types.tsindex 5cb0436ba..105fc76d9 100644--- a/desktop/src/types.ts+++ b/desktop/src/types.ts@@ -186,7 +186,12 @@ export interface InspectSource {override?: boolean;}-export type AssetType =+/**+ * The asset types the editor ships. Kept as a closed union so `ASSET_TYPES` stays an+ * exhaustive record — a built-in type with no badge/icon entry is a compile error,+ * which is the guard that catches a half-added type.+ */+export type BuiltinAssetType =| 'folder'| 'scene'| 'sprite'@@ -210,6 +215,9 @@ export type AssetType =| 'locale'| 'file';+/** A built-in asset type, or one a plugin contributed. */+export type AssetType = BuiltinAssetType | (string & {});+export interface AssetItem {id: string;name: string;diff --git a/desktop/tests/plugin-contributions.test.ts b/desktop/tests/plugin-contributions.test.tsnew file mode 100644index 000000000..bfb6699b5--- /dev/null+++ b/desktop/tests/plugin-contributions.test.ts@@ -0,0 +1,314 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The P3 contribution seams — inspector rows, overlay primitives, context+ * menu rows, contributed asset types, and viewport tool arming.+ *+ * These cover the rules that are easy to get subtly wrong and invisible when they+ * are: a read-only row must never route a write, a partially-projected polyline must+ * not draw a false shape, contributed rows must not leave a dangling separator, a+ * plugin must not be able to re-map a built-in file extension, and arming a built-in+ * tool must disarm a contributed one.+ */+import { describe, it, expect, vi, afterEach } from 'vitest';+import { createSectionBuilder, isInfoRow, inspectorRegistry } from '@/plugins/inspector';+import { contextMenuRegistry, contributedContextRows } from '@/plugins/contextMenus';+import { assetTypeRegistry, assetTypeOf, assetTypeDef, ASSET_TYPES } from '@/project/assetTypes';+import { toolRegistry } from '@/tools/toolRegistry';+import { useEditorStore } from '@/store/editorStore';+import { useTilemapPaint } from '@/store/tilemapPaintStore';+import type { OverlayPrimitive } from '@/plugins/overlays';+import type { GizmoStyle, OverlayGraphics, Vec2 } from '@/plugins/types';++const PLUGIN = 'plugin:acme';+const id = (s: string) => s;++afterEach(() => {+ for (const registry of [inspectorRegistry, contextMenuRegistry, assetTypeRegistry, toolRegistry]) {+ registry.disposeOwner(PLUGIN);+ }+});++// — Inspector builder ——————————————————————————————————————————————————————————++describe('inspector section builder', () => {+ it('turns row calls into the editor`s own field shapes', () => {+ const { ui, fields } = createSectionBuilder(id);+ ui.number('gain', 'Gain', 0.5, { min: 0, max: 1, step: 0.1, unit: 'x' });+ ui.bool('on', 'Enabled', true);+ ui.text('name', 'Name', 'hi');+ ui.vec2('at', 'At', { x: 3, y: 4 });+ ui.color('tint', 'Tint', '#ff0000');+ ui.select('mode', 'Mode', 'b', ['a', 'b']);++ expect(fields.map((f) => [f.key, f.type, f.value])).toEqual([+ ['gain', 'number', 0.5],+ ['on', 'bool', true],+ ['name', 'string', 'hi'],+ ['at', 'vec2', [3, 4]],+ ['tint', 'color', '#ff0000'],+ ['mode', 'select', 'b'],+ ]);+ // A bounded number gets a slider; an unbounded one must not.+ expect(fields[0].slider).toBe(true);+ expect(fields[0].unit).toBe('x');+ expect(fields[5].selectOptions).toEqual(['a', 'b']);+ });++ it('gives read-only rows keys that can never be written back', () => {+ const { ui, fields } = createSectionBuilder(id);+ ui.info('Components', '3');+ ui.info('Children', '1');+ ui.number('real', 'Real', 1);++ // Distinct keys, so two info rows don't collide in the field list...+ expect(fields.map((f) => f.key)).toEqual(['__info0', '__info1', 'real']);+ // ...and both are recognizable as read-only by the write router.+ expect(isInfoRow(fields[0].key)).toBe(true);+ expect(isInfoRow(fields[1].key)).toBe(true);+ expect(isInfoRow(fields[2].key)).toBe(false);+ });++ it('an unbounded number gets no slider', () => {+ const { ui, fields } = createSectionBuilder(id);+ ui.number('n', 'N', 1, { min: 0 });+ expect(fields[0].slider).toBe(false);+ });+});++describe('inspector registry', () => {+ it('resolves sections by component and by asset type, not across', () => {+ inspectorRegistry.register(PLUGIN, {+ kind: 'component', id: 'a', component: 'Sprite', title: 'A', build: () => {},+ });+ inspectorRegistry.register(PLUGIN, {+ kind: 'asset', id: 'b', assetType: 'texture', title: 'B', build: () => {},+ });+ expect(inspectorRegistry.forComponent('Sprite').map((s) => s.id)).toEqual(['a']);+ expect(inspectorRegistry.forComponent('texture')).toEqual([]);+ expect(inspectorRegistry.forAssetType('texture').map((s) => s.id)).toEqual(['b']);+ expect(inspectorRegistry.forAssetType('Sprite')).toEqual([]);+ });+});++// — Overlay primitives —————————————————————————————————————————————————————————++/** A graphics surface with a fixed, invertible projection (no engine needed). */+function fakeGraphics(out: OverlayPrimitive[], project: (x: number, y: number) => Vec2 | null): OverlayGraphics {+ const g: OverlayGraphics = {+ worldToViewport: project,+ viewportToWorld: (x, y) => ({ x, y }),+ line(a, b, style) {+ const p0 = project(a.x, a.y);+ const p1 = project(b.x, b.y);+ if (p0 && p1) out.push({ kind: 'line', points: [p0, p1], style });+ },+ polyline(points, style) {+ const projected: Vec2[] = [];+ for (const p of points) {+ const q = project(p.x, p.y);+ if (!q) return;+ projected.push(q);+ }+ if (projected.length >= 2) out.push({ kind: 'polyline', points: projected, style });+ },+ circle(center, radius, style) {+ const c = project(center.x, center.y);+ const edge = project(center.x + radius, center.y);+ if (c && edge) out.push({ kind: 'circle', center: c, radius: Math.abs(edge.x - c.x), style });+ },+ rect(a, b, style) {+ const p0 = project(a.x, a.y);+ const p1 = project(b.x, b.y);+ if (!p0 || !p1) return;+ out.push({+ kind: 'rect', x: Math.min(p0.x, p1.x), y: Math.min(p0.y, p1.y),+ w: Math.abs(p1.x - p0.x), h: Math.abs(p1.y - p0.y), style,+ });+ },+ text(at, text, style) {+ const p = project(at.x, at.y);+ if (p) out.push({ kind: 'text', at: p, text, style });+ },+ };+ return g;+}++describe('overlay primitives', () => {+ // 2x zoom, y flipped — enough to prove world coords are projected, not passed through.+ const zoom2 = (x: number, y: number): Vec2 => ({ x: x * 2, y: -y * 2 });++ it('projects every point, so a gizmo is authored in world space', () => {+ const out: OverlayPrimitive[] = [];+ const g = fakeGraphics(out, zoom2);+ g.line({ x: 1, y: 2 }, { x: 3, y: 4 });+ expect(out[0]).toMatchObject({ kind: 'line', points: [{ x: 2, y: -4 }, { x: 6, y: -8 }] });+ });++ it('derives a circle`s pixel radius from the projection, so it scales with zoom', () => {+ const out: OverlayPrimitive[] = [];+ fakeGraphics(out, zoom2).circle({ x: 0, y: 0 }, 10);+ // A world radius of 10 at 2x is 20 screen pixels — not 10.+ expect(out[0]).toMatchObject({ kind: 'circle', radius: 20 });+ });++ it('normalizes a rect given by any two opposite corners', () => {+ const out: OverlayPrimitive[] = [];+ fakeGraphics(out, (x, y) => ({ x, y })).rect({ x: 10, y: 10 }, { x: 4, y: 2 });+ expect(out[0]).toMatchObject({ kind: 'rect', x: 4, y: 2, w: 6, h: 8 });+ });++ it('drops a primitive whose projection fails rather than drawing it wrong', () => {+ const out: OverlayPrimitive[] = [];+ const g = fakeGraphics(out, () => null); // no camera yet+ g.line({ x: 0, y: 0 }, { x: 1, y: 1 });+ g.circle({ x: 0, y: 0 }, 5);+ g.text({ x: 0, y: 0 }, 'x');+ expect(out).toEqual([]);+ });++ it('drops a PARTIALLY projectable polyline whole — a half shape is a false shape', () => {+ const out: OverlayPrimitive[] = [];+ let calls = 0;+ const g = fakeGraphics(out, (x, y) => (++calls > 2 ? null : { x, y }));+ g.polyline([{ x: 0, y: 0 }, { x: 1, y: 1 }, { x: 2, y: 2 }]);+ expect(out).toEqual([]);+ });+});++// — Context menu rows ——————————————————————————————————————————————————————————++describe('contributed context menu rows', () => {+ it('adds nothing at all when no plugin contributes — no dangling separator', () => {+ expect(contributedContextRows('outliner/item', { entity: 1 })).toEqual([]);+ });++ it('prefixes a separator when there ARE rows, so grouping is right either way', () => {+ contextMenuRegistry.register(PLUGIN, {+ id: 'acme.row', location: 'outliner/item', label: 'Do it', run: () => {},+ });+ const rows = contributedContextRows('outliner/item', { entity: 1 });+ expect(rows[0]).toEqual({ sep: true });+ expect(rows).toHaveLength(2);+ });++ it('filters by location and by `when`, and passes the target through to run', () => {+ const run = vi.fn();+ contextMenuRegistry.register(PLUGIN, {+ id: 'acme.entityOnly',+ location: 'outliner/item',+ label: 'Entity only',+ when: (target) => target.entity === 7,+ run,+ });+ expect(contributedContextRows('outliner/item', { entity: 1 })).toEqual([]);+ expect(contributedContextRows('content/item', { path: 'a.png' })).toEqual([]);++ const rows = contributedContextRows('outliner/item', { entity: 7 });+ expect(rows).toHaveLength(2);+ (rows[1] as { onClick: () => void }).onClick();+ expect(run).toHaveBeenCalledWith({ entity: 7 });+ });++ it('resolves a localized label against the session locale', () => {+ contextMenuRegistry.register(PLUGIN, {+ id: 'acme.loc', location: 'content/item', label: { en: 'Reveal' }, run: () => {},+ });+ const rows = contributedContextRows('content/item', { path: 'a.png' });+ expect((rows[1] as { label: string }).label).toBe('Reveal');+ });+});++// — Contributed asset types ————————————————————————————————————————————————————++describe('contributed asset types', () => {+ it('resolves its extensions, and falls back to `file` for unknown ones', () => {+ assetTypeRegistry.register(PLUGIN, {+ id: 'acme.dialogue', extensions: ['dlg'], badge: 'DLG', icon: ASSET_TYPES.file.icon, tint: '#abc',+ });+ expect(assetTypeOf('intro.dlg')).toBe('acme.dialogue');+ expect(assetTypeOf('intro.unknown')).toBe('file');+ expect(assetTypeDef('acme.dialogue').badge).toBe('DLG');+ });++ it('cannot re-map a built-in extension', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ assetTypeRegistry.register(PLUGIN, {+ id: 'acme.png-hijack', extensions: ['png'], badge: 'X', icon: ASSET_TYPES.file.icon, tint: '#abc',+ });+ expect(assetTypeOf('hero.png')).toBe('texture');+ warn.mockRestore();+ });++ it('unknown types resolve to the generic file look rather than throwing', () => {+ expect(assetTypeDef('acme.gone')).toBe(ASSET_TYPES.file);+ });+});++// — Viewport tool arming ———————————————————————————————————————————————————————++describe('contributed viewport tools', () => {+ const tool = {+ id: 'acme.measure',+ title: 'Measure',+ onPointerDown: () => true,+ onPointerMove: () => {},+ onPointerUp: () => {},+ };++ it('is only active while armed, and only in its declared modes', () => {+ toolRegistry.register(PLUGIN, { ...tool, modes: ['scene'] });+ expect(toolRegistry.activeFor('scene')).toBeUndefined(); // registered ≠ armed++ toolRegistry.activate('acme.measure');+ expect(toolRegistry.activeFor('scene')?.id).toBe('acme.measure');+ expect(toolRegistry.activeFor('tilemap')).toBeUndefined(); // wrong mode++ toolRegistry.activate(null);+ expect(toolRegistry.activeFor('scene')).toBeUndefined();+ });++ it('is active in every mode when it declares none', () => {+ toolRegistry.register(PLUGIN, tool);+ toolRegistry.activate('acme.measure');+ expect(toolRegistry.activeFor('scene')?.id).toBe('acme.measure');+ expect(toolRegistry.activeFor('tilemap')?.id).toBe('acme.measure');+ });++ it('ignores arming an id that isn`t registered', () => {+ toolRegistry.activate('acme.nope');+ expect(toolRegistry.activeId()).toBeNull();+ });++ it('disarms when the tool is retracted, so no stroke routes to a gone tool', () => {+ const d = toolRegistry.register(PLUGIN, tool);+ toolRegistry.activate('acme.measure');+ d.dispose();+ expect(toolRegistry.activeId()).toBeNull();+ expect(toolRegistry.activeFor('scene')).toBeUndefined();+ });++ it('disarms when its owner is disposed (plugin unload)', () => {+ toolRegistry.register(PLUGIN, tool);+ toolRegistry.activate('acme.measure');+ toolRegistry.disposeOwner(PLUGIN);+ expect(toolRegistry.activeId()).toBeNull();+ });++ it('is disarmed by picking a built-in tool, so the user is never stuck in it', () => {+ toolRegistry.register(PLUGIN, tool);++ toolRegistry.activate('acme.measure');+ useEditorStore.getState().setTool('move');+ expect(toolRegistry.activeId()).toBeNull();++ toolRegistry.activate('acme.measure');+ useTilemapPaint.getState().setTool('brush');+ expect(toolRegistry.activeId()).toBeNull();++ // Clearing the paint tool is not a tool CHOICE, so it must not disarm.+ toolRegistry.activate('acme.measure');+ useTilemapPaint.getState().setTool(null);+ expect(toolRegistry.activeId()).toBe('acme.measure');+ });+});diff --git a/examples/sprite-animation/.esengine/plugins/estella.scene-report/src/editor.ts b/examples/sprite-animation/.esengine/plugins/estella.scene-report/src/editor.tsindex 163586acd..94a44eeb9 100644--- a/examples/sprite-animation/.esengine/plugins/estella.scene-report/src/editor.ts+++ b/examples/sprite-animation/.esengine/plugins/estella.scene-report/src/editor.ts@@ -136,6 +136,132 @@ export default definePlugin({},});+ // — An inspector section. It renders through the editor's own property UI, so it+ // looks native without any styling; `write` receives edits to the rows it+ // built, and wrapping the scene write in transact() makes it one undo step. —+ ctx.inspector.register({+ kind: 'component',+ id: 'transform-report',+ component: 'Transform',+ title: { en: 'Scene Report', 'zh-CN': '场景报告' },+ build: (entity, ui) => {+ const e = ctx.scene.getEntity(entity);+ ui.info({ en: 'Components', 'zh-CN': '组件数' }, String(e?.components.length ?? 0));+ ui.info({ en: 'Children', 'zh-CN': '子实体' }, String(countChildren(ctx, entity)));+ ui.text('label', { en: 'Report label', 'zh-CN': '报告标签' }, e?.name ?? '');+ },+ action: {+ label: { en: 'Log', 'zh-CN': '输出' },+ run: (entity) => ctx.log.info(`entity ${entity}: ${ctx.scene.getEntity(entity)?.name}`),+ },+ // Renaming through ctx.scene means the edit is undoable like any other.+ write: (entity, key, value) => {+ if (key === 'label') ctx.scene.transact('Rename from Scene Report', () => ctx.scene.renameEntity(entity, String(value)));+ },+ });++ // — A viewport overlay. Coordinates are WORLD space and the host projects them,+ // so this gizmo tracks the scene through pan and zoom with no camera math. —+ ctx.overlays.register({+ id: 'selection-ring',+ render: (g) => {+ const id = ctx.scene.getSelection();+ if (id == null) return;+ const p = ctx.scene.getFieldValue(id, 'Transform', 'position');+ if (!Array.isArray(p)) return;+ const at = { x: p[0], y: p[1] };+ // A world-unit radius, so the ring scales with the scene rather than+ // staying a fixed number of pixels.+ g.circle(at, 48, { color: 'var(--star)', width: 1.5, dashed: true });+ g.line({ x: at.x - 64, y: at.y }, { x: at.x + 64, y: at.y }, { color: 'var(--star)', opacity: 0.5 });+ g.text({ x: at.x + 52, y: at.y + 52 }, ctx.scene.getEntity(id)?.name ?? '', { fontSize: 11 });+ },+ });++ // — A viewport tool. Armed via its command; while armed it gets first refusal on+ // every stroke, and picking any built-in tool disarms it. —+ let dragFrom: { x: number; y: number } | null = null;+ ctx.overlays.register({+ id: 'measure-line',+ render: (g) => {+ if (!dragFrom || !dragTo) return;+ g.line(dragFrom, dragTo, { color: '#e0a35a', width: 2 });+ const dx = dragTo.x - dragFrom.x;+ const dy = dragTo.y - dragFrom.y;+ g.text(dragTo, `${Math.hypot(dx, dy).toFixed(1)} wu`, { color: '#e0a35a' });+ },+ });+ let dragTo: { x: number; y: number } | null = null;+ ctx.tools.register({+ id: 'estella.scene-report.measure',+ title: { en: 'Measure', 'zh-CN': '测距' },+ onPointerDown: (p, tc) => {+ // Pointer input arrives in viewport space, the same space ctx.viewport+ // projects from — no conversion needed.+ dragFrom = ctx.viewport.viewportToWorld(p.x, p.y);+ dragTo = dragFrom;+ tc.capture(p.pointerId);+ return true; // claim the stroke+ },+ onPointerMove: (p) => {+ if (dragFrom) dragTo = ctx.viewport.viewportToWorld(p.x, p.y);+ },+ onPointerUp: (p, tc) => {+ tc.release(p.pointerId);+ if (dragFrom && dragTo) {+ ctx.log.info(`measured ${Math.hypot(dragTo.x - dragFrom.x, dragTo.y - dragFrom.y).toFixed(2)} world units`);+ }+ dragFrom = dragTo = null;+ },+ cancel: () => {+ dragFrom = dragTo = null;+ },+ });+ ctx.commands.register({+ id: 'estella.scene-report.measureTool',+ title: { en: 'Measure Tool', 'zh-CN': '测距工具' },+ category: { en: 'Scene Report', 'zh-CN': '场景报告' },+ menu: 'tools',+ isChecked: () => ctx.tools.activeId() === 'estella.scene-report.measure',+ run: () =>+ ctx.tools.activate(+ ctx.tools.activeId() === 'estella.scene-report.measure' ? null : 'estella.scene-report.measure',+ ),+ });++ // — An entity template. The host builds the prefab from these component specs,+ // so it appears in the Create picker beside the built-in ones. —+ ctx.entities.registerTemplate({+ id: 'estella.scene-report.marker',+ label: { en: 'Report Marker', 'zh-CN': '报告标记' },+ category: 'Scripts',+ keywords: ['report', 'marker'],+ components: [{ type: 'Transform' }, { type: 'Marker', data: { type: 'report' } }],+ });++ // — A context-menu row. `when` hides it for targets it doesn't apply to, and the+ // host drops the separator with it, so the menu never shows a stray divider. —+ ctx.contextMenus.register({+ id: 'estella.scene-report.logEntity',+ location: 'outliner/item',+ label: { en: 'Log to Scene Report', 'zh-CN': '输出到场景报告' },+ when: (target) => target.entity != null,+ run: (target) => ctx.log.info(`outliner: ${ctx.scene.getEntity(target.entity!)?.name}`),+ });+ctx.log.info('scene report ready');},});++/** Direct children of an entity, from the scene tree. */+function countChildren(ctx: PluginContext, entity: number): number {+ const find = (nodes: ReturnType<PluginContext['scene']['getSceneTree']>): number | null => {+ for (const n of nodes) {+ if (n.id === entity) return n.children?.length ?? 0;+ const hit = n.children ? find(n.children) : null;+ if (hit !== null) return hit;+ }+ return null;+ };+ return find(ctx.scene.getSceneTree()) ?? 0;+}