Final clean up
Some checks failed
Check & deploy / build (pull_request) Failing after 1m16s

This commit is contained in:
Andras Schmelczer 2026-05-24 10:52:20 +01:00
commit c40c5d97db
58 changed files with 863 additions and 669 deletions

View file

@ -4,6 +4,7 @@ import {
type PlausibleEventOptions,
} from '@plausible-analytics/tracker';
import { appConfig } from './config';
import type { VibeId } from './vibes';
let isInitialized = false;
@ -23,10 +24,10 @@ export const initAnalytics = () => {
try {
plausibleInit({
domain: 'schmelczer.dev/floating',
endpoint: 'https://stats.schmelczer.dev/status',
autoCapturePageviews: true,
logging: true,
domain: appConfig.analytics.domain,
endpoint: appConfig.analytics.endpoint,
autoCapturePageviews: appConfig.analytics.autoCapturePageviews,
logging: appConfig.analytics.logging,
});
isInitialized = true;
} catch (error) {

View file

@ -1,6 +1,7 @@
import type { PianoNoteRole } from './garden-audio-types';
const DEFAULT_AUDIO_VOLUME = 0.5;
export const DEFAULT_AUDIO_VOLUME = 0.5;
export const SILENT_AUDIO_GAIN = 0.0001;
type GardenAudioChordQuality = 'major' | 'minor' | 'sus2' | 'sus4';

View file

@ -1,7 +1,9 @@
import { clamp } from '../utils/math';
import type { GardenAudioConfig } from './garden-audio-config';
import { SILENT_AUDIO_GAIN, type GardenAudioConfig } from './garden-audio-config';
import type { PianoNoteRole } from './garden-audio-types';
type AudioSessionType = NonNullable<NavigatorWithAudioSession['audioSession']>['type'];
type NavigatorWithAudioSession = Navigator & {
audioSession?: {
type:
@ -17,7 +19,7 @@ type NavigatorWithAudioSession = Navigator & {
const outputHighPassFrequencyHz = 45;
const noiseBufferDurationSeconds = 1;
const graphTuning = {
closeGain: 0.0001,
closeGain: SILENT_AUDIO_GAIN,
closeRampSeconds: 0.015,
delayMaxSeconds: 2,
eventBusGain: 1,
@ -54,6 +56,7 @@ export class GardenAudioGraph {
private pianoBusGainScale = 1;
private pianoBusGainScaleAutomationUntil = 0;
private pianoBusGainScaleTimeConstantSeconds = 0;
private previousAudioSessionType: AudioSessionType | null = null;
private readonly pianoBuses = new Map<PianoNoteRole, GainNode>();
public constructor(private readonly config: GardenAudioConfig) {}
@ -77,6 +80,7 @@ export class GardenAudioGraph {
// Audio Session API.
const audioSession = (navigator as NavigatorWithAudioSession).audioSession;
if (audioSession) {
this.previousAudioSessionType ??= audioSession.type;
audioSession.type = 'playback';
}
@ -203,6 +207,21 @@ export class GardenAudioGraph {
if (context.state !== 'closed') {
await context.close().catch(() => undefined);
}
this.restoreAudioSessionType();
}
private restoreAudioSessionType(): void {
const previousType = this.previousAudioSessionType;
this.previousAudioSessionType = null;
if (previousType === null) {
return;
}
const audioSession = (navigator as NavigatorWithAudioSession).audioSession;
if (audioSession) {
audioSession.type = previousType;
}
}
private createDelay(context: AudioContext, masterGain: GainNode): void {

View file

@ -13,8 +13,6 @@ const DEFAULT_PROGRESSION: ReadonlyArray<GardenAudioChord> = [
const DEFAULT_ROOT_MIDI = 57;
const DEFAULT_SCALE: ReadonlyArray<number> = [0, 2, 4, 7, 9];
const profileCache = new WeakMap<VibePreset, GardenAudioVibeProfile>();
const getProfileScale = (vibe: VibePreset): Array<number> => {
const scale = vibe.audio.scale?.length ? vibe.audio.scale : DEFAULT_SCALE;
return [...scale];
@ -26,21 +24,10 @@ const getProfileProgression = (vibe: VibePreset): Array<GardenAudioChord> =>
);
export const getVibeProfile = (vibe: VibePreset): GardenAudioVibeProfile => {
let profile = profileCache.get(vibe);
if (!profile) {
profile = {
...vibe.audio,
rootMidi: DEFAULT_ROOT_MIDI + vibe.audio.notePitchOffset,
scale: getProfileScale(vibe),
progression: getProfileProgression(vibe),
};
profileCache.set(vibe, profile);
return profile;
}
Object.assign(profile, vibe.audio);
profile.rootMidi = DEFAULT_ROOT_MIDI + vibe.audio.notePitchOffset;
profile.scale = getProfileScale(vibe);
profile.progression = getProfileProgression(vibe);
return profile;
return {
...vibe.audio,
rootMidi: DEFAULT_ROOT_MIDI + vibe.audio.notePitchOffset,
scale: getProfileScale(vibe),
progression: getProfileProgression(vibe),
};
};

View file

@ -1,4 +1,4 @@
import { VibePreset } from '../vibes';
import type { VibePreset } from '../vibes';
export interface GardenAudioSnapshot {
vibe: VibePreset;

View file

@ -1,7 +1,11 @@
import { ErrorHandler, Severity } from '../utils/error-handler';
import { clamp01 } from '../utils/math';
import type { VibeId, VibePreset } from '../vibes';
import type { GardenAudioConfig, GardenAudioVibeProfile } from './garden-audio-config';
import {
SILENT_AUDIO_GAIN,
type GardenAudioConfig,
type GardenAudioVibeProfile,
} from './garden-audio-config';
import { GardenAudioEnergy } from './garden-audio-energy';
import { GardenAudioGestureState } from './garden-audio-gesture-state';
import { GardenAudioGraph } from './garden-audio-graph';
@ -13,8 +17,12 @@ import { NoiseBurstPlayer } from './noise-burst-player';
import { PianoSampler } from './piano-sampler';
type AudioLifecycle = 'idle' | 'started' | 'destroyed';
type PianoReleasePhase =
| { kind: 'idle' }
| { kind: 'awaiting-fade' }
| { kind: 'scheduled-fade'; fadeAt: number }
| { kind: 'settling'; stopAt: number };
const muteGain = 0.0001;
const muteRampSeconds = 0.02;
const brushUpPianoBusFadeSeconds = 2.4;
const brushUpPianoBusFadeSettleSeconds = 3.2;
@ -29,16 +37,16 @@ export class GardenAudio {
private readonly pianoEngine: GenerativePianoEngine;
private currentVibeId: VibeId | null = null;
private currentVibe: VibePreset | null = null;
private lifecycle: AudioLifecycle = 'idle';
private isReleasingPiano = false;
private pianoReleasePhase: PianoReleasePhase = { kind: 'idle' };
private isMuted = false;
private isGestureActive = false;
private fadePianoAt: number | null = null;
private masterVolume: number;
private stopPianoAt: number | null = null;
private lastEraserAt = Number.NEGATIVE_INFINITY;
private lastVibeStingerAt = Number.NEGATIVE_INFINITY;
private startRequestId = 0;
private hasLoadedPiano = false;
public constructor(private readonly config: GardenAudioConfig) {
this.masterVolume = clamp01(config.masterVolume);
@ -60,7 +68,8 @@ export class GardenAudio {
if (
this.lifecycle === 'started' &&
this.currentVibeId === vibe.id &&
this.graph.context?.state === 'running'
this.graph.context?.state === 'running' &&
this.hasLoadedPiano
) {
return;
}
@ -74,6 +83,7 @@ export class GardenAudio {
? muteRampSeconds
: this.config.fadeInSeconds;
const needsResume = context.state !== 'running' && context.state !== 'closed';
const startRequestId = ++this.startRequestId;
if (needsResume) {
if (!isUserGesture) {
@ -83,7 +93,7 @@ export class GardenAudio {
.resume()
.then(() => {
if (this.graph.context === context && this.lifecycle !== 'destroyed') {
this.completeStart(vibe, { context, startupRampSeconds });
this.completeStart(vibe, { context, startupRampSeconds, startRequestId });
}
})
.catch((error) => {
@ -95,16 +105,18 @@ export class GardenAudio {
return;
}
this.completeStart(vibe, { context, startupRampSeconds });
this.completeStart(vibe, { context, startupRampSeconds, startRequestId });
}
private completeStart(
vibe: VibePreset,
{
context,
startRequestId,
startupRampSeconds,
}: {
context: AudioContext;
startRequestId: number;
startupRampSeconds: number;
}
): void {
@ -113,11 +125,11 @@ export class GardenAudio {
}
if (this.isMuted) {
this.graph.setMasterGain(muteGain, muteRampSeconds);
this.activateMutedStart(vibe, context);
this.graph.setMasterGain(SILENT_AUDIO_GAIN, muteRampSeconds);
return;
}
const startRequestId = ++this.startRequestId;
void this.piano
.load(context)
.then(() => {
@ -155,15 +167,28 @@ export class GardenAudio {
): void {
this.lifecycle = 'started';
this.currentVibeId = vibe.id;
this.currentVibe = vibe;
const profile = getVibeProfile(vibe);
this.graph.applyDelayProfile(profile.bpm);
this.graph.setMasterGain(this.masterVolume, startupRampSeconds);
if (cuePiano) {
this.hasLoadedPiano = true;
this.pianoEngine.cue(context.currentTime, profile);
}
}
private activateMutedStart(vibe: VibePreset, context: AudioContext): void {
this.lifecycle = 'started';
this.currentVibeId = vibe.id;
this.currentVibe = vibe;
this.hasLoadedPiano = false;
this.graph.applyDelayProfile(getVibeProfile(vibe).bpm);
if (this.graph.context === context) {
this.pianoEngine.reset();
}
}
public changeVibe(vibe: VibePreset, options: { userGesture?: boolean } = {}): void {
const previousVibeId = this.currentVibeId;
this.start(vibe, options);
@ -171,6 +196,7 @@ export class GardenAudio {
if (didChangeVibe) {
this.piano.stopAll();
this.hasLoadedPiano = false;
}
const context = this.graph.context;
@ -192,9 +218,13 @@ export class GardenAudio {
this.isMuted = isMuted;
this.graph.setMasterGain(
isMuted ? muteGain : this.masterVolume,
isMuted ? SILENT_AUDIO_GAIN : this.masterVolume,
isMuted ? muteRampSeconds : this.config.fadeInSeconds
);
if (!isMuted && this.currentVibe && !this.hasLoadedPiano) {
this.start(this.currentVibe);
}
}
public setMasterVolume(masterVolume: number): void {
@ -211,9 +241,7 @@ export class GardenAudio {
}
this.isGestureActive = true;
this.isReleasingPiano = false;
this.fadePianoAt = null;
this.stopPianoAt = null;
this.pianoReleasePhase = { kind: 'idle' };
this.graph.setPianoBusGainScale(1, this.config.fadeInSeconds);
this.gestureState.reset();
this.energy.beginGesture(context.currentTime);
@ -223,9 +251,7 @@ export class GardenAudio {
public endGesture(): void {
this.gestureState.reset();
this.isGestureActive = false;
this.isReleasingPiano = true;
this.fadePianoAt = null;
this.stopPianoAt = null;
this.pianoReleasePhase = { kind: 'awaiting-fade' };
this.energy.endGesture();
this.pianoEngine.endGesture();
}
@ -244,7 +270,7 @@ export class GardenAudio {
this.energy.silence();
}
if (!this.isGestureActive && this.isReleasingPiano) {
if (!this.isGestureActive && this.pianoReleasePhase.kind !== 'idle') {
this.updatePianoRelease(snapshot.vibe, context.currentTime);
this.updateDelay(snapshot, profile);
return;
@ -299,14 +325,14 @@ export class GardenAudio {
await this.graph.close();
this.piano.reset();
this.hasLoadedPiano = false;
this.energy.reset();
this.gestureState.reset();
this.pianoEngine.reset();
this.currentVibeId = null;
this.currentVibe = null;
this.isGestureActive = false;
this.isReleasingPiano = false;
this.fadePianoAt = null;
this.stopPianoAt = null;
this.pianoReleasePhase = { kind: 'idle' };
this.lastEraserAt = Number.NEGATIVE_INFINITY;
this.lastVibeStingerAt = Number.NEGATIVE_INFINITY;
}
@ -327,21 +353,41 @@ export class GardenAudio {
}
private updatePianoRelease(vibe: VibePreset, now: number): void {
if (this.fadePianoAt === null && this.stopPianoAt === null) {
this.fadePianoAt = this.pianoEngine.release(vibe, now);
}
if (this.pianoReleasePhase.kind === 'awaiting-fade') {
const fadeAt = this.pianoEngine.release(vibe, now);
if (now < fadeAt) {
this.pianoReleasePhase = { kind: 'scheduled-fade', fadeAt };
return;
}
if (this.fadePianoAt !== null && now >= this.fadePianoAt) {
this.graph.setPianoBusGainScale(0, brushUpPianoBusFadeSeconds);
this.fadePianoAt = null;
this.stopPianoAt = now + brushUpPianoBusFadeSettleSeconds;
this.pianoReleasePhase = {
kind: 'settling',
stopAt: now + brushUpPianoBusFadeSettleSeconds,
};
return;
}
if (this.stopPianoAt !== null && now >= this.stopPianoAt) {
if (
this.pianoReleasePhase.kind === 'scheduled-fade' &&
now >= this.pianoReleasePhase.fadeAt
) {
this.graph.setPianoBusGainScale(0, brushUpPianoBusFadeSeconds);
this.pianoReleasePhase = {
kind: 'settling',
stopAt: now + brushUpPianoBusFadeSettleSeconds,
};
return;
}
if (
this.pianoReleasePhase.kind === 'settling' &&
now >= this.pianoReleasePhase.stopAt
) {
this.piano.stopAll();
this.pianoEngine.reset();
this.stopPianoAt = null;
this.isReleasingPiano = false;
this.hasLoadedPiano = false;
this.pianoReleasePhase = { kind: 'idle' };
}
}
@ -393,8 +439,10 @@ export class GardenAudio {
}
this.currentVibeId = vibe.id;
this.currentVibe = vibe;
const profile = getVibeProfile(vibe);
this.graph.applyDelayProfile(profile.bpm);
this.pianoEngine.cue(this.graph.context.currentTime, profile);
this.hasLoadedPiano = true;
}
}

View file

@ -45,7 +45,10 @@ export class NoiseBurstPlayer {
filter.connect(envelope);
envelope.connect(panner);
panner.connect(noiseBus);
source.start(scheduledStart, Math.random() * noiseBurstTuning.offsetRandomSeconds);
const maxOffsetSeconds = Math.max(0, noiseBuffer.duration - durationSeconds);
const offsetSeconds =
Math.random() * Math.min(noiseBurstTuning.offsetRandomSeconds, maxOffsetSeconds);
source.start(scheduledStart, offsetSeconds);
source.stop(stopAt);
source.addEventListener(
'ended',

View file

@ -19,6 +19,7 @@ const pianoSamplerTuning = {
minDurationSeconds: 0.08,
minFadeSeconds: 0.08,
minGain: 0.0001,
releaseTimeConstantCount: 5,
tailStopExtraSeconds: 0.05,
voiceStealFadeSeconds: 0.025,
voiceStealStopSeconds: 0.05,
@ -84,7 +85,9 @@ export class PianoSampler {
const sustainAt =
scheduledStart + Math.max(pianoSamplerTuning.minDurationSeconds, durationSeconds);
const releaseAt = sustainAt + sustainSeconds;
const stopAt = releaseAt + this.config.piano.releaseSeconds;
const stopAt =
releaseAt +
this.config.piano.releaseSeconds * pianoSamplerTuning.releaseTimeConstantCount;
const source = context.createBufferSource();
source.buffer = sample.buffer;

View file

@ -31,51 +31,56 @@ import fSharp6SampleUrl from './samples/Fsharp6v12.m4a?url&no-inline';
import fSharp7SampleUrl from './samples/Fsharp7v12.m4a?url&no-inline';
interface PianoSampleDefinition {
midi: number;
path: string;
note: string;
url: string;
}
export interface PianoSampleLoadProgress {
failedCount: number;
loadedCount: number;
settledCount: number;
totalCount: number;
}
const pianoSampleDefinitions: Array<PianoSampleDefinition> = [
{ url: a0SampleUrl, path: './samples/A0v12.m4a', midi: 21 },
{ url: c1SampleUrl, path: './samples/C1v12.m4a', midi: 24 },
{ url: dSharp1SampleUrl, path: './samples/Dsharp1v12.m4a', midi: 27 },
{ url: fSharp1SampleUrl, path: './samples/Fsharp1v12.m4a', midi: 30 },
{ url: a1SampleUrl, path: './samples/A1v12.m4a', midi: 33 },
{ url: c2SampleUrl, path: './samples/C2v12.m4a', midi: 36 },
{ url: dSharp2SampleUrl, path: './samples/Dsharp2v12.m4a', midi: 39 },
{ url: fSharp2SampleUrl, path: './samples/Fsharp2v12.m4a', midi: 42 },
{ url: a2SampleUrl, path: './samples/A2v12.m4a', midi: 45 },
{ url: c3SampleUrl, path: './samples/C3v12.m4a', midi: 48 },
{ url: dSharp3SampleUrl, path: './samples/Dsharp3v12.m4a', midi: 51 },
{ url: fSharp3SampleUrl, path: './samples/Fsharp3v12.m4a', midi: 54 },
{ url: a3SampleUrl, path: './samples/A3v12.m4a', midi: 57 },
{ url: c4SampleUrl, path: './samples/C4v12.m4a', midi: 60 },
{ url: dSharp4SampleUrl, path: './samples/Dsharp4v12.m4a', midi: 63 },
{ url: fSharp4SampleUrl, path: './samples/Fsharp4v12.m4a', midi: 66 },
{ url: a4SampleUrl, path: './samples/A4v12.m4a', midi: 69 },
{ url: c5SampleUrl, path: './samples/C5v12.m4a', midi: 72 },
{ url: dSharp5SampleUrl, path: './samples/Dsharp5v12.m4a', midi: 75 },
{ url: fSharp5SampleUrl, path: './samples/Fsharp5v12.m4a', midi: 78 },
{ url: a5SampleUrl, path: './samples/A5v12.m4a', midi: 81 },
{ url: c6SampleUrl, path: './samples/C6v12.m4a', midi: 84 },
{ url: dSharp6SampleUrl, path: './samples/Dsharp6v12.m4a', midi: 87 },
{ url: fSharp6SampleUrl, path: './samples/Fsharp6v12.m4a', midi: 90 },
{ url: a6SampleUrl, path: './samples/A6v12.m4a', midi: 93 },
{ url: c7SampleUrl, path: './samples/C7v12.m4a', midi: 96 },
{ url: dSharp7SampleUrl, path: './samples/Dsharp7v12.m4a', midi: 99 },
{ url: fSharp7SampleUrl, path: './samples/Fsharp7v12.m4a', midi: 102 },
{ url: a7SampleUrl, path: './samples/A7v12.m4a', midi: 105 },
{ url: c8SampleUrl, path: './samples/C8v12.m4a', midi: 108 },
{ url: a0SampleUrl, note: 'A0' },
{ url: c1SampleUrl, note: 'C1' },
{ url: dSharp1SampleUrl, note: 'Dsharp1' },
{ url: fSharp1SampleUrl, note: 'Fsharp1' },
{ url: a1SampleUrl, note: 'A1' },
{ url: c2SampleUrl, note: 'C2' },
{ url: dSharp2SampleUrl, note: 'Dsharp2' },
{ url: fSharp2SampleUrl, note: 'Fsharp2' },
{ url: a2SampleUrl, note: 'A2' },
{ url: c3SampleUrl, note: 'C3' },
{ url: dSharp3SampleUrl, note: 'Dsharp3' },
{ url: fSharp3SampleUrl, note: 'Fsharp3' },
{ url: a3SampleUrl, note: 'A3' },
{ url: c4SampleUrl, note: 'C4' },
{ url: dSharp4SampleUrl, note: 'Dsharp4' },
{ url: fSharp4SampleUrl, note: 'Fsharp4' },
{ url: a4SampleUrl, note: 'A4' },
{ url: c5SampleUrl, note: 'C5' },
{ url: dSharp5SampleUrl, note: 'Dsharp5' },
{ url: fSharp5SampleUrl, note: 'Fsharp5' },
{ url: a5SampleUrl, note: 'A5' },
{ url: c6SampleUrl, note: 'C6' },
{ url: dSharp6SampleUrl, note: 'Dsharp6' },
{ url: fSharp6SampleUrl, note: 'Fsharp6' },
{ url: a6SampleUrl, note: 'A6' },
{ url: c7SampleUrl, note: 'C7' },
{ url: dSharp7SampleUrl, note: 'Dsharp7' },
{ url: fSharp7SampleUrl, note: 'Fsharp7' },
{ url: a7SampleUrl, note: 'A7' },
{ url: c8SampleUrl, note: 'C8' },
];
let loadedPianoSamples: Array<LoadedPianoSample> | null = null;
let pianoSampleLoadPromise: Promise<Array<LoadedPianoSample>> | null = null;
let lastPianoSampleProgress: PianoSampleLoadProgress | null = null;
const pianoSampleProgressListeners = new Set<
(progress: PianoSampleLoadProgress) => void
>();
const sampleLoadTuning = {
concurrency: 4,
@ -102,50 +107,65 @@ export const loadPianoSamples = (
decodeContext: BaseAudioContext,
onProgress?: (progress: PianoSampleLoadProgress) => void
): Promise<Array<LoadedPianoSample>> => {
const unsubscribeProgress = subscribeToPianoSampleProgress(onProgress);
if (loadedPianoSamples) {
onProgress?.({
emitPianoSampleProgress({
failedCount: 0,
loadedCount: loadedPianoSamples.length,
settledCount: loadedPianoSamples.length,
totalCount: pianoSampleDefinitions.length,
});
unsubscribeProgress();
return Promise.resolve([...loadedPianoSamples]);
}
if (pianoSampleLoadPromise) {
return pianoSampleLoadPromise;
return pianoSampleLoadPromise.finally(unsubscribeProgress);
}
let loadedCount = 0;
let failedCount = 0;
let settledCount = 0;
const totalCount = pianoSampleDefinitions.length;
onProgress?.({ loadedCount, totalCount });
emitPianoSampleProgress({ failedCount, loadedCount, settledCount, totalCount });
pianoSampleLoadPromise = loadPianoSampleBatch(
pianoSampleDefinitions,
async (sample) => {
try {
return await withTimeout(
const loadedSample = await withTimeout(
(signal) => loadPianoSample(decodeContext, sample, signal),
sampleLoadTuning.sampleTimeoutMs
);
} finally {
loadedCount += 1;
onProgress?.({ loadedCount, totalCount });
return loadedSample;
} catch (error) {
failedCount += 1;
throw error;
} finally {
settledCount += 1;
emitPianoSampleProgress({ failedCount, loadedCount, settledCount, totalCount });
}
}
).then(
(samples) => {
loadedPianoSamples = samples.sort((a, b) => a.midi - b.midi);
if (loadedPianoSamples.length !== pianoSampleDefinitions.length) {
throw new Error(
`Loaded ${loadedPianoSamples.length}/${pianoSampleDefinitions.length} piano samples.`
);
)
.then(
(samples) => {
loadedPianoSamples = samples.sort((a, b) => a.midi - b.midi);
if (loadedPianoSamples.length !== pianoSampleDefinitions.length) {
throw new Error(
`Loaded ${loadedPianoSamples.length}/${pianoSampleDefinitions.length} piano samples.`
);
}
return [...loadedPianoSamples];
},
(error: unknown) => {
pianoSampleLoadPromise = null;
pianoSampleProgressListeners.clear();
throw error;
}
return [...loadedPianoSamples];
},
(error: unknown) => {
pianoSampleLoadPromise = null;
throw error;
}
);
)
.finally(unsubscribeProgress);
return pianoSampleLoadPromise;
};
@ -160,12 +180,12 @@ const loadPianoSample = async (
): Promise<LoadedPianoSample> => {
const response = await fetch(sample.url, { signal });
if (!response.ok) {
throw new Error(`Unable to load piano sample ${sample.path}`);
throw new Error(`Unable to load piano sample ${getPianoSamplePath(sample)}`);
}
const audioData = await response.arrayBuffer();
const buffer = await decodeContext.decodeAudioData(audioData);
return { midi: sample.midi, buffer };
return { midi: getMidiForPianoSample(sample), buffer };
};
const loadPianoSampleBatch = async (
@ -205,3 +225,47 @@ const withTimeout = <T>(
}
);
});
const subscribeToPianoSampleProgress = (
onProgress: ((progress: PianoSampleLoadProgress) => void) | undefined
): (() => void) => {
if (!onProgress) {
return () => undefined;
}
pianoSampleProgressListeners.add(onProgress);
if (lastPianoSampleProgress) {
onProgress(lastPianoSampleProgress);
}
return () => {
pianoSampleProgressListeners.delete(onProgress);
};
};
const emitPianoSampleProgress = (progress: PianoSampleLoadProgress): void => {
lastPianoSampleProgress = progress;
pianoSampleProgressListeners.forEach((listener) => listener(progress));
};
const getPianoSamplePath = (sample: PianoSampleDefinition): string =>
`./samples/${sample.note}v12.m4a`;
const getMidiForPianoSample = (sample: PianoSampleDefinition): number => {
const match = /^(?<name>[A-G])(?<accidental>sharp)?(?<octave>\d+)$/.exec(sample.note);
if (!match?.groups) {
throw new Error(`Invalid piano sample note ${sample.note}`);
}
const semitoneByName: Record<string, number> = {
C: 0,
D: 2,
E: 4,
F: 5,
G: 7,
A: 9,
B: 11,
};
const octave = Number(match.groups.octave);
const semitone = semitoneByName[match.groups.name] + (match.groups.accidental ? 1 : 0);
return (octave + 1) * 12 + semitone;
};

View file

@ -5,3 +5,12 @@ under CC BY 3.0.
Source package: @audio-samples/piano-velocity12
Source recording: https://archive.org/details/SalamanderGrandPianoV3
License: https://creativecommons.org/licenses/by/3.0/
Checked-in subset: velocity layer `v12`, every minor-third anchor from A0
through C8: A, C, Dsharp, and Fsharp for octaves 1-7, plus A0, A7, and C8.
The app derives MIDI values from those note names in `piano-samples.ts`.
Repro notes: start from the matching `v12` OGG files in the source package and
transcode each selected sample to AAC/M4A without renaming the note/velocity
stem. The expected output filenames are `<note>v12.m4a`, for example
`C4v12.m4a`.

View file

@ -1,11 +1,12 @@
import { createGardenAudioConfig } from './audio/garden-audio-config';
import {
createGardenAudioConfig,
DEFAULT_AUDIO_VOLUME,
} from './audio/garden-audio-config';
import { defaultSettings } from './config/default-settings';
import { runtimeControls } from './config/runtime-controls';
import type { GardenAppConfig } from './config/types';
import { defaultVibeId, vibePresets } from './config/vibe-presets';
const DEFAULT_AUDIO_VOLUME = 0.5;
export {
normalizeNumberControlValue,
normalizeRuntimeSettings,
@ -19,6 +20,12 @@ export type {
export const appConfig = {
audio: createGardenAudioConfig(),
analytics: {
autoCapturePageviews: true,
domain: 'fleeting.garden',
endpoint: 'https://stats.schmelczer.dev/status',
logging: import.meta.env.DEV,
},
deltaTime: {
maxDeltaTimeSeconds: 1 / 30,
minDeltaTimeSeconds: 1 / 240,
@ -85,13 +92,14 @@ export const appConfig = {
letterSpacingEm: 0.07,
maskAlphaThreshold: 32,
maskGradientThreshold: 8,
maskMaxPixels: 1_000_000,
maskSampleDensity: 540,
maxHeightRatio: 0.25,
maxWidthRatio: 0.76,
minEntryJitterPx: 6,
minFontSizePx: 18,
minTargetJitterPx: 1,
pathEasing: 'easeOutQuad' as GardenAppConfig['simulation']['intro']['pathEasing'],
pathEasing: 'easeOutQuad',
pathProgressEpsilon: 0.001,
radialJitterRatio: 0.35,
radialStartEpsilon: 0.001,
@ -124,7 +132,7 @@ export const appConfig = {
controlScaleMax: 1.34,
controlScaleMin: 0.74,
default: 96,
max: 240,
max: 480,
min: 24,
step: 1,
},

View file

@ -1,14 +1,10 @@
import { runtimeControls } from './runtime-controls';
import { INTERNAL_RENDER_AREA_MEGAPIXEL_LIMITS } from './runtime-setting-bounds';
import type { GardenAppConfig } from './types';
// Mirrors the historical render-scale cap so the default render area stays
// roughly equivalent to native rendering on high-DPR phones without the
// pipeline applying its own clamp. The slider can override freely.
const DEFAULT_DEVICE_PIXEL_RATIO_CAP = 2;
const INTERNAL_RENDER_AREA_BOUNDS = {
min: runtimeControls.internalRenderAreaMegapixels?.min ?? 0.5,
max: runtimeControls.internalRenderAreaMegapixels?.max ?? 16.6,
};
const computeDefaultInternalRenderAreaMegapixels = (): number => {
const rawDpr =
@ -20,8 +16,8 @@ const computeDefaultInternalRenderAreaMegapixels = (): number => {
const cssHeight = typeof window !== 'undefined' ? window.innerHeight : 1080;
const cssMegapixels = (Math.max(cssWidth, 1) * Math.max(cssHeight, 1)) / 1_000_000;
return Math.min(
INTERNAL_RENDER_AREA_BOUNDS.max,
Math.max(INTERNAL_RENDER_AREA_BOUNDS.min, dpr * dpr * cssMegapixels)
INTERNAL_RENDER_AREA_MEGAPIXEL_LIMITS.max,
Math.max(INTERNAL_RENDER_AREA_MEGAPIXEL_LIMITS.min, dpr * dpr * cssMegapixels)
);
};

View file

@ -1,4 +1,5 @@
import { colorInteractionControl } from './color-interactions';
import { INTERNAL_RENDER_AREA_MEGAPIXEL_LIMITS } from './runtime-setting-bounds';
import type { GardenAppConfig } from './types';
const formatPercent = (value: number): string => `${Math.round(value * 100)}%`;
@ -55,6 +56,13 @@ export const runtimeControls: GardenAppConfig['runtimeSettings']['controls'] = {
max: 200,
step: 1,
},
sensorOffsetAngle: {
folder: 'Movement',
label: 'Sensor Angle',
min: 0,
max: 180,
step: 1,
},
moveSpeed: {
folder: 'Movement',
label: 'Travel Speed',
@ -81,7 +89,7 @@ export const runtimeControls: GardenAppConfig['runtimeSettings']['controls'] = {
folder: 'Movement',
label: 'Wander Turn',
min: 0,
max: 6.28,
max: Math.PI * 2,
step: 0.01,
},
individualTrailWeight: {
@ -132,8 +140,8 @@ export const runtimeControls: GardenAppConfig['runtimeSettings']['controls'] = {
internalRenderAreaMegapixels: {
folder: 'Performance',
label: 'Render Quality (MP)',
min: 0.5,
max: 16.6,
min: INTERNAL_RENDER_AREA_MEGAPIXEL_LIMITS.min,
max: INTERNAL_RENDER_AREA_MEGAPIXEL_LIMITS.max,
step: 0.1,
},
};

View file

@ -103,6 +103,12 @@ export interface VibePreset {
export interface GardenAppConfig {
audio: GardenAudioConfig;
analytics: {
autoCapturePageviews: boolean;
domain: string;
endpoint: string;
logging: boolean;
};
deltaTime: {
maxDeltaTimeSeconds: number;
minDeltaTimeSeconds: number;
@ -167,6 +173,7 @@ export interface GardenAppConfig {
letterSpacingEm: number;
maskAlphaThreshold: number;
maskGradientThreshold: number;
maskMaxPixels: number;
maskSampleDensity: number;
maxHeightRatio: number;
maxWidthRatio: number;

View file

@ -1,13 +1,14 @@
import { describe, expect, it } from 'vitest';
import { runtimeControls } from './runtime-controls';
import { vibePresets } from './vibe-presets';
const FINAL_VIBE_NAMES = [
'Aurora Mycelium Copy',
'Velvet Observatory',
'Velvet Observatory Copy',
'Lichen Signal',
'Tidepool Lantern',
'Paper Lantern Fog Copy',
'Paper Lantern Fog',
'Chrome Pollen',
];
@ -17,8 +18,8 @@ const SOFT_PARTICLE_BRUSH_SIZE_MAX = 5;
const SOFT_PARTICLE_CLARITY_MAX = 0.2;
// Performance guardrails — bumping any of these is an explicit perf trade-off.
const MAX_SPAWN_PER_PIXEL = 0.38;
const MAX_BRUSH_SIZE = 36;
const MAX_SPAWN_PER_PIXEL = runtimeControls.spawnPerPixel?.max ?? 0.38;
const MAX_BRUSH_SIZE = runtimeControls.brushSize?.max ?? 36;
const HIGH_DENSITY_SPAWN_THRESHOLD = 0.28;
const HIGH_DENSITY_DECAY_LIMIT = 940;
const HIGH_DENSITY_BRUSH_SIZE_LIMIT = 14;

View file

@ -139,7 +139,7 @@ export const vibePresets: Array<VibePreset> = [
id: VibeId.AuroraMycelium,
name: 'Aurora Mycelium Copy',
colors: [
[221, 255, 78],
[251, 210, 94],
[154, 99, 255],
[255, 31, 199],
],
@ -148,25 +148,25 @@ export const vibePresets: Array<VibePreset> = [
...colorReactions.auroraMycelium,
backgroundGrainStrength: 0.003,
brushSize: 8.75,
clarity: 0.379,
decayRateTrails: 940,
forwardRotationScale: 0,
individualTrailWeight: 0.121,
moveSpeed: 270,
sensorOffsetAngle: 36,
sensorOffsetDistance: 51,
spawnPerPixel: 0.14,
clarity: 1,
decayRateTrails: 973,
forwardRotationScale: 0.37,
individualTrailWeight: 0.053000000000000005,
moveSpeed: 144,
sensorOffsetAngle: 35,
sensorOffsetDistance: 52,
spawnPerPixel: 0.13999999999999999,
strokeAngleJitterRadians: 0.45,
turnSpeed: 22,
turnSpeed: 13,
turnWhenLost: 0,
},
audio: {
...defaultGardenAudioVibeSettings,
idleIntensity: 0.12,
idleIntensity: 0.12000000000000002,
bpm: 60,
rampUpIntensity: 0.7,
rampUpTime: 0.14,
noteLength: 0.86,
noteLength: 0.8599999999999999,
notePitchOffset: -2,
brightness: 0.84,
scale: musicScales.lydian,
@ -175,7 +175,7 @@ export const vibePresets: Array<VibePreset> = [
},
{
id: VibeId.VelvetObservatory,
name: 'Velvet Observatory',
name: 'Velvet Observatory Copy',
colors: [
[178, 76, 62],
[2, 174, 255],
@ -186,21 +186,21 @@ export const vibePresets: Array<VibePreset> = [
...colorReactions.velvetObservatory,
backgroundGrainStrength: 0.005,
brushSize: 9.75,
clarity: 0.437,
decayRateTrails: 915,
clarity: 1,
decayRateTrails: 974,
forwardRotationScale: 0,
individualTrailWeight: 0.1,
moveSpeed: 216,
individualTrailWeight: 0.232,
moveSpeed: 121,
sensorOffsetAngle: 24,
sensorOffsetDistance: 17,
spawnPerPixel: 0.24,
spawnPerPixel: 0.11499999999999999,
strokeAngleJitterRadians: 0.17,
turnSpeed: 33,
turnWhenLost: 0.42,
},
audio: {
...defaultGardenAudioVibeSettings,
idleIntensity: 0.55,
idleIntensity: 0.24000000000000002,
bpm: 72,
rampUpIntensity: 1.42,
rampUpTime: 0.07,
@ -289,7 +289,7 @@ export const vibePresets: Array<VibePreset> = [
},
{
id: VibeId.PaperLanternFog,
name: 'Paper Lantern Fog Copy',
name: 'Paper Lantern Fog',
colors: [
[255, 176, 108],
[239, 90, 108],

View file

@ -145,6 +145,18 @@ describe('AgentPopulation stroke spawning', () => {
expect(pipeline.writtenBatches[0][2]).toBe(0);
});
it('clears active agents when an intro replacement has no generated agents', () => {
const { population } = createPopulation();
population.spawnStrokeAgents(vec2.fromValues(0, 0), vec2.fromValues(3, 0));
expect(population.activeAgentCount).toBe(3);
settings.maxAgentCount = 0;
population.replaceIntroAgents(vec2.fromValues(100, 100), 0);
expect(population.activeAgentCount).toBe(0);
});
it('queues stroke writes while async compaction is in flight', async () => {
const { pipeline, population } = createPopulation();

View file

@ -59,6 +59,8 @@ export class AgentPopulation {
});
if (data.length === 0) {
this.activeCount = 0;
this.replacementCursor = 0;
return;
}

View file

@ -46,14 +46,16 @@ export class FramePerformance {
return;
}
const fps = 1 / deltaSeconds;
this.frameDeltaSeconds = deltaSeconds;
this.measuredFrameTimeMs = deltaSeconds * 1000;
const fps = 1 / deltaSeconds;
this.measuredFps = fps;
if (deltaSeconds > FRAME_GAP_RESET_SECONDS) {
this.frameDeltaSeconds = 0;
this.smoothedFps = ADAPTIVE_REFRESH_TARGET_FPS;
return;
}
this.frameDeltaSeconds = deltaSeconds;
this.smoothedFps = this.smoothedFps * FPS_SMOOTHING_RETAIN + fps * FPS_SMOOTHING_NEW;
}
}

View file

@ -1,6 +1,6 @@
import { vec2 } from 'gl-matrix';
import { appConfig } from '../config';
import { appConfig, type GardenRuntimeSettings } from '../config';
import { AgentGenerationPipeline } from '../pipelines/agents/agent-generation/agent-generation-pipeline';
import { AgentPipeline } from '../pipelines/agents/agent-pipeline';
import { BrushPipeline } from '../pipelines/brush/brush-pipeline';
@ -9,7 +9,6 @@ import { DiffusionPipeline } from '../pipelines/diffusion/diffusion-pipeline';
import { EraserAgentPipeline } from '../pipelines/eraser/eraser-agent-pipeline';
import { EraserTexturePipeline } from '../pipelines/eraser/eraser-texture-pipeline';
import { RenderPipeline } from '../pipelines/render/render-pipeline';
import { settings } from '../settings';
import { initializeContext } from '../utils/graphics/initialize-context';
import { CanvasReadbackRequest, RenderInputs } from './game-loop-types';
import { GpuProfiler } from './gpu-profiler';
@ -25,6 +24,7 @@ interface FrameParameters extends RenderInputs {
introProgress: number;
selectedColorIndex: number;
eraserPixelSize: number;
runtimeSettings: GardenRuntimeSettings;
}
export class GameLoopResources {
@ -46,7 +46,8 @@ export class GameLoopResources {
private readonly device: GPUDevice,
private readonly canvasFormat: GPUTextureFormat,
canvasSize: vec2,
initialAgentCapacity: number
initialAgentCapacity: number,
initialMaxAgentCount: number
) {
const context = initializeContext({ device, canvas, format: canvasFormat });
@ -59,7 +60,7 @@ export class GameLoopResources {
this.agentGenerationPipeline = new AgentGenerationPipeline(
this.device,
Math.min(settings.maxAgentCount, initialAgentCapacity)
Math.min(initialMaxAgentCount, initialAgentCapacity)
);
this.agentPipeline = new AgentPipeline(
@ -74,12 +75,7 @@ export class GameLoopResources {
);
this.eraserTexturePipeline = new EraserTexturePipeline(this.device, this.commonState);
this.diffusionPipeline = new DiffusionPipeline(this.device);
this.renderPipeline = new RenderPipeline(
context,
this.device,
this.commonState,
this.canvasFormat
);
this.renderPipeline = new RenderPipeline(context, this.device, this.canvasFormat);
this.gpuProfiler = GpuProfiler.create(
this.device,
() => appConfig.tuningPane.showFpsOverlay
@ -128,43 +124,43 @@ export class GameLoopResources {
channelColors,
backgroundColor,
eraserPixelSize,
runtimeSettings,
}: FrameParameters): void {
this.commonState.setParameters({
canvasSize,
});
this.agentPipeline.setParameters({
...settings,
...runtimeSettings,
deltaTime,
time,
agentCount: activeAgentCount,
moveSpeed: settings.moveSpeed,
introMoveSpeed: appConfig.simulation.introMoveSpeed,
introProgress,
});
this.brushPipeline.setParameters({
...settings,
...runtimeSettings,
pixelRatio: canvasPixelRatio,
selectedColorIndex,
});
this.diffusionPipeline.setParameters(settings);
this.diffusionPipeline.setParameters(runtimeSettings);
this.renderPipeline.setParameters({
...settings,
...runtimeSettings,
channelColors,
backgroundColor,
});
this.eraserAgentPipeline.setParameters({
agentCount: activeAgentCount,
eraserSize: eraserPixelSize,
eraserMaskAlphaThreshold: settings.eraserMaskAlphaThreshold,
eraserMaskAlphaThreshold: runtimeSettings.eraserMaskAlphaThreshold,
maskSize: canvasSize,
});
this.eraserTexturePipeline.setParameters({
eraserSize: eraserPixelSize,
eraserLineDistanceEpsilon: settings.eraserLineDistanceEpsilon,
eraserClearRed: settings.eraserClearRed,
eraserClearGreen: settings.eraserClearGreen,
eraserClearBlue: settings.eraserClearBlue,
eraserClearAlpha: settings.eraserClearAlpha,
eraserLineDistanceEpsilon: runtimeSettings.eraserLineDistanceEpsilon,
eraserClearRed: runtimeSettings.eraserClearRed,
eraserClearGreen: runtimeSettings.eraserClearGreen,
eraserClearBlue: runtimeSettings.eraserClearBlue,
eraserClearAlpha: runtimeSettings.eraserClearAlpha,
});
}

Some files were not shown because too many files have changed in this diff Show more