Play and stop a pattern from a behavior in the game #336
game-maker / gate (push) Successful in 3m21s
game-maker / suite (push) Failing after 13m22s

A pattern could only be heard in its tab. Songs come with #334, and
only then can #336 play them in a game. Until then a game plays a
single pattern, looped or once, through two new nodes.

- Play pattern plays the whole pattern through its instrument at its
  own tempo. The loop on the ruler is only for editing. Inputs are
  pattern, volume, loop (on by default) and detached. It gives out
  playback, 0 where there is no instrument or no note.
- Stop pattern stops one pattern, every pattern for none, or one
  playback by its number. Let ring lets notes with an Envelope fall
  away in their release.
- A playing is numbered and owned like a voice. Destroying the object,
  Stop sound with nothing named and the end of the run stop it. Stop
  sound with a voice takes a playback too.
- Each playing runs on a scheduler of its own (core/music/playbacks).
  It waits for its files first, and a stop that came earlier wins.
- The scheduler has an end for a sequence that does not loop. It stops
  waking there and is done once its last notes are.
- The worker clock moved to viewport/wake.ts, so SoundLibrary can use
  it without importing music.ts.

Tests:
- pattern-play.test.ts (new): 8 tests, node catalog +7 cases
- e2e 64 (melektaus-atx): ALL PASSED, 23 checks (+3)
- Gate (melektaus-atx): CHECK EXIT 0, 248 files, 3854 tests
- Counter-checks: no end in the scheduler, and no owner for the
  playing, each fail 1 test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
adminandClaude Opus 5.5 committed 2026-10-06 15:29:45 +02:00
1 parent 4ea752feef
commit 2a3b90b017
19 files changed
+745 -28

No files matched your search

