.
Some checks failed
Deploy to Pages / build (pull_request) Failing after 3m15s

This commit is contained in:
Andras Schmelczer 2026-05-13 22:13:15 +01:00
commit 2347ecd201
71 changed files with 3779 additions and 1586 deletions

View file

@ -27,17 +27,33 @@ jobs:
- name: Install dependencies - name: Install dependencies
run: npm ci run: npm ci
- name: Install Playwright browsers
run: npx playwright install --with-deps chromium
- name: Lint - name: Lint
run: npm run lint run: npm run lint
- name: Typecheck - name: Typecheck
run: npm run typecheck run: npm run typecheck
- name: Typecheck browser tests
run: npm run typecheck:e2e
- name: Test - name: Test
run: npm test run: npm test
- name: Build - name: Browser tests
run: npm run build run: npm run test:e2e
- name: Upload Playwright report
if: failure()
uses: actions/upload-artifact@v4
with:
name: playwright-report
path: |
playwright-report/
test-results/
retention-days: 7
- name: Copy build to host pages mount - name: Copy build to host pages mount
if: github.event_name == 'push' && github.ref == 'refs/heads/main' if: github.event_name == 'push' && github.ref == 'refs/heads/main'

2
.gitignore vendored
View file

@ -5,6 +5,8 @@ ts-node--*/
rss.xml rss.xml
dist dist
playwright-report
test-results
# Logs # Logs
logs logs

View file

@ -5,3 +5,10 @@ draw persistent coloured paths, spawn agents from those strokes, erase locally,
and export the scene as a 4K wallpaper. and export the scene as a 4K wallpaper.
Check out the [agent logic](./src/pipelines/agents/agent.wgsl). Check out the [agent logic](./src/pipelines/agents/agent.wgsl).
## Testing
- `npm test` runs the Vitest unit suite.
- `npm run test:e2e` builds the production bundle and runs the Playwright Chromium
smoke test.
- `npx playwright install chromium` installs the local browser binary when needed.

23
e2e/app.spec.ts Normal file
View file

@ -0,0 +1,23 @@
import { expect, test } from '@playwright/test';
test('loads the app shell and WebGPU fallback in Chromium', async ({ page }) => {
await page.addInitScript(() => {
Object.defineProperty(navigator, 'gpu', {
configurable: true,
value: undefined,
});
});
await page.goto('/');
await expect(page).toHaveTitle('Fleeting Garden');
await expect(
page.getByRole('img', { name: 'Interactive generative garden canvas' })
).toBeVisible();
await expect(page.getByRole('toolbar', { name: 'Garden toolbar' })).toBeVisible();
await expect(page.locator('body')).not.toHaveClass(/is-loading/);
await expect(page.getByRole('alert')).toContainText('Fleeting Garden needs WebGPU');
await page.getByRole('button', { name: 'About' }).click();
await expect(page.getByRole('heading', { name: 'Fleeting Garden' })).toBeVisible();
});

View file

