aa03146Maraca shake simulator: MATLAB model and interactive web appmagland 1import { useCallback, useEffect, useRef, useState } from 'react';
2import { DEFAULTS, loadParams, saveParams, type MaracaParams } from './params';
3import { DEFAULT_MFILES, type MFile } from './mfiles';
4import { useRenderer } from './hooks/useRenderer';
5import { encodeWav } from './lib/wav';
6import ParamPanel from './components/ParamPanel';
7import CodePanel from './components/CodePanel';
8import Scene3D from './components/Scene3D';
9import DiagnosticsPanel from './components/DiagnosticsPanel';
10import WaveformPlot from './components/plots/WaveformPlot';
11import SpectrumPlot from './components/plots/SpectrumPlot';
12import SpectrogramPlot from './components/plots/SpectrogramPlot';
13import ImpactRaster from './components/plots/ImpactRaster';
14import ModeMap from './components/plots/ModeMap';
16export default function App() {
17 const [params, setParams] = useState<MaracaParams>(() => loadParams());
18 // Editable copy of the MATLAB implementation. Deliberately not persisted:
19 // a reload restores the code the app shipped with.
20 const [mfiles, setMfiles] = useState<MFile[]>(() => DEFAULT_MFILES.map((f) => ({ ...f })));
21 const [codeOpen, setCodeOpen] = useState(false);
22 const { result, error, busy, stage, progress, renderFull } = useRenderer(params, mfiles);
23 const audioCtxRef = useRef<AudioContext | null>(null);
25 useEffect(() => saveParams(params), [params]);
27 const onChange = useCallback((key: keyof MaracaParams, value: number | boolean) => {
28 setParams((p) => ({ ...p, [key]: value }));
29 }, []);
31 const reset = useCallback(() => setParams({ ...DEFAULTS }), []);
33 // A new seed redraws the whole impact process without touching anything
34 // else, which is the quickest way to hear how much of the character is the
35 // particular draw and how much is the parameters.
36 const reseed = useCallback(
37 () => setParams((p) => ({ ...p, seed: 1 + Math.floor(Math.random() * 9999) })),
38 [],
39 );
41 const onChangeFile = useCallback((name: string, source: string) => {
42 setMfiles((fs) => fs.map((f) => (f.name === name ? { ...f, source } : f)));
43 }, []);
45 const onResetFile = useCallback((name: string) => {
46 setMfiles((fs) =>
47 fs.map((f) =>
48 f.name === name
49 ? { ...f, source: DEFAULT_MFILES.find((d) => d.name === name)?.source ?? f.source }
50 : f,
51 ),
52 );
53 }, []);
55 const onResetAllFiles = useCallback(() => setMfiles(DEFAULT_MFILES.map((f) => ({ ...f }))), []);
56 const codeEdited = mfiles.some(
57 (f) => f.source !== DEFAULT_MFILES.find((d) => d.name === f.name)?.source,
58 );
60 const [looping, setLooping] = useState(false);
61 const loopSrcRef = useRef<AudioBufferSourceNode | null>(null);
63 const getAudioCtx = useCallback((sampleRate: number) => {
64 let ctx = audioCtxRef.current;
65 if (!ctx || ctx.state === 'closed') {
66 ctx = new AudioContext({ sampleRate });
67 audioCtxRef.current = ctx;
68 }
69 void ctx.resume();
70 return ctx;
71 }, []);
73 const makeBuffer = useCallback((ctx: AudioContext, r: NonNullable<typeof result>) => {
74 const buf = ctx.createBuffer(1, r.y.length, r.sampleRate);
75 buf.copyToChannel(new Float32Array(r.y), 0);
76 return buf;
77 }, []);
79 const play = useCallback(() => {
80 if (!result) return;
81 const ctx = getAudioCtx(result.sampleRate);
82 const src = ctx.createBufferSource();
83 src.buffer = makeBuffer(ctx, result);
84 src.connect(ctx.destination);
85 src.start();
86 }, [result, getAudioCtx, makeBuffer]);
88 // Loop mode: repeat the shake continuously, swapping in each new render as
89 // parameters change so edits are audible without pressing Play.
90 useEffect(() => {
91 if (!looping || !result) return;
92 const ctx = getAudioCtx(result.sampleRate);
93 const src = ctx.createBufferSource();
94 src.buffer = makeBuffer(ctx, result);
95 src.loop = true;
96 src.connect(ctx.destination);
97 src.start();
98 loopSrcRef.current = src;
99 return () => {
100 loopSrcRef.current = null;
101 try {
102 src.stop();
103 } catch {
104 // already stopped
105 }
106 src.disconnect();
107 };
108 }, [looping, result, getAudioCtx, makeBuffer]);
110 const download = useCallback(() => {
111 if (!result) return;
112 const blob = encodeWav(result.y, result.sampleRate, params.bit_depth === 16 ? 16 : 24);
113 const url = URL.createObjectURL(blob);
114 const a = document.createElement('a');
115 a.href = url;
116 a.download = result.quality === 'full' ? 'maraca.wav' : 'maraca_preview.wav';
117 a.click();
118 setTimeout(() => URL.revokeObjectURL(url), 5000);
119 }, [result, params.bit_depth]);
121 return (
122 <div className="app">
123 <div className="topbar">
124 <h1>Maraca Simulator</h1>
125 <button className="primary" onClick={renderFull} disabled={busy}>
126 Render
127 </button>
128 <button
129 className={`play ${result?.quality === 'preview' ? 'preview' : ''}`}
130 onClick={play}
131 disabled={!result}
132 title={
133 result?.quality === 'preview'
134 ? 'Playing the fast preview render; press Render for full quality'
135 : 'Play the rendered shake'
136 }
137 >
138 ▶ Play{result?.quality === 'preview' ? ' (preview)' : ''}
139 </button>
140 <button
141 className={`loop ${looping ? 'active' : ''}`}
142 onClick={() => setLooping((v) => !v)}
143 disabled={!result && !looping}
144 title="Repeat the shake continuously so parameter changes are audible immediately"
145 >
146 ⟳ Loop{looping ? ' on' : ''}
147 </button>
148 <button onClick={reseed} title="Draw a new impact process from a new random seed">
149 ⚄ New seed
150 </button>
151 <button onClick={download} disabled={!result}>
152 Download .wav{result?.quality === 'preview' ? ' (preview)' : ''}
153 </button>
154 <button onClick={reset}>Reset to defaults</button>
155 <button
156 className={codeOpen ? 'code active' : 'code'}
157 onClick={() => setCodeOpen((v) => !v)}
158 title="View and edit the MATLAB source that numbl executes"
159 >
160 {'{ }'} Code{codeEdited ? ' •' : ''}
161 </button>
162 <div className="status">
163 {error && <span className="badge err">code error</span>}
164 {result && (
165 <span className={`badge ${result.quality}`}>
166 {result.quality === 'full' ? 'full quality' : 'preview quality — press Render'}
167 </span>
168 )}
169 {busy ? (
170 <>
171 <span>{stage}…</span>
172 <div className="progressbar">
173 <div style={{ width: `${Math.round(progress * 100)}%` }} />
174 </div>
175 </>
176 ) : (
177 <span>ready</span>
178 )}
179 </div>
180 </div>
181 <div className="main">
182 <div className="sidebar">
183 <ParamPanel params={params} onChange={onChange} />
184 </div>
185 <div className="content">
186 {error && (
187 <div className="card wide error-card">
188 <h2>MATLAB error</h2>
189 <div>
190 <strong>
191 {error.file ? `${error.file}${error.line ? `:${error.line}` : ''}` : 'error'}
192 </strong>{' '}
193 {error.message}
194 </div>
195 <div className="code-hint">
196 Showing the last successful render. Open Code to fix the source, or revert it.
197 </div>
198 </div>
199 )}
200 <div className="card wide">
201 <h2>Geometry — shell, grain impacts, microphone</h2>
202 <Scene3D
203 params={params}
204 impactPos={result?.impactPos ?? null}
205 impactV={result?.impactV ?? null}
206 impactT={result?.impactT ?? null}
207 />
208 </div>
209 {result && (
210 <>
211 <div className="card">
212 <h2>Diagnostics</h2>
213 <DiagnosticsPanel result={result} />
214 </div>
215 <div className="card">
216 <h2>Impact process</h2>
217 <ImpactRaster
218 impactT={result.impactT}
219 impactV={result.impactV}
220 rateT={result.rateT}
221 rateHz={result.rateHz}
222 durationS={result.diag.durationS}
223 impactCount={result.diag.impactCount}
224 plotted={result.impactT.length}
225 />
226 </div>
227 <div className="card">
228 <h2>Waveform</h2>
229 <WaveformPlot y={result.y} sampleRate={result.sampleRate} />
230 </div>
231 <div className="card">
232 <h2>Spectrum</h2>
233 <SpectrumPlot
234 y={result.y}
235 sampleRate={result.sampleRate}
236 modeF={result.modeF}
237 breathingHz={result.diag.breathingHz}
238 />
239 </div>
240 <div className="card">
241 <h2>Spectrogram</h2>
242 <SpectrogramPlot y={result.y} sampleRate={result.sampleRate} />
243 </div>
244 <div className="card">
245 <h2>Shell modes</h2>
246 <ModeMap
247 modeF={result.modeF}
248 modeL={result.modeL}
249 modeZeta={result.modeZeta}
250 modeSigma={result.modeSigma}
251 breathingHz={result.diag.breathingHz}
252 />
253 </div>
254 </>
255 )}
256 </div>
257 </div>
258 {codeOpen && (
259 <CodePanel
260 mfiles={mfiles}
261 onChangeFile={onChangeFile}
262 onResetFile={onResetFile}
263 onResetAll={onResetAllFiles}
264 onClose={() => setCodeOpen(false)}
265 onRenderFull={renderFull}
266 error={error}
267 busy={busy}
268 />
269 )}
270 </div>
271 );
272}