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(events): a trigger area is wired like a button, and one verb writes any field

yhhcfd7d6480d8c
diff --git a/desktop/src/events/EventBindingSection.tsx b/desktop/src/events/EventBindingSection.tsx
index 25055f6b6..ecf73591a 100644
--- a/desktop/src/events/EventBindingSection.tsx
+++ b/desktop/src/events/EventBindingSection.tsx
@@ -36,16 +36,30 @@ import { readEventRows, resolveTargetName, sceneEntityNames } from '@/events/eve
import { useInspectorCollapse, isSectionCollapsed } from '@/store/inspectorCollapse';
import { t } from '@/i18n';
import type { EntityId } from '@/types';
-import { UIEventType, parseActionArg } from 'esengine';
+import { UIEventType, PhysicsEventType, parseActionArg } from 'esengine';
import type { AiParamDef, AiParamValue, EventBindingRow } from 'esengine';
const SECTION_KEY = '__events';
-/** The type strings the built-in widgets emit — suggestions, not a closed set. */
-const BUILTIN_EVENTS: string[] = Object.values(UIEventType);
+/**
+ * The type strings the engine emits — widgets (`click`, `change`, …) and the
+ * physics bridge (`trigger_enter`, …). Suggestions, not a closed set: any string
+ * a game emits is authorable.
+ */
+const BUILTIN_EVENTS: string[] = [...Object.values(UIEventType), ...Object.values(PhysicsEventType)];
+
+/**
+ * Components that make an entity an event source. An entity with none of them
+ * emits nothing yet, so an empty Events section there would be noise — but an
+ * authored wire always shows, wherever it is.
+ */
+const EVENT_SOURCES = new Set([
+ 'Interactable', 'UINode', 'Canvas',
+ 'BoxCollider', 'CircleCollider', 'PolygonCollider', 'ChainCollider',
+]);
/** Empty target = "this entity"; the sentinel keeps the Select's value a string. */
const SELF = '';
-export function EventBindingSection({ entityId, interactive }: { entityId: EntityId; interactive: boolean }) {
+export function EventBindingSection({ entityId, components }: { entityId: EntityId; components: readonly string[] }) {
useSyncExternalStore(SceneStore.subscribe, SceneStore.getRevision);
// The project's own actions arrive with the schemas artifact, after open —
// re-render then, so their parameter controls appear without a reselect.
@@ -56,9 +70,7 @@ export function EventBindingSection({ entityId, interactive }: { entityId: Entit
const [expanded, setExpanded] = useState<Record<number, boolean>>({});
const rows = readEventRows(entityId);
- // Non-interactive entities don't emit anything yet, so an empty section there
- // would be pure noise — but an authored wire always shows, wherever it is.
- if (!interactive && rows.length === 0) return null;
+ if (rows.length === 0 && !components.some((c) => EVENT_SOURCES.has(c))) return null;
const addRow = () => {
SceneCommands.addEventBinding(entityId, { event: UIEventType.Click, action: '' });
diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsx
index 42f1875e4..758757936 100644
--- a/desktop/src/panels/Details.tsx
+++ b/desktop/src/panels/Details.tsx
@@ -3748,10 +3748,7 @@ function EditorDetails() {
<ControllersInline entityId={ids[0]!} />
)}
{ids.length === 1 && (
- <EventBindingSection
- entityId={ids[0]!}
- interactive={visible.some((c) => c.name === 'Interactable' || c.name === 'UINode' || c.name === 'Canvas')}
- />
+ <EventBindingSection entityId={ids[0]!} components={visible.map((c) => c.name)} />
)}
{visible.map((comp) => (
<ComponentSection
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 15b915a48..20b6422c3 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1353 stable · 17 beta · 1 deprecated
+Symbols: 1355 stable · 17 beta · 1 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -4439,6 +4439,18 @@ ComponentDef<{}>
ResourceDef<PhysicsAPI>
```
+## PhysicsContactEventData — interface
+```
+approachSpeed: number | undefined
+isSensor: boolean | undefined
+other: number
+```
+
+## PhysicsEventType — type
+```
+typeof PhysicsEventType[keyof typeof PhysicsEventType]
+```
+
## PhysicsEvents — const
```
ResourceDef<PhysicsEventsData>
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 95e50a4b9..972f081ea 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.native
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1372 stable · 22 beta · 1 deprecated
+Symbols: 1374 stable · 22 beta · 1 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -4586,6 +4586,18 @@ ComponentDef<{}>
ResourceDef<PhysicsAPI>
```
+## PhysicsContactEventData — interface
+```
+approachSpeed: number | undefined
+isSensor: boolean | undefined
+other: number
+```
+
+## PhysicsEventType — type
+```
+typeof PhysicsEventType[keyof typeof PhysicsEventType]
+```
+
## PhysicsEvents — const
```
ResourceDef<PhysicsEventsData>
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 54d6ceb9e..82ef613c7 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1352 stable · 19 beta · 1 deprecated
+Symbols: 1354 stable · 19 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -4434,6 +4434,18 @@ ComponentDef<{}>
ResourceDef<PhysicsAPI>
```
+## PhysicsContactEventData — interface
+```
+approachSpeed: number | undefined
+isSensor: boolean | undefined
+other: number
+```
+
+## PhysicsEventType — type
+```
+typeof PhysicsEventType[keyof typeof PhysicsEventType]
+```
+
## PhysicsEvents — const
```
ResourceDef<PhysicsEventsData>
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index fc637ab0e..1b9351799 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/minigame
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1373 stable · 17 beta · 1 deprecated
+Symbols: 1375 stable · 17 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -4649,6 +4649,18 @@ ComponentDef<{}>
ResourceDef<PhysicsAPI>
```
+## PhysicsContactEventData — interface
+```
+approachSpeed: number | undefined
+isSensor: boolean | undefined
+other: number
+```
+
+## PhysicsEventType — type
+```
+typeof PhysicsEventType[keyof typeof PhysicsEventType]
+```
+
## PhysicsEvents — const
```
ResourceDef<PhysicsEventsData>
diff --git a/sdk/etc/physics.api.md b/sdk/etc/physics.api.md
index 2bcf88515..b1ec06275 100644
--- a/sdk/etc/physics.api.md
+++ b/sdk/etc/physics.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/physics
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 65 stable · 0 beta · 0 deprecated
+Symbols: 68 stable · 0 beta · 0 deprecated
## BodyType — enum
```
@@ -329,6 +329,13 @@ static setDebugDraw: (app: App, enabled: boolean) => void
static setDebugDrawConfig: (app: App, config: Partial<PhysicsDebugDrawConfig>) => void
```
+## PhysicsContactEventData — interface
+```
+approachSpeed: number | undefined
+isSensor: boolean | undefined
+other: number
+```
+
## PhysicsDebugDraw — const
```
ResourceDef<PhysicsDebugDrawConfig>
@@ -342,6 +349,11 @@ showContacts: boolean
showVelocity: boolean
```
+## PhysicsEventType — type
+```
+typeof PhysicsEventType[keyof typeof PhysicsEventType]
+```
+
## PhysicsEvents — const
```
ResourceDef<PhysicsEventsData>
@@ -705,6 +717,11 @@ upperTranslation: number
(app: App): void
```
+## registerPhysicsEventBridge — function
+```
+(app: App): void
+```
+
## setupPhysicsDebugDraw — function
```
(app: App, physicsApiRes: ResourceDef<VelocityProvider>, physicsEventsRes: ResourceDef<PhysicsEventsData>): void
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 7bc5033d8..fc8702841 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/wechat
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1363 stable · 17 beta · 1 deprecated
+Symbols: 1365 stable · 17 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -4441,6 +4441,18 @@ ComponentDef<{}>
ResourceDef<PhysicsAPI>
```
+## PhysicsContactEventData — interface
+```
+approachSpeed: number | undefined
+isSensor: boolean | undefined
+other: number
+```
+
+## PhysicsEventType — type
+```
+typeof PhysicsEventType[keyof typeof PhysicsEventType]
+```
+
## PhysicsEvents — const
```
ResourceDef<PhysicsEventsData>
diff --git a/sdk/src/ai/builtins.ts b/sdk/src/ai/builtins.ts
index d766d5a1e..da988dfaa 100644
--- a/sdk/src/ai/builtins.ts
+++ b/sdk/src/ai/builtins.ts
@@ -14,9 +14,10 @@
*/
import { aiRegistry, type AiContext } from './fsm/AiContext';
-import type { AiAction, AiCondition } from './fsm/registry';
+import type { AiAction, AiCondition, AiParamValue } from './fsm/registry';
import { TimelinePlayer } from '../timeline/TimelinePlugin';
import { SpriteAnimator } from '../animation/SpriteAnimator';
+import { setEntityProperty } from '../propertyPath';
/**
* Register the engine's built-in actions/conditions. Idempotent (and safe after
@@ -102,6 +103,39 @@ export function ensureBuiltinAiRegistrations(): void {
const sp = ctx.get(SpriteAnimator);
return sp.finished && !sp.playing;
});
+
+ // The general-purpose write, through the engine's reflection writer — the
+ // same addressing a UIGear binding and a Timeline track use ("Component" +
+ // a dot path). One verb instead of a growing family of setters, and it
+ // reaches project components as readily as builtins.
+ //
+ // `value` is parsed as JSON when it can be, so `3`, `true` and `{"r":1,...}`
+ // arrive as themselves and a bare word stays a string.
+ if (!aiRegistry.hasAction('property.set')) {
+ aiRegistry.registerAction('property.set', {
+ separator: '=',
+ params: [
+ { name: 'path', type: 'string', tooltip: 'Component.field, e.g. UIVisual.color.a' },
+ { name: 'value', type: 'string' },
+ ],
+ run: (ctx, _bb, _arg, params) => {
+ const path = typeof params?.path === 'string' ? params.path.trim() : '';
+ const raw = params?.value;
+ if (!path || raw === undefined) return;
+ setEntityProperty(ctx.world, ctx.entity, path, parseValue(raw));
+ },
+ });
+ }
+}
+
+/** A parameter's JSON reading when it has one; otherwise the value itself. */
+function parseValue(raw: AiParamValue): unknown {
+ if (typeof raw !== 'string') return raw;
+ try {
+ return JSON.parse(raw.trim());
+ } catch {
+ return raw.trim();
+ }
}
function action(name: string, fn: AiAction<AiContext>): void {
diff --git a/sdk/src/core-plugins.ts b/sdk/src/core-plugins.ts
index 090fce61d..3fef24dec 100644
--- a/sdk/src/core-plugins.ts
+++ b/sdk/src/core-plugins.ts
@@ -32,6 +32,10 @@ export { focusPlugin, FocusPlugin } from './ui/input/focus';
export { safeAreaPlugin, SafeAreaPlugin } from './ui/layout/safe-area';
export { PhysicsPlugin, PhysicsEvents, Physics, loadPhysicsModule } from './physics';
+// The contact event names, mirrored into the main barrel: an editor palette (or
+// game code) must be able to spell `trigger_enter` without importing the side
+// module, since the wire is authored whether or not physics is loaded.
+export { PhysicsEventType, type PhysicsContactEventData } from './physics';
export { SpinePlugin, SpineEvents, Spine } from './spine';
export { PostProcessPlugin, postProcessPlugin } from './postprocess';
diff --git a/sdk/src/entityEvents.ts b/sdk/src/entityEvents.ts
index fd24a2252..dabc9f9bc 100644
--- a/sdk/src/entityEvents.ts
+++ b/sdk/src/entityEvents.ts
@@ -21,6 +21,7 @@
*/
import { defineResource } from './resource';
import type { Entity } from './types';
+import type { App } from './app';
import { log } from './logger';
export interface EntityEvent<TData = unknown> {
@@ -279,3 +280,19 @@ export class EntityEventQueue {
* queue during `build()`.
*/
export const EntityEvents = defineResource<EntityEventQueue>(new EntityEventQueue(), 'EntityEvents');
+
+/**
+ * The app's queue, creating it on first ask. Every producer and consumer — the
+ * UI hit-test, the physics bridge, the binding dispatcher — goes through here
+ * instead of inserting its own, so plugin build order cannot decide who wins and
+ * a late plugin can never replace the queue earlier subscribers captured.
+ * Despawn cleanup is wired once, with the queue.
+ */
+export function ensureEntityEvents(app: App): EntityEventQueue {
+ if (!app.hasResource(EntityEvents)) {
+ const queue = new EntityEventQueue();
+ app.insertResource(EntityEvents, queue);
+ app.world.onDespawn((entity: Entity) => queue.removeAll(entity));
+ }
+ return app.getResource(EntityEvents) as EntityEventQueue;
+}
diff --git a/sdk/src/eventBinding.ts b/sdk/src/eventBinding.ts
index fb3da3c92..29533c044 100644
--- a/sdk/src/eventBinding.ts
+++ b/sdk/src/eventBinding.ts
@@ -34,7 +34,7 @@ import { Commands, type CommandsInstance } from './commands';
import { Res, Time, type TimeData } from './resource';
import { playModeOnly } from './env';
import { log } from './logger';
-import { EntityEvents, EntityEventQueue, type EntityEvent, type Unsubscribe } from './entityEvents';
+import { ensureEntityEvents, EntityEventQueue, type EntityEvent, type Unsubscribe } from './entityEvents';
import { Blackboard } from './ai/fsm/Blackboard';
import { aiRegistry, type AiContext } from './ai/fsm/AiContext';
import { invokeAction, type AiParamValue } from './ai/fsm/registry';
@@ -253,14 +253,9 @@ export class EventBindingPlugin implements Plugin {
ensureEventBindingActions();
const world = app.world;
- // The queue belongs to whoever owns the event channel (the UI interaction
- // plugin, today). Binding works with UI absent too — a physics trigger or
- // game code can emit — so we insert one only if nobody has.
- if (!app.hasResource(EntityEvents)) {
- const queue = new EntityEventQueue();
- app.insertResource(EntityEvents, queue);
- world.onDespawn((e: Entity) => queue.removeAll(e));
- }
+ // The app's shared queue — binding works with UI absent too (a physics
+ // trigger or game code can emit), so it must not depend on who built first.
+ const events = ensureEntityEvents(app);
// Blackboards are shared with the FSM layer when it is present, so a
// `fsm.fire` from a click lands in the very blackboard the entity's
@@ -273,7 +268,7 @@ export class EventBindingPlugin implements Plugin {
const runtime = createEventBindingRuntime({
world,
- events: app.getResource(EntityEvents) as EntityEventQueue,
+ events,
blackboardOf: (entity) => {
const fsm = app.hasResource(AiFsm) ? app.getResource(AiFsm) : null;
if (fsm) return fsm.blackboard(entity);
diff --git a/sdk/src/physics/PhysicsEventBridge.ts b/sdk/src/physics/PhysicsEventBridge.ts
new file mode 100644
index 000000000..2b6808d2e
--- /dev/null
+++ b/sdk/src/physics/PhysicsEventBridge.ts
@@ -0,0 +1,95 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file PhysicsEventBridge.ts
+ * @brief Contacts and sensor overlaps, republished on the entity event channel.
+ *
+ * `PhysicsEvents` is a per-frame batch resource: excellent for a system that
+ * wants every contact this tick, useless for "when THIS entity is touched". The
+ * bridge turns each batch entry into an entity-scoped event on the shared queue
+ * — the same channel a button's `click` travels — which is what lets an authored
+ * `EventBinding` row wire a trigger area with no code, exactly like a widget.
+ *
+ * Both participants hear it. A contact has no privileged side, and a trigger's
+ * two roles (the area, and whoever walked into it) both routinely want to react;
+ * each side receives the OTHER entity in the payload.
+ */
+import type { App } from '../app';
+import { Schedule, defineSystem } from '../system';
+import { Res } from '../resource';
+import { playModeOnly } from '../env';
+import { ensureEntityEvents } from '../entityEvents';
+import { PhysicsEvents, type PhysicsEventsData } from './PhysicsTypes';
+import type { Entity } from '../types';
+
+/**
+ * The event types the physics bridge emits. Open strings, like every other
+ * producer's — these constants exist so the editor's palette and game code spell
+ * them the same way (mirrors `UIEventType`).
+ */
+export const PhysicsEventType = {
+ CollisionEnter: 'collision_enter',
+ CollisionExit: 'collision_exit',
+ CollisionHit: 'collision_hit',
+ TriggerEnter: 'trigger_enter',
+ TriggerExit: 'trigger_exit',
+} as const;
+
+export type PhysicsEventType = typeof PhysicsEventType[keyof typeof PhysicsEventType];
+
+/** Payload carried by every bridged event: who else was involved. */
+export interface PhysicsContactEventData {
+ /** The other participant — the body touched, or the trigger/visitor. */
+ other: Entity;
+ /** True on the sensor's own `trigger_*` event (false on the visitor's). */
+ isSensor?: boolean;
+ /** Approach speed, on `collision_hit` only. */
+ approachSpeed?: number;
+}
+
+/**
+ * Republish this frame's physics batch onto the entity event channel. Runs in
+ * Update (after the fixed-step physics has filled the resource) and only in play
+ * mode — the edit realm never steps the world.
+ */
+export function registerPhysicsEventBridge(app: App): void {
+ const events = ensureEntityEvents(app);
+ const world = app.world;
+ const emitPair = (a: Entity, b: Entity, type: string, extra?: Partial<PhysicsContactEventData>): void => {
+ if (world.valid(a)) events.emit<PhysicsContactEventData>(a, type, { other: b, ...extra });
+ if (world.valid(b)) events.emit<PhysicsContactEventData>(b, type, { other: a, ...extra });
+ };
+
+ app.addSystemToSchedule(
+ Schedule.Update,
+ defineSystem([Res(PhysicsEvents)], (physics: PhysicsEventsData) => {
+ for (const c of physics.collisionEnters) {
+ emitPair(c.entityA, c.entityB, PhysicsEventType.CollisionEnter);
+ }
+ for (const c of physics.collisionExits) {
+ emitPair(c.entityA, c.entityB, PhysicsEventType.CollisionExit);
+ }
+ for (const c of physics.collisionHits) {
+ emitPair(c.entityA, c.entityB, PhysicsEventType.CollisionHit, { approachSpeed: c.approachSpeed });
+ }
+ // A sensor pair is asymmetric, so each side is told which it is.
+ for (const s of physics.sensorEnters) {
+ if (world.valid(s.sensorEntity)) {
+ events.emit<PhysicsContactEventData>(s.sensorEntity, PhysicsEventType.TriggerEnter, { other: s.visitorEntity, isSensor: true });
+ }
+ if (world.valid(s.visitorEntity)) {
+ events.emit<PhysicsContactEventData>(s.visitorEntity, PhysicsEventType.TriggerEnter, { other: s.sensorEntity, isSensor: false });
+ }
+ }
+ for (const s of physics.sensorExits) {
+ if (world.valid(s.sensorEntity)) {
+ events.emit<PhysicsContactEventData>(s.sensorEntity, PhysicsEventType.TriggerExit, { other: s.visitorEntity, isSensor: true });
+ }
+ if (world.valid(s.visitorEntity)) {
+ events.emit<PhysicsContactEventData>(s.visitorEntity, PhysicsEventType.TriggerExit, { other: s.sensorEntity, isSensor: false });
+ }
+ }
+ }, { name: 'PhysicsEventBridgeSystem' }),
+ { runIf: playModeOnly },
+ );
+}
diff --git a/sdk/src/physics/PhysicsPlugin.ts b/sdk/src/physics/PhysicsPlugin.ts
index db9777a0f..f348aef09 100644
--- a/sdk/src/physics/PhysicsPlugin.ts
+++ b/sdk/src/physics/PhysicsPlugin.ts
@@ -23,6 +23,7 @@ import { PhysicsRuntime } from './PhysicsRuntime';
import { PhysicsAPI, Physics } from './Physics';
import { registerPhysicsSystem } from './PhysicsSystem';
import { registerCharacterControllerSystem } from './CharacterController';
+import { registerPhysicsEventBridge } from './PhysicsEventBridge';
import {
PhysicsEvents,
type PhysicsPluginConfig,
@@ -137,6 +138,9 @@ export class PhysicsPlugin implements Plugin {
app.getResource(PhysicsRuntime).module = module;
app.insertResource(Physics, PhysicsAPI._fromModule(module));
registerCharacterControllerSystem(app);
+ // Contacts also reach the entity event channel, so a trigger area
+ // can be wired by an authored EventBinding row like a button is.
+ registerPhysicsEventBridge(app);
setupPhysicsDebugDraw(app, Physics, PhysicsEvents);
app.setFixedTimestep(this.config_.fixedTimestep);
// Module loaded, world initialized, systems registered.
diff --git a/sdk/src/physics/index.ts b/sdk/src/physics/index.ts
index 54f677a62..881edf660 100644
--- a/sdk/src/physics/index.ts
+++ b/sdk/src/physics/index.ts
@@ -11,6 +11,14 @@
* ```
*/
+// Contacts as entity events (the channel widgets emit into), so an authored
+// EventBinding row can wire a trigger area with no code.
+export {
+ PhysicsEventType,
+ registerPhysicsEventBridge,
+ type PhysicsContactEventData,
+} from './PhysicsEventBridge';
+
export {
PhysicsPlugin,
physicsPlugin,
diff --git a/sdk/src/ui/util/property-path.ts b/sdk/src/propertyPath.ts
similarity index 72%
rename from sdk/src/ui/util/property-path.ts
rename to sdk/src/propertyPath.ts
index c9bce8cfe..8286f8ef8 100644
--- a/sdk/src/ui/util/property-path.ts
+++ b/sdk/src/propertyPath.ts
@@ -1,8 +1,22 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-import type { World } from '../../world';
-import type { Entity } from '../../types';
-import { getComponent } from '../../component';
+/**
+ * @file propertyPath.ts
+ * @brief Address a component field by `"Component.dot.path"` and read/write it.
+ *
+ * The generic reflection writer: UI gears drive per-page values through it, and
+ * the `property.set` action lets authored data write any field of any component.
+ * It grew up under `ui/util/` but nothing in it is UI — it speaks the component
+ * registry — so it lives here, where a core action can reach it.
+ *
+ * NOT the same as `timeline/TimelineRuntime.setNestedProperty`, and deliberately
+ * so: the timeline's writer is numeric-only and knows about channels a plain dot
+ * path would corrupt (see TimelineEvaluator). Merging them is a real change, not
+ * a rename.
+ */
+import type { World } from './world';
+import type { Entity } from './types';
+import { getComponent } from './component';
export function getNestedProperty(obj: Record<string, any>, path: string): unknown {
const parts = path.split('.');
diff --git a/sdk/src/ui/ARCHITECTURE.md b/sdk/src/ui/ARCHITECTURE.md
index 28a55b61f..6898a09dd 100644
--- a/sdk/src/ui/ARCHITECTURE.md
+++ b/sdk/src/ui/ARCHITECTURE.md
@@ -48,7 +48,7 @@ collection, or widgets.
| `collection/` | Data-driven collections + view recycling | `list-view`, `scroll-container`, `view-pool`, `data-source`, `layout-provider` |
| `text/` | SDF glyph atlas, text layout, rich text, editable text | `glyph-atlas`, `text-renderer`, `layout`, `rich-text-parser`, `text-input`, `text-input-plugin`, `text-input-view` |
| `theme/` | Design tokens + per-entity role markers | `tokens`, `theme-style` |
-| `util/` | Cross-cutting helpers (no engine state of their own) | `helpers`, `math`, `constants`, `property-path`, `ui-pick` |
+| `util/` | Cross-cutting helpers (no engine state of their own) | `helpers`, `math`, `constants`, `ui-pick` |
| `widgets/` | Layer-4 widget **factory functions** + their prefab capture | `button`, `toggle`, `slider`, `progress`, `dialog`, `dropdown`, `text-input`, `list-view`, `scroll-view`, `helpers`, `toPrefab`, `prefabs/` |
Only two files live at the module root, and that is deliberate:
diff --git a/sdk/src/ui/controller/ai-builtins.ts b/sdk/src/ui/controller/ai-builtins.ts
index 3ccbff708..a39eec493 100644
--- a/sdk/src/ui/controller/ai-builtins.ts
+++ b/sdk/src/ui/controller/ai-builtins.ts
@@ -13,6 +13,8 @@
*/
import { aiRegistry } from '../../ai/fsm/AiContext';
import { setControllerPage } from './ui-controller';
+import { UINode } from '../core/ui-node';
+import { UIDisplay } from '../../wasm.generated';
/**
* Idempotently register the UI AI glue. `ui.setPage` takes an arg `"controller:page"`
@@ -21,6 +23,7 @@ import { setControllerPage } from './ui-controller';
* Called when the controller plugin builds (and re-called after an aiRegistry clear).
*/
export function ensureControllerAiRegistrations(): void {
+ ensureVisibilityAction();
if (aiRegistry.hasAction('ui.setPage')) return;
aiRegistry.registerAction('ui.setPage', {
// Declaring the two halves is what turns the editor's single text box into
@@ -39,3 +42,26 @@ export function ensureControllerAiRegistrations(): void {
},
});
}
+
+/**
+ * Show/hide a UI subtree — the most common wire there is (a button opens a
+ * panel). It drives `UINode.display`, the CSS-box switch Yoga and the renderer
+ * both honour, NOT the `Disabled` tag: nothing in the render path reads Disabled
+ * today, so a verb built on it would look right in the inspector and change
+ * nothing on screen.
+ */
+function ensureVisibilityAction(): void {
+ if (aiRegistry.hasAction('ui.setVisible')) return;
+ aiRegistry.registerAction('ui.setVisible', {
+ params: [{ name: 'visible', type: 'bool' }],
+ run: (ctx, _bb, _arg, params) => {
+ if (!ctx.has(UINode)) return;
+ const visible = params?.visible === true;
+ const node = ctx.get(UINode);
+ const next = visible ? UIDisplay.Flex : UIDisplay.None;
+ if (node.display === next) return;
+ node.display = next;
+ ctx.set(UINode, node);
+ },
+ });
+}
diff --git a/sdk/src/ui/index.ts b/sdk/src/ui/index.ts
index 5b3565a36..676558ea9 100644
--- a/sdk/src/ui/index.ts
+++ b/sdk/src/ui/index.ts
@@ -413,7 +413,10 @@ export { signal, derived, type Signal, type ReadonlySignal } from './binding/sig
export { bind } from './binding/bind';
export { bindWidgetValue } from './binding/two-way';
-// Property Path Utilities
+// Property Path Utilities — the engine's generic reflection writer, which UI
+// gears drive fields through. It lives in core now (nothing about it is UI, and
+// core actions like `property.set` need it); re-exported here for the UI's own
+// call sites.
export {
getNestedProperty,
setNestedProperty,
@@ -421,7 +424,7 @@ export {
getEntityProperty,
setEntityProperty,
type ParsedPropertyPath,
-} from './util/property-path';
+} from '../propertyPath';
// Rich Text
export {
diff --git a/sdk/src/ui/input/interaction.ts b/sdk/src/ui/input/interaction.ts
index ebe703797..f15f5a821 100644
--- a/sdk/src/ui/input/interaction.ts
+++ b/sdk/src/ui/input/interaction.ts
@@ -12,7 +12,8 @@ import { playModeOnly } from '../../env';
import { Interactable } from './interactable';
import { UIInteraction } from './interactable';
import type { UIInteractionData } from './interactable';
-import { UIEvents, UIEventQueue, UIEventType } from '../core/events';
+import { UIEventQueue, UIEventType } from '../core/events';
+import { ensureEntityEvents } from '../../entityEvents';
import { UICameraInfo } from '../core/ui-camera-info';
import type { UICameraData } from '../core/ui-camera-info';
import type { InteractableData } from './interactable';
@@ -54,12 +55,9 @@ export class UIInteractionPlugin implements Plugin {
const world = app.world;
const engine = engineApi(app);
const registry = world.getCppRegistry() as CppRegistry;
- const events = new UIEventQueue();
- app.insertResource(UIEvents, events);
- // Prune handlers when an entity dies. Replaces the old
- // setEntityValidator pattern; canonical UIEventQueue has no
- // validator hook because it's the plugin's job to wire cleanup.
- app.world.onDespawn((e) => events.removeAll(e));
+ // The app's one entity-event queue (created on first ask, despawn cleanup
+ // included) — shared with every other producer, not owned by the UI.
+ const events = ensureEntityEvents(app);
let hoveredEntity: Entity | null = null;
let pressedEntity: Entity | null = null;
diff --git a/sdk/tests/ai-builtin-verbs.test.ts b/sdk/tests/ai-builtin-verbs.test.ts
new file mode 100644
index 000000000..469fd706b
--- /dev/null
+++ b/sdk/tests/ai-builtin-verbs.test.ts
@@ -0,0 +1,122 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ai-builtin-verbs.test.ts
+ * @brief The engine verbs an authored wire can reach with no game code:
+ * `property.set` (the generic reflection write) and `ui.setVisible`
+ * (show/hide, on the switch the renderer actually honours).
+ */
+import { beforeEach, describe, expect, it } from 'vitest';
+import { aiRegistry } from '../src/ai/fsm/AiContext';
+import { ensureBuiltinAiRegistrations } from '../src/ai/builtins';
+import { ensureControllerAiRegistrations } from '../src/ui/controller/ai-builtins';
+import { Blackboard } from '../src/ai/fsm/Blackboard';
+import { UINode } from '../src/ui/core/ui-node';
+import { UIDisplay } from '../src/wasm.generated';
+import { registerComponent, defineComponent } from '../src/component';
+import type { AnyComponentDef } from '../src/component';
+import type { Entity } from '../src/types';
+
+const Score = defineComponent<{ points: number; label: string }>('TestScore', { points: 0, label: '' });
+
+function makeWorld() {
+ const storage = new Map<AnyComponentDef, Map<Entity, unknown>>();
+ const storeFor = (c: AnyComponentDef) => {
+ let s = storage.get(c);
+ if (!s) storage.set(c, (s = new Map()));
+ return s;
+ };
+ return {
+ has: (e: Entity, c: AnyComponentDef) => storeFor(c).has(e),
+ get: (e: Entity, c: AnyComponentDef) => storeFor(c).get(e),
+ set: (e: Entity, c: AnyComponentDef, d: unknown) => storeFor(c).set(e, d),
+ insert: (e: Entity, c: AnyComponentDef, d: unknown) => storeFor(c).set(e, d),
+ valid: () => true,
+ };
+}
+
+const E = 1 as Entity;
+
+function ctxFor(world: ReturnType<typeof makeWorld>, entity = E) {
+ return {
+ entity,
+ world,
+ dt: 0,
+ get: (c: AnyComponentDef) => world.get(entity, c),
+ set: (c: AnyComponentDef, d: unknown) => world.set(entity, c, d),
+ has: (c: AnyComponentDef) => world.has(entity, c),
+ } as never;
+}
+
+beforeEach(() => {
+ aiRegistry.clear();
+ ensureBuiltinAiRegistrations();
+ ensureControllerAiRegistrations();
+ registerComponent('TestScore', Score);
+});
+
+describe('property.set', () => {
+ it('writes a component field addressed by Component.path', () => {
+ const world = makeWorld();
+ world.insert(E, Score, { points: 0, label: '' });
+
+ aiRegistry.getAction('property.set')!(ctxFor(world), new Blackboard(), 'TestScore.points=7');
+
+ expect(world.get(E, Score)).toEqual({ points: 7, label: '' });
+ });
+
+ it('keeps a bare word a string, and reads JSON when there is one', () => {
+ const world = makeWorld();
+ world.insert(E, Score, { points: 0, label: '' });
+ const bb = new Blackboard();
+
+ aiRegistry.getAction('property.set')!(ctxFor(world), bb, 'TestScore.label=ready');
+ expect(world.get(E, Score)).toMatchObject({ label: 'ready' });
+
+ aiRegistry.getAction('property.set')!(ctxFor(world), bb, 'TestScore.points=12');
+ expect(world.get(E, Score)).toMatchObject({ points: 12 });
+ });
+
+ it('reaches a nested path (a colour channel)', () => {
+ const Tint = defineComponent<{ color: { r: number; g: number; b: number; a: number } }>(
+ 'TestTint', { color: { r: 1, g: 1, b: 1, a: 1 } },
+ );
+ registerComponent('TestTint', Tint);
+ const world = makeWorld();
+ world.insert(E, Tint, { color: { r: 1, g: 1, b: 1, a: 1 } });
+
+ aiRegistry.getAction('property.set')!(ctxFor(world), new Blackboard(), 'TestTint.color.a=0.25');
+
+ expect(world.get(E, Tint)).toEqual({ color: { r: 1, g: 1, b: 1, a: 0.25 } });
+ });
+
+ it('is a no-op for a missing component, path or value — never a throw', () => {
+ const world = makeWorld();
+ const run = aiRegistry.getAction('property.set')!;
+ expect(() => run(ctxFor(world), new Blackboard(), 'Nope.field=1')).not.toThrow();
+ expect(() => run(ctxFor(world), new Blackboard(), '')).not.toThrow();
+ expect(() => run(ctxFor(world), new Blackboard(), 'TestScore.points')).not.toThrow();
+ });
+});
+
+describe('ui.setVisible', () => {
+ it('drives UINode.display, the switch layout and rendering honour', () => {
+ const world = makeWorld();
+ world.insert(E, UINode, { display: UIDisplay.Flex });
+
+ aiRegistry.getAction('ui.setVisible')!(ctxFor(world), new Blackboard(), 'false');
+ expect((world.get(E, UINode) as { display: number }).display).toBe(UIDisplay.None);
+
+ aiRegistry.getAction('ui.setVisible')!(ctxFor(world), new Blackboard(), 'true');
+ expect((world.get(E, UINode) as { display: number }).display).toBe(UIDisplay.Flex);
+ });
+
+ it('does nothing on an entity without a UINode', () => {
+ const world = makeWorld();
+ expect(() => aiRegistry.getAction('ui.setVisible')!(ctxFor(world), new Blackboard(), 'false')).not.toThrow();
+ });
+
+ it('declares a bool parameter, so the inspector renders a checkbox', () => {
+ expect(aiRegistry.getActionParams('ui.setVisible')).toEqual([{ name: 'visible', type: 'bool' }]);
+ });
+});
diff --git a/sdk/tests/physics-event-bridge.test.ts b/sdk/tests/physics-event-bridge.test.ts
new file mode 100644
index 000000000..f96308218
--- /dev/null
+++ b/sdk/tests/physics-event-bridge.test.ts
@@ -0,0 +1,105 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file physics-event-bridge.test.ts
+ * @brief Contacts republished on the entity event channel — the step that
+ * lets an authored EventBinding row wire a trigger area exactly like a
+ * button, with the same queue and the same dispatcher.
+ */
+import { describe, expect, it, vi } from 'vitest';
+import { EntityEventQueue, EntityEvents } from '../src/entityEvents';
+import { PhysicsEventType, registerPhysicsEventBridge, type PhysicsContactEventData } from '../src/physics/PhysicsEventBridge';
+import { PhysicsEvents, type PhysicsEventsData } from '../src/physics/PhysicsTypes';
+import type { Entity } from '../src/types';
+
+const EMPTY: PhysicsEventsData = {
+ collisionEnters: [], collisionExits: [], collisionHits: [], sensorEnters: [], sensorExits: [],
+};
+
+/** A fake App exposing only what the bridge touches, plus a manual tick. */
+function makeApp(batch: Partial<PhysicsEventsData>) {
+ const queue = new EntityEventQueue();
+ const resources = new Map<unknown, unknown>([[PhysicsEvents, { ...EMPTY, ...batch }]]);
+ let system: (() => void) | null = null;
+ const app = {
+ world: {
+ valid: () => true,
+ onDespawn: () => () => {},
+ },
+ hasResource: (def: unknown) => resources.has(def),
+ getResource: (def: unknown) => resources.get(def),
+ insertResource: (def: unknown, v: unknown) => { resources.set(def, v); },
+ addSystemToSchedule: (_s: unknown, def: { _fn: (...args: unknown[]) => void }) => {
+ // The bridge's only system param is Res(PhysicsEvents); feed it directly
+ // rather than standing up a scheduler.
+ system = () => def._fn(resources.get(PhysicsEvents));
+ },
+ };
+ registerPhysicsEventBridge(app as never);
+ return { queue: resources.get(EntityEvents) as EntityEventQueue, tick: () => system?.(), fallback: queue };
+}
+
+/** Collect (type, entity, other) for everything the bridge emits. */
+function record(queue: EntityEventQueue, types: string[]) {
+ const seen: Array<{ type: string; entity: Entity; other: Entity; isSensor?: boolean }> = [];
+ for (const type of types) {
+ queue.on(type, (e) => {
+ const data = e.data as PhysicsContactEventData;
+ seen.push({ type: e.type, entity: e.currentTarget, other: data.other, isSensor: data.isSensor });
+ });
+ }
+ return seen;
+}
+
+const A = 1 as Entity;
+const B = 2 as Entity;
+
+describe('physics → entity events', () => {
+ it('emits collision_enter on BOTH bodies, each told about the other', () => {
+ const app = makeApp({ collisionEnters: [{ entityA: A, entityB: B, pointX: 0, pointY: 0, normalX: 0, normalY: 1 } as never] });
+ const seen = record(app.queue, [PhysicsEventType.CollisionEnter]);
+
+ app.tick();
+
+ expect(seen).toEqual([
+ { type: 'collision_enter', entity: A, other: B, isSensor: undefined },
+ { type: 'collision_enter', entity: B, other: A, isSensor: undefined },
+ ]);
+ });
+
+ it('a sensor pair says which side is the trigger', () => {
+ const app = makeApp({ sensorEnters: [{ sensorEntity: A, visitorEntity: B }] });
+ const seen = record(app.queue, [PhysicsEventType.TriggerEnter]);
+
+ app.tick();
+
+ expect(seen).toEqual([
+ { type: 'trigger_enter', entity: A, other: B, isSensor: true },
+ { type: 'trigger_enter', entity: B, other: A, isSensor: false },
+ ]);
+ });
+
+ it('carries the impact speed on collision_hit', () => {
+ const app = makeApp({
+ collisionHits: [{ entityA: A, entityB: B, pointX: 0, pointY: 0, normalX: 0, normalY: 1, approachSpeed: 7.5 }],
+ });
+ const speeds: number[] = [];
+ app.queue.on(PhysicsEventType.CollisionHit, (e) => {
+ speeds.push((e.data as PhysicsContactEventData).approachSpeed!);
+ });
+
+ app.tick();
+
+ expect(speeds).toEqual([7.5, 7.5]); // both participants
+ });
+
+ it('an empty frame emits nothing', () => {
+ const app = makeApp({});
+ const spy = vi.fn();
+ for (const t of Object.values(PhysicsEventType)) app.queue.on(t, spy);
+
+ app.tick();
+
+ expect(spy).not.toHaveBeenCalled();
+ });
+});
diff --git a/sdk/tests/propertyPath.test.ts b/sdk/tests/propertyPath.test.ts
index 4382743fe..484083d00 100644
--- a/sdk/tests/propertyPath.test.ts
+++ b/sdk/tests/propertyPath.test.ts
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { describe, it, expect } from 'vitest';
-import { getNestedProperty, setNestedProperty, parsePropertyPath } from '../src/ui/util/property-path';
+import { getNestedProperty, setNestedProperty, parsePropertyPath } from '../src/propertyPath';
describe('propertyPath', () => {
describe('getNestedProperty', () => {