@ -6,7 +6,7 @@
name="viewport" name="viewport"
content="width=device-width,initial-scale=1,viewport-fit=cover" content="width=device-width,initial-scale=1,viewport-fit=cover"
/> />
<meta name="theme-color" content="#b7455e" /> <meta name="theme-color" content="#10151f" />
<meta <meta
name="description" name="description"
content="Fleeting Garden is a joyful WebGPU drawing garden where your coloured paths bloom into moving organic trails." content="Fleeting Garden is a joyful WebGPU drawing garden where your coloured paths bloom into moving organic trails."
@ -29,7 +29,7 @@
<title>Fleeting Garden</title> <title>Fleeting Garden</title>
</head> </head>
<body> <body class="is-loading">
<main class="canvas-container"> <main class="canvas-container">
<canvas <canvas
role="img" role="img"
@ -47,6 +47,25 @@
<div class="eraser-preview" aria-hidden="true"></div> <div class="eraser-preview" aria-hidden="true"></div>
<div class="garden-prompt" aria-live="polite"></div> <div class="garden-prompt" aria-live="polite"></div>
<div class="loading-indicator" role="status" aria-live="polite">
<div class="loading-dots" aria-hidden="true">
<span class="loading-dot"></span>
<span class="loading-dot"></span>
<span class="loading-dot"></span>
</div>
<div class="loading-status">Starting up&hellip;</div>
<div
class="loading-progress"
role="progressbar"
aria-label="Loading Fleeting Garden"
aria-valuemin="0"
aria-valuemax="100"
aria-valuenow="0"
>
<div class="loading-progress-fill"></div>
</div>
</div>
<section class="errors-container"> <section class="errors-container">
<noscript>JavaScript is required for this website.</noscript> <noscript>JavaScript is required for this website.</noscript>
</section> </section>
@ -57,16 +76,20 @@
<section> <section>
<h1>Fleeting Garden</h1> <h1>Fleeting Garden</h1>
<p> <p>
Pick a vibe palette, draw with one of the three colours, and agents grow A living sketchpad where each stroke becomes a trail that agents follow,
organic paths from your strokes. branch from, and weave into the scene.
</p> </p>
<p> <p>
Your drawn paths persist until you erase them. Switching vibes recolours the Paint with the three colour swatches, carve space with the eraser, and raise
whole garden without clearing the scene. the mirror control when you want radial patterns instead of a single line.
</p> </p>
<p> <p>
Runs entirely on your GPU via WebGPU compute shaders &mdash; no servers, no Switch vibes to recolour the whole garden without clearing your drawing. Add
tracking, no analytics. Source on or mute the generated piano, restart for a blank canvas, or export the current
frame as a 4K image.
</p>
<p>
Built with WebGPU and running locally in your browser. Source on
<a href="https://github.com/schmelczer/webgpu" target="_blank" rel="noopener" <a href="https://github.com/schmelczer/webgpu" target="_blank" rel="noopener"
>GitHub</a >GitHub</a
>. >.

64
package-lock.json generated
View file

