-
Notifications
You must be signed in to change notification settings - Fork 49
/
Copy pathdialog-audio-vocal-synth.js
1387 lines (1234 loc) · 41.7 KB
/
dialog-audio-vocal-synth.js
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
/**
🎺
@file dialog audio vocal synth
@summary animal crossing-style audio powered by the pink trombone vocal synth
@license MIT
@author Sean S. LeBlanc
@version 22.1.0
@requires Bitsy 8.12
@description
An extension of the dialog audio hack which incorporates
a vocal synth with multiple voice support
Voices are defined in `hackOptions.voices` below
A default voice is required, but the volume can be set to zero if needed
Other voices don't need to have every property specified:
if one is missing, it will use the default voice's value instead
Usage:
(voice "<voice name>")
Parameter notes:
- Valid voice names are the keys in `hackOptions.voices`
- If a voice name is used that does not exist, the default voice will be used instead
Examples:
(voice "myVoice")
(voice "default")
(voice "") // same effect as default
Note: most of the credit for this goes to Neil Thapen,
the creator of the Pink Trombone vocal synth;
this uses a fork of its source code to drive the audio
HOW TO USE:
1. Copy-paste into a script tag after the bitsy source
2. Edit `hackOptions` below as needed
3. Add (voice "<voice name>") commands to your dialog as needed
*/
this.hacks = this.hacks || {};
(function (exports, bitsy) {
'use strict';
var hackOptions = {
autoReset: true, // if true, automatically resets the voice to default when dialog is exited
// list of voices that can be used with the provided dialog command
// the values use for voice parameters are [base, range] pairs for RNG;
// e.g. [0.5, 0.1] will produce values between 0.4 and 0.6
voices: {
default: {
// volume randomly applied to each letter
volume: [0.3, 0.1],
// pitch randomly applied to each letter
pitch: [240, 200],
// vibrato randomly applied to each letter
vibrato: [0.01, 0.005],
// how much phonemes to affect tract shape
phoneme: [0.9, 0.1],
// multiplier for nasalness (based on phoneme)
nasal: [0.9, 0.1],
// multiplier for voiced (based on phoneme)
voiced: [0.4, 0.2],
// note: tongue is a modification *on top* of the phoneme modification
// where to modify
tonguePosition: [0.5, 0.5],
// range from the position in which points are modified
tongueSize: [0.3, 0.2],
// how much modification is applied (this is a multiplier, so base: 1, range: 0 means no modification)
tongueAmount: [1.0, 0.1],
},
// an example voice which overrides the default's pitch and vibrato
overrideExample: {
pitch: [650, 325],
vibrato: [0.3, 0.1],
},
},
};
/*
* A speed-improved perlin and simplex noise algorithms for 2D.
*
* Based on example code by Stefan Gustavson ([email protected]).
* Optimisations by Peter Eastman ([email protected]).
* Better rank ordering method by Stefan Gustavson in 2012.
* Converted to Javascript by Joseph Gentle.
*
* Version 2012-03-09
*
* This code was placed in the public domain by its original author,
* Stefan Gustavson. You may use it as you see fit, but
* attribution is appreciated.
*
*/
var module = {};
function Grad(x, y, z) {
this.x = x;
this.y = y;
this.z = z;
}
Grad.prototype.dot2 = function (x, y) {
return this.x * x + this.y * y;
};
Grad.prototype.dot3 = function (x, y, z) {
return this.x * x + this.y * y + this.z * z;
};
var grad3 = [new Grad(1, 1, 0), new Grad(-1, 1, 0), new Grad(1, -1, 0), new Grad(-1, -1, 0),
new Grad(1, 0, 1), new Grad(-1, 0, 1), new Grad(1, 0, -1), new Grad(-1, 0, -1),
new Grad(0, 1, 1), new Grad(0, -1, 1), new Grad(0, 1, -1), new Grad(0, -1, -1)
];
var p = [151, 160, 137, 91, 90, 15,
131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23,
190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33,
88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166,
77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244,
102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196,
135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 250, 124, 123,
5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42,
223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9,
129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228,
251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107,
49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254,
138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180
];
// To remove the need for index wrapping, double the permutation table length
var perm = new Array(512);
var gradP = new Array(512);
// This isn't a very good seeding function, but it works ok. It supports 2^16
// different seed values. Write something better if you need more seeds.
module.seed = function (seed) {
if (seed > 0 && seed < 1) {
// Scale the seed out
seed *= 65536;
}
seed = Math.floor(seed);
if (seed < 256) {
seed |= seed << 8;
}
for (var i = 0; i < 256; i++) {
var v;
if (i & 1) {
v = p[i] ^ (seed & 255);
} else {
v = p[i] ^ ((seed >> 8) & 255);
}
perm[i] = perm[i + 256] = v;
gradP[i] = gradP[i + 256] = grad3[v % 12];
}
};
module.seed(Date.now());
/*
for(var i=0; i<256; i++) {
perm[i] = perm[i + 256] = p[i];
gradP[i] = gradP[i + 256] = grad3[perm[i] % 12];
}*/
// Skewing and unskewing factors for 2, 3, and 4 dimensions
var F2 = 0.5 * (Math.sqrt(3) - 1);
var G2 = (3 - Math.sqrt(3)) / 6;
// 2D simplex noise
module.simplex2 = function (xin, yin) {
var n0, n1, n2; // Noise contributions from the three corners
// Skew the input space to determine which simplex cell we're in
var s = (xin + yin) * F2; // Hairy factor for 2D
var i = Math.floor(xin + s);
var j = Math.floor(yin + s);
var t = (i + j) * G2;
var x0 = xin - i + t; // The x,y distances from the cell origin, unskewed.
var y0 = yin - j + t;
// For the 2D case, the simplex shape is an equilateral triangle.
// Determine which simplex we are in.
var i1, j1; // Offsets for second (middle) corner of simplex in (i,j) coords
if (x0 > y0) { // lower triangle, XY order: (0,0)->(1,0)->(1,1)
i1 = 1;
j1 = 0;
} else { // upper triangle, YX order: (0,0)->(0,1)->(1,1)
i1 = 0;
j1 = 1;
}
// A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and
// a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where
// c = (3-sqrt(3))/6
var x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords
var y1 = y0 - j1 + G2;
var x2 = x0 - 1 + 2 * G2; // Offsets for last corner in (x,y) unskewed coords
var y2 = y0 - 1 + 2 * G2;
// Work out the hashed gradient indices of the three simplex corners
i &= 255;
j &= 255;
var gi0 = gradP[i + perm[j]];
var gi1 = gradP[i + i1 + perm[j + j1]];
var gi2 = gradP[i + 1 + perm[j + 1]];
// Calculate the contribution from the three corners
var t0 = 0.5 - x0 * x0 - y0 * y0;
if (t0 < 0) {
n0 = 0;
} else {
t0 *= t0;
n0 = t0 * t0 * gi0.dot2(x0, y0); // (x,y) of grad3 used for 2D gradient
}
var t1 = 0.5 - x1 * x1 - y1 * y1;
if (t1 < 0) {
n1 = 0;
} else {
t1 *= t1;
n1 = t1 * t1 * gi1.dot2(x1, y1);
}
var t2 = 0.5 - x2 * x2 - y2 * y2;
if (t2 < 0) {
n2 = 0;
} else {
t2 *= t2;
n2 = t2 * t2 * gi2.dot2(x2, y2);
}
// Add contributions from each corner to get the final noise value.
// The result is scaled to return values in the interval [-1,1].
return 70 * (n0 + n1 + n2);
};
module.simplex1 = function (x) {
return module.simplex2(x * 1.2, -x * 0.7);
};
/**
P I N K T R O M B O N E
Bare-handed procedural speech synthesis
version 1.1, March 2017
by Neil Thapen
venuspatrol.nfshost.com
Bibliography
Julius O. Smith III, "Physical audio signal processing for virtual musical instruments and audio effects."
https://ccrma.stanford.edu/~jos/pasp/
Story, Brad H. "A parametric model of the vocal tract area function for vowel and consonant simulation."
The Journal of the Acoustical Society of America 117.5 (2005): 3231-3254.
Lu, Hui-Ling, and J. O. Smith. "Glottal source modeling for singing voice synthesis."
Proceedings of the 2000 International Computer Music Conference. 2000.
Mullen, Jack. Physical modelling of the vocal tract with the 2D digital waveguide mesh.
PhD thesis, University of York, 2006.
Copyright 2017 Neil Thapen
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/
function clamp$1(number, min, max) {
if (number < min) return min;
else if (number > max) return max;
else return number;
}
function moveTowards(current, target, amountUp, amountDown) {
if (current < target) return Math.min(current + amountUp, target);
else return Math.max(current - amountDown, target);
}
var sampleRate;
var alwaysVoice = false;
var AudioSystem = {
blockLength: 512,
blockTime: 1,
started: false,
soundOn: false,
init: function () {
window.AudioContext = window.AudioContext || window.webkitAudioContext;
this.audioContext = new window.AudioContext();
sampleRate = this.audioContext.sampleRate;
this.blockTime = this.blockLength / sampleRate;
var unmute = () => {
if (!this.started) {
this.started = true;
this.startSound();
document.removeEventListener('pointerup', unmute);
document.removeEventListener('keydown', unmute);
}
};
document.addEventListener('pointerup', unmute);
document.addEventListener('keydown', unmute);
},
startSound: function () {
//scriptProcessor may need a dummy input channel on iOS
this.scriptProcessor = this.audioContext.createScriptProcessor(this.blockLength, 2, 1);
this.scriptProcessor.connect(this.audioContext.destination);
this.scriptProcessor.onaudioprocess = AudioSystem.doScriptProcessor;
var whiteNoise = this.createWhiteNoiseNode(2 * sampleRate); // 2 seconds of noise
var aspirateFilter = this.audioContext.createBiquadFilter();
aspirateFilter.type = "bandpass";
aspirateFilter.frequency.value = 500;
aspirateFilter.Q.value = 0.5;
whiteNoise.connect(aspirateFilter);
aspirateFilter.connect(this.scriptProcessor);
var fricativeFilter = this.audioContext.createBiquadFilter();
fricativeFilter.type = "bandpass";
fricativeFilter.frequency.value = 1000;
fricativeFilter.Q.value = 0.5;
whiteNoise.connect(fricativeFilter);
fricativeFilter.connect(this.scriptProcessor);
whiteNoise.start(0);
},
createWhiteNoiseNode: function (frameCount) {
var myArrayBuffer = this.audioContext.createBuffer(1, frameCount, sampleRate);
var nowBuffering = myArrayBuffer.getChannelData(0);
for (var i = 0; i < frameCount; i++) {
nowBuffering[i] = Math.random(); // gaussian();
}
var source = this.audioContext.createBufferSource();
source.buffer = myArrayBuffer;
source.loop = true;
return source;
},
doScriptProcessor: function (event) {
var inputArray1 = event.inputBuffer.getChannelData(0);
var inputArray2 = event.inputBuffer.getChannelData(1);
var outArray = event.outputBuffer.getChannelData(0);
for (var j = 0, N = outArray.length; j < N; j++) {
var lambda1 = j / N;
var lambda2 = (j + 0.5) / N;
var glottalOutput = Glottis.runStep(lambda1, inputArray1[j]);
var vocalOutput = 0;
//Tract runs at twice the sample rate
Tract.runStep(glottalOutput, inputArray2[j], lambda1);
vocalOutput += Tract.lipOutput + Tract.noseOutput;
Tract.runStep(glottalOutput, inputArray2[j], lambda2);
vocalOutput += Tract.lipOutput + Tract.noseOutput;
outArray[j] = vocalOutput * 0.125;
}
Glottis.finishBlock();
Tract.finishBlock();
},
mute: function () {
this.scriptProcessor.disconnect();
},
unmute: function () {
this.scriptProcessor.connect(this.audioContext.destination);
}
};
var Glottis = {
timeInWaveform: 0,
oldFrequency: 140,
newFrequency: 140,
UIFrequency: 140,
smoothFrequency: 140,
oldTenseness: 0.6,
newTenseness: 0.6,
UITenseness: 0.6,
totalTime: 0,
vibratoAmount: 0.005,
vibratoFrequency: 6,
intensity: 0,
loudness: 1,
isTouched: false,
init: function () {
this.setupWaveform(0);
},
runStep: function (lambda, noiseSource) {
var timeStep = 1.0 / sampleRate;
this.timeInWaveform += timeStep;
this.totalTime += timeStep;
if (this.timeInWaveform > this.waveformLength) {
this.timeInWaveform -= this.waveformLength;
this.setupWaveform(lambda);
}
var out = this.normalizedLFWaveform(this.timeInWaveform / this.waveformLength);
var aspiration = this.intensity * (1 - Math.sqrt(this.UITenseness)) * this.getNoiseModulator() * noiseSource;
aspiration *= 0.2 + 0.02 * module.simplex1(this.totalTime * 1.99);
out += aspiration;
return out;
},
getNoiseModulator: function () {
var voiced = 0.1 + 0.2 * Math.max(0, Math.sin(Math.PI * 2 * this.timeInWaveform / this.waveformLength));
//return 0.3;
return this.UITenseness * this.intensity * voiced + (1 - this.UITenseness * this.intensity) * 0.3;
},
finishBlock: function () {
var vibrato = 0;
vibrato += this.vibratoAmount * Math.sin(2 * Math.PI * this.totalTime * this.vibratoFrequency);
vibrato += 0.02 * module.simplex1(this.totalTime * 4.07);
vibrato += 0.04 * module.simplex1(this.totalTime * 2.15);
if (this.UIFrequency > this.smoothFrequency)
this.smoothFrequency = Math.min(this.smoothFrequency * 1.1, this.UIFrequency);
if (this.UIFrequency < this.smoothFrequency)
this.smoothFrequency = Math.max(this.smoothFrequency / 1.1, this.UIFrequency);
this.oldFrequency = this.newFrequency;
this.newFrequency = this.smoothFrequency * (1 + vibrato);
this.oldTenseness = this.newTenseness;
this.newTenseness = this.UITenseness +
0.1 * module.simplex1(this.totalTime * 0.46) + 0.05 * module.simplex1(this.totalTime * 0.36);
if (!this.isTouched && alwaysVoice) this.newTenseness += (3 - this.UITenseness) * (1 - this.intensity);
if (this.isTouched || alwaysVoice) this.intensity += 0.13;
else this.intensity -= 0.05;
this.intensity = clamp$1(this.intensity, 0, 1);
},
setupWaveform: function (lambda) {
this.frequency = this.oldFrequency * (1 - lambda) + this.newFrequency * lambda;
var tenseness = this.oldTenseness * (1 - lambda) + this.newTenseness * lambda;
this.Rd = 3 * (1 - tenseness);
this.waveformLength = 1.0 / this.frequency;
var Rd = this.Rd;
if (Rd < 0.5) Rd = 0.5;
if (Rd > 2.7) Rd = 2.7;
// normalized to time = 1, Ee = 1
var Ra = -0.01 + 0.048 * Rd;
var Rk = 0.224 + 0.118 * Rd;
var Rg = (Rk / 4) * (0.5 + 1.2 * Rk) / (0.11 * Rd - Ra * (0.5 + 1.2 * Rk));
var Ta = Ra;
var Tp = 1 / (2 * Rg);
var Te = Tp + Tp * Rk; //
var epsilon = 1 / Ta;
var shift = Math.exp(-epsilon * (1 - Te));
var Delta = 1 - shift; //divide by this to scale RHS
var RHSIntegral = (1 / epsilon) * (shift - 1) + (1 - Te) * shift;
RHSIntegral = RHSIntegral / Delta;
var totalLowerIntegral = -(Te - Tp) / 2 + RHSIntegral;
var totalUpperIntegral = -totalLowerIntegral;
var omega = Math.PI / Tp;
var s = Math.sin(omega * Te);
// need E0*e^(alpha*Te)*s = -1 (to meet the return at -1)
// and E0*e^(alpha*Tp/2) * Tp*2/pi = totalUpperIntegral
// (our approximation of the integral up to Tp)
// writing x for e^alpha,
// have E0*x^Te*s = -1 and E0 * x^(Tp/2) * Tp*2/pi = totalUpperIntegral
// dividing the second by the first,
// letting y = x^(Tp/2 - Te),
// y * Tp*2 / (pi*s) = -totalUpperIntegral;
var y = -Math.PI * s * totalUpperIntegral / (Tp * 2);
var z = Math.log(y);
var alpha = z / (Tp / 2 - Te);
var E0 = -1 / (s * Math.exp(alpha * Te));
this.alpha = alpha;
this.E0 = E0;
this.epsilon = epsilon;
this.shift = shift;
this.Delta = Delta;
this.Te = Te;
this.omega = omega;
},
normalizedLFWaveform: function (t) {
var output;
if (t > this.Te) output = (-Math.exp(-this.epsilon * (t - this.Te)) + this.shift) / this.Delta;
else output = this.E0 * Math.exp(this.alpha * t) * Math.sin(this.omega * t);
return output * this.intensity * this.loudness;
}
};
var Tract = {
n: 44,
bladeStart: 10,
tipStart: 32,
lipStart: 39,
R: [], //component going right
L: [], //component going left
reflection: [],
junctionOutputR: [],
junctionOutputL: [],
maxAmplitude: [],
diameter: [],
restDiameter: [],
targetDiameter: [],
newDiameter: [],
A: [],
glottalReflection: 0.75,
lipReflection: -0.85,
lastObstruction: -1,
fade: 1.0, //0.9999,
movementSpeed: 15, //cm per second
transients: [],
lipOutput: 0,
noseOutput: 0,
velumTarget: 0.01,
init: function () {
this.bladeStart = Math.floor(this.bladeStart * this.n / 44);
this.tipStart = Math.floor(this.tipStart * this.n / 44);
this.lipStart = Math.floor(this.lipStart * this.n / 44);
this.diameter = new Float64Array(this.n);
this.restDiameter = new Float64Array(this.n);
this.targetDiameter = new Float64Array(this.n);
this.newDiameter = new Float64Array(this.n);
for (var i = 0; i < this.n; i++) {
var diameter = 0;
if (i < 7 * this.n / 44 - 0.5) diameter = 0.6;
else if (i < 12 * this.n / 44) diameter = 1.1;
else diameter = 1.5;
this.diameter[i] = this.restDiameter[i] = this.targetDiameter[i] = this.newDiameter[i] = diameter;
}
this.R = new Float64Array(this.n);
this.L = new Float64Array(this.n);
this.reflection = new Float64Array(this.n + 1);
this.newReflection = new Float64Array(this.n + 1);
this.junctionOutputR = new Float64Array(this.n + 1);
this.junctionOutputL = new Float64Array(this.n + 1);
this.A = new Float64Array(this.n);
this.maxAmplitude = new Float64Array(this.n);
this.noseLength = Math.floor(28 * this.n / 44);
this.noseStart = this.n - this.noseLength + 1;
this.noseR = new Float64Array(this.noseLength);
this.noseL = new Float64Array(this.noseLength);
this.noseJunctionOutputR = new Float64Array(this.noseLength + 1);
this.noseJunctionOutputL = new Float64Array(this.noseLength + 1);
this.noseReflection = new Float64Array(this.noseLength + 1);
this.noseDiameter = new Float64Array(this.noseLength);
this.noseA = new Float64Array(this.noseLength);
this.noseMaxAmplitude = new Float64Array(this.noseLength);
for (var i = 0; i < this.noseLength; i++) {
var diameter;
var d = 2 * (i / this.noseLength);
if (d < 1) diameter = 0.4 + 1.6 * d;
else diameter = 0.5 + 1.5 * (2 - d);
diameter = Math.min(diameter, 1.9);
this.noseDiameter[i] = diameter;
}
this.newReflectionLeft = this.newReflectionRight = this.newReflectionNose = 0;
this.calculateReflections();
this.calculateNoseReflections();
this.noseDiameter[0] = this.velumTarget;
},
reshapeTract: function (deltaTime) {
var amount = deltaTime * this.movementSpeed; var newLastObstruction = -1;
for (var i = 0; i < this.n; i++) {
var diameter = this.diameter[i];
var targetDiameter = this.targetDiameter[i];
if (diameter <= 0) newLastObstruction = i;
var slowReturn;
if (i < this.noseStart) slowReturn = 0.6;
else if (i >= this.tipStart) slowReturn = 1.0;
else slowReturn = 0.6 + 0.4 * (i - this.noseStart) / (this.tipStart - this.noseStart);
this.diameter[i] = moveTowards(diameter, targetDiameter, slowReturn * amount, 2 * amount);
}
if (this.lastObstruction > -1 && newLastObstruction == -1 && this.noseA[0] < 0.05) {
this.addTransient(this.lastObstruction);
}
this.lastObstruction = newLastObstruction;
amount = deltaTime * this.movementSpeed;
this.noseDiameter[0] = moveTowards(this.noseDiameter[0], this.velumTarget,
amount * 0.25, amount * 0.1);
this.noseA[0] = this.noseDiameter[0] * this.noseDiameter[0];
},
calculateReflections: function () {
for (var i = 0; i < this.n; i++) {
this.A[i] = this.diameter[i] * this.diameter[i]; //ignoring PI etc.
}
for (var i = 1; i < this.n; i++) {
this.reflection[i] = this.newReflection[i];
if (this.A[i] == 0) this.newReflection[i] = 0.999; //to prevent some bad behaviour if 0
else this.newReflection[i] = (this.A[i - 1] - this.A[i]) / (this.A[i - 1] + this.A[i]);
}
//now at junction with nose
this.reflectionLeft = this.newReflectionLeft;
this.reflectionRight = this.newReflectionRight;
this.reflectionNose = this.newReflectionNose;
var sum = this.A[this.noseStart] + this.A[this.noseStart + 1] + this.noseA[0];
this.newReflectionLeft = (2 * this.A[this.noseStart] - sum) / sum;
this.newReflectionRight = (2 * this.A[this.noseStart + 1] - sum) / sum;
this.newReflectionNose = (2 * this.noseA[0] - sum) / sum;
},
calculateNoseReflections: function () {
for (var i = 0; i < this.noseLength; i++) {
this.noseA[i] = this.noseDiameter[i] * this.noseDiameter[i];
}
for (var i = 1; i < this.noseLength; i++) {
this.noseReflection[i] = (this.noseA[i - 1] - this.noseA[i]) / (this.noseA[i - 1] + this.noseA[i]);
}
},
runStep: function (glottalOutput, turbulenceNoise, lambda) {
var updateAmplitudes = (Math.random() < 0.1);
//mouth
this.processTransients();
//this.glottalReflection = -0.8 + 1.6 * Glottis.newTenseness;
this.junctionOutputR[0] = this.L[0] * this.glottalReflection + glottalOutput;
this.junctionOutputL[this.n] = this.R[this.n - 1] * this.lipReflection;
for (var i = 1; i < this.n; i++) {
var r = this.reflection[i] * (1 - lambda) + this.newReflection[i] * lambda;
var w = r * (this.R[i - 1] + this.L[i]);
this.junctionOutputR[i] = this.R[i - 1] - w;
this.junctionOutputL[i] = this.L[i] + w;
}
//now at junction with nose
var i = this.noseStart;
var r = this.newReflectionLeft * (1 - lambda) + this.reflectionLeft * lambda;
this.junctionOutputL[i] = r * this.R[i - 1] + (1 + r) * (this.noseL[0] + this.L[i]);
r = this.newReflectionRight * (1 - lambda) + this.reflectionRight * lambda;
this.junctionOutputR[i] = r * this.L[i] + (1 + r) * (this.R[i - 1] + this.noseL[0]);
r = this.newReflectionNose * (1 - lambda) + this.reflectionNose * lambda;
this.noseJunctionOutputR[0] = r * this.noseL[0] + (1 + r) * (this.L[i] + this.R[i - 1]);
for (var i = 0; i < this.n; i++) {
this.R[i] = this.junctionOutputR[i] * 0.999;
this.L[i] = this.junctionOutputL[i + 1] * 0.999;
//this.R[i] = clamp(this.junctionOutputR[i] * this.fade, -1, 1);
//this.L[i] = clamp(this.junctionOutputL[i+1] * this.fade, -1, 1);
if (updateAmplitudes) {
var amplitude = Math.abs(this.R[i] + this.L[i]);
if (amplitude > this.maxAmplitude[i]) this.maxAmplitude[i] = amplitude;
else this.maxAmplitude[i] *= 0.999;
}
}
this.lipOutput = this.R[this.n - 1];
//nose
this.noseJunctionOutputL[this.noseLength] = this.noseR[this.noseLength - 1] * this.lipReflection;
for (var i = 1; i < this.noseLength; i++) {
var w = this.noseReflection[i] * (this.noseR[i - 1] + this.noseL[i]);
this.noseJunctionOutputR[i] = this.noseR[i - 1] - w;
this.noseJunctionOutputL[i] = this.noseL[i] + w;
}
for (var i = 0; i < this.noseLength; i++) {
this.noseR[i] = this.noseJunctionOutputR[i] * this.fade;
this.noseL[i] = this.noseJunctionOutputL[i + 1] * this.fade;
//this.noseR[i] = clamp(this.noseJunctionOutputR[i] * this.fade, -1, 1);
//this.noseL[i] = clamp(this.noseJunctionOutputL[i+1] * this.fade, -1, 1);
if (updateAmplitudes) {
var amplitude = Math.abs(this.noseR[i] + this.noseL[i]);
if (amplitude > this.noseMaxAmplitude[i]) this.noseMaxAmplitude[i] = amplitude;
else this.noseMaxAmplitude[i] *= 0.999;
}
}
this.noseOutput = this.noseR[this.noseLength - 1];
},
finishBlock: function () {
this.reshapeTract(AudioSystem.blockTime);
this.calculateReflections();
},
addTransient: function (position) {
var trans = {};
trans.position = position;
trans.timeAlive = 0;
trans.lifeTime = 0.2;
trans.strength = 0.3;
trans.exponent = 200;
this.transients.push(trans);
},
processTransients: function () {
for (var i = 0; i < this.transients.length; i++) {
var trans = this.transients[i];
var amplitude = trans.strength * Math.pow(2, -trans.exponent * trans.timeAlive);
this.R[trans.position] += amplitude / 2;
this.L[trans.position] += amplitude / 2;
trans.timeAlive += 1.0 / (sampleRate * 2);
}
for (var i = this.transients.length - 1; i >= 0; i--) {
var trans = this.transients[i];
if (trans.timeAlive > trans.lifeTime) {
this.transients.splice(i, 1);
}
}
},
};
AudioSystem.init();
Glottis.init();
Tract.init();
/**
* Helper used to replace code in a script tag based on a search regex.
* To inject code without erasing original string, using capturing groups; e.g.
* ```js
* inject(/(some string)/,'injected before $1 injected after');
* ```
* @param searcher Regex to search and replace
* @param replacer Replacer string/fn
*/
function inject$1(searcher, replacer) {
// find the relevant script tag
var scriptTags = document.getElementsByTagName('script');
var scriptTag;
var code = '';
for (var i = 0; i < scriptTags.length; ++i) {
scriptTag = scriptTags[i];
if (!scriptTag.textContent)
continue;
var matchesSearch = scriptTag.textContent.search(searcher) !== -1;
var isCurrentScript = scriptTag === document.currentScript;
if (matchesSearch && !isCurrentScript) {
code = scriptTag.textContent;
break;
}
}
// error-handling
if (!code || !scriptTag) {
throw new Error('Couldn\'t find "' + searcher + '" in script tags');
}
// modify the content
code = code.replace(searcher, replacer);
// replace the old script tag with a new one using our modified code
var newScriptTag = document.createElement('script');
newScriptTag.textContent = code;
scriptTag.insertAdjacentElement('afterend', newScriptTag);
scriptTag.remove();
}
/**
* Helper for getting an array with unique elements
* @param {Array} array Original array
* @return {Array} Copy of array, excluding duplicates
*/
function unique(array) {
return array.filter(function (item, idx) {
return array.indexOf(item) === idx;
});
}
// Ex: inject(/(names.sprite.set\( name, id \);)/, '$1console.dir(names)');
/** test */
function kitsyInject(searcher, replacer) {
if (!kitsy.queuedInjectScripts.some(function (script) {
return searcher.toString() === script.searcher.toString() && replacer === script.replacer;
})) {
kitsy.queuedInjectScripts.push({
searcher: searcher,
replacer: replacer,
});
}
else {
console.warn('Ignored duplicate inject');
}
}
// Ex: before('load_game', function run() { alert('Loading!'); });
// before('show_text', function run(text) { return text.toUpperCase(); });
// before('show_text', function run(text, done) { done(text.toUpperCase()); });
function before$1(targetFuncName, beforeFn) {
kitsy.queuedBeforeScripts[targetFuncName] = kitsy.queuedBeforeScripts[targetFuncName] || [];
kitsy.queuedBeforeScripts[targetFuncName].push(beforeFn);
}
// Ex: after('load_game', function run() { alert('Loaded!'); });
function after$1(targetFuncName, afterFn) {
kitsy.queuedAfterScripts[targetFuncName] = kitsy.queuedAfterScripts[targetFuncName] || [];
kitsy.queuedAfterScripts[targetFuncName].push(afterFn);
}
function applyInjects() {
kitsy.queuedInjectScripts.forEach(function (injectScript) {
inject$1(injectScript.searcher, injectScript.replacer);
});
}
function applyHooks(root) {
var allHooks = unique(Object.keys(kitsy.queuedBeforeScripts).concat(Object.keys(kitsy.queuedAfterScripts)));
allHooks.forEach(applyHook.bind(this, root || window));
}
function applyHook(root, functionName) {
var functionNameSegments = functionName.split('.');
var obj = root;
while (functionNameSegments.length > 1) {
obj = obj[functionNameSegments.shift()];
}
var lastSegment = functionNameSegments[0];
var superFn = obj[lastSegment];
var superFnLength = superFn ? superFn.length : 0;
var functions = [];
// start with befores
functions = functions.concat(kitsy.queuedBeforeScripts[functionName] || []);
// then original
if (superFn) {
functions.push(superFn);
}
// then afters
functions = functions.concat(kitsy.queuedAfterScripts[functionName] || []);
// overwrite original with one which will call each in order
obj[lastSegment] = function () {
var returnVal;
var args = [].slice.call(arguments);
var i = 0;
function runBefore() {
// All outta functions? Finish
if (i === functions.length) {
return returnVal;
}
// Update args if provided.
if (arguments.length > 0) {
args = [].slice.call(arguments);
}
if (functions[i].length > superFnLength) {
// Assume funcs that accept more args than the original are
// async and accept a callback as an additional argument.
return functions[i++].apply(this, args.concat(runBefore.bind(this)));
}
// run synchronously
returnVal = functions[i++].apply(this, args);
if (returnVal && returnVal.length) {
args = returnVal;
}
return runBefore.apply(this, args);
}
return runBefore.apply(this, arguments);
};
}
/**
@file kitsy-script-toolkit
@summary Monkey-patching toolkit to make it easier and cleaner to run code before and after functions or to inject new code into script tags
@license WTFPL (do WTF you want)
@author Original by mildmojo; modified by Sean S. LeBlanc
@version 22.1.0
@requires Bitsy 8.12
*/
var kitsy = (window.kitsy = window.kitsy || {
queuedInjectScripts: [],
queuedBeforeScripts: {},
queuedAfterScripts: {},
inject: kitsyInject,
before: before$1,
after: after$1,
/**
* Applies all queued `inject` calls.
*
* An object that instantiates an class modified via injection will still refer to the original class,
* so make sure to reinitialize globals that refer to injected scripts before calling `applyHooks`.
*/
applyInjects,
/** Apples all queued `before`/`after` calls. */
applyHooks,
});
// Rewrite custom functions' parentheses to curly braces for Bitsy's
// interpreter. Unescape escaped parentheticals, too.
function convertDialogTags(input, tag) {
return input.replace(new RegExp('\\\\?\\((' + tag + '(\\s+(".*?"|.+?))?)\\\\?\\)', 'g'), function (match, group) {
if (match.substr(0, 1) === '\\') {
return '(' + group + ')'; // Rewrite \(tag "..."|...\) to (tag "..."|...)
}
return '{' + group + '}'; // Rewrite (tag "..."|...) to {tag "..."|...}
});
}
var hooked = kitsy.hooked;
if (!hooked) {
kitsy.hooked = true;
var oldStartFunc = bitsy.startExportedGame;
bitsy.startExportedGame = function doAllInjections() {
// Only do this once.
bitsy.startExportedGame = oldStartFunc;
// Rewrite scripts
kitsy.applyInjects();
// recreate the script and dialog objects so that they'll be
// referencing the code with injections instead of the original
bitsy.scriptModule = new bitsy.Script();
bitsy.scriptInterpreter = bitsy.scriptModule.CreateInterpreter();
bitsy.dialogModule = new bitsy.Dialog();
bitsy.dialogRenderer = bitsy.dialogModule.CreateRenderer();
bitsy.dialogBuffer = bitsy.dialogModule.CreateBuffer();
bitsy.renderer = new bitsy.TileRenderer(bitsy.tilesize);
bitsy.transition = new bitsy.TransitionManager();
// Hook everything
kitsy.applyHooks();
// Start the game
bitsy.startExportedGame.apply(this, arguments);
};
}
/** @see kitsy.inject */
var inject = kitsy.inject;
/** @see kitsy.before */
var before = kitsy.before;
/** @see kitsy.after */
var after = kitsy.after;
function addDialogFunction(tag, fn) {
kitsy.dialogFunctions = kitsy.dialogFunctions || {};
if (kitsy.dialogFunctions[tag]) {
console.warn('The dialog function "' + tag + '" already exists.');
return;
}
// Hook into game load and rewrite custom functions in game data to Bitsy format.
before('parseWorld', function (gameData) {
return [convertDialogTags(gameData, tag)];
});
kitsy.dialogFunctions[tag] = fn;
}
function injectDialogTag(tag, code) {
inject(/(var functionMap = \{\};[^]*?)(this.HasFunction)/m, '$1\nfunctionMap["' + tag + '"] = ' + code + ';\n$2');
}
/**
* Adds a custom dialog tag which executes the provided function.
* For ease-of-use with the bitsy editor, tags can be written as
* (tagname "parameters") in addition to the standard {tagname "parameters"}
*
* Function is executed immediately when the tag is reached.
*
* @param {string} tag Name of tag
* @param {Function} fn Function to execute, with signature `function(environment, parameters, onReturn){}`
* environment: provides access to SetVariable/GetVariable (among other things, see Environment in the bitsy source for more info)
* parameters: array containing parameters as string in first element (i.e. `parameters[0]`)
* onReturn: function to call with return value (just call `onReturn(null);` at the end of your function if your tag doesn't interact with the logic system)
*/
function addDialogTag(tag, fn) {
addDialogFunction(tag, fn);
injectDialogTag(tag, 'kitsy.dialogFunctions["' + tag + '"]');
}
/**
💬
@file dialog audio
@summary animal crossing-style audio
@license MIT
@author Sean S. LeBlanc
@version 22.1.0
@requires Bitsy 8.12
@description