diff --git a/README.md b/README.md index 582b5688..59710ec8 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ npm run build # writes dist/ and regenerates index.html; the folder is wh The browser suite and the three example games need a machine with a GPU: ```bash -node tools/seed-e2e.mjs && node tools/e2e.mjs # the editor, 1676 checks (GM_STEPS=20 for one step) +node tools/seed-e2e.mjs && node tools/e2e.mjs # the editor, 1680 checks (GM_STEPS=20 for one step) # every tool signs in first – see the Accounts page node tools/seed-jumprun.mjs && node tools/smoke-jumprun.mjs node tools/seed-tetris.mjs && node tools/smoke-tetris.mjs diff --git a/benchmark/engine-prompt.md b/benchmark/engine-prompt.md index 3b395197..a1a430a2 100644 --- a/benchmark/engine-prompt.md +++ b/benchmark/engine-prompt.md @@ -205,7 +205,7 @@ A variable, a struct field or a list item is one of: number, text, boolean, colo Implement all of these. Names are the palette names. - **Events:** `On start`, `On enable`, `On update` (outputs `dt`), `On disable`, `On destroy`, `On key down` (with optional auto-repeat: delay and interval in ms), `On key up`, `On key held`, `On timer` (interval; output `late`), `On collision enter` / `stay` / `exit` (outputs `other`, `other collider`, `collider`, and for enter/stay `normal x/y`, `impulse`, `point x/y`), `On click`, `On mouse wheel`, `On animation finished`, `On state entered`, `On state exited`. Keys ignore case. -- **Flow:** `Branch`, `Sequence` (grows an output whenever the last one is connected), `Repeat` (`index`, `body`, `done`), `For each` (`item`, `index`, a `break` input read before every round, `done`), `Run behavior`, `Start` and `End` (declare the inputs and outputs of a behavior that is called), `State branch`, `Set state`, `Set state by name`, `State transition`. +- **Flow:** `Branch`, `Sequence` (grows an output whenever the last one is connected), `Repeat` (`index`, `body`, `done`), `For each` (`item`, `index`, a `break` input read before every round, `done`), `Run behavior`, `Start` and `End` (declare the inputs and outputs of a behavior that is called, values and further flow ports alike), `State branch`, `Set state`, `Set state by name`, `State transition`. - **Objects:** `Self`, `Owner`, `Parent`, `Object by name`, `Child by name` (nearest level first), `Objects by name`, `Children` (optionally recursive), `Children by name`, `Objects of asset`, `Name of`, `Is asset`, `Is enabled`, `Get position` (local and world). - **Values:** `Variables`, `Properties`, the literals `Number`, `Text`, `Boolean`, `Texture`, `State machine`, `Sound`, `Scene`, `Animation`, `Asset`. - **Math and logic:** `Add`, `Subtract`, `Multiply`, `Divide` (by 0 gives 0), `Modulo`, `Min`, `Max`, `Abs`, `Sqrt`, `Clamp`, `Floor`, `Ceil`, `Round`, `Lerp` (with ease: Linear, In, Out, In-out, or a curve asset), `Random`, `Length`, `Distance`, `Normalize`, `Compare`, `Equals`, `And`, `Or`, `Not`, `Select`, `First not empty`, `Time`. `Compare` and `Equals` treat two numbers as equal up to a relative 1e-9. @@ -223,7 +223,9 @@ Two nodes carry most graphs and deserve care: ### 8.5 Calling a behavior -`Run behavior` runs another behavior as one step. The inputs declared on the callee's `Start` node become input ports of the call, the outputs declared on its `End` node become output ports. A call is synchronous and isolated: the callee runs with a fresh copy of its variable defaults and its own data cache, and values travel only through the ports. A variable of the callee marked **Keep** instead resumes from where the last call from the same node on the same object left it. A behavior calling itself raises an error. Double-clicking a call node opens the callee, with a breadcrumb back. Dragging a behavior asset onto a graph creates a call. Renaming or removing a declared port updates every caller. +`Run behavior` runs another behavior as one step. The inputs declared on the callee's `Start` node become input ports of the call, the outputs declared on its `End` node become output ports. A call is synchronous and isolated: the callee runs with a fresh copy of its variable defaults and its own data cache, and values travel only through the ports. A variable of the callee marked **Keep** instead resumes from where the last call from the same node on the same object left it. A behavior calling itself raises an error. Double-clicking a call node opens the callee, with a breadcrumb back. Dragging a behavior asset onto a graph creates a call. Renaming or removing a declared port updates every caller. A port declared on `Start` or `End` may be of the kind **Flow**: on `Start` it is a further flow input of the call, and a call arriving there begins at the `Start` output of that name only; on `End` it is a further flow output, and the call continues first through the one its `End` was reached by last, then through its plain `exec`, which always fires. + +`On behavior` is the same behavior used as an event. The node has no flow input; the behavior it names runs at the node for as long as the surrounding behavior does, with all of its own events firing and its own variables, timers and local state machines, one set per node. Whenever one of its flows reaches its `End`, the node fires through the output named like the flow input reached last (the plain `exec` only when `End` was reached by `exec`), carrying the values `End` was handed. The value inputs of `Start` are inputs of the node, read anew for every inner flow. Behaviors may listen to each other to any depth; a behavior listening to itself, directly or through others, is reported on the node and not started again. Inside a behavior that is run as a call, `On behavior` stays silent. ### 8.6 Lifecycle and event order diff --git a/src/core/commands/portCommands.ts b/src/core/commands/portCommands.ts index 1110539d..84695405 100644 --- a/src/core/commands/portCommands.ts +++ b/src/core/commands/portCommands.ts @@ -9,11 +9,12 @@ import { type Graph, type GraphEdge, type GraphNode, + isFlowPort, isTerminalNode, isValidPortName, + namesBehavior, OBJECT_BEHAVIOR_PARAM, propertyTargetOf, - RUN_BEHAVIOR, variablesSourceOf, } from '../graph'; import type { PropertyValue } from '../model/Properties'; @@ -32,8 +33,9 @@ interface PortSite { /** * Where a change to `node`'s declaration has to be mirrored. For most nodes that is the node - * itself. A behavior's terminal is the exception: its ports are also ports of every node calling - * the behavior – facing the other way, because what a start node hands out the caller passes in. + * itself. A behavior's terminal is the exception: its ports are also ports of every node running or + * hearing the behavior – facing the other way, because what a start node hands out the caller passes in. + * A node that has no such port (an `On behavior` and a flow port of the start) has no edges on it either. */ function portSites(project: Project, assetId: string, node: GraphNode): PortSite[] { const sites = ownSites(requireBehavior(project, assetId).graph, node); @@ -41,7 +43,7 @@ function portSites(project: Project, assetId: string, node: GraphNode): PortSite for (const other of project.assets) { if (other.type !== 'behavior') continue; for (const caller of other.graph.nodes) { - if (caller.type !== RUN_BEHAVIOR || caller.params[BEHAVIOR_PARAM] !== assetId) continue; + if (!namesBehavior(caller.type) || caller.params[BEHAVIOR_PARAM] !== assetId) continue; sites.push({ graph: other.graph, nodeId: caller.id, asInput: node.type === BEHAVIOR_START }); } } @@ -135,6 +137,8 @@ export class AddPortsCommand implements Command { const keys = new Set((node.ports ?? []).map((p) => p.key)); for (const port of this.ports) { checkPortName(node, port.key); + if (isFlowPort(port) && !isTerminalNode(node)) + throw new CommandError('Only a start or an end node declares a flow port'); if (keys.has(port.key)) throw new CommandError(`"${port.key}" already exists`); keys.add(port.key); } diff --git a/src/core/graph/GraphInterpreter.ts b/src/core/graph/GraphInterpreter.ts index d7d4a3fa..efd4ce6a 100644 --- a/src/core/graph/GraphInterpreter.ts +++ b/src/core/graph/GraphInterpreter.ts @@ -2,7 +2,7 @@ import { blockProblem, findMode, MATCH_INPUT, matchOf, searchOutcome, stopsAtHit import type { Graph, GraphNode } from './Graph'; import { type GraphCache, type GraphIndex, searchingIndex } from './graphIndex'; import { type GraphLookup, NO_LOOKUP } from './lookup'; -import { BEHAVIOR_END, callEntries, terminalNode } from './nested'; +import { BEHAVIOR_END, BEHAVIOR_START, callEntries } from './nested'; import { fieldValue, splitField, withSplitValues } from './portSplits'; import type { PropertyBag, PropertyValue } from '../model/Properties'; import type { NodeContext } from './NodeContext'; @@ -41,6 +41,14 @@ interface Frame { index: GraphIndex; outputCache: Map>; dataCache: Map>; + /** The flow input this graph's end node was reached by last, once it was reached at all (#294). */ + ended?: string; +} + +/** How a graph was left: through which flow input of its end node, and with what. */ +export interface Ending { + port: string; + values: Record; } /** @@ -83,6 +91,11 @@ export class GraphInterpreter { private callSites: string[] = []; private steps = 0; trace: TraceListener | null = null; + /** + * What the start node hands out while this graph runs on its own events and not as a call: the + * inputs of the `On behavior` node listening to it (#294). Set by whoever sends the pulses. + */ + given: Record | null = null; constructor( readonly graph: Graph, @@ -101,6 +114,14 @@ export class GraphInterpreter { return { graph, index: this.indexOf(graph), outputCache: new Map(), dataCache: new Map() }; } + /** A frame of the graph itself, its start node holding what was given from outside. */ + private ownFrame(): Frame { + const frame = this.emptyFrame(this.graph); + const start = this.given ? frame.index.ofType(BEHAVIOR_START)[0] : undefined; + if (start && this.given) frame.outputCache.set(start.id, { ...this.given }); + return frame; + } + eventNodes(type: string): readonly GraphNode[] { return this.indexOf(this.graph).ofType(type); } @@ -110,7 +131,7 @@ export class GraphInterpreter { * through – a state event names one. */ pulse(node: GraphNode, ctx: NodeContext, outputs: Record = {}, port = 'exec'): void { - this.frame = this.emptyFrame(this.graph); + this.frame = this.ownFrame(); this.callStack = []; this.callSites = []; this.steps = 0; @@ -125,12 +146,30 @@ export class GraphInterpreter { * the node at all (#160). Null for an input the node does not have. */ eventInput(node: GraphNode, key: string, ctx: NodeContext): Value { - this.frame = this.emptyFrame(this.graph); + this.frame = this.ownFrame(); this.steps = 0; const port = this.def(node)?.inputs.find((p) => p.key === key); return port ? this.inputValue(node, port, ctx) : null; } + /** Every data input of an event node, read ahead of a pulse like `eventInput`. */ + eventInputs(node: GraphNode, ctx: NodeContext): Record { + this.frame = this.ownFrame(); + this.steps = 0; + return this.collectInputs(node, ctx); + } + + /** How the last pulse left this graph, or null when it never reached the end node. */ + get ending(): Ending | null { + return this.endingOf(this.frame); + } + + private endingOf(frame: Frame): Ending | null { + if (frame.ended === undefined) return null; + const end = frame.index.ofType(BEHAVIOR_END)[0]; + return { port: frame.ended, values: (end && frame.outputCache.get(end.id)) ?? {} }; + } + /** * The `On state entered` / `On state exited` nodes watching one machine. A node whose machine * input carries a running value rather than a pick has no state outputs at all, so it is never @@ -161,30 +200,33 @@ export class GraphInterpreter { if (!def?.run) return; const inputs = this.collectInputs(node, ctx); const result = def.run(ctx, inputs, node.params, def, entry, this.lookup); - const returned = result.call ? this.call(result.call, node.id, ctx, depth) : {}; - const produced = { ...result.outputs, ...returned }; + const returned = result.call ? this.call(result.call, node.id, ctx, depth) : null; + const produced = { ...result.outputs, ...returned?.values }; + if (node.type === BEHAVIOR_END) this.frame.ended = entry; if (!def.read) this.frame.outputCache.set(node.id, produced); this.trace?.onNode(node.id); if (this.trace?.onValues) this.record(node.id, def.read ? this.readAll(node, def, ctx) : produced); if (result.repeat) this.loop(node, result.repeat, ctx, depth); if (result.find) this.search(node, result.find, ctx, depth); const next = result.next === undefined ? [] : Array.isArray(result.next) ? result.next : [result.next]; - for (const port of next) this.follow(node, port, ctx, depth); + // The way out the called graph took comes first, so `exec` reads as "and then" (#294). + const ways = returned && returned.port !== 'exec' ? [returned.port, ...next] : next; + for (const port of ways) this.follow(node, port, ctx, depth); } /** * Runs another behavior from its start node (or, lacking one, its `On start` nodes) to its end - * node and returns what the end node was handed. The nested graph gets its own frame and a fresh + * node and returns how it was left; null when it never got there. The nested graph gets its own frame and a fresh * copy of its variable defaults, so it is a call and not an inlining: nothing of it survives the * return but the values it hands back – and the variables it keeps, which wait for the next call * from the same site. */ - private call(call: CallResult, site: string, ctx: NodeContext, depth: number): Record { + private call(call: CallResult, site: string, ctx: NodeContext, depth: number): Ending | null { const program = this.lookup.behavior(call.behaviorId); - if (!program) return {}; + if (!program) return null; if (this.callStack.includes(call.behaviorId)) throw new Error(`Behavior "${program.name}" runs itself`); const entries = callEntries(program.graph); - if (entries.length === 0) return {}; + if (entries.length === 0) return null; const sites = [...this.callSites, site].join('/'); const kept = program.kept ?? []; const variables = resumedVariables(program.defaults, this.keptCalls.get(sites), kept); @@ -212,10 +254,9 @@ export class GraphInterpreter { try { for (const entry of entries) { this.trace?.onNode(entry.id); - this.follow(entry, 'exec', inner, depth + 1); + this.follow(entry, call.entry, inner, depth + 1); } - const end = terminalNode(program.graph, BEHAVIOR_END); - return (end && this.frame.outputCache.get(end.id)) ?? {}; + return this.endingOf(this.frame); } finally { this.callStack.pop(); this.callSites.pop(); diff --git a/src/core/graph/NodeRegistry.ts b/src/core/graph/NodeRegistry.ts index 56b0107b..ac1c94c9 100644 --- a/src/core/graph/NodeRegistry.ts +++ b/src/core/graph/NodeRegistry.ts @@ -61,6 +61,8 @@ export interface RepeatResult { export interface CallResult { behaviorId: string; inputs: Record; + /** The flow input the call came in by, which is the output its start node leaves through (#294). */ + entry: string; } export interface RunResult { diff --git a/src/core/graph/nested.ts b/src/core/graph/nested.ts index 85c3aacc..ed9d1a0c 100644 --- a/src/core/graph/nested.ts +++ b/src/core/graph/nested.ts @@ -20,6 +20,7 @@ import { agreedType, type SharedPortGroup } from './portTypes'; export const BEHAVIOR_START = 'BehaviorStart'; export const BEHAVIOR_END = 'BehaviorEnd'; export const RUN_BEHAVIOR = 'RunBehavior'; +export const ON_BEHAVIOR = 'OnBehavior'; export const VARIABLES = 'Variables'; export const PROPERTIES = 'Properties'; const ON_START = 'OnStart'; @@ -123,6 +124,16 @@ export function isTerminalNode(node: GraphNode): boolean { return isTerminalType(node.type); } +/** The two nodes that stand for another behavior: the one running it, the one listening to it (#294). */ +export function namesBehavior(type: string): boolean { + return type === RUN_BEHAVIOR || type === ON_BEHAVIOR; +} + +/** A further flow port of a start or end node, next to its fixed `exec` (#294). */ +export function isFlowPort(port: DeclaredPort): boolean { + return port.kind === 'flow'; +} + /** * A tagged kind is one the value cannot show, so its port carries the field that edits it – except * an object, which nothing can type in. @@ -324,6 +335,7 @@ export function ghostProblem(node: GraphNode, graph: Graph, def: NodeDef): strin * `Lerp` depends on another asset as well, the curve it eases along (#247), and says so here too. */ export function callProblem(node: GraphNode, lookup: GraphLookup, ownerId = ''): string | null { + if (node.type === ON_BEHAVIOR) return listenProblem(node, lookup, ownerId); if (node.type !== RUN_BEHAVIOR) return lerpProblem(node, lookup); const id = textOf(node.params[BEHAVIOR_PARAM] ?? ''); if (!id) return 'No behavior picked'; @@ -334,6 +346,39 @@ export function callProblem(node: GraphNode, lookup: GraphLookup, ownerId = ''): return null; } +/** Why an `On behavior` never fires: it hears nothing, itself, or a graph without an end to reach. */ +function listenProblem(node: GraphNode, lookup: GraphLookup, ownerId: string): string | null { + const id = textOf(node.params[BEHAVIOR_PARAM] ?? ''); + if (!id) return 'No behavior picked'; + const program = lookup.behavior(id); + if (!program) return 'That behavior is gone'; + if (ownerId && listensTo(lookup, id, ownerId)) return 'A behavior cannot listen to itself'; + if (!terminalNode(program.graph, BEHAVIOR_END)) return 'No End node – never fires'; + return null; +} + +/** The behaviors the `On behavior` nodes of that graph name, picked or not found alike. */ +export function heardBehaviors(graph: Graph): string[] { + return graph.nodes + .filter((n) => n.type === ON_BEHAVIOR) + .map((n) => textOf(n.params[BEHAVIOR_PARAM] ?? '')) + .filter((id) => id !== ''); +} + +/** Whether `from` is `target` or hears it, however many behaviors lie between. */ +export function listensTo( + lookup: GraphLookup, + from: string, + target: string, + seen: Set = new Set(), +): boolean { + if (from === target) return true; + if (seen.has(from)) return false; + seen.add(from); + const program = lookup.behavior(from); + return program ? heardBehaviors(program.graph).some((id) => listensTo(lookup, id, target, seen)) : false; +} + /** * Everything that changes how a node looks, as one string. Views and the inspector rebuild when it * changes – a port list that is derived rather than fixed has no other way of being noticed. diff --git a/src/core/graph/nodes/events/OnBehavior.ts b/src/core/graph/nodes/events/OnBehavior.ts new file mode 100644 index 00000000..10af1ac7 --- /dev/null +++ b/src/core/graph/nodes/events/OnBehavior.ts @@ -0,0 +1,32 @@ +import type { NodeDef } from '../../NodeRegistry'; +import { textOf } from '../../../model/Properties'; +import { BEHAVIOR_END, BEHAVIOR_PARAM, BEHAVIOR_START, declaredPorts, ON_BEHAVIOR } from '../../nested'; +import { exec } from '../shared'; + +/** + * Another behavior used as an event (#294): it lives at this node for as long as the behavior around + * it runs, its own events fire, and each of its pulses that reaches its end node goes on here. The + * running game keeps that second behavior; the interpreter only ever sees the pulse arriving. + */ +export const OnBehavior: NodeDef = { + type: ON_BEHAVIOR, + label: 'On behavior', + category: 'event', + description: + 'Listens to another behavior. That behavior runs here with its own events and variables, and ' + + 'whenever one of its flows reaches its End, this node fires: through the output named like ' + + 'the flow port the End was reached by last, with the values the End was handed. The inputs ' + + 'are what its Start hands out.', + inputs: [], + outputs: [exec()], + params: [{ key: BEHAVIOR_PARAM, label: 'Behavior', kind: 'asset', default: '', assetTypes: ['behavior'] }], + derivePorts: ({ node, lookup }) => { + const program = lookup.behavior(textOf(node.params[BEHAVIOR_PARAM] ?? '')); + return { + label: program ? `On ${program.name}` : undefined, + // No flow in: the behavior starts its own pulses, so the ways into its Start have no use here. + inputs: declaredPorts(program?.graph, BEHAVIOR_START).filter((port) => port.type !== 'exec'), + outputs: declaredPorts(program?.graph, BEHAVIOR_END), + }; + }, +}; diff --git a/src/core/graph/nodes/flow/BehaviorEnd.ts b/src/core/graph/nodes/flow/BehaviorEnd.ts index 94377f7e..7821439b 100644 --- a/src/core/graph/nodes/flow/BehaviorEnd.ts +++ b/src/core/graph/nodes/flow/BehaviorEnd.ts @@ -13,7 +13,8 @@ export const BehaviorEnd: NodeDef = { category: 'flow', description: 'Ends this behavior and hands its results back to the graph that ran it. Every output declared ' + - 'here becomes an output port on that node.', + 'here becomes an output port on that node. An output of the kind Flow is a further way out: ' + + 'the node that ran or hears this behavior goes on through the one reached last.', inputs: [exec()], outputs: [], params: [], diff --git a/src/core/graph/nodes/flow/BehaviorStart.ts b/src/core/graph/nodes/flow/BehaviorStart.ts index 16908e28..345cbf1c 100644 --- a/src/core/graph/nodes/flow/BehaviorStart.ts +++ b/src/core/graph/nodes/flow/BehaviorStart.ts @@ -12,7 +12,8 @@ export const BehaviorStart: NodeDef = { category: 'event', description: 'Where this behavior begins when another graph runs it as a node. Every input declared here ' + - 'becomes an input port on that node.', + 'becomes an input port on that node. An input of the kind Flow is a further way in: a call ' + + 'arriving through it leaves here through the output of that name and not through the plain one.', inputs: [], outputs: [exec()], params: [], diff --git a/src/core/graph/nodes/flow/RunBehavior.ts b/src/core/graph/nodes/flow/RunBehavior.ts index f89339ff..302ffdd7 100644 --- a/src/core/graph/nodes/flow/RunBehavior.ts +++ b/src/core/graph/nodes/flow/RunBehavior.ts @@ -16,7 +16,9 @@ export const RunBehavior: NodeDef = { 'Runs another behavior as a step of this one, passing values in and taking results out. It ' + 'begins at the Behavior start node, or at On start if that behavior has none. A ' + 'variable marked Keep in that behavior carries on from the last call of this node on this ' + - 'object; the others start at their defaults every time.', + 'object; the others start at their defaults every time. A flow port declared at that ' + + "behavior's Start is a further way in, one declared at its End a further way out: the " + + 'call leaves through the one its End was reached by last, and then through the plain one.', inputs: [exec()], outputs: [exec()], params: [{ key: BEHAVIOR_PARAM, label: 'Behavior', kind: 'asset', default: '', assetTypes: ['behavior'] }], @@ -29,8 +31,8 @@ export const RunBehavior: NodeDef = { outputs: declaredPorts(program?.graph, BEHAVIOR_END), }; }, - run: (_ctx, inputs, params) => ({ - call: { behaviorId: textOf(params[BEHAVIOR_PARAM] ?? ''), inputs }, + run: (_ctx, inputs, params, _def, entry) => ({ + call: { behaviorId: textOf(params[BEHAVIOR_PARAM] ?? ''), inputs, entry }, next: 'exec', }), }; diff --git a/src/core/graph/nodes/index.ts b/src/core/graph/nodes/index.ts index 89b2afa5..d03b5455 100644 --- a/src/core/graph/nodes/index.ts +++ b/src/core/graph/nodes/index.ts @@ -106,6 +106,7 @@ import { SetItem } from './data/SetItem'; import { SubList } from './data/SubList'; import { TextureSize } from './data/TextureSize'; import { OnAnimationFinished } from './events/OnAnimationFinished'; +import { OnBehavior } from './events/OnBehavior'; import { OnClick } from './events/OnClick'; import { OnMouseWheel } from './events/OnMouseWheel'; import { OnCollisionEnter } from './events/OnCollisionEnter'; @@ -160,6 +161,7 @@ export const BUILT_IN_NODES: readonly NodeDef[] = [ OnClick, OnMouseWheel, OnAnimationFinished, + OnBehavior, OnStateEntered, OnStateExited, BehaviorStart, diff --git a/src/core/properties/kinds.ts b/src/core/properties/kinds.ts index 54e21295..bb56f960 100644 --- a/src/core/properties/kinds.ts +++ b/src/core/properties/kinds.ts @@ -176,6 +176,8 @@ export const KINDS = [ }, { kind: 'list', label: 'List', travels: 'list', variable: true, port: true }, { kind: 'struct', label: 'Struct', travels: 'struct', variable: true, port: true }, + /** No value at all: a start or end node declares a further flow port with it (#294). */ + { kind: 'flow', label: 'Flow', travels: 'exec', port: true }, // Schema-only kinds: a setting has them, nothing a user declares does. { kind: 'enum', label: 'Choice', travels: 'string', empty: '', coerce: text }, /** A keyboard key name (`KeyboardEvent.key`), captured by pressing it. */ diff --git a/src/editor/clipboard.ts b/src/editor/clipboard.ts index d57927b9..b833a12b 100644 --- a/src/editor/clipboard.ts +++ b/src/editor/clipboard.ts @@ -9,7 +9,7 @@ import { findNode, type GraphNode, nodeDef, - RUN_BEHAVIOR, + namesBehavior, } from '../core/graph'; import type { GraphAsset } from '../core/model/Asset'; import { type Clip, copyGraph, copyObjects, type GraphClip, type ObjectClip } from '../core/model/clipboard'; @@ -160,7 +160,7 @@ function fitsGraph(project: Project, asset: GraphAsset, node: GraphNode): boolea return paletteEntries(project, asset).some( (entry) => entry.def.type === node.type && - (node.type !== RUN_BEHAVIOR || entry.params[BEHAVIOR_PARAM] === node.params[BEHAVIOR_PARAM]), + (!namesBehavior(node.type) || entry.params[BEHAVIOR_PARAM] === node.params[BEHAVIOR_PARAM]), ); } diff --git a/src/editor/graph/GraphCanvas.ts b/src/editor/graph/GraphCanvas.ts index 9377935e..d36f12ee 100644 --- a/src/editor/graph/GraphCanvas.ts +++ b/src/editor/graph/GraphCanvas.ts @@ -17,6 +17,7 @@ import { type PortDef, type PortSide, resolveDef, + namesBehavior, RUN_BEHAVIOR, startStateOf, } from '../../core/graph'; @@ -627,7 +628,7 @@ export class GraphCanvas extends Widget { } private openCalledBehavior(node: GraphNode): boolean { - if (node.type !== RUN_BEHAVIOR) return false; + if (!namesBehavior(node.type)) return false; const id = textOf(node.params[BEHAVIOR_PARAM] ?? ''); const asset = id ? findAsset(this.state.project, id) : undefined; if (asset?.type !== 'behavior') return false; diff --git a/src/editor/graph/paletteEntries.ts b/src/editor/graph/paletteEntries.ts index 09b6c780..fe8c1e24 100644 --- a/src/editor/graph/paletteEntries.ts +++ b/src/editor/graph/paletteEntries.ts @@ -1,12 +1,15 @@ import { searchRank } from '../../ui/search'; import { allNodeDefs, + BEHAVIOR_END, BEHAVIOR_PARAM, createEmptyGraph, isTerminalType, + namesBehavior, nextStateName, type NodeCategory, type NodeDef, + ON_BEHAVIOR, resolveDef, RUN_BEHAVIOR, State, @@ -83,7 +86,8 @@ function filterEntry(find: NodeDef): PaletteEntry { * The node types offerable in `asset`'s graph. A state machine holds states and nothing else, each * new one named by its number; a shader holds shader nodes, its one Output dropping out once * placed. In a behavior, every other behavior appears under its own name instead of behind a - * generic "Run behavior", and the two terminals drop out once the graph has them. + * generic "Run behavior" – and once more as the event "On " if it has an End to be heard + * through (#294) –, and the two terminals drop out once the graph has them. */ export function paletteEntries(project: Project, asset: GraphAsset): PaletteEntry[] { if (asset.type === 'statemachine') { @@ -109,7 +113,7 @@ export function paletteEntries(project: Project, asset: GraphAsset): PaletteEntr } const entries: PaletteEntry[] = []; for (const def of allNodeDefs()) { - if (def.type === RUN_BEHAVIOR || def.category === 'state') continue; + if (namesBehavior(def.type) || def.category === 'state') continue; if (def.category === 'shader' || def.category === 'particles') continue; if (isTerminalType(def.type) && terminalNode(asset.graph, def.type)) continue; entries.push({ id: def.type, hint: def.category, def, params: {} }); @@ -121,8 +125,12 @@ export function paletteEntries(project: Project, asset: GraphAsset): PaletteEntr if (other.type !== 'behavior' || other.id === asset.id) continue; const params = { [BEHAVIOR_PARAM]: other.id }; // The entry is a preview of a node that sits in no graph yet, hence the empty one. - const def = resolveDef({ id: '', type: RUN_BEHAVIOR, x: 0, y: 0, params }, createEmptyGraph(), lookup); + const preview = (type: string) => + resolveDef({ id: '', type, x: 0, y: 0, params }, createEmptyGraph(), lookup); + const def = preview(RUN_BEHAVIOR); if (def) entries.push({ id: `${RUN_BEHAVIOR}:${other.id}`, hint: 'behavior', def, params }); + const heard = terminalNode(other.graph, BEHAVIOR_END) ? preview(ON_BEHAVIOR) : undefined; + if (heard) entries.push({ id: `${ON_BEHAVIOR}:${other.id}`, hint: 'event', def: heard, params }); } return entries; } diff --git a/src/editor/inspector/portSection.ts b/src/editor/inspector/portSection.ts index ff356830..a7082c0a 100644 --- a/src/editor/inspector/portSection.ts +++ b/src/editor/inspector/portSection.ts @@ -231,7 +231,9 @@ export function buildPortSection( if (noun === 'Field') addShapePicker(host, assetId, node, variables, header); const add = new Dropdown(`+ ${noun}`, { variant: 'ghost' }); add.onClick = () => { - const items = kindMenu(DECLARED_PORT_KINDS, (kind) => + // A further way in or out is a start or end node's to declare; a struct has fields only. + const kinds = DECLARED_PORT_KINDS.filter((kind) => kind !== 'flow' || noun !== 'Field'); + const items = kindMenu(kinds, (kind) => host.state.execute(new AddPortCommand(assetId, node.id, { key: nextPortName(node, base), kind })), ); new Menu(items).openBelow(add); @@ -246,8 +248,8 @@ export function buildPortSection( noun === 'Field' ? 'No fields yet. Every field added here becomes a port of the struct.' : onStart - ? 'No inputs yet. Every input added here becomes a port on the node that runs this behavior.' - : 'No outputs yet. Every output added here becomes a result of running this behavior.', + ? 'No inputs yet. Every input added here becomes a port on the node that runs this behavior; one of the kind Flow is a further way in.' + : 'No outputs yet. Every output added here becomes a result of running this behavior; one of the kind Flow is a further way out.', ); for (const port of ports) portRow(host, assetId, node, port, portNameField(host, assetId, node, port)); diff --git a/src/editor/panels/icons/kind-flow.svg b/src/editor/panels/icons/kind-flow.svg new file mode 100644 index 00000000..b270e3ae --- /dev/null +++ b/src/editor/panels/icons/kind-flow.svg @@ -0,0 +1,3 @@ + + + diff --git a/src/editor/panels/markIcons.ts b/src/editor/panels/markIcons.ts index a3c213f3..27faf806 100644 --- a/src/editor/panels/markIcons.ts +++ b/src/editor/panels/markIcons.ts @@ -13,6 +13,7 @@ import animation from './icons/kind-animation.svg?raw'; import asset from './icons/kind-asset.svg?raw'; import boolean from './icons/kind-boolean.svg?raw'; import color from './icons/kind-color.svg?raw'; +import flow from './icons/kind-flow.svg?raw'; import list from './icons/kind-list.svg?raw'; import object from './icons/kind-object.svg?raw'; import scene from './icons/kind-scene.svg?raw'; @@ -30,6 +31,7 @@ export const KIND_ICON_SVG: Partial> = { asset, boolean, color, + flow, list, object, scene, diff --git a/src/runtime/systems/BehaviorSystem.ts b/src/runtime/systems/BehaviorSystem.ts index 9dd8485f..91636d69 100644 --- a/src/runtime/systems/BehaviorSystem.ts +++ b/src/runtime/systems/BehaviorSystem.ts @@ -1,16 +1,19 @@ import { adoptDeclarations, asBoolean, + BEHAVIOR_PARAM, buildSharedState, carriedForward, declaredVariables, emptySharedState, type Graph, GraphInterpreter, + type GraphNode, hierarchyRanks, inEventOrder, isHandleEnabled, type NodeContext, + ON_BEHAVIOR, restartedAssets, restoreSaved, type SaveArea, @@ -356,6 +359,7 @@ export class BehaviorSystem implements System { this.instances.push(instance); born.add(instance); } + if (born.size > 0 || this.unranked) this.syncHeard(world, born); if (born.size > 0 || this.unranked) this.rank(world); const fresh = this.instances.filter((i) => born.has(i)); for (const instance of fresh) this.enterStartStates(instance, (starts ??= startStates(this.project))); @@ -365,6 +369,66 @@ export class BehaviorSystem implements System { this.flushStateChanges(); } + /** + * One further instance per `On behavior` node (#294), on the entity of the behavior holding it and + * for as long as that one runs – and so on down, since the behavior heard may listen in turn. An + * edit to a graph while it runs adds and drops them like objects coming and going. + */ + private syncHeard(world: World, born: Set): void { + const held = new Map(); + for (const instance of this.instances) { + const host = instance.host?.instance; + if (host) held.set(host, [...(held.get(host) ?? []), instance]); + } + const dropped: Instance[] = []; + const drop = (instance: Instance) => { + dropped.push(instance); + for (const below of held.get(instance) ?? []) drop(below); + }; + const visit = (host: Instance, chain: readonly string[]) => { + const below = held.get(host) ?? []; + const kept = new Set(); + for (const node of host.interpreter.eventNodes(ON_BEHAVIOR)) { + const behaviorId = textOf(node.params[BEHAVIOR_PARAM] ?? ''); + // A behavior hearing itself, however far round, would be built without end. + if (chain.includes(behaviorId) || !findAssetOf(this.project, behaviorId, 'behavior')) continue; + const heard = + below.find((i) => i.host?.nodeId === node.id && i.host.behaviorId === behaviorId) ?? + this.hear(host, node.id, behaviorId, world); + if (!heard) continue; + if (!below.includes(heard)) born.add(heard); + kept.add(heard); + visit(heard, [...chain, behaviorId]); + } + for (const instance of below) if (!kept.has(instance)) drop(instance); + }; + for (const instance of [...this.instances]) + if (!instance.host) visit(instance, [instance.entity.assetId]); + if (dropped.length === 0) return; + this.instances = this.instances.filter((i) => !dropped.includes(i)); + this.finish(dropped); + } + + /** A running copy of that behavior for one `On behavior` node, with variables of its own. */ + private hear(host: Instance, nodeId: string, behaviorId: string, world: World): Instance | null { + const lookup = graphLookup(this.project); + const program = lookup.behavior(behaviorId); + if (!program) return null; + const heard: Instance = { + entity: host.entity, + interpreter: new GraphInterpreter(program.graph, lookup, this.graphs), + trace: { edges: new Map(), nodes: new Map() }, + values: new Map(), + states: {}, + active: true, + host: { instance: host, nodeId, behaviorId }, + variables: structuredClone(program.defaults), + }; + this.listen(heard, world); + this.instances.push(heard); + return heard; + } + /** Has the instance note what it runs, timed by the world it runs in. */ private listen({ interpreter, trace, values }: Instance, world: World): void { interpreter.trace = { @@ -488,7 +552,8 @@ export class BehaviorSystem implements System { this.runPulses(pulsesOf(instances, 'OnDestroy'), contextOf); // After `On destroy`, not before: that graph may still say something, and a sound it wants to // outlive the object says so itself by being detached. - for (const instance of instances) this.audio.stopOwner(instance.entity.id); + // Its sounds are the entity's, so they end with the behavior placed there and not with one it hears. + for (const instance of instances) if (!instance.host) this.audio.stopOwner(instance.entity.id); } /** @@ -579,7 +644,7 @@ export class BehaviorSystem implements System { } runningIds(): string[] { - return this.instances.map((i) => i.entity.objectId); + return this.instances.filter((i) => !i.host).map((i) => i.entity.objectId); } /** @@ -594,7 +659,8 @@ export class BehaviorSystem implements System { const graph = findAssetOf(this.project, assetId, 'behavior')?.graph; const newest = new Map(); for (const instance of this.instances) { - if (instance.entity.assetId !== assetId && !instance.interpreter.calledBehaviors.has(assetId)) continue; + const own = instance.host?.behaviorId ?? instance.entity.assetId; + if (own !== assetId && !instance.interpreter.calledBehaviors.has(assetId)) continue; latest(merged.edges, instance.trace.edges); latest(merged.nodes, instance.trace.nodes); for (const [id, produced] of (graph && instance.values.get(graph)) ?? []) { @@ -617,7 +683,9 @@ export class BehaviorSystem implements System { for (const { instance, node, outputs, port } of inEventOrder(pulses)) { if (living && !world.entities.includes(instance.entity)) continue; try { + this.give(instance, contextOf); instance.interpreter.pulse(node, contextOf(instance), outputs, port); + this.surface(instance, contextOf); } catch (error) { world.log.push( `${ERROR_PREFIX} "${instance.entity.name}": ${error instanceof Error ? error.message : String(error)}`, @@ -627,6 +695,33 @@ export class BehaviorSystem implements System { } } + /** The `On behavior` node an instance is heard by, as the graph holds it now. */ + private hearing(instance: Instance): { host: Instance; node: GraphNode } | null { + const host = instance.host; + const node = host?.instance.interpreter.eventNodes(ON_BEHAVIOR).find((n) => n.id === host.nodeId); + return host && node ? { host: host.instance, node } : null; + } + + /** A heard behavior's start node hands out the inputs of the node hearing it, read anew for each pulse. */ + private give(instance: Instance, contextOf: (instance: Instance) => NodeContext): void { + const heard = this.hearing(instance); + if (heard) + instance.interpreter.given = heard.host.interpreter.eventInputs(heard.node, contextOf(heard.host)); + } + + /** + * A pulse of a heard behavior that reached its end node goes on at the node hearing it, through + * the output named like the way it took – and from there further up, if that graph ends in turn. + */ + private surface(instance: Instance, contextOf: (instance: Instance) => NodeContext): void { + for (let inner = instance; inner.host; inner = inner.host.instance) { + const ending = inner.interpreter.ending; + const heard = this.hearing(inner); + if (!ending || !heard) return; + heard.host.interpreter.pulse(heard.node, contextOf(heard.host), ending.values, ending.port); + } + } + /** One context per instance for as long as the answer is used – a frame, or one round of events. */ private contexts(world: World, dt: number): (instance: Instance) => NodeContext { const made = new Map(); diff --git a/src/runtime/systems/behaviorContext.ts b/src/runtime/systems/behaviorContext.ts index 7449a800..6f866eb8 100644 --- a/src/runtime/systems/behaviorContext.ts +++ b/src/runtime/systems/behaviorContext.ts @@ -52,7 +52,7 @@ export function behaviorContext( return { self: entity, owner: entity.parent, - variables: entity.props, + variables: instance.variables ?? entity.props, states, shared: run.shared, stateChanged: (machineId, from, to) => run.stateChanged(machineId, from, to), diff --git a/src/runtime/systems/behaviorPulses.ts b/src/runtime/systems/behaviorPulses.ts index 79f77d75..cf9567da 100644 --- a/src/runtime/systems/behaviorPulses.ts +++ b/src/runtime/systems/behaviorPulses.ts @@ -6,7 +6,7 @@ import { asNumber, type Graph, type GraphInterpreter, type GraphNode, type Value } from '../../core/graph'; import { stepKeyRepeat } from '../../core/graph/keyRepeat'; import { keyName } from '../../core/keys'; -import { textOf } from '../../core/model/Properties'; +import { type PropertyBag, textOf } from '../../core/model/Properties'; import { parentChain } from '../../core/model/walk'; import type { Entity } from '../Entity'; import type { AnimationSystem } from './AnimationSystem'; @@ -29,6 +29,13 @@ export interface Instance { states: Record; /** Whether the behavior was effectively on when last looked at; a change fires On enable/On disable. */ active: boolean; + /** + * Set on a behavior an `On behavior` node listens to (#294): it runs on the same entity as the + * one holding that node, which hears every pulse of it that reaches the end node. + */ + host?: { instance: Instance; nodeId: string; behaviorId: string }; + /** Its own variables, where it has a host; the entity's belong to the behavior placed on it. */ + variables?: PropertyBag; } /** One event node about to run for one instance: what the event hands it, and the output it leaves by. */ diff --git a/tests/core/event-order.test.ts b/tests/core/event-order.test.ts index 9a7635cf..40142688 100644 --- a/tests/core/event-order.test.ts +++ b/tests/core/event-order.test.ts @@ -12,6 +12,7 @@ import { AddNodeCommand, SetNodeParamCommand } from '../../src/core/commands/gra import { ReorderObjectCommand, SetOverrideCommand } from '../../src/core/commands/sceneObjectCommands'; import { BEHAVIOR_START, + ON_BEHAVIOR, EVENT_ORDER, eventOrder, type GraphNode, @@ -99,7 +100,10 @@ describe('the order rule', () => { }); it('gives every event node the setting, and leaves the row off the node at 0', () => { - const events = BUILT_IN_NODES.filter((def) => def.category === 'event' && def.type !== BEHAVIOR_START); + // `On behavior` fires inside a pulse of the behavior it hears, whose event nodes carry the order. + const events = BUILT_IN_NODES.filter( + (def) => def.category === 'event' && def.type !== BEHAVIOR_START && def.type !== ON_BEHAVIOR, + ); expect(events).toHaveLength(17); for (const def of events) { expect( diff --git a/tests/core/flow-ports.test.ts b/tests/core/flow-ports.test.ts new file mode 100644 index 00000000..d621a2dd --- /dev/null +++ b/tests/core/flow-ports.test.ts @@ -0,0 +1,327 @@ +/** + * Further flow ports at a behavior's start and end node (#294): a call comes in by one of several + * ways and leaves by the one its end node was reached through last, before going on along `exec`. + */ +import { describe, expect, it } from 'vitest'; +import { CommandError } from '../../src/core/commands/Command'; +import { AddPortCommand, RemovePortCommand, RenamePortCommand } from '../../src/core/commands/portCommands'; +import { + BEHAVIOR_END, + BEHAVIOR_PARAM, + BEHAVIOR_START, + type GraphNode, + GraphInterpreter, + resolveDef, + RUN_BEHAVIOR, +} from '../../src/core/graph'; +import type { BehaviorAsset } from '../../src/core/model/Asset'; +import { graphLookup } from '../../src/core/model/graphLookup'; +import { deserializeProject, serializeProject } from '../../src/core/store/serialize'; +import { fakeContext, fire, graphEditor, makeBehavior, makeProject, type ProjectFixture } from '../helpers'; + +interface Gate { + asset: BehaviorAsset; + start: GraphNode; + end: GraphNode; +} + +/** A behavior with the ways in `open` and `shut` and the ways out `yes` and `no`, wired by the test. */ +function gate(fixture: ProjectFixture, name = 'Gate'): Gate { + const asset = makeBehavior(fixture, name); + const edit = graphEditor(fixture, asset); + const start = edit.addNode(BEHAVIOR_START); + const end = edit.addNode(BEHAVIOR_END); + for (const key of ['open', 'shut']) + fixture.stack.execute(new AddPortCommand(asset.id, start.id, { key, kind: 'flow' })); + for (const key of ['yes', 'no']) + fixture.stack.execute(new AddPortCommand(asset.id, end.id, { key, kind: 'flow' })); + return { asset, start, end }; +} + +/** `On start → Gate`, entered by `entry`, with a Log on each of its outputs saying which one fired. */ +function caller(fixture: ProjectFixture, callee: BehaviorAsset, entry = 'exec'): BehaviorAsset { + const asset = makeBehavior(fixture, 'Caller'); + const edit = graphEditor(fixture, asset); + const call = edit.addNode(RUN_BEHAVIOR, { [BEHAVIOR_PARAM]: callee.id }); + edit.connect(edit.addNode('OnStart'), 'exec', call, entry); + for (const port of ['yes', 'no', 'exec']) + edit.connect(call, port, edit.addNode('Log', { message: port }), 'exec'); + return asset; +} + +function logsOf(fixture: ProjectFixture, asset: BehaviorAsset): string[] { + const ctx = fakeContext(); + fire(new GraphInterpreter(asset.graph, graphLookup(fixture.project)), 'OnStart', ctx); + return ctx.logs; +} + +describe('flow ports declared at a start and an end node', () => { + it('stand on both nodes and on the node running the behavior, flow first and facing the other way', () => { + const fixture = makeProject(); + const { asset, start, end } = gate(fixture); + fixture.stack.execute(new AddPortCommand(asset.id, start.id, { key: 'amount', kind: 'number' })); + fixture.stack.execute(new AddPortCommand(asset.id, start.id, { key: 'late', kind: 'flow' })); + const lookup = graphLookup(fixture.project); + const ports = (node: GraphNode, graph = asset.graph) => { + const def = resolveDef(node, graph, lookup)!; + const list = (side: typeof def.inputs) => side.map((p) => `${p.key}:${p.type}`); + return { inputs: list(def.inputs), outputs: list(def.outputs) }; + }; + expect(ports(start).outputs).toEqual([ + 'exec:exec', + 'open:exec', + 'shut:exec', + 'late:exec', + 'amount:number', + ]); + expect(ports(end).inputs).toEqual(['exec:exec', 'yes:exec', 'no:exec']); + + const outer = caller(fixture, asset); + const call = outer.graph.nodes.find((n) => n.type === RUN_BEHAVIOR)!; + expect(ports(call, outer.graph)).toEqual({ + inputs: ['exec:exec', 'open:exec', 'shut:exec', 'late:exec', 'amount:number'], + outputs: ['exec:exec', 'yes:exec', 'no:exec'], + }); + }); + + it('offer nothing to type in: a flow port has no value', () => { + const fixture = makeProject(); + const { asset } = gate(fixture); + const outer = caller(fixture, asset); + const call = outer.graph.nodes.find((n) => n.type === RUN_BEHAVIOR)!; + const def = resolveDef(call, outer.graph, graphLookup(fixture.project))!; + expect(def.inputs.filter((p) => p.field !== undefined)).toEqual([]); + }); + + it('share their names with the value ports, and never take `exec`', () => { + const fixture = makeProject(); + const { asset, end } = gate(fixture); + const add = (key: string) => + fixture.stack.execute(new AddPortCommand(asset.id, end.id, { key, kind: 'number' })); + expect(() => add('yes')).toThrow(CommandError); + expect(() => + fixture.stack.execute(new AddPortCommand(asset.id, end.id, { key: 'exec', kind: 'flow' })), + ).toThrow(CommandError); + }); + + it('belong to a start or an end node only', () => { + const fixture = makeProject(); + const asset = makeBehavior(fixture, 'Packs'); + const pack = graphEditor(fixture, asset).addNode('PackStruct'); + expect(() => + fixture.stack.execute(new AddPortCommand(asset.id, pack.id, { key: 'way', kind: 'flow' })), + ).toThrow('Only a start or an end node declares a flow port'); + }); + + it('survive saving and loading as flow ports', () => { + const fixture = makeProject(); + const { asset } = gate(fixture); + const loaded = deserializeProject(JSON.parse(JSON.stringify(serializeProject(fixture.project)))); + const again = loaded.assets.find((a) => a.id === asset.id) as BehaviorAsset; + const kinds = (type: string) => + again.graph.nodes.find((n) => n.type === type)?.ports?.map((p) => `${p.key}:${p.kind}`); + expect(kinds(BEHAVIOR_START)).toEqual(['open:flow', 'shut:flow']); + expect(kinds(BEHAVIOR_END)).toEqual(['yes:flow', 'no:flow']); + }); +}); + +describe('a call leaving through a flow port of the end node', () => { + it('fires that output first and `exec` after it', () => { + const fixture = makeProject(); + const { asset, start, end } = gate(fixture); + graphEditor(fixture, asset).connect(start, 'exec', end, 'yes'); + expect(logsOf(fixture, caller(fixture, asset))).toEqual(['yes', 'exec']); + }); + + it('fires only `exec` when the end was reached by its plain input', () => { + const fixture = makeProject(); + const { asset, start, end } = gate(fixture); + graphEditor(fixture, asset).connect(start, 'exec', end, 'exec'); + expect(logsOf(fixture, caller(fixture, asset))).toEqual(['exec']); + }); + + it('fires only `exec` when the end was never reached', () => { + const fixture = makeProject(); + const { asset } = gate(fixture); + expect(logsOf(fixture, caller(fixture, asset))).toEqual(['exec']); + }); + + it('takes the way reached last when one call reaches the end by several', () => { + const fixture = makeProject(); + const { asset, start, end } = gate(fixture); + const edit = graphEditor(fixture, asset); + const both = edit.addNode('Sequence'); + edit.wire([ + [start, 'exec', both, 'exec'], + [both, 'a', end, 'yes'], + [both, 'b', end, 'no'], + ]); + expect(logsOf(fixture, caller(fixture, asset))).toEqual(['no', 'exec']); + }); + + it('is back at `exec` alone when the plain input was reached after a named one', () => { + const fixture = makeProject(); + const { asset, start, end } = gate(fixture); + const edit = graphEditor(fixture, asset); + const both = edit.addNode('Sequence'); + edit.wire([ + [start, 'exec', both, 'exec'], + [both, 'a', end, 'yes'], + [both, 'b', end, 'exec'], + ]); + expect(logsOf(fixture, caller(fixture, asset))).toEqual(['exec']); + }); + + it('decides anew for every call, so a loop takes each round its own way', () => { + const fixture = makeProject(); + const { asset, start, end } = gate(fixture); + fixture.stack.execute(new AddPortCommand(asset.id, start.id, { key: 'round', kind: 'number' })); + const edit = graphEditor(fixture, asset); + const odd = edit.addNode('Compare', { op: '==', b: 1 }); + const branch = edit.addNode('Branch'); + edit.wire([ + [start, 'exec', branch, 'exec'], + [start, 'round', odd, 'a'], + [odd, 'result', branch, 'condition'], + [branch, 'then', end, 'yes'], + ]); + + const outer = makeBehavior(fixture, 'Caller'); + const oEdit = graphEditor(fixture, outer); + const repeat = oEdit.addNode('Repeat', { times: 3 }); + const call = oEdit.addNode(RUN_BEHAVIOR, { [BEHAVIOR_PARAM]: asset.id }); + oEdit.wire([ + [oEdit.addNode('OnStart'), 'exec', repeat, 'exec'], + [repeat, 'body', call, 'exec'], + [repeat, 'index', call, 'round'], + [call, 'yes', oEdit.addNode('Log', { message: 'yes' }), 'exec'], + [call, 'exec', oEdit.addNode('Log', { message: 'exec' }), 'exec'], + ]); + expect(logsOf(fixture, outer)).toEqual(['exec', 'yes', 'exec', 'exec']); + }); + + it('keeps the way an inner call took to that call', () => { + const fixture = makeProject(); + const inner = gate(fixture, 'Inner'); + graphEditor(fixture, inner.asset).connect(inner.start, 'exec', inner.end, 'yes'); + + const middle = gate(fixture, 'Middle'); + const mEdit = graphEditor(fixture, middle.asset); + const call = mEdit.addNode(RUN_BEHAVIOR, { [BEHAVIOR_PARAM]: inner.asset.id }); + mEdit.wire([ + [middle.start, 'exec', call, 'exec'], + [call, 'exec', middle.end, 'exec'], + ]); + expect(logsOf(fixture, caller(fixture, middle.asset))).toEqual(['exec']); + }); + + it('hands the values of the end node out whichever way was taken', () => { + const fixture = makeProject(); + const { asset, start, end } = gate(fixture); + fixture.stack.execute(new AddPortCommand(asset.id, end.id, { key: 'score', kind: 'number' })); + const edit = graphEditor(fixture, asset); + edit.connect(start, 'exec', end, 'no'); + edit.connect(edit.addNode('Number', { value: 7 }), 'value', end, 'score'); + + const outer = makeBehavior(fixture, 'Caller'); + const oEdit = graphEditor(fixture, outer); + const call = oEdit.addNode(RUN_BEHAVIOR, { [BEHAVIOR_PARAM]: asset.id }); + const log = oEdit.addNode('Log'); + oEdit.wire([ + [oEdit.addNode('OnStart'), 'exec', call, 'exec'], + [call, 'no', log, 'exec'], + [call, 'score', log, 'message'], + ]); + expect(logsOf(fixture, outer)).toEqual(['7']); + }); +}); + +describe('a call coming in by a flow port of the start node', () => { + function ways(fixture: ProjectFixture): Gate { + const g = gate(fixture); + const edit = graphEditor(fixture, g.asset); + for (const port of ['exec', 'open', 'shut']) + edit.connect(g.start, port, edit.addNode('Log', { message: `in ${port}` }), 'exec'); + return g; + } + + it('begins at the output of that name and nowhere else', () => { + const fixture = makeProject(); + expect(logsOf(fixture, caller(fixture, ways(fixture).asset, 'open'))).toEqual(['in open', 'exec']); + }); + + it('begins at the plain output when it came in by `exec`', () => { + const fixture = makeProject(); + expect(logsOf(fixture, caller(fixture, ways(fixture).asset, 'exec'))).toEqual(['in exec', 'exec']); + }); + + it('passes the same values in whichever way it came', () => { + const fixture = makeProject(); + const { asset, start } = gate(fixture); + fixture.stack.execute(new AddPortCommand(asset.id, start.id, { key: 'amount', kind: 'number' })); + const edit = graphEditor(fixture, asset); + const log = edit.addNode('Log'); + edit.connect(start, 'shut', log, 'exec'); + edit.connect(start, 'amount', log, 'message'); + + const outer = makeBehavior(fixture, 'Caller'); + const oEdit = graphEditor(fixture, outer); + const call = oEdit.addNode(RUN_BEHAVIOR, { [BEHAVIOR_PARAM]: asset.id, amount: 5 }); + oEdit.connect(oEdit.addNode('OnStart'), 'exec', call, 'shut'); + expect(logsOf(fixture, outer)).toEqual(['5']); + }); + + it('does nothing in a behavior without a start node, which has no such ways in', () => { + const fixture = makeProject(); + const asset = makeBehavior(fixture, 'Plain'); + const edit = graphEditor(fixture, asset); + edit.connect(edit.addNode('OnStart'), 'exec', edit.addNode('Log', { message: 'ran' }), 'exec'); + const outer = makeBehavior(fixture, 'Caller'); + const oEdit = graphEditor(fixture, outer); + const call = oEdit.addNode(RUN_BEHAVIOR, { [BEHAVIOR_PARAM]: asset.id }); + oEdit.connect(oEdit.addNode('OnStart'), 'exec', call, 'exec'); + expect(logsOf(fixture, outer)).toEqual(['ran']); + }); +}); + +describe('renaming and removing a flow port', () => { + it('takes the edges on the calling nodes along, and undo puts them back', () => { + const fixture = makeProject(); + const { asset, start, end } = gate(fixture); + graphEditor(fixture, asset).connect(start, 'open', end, 'yes'); + const outer = caller(fixture, asset, 'open'); + const onCall = () => + outer.graph.edges + .flatMap((e) => [e.from.port, e.to.port]) + .filter((port) => ['open', 'enter', 'yes', 'done'].includes(port)) + .sort(); + expect(onCall()).toEqual(['open', 'yes']); + + fixture.stack.execute(new RenamePortCommand(asset.id, start.id, 'open', 'enter')); + fixture.stack.execute(new RenamePortCommand(asset.id, end.id, 'yes', 'done')); + expect(onCall()).toEqual(['done', 'enter']); + // Still wired through: the call comes in and leaves by the renamed ports. + expect(logsOf(fixture, outer)).toEqual(['yes', 'exec']); + + fixture.stack.undo(); + fixture.stack.undo(); + expect(onCall()).toEqual(['open', 'yes']); + expect(logsOf(fixture, outer)).toEqual(['yes', 'exec']); + }); + + it('drops the edges on the calling nodes with the port, and undo brings them back', () => { + const fixture = makeProject(); + const { asset, start, end } = gate(fixture); + graphEditor(fixture, asset).connect(start, 'exec', end, 'yes'); + const outer = caller(fixture, asset); + const edges = outer.graph.edges.length; + + fixture.stack.execute(new RemovePortCommand(asset.id, end.id, 'yes')); + expect(outer.graph.edges).toHaveLength(edges - 1); + expect(logsOf(fixture, outer)).toEqual(['exec']); + + fixture.stack.undo(); + expect(outer.graph.edges).toHaveLength(edges); + expect(logsOf(fixture, outer)).toEqual(['yes', 'exec']); + }); +}); diff --git a/tests/core/node-catalog.test.ts b/tests/core/node-catalog.test.ts index 21bbe1e7..ddc14f92 100644 --- a/tests/core/node-catalog.test.ts +++ b/tests/core/node-catalog.test.ts @@ -178,12 +178,19 @@ const CASES: Record = { name: 'asks for the named behavior to run, passing its inputs on', inputs: { power: 3 }, params: { behavior: 'b1' }, - call: { behaviorId: 'b1', inputs: { power: 3 } }, + call: { behaviorId: 'b1', inputs: { power: 3 }, entry: 'exec' }, + next: 'exec', + }, + { + name: 'names the flow input the call came in by, so the start node leaves through that one', + params: { behavior: 'b1' }, + entry: 'open', + call: { behaviorId: 'b1', inputs: {}, entry: 'open' }, next: 'exec', }, { name: 'without a behavior chosen it still continues, calling nothing that exists', - call: { behaviorId: '', inputs: {} }, + call: { behaviorId: '', inputs: {}, entry: 'exec' }, next: 'exec', }, ], @@ -1883,6 +1890,7 @@ function eqNamesakes(): Record { */ const EVENT_NODES: Record = { BehaviorStart: 'nested-behavior.test.ts', + OnBehavior: 'on-behavior.test.ts', OnStart: 'graph.test.ts', OnEnable: 'behavior-events.test.ts', OnUpdate: 'graph.test.ts', diff --git a/tests/core/on-behavior.test.ts b/tests/core/on-behavior.test.ts new file mode 100644 index 00000000..addd6df0 --- /dev/null +++ b/tests/core/on-behavior.test.ts @@ -0,0 +1,475 @@ +/** + * `On behavior` (#294): another behavior used as an event. It lives at the node for as long as the + * behavior around it runs, its own events fire, and each of its pulses that reaches its end node + * goes on at the node hearing it. Driven through a real world, since the running game keeps it. + */ +import { describe, expect, it } from 'vitest'; +import { AddNodeCommand, RemoveNodeCommand } from '../../src/core/commands/graphCommands'; +import { AddPortCommand, RemovePortCommand, RenamePortCommand } from '../../src/core/commands/portCommands'; +import { + BEHAVIOR_END, + BEHAVIOR_PARAM, + BEHAVIOR_START, + callProblem, + type GraphNode, + ON_BEHAVIOR, + resolveDef, + RUN_BEHAVIOR, +} from '../../src/core/graph'; +import type { BehaviorAsset } from '../../src/core/model/Asset'; +import { graphLookup } from '../../src/core/model/graphLookup'; +import { + graphEditor, + makeBehavior, + makeSpriteScene, + place, + type ProjectFixture, + type SceneFixture, + startWorld, +} from '../helpers'; + +/** "Confirm": Space or Enter going down reaches the end node by its flow port `pressed`. */ +function confirm(f: ProjectFixture, name = 'Confirm'): { asset: BehaviorAsset; end: GraphNode } { + const asset = makeBehavior(f, name); + const edit = graphEditor(f, asset); + const end = edit.addNode(BEHAVIOR_END); + f.stack.execute(new AddPortCommand(asset.id, end.id, { key: 'pressed', kind: 'flow' })); + for (const key of [' ', 'Enter']) edit.connect(edit.addNode('OnKeyDown', { key }), 'exec', end, 'pressed'); + return { asset, end }; +} + +/** A behavior on a box hearing `heard`, with a Log on each named output of the node. */ +function hearing( + f: SceneFixture, + heard: BehaviorAsset, + outputs: readonly string[], + name = 'Player', +): { asset: BehaviorAsset; node: GraphNode; objectId: string } { + const asset = makeBehavior(f, name); + const edit = graphEditor(f, asset); + const node = edit.addNode(ON_BEHAVIOR, { [BEHAVIOR_PARAM]: heard.id }); + for (const port of outputs) + edit.connect(node, port, edit.addNode('Log', { message: `${name} ${port}` }), 'exec'); + const box = place(f, f.spriteId, { x: 0, y: 0 }); + return { asset, node, objectId: place(f, asset.id, { x: 0, y: 0 }, box) }; +} + +describe('On behavior', () => { + it('fires when an event of the behavior it hears reaches that behavior’s end node', () => { + const f = makeSpriteScene(); + hearing(f, confirm(f).asset, ['pressed', 'exec']); + const { world, input, frame } = startWorld(f, { behaviors: true }); + + frame(); + expect(world.log).toEqual([]); + + input.press('Enter'); + frame(); + expect(world.log).toEqual(['Player pressed']); + + input.release('Enter'); + input.press(' '); + frame(); + expect(world.log).toEqual(['Player pressed', 'Player pressed']); + }); + + it('stays silent for a pulse that does not reach the end node', () => { + const f = makeSpriteScene(); + const { asset } = confirm(f); + const edit = graphEditor(f, asset); + edit.connect(edit.addNode('OnUpdate'), 'exec', edit.addNode('Log', { message: 'inner update' }), 'exec'); + hearing(f, asset, ['pressed', 'exec']); + const { world, frame } = startWorld(f, { behaviors: true }); + + frame(); + frame(); + expect(world.log).toEqual(['inner update', 'inner update']); + }); + + it('fires `exec` only when the end node was reached by its plain input', () => { + const f = makeSpriteScene(); + const { asset, end } = confirm(f); + const edit = graphEditor(f, asset); + edit.connect(edit.addNode('OnKeyDown', { key: 'x' }), 'exec', end, 'exec'); + hearing(f, asset, ['pressed', 'exec']); + const { world, input, frame } = startWorld(f, { behaviors: true }); + + input.press('x'); + frame(); + expect(world.log).toEqual(['Player exec']); + + input.press('Enter'); + frame(); + expect(world.log).toEqual(['Player exec', 'Player pressed']); + }); + + it('fires once, by the way reached last, when one pulse reaches the end node twice', () => { + const f = makeSpriteScene(); + const asset = makeBehavior(f, 'Twice'); + const edit = graphEditor(f, asset); + const end = edit.addNode(BEHAVIOR_END); + for (const key of ['first', 'second']) + f.stack.execute(new AddPortCommand(asset.id, end.id, { key, kind: 'flow' })); + const both = edit.addNode('Sequence'); + edit.wire([ + [edit.addNode('OnKeyDown', { key: 'a' }), 'exec', both, 'exec'], + [both, 'a', end, 'first'], + [both, 'b', end, 'second'], + ]); + hearing(f, asset, ['first', 'second', 'exec']); + const { world, input, frame } = startWorld(f, { behaviors: true }); + + input.press('a'); + frame(); + expect(world.log).toEqual(['Player second']); + }); + + it('has the outputs of the end node and the value inputs of the start node, under the behavior’s name', () => { + const f = makeSpriteScene(); + const { asset, end } = confirm(f); + const start = graphEditor(f, asset).addNode(BEHAVIOR_START); + f.stack.execute(new AddPortCommand(asset.id, start.id, { key: 'way', kind: 'flow' })); + f.stack.execute(new AddPortCommand(asset.id, start.id, { key: 'amount', kind: 'number' })); + f.stack.execute(new AddPortCommand(asset.id, end.id, { key: 'score', kind: 'number' })); + const { asset: outer, node } = hearing(f, asset, []); + const def = resolveDef(node, outer.graph, graphLookup(f.project))!; + expect(def.label).toBe('On Confirm'); + expect(def.category).toBe('event'); + expect(def.inputs.map((p) => `${p.key}:${p.type}`)).toEqual(['amount:number']); + expect(def.outputs.map((p) => `${p.key}:${p.type}`)).toEqual([ + 'exec:exec', + 'pressed:exec', + 'score:number', + ]); + }); + + it('hands its inputs to the start node, read anew for every pulse, and the end node’s values out', () => { + const f = makeSpriteScene(); + const asset = makeBehavior(f, 'Doubled'); + const edit = graphEditor(f, asset); + const start = edit.addNode(BEHAVIOR_START); + const end = edit.addNode(BEHAVIOR_END); + f.stack.execute(new AddPortCommand(asset.id, start.id, { key: 'amount', kind: 'number' })); + f.stack.execute(new AddPortCommand(asset.id, end.id, { key: 'twice', kind: 'number' })); + const times = edit.addNode('Multiply', { b: 2 }); + edit.wire([ + [edit.addNode('OnKeyDown', { key: 'a' }), 'exec', end, 'exec'], + [start, 'amount', times, 'a'], + [times, 'result', end, 'twice'], + ]); + + const outer = makeBehavior(f, 'Player', ['count']); + const oEdit = graphEditor(f, outer); + const node = oEdit.addNode(ON_BEHAVIOR, { [BEHAVIOR_PARAM]: asset.id }); + const log = oEdit.addNode('Log'); + const plus = oEdit.addNode('Add', { b: 1 }); + const set = oEdit.variables(['count'], { write: true }); + const get = oEdit.variables(['count']); + oEdit.wire([ + [get, 'count', node, 'amount'], + [node, 'exec', log, 'exec'], + [node, 'twice', log, 'message'], + [log, 'exec', set, 'exec'], + [get, 'count', plus, 'a'], + [plus, 'result', set, 'count'], + ]); + const box = place(f, f.spriteId, { x: 0, y: 0 }); + place(f, outer.id, { x: 0, y: 0 }, box); + const { world, input, frame } = startWorld(f, { behaviors: true }); + + for (let i = 0; i < 3; i++) { + input.press('a'); + frame(); + input.release('a'); + frame(); + } + expect(world.log).toEqual(['0', '2', '4']); + }); + + it('keeps the variables of the behavior it hears alive, one set per node', () => { + const f = makeSpriteScene(); + const asset = makeBehavior(f, 'Counter', ['count']); + const edit = graphEditor(f, asset); + const end = edit.addNode(BEHAVIOR_END); + f.stack.execute(new AddPortCommand(asset.id, end.id, { key: 'count', kind: 'number' })); + const plus = edit.addNode('Add', { b: 1 }); + const set = edit.variables(['count'], { write: true }); + const get = edit.variables(['count']); + edit.wire([ + [edit.addNode('OnKeyDown', { key: 'a' }), 'exec', set, 'exec'], + [get, 'count', plus, 'a'], + [plus, 'result', set, 'count'], + [set, 'exec', end, 'exec'], + [get, 'count', end, 'count'], + ]); + // Not kept from call to call: what holds the count here is the node it lives at. + asset.keptVariables = []; + + const outer = makeBehavior(f, 'Player', ['count']); + const oEdit = graphEditor(f, outer); + for (const name of ['one', 'two']) { + const node = oEdit.addNode(ON_BEHAVIOR, { [BEHAVIOR_PARAM]: asset.id }); + const say = oEdit.addNode('Join', { a: `${name} ` }); + const log = oEdit.addNode('Log'); + oEdit.wire([ + [node, 'exec', log, 'exec'], + [node, 'count', say, 'b'], + [say, 'text', log, 'message'], + ]); + } + const box = place(f, f.spriteId, { x: 0, y: 0 }); + const objectId = place(f, outer.id, { x: 0, y: 0 }, box); + const { world, input, frame } = startWorld(f, { behaviors: true }); + + for (let i = 0; i < 2; i++) { + input.press('a'); + frame(); + input.release('a'); + frame(); + } + expect(world.log).toEqual(['one 1', 'two 1', 'one 2', 'two 2']); + // The outer behavior's own variable of the same name is another one. + expect(world.entities.find((e) => e.objectId === objectId)?.props.count).toBe(0); + }); + + it('runs the lifecycle events of the behavior it hears in step with the one around it', () => { + const f = makeSpriteScene(); + const asset = makeBehavior(f, 'Life'); + const edit = graphEditor(f, asset); + const end = edit.addNode(BEHAVIOR_END); + for (const type of ['OnStart', 'OnEnable', 'OnDisable', 'OnDestroy']) { + f.stack.execute(new AddPortCommand(asset.id, end.id, { key: type, kind: 'flow' })); + edit.connect(edit.addNode(type), 'exec', end, type); + } + const { asset: outer } = hearing(f, asset, ['OnStart', 'OnEnable', 'OnDisable', 'OnDestroy']); + const oEdit = graphEditor(f, outer); + oEdit.connect(oEdit.addNode('OnStart'), 'exec', oEdit.addNode('Log', { message: 'own start' }), 'exec'); + const { world, frame } = startWorld(f, { behaviors: true }); + + frame(); + expect(world.log).toEqual(['own start', 'Player OnStart', 'Player OnEnable']); + world.destroy(); + expect(world.log.slice(3)).toEqual(['Player OnDisable', 'Player OnDestroy']); + }); + + it('hears a timer of that behavior', () => { + const f = makeSpriteScene(); + const asset = makeBehavior(f, 'Tick'); + const edit = graphEditor(f, asset); + edit.connect(edit.addNode('OnTimer', { interval: 0.5 }), 'exec', edit.addNode(BEHAVIOR_END), 'exec'); + hearing(f, asset, ['exec']); + const { world, frame } = startWorld(f, { behaviors: true }); + + frame(0.3); + expect(world.log).toEqual([]); + frame(0.3); + expect(world.log).toEqual(['Player exec']); + }); + + it('goes as deep as behaviors hear each other', () => { + const f = makeSpriteScene(); + const inner = confirm(f).asset; + const middle = makeBehavior(f, 'Menu'); + const mEdit = graphEditor(f, middle); + const end = mEdit.addNode(BEHAVIOR_END); + f.stack.execute(new AddPortCommand(middle.id, end.id, { key: 'chosen', kind: 'flow' })); + mEdit.connect(mEdit.addNode(ON_BEHAVIOR, { [BEHAVIOR_PARAM]: inner.id }), 'pressed', end, 'chosen'); + hearing(f, middle, ['chosen', 'exec']); + const { world, input, frame } = startWorld(f, { behaviors: true }); + + input.press('Enter'); + frame(); + expect(world.log).toEqual(['Player chosen']); + }); + + it('stays silent in a behavior that is run as a node, like every event there', () => { + const f = makeSpriteScene(); + const inner = confirm(f).asset; + const called = makeBehavior(f, 'Called'); + const cEdit = graphEditor(f, called); + cEdit.connect( + cEdit.addNode(ON_BEHAVIOR, { [BEHAVIOR_PARAM]: inner.id }), + 'pressed', + cEdit.addNode('Log', { message: 'heard in a call' }), + 'exec', + ); + cEdit.addNode(BEHAVIOR_START); + + const outer = makeBehavior(f, 'Player'); + const oEdit = graphEditor(f, outer); + oEdit.connect( + oEdit.addNode('OnUpdate'), + 'exec', + oEdit.addNode(RUN_BEHAVIOR, { [BEHAVIOR_PARAM]: called.id }), + 'exec', + ); + const box = place(f, f.spriteId, { x: 0, y: 0 }); + place(f, outer.id, { x: 0, y: 0 }, box); + const { world, input, frame } = startWorld(f, { behaviors: true }); + + input.press('Enter'); + frame(); + expect(world.log).toEqual([]); + }); + + it('does not count as a running behavior of its own', () => { + const f = makeSpriteScene(); + const { objectId } = hearing(f, confirm(f).asset, ['pressed']); + const { behaviors, frame } = startWorld(f, { behaviors: true }); + frame(); + expect(behaviors?.runningIds()).toEqual([objectId]); + }); + + it('lights up the graph of the behavior it hears', () => { + const f = makeSpriteScene(); + const { asset, end } = confirm(f); + hearing(f, asset, ['pressed']); + const { behaviors, input, frame } = startWorld(f, { behaviors: true }); + + frame(); + expect(behaviors?.traceFor(asset.id).nodes.has(end.id)).toBe(false); + input.press('Enter'); + frame(); + expect(behaviors?.traceFor(asset.id).nodes.has(end.id)).toBe(true); + }); +}); + +describe('On behavior while the graph is edited during a run', () => { + it('starts hearing a node added to the running graph, and stops hearing a removed one', () => { + const f = makeSpriteScene(); + const heard = confirm(f).asset; + const outer = makeBehavior(f, 'Player'); + const box = place(f, f.spriteId, { x: 0, y: 0 }); + place(f, outer.id, { x: 0, y: 0 }, box); + const { world, behaviors, input, frame } = startWorld(f, { behaviors: true }); + const tap = () => { + input.press('Enter'); + frame(); + input.release('Enter'); + frame(); + }; + + tap(); + expect(world.log).toEqual([]); + + const add = new AddNodeCommand(outer.id, ON_BEHAVIOR, 0, 0, { [BEHAVIOR_PARAM]: heard.id }); + f.stack.execute(add); + const edit = graphEditor(f, outer); + edit.connect(add.node, 'pressed', edit.addNode('Log', { message: 'heard' }), 'exec'); + behaviors?.syncFromModel(); + tap(); + expect(world.log).toEqual(['heard']); + + f.stack.execute(new RemoveNodeCommand(outer.id, add.node.id)); + behaviors?.syncFromModel(); + tap(); + expect(world.log).toEqual(['heard']); + }); + it('ends the behavior a removed node was hearing: it says goodbye and runs no more', () => { + const f = makeSpriteScene(); + const heard = makeBehavior(f, 'Chatty'); + const hEdit = graphEditor(f, heard); + hEdit.addNode(BEHAVIOR_END); + hEdit.connect( + hEdit.addNode('OnUpdate'), + 'exec', + hEdit.addNode('Log', { message: 'inner update' }), + 'exec', + ); + hEdit.connect(hEdit.addNode('OnDestroy'), 'exec', hEdit.addNode('Log', { message: 'inner bye' }), 'exec'); + const { asset: outer, node } = hearing(f, heard, []); + const { world, behaviors, frame } = startWorld(f, { behaviors: true }); + + frame(); + expect(world.log).toEqual(['inner update']); + + f.stack.execute(new RemoveNodeCommand(outer.id, node.id)); + behaviors?.syncFromModel(); + frame(); + frame(); + expect(world.log).toEqual(['inner update', 'inner bye']); + }); +}); + +describe('an On behavior node that cannot fire', () => { + const problemOf = (f: ProjectFixture, outer: BehaviorAsset, node: GraphNode) => + callProblem(node, graphLookup(f.project), outer.id); + + it('says so: nothing picked, the behavior gone, or no end node to be reached', () => { + const f = makeSpriteScene(); + const outer = makeBehavior(f, 'Player'); + const edit = graphEditor(f, outer); + expect(problemOf(f, outer, edit.addNode(ON_BEHAVIOR))).toBe('No behavior picked'); + expect(problemOf(f, outer, edit.addNode(ON_BEHAVIOR, { [BEHAVIOR_PARAM]: 'nope' }))).toBe( + 'That behavior is gone', + ); + const endless = makeBehavior(f, 'Endless'); + expect(problemOf(f, outer, edit.addNode(ON_BEHAVIOR, { [BEHAVIOR_PARAM]: endless.id }))).toBe( + 'No End node – never fires', + ); + expect( + problemOf(f, outer, edit.addNode(ON_BEHAVIOR, { [BEHAVIOR_PARAM]: confirm(f).asset.id })), + ).toBeNull(); + }); + + it('is reported for a behavior hearing itself, directly or through others, and such a circle does not run', () => { + const f = makeSpriteScene(); + const a = makeBehavior(f, 'A'); + const b = makeBehavior(f, 'B'); + const aEdit = graphEditor(f, a); + const bEdit = graphEditor(f, b); + const aEnd = aEdit.addNode(BEHAVIOR_END); + const bEnd = bEdit.addNode(BEHAVIOR_END); + const hearsB = aEdit.addNode(ON_BEHAVIOR, { [BEHAVIOR_PARAM]: b.id }); + const hearsA = bEdit.addNode(ON_BEHAVIOR, { [BEHAVIOR_PARAM]: a.id }); + const hearsSelf = aEdit.addNode(ON_BEHAVIOR, { [BEHAVIOR_PARAM]: a.id }); + aEdit.connect(hearsB, 'exec', aEnd, 'exec'); + bEdit.connect(hearsA, 'exec', bEnd, 'exec'); + bEdit.connect(bEdit.addNode('OnKeyDown', { key: 'a' }), 'exec', bEnd, 'exec'); + aEdit.connect(hearsB, 'exec', aEdit.addNode('Log', { message: 'A heard B' }), 'exec'); + + expect(problemOf(f, a, hearsB)).toBe('A behavior cannot listen to itself'); + expect(problemOf(f, b, hearsA)).toBe('A behavior cannot listen to itself'); + expect(problemOf(f, a, hearsSelf)).toBe('A behavior cannot listen to itself'); + + const box = place(f, f.spriteId, { x: 0, y: 0 }); + place(f, a.id, { x: 0, y: 0 }, box); + const { world, input, frame } = startWorld(f, { behaviors: true }); + input.press('a'); + frame(); + // B runs once below A; the A it names in turn is the one already running, so it is not built again. + expect(world.log).toEqual(['A heard B']); + expect(world.stopRequested).toBe(false); + }); +}); + +describe('the ports of an On behavior node follow the behavior it hears', () => { + it('keeps its edges through a rename at the end node and loses them with the port', () => { + const f = makeSpriteScene(); + const { asset, end } = confirm(f); + const { asset: outer } = hearing(f, asset, ['pressed']); + const ports = () => outer.graph.edges.map((e) => e.from.port); + expect(ports()).toEqual(['pressed']); + + f.stack.execute(new RenamePortCommand(asset.id, end.id, 'pressed', 'confirmed')); + expect(ports()).toEqual(['confirmed']); + + f.stack.execute(new RemovePortCommand(asset.id, end.id, 'confirmed')); + expect(ports()).toEqual([]); + f.stack.undo(); + expect(ports()).toEqual(['confirmed']); + }); + + it('keeps the typed-in value of an input through a rename at the start node', () => { + const f = makeSpriteScene(); + const { asset } = confirm(f); + const start = graphEditor(f, asset).addNode(BEHAVIOR_START); + f.stack.execute(new AddPortCommand(asset.id, start.id, { key: 'amount', kind: 'number' })); + const outer = makeBehavior(f, 'Player'); + const node = graphEditor(f, outer).addNode(ON_BEHAVIOR, { [BEHAVIOR_PARAM]: asset.id, amount: 5 }); + + f.stack.execute(new RenamePortCommand(asset.id, start.id, 'amount', 'size')); + expect(node.params.size).toBe(5); + expect(node.params.amount).toBeUndefined(); + }); +}); diff --git a/tools/e2e/19-nested-behavior.mjs b/tools/e2e/19-nested-behavior.mjs index a989a0e3..17cf90eb 100644 --- a/tools/e2e/19-nested-behavior.mjs +++ b/tools/e2e/19-nested-behavior.mjs @@ -191,6 +191,109 @@ export async function nestedBehavior(t) { `${JSON.stringify(afterUndo)}`, ); + // 19e-ii. Further flow ports and `On behavior` (#294). The end node declares a second way out + // with the mouse, the call grows the pin, and takes it once the end is reached by it. + // "Confirm" is a behavior heard as an event: Enter or Space inside, one node outside. + const WAY = 'left by out2'; + const HEARD = 'confirm heard'; + const endPorts = async () => + (await asset('nb-double')).graph.nodes.find((n) => n.id === 'nb-end').ports ?? []; + await t.select({ kind: 'node', assetId: 'nb-double', nodeId: 'nb-end', nodeIds: ['nb-end'] }); + await clickText('+ Output'); + await clickText('Flow'); + const ways = await endPorts(); + await t.select({ kind: 'node', assetId: 'nb-caller', nodeId: 'nb-call', nodeIds: ['nb-call'] }); + const wayPin = await portAt('nb-call', 'out2', true); + const valuePin = await portAt('nb-call', 'out1', true); + check( + 'a flow port declared at the end node becomes a flow output of the call, above its values', + ways.length === 2 && + ways[1].key === 'out2' && + ways[1].kind === 'flow' && + Boolean(wayPin) && + wayPin.y < valuePin.y, + `${JSON.stringify(ways)} pin=${JSON.stringify(wayPin)} value=${JSON.stringify(valuePin)}`, + ); + await mutate(` + const p = __gm.state.project; + const find = (id) => p.assets.find((a) => a.id === id); + const confirm = structuredClone(find('nb-empty')); + Object.assign(confirm, { id: 'nb-confirm', name: 'Confirm', graph: ${JSON.stringify({ + nodes: [ + node('nb-k1', 'OnKeyDown', 0, 0, { key: 'Enter' }), + node('nb-k2', 'OnKeyDown', 0, 200, { key: ' ' }), + node('nb-cend', 'BehaviorEnd', 360, 80, {}, [port('pressed', 'flow')]), + ], + edges: [ + edge('nb-k1e', 'nb-k1', 'exec', 'nb-cend', 'pressed'), + edge('nb-k2e', 'nb-k2', 'exec', 'nb-cend', 'pressed'), + ], + })} }); + p.assets.unshift(confirm); + find('nb-double').graph.edges.push(${JSON.stringify(edge('nb-way', 'nb-start', 'exec', 'nb-end', 'out2'))}); + const caller = find('nb-caller').graph; + caller.nodes.push( + ${JSON.stringify(node('nb-way-log', 'Log', 560, 260, { message: WAY }))}, + ${JSON.stringify(node('nb-on', 'OnBehavior', 0, 420, { behavior: 'nb-confirm' }))}, + ${JSON.stringify(node('nb-on-log', 'Log', 340, 420, { message: HEARD }))}, + ); + caller.edges.push( + ${JSON.stringify(edge('nb-w1', 'nb-call', 'out2', 'nb-way-log', 'exec'))}, + ${JSON.stringify(edge('nb-w2', 'nb-on', 'pressed', 'nb-on-log', 'exec'))}, + ); + `); + await clickText('Fit'); + const heardTitle = await evaluate(`__gm.graph.nodeLabel('nb-on')`); + const heardPin = await portAt('nb-on', 'pressed', true); + check( + 'a behavior heard as an event stands in the graph as "On " with the flow ports of its end', + heardTitle === 'On Confirm' && + Boolean(heardPin) && + (await evaluate(`__gm.graph.nodeProblem('nb-on')`)) === null, + `title=${JSON.stringify(heardTitle)} pin=${JSON.stringify(heardPin)}`, + ); + await shot('38b-flow-ports'); + const lines = async (text) => (await t.world()).log.filter((line) => line.includes(text)).length; + await t.play(); + await sleep(400); + const quiet = { way: await lines(WAY), heard: await lines(HEARD) }; + await t.holdKey('Enter', 120); + await sleep(200); + const afterEnter = await lines(HEARD); + await t.holdKey('Space', 120); + await sleep(200); + const afterSpace = await lines(HEARD); + await sleep(300); + const afterWait = await lines(HEARD); + const speedBoth = (await entity('nb-box')).x; + await stop(); + check( + 'a call leaves through the flow port its end node was reached by, and still goes on along exec', + quiet.way > 5 && speedBoth > idleX + 20, + `"${WAY}" ${quiet.way} times in 0.4 s, box at ${speedBoth.toFixed(1)} from ${idleX}`, + ); + check( + 'On behavior fires once for each key the behavior it hears listens to, and not in between', + quiet.heard === 0 && afterEnter === 1 && afterSpace === 2 && afterWait === 2, + `idle=${quiet.heard} Enter=${afterEnter} Space=${afterSpace} later=${afterWait}`, + ); + await mutate(` + const p = __gm.state.project; + const find = (id) => p.assets.find((a) => a.id === id); + p.assets = p.assets.filter((a) => a.id !== 'nb-confirm'); + const double = find('nb-double').graph; + double.edges = double.edges.filter((e) => e.id !== 'nb-way'); + const end = double.nodes.find((n) => n.id === 'nb-end'); + end.ports = end.ports.filter((port) => port.key !== 'out2'); + const caller = find('nb-caller').graph; + caller.nodes = caller.nodes.filter((n) => !['nb-way-log', 'nb-on', 'nb-on-log'].includes(n.id)); + caller.edges = caller.edges.filter((e) => !['nb-w1', 'nb-w2'].includes(e.id)); + `); + // Stopping leaves the game tab in front; what follows clicks in the graph. + await t.showTab('graph'); + await t.select({ kind: 'node', assetId: 'nb-caller', nodeId: 'nb-call', nodeIds: ['nb-call'] }); + await clickText('Fit'); + // 19f. The palette offers a behavior under its own name, and picking it leaves a node that // already names it – one pick, not a pick plus a dropdown. ("Double" also labels the asset // in the list on the left, so the proof is the node that appears, not the row.)