@ -14,6 +14,7 @@
"devDependencies": { "devDependencies": {
"@eslint/js": "^10.0.1", "@eslint/js": "^10.0.1",
"@ianvs/prettier-plugin-sort-imports": "^4.7.1", "@ianvs/prettier-plugin-sort-imports": "^4.7.1",
"@playwright/test": "^1.60.0",
"@tweakpane/core": "^2.0.5", "@tweakpane/core": "^2.0.5",
"@types/node": "^25.6.0", "@types/node": "^25.6.0",
"@vite-pwa/assets-generator": "^1.0.2", "@vite-pwa/assets-generator": "^1.0.2",
@ -1261,6 +1262,22 @@
"url": "https://opencollective.com/pkgr" "url": "https://opencollective.com/pkgr"
} }
}, },
"node_modules/@playwright/test": {
"version": "1.60.0",
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.60.0.tgz",
"integrity": "sha512-O71yZIbAh/PxDMNGns37GHBIfrVkEVyn+AXyIa5dOTfb4/xNvRWV+Vv/NMbNCtODB/pO7vLlF2OTmMVLhmr7Ag==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright": "1.60.0"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=18"
}
},
"node_modules/@quansync/fs": { "node_modules/@quansync/fs": {
"version": "1.0.0", "version": "1.0.0",
"resolved": "https://registry.npmjs.org/@quansync/fs/-/fs-1.0.0.tgz", "resolved": "https://registry.npmjs.org/@quansync/fs/-/fs-1.0.0.tgz",
@ -3461,6 +3478,53 @@
"url": "https://github.com/sponsors/jonschlinkert" "url": "https://github.com/sponsors/jonschlinkert"
} }
}, },
"node_modules/playwright": {
"version": "1.60.0",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.60.0.tgz",
"integrity": "sha512-hheHdokM8cdqCb0lcE3s+zT4t4W+vvjpGxsZlDnikarzx8tSzMebh3UiFtgqwFwnTnjYQcsyMF8ei2mCO/tpeA==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright-core": "1.60.0"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"fsevents": "2.3.2"
}
},
"node_modules/playwright-core": {
"version": "1.60.0",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.60.0.tgz",
"integrity": "sha512-9bW6zvX/m0lEbgTKJ6YppOKx8H3VOPBMOCFh2irXFOT4BbHgrx5hPjwJYLT40Lu+4qtD36qKc/Hn56StUW57IA==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=18"
}
},
"node_modules/playwright/node_modules/fsevents": {
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/postcss": { "node_modules/postcss": {
"version": "8.5.13", "version": "8.5.13",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.13.tgz", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.13.tgz",

View file

@ -9,13 +9,17 @@
"build": "vite build", "build": "vite build",
"preview": "vite preview", "preview": "vite preview",
"lint": "npm run lint:check", "lint": "npm run lint:check",
"lint:check": "eslint --rule \"prettier/prettier: off\" \"src/**/*.ts\"", "lint:check": "eslint --rule \"prettier/prettier: off\" \"src/**/*.ts\" && npm run unused:check",
"lint:fix": "eslint --fix \"src/**/*.ts\"", "lint:fix": "eslint --fix \"src/**/*.ts\"",
"format": "prettier --write \"index.html\" \"src/**/*.{ts,scss,json,html}\" \".forgejo/workflows/*.yml\" \"*.{json,js,ts,md}\" \".prettierrc\"", "format": "prettier --write \"index.html\" \"src/**/*.{ts,scss,json,html}\" \"scripts/**/*.mjs\" \"e2e/**/*.ts\" \".forgejo/workflows/*.yml\" \"*.{json,js,ts,md}\" \".prettierrc\"",
"format:check": "prettier --check \"index.html\" \"src/**/*.{ts,scss,json,html}\" \".forgejo/workflows/*.yml\" \"*.{json,js,ts,md}\" \".prettierrc\"", "format:check": "prettier --check \"index.html\" \"src/**/*.{ts,scss,json,html}\" \"scripts/**/*.mjs\" \"e2e/**/*.ts\" \".forgejo/workflows/*.yml\" \"*.{json,js,ts,md}\" \".prettierrc\"",
"typecheck": "tsc --noEmit", "typecheck": "tsc --noEmit",
"typecheck:e2e": "tsc --noEmit --project tsconfig.playwright.json",
"test": "vitest run", "test": "vitest run",
"test:e2e": "npm run build && playwright test",
"test:e2e:ui": "npm run build && playwright test --ui",
"test:watch": "vitest", "test:watch": "vitest",
"unused:check": "node scripts/check-unused-exports.mjs",
"generate-icons": "pwa-assets-generator", "generate-icons": "pwa-assets-generator",
"update": "ncu" "update": "ncu"
}, },
@ -40,6 +44,7 @@
"devDependencies": { "devDependencies": {
"@eslint/js": "^10.0.1", "@eslint/js": "^10.0.1",
"@ianvs/prettier-plugin-sort-imports": "^4.7.1", "@ianvs/prettier-plugin-sort-imports": "^4.7.1",
"@playwright/test": "^1.60.0",
"@tweakpane/core": "^2.0.5", "@tweakpane/core": "^2.0.5",
"@types/node": "^25.6.0", "@types/node": "^25.6.0",
"@vite-pwa/assets-generator": "^1.0.2", "@vite-pwa/assets-generator": "^1.0.2",

32
playwright.config.ts Normal file
View file

@ -0,0 +1,32 @@
import { defineConfig, devices } from '@playwright/test';
const port = 4173;
const baseURL = `https://127.0.0.1:${port}`;
const isCi = Boolean(process.env.CI);
export default defineConfig({
testDir: './e2e',
fullyParallel: true,
forbidOnly: isCi,
retries: isCi ? 2 : 0,
workers: isCi ? 1 : undefined,
reporter: isCi ? [['list'], ['html', { open: 'never' }]] : 'list',
use: {
baseURL,
ignoreHTTPSErrors: true,
trace: 'on-first-retry',
},
webServer: {
command: `npm run preview -- --host 127.0.0.1 --port ${port}`,
ignoreHTTPSErrors: true,
reuseExistingServer: !isCi,
timeout: 120_000,
url: baseURL,
},
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
},
],
});

Binary file not shown.

Before

