-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1735 lines (1515 loc) · 70.3 KB
/
Copy pathscript.js
File metadata and controls
1735 lines (1515 loc) · 70.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ---------- Application State ----------
const state = {
mode: 'fundamental', // 'fundamental', 'reflection', 'aircolumn', 'helmholtz'
params: {
amp: 1.0,
freq: 440,
speed: 340,
time: 0, // Master simulation time
// Mode specific params
reflectionBoundary: 'fixed', // 'fixed', 'free'
pipeType: 'open', // 'open', 'closed'
pipeLength: 0.5, // meters
cavityVol: 0.001, // m^3
neckArea: 0.0005, // m^2
neckLength: 0.05, // m
// Vocal Tract / Concatenated Tube params
tractSections: 4,
tractAreas: [1.0, 1.0, 1.0, 1.0], // Default cross sections cm^2
tractLength: 17.0, // Default length in cm
f0: 120, // Glottal source fundamental frequency
// Derived or selected visualization params
viewType: 'y-x', // 'transverse', 'longitudinal', 'y-x', 'y-t'
reflectionView: 'super', // 'super', 'parts'
n: 1, // harmonic number
pipeDisplay: 'pressure' // 'pressure', 'displacement'
},
audio: {
ctx: null,
oscillator: null,
gainNode: null,
scriptNode: null,
isPlaying: false,
volume: 0.5
},
animationFrameId: null,
isPaused: false,
playbackSpeed: 1.0,
vocalTract: null // will be initialized holding pPlus and pMinus
};
// ---------- DOM Elements ----------
const canvas = document.getElementById('sim-canvas');
const ctx = canvas.getContext('2d');
const navItems = document.querySelectorAll('.nav-links li');
const titleEl = document.getElementById('mode-title');
const subtitleEl = document.getElementById('mode-subtitle');
const formulaEl = document.getElementById('formula-display');
const controlsGrid = document.getElementById('controls-grid');
const sliderAmp = document.getElementById('slider-amp');
const sliderFreq = document.getElementById('slider-freq');
const sliderSpeed = document.getElementById('slider-speed');
const valAmp = document.getElementById('val-amp');
const valFreq = document.getElementById('val-freq');
const valSpeed = document.getElementById('val-speed');
const btnToggleSound = document.getElementById('btn-toggle-sound');
const soundIcon = document.getElementById('sound-icon');
const soundText = document.getElementById('sound-text');
const statusIndicator = document.querySelector('.status-indicator');
// Playback controls
const btnPlayPause = document.getElementById('btn-play-pause');
const btnStepForward = document.getElementById('btn-step-forward');
const btnStepBack = document.getElementById('btn-step-back');
const sliderSpeedMult = document.getElementById('slider-speed-mult');
const valSpeedMult = document.getElementById('val-speed-mult');
const calcGrid = document.getElementById('calc-grid');
// ---------- Initialization ----------
function init() {
resizeCanvas();
window.addEventListener('resize', resizeCanvas);
// Bind global controls
sliderAmp.addEventListener('input', (e) => updateParam('amp', parseFloat(e.target.value), valAmp));
sliderFreq.addEventListener('input', (e) => updateParam('freq', parseFloat(e.target.value), valFreq));
sliderSpeed.addEventListener('input', (e) => updateParam('speed', parseFloat(e.target.value), valSpeed));
// Bind Navigation
navItems.forEach(item => {
item.addEventListener('click', (e) => {
navItems.forEach(n => n.classList.remove('active'));
e.currentTarget.classList.add('active');
setMode(e.currentTarget.dataset.mode);
});
});
// Audio binding
btnToggleSound.addEventListener('click', toggleAudio);
// Playback controls
btnPlayPause.addEventListener('click', togglePause);
btnStepForward.addEventListener('click', () => stepFrame(1));
btnStepBack.addEventListener('click', () => stepFrame(-1));
sliderSpeedMult.addEventListener('input', (e) => {
state.playbackSpeed = parseFloat(e.target.value);
valSpeedMult.textContent = '×' + state.playbackSpeed.toFixed(state.playbackSpeed % 1 === 0 ? 1 : 2);
});
// Volume slider binding
const sliderVolume = document.getElementById('slider-volume');
const valVolume = document.getElementById('val-volume');
sliderVolume.addEventListener('input', (e) => {
const vol = parseInt(e.target.value);
state.audio.volume = vol / 100;
valVolume.innerText = vol;
if (state.audio.isPlaying && state.audio.gainNode) {
state.audio.gainNode.gain.setTargetAtTime(state.audio.volume, state.audio.ctx.currentTime, 0.05);
}
});
// Initial render setup
buildDynamicControls();
updateFormulaDisplay();
updateCalcPanel();
startSimulation();
}
function resizeCanvas() {
// Make canvas responsive to its container
const container = canvas.parentElement;
canvas.width = container.clientWidth;
canvas.height = container.clientHeight;
}
// ---------- Logic / Updates ----------
function updateParam(key, val, displayEl) {
state.params[key] = val;
if (displayEl) displayEl.innerText = val.toFixed(key === 'amp' ? 1 : 0);
// Update audio if playing
if (state.audio.isPlaying && state.audio.oscillator) {
state.audio.oscillator.frequency.setTargetAtTime(calcCurrentFrequency(), state.audio.ctx.currentTime, 0.1);
}
// Some params depend on others, update derived formulas
updateFormulaDisplay();
updateCalcPanel();
}
function calcCurrentFrequency() {
// For fundamental mode and reflection, frequency is the slider
if (state.mode === 'fundamental' || state.mode === 'reflection') {
return state.params.freq;
}
// For air columns, f = n*v/(2L) or (2n-1)v/(4L) depending on pipe type
else if (state.mode === 'aircolumn') {
const v = state.params.speed;
const L = state.params.pipeLength;
if (state.params.pipeType === 'open') {
return (state.params.n * v) / (2 * L);
} else {
const m = 2 * state.params.n - 1;
return (m * v) / (4 * L);
}
}
// For Helmholtz, f = (v/(2*pi)) * sqrt(A/(V*L))
else if (state.mode === 'helmholtz') {
const v = state.params.speed;
const A = state.params.neckArea;
const V = state.params.cavityVol;
const L_eff = state.params.neckLength; // should actually be L + 0.6r etc, simplifying for now
return (v / (2 * Math.PI)) * Math.sqrt(A / (V * L_eff));
}
// For Vocal Tract, compute first formant F1 based on tube geometry
else if (state.mode === 'vocaltract') {
return findF1();
}
return 440;
}
// --- New acoustic calculation functions ---
function getTractGain(f, areas, L_total, c) {
const k = 2 * Math.PI * f / c;
const sections = areas.length;
const l = (L_total / 100) / sections;
let p_re = 0, p_im = 0; // p_out = 0 (open lips)
let U_re = 1, U_im = 0; // U_out = 1
for (let i = sections - 1; i >= 0; i--) {
const A = areas[i];
const Z_c = 1.0 / A;
const cos_kl = Math.cos(k * l);
const sin_kl = Math.sin(k * l);
const next_p_re = p_re * cos_kl - U_im * Z_c * sin_kl;
const next_p_im = p_im * cos_kl + U_re * Z_c * sin_kl;
const next_U_re = -(p_im / Z_c) * sin_kl + U_re * cos_kl;
const next_U_im = (p_re / Z_c) * sin_kl + U_im * cos_kl;
p_re = next_p_re;
p_im = next_p_im;
U_re = next_U_re;
U_im = next_U_im;
}
const U_in_mag = Math.sqrt(U_re*U_re + U_im*U_im);
return 1.0 / (U_in_mag + 1e-10);
}
// Cache F1 to avoid calculating it on every frame unless parameters changed
let lastF1Params = "";
let cachedF1 = 500;
function findF1() {
const paramsStr = `${state.params.tractLength}_${state.params.speed}_${state.params.tractAreas.join(',')}`;
if (paramsStr === lastF1Params) return cachedF1;
let maxGain = -1;
let bestF = 500;
for (let f = 100; f <= 1500; f += 2) {
const gain = getTractGain(f, state.params.tractAreas, state.params.tractLength, state.params.speed);
if (gain > maxGain) {
maxGain = gain;
bestF = f;
}
}
lastF1Params = paramsStr;
cachedF1 = bestF;
return bestF;
}
function setMode(newMode) {
state.mode = newMode;
switch(newMode) {
case 'fundamental':
titleEl.textContent = '波の基本とグラフ';
subtitleEl.textContent = '縦波・横波の視覚化と、y-x / y-t グラフでの正弦波の理解';
break;
case 'reflection':
titleEl.textContent = '反射と定常波';
subtitleEl.textContent = '固定端反射・自由端反射による合成波(定常波)の形成';
break;
case 'aircolumn':
titleEl.textContent = '気柱 (開管・閉管)';
subtitleEl.textContent = '開管および閉管での管内の圧力波と定常波(音の共鳴)';
break;
case 'helmholtz':
titleEl.textContent = 'ヘルムホルツ共鳴腔';
subtitleEl.textContent = '体積、首の長さ・面積に基づく共鳴周波数の計算と音響モデル';
// In Helmholtz, general frequency slider isn't the driver, we calculate freq from dims.
break;
case 'vocaltract':
titleEl.textContent = '連結管モデル (声道)';
subtitleEl.textContent = '断面積の異なる管の境界における波の反射・透過による共鳴の形成';
break;
}
buildDynamicControls();
updateFormulaDisplay();
updateCalcPanel();
// If playing, immediately update audio to new formula target
if (state.audio.isPlaying) {
state.audio.oscillator.frequency.setTargetAtTime(calcCurrentFrequency(), state.audio.ctx.currentTime, 0.1);
}
}
// Builds the specific knobs depending on current mode
function buildDynamicControls() {
// Clear out any old dynamic properties
const toRemove = controlsGrid.querySelectorAll('.dynamic-ctrl');
toRemove.forEach(el => el.remove());
// Basic Frequency slider is confusing in AirColumn/Helmholtz since freq is DERIVED from length/volume.
// So we'll disable/hide standard freq slider for those modes.
const freqBlock = document.getElementById('slider-freq').parentElement;
if (state.mode === 'fundamental' || state.mode === 'reflection') {
freqBlock.style.display = 'flex';
} else {
freqBlock.style.display = 'none';
}
if (state.mode === 'fundamental') {
const html = `
<div class="control-block dynamic-ctrl" style="grid-column: span 2;">
<label>表示モード (View Mode)</label>
<div class="radio-group" id="radio-fundamental-view">
<div class="radio-btn ${state.params.viewType === 'y-x' ? 'active' : ''}" data-val="y-x">y-x グラフ</div>
<div class="radio-btn ${state.params.viewType === 'y-t' ? 'active' : ''}" data-val="y-t">y-t グラフ</div>
<div class="radio-btn ${state.params.viewType === 'transverse' ? 'active' : ''}" data-val="transverse">横波 (粒子)</div>
<div class="radio-btn ${state.params.viewType === 'longitudinal' ? 'active' : ''}" data-val="longitudinal">縦波 (粒子)</div>
</div>
</div>
`;
controlsGrid.insertAdjacentHTML('beforeend', html);
document.querySelectorAll('#radio-fundamental-view .radio-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
document.querySelectorAll('#radio-fundamental-view .radio-btn').forEach(b => b.classList.remove('active'));
e.target.classList.add('active');
state.params.viewType = e.target.dataset.val;
});
});
} else if (state.mode === 'reflection') {
const html = `
<div class="control-block dynamic-ctrl" style="grid-column: span 2;">
<label>境界条件 (Boundary Condition)</label>
<div class="radio-group" id="radio-reflection-type">
<div class="radio-btn ${state.params.reflectionBoundary === 'fixed' ? 'active' : ''}" data-val="fixed">固定端反射 (Fixed End)</div>
<div class="radio-btn ${state.params.reflectionBoundary === 'free' ? 'active' : ''}" data-val="free">自由端反射 (Free End)</div>
</div>
</div>
<div class="control-block dynamic-ctrl" style="grid-column: span 2;">
<label>波の表示 (Wave Display)</label>
<div class="radio-group" id="radio-reflection-view">
<div class="radio-btn ${state.params.reflectionView === 'super' ? 'active' : ''}" data-val="super">合成波 (Superposition)</div>
<div class="radio-btn ${state.params.reflectionView === 'parts' ? 'active' : ''}" data-val="parts">入射波+反射波 (Components)</div>
</div>
</div>
`;
controlsGrid.insertAdjacentHTML('beforeend', html);
document.querySelectorAll('#radio-reflection-type .radio-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
document.querySelectorAll('#radio-reflection-type .radio-btn').forEach(b => b.classList.remove('active'));
e.target.classList.add('active');
state.params.reflectionBoundary = e.target.dataset.val;
updateFormulaDisplay();
});
});
document.querySelectorAll('#radio-reflection-view .radio-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
document.querySelectorAll('#radio-reflection-view .radio-btn').forEach(b => b.classList.remove('active'));
e.target.classList.add('active');
state.params.reflectionView = e.target.dataset.val;
});
});
} else if (state.mode === 'aircolumn') {
const html = `
<div class="control-block dynamic-ctrl" style="grid-column: span 2;">
<label>管の種類 (Pipe Type)</label>
<div class="radio-group" id="radio-aircolumn-type">
<div class="radio-btn ${state.params.pipeType === 'open' ? 'active' : ''}" data-val="open">開管 (Open Pipe)</div>
<div class="radio-btn ${state.params.pipeType === 'closed' ? 'active' : ''}" data-val="closed">閉管 (Closed Pipe)</div>
</div>
</div>
<div class="control-block dynamic-ctrl" style="grid-column: span 2;">
<label>波の表示 (Wave Display)</label>
<div class="radio-group" id="radio-aircolumn-view">
<div class="radio-btn ${state.params.pipeDisplay === 'pressure' ? 'active' : ''}" data-val="pressure">圧力変化 (Pressure)</div>
<div class="radio-btn ${state.params.pipeDisplay === 'displacement' ? 'active' : ''}" data-val="displacement">変位 (Displacement)</div>
</div>
</div>
<div class="control-block dynamic-ctrl">
<div class="label-row">
<label>管の長さ L (m)</label>
<span class="val-badge"><span id="val-pipelength">${state.params.pipeLength.toFixed(2)}</span></span>
</div>
<input type="range" id="slider-pipelength" class="custom-slider" min="0.1" max="2.0" step="0.05" value="${state.params.pipeLength}">
</div>
<div class="control-block dynamic-ctrl">
<div class="label-row">
<label>倍音 n (Harmonic)</label>
<span class="val-badge"><span id="val-harmonic">${state.params.n}</span></span>
</div>
<input type="range" id="slider-harmonic" class="custom-slider" min="1" max="5" step="1" value="${state.params.n}">
</div>
`;
controlsGrid.insertAdjacentHTML('beforeend', html);
document.getElementById('slider-pipelength').addEventListener('input', (e) => {
updateParam('pipeLength', parseFloat(e.target.value), document.getElementById('val-pipelength'));
});
document.getElementById('slider-harmonic').addEventListener('input', (e) => {
updateParam('n', parseInt(e.target.value), document.getElementById('val-harmonic'));
});
document.querySelectorAll('#radio-aircolumn-type .radio-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
document.querySelectorAll('#radio-aircolumn-type .radio-btn').forEach(b => b.classList.remove('active'));
e.target.classList.add('active');
state.params.pipeType = e.target.dataset.val;
updateFormulaDisplay();
if (state.audio.isPlaying) state.audio.oscillator.frequency.setTargetAtTime(calcCurrentFrequency(), state.audio.ctx.currentTime, 0.1);
});
});
document.querySelectorAll('#radio-aircolumn-view .radio-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
document.querySelectorAll('#radio-aircolumn-view .radio-btn').forEach(b => b.classList.remove('active'));
e.target.classList.add('active');
state.params.pipeDisplay = e.target.dataset.val;
});
});
} else if (state.mode === 'helmholtz') {
const html = `
<div class="control-block dynamic-ctrl" style="grid-column: span 2;">
<div class="label-row">
<label>空洞の体積 V (L)</label>
<span class="val-badge"><span id="val-cavityVol">${(state.params.cavityVol * 1000).toFixed(1)}</span></span>
</div>
<input type="range" id="slider-cavityVol" class="custom-slider" min="0.0001" max="0.005" step="0.0001" value="${state.params.cavityVol}">
</div>
<div class="control-block dynamic-ctrl">
<div class="label-row">
<label>首の面積 A (cm²)</label>
<span class="val-badge"><span id="val-neckArea">${(state.params.neckArea * 10000).toFixed(1)}</span></span>
</div>
<input type="range" id="slider-neckArea" class="custom-slider" min="0.00005" max="0.002" step="0.00005" value="${state.params.neckArea}">
</div>
<div class="control-block dynamic-ctrl">
<div class="label-row">
<label>首の長さ L (cm)</label>
<span class="val-badge"><span id="val-neckLength">${(state.params.neckLength * 100).toFixed(1)}</span></span>
</div>
<input type="range" id="slider-neckLength" class="custom-slider" min="0.01" max="0.2" step="0.01" value="${state.params.neckLength}">
</div>
`;
controlsGrid.insertAdjacentHTML('beforeend', html);
document.getElementById('slider-cavityVol').addEventListener('input', (e) => {
const val = parseFloat(e.target.value);
updateParam('cavityVol', val, null);
document.getElementById('val-cavityVol').innerText = (val * 1000).toFixed(1);
});
document.getElementById('slider-neckArea').addEventListener('input', (e) => {
const val = parseFloat(e.target.value);
updateParam('neckArea', val, null);
document.getElementById('val-neckArea').innerText = (val * 10000).toFixed(1);
});
document.getElementById('slider-neckLength').addEventListener('input', (e) => {
const val = parseFloat(e.target.value);
updateParam('neckLength', val, null);
document.getElementById('val-neckLength').innerText = (val * 100).toFixed(1);
});
} else if (state.mode === 'vocaltract') {
let slidersHtml = '';
for (let i = 0; i < state.params.tractSections; i++) {
slidersHtml += `
<div class="control-block dynamic-ctrl" style="grid-column: span 1;">
<div class="label-row">
<label>管 ${i+1} 面積 (cm²)</label>
<span class="val-badge"><span id="val-tractArea-${i}">${state.params.tractAreas[i].toFixed(1)}</span></span>
</div>
<input type="range" id="slider-tractArea-${i}" class="custom-slider" min="0.1" max="10.0" step="0.1" value="${state.params.tractAreas[i]}" data-idx="${i}">
</div>
`;
}
const html = `
<div class="control-block dynamic-ctrl" style="grid-column: span 2;">
<label>母音プリセット (Vowels)</label>
<div class="radio-group" id="radio-vowels">
<div class="radio-btn" data-vowel="a">ア [a]</div>
<div class="radio-btn" data-vowel="i">イ [i]</div>
<div class="radio-btn" data-vowel="u">ウ [u]</div>
<div class="radio-btn" data-vowel="e">エ [e]</div>
<div class="radio-btn" data-vowel="o">オ [o]</div>
</div>
</div>
<div class="control-block dynamic-ctrl" style="grid-column: span 1;">
<div class="label-row">
<label>声道長 L (cm)</label>
<span class="val-badge"><span id="val-tractLength">${state.params.tractLength.toFixed(1)}</span></span>
</div>
<input type="range" id="slider-tractLength" class="custom-slider" min="10.0" max="25.0" step="0.5" value="${state.params.tractLength}">
</div>
<div class="control-block dynamic-ctrl" style="grid-column: span 1;">
<div class="label-row">
<label>基本周波数 F0 (Hz)</label>
<span class="val-badge"><span id="val-f0">${state.params.f0.toFixed(0)}</span></span>
</div>
<input type="range" id="slider-f0" class="custom-slider" min="50" max="400" step="5" value="${state.params.f0}">
</div>
${slidersHtml}
`;
controlsGrid.insertAdjacentHTML('beforeend', html);
document.querySelectorAll('#radio-vowels .radio-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
const vowel = e.target.dataset.vowel;
const presets = {
'a': [1.0, 2.0, 6.0, 10.0],
'i': [9.0, 5.0, 1.0, 0.5],
'u': [3.0, 7.0, 2.0, 0.5],
'e': [4.0, 3.0, 5.0, 4.0],
'o': [2.0, 7.0, 3.0, 1.0]
};
if (presets[vowel]) {
document.querySelectorAll('#radio-vowels .radio-btn').forEach(b => b.classList.remove('active'));
e.target.classList.add('active');
for(let i=0; i<state.params.tractSections; i++) {
if (i < presets[vowel].length) {
state.params.tractAreas[i] = presets[vowel][i];
const slider = document.getElementById(`slider-tractArea-${i}`);
const valDisplay = document.getElementById(`val-tractArea-${i}`);
if(slider) slider.value = presets[vowel][i];
if(valDisplay) valDisplay.innerText = presets[vowel][i].toFixed(1);
}
}
updateFormulaDisplay();
updateCalcPanel();
}
});
});
document.getElementById('slider-tractLength').addEventListener('input', (e) => {
state.params.tractLength = parseFloat(e.target.value);
document.getElementById('val-tractLength').innerText = state.params.tractLength.toFixed(1);
updateFormulaDisplay();
updateCalcPanel();
});
document.getElementById('slider-f0').addEventListener('input', (e) => {
state.params.f0 = parseFloat(e.target.value);
document.getElementById('val-f0').innerText = state.params.f0.toFixed(0);
updateFormulaDisplay();
updateCalcPanel();
});
for (let i = 0; i < state.params.tractSections; i++) {
document.getElementById(`slider-tractArea-${i}`).addEventListener('input', (e) => {
const idx = parseInt(e.target.dataset.idx);
state.params.tractAreas[idx] = parseFloat(e.target.value);
document.getElementById(`val-tractArea-${idx}`).innerText = state.params.tractAreas[idx].toFixed(1);
updateFormulaDisplay();
updateCalcPanel();
});
}
}
}
function updateFormulaDisplay() {
// Updates MathJax math content string
let mathStr = "";
if (state.mode === 'fundamental') {
mathStr = `$$ y(x,t) = A \\sin \\left( 2\\pi ft - \\frac{2\\pi x}{\\lambda} \\right) $$`;
} else if (state.mode === 'reflection') {
mathStr = `$$ y(x,t) = 2A \\sin(kx) \\cos(\\omega t) \\quad \\text{(定常波)} $$`;
} else if (state.mode === 'aircolumn') {
if (state.params.pipeType === 'open') {
mathStr = `$$ f_n = \\frac{nv}{2L} \\implies f_{${state.params.n}} = \\frac{${state.params.n} \\times ${state.params.speed.toFixed(0)}}{2 \\times ${state.params.pipeLength.toFixed(2)}} = ${calcCurrentFrequency().toFixed(1)}\\text{ Hz} $$`;
} else {
const m = 2 * state.params.n - 1;
mathStr = `$$ f_m = \\frac{mv}{4L} \\implies f_{${m}} = \\frac{${m} \\times ${state.params.speed.toFixed(0)}}{4 \\times ${state.params.pipeLength.toFixed(2)}} = ${calcCurrentFrequency().toFixed(1)}\\text{ Hz} $$`;
}
} else if (state.mode === 'helmholtz') {
mathStr = `$$ f = \\frac{v}{2\\pi} \\sqrt{\\frac{A}{VL}} \\approx ${calcCurrentFrequency().toFixed(1)}\\text{ Hz} $$`;
} else if (state.mode === 'vocaltract') {
mathStr = `$$ r = \\frac{A_1 - A_2}{A_1 + A_2} \\quad \\text{(反射係数)} $$`;
}
formulaEl.innerHTML = mathStr;
if (window.MathJax) {
MathJax.typesetPromise([formulaEl]).catch((err) => console.log(err.message));
}
}
// ---------- Real-time Calculation Panel ----------
function updateCalcPanel() {
const f = calcCurrentFrequency();
const v = state.params.speed;
const lambda = v / f;
const T = 1 / f;
const k = (2 * Math.PI) / lambda;
const omega = 2 * Math.PI * f;
let items = [];
if (state.mode === 'fundamental' || state.mode === 'reflection') {
items = [
{ symbol: 'λ', label: '波長', value: lambda >= 1 ? lambda.toFixed(3) : (lambda * 100).toFixed(1), unit: lambda >= 1 ? 'm' : 'cm' },
{ symbol: 'T', label: '周期', value: T >= 0.001 ? (T * 1000).toFixed(2) : (T * 1e6).toFixed(1), unit: T >= 0.001 ? 'ms' : 'μs' },
{ symbol: 'f', label: '周波数', value: f.toFixed(1), unit: 'Hz' },
{ symbol: 'k', label: '波数', value: k.toFixed(2), unit: 'rad/m' },
{ symbol: 'ω', label: '角振動数', value: omega.toFixed(1), unit: 'rad/s' },
{ symbol: 'v', label: '波の速さ', value: v.toFixed(0), unit: 'm/s' },
];
} else if (state.mode === 'aircolumn') {
const L = state.params.pipeLength;
const lambdaPipe = state.params.pipeType === 'open' ? (2 * L / state.params.n) : (4 * L / (2 * state.params.n - 1));
items = [
{ symbol: 'f', label: '共鳴周波数', value: f.toFixed(1), unit: 'Hz' },
{ symbol: 'L', label: '管の長さ', value: (L * 100).toFixed(1), unit: 'cm' },
{ symbol: 'λ', label: '管内波長', value: (lambdaPipe * 100).toFixed(1), unit: 'cm' },
{ symbol: 'n', label: '倍音次数', value: state.params.n.toString(), unit: '' },
{ symbol: 'v', label: '音速', value: v.toFixed(0), unit: 'm/s' },
];
} else if (state.mode === 'helmholtz') {
const V = state.params.cavityVol;
const A = state.params.neckArea;
const Ln = state.params.neckLength;
items = [
{ symbol: 'f₀', label: '共鳴周波数', value: f.toFixed(1), unit: 'Hz' },
{ symbol: 'V', label: '空洞体積', value: (V * 1e6).toFixed(0), unit: 'cm³' },
{ symbol: 'A', label: '首断面積', value: (A * 1e4).toFixed(2), unit: 'cm²' },
{ symbol: 'L', label: '首の長さ', value: (Ln * 100).toFixed(1), unit: 'cm' },
{ symbol: 'v', label: '音速', value: v.toFixed(0), unit: 'm/s' },
];
} else if (state.mode === 'vocaltract') {
let rs = [];
for (let i=0; i < state.params.tractSections - 1; i++) {
const a1 = state.params.tractAreas[i];
const a2 = state.params.tractAreas[i+1];
const r = (a1 + a2) === 0 ? 0 : (a1 - a2) / (a1 + a2);
rs.push(r.toFixed(2));
}
items = [
{ symbol: 'F₀', label: '基本周波数', value: state.params.f0.toFixed(0), unit: 'Hz' },
{ symbol: 'F₁', label: '第1フォルマント', value: f.toFixed(1), unit: 'Hz' },
{ symbol: 'L', label: '声道長', value: state.params.tractLength.toFixed(1), unit: 'cm' },
{ symbol: 'r₁', label: '反射(1-2)', value: rs[0] || "0", unit: '' },
{ symbol: 'r₂', label: '反射(2-3)', value: rs[1] || "0", unit: '' },
{ symbol: 'r₃', label: '反射(3-4)', value: rs[2] || "0", unit: '' },
];
}
// Build HTML
const prevValues = {};
calcGrid.querySelectorAll('.calc-item').forEach(el => {
prevValues[el.dataset.key] = el.querySelector('.calc-value').textContent;
});
calcGrid.innerHTML = items.map(item => {
const valStr = item.value + (item.unit ? ' ' : '');
const changed = prevValues[item.symbol] !== undefined && prevValues[item.symbol] !== valStr;
return `<div class="calc-item" data-key="${item.symbol}">
<span class="calc-label"><span class="calc-symbol">${item.symbol}</span>${item.label}</span>
<span class="calc-value${changed ? ' flash' : ''}">${valStr}<span class="calc-unit">${item.unit}</span></span>
</div>`;
}).join('');
// Remove flash class after animation
setTimeout(() => {
calcGrid.querySelectorAll('.calc-value.flash').forEach(el => el.classList.remove('flash'));
}, 400);
}
// ---------- Audio Synthesis Web Audio API ----------
async function toggleAudio() {
if (!state.audio.ctx) {
// Initialize Web Audio API
state.audio.ctx = new (window.AudioContext || window.webkitAudioContext)();
state.audio.gainNode = state.audio.ctx.createGain();
state.audio.gainNode.gain.setValueAtTime(0, state.audio.ctx.currentTime);
state.audio.gainNode.connect(state.audio.ctx.destination);
}
// Ensure context is running (browser autoplay policies)
if (state.audio.ctx.state === 'suspended') {
await state.audio.ctx.resume();
}
if (!state.audio.isPlaying) {
if (state.mode === 'vocaltract') {
const bufferSize = 1024;
const createProcessor = state.audio.ctx.createScriptProcessor || state.audio.ctx.createJavaScriptNode;
state.audio.scriptNode = createProcessor.call(state.audio.ctx, bufferSize, 1, 1);
const sampleRate = state.audio.ctx.sampleRate;
const sections = state.params.tractSections;
const c = state.params.speed;
// To support varying tract lengths up to 30cm dynamically,
// we allocate a buffer large enough for max possible delay per section.
// 30cm / 4 sections = 7.5cm/section. Max delay = 0.075 / 340 * 48000 = ~10.6 samples.
// 64 is safely large enough.
const MAX_SECTION_DELAY = 64;
const plusBufs = Array.from({length: sections}, () => new Float32Array(MAX_SECTION_DELAY));
const minusBufs = Array.from({length: sections}, () => new Float32Array(MAX_SECTION_DELAY));
let ptr = 0;
let phase = 0;
state.audio.scriptNode.onaudioprocess = function(e) {
const output = e.outputBuffer.getChannelData(0);
const freq = state.params.f0;
const phaseInc = 2 * Math.PI * freq / sampleRate;
const r = new Float32Array(sections - 1);
for (let i=0; i<sections-1; i++) {
const A1 = state.params.tractAreas[i];
const A2 = state.params.tractAreas[i+1];
r[i] = (A1 + A2 === 0) ? 0 : (A1 - A2) / (A1 + A2);
}
// Calculate dynamic fractional delay
const currentTractL = state.params.tractLength / 100; // m
const actualDelay = (currentTractL / sections) / state.params.speed * sampleRate;
let dInt = Math.floor(actualDelay);
let dFrac = actualDelay - dInt;
// Safety bound
if (dInt < 1) dInt = 1;
if (dInt >= MAX_SECTION_DELAY - 1) dInt = MAX_SECTION_DELAY - 2;
for (let i = 0; i < bufferSize; i++) {
phase += phaseInc;
if(phase >= 2*Math.PI) phase -= 2*Math.PI;
// Pseudo-glottal pulse (LF-like approximation): open slowly, close fast
const nPhase = phase / Math.PI; // 0 to 2
let source = 0;
if (nPhase < 1.0) {
source = 0.5 * (1.0 - Math.cos(nPhase * Math.PI)); // Gradual opening
} else {
source = Math.max(0, 1.0 - (nPhase - 1.0) * 5.0); // Fast closing snapping shut
}
source = (source - 0.5) * state.params.amp; // center around 0
const pUp = new Float32Array(sections);
const pDown = new Float32Array(sections);
// Fractional delay reading using linear interpolation
const readPtr1 = (ptr + dInt) % MAX_SECTION_DELAY;
const readPtr2 = (ptr + dInt + 1) % MAX_SECTION_DELAY;
for(let s=0; s<sections; s++) {
const up1 = plusBufs[s][readPtr1];
const up2 = plusBufs[s][readPtr2];
pUp[s] = up1 * (1 - dFrac) + up2 * dFrac;
const down1 = minusBufs[s][readPtr1];
const down2 = minusBufs[s][readPtr2];
pDown[s] = down1 * (1 - dFrac) + down2 * dFrac;
}
// Boundary scatterings
const inPlus = source + 0.9 * pDown[0]; // Glottis reflection
const inMinus = -0.9 * pUp[sections-1]; // Lips reflection
const scatteredPlus = new Float32Array(sections);
const scatteredMinus = new Float32Array(sections);
scatteredPlus[0] = inPlus;
scatteredMinus[sections-1] = inMinus;
for (let s = 0; s < sections - 1; s++) {
scatteredPlus[s+1] = (1 + r[s]) * pUp[s] - r[s] * pDown[s+1];
scatteredMinus[s] = r[s] * pUp[s] + (1 - r[s]) * pDown[s+1];
}
// Attrition (simulate wall loss)
const attenuation = 0.999;
// Retreat pointer
ptr = (ptr === 0) ? MAX_SECTION_DELAY - 1 : ptr - 1;
for (let s=0; s<sections; s++) {
plusBufs[s][ptr] = scatteredPlus[s] * attenuation;
minusBufs[s][ptr] = scatteredMinus[s] * attenuation;
}
output[i] = pUp[sections-1] * 0.5;
}
};
state.audio.scriptNode.connect(state.audio.gainNode);
} else {
state.audio.oscillator = state.audio.ctx.createOscillator();
state.audio.oscillator.type = 'sine';
state.audio.oscillator.frequency.value = calcCurrentFrequency();
state.audio.oscillator.connect(state.audio.gainNode);
state.audio.oscillator.start();
}
// Envelope Attack (fade in to avoid click)
state.audio.gainNode.gain.setTargetAtTime(state.audio.volume, state.audio.ctx.currentTime, 0.05);
state.audio.isPlaying = true;
// Update UI
btnToggleSound.classList.add('active-play');
btnToggleSound.classList.remove('primary');
soundIcon.innerText = "🔊";
soundText.innerText = "Stop Sound";
statusIndicator.innerText = "Active";
statusIndicator.classList.remove('off');
statusIndicator.classList.add('on');
} else {
// Envelope Release (fade out to avoid click)
state.audio.gainNode.gain.setTargetAtTime(0, state.audio.ctx.currentTime, 0.05);
setTimeout(() => {
if (state.audio.oscillator) {
state.audio.oscillator.stop();
state.audio.oscillator.disconnect();
state.audio.oscillator = null;
}
if (state.audio.scriptNode) {
state.audio.scriptNode.disconnect();
state.audio.scriptNode = null;
}
}, 100); // Wait for fade out
state.audio.isPlaying = false;
// Update UI
btnToggleSound.classList.remove('active-play');
btnToggleSound.classList.add('primary');
soundIcon.innerText = "🔇";
soundText.innerText = "Play Sound";
statusIndicator.innerText = "Off";
statusIndicator.classList.remove('on');
statusIndicator.classList.add('off');
}
}
// ---------- Simulation Rendering Frame ----------
function togglePause() {
state.isPaused = !state.isPaused;
btnPlayPause.textContent = state.isPaused ? '▶' : '⏸';
btnPlayPause.classList.toggle('paused', state.isPaused);
}
function stepFrame(dir) {
if (!state.isPaused) togglePause();
state.params.time += (1/60) * 5 * dir;
renderFrame();
}
function startSimulation() {
let lastTime = performance.now();
function loop(now) {
const dt = (now - lastTime) / 1000;
lastTime = now;
if (!state.isPaused) {
state.params.time += dt * 5 * state.playbackSpeed;
}
renderFrame();
state.animationFrameId = requestAnimationFrame(loop);
}
state.animationFrameId = requestAnimationFrame(loop);
}
function drawParticle(x, y, color) {
ctx.beginPath();
ctx.arc(x, y, 6, 0, Math.PI * 2);
ctx.fillStyle = color;
ctx.fill();
ctx.strokeStyle = '#fff';
ctx.lineWidth = 1;
ctx.stroke();
}
function drawDoubleArrow(x1, y1, x2, y2, label, color) {
const headLen = 8;
const dx = x2 - x1;
const dy = y2 - y1;
const angle = Math.atan2(dy, dx);
ctx.save();
ctx.strokeStyle = color;
ctx.fillStyle = color;
ctx.lineWidth = 1.5;
ctx.setLineDash([]);
// Line
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
// Arrowhead at start
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x1 + headLen * Math.cos(angle - Math.PI/6), y1 + headLen * Math.sin(angle - Math.PI/6));
ctx.lineTo(x1 + headLen * Math.cos(angle + Math.PI/6), y1 + headLen * Math.sin(angle + Math.PI/6));
ctx.closePath();
ctx.fill();
// Arrowhead at end
ctx.beginPath();
ctx.moveTo(x2, y2);
ctx.lineTo(x2 - headLen * Math.cos(angle - Math.PI/6), y2 - headLen * Math.sin(angle - Math.PI/6));
ctx.lineTo(x2 - headLen * Math.cos(angle + Math.PI/6), y2 - headLen * Math.sin(angle + Math.PI/6));
ctx.closePath();
ctx.fill();
// Label
const midX = (x1 + x2) / 2;
const midY = (y1 + y2) / 2;
ctx.font = 'bold 14px Inter';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
// Offset label perpendicular to arrow for readability
const perpX = -Math.sin(angle) * 16;
const perpY = Math.cos(angle) * 16;
ctx.fillText(label, midX + perpX, midY + perpY);
ctx.restore();
}
function drawFundamental(w, h) {
const amp = state.params.amp * (h / 4);
// Map physical screen width to 4.0 meters
const physicalLength = 4.0;
const pixelsPerMeter = w / physicalLength;
// Calculate wavelength based on actual speed and frequency: λ = v / f
const lambda_phys = state.params.speed / state.params.freq;
const lambda_vis = lambda_phys * pixelsPerMeter;
const visualK = (2 * Math.PI) / lambda_vis;
// Scale animation speed, with 440 Hz as a baseline "pleasing visual speed"
const baseFreq = 440;
const omega_vis = 2 * Math.PI * 0.4 * (state.params.freq / baseFreq);
const t = state.params.time * omega_vis;
if (state.params.viewType === 'y-x') {
// --- y-x graph: snapshot of wave shape at current time ---
// Draw axis labels
ctx.fillStyle = 'rgba(255,255,255,0.5)';
ctx.font = '13px Inter';
ctx.fillText('x →', w - 30, h / 2 + 20);
ctx.fillText('y ↑', 10, 30);
ctx.beginPath();
for (let x = 0; x < w; x++) {
const y = h / 2 + amp * Math.sin(visualK * x - t);
if (x === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
}
ctx.strokeStyle = '#3b82f6';
ctx.lineWidth = 3;
ctx.stroke();
// Highlight one particle (red dot) moving up/down at x = w/2
const pX = w / 2;
const pY = h / 2 + amp * Math.sin(visualK * pX - t);
drawParticle(pX, pY, '#ef4444');
// Draw vertical guide line at pX
ctx.beginPath();
ctx.setLineDash([4, 4]);
ctx.moveTo(pX, h / 2 - amp - 20);
ctx.lineTo(pX, h / 2 + amp + 20);
ctx.strokeStyle = 'rgba(239, 68, 68, 0.3)';
ctx.lineWidth = 1;
ctx.stroke();
ctx.setLineDash([]);
// --- Annotations: A (amplitude) ---
const ampAnnotX = w * 0.15;
const ampAnnotY = h / 2 + amp * Math.sin(visualK * ampAnnotX - t);
// Draw from center line to wave
ctx.beginPath();
ctx.setLineDash([3, 3]);
ctx.moveTo(ampAnnotX, h / 2);
ctx.lineTo(ampAnnotX, h / 2 - amp);
ctx.strokeStyle = 'rgba(239, 68, 68, 0.4)';
ctx.lineWidth = 1;
ctx.stroke();
ctx.setLineDash([]);
drawDoubleArrow(ampAnnotX, h / 2, ampAnnotX, h / 2 - amp, 'A', '#ef4444');
} else if (state.params.viewType === 'y-t') {
// --- y-t graph: oscillation history of a single particle ---
ctx.fillStyle = 'rgba(255,255,255,0.5)';
ctx.font = '13px Inter';
ctx.fillText('t →', w - 30, h / 2 + 20);
ctx.fillText('y ↑', 10, 30);
ctx.beginPath();
for (let x = 0; x < w; x++) {
// x-axis represents time going to the right
const tLocal = t - x * 0.02;
const y = h / 2 + amp * Math.sin(-tLocal);
if (x === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
}
ctx.strokeStyle = '#10b981';
ctx.lineWidth = 3;
ctx.stroke();
// --- Annotation: T (period) ---
const periodPx = (2 * Math.PI) / 0.02;
const tPhase = t % (2 * Math.PI);
let firstPeakX = tPhase / 0.02;
while (firstPeakX < 40) firstPeakX += periodPx;
while (firstPeakX > w - periodPx - 40) firstPeakX -= periodPx;
const secondPeakX = firstPeakX + periodPx;
if (secondPeakX < w - 20 && firstPeakX > 20) {
const arrowY = h / 2 - amp - 35;
drawDoubleArrow(firstPeakX, arrowY, secondPeakX, arrowY, 'T', '#facc15');
}
} else if (state.params.viewType === 'transverse') {
// --- Transverse wave: particles move perpendicular to propagation ---
const spacing = 24;
for (let x = spacing; x < w - spacing; x += spacing) {
const y = h / 2 + amp * Math.sin(visualK * x - t);
// Draw equilibrium guide
ctx.beginPath();