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(sdk): behavior-tree orphan nodes for the editor
esengine5025549446b1
diff --git a/sdk/src/ai/bt/btGraph.ts b/sdk/src/ai/bt/btGraph.tsindex fa2d51dd8..e15ec512d 100644--- a/sdk/src/ai/bt/btGraph.ts+++ b/sdk/src/ai/bt/btGraph.ts@@ -5,10 +5,11 @@* @brief Immutable tree operations on a BtDefinition — the editor's model.** Pure functions returning new definitions (never mutating), so the tree editor- * drives them through AssetDocument.edit for free undo, mirroring fsmGraph. Nodes- * carry an editor-only `id` (the interpreter ignores it); a `.esbt` IS the runtime- * definition, so there is no compile step. Composite/decorator/leaf capacities are- * enforced so the graph can only form a valid tree.+ * drives them through AssetDocument.edit for free undo, mirroring fsmGraph. The+ * editor model is a forest: the run tree (`root`) plus `orphans` — unconnected+ * nodes/subtrees the interpreter ignores. Dragging a parent's handle to an+ * orphan reparents it into the tree. Nodes carry an editor-only `id`/`x`/`y`+ * that the interpreter ignores; a `.esbt` IS the runtime definition (no compile).*/import type { BtDefinition, BtNode, BtNodeType } from './types';@@ -38,32 +39,63 @@ function clone(def: BtDefinition): BtDefinition {return JSON.parse(JSON.stringify(def)) as BtDefinition;}-function walk(node: BtNode, fn: (n: BtNode) => void): void {+/** All top-level trees: the run root plus every orphan. */+function roots(def: BtDefinition): BtNode[] {+ return def.orphans ? [def.root, ...def.orphans] : [def.root];+}++function walkNode(node: BtNode, fn: (n: BtNode) => void): void {fn(node);- for (const c of node.children ?? []) walk(c, fn);+ for (const c of node.children ?? []) walkNode(c, fn);+}++function walk(def: BtDefinition, fn: (n: BtNode) => void): void {+ for (const r of roots(def)) walkNode(r, fn);}-function find(node: BtNode, id: string): BtNode | null {+/** Find a node anywhere in the forest. */+function find(def: BtDefinition, id: string): BtNode | null {+ for (const r of roots(def)) {+ const hit = findInSubtree(r, id);+ if (hit) return hit;+ }+ return null;+}++function findInSubtree(node: BtNode, id: string): BtNode | null {if (node.id === id) return node;for (const c of node.children ?? []) {- const r = find(c, id);- if (r) return r;+ const hit = findInSubtree(c, id);+ if (hit) return hit;}return null;}-function findParent(node: BtNode, id: string): BtNode | null {+/** Find a node's parent, or null if it is a top-level root (run root or an orphan root). */+function findParent(def: BtDefinition, id: string): BtNode | null {+ for (const r of roots(def)) {+ const p = findParentInSubtree(r, id);+ if (p) return p;+ }+ return null;+}++function findParentInSubtree(node: BtNode, id: string): BtNode | null {for (const c of node.children ?? []) {if (c.id === id) return node;- const r = findParent(c, id);- if (r) return r;+ const p = findParentInSubtree(c, id);+ if (p) return p;}return null;}+function isOrphanRoot(def: BtDefinition, id: string): boolean {+ return def.orphans?.some(o => o.id === id) ?? false;+}+function freshId(def: BtDefinition): string {const used = new Set<string>();- walk(def.root, n => { if (n.id) used.add(n.id); });+ walk(def, n => { if (n.id) used.add(n.id); });let i = 0;let id: string;do { id = `n${i++}`; } while (used.has(id));@@ -73,7 +105,7 @@ function freshId(def: BtDefinition): string {/** Assign ids to any node missing one (e.g. a hand-written `.esbt`). Mutates + returns the def. */export function ensureBtIds(def: BtDefinition): BtDefinition {const used = new Set<string>();- walk(def.root, n => { if (n.id) used.add(n.id); });+ walk(def, n => { if (n.id) used.add(n.id); });let i = 0;const nextId = () => {let id: string;@@ -81,7 +113,7 @@ export function ensureBtIds(def: BtDefinition): BtDefinition {used.add(id);return id;};- walk(def.root, n => { if (!n.id) n.id = nextId(); });+ walk(def, n => { if (!n.id) n.id = nextId(); });return def;}@@ -90,17 +122,17 @@ export function emptyBt(): BtDefinition {return { root: { type: 'selector', id: 'n0', x: 60, y: 80, children: [] } };}-/** All nodes flattened (for the canvas). */+/** All nodes flattened (run tree + orphans), for the canvas. */export function btNodes(def: BtDefinition): BtNode[] {const out: BtNode[] = [];- walk(def.root, n => out.push(n));+ walk(def, n => out.push(n));return out;}-/** Parent -> child edges. */+/** Parent -> child edges across the run tree and every orphan subtree. */export function btEdges(def: BtDefinition): BtEdge[] {const edges: BtEdge[] = [];- walk(def.root, n => {+ walk(def, n => {for (const c of n.children ?? []) {if (n.id && c.id) edges.push({ id: `${n.id}->${c.id}`, from: n.id, to: c.id });}@@ -110,17 +142,32 @@ export function btEdges(def: BtDefinition): BtEdge[] {export function addBtChild(def: BtDefinition, parentId: string, type: BtNodeType, x = 0, y = 0): BtDefinition {const next = clone(def);- const parent = find(next.root, parentId);+ const parent = find(next, parentId);if (!parent || (parent.children?.length ?? 0) >= maxChildren(parent.type)) return def;const child: BtNode = { type, id: freshId(next), x, y };(parent.children ??= []).push(child);return next;}+/** Add an unconnected node to the editor's orphan pool (not ticked until wired under root). */+export function addBtOrphan(def: BtDefinition, type: BtNodeType, x = 0, y = 0): BtDefinition {+ const next = clone(def);+ const node: BtNode = { type, id: freshId(next), x, y };+ (next.orphans ??= []).push(node);+ return next;+}+export function removeBtNode(def: BtDefinition, id: string): BtDefinition {- if (def.root.id === id) return def; // the root can't be removed+ if (def.root.id === id) return def; // the run root can't be removedconst next = clone(def);- const parent = findParent(next.root, id);+ if (isOrphanRoot(next, id)) {+ // Set to undefined (not `delete`) so an Object.assign apply in the editor+ // overwrites a stale orphans array instead of leaving it in place.+ const rest = (next.orphans ?? []).filter(o => o.id !== id);+ next.orphans = rest.length ? rest : undefined;+ return next;+ }+ const parent = findParent(next, id);if (!parent?.children) return def;parent.children = parent.children.filter(c => c.id !== id);return next;@@ -128,7 +175,7 @@ export function removeBtNode(def: BtDefinition, id: string): BtDefinition {export function moveBtNode(def: BtDefinition, id: string, x: number, y: number): BtDefinition {const next = clone(def);- const n = find(next.root, id);+ const n = find(next, id);if (!n) return def;n.x = x;n.y = y;@@ -138,7 +185,7 @@ export function moveBtNode(def: BtDefinition, id: string, x: number, y: number):/** Patch a node's fields (type/name/count/policy/seconds). Changing type clamps children to the new capacity. */export function setBtNodeField(def: BtDefinition, id: string, patch: Partial<BtNode>): BtDefinition {const next = clone(def);- const n = find(next.root, id);+ const n = find(next, id);if (!n) return def;Object.assign(n, patch);if (patch.type) {@@ -150,19 +197,29 @@ export function setBtNodeField(def: BtDefinition, id: string, patch: Partial<BtN}/**- * Reparent a subtree under a new parent (canvas drag-to-connect). No-ops on a- * cycle (new parent is a descendant), a full parent, or the root itself.+ * Reparent a subtree under a new parent (canvas drag-to-connect) — moves it out+ * of the orphan pool or from its current parent. No-ops on a cycle (new parent+ * is a descendant), a full parent, or the run root itself.*/export function reparentBtNode(def: BtDefinition, id: string, newParentId: string): BtDefinition {if (id === newParentId || def.root.id === id) return def;const next = clone(def);- const node = find(next.root, id);- const newParent = find(next.root, newParentId);+ const node = find(next, id);+ const newParent = find(next, newParentId);if (!node || !newParent) return def;- if (find(node, newParentId)) return def; // would create a cycle+ if (findInSubtree(node, newParentId)) return def; // would create a cycleif ((newParent.children?.length ?? 0) >= maxChildren(newParent.type)) return def;- const oldParent = findParent(next.root, id);- if (oldParent?.children) oldParent.children = oldParent.children.filter(c => c.id !== id);++ // Detach from wherever it currently lives. Set orphans to undefined (not+ // `delete`) when emptied so an Object.assign apply overwrites the stale array.+ if (isOrphanRoot(next, id)) {+ const rest = (next.orphans ?? []).filter(o => o.id !== id);+ next.orphans = rest.length ? rest : undefined;+ } else {+ const oldParent = findParent(next, id);+ if (!oldParent?.children) return def;+ oldParent.children = oldParent.children.filter(c => c.id !== id);+ }(newParent.children ??= []).push(node);return next;}diff --git a/sdk/src/ai/bt/index.ts b/sdk/src/ai/bt/index.tsindex 4341f3e00..e39b5d366 100644--- a/sdk/src/ai/bt/index.ts+++ b/sdk/src/ai/bt/index.ts@@ -15,6 +15,7 @@ export {maxChildren,canHaveChildren,addBtChild,+ addBtOrphan,removeBtNode,moveBtNode,setBtNodeField,diff --git a/sdk/src/ai/bt/types.ts b/sdk/src/ai/bt/types.tsindex 1aff0fb1a..56cb5c641 100644--- a/sdk/src/ai/bt/types.ts+++ b/sdk/src/ai/bt/types.ts@@ -38,4 +38,9 @@ export interface BtNode {export interface BtDefinition {root: BtNode;+ /**+ * Editor-only unconnected nodes/subtrees (created but not yet wired under+ * root). The interpreter ignores them — only `root` is ticked.+ */+ orphans?: BtNode[];}diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex 30353a90e..e23a75488 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -492,6 +492,7 @@ export {maxChildren,canHaveChildren,addBtChild,+ addBtOrphan,removeBtNode,moveBtNode,setBtNodeField,diff --git a/sdk/tests/bt-graph.test.ts b/sdk/tests/bt-graph.test.tsindex 757216158..3503934b4 100644--- a/sdk/tests/bt-graph.test.ts+++ b/sdk/tests/bt-graph.test.ts@@ -3,7 +3,7 @@import { describe, it, expect } from 'vitest';import {emptyBt, ensureBtIds, btNodes, btEdges, maxChildren, canHaveChildren,- addBtChild, removeBtNode, moveBtNode, setBtNodeField, reparentBtNode,+ addBtChild, addBtOrphan, removeBtNode, moveBtNode, setBtNodeField, reparentBtNode,} from '../src/ai/bt/btGraph';import type { BtDefinition } from '../src/ai/bt/types';@@ -96,6 +96,54 @@ describe('btGraph', () => {});});+describe('btGraph orphans', () => {+ it('adds an unconnected orphan node with no edge', () => {+ let def = emptyBt();+ def = addBtOrphan(def, 'action', 300, 100);+ expect(btNodes(def)).toHaveLength(2); // root + orphan+ expect(btEdges(def)).toHaveLength(0); // orphan is not connected+ expect(def.orphans).toHaveLength(1);+ });++ it('reparents an orphan into the tree and empties the pool', () => {+ let def = emptyBt(); // selector root n0+ def = addBtOrphan(def, 'sequence', 300, 100);+ const orphanId = def.orphans![0].id!;+ def = reparentBtNode(def, orphanId, 'n0');+ expect(def.orphans).toBeUndefined();+ expect(btEdges(def).map(e => e.id)).toEqual([`n0->${orphanId}`]);+ });++ it('removes an orphan', () => {+ let def = emptyBt();+ def = addBtOrphan(def, 'action');+ const id = def.orphans![0].id!;+ def = removeBtNode(def, id);+ expect(def.orphans).toBeUndefined();+ expect(btNodes(def)).toHaveLength(1);+ });++ it('moves and edits an orphan like any node', () => {+ let def = addBtOrphan(emptyBt(), 'wait');+ const id = def.orphans![0].id!;+ def = moveBtNode(def, id, 400, 200);+ def = setBtNodeField(def, id, { seconds: 1.5 });+ const o = def.orphans![0];+ expect(o).toMatchObject({ x: 400, y: 200, seconds: 1.5 });+ });++ it('clears orphans as undefined so an Object.assign apply leaves no duplicate node', () => {+ let def = addBtOrphan(emptyBt(), 'action');+ const orphanId = def.orphans![0].id!;+ // Reproduce the editor's `Object.assign(draft, op(draft))` apply path.+ const draft = JSON.parse(JSON.stringify(def)) as typeof def; // draft has orphans=[orphanId]+ Object.assign(draft, reparentBtNode(draft, orphanId, 'n0'));+ expect(draft.orphans).toBeUndefined(); // stale array overwritten, not left behind+ const ids = btNodes(draft).map(n => n.id);+ expect(new Set(ids).size).toBe(ids.length); // all ids unique — no duplicate key+ });+});+// Local helper mirroring btGraph's private find, for assertions.function find(def: BtDefinition, id: string): import('../src/ai/bt/types').BtNode | null {const stack = [def.root];