Width:  |  Height:  |  Size: 908 B

After

Width:  |  Height:  |  Size: 1.2 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 587 B

After

Width:  |  Height:  |  Size: 914 B

Before After
Before After

View file

@ -1,6 +1,31 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
<rect width="64" height="64" rx="14" fill="#b7455e" /> <defs>
<circle cx="22" cy="26" r="9" fill="#fff" opacity="0.95" /> <clipPath id="icon-clip">
<circle cx="42" cy="32" r="11" fill="#fff" opacity="0.85" /> <rect width="64" height="64" rx="14" />
<circle cx="28" cy="44" r="7" fill="#fff" opacity="0.75" /> </clipPath>
</defs>
<g clip-path="url(#icon-clip)">
<rect width="64" height="64" fill="#10151f" />
<path d="M0 64a32 32 0 0 1 64 0Z" fill="#ffd84d" />
<path
d="M32 34c1.2-7.2 4.8-12.3 10-16"
fill="none"
stroke="#10151f"
stroke-linecap="round"
stroke-width="8"
/>
<path
d="M32 34c1.2-7.2 4.8-12.3 10-16"
fill="none"
stroke="#ff2fa3"
stroke-linecap="round"
stroke-width="4"
/>
<ellipse cx="42" cy="11.5" rx="4.2" ry="6.4" fill="#ff2fa3" />
<ellipse cx="48.5" cy="18" rx="6.4" ry="4.2" fill="#ff2fa3" />
<ellipse cx="42" cy="24.5" rx="4.2" ry="6.4" fill="#ff2fa3" />
<ellipse cx="35.5" cy="18" rx="6.4" ry="4.2" fill="#ff2fa3" />
<circle cx="42" cy="18" r="3.2" fill="#10151f" />
</g>
</svg> </svg>

Before

Width:  |  Height:  |  Size: 312 B

After

Width:  |  Height:  |  Size: 950 B

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.9 KiB

After

Width:  |  Height:  |  Size: 3.4 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

After

Width:  |  Height:  |  Size: 1.6 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3 KiB

After

Width:  |  Height:  |  Size: 4.1 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 488 B

After

Width:  |  Height:  |  Size: 709 B

Before After
Before After

View file

