Refactoring round 7: split BehaviorSystem, fewer copies (#85)
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:
1 parent
dded62b9f9
commit
bc688f3efc
93 files changed
+914
-902
No files matched your search
@@ -6,7 +6,7 @@ import type { ColliderShape } from '../../core/properties/collider';
|
||||
import { toPixels } from './engine';
|
||||
|
||||
/** A pose that moved less than this (world units, radians) was not moved by anyone. */
|
||||
export const POSE_EPSILON = 1e-6;
|
||||
const POSE_EPSILON = 1e-6;
|
||||
|
||||
export interface Pose {
|
||||
x: number;
|
||||
|
||||
@@ -1,19 +1,15 @@
|
||||
import {
|
||||
adoptDeclarations,
|
||||
asNumber,
|
||||
buildSharedState,
|
||||
carriedForward,
|
||||
declaredVariables,
|
||||
emptySharedState,
|
||||
type EntityHandle,
|
||||
type Graph,
|
||||
type GraphNode,
|
||||
GraphInterpreter,
|
||||
hierarchyRanks,
|
||||
inEventOrder,
|
||||
isHandleEnabled,
|
||||
type NodeContext,
|
||||
type PhysicsControl,
|
||||
restartedAssets,
|
||||
restoreSaved,
|
||||
type SaveArea,
|
||||
@@ -24,28 +20,38 @@ import {
|
||||
type Value,
|
||||
} from '../../core/graph';
|
||||
import { GraphCache } from '../../core/graph/graphIndex';
|
||||
import { stepKeyRepeat } from '../../core/graph/keyRepeat';
|
||||
import { keyName } from '../../core/keys';
|
||||
import { graphLookup } from '../../core/model/graphLookup';
|
||||
import { type PropertyBag, textOf, type Vec2 } from '../../core/model/Properties';
|
||||
import { type PropertyBag, textOf } from '../../core/model/Properties';
|
||||
import { treeOrder } from '../../core/model/hierarchy';
|
||||
import { resolveObjects } from '../../core/model/instance';
|
||||
import { findAssetOf, findScene, type Project } from '../../core/model/Project';
|
||||
import { soundFileOf } from '../../core/model/sound';
|
||||
import { parentChain } from '../../core/model/walk';
|
||||
import { resolveAssetProps } from '../../core/properties/resolve';
|
||||
import { loopsOf, volumeOf } from '../../core/properties/sounds';
|
||||
import { type AudioSink, SILENT_AUDIO } from './Audio';
|
||||
import type { Entity } from '../Entity';
|
||||
import type { World } from '../World';
|
||||
import type { Rapier } from '../physics/engine';
|
||||
import { PhysicsSystem } from '../physics/PhysicsSystem';
|
||||
import { behaviorContext, type TimeScaled } from './behaviorContext';
|
||||
import {
|
||||
animationFinishedPulses,
|
||||
collisionEnterPulses,
|
||||
collisionExitPulses,
|
||||
collisionStayPulses,
|
||||
type Instance,
|
||||
keyDownPulses,
|
||||
type Produced,
|
||||
type Pulse,
|
||||
pulsesOf,
|
||||
timerPulses,
|
||||
} from './behaviorPulses';
|
||||
import { CollisionSystem } from './CollisionSystem';
|
||||
import { bodyOf, type CollisionPair, type CollisionSource, type Contact, NOT_BLOCKED } from './solids';
|
||||
import type { CollisionSource } from './solids';
|
||||
import { AnimationSystem } from './AnimationSystem';
|
||||
import type { Input } from './Input';
|
||||
import type { System } from './System';
|
||||
|
||||
export type { TimeScaled } from './behaviorContext';
|
||||
|
||||
/** How long (seconds) a traversed edge/node counts as "hot" for the editor's live highlight. */
|
||||
export const TRACE_FADE = 0.35;
|
||||
|
||||
@@ -56,11 +62,6 @@ export interface Trace {
|
||||
values: Map<string, Record<string, Value>>;
|
||||
}
|
||||
|
||||
interface Produced {
|
||||
time: number;
|
||||
values: Record<string, Value>;
|
||||
}
|
||||
|
||||
/**
|
||||
* A move one graph made, waiting for its events. `source` is the instance that caused it, and who
|
||||
* hears it when the machine is local; a `global` machine is heard by every instance, so the move it
|
||||
@@ -73,42 +74,9 @@ interface StateChange {
|
||||
source: Instance | null;
|
||||
}
|
||||
|
||||
const NO_DYNAMIC_BODY =
|
||||
'has no dynamic rigidbody, so Apply force, Apply impulse and Set velocity do nothing on it.';
|
||||
|
||||
/** How often state events may cause the next move before the run is called endless. */
|
||||
const MAX_STATE_ROUNDS = 100;
|
||||
|
||||
/** A collision pair seen from one behavior's body: its own collider and the one across. */
|
||||
interface Side {
|
||||
pair: CollisionPair;
|
||||
own: Entity;
|
||||
other: Entity;
|
||||
}
|
||||
|
||||
/** One event node about to run for one instance: what the event hands it, and the output it leaves by. */
|
||||
interface Pulse {
|
||||
instance: Instance;
|
||||
node: GraphNode;
|
||||
outputs?: Record<string, Value>;
|
||||
port?: string;
|
||||
}
|
||||
|
||||
interface Instance {
|
||||
entity: Entity;
|
||||
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>;
|
||||
/** Whether the behavior was effectively on when last looked at; a change fires On enable/On disable. */
|
||||
active: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the graph of every behavior entity. Each instance has its own interpreter (and
|
||||
* therefore its own timers and variable state); the project is only read to find graphs.
|
||||
*/
|
||||
const ERROR_PREFIX = 'Error in behavior';
|
||||
|
||||
export interface GameSystemOptions {
|
||||
@@ -130,10 +98,6 @@ export interface GameSystemOptions {
|
||||
saves?: SaveArea | null;
|
||||
}
|
||||
|
||||
export interface TimeScaled {
|
||||
scale: number;
|
||||
}
|
||||
|
||||
/** Collisions and animations are ticked first, so behaviors see this frame's events. */
|
||||
export function addGameSystems(
|
||||
world: World,
|
||||
@@ -179,6 +143,10 @@ export function behaviorError(world: World): string | undefined {
|
||||
return world.log.find((line) => line.startsWith(ERROR_PREFIX));
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the graph of every behavior entity. Each instance has its own interpreter (and
|
||||
* therefore its own timers and variable state); the project is only read to find graphs.
|
||||
*/
|
||||
export class BehaviorSystem implements System {
|
||||
/** A paused frame still ticks the behaviors that run while paused (see `update`). */
|
||||
readonly runsWhilePaused = true;
|
||||
@@ -511,17 +479,20 @@ export class BehaviorSystem implements System {
|
||||
const owner = i.entity.parent;
|
||||
return owner ? world.hitTest(owner, pointer.x, pointer.y) : pointer.inside;
|
||||
};
|
||||
const { input, collisions, animations } = this;
|
||||
const kinds: (() => Pulse[])[] = [
|
||||
() =>
|
||||
ticking.flatMap((i) => i.interpreter.eventNodes('OnKeyDown').flatMap((n) => this.keyDown(i, n, dt))),
|
||||
() => pulsesOf(ticking, 'OnKeyUp', {}, (n) => this.input.justReleased.has(keyOf(n))),
|
||||
() => pulsesOf(ticking, 'OnKeyHeld', { dt }, (n) => this.input.heldKeys.has(keyOf(n))),
|
||||
() => ticking.flatMap((i) => this.timers(i, dt)),
|
||||
ticking.flatMap((i) =>
|
||||
i.interpreter.eventNodes('OnKeyDown').flatMap((n) => keyDownPulses(i, n, input, dt)),
|
||||
),
|
||||
() => pulsesOf(ticking, 'OnKeyUp', {}, (n) => input.justReleased.has(keyOf(n))),
|
||||
() => pulsesOf(ticking, 'OnKeyHeld', { dt }, (n) => input.heldKeys.has(keyOf(n))),
|
||||
() => ticking.flatMap((i) => timerPulses(i, dt)),
|
||||
// Neither system ticked in a paused frame: what they hold is last frame's, already told.
|
||||
() => (frozen ? [] : ticking.flatMap((i) => this.collisionEnters(i))),
|
||||
() => (frozen ? [] : ticking.flatMap((i) => this.collisionStays(i, dt))),
|
||||
() => (frozen ? [] : ticking.flatMap((i) => this.collisionExits(i))),
|
||||
() => (frozen ? [] : ticking.flatMap((i) => this.animationsFinished(i))),
|
||||
() => (frozen ? [] : ticking.flatMap((i) => collisionEnterPulses(i, collisions))),
|
||||
() => (frozen ? [] : ticking.flatMap((i) => collisionStayPulses(i, collisions, dt))),
|
||||
() => (frozen ? [] : ticking.flatMap((i) => collisionExitPulses(i, collisions))),
|
||||
() => (frozen ? [] : ticking.flatMap((i) => animationFinishedPulses(i, animations))),
|
||||
() =>
|
||||
pointer.pressed ? pulsesOf(ticking.filter(pointed), 'OnClick', { x: pointer.x, y: pointer.y }) : [],
|
||||
() =>
|
||||
@@ -545,129 +516,6 @@ export class BehaviorSystem implements System {
|
||||
this.persist();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
private keyDown(instance: Instance, node: GraphNode, 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: this.input.justPressed.has(key),
|
||||
down: this.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 }));
|
||||
}
|
||||
|
||||
private timers(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.
|
||||
*/
|
||||
private 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 }] : [];
|
||||
});
|
||||
}
|
||||
|
||||
private collisionEnters(instance: Instance): Pulse[] {
|
||||
const sides = this.sides(instance, this.collisions?.enters ?? []);
|
||||
return instance.interpreter
|
||||
.eventNodes('OnCollisionEnter')
|
||||
.flatMap((node) => sides.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.
|
||||
*/
|
||||
private collisionStays(instance: Instance, dt: number): Pulse[] {
|
||||
const collisions = this.collisions;
|
||||
if (!collisions) return [];
|
||||
const interpreter = instance.interpreter;
|
||||
const stays = this.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;
|
||||
}
|
||||
|
||||
private collisionExits(instance: Instance): Pulse[] {
|
||||
const sides = this.sides(instance, this.collisions?.exits ?? []);
|
||||
return instance.interpreter
|
||||
.eventNodes('OnCollisionExit')
|
||||
.flatMap((node) => sides.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.
|
||||
*/
|
||||
private animationsFinished(instance: Instance): Pulse[] {
|
||||
const owner = instance.entity.parent;
|
||||
const finished = (this.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 } }));
|
||||
});
|
||||
}
|
||||
|
||||
runningIds(): string[] {
|
||||
return this.instances.map((i) => i.entity.objectId);
|
||||
}
|
||||
@@ -696,19 +544,6 @@ export class BehaviorSystem implements System {
|
||||
return merged;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the graph asked for, as the sink understands it: the asset's own volume scaled by the
|
||||
* node's, and its loop flag unless the node overrules it either way. The asset is what a sound
|
||||
* *is* – a node that says nothing therefore plays it as the project describes it.
|
||||
*/
|
||||
private playSound(assetId: string, volume: number, loop: boolean | undefined, owner: string): void {
|
||||
const asset = findAssetOf(this.project, assetId, 'sound');
|
||||
if (!asset?.file) return;
|
||||
const props = resolveAssetProps(this.project, asset);
|
||||
const level = Math.max(0, Math.min(1, volumeOf(props) * volume));
|
||||
this.audio.play(asset.file, level, loop ?? loopsOf(props), owner);
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the pulses of one event kind in their order (see `core/graph/eventOrder.ts`). An exception
|
||||
* stops play and is logged, never thrown. `living`: a pulse whose object an earlier one destroyed
|
||||
@@ -741,201 +576,14 @@ export class BehaviorSystem implements System {
|
||||
}
|
||||
|
||||
private context(instance: Instance, world: World, dt: number): NodeContext {
|
||||
const { entity, states } = instance;
|
||||
// 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;
|
||||
return {
|
||||
self: entity,
|
||||
owner: entity.parent,
|
||||
variables: entity.props,
|
||||
states,
|
||||
return behaviorContext(instance, world, dt, {
|
||||
project: this.project,
|
||||
input: this.input,
|
||||
collisions: this.collisions,
|
||||
audio: this.audio,
|
||||
clock: this.clock,
|
||||
shared: this.sharedState,
|
||||
stateChanged: (machineId, from, to) => this.pending.push({ machineId, from, to, source: instance }),
|
||||
time: world.time,
|
||||
dt,
|
||||
findByName: (name) => world.findByName(name) ?? null,
|
||||
// By identity, not by id: a restarted scene builds new entities under the same ids.
|
||||
isAlive: (target) => world.entities.some((e) => e === target),
|
||||
findReferenced: (from, ref) => {
|
||||
const found = resolve(from);
|
||||
return (found && world.findReferenced(found, ref)) ?? null;
|
||||
},
|
||||
childByName: (parent, name) => {
|
||||
const found = resolve(parent);
|
||||
return (found && world.childByName(found, name)) ?? null;
|
||||
},
|
||||
objects: () => world.entities,
|
||||
isKeyDown: (key) => this.input.isDown(key),
|
||||
pointer: world.pointer,
|
||||
hitTest: (target, x, y) => {
|
||||
const found = resolve(target);
|
||||
return Boolean(found && world.hitTest(found, x, y));
|
||||
},
|
||||
isTouching: (a, b) => {
|
||||
const ea = resolve(a);
|
||||
const eb = resolve(b);
|
||||
return Boolean(this.collisions && ea && eb && this.collisions.touching(world, ea, eb));
|
||||
},
|
||||
moveAndSlide: (target, dx, dy) => {
|
||||
const found = resolve(target);
|
||||
if (!found) return NOT_BLOCKED;
|
||||
if (this.collisions) return this.collisions.moveAndSlide(world, found, dx, dy);
|
||||
found.x += dx;
|
||||
found.y += dy;
|
||||
return NOT_BLOCKED;
|
||||
},
|
||||
raycast: (from, direction, length, { ignore, triggers, layers }) => {
|
||||
const hit = this.collisions?.raycast(world, from, direction, length, {
|
||||
ignore: resolve(ignore) ?? null,
|
||||
triggers,
|
||||
layers,
|
||||
});
|
||||
world.noteRay(from, hit?.point ?? pointAlong(from, direction, length), Boolean(hit));
|
||||
return hit ? { ...hit, object: bodyOf(hit.collider) } : null;
|
||||
},
|
||||
raycastAll: (from, direction, length, { ignore, triggers, layers, maxHits }) => {
|
||||
const hits =
|
||||
this.collisions?.raycastAll(
|
||||
world,
|
||||
from,
|
||||
direction,
|
||||
length,
|
||||
{ ignore: resolve(ignore) ?? null, triggers, layers },
|
||||
maxHits,
|
||||
) ?? [];
|
||||
// Drawn to the last thing it met, not to the first: that is how far this ray looked.
|
||||
const last = hits[hits.length - 1];
|
||||
const end = last ? last.point : pointAlong(from, direction, length);
|
||||
world.noteRay(from, end, hits.length > 0);
|
||||
return hits.map((hit) => ({ ...hit, object: bodyOf(hit.collider) }));
|
||||
},
|
||||
ignoreOneWay: (target, seconds) => {
|
||||
const found = resolve(target);
|
||||
if (found) world.ignoreOneWay(found, seconds);
|
||||
},
|
||||
isTilemap: (target) => {
|
||||
const found = resolve(target);
|
||||
return found ? world.isTilemap(found) : false;
|
||||
},
|
||||
tileAt: (target, layer, cell) => {
|
||||
const found = resolve(target);
|
||||
return found ? world.tileAt(found, layer, cell) : null;
|
||||
},
|
||||
setTile: (target, layer, cell, tileId) => {
|
||||
const found = resolve(target);
|
||||
return found ? world.setTile(found, layer, cell, tileId) : false;
|
||||
},
|
||||
physics:
|
||||
this.collisions instanceof PhysicsSystem
|
||||
? physicsControl(world, this.collisions, resolve)
|
||||
: undefined,
|
||||
log: (message) => {
|
||||
world.log.push(message);
|
||||
// The `Log` node's whole purpose: the author wants this in the browser console.
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(`[behavior ${entity.name}]`, message);
|
||||
},
|
||||
playSound: (assetId, volume, loop, detached) =>
|
||||
this.playSound(assetId, volume, loop, detached ? '' : entity.id),
|
||||
// An id nothing resolves stops nothing, rather than silencing the whole run by accident;
|
||||
// only the empty id means "everything", which is what the node promises.
|
||||
stopSound: (assetId) => {
|
||||
const file = assetId === '' ? '' : soundFileOf(this.project, assetId);
|
||||
if (assetId === '' || file) this.audio.stop(file);
|
||||
},
|
||||
spawn: (assetId, position, parent) => world.spawn(assetId, position, resolve(parent) ?? null),
|
||||
destroy: (target, keepChildren) => {
|
||||
const found = resolve(target);
|
||||
if (!found) return [];
|
||||
if (keepChildren) return world.removeKeepingChildren(found);
|
||||
world.remove(found);
|
||||
return [];
|
||||
},
|
||||
loadScene: (sceneId) => {
|
||||
// An id naming no scene is dropped here rather than half way through the swap, where the
|
||||
// run would already have torn down the world it is still standing in.
|
||||
if (findScene(this.project, sceneId)) world.loadSceneRequested = sceneId;
|
||||
else world.log.push(`Load scene: no scene ${sceneId}`);
|
||||
},
|
||||
stop: () => {
|
||||
world.stopRequested = true;
|
||||
},
|
||||
restart: () => {
|
||||
world.restartRequested = true;
|
||||
},
|
||||
timeScale: () => this.clock?.scale ?? 1,
|
||||
setTimeScale: (scale) => {
|
||||
if (this.clock) this.clock.scale = scale;
|
||||
else world.log.push(`Set time scale is ignored in the editor run (${scale})`);
|
||||
},
|
||||
isPaused: () => world.paused,
|
||||
setPaused: (paused) => {
|
||||
world.paused = paused;
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** Every node of one event type in these instances, in hierarchy and then node order. */
|
||||
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 })),
|
||||
);
|
||||
}
|
||||
|
||||
/** 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;
|
||||
}
|
||||
|
||||
/** Where a ray of that length ends; where it has no direction, where it starts. */
|
||||
function pointAlong(from: Vec2, direction: Vec2, length: number): Vec2 {
|
||||
const d = Math.hypot(direction.x, direction.y);
|
||||
if (!(d > 0) || !(length > 0)) return from;
|
||||
return { x: from.x + (direction.x / d) * length, y: from.y + (direction.y / d) * length };
|
||||
}
|
||||
|
||||
/** The physics nodes' way into the played game's engine, with the handles of the graph resolved. */
|
||||
function physicsControl(
|
||||
world: World,
|
||||
physics: PhysicsSystem,
|
||||
resolve: (handle: EntityHandle | null) => Entity | undefined,
|
||||
): PhysicsControl {
|
||||
const act = (handle: EntityHandle, action: (entity: Entity) => boolean): boolean => {
|
||||
const found = resolve(handle);
|
||||
if (!found) return false;
|
||||
if (action(found)) return true;
|
||||
physics.hint(world, found, NO_DYNAMIC_BODY);
|
||||
return false;
|
||||
};
|
||||
return {
|
||||
velocityOf: (handle) => {
|
||||
const found = resolve(handle);
|
||||
const v = found ? physics.velocityOf(found) : null;
|
||||
return found && v ? { ...v, angular: physics.angularVelocityOf(found) ?? 0 } : null;
|
||||
},
|
||||
setVelocity: (handle, x, y) => act(handle, (e) => physics.setVelocity(e, { x, y })),
|
||||
setAngularVelocity: (handle, degrees) => act(handle, (e) => physics.setAngularVelocity(e, degrees)),
|
||||
applyImpulse: (handle, x, y) => act(handle, (e) => physics.applyImpulse(e, { x, y })),
|
||||
setGravity: (x, y) => physics.setGravity(world, { x, y }),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
/**
|
||||
* What a behavior's graph reaches of the running game, as the `NodeContext` its nodes are handed:
|
||||
* the world, the keyboard, collisions and rays, physics, sound, the clock and the shared values.
|
||||
* Handles arriving from a graph are resolved to the world's entities here, so no node holds one.
|
||||
*/
|
||||
import type { EntityHandle, NodeContext, PhysicsControl, SharedState } from '../../core/graph';
|
||||
import type { Vec2 } from '../../core/model/Properties';
|
||||
import { findAssetOf, findScene, type Project } from '../../core/model/Project';
|
||||
import { soundFileOf } from '../../core/model/sound';
|
||||
import { resolveAssetProps } from '../../core/properties/resolve';
|
||||
import { loopsOf, volumeOf } from '../../core/properties/sounds';
|
||||
import type { Entity } from '../Entity';
|
||||
import { PhysicsSystem } from '../physics/PhysicsSystem';
|
||||
import type { World } from '../World';
|
||||
import type { AudioSink } from './Audio';
|
||||
import type { Instance } from './behaviorPulses';
|
||||
import type { Input } from './Input';
|
||||
import { bodyOf, type CollisionSource, NOT_BLOCKED } from './solids';
|
||||
|
||||
export interface TimeScaled {
|
||||
scale: number;
|
||||
}
|
||||
|
||||
/** What the running `BehaviorSystem` lends every context it makes. */
|
||||
export interface ContextSources {
|
||||
project: Project;
|
||||
input: Input;
|
||||
collisions: CollisionSource | null;
|
||||
audio: AudioSink;
|
||||
clock: TimeScaled | null;
|
||||
shared: SharedState;
|
||||
/** A graph moved one of this instance's machines; its events follow between exec flows. */
|
||||
stateChanged(machineId: string, from: string, to: string): void;
|
||||
}
|
||||
|
||||
const NO_DYNAMIC_BODY =
|
||||
'has no dynamic rigidbody, so Apply force, Apply impulse and Set velocity do nothing on it.';
|
||||
|
||||
export function behaviorContext(
|
||||
instance: Instance,
|
||||
world: World,
|
||||
dt: number,
|
||||
run: ContextSources,
|
||||
): NodeContext {
|
||||
const { entity, states } = instance;
|
||||
const { project, collisions, clock } = run;
|
||||
// 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;
|
||||
return {
|
||||
self: entity,
|
||||
owner: entity.parent,
|
||||
variables: entity.props,
|
||||
states,
|
||||
shared: run.shared,
|
||||
stateChanged: (machineId, from, to) => run.stateChanged(machineId, from, to),
|
||||
time: world.time,
|
||||
dt,
|
||||
findByName: (name) => world.findByName(name) ?? null,
|
||||
// By identity, not by id: a restarted scene builds new entities under the same ids.
|
||||
isAlive: (target) => world.entities.some((e) => e === target),
|
||||
findReferenced: (from, ref) => {
|
||||
const found = resolve(from);
|
||||
return (found && world.findReferenced(found, ref)) ?? null;
|
||||
},
|
||||
childByName: (parent, name) => {
|
||||
const found = resolve(parent);
|
||||
return (found && world.childByName(found, name)) ?? null;
|
||||
},
|
||||
objects: () => world.entities,
|
||||
isKeyDown: (key) => run.input.isDown(key),
|
||||
pointer: world.pointer,
|
||||
hitTest: (target, x, y) => {
|
||||
const found = resolve(target);
|
||||
return Boolean(found && world.hitTest(found, x, y));
|
||||
},
|
||||
isTouching: (a, b) => {
|
||||
const ea = resolve(a);
|
||||
const eb = resolve(b);
|
||||
return Boolean(collisions && ea && eb && collisions.touching(world, ea, eb));
|
||||
},
|
||||
moveAndSlide: (target, dx, dy) => {
|
||||
const found = resolve(target);
|
||||
if (!found) return NOT_BLOCKED;
|
||||
if (collisions) return collisions.moveAndSlide(world, found, dx, dy);
|
||||
found.x += dx;
|
||||
found.y += dy;
|
||||
return NOT_BLOCKED;
|
||||
},
|
||||
raycast: (from, direction, length, { ignore, triggers, layers }) => {
|
||||
const hit = collisions?.raycast(world, from, direction, length, {
|
||||
ignore: resolve(ignore) ?? null,
|
||||
triggers,
|
||||
layers,
|
||||
});
|
||||
world.noteRay(from, hit?.point ?? pointAlong(from, direction, length), Boolean(hit));
|
||||
return hit ? { ...hit, object: bodyOf(hit.collider) } : null;
|
||||
},
|
||||
raycastAll: (from, direction, length, { ignore, triggers, layers, maxHits }) => {
|
||||
const hits =
|
||||
collisions?.raycastAll(
|
||||
world,
|
||||
from,
|
||||
direction,
|
||||
length,
|
||||
{ ignore: resolve(ignore) ?? null, triggers, layers },
|
||||
maxHits,
|
||||
) ?? [];
|
||||
// Drawn to the last thing it met, not to the first: that is how far this ray looked.
|
||||
const last = hits[hits.length - 1];
|
||||
const end = last ? last.point : pointAlong(from, direction, length);
|
||||
world.noteRay(from, end, hits.length > 0);
|
||||
return hits.map((hit) => ({ ...hit, object: bodyOf(hit.collider) }));
|
||||
},
|
||||
ignoreOneWay: (target, seconds) => {
|
||||
const found = resolve(target);
|
||||
if (found) world.ignoreOneWay(found, seconds);
|
||||
},
|
||||
isTilemap: (target) => {
|
||||
const found = resolve(target);
|
||||
return found ? world.isTilemap(found) : false;
|
||||
},
|
||||
tileAt: (target, layer, cell) => {
|
||||
const found = resolve(target);
|
||||
return found ? world.tileAt(found, layer, cell) : null;
|
||||
},
|
||||
setTile: (target, layer, cell, tileId) => {
|
||||
const found = resolve(target);
|
||||
return found ? world.setTile(found, layer, cell, tileId) : false;
|
||||
},
|
||||
physics: collisions instanceof PhysicsSystem ? physicsControl(world, collisions, resolve) : undefined,
|
||||
log: (message) => {
|
||||
world.log.push(message);
|
||||
// The `Log` node's whole purpose: the author wants this in the browser console.
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(`[behavior ${entity.name}]`, message);
|
||||
},
|
||||
playSound: (assetId, volume, loop, detached) =>
|
||||
playSound(run, assetId, volume, loop, detached ? '' : entity.id),
|
||||
// An id nothing resolves stops nothing, rather than silencing the whole run by accident;
|
||||
// only the empty id means "everything", which is what the node promises.
|
||||
stopSound: (assetId) => {
|
||||
const file = assetId === '' ? '' : soundFileOf(project, assetId);
|
||||
if (assetId === '' || file) run.audio.stop(file);
|
||||
},
|
||||
spawn: (assetId, position, parent) => world.spawn(assetId, position, resolve(parent) ?? null),
|
||||
destroy: (target, keepChildren) => {
|
||||
const found = resolve(target);
|
||||
if (!found) return [];
|
||||
if (keepChildren) return world.removeKeepingChildren(found);
|
||||
world.remove(found);
|
||||
return [];
|
||||
},
|
||||
loadScene: (sceneId) => {
|
||||
// An id naming no scene is dropped here rather than half way through the swap, where the
|
||||
// run would already have torn down the world it is still standing in.
|
||||
if (findScene(project, sceneId)) world.loadSceneRequested = sceneId;
|
||||
else world.log.push(`Load scene: no scene ${sceneId}`);
|
||||
},
|
||||
stop: () => {
|
||||
world.stopRequested = true;
|
||||
},
|
||||
restart: () => {
|
||||
world.restartRequested = true;
|
||||
},
|
||||
timeScale: () => clock?.scale ?? 1,
|
||||
setTimeScale: (scale) => {
|
||||
if (clock) clock.scale = scale;
|
||||
else world.log.push(`Set time scale is ignored in the editor run (${scale})`);
|
||||
},
|
||||
isPaused: () => world.paused,
|
||||
setPaused: (paused) => {
|
||||
world.paused = paused;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* What the graph asked for, as the sink understands it: the asset's own volume scaled by the
|
||||
* node's, and its loop flag unless the node overrules it either way. The asset is what a sound
|
||||
* *is* – a node that says nothing therefore plays it as the project describes it.
|
||||
*/
|
||||
function playSound(
|
||||
{ project, audio }: ContextSources,
|
||||
assetId: string,
|
||||
volume: number,
|
||||
loop: boolean | undefined,
|
||||
owner: string,
|
||||
): void {
|
||||
const asset = findAssetOf(project, assetId, 'sound');
|
||||
if (!asset?.file) return;
|
||||
const props = resolveAssetProps(project, asset);
|
||||
const level = Math.max(0, Math.min(1, volumeOf(props) * volume));
|
||||
audio.play(asset.file, level, loop ?? loopsOf(props), owner);
|
||||
}
|
||||
|
||||
/** Where a ray of that length ends; where it has no direction, where it starts. */
|
||||
function pointAlong(from: Vec2, direction: Vec2, length: number): Vec2 {
|
||||
const d = Math.hypot(direction.x, direction.y);
|
||||
if (!(d > 0) || !(length > 0)) return from;
|
||||
return { x: from.x + (direction.x / d) * length, y: from.y + (direction.y / d) * length };
|
||||
}
|
||||
|
||||
/** The physics nodes' way into the played game's engine, with the handles of the graph resolved. */
|
||||
function physicsControl(
|
||||
world: World,
|
||||
physics: PhysicsSystem,
|
||||
resolve: (handle: EntityHandle | null) => Entity | undefined,
|
||||
): PhysicsControl {
|
||||
const act = (handle: EntityHandle, action: (entity: Entity) => boolean): boolean => {
|
||||
const found = resolve(handle);
|
||||
if (!found) return false;
|
||||
if (action(found)) return true;
|
||||
physics.hint(world, found, NO_DYNAMIC_BODY);
|
||||
return false;
|
||||
};
|
||||
return {
|
||||
velocityOf: (handle) => {
|
||||
const found = resolve(handle);
|
||||
const v = found ? physics.velocityOf(found) : null;
|
||||
return found && v ? { ...v, angular: physics.angularVelocityOf(found) ?? 0 } : null;
|
||||
},
|
||||
setVelocity: (handle, x, y) => act(handle, (e) => physics.setVelocity(e, { x, y })),
|
||||
setAngularVelocity: (handle, degrees) => act(handle, (e) => physics.setAngularVelocity(e, degrees)),
|
||||
applyImpulse: (handle, x, y) => act(handle, (e) => physics.applyImpulse(e, { x, y })),
|
||||
setGravity: (x, y) => physics.setGravity(world, { x, y }),
|
||||
};
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
Reference in new issue
Block a user