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): a dropdown's options can depend on what the entity references
esenginec4f82e2ddc5b
diff --git a/desktop/src/engine/schema.ts b/desktop/src/engine/schema.tsindex 3ce1424e1..86d76caaa 100644--- a/desktop/src/engine/schema.ts+++ b/desktop/src/engine/schema.ts@@ -508,14 +508,22 @@ export function setBitmaskSource(name: string, provider: (() => EnumOption[]) |// Editor-registered providers of dynamic enum options (e.g. project sorting// layers). A field with `enumSource` becomes a dropdown when its source yields// options, else a plain number — so free-int editing survives an empty set.-const enumSources = new Map<string, () => EnumOption[]>();+/**+ * A provider is handed the component's own values, because some option sets are+ * not global. Sorting layers are a project fact and ignore it; which armatures+ * exist depends on which file THIS entity's `skeletonPath` points at, and two+ * entities of one component type legitimately answer differently.+ */+export type EnumOptionProvider = (data: Readonly<Record<string, unknown>>) => EnumOption[];++const enumSources = new Map<string, EnumOptionProvider>();/** Register (or clear) a named source of dynamic enum options. */-export function setEnumSource(name: string, provider: (() => EnumOption[]) | null): void {+export function setEnumSource(name: string, provider: EnumOptionProvider | null): void {if (provider) enumSources.set(name, provider);else enumSources.delete(name);}-function enumSourceOptions(name: string): EnumOption[] {- return enumSources.get(name)?.() ?? [];+function enumSourceOptions(name: string, data: Readonly<Record<string, unknown>>): EnumOption[] {+ return enumSources.get(name)?.(data) ?? [];}/** The bit options for a bitmask field: its source's labels, else `Layer N`. */function bitmaskOptions(meta: { bits?: number; source?: string }): EnumOption[] {@@ -534,6 +542,7 @@ function fieldFor(key: string,value: unknown,isColor: boolean,+ data: Readonly<Record<string, unknown>> = {},): InspectorField | null {const meta = fieldMetaFor(compType, key);const at = assetFieldType(compType, key) ?? spineSlotType(compType, key);@@ -567,8 +576,13 @@ function fieldFor(field = { key, label: prettyLabel(key), type: 'flags', value: Number(value) || 0, options: meta.flags.map((o) => ({ ...o })) };} else if (meta?.enum && meta.enum.length) {field = { key, label: prettyLabel(key), type: 'enum', value: Number(value) || 0, options: meta.enum.map((o) => ({ ...o })) };- } else if (meta?.enumSource && enumSourceOptions(meta.enumSource).length) {- field = { key, label: prettyLabel(key), type: 'enum', value: Number(value) || 0, options: enumSourceOptions(meta.enumSource) };+ } else if (meta?.enumSource && enumSourceOptions(meta.enumSource, data).length) {+ const options = enumSourceOptions(meta.enumSource, data);+ // A string-valued source names things; coercing through Number would turn+ // every option into NaN and the field into a broken 0.+ const stringly = typeof options[0].value === 'string';+ const v = stringly ? (typeof value === 'string' ? value : '') : (Number(value) || 0);+ field = { key, label: prettyLabel(key), type: 'enum', value: v, options };} else {field = inferField(key, value, isColor);if (field && field.type === 'number' && meta) {@@ -674,12 +688,12 @@ export function inspectorFields(if (DERIVED_FIELDS.has(key)) continue;if (isConditionallyHidden(compType, key, eff)) continue;const value = key in data ? data[key] : defaults?.[key];- const f = fieldFor(compType, key, value, colorKeys.has(key));+ const f = fieldFor(compType, key, value, colorKeys.has(key), eff);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));+ const bf = fieldFor(compType, key, baseRaw, colorKeys.has(key), eff);if (bf) f.defaultValue = bf.value;}fields.push(f);diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsxindex 4336f13c3..0c9f737c2 100644--- a/desktop/src/panels/Details.tsx+++ b/desktop/src/panels/Details.tsx@@ -318,7 +318,7 @@ export function EnumControl({onBegin,onEnd,onChange,-}: ControlGesture & { value: number; options: EnumOption[]; mixed?: boolean; onChange: (v: number) => void }) {+}: ControlGesture & { value: string | number; options: EnumOption[]; mixed?: boolean; onChange: (v: string | number) => void }) {const pop = usePopover();const trigger = useRef<HTMLButtonElement>(null);const [q, setQ] = useState('');@@ -479,7 +479,11 @@ function FlagsControl({}: ControlGesture & { value: number; options: EnumOption[]; mixed?: boolean; onChange: (v: number) => void }) {const pop = usePopover();const trigger = useRef<HTMLButtonElement>(null);- const bits = options.filter((o) => o.value !== 0);+ // A flag IS a bit. These options come from a bitmask or a flag list, both of+ // which are numeric by construction — a named option could never be OR'd.+ const bits = options+ .map((o) => ({ ...o, value: Number(o.value) }))+ .filter((o) => o.value !== 0);const all = bits.reduce((m, o) => m | o.value, 0);const active = bits.filter((o) => (value & o.value) === o.value);const summary = mixeddiff --git a/desktop/src/types.ts b/desktop/src/types.tsindex 792fe8db5..4c310cf01 100644--- a/desktop/src/types.ts+++ b/desktop/src/types.ts@@ -51,7 +51,13 @@ export type InspectorFieldType =/** A dropdown option for an `enum` field: the label shown, the int stored. */export interface EnumOption {label: string;- value: number;+ /**+ * Strings as well as numbers: a C++ enum's options are ordinals, but a name+ * chosen from a referenced asset — which animation, which armature — IS the+ * value, and mapping it through an index would break the moment the asset is+ * re-exported with its animations in another order.+ */+ value: string | number;}/** One stop of a `gradient` field: a 0..1 position + an RGBA color (0..1 channels). */diff --git a/desktop/tests/enum-source-context.test.ts b/desktop/tests/enum-source-context.test.tsnew file mode 100644index 000000000..abc2852e2--- /dev/null+++ b/desktop/tests/enum-source-context.test.ts@@ -0,0 +1,78 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+//+// Dynamic dropdown options used to be a project-wide fact (sorting layers) read+// through a source that was handed nothing. Some option sets are not: which+// armatures exist depends on which file THIS entity points at, so two entities of+// one component type legitimately answer differently. These cover the two things+// that had to change for that — the provider seeing the component, and an option+// being allowed to BE a name rather than an index into one.+import { describe, it, expect, afterEach } from 'vitest';+import { setEnumSource, inspectorFields } from '@/engine/schema';++const FIELD = 'layer';++afterEach(() => {+ setEnumSource('sortingLayers', null);+});++const fieldsOf = (comp: string, data: Record<string, unknown>) => inspectorFields(comp, data);++describe('enum sources', () => {+ it('hands the provider the component`s own values', () => {+ let seen: Record<string, unknown> | null = null;+ setEnumSource('sortingLayers', (data) => {+ seen = data as Record<string, unknown>;+ return [{ label: 'Default', value: 0 }];+ });++ fieldsOf('Sprite', { layer: 0, texture: 0 });+ expect(seen).not.toBeNull();+ expect(seen!.texture).toBe(0);+ });++ it('lets two entities of one component type see different options', () => {+ // The whole reason the provider needed context: a global source cannot+ // express "depends on what this one references".+ setEnumSource('sortingLayers', (data) =>+ data.texture === 1+ ? [{ label: 'A', value: 0 }, { label: 'B', value: 1 }]+ : [{ label: 'Only', value: 0 }]);++ const one = fieldsOf('Sprite', { layer: 0, texture: 1 }).find((f) => f.key === FIELD);+ const two = fieldsOf('Sprite', { layer: 0, texture: 2 }).find((f) => f.key === FIELD);+ expect(one?.options?.length).toBe(2);+ expect(two?.options?.length).toBe(1);+ });++ it('keeps a name as the value instead of an index into a list', () => {+ // An ordinal would silently point at a different animation the next time+ // the asset is exported with its list in another order.+ setEnumSource('sortingLayers', () => [+ { label: 'walk', value: 'walk' },+ { label: 'idle', value: 'idle' },+ ]);++ const f = fieldsOf('Sprite', { layer: 'idle' }).find((x) => x.key === FIELD);+ expect(f?.type).toBe('enum');+ expect(f?.value).toBe('idle');+ });++ it('leaves a numeric source resolving exactly as before', () => {+ setEnumSource('sortingLayers', () => [+ { label: 'Default', value: 0 },+ { label: 'Foreground', value: 3 },+ ]);++ const f = fieldsOf('Sprite', { layer: 3 }).find((x) => x.key === FIELD);+ expect(f?.type).toBe('enum');+ expect(f?.value).toBe(3);+ });++ it('stays a plain field while its source knows nothing', () => {+ // A source that yields nothing must not strand the value in an empty+ // dropdown — free editing has to survive an unwarmed cache.+ const f = fieldsOf('Sprite', { layer: 2 }).find((x) => x.key === FIELD);+ expect(f?.type).not.toBe('enum');+ });+});