@ -0,0 +1,185 @@
import { existsSync, readdirSync, readFileSync } from 'node:fs';
import path from 'node:path';
import ts from 'typescript';
const projectRoot = process.cwd();
const sourceRoot = path.join(projectRoot, 'src');
const toPosix = (value) => value.split(path.sep).join('/');
const listTypeScriptFiles = (directory) =>
readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
const entryPath = path.join(directory, entry.name);
if (entry.isDirectory()) {
return listTypeScriptFiles(entryPath);
}
return entry.isFile() && entry.name.endsWith('.ts') && !entry.name.endsWith('.d.ts')
? [entryPath]
: [];
});
const files = listTypeScriptFiles(sourceRoot);
const fileSet = new Set(files.map((file) => path.resolve(file)));
const resolveModule = (fromFile, specifier) => {
if (!specifier.startsWith('.')) {
return null;
}
const base = path.resolve(path.dirname(fromFile), specifier);
const candidates = [
`${base}.ts`,
path.join(base, 'index.ts'),
base.endsWith('.ts') ? base : null,
].filter(Boolean);
return candidates.find((candidate) => existsSync(candidate) && fileSet.has(candidate)) ?? null;
};
const exportKey = (file, name) => `${path.resolve(file)}:${name}`;
const isExported = (node) =>
ts.canHaveModifiers(node) &&
(ts.getModifiers(node) ?? []).some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword);
const isDefaultExported = (node) =>
ts.canHaveModifiers(node) &&
(ts.getModifiers(node) ?? []).some((modifier) => modifier.kind === ts.SyntaxKind.DefaultKeyword);
const exportedDeclarations = new Map();
const usedExports = new Set();
const wildcardUsedFiles = new Set();
const markUsed = (fromFile, name) => {
usedExports.add(exportKey(fromFile, name));
};
const collectImportUsage = (file, sourceFile) => {
sourceFile.forEachChild((node) => {
if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) {
const resolved = resolveModule(file, node.moduleSpecifier.text);
if (!resolved || !node.importClause) {
return;
}
if (node.importClause.name) {
markUsed(resolved, 'default');
}
const namedBindings = node.importClause.namedBindings;
if (namedBindings && ts.isNamedImports(namedBindings)) {
namedBindings.elements.forEach((element) => {
markUsed(resolved, (element.propertyName ?? element.name).text);
});
} else if (namedBindings && ts.isNamespaceImport(namedBindings)) {
wildcardUsedFiles.add(path.resolve(resolved));
}
return;
}
if (
ts.isExportDeclaration(node) &&
node.moduleSpecifier &&
ts.isStringLiteral(node.moduleSpecifier)
) {
const resolved = resolveModule(file, node.moduleSpecifier.text);
if (!resolved) {
return;
}
if (!node.exportClause) {
wildcardUsedFiles.add(path.resolve(resolved));
return;
}
if (ts.isNamedExports(node.exportClause)) {
node.exportClause.elements.forEach((element) => {
markUsed(resolved, (element.propertyName ?? element.name).text);
});
}
}
});
};
const collectExportedDeclarations = (file, sourceFile) => {
if (file.endsWith('.test.ts')) {
return;
}
sourceFile.forEachChild((node) => {
if (ts.isVariableStatement(node) && isExported(node)) {
node.declarationList.declarations.forEach((declaration) => {
if (ts.isIdentifier(declaration.name)) {
exportedDeclarations.set(exportKey(file, declaration.name.text), {
file,
name: declaration.name.text,
});
}
});
return;
}
if (
(ts.isFunctionDeclaration(node) ||
ts.isClassDeclaration(node) ||
ts.isInterfaceDeclaration(node) ||
ts.isTypeAliasDeclaration(node) ||
ts.isEnumDeclaration(node)) &&
isExported(node)
) {
if (isDefaultExported(node)) {
exportedDeclarations.set(exportKey(file, 'default'), { file, name: 'default' });
return;
}
if (node.name) {
exportedDeclarations.set(exportKey(file, node.name.text), {
file,
name: node.name.text,
});
}
return;
}
if (
ts.isExportDeclaration(node) &&
!node.moduleSpecifier &&
node.exportClause &&
ts.isNamedExports(node.exportClause)
) {
node.exportClause.elements.forEach((element) => {
exportedDeclarations.set(exportKey(file, element.name.text), {
file,
name: element.name.text,
});
});
}
});
};
const parsedFiles = files.map((file) => ({
file,
sourceFile: ts.createSourceFile(
file,
readFileSync(file, 'utf8'),
ts.ScriptTarget.Latest,
true,
ts.ScriptKind.TS
),
}));
parsedFiles.forEach(({ file, sourceFile }) => collectImportUsage(file, sourceFile));
parsedFiles.forEach(({ file, sourceFile }) => collectExportedDeclarations(file, sourceFile));
const unusedExports = Array.from(exportedDeclarations.entries())
.filter(([key, declaration]) => !usedExports.has(key) && !wildcardUsedFiles.has(declaration.file))
.map(([, declaration]) => declaration)
.sort((left, right) =>
`${left.file}:${left.name}`.localeCompare(`${right.file}:${right.name}`)
);
if (unusedExports.length > 0) {
console.error('Unused exported declarations found:');
unusedExports.forEach(({ file, name }) => {
console.error(`- ${toPosix(path.relative(projectRoot, file))}: ${name}`);
});
process.exitCode = 1;
}

View file

