more cleaning up

This commit is contained in:
Andras Schmelczer 2026-05-16 20:45:42 +01:00
commit 560398fefb
110 changed files with 931 additions and 2645 deletions

View file

@ -1,7 +1,5 @@
import { expect, test, type Page } from '@playwright/test'; import { expect, test, type Page } from '@playwright/test';
type WebGpuFailureMode = 'adapter-null' | 'adapter-rejects' | 'device-rejects';
const disableWebGpu = async (page: Page) => { const disableWebGpu = async (page: Page) => {
await page.addInitScript(() => { await page.addInitScript(() => {
Object.defineProperty(navigator, 'gpu', { Object.defineProperty(navigator, 'gpu', {
@ -11,54 +9,6 @@ const disableWebGpu = async (page: Page) => {
}); });
}; };
const emulateWebGpuFailure = async (page: Page, mode: WebGpuFailureMode) => {
await page.addInitScript((failureMode) => {
const limits = {
maxBufferSize: 256 * 1024 * 1024,
maxComputeWorkgroupsPerDimension: 65_535,
maxStorageBufferBindingSize: 128 * 1024 * 1024,
};
const adapter = {
features: new Set(),
info: {
architecture: 'test',
description: 'Playwright fake adapter',
device: 'test-device',
isFallbackAdapter: false,
subgroupMaxSize: 0,
subgroupMinSize: 0,
vendor: 'test-vendor',
},
limits,
requestDevice: async () => {
if (failureMode === 'device-rejects') {
throw new Error('Playwright fake device failure');
}
return {};
},
};
Object.defineProperty(navigator, 'gpu', {
configurable: true,
value: {
getPreferredCanvasFormat: () => 'rgba8unorm',
requestAdapter: async () => {
if (failureMode === 'adapter-null') {
return null;
}
if (failureMode === 'adapter-rejects') {
throw new Error('Playwright fake adapter failure');
}
return adapter;
},
},
});
}, mode);
};
const getFirstSwatchColor = (page: Page) => const getFirstSwatchColor = (page: Page) =>
page page
.locator('.color-swatch') .locator('.color-swatch')
@ -71,6 +21,18 @@ const getGardenBackground = (page: Page) =>
); );
test('loads the app shell and WebGPU fallback in Chromium', async ({ page }) => { test('loads the app shell and WebGPU fallback in Chromium', async ({ page }) => {
const browserFailures: Array<string> = [];
page.on('requestfailed', (request) => {
const failure = request.failure();
browserFailures.push(`${request.method()} ${request.url()} ${failure?.errorText}`);
});
page.on('response', (response) => {
if (response.status() >= 400) {
browserFailures.push(`${response.status()} ${response.url()}`);
}
});
await disableWebGpu(page); await disableWebGpu(page);
await page.goto('/'); await page.goto('/');
@ -85,6 +47,7 @@ test('loads the app shell and WebGPU fallback in Chromium', async ({ page }) =>
await page.getByRole('button', { name: 'About' }).click(); await page.getByRole('button', { name: 'About' }).click();
await expect(page.getByRole('heading', { name: 'Fleeting Garden' })).toBeVisible(); await expect(page.getByRole('heading', { name: 'Fleeting Garden' })).toBeVisible();
expect(browserFailures).toEqual([]);
}); });
test('keeps fallback controls interactive and accessible', async ({ page }) => { test('keeps fallback controls interactive and accessible', async ({ page }) => {
@ -106,13 +69,21 @@ test('keeps fallback controls interactive and accessible', async ({ page }) => {
await expect(aboutPanel).toHaveAttribute('aria-hidden', 'true'); await expect(aboutPanel).toHaveAttribute('aria-hidden', 'true');
await expect(aboutPanel).toHaveAttribute('inert', ''); await expect(aboutPanel).toHaveAttribute('inert', '');
const settingsButton = page.getByRole('button', { name: 'Show config overlay' }); const settingsButton = page.locator('button.settings');
await expect(settingsButton).toHaveAttribute('aria-label', 'Show config overlay');
await expect(settingsButton).toHaveAttribute('aria-expanded', 'false');
await settingsButton.click(); await settingsButton.click();
await expect(page.getByRole('button', { name: 'Hide config overlay' })).toHaveAttribute( await expect(settingsButton).toHaveAttribute('aria-expanded', 'true');
'aria-expanded', await expect(settingsButton).toHaveAttribute('aria-label', 'Hide config overlay');
'true'
);
await expect(page.locator('.config-pane')).toBeVisible(); await expect(page.locator('.config-pane')).toBeVisible();
await expect(page.locator('.config-pane')).toContainText('Runtime');
await expect(page.locator('.color-reaction-matrix')).toBeVisible();
const colorReaction = page.getByLabel('Color 1 agents reacting to color 2');
await colorReaction.selectOption('-1');
await expect(colorReaction).toHaveValue('-1');
await settingsButton.click();
await expect(settingsButton).toHaveAttribute('aria-expanded', 'false');
const soundButton = page.locator('button.sound'); const soundButton = page.locator('button.sound');
await expect(soundButton).toHaveAttribute('aria-pressed', 'false'); await expect(soundButton).toHaveAttribute('aria-pressed', 'false');
@ -146,98 +117,35 @@ test('keeps fallback controls interactive and accessible', async ({ page }) => {
await expect(page.locator('.mirror-segment-control')).toHaveClass(/active/); await expect(page.locator('.mirror-segment-control')).toHaveClass(/active/);
}); });
( test('keeps the fallback shell usable on mobile', async ({ page }) => {
[ await page.setViewportSize({ height: 844, width: 390 });
{
expectedCode: 'webgpu-adapter-unavailable',
expectedMessage:
'WebGPU is available, but this browser could not provide a compatible GPU adapter.',
mode: 'adapter-null',
},
{
expectedCode: 'webgpu-adapter-unavailable',
expectedMessage: 'Could not request a WebGPU adapter.',
mode: 'adapter-rejects',
},
{
expectedCode: 'webgpu-device-unavailable',
expectedMessage: 'Could not create a WebGPU device for this adapter.',
mode: 'device-rejects',
},
] satisfies Array<{
expectedCode: string;
expectedMessage: string;
mode: WebGpuFailureMode;
}>
).forEach(({ expectedCode, expectedMessage, mode }) => {
test(`reports ${mode} startup failures without leaving the shell loading`, async ({
page,
}) => {
await emulateWebGpuFailure(page, mode);
await page.goto('/');
await expect(page.locator('body')).not.toHaveClass(/is-loading/);
await expect(page.getByRole('toolbar', { name: 'Garden toolbar' })).toBeVisible();
await expect(page.getByRole('alert')).toContainText(expectedMessage);
await expect(page.getByRole('alert')).toContainText(expectedCode);
});
});
test('serves the production bundle without missing browser assets', async ({ page }) => {
const browserFailures: Array<string> = [];
page.on('requestfailed', (request) => {
const failure = request.failure();
browserFailures.push(`${request.method()} ${request.url()} ${failure?.errorText}`);
});
page.on('response', (response) => {
if (response.status() >= 400) {
browserFailures.push(`${response.status()} ${response.url()}`);
}
});
await disableWebGpu(page); await disableWebGpu(page);
await page.goto('/'); await page.goto('/');
await expect(page.locator('body')).not.toHaveClass(/is-loading/); await expect(page.locator('body')).not.toHaveClass(/is-loading/);
expect(browserFailures).toEqual([]); const canvasBox = await page
}); .getByRole('img', { name: 'Interactive generative garden canvas' })
.boundingBox();
expect(canvasBox?.width).toBeGreaterThan(0);
expect(canvasBox?.height).toBeGreaterThan(0);
await expect(page.getByRole('toolbar', { name: 'Garden toolbar' })).toBeVisible();
await expect(page.getByRole('button', { name: 'About' })).toBeVisible();
await expect(page.getByRole('alert')).toContainText('Fleeting Garden needs WebGPU');
[ const aboutButtonReceivesPointer = await page
{ height: 720, name: 'desktop', width: 1280 }, .getByRole('button', { name: 'About' })
{ height: 844, name: 'mobile', width: 390 }, .evaluate((button) => {
].forEach(({ height, name, width }) => { const rect = button.getBoundingClientRect();
test(`keeps the fallback shell usable on ${name}`, async ({ page }) => { const target = document.elementFromPoint(
await page.setViewportSize({ height, width }); rect.left + rect.width / 2,
await disableWebGpu(page); rect.top + rect.height / 2
);
await page.goto('/'); return button === target || button.contains(target);
await expect(page.locator('body')).not.toHaveClass(/is-loading/); });
const canvasBox = await page expect(aboutButtonReceivesPointer).toBe(true);
.getByRole('img', { name: 'Interactive generative garden canvas' })
.boundingBox();
expect(canvasBox?.width).toBeGreaterThan(0);
expect(canvasBox?.height).toBeGreaterThan(0);
await expect(page.getByRole('toolbar', { name: 'Garden toolbar' })).toBeVisible();
await expect(page.getByRole('button', { name: 'About' })).toBeVisible();
await expect(page.getByRole('alert')).toContainText('Fleeting Garden needs WebGPU');
const aboutButtonReceivesPointer = await page
.getByRole('button', { name: 'About' })
.evaluate((button) => {
const rect = button.getBoundingClientRect();
const target = document.elementFromPoint(
rect.left + rect.width / 2,
rect.top + rect.height / 2
);
return button === target || button.contains(target);
});
expect(aboutButtonReceivesPointer).toBe(true);
});
}); });
test('hides the bottom dock after the cursor leaves fullscreen controls', async ({ test('hides the bottom dock after the cursor leaves fullscreen controls', async ({
@ -305,5 +213,5 @@ test('keeps the bottom dock visible in mobile fullscreen', async ({ page }) => {
await page.waitForTimeout(5200); await page.waitForTimeout(5200);
await expect(page.locator('aside.control-dock')).not.toHaveClass(/menu-hidden/); await expect(page.locator('aside.control-dock')).not.toHaveClass(/menu-hidden/);
await expect(page.getByRole('button', { name: 'Show config overlay' })).toBeVisible(); await expect(page.getByRole('button', { name: 'About' })).toBeVisible();
}); });

View file

@ -22,10 +22,9 @@
<meta property="og:image:width" content="1920" /> <meta property="og:image:width" content="1920" />
<meta property="og:image:height" content="1920" /> <meta property="og:image:height" content="1920" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" /> <link rel="icon" type="image/svg+xml" href="favicon.svg" />
<link rel="icon" type="image/x-icon" href="/favicon.ico" /> <link rel="apple-touch-icon" href="apple-touch-icon-180x180.png" />
<link rel="apple-touch-icon" href="/apple-touch-icon-180x180.png" /> <link rel="manifest" href="manifest.webmanifest" />
<link rel="manifest" href="/manifest.webmanifest" />
<title>Fleeting Garden</title> <title>Fleeting Garden</title>
</head> </head>
@ -41,13 +40,13 @@
</canvas> </canvas>
<p id="canvas-description" class="visually-hidden"> <p id="canvas-description" class="visually-hidden">
Fleeting Garden is a pointer-driven WebGPU drawing canvas. Drag or touch the scene Fleeting Garden is a pointer-driven WebGPU drawing canvas. Drag or touch the scene
to paint coloured paths, then use the toolbar to change colours, erase, adjust the to paint coloured paths, then use the toolbar to change colours, erase, export,
config overlay, export, restart, or open more information. adjust the config overlay, restart, or open more information.
</p> </p>
<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-indicator" role="status">
<div class="loading-dots" aria-hidden="true"> <div class="loading-dots" aria-hidden="true">
<span class="loading-dot"></span> <span class="loading-dot"></span>
<span class="loading-dot"></span> <span class="loading-dot"></span>
@ -61,9 +60,7 @@
aria-valuemin="0" aria-valuemin="0"
aria-valuemax="100" aria-valuemax="100"
aria-valuenow="0" aria-valuenow="0"
> ></div>
<div class="loading-progress-fill"></div>
</div>
</div> </div>
<section class="errors-container"> <section class="errors-container">
@ -72,7 +69,15 @@
</main> </main>
<aside class="control-dock"> <aside class="control-dock">
<section id="info-panel" class="pages hidden info-page" aria-hidden="true" inert> <section
id="info-panel"
class="hidden info-page"
role="region"
aria-label="About panel"
aria-hidden="true"
tabindex="-1"
inert
>
<section> <section>
<h1>Fleeting Garden</h1> <h1>Fleeting Garden</h1>
<p> <p>
@ -125,22 +130,12 @@
title="Draw colour 3" title="Draw colour 3"
></button> ></button>
<label class="eraser-size-control" title="Erase and resize"> <label class="eraser-size-control" title="Erase and resize">
<input <input class="eraser-size-slider" type="range" aria-label="Eraser size" />
class="eraser-size-slider"
type="range"
min="24"
max="240"
step="1"
aria-label="Eraser size"
/>
</label> </label>
<label class="mirror-segment-control" title="Mirror off"> <label class="mirror-segment-control" title="Mirror off">
<input <input
class="mirror-segment-slider" class="mirror-segment-slider"
type="range" type="range"
min="1"
max="12"
step="1"
aria-label="Mirror segments" aria-label="Mirror segments"
/> />
</label> </label>

114
package-lock.json generated
View file

@ -24,13 +24,10 @@
"browserslist": "^4.28.2", "browserslist": "^4.28.2",
"eslint": "^10.3.0", "eslint": "^10.3.0",
"eslint-config-prettier": "^10.1.8", "eslint-config-prettier": "^10.1.8",
"eslint-plugin-prettier": "^5.5.5",
"eslint-plugin-unused-imports": "^4.4.1",
"gl-matrix": "^3.4.4", "gl-matrix": "^3.4.4",
"globals": "^17.6.0", "globals": "^17.6.0",
"knip": "^6.14.1", "knip": "^6.14.1",
"lightningcss": "^1.32.0", "lightningcss": "^1.32.0",
"npm-check-updates": "^22.1.0",
"prettier": "^3.8.3", "prettier": "^3.8.3",
"sass": "^1.99.0", "sass": "^1.99.0",
"typescript": "^6.0.3", "typescript": "^6.0.3",
@ -1924,19 +1921,6 @@
"url": "https://opencollective.com/parcel" "url": "https://opencollective.com/parcel"
} }
}, },
"node_modules/@pkgr/core": {
"version": "0.2.9",
"resolved": "https://registry.npmjs.org/@pkgr/core/-/core-0.2.9.tgz",
"integrity": "sha512-QNqXyfVS2wm9hweSYD2O7F0G06uurj9kZ96TRQE5Y9hU7+tgdZwIkbAKc5Ocy1HxEY2kuDQa6cQ1WRs/O5LFKA==",
"dev": true,
"license": "MIT",
"engines": {
"node": "^12.20.0 || ^14.18.0 || >=16.0.0"
},
"funding": {
"url": "https://opencollective.com/pkgr"
}
},
"node_modules/@plausible-analytics/tracker": { "node_modules/@plausible-analytics/tracker": {
"version": "0.4.5", "version": "0.4.5",
"resolved": "https://registry.npmjs.org/@plausible-analytics/tracker/-/tracker-0.4.5.tgz", "resolved": "https://registry.npmjs.org/@plausible-analytics/tracker/-/tracker-0.4.5.tgz",
@ -3169,53 +3153,6 @@
"eslint": ">=7.0.0" "eslint": ">=7.0.0"
} }
}, },
"node_modules/eslint-plugin-prettier": {
"version": "5.5.5",
"resolved": "https://registry.npmjs.org/eslint-plugin-prettier/-/eslint-plugin-prettier-5.5.5.tgz",
"integrity": "sha512-hscXkbqUZ2sPithAuLm5MXL+Wph+U7wHngPBv9OMWwlP8iaflyxpjTYZkmdgB4/vPIhemRlBEoLrH7UC1n7aUw==",
"dev": true,
"license": "MIT",
"dependencies": {
"prettier-linter-helpers": "^1.0.1",
"synckit": "^0.11.12"
},
"engines": {
"node": "^14.18.0 || >=16.0.0"
},
"funding": {
"url": "https://opencollective.com/eslint-plugin-prettier"
},
"peerDependencies": {
"@types/eslint": ">=8.0.0",
"eslint": ">=8.0.0",
"eslint-config-prettier": ">= 7.0.0 <10.0.0 || >=10.1.0",
"prettier": ">=3.0.0"
},
"peerDependenciesMeta": {
"@types/eslint": {
"optional": true
},
"eslint-config-prettier": {
"optional": true
}
}
},
"node_modules/eslint-plugin-unused-imports": {
"version": "4.4.1",
"resolved": "https://registry.npmjs.org/eslint-plugin-unused-imports/-/eslint-plugin-unused-imports-4.4.1.tgz",
"integrity": "sha512-oZGYUz1X3sRMGUB+0cZyK2VcvRX5lm/vB56PgNNcU+7ficUCKm66oZWKUubXWnOuPjQ8PvmXtCViXBMONPe7tQ==",
"dev": true,
"license": "MIT",
"peerDependencies": {
"@typescript-eslint/eslint-plugin": "^8.0.0-0 || ^7.0.0 || ^6.0.0 || ^5.0.0",
"eslint": "^10.0.0 || ^9.0.0 || ^8.0.0"
},
"peerDependenciesMeta": {
"@typescript-eslint/eslint-plugin": {
"optional": true
}
}
},
"node_modules/eslint-scope": { "node_modules/eslint-scope": {
"version": "9.1.2", "version": "9.1.2",
"resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-9.1.2.tgz", "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-9.1.2.tgz",
@ -3339,13 +3276,6 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/fast-diff": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/fast-diff/-/fast-diff-1.3.0.tgz",
"integrity": "sha512-VxPP4NqbUjj6MaAOafWeUn2cXWLcCtljklUtZf0Ind4XQ+QPtmA0b18zZy0jIQx+ExRVCR/ZQpBmik5lXshNsw==",
"dev": true,
"license": "Apache-2.0"
},
"node_modules/fast-json-stable-stringify": { "node_modules/fast-json-stable-stringify": {
"version": "2.1.0", "version": "2.1.0",
"resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz",
@ -4125,21 +4055,6 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/npm-check-updates": {
"version": "22.1.0",
"resolved": "https://registry.npmjs.org/npm-check-updates/-/npm-check-updates-22.1.0.tgz",
"integrity": "sha512-zKjYAa205S6UyHkNJGmiLFmm6M31175cvUA3OdHvVlCdtyTfkyQbPWoov/GJEc6PWVbCV5e+60c7S2eVp0ybOA==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"ncu": "build/cli.js",
"npm-check-updates": "build/cli.js"
},
"engines": {
"node": "^20.19.0 || ^22.12.0 || >=24.0.0",
"npm": ">=10.0.0"
}
},
"node_modules/obug": { "node_modules/obug": {
"version": "2.1.1", "version": "2.1.1",
"resolved": "https://registry.npmjs.org/obug/-/obug-2.1.1.tgz", "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.1.tgz",
@ -4430,19 +4345,6 @@
"url": "https://github.com/prettier/prettier?sponsor=1" "url": "https://github.com/prettier/prettier?sponsor=1"
} }
}, },
"node_modules/prettier-linter-helpers": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/prettier-linter-helpers/-/prettier-linter-helpers-1.0.1.tgz",
"integrity": "sha512-SxToR7P8Y2lWmv/kTzVLC1t/GDI2WGjMwNhLLE9qtH8Q13C+aEmuRlzDst4Up4s0Wc8sF2M+J57iB3cMLqftfg==",
"dev": true,
"license": "MIT",
"dependencies": {
"fast-diff": "^1.1.2"
},
"engines": {
"node": ">=6.0.0"
}
},
"node_modules/punycode": { "node_modules/punycode": {
"version": "2.3.1", "version": "2.3.1",
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
@ -4704,22 +4606,6 @@
"url": "https://github.com/sponsors/sindresorhus" "url": "https://github.com/sponsors/sindresorhus"
} }
}, },
"node_modules/synckit": {
"version": "0.11.12",
"resolved": "https://registry.npmjs.org/synckit/-/synckit-0.11.12.tgz",
"integrity": "sha512-Bh7QjT8/SuKUIfObSXNHNSK6WHo6J1tHCqJsuaFDP7gP0fkzSfTxI8y85JrppZ0h8l0maIgc2tfuZQ6/t3GtnQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@pkgr/core": "^0.2.9"
},
"engines": {
"node": "^14.18.0 || >=16.0.0"
},
"funding": {
"url": "https://opencollective.com/synckit"
}
},
"node_modules/tinybench": { "node_modules/tinybench": {
"version": "2.9.0", "version": "2.9.0",
"resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",

View file

@ -8,7 +8,7 @@
"dev": "vite --host 0.0.0.0", "dev": "vite --host 0.0.0.0",
"build": "vite build", "build": "vite build",
"preview": "vite preview", "preview": "vite preview",
"lint:check": "eslint --rule \"prettier/prettier: off\" \"src/**/*.ts\" && npm run unused:check", "lint:check": "eslint \"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}\" \"e2e/**/*.ts\" \".forgejo/workflows/*.yml\" \"*.{json,js,ts,md}\" \".prettierrc\"", "format": "prettier --write \"index.html\" \"src/**/*.{ts,scss,json,html}\" \"e2e/**/*.ts\" \".forgejo/workflows/*.yml\" \"*.{json,js,ts,md}\" \".prettierrc\"",
"format:check": "prettier --check \"index.html\" \"src/**/*.{ts,scss,json,html}\" \"e2e/**/*.ts\" \".forgejo/workflows/*.yml\" \"*.{json,js,ts,md}\" \".prettierrc\"", "format:check": "prettier --check \"index.html\" \"src/**/*.{ts,scss,json,html}\" \"e2e/**/*.ts\" \".forgejo/workflows/*.yml\" \"*.{json,js,ts,md}\" \".prettierrc\"",
@ -18,9 +18,8 @@
"test:e2e": "npm run build && playwright test", "test:e2e": "npm run build && playwright test",
"test:e2e:ui": "npm run build && playwright test --ui", "test:e2e:ui": "npm run build && playwright test --ui",
"test:watch": "vitest", "test:watch": "vitest",
"unused:check": "knip --exports --include-entry-exports", "unused:check": "knip --production --files --dependencies && knip --exports --include-entry-exports",
"generate-icons": "pwa-assets-generator", "generate-icons": "pwa-assets-generator"
"update": "ncu"
}, },
"engines": { "engines": {
"node": ">=20" "node": ">=20"
@ -40,6 +39,11 @@
"browserslist": [ "browserslist": [
"supports webgpu and last 2 years" "supports webgpu and last 2 years"
], ],
"knip": {
"ignoreFiles": [
"pwa-assets.config.ts"
]
},
"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",
@ -52,13 +56,10 @@
"browserslist": "^4.28.2", "browserslist": "^4.28.2",
"eslint": "^10.3.0", "eslint": "^10.3.0",
"eslint-config-prettier": "^10.1.8", "eslint-config-prettier": "^10.1.8",
"eslint-plugin-prettier": "^5.5.5",
"eslint-plugin-unused-imports": "^4.4.1",
"gl-matrix": "^3.4.4", "gl-matrix": "^3.4.4",
"globals": "^17.6.0", "globals": "^17.6.0",
"knip": "^6.14.1", "knip": "^6.14.1",
"lightningcss": "^1.32.0", "lightningcss": "^1.32.0",
"npm-check-updates": "^22.1.0",
"prettier": "^3.8.3", "prettier": "^3.8.3",
"sass": "^1.99.0", "sass": "^1.99.0",
"typescript": "^6.0.3", "typescript": "^6.0.3",

View file

@ -17,7 +17,7 @@ export default defineConfig({
trace: 'on-first-retry', trace: 'on-first-retry',
}, },
webServer: { webServer: {
command: `npm run preview -- --host 127.0.0.1 --port ${port}`, command: `npm run build && npm run preview -- --host 127.0.0.1 --port ${port}`,
ignoreHTTPSErrors: true, ignoreHTTPSErrors: true,
reuseExistingServer: false, reuseExistingServer: false,
timeout: 120_000, timeout: 120_000,

View file

@ -3,23 +3,14 @@
"short_name": "Garden", "short_name": "Garden",
"description": "A joyful WebGPU drawing garden where coloured paths grow into organic agent trails.", "description": "A joyful WebGPU drawing garden where coloured paths grow into organic agent trails.",
"start_url": "./", "start_url": "./",
"scope": "./",
"display": "fullscreen", "display": "fullscreen",
"display_override": ["fullscreen", "standalone", "minimal-ui"],
"orientation": "any",
"background_color": "#10151f", "background_color": "#10151f",
"theme_color": "#10151f", "theme_color": "#10151f",
"icons": [ "icons": [
{ {
"src": "favicon.svg", "src": "favicon.svg",
"sizes": "any", "sizes": "any",
"type": "image/svg+xml", "type": "image/svg+xml"
"purpose": "any"
},
{
"src": "pwa-64x64.png",
"sizes": "64x64",
"type": "image/png"
}, },
{ {
"src": "pwa-192x192.png", "src": "pwa-192x192.png",

View file

@ -1,2 +0,0 @@
User-agent: *
Allow: /

View file

@ -24,11 +24,7 @@ export const initAnalytics = () => {
domain: 'schmelczer.dev/floating', domain: 'schmelczer.dev/floating',
endpoint: 'https://stats.schmelczer.dev/status', endpoint: 'https://stats.schmelczer.dev/status',
autoCapturePageviews: true, autoCapturePageviews: true,
captureOnLocalhost: true,
logging: true, logging: true,
fileDownloads: true,
outboundLinks: true,
hashBasedRouting: true,
}); });
isInitialized = true; isInitialized = true;
} catch (error) { } catch (error) {
@ -63,7 +59,3 @@ export const trackExport = ({ vibeId }: { vibeId: string }) => {
}, },
}); });
}; };
export const trackSettingsOpen = () => {
track('Settings Open');
};

