-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
1693 lines (1533 loc) · 52.1 KB
/
index.html
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
<html>
<head>
<title>hydro</title>
<style>
canvas {
position: fixed;
top: 0;
left: 0;
z-index: 0;
width: 100%;
height: 100%;
}
body {
margin: 0;
background: black;
overflow: auto;
height: 100%;
width: 100%;
}
.textarea-wrapper {
position: relative;
font-family: monospace;
display: flex;
}
.aligned {
margin: 0;
padding: 0;
position: absolute;
top: 0;
left: 0;
line-height: 1.3em;
overflow: hidden;
font-size: 20px;
width: 100%;
}
#code {
z-index: 2;
background-color: transparent;
border: 0;
outline: none;
resize: none;
color: white;
overflow: hidden;
height: 100%;
}
#highlighted-text {
color: transparent;
z-index: 1;
white-space: pre-wrap;
}
#highlighted-text > span {
background-color: #00000090;
}
</style>
</head>
<body>
<div class="textarea-wrapper">
<div id="highlighted-text" class="aligned"></div>
<textarea id="code" class="aligned" spellcheck="false"></textarea>
</div>
<canvas id="canvas"></canvas>
<script>
"use strict";
// what follows is a trimmed down version of kabelsalat/core
class Node {
constructor(type, value) {
this.type = type;
value !== undefined && (this.value = value);
this.ins = [];
}
}
function getNode(type, args, schema) {
const next = new Node(type);
next.schema = schema;
next.ins = args.map((arg) => parseInput(arg, next));
return next;
}
let register = (name, fn) => {
Node.prototype[name] = function (...args) {
return fn(this, ...args);
};
return fn;
};
let registerNode = (type, schema) =>
register(type, (...args) => getNode(type, args, schema));
let n = register("n", (value) => {
if (typeof value === "object") {
return value;
}
return new Node("n", value);
});
function parseInput(input, node) {
// array = sequence of floats, function = value setter function
if (Array.isArray(input) || typeof input === "function") {
const floatNode = float();
floatNode.value = input;
return floatNode;
}
if (typeof input === "object") {
return input;
}
if (typeof input === "number" && !isNaN(input)) {
return n(input);
}
if (typeof input === "string") {
return n(input);
}
console.log(
`invalid input type "${typeof input}" for node of type "${
node.type
}", falling back to 0. The input was:`,
input
);
return 0;
}
Node.prototype.apply = function (fn) {
return fn(this);
};
Node.prototype.dfs = function (fn, visited) {
return this.apply((node) => dfs(node, fn, visited));
};
let dfs = (node, fn, visited = []) => {
node = fn(node, visited);
visited.push(node);
node.ins = node.ins.map((input) => {
if (visited.includes(input)) {
return input;
}
return dfs(input, fn, visited);
});
return node;
};
// sort nodes by dependencies
function topoSort(graph) {
const sorted = [];
const visited = new Set();
function dfs(node) {
if (!(node instanceof Node) || visited.has(node)) {
return; // constant values or already visited nodes
}
visited.add(node);
for (let i in node.ins) {
dfs(node.ins[i]);
}
sorted.push(node);
}
dfs(graph);
return sorted;
}
function compile(node, options = {}) {
const { log = false, constType = "n", varPrefix = "n" } = options;
log && console.log("compile", node);
const nodes = topoSort(node);
let lines = [];
let v = (node) => {
if (node.type !== constType) {
const id = nodes.indexOf(node);
return `${varPrefix}${id}`;
}
if (typeof node.value === "string") {
return `"${node.value}"`;
}
return node.value;
};
for (let id in nodes) {
const node = nodes[id];
const vars = nodes[id].ins.map((inlet) => v(inlet));
const meta = {
vars,
node,
nodes,
id,
name: v(node),
};
if (node.schema && node.schema.compile) {
lines.push(node.schema.compile(meta));
}
}
const src = lines.join("\n");
if (log) {
console.log("compiled code:");
console.log(src);
}
return { src };
}
Node.prototype.compile = function (options) {
return compile(this, options);
};
//// Hydra specific logic
let glslNode = (functionName, schema) => {
if (!schema.type) {
throw new Error(`no "schema.type" set for node ${functionName}`);
}
if (!schema.args) {
throw new Error(`no "schema.args" set for node ${functionName}`);
}
return register(functionName, (...args) =>
getNode(functionName, schema.args(...args), {
compile: ({ vars, name }) =>
`${schema.type} ${name} = ${functionName}(${glslArgs(...vars)});`,
...schema,
})
);
};
let glslArgs = (...args) =>
args
.map((arg) => {
if (isNaN(Number(arg))) {
return arg;
}
if (Number.isInteger(Number(arg))) {
return arg + ".";
}
return arg;
})
.join(", ");
let _st = registerNode("_st", {
compile: ({ name }) => `vec2 ${name} = st;`,
});
let st = _st();
let _mouseX = registerNode("_mouseX", {
compile: ({ name }) => `float ${name} = iMouse.x;`,
});
let mouseX = _mouseX();
let _mouseY = registerNode("_mouseY", {
compile: ({ name }) => `float ${name} = iMouse.y;`,
});
let mouseY = _mouseY();
// SOURCES
let o0 = 0,
o1 = 1,
o2 = 2,
o3 = 3,
toRender = o0;
let render = (output = o0) => (toRender = output);
let _src = registerNode("src", {
compile: ({ vars, name }) => {
let tex = `tex${vars[1]}`;
return `vec4 ${name} = src(${glslArgs(vars[0])},${tex});`;
},
});
let src = register("src", (tex = o0) => {
if (typeof tex !== "number") {
// this is to avoid error when doing src(s0) atm
console.warn("src expects a number.. falling back to 0");
tex = 0;
}
return _src(st, tex);
});
// this allows using o0..o3 (=number) as texture inputs
let vec4 = (input) => (typeof input === "number" ? src(input) : input);
// this node is used to get a float in from the outside
// used for functions and sequences (Arrays)
let float = registerNode("float", {
compile: ({ vars, name, node }) => {
const uniformName = `float${node.id}`;
return `float ${name} = ${uniformName};`;
},
});
let _osc = registerNode("_osc", {
compile: ({ vars, name }) =>
`vec4 ${name} = osc(${glslArgs(...vars)});`,
});
let osc = register("osc", (freq = 60, sync = 0.1, offset = 0) =>
_osc(st, freq, sync, offset)
);
let _noise = registerNode("_noise", {
compile: ({ vars, name }) =>
`vec4 ${name} = noise(${glslArgs(...vars)});`,
});
let noise = register("noise", (scale = 10, offset = 0.1) =>
_noise(st, scale, offset)
);
let _voronoi = registerNode("_voronoi", {
compile: ({ vars, name }) =>
`vec4 ${name} = voronoi(${glslArgs(...vars)});`,
});
let voronoi = register(
"voronoi",
(scale = 5, speed = 0.3, blending = 0.3) =>
_voronoi(st, scale, speed, blending)
);
let _gradient = registerNode("_gradient", {
compile: ({ vars, name }) =>
`vec4 ${name} = gradient(${glslArgs(...vars)});`,
});
let gradient = register("gradient", (speed = 0) => _gradient(st, speed));
let _shape = registerNode("_shape", {
compile: ({ vars, name }) =>
`vec4 ${name} = shape(${glslArgs(...vars)});`,
});
let shape = register(
"shape",
(sides = 3, radius = 0.3, smoothing = 0.01) =>
_shape(st, sides, radius, smoothing)
);
let _solid = registerNode("_solid", {
compile: ({ vars, name }) =>
`vec4 ${name} = solid(${glslArgs(...vars)});`,
});
let solid = register("solid", (r = 0, g = 0, b = 0, a = 1) =>
_solid(st, r, g, b, a)
);
let outputs = { [o0]: solid() };
// GEOMETRY
function editGeometry(input, fn) {
// we need to edit all _st nodes in all parents
input.dfs((node, visited) => {
if (node.ins[0]?.type === "_st") {
node.ins[0] = fn(node.ins[0]);
visited.push(node.ins[0]); // prevents inifinite loop
}
return node;
});
return input;
}
let _rotate = registerNode("_rotate", {
compile: ({ vars, name }) =>
`vec2 ${name} = rotate(${glslArgs(...vars)});`,
});
let rotate = register("rotate", (input, angle = 10, speed = 0) =>
editGeometry(input, (st) => st._rotate(angle, speed))
);
let _scale = registerNode("_scale", {
compile: ({ vars, name }) =>
`vec2 ${name} = scale(${glslArgs(...vars)});`,
});
let scale = register(
"scale",
(
input,
amount = 1.5,
xMult = 1,
yMult = 1,
offsetX = 0.5,
offsetY = 0.5
) =>
editGeometry(input, (st) =>
st._scale(amount, xMult, yMult, offsetX, offsetY)
)
);
let _pixelate = registerNode("_pixelate", {
compile: ({ vars, name }) =>
`vec2 ${name} = pixelate(${glslArgs(...vars)});`,
});
let pixelate = register("pixelate", (input, pixelX = 20, pixelY = 20) =>
editGeometry(input, (st) => st._pixelate(pixelX, pixelY))
);
let _repeat = registerNode("_repeat", {
compile: ({ vars, name }) =>
`vec2 ${name} = repeat(${glslArgs(...vars)});`,
});
let repeat = register(
"repeat",
(input, repeatX = 3, repeatY = 3, offsetX = 0, offsetY = 0) =>
editGeometry(input, (st) =>
st._repeat(repeatX, repeatY, offsetX, offsetY)
)
);
let _repeatX = registerNode("_repeatX", {
compile: ({ vars, name }) =>
`vec2 ${name} = repeatX(${glslArgs(...vars)});`,
});
let repeatX = register("repeatX", (input, reps = 3, offset = 0) =>
editGeometry(input, (st) => st._repeatX(reps, offset))
);
let _repeatY = registerNode("_repeatY", {
compile: ({ vars, name }) =>
`vec2 ${name} = repeatY(${glslArgs(...vars)});`,
});
let repeatY = register("repeatY", (input, reps = 3, offset = 0) =>
editGeometry(input, (st) => st._repeatY(reps, offset))
);
let _kaleid = registerNode("_kaleid", {
compile: ({ vars, name }) =>
`vec2 ${name} = kaleid(${glslArgs(...vars)});`,
});
let kaleid = register("kaleid", (input, nSides = 4) =>
editGeometry(input, (st) => st._kaleid(nSides))
);
let _scroll = registerNode("_scroll", {
compile: ({ vars, name }) =>
`vec2 ${name} = scroll(${glslArgs(...vars)});`,
});
let scroll = register(
"scroll",
(input, scrollX = 0.5, scrollY = 0.5, speedX = 0, speedY = 0) =>
editGeometry(input, (st) =>
st._scroll(scrollX, scrollY, speedX, speedY)
)
);
let _scrollX = registerNode("_scrollX", {
compile: ({ vars, name }) =>
`vec2 ${name} = scrollX(${glslArgs(...vars)});`,
});
let scrollX = register("scrollX", (input, scroll = 0.5, speed = 0) =>
editGeometry(input, (st) => st._scrollX(scroll, speed))
);
let _scrollY = registerNode("_scrollY", {
compile: ({ vars, name }) =>
`vec2 ${name} = scrollY(${glslArgs(...vars)});`,
});
let scrollY = register("scrollY", (input, scroll = 0.5, speed = 0) =>
editGeometry(input, (st) => st._scrollY(scroll, speed))
);
// Color
let posterize = glslNode("posterize", {
type: "vec4",
args: (input, bins = 3, gamma = 0.6) => [vec4(input), bins, gamma],
});
let shift = glslNode("shift", {
type: "vec4",
args: (input, r = 0.5, g = 0, b = 0, a = 0) => [
vec4(input),
r,
g,
b,
a,
],
});
let invert = glslNode("invert", {
type: "vec4",
args: (input, amount = 1) => [vec4(input), amount],
});
let contrast = glslNode("contrast", {
type: "vec4",
args: (input, amount = 1.6) => [vec4(input), amount],
});
let brightness = glslNode("brightness", {
type: "vec4",
args: (input, amount = 0.4) => [vec4(input), amount],
});
let luma = glslNode("luma", {
type: "vec4",
args: (input, threshold = 0.5, tolerance = 0.1) => [
vec4(input),
threshold,
tolerance,
],
});
let thresh = glslNode("thresh", {
type: "vec4",
args: (input, threshold = 0.5, tolerance = 0.04) => [
vec4(input),
threshold,
tolerance,
],
});
let color = glslNode("color", {
type: "vec4",
args: (input, r = 1, g = 1, b = 1, a = 1) => [vec4(input), r, g, b, a],
});
let saturate = glslNode("saturate", {
type: "vec4",
args: (input, amount = 2) => [vec4(input), amount],
});
let hue = glslNode("hue", {
type: "vec4",
args: (input, hue = 0.4) => [vec4(input), hue],
});
let colorama = glslNode("colorama", {
type: "vec4",
args: (input, amount = 0.005) => [vec4(input), amount],
});
let r = glslNode("r", {
type: "vec4",
args: (input, scale = 1, offset = 0) => [vec4(input), scale, offset],
});
let g = glslNode("g", {
type: "vec4",
args: (input, scale = 1, offset = 0) => [vec4(input), scale, offset],
});
let b = glslNode("b", {
type: "vec4",
args: (input, scale = 1, offset = 0) => [vec4(input), scale, offset],
});
// clashes with audio object
/* let a = glslNode("a", {
type: "vec4",
args: (input, scale = 1, offset = 0) => [vec4(input), scale, offset],
}); */
// blend
let add = glslNode("add", {
type: "vec4",
args: (input, texture, amount = 1) => [
vec4(input),
vec4(texture),
amount,
],
});
let sub = glslNode("sub", {
type: "vec4",
args: (input, texture, amount = 1) => [
vec4(input),
vec4(texture),
amount,
],
});
let layer = glslNode("layer", {
type: "vec4",
args: (input, texture) => [vec4(input), vec4(texture)],
});
let blend = glslNode("blend", {
type: "vec4",
args: (input, texture, amount = 0.5) => [
vec4(input),
vec4(texture),
amount,
],
});
let mult = glslNode("mult", {
type: "vec4",
args: (input, texture, amount = 1) => [
vec4(input),
vec4(texture),
amount,
],
});
let diff = glslNode("diff", {
type: "vec4",
args: (input, texture) => [vec4(input), vec4(texture)],
});
let mask = glslNode("mask", {
type: "vec4",
args: (input, texture) => [vec4(input), vec4(texture)],
});
// modulate
let _modulate = registerNode("_modulate", {
compile: ({ vars, name }) =>
`vec2 ${name} = modulate(${glslArgs(...vars)});`,
});
let modulate = register("modulate", (input, modulator, amount = 0.1) =>
editGeometry(input, (st) => st._modulate(vec4(modulator), amount))
);
let _modulateRepeat = registerNode("_modulateRepeat", {
compile: ({ vars, name }) =>
`vec2 ${name} = modulateRepeat(${glslArgs(...vars)});`,
});
let modulateRepeat = register(
"modulateRepeat",
(
input,
texture,
repeatX = 3,
repeatY = 3,
offsetX = 0.5,
offsetY = 0.5
) =>
editGeometry(input, (st) =>
st._modulateRepeat(
vec4(texture),
repeatX,
repeatY,
offsetX,
offsetY
)
)
);
let _modulateRepeatX = registerNode("_modulateRepeatX", {
compile: ({ vars, name }) =>
`vec2 ${name} = modulateRepeatX(${glslArgs(...vars)});`,
});
let modulateRepeatX = register(
"modulateRepeatX",
(input, texture, reps = 3, offset = 0.5) =>
editGeometry(input, (st) =>
st._modulateRepeatX(vec4(texture), reps, offset)
)
);
let _modulateRepeatY = registerNode("_modulateRepeatY", {
compile: ({ vars, name }) =>
`vec2 ${name} = modulateRepeatY(${glslArgs(...vars)});`,
});
let modulateRepeatY = register(
"modulateRepeatY",
(input, texture, reps = 3, offset = 0.5) =>
editGeometry(input, (st) =>
st._modulateRepeatY(vec4(texture), reps, offset)
)
);
let _modulateKaleid = registerNode("_modulateKaleid", {
compile: ({ vars, name }) =>
`vec2 ${name} = modulateKaleid(${glslArgs(...vars)});`,
});
let modulateKaleid = register(
"modulateKaleid",
(input, texture, nSides = 4) =>
editGeometry(input, (st) => st._modulateKaleid(vec4(texture), nSides))
);
let _modulateScrollX = registerNode("_modulateScrollX", {
compile: ({ vars, name }) =>
`vec2 ${name} = modulateScrollX(${glslArgs(...vars)});`,
});
let modulateScrollX = register(
"modulateScrollX",
(input, texture, scrollX = 0.5, speed = 0) =>
editGeometry(input, (st) =>
st._modulateScrollX(vec4(texture), scrollX, speed)
)
);
let _modulateScrollY = registerNode("_modulateScrollY", {
compile: ({ vars, name }) =>
`vec2 ${name} = modulateScrollY(${glslArgs(...vars)});`,
});
let modulateScrollY = register(
"modulateScrollY",
(input, texture, scrollY = 0.5, speed = 0) =>
editGeometry(input, (st) =>
st._modulateScrollY(vec4(texture), scrollY, speed)
)
);
let _modulateScale = registerNode("_modulateScale", {
compile: ({ vars, name }) =>
`vec2 ${name} = modulateScale(${glslArgs(...vars)});`,
});
let modulateScale = register(
"modulateScale",
(input, texture, multiple = 1, offset = 1) =>
editGeometry(input, (st) =>
st._modulateScale(vec4(texture), multiple, offset)
)
);
let _modulatePixelate = registerNode("_modulatePixelate", {
compile: ({ vars, name }) =>
`vec2 ${name} = modulatePixelate(${glslArgs(...vars)});`,
});
let modulatePixelate = register(
"modulatePixelate",
(input, texture, multiple = 10, offset = 13) =>
editGeometry(input, (st) =>
st._modulatePixelate(vec4(texture), multiple, offset)
)
);
let _modulateRotate = registerNode("_modulateRotate", {
compile: ({ vars, name }) =>
`vec2 ${name} = modulateRotate(${glslArgs(...vars)});`,
});
let modulateRotate = register(
"modulateRotate",
(input, texture, multiple = 1, offset = 0) =>
editGeometry(input, (st) =>
st._modulateRotate(vec4(texture), multiple, offset)
)
);
let _modulateHue = registerNode("_modulateHue", {
compile: ({ vars, name }) =>
`vec2 ${name} = modulateHue(${glslArgs(...vars)});`,
});
let modulateHue = register("modulateHue", (input, texture, amount = 1) =>
editGeometry(input, (st) => st._modulateHue(vec4(texture), amount))
);
let draw = registerNode("draw", {
compile: ({ vars, name }) => `fragColor = ${vars[0]};`,
});
let exit = registerNode("exit", { internal: true });
// read base64 code from url
let urlCode = window.location.hash.slice(1);
let parseCode = (hash) => decodeURIComponent(atob(hash));
let hashCode = (code) => btoa(encodeURIComponent(code));
if (urlCode) {
urlCode = parseCode(urlCode);
console.log("loaded code from url!");
}
// use urlCode or fall back to default shadertoy example
const initialShader =
urlCode ||
`osc(11, 0.01, 1.4)
.rotate(0, 0.1)
.mult(
osc(10, 0.1)
.modulate(
osc(10)
.rotate(0, -0.1),
1
)
)
.color(2.83,0.91,0.39)
.out()`;
// global vars
let programs = {}; // needs global var to reuse textures
let then = 0; // last render callback time
let time = 0; // time in seconds
let mouse = { x: 0, y: 0 };
let speed = 1;
let width = canvas.width;
let height = canvas.height;
let bpm = 30;
// stub definition for audio object
let a = {
fft: [0, 0, 0, 0],
setSmooth: () => {},
setCutoff: () => {},
setBins: () => {},
setScale: () => {},
hide: () => {},
show: () => {},
};
// Array functions
function enhanceArray(method, fn) {
Object.defineProperty(Array.prototype, method, {
value: function (...args) {
return fn(this, ...args);
},
enumerable: false,
writable: false,
configurable: false,
});
}
enhanceArray("fast", (arr, speed = 1) => {
arr._speed = speed;
return arr;
});
enhanceArray("offset", (arr, offset = 0.5) => {
arr._offset = offset % 1;
return arr;
});
let remap = (num, in_min, in_max, out_min, out_max) => {
return (
((num - in_min) * (out_max - out_min)) / (in_max - in_min) + out_min
);
};
enhanceArray("fit", (arr, low = 0, high = 1) => {
let lowest = Math.min(...arr);
let highest = Math.max(...arr);
var newArr = arr.map((num) => remap(num, lowest, highest, low, high));
newArr._speed = arr._speed;
newArr._smooth = arr._smooth;
newArr._ease = arr._ease;
return newArr;
});
enhanceArray("smooth", (arr, smooth = 1) => {
arr._smooth = smooth;
return arr;
});
// from https://gist.github.com/gre/1650294
let easing = {
// no easing, no acceleration
linear: (t) => t,
// accelerating from zero velocity
easeInQuad: (t) => t * t,
// decelerating to zero velocity
easeOutQuad: (t) => t * (2 - t),
// acceleration until halfway, then deceleration
easeInOutQuad: (t) => (t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t),
// accelerating from zero velocity
easeInCubic: (t) => t * t * t,
// decelerating to zero velocity
easeOutCubic: (t) => --t * t * t + 1,
// acceleration until halfway, then deceleration
easeInOutCubic: (t) =>
t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1,
// accelerating from zero velocity
easeInQuart: (t) => t * t * t * t,
// decelerating to zero velocity
easeOutQuart: (t) => 1 - --t * t * t * t,
// acceleration until halfway, then deceleration
easeInOutQuart: (t) =>
t < 0.5 ? 8 * t * t * t * t : 1 - 8 * --t * t * t * t,
// accelerating from zero velocity
easeInQuint: (t) => t * t * t * t * t,
// decelerating to zero velocity
easeOutQuint: (t) => 1 + --t * t * t * t * t,
// acceleration until halfway, then deceleration
easeInOutQuint: (t) =>
t < 0.5 ? 16 * t * t * t * t * t : 1 + 16 * --t * t * t * t * t,
// sin shape
sin: (t) => 1 + Math.sin(Math.PI * t - Math.PI / 2),
};
enhanceArray("ease", (arr, ease = "linear") => {
arr._smooth = 1;
if (typeof ease == "function") {
arr._ease = ease;
} else if (easing[ease]) {
arr._ease = easing[ease];
}
return arr;
});
// synth settings (stub definitions)
let update = () => console.warn("update function not implemented");
let setResolution = () =>
console.warn("setResolution function not implemented");
let hush = () => console.warn("hush function not implemented");
let setFunction = () =>
console.warn("setFunction function not implemented");
let sourceStub = {
initCam: () => console.warn("s0.initCam not implemented"),
};
let s0 = sourceStub,
s1 = sourceStub,
s2 = sourceStub,
s3 = sourceStub;
// speed
function main() {
// set up code input
const input = document.querySelector("#code");
const wrapper = document.querySelector(".textarea-wrapper");
const highlightedText = document.querySelector("#highlighted-text");
function updateLineBackground() {
const lines = input.value.split("\n");
highlightedText.innerHTML = `<span>${lines.join(
"</span>\n<span>"
)}</span> `;
wrapper.style.height = highlightedText.clientHeight;
}
document.body.onclick = () => input.focus();
input.value = initialShader;
updateLineBackground();
window.codestyle = (attr, value) => (input.style[attr] = value);
let examples;
let loadExamples = async () => {
if (!examples) {
let res = await fetch(
"https://raw.githubusercontent.com/hydra-synth/hydra/main/src/stores/examples.json"
);
examples = await res.json();
}
return examples;
};
let runExample = (example) => {
console.log("run example", example);
const code = parseCode(example.code);
input.value = code;
updateLineBackground();
window.location.hash = "#" + hashCode(code);
evaluate(code);
};
window.shuffle = async () => {
let examples = await loadExamples();
const example = examples[Math.floor(Math.random() * examples.length)];
runExample(example);
};
window.example = async (index = 0) => {
let examples = await loadExamples();
if (index < 0 || index > examples.length - 1) {
throw new Error(
`example(${index}) out of range. valid range: 0-${
examples.length - 1
}`
);
}
const example = examples[index];
runExample(example);
// not working
// example(55) : n is not a function
};
// vertex shader
const vs = `
attribute vec4 a_position;
void main() {
gl_Position = a_position;
}
`;
// set up canvas
const canvas = document.querySelector("#canvas");
canvas.width = canvas.clientWidth * window.devicePixelRatio;
canvas.height = canvas.clientHeight * window.devicePixelRatio;
const gl = canvas.getContext("webgl");
gl.viewport(0, 0, canvas.width, canvas.height);
const rect = canvas.getBoundingClientRect();
// mouse logic
document.addEventListener("mousemove", (e) => {
const { left, height, top } = canvas.getBoundingClientRect();
mouse.x = e.clientX - left;
mouse.y = height - (e.clientY - top) - 1;
});
// animation frame logic
let requestId;
function requestFrame(render) {
if (!requestId) {
requestId = requestAnimationFrame(render);
}
}
function cancelFrame() {
if (requestId) {
cancelAnimationFrame(requestId);
requestId = undefined;
}
}
// find out which outputs are src'ed into this graph
function getUniforms(graph) {
const uniforms = {};
let floatCount = 0;
graph.dfs((node) => {
if (node.type === "src") {
let id = node.ins[1].value;
const name = `tex${id}`;
const definition = `uniform sampler2D ${name};`;
uniforms[name] = { definition, id, type: "tex" };
}
if (node.type === "float") {
const id = floatCount++;
node.id = id;
const name = `float${id}`;
const definition = `uniform float ${name};`;
let type;
if (Array.isArray(node.value)) {
type = "sequence";
} else if (typeof node.value === "function") {
type = "fn";
} else {
throw new Error("unexpected value of float type");
}
uniforms[name] = {
definition,
id,
type,
value: node.value,
};
}
return node;
});
return uniforms;
}
// compiles a kabelsalat graph into a fragment shader
function compileFragmentShader(graph, uniforms = {}) {
graph = draw(graph).exit();
const unit = graph.compile();
const sourceUniforms = Object.values(uniforms)
.map(({ definition }) => definition)
.join("\n");
let precision = "highp";
//let precision = "mediump";
let head = `precision ${precision} float;
uniform vec2 iResolution;
uniform vec2 iMouse;
uniform float iTime;
${sourceUniforms}
`;
let definitions = `
float _luminance(vec3 rgb) {
const vec3 W = vec3(0.2125, 0.7154, 0.0721);
return dot(rgb, W);