-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.html
769 lines (716 loc) · 23 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
<!DOCTYPE html>
<html lang="en">
<head>
<script async src="https://www.googletagmanager.com/gtag/js?id=G-48BCEQZ17X"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-48BCEQZ17X');
</script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>textshader</title>
<style>
:root {
--bgcolor: #207687;
}
html {
line-height: 1.15;
-webkit-text-size-adjust: 100%;
}
main {
display: block;
}
[hidden] {
display: none;
}
.header {
padding: 5px;
color: white;
font-size: 25px;
font-family: monospace;
font-weight: bolder;
text-align: left;
display: flex;
white-space: nowrap;
}
.footer {
padding: 5px;
color: white;
font-size: 25px;
font-family: monospace;
font-weight: bolder;
text-align: left;
display: flex;
}
html,
body {
height: 100%;
overflow-x: hidden;
background: #207687;
}
body {
margin: 0;
display: flex;
flex-direction: column;
}
.content {
display: flex;
flex-grow: 1;
flex-wrap: wrap;
justify-content: center;
}
.content > div {
flex-grow: 1;
flex-basis: 0;
min-height: 5ch;
}
#editor {
min-width: 20ch;
}
#frame {
background: #000000;
color: rgba(256,256,256,0.5);
white-space: pre;
font-family: monospace;
text-shadow: 0.1ch 0.1ch 0.1ch #00FF00,
0.1ch 0ch 0.1ch #0000FF,
0.0ch 0.1ch 0.1ch #FF0000;
font-size: 13px;
max-width: 80ch;
min-width: 80ch;
-webkit-user-select: none;
-ms-user-select: none;
user-select: none;
cursor: pointer;
}
.lightmode #frame {
background: #EEEEEE;
color: rgba(0,0,0,1);
text-shadow: 0 0 0.1ch #000000;
}
.fullscreen #frame {
font-size: 2.08vw;
}
.header > span:first-child {
flex-grow: 1;
padding: 0px 5px 0px 5px;
}
.header > span:not(:first-child) {
flex-grow: 0;
padding: 0px 5px 0px 5px;
font-weight: normal;
}
.footer > span:first-child {
flex-grow: 1;
padding: 0px 5px 0px 5px;
}
.footer > span:not(:first-child) {
flex-grow: 0;
padding: 0px 5px 0px 5px;
}
.menubutton {
cursor:pointer;
user-select: none;
-webkit-user-select: none;
}
select {
font-size: 75%;
width: 10ch;
white-space: pre;
}
#hamburger {
appearance: none;
-webkit-appearance: none;
-moz-appearance: none;
background-color: rgba(0,0,0,0);
border: 0px solid white;
color: white;
text-align: center;
width: 2.5ch;
cursor: pointer;
transform: scale(2) translate(0px,-3px);
}
/* Safari renders weirdly and needs correcting but only on desktop */
_::-webkit-full-page-media, _:future, :root #hamburger {
transform: scale(2) translate(5px,-3px);
}
@media screen and (max-width: 1000px) {
.nomobile {
display: none;
}
#hamburger {
transform: scale(2) translate(0px,-3px) !important;
}
}
a, a:hover, a:visited, a:active {
color: inherit;
}
</style>
</head>
<body>
<div class="header">
<span>textshader</span>
<span>by <a href="https://leoadberg.com" target="_blank">Leo Adberg</a> and inspired by <a href="https://www.shadertoy.com/" target="_blank">shadertoy</a></span>
</div>
<div class="content">
<div id="editor"></div>
<div id="frame"></div>
</div>
<div class="footer">
<span id="hint"></span>
<span>
<label for="examples">examples:</label>
<select name="examples" id="examples">
</select>
</span>
<span>
<label for="charsets">charset:</label>
<select name="charsets" id="charsets">
<option value=" .'`^",:;Il!i><~+_-?][}{1)(|\/tfjrxnuvczXYUJCLQ0OZmwqpdbkhao*#MW&8%B@$">default</option>
<option value=" !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ">ascii</option>
<option value=" ░▒▓█">block</option>
<option value="0123456789#">debug</option>
</select>
</span>
<span id="playpause" class="menubutton" title="play/pause">⏸︎</span>
<span id="fullscreen" class="menubutton nomobile" title="fullscreen"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path fill="#FFFFFF" d="M24 9h-2v-4h-4v-2h6v6zm-6 12v-2h4v-4h2v6h-6zm-18-6h2v4h4v2h-6v-6zm6-12v2h-4v4h-2v-6h6zm14 4h-16v10h16v-10z"/></svg></span>
<span>
<select name="hamburger" id="hamburger" onchange="console.log(this)">
<option disabled selected>☰</option>
<option>Share Shader</option>
<option>Copy Frame Text</option>
<option>Light Mode</option>
</select>
</span>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.12.3/ace.min.js" type="text/javascript" charset="utf-8"></script>
<script>
ace.config.set('basePath', 'https://cdnjs.cloudflare.com/ajax/libs/ace/1.12.3/')
var editor = ace.edit("editor")
editor.setOptions({fontSize: "12pt"})
editor.setTheme("ace/theme/twilight")
editor.session.setMode("ace/mode/javascript")
editor.session.on("changeMode", ()=>editor.session.$worker.send("changeOptions", [{asi: true, esversion: 7}]))
const fastmap = (v, f) => {
let ret = []
for (let i = 0; i < v.length; i++) {
ret.push(f(v[i], i))
}
return ret
}
const hint = document.getElementById("hint")
let lastHint = null
let loading = false
let loadingText = "-\\|/"
const updateHint = message => {
if (message == "loading") {
loading = true
} else {
loading = false
clearTimeout(lastHint)
hint.innerText = message
lastHint = setTimeout(()=>{hint.innerText = ""}, 5000)
}
}
setInterval(()=>{if (loading) hint.innerText = loadingText[(loadingText.indexOf(hint.innerText) + 1) % loadingText.length]}, 100)
let paused = false
const playpause = document.getElementById("playpause")
playpause.onclick = ()=>{
paused = !paused
playpause.innerText = paused ? "▶️" : "⏸︎"
}
let focused = true
document.addEventListener("visibilitychange", ()=>{
focused = document.visibilityState != "hidden"
});
let fullscreen = false
const hamburger = document.getElementById("hamburger")
hamburger.onclick = function() {
console.log(this)
}
hamburger.onchange = function() {
const selected = this.options[this.selectedIndex]
this.selectedIndex = 0
switch (selected.value) {
case "Share Shader":
const source = editor.getValue()
const charset = charsets.options[charsets.selectedIndex].text
updateHint("loading")
fetch('https://i2ysre27srfphdamezwoi52l3a0auncn.lambda-url.us-east-1.on.aws',
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({charset: charset, source: source})
})
.then(response => {
if (response.ok) return response.text()
console.log(response.text())
console.log(response)
updateHint("Error!")
throw new Error(`Could not fetch source`)
})
.then(data => {
console.log(data)
location.hash = `${charset}.${data}`
navigator.clipboard.writeText(location.href)
updateHint("Copied link!")
})
.catch(error => {
updateHint("Error!")
console.log(error)
});
break;
case "Copy Frame Text":
navigator.clipboard.writeText(frame.innerText)
updateHint("Copied!")
break;
case "Light Mode":
document.body.classList.add("lightmode")
selected.text = "Dark Mode"
editor.setTheme("ace/theme/chrome")
editor.focus()
break;
case "Dark Mode":
document.body.classList.remove("lightmode")
selected.text = "Light Mode"
editor.setTheme("ace/theme/twilight")
editor.focus()
break;
}
}
const fullscreenElem = document.getElementById("fullscreen")
fullscreenElem.onclick = ()=>{
let requested = true
if (frame.requestFullscreen) {
frame.requestFullscreen()
} else if (frame.mozRequestFullscreen) {
frame.mozRequestFullScreen()
} else if (frame.webkitRequestFullscreen) {
frame.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT)
} else if (frame.msRequestFullscreen) {
frame.msRequestFullscreen()
} else {
requested = false
}
if (requested) {
console.log((document.fullscreenElement || document.webkitFullscreenElement ||
document.mozFullScreenElement))
fullscreen = true
document.body.classList.add("fullscreen")
} else {
updateHint("Unsupported browser")
}
}
function exitHandler() {
if (!document.fullscreenElement && !document.webkitIsFullScreen && !document.mozFullScreen && !document.msFullscreenElement) {
fullscreen = false
document.body.classList.remove("fullscreen")
}
}
for (const e of ['fullscreenchange', 'webkitfullscreenchange', 'mozfullscreenchange', 'MSFullscreenChange']) {
document.addEventListener(e, exitHandler)
}
const charsets = document.getElementById("charsets")
let colors = ""
charsets.onchange = function() {
colors = this.options[this.selectedIndex].value
}
charsets.onchange()
const setCharset = charset => {
for (let i = 0; i < charsets.options.length; i++) {
if (charsets.options[i].text == charset) {
charsets.selectedIndex = i
charsets.onchange()
break
}
}
}
const examples = [
["blank", "default", `function shader(x, y, t) {
return 0
}`],
["tutorial", "ascii", `function shader(x, y, t) {
tutorial = [
"// textshader is a live rendered view of a shader written in javascript.",
"// All js is valid but a few ease-of-use changes have been made:",
"",
"// All of Math has been imported directly so no need to use Math.foo:",
"[floor(4.5), cos(PI), pow(3,3)]",
"",
"// Additional math functions have been added:",
"lerp(10, 20, 0.5)",
"clamp(10,0,1)",
"dot([1,2,3], [4,5,6])",
"[add([1,2,3], [4,5,6]), sub([1,2,3], [4,5,6])]",
"[mul([1,2,3], 4), div([1,2,3], 4)]",
"length([1,2,3])",
"norm([3,4])",
// "// (all work for any sized vector)",
"",
"// Time is in seconds",
"t",
"",
"// Some extra hidden variables are available",
"[width, height, mousedown, mousex, mousey]",
"",
"// The last frame is also available (in text-space coordinates)",
"prevBuffer[16][7] // Seconds of 't' line",
"",
"// Happy hacking!",
]
// Convert to text-space coords
x = round(x * (width-1))
y = round((1-y) * (height-1))
if (y < tutorial.length) {
let line = tutorial[y]
const result = eval(line)
if (result) line += \` -> \${JSON.stringify(result)}\`
return line.charCodeAt(x)/127
}
return 0;
}`],
["earth", "default", `function shader(x, y, t) {
// Not scientific in the slightest
// Click to zoom + xray
let xray = false
if (mousedown) {
const zoom = 4
if (x > 0.5 && y < 0.5) {
x = (x-.75) / zoom + mousex
y = (y-.25) / zoom + mousey
xray = true
} else if (abs(x - mousex) < .5/zoom && abs(y - mousey) < .5/zoom) {
xray = true
}
}
const dir = norm([x-0.5, (y-0.5)*0.6, 1])
const tex = [0x7fffffc,0x7fffffc,0x7fffffc,0x7fffffc,0x3fffffc,0x7fffffc,0x5fffffc,0x1fffffc,0x5fffffc,0x5fffffc,0x3fffffc,0x3fffffc,0x3fefffc,0x3f77ffc,0x3fffffc,0x3fffffc,0x3fffff8,0x3fffff8,0x3fffff8,0x7fffff8,0x7fffff8,0x7fffff8,0x3fffff8,0x3fffff8,0x3fffff8,0x3fffff8,0x1fffff8,0x1fffff8,0x1fffff8,0x1fffff8,0xfffff8,0x3ffff8,0x3ffff8,0x3ffff8,0x1ffff8,0x1ffff8,0x1ffff8,0xffff8,0xffbf8,0xffff8,0xffff8,0x7fff8,0x7fff8,0x7fff8,0x7fff8,0x7fff8,0x17fff8,0x17fff8,0x1bfff8,0x413fff8,0x413fff8,0x513fff8,0x419fff8,0x419fff8,0x40dfff8,0xc2d3ff8,0x253ff8,0x241ff8,0x241f70,0x741c30,0x741030,0xf40030,0xf40070,0x10fc0060,0x10fc00e0,0x1cfc00e0,0x1cf801a8,0x1cfe01e8,0x1cfe01e8,0xcfe03fc,0x6fe03fc,0x7fe03fc,0x7fe03fc,0x7ff0ffc,0x3ff07fc,0x7ff0ffc,0x7ff0ffc,0x7ff0ffc,0xfff1ffc,0xfffbffc,0xfffbffc,0xffffffc,0xffffff8,0xffffffc,0xfffffdc,0xfffffd8,0x7fbfff8,0x7fffff8,0x17fffff8,0x17fffff8,0x17fffff8,0x37e3fff8,0x3fe1fff8,0x3fe1fff8,0x1dc1fff8,0x1d01fff0,0x1d01fff0,0x1c01fff0,0x1801fff0,0x1c01fff0,0x1c01fff0,0x1e01fff0,0x1881fff0,0x1881fff0,0x1001fff0,0x38807ff0,0x30005ff0,0x10000ff0,0x108007f0,0x104003f0,0x206003f0,0x244003f0,0x200003f0,0x200003f0,0x3f0,0x200003f0,0x208003f0,0x200003f0,0x208007f0,0x380007f0,0x20801f70,0x30001ff0,0x10801ff0,0x1000fff0,0x3000e7f0,0x3000e7f0,0x3001c7f0,0x3085dff0,0x3003ffe0,0x1017ffe0,0x3007fff0,0x2007fff0,0x17eff0,0xffff0,0x100ffff0,0x100feff0,0xffff0,0x200ffff0,0x200ffff0,0x2007fff0,0x2004fff0,0x3fff0,0x2001fff0,0x2001fff0,0x1fff0,0x7fff0,0x7fff0,0x2007fff0,0xffff0,0xffff0,0xffff0,0x7fff0,0x7ffe0,0x6ffe0,0xffe0,0x7ff0,0x227ff0,0x27ff0,0x17fe0,0x37ff0,0x23ff0,0x63ff0,0xe37f0,0xe37f0,0xe23f0,0xcb3f0,0x723f0,0x963f0,0x1923f0,0x7d83e0,0x3f03f0,0x2e63f0,0x1f43e0,0x3f43f0,0x7d43e0,0xbf43e0,0xbf03f0,0x3f21f0,0x1af01f0,0x7f81f0,0x3fb80f0,0x3ffa0f0,0x7fda0f0,0x7fdb1f0,0x3fff3f0,0x3fff7f0,0x5fffff0,0x5ffbff0,0x5ffaff0,0x3ffbff0,0x13fffff0,0x3ffeffc,0x7ffcf7c,0x7ffdff0,0x7fffefc,0x7fffefc,0x7fffcfc,0x7fffdfc,0x5fffdfc,0x7ffbffc]
// Rays implicitly originate at [0,0,0] to simplify
function intersect(pos, r) {
const b = -dot(pos, dir);
const c = dot(pos, pos) - r*r;
if (c > 0 && b > 0) return [false];
const d = b*b - c;
if (d < 0) return [false];
const t = -b - sqrt(d);
const hitp = mul(dir, t)
const normal = norm(sub(hitp, pos))
return [true, t, normal];
}
const sunDir = norm([sin(t*2),sin(t*0.1)*0.4,cos(t*2)])
const earthPos = [0,0,10]
const earthSize = 3;
const moonOrbitRadius = 6;
const moonOrbitSpeed = 0.1;
const moonPos = [sin(t*moonOrbitSpeed)*moonOrbitRadius,0,10+cos(t*moonOrbitSpeed)*moonOrbitRadius]
const moonSize = 0.5;
const [hitearth, earthtime, earthnormal] = intersect(earthPos,earthSize)
const [hitmoon, moontime, moonnormal] = intersect(moonPos,moonSize)
if (hitmoon && (!hitearth || moontime < earthtime)) {
return dot(moonnormal, sunDir)
}
const sample = (lat, lon) => {
const xind = round(((((lat / (2*PI)) % 1) + 1) % 1) * (tex.length-1))
const yind = round(lon * 31)
return tex[xind] >> yind & 1
}
if (hitearth) {
const lat = t*0.2 - atan2(earthnormal[0], earthnormal[2])
const lon = (earthnormal[1]+1) / 2
if (mousedown && xray) {
const land = sample(lat, lon)
const near1 = sample(lat + 0.02, lon+0.005)
const near2 = sample(lat + 0.02, lon-0.005)
const linedetector = land != near1 || land != near2
return linedetector || (1-land) * 0.1 || 0.05
} else {
const land = 1.05 - sample(lat, lon)
return (dot(earthnormal, sunDir)+0.2) * land
}
}
return 0.1*((round(round(x*(width-1)+t*2) * (y*(height-1)+10)) + y*18 & 0x1f) == 0)
}`],
["xeyes", "default", `function shader(x, y, t) {
// Squeeze a bit
x *= 2
mouse = [mousex*2, mousey]
let res = 0
function drawCircle(center, radius, value) {
if (dist([x,y], center) < radius) res = value
}
function drawEye(center) {
drawCircle(center, 0.41, .1)
drawCircle(center, 0.4, 1)
drawCircle(center, 0.35, 0.1)
let delta = sub(mouse, center)
if (length(delta) > 0.2) {
delta = mul(norm(delta), 0.2)
}
drawCircle(add(center, delta), mousedown ? 0.1 : 0.15, 0.7)
}
drawEye([0.5,0.5])
drawEye([1.5,0.5])
return res
}`],
["mandelbrot", "default", `function shader(x, y, t) {
const center = [-.7451544,.1861545]
const lo = sub(center, mul([1,1], pow(0.5, t%5)))
const hi = add(center, mul([1,1], pow(0.5, t%5)))
x = lerp(lo[0], hi[0], x)
y = lerp(lo[1], hi[1], y)
const cmul = (c1, c2) => [c1[0]*c2[0] - c1[1]*c2[1], c1[0]*c2[1] + c1[1]*c2[0]]
let v = [x,y]
for (let i = 0; i < 100; i++) {
v = add(cmul(v,v), [x,y])
}
return 1 / length(v)
}`],
["grapher", "ascii", `function shader(x, y, t) {
const f = x => 5*sin(x*0.1 + t*5)
// Convert to graph-space coords
x = round(x * (width-1) - width/2)
y = round(y * (height-1) - height/2)
cursor = round(mousex * (width-1) - width/2)
let ret = " "
// Plot axes
if (x == 0 && y == 0) {
ret = "+"
} else if (x == 0) {
ret = "|"
} else if (y == 0) {
ret = "-"
}
// Plot graph
if (round(f(x)) == y) {
ret = x == cursor ? "#" : "."
}
// Legend
if (y == -floor(height/2)) {
const text = \`Plotting: \${f}, x=\${cursor}, y=\${f(cursor).toFixed(3)}\`
const start = -floor(width/2)
if (x >= start && x < start + text.length) {
ret = text[x - start]
}
}
return ret.charCodeAt()/127
}`],
["bounce", "default", `function shader(x, y, t) {
const bounce = (v, P) => {
const a = v % (2*P)
return a < P ? a/P : 2 - a/P;
}
const drawBall = t => {
const x2 = bounce(t, 3) * 0.8 + 0.1
const y2 = bounce(t, 3.95) * 0.8 + 0.1
const dist = pow(x - x2, 2) + pow(y - y2, 2)
return max(1.1-dist*50, 0);
}
return drawBall(t) + drawBall(t+1) + drawBall(t+2)
}`],
["rick", "default", `if (video == undefined) {
const container = document.createElement("div")
container.innerHTML = \`
<video id="rickvideo" autoplay muted loop playsinline>
<source src="rick.mp4"></source>
</video>
<canvas id="rickcanvas"></canvas>
\`;
var [video, canvas] = container.children
}
let lastT = null
let data = null
let vw = null
let vh = null
function shader(x, y, t) {
if (t != lastT) {
lastT = t
video.play()
let ctx = canvas.getContext("2d")
vw = video.videoWidth
vh = video.videoHeight
if (vw == 0) return // Not loaded yet
canvas.width = vw
canvas.height = vh
ctx.drawImage(video,0,0)
data = ctx.getImageData(0,0,vw,vh).data
}
if (vw == 0) return // Not loaded yet
const i = round((1-y) * vh)
const j = round(x * vw)
return (data[(i * vw + j) * 4] / 500) - 0.2
}`],
]
const examplesElem = document.getElementById("examples")
for (const [name, charset, source] of examples) {
const option = document.createElement('option')
option.innerText = name
option.value = source
option.setAttribute("charset", charset)
examplesElem.appendChild(option)
}
examplesElem.onchange = function() {
const option = this.options[this.selectedIndex]
editor.setValue(option.value)
editor.clearSelection()
setCharset(option.getAttribute("charset"))
}
const hash = location.hash.substr(1)
if (hash == "") {
// Pick a random example non-blank on load
examplesElem.selectedIndex = 1 + Math.floor(Math.random() * (examples.length - 1))
examplesElem.onchange()
} else {
// Fetch the gist
const [charset, pastecode] = hash.split(".")
if (confirm(`Do you trust the code at https://gist.github.com/${pastecode} to run in your browser?`))
fetch(`https://api.github.com/gists/${pastecode}`)
.then(response => {
if (response.ok) return response.json()
throw new Error('Could not fetch source')
})
.then(data => {
const sourceURL = data.files["textshader.js"].raw_url
fetch(sourceURL)
.then(response => {
if (response.ok) return response.text()
throw new Error('Could not fetch source')
})
.then(data => {
editor.setValue(data)
setCharset(charset)
});
});
}
let mousedown = false
let mousex = 0
let mousey = 0
function onMousemove(e) {
// Taken from https://stackoverflow.com/questions/16154857
let m_posx = 0, m_posy = 0, e_posx = 0, e_posy = 0;
if (!e) e = window.event
if (e.pageX || e.pageY) {
m_posx = e.pageX;
m_posy = e.pageY;
} else if (e.clientX || e.clientY) {
m_posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
m_posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
let curObj = frame;
if (curObj.offsetParent) {
do {
e_posx += curObj.offsetLeft;
e_posy += curObj.offsetTop;
} while (curObj = curObj.offsetParent);
}
mousex = (m_posx-e_posx) / frame.offsetWidth
mousey = 1 - (m_posy-e_posy) / (height * parseInt(window.getComputedStyle(frame).lineHeight))
// Round to display more cleanly
mousex = round(mousex*1000)/1000
mousey = round(mousey*1000)/1000
}
function setPrimaryButtonState(e) {
const flags = e.buttons !== undefined ? e.buttons : e.which;
mousedown = (flags & 1) === 1;
}
document.addEventListener("mousemove", onMousemove)
document.addEventListener("mousedown", setPrimaryButtonState)
document.addEventListener("mousemove", setPrimaryButtonState)
document.addEventListener("mouseup", setPrimaryButtonState)
const frame = document.getElementById("frame")
const originalFrameWidth = frame.offsetWidth
const width = 80
const height = 25
const FPS = 60
const start = Date.now()
let lastSource = ""
let curError = ""
let prevBuffer = [...Array(height)].map(_=>Array(width).fill(0))
function updateFrame() {
if (paused || !focused) return
const t = (Date.now() - start)/1000;
if (fullscreen) {
frame.removeAttribute("style")
} else {
if (document.body.offsetWidth < originalFrameWidth) {
frame.style.fontSize = `${13 * document.body.offsetWidth / originalFrameWidth}px`
} else if (getComputedStyle(frame) != "13px") {
frame.style.fontSize = "13px"
}
}
// Reload everything on source change just in case
const source = editor.getValue()
if (lastSource != source) {
// Import all of Math's properties
for (const v of Object.getOwnPropertyNames(Math)) {
this[v] = Math[v]
}
// Add some more common math functions
this.lerp = (a, b, p)=>{
return a*(1-p) + b*p
}
this.clamp = (x, lo, hi)=>{
return min(max(x, lo), hi)
}
this.dot = (v1, v2)=>{
if (v1.length != v2.length) throw "Mismatching vector lengths"
let sum = 0
for (let i = 0; i < v1.length; i++) {
sum += v1[i] * v2[i]
}
return sum
}
this.add = (v1, v2)=>{
if (v1.length != v2.length) throw "Mismatching vector lengths"
return fastmap(v1, (e, i) => e + v2[i])
}
this.sub = (v1, v2)=>{
if (v1.length != v2.length) throw "Mismatching vector lengths"
return fastmap(v1, (e, i) => e - v2[i])
}
this.mul = (v, x) => fastmap(v, e => e*x)
this.div = (v, x) => fastmap(v, e => e/x)
this.length = v => sqrt(dot(v, v))
this.norm = v => div(v, length(v))
this.dist = (v1, v2) => length(sub(v1, v2))
lastSource = source
try {
// Yeah yeah, very dangerous and fragile, I know
eval?.(source) // Indirect eval
curError = ""
} catch(e) {
curError = e.message
}
}
let buffer = [...Array(height)].map(_=>Array(width).fill(0))
let textBuffer = ""
for (let i = 0; i < height; i++) {
for (let j = 0; j < width; j++) {
let ind = 0
let val = 0
try {
val = shader(j/(width-1), (height - 1 - i) / (height - 1), t)
val = clamp(val, 0, 1)
if (!Number.isFinite(val)) {
val = 0
}
} catch(e) {
if (!curError) curError = e.message
}
ind = floor(clamp(val * (colors.length - 1), 0, colors.length - 1))
buffer[i][j] = val
textBuffer += colors[ind]
}
textBuffer += "\n"
}
if (curError) textBuffer += `\nERROR: ${curError}`
if (frame.innerText != textBuffer) {
frame.innerText = textBuffer
}
prevBuffer = buffer
}
setInterval(updateFrame, 1000 / FPS);
</script>
</body>
</html>