-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
1818 lines (1649 loc) · 53.2 KB
/
script.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
//lucid.app/documents/embeddedchart/d9ac4c82-8cb8-43d2-bd67-c0f5438e2086
import * as THREE from "//cdn.skypack.dev/three@0.131.1/";
import { OrbitControls } from "//cdn.skypack.dev/three@0.131.1/examples/jsm/controls/OrbitControls.js";
import { OimoPhysics } from "//cdn.skypack.dev/three@0.131.1/examples/jsm/physics/OimoPhysics.js";
import { TWEEN } from "//cdn.skypack.dev/three@0.131.1/examples/jsm/libs/tween.module.min.js";
import { GUI } from "//cdn.skypack.dev/three@0.131.1/examples/jsm/libs/dat.gui.module.js";
import Stats from "//cdn.skypack.dev/three@0.131.1/examples/jsm/libs/stats.module.js";
import { Perlin, FBM } from "//assets.codepen.io/697675/three-noise.js?v=131.1";
vis = {
cfg: {
demo: true,
shield: 0,
type: "oscillator",
axis: "z",
bands: { sub: 3, max: 3 },
//style
intensity: 1,
primary: { hex: "#4040c0" },
accents: { hex: "#c04040" },
loss: 5,
//music
delay: 5,
iso: 15 / 128
},
var: {
frame: 1,
time: { start: null, delta: [], tweens: {} },
resolution: (window.innerWidth + window.innerHeight) / 2,
freqPeak: [],
PATH: {
width: 10,
min: 0.4,
axis: null,
type: null,
freqBand: {},
freqPeak: {},
doRadial: function (seg, tot, freq = 1, seed = 0) {
seg += 1;
let PI = Math.PI;
// total angle
let angle = (2 * PI) / tot;
let m = angle * seg;
// position offsets, primary
let dist = (vis.var.PATH.width + vis.var.PATH.min * freq) / 2;
let x = Math.cos(m + seed * 360) * dist;
let z = Math.sin(m + seed * 360) * dist;
// rotation radians, secondary
let deg = (seg / tot) * 360;
let rad = deg * (PI / 180);
// clockwise from (-5,0)
return { x: -x, z: -z || 15, rad: -rad };
// note: radial amplitude affects directionality
}
}
},
mat: function material(opts = {}) {
// material performance
let type = [
"MeshStandardMaterial",
"MeshStandardMaterial",
"MeshStandardMaterial",
"MeshPhongMaterial",
"MeshPhongMaterial"
][vis.cfg.loss - 1];
if (opts.type) {
// force type (MeshBasicMaterial)
type = opts.type;
}
// type-specific
opts.roughness = opts.roughness || 0.5;
opts.metalness = opts.metalness || 0.66;
opts.shininess = opts.shininess || 150;
// core
let mat = new THREE[type]({
color: opts.color || vis.cfg.primary.col,
side: opts.side || THREE.FrontSide,
shadowSide: opts.shadowSide || THREE.BackSide,
userData: opts
});
mat.color.convertSRGBToLinear();
// mesh-specific
for (let key in opts) {
if (mat.hasOwnProperty(key)) {
mat[key] = opts[key];
}
}
return mat;
//www.donmccurdy.com/2020/06/17/color-management-in-threejs/
},
three: async function () {
//github.com/lo-th/Oimo.js/
//codepen.io/ste-vg/pen/BazEQbY
let vars = vis.var;
const physics = (vars.physics = await OimoPhysics());
// COMMON
const PI = Math.PI;
// color
vis.cfg.primary.col = new THREE.Color(
vis.cfg.primary.hex
).convertSRGBToLinear();
vis.cfg.accents.col = new THREE.Color(
vis.cfg.accents.hex
).convertSRGBToLinear();
// material
vis.cfg.primary.mat = vis.mat({
color: vis.cfg.primary.col,
flatShading: true
});
vis.cfg.accents.mat = vis.mat({
color: vis.cfg.accents.col,
flatShading: true
});
// SCENE
const scene = (vars.scene = new THREE.Scene());
const environ = (vars.environ = new THREE.Group());
environ.name = "environ";
scene.add(environ);
// camera group: camera mount, camera proper, local axis, orbit target
vars.camera = new THREE.PerspectiveCamera(
45,
window.innerWidth / window.innerHeight,
0.01,
120
);
vars.camera.position.set(0, 1, 15);
scene.add(vars.camera);
// camera orbit target
let mount = new THREE.Group();
let orbit = new THREE.Object3D();
orbit.position.z = vars.PATH.width;
vars.camera.userData = {
mount: mount,
orbit: orbit
};
mount.add(orbit);
scene.add(mount);
// catmull render texture (fractal)
vars.renderCatmull = new THREE.WebGLRenderTarget(256, 256);
const cameraCatmull = new THREE.OrthographicCamera(-15, 15, 15, -15, 1, 20);
cameraCatmull.name = "catmull frame";
cameraCatmull.position.set(0, -90, 0);
cameraCatmull.lookAt(0, -100, 0);
vars.cameraCatmull = cameraCatmull;
scene.add(cameraCatmull);
// catmull materials
vars.matCatmullL = vis.mat({
color: vis.cfg.accents.col,
type: "LineBasicMaterial"
});
vars.matCatmullM = vis.mat({
color: vis.cfg.accents.col,
type: "MeshBasicMaterial",
side: THREE.BackSide
});
let maskFractal = vis.mat({
color: vis.cfg.accents.col,
map: vis.var.renderCatmull.texture,
transparent: true,
alphaTest: 1,
side: THREE.DoubleSide,
blending: THREE.AdditiveBlending, //THREE.AdditiveBlending
emissive: vis.cfg.primary.col,
emissiveIntensity: 0.125
});
vars.matCatmullT = maskFractal;
// center
//var box = new THREE.Box3().setFromObject( mesh );
//box.center( mesh.position ); // this re-sets the mesh position
//mesh.position.multiplyScalar( - 1 );
//
const renderer = (vars.renderer = new THREE.WebGLRenderer({
antialias: true
//precision: "mediump", // lowp washed-out
}));
renderer.outputEncoding = THREE.sRGBEncoding;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.setPixelRatio(window.devicePixelRatio / vis.cfg.loss);
renderer.setSize(window.innerWidth, window.innerHeight);
const axesHelper = new THREE.AxesHelper(10);
scene.add(axesHelper);
// MATERIALS
const glass = vis.mat({
transparent: true,
opacity: 0.25,
specular: vis.cfg.primary.col,
flatShading: true,
shininess: 50,
depthWrite: false // no artifact
});
// RENDER TEXTURE MIDI PORTAL
//threejs.org/examples/webgl_rtt.html
vars.renderMIDI = new THREE.WebGLRenderTarget(256, 256, {
magFilter: THREE.NearestFilter,
minFilter: THREE.NearestFilter
});
// portal scene
const sceneMIDI = (vars.sceneMIDI = new THREE.Scene());
sceneMIDI.add(vars.camera);
const light = new THREE.AmbientLight(0xffffff, 40);
sceneMIDI.add(light);
// MIDI notes InstancedMesh
let iso = new THREE.PlaneGeometry(1, 1);
iso.translate(0, 1, 0); // pivot rotation
let midi = (vars.midiNote = new THREE.InstancedMesh(
iso,
vis.mat({
// fastest flat-shade
type: "MeshBasicMaterial",
depthTest: false
}),
Math.floor(vars.resolution / 8) * 5
//128 * vis.cfg.delay // max count is 128 keys * ~5 seconds
));
midi.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
midi.userData.dummy = new THREE.Object3D();
midi.name = "MIDI note";
sceneMIDI.add(midi);
// LIGHTS
// frontal accent (audio range color)
const near = new THREE.PointLight(vis.cfg.accents.col, 16, 20, 2);
near.position.set(0, 5, 10);
near.name = "near";
// direct drama (audio room shadow)
const far = new THREE.PointLight(vis.cfg.primary.col, 8, 25, 2);
far.position.set(0, 5, 10);
far.castShadow = true;
far.name = "far";
// low fill (falling peak shadow)
const low = new THREE.PointLight(vis.cfg.accents.col, 32, 30, 2);
low.position.set(0, -10, 5);
low.castShadow = true;
low.name = "low";
// shadow sizes
far.shadow.mapSize = low.shadow.mapSize = new THREE.Vector2(128, 128);
environ.add(near, far, low);
// OBJECTS
// environment audio...
const plane = new THREE.PlaneGeometry(40, 40, 20, 20);
plane.attributes.position.setUsage(THREE.DynamicDrawUsage);
const sky = new THREE.Mesh(
plane,
vis.mat({
flatShading: false
})
);
sky.userData = {
position: sky.geometry.attributes.position.clone(),
normal: sky.geometry.attributes.normal.clone()
};
sky.name = "audio_hi";
sky.position.y = 12.5;
sky.rotation.x = 0.5 * PI;
sky.receiveShadow = true;
const sphere = new THREE.IcosahedronGeometry(20, 3);
sphere.attributes.position.setUsage(THREE.DynamicDrawUsage);
const skyBox = new THREE.Mesh(
sphere,
vis.mat({
side: THREE.BackSide,
shininess: 500,
roughness: 0.25,
flatShading: true
})
);
skyBox.userData = {
position: skyBox.geometry.attributes.position.clone(),
normal: skyBox.geometry.attributes.normal.clone()
};
skyBox.name = "audio_lo";
skyBox.receiveShadow = true;
environ.add(sky, skyBox);
// floor...
const floorL = new THREE.Mesh(new THREE.BoxGeometry(25, 0.2, 25), glass);
floorL.name = "floor_sleep";
floorL.position.y = -5;
floorL.rotation.y = -PI / 4;
floorL.receiveShadow = true;
environ.add(floorL);
physics.addMesh(floorL, 0);
const floorF = new THREE.Mesh(
new THREE.BoxGeometry(10, 0.2, 40),
vis.mat()
);
floorF.name = "floor_solid";
floorF.position.z = -20;
floorF.castShadow = true;
floorF.receiveShadow = true;
environ.add(floorF);
physics.addMesh(floorF, 0);
const floorN = new THREE.Mesh(new THREE.BoxGeometry(10, 0.2, 40), glass);
floorN.name = "floor_glass";
floorN.position.z = 20;
//floorN.castShadow = true;
floorN.receiveShadow = true;
environ.add(floorN);
physics.addMesh(floorN, 0);
const base = new THREE.Mesh(new THREE.BoxGeometry(10, 0.8, 1.2), vis.mat());
base.name = "floor_origin";
base.castShadow = true;
base.receiveShadow = true;
environ.add(base);
physics.addMesh(base, 0);
// portal...
const ring = new THREE.RingGeometry(0, 10, 6, 1, 0, PI * 2);
const portalRT = new THREE.Mesh(
ring,
vis.mat({
map: vars.renderMIDI.texture,
alphaTest: 0.25,
emissive: vis.cfg.primary.col,
emissiveIntensity: 0.125
})
);
portalRT.name = "portal_render";
const portalGlass = new THREE.Mesh(ring, glass);
portalGlass.name = "portal_glass";
portalRT.position.z = portalGlass.position.z = -15;
environ.add(portalRT, portalGlass);
// shield...
const icon = vis.mat({
transparent: true,
opacity: 0.25,
side: THREE.DoubleSide,
alphaMap: new THREE.TextureLoader().load(
"//assets.codepen.io/697675/shield_mask.png"
)
});
icon.alphaMap.minFilter = icon.alphaMap.magFilter = THREE.NearestFilter;
const shield = new THREE.Mesh(new THREE.PlaneGeometry(10, 10), icon);
shield.name = "shield";
shield.geometry.rotateX(-PI / 2);
environ.add(shield);
const shieldHit = new THREE.Mesh(
new THREE.BoxGeometry(10, 5, 5),
vis.mat({
visible: false,
wireframe: true,
type: "MeshBasicMaterial"
})
);
shieldHit.name = "shield_hit";
environ.add(shieldHit);
physics.addMesh(shieldHit, 1e6);
// BANDS, PEAKS
vis.fpath(true, {
name: "freqBand"
});
vis.fpath(true, {
name: "freqPeak",
axis: "x"
});
// BEATS MIDI
const beats = (vars.midiBeat = new THREE.InstancedMesh(
new THREE.BoxGeometry(vars.PATH.min, vars.PATH.min, vars.PATH.min),
vis.cfg.primary.mat,
8
));
beats.userData = {
idx: [],
dummy: new THREE.Object3D(),
color: vis.cfg.primary.col.clone()
};
for (let i = beats.count; i--; ) {
beats.setColorAt(i, beats.userData.color);
beats.userData.idx[i] = {
note: {},
dummy: new THREE.Object3D()
};
}
beats.instanceColor.needsUpdate = true;
beats.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
//
//beats.castShadow = true;
beats.name = "MIDI beat";
vars.scene.add(beats);
beats.count = 0;
// OUTPUT
document.body.appendChild(renderer.domElement);
vis.stats = new Stats();
document.body.appendChild(vis.stats.dom);
vis.gui.controllers = vis.gui.create(vis.cfg);
//camera range limits
let controls = (vars.controls = new OrbitControls(
vars.camera,
renderer.domElement
));
// limits
controls.enablePan = false;
controls.minDistance = 10;
controls.maxDistance = 25;
controls.minPolarAngle = 0;
controls.maxPolarAngle = PI / 1.75;
controls.minAzimuthAngle = -PI / 3;
controls.maxAzimuthAngle = PI / 3;
controls.update();
vis.render(performance.now());
// EVENT LISTENERS
let optEL = {
capture: true,
passive: true
};
let resizeTimer;
vis.ux.resize = function () {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(function () {
let width = window.innerWidth,
height = window.innerHeight;
vars.camera.aspect = width / height;
vars.camera.updateProjectionMatrix();
vars.renderer.setSize(width, height);
// res contributes to performance
vars.resolution = (width + height) / 2;
}, 250);
};
window.addEventListener("resize", vis.ux.resize, optEL);
document.addEventListener("mousemove", vis.ux.pointer, optEL);
document
.getElementById("webaudio")
.addEventListener("click", vis.WA.button, optEL);
document
.getElementById("midiFile")
.addEventListener("change", vis.MM.button, optEL);
document
.getElementById("playback")
.addEventListener("click", vis.MM.playback, optEL);
},
fpath: function (arg, opts = {}) {
// arg valid: false, power, axis, type...
let power = typeof arg == "number" ? arg : false;
let o = opts.o ? opts.o : { x: 0, y: 0, z: 0 };
// the primary axis central to visuals
let PATH = vis.var.PATH;
let axis = opts.axis || vis.cfg.axis;
PATH.type = vis.cfg.type;
PATH.axis = vis.cfg.axis;
// arg==power ? fun blocks : intial max/sub || type/axis select
let label = power !== false ? "freqPeak" : opts.name || "freqBand";
//console.log(arg, power, label, opts.name)
let coord = [];
let key = PATH[label];
key.name = opts.name = label;
// instancedMesh
// fun blocks or max
let pSource = power ? power : vis.cfg.bands.max;
key.count = Math.pow(2, pSource);
key.mass = label == "freqBand" ? 0 : 100;
key.width = PATH.width / key.count;
key.depth = 1;
// tertiary animation
if (label == "freqBand" && axis != "x") {
key.depth = key.count;
if (axis == "z" && PATH.type == "spectrum") {
key.depth = key.count / 2;
key.count = key.count * 2;
}
}
// PLOT COORDS
let idx = 0,
tot = key.count * key.depth;
for (let i = 0, iL = key.depth; i < iL; i++) {
for (let j = 0, jL = key.count; j < jL; j++) {
let prc = +(j / key.count).toFixed(3);
let dummy = new THREE.Object3D();
//position, centered
let m = 0;
if (axis == "x") {
// type spectrum: frequency analyzer (1d)
// type oscillator: linear oscillator (1d)
dummy.position.x = key.width * j;
dummy.position.x -= (PATH.width - key.width) / 2;
} else if (axis == "y") {
// type spectrum: grid spectrograph (2d)
// type oscillator: radial fractal (2d)
if (PATH.type == "oscillator") {
let rot = PATH.doRadial(idx, tot);
dummy.position.x = rot.x;
dummy.position.z = rot.z;
dummy.rotation.y = rot.rad;
// chance of alternate style
if (vis.var.frame % 2 == 0) {
prc = +(idx / tot).toFixed(3);
}
} else if (PATH.type == "spectrum") {
dummy.position.x = key.width * j;
dummy.position.x -= (PATH.width - key.width) / 2;
dummy.position.z = i * -PATH.freqBand.width;
}
} else if (axis == "z") {
// starfield, path runner
// turn 90-deg for square
dummy.rotation.z += Math.PI / 2;
if (PATH.type == "oscillator") {
// scale
//dummy.scale.set(0.25, 20, 20);
let rot = PATH.doRadial(Math.floor(idx / key.count), key.count);
// position, nearly 0 fills gap but vector permits scale
//dummy.position.set(0, 0, 0)
dummy.position.x = rot.x / PATH.width;
dummy.position.z = rot.z / PATH.width;
//dummy.position.x = 0;
//dummy.position.z = 0;
// rotation
dummy.rotation.y = rot.rad;
// corner at center
dummy.rotation.y += Math.PI / 4;
} else if (PATH.type == "spectrum") {
let factor = 6;
let mid = key.count / 4;
function quad(int) {
return int % mid;
}
// scale
//dummy.scale.set(0.25, 20, 20);
// x-pos, centered
dummy.position.x = key.width * quad(j);
dummy.position.x -= PATH.freqBand.width / 2 + key.width;
// z-pos, centered
dummy.position.z = -PATH.freqBand.width * Math.floor(j / key.depth);
dummy.position.z += PATH.freqBand.width / 2 + key.width;
// y-pos, halfpipe
let jMid = quad(j) < mid / 2 ? 0 : 1;
let halfpipe = Math.abs(mid / 2 - (quad(j) + jMid));
dummy.position.y = (halfpipe * factor) / 2;
dummy.rotation.z +=
-(Math.PI / 16) * (halfpipe + 1) * (jMid ? -1 : 1);
// position multiple
dummy.position.multiply(new THREE.Vector3(factor, 1, factor));
dummy.position.y -= 10;
}
}
// output
let offset = new THREE.Vector3(o.x, o.y, o.z);
dummy.position.add(offset);
dummy.updateMatrix();
if (coord[i] == undefined) {
coord[i] = [];
}
coord[i][j] = {
proto: dummy,
m: m,
prc: prc
};
idx++;
}
}
coord = coord.flat();
key.coords = coord;
if (typeof arg == "string") {
// mesh reset for axis/type change
opts.reset = true;
}
vis.fmesh(power, opts);
},
fmesh: function (power, opts = {}) {
let vars = vis.var;
let instancedMesh;
let PATHs =
opts.name == "freqBand" ? vars.PATH.freqBand : vars.PATH.freqPeak;
if(opts.name == "freqPeak" && vars.freqPeak.length >= 4){return}
if (!opts.reset) {
// create instancedMesh to limit
const box = new THREE.BoxGeometry(
PATHs.width,
vars.PATH.min,
vars.PATH.min
);
instancedMesh = new THREE.InstancedMesh(
box,
vis.cfg.accents.mat,
PATHs.count * PATHs.depth
);
instancedMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
instancedMesh.name = PATHs.name;
instancedMesh.castShadow = true;
} else {
instancedMesh = vars.freqBand;
}
let len = PATHs.depth * PATHs.count;
if (opts.name == "freqBand") {
// reset custom properties, timeline
instancedMesh.position.set(0, 0, 0);
instancedMesh.userData.depth = 0;
instancedMesh.count = len;
if (vars.PATH.axis == "z") {
//random blend mode
let blend = [
THREE.AdditiveBlending,
THREE.SubtractiveBlending,
THREE.MultiplyBlending
];
vars.matCatmullT.blending =
blend[Math.floor(Math.random() * blend.length)];
// material no sides, no shadow
instancedMesh.material = [vars.matCatmullT, null];
instancedMesh.castShadow = false;
// staging assets
if (vars.PATH.type == "oscillator") {
instancedMesh.position.set(0, -20, -5);
}
} else {
instancedMesh.material = vis.cfg.accents.mat;
instancedMesh.castShadow = true;
}
}
// loop instancedMesh from PATH dummy, set color
let hue = vis.cfg.accents.col.clone();
let hues = [
hue.clone().multiplyScalar(0.33),
hue.clone().multiplyScalar(0.66)
];
instancedMesh.userData.dummy = [];
while (len--) {
let coord = PATHs.coords[len];
if (PATHs.name == "freqBand") {
instancedMesh.userData.dummy[len] = coord.proto;
}
// color bass/treble
let hue = coord.prc < 0.5 ? hues[0] : hues[1];
instancedMesh.setMatrixAt(len, coord.proto.matrix);
instancedMesh.setColorAt(len, hue);
}
instancedMesh.instanceColor.needsUpdate = true;
instancedMesh.instanceMatrix.needsUpdate = true;
// output mesh, physics
if (PATHs.name == "freqPeak") {
vars[PATHs.name].push(instancedMesh);
vars.physics.addMesh(instancedMesh, PATHs.mass);
} else {
vars[PATHs.name] = instancedMesh;
}
vars.scene.add(instancedMesh);
// mesh animation params
//instancedMesh.userData.depth = 0; // internal timeline
//instancedMesh.userData.origin = true; // transition state
},
fwave: function (vars, bpf) {
// PATH
const PATH = vars.PATH;
const type = PATH.type,
axis = PATH.axis;
const max = PATH.freqBand;
// instancedMesh
const bands = vars.freqBand,
peaks = vars.freqPeak[0];
// accumulate
let pL = 0;
let freq = [];
let catmullRom = [];
// yOsc to 180-deg in 2s at 60fps
let t = 60 * 2;
const seed = (1e-3 + ((vars.frame / t) % t)) / t;
// depth cycle
let userData = bands.userData;
if (userData.depth >= max.depth) {
userData.depth = 0;
}
// count loop
let i = userData.depth * max.count;
let iL = i + max.count;
if ((axis == "y" && type == "oscillator") || axis == "z") {
if (axis == "z") {
i = 0;
}
iL = max.coords.length;
}
// transform PATH dummy(s) by type/axis with WebAudio
for (; i < iL; i++) {
let coords = max.coords[i];
// dummy transform, compound or simple
let cumulate = axis == "y" && type == "oscillator";
let dummy = cumulate ? coords.proto : coords.proto.clone();
// WebAudio analyser
let data = vis.WA.analyser.data;
let frequency =
data[Math.floor((data.length - 1) * coords.prc)];
freq.push(frequency);
frequency = (frequency / 256 / 2) * 100;
// y-oscillator
let rot = PATH.doRadial(i, max.coords.length, frequency, seed);
// TRANSFORM BANDS
let dPos = dummy.position;
if (axis != "z") {
// cumulate z could be lerped, yet only y-oscillator uses
dummy.scale.set(1, 1, 1);
// position
if (type == "oscillator") {
if (axis == "x") {
dPos.y = (PATH.min / 2) * frequency;
} else if (axis == "y") {
dPos.x = rot.x;
dPos.z = rot.z;
dPos.y = 0;
}
}
// rotation
if (axis == "y" && type == "oscillator") {
//let last = dummy.rotation.y;
dummy.rotateY(-(6.28319 / 60 / 4));
}
// scale
if (type == "spectrum") {
dummy.scale.y = 1 + frequency;
}
} else {
// secondary animation param (userData.depth)
let nFreq = freq[i] / 256,
nDepth = 0;
if (type == "spectrum") {
dummy.scale.set(0.25, 8, 8);
nDepth = Math.floor(i / max.count) / max.depth;
let fScale = nFreq * nDepth;
let orbit = new THREE.Vector3();
vars.camera.userData.orbit.getWorldPosition(orbit);
// chase camera position and scale tier
dPos.lerp(orbit, fScale*1.33);
dummy.rotateY((-Math.PI / 4) * nDepth);
dummy.rotateX((-Math.PI / 8) * nDepth);
dummy.scale.y *= 1 + (fScale*4);
dummy.scale.z *= 1 + (fScale*4);
} else if (type == "oscillator") {
dummy.scale.set(0.25, 80, 80);
nDepth = (i % max.count) / max.count;
// starburst or fractal
let fractal = dPos.clone();
fractal.multiply(new THREE.Vector3(1 + nFreq, 1, 1 + nFreq));
dPos.lerp(fractal, 0.5);
dummy.rotateZ((-Math.PI / 2) * nDepth);
dummy.scale.multiplyScalar(1 + nFreq);
}
//dummy.position.y += nDepth / 64;
//if (!userData.origin) {
// // halfpipe
//} else {
// // fractal
//}
let hue = vis.cfg.primary.col.clone();
hue.offsetHSL(nFreq, 0, nFreq);
bands.setColorAt(i, hue);
}
// UPDATE BANDS
dummy.updateMatrix();
bands.setMatrixAt(i, dummy.matrix);
//bands.userData.dummy[i].copy(dummy);
// catmull
let cPos = axis != "x" ? new THREE.Vector3(rot.x, rot.z, 0) : dPos;
catmullRom.push(cPos);
// TRANSFORM PEAKS
if (peaks && axis != "z") {
let sub = PATH.freqPeak;
let iP = i;
// peaks (0-7) is some factor of bands (0-63)
let factor = true;
if (axis == "y") {
if (type == "spectrum") {
iP = pL;
} else if (type == "oscillator" && i % 8 != 0) {
factor = false;
}
}
if (pL < peaks.count && factor) {
//let hue = new THREE.Color();
//bands.getColorAt(i, hue);
//let p = Math.floor(i / sub.factor);
let _dummy = dummy.clone();
// frequency threshold
if (freq[iP] > bpf * 1.5) {
let posOff = frequency * (PATH.min / 2);
if (axis == "z") {
_dummy.position.z = posOff;
_dummy.rotation.set(0, 0, 0);
_dummy.scale.set(1, 0.5, 1);
} else {
_dummy.scale.set(1, 1, 1);
if (type == "oscillator") {
_dummy.scale.y = 2;
} else if (type == "spectrum") {
_dummy.position.y = posOff + PATH.min * 2;
}
if (axis == "y" && type == "oscillator") {
_dummy.scale.set(2, 2, 2);
} else {
_dummy.rotation.set(0, 0, 0);
}
}
// color freq exceed
//hue.multiplyScalar(1.5);
//peaks.setColorAt(pL, hue);
}
// color freq normal
//peaks.setColorAt(pL, hue);
// UPDATE PEAKS
_dummy.updateMatrix();
peaks.setMatrixAt(pL, _dummy.matrix);
vars.physics.setMeshPosition(peaks, _dummy.position, pL);
pL++;
}
}
}
bands.instanceMatrix.needsUpdate = true;
peaks.instanceMatrix.needsUpdate = true;
bands.instanceColor.needsUpdate = true;
// UPDATE CATMULL
let catmull = vars.freqCatmull;
if (catmull != undefined) {
// CatmullRom dispose
catmull.geometry.dispose();
catmull.removeFromParent();
catmull = null;
}
if (type == "oscillator" || axis == "z") {
// CatmullRom create, every frame
let spline = new THREE.CatmullRomCurve3(catmullRom);
spline.closed = axis != "x" ? true : false;
let points = spline.getPoints(64);
if (spline.closed) {
let shape = new THREE.Shape(points);
let geometry = new THREE.ShapeGeometry(shape);
catmull = new THREE.Mesh(geometry, vars.matCatmullM);
catmull.rotateX(1.5708);
if (axis == "z") {
catmull.position.y = -100;
}
} else {
let geometry = new THREE.BufferGeometry().setFromPoints(points);
// CatmullRom to scene
catmull = new THREE.Line(geometry, vars.matCatmullL);
}
catmull.position.y -= 0.01; // !flickr
vars.scene.add(catmull);
vars.freqCatmull = catmull;
}
// advance secondary iterator
if (vars.frame % 60 == 0) {
if (!(axis == "y" && type == "oscillator")) {
userData.depth++;
}
}
},
fnoise: function (timestamp, frequency, mesh, type) {
let geo = mesh.geometry;
const position = geo.attributes.position;
const normal = geo.attributes.normal;
const p = [];
for (let i = 0; i < position.count; i++) {
const pos = new THREE.Vector3().fromBufferAttribute(
mesh.userData.position,
i
);
const norm = new THREE.Vector3().fromBufferAttribute(
mesh.userData.normal,
i
);
const newPos = pos.clone();
pos.multiplyScalar(0.125);
pos.z += timestamp * 0.002;
const n = vis.WA.noise[type](pos) * frequency;
newPos.add(norm.multiplyScalar(n));
p.push(newPos);
}
position.copyVector3sArray(p);
geo.computeVertexNormals();
geo.attributes.position.needsUpdate = true;
},
midi: function (file) {
//hello-magenta.glitch.me/
let vars = vis.var;
let midi = vars.midiNote,
beats = vars.midiBeat;
let MM = vis.MM;
const iso = vis.cfg.iso;
const delay = vis.cfg.delay;
// create file or update notes
if (file) {
// reset magenta, idle...
vis.MM.playback("stop");
let sequence = mm.midiToSequenceProto(file);
let bins = (sequence.bins = []);
let last = false;
for (let i = sequence.notes.length; i--; ) {
let note = sequence.notes[i];
//en.wikipedia.org/wiki/File:GMStandardDrumMap.gif
note.isDrumBD = note.isDrum && (note.pitch == 35 || note.pitch == 36);
note.duration = note.endTime - note.startTime;
if (last == false) {
last = note;
}
let sequential = last.startTime >= note.startTime;
if (note.duration >= 15 || note.duration <= 0) {
//console.log("note error");
sequence.notes.splice(i, 1);
continue;
}
// bin notes for render performance