Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(editor): entity-reference fields become a scene-entity picker (ExposeRef foundation) (P2 UX)

yhhcf82a7688042
diff --git a/desktop/src/engine/EditorControlSurface.ts b/desktop/src/engine/EditorControlSurface.ts
index 2b6fe44eb..e415e5c27 100644
--- a/desktop/src/engine/EditorControlSurface.ts
+++ b/desktop/src/engine/EditorControlSurface.ts
@@ -88,7 +88,9 @@ export function coerceFieldValue(
switch (declared) {
case 'number':
case 'enum':
- case 'flags': {
+ case 'flags':
+ case 'entity': {
+ // 'entity' is a source-id reference to another entity — a plain number.
const n = Number(value);
return Number.isFinite(n) ? n : fail('a number');
}
diff --git a/desktop/src/engine/schema.ts b/desktop/src/engine/schema.ts
index 5fef3cb49..bffb153a0 100644
--- a/desktop/src/engine/schema.ts
+++ b/desktop/src/engine/schema.ts
@@ -508,6 +508,10 @@ function fieldFor(
// flag a perfectly-loaded asset red. 0/other stays the empty sentinel.
const v = typeof value === 'string' ? value : typeof value === 'number' ? value : 0;
field = { key, label: prettyLabel(key), type: 'asset', value: v, assetType: at };
+ } else if (componentEntityFields(componentByName(compType)).includes(key)) {
+ // An entity-reference field (e.g. a joint's connectedBody): a scene-entity
+ // picker, not a raw number. The value is a source id (0 / INVALID = unset).
+ field = { key, label: prettyLabel(key), type: 'entity', value: typeof value === 'number' ? value : 0 };
} else if (meta?.gradient) {
const g = value && typeof value === 'object' && Array.isArray((value as GradientValue).stops) ? (value as GradientValue) : { stops: [] };
field = { key, label: prettyLabel(key), type: 'gradient', value: g };
diff --git a/desktop/src/i18n/messages/details.ts b/desktop/src/i18n/messages/details.ts
index ab2bbb4af..5068aaffd 100644
--- a/desktop/src/i18n/messages/details.ts
+++ b/desktop/src/i18n/messages/details.ts
@@ -200,6 +200,7 @@ export const detailsMessages = defineMessages({
'det.editing': { en: 'Editing', zh: '编辑中' },
'det.editingShared': { en: '{count} entities · shared components', zh: '{count} 个实体 · 共同组件' },
'det.id': { en: 'ID', zh: 'ID' },
+ 'det.entityNone': { en: 'None', zh: '无' },
'det.prefabEdit': { en: 'Edit', zh: '编辑' },
'det.prefabEditTip': { en: 'Open this prefab in Prefab Mode', zh: '在预制体模式中打开此预制体' },
'det.staleOverrides': {
diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsx
index 083628d12..0f2ccf111 100644
--- a/desktop/src/panels/Details.tsx
+++ b/desktop/src/panels/Details.tsx
@@ -55,7 +55,7 @@ import { InspectorClipboard } from '@/engine/inspectorClipboard';
import { SceneCommands, toModelValue } from '@/engine/SceneCommands';
import { ENTITY_SOURCES, createFromSource } from '@/engine/entitySources';
import { PlayInspect } from '@/engine/PlayInspect';
-import { DimensionUnit, AnchorAxis, detectAnchorAxes, UIPositionType, parseLocaleTable, EasingType } from 'esengine';
+import { DimensionUnit, AnchorAxis, detectAnchorAxes, UIPositionType, parseLocaleTable, EasingType, INVALID_ENTITY } from 'esengine';
import type { SceneData, InputMapAsset, ActionType, Binding, LocaleTableAsset, PluralCategory, GearValue, GearTween } from 'esengine';
import { modelAddableComponentEntries, subscribeSchemas, getSchemaRevision, prettyLabel, hexToRgba, dynamicEnumOptions, boxGroupsFor, isRequiredEmpty, type BoxGroupDef } from '@/engine/schema';
import * as imap from '@/project/inputMapDoc';
@@ -269,6 +269,82 @@ export function EnumControl({
);
}
+/** True when an entity-ref source id means "unset" (nothing bound). Both engine
+ * invalid sentinels count; INVALID_ENTITY is 0, which is also why source id 0 is
+ * never offered as a target (a ref to it is indistinguishable from "unset"). */
+const isUnsetEntity = (v: number): boolean => v === INVALID_ENTITY || v === 0xffffffff;
+
+// A reference to ANOTHER scene entity (e.g. a joint's connectedBody): a picker of
+// the scene's entities by name, storing the target's SOURCE id. Was a raw number
+// input before. "None" writes the unset sentinel; the current target shows by name.
+export function EntityControl({
+ value,
+ mixed,
+ onBegin,
+ onEnd,
+ onChange,
+}: ControlGesture & { value: number; mixed?: boolean; onChange: (v: number) => void }) {
+ const pop = usePopover();
+ const trigger = useRef<HTMLButtonElement>(null);
+ const [q, setQ] = useState('');
+ // The scene's entities (source id + name) — rebuilt each open so it's current.
+ // Source id 0 (== INVALID_ENTITY) is excluded: a ref to it can't be told apart
+ // from "unset", so it isn't a bindable target.
+ const options = useMemo(
+ () => (SceneModel.current?.entities ?? [])
+ .filter((e) => e.id !== INVALID_ENTITY)
+ .map((e) => ({ id: e.id, name: e.name || `#${e.id}` })),
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [pop.isOpen],
+ );
+ const cur = options.find((o) => o.id === value);
+ const label = mixed ? '—' : isUnsetEntity(value) ? t('det.entityNone') : cur?.name ?? `#${value}`;
+ const ql = q.trim().toLowerCase();
+ const filtered = ql ? options.filter((o) => o.name.toLowerCase().includes(ql)) : options;
+ const close = () => {
+ pop.close();
+ onEnd?.();
+ };
+ const toggle = () => {
+ if (pop.isOpen) return close();
+ setQ('');
+ onBegin?.();
+ pop.open(trigger.current);
+ };
+ const pick = (id: number) => {
+ onChange(id);
+ close();
+ };
+ return (
+ <span className="field dropdown">
+ <button ref={trigger} type="button" className="dd-trigger" onMouseDown={(e) => e.stopPropagation()} onClick={toggle}>
+ <span className={`dd-val${mixed || isUnsetEntity(value) ? ' dd-none' : ''}`}>{mixed ? '—' : label}</span>
+ <ChevronDown size={12} strokeWidth={2} />
+ </button>
+ {pop.anchor && (
+ <Popover anchor={pop.anchor} width={Math.max(pop.anchor.width, 160)} onClose={close}>
+ {options.length > 8 && (
+ <SearchField flush className="dd-search" iconSize={12} autoFocus placeholder={t('ui.search')} value={q} onChange={setQ} />
+ )}
+ <div className="dd-list">
+ <button type="button" className={`dd-opt${isUnsetEntity(value) && !mixed ? ' on' : ''}`} onClick={() => pick(INVALID_ENTITY)}>
+ <span className="dd-opt-label dd-none">{t('det.entityNone')}</span>
+ {isUnsetEntity(value) && !mixed && <Check size={12} strokeWidth={2.4} />}
+ </button>
+ {filtered.map((o) => (
+ <button key={o.id} type="button" className={`dd-opt${o.id === value && !mixed ? ' on' : ''}`} onClick={() => pick(o.id)}>
+ <span className="dd-opt-label">{o.name}</span>
+ {o.id === value && !mixed && <Check size={12} strokeWidth={2.4} />}
+ </button>
+ ))}
+ {filtered.length === 0 && <div className="empty-line empty-line--sm">{t('det.noMatch')}</div>}
+ </div>
+ </Popover>
+ )}
+ </span>
+ );
+}
+
// An int bitmask, edited as a multi-select of its bits (e.g. Camera clear flags).
// The popover stays open across toggles; the whole burst is one undo step (the
// field's gesture coalesces). The summary reads "Color | Depth" or "None".
@@ -1147,6 +1223,9 @@ function FieldRow({ entities, comp, field, write }: { entities: EntityId[]; comp
/>
);
break;
+ case 'entity':
+ control = <EntityControl value={field.value as number} mixed={mixed} onBegin={begin} onEnd={end} onChange={apply} />;
+ break;
case 'color':
control = <ColorControl value={field.value as string} onBegin={begin} onEnd={end} onChange={apply} />;
break;
diff --git a/desktop/src/types.ts b/desktop/src/types.ts
index 43090b2ad..c15c97228 100644
--- a/desktop/src/types.ts
+++ b/desktop/src/types.ts
@@ -42,7 +42,8 @@ export type InspectorFieldType =
| 'gradient' // a color-over-life gradient ({ stops: [...] })
| 'curve' // a scalar over-life curve ({ keys: [...] })
| 'dimension' // a CSS-style length ({ value, unit }) — UINode box/inset fields
- | 'asset'; // a texture/material/font/... ref (@uuid: string, or 0 for none)
+ | 'asset' // a texture/material/font/... ref (@uuid: string, or 0 for none)
+ | 'entity'; // a reference to another scene entity (source id, or 0/INVALID for none)
/** A dropdown option for an `enum` field: the label shown, the int stored. */
export interface EnumOption {