View file

@ -7,7 +7,7 @@ export interface GardenAudioChord {
quality: GardenAudioChordQuality; quality: GardenAudioChordQuality;
} }
interface GardenAudioColorVoice { interface GardenAudioStyleVoice {
scaleDegreeOffset: number; scaleDegreeOffset: number;
velocityMultiplier: number; velocityMultiplier: number;
panOffset: number; panOffset: number;
@ -20,13 +20,14 @@ export interface GardenAudioRegister {
pan: number; pan: number;
} }
export interface GardenAudioColorPool extends GardenAudioRegister { export interface GardenAudioStylePool extends GardenAudioRegister {
scaleDegrees: Array<number>; scaleDegrees: Array<number>;
} }
interface GardenAudioGenerativePianoConfig { interface GardenAudioGenerativePianoConfig {
colorPools: [GardenAudioColorPool, GardenAudioColorPool, GardenAudioColorPool]; stylePools: [GardenAudioStylePool, GardenAudioStylePool, GardenAudioStylePool];
padRegisters: [GardenAudioRegister, GardenAudioRegister, GardenAudioRegister]; padRegisters: [GardenAudioRegister, GardenAudioRegister, GardenAudioRegister];
styleRotationSeconds: number;
chordBars: number; chordBars: number;
supportBarSpacing: number; supportBarSpacing: number;
supportBarOffset: number; supportBarOffset: number;
@ -38,16 +39,14 @@ interface GardenAudioGenerativePianoConfig {
noteScorePreferenceWeight: number; noteScorePreferenceWeight: number;
noteScoreRegisterWeight: number; noteScoreRegisterWeight: number;
noteScoreRepeatPenalty: number; noteScoreRepeatPenalty: number;
gestureAccentSpacingSeconds: number;
gestureAccentMinIntervalSeconds: number; gestureAccentMinIntervalSeconds: number;
strokeAccentMinIntervalSeconds: number; strokeAccentMinIntervalSeconds: number;
strokeAccentThreshold: number; strokeAccentThreshold: number;
stingerSpacingSeconds: number;
stingerDurationSeconds: number; stingerDurationSeconds: number;
stingerSpacingSeconds: number;
maxBrushPhraseLayers: number; maxBrushPhraseLayers: number;
brushLayerBaseSeconds: number; brushLayerBaseSeconds: number;
brushLayerEnergySeconds: number; brushLayerEnergySeconds: number;
brushLayerMirrorSeconds: number;
brushLayerMinIntensity: number; brushLayerMinIntensity: number;
brushStreamIdleIntervalBeats: number; brushStreamIdleIntervalBeats: number;
brushStreamActiveIntervalBeats: number; brushStreamActiveIntervalBeats: number;
@ -137,12 +136,10 @@ export interface GardenAudioConfig {
unlockTickSeconds: number; unlockTickSeconds: number;
}; };
input: { input: {
activeActivityThreshold: number;
distanceWindowForFullActivityPixels: number; distanceWindowForFullActivityPixels: number;
distanceWindowSeconds: number; distanceWindowSeconds: number;
fallbackFrameSeconds: number; fallbackFrameSeconds: number;
manicActivityThreshold: number; manicActivityThreshold: number;
manicModeThreshold: number;
}; };
muteGain: number; muteGain: number;
muteRampSeconds: number; muteRampSeconds: number;
@ -156,8 +153,7 @@ export interface GardenAudioConfig {
startDelaySeconds: number; startDelaySeconds: number;
vibeChangeStingerMinIntervalSeconds: number; vibeChangeStingerMinIntervalSeconds: number;
generativePiano: GardenAudioGenerativePianoConfig; generativePiano: GardenAudioGenerativePianoConfig;
colorVoices: [GardenAudioColorVoice, GardenAudioColorVoice, GardenAudioColorVoice]; styleVoices: [GardenAudioStyleVoice, GardenAudioStyleVoice, GardenAudioStyleVoice];
vibes: Record<string, GardenAudioVibeProfile>;
} }
export const gardenAudioConfig: GardenAudioConfig = appConfig.audio; export const gardenAudioConfig: GardenAudioConfig = appConfig.audio;

View file

@ -2,10 +2,7 @@ import { clamp01 } from '../utils/clamp';
import type { GardenAudioConfig } from './garden-audio-config'; import type { GardenAudioConfig } from './garden-audio-config';
import type { GardenAudioStrokeMetrics } from './garden-audio-input'; import type { GardenAudioStrokeMetrics } from './garden-audio-input';
type GardenAudioGestureMode = 'calm' | 'active' | 'manic' | 'afterglow';
interface GardenAudioGestureFrame { interface GardenAudioGestureFrame {
mode: GardenAudioGestureMode;
activity: number; activity: number;
maniaAmount: number; maniaAmount: number;
} }
@ -15,44 +12,18 @@ interface GestureDistanceSample {
distancePixels: number; distancePixels: number;
} }
const DEFAULT_FRAME: GardenAudioGestureFrame = {
mode: 'calm',
activity: 0,
maniaAmount: 0,
};
export class GardenAudioGestureState { export class GardenAudioGestureState {
private readonly samples: Array<GestureDistanceSample> = []; private readonly samples: Array<GestureDistanceSample> = [];
private gestureClockSeconds = 0; private gestureClockSeconds = 0;
private peakActivity = 0;
private lastFrame: GardenAudioGestureFrame = DEFAULT_FRAME;
public constructor(private readonly inputConfig: GardenAudioConfig['input']) {} public constructor(private readonly inputConfig: GardenAudioConfig['input']) {}
public beginGesture(): void { public beginGesture(): void {
this.samples.length = 0; this.reset();
this.gestureClockSeconds = 0;
this.peakActivity = 0;
this.lastFrame = DEFAULT_FRAME;
} }
public endGesture(): GardenAudioGestureFrame { public endGesture(): void {
this.samples.length = 0; this.reset();
this.gestureClockSeconds = 0;
this.lastFrame = {
...DEFAULT_FRAME,
mode:
this.peakActivity >= this.inputConfig.activeActivityThreshold
? 'afterglow'
: 'calm',
};
this.peakActivity = 0;
return this.lastFrame;
}
public recordTouchDown(): GardenAudioGestureFrame {
this.lastFrame = DEFAULT_FRAME;
return this.lastFrame;
} }
public recordStroke({ public recordStroke({
@ -77,28 +48,16 @@ export class GardenAudioGestureState {
const activity = clamp01( const activity = clamp01(
windowDistancePixels / this.inputConfig.distanceWindowForFullActivityPixels windowDistancePixels / this.inputConfig.distanceWindowForFullActivityPixels
); );
const maniaAmount = smoothstep(this.inputConfig.manicActivityThreshold, 1, activity);
this.peakActivity = Math.max(this.peakActivity, activity); return {
this.lastFrame = {
...DEFAULT_FRAME,
mode: this.getMode(activity, maniaAmount),
activity, activity,
maniaAmount, maniaAmount: smoothstep(this.inputConfig.manicActivityThreshold, 1, activity),
}; };
return this.lastFrame;
}
public getFrame(): GardenAudioGestureFrame {
return this.lastFrame;
} }
public reset(): void { public reset(): void {
this.samples.length = 0; this.samples.length = 0;
this.gestureClockSeconds = 0; this.gestureClockSeconds = 0;
this.peakActivity = 0;
this.lastFrame = DEFAULT_FRAME;
} }
private trimSamples(): void { private trimSamples(): void {
@ -107,14 +66,6 @@ export class GardenAudioGestureState {
this.samples.shift(); this.samples.shift();
} }
} }
private getMode(activity: number, maniaAmount: number): GardenAudioGestureMode {
if (maniaAmount >= this.inputConfig.manicModeThreshold) {
return 'manic';
}
return activity >= this.inputConfig.activeActivityThreshold ? 'active' : 'calm';
}
} }
const smoothstep = (edge0: number, edge1: number, value: number): number => { const smoothstep = (edge0: number, edge1: number, value: number): number => {

View file

@ -1,25 +1,7 @@
import { VibePreset } from '../vibes'; import { VibePreset } from '../vibes';
import { import { GardenAudioChord, GardenAudioVibeProfile } from './garden-audio-config';
GardenAudioChord,
GardenAudioConfig,
GardenAudioVibeProfile,
} from './garden-audio-config';
import { GardenAudioColorIndex } from './garden-audio-types';
export const normalizeColorIndex = (index: number): GardenAudioColorIndex => export const getVibeProfile = (vibe: VibePreset): GardenAudioVibeProfile => vibe.audio;
Math.max(0, Math.min(2, Math.round(index))) as GardenAudioColorIndex;
export const getVibeProfile = (
config: GardenAudioConfig,
vibe: VibePreset
): GardenAudioVibeProfile => {
const profile = config.vibes[vibe.id];
if (!profile) {
throw new Error(`Missing audio profile for vibe "${vibe.id}"`);
}
return profile;
};
export const getChordIntervals = ( export const getChordIntervals = (
chord: GardenAudioChord, chord: GardenAudioChord,

View file

@ -1,10 +1,7 @@
import { VibePreset } from '../vibes'; import { VibePreset } from '../vibes';
export type GardenAudioColorIndex = 0 | 1 | 2;
export interface GardenAudioSnapshot { export interface GardenAudioSnapshot {
vibe: VibePreset; vibe: VibePreset;
selectedColorIndex: number;
isErasing: boolean; isErasing: boolean;
} }
@ -12,15 +9,10 @@ export interface GardenAudioStroke {
vibe: VibePreset; vibe: VibePreset;
from: ArrayLike<number>; from: ArrayLike<number>;
to: ArrayLike<number>; to: ArrayLike<number>;
colorIndex: number;
isErasing: boolean; isErasing: boolean;
elapsedSeconds?: number; elapsedSeconds?: number;
} }
export interface GardenAudioTouchDown {
colorIndex: number;
}
export interface GardenAudioStartOptions { export interface GardenAudioStartOptions {
userGesture?: boolean; userGesture?: boolean;
} }
@ -33,7 +25,6 @@ export interface LoadedPianoSample {
export interface ActivePianoVoice { export interface ActivePianoVoice {
gain: GainNode; gain: GainNode;
source: AudioScheduledSourceNode; source: AudioScheduledSourceNode;
startAt: number;
stopAt: number; stopAt: number;
} }

View file

@ -1,11 +1,8 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { appConfig } from '../config'; import { appConfig } from '../config';
import { ErrorHandler, Severity } from '../utils/error-handler';
import { VIBE_PRESETS } from '../vibes'; import { VIBE_PRESETS } from '../vibes';
import { GardenAudio } from './garden-audio';
import { gardenAudioConfig, GardenAudioConfig } from './garden-audio-config'; import { gardenAudioConfig, GardenAudioConfig } from './garden-audio-config';
import { loadPianoSamples, resetPianoSampleCacheForTest } from './piano-samples';
type FakeScheduledSourceNode = { type FakeScheduledSourceNode = {
start: ReturnType<typeof vi.fn>; start: ReturnType<typeof vi.fn>;
@ -21,6 +18,10 @@ const calls = {
let contextState: AudioContextState = 'suspended'; let contextState: AudioContextState = 'suspended';
let resumeError: Error | null = null; let resumeError: Error | null = null;
let ErrorHandler: typeof import('../utils/error-handler').ErrorHandler;
let GardenAudio: typeof import('./garden-audio').GardenAudio;
let loadPianoSamples: typeof import('./piano-samples').loadPianoSamples;
let Severity: typeof import('../utils/error-handler').Severity;
class FakeAudioParam { class FakeAudioParam {
public value = 0; public value = 0;
@ -140,14 +141,18 @@ const makeConfig = (): GardenAudioConfig => ({
}); });
describe('GardenAudio startup policy', () => { describe('GardenAudio startup policy', () => {
beforeEach(() => { beforeEach(async () => {
vi.resetModules();
({ ErrorHandler, Severity } = await import('../utils/error-handler'));
({ GardenAudio } = await import('./garden-audio'));
({ loadPianoSamples } = await import('./piano-samples'));
calls.constructed = 0; calls.constructed = 0;
calls.resumed = 0; calls.resumed = 0;
calls.sourcesStarted = 0; calls.sourcesStarted = 0;
calls.sources = []; calls.sources = [];
contextState = 'suspended'; contextState = 'suspended';
resumeError = null; resumeError = null;
resetPianoSampleCacheForTest();
vi.stubGlobal('AudioContext', FakeAudioContext); vi.stubGlobal('AudioContext', FakeAudioContext);
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('not loaded in tests'))); vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('not loaded in tests')));
}); });
@ -155,7 +160,6 @@ describe('GardenAudio startup policy', () => {
afterEach(() => { afterEach(() => {
vi.restoreAllMocks(); vi.restoreAllMocks();
vi.unstubAllGlobals(); vi.unstubAllGlobals();
resetPianoSampleCacheForTest();
}); });
it('does not create an AudioContext from passive audio paths', () => { it('does not create an AudioContext from passive audio paths', () => {
@ -167,7 +171,6 @@ describe('GardenAudio startup policy', () => {
vibe, vibe,
from: [0, 0], from: [0, 0],
to: [12, 0], to: [12, 0],
colorIndex: 0,
isErasing: false, isErasing: false,
}); });
@ -215,14 +218,10 @@ describe('GardenAudio startup policy', () => {
expect(calls.sourcesStarted).toBe(1); expect(calls.sourcesStarted).toBe(1);
audio.beginGesture(); audio.beginGesture();
audio.touchDown({
colorIndex: 1,
});
audio.stroke({ audio.stroke({
vibe, vibe,
from: [30, 40], from: [30, 40],
to: [60, 60], to: [60, 60],
colorIndex: 1,
isErasing: false, isErasing: false,
elapsedSeconds: 0.05, elapsedSeconds: 0.05,
}); });
@ -233,7 +232,6 @@ describe('GardenAudio startup policy', () => {
vibe, vibe,
from: [60, 60], from: [60, 60],
to: [75, 80], to: [75, 80],
colorIndex: 1,
isErasing: true, isErasing: true,
elapsedSeconds: 0.05, elapsedSeconds: 0.05,
}); });
@ -256,14 +254,10 @@ describe('GardenAudio startup policy', () => {
audio.start(vibe, { userGesture: true }); audio.start(vibe, { userGesture: true });
audio.beginGesture(); audio.beginGesture();
audio.touchDown({
colorIndex: 1,
});
audio.stroke({ audio.stroke({
vibe, vibe,
from: [30, 40], from: [30, 40],
to: [90, 40], to: [90, 40],
colorIndex: 1,
elapsedSeconds: 0.05, elapsedSeconds: 0.05,
isErasing: false, isErasing: false,
}); });

View file

@ -6,13 +6,11 @@ import { GardenAudioEnergy } from './garden-audio-energy';
import { GardenAudioGestureState } from './garden-audio-gesture-state'; import { GardenAudioGestureState } from './garden-audio-gesture-state';
import { GardenAudioGraph } from './garden-audio-graph'; import { GardenAudioGraph } from './garden-audio-graph';
import { getStrokeMetrics } from './garden-audio-input'; import { getStrokeMetrics } from './garden-audio-input';
import { getVibeProfile, normalizeColorIndex } from './garden-audio-music'; import { getVibeProfile } from './garden-audio-music';
import type { import type {
GardenAudioColorIndex,
GardenAudioSnapshot, GardenAudioSnapshot,
GardenAudioStartOptions, GardenAudioStartOptions,
GardenAudioStroke, GardenAudioStroke,
GardenAudioTouchDown,
} from './garden-audio-types'; } from './garden-audio-types';
import { GenerativePianoEngine } from './generative-piano'; import { GenerativePianoEngine } from './generative-piano';
import { NoiseBurstPlayer } from './noise-burst-player'; import { NoiseBurstPlayer } from './noise-burst-player';
@ -22,7 +20,6 @@ export type {
GardenAudioSnapshot, GardenAudioSnapshot,
GardenAudioStartOptions, GardenAudioStartOptions,
GardenAudioStroke, GardenAudioStroke,
GardenAudioTouchDown,
} from './garden-audio-types'; } from './garden-audio-types';
export class GardenAudio { export class GardenAudio {
@ -38,7 +35,6 @@ export class GardenAudio {
private isDestroyed = false; private isDestroyed = false;
private isMuted = false; private isMuted = false;
private isGestureActive = false; private isGestureActive = false;
private selectedColorIndex: GardenAudioColorIndex = 0;
private hasQueuedPianoLoad = false; private hasQueuedPianoLoad = false;
private lastEraserAt = Number.NEGATIVE_INFINITY; private lastEraserAt = Number.NEGATIVE_INFINITY;
private lastVibeStingerAt = Number.NEGATIVE_INFINITY; private lastVibeStingerAt = Number.NEGATIVE_INFINITY;
@ -162,20 +158,6 @@ export class GardenAudio {
this.pianoEngine.endGesture(); this.pianoEngine.endGesture();
} }
public touchDown(touch: GardenAudioTouchDown): void {
if (this.isDestroyed || this.isMuted) {
return;
}
const context = this.graph.context;
if (!context || !this.isGestureActive) {
return;
}
this.selectedColorIndex = normalizeColorIndex(touch.colorIndex);
this.gestureState.recordTouchDown();
}
public update(snapshot: GardenAudioSnapshot): void { public update(snapshot: GardenAudioSnapshot): void {
const context = this.graph.context; const context = this.graph.context;
if (!this.hasStarted || !context || this.isMuted) { if (!this.hasStarted || !context || this.isMuted) {
@ -183,7 +165,6 @@ export class GardenAudio {
} }
this.applyVibe(snapshot.vibe); this.applyVibe(snapshot.vibe);
this.selectedColorIndex = normalizeColorIndex(snapshot.selectedColorIndex);
this.energy.update(context.currentTime); this.energy.update(context.currentTime);
if (snapshot.isErasing) { if (snapshot.isErasing) {
@ -194,7 +175,6 @@ export class GardenAudio {
vibe: snapshot.vibe, vibe: snapshot.vibe,
now: context.currentTime, now: context.currentTime,
activity: snapshot.isErasing ? 0 : this.energy.getLevel(), activity: snapshot.isErasing ? 0 : this.energy.getLevel(),
selectedColorIndex: this.selectedColorIndex,
}); });
this.updateDelay(snapshot); this.updateDelay(snapshot);
} }
@ -216,7 +196,6 @@ export class GardenAudio {
const metrics = getStrokeMetrics(stroke, this.config.input); const metrics = getStrokeMetrics(stroke, this.config.input);
const now = context.currentTime; const now = context.currentTime;
this.selectedColorIndex = normalizeColorIndex(stroke.colorIndex);
const frame = this.gestureState.recordStroke({ metrics }); const frame = this.gestureState.recordStroke({ metrics });
const strokeEnergy = frame.activity; const strokeEnergy = frame.activity;
@ -231,7 +210,6 @@ export class GardenAudio {
vibe: stroke.vibe, vibe: stroke.vibe,
now, now,
activity: strokeEnergy, activity: strokeEnergy,
selectedColorIndex: this.selectedColorIndex,
maniaAmount: frame.maniaAmount, maniaAmount: frame.maniaAmount,
}); });
} }
@ -247,7 +225,6 @@ export class GardenAudio {
this.currentVibeId = null; this.currentVibeId = null;
this.hasStarted = false; this.hasStarted = false;
this.isGestureActive = false; this.isGestureActive = false;
this.selectedColorIndex = 0;
this.hasQueuedPianoLoad = false; this.hasQueuedPianoLoad = false;
this.lastEraserAt = Number.NEGATIVE_INFINITY; this.lastEraserAt = Number.NEGATIVE_INFINITY;
this.lastVibeStingerAt = Number.NEGATIVE_INFINITY; this.lastVibeStingerAt = Number.NEGATIVE_INFINITY;
@ -301,7 +278,7 @@ export class GardenAudio {
return; return;
} }
const profile = getVibeProfile(this.config, snapshot.vibe); const profile = getVibeProfile(snapshot.vibe);
const activity = snapshot.isErasing const activity = snapshot.isErasing
? this.config.delay.erasingActivity ? this.config.delay.erasingActivity
: this.energy.getLevel(); : this.energy.getLevel();
@ -314,7 +291,7 @@ export class GardenAudio {
} }
this.currentVibeId = vibe.id; this.currentVibeId = vibe.id;
this.graph.applyDelayProfile(getVibeProfile(this.config, vibe)); this.graph.applyDelayProfile(getVibeProfile(vibe));
this.pianoEngine.cue(this.graph.context.currentTime); this.pianoEngine.cue(this.graph.context.currentTime);
} }
} }

View file

@ -24,14 +24,13 @@ const getBeatsPerBar = (): number =>
const renderBars = ( const renderBars = (
engine: GenerativePianoEngine, engine: GenerativePianoEngine,
activity: number, activity: number,
selectedColorIndex = 0, bars = 8,
bars = 8 now = 0
) => { ) => {
engine.renderLookahead({ engine.renderLookahead({
vibe: VIBE_PRESETS[0], vibe: VIBE_PRESETS[0],
now: 0, now,
activity, activity,
selectedColorIndex: selectedColorIndex as 0 | 1 | 2,
lookaheadSeconds: getBeatSeconds() * getBeatsPerBar() * bars, lookaheadSeconds: getBeatSeconds() * getBeatsPerBar() * bars,
}); });
}; };
@ -64,7 +63,7 @@ describe('GenerativePianoEngine', () => {
it('keeps the background sparse instead of filling every beat', () => { it('keeps the background sparse instead of filling every beat', () => {
const { engine, notes } = makeEngine(); const { engine, notes } = makeEngine();
renderBars(engine, 0, 1, 4); renderBars(engine, 0, 4);
expect(uniqueStartTimes(notes).length).toBeLessThan(8); expect(uniqueStartTimes(notes).length).toBeLessThan(8);
}); });
@ -74,8 +73,8 @@ describe('GenerativePianoEngine', () => {
const active = makeEngine(); const active = makeEngine();
const startDelaySeconds = 0.02; const startDelaySeconds = 0.02;
renderBars(idle.engine, 0, 1, 8); renderBars(idle.engine, 0, 8);
renderBars(active.engine, 1, 1, 8); renderBars(active.engine, 1, 8);
expect(active.notes.length).toBeGreaterThan(idle.notes.length); expect(active.notes.length).toBeGreaterThan(idle.notes.length);
active.notes.forEach((note) => { active.notes.forEach((note) => {
@ -84,29 +83,34 @@ describe('GenerativePianoEngine', () => {
}); });
}); });
it('uses color pools with multiple notes instead of one key per color', () => { it('uses style pools with multiple notes instead of one repeating key', () => {
([0, 1, 2] as const).forEach((selectedColorIndex) => { const { engine, notes } = makeEngine();
const { engine, notes } = makeEngine();
renderBars(engine, 1, selectedColorIndex, 16); renderBars(engine, 1, 16);
expect(new Set(notes.map((note) => note.midi)).size).toBeGreaterThan(3); expect(new Set(notes.map((note) => note.midi)).size).toBeGreaterThan(3);
});
}); });
it('keeps the upper color higher and wider than the lower color', () => { it('changes musical style over time without a color change', () => {
const lower = makeEngine(); const { engine, notes } = makeEngine();
const upper = makeEngine();
renderBars(lower.engine, 1, 0, 16); renderBars(engine, 1, 32);
renderBars(upper.engine, 1, 2, 16);
expect(average(upper.notes.map((note) => note.midi))).toBeGreaterThan( const styleWindows = [
average(lower.notes.map((note) => note.midi)) notes.filter((note) => note.startTime >= 0 && note.startTime < 8),
notes.filter((note) => note.startTime >= 8 && note.startTime < 16),
notes.filter((note) => note.startTime >= 16 && note.startTime < 24),
];
const averageMidiByWindow = styleWindows.map((windowNotes) =>
Math.round(average(windowNotes.map((note) => note.midi)))
); );
expect(average(upper.notes.map((note) => note.pan))).toBeGreaterThan( const averagePanByWindow = styleWindows.map((windowNotes) =>
average(lower.notes.map((note) => note.pan)) Number(average(windowNotes.map((note) => note.pan)).toFixed(2))
); );
expect(styleWindows.every((windowNotes) => windowNotes.length > 0)).toBe(true);
expect(new Set(averageMidiByWindow).size).toBeGreaterThan(1);
expect(new Set(averagePanByWindow).size).toBeGreaterThan(1);
}); });
it('starts a fading brush phrase layer with each new brush gesture', () => { it('starts a fading brush phrase layer with each new brush gesture', () => {
@ -118,7 +122,6 @@ describe('GenerativePianoEngine', () => {
vibe: VIBE_PRESETS[0], vibe: VIBE_PRESETS[0],
now, now,
activity: 0.35, activity: 0.35,
selectedColorIndex: 1,
lookaheadSeconds: 12, lookaheadSeconds: 12,
}); });
@ -127,14 +130,11 @@ describe('GenerativePianoEngine', () => {
vibe: VIBE_PRESETS[0], vibe: VIBE_PRESETS[0],
now, now,
activity: 0.85, activity: 0.85,
selectedColorIndex: 1,
mirrorAmount: 0.45,
}); });
layered.engine.renderLookahead({ layered.engine.renderLookahead({
vibe: VIBE_PRESETS[0], vibe: VIBE_PRESETS[0],
now, now,
activity: 0.35, activity: 0.35,
selectedColorIndex: 1,
lookaheadSeconds: 12, lookaheadSeconds: 12,
}); });
@ -149,46 +149,6 @@ describe('GenerativePianoEngine', () => {
expect(lateExtra).toBe(0); expect(lateExtra).toBe(0);
}); });
it('makes brush phrase layers denser at higher mirror amounts', () => {
const lowMirror = makeEngine();
const highMirror = makeEngine();
const now = 4;
lowMirror.engine.beginGesture();
lowMirror.engine.recordStroke({
vibe: VIBE_PRESETS[0],
now,
activity: 0.85,
selectedColorIndex: 2,
mirrorAmount: 0,
});
lowMirror.engine.renderLookahead({
vibe: VIBE_PRESETS[0],
now,
activity: 0.35,
selectedColorIndex: 2,
lookaheadSeconds: 9,
});
highMirror.engine.beginGesture();
highMirror.engine.recordStroke({
vibe: VIBE_PRESETS[0],
now,
activity: 0.85,
selectedColorIndex: 2,
mirrorAmount: 1,
});
highMirror.engine.renderLookahead({
vibe: VIBE_PRESETS[0],
now,
activity: 0.35,
selectedColorIndex: 2,
lookaheadSeconds: 9,
});
expect(highMirror.notes.length).toBeGreaterThan(lowMirror.notes.length);
});
it('plays one immediate touch note and throttles later stroke accents', () => { it('plays one immediate touch note and throttles later stroke accents', () => {
const { engine, notes } = makeEngine(); const { engine, notes } = makeEngine();
const now = 4; const now = 4;
@ -198,13 +158,11 @@ describe('GenerativePianoEngine', () => {
vibe: VIBE_PRESETS[0], vibe: VIBE_PRESETS[0],
now, now,
activity: 0.9, activity: 0.9,
selectedColorIndex: 1,
}); });
engine.recordStroke({ engine.recordStroke({
vibe: VIBE_PRESETS[0], vibe: VIBE_PRESETS[0],
now: now + 1, now: now + 1,
activity: 0.95, activity: 0.95,
selectedColorIndex: 1,
}); });
expect(notes).toHaveLength(1); expect(notes).toHaveLength(1);
@ -214,7 +172,6 @@ describe('GenerativePianoEngine', () => {
vibe: VIBE_PRESETS[0], vibe: VIBE_PRESETS[0],
now: now + 6, now: now + 6,
activity: 0.95, activity: 0.95,
selectedColorIndex: 1,
}); });
expect(notes).toHaveLength(2); expect(notes).toHaveLength(2);
@ -225,8 +182,8 @@ describe('GenerativePianoEngine', () => {
const first = makeEngine(); const first = makeEngine();
const second = makeEngine(); const second = makeEngine();
renderBars(first.engine, 0.78, 2, 16); renderBars(first.engine, 0.78, 16);
renderBars(second.engine, 0.78, 2, 16); renderBars(second.engine, 0.78, 16);
expect(second.notes).toEqual(first.notes); expect(second.notes).toEqual(first.notes);
}); });

View file

@ -2,9 +2,9 @@ import { clamp, clamp01 } from '../utils/clamp';
import { VibePreset } from '../vibes'; import { VibePreset } from '../vibes';
import { import {
GardenAudioChord, GardenAudioChord,
GardenAudioColorPool,
GardenAudioConfig, GardenAudioConfig,
GardenAudioRegister, GardenAudioRegister,
GardenAudioStylePool,
GardenAudioVibeProfile, GardenAudioVibeProfile,
} from './garden-audio-config'; } from './garden-audio-config';
import { import {
@ -12,13 +12,14 @@ import {
getChordIntervals, getChordIntervals,
getVibeProfile, getVibeProfile,
} from './garden-audio-music'; } from './garden-audio-music';
import { GardenAudioColorIndex, PianoNote } from './garden-audio-types'; import { PianoNote } from './garden-audio-types';
type GardenAudioStyleIndex = 0 | 1 | 2;
interface RenderLookaheadRequest { interface RenderLookaheadRequest {
vibe: VibePreset; vibe: VibePreset;
now: number; now: number;
activity: number; activity: number;
selectedColorIndex: GardenAudioColorIndex;
lookaheadSeconds?: number; lookaheadSeconds?: number;
} }
@ -26,14 +27,6 @@ interface StrokeAccentRequest {
vibe: VibePreset; vibe: VibePreset;
now: number; now: number;
activity: number; activity: number;
selectedColorIndex: GardenAudioColorIndex;
mirrorAmount?: number;
panBias?: number;
registerBias?: number;
brightnessBias?: number;
contour?: number;
pressureAmount?: number;
pressureDelta?: number;
maniaAmount?: number; maniaAmount?: number;
} }
@ -41,14 +34,6 @@ interface TouchDownRequest {
vibe: VibePreset; vibe: VibePreset;
now: number; now: number;
strength: number; strength: number;
selectedColorIndex: GardenAudioColorIndex;
mirrorAmount?: number;
panBias?: number;
registerBias?: number;
brightnessBias?: number;
contour?: number;
pressureAmount?: number;
pressureDelta?: number;
maniaAmount?: number; maniaAmount?: number;
} }
@ -66,16 +51,9 @@ interface BrushPhraseLayer {
vibe: VibePreset; vibe: VibePreset;
startedAt: number; startedAt: number;
expiresAt: number; expiresAt: number;
selectedColorIndex: GardenAudioColorIndex; styleIndex: GardenAudioStyleIndex;
energy: number; energy: number;
mirrorAmount: number;
motifOffsets: Array<number>; motifOffsets: Array<number>;
panBias: number;
registerBias: number;
brightnessBias: number;
contour: number;
pressureAmount: number;
pressureDelta: number;
maniaAmount: number; maniaAmount: number;
} }
@ -86,7 +64,7 @@ export class GenerativePianoEngine {
private isWaitingForGestureAccent = false; private isWaitingForGestureAccent = false;
private lastGestureAccentAt = Number.NEGATIVE_INFINITY; private lastGestureAccentAt = Number.NEGATIVE_INFINITY;
private lastStrokeAccentAt = Number.NEGATIVE_INFINITY; private lastStrokeAccentAt = Number.NEGATIVE_INFINITY;
private readonly lastMidiByColor: [number | null, number | null, number | null] = [ private readonly lastMidiByStyle: [number | null, number | null, number | null] = [
null, null,
null, null,
null, null,
@ -130,31 +108,15 @@ export class GenerativePianoEngine {
this.isWaitingForGestureAccent = false; this.isWaitingForGestureAccent = false;
} }
public recordTouchDown({ private recordTouchDown({
vibe, vibe,
now, now,
strength, strength,
selectedColorIndex,
mirrorAmount = 0,
panBias = 0,
registerBias = 0,
brightnessBias = 0.5,
contour = 0,
pressureAmount = 0,
pressureDelta = 0,
maniaAmount = 0, maniaAmount = 0,
}: TouchDownRequest): void { }: TouchDownRequest): void {
const normalizedStrength = clamp01(strength); const normalizedStrength = clamp01(strength);
const normalizedMirrorAmount = clamp01(mirrorAmount); const normalizedManiaAmount = clamp01(maniaAmount);
const normalizedMotif = this.normalizeMotif({ const styleIndex = this.getStyleIndex(now);
panBias,
registerBias,
brightnessBias,
contour,
pressureAmount,
pressureDelta,
maniaAmount,
});
this.isWaitingForGestureAccent = false; this.isWaitingForGestureAccent = false;
this.lastGestureAccentAt = now; this.lastGestureAccentAt = now;
@ -163,18 +125,14 @@ export class GenerativePianoEngine {
vibe, vibe,
now, now,
strength: normalizedStrength, strength: normalizedStrength,
selectedColorIndex, styleIndex,
mirrorAmount: normalizedMirrorAmount, maniaAmount: normalizedManiaAmount,
...normalizedMotif,
}); });
this.playTouchNote({ this.playTouchNote({
vibe, vibe,
now, now,
selectedColorIndex, styleIndex,
strength: normalizedStrength, strength: normalizedStrength,
panBias: normalizedMotif.panBias,
registerBias: normalizedMotif.registerBias,
brightnessBias: normalizedMotif.brightnessBias,
}); });
} }
@ -182,27 +140,11 @@ export class GenerativePianoEngine {
vibe, vibe,
now, now,
activity, activity,
selectedColorIndex,
mirrorAmount = 0,
panBias = 0,
registerBias = 0,
brightnessBias = 0.5,
contour = 0,
pressureAmount = 0,
pressureDelta = 0,
maniaAmount = 0, maniaAmount = 0,
}: StrokeAccentRequest): void { }: StrokeAccentRequest): void {
const strength = clamp01(activity); const strength = clamp01(activity);
const normalizedMirrorAmount = clamp01(mirrorAmount); const normalizedManiaAmount = clamp01(maniaAmount);
const normalizedMotif = this.normalizeMotif({ const styleIndex = this.getStyleIndex(now);
panBias,
registerBias,
brightnessBias,
contour,
pressureAmount,
pressureDelta,
maniaAmount,
});
if ( if (
this.isWaitingForGestureAccent && this.isWaitingForGestureAccent &&
@ -212,9 +154,7 @@ export class GenerativePianoEngine {
vibe, vibe,
now, now,
strength, strength,
selectedColorIndex, maniaAmount: normalizedManiaAmount,
mirrorAmount: normalizedMirrorAmount,
...normalizedMotif,
}); });
return; return;
} }
@ -223,16 +163,15 @@ export class GenerativePianoEngine {
this.updateBrushPhraseLayer({ this.updateBrushPhraseLayer({
now, now,
strength, strength,
selectedColorIndex, styleIndex,
mirrorAmount: normalizedMirrorAmount, maniaAmount: normalizedManiaAmount,
...normalizedMotif,
}); });
if ( if (
strength >= this.generation.strokeAccentThreshold && strength >= this.generation.strokeAccentThreshold &&
now - this.lastStrokeAccentAt >= this.generation.strokeAccentMinIntervalSeconds now - this.lastStrokeAccentAt >= this.generation.strokeAccentMinIntervalSeconds
) { ) {
this.lastStrokeAccentAt = now; this.lastStrokeAccentAt = now;
this.playGestureAccent(vibe, now, selectedColorIndex, strength, 1); this.playGestureAccent(vibe, now, styleIndex, strength);
} }
} }
@ -240,7 +179,6 @@ export class GenerativePianoEngine {
vibe, vibe,
now, now,
activity, activity,
selectedColorIndex,
lookaheadSeconds = this.config.rhythm.lookaheadSeconds, lookaheadSeconds = this.config.rhythm.lookaheadSeconds,
}: RenderLookaheadRequest): void { }: RenderLookaheadRequest): void {
this.prime(now); this.prime(now);
@ -250,7 +188,7 @@ export class GenerativePianoEngine {
return; return;
} }
const profile = getVibeProfile(this.config, vibe); const profile = getVibeProfile(vibe);
const lookaheadEnd = now + lookaheadSeconds; const lookaheadEnd = now + lookaheadSeconds;
while (this.nextBeatAt <= lookaheadEnd) { while (this.nextBeatAt <= lookaheadEnd) {
this.renderBeat({ this.renderBeat({
@ -258,7 +196,6 @@ export class GenerativePianoEngine {
beatIndex: this.beatIndex, beatIndex: this.beatIndex,
startTime: this.nextBeatAt, startTime: this.nextBeatAt,
expression: this.getExpression(activity), expression: this.getExpression(activity),
selectedColorIndex,
}); });
this.nextBeatAt += this.getBeatDurationSeconds(); this.nextBeatAt += this.getBeatDurationSeconds();
this.beatIndex += 1; this.beatIndex += 1;
@ -268,12 +205,11 @@ export class GenerativePianoEngine {
now, now,
lookaheadEnd, lookaheadEnd,
activity, activity,
selectedColorIndex,
}); });
} }
public playVibeChangeStinger(vibe: VibePreset, now: number): void { public playVibeChangeStinger(vibe: VibePreset, now: number): void {
const profile = getVibeProfile(this.config, vibe); const profile = getVibeProfile(vibe);
const chord = this.getChord(profile, 0); const chord = this.getChord(profile, 0);
const intervals = getChordIntervals(chord, true); const intervals = getChordIntervals(chord, true);
const rootMidi = profile.rootMidi + chord.rootOffset; const rootMidi = profile.rootMidi + chord.rootOffset;
@ -324,9 +260,9 @@ export class GenerativePianoEngine {
this.isWaitingForGestureAccent = false; this.isWaitingForGestureAccent = false;
this.lastGestureAccentAt = Number.NEGATIVE_INFINITY; this.lastGestureAccentAt = Number.NEGATIVE_INFINITY;
this.lastStrokeAccentAt = Number.NEGATIVE_INFINITY; this.lastStrokeAccentAt = Number.NEGATIVE_INFINITY;
this.lastMidiByColor[0] = null; this.lastMidiByStyle[0] = null;
this.lastMidiByColor[1] = null; this.lastMidiByStyle[1] = null;
this.lastMidiByColor[2] = null; this.lastMidiByStyle[2] = null;
this.brushPhraseLayers = []; this.brushPhraseLayers = [];
this.nextBrushStreamAt = null; this.nextBrushStreamAt = null;
this.brushStreamNoteIndex = 0; this.brushStreamNoteIndex = 0;
@ -338,31 +274,30 @@ export class GenerativePianoEngine {
beatIndex, beatIndex,
startTime, startTime,
expression, expression,
selectedColorIndex,
}: { }: {
profile: GardenAudioVibeProfile; profile: GardenAudioVibeProfile;
beatIndex: number; beatIndex: number;
startTime: number; startTime: number;
expression: number; expression: number;
selectedColorIndex: GardenAudioColorIndex;
}): void { }): void {
const beatsPerBar = this.getBeatsPerBar(); const beatsPerBar = this.getBeatsPerBar();
const beatInBar = beatIndex % beatsPerBar; const beatInBar = beatIndex % beatsPerBar;
const barIndex = Math.floor(beatIndex / beatsPerBar); const barIndex = Math.floor(beatIndex / beatsPerBar);
const styleIndex = this.getStyleIndex(startTime);
if (beatInBar === 0 && barIndex % this.generation.chordBars === 0) { if (beatInBar === 0 && barIndex % this.generation.chordBars === 0) {
this.playPadChord(profile, barIndex, startTime, expression); this.playPadChord(profile, barIndex, startTime, expression);
} }
if (beatInBar === 0 && this.shouldPlaySupport(expression, barIndex)) { if (beatInBar === 0 && this.shouldPlaySupport(expression, barIndex)) {
this.playSupportNote(profile, barIndex, startTime, expression, selectedColorIndex); this.playSupportNote(profile, barIndex, startTime, expression, styleIndex);
} }
if ( if (
beatInBar === this.generation.textureBeat && beatInBar === this.generation.textureBeat &&
this.shouldPlayTexture(expression, barIndex) this.shouldPlayTexture(expression, barIndex)
) { ) {
this.playTextureNote(profile, barIndex, startTime, expression, selectedColorIndex); this.playTextureNote(profile, barIndex, startTime, expression, styleIndex);
} }
if ( if (
@ -374,7 +309,7 @@ export class GenerativePianoEngine {
barIndex + 1, barIndex + 1,
startTime, startTime,
expression * 0.9, expression * 0.9,
selectedColorIndex styleIndex
); );
} }
} }
@ -429,31 +364,31 @@ export class GenerativePianoEngine {
barIndex: number, barIndex: number,
startTime: number, startTime: number,
expression: number, expression: number,
selectedColorIndex: GardenAudioColorIndex styleIndex: GardenAudioStyleIndex
): void { ): void {
const pool = this.generation.colorPools[selectedColorIndex]; const pool = this.generation.stylePools[styleIndex];
const chord = this.getChord(profile, barIndex); const chord = this.getChord(profile, barIndex);
const chordIntervals = getChordIntervals(chord, false); const chordIntervals = getChordIntervals(chord, false);
const rootMidi = profile.rootMidi + chord.rootOffset; const rootMidi = profile.rootMidi + chord.rootOffset;
const midi = this.chooseMidi( const midi = this.chooseMidi(
{ {
baseMidi: rootMidi, baseMidi: rootMidi,
offsets: this.getSupportOffsets(chordIntervals, selectedColorIndex), offsets: this.getSupportOffsets(chordIntervals, styleIndex),
}, },
pool, pool,
this.lastMidiByColor[selectedColorIndex], this.lastMidiByStyle[styleIndex],
true true
); );
this.lastMidiByColor[selectedColorIndex] = midi; this.lastMidiByStyle[styleIndex] = midi;
this.playNote({ this.playNote({
midi, midi,
velocity: velocity:
(0.105 + expression * 0.07) * (0.105 + expression * 0.07) *
this.config.colorVoices[selectedColorIndex].velocityMultiplier, this.config.styleVoices[styleIndex].velocityMultiplier,
startTime, startTime,
durationSeconds: 1.35 + expression * 0.4, durationSeconds: 1.35 + expression * 0.4,
pan: this.getColorPan(selectedColorIndex), pan: this.getStylePan(styleIndex),
delaySend: 0.016 + expression * 0.006, delaySend: 0.016 + expression * 0.006,
lowpassHz: this.getLowpassHz(profile, midi, expression * 0.7), lowpassHz: this.getLowpassHz(profile, midi, expression * 0.7),
}); });
@ -464,29 +399,29 @@ export class GenerativePianoEngine {
barIndex: number, barIndex: number,
startTime: number, startTime: number,
expression: number, expression: number,
selectedColorIndex: GardenAudioColorIndex styleIndex: GardenAudioStyleIndex
): void { ): void {
const pool = this.generation.colorPools[selectedColorIndex]; const pool = this.generation.stylePools[styleIndex];
const degrees = this.rotate(pool.scaleDegrees, barIndex + selectedColorIndex); const degrees = this.rotate(pool.scaleDegrees, barIndex + styleIndex);
const midi = this.chooseMidi( const midi = this.chooseMidi(
{ {
baseMidi: profile.rootMidi, baseMidi: profile.rootMidi,
offsets: degrees.map((degree) => degreeToSemitone(profile, degree)), offsets: degrees.map((degree) => degreeToSemitone(profile, degree)),
}, },
pool, pool,
this.lastMidiByColor[selectedColorIndex], this.lastMidiByStyle[styleIndex],
true true
); );
this.lastMidiByColor[selectedColorIndex] = midi; this.lastMidiByStyle[styleIndex] = midi;
this.playNote({ this.playNote({
midi, midi,
velocity: velocity:
(0.09 + expression * 0.08) * (0.09 + expression * 0.08) *
this.config.colorVoices[selectedColorIndex].velocityMultiplier, this.config.styleVoices[styleIndex].velocityMultiplier,
startTime, startTime,
durationSeconds: 0.62 + expression * 0.24, durationSeconds: 0.62 + expression * 0.24,
pan: this.getColorPan(selectedColorIndex), pan: this.getStylePan(styleIndex),
delaySend: 0.016 + expression * 0.006, delaySend: 0.016 + expression * 0.006,
lowpassHz: this.getLowpassHz(profile, midi, expression), lowpassHz: this.getLowpassHz(profile, midi, expression),
}); });
@ -495,95 +430,74 @@ export class GenerativePianoEngine {
private playGestureAccent( private playGestureAccent(
vibe: VibePreset, vibe: VibePreset,
now: number, now: number,
selectedColorIndex: GardenAudioColorIndex, styleIndex: GardenAudioStyleIndex,
strength: number, strength: number
noteCount: number
): void { ): void {
const profile = getVibeProfile(this.config, vibe); const profile = getVibeProfile(vibe);
const pool = this.generation.colorPools[selectedColorIndex]; const pool = this.generation.stylePools[styleIndex];
const degrees = this.rotate(pool.scaleDegrees, Math.round(strength * 3)); const degrees = this.rotate(pool.scaleDegrees, Math.round(strength * 3));
for (let index = 0; index < noteCount; index += 1) { const midi = this.chooseMidi(
const midi = this.chooseMidi( {
{ baseMidi: profile.rootMidi,
baseMidi: profile.rootMidi, offsets: degrees.map((degree) => degreeToSemitone(profile, degree)),
offsets: degrees },
.slice(index) pool,
.concat(degrees.slice(0, index)) this.lastMidiByStyle[styleIndex],
.map((degree) => degreeToSemitone(profile, degree)), true
}, );
pool,
this.lastMidiByColor[selectedColorIndex],
true
);
this.lastMidiByColor[selectedColorIndex] = midi; this.lastMidiByStyle[styleIndex] = midi;
this.playNote({ this.playNote({
midi, midi,
velocity: velocity:
(0.12 + strength * 0.09) * (0.12 + strength * 0.09) * this.config.styleVoices[styleIndex].velocityMultiplier,
this.config.colorVoices[selectedColorIndex].velocityMultiplier, startTime: now + this.config.startDelaySeconds,
startTime: durationSeconds: 0.48 + strength * 0.22,
now + pan: this.getStylePan(styleIndex),
this.config.startDelaySeconds + delaySend: 0.012,
index * this.generation.gestureAccentSpacingSeconds, lowpassHz: this.getLowpassHz(profile, midi, strength),
durationSeconds: 0.48 + strength * 0.22, });
pan: this.getColorPan(selectedColorIndex),
delaySend: 0.012,
lowpassHz: this.getLowpassHz(profile, midi, strength),
});
}
} }
private playTouchNote({ private playTouchNote({
vibe, vibe,
now, now,
selectedColorIndex, styleIndex,
strength, strength,
panBias,
registerBias,
brightnessBias,
}: { }: {
vibe: VibePreset; vibe: VibePreset;
now: number; now: number;
selectedColorIndex: GardenAudioColorIndex; styleIndex: GardenAudioStyleIndex;
strength: number; strength: number;
panBias: number;
registerBias: number;
brightnessBias: number;
}): void { }): void {
const profile = getVibeProfile(this.config, vibe); const profile = getVibeProfile(vibe);
const pool = this.generation.colorPools[selectedColorIndex]; const pool = this.generation.stylePools[styleIndex];
const register = this.getBiasedRegister(pool, registerBias, 0); const register = this.getBiasedRegister(pool, 0);
const chord = this.getChord(profile, this.getGlobalBarIndex(now)); const chord = this.getChord(profile, this.getGlobalBarIndex(now));
const chordIntervals = getChordIntervals(chord, false); const chordIntervals = getChordIntervals(chord, false);
const rootMidi = profile.rootMidi + chord.rootOffset; const rootMidi = profile.rootMidi + chord.rootOffset;
const midi = this.chooseMidi( const midi = this.chooseMidi(
{ {
baseMidi: rootMidi, baseMidi: rootMidi,
offsets: this.getSupportOffsets(chordIntervals, selectedColorIndex), offsets: this.getSupportOffsets(chordIntervals, styleIndex),
}, },
register, register,
this.lastMidiByColor[selectedColorIndex], this.lastMidiByStyle[styleIndex],
true true
); );
this.lastMidiByColor[selectedColorIndex] = midi; this.lastMidiByStyle[styleIndex] = midi;
this.lastBrushStreamMidi = midi; this.lastBrushStreamMidi = midi;
this.playNote({ this.playNote({
midi, midi,
velocity: velocity:
(0.14 + strength * 0.11) * (0.14 + strength * 0.11) * this.config.styleVoices[styleIndex].velocityMultiplier,
this.config.colorVoices[selectedColorIndex].velocityMultiplier,
startTime: now, startTime: now,
durationSeconds: 0.55 + strength * 0.18, durationSeconds: 0.55 + strength * 0.18,
pan: this.getLayerPan(selectedColorIndex, panBias, 0, 0), pan: this.getStylePan(styleIndex),
delaySend: 0.006, delaySend: 0.006,
lowpassHz: this.getLowpassHz( lowpassHz: this.getLowpassHz(profile, midi, clamp01(0.55 + strength * 0.35)),
profile,
midi,
clamp01(0.45 + strength * 0.35 + brightnessBias * 0.2)
),
}); });
} }
@ -591,52 +505,26 @@ export class GenerativePianoEngine {
vibe, vibe,
now, now,
strength, strength,
selectedColorIndex, styleIndex,
mirrorAmount,
panBias,
registerBias,
brightnessBias,
contour,
pressureAmount,
pressureDelta,
maniaAmount, maniaAmount,
}: { }: {
vibe: VibePreset; vibe: VibePreset;
now: number; now: number;
strength: number; strength: number;
selectedColorIndex: GardenAudioColorIndex; styleIndex: GardenAudioStyleIndex;
mirrorAmount: number;
panBias: number;
registerBias: number;
brightnessBias: number;
contour: number;
pressureAmount: number;
pressureDelta: number;
maniaAmount: number; maniaAmount: number;
}): void { }): void {
const lifetimeSeconds = const lifetimeSeconds =
this.generation.brushLayerBaseSeconds + this.generation.brushLayerBaseSeconds +
strength * this.generation.brushLayerEnergySeconds + strength * this.generation.brushLayerEnergySeconds;
mirrorAmount * this.generation.brushLayerMirrorSeconds;
this.brushPhraseLayers.push({ this.brushPhraseLayers.push({
vibe, vibe,
startedAt: now, startedAt: now,
expiresAt: now + lifetimeSeconds, expiresAt: now + lifetimeSeconds,
selectedColorIndex, styleIndex,
energy: strength, energy: strength,
mirrorAmount, motifOffsets: [styleIndex - 1],
motifOffsets: this.getInitialMotifOffsets({
selectedColorIndex,
registerBias,
contour,
}),
panBias,
registerBias,
brightnessBias,
contour,
pressureAmount,
pressureDelta,
maniaAmount, maniaAmount,
}); });
@ -650,26 +538,12 @@ export class GenerativePianoEngine {
private updateBrushPhraseLayer({ private updateBrushPhraseLayer({
now, now,
strength, strength,
selectedColorIndex, styleIndex,
mirrorAmount,
panBias,
registerBias,
brightnessBias,
contour,
pressureAmount,
pressureDelta,
maniaAmount, maniaAmount,
}: { }: {
now: number; now: number;
strength: number; strength: number;
selectedColorIndex: GardenAudioColorIndex; styleIndex: GardenAudioStyleIndex;
mirrorAmount: number;
panBias: number;
registerBias: number;
brightnessBias: number;
contour: number;
pressureAmount: number;
pressureDelta: number;
maniaAmount: number; maniaAmount: number;
}): void { }): void {
const layer = this.brushPhraseLayers[this.brushPhraseLayers.length - 1]; const layer = this.brushPhraseLayers[this.brushPhraseLayers.length - 1];
@ -677,20 +551,10 @@ export class GenerativePianoEngine {
return; return;
} }
const followAmount = 0.24 + clamp01(strength) * 0.24; layer.styleIndex = styleIndex;
layer.selectedColorIndex = selectedColorIndex;
layer.energy = Math.max(layer.energy * 0.94, strength); layer.energy = Math.max(layer.energy * 0.94, strength);
layer.mirrorAmount = Math.max(layer.mirrorAmount * 0.96, mirrorAmount);
layer.panBias = mix(layer.panBias, panBias, followAmount);
layer.registerBias = mix(layer.registerBias, registerBias, followAmount);
layer.brightnessBias = mix(layer.brightnessBias, brightnessBias, followAmount);
layer.contour = mix(layer.contour, contour, followAmount);
layer.pressureAmount = mix(layer.pressureAmount, pressureAmount, followAmount);
layer.pressureDelta = pressureDelta;
layer.maniaAmount = Math.max(layer.maniaAmount * 0.92, maniaAmount); layer.maniaAmount = Math.max(layer.maniaAmount * 0.92, maniaAmount);
layer.motifOffsets.push( layer.motifOffsets.push(this.getMotifOffset(strength));
this.getMotifOffset({ registerBias, contour, pressureDelta, strength })
);
if (layer.motifOffsets.length > this.generation.brushMotifMaxSteps) { if (layer.motifOffsets.length > this.generation.brushMotifMaxSteps) {
layer.motifOffsets = layer.motifOffsets.slice(-this.generation.brushMotifMaxSteps); layer.motifOffsets = layer.motifOffsets.slice(-this.generation.brushMotifMaxSteps);
} }
@ -701,13 +565,11 @@ export class GenerativePianoEngine {
now, now,
lookaheadEnd, lookaheadEnd,
activity, activity,
selectedColorIndex,
}: { }: {
vibe: VibePreset; vibe: VibePreset;
now: number; now: number;
lookaheadEnd: number; lookaheadEnd: number;
activity: number; activity: number;
selectedColorIndex: GardenAudioColorIndex;
}): void { }): void {
const earliestStart = now + this.config.piano.scheduleAheadSeconds; const earliestStart = now + this.config.piano.scheduleAheadSeconds;
this.nextBrushStreamAt ??= now + this.config.startDelaySeconds; this.nextBrushStreamAt ??= now + this.config.startDelaySeconds;
@ -729,7 +591,7 @@ export class GenerativePianoEngine {
vibe, vibe,
startTime: this.nextBrushStreamAt, startTime: this.nextBrushStreamAt,
intensity: frame.intensity, intensity: frame.intensity,
selectedColorIndex: frame.selectedColorIndex ?? selectedColorIndex, styleIndex: this.getStyleIndex(this.nextBrushStreamAt),
layer: frame.layer, layer: frame.layer,
}); });
} }
@ -742,23 +604,19 @@ export class GenerativePianoEngine {
vibe, vibe,
startTime, startTime,
intensity, intensity,
selectedColorIndex, styleIndex,
layer, layer,
}: { }: {
vibe: VibePreset; vibe: VibePreset;
startTime: number; startTime: number;
intensity: number; intensity: number;
selectedColorIndex: GardenAudioColorIndex; styleIndex: GardenAudioStyleIndex;
layer: BrushPhraseLayer | null; layer: BrushPhraseLayer | null;
}): void { }): void {
const profile = getVibeProfile(this.config, vibe); const profile = getVibeProfile(vibe);
const pool = this.generation.colorPools[selectedColorIndex]; const pool = this.generation.stylePools[styleIndex];
const maniaAmount = layer?.maniaAmount ?? clamp01((intensity - 0.82) / 0.18); const maniaAmount = layer?.maniaAmount ?? clamp01((intensity - 0.82) / 0.18);
const register = this.getBiasedRegister( const register = this.getBiasedRegister(pool, maniaAmount * 0.45);
pool,
layer?.registerBias ?? 0,
maniaAmount * 0.45
);
const chord = this.getChord(profile, this.getGlobalBarIndex(startTime)); const chord = this.getChord(profile, this.getGlobalBarIndex(startTime));
const chordIntervals = getChordIntervals(chord, false); const chordIntervals = getChordIntervals(chord, false);
const rootMidi = profile.rootMidi + chord.rootOffset; const rootMidi = profile.rootMidi + chord.rootOffset;
@ -766,44 +624,35 @@ export class GenerativePianoEngine {
const source = useChordTone const source = useChordTone
? { ? {
baseMidi: rootMidi, baseMidi: rootMidi,
offsets: this.getSupportOffsets(chordIntervals, selectedColorIndex), offsets: this.getSupportOffsets(chordIntervals, styleIndex),
} }
: { : {
baseMidi: profile.rootMidi, baseMidi: profile.rootMidi,
offsets: this.getBrushMotifDegrees({ offsets: this.getBrushMotifDegrees({
layer, layer,
pool, pool,
selectedColorIndex, styleIndex,
}).map((degree) => degreeToSemitone(profile, degree)), }).map((degree) => degreeToSemitone(profile, degree)),
}; };
const midi = this.chooseMidi(source, register, this.lastBrushStreamMidi, true); const midi = this.chooseMidi(source, register, this.lastBrushStreamMidi, true);
const pan = this.getLayerPan( const pan = this.getStylePan(styleIndex);
selectedColorIndex,
layer?.panBias ?? 0,
maniaAmount,
layer?.mirrorAmount ?? 0
);
const durationSeconds = clamp( const durationSeconds = clamp(
0.48 + intensity * 0.08 - maniaAmount * 0.34, 0.48 + intensity * 0.08 - maniaAmount * 0.34,
0.14, 0.14,
0.62 0.62
); );
const delaySend = clamp( const delaySend = clamp(
0.012 + 0.012 + intensity * 0.011 - maniaAmount * 0.006,
intensity * 0.011 +
(layer?.mirrorAmount ?? 0) * 0.004 -
maniaAmount * 0.006,
0.006, 0.006,
0.032 0.032
); );
this.lastBrushStreamMidi = midi; this.lastBrushStreamMidi = midi;
this.lastMidiByColor[selectedColorIndex] = midi; this.lastMidiByStyle[styleIndex] = midi;
this.playNote({ this.playNote({
midi, midi,
velocity: velocity:
(0.1 + intensity * 0.13) * (0.1 + intensity * 0.13) * this.config.styleVoices[styleIndex].velocityMultiplier,
this.config.colorVoices[selectedColorIndex].velocityMultiplier,
startTime, startTime,
durationSeconds, durationSeconds,
pan, pan,
@ -811,12 +660,7 @@ export class GenerativePianoEngine {
lowpassHz: this.getLowpassHz( lowpassHz: this.getLowpassHz(
profile, profile,
midi, midi,
clamp01( clamp01(0.39 + intensity * 0.48 + maniaAmount * 0.18)
0.32 +
intensity * 0.48 +
(layer?.brightnessBias ?? 0.5) * 0.14 +
maniaAmount * 0.18
)
), ),
}); });
@ -829,11 +673,8 @@ export class GenerativePianoEngine {
midi: echoMidi, midi: echoMidi,
velocity: velocity:
(0.045 + intensity * 0.05) * (0.045 + intensity * 0.05) *
this.config.colorVoices[selectedColorIndex].velocityMultiplier, this.config.styleVoices[styleIndex].velocityMultiplier,
startTime: startTime: startTime + this.generation.brushMotifCanonDelaySeconds,
startTime +
this.generation.brushMotifCanonDelaySeconds +
(layer?.mirrorAmount ?? 0) * 0.04,
durationSeconds: Math.max(0.11, durationSeconds * 0.68), durationSeconds: Math.max(0.11, durationSeconds * 0.68),
pan: clamp(-pan * 0.75, -1, 1), pan: clamp(-pan * 0.75, -1, 1),
delaySend: Math.max(0.006, delaySend * 0.72), delaySend: Math.max(0.006, delaySend * 0.72),
@ -847,7 +688,6 @@ export class GenerativePianoEngine {
activity: number activity: number
): { ): {
intensity: number; intensity: number;
selectedColorIndex: GardenAudioColorIndex | null;
layer: BrushPhraseLayer | null; layer: BrushPhraseLayer | null;
} { } {
const layerStates = this.brushPhraseLayers.map((layer) => ({ const layerStates = this.brushPhraseLayers.map((layer) => ({
@ -855,7 +695,7 @@ export class GenerativePianoEngine {
intensity: intensity:
layer.energy * layer.energy *
this.getBrushPhraseFade(layer, startTime) * this.getBrushPhraseFade(layer, startTime) *
(0.8 + layer.mirrorAmount * 0.45 + layer.maniaAmount * 0.42), (0.8 + layer.maniaAmount * 0.42),
})); }));
const dominant = layerStates.reduce<{ const dominant = layerStates.reduce<{
layer: BrushPhraseLayer; layer: BrushPhraseLayer;
@ -875,7 +715,6 @@ export class GenerativePianoEngine {
intensity: clamp01( intensity: clamp01(
activity * 0.42 + layeredIntensity + (dominant?.layer.maniaAmount ?? 0) * 0.18 activity * 0.42 + layeredIntensity + (dominant?.layer.maniaAmount ?? 0) * 0.18
), ),
selectedColorIndex: dominant?.layer.selectedColorIndex ?? null,
layer: dominant?.layer ?? null, layer: dominant?.layer ?? null,
}; };
} }
@ -898,98 +737,28 @@ export class GenerativePianoEngine {
return clamp01(1 - ageSeconds / Math.max(0.001, lifetimeSeconds)); return clamp01(1 - ageSeconds / Math.max(0.001, lifetimeSeconds));
} }
private normalizeMotif({ private getMotifOffset(strength: number): number {
panBias,
registerBias,
brightnessBias,
contour,
pressureAmount,
pressureDelta,
maniaAmount,
}: {
panBias: number;
registerBias: number;
brightnessBias: number;
contour: number;
pressureAmount: number;
pressureDelta: number;
maniaAmount: number;
}): {
panBias: number;
registerBias: number;
brightnessBias: number;
contour: number;
pressureAmount: number;
pressureDelta: number;
maniaAmount: number;
} {
return {
panBias: clamp(panBias, -1, 1),
registerBias: clamp(registerBias, -1, 1),
brightnessBias: clamp01(brightnessBias),
contour: clamp(contour, -1, 1),
pressureAmount: clamp01(pressureAmount),
pressureDelta: clamp(pressureDelta, -1, 1),
maniaAmount: clamp01(maniaAmount),
};
}
private getInitialMotifOffsets({
selectedColorIndex,
registerBias,
contour,
}: {
selectedColorIndex: GardenAudioColorIndex;
registerBias: number;
contour: number;
}): Array<number> {
const start = selectedColorIndex - 1 + Math.round(registerBias);
const motion = contour > 0.2 ? 1 : contour < -0.2 ? -1 : 0;
return [start, start + motion, start + motion * 2, start + motion];
}
private getMotifOffset({
registerBias,
contour,
pressureDelta,
strength,
}: {
registerBias: number;
contour: number;
pressureDelta: number;
strength: number;
}): number {
const contourStep = contour > 0.3 ? 1 : contour < -0.3 ? -1 : 0;
const registerStep = Math.round(registerBias * 2);
const pressureStep = pressureDelta > 0.08 ? 1 : pressureDelta < -0.08 ? -1 : 0;
const energyStep = strength >= 0.82 ? 1 : strength >= 0.55 ? 0 : -1; const energyStep = strength >= 0.82 ? 1 : strength >= 0.55 ? 0 : -1;
return clamp(contourStep + registerStep + pressureStep + energyStep, -3, 4); return clamp(energyStep, -3, 4);
} }
private getBrushMotifDegrees({ private getBrushMotifDegrees({
layer, layer,
pool, pool,
selectedColorIndex, styleIndex,
}: { }: {
layer: BrushPhraseLayer | null; layer: BrushPhraseLayer | null;
pool: GardenAudioColorPool; pool: GardenAudioStylePool;
selectedColorIndex: GardenAudioColorIndex; styleIndex: GardenAudioStyleIndex;
}): Array<number> { }): Array<number> {
const colorOffset = this.config.colorVoices[selectedColorIndex].scaleDegreeOffset; const styleOffset = this.config.styleVoices[styleIndex].scaleDegreeOffset;
if (!layer || layer.motifOffsets.length === 0) { if (!layer || layer.motifOffsets.length === 0) {
return this.rotate(pool.scaleDegrees, this.brushStreamNoteIndex + colorOffset); return this.rotate(pool.scaleDegrees, this.brushStreamNoteIndex + styleOffset);
} }
const motifOffset = const motifOffset =
layer.motifOffsets[this.brushStreamNoteIndex % layer.motifOffsets.length]; layer.motifOffsets[this.brushStreamNoteIndex % layer.motifOffsets.length];
const contourOffset = const baseOffset = styleOffset + motifOffset;
layer.contour > 0.28
? this.brushStreamNoteIndex % 3
: layer.contour < -0.28
? -(this.brushStreamNoteIndex % 3)
: 0;
const pressureLift = layer.pressureAmount > 0.68 ? 1 : 0;
const baseOffset = colorOffset + motifOffset + contourOffset + pressureLift;
return this.rotate( return this.rotate(
pool.scaleDegrees.map((degree) => degree + baseOffset), pool.scaleDegrees.map((degree) => degree + baseOffset),
@ -999,10 +768,9 @@ export class GenerativePianoEngine {
private getBiasedRegister( private getBiasedRegister(
register: GardenAudioRegister, register: GardenAudioRegister,
registerBias: number,
maniaAmount: number maniaAmount: number
): GardenAudioRegister { ): GardenAudioRegister {
const shift = Math.round(registerBias * 7 + maniaAmount * 4); const shift = Math.round(maniaAmount * 4);
const midiMin = clamp(register.midiMin + shift, 36, 86); const midiMin = clamp(register.midiMin + shift, 36, 86);
const midiMax = clamp(register.midiMax + shift, midiMin + 4, 91); const midiMax = clamp(register.midiMax + shift, midiMin + 4, 91);
@ -1014,26 +782,6 @@ export class GenerativePianoEngine {
}; };
} }
private getLayerPan(
selectedColorIndex: GardenAudioColorIndex,
panBias: number,
maniaAmount: number,
mirrorAmount: number
): number {
const shimmer =
maniaAmount > 0.4
? Math.sin(this.brushStreamNoteIndex * Math.PI * 0.5) * mirrorAmount * 0.14
: 0;
return clamp(
this.getColorPan(selectedColorIndex) +
panBias * (0.18 + maniaAmount * 0.42) +
shimmer,
-1,
1
);
}
private chooseMidi( private chooseMidi(
pitchSource: PitchSource, pitchSource: PitchSource,
register: GardenAudioRegister, register: GardenAudioRegister,
@ -1113,13 +861,13 @@ export class GenerativePianoEngine {
private getSupportOffsets( private getSupportOffsets(
chordIntervals: ReadonlyArray<number>, chordIntervals: ReadonlyArray<number>,
selectedColorIndex: GardenAudioColorIndex styleIndex: GardenAudioStyleIndex
): Array<number> { ): Array<number> {
if (selectedColorIndex === 0) { if (styleIndex === 0) {
return [0, chordIntervals[2], 12]; return [0, chordIntervals[2], 12];
} }
if (selectedColorIndex === 1) { if (styleIndex === 1) {
return [chordIntervals[1], chordIntervals[2], 0, 12]; return [chordIntervals[1], chordIntervals[2], 0, 12];
} }
@ -1138,10 +886,19 @@ export class GenerativePianoEngine {
return Math.floor(elapsedSeconds / this.getBarDurationSeconds()); return Math.floor(elapsedSeconds / this.getBarDurationSeconds());
} }
private getColorPan(selectedColorIndex: GardenAudioColorIndex): number { private getStyleIndex(startTime: number): GardenAudioStyleIndex {
const pool = this.generation.colorPools[selectedColorIndex]; const timelineStartedAt = this.timelineStartedAt ?? startTime;
const colorVoice = this.config.colorVoices[selectedColorIndex]; const elapsedSeconds = Math.max(0, startTime - timelineStartedAt);
return clamp(pool.pan + colorVoice.panOffset * 0.35, -1, 1); const styleCount = this.generation.stylePools.length;
const rotationSeconds = Math.max(0.001, this.generation.styleRotationSeconds);
return (Math.floor(elapsedSeconds / rotationSeconds) %
styleCount) as GardenAudioStyleIndex;
}
private getStylePan(styleIndex: GardenAudioStyleIndex): number {
const pool = this.generation.stylePools[styleIndex];
const styleVoice = this.config.styleVoices[styleIndex];
return clamp(pool.pan + styleVoice.panOffset * 0.35, -1, 1);
} }
private getLowpassHz( private getLowpassHz(
@ -1199,6 +956,3 @@ export class GenerativePianoEngine {
return values.map((_, index) => values[(index + offset) % values.length]); return values.map((_, index) => values[(index + offset) % values.length]);
} }
} }
const mix = (from: number, to: number, amount: number): number =>
from + (to - from) * clamp01(amount);

View file

@ -2,12 +2,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { gardenAudioConfig } from './garden-audio-config'; import { gardenAudioConfig } from './garden-audio-config';
import type { GardenAudioGraph } from './garden-audio-graph'; import type { GardenAudioGraph } from './garden-audio-graph';
import { PianoSampler } from './piano-sampler'; import type { PianoSampler } from './piano-sampler';
import { pianoSampleDefinitions, resetPianoSampleCacheForTest } from './piano-samples';
const calls = { const calls = {
bufferSourcesStarted: 0, bufferSourcesStarted: 0,
}; };
const sampleCount = 30;
class FakeAudioParam { class FakeAudioParam {
public value = 0; public value = 0;
@ -61,7 +61,8 @@ class FakeAudioContext {
} }
} }
const makeSampler = (context: AudioContext): PianoSampler => { const makeSampler = async (context: AudioContext): Promise<PianoSampler> => {
const { PianoSampler } = await import('./piano-sampler');
const eventBus = new FakeAudioNode() as unknown as GainNode; const eventBus = new FakeAudioNode() as unknown as GainNode;
const graph = { const graph = {
context, context,
@ -75,17 +76,16 @@ const makeSampler = (context: AudioContext): PianoSampler => {
describe('PianoSampler', () => { describe('PianoSampler', () => {
beforeEach(() => { beforeEach(() => {
calls.bufferSourcesStarted = 0; calls.bufferSourcesStarted = 0;
resetPianoSampleCacheForTest(); vi.resetModules();
}); });
afterEach(() => { afterEach(() => {
vi.unstubAllGlobals(); vi.unstubAllGlobals();
resetPianoSampleCacheForTest();
}); });
it('loads every piano sample before playback', async () => { it('loads every piano sample before playback', async () => {
const context = new FakeAudioContext() as unknown as AudioContext; const context = new FakeAudioContext() as unknown as AudioContext;
const sampler = makeSampler(context); const sampler = await makeSampler(context);
const fetch = vi.fn(async () => { const fetch = vi.fn(async () => {
return { return {
arrayBuffer: async () => new ArrayBuffer(8), arrayBuffer: async () => new ArrayBuffer(8),
@ -103,23 +103,23 @@ describe('PianoSampler', () => {
velocity: 0.5, velocity: 0.5,
}); });
expect(fetch).toHaveBeenCalledTimes(pianoSampleDefinitions.length); expect(fetch).toHaveBeenCalledTimes(sampleCount);
expect(context.decodeAudioData).toHaveBeenCalledTimes(pianoSampleDefinitions.length); expect(context.decodeAudioData).toHaveBeenCalledTimes(sampleCount);
expect(calls.bufferSourcesStarted).toBe(1); expect(calls.bufferSourcesStarted).toBe(1);
}); });
it('stays silent when no decoded sample is available', () => { it('stays silent when no decoded sample is available', () => {
const context = new FakeAudioContext() as unknown as AudioContext; const context = new FakeAudioContext() as unknown as AudioContext;
const sampler = makeSampler(context); return makeSampler(context).then((sampler) => {
sampler.play({
durationSeconds: 0.2,
midi: 60,
pan: 0,
startTime: context.currentTime,
velocity: 0.5,
});
sampler.play({ expect(calls.bufferSourcesStarted).toBe(0);
durationSeconds: 0.2,
midi: 60,
pan: 0,
startTime: context.currentTime,
velocity: 0.5,
}); });
expect(calls.bufferSourcesStarted).toBe(0);
}); });
}); });

View file

@ -124,7 +124,7 @@ export class PianoSampler {
source.start(scheduledStart); source.start(scheduledStart);
source.stop(stopAt + this.config.piano.tailStopExtraSeconds); source.stop(stopAt + this.config.piano.tailStopExtraSeconds);
this.activeVoices.push({ gain, source, startAt: scheduledStart, stopAt }); this.activeVoices.push({ gain, source, stopAt });
source.addEventListener( source.addEventListener(
'ended', 'ended',

View file

@ -1,6 +1,6 @@
import type { LoadedPianoSample } from './garden-audio-types'; import type { LoadedPianoSample } from './garden-audio-types';
export interface PianoSampleDefinition { interface PianoSampleDefinition {
midi: number; midi: number;
url: string; url: string;
} }
@ -46,7 +46,7 @@ const sampleFiles: Array<[fileName: string, midi: number]> = [
['C8v12.m4a', 108], ['C8v12.m4a', 108],
]; ];
export const pianoSampleDefinitions: Array<PianoSampleDefinition> = sampleFiles const pianoSampleDefinitions: Array<PianoSampleDefinition> = sampleFiles
.map(([fileName, midi]) => ({ .map(([fileName, midi]) => ({
midi, midi,
url: `${sampleBaseUrl}${fileName}`, url: `${sampleBaseUrl}${fileName}`,
@ -116,11 +116,6 @@ export const loadPianoSamples = (
export const getLoadedPianoSamples = (): Array<LoadedPianoSample> | null => export const getLoadedPianoSamples = (): Array<LoadedPianoSample> | null =>
loadedPianoSamples ? [...loadedPianoSamples] : null; loadedPianoSamples ? [...loadedPianoSamples] : null;
export const resetPianoSampleCacheForTest = (): void => {
loadedPianoSamples = null;
pianoSampleLoadPromise = null;
};
const loadPianoSample = async ( const loadPianoSample = async (
decodeContext: BaseAudioContext, decodeContext: BaseAudioContext,
sample: PianoSampleDefinition sample: PianoSampleDefinition

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