State machines: asset, tab, State branch and Set state nodes (#51)

A state machine is an asset whose graph holds one `State` node per state
(no ports, name as title), edited in a new "State machine" tab that reuses
the graph canvas: right-click places "State n", snap toggle shared with the
Behavior tab via SnapToggle. `statemachine` is a value kind like texture
(port, literal node, variable, struct field, tagged list item).

Behaviors use it through `State branch` (one exec output per state) and
`Set state` (one exec input per state; the interpreter now hands `run` the
entry port). States live per behavior instance in NodeContext.states, with
no initial state. Ports derive from the inline picker or a wired
`State machine` literal; BehaviorLookup became GraphLookup with
behavior(id) and machine(id).

The Graph tab is labelled "Behavior" (key unchanged). Unit tests
(state-machine, kinds, catalog, ports), e2e step 26 and README added.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
rootandClaude Fable 5.1 committed 2026-09-12 18:00:23 +02:00
1 parent ce42d16657
commit e7d82bd1a9
60 files changed
+1269 -213

No files matched your search

+2
View File
@@ -34,6 +34,8 @@ export function buildAsset(type: AssetType, name: string, id = newId()): Asset {
return { ...base, type: 'container', objects: [] };
case 'animation':
return { ...base, type: 'animation', frames: [] };
case 'statemachine':
return { ...base, type: 'statemachine', graph: createEmptyGraph() };
}
}
+16 -16
View File
@@ -8,14 +8,14 @@ import {
} from '../graph/Graph';
import { isTerminalType, resolveDef, terminalNode } from '../graph/nested';
import { nodeDef } from '../graph/NodeRegistry';
import { behaviorLookup } from '../model/behaviorPrograms';
import { graphLookup } from '../model/graphLookup';
import { newId } from '../ids';
import type { PropertyBag, PropertyValue } from '../model/Properties';
import type { Project } from '../model/Project';
import { coerceValue, defaultsOf } from '../properties/PropertySchema';
import { type Removed, removeById, removeFirst, removeWhere, restoreAt } from '../util/list';
import { type Command, CommandError } from './Command';
import { requireBehavior, requireNode, requireNodeDef } from './require';
import { requireGraph, requireNode, requireNodeDef } from './require';
import { SetBagValueCommand } from './SetBagValueCommand';
export class AddNodeCommand implements Command {
@@ -44,16 +44,16 @@ export class AddNodeCommand implements Command {
execute(project: Project): void {
requireNodeDef(this.node.type);
const graph = requireBehavior(project, this.assetId).graph;
const graph = requireGraph(project, this.assetId);
// The two terminals give the behavior its signature; a second one of either would make
// "which ports does this behavior have" ambiguous.
if (isTerminalType(this.node.type) && terminalNode(graph, this.node.type))
throw new CommandError(`This behavior already has a ${nodeDef(this.node.type)?.label} node`);
throw new CommandError(`This graph already has a ${nodeDef(this.node.type)?.label} node`);
graph.nodes.push(this.node);
}
undo(project: Project): void {
const graph = requireBehavior(project, this.assetId).graph;
const graph = requireGraph(project, this.assetId);
graph.nodes = removeById(graph.nodes, this.node.id);
}
}
@@ -69,7 +69,7 @@ export class RemoveNodeCommand implements Command {
) {}
execute(project: Project): void {
const graph = requireBehavior(project, this.assetId).graph;
const graph = requireGraph(project, this.assetId);
const node = removeFirst(graph.nodes, (n) => n.id === this.nodeId);
if (!node) throw new CommandError(`Node ${this.nodeId} not found`);
// `edgesOfNode` reads the edge list only, so it still finds them after the node is gone.
@@ -79,7 +79,7 @@ export class RemoveNodeCommand implements Command {
undo(project: Project): void {
if (!this.removed) return;
const graph = requireBehavior(project, this.assetId).graph;
const graph = requireGraph(project, this.assetId);
restoreAt(graph.nodes, [this.removed.node]);
restoreAt(graph.edges, this.removed.edges);
}
@@ -134,9 +134,9 @@ export class SetNodeParamCommand extends SetBagValueCommand<GraphNode> {
override execute(project: Project): void {
super.execute(project);
const graph = requireBehavior(project, this.assetId).graph;
const graph = requireGraph(project, this.assetId);
const node = requireNode(project, this.assetId, this.nodeId);
const def = resolveDef(node, graph, behaviorLookup(project));
const def = resolveDef(node, graph, graphLookup(project));
if (!def) return;
const outputs = new Set(def.outputs.map((p) => p.key));
const inputs = new Set(def.inputs.map((p) => p.key));
@@ -150,7 +150,7 @@ export class SetNodeParamCommand extends SetBagValueCommand<GraphNode> {
override undo(project: Project): void {
super.undo(project);
restoreAt(requireBehavior(project, this.assetId).graph.edges, this.orphans);
restoreAt(requireGraph(project, this.assetId).edges, this.orphans);
}
protected override resolveTarget(project: Project): GraphNode {
@@ -183,12 +183,12 @@ export class ConnectCommand implements Command {
}
execute(project: Project): void {
const graph = requireBehavior(project, this.assetId).graph;
const graph = requireGraph(project, this.assetId);
const fromNode = findNode(graph, this.edge.from.node);
const toNode = findNode(graph, this.edge.to.node);
if (!fromNode || !toNode) throw new CommandError('Node not found');
if (fromNode === toNode) throw new CommandError('A node cannot connect to itself');
const lookup = behaviorLookup(project);
const lookup = graphLookup(project);
const out = resolveDef(fromNode, graph, lookup)?.outputs.find((p) => p.key === this.edge.from.port);
const inp = resolveDef(toNode, graph, lookup)?.inputs.find((p) => p.key === this.edge.to.port);
if (!out || !inp) throw new CommandError('Port not found');
@@ -201,7 +201,7 @@ export class ConnectCommand implements Command {
}
undo(project: Project): void {
const graph = requireBehavior(project, this.assetId).graph;
const graph = requireGraph(project, this.assetId);
graph.edges = removeById(graph.edges, this.edge.id);
restoreAt(graph.edges, this.replaced);
}
@@ -231,7 +231,7 @@ export class FoldEdgeCommand implements Command {
}
private edge(project: Project): GraphEdge {
const edge = requireBehavior(project, this.assetId).graph.edges.find((e) => e.id === this.edgeId);
const edge = requireGraph(project, this.assetId).edges.find((e) => e.id === this.edgeId);
if (!edge) throw new CommandError(`Edge ${this.edgeId} not found`);
return edge;
}
@@ -282,13 +282,13 @@ export class DisconnectCommand implements Command {
) {}
execute(project: Project): void {
const graph = requireBehavior(project, this.assetId).graph;
const graph = requireGraph(project, this.assetId);
this.removed = removeWhere(graph.edges, (e) => e.id === this.edgeId);
if (this.removed.length === 0) throw new CommandError(`Edge ${this.edgeId} not found`);
}
undo(project: Project): void {
restoreAt(requireBehavior(project, this.assetId).graph.edges, this.removed);
restoreAt(requireGraph(project, this.assetId).edges, this.removed);
}
}
+17 -3
View File
@@ -1,10 +1,17 @@
/** Lookups that throw a `CommandError` when the target does not exist. */
import { findNode, type GraphNode } from '../graph/Graph';
import { findNode, type Graph, type GraphNode } from '../graph/Graph';
import { type NodeDef, nodeDef } from '../graph/NodeRegistry';
import type { Asset, BehaviorAsset } from '../model/Asset';
import { findObject, type ObjectTree } from '../model/hierarchy';
import { isTemplateContent, objectRef, type ObjectRef } from '../model/instance';
import { findAsset, findAssetOf, findObjectHolder, type ObjectHolder, type Project } from '../model/Project';
import {
findAsset,
findAssetOf,
findGraphAsset,
findObjectHolder,
type ObjectHolder,
type Project,
} from '../model/Project';
import type { SceneObject } from '../model/SceneObject';
import { propDef, type PropertyDef } from '../properties/PropertySchema';
import { CommandError } from './Command';
@@ -64,8 +71,15 @@ export function requireBehavior(project: Project, assetId: string): BehaviorAsse
return asset;
}
/** The graph of a behavior or of a state machine – what every graph command edits. */
export function requireGraph(project: Project, assetId: string): Graph {
const asset = findGraphAsset(project, assetId);
if (!asset) throw new CommandError(`Behavior or state machine ${assetId} not found`);
return asset.graph;
}
export function requireNode(project: Project, assetId: string, nodeId: string): GraphNode {
const node = findNode(requireBehavior(project, assetId).graph, nodeId);
const node = findNode(requireGraph(project, assetId), nodeId);
if (!node) throw new CommandError(`Node ${nodeId} not found`);
return node;
}
+10 -9
View File
@@ -1,5 +1,5 @@
import { edgesInto, edgesOutOf, type Graph, type GraphNode } from './Graph';
import { type BehaviorLookup, NO_BEHAVIORS } from './lookup';
import { type GraphLookup, NO_LOOKUP } from './lookup';
import { BEHAVIOR_END, BEHAVIOR_START, resolveDef, terminalNode } from './nested';
import type { NodeContext } from './NodeContext';
import {
@@ -58,7 +58,7 @@ export class GraphInterpreter {
constructor(
readonly graph: Graph,
private readonly behaviors: BehaviorLookup = NO_BEHAVIORS,
private readonly lookup: GraphLookup = NO_LOOKUP,
) {
this.frame = emptyFrame(graph);
}
@@ -93,11 +93,11 @@ export class GraphInterpreter {
const target = this.node(edge.to.node);
if (!target) continue;
this.trace?.onEdge(edge.id);
this.execute(target, ctx, depth + 1);
this.execute(target, ctx, depth + 1, edge.to.port);
}
}
private execute(node: GraphNode, ctx: NodeContext, depth: number): void {
private execute(node: GraphNode, ctx: NodeContext, depth: number, entry: string): void {
if (++this.steps > MAX_STEPS_PER_FIRE)
throw new Error('Behavior graph exceeded the step limit (endless loop?)');
if (depth > MAX_DEPTH)
@@ -105,7 +105,7 @@ export class GraphInterpreter {
const def = this.def(node);
if (!def?.run) return;
const inputs = this.collectInputs(node, ctx);
const result = def.run(ctx, inputs, node.params, def);
const result = def.run(ctx, inputs, node.params, def, entry);
const returned = result.call ? this.call(result.call, ctx, depth) : {};
const produced = { ...result.outputs, ...returned };
if (!def.read) this.frame.outputCache.set(node.id, produced);
@@ -122,7 +122,7 @@ export class GraphInterpreter {
* a call and not an inlining: nothing of it survives the return but the values it hands back.
*/
private call(call: CallResult, ctx: NodeContext, depth: number): Record<string, Value> {
const program = this.behaviors(call.behaviorId);
const program = this.lookup.behavior(call.behaviorId);
if (!program) return {};
if (this.callStack.includes(call.behaviorId)) throw new Error(`Behavior "${program.name}" runs itself`);
const start = terminalNode(program.graph, BEHAVIOR_START);
@@ -135,7 +135,8 @@ export class GraphInterpreter {
this.calledBehaviors.add(call.behaviorId);
try {
this.trace?.onNode(start.id);
this.follow(start, 'exec', { ...ctx, variables: { ...program.defaults } }, depth + 1);
// Fresh variables and fresh states alike: a call keeps nothing, and sees nothing of the caller's.
this.follow(start, 'exec', { ...ctx, variables: { ...program.defaults }, states: {} }, depth + 1);
const end = terminalNode(program.graph, BEHAVIOR_END);
return (end && this.frame.outputCache.get(end.id)) ?? {};
} finally {
@@ -196,7 +197,7 @@ export class GraphInterpreter {
throw new Error('Behavior graph exceeded the step limit (data cycle?)');
// Mark before evaluating so a data cycle reads null instead of recursing forever.
this.frame.dataCache.set(nodeId, {});
const outputs = def.run(ctx, this.collectInputs(source, ctx), source.params, def).outputs ?? {};
const outputs = def.run(ctx, this.collectInputs(source, ctx), source.params, def, '').outputs ?? {};
this.frame.dataCache.set(nodeId, outputs);
this.trace?.onNode(nodeId);
this.record(nodeId, outputs);
@@ -220,7 +221,7 @@ export class GraphInterpreter {
}
private def(node: GraphNode) {
return resolveDef(node, this.frame.graph, this.behaviors);
return resolveDef(node, this.frame.graph, this.lookup);
}
private node(id: string): GraphNode | undefined {
+5
View File
@@ -62,6 +62,11 @@ export interface NodeContext {
/** The behavior's parent object – the one the graph acts on. */
owner: EntityHandle | null;
variables: PropertyBag;
/**
* The current state of each state machine this instance has set, keyed by machine asset id,
* as the state node's id. A machine not in here is in no state: `State branch` follows nothing.
*/
states: Record<string, string>;
/** Seconds since the world started and since the last tick. */
time: number;
dt: number;
+14 -6
View File
@@ -2,7 +2,7 @@ import type { PropertyBag, PropertyValue } from '../model/Properties';
import { isKindWith, plainKindOf } from '../properties/kinds';
import { flatDef, type PropertyDef } from '../properties/PropertySchema';
import type { DeclaredPort, Graph, GraphNode, PortType } from './Graph';
import type { BehaviorLookup } from './lookup';
import type { GraphLookup } from './lookup';
import type { NodeContext } from './NodeContext';
import { asList, type Value } from './values';
@@ -16,7 +16,8 @@ export interface PortDef {
field?: PropertyDef;
}
export type NodeCategory = 'event' | 'flow' | 'data' | 'variable' | 'action';
/** `state` is the one category no behavior graph offers: its nodes are the states of a state machine. */
export type NodeCategory = 'event' | 'flow' | 'data' | 'variable' | 'action' | 'state';
/**
* How a loop node asks for one of its exec outputs to be run repeatedly: `port` carries the body,
@@ -45,11 +46,11 @@ export interface RunResult {
call?: CallResult;
}
/** What a node may compute its ports from: itself, the graph it sits in, and the behaviors around it. */
/** What a node may compute its ports from: itself, the graph it sits in, and the project around it. */
export interface PortSource {
node: GraphNode;
graph: Graph;
behaviors: BehaviorLookup;
lookup: GraphLookup;
}
/** Ports a single node has on top of the fixed ones of its type, and a label naming what it does. */
@@ -95,9 +96,16 @@ export interface NodeDef {
read?(ctx: NodeContext, params: PropertyBag, input: (key: string) => Value): Record<string, Value>;
/**
* Event nodes have no `run` – the interpreter seeds their outputs. `def` is resolved for the node at
* hand, the only way a node with derived ports knows how many it has.
* hand, the only way a node with derived ports knows how many it has. `entry` is the exec input
* the pulse arrived through – what a node with one exec input per meaning reads.
*/
run?(ctx: NodeContext, inputs: Record<string, Value>, params: PropertyBag, def: NodeDef): RunResult;
run?(
ctx: NodeContext,
inputs: Record<string, Value>,
params: PropertyBag,
def: NodeDef,
entry: string,
): RunResult;
}
const defs = new Map<string, NodeDef>();
+4 -4
View File
@@ -1,5 +1,5 @@
import { edgesInto, findNode, type Graph, type PortType, portsCompatible } from './Graph';
import type { BehaviorLookup } from './lookup';
import type { GraphLookup } from './lookup';
import { resolveDef } from './nested';
import type { NodeDef } from './NodeRegistry';
@@ -10,7 +10,7 @@ export interface PortSide {
isOutput: boolean;
}
export function portTypeOf(graph: Graph, side: PortSide, lookup: BehaviorLookup): PortType | undefined {
export function portTypeOf(graph: Graph, side: PortSide, lookup: GraphLookup): PortType | undefined {
const node = findNode(graph, side.nodeId);
const def = node && resolveDef(node, graph, lookup);
const list = side.isOutput ? def?.outputs : def?.inputs;
@@ -18,7 +18,7 @@ export function portTypeOf(graph: Graph, side: PortSide, lookup: BehaviorLookup)
}
/** Whether a drag from `from` may land on `to`, i.e. whether ConnectCommand would accept it. */
export function canConnect(graph: Graph, from: PortSide, to: PortSide, lookup: BehaviorLookup): boolean {
export function canConnect(graph: Graph, from: PortSide, to: PortSide, lookup: GraphLookup): boolean {
if (from.isOutput === to.isOutput || from.nodeId === to.nodeId) return false;
const fromType = portTypeOf(graph, from, lookup);
const toType = portTypeOf(graph, to, lookup);
@@ -36,7 +36,7 @@ export function dropTargetPort(
graph: Graph,
from: PortSide,
nodeId: string,
lookup: BehaviorLookup,
lookup: GraphLookup,
): PortSide | null {
if (nodeId === from.nodeId) return null;
const node = findNode(graph, nodeId);
+1
View File
@@ -8,6 +8,7 @@ export * from './nested';
export * from './NodeContext';
export * from './NodeRegistry';
export * from './propertyPorts';
export * from './stateMachine';
export * from './values';
export * from './variablePorts';
export { GraphInterpreter, type TraceListener } from './GraphInterpreter';
+20 -2
View File
@@ -8,6 +8,24 @@ export interface BehaviorProgram {
defaults: PropertyBag;
}
export type BehaviorLookup = (assetId: string) => BehaviorProgram | null;
/** One state of a machine: the node id is what a port and the runtime hold, the name is the label. */
export interface MachineState {
id: string;
name: string;
}
export const NO_BEHAVIORS: BehaviorLookup = () => null;
export interface StateMachine {
name: string;
states: MachineState[];
}
/**
* What a node may look up in the project around its graph: the behaviors it can run and the
* state machines it can read. One handle, so no caller can resolve a node with half of it.
*/
export interface GraphLookup {
behavior(assetId: string): BehaviorProgram | null;
machine(assetId: string): StateMachine | null;
}
export const NO_LOOKUP: GraphLookup = { behavior: () => null, machine: () => null };
+6 -6
View File
@@ -2,7 +2,7 @@ import { textOf } from '../model/Properties';
import { isTaggedKind } from '../properties/kinds';
import { flatDef, isValidFieldName } from '../properties/PropertySchema';
import { type DeclaredPort, declaredPortType, type Graph, type GraphNode } from './Graph';
import type { BehaviorLookup } from './lookup';
import type { GraphLookup } from './lookup';
import { nodeDef, type NodeDef, type PortDef } from './NodeRegistry';
export const BEHAVIOR_START = 'BehaviorStart';
@@ -92,14 +92,14 @@ export function declaredPorts(graph: Graph | undefined, type: string): PortDef[]
* The node definition as it applies to *this* node: identical to the registered one, unless the
* type declares ports per node (`declaresPorts`) or computes them (`derivePorts`).
*/
export function resolveDef(node: GraphNode, graph: Graph, lookup: BehaviorLookup): NodeDef | undefined {
export function resolveDef(node: GraphNode, graph: Graph, lookup: GraphLookup): NodeDef | undefined {
const def = nodeDef(node.type);
if (!def || (!def.declaresPorts && !def.derivePorts)) return def;
const own = (side: 'inputs' | 'outputs') =>
declaredOn(def, node.ports ?? [], side).map((p) =>
def.declaredPort ? def.declaredPort(p, node) : portDefOf(p),
);
const grown = def.derivePorts?.({ node, graph, behaviors: lookup }) ?? {};
const grown = def.derivePorts?.({ node, graph, lookup }) ?? {};
const side = (key: 'inputs' | 'outputs') => execFirst([...def[key], ...(grown[key] ?? []), ...own(key)]);
return { ...def, label: grown.label ?? def.label, inputs: side('inputs'), outputs: side('outputs') };
}
@@ -113,12 +113,12 @@ function execFirst(ports: PortDef[]): PortDef[] {
* Why this call cannot do anything, or null if it can. A call is the one node that depends on a
* *different* graph, so it is the one node that can look perfectly healthy and still be dead.
*/
export function callProblem(node: GraphNode, lookup: BehaviorLookup, ownerId = ''): string | null {
export function callProblem(node: GraphNode, lookup: GraphLookup, ownerId = ''): string | null {
if (node.type !== RUN_BEHAVIOR) return null;
const id = textOf(node.params[BEHAVIOR_PARAM] ?? '');
if (!id) return 'No behavior picked';
if (id === ownerId) return 'A behavior cannot run itself';
const program = lookup(id);
const program = lookup.behavior(id);
if (!program) return 'That behavior is gone';
if (!terminalNode(program.graph, BEHAVIOR_START)) return 'No start node – does nothing';
return null;
@@ -128,7 +128,7 @@ export function callProblem(node: GraphNode, lookup: BehaviorLookup, ownerId = '
* 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.
*/
export function portSignature(node: GraphNode, graph: Graph, lookup: BehaviorLookup, ownerId = ''): string {
export function portSignature(node: GraphNode, graph: Graph, lookup: GraphLookup, ownerId = ''): string {
const def = resolveDef(node, graph, lookup);
if (!def) return 'missing';
const list = (ports: PortDef[]) => ports.map((p) => `${p.key}:${p.type}`).join(',');
+5
View File
@@ -30,6 +30,11 @@ export const TextureLiteral = literal(
'texture',
'A constant picture: a texture, one of its frames or an animation, as a sprite wears it.',
);
export const StateMachineLiteral = literal(
'StateMachine',
'statemachine',
'A constant state machine, for a "State branch" or a "Set state" to work on.',
);
export const ListLiteral = literal(
'List',
'list',
+2 -2
View File
@@ -18,8 +18,8 @@ export const RunBehavior: NodeDef = {
inputs: [exec()],
outputs: [exec()],
params: [{ key: BEHAVIOR_PARAM, label: 'Behavior', kind: 'asset', default: '', assetTypes: ['behavior'] }],
derivePorts: ({ node, behaviors }) => {
const program = behaviors(textOf(node.params[BEHAVIOR_PARAM] ?? ''));
derivePorts: ({ node, lookup }) => {
const program = lookup.behavior(textOf(node.params[BEHAVIOR_PARAM] ?? ''));
return {
// The graph reads as what it does, not as a row of identical "Run behavior" boxes.
label: program?.name,
+23
View File
@@ -0,0 +1,23 @@
import type { NodeDef } from '../../NodeRegistry';
import { machineOf, machinePort, statePorts } from '../../stateMachine';
import { asString } from '../../values';
import { exec } from '../shared';
/** The mirror image of `State branch`: the input the flow arrives through names the new state. */
export const SetState: NodeDef = {
type: 'SetState',
label: 'Set state',
category: 'action',
description:
'Puts the machine into the state whose input the flow arrived through, then continues. Each ' +
'behavior instance keeps its own states.',
inputs: [machinePort()],
outputs: [exec()],
params: [],
derivePorts: (source) => ({ inputs: statePorts(machineOf(source)) }),
run: (ctx, inputs, _params, def, entry) => {
const machine = asString(inputs.machine);
if (machine && def.inputs.some((p) => p.type === 'exec' && p.key === entry)) ctx.states[machine] = entry;
return { next: 'exec' };
},
};
+22
View File
@@ -0,0 +1,22 @@
import type { NodeDef } from '../../NodeRegistry';
import { machineOf, machinePort, statePorts } from '../../stateMachine';
import { asString } from '../../values';
import { exec } from '../shared';
/** No state set yet, or a state of another machine: the flow ends here, along no output. */
export const StateBranch: NodeDef = {
type: 'StateBranch',
label: 'State branch',
category: 'flow',
description:
'Continues along the output of the state the machine is in. Before "Set state" has run, the ' +
'machine is in no state and nothing continues.',
inputs: [exec(), machinePort()],
outputs: [],
params: [],
derivePorts: (source) => ({ outputs: statePorts(machineOf(source)) }),
run: (ctx, inputs, _params, def) => {
const current = ctx.states[asString(inputs.machine)];
return def.outputs.some((p) => p.key === current) ? { next: current } : {};
},
};
+16 -1
View File
@@ -26,7 +26,14 @@ import { IsTouching } from './data/IsTouching';
import { Join } from './data/Join';
import { KeyIsDown } from './data/KeyIsDown';
import { Length } from './data/Length';
import { BooleanLiteral, ListLiteral, NumberLiteral, StringLiteral, TextureLiteral } from './data/literals';
import {
BooleanLiteral,
ListLiteral,
NumberLiteral,
StateMachineLiteral,
StringLiteral,
TextureLiteral,
} from './data/literals';
import { Max } from './data/Max';
import { Min } from './data/Min';
import { Modulo } from './data/Modulo';
@@ -76,6 +83,9 @@ import { Branch } from './flow/Branch';
import { Repeat } from './flow/Repeat';
import { RunBehavior } from './flow/RunBehavior';
import { Sequence } from './flow/Sequence';
import { SetState } from './flow/SetState';
import { StateBranch } from './flow/StateBranch';
import { State } from '../stateMachine';
import { Variables } from './variable/Variables';
/**
@@ -99,6 +109,8 @@ export const BUILT_IN_NODES: readonly NodeDef[] = [
Sequence,
Repeat,
RunBehavior,
StateBranch,
SetState,
BehaviorEnd,
Variables,
Self,
@@ -114,6 +126,7 @@ export const BUILT_IN_NODES: readonly NodeDef[] = [
BooleanLiteral,
StringLiteral,
TextureLiteral,
StateMachineLiteral,
Add,
Subtract,
Multiply,
@@ -168,3 +181,5 @@ export const BUILT_IN_NODES: readonly NodeDef[] = [
];
for (const def of BUILT_IN_NODES) registerNode(def);
// Registered so a machine's graph loads and draws, but not built in: no behavior graph offers it.
registerNode(State);
+73
View File
@@ -0,0 +1,73 @@
import { textOf } from '../model/Properties';
import { flatDef } from '../properties/PropertySchema';
import { edgesInto, type Graph, type GraphNode } from './Graph';
import type { MachineState, StateMachine } from './lookup';
import type { NodeDef, PortDef, PortSource } from './NodeRegistry';
export const STATE = 'State';
export const STATE_MACHINE = 'StateMachine';
export const STATE_NAME_PARAM = 'name';
/** The input naming the machine on `State branch` and `Set state`. */
export const MACHINE_PORT = 'machine';
/**
* One state of a state machine: a node with no ports whose name is its title. Its graph is the
* machine asset's, never a behavior's – the palette leaves the `state` category out.
*/
export const State: NodeDef = {
type: STATE,
label: 'State',
category: 'state',
description: 'One state of a state machine.',
inputs: [],
outputs: [],
params: [flatDef(STATE_NAME_PARAM, 'text', { label: 'Name', value: 'State' })],
derivePorts: ({ node }) => ({ label: stateName(node) }),
};
export function isStateNode(node: GraphNode): boolean {
return node.type === STATE;
}
export function stateName(node: GraphNode): string {
return textOf(node.params[STATE_NAME_PARAM] ?? '') || State.label;
}
/** The states of a machine's graph in node order – what its ports and the runtime name. */
export function statesOf(graph: Graph): MachineState[] {
return graph.nodes.filter(isStateNode).map((node) => ({ id: node.id, name: stateName(node) }));
}
/** What a state placed from the palette is called: "State 3" for the third. */
export function nextStateName(graph: Graph): string {
return `${State.label} ${statesOf(graph).length + 1}`;
}
/** The `machine` input; unconnected, it shows the machine picker. */
export const machinePort = (): PortDef => ({
key: MACHINE_PORT,
label: 'machine',
type: 'string',
field: flatDef(MACHINE_PORT, 'statemachine', { label: 'Machine' }),
});
/**
* The machine a node's `machine` input names while the graph is drawn: the inline pick, or the
* `State machine` literal an edge brings in. A port is derived from the graph, not from a running
* value, so a variable or a list item feeding the input yields no state ports.
*/
export function machineOf({ node, graph, lookup }: PortSource): StateMachine | null {
const edge = edgesInto(graph, node.id, MACHINE_PORT)[0];
const source = edge && graph.nodes.find((n) => n.id === edge.from.node);
const id = edge
? source?.type === STATE_MACHINE
? textOf(source.params.value ?? '')
: ''
: textOf(node.params[MACHINE_PORT] ?? '');
return id ? lookup.machine(id) : null;
}
/** One exec port per state, keyed by the state's id – a rename keeps every edge. */
export function statePorts(machine: StateMachine | null): PortDef[] {
return (machine?.states ?? []).map((state) => ({ key: state.id, label: state.name, type: 'exec' }));
}
+18 -1
View File
@@ -82,6 +82,15 @@ export interface AnimationAsset extends AssetBase {
frames: string[];
}
/**
* The graph holds one `State` node per state and nothing else; a behavior reads the machine's
* current state through `State branch` and moves it through `Set state`.
*/
export interface StateMachineAsset extends AssetBase {
type: 'statemachine';
graph: Graph;
}
export type Asset =
| SpriteAsset
| CameraAsset
@@ -91,7 +100,15 @@ export type Asset =
| ColliderAsset
| ContainerAsset
| TextureAsset
| AnimationAsset;
| AnimationAsset
| StateMachineAsset;
/** The assets edited as a node graph – what the graph canvas and the graph commands work on. */
export type GraphAsset = BehaviorAsset | StateMachineAsset;
export function isGraphAsset(asset: Asset): asset is GraphAsset {
return asset.type === 'behavior' || asset.type === 'statemachine';
}
export function isSceneAsset(asset: Asset): asset is SceneAsset {
return asset.type === 'scene';
+8 -3
View File
@@ -8,6 +8,7 @@ export const ASSET_TYPES = [
'container',
'texture',
'animation',
'statemachine',
] as const;
export type AssetType = (typeof ASSET_TYPES)[number];
@@ -22,13 +23,17 @@ export const ASSET_TYPE_LABELS: Record<AssetType, string> = {
container: 'Container',
texture: 'Texture',
animation: 'Animation',
statemachine: 'State machine',
};
/** Textures and animations are not placeable: they are pictures a sprite wears through `texture`. */
export type PlaceableAssetType = Exclude<AssetType, 'scene' | 'texture' | 'animation'>;
/**
* Textures and animations are not placeable: they are pictures a sprite wears through `texture`.
* A state machine is not either: a behavior refers to it by id.
*/
export type PlaceableAssetType = Exclude<AssetType, 'scene' | 'texture' | 'animation' | 'statemachine'>;
export function isPlaceableType(type: AssetType): type is PlaceableAssetType {
return type !== 'scene' && type !== 'texture' && type !== 'animation';
return type !== 'scene' && type !== 'texture' && type !== 'animation' && type !== 'statemachine';
}
export function isAssetType(value: unknown): value is AssetType {
+13 -1
View File
@@ -1,4 +1,11 @@
import { type Asset, type ContainerAsset, isSceneAsset, type SceneAsset } from './Asset';
import {
type Asset,
type ContainerAsset,
type GraphAsset,
isGraphAsset,
isSceneAsset,
type SceneAsset,
} from './Asset';
/** 2: a placed container carries no copy of its template. */
export const PROJECT_FORMAT_VERSION = 2;
@@ -38,6 +45,11 @@ export function listScenes(project: Project): SceneAsset[] {
return project.assets.filter(isSceneAsset);
}
export function findGraphAsset(project: Project, assetId: string): GraphAsset | undefined {
const asset = findAsset(project, assetId);
return asset && isGraphAsset(asset) ? asset : undefined;
}
/**
* Everything that holds placed objects. A container's `objects` are a template, so anything
* walking "all placed objects" must cover both or it silently skips the templates.
-15
View File
@@ -1,15 +0,0 @@
import type { BehaviorLookup } from '../graph/lookup';
import { resolveAssetProps } from '../properties/resolve';
import { findAssetOf, type Project } from './Project';
/**
* What a `Run behavior` node needs from the project. `defaults` are the asset's variable values;
* every call copies them, so a nested behavior never carries state from one call to the next.
*/
export function behaviorLookup(project: Project): BehaviorLookup {
return (assetId) => {
const asset = findAssetOf(project, assetId, 'behavior');
if (!asset) return null;
return { name: asset.name, graph: asset.graph, defaults: resolveAssetProps(asset) };
};
}
+22
View File
@@ -0,0 +1,22 @@
import type { GraphLookup } from '../graph/lookup';
import { statesOf } from '../graph/stateMachine';
import { resolveAssetProps } from '../properties/resolve';
import { findAssetOf, type Project } from './Project';
/**
* What a graph may see of the project around it. A behavior's `defaults` are its variable values;
* every call copies them, so a nested behavior never carries state from one call to the next.
*/
export function graphLookup(project: Project): GraphLookup {
return {
behavior: (assetId) => {
const asset = findAssetOf(project, assetId, 'behavior');
if (!asset) return null;
return { name: asset.name, graph: asset.graph, defaults: resolveAssetProps(asset) };
},
machine: (assetId) => {
const asset = findAssetOf(project, assetId, 'statemachine');
return asset ? { name: asset.name, states: statesOf(asset.graph) } : null;
},
};
}
+2
View File
@@ -155,6 +155,8 @@ const ASSET_SCHEMAS: Record<AssetType, PropertySchema> = {
],
// Behaviors declare their own properties (variables) per asset too – see `schemaForAsset`.
behavior: [{ key: 'runInEditor', label: 'Run in editor', kind: 'boolean', default: false }],
// The states are the asset's graph (see StateMachineAsset), not a property.
statemachine: [],
collider: [
{
key: 'shape',
+14
View File
@@ -92,6 +92,20 @@ export const KINDS = [
field: true,
port: true,
},
/** A state machine asset's id – a text, so it is tagged in a list like a texture. */
{
kind: 'statemachine',
label: 'State machine',
mark: '◈',
travels: 'string',
empty: '',
coerce: text,
tagged: true,
reference: true,
variable: true,
field: true,
port: true,
},
{ kind: 'object', label: 'Object', mark: '◇', travels: 'object', port: true },
{ kind: 'list', label: 'List', mark: '≡', travels: 'list', variable: true, port: true },
{ kind: 'struct', label: 'Struct', mark: '⊞', travels: 'struct', variable: true, port: true },
+6 -2
View File
@@ -9,6 +9,7 @@ import {
isValidPortName,
fixedPortKeys,
nodeDef,
STATE,
} from '../graph';
import type { Asset, TextureFrame } from '../model/Asset';
import { isAssetType } from '../model/AssetTypes';
@@ -89,6 +90,8 @@ export function deserializeProject(raw: unknown, fallbackId = ''): Project {
variables: variables.get(id) ?? [],
graph: normalizeGraph(a.graph),
});
} else if (type === 'statemachine') {
assets.push({ id, type, name, props, graph: normalizeGraph(a.graph, STATE) });
} else if (type === 'texture') {
assets.push({ id, type, name, props, ...normalizeTexture(a, takenIds) });
} else if (type === 'animation') {
@@ -242,7 +245,8 @@ function normalizePorts(raw: unknown, fixed: readonly string[], writable: boolea
return ports;
}
function normalizeGraph(raw: unknown): Graph {
/** `only` restricts the node types kept: a state machine's graph holds states and nothing else. */
function normalizeGraph(raw: unknown, only?: string): Graph {
const g = asRecord(raw);
const graph = createEmptyGraph();
const nodeIds = new Set<string>();
@@ -251,7 +255,7 @@ function normalizeGraph(raw: unknown): Graph {
const id = typeof n.id === 'string' ? n.id : '';
const type = typeof n.type === 'string' ? n.type : '';
const def = nodeDef(type);
if (!id || nodeIds.has(id) || !def) continue;
if (!id || nodeIds.has(id) || !def || (only !== undefined && type !== only)) continue;
nodeIds.add(id);
// Params carry both settings and inline input values, so there is no schema to coerce against.
const params: PropertyBag = {};
+1 -1
View File
@@ -30,7 +30,7 @@ export interface AssetTabOptions {
}
/**
* The Graph, Texture and Container tabs; each keeps its last asset when the selection moves elsewhere.
* The Behavior, State machine, Texture and Container tabs; each keeps its last asset when the selection moves elsewhere.
* A subclass must call `mount()`: header and canvas depend on each other, so the base cannot build them.
*/
export abstract class AssetTabEditor<
+25 -5
View File
@@ -17,19 +17,31 @@ import { HierarchyPanel } from './panels/HierarchyPanel';
import { Toolbar } from './panels/Toolbar';
import { type PlayHost, PlaySession, type WorldSnapshot } from './PlaySession';
import { ProjectSession } from './ProjectSession';
import { StateMachineEditor } from './statemachine/StateMachineEditor';
import { installShortcuts } from './shortcuts';
import type { EditorState } from './state';
import { TextureEditor } from './texture/TextureEditor';
import { installTextureImport } from './textureImport';
export type CentreTab = 'scene' | 'graph' | 'game' | 'texture' | 'animation' | 'container' | 'list';
export type CentreTab =
'scene' | 'graph' | 'statemachine' | 'game' | 'texture' | 'animation' | 'container' | 'list';
const TAB_ORDER = ['scene', 'game', 'graph', 'texture', 'animation', 'container', 'list'] as const;
const TAB_ORDER = [
'scene',
'game',
'graph',
'statemachine',
'texture',
'animation',
'container',
'list',
] as const;
const TAB_LABELS: Record<CentreTab, string> = {
scene: 'Scene',
game: 'Game',
graph: 'Graph',
graph: 'Behavior',
statemachine: 'State machine',
texture: 'Texture',
animation: 'Animation',
container: 'Container',
@@ -52,6 +64,7 @@ export class Editor implements PlayHost {
/** Game tab: the running world through its camera. */
readonly gameView: GameViewport;
readonly graphEditor: GraphEditor;
readonly stateMachineEditor: StateMachineEditor;
readonly textureEditor: TextureEditor;
readonly animationEditor: AnimationEditor;
readonly containerEditor: ContainerEditor;
@@ -88,6 +101,7 @@ export class Editor implements PlayHost {
this.viewport = new SceneViewport(state);
this.gameView = new GameViewport(state);
this.graphEditor = new GraphEditor(state);
this.stateMachineEditor = new StateMachineEditor(state);
this.textureEditor = new TextureEditor(state);
this.animationEditor = new AnimationEditor(state);
this.containerEditor = new ContainerEditor(state);
@@ -132,6 +146,7 @@ export class Editor implements PlayHost {
scene: this.viewport,
game: this.gameView,
graph: this.graphEditor,
statemachine: this.stateMachineEditor,
texture: this.textureEditor,
animation: this.animationEditor,
container: this.containerEditor,
@@ -141,6 +156,7 @@ export class Editor implements PlayHost {
scene: this.tabButton('scene'),
game: this.tabButton('game'),
graph: this.tabButton('graph'),
statemachine: this.tabButton('statemachine'),
texture: this.tabButton('texture'),
animation: this.tabButton('animation'),
container: this.tabButton('container'),
@@ -182,10 +198,14 @@ export class Editor implements PlayHost {
});
app.ticker.add((ticker) => this.tick(ticker.deltaMS / 1000));
// A node, a frame and a template object exist only in their own tab, so selecting one
// switches to it; selecting the behavior, texture or container asset itself does not.
// switches to it; selecting the behavior, texture or container asset itself does not. A state
// machine asset does switch (user's choice): its tab is the only place it shows anything.
state.on('selection', () => {
const s = state.selection;
if (s?.kind === 'node' && this.tab !== 'graph') this.showTab('graph');
const machine = state.selectedStateMachineId !== null;
if (s?.kind === 'node' && !machine && this.tab !== 'graph') this.showTab('graph');
if ((s?.kind === 'node' || s?.kind === 'asset') && machine && this.tab !== 'statemachine')
this.showTab('statemachine');
if (s?.kind === 'frame' && this.tab !== 'texture') this.showTab('texture');
if (
s?.kind === 'object' &&
+10
View File
@@ -230,6 +230,16 @@ export function installDebugHook(app: Application, state: EditorState, editor: E
snapping: () => graphEditor.canvas.snapEnabled,
crumbs: () => graphEditor.breadcrumb.crumbsDrawn(),
},
stateMachine: {
current: () => editor.stateMachineEditor.currentAssetId,
pickerAt: () => centreOf(editor.stateMachineEditor.picker),
nodeAt: (nodeId: string) => editor.stateMachineEditor.canvas.nodeGlobal(nodeId),
nodeLabel: (nodeId: string) => editor.stateMachineEditor.canvas.nodeLabel(nodeId),
nodeRect: (nodeId: string) => editor.stateMachineEditor.canvas.nodeRect(nodeId),
canvasRect: () => editor.stateMachineEditor.canvas.canvasRect(),
center: () => centreOf(editor.stateMachineEditor.canvas),
snapping: () => editor.stateMachineEditor.canvas.snapEnabled,
},
/** The open image picker: what it offers, what is picked, and where a tile sits. */
imagePicker: () => currentImagePicker()?.debugInfo() ?? null,
imagePickerTile: (file: string) => currentImagePicker()?.tileGlobal(file) ?? null,
+22 -20
View File
@@ -17,17 +17,18 @@ import {
edgesInto,
edgesOutOf,
firstPortFor,
type Graph,
type GraphNode,
type BehaviorLookup,
type GraphLookup,
type PortSide,
type PortType,
portTypeOf,
resolveDef,
RUN_BEHAVIOR,
} from '../../core/graph';
import type { BehaviorAsset } from '../../core/model/Asset';
import { behaviorLookup } from '../../core/model/behaviorPrograms';
import { findAsset } from '../../core/model/Project';
import type { GraphAsset } from '../../core/model/Asset';
import { graphLookup } from '../../core/model/graphLookup';
import { findAsset, findGraphAsset } from '../../core/model/Project';
import { type Trace, TRACE_FADE } from '../../runtime/systems/BehaviorSystem';
import { beadsInFlight, launchBead } from './beads';
import {
@@ -69,8 +70,8 @@ const DRAG_THRESHOLD = 3;
const LIVE_VALUE_INTERVAL_MS = 100;
/**
* The node graph of one behavior asset. Which behavior that is comes from the outside (`show`),
* so the canvas never has an opinion about the selection – the GraphEditor around it does.
* The node graph of one behavior or state machine asset. Which one that is comes from the outside
* (`show`), so the canvas never has an opinion about the selection – the tab around it does.
*/
export class GraphCanvas extends Widget {
private readonly bg = new Graphics();
@@ -123,7 +124,11 @@ export class GraphCanvas extends Widget {
/** A double-clicked call node; the tab opens the behavior and records the step. */
onOpenBehavior: (assetId: string) => void = (assetId) => this.state.select({ kind: 'asset', assetId });
constructor(private readonly state: EditorState) {
constructor(
private readonly state: EditorState,
/** Names the asset kind in the empty state: "No behavior selected …". */
private readonly noun = 'behavior',
) {
super();
this.canvas.addChild(this.edgeLayer, this.nodeLayer, this.tempEdge);
this.addChild(this.bg, this.grid, this.canvas, this.band, this.hint, this.clip);
@@ -187,20 +192,19 @@ export class GraphCanvas extends Widget {
return { w: Math.max(this.minWidth, 200), h: Math.max(this.minHeight, 200) };
}
private behaviors(): BehaviorLookup {
return behaviorLookup(this.state.project);
private behaviors(): GraphLookup {
return graphLookup(this.state.project);
}
private asset(): BehaviorAsset | null {
const asset = this.assetId ? findAsset(this.state.project, this.assetId) : undefined;
return asset && asset.type === 'behavior' ? asset : null;
private asset(): GraphAsset | null {
return (this.assetId && findGraphAsset(this.state.project, this.assetId)) || null;
}
/** Rebuilds node views from the model (cheap: views are reused by node id). */
private sync(): void {
const asset = this.asset();
if (!asset) {
// A behavior that was deleted (or undone away) must not linger as a graph.
// An asset that was deleted (or undone away) must not linger as a graph.
this.assetId = '';
for (const view of this.views.values()) view.destroy({ children: true });
this.views.clear();
@@ -208,7 +212,7 @@ export class GraphCanvas extends Widget {
return;
}
const seen = new Set<string>();
const lookup = behaviorLookup(this.state.project);
const lookup = graphLookup(this.state.project);
for (const node of asset.graph.nodes) {
const def = resolveDef(node, asset.graph, lookup);
if (!def) continue;
@@ -435,7 +439,8 @@ export class GraphCanvas extends Widget {
const local = this.toLocal(e.global);
const inside = local.x >= 0 && local.x <= this.w && local.y >= 0 && local.y <= this.h;
const asset = dragged.kind === 'asset' ? findAsset(this.state.project, dragged.id) : undefined;
if (!inside || !this.assetId || asset?.type !== 'behavior') {
// Only a behavior graph runs other behaviors; a state machine has nothing to drop in.
if (!inside || this.asset()?.type !== 'behavior' || asset?.type !== 'behavior') {
this.setIncoming(null);
return;
}
@@ -631,10 +636,7 @@ export class GraphCanvas extends Widget {
this.state.select(nodeSelection(this.assetId, [add.node.id]));
}
private openLinks(
pick: (graph: BehaviorAsset['graph']) => BehaviorAsset['graph']['edges'],
at: { x: number; y: number },
): void {
private openLinks(pick: (graph: Graph) => Graph['edges'], at: { x: number; y: number }): void {
const graph = this.asset()?.graph;
if (graph) openLinkMenu(this.state, this.assetId, pick(graph), at.x, at.y);
}
@@ -652,7 +654,7 @@ export class GraphCanvas extends Widget {
const asset = this.asset();
this.canvas.visible = asset !== null;
if (!asset) {
this.hint.text = 'No behavior selected – pick one above, or add a behavior asset.';
this.hint.text = `No ${this.noun} selected – pick one above, or add a ${this.noun} asset.`;
return;
}
const playing = this.state.mode === 'play';
+4 -9
View File
@@ -1,29 +1,24 @@
import type { Asset, BehaviorAsset } from '../../core/model/Asset';
import { findAsset, findAssetOf } from '../../core/model/Project';
import { Checkbox, Label } from '../../ui';
import { AssetTabEditor } from '../AssetTabEditor';
import type { EditorState } from '../state';
import { Breadcrumb } from './Breadcrumb';
import { GraphCanvas } from './GraphCanvas';
import { SnapToggle } from './SnapToggle';
import { backTo, descend, follow, type Trail } from './trail';
/** Room kept for the "N nodes · M links" readout, wide enough for a three-digit graph. */
const INFO_WIDTH = 150;
export class GraphEditor extends AssetTabEditor<BehaviorAsset, GraphCanvas> {
private readonly snapBox = new Checkbox();
private readonly snap = new SnapToggle(() => this.canvas);
readonly breadcrumb = new Breadcrumb();
private trail: Trail = [];
constructor(state: EditorState) {
super(state, { noun: 'Behavior', infoWidth: INFO_WIDTH });
this.snapBox.onChange = (on) => this.canvas.setSnapping(on);
this.breadcrumb.onPick = (index) => this.open(this.trail[index]!, backTo(this.trail, index));
this.mount(
new GraphCanvas(state),
[new Label('Snap', { style: 'muted' }), this.snapBox],
this.breadcrumb,
);
this.mount(new GraphCanvas(state), this.snap.widgets, this.breadcrumb);
this.canvas.onOpenBehavior = (id) => this.open(id, descend(this.trail, this.currentAssetId, id));
// Play swaps in the runtime copy of the project, and back.
state.on('mode', () => this.refresh());
@@ -69,6 +64,6 @@ export class GraphEditor extends AssetTabEditor<BehaviorAsset, GraphCanvas> {
}
protected override syncExtras(asset: BehaviorAsset | null): void {
this.snapBox.setEnabled(Boolean(asset));
this.snap.setEnabled(Boolean(asset));
}
}
+1 -1
View File
@@ -2,7 +2,7 @@ import type { NodeCategory, NodeDef } from '../../core/graph';
import { ListView, Popup, ScrollContainer, TextField, Theme, ui } from '../../ui';
import type { PaletteEntry } from './paletteEntries';
const CATEGORY_ORDER: NodeCategory[] = ['event', 'flow', 'variable', 'data', 'action'];
const CATEGORY_ORDER: NodeCategory[] = ['event', 'flow', 'variable', 'data', 'action', 'state'];
/** Searchable list of node types; right-click menu of the graph editor. */
export class NodePalette extends Popup {
+2
View File
@@ -49,6 +49,8 @@ export function categoryColor(category: NodeCategory): number {
return c.categoryVariable;
case 'action':
return c.categoryAction;
case 'state':
return c.categoryState;
}
}
+17
View File
@@ -0,0 +1,17 @@
import { Checkbox, Label, type Widget } from '../../ui';
import type { GraphCanvas } from './GraphCanvas';
/** The "Snap" checkbox every tab on the graph canvas carries in its header. */
export class SnapToggle {
private readonly box = new Checkbox();
readonly widgets: readonly Widget[];
constructor(canvas: () => GraphCanvas) {
this.box.onChange = (on) => canvas().setSnapping(on);
this.widgets = [new Label('Snap', { style: 'muted' }), this.box];
}
setEnabled(on: boolean): void {
this.box.setEnabled(on);
}
}
+15 -7
View File
@@ -3,13 +3,16 @@ import {
BEHAVIOR_PARAM,
createEmptyGraph,
isTerminalType,
nextStateName,
type NodeDef,
resolveDef,
RUN_BEHAVIOR,
State,
STATE_NAME_PARAM,
terminalNode,
} from '../../core/graph';
import type { BehaviorAsset } from '../../core/model/Asset';
import { behaviorLookup } from '../../core/model/behaviorPrograms';
import type { GraphAsset } from '../../core/model/Asset';
import { graphLookup } from '../../core/model/graphLookup';
import type { PropertyBag } from '../../core/model/Properties';
import type { Project } from '../../core/model/Project';
@@ -25,17 +28,22 @@ export interface PaletteEntry {
}
/**
* The node types offerable in `asset`'s graph. Every other behavior appears under its own name
* instead of behind a generic "Run behavior"; the two terminals drop out once the graph has them.
* The node types offerable in `asset`'s graph. A state machine holds states and nothing else, each
* new one named by its number. 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.
*/
export function paletteEntries(project: Project, asset: BehaviorAsset): PaletteEntry[] {
export function paletteEntries(project: Project, asset: GraphAsset): PaletteEntry[] {
if (asset.type === 'statemachine') {
const params = { [STATE_NAME_PARAM]: nextStateName(asset.graph) };
return [{ id: State.type, hint: State.category, def: State, params }];
}
const entries: PaletteEntry[] = [];
for (const def of allNodeDefs()) {
if (def.type === RUN_BEHAVIOR) continue;
if (def.type === RUN_BEHAVIOR || def.category === 'state') continue;
if (isTerminalType(def.type) && terminalNode(asset.graph, def.type)) continue;
entries.push({ id: def.type, hint: def.category, def, params: {} });
}
const lookup = behaviorLookup(project);
const lookup = graphLookup(project);
for (const other of project.assets) {
// A behavior running itself is an endless loop, so it is not on offer.
if (other.type !== 'behavior' || other.id === asset.id) continue;
+7
View File
@@ -231,6 +231,12 @@ const REFERENCES: Record<ReferenceKind, Reference> = {
})),
},
texture: { none: NO_TEXTURE_LABEL, label: textureRefLabel, choices: textureRefChoices },
statemachine: {
none: NO_ASSET_LABEL,
label: assetRefLabel,
choices: (project) =>
assetRefChoices(project, ['statemachine']).map((a) => ({ id: a.id, label: a.name })),
},
};
/** An id in the words of its reference kind; nothing for a kind that names nothing. */
@@ -355,6 +361,7 @@ export function createField(
}
case 'asset':
case 'texture':
case 'statemachine':
return referenceField(ctx, def, REFERENCES[def.kind], value, handlers);
}
}
+17 -11
View File
@@ -11,8 +11,9 @@ import {
portSignature,
resolveDef,
} from '../../core/graph';
import { behaviorLookup } from '../../core/model/behaviorPrograms';
import { findAssetOf, type Project } from '../../core/model/Project';
import type { GraphAsset } from '../../core/model/Asset';
import { graphLookup } from '../../core/model/graphLookup';
import { findGraphAsset, type Project } from '../../core/model/Project';
import { textOf } from '../../core/model/Properties';
import type { PropertyDef } from '../../core/properties/PropertySchema';
import { Label } from '../../ui';
@@ -24,11 +25,11 @@ import { currentNode, nodeParamValue } from './valueSpecs';
/** Structure-defining facts of a node selection: ports, connected inputs, declared variables. */
export function nodeSignature(project: Project, assetId: string, nodeId: string): string {
const asset = findAssetOf(project, assetId, 'behavior');
const asset = findGraphAsset(project, assetId);
if (!asset) return 'missing';
const node = asset.graph.nodes.find((n) => n.id === nodeId);
if (!node) return 'missing';
const lookup = behaviorLookup(project);
const lookup = graphLookup(project);
const def = resolveDef(node, asset.graph, lookup);
const connected = def
? inlineInputs(def)
@@ -38,23 +39,28 @@ export function nodeSignature(project: Project, assetId: string, nodeId: string)
const declared = (node.ports ?? []).map((p) => `${p.key}:${p.kind}${p.write ? ':set' : ''}`).join(',');
// They decide which rows the inspector builds, and two behaviors may share a name in the title.
const target = `${textOf(node.params[OBJECT_TYPE_PARAM] ?? '')}:${textOf(node.params[OBJECT_BEHAVIOR_PARAM] ?? '')}`;
return `${portSignature(node, asset.graph, lookup, assetId)}|${declared}|${connected.join(',')}|${asset.variables
return `${portSignature(node, asset.graph, lookup, assetId)}|${declared}|${connected.join(',')}|${variablesOf(
asset,
)
.map((v) => v.key)
.join(',')}|${target}`;
}
/** A state machine declares no variables; its one node type has none to name. */
const variablesOf = (asset: GraphAsset): PropertyDef[] => (asset.type === 'behavior' ? asset.variables : []);
/** Description, settings (params) and the inline values of unconnected data inputs. */
export function buildNodeSection(host: InspectorHost, assetId: string, nodeId: string): void {
const asset = findAssetOf(host.state.project, assetId, 'behavior');
const asset = findGraphAsset(host.state.project, assetId);
if (!asset) return;
const node = asset.graph.nodes.find((n) => n.id === nodeId);
const def = node && resolveDef(node, asset.graph, behaviorLookup(host.state.project));
const def = node && resolveDef(node, asset.graph, graphLookup(host.state.project));
if (!node || !def) return;
addTitle(host, `${def.category.toUpperCase()} NODE`);
host.body.add(new Label(def.label, { style: 'bodyBold' }));
addNote(host, def.description);
const problem = callProblem(node, behaviorLookup(host.state.project), assetId);
const problem = callProblem(node, graphLookup(host.state.project), assetId);
if (problem) addNote(host, problem, 'warning');
const addSetting = (param: PropertyDef) => {
const row = createFieldRow(
@@ -67,9 +73,9 @@ export function buildNodeSection(host: InspectorHost, assetId: string, nodeId: s
host.body.add(row.row);
};
const ownSettings = declaresPropertyPorts(node.type);
if (declaresVariablePorts(node.type)) buildVariablePortSection(host, assetId, node, asset.variables);
if (declaresVariablePorts(node.type)) buildVariablePortSection(host, assetId, node, variablesOf(asset));
else if (ownSettings) buildPropertyPortSection(host, assetId, node, addSetting);
else if (def.declaresPorts) buildPortSection(host, assetId, node, asset.variables);
else if (def.declaresPorts) buildPortSection(host, assetId, node, variablesOf(asset));
if (!ownSettings && def.params.length > 0) {
addTitle(host, 'SETTINGS');
@@ -94,7 +100,7 @@ export function buildNodeSection(host: InspectorHost, assetId: string, nodeId: s
/** Pushes the node's current params into the rows. False when the node is gone (rebuild). */
export function refreshNodeSection(host: InspectorHost, assetId: string, nodeId: string): boolean {
const found = currentNode(host.state.project, assetId, nodeId);
const def = found && resolveDef(found.node, found.graph, behaviorLookup(host.state.project));
const def = found && resolveDef(found.node, found.graph, graphLookup(host.state.project));
if (!found || !def) return false;
for (const [key, row] of host.fields) {
const [scope, name] = key.split(':') as ['param' | 'input', string];
+2 -2
View File
@@ -4,7 +4,7 @@ import { SetOverrideCommand } from '../../core/commands/sceneObjectCommands';
import { findNode, type Graph, type GraphNode } from '../../core/graph/Graph';
import type { Asset } from '../../core/model/Asset';
import type { ObjectRef } from '../../core/model/instance';
import { findAsset, findAssetOf, type Project } from '../../core/model/Project';
import { findAsset, findGraphAsset, type Project } from '../../core/model/Project';
import type { EditorState } from '../state';
import { currentProps, currentRef } from './objectQueries';
import type { PreviewedValue } from './previewHandlers';
@@ -57,7 +57,7 @@ export function currentNode(
assetId: string,
nodeId: string,
): { node: GraphNode; graph: Graph } | undefined {
const asset = findAssetOf(project, assetId, 'behavior');
const asset = findGraphAsset(project, assetId);
if (!asset) return undefined;
const node = findNode(asset.graph, nodeId);
return node && { node, graph: asset.graph };
+2 -2
View File
@@ -6,7 +6,7 @@ import { edgesInto, type Graph, type GraphNode } from '../../core/graph/Graph';
import { resolveDef } from '../../core/graph/nested';
import { inlineInputDef, inlineInputs, type NodeDef } from '../../core/graph/NodeRegistry';
import type { Asset } from '../../core/model/Asset';
import { behaviorLookup } from '../../core/model/behaviorPrograms';
import { graphLookup } from '../../core/model/graphLookup';
import type { ObjectRef } from '../../core/model/instance';
import { isList, type ListValue, type PropertyValue, type StructValue } from '../../core/model/Properties';
import { findAsset } from '../../core/model/Project';
@@ -181,7 +181,7 @@ function objectOwner(
function nodeOwner(state: EditorState, slot: Extract<ListSlot, { kind: 'node' }>): Owner<GraphNode> | null {
const found = currentNode(state.project, slot.assetId, slot.nodeId);
if (!found) return null;
const nodeDef = resolveDef(found.node, found.graph, behaviorLookup(state.project));
const nodeDef = resolveDef(found.node, found.graph, graphLookup(state.project));
const def =
nodeDef && (nodeDef.params.find((p) => p.key === slot.key) ?? inlineListDef(nodeDef, found, slot.key));
if (!nodeDef || !def) return null;
+15 -5
View File
@@ -7,6 +7,7 @@ import {
createEmptyProject,
findAsset,
findAssetOf,
findGraphAsset,
findObjectHolder,
findScene,
type Project,
@@ -313,8 +314,8 @@ export class EditorState {
if (alive.length !== s.objectIds.length) this.select(objectSelection(s.holderId, alive, s.objectId));
}
if (s.kind === 'node') {
const asset = findAssetOf(this.project, s.assetId, 'behavior');
// Fall back to the behavior asset so the graph stays open when its node vanished (undo).
const asset = findGraphAsset(this.project, s.assetId);
// Fall back to the asset so the graph stays open when its node vanished (undo).
if (!asset) this.select(null);
else {
const alive = s.nodeIds.filter((id) => asset.graph.nodes.some((n) => n.id === id));
@@ -346,12 +347,21 @@ export class EditorState {
/** The behavior asset the current selection refers to (asset, placed object or node), if any. */
get selectedBehaviorId(): string | null {
return this.selectedGraphId('behavior');
}
/** The state machine the current selection refers to: the asset, or one of its states. */
get selectedStateMachineId(): string | null {
return this.selectedGraphId('statemachine');
}
private selectedGraphId(type: 'behavior' | 'statemachine'): string | null {
const s = this.selection;
if (!s) return null;
if (s.kind === 'node') return s.assetId;
if (s.kind === 'frame') return null;
const asset = this.assetBehind(s);
return asset && asset.type === 'behavior' ? asset.id : null;
// A node names its asset; which tab that is depends on what the asset is.
const asset = s.kind === 'node' ? findAsset(this.project, s.assetId) : this.assetBehind(s);
return asset && asset.type === type ? asset.id : null;
}
/**
@@ -0,0 +1,42 @@
import { statesOf } from '../../core/graph';
import type { Asset, StateMachineAsset } from '../../core/model/Asset';
import { AssetTabEditor } from '../AssetTabEditor';
import { GraphCanvas } from '../graph/GraphCanvas';
import { SnapToggle } from '../graph/SnapToggle';
import type { EditorState } from '../state';
/** Room kept for the "N states" readout. */
const INFO_WIDTH = 90;
/**
* The states of one state machine, on the graph canvas the Behavior tab uses: a state is a node,
* so placing (right-click), moving, snapping, renaming, deleting and undo are the graph's.
* Transitions are a later step.
*/
export class StateMachineEditor extends AssetTabEditor<StateMachineAsset, GraphCanvas> {
private readonly snap = new SnapToggle(() => this.canvas);
constructor(state: EditorState) {
super(state, { noun: 'State machine', infoWidth: INFO_WIDTH });
this.mount(new GraphCanvas(state, 'state machine'), this.snap.widgets);
// Play swaps in the runtime copy of the project, and back.
state.on('mode', () => this.refresh());
}
protected override selectedId(): string {
return this.state.selectedStateMachineId ?? '';
}
protected override isMine(asset: Asset): asset is StateMachineAsset {
return asset.type === 'statemachine';
}
protected override infoText(asset: StateMachineAsset): string {
const count = statesOf(asset.graph).length;
return `${count} ${count === 1 ? 'state' : 'states'}`;
}
protected override syncExtras(asset: StateMachineAsset | null): void {
this.snap.setEnabled(Boolean(asset));
}
}
+8 -5
View File
@@ -10,7 +10,7 @@ import {
type Value,
} from '../../core/graph';
import { stepKeyRepeat } from '../../core/graph/keyRepeat';
import { behaviorLookup } from '../../core/model/behaviorPrograms';
import { graphLookup } from '../../core/model/graphLookup';
import { type PropertyBag, textOf } from '../../core/model/Properties';
import { findAssetOf, type Project } from '../../core/model/Project';
import { parentChain } from '../../core/model/walk';
@@ -41,6 +41,8 @@ interface Instance {
interpreter: GraphInterpreter;
trace: Omit<Trace, 'values'>;
values: Map<Graph, Map<string, Produced>>;
/** Current state per state machine – this instance's alone, like its variables. */
states: Record<string, string>;
}
/**
@@ -125,7 +127,7 @@ export class BehaviorSystem implements System {
if (!asset) continue;
const trace = { edges: new Map<string, number>(), nodes: new Map<string, number>() };
const values = new Map<Graph, Map<string, Produced>>();
const interpreter = new GraphInterpreter(asset.graph, behaviorLookup(this.project));
const interpreter = new GraphInterpreter(asset.graph, graphLookup(this.project));
interpreter.trace = {
onEdge: (id) => trace.edges.set(id, world.time),
onNode: (id) => trace.nodes.set(id, world.time),
@@ -135,7 +137,7 @@ export class BehaviorSystem implements System {
byNode.set(id, { time: world.time, values: produced });
},
} satisfies TraceListener;
const instance = { entity, interpreter, trace, values };
const instance: Instance = { entity, interpreter, trace, values, states: {} };
this.instances.push(instance);
this.run(instance, (i, ctx) => i.fire('OnStart', ctx), 0);
}
@@ -275,7 +277,7 @@ export class BehaviorSystem implements System {
): void {
const world = this.world;
if (!world) return;
const ctx = this.context(instance.entity, world, dt);
const ctx = this.context(instance, world, dt);
try {
body(instance.interpreter, ctx);
} catch (error) {
@@ -286,7 +288,7 @@ export class BehaviorSystem implements System {
}
}
private context(entity: Entity, world: World, dt: number): NodeContext {
private context({ entity, states }: Instance, world: World, dt: number): NodeContext {
// Handles arriving from the graph are the entities themselves, or test doubles with the same id.
const resolve = (handle: EntityHandle | null): Entity | undefined =>
handle ? world.entities.find((e) => e === handle || e.id === handle.id) : undefined;
@@ -294,6 +296,7 @@ export class BehaviorSystem implements System {
self: entity,
owner: entity.parent,
variables: entity.props,
states,
time: world.time,
dt,
findByName: (name) => world.findByName(name) ?? null,
+1
View File
@@ -54,6 +54,7 @@ export const Theme = {
categoryData: 0x2e8b57,
categoryVariable: 0xb8860b,
categoryAction: 0x2f6fd6,
categoryState: 0x8e5ad6,
portExec: 0xffffff,
portNumber: 0x6fcf97,
portBoolean: 0xe57373,