Refactoring round 7: split BehaviorSystem, fewer copies (#85)
game-maker / gate (push) Successful in 3m50s
game-maker / suite (push) Successful in 12m3s

Recurring cleanup round over the code since round 6 (056a622), 105
commits. Behaviour is unchanged. Duplicated code in src went from 29
clones with 229 lines (0.32 %) to 14 clones with 109 lines (0.15 %),
measured with jscpd and the same settings as round 6.

- BehaviorSystem.ts shrinks from 941 to 589 lines. Collecting the
  pulses (keys, timers, collisions, animations) moved to
  behaviorPulses.ts. The NodeContext the nodes receive moved to
  behaviorContext.ts. Imports from outside stay the same, TimeScaled
  is still exported from BehaviorSystem.ts.
- PointKindButton and drawPointGrip replace the "Point:" button with
  its menu and the point and handle drawing that the curve and the
  vector art tab each had on their own.
- lerpVec, cubicAt and splitCubic in src/core/util/vec.ts replace four
  copies of the cubic curve and two de Casteljau splits.
- mapNested in Properties.ts is the one walk over lists and structs
  that liveObjects and objectRefs did separately. withFieldRenamed
  and withoutField replace three copies of renaming a struct field
  and two of removing one.
- jsonBody and staleRevision build the JSON body and turn a 409 into
  StaleRevisionError for all stores. The auth store turns a 401 into
  its error in one place.
- Smaller helpers: structAssetFrom for the two "Make struct type"
  commands, shownObject in the inspector, selectedItem for the size
  gizmo and the polygon corners, solidTiles in the tilemap collision,
  requireVariablesAsset and requireBehaviorVariable.
- Left as is on purpose: the plain forwarding from the collision and
  physics systems to Solids, the pointer wiring of the canvases and
  the identical last lines of the two make commands.
- Removed unused code: tilemapTileIds and tilemapsUsing were never
  called since #128 and #131. EditorState.runtimeProject became unused
  with GameRun in #266. The assetId getter of the make commands was
  read only by a test.
- 60 values used only in their own file lost their export. The shader
  and particle node catalogues stay exported as in round 6.
- Five comments that told history now describe the current state. The
  doc comment of BehaviorSystem sits on the class again.
- README lists the struct, clip area and curve assets and mentions the
  game link from #266.

Findings:
- Deleting a tile that is painted on a tilemap leaves its cells in
  place, and they draw nothing. The delete dialog does not mention the
  tilemaps. That was probably the job of the unused tilemapsUsing.
  Left as is, because fixing it changes behaviour.
- The solid filter for tile surfaces was untested. A bent filter
  stayed green. A new test in tests/core/surface.test.ts now fails
  against it.

Tests:
- ./check.sh: 195 files, 2815 tests, exit 0 (one test removed with
  tilemapsUsing, one added for tile surfaces).
- Full e2e run: ALL PASSED, 1580 checks.
- Smokes jumprun, tetris, actor: 24, 19 and 21 checks, all passed.
  The example project files were restored byte for byte afterwards.
- Counter-checks, 12, all fail as expected: 10 in unit tests (among
  them mapNested, splitCubic, cubicAt, staleRevision, the stay pulse,
  the late timer and the time scale), 2 in the browser (Point button
  always enabled fails 47, selectedItem without a hit fails 29).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
adminandClaude Opus 5.5 committed 2026-09-29 16:16:37 +02:00
1 parent dded62b9f9
commit bc688f3efc
93 files changed
+914 -902

No files matched your search

+203
View File
@@ -0,0 +1,203 @@
/**
* A running behavior, and the pulses the events of one frame send into it: one per event node that
* fires, with what the event hands on. `BehaviorSystem` decides when each kind is gathered and runs
* them in their order.
*/
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 { parentChain } from '../../core/model/walk';
import type { Entity } from '../Entity';
import type { AnimationSystem } from './AnimationSystem';
import type { Input } from './Input';
import { bodyOf, type CollisionPair, type CollisionSource, type Contact } from './solids';
/** What one node last handed on, and when – the graph tab shows the newest of every instance. */
export interface Produced {
time: number;
values: Record<string, Value>;
}
export interface Instance {
entity: Entity;
interpreter: GraphInterpreter;
/** Recency of exec edges and nodes, keyed by id, in world time. */
trace: { edges: Map<string, number>; nodes: Map<string, number> };
values: Map<Graph, Map<string, Produced>>;
/** Current state per state machine – this instance's alone, like its variables. */
states: Record<string, string>;
/** Whether the behavior was effectively on when last looked at; a change fires On enable/On disable. */
active: boolean;
}
/** One event node about to run for one instance: what the event hands it, and the output it leaves by. */
export interface Pulse {
instance: Instance;
node: GraphNode;
outputs?: Record<string, Value>;
port?: string;
}
/** A collision pair seen from one behavior's body: its own collider and the one across. */
interface Side {
pair: CollisionPair;
own: Entity;
other: Entity;
}
/** Every node of one event type in these instances, in hierarchy and then node order. */
export function pulsesOf(
instances: readonly Instance[],
type: string,
outputs: Record<string, Value> = {},
filter?: (node: GraphNode) => boolean,
): Pulse[] {
return instances.flatMap((instance) =>
instance.interpreter
.eventNodes(type)
.filter((node) => !filter || filter(node))
.map((node) => ({ instance, node, outputs })),
);
}
/**
* The press plus whatever repeats holding the key has earned. Each node keeps its own hold clock
* in `nodeState`, so two nodes on the same key repeat on their own schedules.
*/
export function keyDownPulses(instance: Instance, node: GraphNode, input: Input, dt: number): Pulse[] {
const i = instance.interpreter;
const key = keyName(textOf(node.params.key ?? ''));
const stored = i.nodeState.get(node.id);
const { state, fires } = stepKeyRepeat(
stored ? { held: stored.held ?? 0, repeats: stored.repeats ?? 0 } : null,
{
pressed: input.justPressed.has(key),
down: input.heldKeys.has(key),
dt,
// The node asks for milliseconds so the fields stay whole numbers; the clock runs in seconds.
after: asNumber(node.params.repeatAfter ?? 0) / 1000,
interval: asNumber(node.params.repeatInterval ?? 0) / 1000,
},
);
if (state) i.nodeState.set(node.id, { held: state.held, repeats: state.repeats });
else i.nodeState.delete(node.id);
return Array.from({ length: fires }, () => ({ instance, node }));
}
export function timerPulses(instance: Instance, dt: number): Pulse[] {
const i = instance.interpreter;
const pulses: Pulse[] = [];
for (const node of i.eventNodes('OnTimer')) {
const state = i.nodeState.get(node.id) ?? { elapsed: 0 };
i.nodeState.set(node.id, state);
const interval = Math.max(0.01, Number(node.params.interval ?? 1));
state.elapsed = (state.elapsed ?? 0) + dt;
// What is left after taking one interval is how long ago this tick was due. When one frame
// catches up several ticks, the first one was due longest ago and is the latest.
while (state.elapsed >= interval) {
state.elapsed -= interval;
pulses.push({ instance, node, outputs: { late: state.elapsed } });
}
}
return pulses;
}
/**
* The collision pairs of one kind that concern this behavior: every pair in which one collider
* belongs to the behavior's body (its owner, or itself when it has none), with `other` being the
* body on the far side.
*/
function sides(instance: Instance, pairs: readonly CollisionPair[]): Side[] {
const body = instance.entity.parent ?? instance.entity;
return pairs.flatMap((pair) => {
const own = bodyOf(pair.a) === body ? pair.a : bodyOf(pair.b) === body ? pair.b : null;
return own ? [{ pair, own, other: own === pair.a ? pair.b : pair.a }] : [];
});
}
export function collisionEnterPulses(instance: Instance, collisions: CollisionSource | null): Pulse[] {
const entered = sides(instance, collisions?.enters ?? []);
return instance.interpreter
.eventNodes('OnCollisionEnter')
.flatMap((node) => entered.map((side) => ({ instance, node, outputs: sideOutputs(side, side.pair) })));
}
/**
* Stay fires every frame or, with an interval, once each time that long has passed since the pair
* met (#149). Each stay node keeps a clock per pair in its node state, and a pair that is gone
* takes its clock with it.
*/
export function collisionStayPulses(
instance: Instance,
collisions: CollisionSource | null,
dt: number,
): Pulse[] {
if (!collisions) return [];
const interpreter = instance.interpreter;
const stays = sides(instance, collisions.stays);
const contacts = new Map<CollisionPair, Contact | null>();
const contactOf = (pair: CollisionPair) => {
if (!contacts.has(pair)) contacts.set(pair, collisions.contactOf(pair));
return contacts.get(pair)!;
};
const pulses: Pulse[] = [];
for (const node of interpreter.eventNodes('OnCollisionStay')) {
const interval = Math.max(0, Number(node.params.interval ?? 0)) || 0;
const clocks = interpreter.nodeState.get(node.id) ?? {};
const running: Record<string, number> = {};
for (const side of stays) {
let fires = 1;
if (interval > 0) {
const key = `${side.pair.a.id}|${side.pair.b.id}`;
let elapsed = (clocks[key] ?? 0) + dt;
for (fires = 0; elapsed >= interval - 1e-9; fires++) elapsed -= interval;
running[key] = elapsed;
}
for (let i = 0; i < fires; i++)
pulses.push({ instance, node, outputs: sideOutputs(side, contactOf(side.pair)) });
}
if (interval > 0) interpreter.nodeState.set(node.id, running);
else interpreter.nodeState.delete(node.id);
}
return pulses;
}
export function collisionExitPulses(instance: Instance, collisions: CollisionSource | null): Pulse[] {
const left = sides(instance, collisions?.exits ?? []);
return instance.interpreter
.eventNodes('OnCollisionExit')
.flatMap((node) => left.map((side) => ({ instance, node, outputs: sideOutputs(side) })));
}
/**
* A behavior hears the sprites of its owner's subtree – the owner itself, or a sprite placed below
* it next to the behavior. Without an owner it hears every sprite, like `On click` hears the view.
*/
export function animationFinishedPulses(instance: Instance, animations: AnimationSystem | null): Pulse[] {
const owner = instance.entity.parent;
const finished = (animations?.finished ?? []).filter(
({ entity }) => !owner || [...parentChain(entity, (e) => e.parent)].includes(owner),
);
return instance.interpreter.eventNodes('OnAnimationFinished').flatMap((node) => {
const wanted = textOf(node.params.animation ?? '');
return finished
.filter(({ animationId }) => wanted === '' || wanted === animationId)
.map(({ entity }) => ({ instance, node, outputs: { object: entity } }));
});
}
/** What a collision event hands on, seen from the behavior's side; `contact` only for enter and stay. */
function sideOutputs({ own, other, pair }: Side, contact?: Partial<Contact> | null): Record<string, Value> {
const outputs: Record<string, Value> = { other: bodyOf(other), otherCollider: other, collider: own };
if (contact !== undefined) {
// The pair's normal points towards `a`; seen from `b` it points the other way.
const sign = own === pair.a ? 1 : -1;
outputs.normalX = sign * (contact?.normal?.x ?? 0) || 0;
outputs.normalY = sign * (contact?.normal?.y ?? 0) || 0;
outputs.impulse = contact?.impulse ?? 0;
outputs.pointX = contact?.point?.x ?? 0;
outputs.pointY = contact?.point?.y ?? 0;
}
return outputs;
}