+8
View File
@@ -269,6 +269,14 @@ export interface NodeContext {
instrumentParams: FxParams,
tempo: number,
): number;
/**
* Plays a pattern asset through its instrument, at its own tempo, once or round and round, every
* note at `volume`. Owned like a `playSound` voice. Returns its number, for `stopVoice`; 0 where
* there is nothing to play.
*/
playPattern(patternId: string, volume: number, loop: boolean, detached: boolean): number;
/** Stops every playing of that pattern, `''` every pattern; `letRing` lets its notes fall away in their release. */
stopPattern(patternId: string, letRing: boolean): void;
/**
* How many seconds one run of that sound asset lasts, so a change can span it; 0 where it does not
* exist or has not been loaded yet.
@@ -0,0 +1,52 @@
import type { NodeDef, PortDef } from '../../NodeRegistry';
import { asBoolean, asNumber, asString } from '../../values';
import { exec, num, withDefault } from '../shared';
export const patternPort = (): PortDef => ({
key: 'pattern',
label: 'pattern',
type: 'string',
field: { key: 'pattern', label: 'Pattern', kind: 'asset', default: '', assetTypes: ['pattern'] },
});
export const PlayPattern: NodeDef = {
type: 'PlayPattern',
label: 'Play pattern',
category: 'action',
description:
'Plays a pattern asset through its instrument, at the tempo the pattern has. The whole pattern ' +
'is played, from its start to its end: once, or with "loop" round and round until a Stop ' +
'pattern ends it – the loop set on its ruler is only for editing. "volume" makes every note of ' +
'it quieter. Each play is a playing of its own: firing this twice plays it twice, overlapping. ' +
'It belongs to this object like a sound and stops when the object is destroyed, unless ' +
'"detached" is on. "playback" is the number of this playing, for Stop pattern; 0 where the ' +
'pattern has no instrument or no notes.',
inputs: [
exec(),
patternPort(),
withDefault(num('volume'), 1),
{
key: 'loop',
label: 'loop',
type: 'boolean',
default: true,
field: { key: 'loop', label: 'Loop', kind: 'boolean', default: true },
},
{
key: 'detached',
label: 'detached',
type: 'boolean',
default: false,
field: { key: 'detached', label: 'Detached (outlives this object)', kind: 'boolean', default: false },
},
],
outputs: [exec(), num('playback')],
params: [],
run: (ctx, inputs) => {
const pattern = asString(inputs.pattern);
const playback = pattern
? ctx.playPattern(pattern, asNumber(inputs.volume), asBoolean(inputs.loop), asBoolean(inputs.detached))
: 0;
return { next: 'exec', outputs: { playback } };
},
};
@@ -0,0 +1,41 @@
import type { NodeDef } from '../../NodeRegistry';
import { asBoolean, asNumber, asString } from '../../values';
import { exec, num } from '../shared';
import { patternPort } from './PlayPattern';
export const StopPattern: NodeDef = {
type: 'StopPattern',
label: 'Stop pattern',
category: 'action',
description:
'Stops every playing of a pattern, however many Play pattern started. With no pattern picked it ' +
'stops every pattern, and leaves the sounds alone. With "playback" connected it stops only that ' +
'one playing, the number Play pattern handed out, and nothing where it is 0. Its notes fade out ' +
'in a few milliseconds; with "let ring" those of an instrument with an Envelope fall away in ' +
'its release.',
inputs: [
exec(),
patternPort(),
// Not typed in: unconnected it is null, and only then does the pattern decide.
{ ...num('playback'), inline: false },
{
key: 'letRing',
label: 'let ring',
type: 'boolean',
default: false,
field: { key: 'letRing', label: 'Let ring', kind: 'boolean', default: false },
},
],
outputs: [exec()],
params: [],
run: (ctx, inputs) => {
const letRing = asBoolean(inputs.letRing);
if (inputs.playback === null || inputs.playback === undefined)
ctx.stopPattern(asString(inputs.pattern), letRing);
else {
const playback = asNumber(inputs.playback);
if (playback > 0) ctx.stopVoice(playback, letRing);
}
return { next: 'exec' };
},
};
+4
View File
@@ -25,6 +25,8 @@ import { RestartGame } from './action/RestartGame';
import { SetPosition } from './action/SetPosition';
import { SetSoundFxParameters } from './action/SetSoundFxParameters';
import { PlayNote } from './action/PlayNote';
import { PlayPattern } from './action/PlayPattern';
import { StopPattern } from './action/StopPattern';
import { SetZ } from './action/SetZ';
import { Spawn } from './action/Spawn';
import { StopGame } from './action/StopGame';
@@ -308,6 +310,8 @@ export const BUILT_IN_NODES: readonly NodeDef[] = [
SoundFxParameters,
PlayNote,
InstrumentParameterValues,
PlayPattern,
StopPattern,
LoadScene,
Log,
StopGame,
+22 -4
View File
@@ -37,7 +37,8 @@ export interface SchedulerHost {
/** Starts the note, gives back the number of its voice; 0 where nothing plays. */
play(note: ScheduledNote): number;
playing(voice: number): boolean;
stop(voices: readonly number[]): void;
/** Ends these voices; with `letRing` a note falls away in the release of its Envelope. */
stop(voices: readonly number[], letRing?: boolean): void;
/** Calls `pump` every `INTERVAL` seconds, also in a hidden tab, until the returned function is called. */
wake(pump: () => void): () => void;
}
@@ -46,6 +47,8 @@ export interface SchedulerOptions {
tempo?: number;
meter?: Meter;
loop?: LoopRange | null;
/** Where it ends, in ticks of the sequence, when it does not loop: it plans nothing after that. */
end?: number;
}
/**
@@ -58,6 +61,9 @@ export class Scheduler {
private tempo: number;
private meter: Meter;
private loop: LoopRange | null;
private readonly end: number;
/** Planned up to its end: it wakes no more, and is over once its last notes are. */
private ended = false;
/** Where the playhead started, in ticks of the sequence. */
private from = 0;
/** Where on the audio clock playing time 0 is; null while stopped. */
@@ -77,12 +83,18 @@ export class Scheduler {
this.tempo = heldTempo(options.tempo ?? DEFAULT_TEMPO);
this.meter = heldMeter(options.meter ?? COMMON_TIME);
this.loop = heldLoop(options.loop ?? null);
this.end = options.end ?? Infinity;
}
get playing(): boolean {
return this.anchor !== null;
}
/** Played to its end, and none of its notes is heard any more. */
get done(): boolean {
return this.ended && this.voices.every((voice) => !this.host.playing(voice));
}
/** Plays from `from` ticks of the sequence, or from where it was last started or sent. */
start(from = this.from): void {
this.stop();
@@ -90,18 +102,19 @@ export class Scheduler {
this.anchor = this.host.now() + LEAD;
this.until = 0;
this.before = null;
this.ended = false;
this.sleep = this.host.wake(() => this.pump());
this.pump();
}
/** Every note it started fades out, those still to come with them. */
stop(): void {
/** Every note it started fades out, those still to come with them; with `letRing` in their release. */
stop(letRing = false): void {
this.sleep?.();
this.sleep = null;
if (this.anchor !== null) this.from = Math.floor(this.headAt(this.host.now()));
this.anchor = null;
this.before = null;
if (this.voices.length > 0) this.host.stop(this.voices);
if (this.voices.length > 0) this.host.stop(this.voices, letRing);
this.voices = [];
}
@@ -153,6 +166,11 @@ export class Scheduler {
if (voice !== 0) this.voices.push(voice);
}
this.until = to;
if (!this.loop && playheadAt(to, this.from, null) >= this.end) {
this.ended = true;
this.sleep?.();
this.sleep = null;
}
}
/** The playhead at a second of the audio clock; before the anchor, where it starts. */
+90
View File
@@ -0,0 +1,90 @@
import type { FxPlan } from '../soundfx/nodes';
import { type ScheduledNote, Scheduler, type SchedulerHost } from './Scheduler';
import type { Sequence } from './sequence';
/** What a game asks to hear of a pattern: its notes, how fast, how long, and whether round and round. */
export interface SequencePlay {
sequence: Sequence;
tempo: number;
/** In ticks: where it ends, and with `loop` where it starts again from 0. */
length: number;
loop: boolean;
/** What its notes are made of, loaded before the first one is planned. */
layers: readonly FxPlan[];
/** Starts one note as the player was asked to, and gives back the number of its voice. */
strike(note: ScheduledNote): number;
}
export interface PlaybackHost extends Omit<SchedulerHost, 'play'> {
prepare(layers: readonly FxPlan[]): Promise<void>;
}
export interface Playback {
id: number;
/** What stands for the pattern, as a file stands for a sound. */
name: string;
owner: string;
scheduler: Scheduler;
/** The last notes planned, newest last, for a check to hold against the clock. */
planned: ScheduledNote[];
}
/**
* The patterns a game plays (#336 ahead of songs): each on a scheduler of its own, numbered like a
* voice, owned like one and stopped like one. One played to its end goes by itself.
*/
export class Playbacks {
private list: Playback[] = [];
constructor(private readonly host: PlaybackHost) {}
/** Starts once its files are there; a stop that came first wins. */
start(id: number, name: string, play: SequencePlay, owner: string): void {
const planned: ScheduledNote[] = [];
const strike = (note: ScheduledNote) => {
planned.push(note);
if (planned.length > 64) planned.shift();
return play.strike(note);
};
const scheduler = new Scheduler({ ...this.host, play: strike }, () => play.sequence, {
tempo: play.tempo,
loop: play.loop ? { start: 0, end: play.length } : null,
end: play.length,
});
const playback = { id, name, owner, scheduler, planned };
this.list.push(playback);
void this.host.prepare(play.layers).then(() => {
if (this.list.includes(playback)) scheduler.start(0);
});
}
/** Whether that one is still to be heard: waiting on its files, playing, or its last notes ringing. */
has(id: number): boolean {
return this.current().some((playback) => playback.id === id);
}
/** Those whose name is `name`, every one where it is `''`. */
stopNamed(name: string, letRing = false): void {
this.stopWhere((playback) => name === '' || playback.name === name, letRing);
}
stopId(id: number, letRing = false): void {
this.stopWhere((playback) => playback.id === id, letRing);
}
/** An empty owner is no one, as for a voice: those were started to outlive whatever started them. */
stopOwner(owner: string): void {
if (owner !== '') this.stopWhere((playback) => playback.owner === owner, false);
}
/** What is playing, oldest first (test hook). */
current(): readonly Readonly<Playback>[] {
this.list = this.list.filter((playback) => !playback.scheduler.done);
return this.list;
}
private stopWhere(going: (playback: Playback) => boolean, letRing: boolean): void {
for (const playback of this.list.filter(going)) playback.scheduler.stop(letRing);
this.list = this.list.filter((playback) => !going(playback));
}
}