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): metadata-driven Details — enums, ranges, reset & per-component enable
esenginec6f210d56496
diff --git a/desktop/electron/extractSchemas.ts b/desktop/electron/extractSchemas.tsindex d5d09e293..c5290d1f0 100644--- a/desktop/electron/extractSchemas.ts+++ b/desktop/electron/extractSchemas.ts@@ -55,6 +55,18 @@ export interface ComponentSchema {spineFields?: unknown;/** Field keys that hold an Entity handle. */entityFields: string[];+ /** Per-field editor metadata (enum + numeric range/unit), keyed by field name. */+ fields?: Record<string, SerializedFieldMeta>;+}++/** The serialized editor metadata of one component field. */+export interface SerializedFieldMeta {+ enum?: Array<{ label: string; value: number }>;+ min?: number;+ max?: number;+ step?: number;+ slider?: boolean;+ unit?: string;}export interface ExtractSchemasResult {@@ -179,6 +191,27 @@ interface UserComponentDef {assetFields?: readonly unknown[];spineFields?: unknown;entityFields?: readonly string[];+ fieldMeta?: Record<string, SerializedFieldMeta>;+}++// Keep only fields the inspector actually consumes (enum / numeric range / unit),+// dropping empties so schemas.json doesn't balloon with `{}` per field.+function pickFieldMeta(+ fieldMeta: UserComponentDef['fieldMeta'],+): ComponentSchema['fields'] | undefined {+ if (!fieldMeta) return undefined;+ const out: Record<string, SerializedFieldMeta> = {};+ for (const [key, meta] of Object.entries(fieldMeta)) {+ const m: SerializedFieldMeta = {};+ if (meta.enum && meta.enum.length) m.enum = meta.enum.map((o) => ({ ...o }));+ if (meta.min != null) m.min = meta.min;+ if (meta.max != null) m.max = meta.max;+ if (meta.step != null) m.step = meta.step;+ if (meta.slider != null) m.slider = meta.slider;+ if (meta.unit != null) m.unit = meta.unit;+ if (Object.keys(m).length) out[key] = m;+ }+ return Object.keys(out).length ? out : undefined;}function toSchema(def: unknown): ComponentSchema {@@ -193,5 +226,7 @@ function toSchema(def: unknown): ComponentSchema {entityFields: [...(d.entityFields ?? [])],};if (d.spineFields) schema.spineFields = d.spineFields;+ const fields = pickFieldMeta(d.fieldMeta);+ if (fields) schema.fields = fields;return schema;}diff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.tsindex 15e069746..768c8db4f 100644--- a/desktop/src/engine/SceneCommands.ts+++ b/desktop/src/engine/SceneCommands.ts@@ -75,6 +75,7 @@ export function toModelValue(): unknown {switch (type) {case 'number':+ case 'enum':return Number(value);case 'bool':return Boolean(value);diff --git a/desktop/src/engine/SceneQuery.ts b/desktop/src/engine/SceneQuery.tsindex 4602b99a5..4855d2afd 100644--- a/desktop/src/engine/SceneQuery.ts+++ b/desktop/src/engine/SceneQuery.ts@@ -8,6 +8,7 @@ import {inspectorFields,inferField,isColorKey,+ componentEnable,modelInspectableComponents,modelKindOf,modelNameOf,@@ -52,14 +53,26 @@ export function buildEntityInfo(data: SceneData | null, id: EntityId): { name: sreturn { name: modelNameOf(e, kind), kind, components: modelInspectableComponents(e).map((c) => c.label) };}-/** Full inspector model for one entity in a SceneData. */-export function buildInspector(data: SceneData | null, id: EntityId): InspectorComponent[] {+/**+ * Full inspector model for one entity in a SceneData. `baseOf` (optional) supplies+ * a per-component override base — the prefab-instance base data, when the entity+ * is a prefab instance — so reset/override marks compare against the prefab rather+ * than the class default. Without it, fields fall back to the component default.+ */+export function buildInspector(+ data: SceneData | null,+ id: EntityId,+ baseOf?: (comp: string) => Record<string, unknown> | undefined,+): InspectorComponent[] {const e = data?.entities.find((x) => x.id === id);if (!e) return [];const out: InspectorComponent[] = [];for (const { name, label } of modelInspectableComponents(e)) {const cdata = (e.components.find((c) => c.type === name)?.data as Record<string, unknown>) ?? {};- out.push({ name, label, fields: inspectorFields(name, cdata) });+ const enable = componentEnable(name, cdata) ?? undefined;+ // The enable field is promoted to the header checkbox — drop it from the body.+ const fields = inspectorFields(name, cdata, baseOf?.(name)).filter((f) => f.key !== enable?.key);+ out.push({ name, label, fields, enable });}return out;}@@ -105,7 +118,26 @@ export class SceneQueryImpl {/** Full editable inspector model for a source entity — fields resolved per component. */readInspector(id: EntityId): InspectorComponent[] {- return buildInspector(this.model.current, id);+ return buildInspector(this.model.current, id, this.prefabBaseOf(id));+ }++ /**+ * The prefab-instance base for an entity: a per-component lookup into the prefab+ * asset's data, so the inspector marks/resets fields against the prefab (the UE+ * override semantic) rather than the class default. Undefined when the entity+ * isn't a prefab instance or no resolver is registered (e.g. isolated tests) —+ * then fields fall back to the component default. The prefab asset is owned by+ * the project layer, so the data source is injected (see {@link setPrefabBaseResolver}).+ */+ private prefabBaseOf(id: EntityId): ((comp: string) => Record<string, unknown> | undefined) | undefined {+ if (!prefabBaseResolver) return undefined;+ const tag = this.model.prefabTag(id);+ if (!tag) return undefined;+ const ref = tag.prefab ?? this.model.prefabTag(tag.instanceRoot)?.prefab;+ if (!ref) return undefined;+ const comps = prefabBaseResolver(ref, tag.prefabId);+ if (!comps) return undefined;+ return (comp) => comps.find((c) => c.type === comp)?.data;}/** Read one inspector field's current value (for undo before/after capture). */@@ -118,5 +150,18 @@ export class SceneQueryImpl {}}+/** Resolves a prefab instance's base component data, by ref + the entity's prefab id. */+export type PrefabBaseComponents = Array<{ type: string; data: Record<string, unknown> }>;+export type PrefabBaseResolver = (ref: string, prefabId: string) => PrefabBaseComponents | null;++// Injected by the project layer (it owns the loaded `.esprefab` cache). Left unset+// in isolated sessions/tests, where reset falls back to the component default.+let prefabBaseResolver: PrefabBaseResolver | null = null;++/** Register the source of prefab-instance base data (for override-aware reset). */+export function setPrefabBaseResolver(resolver: PrefabBaseResolver | null): void {+ prefabBaseResolver = resolver;+}+/** The app's default-session query surface. Other sessions construct their own SceneQueryImpl(model, store). */export const SceneQuery = new SceneQueryImpl(SceneModel, SceneStore);diff --git a/desktop/src/engine/schema.ts b/desktop/src/engine/schema.tsindex 24d1cdfc0..5bfbcac79 100644--- a/desktop/src/engine/schema.ts+++ b/desktop/src/engine/schema.ts@@ -1,8 +1,8 @@// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-import { getAllRegisteredComponents, getUserComponents, getComponent, getComponentAssetFieldDescriptors } from 'esengine';+import { getAllRegisteredComponents, getUserComponents, getComponent, getComponentAssetFieldDescriptors, getComponentFieldMeta } from 'esengine';import type { App, SceneData } from 'esengine';-import type { NodeKind, InspectorField } from '@/types';+import type { NodeKind, InspectorField, EnumOption } from '@/types';type SceneEntityLike = SceneData['entities'][number];@@ -167,6 +167,18 @@ export interface UserComponentSchema {colorKeys: string[];/** Asset-ref fields (e.g. `[{field:'texture', type:'texture'}]`). */assetFields?: Array<{ field: string; type: string }>;+ /** Per-field editor metadata (enum + numeric range/unit), keyed by field name. */+ fields?: Record<string, UserFieldMeta>;+}++/** A serialized field's editor metadata, as carried in `schemas.json`. */+export interface UserFieldMeta {+ enum?: EnumOption[];+ min?: number;+ max?: number;+ step?: number;+ slider?: boolean;+ unit?: string;}const userSchemas = new Map<string, UserComponentSchema>();@@ -219,6 +231,37 @@ export function assetFieldType(compType: string, key: string): string | null {return null;}+// — Field presentation metadata (the SDK's UPROPERTY analog) —+//+// A component declares per-field editor policy (enum options, numeric range,+// step, slider, unit) at its definition site, so e.g. Camera.projectionType+// renders as a "Perspective / Orthographic" dropdown and TilemapLayer.opacity as+// a 0..1 slider — and the enum labels can never drift from the engine's enum+// constants. Builtins resolve via the engine registry; user/script components+// (absent from it) declare theirs in schemas.json.++/** Merged per-field metadata: the engine component def first, then the user schema. */+export function fieldMetaFor(compType: string, key: string): UserFieldMeta | null {+ const fromDef = getComponentFieldMeta(compType)[key];+ if (fromDef) {+ return {+ enum: fromDef.enum?.map((o) => ({ label: o.label, value: o.value })),+ min: fromDef.min,+ max: fromDef.max,+ step: fromDef.step,+ slider: fromDef.slider,+ unit: fromDef.unit,+ };+ }+ return userSchema(compType)?.fields?.[key] ?? null;+}++/** The dropdown options for an enum field, or null if the field isn't an enum. */+export function enumFieldOptions(compType: string, key: string): EnumOption[] | null {+ const e = fieldMetaFor(compType, key)?.enum;+ return e && e.length ? e.map((o) => ({ ...o })) : null;+}+/*** Build one inspector field: an **asset control** for asset-ref fields (carrying* the `@uuid:` ref or 0 for none), else a value-shape-inferred control.@@ -239,7 +282,19 @@ function fieldFor(assetType: at,};}- return inferField(key, value, isColor);+ const meta = fieldMetaFor(compType, key);+ if (meta?.enum && meta.enum.length) {+ return { key, label: prettyLabel(key), type: 'enum', value: Number(value) || 0, options: meta.enum.map((o) => ({ ...o })) };+ }+ const base = inferField(key, value, isColor);+ if (base && base.type === 'number' && meta) {+ if (meta.min != null) base.min = meta.min;+ if (meta.max != null) base.max = meta.max;+ if (meta.step != null) base.step = meta.step;+ if (meta.unit != null) base.unit = meta.unit;+ if (meta.slider && meta.min != null && meta.max != null) base.slider = true;+ }+ return base;}/**@@ -247,8 +302,17 @@ function fieldFor(* comes from (in order): the engine registry, the user schema, or — as a* best-effort fallback — the data values themselves; asset-ref fields become an* asset control. `DERIVED_FIELDS` are skipped.+ *+ * Each field also carries `defaultValue` — the value a reset reverts to — taken+ * from `baseData` (the prefab-instance base, when given) else the component's+ * registered default. The caller diffs `value` vs `defaultValue` to mark+ * overrides; an entity with no prefab base just compares against the default.*/-export function inspectorFields(compType: string, data: Record<string, unknown>): InspectorField[] {+export function inspectorFields(+ compType: string,+ data: Record<string, unknown>,+ baseData?: Record<string, unknown>,+): InspectorField[] {const def = componentByName(compType);const schema = def ? undefined : userSchema(compType);const colorKeys = new Set<string>(def ? def.colorKeys : (schema?.colorKeys ?? []));@@ -260,11 +324,42 @@ export function inspectorFields(compType: string, data: Record<string, unknown>)if (DERIVED_FIELDS.has(key)) continue;const value = key in data ? data[key] : defaults?.[key];const f = fieldFor(compType, key, value, colorKeys.has(key));- if (f) fields.push(f);+ if (!f) continue;+ // Reset target: the prefab base for this key, else the registered default.+ const baseRaw = baseData && key in baseData ? baseData[key] : defaults?.[key];+ if (baseRaw !== undefined) {+ const bf = fieldFor(compType, key, baseRaw, colorKeys.has(key));+ if (bf) f.defaultValue = bf.value;+ }+ fields.push(f);}return fields;}+// The boolean field a component's header enable-checkbox toggles: `enabled` for+// most, `isActive` (Camera) / `visible` (TilemapLayer) for the few that name it+// differently. Promoted to the header (and hidden from the body field list) — the+// UE per-component enable affordance. Null when the component can't be disabled+// (Transform, Canvas), where the header shows a static, non-interactive check.+const ENABLE_KEYS = ['enabled', 'isActive', 'visible'] as const;++/** The component's enable field + current value, or null if it has none. */+export function componentEnable(+ compType: string,+ data: Record<string, unknown>,+): { key: string; value: boolean } | null {+ const def = componentByName(compType);+ const defaults = def ? componentDefaults(def) : userSchema(compType)?.default;+ const src = defaults ?? data;+ for (const key of ENABLE_KEYS) {+ if (typeof src[key] === 'boolean') {+ const raw = key in data ? data[key] : src[key];+ return { key, value: raw !== false };+ }+ }+ return null;+}+// — Model-based reflection (the editor reads the model, not the World) —const orderIndex = (name: string): number => {diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsxindex 23709d7e4..ba1eb941a 100644--- a/desktop/src/panels/Details.tsx+++ b/desktop/src/panels/Details.tsx@@ -16,6 +16,7 @@ import {Move3d,Package,Plus,+ RotateCcw,Search,Square,Trash2,@@ -35,15 +36,29 @@ import { SceneModel } from '@/engine/SceneModel';import { SceneCommands, toModelValue } from '@/engine/SceneCommands';import { PlayInspect } from '@/engine/PlayInspect';import type { SceneData } from 'esengine';-import { modelAddableComponentEntries, subscribeSchemas, getSchemaRevision } from '@/engine/schema';+import { modelAddableComponentEntries, subscribeSchemas, getSchemaRevision, prettyLabel } from '@/engine/schema';import { ProjectStore } from '@/project/ProjectStore';import { ContextMenu } from '@/components/Menu';import { AddComponentMenu } from '@/components/AddComponentMenu';-import type { InspectorComponent, InspectorField, EntityId, NodeKind } from '@/types';+import type { InspectorComponent, InspectorField, InspectorFieldValue, EntityId, NodeKind, EnumOption } from '@/types';const AXES = ['x', 'y', 'z'];const fmt = (n: number) => String(Math.round(n * 1000) / 1000);+// Field-value equality for the "modified" (override) mark. Vectors compare+// element-wise; numbers tolerate float drift so a no-op edit doesn't read as one.+function fieldEqual(a: InspectorFieldValue, b: InspectorFieldValue): boolean {+ if (Array.isArray(a) && Array.isArray(b))+ return a.length === b.length && a.every((n, i) => Math.abs(n - (b[i] as number)) < 1e-6);+ if (typeof a === 'number' && typeof b === 'number') return Math.abs(a - b) < 1e-6;+ return a === b;+}++/** Whether a field differs from its reset target (prefab base, else class default). */+function isModified(f: InspectorField): boolean {+ return f.defaultValue !== undefined && !fieldEqual(f.value, f.defaultValue);+}+// Component domain → header glyph, derived from the component name (the engine// exposes no category metadata). The icon hue is neutral by design — set in CSS.function componentIcon(name: string): LucideIcon {@@ -77,11 +92,18 @@ interface ControlGesture {onEnd?: () => void;}+interface ScrubOpts extends ControlGesture {+ /** Units per pixel of drag (default 0.1); Shift = ÷10, Alt = ×10. */+ step?: number;+ min?: number;+ max?: number;+}+// Drag-to-scrub. The affordance lives on the property LABEL (scalars) or the// colored axis TAB (vectors) — NOT the input — so the field stays a plain-// click-to-type box. Press + drag horizontally to nudge: Shift = fine (0.01/px),-// Alt = coarse (1/px), else 0.1/px; a press under the 3px threshold is ignored.-function useScrub(value: number, onCommit: (n: number) => void, onBegin?: () => void, onEnd?: () => void) {+// click-to-type box. Press + drag horizontally to nudge; a press under the 3px+// threshold is ignored. The result clamps to [min,max] when the field is ranged.+function useScrub(value: number, onCommit: (n: number) => void, opts: ScrubOpts = {}) {const scrub = useRef<{ x: number; base: number; moved: boolean } | null>(null);return {onPointerDown: (e: React.PointerEvent) => {@@ -97,17 +119,21 @@ function useScrub(value: number, onCommit: (n: number) => void, onBegin?: () =>if (!s.moved) {if (Math.abs(dx) < 3) return;s.moved = true;- onBegin?.();+ opts.onBegin?.();}- const step = e.shiftKey ? 0.01 : e.altKey ? 1 : 0.1;- onCommit(Math.round((s.base + dx * step) * 1000) / 1000);+ const base = opts.step ?? 0.1;+ const step = e.shiftKey ? base / 10 : e.altKey ? base * 10 : base;+ let next = Math.round((s.base + dx * step) * 1000) / 1000;+ if (opts.min != null) next = Math.max(opts.min, next);+ if (opts.max != null) next = Math.min(opts.max, next);+ onCommit(next);},onPointerUp: (e: React.PointerEvent) => {const s = scrub.current;scrub.current = null;if (!s) return;e.currentTarget.releasePointerCapture?.(e.pointerId);- if (s.moved) onEnd?.();+ if (s.moved) opts.onEnd?.();},};}@@ -154,7 +180,7 @@ function VecField({onEnd,onCommit,}: ControlGesture & { axis: string; value: number; onCommit: (n: number) => void }) {- const scrub = useScrub(value, onCommit, onBegin, onEnd);+ const scrub = useScrub(value, onCommit, { onBegin, onEnd });const [editing, setEditing] = useState(false);const [text, setText] = useState('');return (@@ -210,6 +236,103 @@ function VecControl({);}+// A named-int dropdown (e.g. Camera projection, body type). The stored value is+// the option's int; an out-of-range value keeps a synthetic row so the select+// never silently misrepresents the model.+function EnumControl({+ value,+ options,+ onBegin,+ onEnd,+ onChange,+}: ControlGesture & { value: number; options: EnumOption[]; onChange: (v: number) => void }) {+ const known = options.some((o) => o.value === value);+ return (+ <span className="field">+ <select+ value={String(value)}+ onChange={(e) => {+ onBegin?.();+ onChange(Number(e.target.value));+ onEnd?.();+ }}+ >+ {!known && <option value={String(value)}>{`(${value})`}</option>}+ {options.map((o) => (+ <option key={o.value} value={String(o.value)}>+ {prettyLabel(o.label)}+ </option>+ ))}+ </select>+ </span>+ );+}++// A bounded number: a draggable track (the .slider widget) paired with a compact+// exact-entry box. Both snap to `step` and clamp to [min,max].+function SliderControl({+ value,+ min,+ max,+ step,+ unit,+ onBegin,+ onEnd,+ onChange,+}: ControlGesture & {+ value: number;+ min: number;+ max: number;+ step?: number;+ unit?: string;+ onChange: (n: number) => void;+}) {+ const track = useRef<HTMLDivElement>(null);+ const dragging = useRef(false);+ const span = max - min;+ const pct = span > 0 ? Math.max(0, Math.min(1, (value - min) / span)) : 0;+ const setFromX = (clientX: number) => {+ const el = track.current;+ if (!el) return;+ const r = el.getBoundingClientRect();+ const t = r.width ? Math.max(0, Math.min(1, (clientX - r.left) / r.width)) : 0;+ let v = min + t * span;+ if (step) v = Math.round(v / step) * step;+ onChange(Math.max(min, Math.min(max, Math.round(v * 1000) / 1000)));+ };+ return (+ <>+ <div+ ref={track}+ className="slider"+ onPointerDown={(e) => {+ if (e.button !== 0) return;+ e.preventDefault();+ dragging.current = true;+ e.currentTarget.setPointerCapture(e.pointerId);+ onBegin?.();+ setFromX(e.clientX);+ }}+ onPointerMove={(e) => {+ if (dragging.current) setFromX(e.clientX);+ }}+ onPointerUp={(e) => {+ if (!dragging.current) return;+ dragging.current = false;+ e.currentTarget.releasePointerCapture?.(e.pointerId);+ onEnd?.();+ }}+ >+ <span className="fill" style={{ width: `${pct * 100}%` }} />+ <span className="thumb" style={{ left: `${pct * 100}%` }} />+ </div>+ <span className="snum">+ <NumField value={value} suffix={unit} onBegin={onBegin} onEnd={onEnd} onCommit={onChange} />+ </span>+ </>+ );+}+function BoolControl({value,onBegin,@@ -361,19 +484,49 @@ function AssetControl({type FieldWrite = (key: string, type: InspectorField['type'], value: number | boolean | string | number[]) => void;function FieldRow({ entity, comp, field, write }: { entity: EntityId; comp: string; field: InspectorField; write?: FieldWrite }) {- const apply = (value: number | boolean | string | number[]) =>- write ? write(field.key, field.type, value) : SceneCommands.setField(entity, comp, field.key, field.type, value as never);+ const ranged = field.min != null || field.max != null;+ const clamp = (n: number) => {+ let v = n;+ if (field.min != null) v = Math.max(field.min, v);+ if (field.max != null) v = Math.min(field.max, v);+ return v;+ };+ const apply = (value: number | boolean | string | number[]) => {+ const v = ranged && typeof value === 'number' ? clamp(value) : value;+ return write ? write(field.key, field.type, v) : SceneCommands.setField(entity, comp, field.key, field.type, v as never);+ };const begin = () => (write ? undefined : SceneCommands.beginGesture(`Edit ${field.label}`));const end = () => (write ? undefined : SceneCommands.endGesture());- // Scalars (number/angle) scrub from the label; vectors from their axis tabs.- const isScalar = field.type === 'number' || field.type === 'angle';- const labelScrub = useScrub(isScalar ? (field.value as number) : 0, apply, begin, end);+ // Plain numbers + angles scrub from the label; vectors from their axis tabs; a+ // slider owns its own drag so its label stays inert.+ const isScalar = (field.type === 'number' && !field.slider) || field.type === 'angle';+ const labelScrub = useScrub(isScalar ? (field.value as number) : 0, apply, {+ onBegin: begin,+ onEnd: end,+ step: field.step,+ min: field.min,+ max: field.max,+ });let control;switch (field.type) {case 'number':- control = <NumField value={field.value as number} onBegin={begin} onEnd={end} onCommit={apply} />;+ control =+ field.slider && field.min != null && field.max != null ? (+ <SliderControl+ value={field.value as number}+ min={field.min}+ max={field.max}+ step={field.step}+ unit={field.unit}+ onBegin={begin}+ onEnd={end}+ onChange={apply}+ />+ ) : (+ <NumField value={field.value as number} suffix={field.unit} onBegin={begin} onEnd={end} onCommit={apply} />+ );break;case 'angle':control = <NumField value={field.value as number} suffix="°" onBegin={begin} onEnd={end} onCommit={apply} />;@@ -385,6 +538,17 @@ function FieldRow({ entity, comp, field, write }: { entity: EntityId; comp: stricase 'bool':control = <BoolControl value={field.value as boolean} onBegin={begin} onEnd={end} onChange={apply} />;break;+ case 'enum':+ control = (+ <EnumControl+ value={field.value as number}+ options={field.options ?? []}+ onBegin={begin}+ onEnd={end}+ onChange={apply}+ />+ );+ break;case 'color':control = <ColorControl value={field.value as string} onBegin={begin} onEnd={end} onChange={apply} />;break;@@ -403,13 +567,29 @@ function FieldRow({ entity, comp, field, write }: { entity: EntityId; comp: stricontrol = <StringControl value={String(field.value)} onBegin={begin} onEnd={end} onChange={apply} />;}+ const modified = isModified(field);+ const reset = () => {+ if (field.defaultValue === undefined) return;+ begin();+ apply(field.defaultValue);+ end();+ };+return (- <div className="prop">+ <div className={`prop${modified ? ' modified' : ''}`}><span className={`prop-label${isScalar ? ' scrub' : ''}`} {...(isScalar ? labelScrub : {})}>{field.label}</span><div className="prop-value">{control}</div>- <button type="button" className="prop-reset" tabIndex={-1} />+ <button+ type="button"+ className={`prop-reset${modified ? ' show' : ''}`}+ tabIndex={-1}+ title="Reset to default"+ onClick={modified ? reset : undefined}+ >+ <RotateCcw size={11} strokeWidth={2} />+ </button></div>);}@@ -430,15 +610,32 @@ function ComponentSection({write?: FieldWrite;}) {const Icon = componentIcon(comp.name);+ const overridden = comp.fields.some(isModified);+ const enable = comp.enable;+ const on = !enable || enable.value;+ // The header checkbox toggles the component's enable field (one undo step), or+ // is a static "always on" for components that can't be disabled (e.g. Transform).+ const toggleEnable = (e: React.MouseEvent) => {+ e.stopPropagation();+ if (!enable) return;+ const next = !enable.value;+ if (write) write(enable.key, 'bool', next);+ else SceneCommands.setField(entity, comp.name, enable.key, 'bool', next);+ };return (- <section className={`comp${collapsed ? '' : ' open'}`}>+ <section className={`comp${collapsed ? '' : ' open'}${overridden ? ' override' : ''}${enable && !on ? ' disabled' : ''}`}><header className="comp-head" onClick={onToggle}><span className="comp-arrow"><ChevronRight size={9} strokeWidth={3} /></span>- {/* Component enable — visual for now; per-component enable isn't yet exposed. */}- <span className="comp-chk on" onClick={(e) => e.stopPropagation()}>- <Check size={9} strokeWidth={3.2} />+ <span+ className={`comp-chk${on ? ' on' : ''}`}+ role={enable ? 'checkbox' : undefined}+ aria-checked={enable ? enable.value : undefined}+ title={enable ? (enable.value ? 'Disable component' : 'Enable component') : undefined}+ onClick={enable ? toggleEnable : (e) => e.stopPropagation()}+ >+ {on && <Check size={9} strokeWidth={3.2} />}</span><span className="comp-icon"><Icon size={13} strokeWidth={1.9} />diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.tsindex f274699c7..f689f25cd 100644--- a/desktop/src/project/ProjectStore.ts+++ b/desktop/src/project/ProjectStore.ts@@ -9,6 +9,7 @@ import { Reconciler } from '@/engine/Reconciler';import { EditorHistory } from '@/engine/EditorHistory';import { expandScenePrefabs, collapseScenePrefabs } from '@/engine/PrefabInstance';import { SceneCommands } from '@/engine/SceneCommands';+import { setPrefabBaseResolver } from '@/engine/SceneQuery';import { setUserSchemas, userSchema, type UserComponentSchema } from '@/engine/schema';import { useSelection } from '@/store/selectionStore';import { Toasts } from '@/store/Toasts';@@ -80,6 +81,17 @@ class ProjectStoreImpl {/** The latest scene preload result; the Reconciler resolver reads handles from* it for entities recreated incrementally (duplicate / undo / play-stop). */private lastAssetResult: PreloadResult | null = null;+ constructor() {+ // The inspector's override-aware reset reads prefab base data from the loaded+ // `.esprefab` cache this store owns. Non-variant prefabs resolve their base+ // directly from the asset entities; a variant/nested base degrades to the+ // component default (the entry simply isn't found here).+ setPrefabBaseResolver((ref, prefabId) => {+ const pe = this.prefabCache.get(ref)?.entities.find((e) => e.prefabEntityId === prefabId);+ return pe ? pe.components : null;+ });+ }+/** Read accessor so existing `this.state` reads stay unchanged after the move. */private get state(): ProjectState | null {return this.store.getState().project;diff --git a/desktop/src/theme/inspector.css b/desktop/src/theme/inspector.cssindex c5d7005fc..b934a669a 100644--- a/desktop/src/theme/inspector.css+++ b/desktop/src/theme/inspector.css@@ -76,6 +76,9 @@.comp-icon { color: var(--text-dim); display: grid; place-items: center; }.comp-name { font-weight: 600; font-size: var(--fs-sm); color: var(--text); flex: 1; }.comp.override .comp-name::after { content: ''; display: inline-block; width: 5px; height: 5px; background: var(--warn); border-radius: 50%; margin-left: 7px; vertical-align: middle; }+/* a disabled component dims its icon/name + body; the enable checkbox stays full */+.comp.disabled .comp-icon, .comp.disabled .comp-name { opacity: .45; }+.comp.disabled .comp-body { opacity: .5; }.comp-badge { font-size: var(--fs-2xs); color: var(--text-mute); font-family: var(--mono); }.comp-menu { width: 22px; height: 22px; display: grid; place-items: center; color: var(--text-mute); border-radius: var(--r-sm); opacity: 0; transition: opacity var(--t-fast), color var(--t-fast), background var(--t-fast); }.comp-head:hover .comp-menu { opacity: 1; }@@ -112,9 +115,11 @@.vfield input { width: 100%; min-width: 0; background: none; border: none; outline: none; padding: 0 5px; font-size: var(--fs-xs); color: var(--text); font-family: var(--mono); }.sw { width: 22px; height: 18px; border-radius: var(--r-xs); border: 1px solid var(--border-line); flex-shrink: 0; cursor: pointer; }-.slider { flex: 1; height: 6px; background: var(--inset); border-radius: var(--r-pill); position: relative; cursor: pointer; }+.slider { flex: 1; height: 6px; background: var(--inset); border-radius: var(--r-pill); position: relative; cursor: ew-resize; touch-action: none; }.slider .fill { position: absolute; left: 0; top: 0; bottom: 0; background: var(--acc); border-radius: var(--r-pill); }.slider .thumb { position: absolute; top: 50%; width: 11px; height: 11px; border-radius: 50%; background: var(--text); transform: translate(-50%,-50%); box-shadow: var(--shadow-1); }+/* compact exact-entry box paired with a slider track */+.snum { width: 54px; flex-shrink: 0; display: flex; }.toggle { width: 30px; height: 17px; border-radius: var(--r-pill); background: var(--srf-5); position: relative; cursor: pointer; flex-shrink: 0; transition: background var(--t-fast); }.toggle::after { content: ''; position: absolute; top: 2px; left: 2px; width: 13px; height: 13px; border-radius: 50%; background: var(--text-dim); transition: left var(--t-fast) var(--e-out), background var(--t-fast); }.toggle.on { background: var(--acc); }diff --git a/desktop/src/types.ts b/desktop/src/types.tsindex 3bb92ca3b..798a4c489 100644--- a/desktop/src/types.ts+++ b/desktop/src/types.ts@@ -35,8 +35,15 @@ export type InspectorFieldType =| 'vec3'| 'angle' // 2D rotation: a quaternion shown/edited as Z degrees| 'color'+ | 'enum' // an int field with named options, shown as a dropdown| 'asset'; // a texture/material/font/... ref (@uuid: string, or 0 for none)+/** A dropdown option for an `enum` field: the label shown, the int stored. */+export interface EnumOption {+ label: string;+ value: number;+}+export type InspectorFieldValue =| number| boolean@@ -52,6 +59,24 @@ export interface InspectorField {value: InspectorFieldValue;/** For `type: 'asset'` — the asset kind (texture/material/font/...). */assetType?: string;+ /** For `type: 'enum'` — the selectable options (label + stored int). */+ options?: EnumOption[];+ /**+ * The value this field resets to — the prefab-instance base if the entity is a+ * prefab instance, else the component's registered default. Absent when no base+ * is known. `value !== defaultValue` ⇒ the field is "modified" (override).+ */+ defaultValue?: InspectorFieldValue;+ // — Numeric presentation (number fields only) —+ /** Hard range; clamps both typed entry and drag-scrub. */+ min?: number;+ max?: number;+ /** Scrub/step granularity (defaults to 0.1 per pixel). */+ step?: number;+ /** Render as a slider; set only when `min`/`max` are both finite. */+ slider?: boolean;+ /** Unit shown after the resting value (e.g. '°', 'px'). */+ unit?: string;}export interface InspectorComponent {@@ -59,6 +84,12 @@ export interface InspectorComponent {name: string;label: string;fields: InspectorField[];+ /**+ * The component's enable toggle — its `enabled`/`isActive`/`visible` field ++ * current value — surfaced in the header (and hidden from `fields`). Absent for+ * components that can't be disabled (e.g. Transform).+ */+ enable?: { key: string; value: boolean };}export type AssetType =diff --git a/desktop/tests/inspector-model.test.ts b/desktop/tests/inspector-model.test.tsindex 798de47d5..935388a33 100644--- a/desktop/tests/inspector-model.test.ts+++ b/desktop/tests/inspector-model.test.ts@@ -11,10 +11,20 @@* Runs in an isolated EditorSession (P2) — fresh model/query/commands/history,* no shared-singleton state to clear.*/-import { describe, it, expect, beforeEach } from 'vitest';+import { describe, it, expect, beforeEach, afterEach } from 'vitest';import type { SceneData } from 'esengine';import { EditorSession } from '@/engine/EditorSession';-import { setUserSchemas } from '@/engine/schema';+import { setUserSchemas, enumFieldOptions } from '@/engine/schema';+import { setPrefabBaseResolver } from '@/engine/SceneQuery';++/** A one-entity scene carrying a Camera with the given component-data overrides. */+function sceneWithCamera(data: Record<string, unknown>): SceneData {+ return {+ version: '1.0',+ name: 'cam',+ entities: [{ id: 1, name: 'Cam', parent: null, children: [], components: [{ type: 'Camera', data }] }],+ } as unknown as SceneData;+}const WAVE_SCHEMA = {name: 'WaveMotion',@@ -94,6 +104,150 @@ describe('Unknown-component inspector (schemas.json consumer)', () => {expect(wave!.fields.find((f) => f.key === 'amplitude')!.value).toBe(5);});+ it('surfaces a builtin int field as an enum with engine-derived options', () => {+ const opts = enumFieldOptions('Camera', 'projectionType');+ expect(opts).not.toBeNull();+ // Labels come straight from the engine's ProjectionType const (no hand-mirror).+ expect(opts!.map((o) => o.label)).toEqual(expect.arrayContaining(['Perspective', 'Orthographic']));+ expect(typeof opts!.find((o) => o.label === 'Orthographic')!.value).toBe('number');+ expect(enumFieldOptions('Camera', 'orthoSize')).toBeNull(); // a plain number, not an enum+ });++ it("builds an enum field as type 'enum' carrying its options + stored int", () => {+ const fresh = EditorSession.create();+ fresh.model.adopt(+ {+ version: '1.0',+ name: 'cam',+ entities: [+ {+ id: 1,+ name: 'Cam',+ parent: null,+ children: [],+ components: [{ type: 'Camera', data: { projectionType: 1, orthoSize: 540 } }],+ },+ ],+ } as unknown as SceneData,+ new Map([[1, 1]]),+ );+ const proj = fresh.query.readInspector(1).find((c) => c.name === 'Camera')!.fields.find((f) => f.key === 'projectionType')!;+ expect(proj.type).toBe('enum');+ expect(proj.value).toBe(1);+ expect(proj.options!.length).toBeGreaterThanOrEqual(2);+ });++ it('lets a user component declare an enum field via its schema', () => {+ setUserSchemas([+ {+ name: 'Mover',+ isTag: false,+ default: { mode: 0 },+ colorKeys: [],+ fields: { mode: { enum: [{ label: 'Walk', value: 0 }, { label: 'Run', value: 1 }] } },+ },+ ]);+ const fresh = EditorSession.create();+ fresh.model.adopt(+ {+ version: '1.0',+ name: 'm',+ entities: [+ { id: 1, name: 'M', parent: null, children: [], components: [{ type: 'Mover', data: { mode: 1 } }] },+ ],+ } as unknown as SceneData,+ new Map([[1, 1]]),+ );+ const mode = fresh.query.readInspector(1).find((c) => c.name === 'Mover')!.fields.find((f) => f.key === 'mode')!;+ expect(mode.type).toBe('enum');+ expect(mode.options!.map((o) => o.label)).toEqual(['Walk', 'Run']);+ expect(mode.value).toBe(1);+ });++ it('attaches numeric range + unit metadata to a builtin number field', () => {+ const fresh = EditorSession.create();+ fresh.model.adopt(+ {+ version: '1.0',+ name: 'cam',+ entities: [+ {+ id: 1,+ name: 'Cam',+ parent: null,+ children: [],+ components: [{ type: 'Camera', data: { fov: 60 } }],+ },+ ],+ } as unknown as SceneData,+ new Map([[1, 1]]),+ );+ const cam = fresh.query.readInspector(1).find((c) => c.name === 'Camera')!;+ const fov = cam.fields.find((f) => f.key === 'fov')!;+ expect(fov.type).toBe('number');+ expect(fov.min).toBe(1);+ expect(fov.max).toBe(179);+ expect(fov.unit).toBe('°');+ expect(fov.slider).toBeFalsy(); // ranged but not a slider+ });++ it('marks a 0..1 field as a slider; an unannotated number stays plain', () => {+ const fresh = EditorSession.create();+ fresh.model.adopt(+ {+ version: '1.0',+ name: 't',+ entities: [+ {+ id: 1,+ name: 'T',+ parent: null,+ children: [],+ components: [{ type: 'TilemapLayer', data: { opacity: 0.5, renderLayer: 3 } }],+ },+ ],+ } as unknown as SceneData,+ new Map([[1, 1]]),+ );+ const tm = fresh.query.readInspector(1).find((c) => c.name === 'TilemapLayer')!;+ const opacity = tm.fields.find((f) => f.key === 'opacity')!;+ expect(opacity.slider).toBe(true);+ expect([opacity.min, opacity.max]).toEqual([0, 1]);+ // renderLayer is an integer-stepped number, not a slider (no finite range).+ const layer = tm.fields.find((f) => f.key === 'renderLayer')!;+ expect(layer.type).toBe('number');+ expect(layer.step).toBe(1);+ expect(layer.slider).toBeFalsy();+ });++ it('lets a user component declare numeric range/unit via its schema', () => {+ setUserSchemas([+ {+ name: 'Spin',+ isTag: false,+ default: { speed: 0, ratio: 0.5 },+ colorKeys: [],+ fields: { speed: { unit: '°/s', min: 0 }, ratio: { min: 0, max: 1, slider: true } },+ },+ ]);+ const fresh = EditorSession.create();+ fresh.model.adopt(+ {+ version: '1.0',+ name: 's',+ entities: [+ { id: 1, name: 'S', parent: null, children: [], components: [{ type: 'Spin', data: { speed: 90, ratio: 0.25 } }] },+ ],+ } as unknown as SceneData,+ new Map([[1, 1]]),+ );+ const spin = fresh.query.readInspector(1).find((c) => c.name === 'Spin')!;+ expect(spin.fields.find((f) => f.key === 'speed')!.unit).toBe('°/s');+ const ratio = spin.fields.find((f) => f.key === 'ratio')!;+ expect(ratio.slider).toBe(true);+ expect([ratio.min, ratio.max]).toEqual([0, 1]);+ });+it('renders a component asset-ref field as an asset control, not a raw uuid', () => {const ref = '@uuid:44444444-4444-4444-8444-444444444444';const fresh = EditorSession.create();@@ -121,3 +275,113 @@ describe('Unknown-component inspector (schemas.json consumer)', () => {expect(tex!.value).toBe(ref);});});++describe('Per-component enable (D4)', () => {+ function sceneWith(type: string, data: Record<string, unknown>): SceneData {+ return {+ version: '1.0',+ name: 's',+ entities: [{ id: 1, name: 'E', parent: null, children: [], components: [{ type, data }] }],+ } as unknown as SceneData;+ }+ const enableOf = (S: EditorSession, type: string) =>+ S.query.readInspector(1).find((c) => c.name === type)!;++ it("surfaces a component's enable field + hides it from the body", () => {+ const S = EditorSession.create();+ S.model.adopt(sceneWith('Sprite', { enabled: true, layer: 0 }), new Map([[1, 1]]));+ const sprite = enableOf(S, 'Sprite');+ expect(sprite.enable).toEqual({ key: 'enabled', value: true });+ expect(sprite.fields.some((f) => f.key === 'enabled')).toBe(false); // promoted to header+ });++ it('resolves the differently-named enable field per component', () => {+ const cam = EditorSession.create();+ cam.model.adopt(sceneWith('Camera', { isActive: true }), new Map([[1, 1]]));+ expect(enableOf(cam, 'Camera').enable).toEqual({ key: 'isActive', value: true });++ const tm = EditorSession.create();+ tm.model.adopt(sceneWith('TilemapLayer', { visible: false }), new Map([[1, 1]]));+ expect(enableOf(tm, 'TilemapLayer').enable).toEqual({ key: 'visible', value: false });+ });++ it('reflects a toggle of the enable field', () => {+ const S = EditorSession.create();+ S.model.adopt(sceneWith('Sprite', { enabled: true, layer: 0 }), new Map([[1, 1]]));+ S.commands.setField(1, 'Sprite', 'enabled', 'bool', false);+ expect(enableOf(S, 'Sprite').enable).toEqual({ key: 'enabled', value: false });+ });++ it('has no enable toggle for a component that cannot be disabled', () => {+ const S = EditorSession.create();+ S.model.adopt(+ {+ version: '1.0',+ name: 's',+ entities: [+ {+ id: 1,+ name: 'E',+ parent: null,+ children: [],+ components: [+ { type: 'Transform', data: { position: { x: 0, y: 0, z: 0 }, rotation: { w: 1, x: 0, y: 0, z: 0 }, scale: { x: 1, y: 1, z: 1 } } },+ ],+ },+ ],+ } as unknown as SceneData,+ new Map([[1, 1]]),+ );+ expect(enableOf(S, 'Transform').enable).toBeUndefined();+ });+});++describe('Reset-to-default + override base (D3)', () => {+ afterEach(() => setPrefabBaseResolver(null));++ it('carries the component default as each field reset target', () => {+ const S = EditorSession.create();+ S.model.adopt(sceneWithCamera({ orthoSize: 800 }), new Map([[1, 1]]));+ const cam = S.query.readInspector(1).find((c) => c.name === 'Camera')!;+ const orthoSize = cam.fields.find((f) => f.key === 'orthoSize')!;+ expect(orthoSize.value).toBe(800);+ expect(orthoSize.defaultValue).toBe(540); // an override: value ≠ default+ // A field left untouched reads value === default (not modified).+ const fov = cam.fields.find((f) => f.key === 'fov')!;+ expect(fov.value).toBe(fov.defaultValue);+ });++ it('resetting a field to its defaultValue restores the default', () => {+ const S = EditorSession.create();+ S.model.adopt(sceneWithCamera({ orthoSize: 800 }), new Map([[1, 1]]));+ const before = S.query.readInspector(1).find((c) => c.name === 'Camera')!.fields.find((f) => f.key === 'orthoSize')!;+ S.commands.setField(1, 'Camera', 'orthoSize', 'number', before.defaultValue as number);+ const after = S.query.readInspector(1).find((c) => c.name === 'Camera')!.fields.find((f) => f.key === 'orthoSize')!;+ expect(after.value).toBe(540);+ expect(after.value).toBe(after.defaultValue); // no longer modified+ });++ it('a prefab instance resets to the prefab base, not the class default', () => {+ setPrefabBaseResolver((ref, prefabId) =>+ ref === '@uuid:p' && prefabId === 'root' ? [{ type: 'Camera', data: { orthoSize: 300 } }] : null,+ );+ const S = EditorSession.create();+ S.model.adopt(sceneWithCamera({ orthoSize: 800 }), new Map([[1, 1]]));+ S.model.setPrefabTag(1, { instanceRoot: 1, prefabId: 'root', prefab: '@uuid:p' });+ const cam = S.query.readInspector(1).find((c) => c.name === 'Camera')!;+ const orthoSize = cam.fields.find((f) => f.key === 'orthoSize')!;+ expect(orthoSize.value).toBe(800);+ expect(orthoSize.defaultValue).toBe(300); // prefab base wins over the 540 class default+ // A field the prefab base omits falls back to the class default.+ const fov = cam.fields.find((f) => f.key === 'fov')!;+ expect(fov.defaultValue).toBe(60);+ });++ it('without a registered resolver, a tagged instance just uses the class default', () => {+ const S = EditorSession.create();+ S.model.adopt(sceneWithCamera({ orthoSize: 800 }), new Map([[1, 1]]));+ S.model.setPrefabTag(1, { instanceRoot: 1, prefabId: 'root', prefab: '@uuid:p' });+ const orthoSize = S.query.readInspector(1).find((c) => c.name === 'Camera')!.fields.find((f) => f.key === 'orthoSize')!;+ expect(orthoSize.defaultValue).toBe(540);+ });+});