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
|
<!doctype html>
<!--
slosh shadertoy — write a shader expression, watch it happen.
One file, no build, no network: open it with a browser and it works. The
expression language is the one slosh compiles (src/expr.c), reimplemented
here in JavaScript, so what you see is what your config will do. That
duplication is the obvious hazard, so tests/test_shadertoy.py runs the same
expressions through both and fails if they ever disagree.
Move the mouse over the preview to move the cursor: `curx`/`cury` follow it,
which is how a spotlight is meant to be judged.
-->
<html lang="en">
<head>
<meta charset="utf-8">
<title>slosh shadertoy</title>
<style>
:root {
--bg: #0d0d10; --panel: #16161b; --line: #2a2a32;
--fg: #e8e8ea; --dim: #7a7a86; --accent: #ff5fd7; --bad: #ff6b6b;
--mono: ui-monospace, "JetBrains Mono", "Fira Code", Menlo, monospace;
}
* { box-sizing: border-box; }
body {
margin: 0; background: var(--bg); color: var(--fg);
font: 13px/1.5 var(--mono);
display: grid; grid-template-columns: 420px 1fr; height: 100vh;
}
#left { border-right: 1px solid var(--line); overflow-y: auto; padding: 14px; }
#right { padding: 14px; display: flex; flex-direction: column; gap: 10px; min-width: 0; }
h1 { font-size: 14px; margin: 0 0 2px; letter-spacing: .04em; }
h1 span { color: var(--accent); }
.sub { color: var(--dim); margin: 0 0 14px; font-size: 11px; }
h2 { font-size: 11px; text-transform: uppercase; letter-spacing: .09em;
color: var(--dim); margin: 16px 0 6px; font-weight: 500; }
.pass {
background: var(--panel); border: 1px solid var(--line); border-radius: 5px;
padding: 8px; margin-bottom: 7px;
}
.pass .row { display: flex; gap: 6px; align-items: center; }
.pass .row + .row { margin-top: 6px; }
select, input[type=text] {
background: #0b0b0e; color: var(--fg); border: 1px solid var(--line);
border-radius: 4px; padding: 5px 7px; font: inherit;
}
input[type=text] { flex: 1; min-width: 0; }
input[type=text]:focus, select:focus { outline: 1px solid var(--accent); }
input[type=color] {
width: 28px; height: 28px; padding: 0; border: 1px solid var(--line);
border-radius: 4px; background: none;
}
button {
background: #22222a; color: var(--fg); border: 1px solid var(--line);
border-radius: 4px; padding: 5px 9px; font: inherit; cursor: pointer;
}
button:hover { border-color: var(--accent); color: var(--accent); }
button.x { padding: 5px 8px; color: var(--dim); }
.err { color: var(--bad); font-size: 11px; margin-top: 5px; white-space: pre-wrap; }
.deps { color: var(--dim); font-size: 11px; margin-top: 5px; }
.deps b { color: var(--accent); font-weight: 500; }
.deps .cached { color: #7fd67f; }
.deps .live { color: #f0c674; }
/* Never scaled up: the preview is drawn at the size it means, and a
viewport with room to spare gets space around it rather than a blur.
Shrinks (smoothly) when the window is genuinely too small for it. */
canvas { border: 1px solid var(--line); border-radius: 5px;
max-width: 100%; height: auto; align-self: start; }
pre#config {
background: var(--panel); border: 1px solid var(--line); border-radius: 5px;
padding: 10px; margin: 0; overflow-x: auto; color: var(--fg); font-size: 12px;
}
.hint { color: var(--dim); font-size: 11px; }
.ref { color: var(--dim); font-size: 11px; line-height: 1.7; }
.ref code { color: var(--fg); }
.presets { display: flex; flex-wrap: wrap; gap: 5px; margin-bottom: 8px; }
.presets button { font-size: 11px; padding: 4px 7px; }
.group { color: var(--dim); font-size: 10px; letter-spacing: .08em;
text-transform: uppercase; margin: 8px 0 4px; }
</style>
</head>
<body>
<div id="left">
<h1>slosh <span>shadertoy</span></h1>
<p class="sub">A shader's strength is an expression, evaluated for every cell.</p>
<h2>presets</h2>
<div id="presets"></div>
<h2>chain</h2>
<div id="chain"></div>
<button id="add">+ pass</button>
<h2>for your config</h2>
<pre id="config"></pre>
<h2>language</h2>
<p class="ref">
<code>x y</code> the cell, inside the pane<br>
<code>cols rows</code> the size of the pane<br>
<code>curx cury</code> the cursor (follows your mouse), <code>cursor</code> 0/1<br>
<code>focused</code> 0/1 <code>t</code> milliseconds<br>
<code>since</code> ms in the pane's current state (<code>bell</code>,
<code>dead</code>…); here it restarts every 3s so a flash is visible<br>
<code>+ - * / %</code> integer only; division by zero is 0<br>
<code>< > <= >= == != && || !</code> give 0 or 1, so
<code>(x < 10) * 200</code> is a rule<br>
<code>& | ^ ~ << >></code> on the 32-bit value, binding tighter
than comparison, so <code>x & 7 == 0</code> reads as it looks<br>
<code>a ? b : c</code> <code>min max abs clamp dist</code><br>
<code>sin cos</code> take <em>degrees</em> and answer -255..255, so
<code>128 + sin(t / 4) / 2</code> is a breathe<br>
<code>dist</code> counts a row double, because a cell is about twice as
tall as it is wide.
</p>
</div>
<div id="right">
<canvas id="screen"></canvas>
<p class="hint" id="status">move the mouse over the preview to move the cursor</p>
</div>
<script>
"use strict";
/* ---- the language ------------------------------------------------------
*
* A transcription of src/expr.c: same variables, same functions, same
* arithmetic, same refusals. Integer everywhere, division by zero is 0
* rather than a trap, and `?:` evaluates both sides and selects — there is
* nothing here with an effect, so it can.
*/
const DEP = { POS: 1, CURSOR: 2, TIME: 4, FOCUS: 8, SIZE: 16 };
/* Pi is not a number in an angle language, it is a half turn -- and angles here
are degrees, so `PI` is 180 and `TAU` is 360. A radian-shaped formula ports
across unchanged, and the common fractions of a turn stay whole. Same table as
src/expr.c, spelled-out numbers rather than variables. */
const CONSTS = { PI: 180, TAU: 360 };
const VARS = {
x: { dep: DEP.POS },
y: { dep: DEP.POS },
cols: { dep: DEP.SIZE },
rows: { dep: DEP.SIZE },
curx: { dep: DEP.CURSOR },
cury: { dep: DEP.CURSOR },
cursor: { dep: DEP.CURSOR },
focused: { dep: DEP.FOCUS },
t: { dep: DEP.TIME },
since: { dep: DEP.TIME },
};
const FNS = { min: 2, max: 2, abs: 1, clamp: 3, dist: 4, sin: 1, cos: 1 };
/* Degrees in, -255..255 out. The same quarter-turn table src/expr.c carries and
the same reduction: identical data cannot drift the way two approximations of
one curve would, and a preview that disagrees with the compiler is worse than
no preview. */
const SIN_Q = [
0, 4, 9, 13, 18, 22, 27, 31, 35, 40, 44, 49, 53,
57, 62, 66, 70, 75, 79, 83, 87, 91, 96, 100, 104, 108,
112, 116, 120, 124, 127, 131, 135, 139, 143, 146, 150, 153, 157,
160, 164, 167, 171, 174, 177, 180, 183, 186, 190, 192, 195, 198,
201, 204, 206, 209, 211, 214, 216, 219, 221, 223, 225, 227, 229,
231, 233, 235, 236, 238, 240, 241, 243, 244, 245, 246, 247, 248,
249, 250, 251, 252, 253, 253, 254, 254, 254, 255, 255, 255, 255
];
const isin = (deg) => {
let d = deg % 360;
if (d < 0) d += 360;
if (d <= 90) return SIN_Q[d];
if (d <= 180) return SIN_Q[180 - d];
if (d <= 270) return -SIN_Q[d - 180];
return -SIN_Q[360 - d];
};
function compile(src) {
let i = 0, deps = 0;
const ws = () => { while (i < src.length && /\s/.test(src[i])) i++; };
const fail = (what) => { throw new Error(`${what} at offset ${i}`); };
function primary() {
ws();
if (src[i] === "(") { i++; const e = expr(); ws();
if (src[i] !== ")") fail("expected )"); i++; return e; }
/* The env has to be threaded through every closure, including these two:
* forgetting it here made `!x` throw instead of evaluating, which the
* conformance test caught on its first run. */
if (src[i] === "-") { i++; const a = primary(); return (e) => -a(e); }
if (src[i] === "~") { i++; const a = primary(); return (e) => ~a(e); }
if (src[i] === "!") { i++; const a = primary(); return (e) => a(e) ? 0 : 1; }
if (/[0-9]/.test(src[i] || "")) {
let s = i; while (/[0-9]/.test(src[i] || "")) i++;
const v = parseInt(src.slice(s, i), 10); return () => v;
}
if (/[A-Za-z_]/.test(src[i] || "")) {
let s = i; while (/[A-Za-z0-9_]/.test(src[i] || "")) i++;
const name = src.slice(s, i);
ws();
if (src[i] === "(") {
i++;
const arity = FNS[name];
if (arity === undefined) { i = s; fail("unknown function"); }
const args = [];
for (let a = 0; a < arity; a++) {
if (a) { ws(); if (src[i] !== ",") fail("expected ,"); i++; }
args.push(expr());
}
ws(); if (src[i] !== ")") fail("expected )"); i++;
return makeCall(name, args);
}
if (name in CONSTS) { const k = CONSTS[name]; return () => k; }
const v = VARS[name];
if (!v) { i = s; fail("unknown name"); }
deps |= v.dep;
return (env) => env[name];
}
fail("expected a value");
}
function makeCall(name, a) {
switch (name) {
case "min": return (e) => Math.min(a[0](e), a[1](e));
case "max": return (e) => Math.max(a[0](e), a[1](e));
case "abs": return (e) => Math.abs(a[0](e));
case "sin": return (e) => isin(a[0](e));
case "cos": return (e) => isin(a[0](e) + 90);
case "clamp": return (e) => { const v = a[0](e), lo = a[1](e), hi = a[2](e);
return v < lo ? lo : v > hi ? hi : v; };
/* A row counts double: a cell is about twice as tall as it is wide, and
* without this every "circle" is an ellipse. Integer square root, so
* `dist` is a distance and not its square. */
case "dist": return (e) => {
const dx = a[0](e) - a[2](e), dy = (a[1](e) - a[3](e)) * 2;
return Math.min(Math.floor(Math.sqrt(dx * dx + dy * dy)), 4096);
};
}
}
const binop = (op, l, r) => {
switch (op) {
case "*": return (e) => Math.trunc(l(e) * r(e));
case "/": return (e) => { const b = r(e); return b ? Math.trunc(l(e) / b) : 0; };
case "%": return (e) => { const b = r(e); return b ? l(e) % b : 0; };
case "+": return (e) => l(e) + r(e);
case "-": return (e) => l(e) - r(e);
case "<": return (e) => (l(e) < r(e)) | 0;
case ">": return (e) => (l(e) > r(e)) | 0;
case "<=": return (e) => (l(e) <= r(e)) | 0;
case ">=": return (e) => (l(e) >= r(e)) | 0;
case "==": return (e) => (l(e) === r(e)) | 0;
case "!=": return (e) => (l(e) !== r(e)) | 0;
case "&&": return (e) => (l(e) && r(e)) ? 1 : 0;
case "||": return (e) => (l(e) || r(e)) ? 1 : 0;
/* JS's own bitwise operators are int32 with a five-bit shift count, which
is exactly what the compiler in src/expr.c does -- deliberately, so that
this preview and the real thing cannot disagree. */
case "&": return (e) => l(e) & r(e);
case "^": return (e) => l(e) ^ r(e);
case "|": return (e) => l(e) | r(e);
case "<<": return (e) => l(e) << r(e);
case ">>": return (e) => l(e) >> r(e);
}
};
function mul() {
let l = primary();
for (;;) { ws();
const c = src[i];
if (c !== "*" && c !== "/" && c !== "%") return l;
i++; l = binop(c, l, primary());
}
}
function add() {
let l = mul();
for (;;) { ws();
const c = src[i];
if (c !== "+" && c !== "-") return l;
i++; l = binop(c, l, mul());
}
}
/* Bitwise binds tighter than comparison, unlike C: `x & 7 == 0` asks what it
looks like. Same ladder as src/expr.c, which is the point. */
function shift() {
let l = add();
for (;;) { ws();
const two = src.substr(i, 2);
if (two !== "<<" && two !== ">>") return l;
i += 2; l = binop(two, l, add());
}
}
function band() {
let l = shift();
for (;;) { ws();
if (src[i] !== "&" || src[i + 1] === "&") return l; /* not `&&` */
i++; l = binop("&", l, shift());
}
}
function bxor() {
let l = band();
for (;;) { ws();
if (src[i] !== "^") return l;
i++; l = binop("^", l, band());
}
}
function bor() {
let l = bxor();
for (;;) { ws();
if (src[i] !== "|" || src[i + 1] === "|") return l; /* not `||` */
i++; l = binop("|", l, bxor());
}
}
function cmp() {
let l = bor();
for (;;) { ws();
/* Longest first, or `<` eats the `<` of `<=` and leaves an `=`. */
const two = src.substr(i, 2);
if (["<=", ">=", "==", "!="].includes(two)) { i += 2; l = binop(two, l, bor()); continue; }
const c = src[i];
if (c === "<" || c === ">") { i++; l = binop(c, l, bor()); continue; }
return l;
}
}
function and() {
let l = cmp();
while (ws(), src.substr(i, 2) === "&&") { i += 2; l = binop("&&", l, cmp()); }
return l;
}
function or() {
let l = and();
while (ws(), src.substr(i, 2) === "||") { i += 2; l = binop("||", l, and()); }
return l;
}
function expr() {
const c = or(); ws();
if (src[i] !== "?") return c;
i++;
const a = expr(); ws();
if (src[i] !== ":") fail("expected :");
i++;
const b = expr();
return (e) => (c(e) ? a(e) : b(e));
}
if (!src.trim()) throw new Error("empty expression");
const fn = expr();
ws();
if (i < src.length) fail("unexpected trailing input");
return { fn, deps, constant: deps === 0 };
}
/* ---- the colour ops ----------------------------------------------------
* The three that take an expression. Identical maths to src/shader.c,
* including Rec. 601 luma — the green weight is not a rounding error.
*/
const mix8 = (from, to, a) => ((from * (255 - a) + to * a) / 255) | 0;
const mix = (c, to, a) => [mix8(c[0], to[0], a), mix8(c[1], to[1], a), mix8(c[2], to[2], a)];
const luma = (c) => ((c[0] * 77 + c[1] * 150 + c[2] * 29) >> 8);
const OPS = {
dim: (cell, amt) => { cell.fg = mix(cell.fg, [0, 0, 0], amt);
cell.bg = mix(cell.bg, [0, 0, 0], amt); },
grayscale: (cell, amt) => { const f = luma(cell.fg), b = luma(cell.bg);
cell.fg = mix(cell.fg, [f, f, f], amt);
cell.bg = mix(cell.bg, [b, b, b], amt); },
tint: (cell, amt, col) => { cell.fg = mix(cell.fg, col, amt);
cell.bg = mix(cell.bg, col, amt); },
};
/* ---- the fake pane ------------------------------------------------------ */
const COLS = 64, ROWS = 24, CW = 9, CH = 18;
const DEFAULT_FG = [0xff, 0xff, 0xff], DEFAULT_BG = [0x0d, 0x0d, 0x10];
/* Something with shape to it, so an effect has something to be wrong about. */
const SAMPLE = [
["#7a7a86", "/* the layout pass, once a frame */"],
["#ff5fd7", "static void layout_node(node_t *n, rect_t r) {"],
["#e8e8ea", " n->rect = r; // derived, never remembered"],
["#e8e8ea", " if (n->kind == NODE_LEAF) return;"],
["", ""],
["#e8e8ea", " int total = 0;"],
["#e8e8ea", " for (size_t i = 0; i < n->nkids; i++)"],
["#f0c674", " total += n->kids[i]->weight;"],
["", ""],
["#7a7a86", " /* every child gets its share of the axis */"],
["#e8e8ea", " for (size_t i = 0; i < n->nkids; i++) {"],
["#81a2be", " rect_t k = split_share(r, n->kids[i], total);"],
["#81a2be", " layout_node(n->kids[i], k);"],
["#e8e8ea", " }"],
["#e8e8ea", "}"],
["", ""],
["#7a7a86", "$ slosh -s work"],
["#b5bd68", "user@clank ~/dev/slosh master ❯ make test"],
["#7fd67f", " ok test_shaders.py 48 checks"],
["#7fd67f", " ok test_shader_expr.py 11 checks"],
["#7fd67f", " ok test_graphics.py 33 checks"],
["#e8e8ea", " all green"],
["", ""],
["#b5bd68", "user@clank ~/dev/slosh master ❯ "],
];
const hex2rgb = (h) => [parseInt(h.slice(1, 3), 16), parseInt(h.slice(3, 5), 16),
parseInt(h.slice(5, 7), 16)];
const rgb2css = (c) => `rgb(${c[0]},${c[1]},${c[2]})`;
/* ---- presets ------------------------------------------------------------
*
* Grouped, because most of these are not effects so much as *instruments*:
* something that tells you where the cursor is, or where column 64 is, in a
* program that has never heard of either.
*
* Two rules learned the hard way, both about staying identical to the C:
* - never multiply `t`. It is a millisecond clock and gets large; divide it
* down first (`t / 40`) and the arithmetic stays inside an int32 forever.
* - keep coefficients small for the same reason. `(x * 11) % 23` is a fine
* hash here; `x * 2654435761` is a different number in C than in JS.
*/
const PRESETS = {
"guides": {
"cursor line": [{ op: "tint", amount: "(y == cury) * 45", color: "#ff5fd7" }],
"crosshair": [{ op: "dim", amount: "((y == cury) || (x == curx)) * 55", color: "#ff5fd7" }],
"focus mode": [{ op: "dim", amount: "clamp(abs(y - cury) * 26, 0, 190)", color: "#ff5fd7" }],
"torch": [{ op: "dim", amount: "clamp((dist(x, y, curx, cury) - 8) * 22, 0, 215)", color: "#ff5fd7" }],
"indent guides":[{ op: "tint", amount: "(x % 4 == 0) * 38", color: "#7aa2f7" }],
"thirds": [{ op: "tint", amount: "(x == cols / 3 || x == cols * 2 / 3) * 140", color: "#ff5fd7" }],
"right margin": [{ op: "dim", amount: "clamp((x - cols * 3 / 4) * 30, 0, 170)", color: "#ff5fd7" }],
"edge falloff": [{ op: "dim", amount: "clamp((5 - min(x, cols - 1 - x)) * 34, 0, 170)", color: "#ff5fd7" }],
},
"crt": {
"phosphor": [
{ op: "grayscale", amount: "255", color: "#33ff66" },
{ op: "tint", amount: "80", color: "#33ff66" },
{ op: "dim", amount: "(y % 3 == 0) * 55", color: "#33ff66" },
{ op: "dim", amount: "clamp(dist(x, y, cols / 2, rows / 2) * 4, 0, 150)", color: "#33ff66" },
],
"amber": [
{ op: "grayscale", amount: "255", color: "#ffb000" },
{ op: "tint", amount: "95", color: "#ffb000" },
{ op: "dim", amount: "(y % 2) * 40", color: "#ffb000" },
],
"rolling bar": [{ op: "dim", amount: "(abs(y - (t / 90) % rows) < 2) * 70", color: "#ff5fd7" }],
"interlace": [{ op: "dim", amount: "((y + t / 80) % 2) * 45", color: "#ff5fd7" }],
"film": [
{ op: "grayscale", amount: "255", color: "#ffffff" },
{ op: "dim", amount: "((x * 7 + y * 13 + t / 40) % 17 < 2) * 70", color: "#ffffff" },
{ op: "dim", amount: "clamp(dist(x, y, cols / 2, rows / 2) * 5, 0, 165)", color: "#ffffff" },
],
},
"motion": {
"sonar": [{ op: "tint", amount: "(abs(dist(x, y, curx, cury) - (t / 22) % 80) < 3) * 220", color: "#33ff66" }],
"ripples": [{ op: "tint", amount: "((dist(x, y, curx, cury) + t / 30) % 10 < 5) * 50", color: "#7aa2f7" }],
"matrix rain": [
{ op: "grayscale", amount: "220", color: "#33ff66" },
{ op: "tint", color: "#33ff66",
amount: "clamp(240 - (((t / 70 + (x * 11) % 23 * 3) % rows - y + rows) % rows) * 45, 0, 240)" },
],
"barber pole": [{ op: "dim", amount: "((x + y + t / 50) / 3 % 2) * 50", color: "#ff5fd7" }],
"plasma": [{ op: "dim",
amount: "clamp(abs((x * 2 + t / 40) % 34 - 17) * 7 + abs((y * 3 - t / 55) % 26 - 13) * 6 - 40, 0, 170)",
color: "#ff5fd7" }],
"sweep": [{ op: "dim", amount: "clamp(abs(x - (t / 24) % cols) * 22, 0, 200)", color: "#ff5fd7" }],
"pulse": [{ op: "tint", amount: "clamp((t / 6) % 300 - 45, 0, 160)", color: "#ff5fd7" }],
"typewriter": [{ op: "dim", amount: "(y > (t / 400) % rows) * 200", color: "#ff5fd7" }],
},
"built-ins, as expressions": {
"scanlines": [{ op: "dim", amount: "(y % 2) * 40", color: "#ff5fd7" }],
"vignette": [{ op: "dim", amount: "clamp(dist(x, y, cols / 2, rows / 2) * 4, 0, 190)", color: "#ff5fd7" }],
"spotlight": [{ op: "dim", amount: "clamp(dist(x, y, curx, cury) * 9, 0, 200)", color: "#ff5fd7" }],
"zebra": [{ op: "dim", amount: "(y / 3 % 2) * 60", color: "#ff5fd7" }],
"ruler": [{ op: "tint", amount: "(x == 40) * 220", color: "#ff5fd7" }],
"gradient": [{ op: "dim", amount: "y * 200 / rows", color: "#ff5fd7" }],
"checker": [{ op: "dim", amount: "((x / 8 + y / 4) % 2) * 45", color: "#ff5fd7" }],
},
"pane states": {
"unfocused": [{ op: "dim", amount: "90", color: "#ff5fd7" }],
"dead": [{ op: "grayscale", amount: "200", color: "#ff5fd7" },
{ op: "dim", amount: "90", color: "#ff5fd7" }],
"scrolled": [{ op: "tint", amount: "30", color: "#ffcc88" }],
"suspended": [{ op: "grayscale", amount: "180", color: "#ff5fd7" },
{ op: "dim", amount: "90", color: "#ff5fd7" }],
},
};
/* ---- the chain UI ------------------------------------------------------- */
let chain = structuredClone(PRESETS["guides"]["focus mode"]);
let cursor = { x: 44, y: 23 };
const el = (tag, props = {}, kids = []) => {
const n = Object.assign(document.createElement(tag), props);
for (const k of kids) n.append(k);
return n;
};
function renderChain() {
const box = document.getElementById("chain");
box.replaceChildren();
chain.forEach((pass, idx) => {
const op = el("select");
for (const name of Object.keys(OPS)) {
op.append(el("option", { value: name, textContent: name, selected: pass.op === name }));
}
op.onchange = () => { pass.op = op.value; refresh(); };
const col = el("input", { type: "color", value: pass.color, title: "color, for tint" });
col.oninput = () => { pass.color = col.value; refresh(); };
const amt = el("input", { type: "text", value: pass.amount, spellcheck: false,
placeholder: "amount expression" });
amt.oninput = () => { pass.amount = amt.value; refresh(); };
const del = el("button", { className: "x", textContent: "×", title: "remove" });
del.onclick = () => { chain.splice(idx, 1); renderChain(); refresh(); };
const err = el("div", { className: "err", id: `err${idx}` });
const deps = el("div", { className: "deps", id: `dep${idx}` });
box.append(el("div", { className: "pass" }, [
el("div", { className: "row" }, [op, col, del]),
el("div", { className: "row" }, [amt]),
err, deps,
]));
});
}
function renderPresets() {
const box = document.getElementById("presets");
for (const [group, entries] of Object.entries(PRESETS)) {
box.append(el("div", { className: "group", textContent: group }));
const row = el("div", { className: "presets" });
for (const [name, passes] of Object.entries(entries)) {
const b = el("button", { textContent: name });
b.onclick = () => { chain = structuredClone(passes); renderChain(); refresh(); };
row.append(b);
}
box.append(row);
}
}
/* ---- the preview -------------------------------------------------------- */
const canvas = document.getElementById("screen");
const ctx = canvas.getContext("2d");
/* Two sizes, deliberately. The backing store is device pixels, so text stays
* sharp on a HiDPI screen; the CSS size is the one the layout sees, and it is
* fixed at the real thing so nothing ever stretches a 576-pixel preview
* across a 1400-pixel pane and calls it a terminal. */
function sizeCanvas() {
const dpr = Math.max(1, Math.min(3, window.devicePixelRatio || 1));
canvas.width = COLS * CW * dpr;
canvas.height = ROWS * CH * dpr;
canvas.style.width = `${COLS * CW}px`;
canvas.style.height = `${ROWS * CH}px`;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
}
sizeCanvas();
window.addEventListener("resize", sizeCanvas);
canvas.addEventListener("mousemove", (e) => {
const r = canvas.getBoundingClientRect();
cursor.x = Math.max(0, Math.min(COLS - 1, Math.floor((e.clientX - r.left) / r.width * COLS)));
cursor.y = Math.max(0, Math.min(ROWS - 1, Math.floor((e.clientY - r.top) / r.height * ROWS)));
});
let compiled = [];
function refresh() {
compiled = chain.map((pass, idx) => {
const errBox = document.getElementById(`err${idx}`);
const depBox = document.getElementById(`dep${idx}`);
try {
const prog = compile(pass.amount);
if (errBox) errBox.textContent = "";
if (depBox) {
const names = Object.entries(DEP)
.filter(([, bit]) => prog.deps & bit)
.map(([n]) => n.toLowerCase());
/* The same classification slosh makes, and for the same reason:
* anything that does not read the clock is worked out once per cell
* and reused. */
const cacheable = !(prog.deps & DEP.TIME);
depBox.innerHTML = prog.constant
? `reads <b>nothing</b> · folded to a constant at load`
: `reads <b>${names.join(", ")}</b> · ` + (cacheable
? `<span class="cached">cached as a per-cell map</span>`
: `<span class="live">re-evaluated every frame</span>`);
}
return { ...pass, prog };
} catch (e) {
if (errBox) errBox.textContent = e.message;
if (depBox) depBox.textContent = "";
return null; /* refused: this pass does nothing */
}
}).filter(Boolean);
document.getElementById("config").textContent =
"shaders {\n" + chain.map((p) =>
` ${p.op}${p.op === "tint" ? ` color="${p.color}"` : ""} amount="${p.amount}"`
).join("\n") + "\n}";
}
function draw(now) {
ctx.fillStyle = rgb2css(DEFAULT_BG);
ctx.fillRect(0, 0, COLS * CW, ROWS * CH);
ctx.font = `${CH - 5}px ui-monospace, monospace`;
ctx.textBaseline = "top";
/* `since` is how long the pane has been in its current state. This preview
has no pane and no states, so it is simulated: the clock restarts every
three seconds, as if something rang again — which is the only way a
one-shot effect (a bell flash) is visible in a preview at all. Said out
loud in the legend, because a preview that quietly means something else
than the session does is worse than no preview. */
const env = { cols: COLS, rows: ROWS, curx: cursor.x, cury: cursor.y,
cursor: 1, focused: 1, t: Math.floor(now),
since: Math.floor(now) % 3000, x: 0, y: 0 };
for (let y = 0; y < ROWS; y++) {
const [colour, text] = SAMPLE[y] || ["", ""];
const fg0 = colour ? hex2rgb(colour) : DEFAULT_FG;
for (let x = 0; x < COLS; x++) {
const ch = text[x] || " ";
const cell = { fg: fg0.slice(), bg: DEFAULT_BG.slice() };
env.x = x; env.y = y;
for (const pass of compiled) {
let amt = pass.prog.fn(env);
amt = amt < 0 ? 0 : amt > 255 ? 255 : amt | 0;
OPS[pass.op](cell, amt, hex2rgb(pass.color));
}
ctx.fillStyle = rgb2css(cell.bg);
ctx.fillRect(x * CW, y * CH, CW, CH);
if (ch !== " ") {
ctx.fillStyle = rgb2css(cell.fg);
ctx.fillText(ch, x * CW, y * CH + 2);
}
}
}
/* The cursor, drawn the way a terminal would, so a spotlight has something
* to point at. */
ctx.fillStyle = "#ff5fd7";
ctx.globalAlpha = 0.85;
ctx.fillRect(cursor.x * CW, cursor.y * CH, CW, CH);
ctx.globalAlpha = 1;
document.getElementById("status").textContent =
`cursor ${cursor.x},${cursor.y} · ${COLS}×${ROWS} cells · ` +
(compiled.some((p) => p.prog.deps & DEP.TIME)
? "animating (an expression reads t)"
: "static (nothing reads t)");
requestAnimationFrame(draw);
}
document.getElementById("add").onclick = () => {
chain.push({ op: "dim", amount: "90", color: "#ff5fd7" });
renderChain(); refresh();
};
renderPresets();
renderChain();
refresh();
requestAnimationFrame(draw);
</script>
</body>
</html>
|