@ -1,13 +1,13 @@
import { appConfig } from '../config'; import { appConfig } from '../config';
export type GardenAudioChordQuality = 'major' | 'minor'; type GardenAudioChordQuality = 'major' | 'minor';
export interface GardenAudioChord { export interface GardenAudioChord {
rootOffset: number; rootOffset: number;
quality: GardenAudioChordQuality; quality: GardenAudioChordQuality;
} }
export interface GardenAudioColorVoice { interface GardenAudioColorVoice {
scaleDegreeOffset: number; scaleDegreeOffset: number;
velocityMultiplier: number; velocityMultiplier: number;
panOffset: number; panOffset: number;

View file

@ -1,4 +1,4 @@
import { appConfig } from '../config'; import type { GardenAudioEngineConfig } from '../config';
import { clamp01 } from '../utils/clamp'; import { clamp01 } from '../utils/clamp';
const STROKE_IMMEDIATE_ACTIVITY_SCALE = 0.85; const STROKE_IMMEDIATE_ACTIVITY_SCALE = 0.85;
@ -9,6 +9,8 @@ export class GardenAudioEnergy {
private targetEnergy = 0; private targetEnergy = 0;
private lastEnergyUpdateAt = 0; private lastEnergyUpdateAt = 0;
public constructor(private readonly engineConfig: GardenAudioEngineConfig) {}
public beginGesture(now: number): void { public beginGesture(now: number): void {
this.isGestureActive = true; this.isGestureActive = true;
this.lastEnergyUpdateAt = now; this.lastEnergyUpdateAt = now;
@ -46,15 +48,15 @@ export class GardenAudioEnergy {
const elapsedSeconds = Math.max(0, now - this.lastEnergyUpdateAt); const elapsedSeconds = Math.max(0, now - this.lastEnergyUpdateAt);
this.lastEnergyUpdateAt = now; this.lastEnergyUpdateAt = now;
this.targetEnergy *= Math.exp( this.targetEnergy *= Math.exp(
-elapsedSeconds / appConfig.audioEngine.energy.strokeDecaySeconds -elapsedSeconds / this.engineConfig.energy.strokeDecaySeconds
); );
const target = this.isGestureActive ? this.targetEnergy : 0; const target = this.isGestureActive ? this.targetEnergy : 0;
let timeConstant = appConfig.audioEngine.energy.decaySeconds; let timeConstant = this.engineConfig.energy.decaySeconds;
if (!this.isGestureActive) { if (!this.isGestureActive) {
timeConstant = appConfig.audioEngine.energy.releaseSeconds; timeConstant = this.engineConfig.energy.releaseSeconds;
} else if (target > this.energy) { } else if (target > this.energy) {
timeConstant = appConfig.audioEngine.energy.attackSeconds; timeConstant = this.engineConfig.energy.attackSeconds;
} }
const amount = 1 - Math.exp(-elapsedSeconds / timeConstant); const amount = 1 - Math.exp(-elapsedSeconds / timeConstant);
this.energy += (target - this.energy) * amount; this.energy += (target - this.energy) * amount;

View file

@ -1,4 +1,4 @@
import { appConfig } from '../config'; import type { GardenAudioEngineConfig } from '../config';
import { clamp } from '../utils/clamp'; import { clamp } from '../utils/clamp';
import { GardenAudioConfig, GardenAudioVibeProfile } from './garden-audio-config'; import { GardenAudioConfig, GardenAudioVibeProfile } from './garden-audio-config';
@ -14,7 +14,10 @@ export class GardenAudioGraph {
private delayOutput: GainNode | null = null; private delayOutput: GainNode | null = null;
private hasUnlocked = false; private hasUnlocked = false;
public constructor(private readonly config: GardenAudioConfig) {} public constructor(
private readonly config: GardenAudioConfig,
private readonly engineConfig: GardenAudioEngineConfig
) {}
public ensureContext(canCreate: boolean): AudioContext | null { public ensureContext(canCreate: boolean): AudioContext | null {
if (this.context) { if (this.context) {
@ -62,8 +65,8 @@ export class GardenAudioGraph {
const buffer = this.context.createBuffer( const buffer = this.context.createBuffer(
1, 1,
appConfig.audioEngine.graph.unlockBufferLength, this.engineConfig.graph.unlockBufferLength,
appConfig.audioEngine.graph.unlockSampleRate this.engineConfig.graph.unlockSampleRate
); );
const source = this.context.createBufferSource(); const source = this.context.createBufferSource();
source.buffer = buffer; source.buffer = buffer;
@ -92,7 +95,7 @@ export class GardenAudioGraph {
this.delayNode.delayTime.setTargetAtTime( this.delayNode.delayTime.setTargetAtTime(
this.config.delay.timeSeconds * profile.delayTimeMultiplier, this.config.delay.timeSeconds * profile.delayTimeMultiplier,
this.context.currentTime, this.context.currentTime,
appConfig.audioEngine.graph.delayTimeRampSeconds this.engineConfig.graph.delayTimeRampSeconds
); );
} }
@ -105,22 +108,22 @@ export class GardenAudioGraph {
this.delayNode.delayTime.setTargetAtTime( this.delayNode.delayTime.setTargetAtTime(
this.config.delay.timeSeconds * profile.delayTimeMultiplier, this.config.delay.timeSeconds * profile.delayTimeMultiplier,
now, now,
appConfig.audioEngine.graph.delayTimeRampSeconds this.engineConfig.graph.delayTimeRampSeconds
); );
this.delayFeedback.gain.setTargetAtTime( this.delayFeedback.gain.setTargetAtTime(
clamp( clamp(
this.config.delay.feedback + this.config.delay.feedback +
activity * appConfig.audioEngine.graph.delayActivityFeedbackWeight, activity * this.engineConfig.graph.delayActivityFeedbackWeight,
appConfig.audioEngine.graph.delayFeedbackMin, this.engineConfig.graph.delayFeedbackMin,
appConfig.audioEngine.graph.delayFeedbackMax this.engineConfig.graph.delayFeedbackMax
), ),
now, now,
this.config.updateRampSeconds this.config.updateRampSeconds
); );
this.delayOutput.gain.setTargetAtTime( this.delayOutput.gain.setTargetAtTime(
this.config.delay.wetGain * this.config.delay.wetGain *
(appConfig.audioEngine.graph.delayOutputBase + (this.engineConfig.graph.delayOutputBase +
activity * appConfig.audioEngine.graph.delayOutputActivityWeight), activity * this.engineConfig.graph.delayOutputActivityWeight),
now, now,
this.config.updateRampSeconds this.config.updateRampSeconds
); );
@ -134,9 +137,9 @@ export class GardenAudioGraph {
if (this.masterGain && context.state !== 'closed') { if (this.masterGain && context.state !== 'closed') {
this.masterGain.gain.setTargetAtTime( this.masterGain.gain.setTargetAtTime(
appConfig.audioEngine.graph.closeGain, this.engineConfig.graph.closeGain,
context.currentTime, context.currentTime,
appConfig.audioEngine.graph.closeRampSeconds this.engineConfig.graph.closeRampSeconds
); );
} }
@ -171,7 +174,7 @@ export class GardenAudioGraph {
private createBuses(context: AudioContext, masterGain: GainNode): void { private createBuses(context: AudioContext, masterGain: GainNode): void {
this.eventBus = context.createGain(); this.eventBus = context.createGain();
this.eventBus.gain.value = appConfig.audioEngine.graph.eventBusGain; this.eventBus.gain.value = this.engineConfig.graph.eventBusGain;
this.eventBus.connect(masterGain); this.eventBus.connect(masterGain);
} }
@ -181,9 +184,9 @@ export class GardenAudioGraph {
for (let index = 0; index < data.length; index++) { for (let index = 0; index < data.length; index++) {
data[index] = data[index] =
appConfig.audioEngine.graph.noiseMin + this.engineConfig.graph.noiseMin +
Math.random() * Math.random() *
(appConfig.audioEngine.graph.noiseMax - appConfig.audioEngine.graph.noiseMin); (this.engineConfig.graph.noiseMax - this.engineConfig.graph.noiseMin);
} }
return buffer; return buffer;

View file

@ -1,4 +1,4 @@
import { appConfig } from '../config'; import type { GardenAudioEngineConfig } from '../config';
import { clamp01 } from '../utils/clamp'; import { clamp01 } from '../utils/clamp';
import { GardenAudioStroke } from './garden-audio-types'; import { GardenAudioStroke } from './garden-audio-types';
@ -12,24 +12,25 @@ export interface GardenAudioStrokeMetrics {
export const getStrokeMetrics = ( export const getStrokeMetrics = (
stroke: GardenAudioStroke, stroke: GardenAudioStroke,
speedForFullEnergyPixelsPerSecond: number, speedForFullEnergyPixelsPerSecond: number,
fallbackPressure: number fallbackPressure: number,
inputConfig: GardenAudioEngineConfig['input']
): GardenAudioStrokeMetrics => { ): GardenAudioStrokeMetrics => {
const dx = stroke.to[0] - stroke.from[0]; const dx = stroke.to[0] - stroke.from[0];
const dy = stroke.to[1] - stroke.from[1]; const dy = stroke.to[1] - stroke.from[1];
const distancePixels = Math.hypot(dx, dy); const distancePixels = Math.hypot(dx, dy);
const speedPixelsPerSecond = getStrokeVelocity(stroke, distancePixels); const speedPixelsPerSecond = getStrokeVelocity(stroke, distancePixels, inputConfig);
const pressure = getPressureAmount(stroke, fallbackPressure); const pressure = getPressureAmount(stroke, fallbackPressure, inputConfig);
const speedAmount = clamp01(speedPixelsPerSecond / speedForFullEnergyPixelsPerSecond); const speedAmount = clamp01(speedPixelsPerSecond / speedForFullEnergyPixelsPerSecond);
const strokeEnergy = clamp01( const strokeEnergy = clamp01(
appConfig.audioEngine.input.strokeEnergyBase + inputConfig.strokeEnergyBase +
speedAmount * appConfig.audioEngine.input.strokeEnergySpeedWeight + speedAmount * inputConfig.strokeEnergySpeedWeight +
pressure * appConfig.audioEngine.input.strokeEnergyPressureWeight pressure * inputConfig.strokeEnergyPressureWeight
); );
const effectiveEnergy = const effectiveEnergy =
strokeEnergy * strokeEnergy *
(appConfig.audioEngine.input.distanceEnergyBase + (inputConfig.distanceEnergyBase +
clamp01(distancePixels / appConfig.audioEngine.input.distanceForFullEnergyPixels) * clamp01(distancePixels / inputConfig.distanceForFullEnergyPixels) *
appConfig.audioEngine.input.distanceEnergyScale); inputConfig.distanceEnergyScale);
return { return {
distancePixels, distancePixels,
@ -39,7 +40,11 @@ export const getStrokeMetrics = (
}; };
}; };
const getStrokeVelocity = (stroke: GardenAudioStroke, distancePixels: number): number => { const getStrokeVelocity = (
stroke: GardenAudioStroke,
distancePixels: number,
inputConfig: GardenAudioEngineConfig['input']
): number => {
if ( if (
stroke.velocityPixelsPerSecond !== undefined && stroke.velocityPixelsPerSecond !== undefined &&
Number.isFinite(stroke.velocityPixelsPerSecond) && Number.isFinite(stroke.velocityPixelsPerSecond) &&
@ -48,12 +53,13 @@ const getStrokeVelocity = (stroke: GardenAudioStroke, distancePixels: number): n
return stroke.velocityPixelsPerSecond; return stroke.velocityPixelsPerSecond;
} }
return distancePixels / appConfig.audioEngine.input.fallbackFrameSeconds; return distancePixels / inputConfig.fallbackFrameSeconds;
}; };
const getPressureAmount = ( const getPressureAmount = (
stroke: GardenAudioStroke, stroke: GardenAudioStroke,
fallbackPressure: number fallbackPressure: number,
inputConfig: GardenAudioEngineConfig['input']
): number => { ): number => {
if ( if (
stroke.pressure !== undefined && stroke.pressure !== undefined &&
@ -64,6 +70,6 @@ const getPressureAmount = (
} }
return stroke.pointerType === 'pen' return stroke.pointerType === 'pen'
? Math.max(appConfig.audioEngine.input.penMinPressure, clamp01(fallbackPressure)) ? Math.max(inputConfig.penMinPressure, clamp01(fallbackPressure))
: clamp01(fallbackPressure); : clamp01(fallbackPressure);
}; };

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