Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
416 lines (365 loc) · 13.7 KB
/
Copy pathindex.js
File metadata and controls
416 lines (365 loc) · 13.7 KB
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
// Renders f(X, Y) = ((X + tx)(Y + ty) + step) mod n per CSS pixel.
// (X, Y) are canvas pixel coordinates (top-left origin). (tx, ty) is the
// pan offset. n is THE knob.
//
// The pattern is periodic with period n in both X and Y: changing n
// renders a different-sized tile of the same modular-multiplication
// structure (mod 256, mod 512, mod 2048 all share the same hyperbolic
// structure; bigger n just means a bigger tile with more bands resolved
// inside it). The canvas may show multiple tiles side-by-side.
//
// "Zoom by α around cursor (cx, cy)" means:
// • The tile grows from n × n pixels to (α·n) × (α·n) pixels.
// • The cursor stays at the same relative position inside whichever
// tile it's in: (cx + tx) mod n / n is invariant across the zoom.
//
// To achieve that, the cursor's intrinsic coord A = cx + tx must satisfy
// A_new / n_new = A_old / n_old, i.e. A scales linearly with n:
//
// n ← α · n
// tx ← cx·(α − 1) + α·tx
// ty ← cy·(α − 1) + α·ty
//
// The color at the cursor pixel does change after a zoom — what's
// preserved is the cursor's *position* in the tile, not the value the
// pattern happens to take there (since "mod 256" and "mod 512" of the
// same intrinsic product give different residues).
//
// Precision. The shader works in float32 (24-bit mantissa). Direct
// computation of (X + tx)(Y + ty) overflows precision as tx, ty grow,
// so we expand: (X + tx)(Y + ty) = X·Y + X·ty + Y·tx + tx·ty. JS computes
// c0 = (tx·ty) mod n at double precision and passes it as a uniform; the
// shader works with the residual terms whose magnitudes are bounded by
// canvas_w · |ty|, canvas_h · |tx|.
const canvas = document.getElementById('canvas');
const gl = canvas.getContext('webgl', { antialias: false, preserveDrawingBuffer: false });
if (!gl) throw new Error('WebGL not supported');
const vs = `
attribute vec2 pos;
varying vec2 uv;
void main() {
uv = pos * 0.5 + 0.5;
gl_Position = vec4(pos, 0.0, 1.0);
}
`;
const fs = `
precision highp float;
varying vec2 uv;
uniform float c0; // (tx * ty) mod n, precomputed in JS doubles
uniform float canvas_w; // CSS pixels
uniform float canvas_h;
uniform float tx;
uniform float ty;
uniform float n;
uniform float step_;
uniform int palette;
const float PI = 3.14159265358979;
vec3 hsv2rgb(vec3 c) {
vec4 K = vec4(1.0, 2.0/3.0, 1.0/3.0, 3.0);
vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);
return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);
}
void main() {
// CSS pixel coords with top-left origin (matches mouse coords).
float X = uv.x * canvas_w;
float Y = (1.0 - uv.y) * canvas_h;
float val = X * Y + X * ty + Y * tx + c0 + step_;
float m = mod(val, n);
float t = m / n;
vec3 color;
if (palette == 0) {
color = vec3(t);
} else if (palette == 1) {
color = vec3(step(0.5, t));
} else if (palette == 2) {
color = vec3(min(1.0 - t, t) * 2.0);
} else if (palette == 3) {
color = vec3(sin(t * PI));
} else if (palette == 4) {
float mg = mod(m + n / 3.0, n);
float mb = mod(m + 2.0 * n / 3.0, n);
float tg = mg / n;
float tb = mb / n;
float r = (sin(t * PI) - 0.9) * 10.0;
float g = (sin(tg * PI) - 0.9) * 10.0;
float b = (sin(tb * PI) - 0.9) * 10.0;
color = vec3(r, g, b);
} else {
color = hsv2rgb(vec3(t, 1.0, 1.0));
}
gl_FragColor = vec4(color, 1.0);
}
`;
function compile(type, src) {
const sh = gl.createShader(type);
gl.shaderSource(sh, src);
gl.compileShader(sh);
if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) {
throw new Error('Shader compile failed: ' + gl.getShaderInfoLog(sh));
}
return sh;
}
const program = gl.createProgram();
gl.attachShader(program, compile(gl.VERTEX_SHADER, vs));
gl.attachShader(program, compile(gl.FRAGMENT_SHADER, fs));
gl.linkProgram(program);
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
throw new Error('Program link failed: ' + gl.getProgramInfoLog(program));
}
gl.useProgram(program);
const buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
-1, -1, 1, -1, -1, 1,
-1, 1, 1, -1, 1, 1,
]), gl.STATIC_DRAW);
const posLoc = gl.getAttribLocation(program, 'pos');
gl.enableVertexAttribArray(posLoc);
gl.vertexAttribPointer(posLoc, 2, gl.FLOAT, false, 0, 0);
const uniforms = {
c0: gl.getUniformLocation(program, 'c0'),
canvas_w: gl.getUniformLocation(program, 'canvas_w'),
canvas_h: gl.getUniformLocation(program, 'canvas_h'),
tx: gl.getUniformLocation(program, 'tx'),
ty: gl.getUniformLocation(program, 'ty'),
n: gl.getUniformLocation(program, 'n'),
step: gl.getUniformLocation(program, 'step_'),
palette: gl.getUniformLocation(program, 'palette'),
};
// --- State ---------------------------------------------------------------
const DEFAULT_N = 1024;
const state = {
tx: 0,
ty: 0,
n: DEFAULT_N,
palette: 0,
paused: false,
speed: 1.0, // speed=1 → one full color cycle per ~1024 frames
phase: 0, // animation phase in [0, 1); shader step = phase · n
debug: false, // show tile box + cursor crosshair + cursor readout
};
const CYCLE_FRAMES = 1024;
function positiveMod(a, b) {
return ((a % b) + b) % b;
}
// Zoom by α around cursor (cx, cy) in CSS-pixel coords.
//
// "Zoom by α" means the pattern's natural unit [0, n] × [0, n] grows by
// α in each linear pixel dimension (so features inside it appear α times
// bigger on screen), and the cursor stays at the same *relative* position
// within that unit.
//
// Cursor's intrinsic coord A = cx + tx. Cursor's relative position in the
// natural unit is A/n. For that to be invariant under zoom:
// A_new / n_new = A_old / n_old
// with n_new = α·n_old, this gives A_new = α·A_old, i.e.:
// tx_new = cx·(α-1) + α·tx_old
// ty_new = cy·(α-1) + α·ty_old
// n_new = α·n_old
//
// Pattern at cursor pixel does change color across the zoom — what stays
// invariant is the cursor's position in the natural unit, not the value
// the pattern happens to take there.
function zoomAround(alpha, cx, cy) {
if (!Number.isFinite(alpha) || alpha <= 0 || alpha === 1) return;
state.n *= alpha;
state.tx = cx * (alpha - 1) + alpha * state.tx;
state.ty = cy * (alpha - 1) + alpha * state.ty;
}
// Resize the framebuffer to match the window at devicePixelRatio.
function resizeCanvas() {
const dpr = window.devicePixelRatio || 1;
const cssW = window.innerWidth;
const cssH = window.innerHeight;
canvas.style.width = cssW + 'px';
canvas.style.height = cssH + 'px';
const w = Math.max(1, Math.floor(cssW * dpr));
const h = Math.max(1, Math.floor(cssH * dpr));
if (canvas.width !== w || canvas.height !== h) {
canvas.width = w;
canvas.height = h;
gl.viewport(0, 0, w, h);
}
}
// --- UI ------------------------------------------------------------------
const paletteSelect = document.getElementById('palette-select');
const speedSlider = document.getElementById('speed-slider');
const speedValue = document.getElementById('speed-value');
const nInput = document.getElementById('n-input');
const pauseBtn = document.getElementById('pause-btn');
const resetBtn = document.getElementById('reset-btn');
const debugBtn = document.getElementById('debug-btn');
const readout = document.getElementById('coord-readout');
const cursorMarker = document.getElementById('cursor-marker');
const tileBox = document.getElementById('tile-box');
// Tracked cursor position (CSS pixels relative to canvas top-left).
let cursorCx = NaN;
let cursorCy = NaN;
paletteSelect.addEventListener('change', e => {
state.palette = parseInt(e.target.value, 10) | 0;
});
function applySpeedSlider() {
// log slider: -2 → 0.01, 0 → 1, 2 → 100
state.speed = Math.pow(10, parseFloat(speedSlider.value));
speedValue.textContent = state.speed.toFixed(state.speed < 0.1 ? 3 : 2);
}
speedSlider.addEventListener('input', applySpeedSlider);
applySpeedSlider();
// Typing n: snap to that modulus around viewport center. Equivalent to a
// zoom by α = sqrt(new_n / current_n) centered on the canvas — keeps the
// middle of the screen anchored visually instead of jumping arbitrarily.
nInput.addEventListener('input', e => {
const v = parseFloat(e.target.value);
if (Number.isFinite(v) && v > 0 && v !== state.n) {
const cx = canvas.clientWidth / 2;
const cy = canvas.clientHeight / 2;
const alpha = Math.sqrt(v / state.n);
zoomAround(alpha, cx, cy);
}
});
pauseBtn.addEventListener('click', () => {
state.paused = !state.paused;
pauseBtn.textContent = state.paused ? 'Play' : 'Pause';
});
function setDebug(on) {
state.debug = on;
debugBtn.textContent = on ? 'Debug ✓' : 'Debug';
tileBox.style.display = on ? 'block' : 'none';
if (!on) cursorMarker.style.display = 'none';
}
debugBtn.addEventListener('click', () => setDebug(!state.debug));
function resetAll() {
state.tx = 0;
state.ty = 0;
state.n = DEFAULT_N;
state.phase = 0;
nInput.value = String(DEFAULT_N);
}
resetBtn.addEventListener('click', resetAll);
window.addEventListener('keydown', e => {
if (e.target instanceof HTMLInputElement || e.target instanceof HTMLSelectElement) return;
if (e.key === ' ' || e.code === 'Space') {
e.preventDefault();
pauseBtn.click();
} else if (e.key === 'r' || e.key === 'R') {
resetBtn.click();
} else if (e.key === 'd' || e.key === 'D') {
setDebug(!state.debug);
}
});
// --- Mouse pan / zoom ----------------------------------------------------
let dragging = false;
let lastPx = 0;
let lastPy = 0;
canvas.addEventListener('mousedown', e => {
dragging = true;
lastPx = e.clientX;
lastPy = e.clientY;
canvas.classList.add('dragging');
});
window.addEventListener('mouseup', () => {
dragging = false;
canvas.classList.remove('dragging');
});
window.addEventListener('mousemove', e => {
// Track cursor for marker + readout, regardless of dragging.
const rect = canvas.getBoundingClientRect();
cursorCx = e.clientX - rect.left;
cursorCy = e.clientY - rect.top;
if (state.debug) {
cursorMarker.style.left = e.clientX + 'px';
cursorMarker.style.top = e.clientY + 'px';
cursorMarker.style.display = 'block';
}
if (!dragging) return;
const dpx = e.clientX - lastPx;
const dpy = e.clientY - lastPy;
lastPx = e.clientX;
lastPy = e.clientY;
// f_new(X, Y) = f_old(X - dpx, Y - dpy) → tx -= dpx, ty -= dpy.
// (Drag right makes the pattern follow the cursor.)
state.tx -= dpx;
state.ty -= dpy;
});
window.addEventListener('mouseleave', () => {
cursorMarker.style.display = 'none';
});
// Explicit 2× zoom at click position — easier to verify the anchor visually
// than tiny wheel ticks. Shift-double-click for 0.5× (zoom out). Reset is
// the R key (no longer double-click, to avoid the conflict).
canvas.addEventListener('dblclick', e => {
const rect = canvas.getBoundingClientRect();
const cx = e.clientX - rect.left;
const cy = e.clientY - rect.top;
const alpha = e.shiftKey ? 0.5 : 2;
zoomAround(alpha, cx, cy);
});
canvas.addEventListener('wheel', e => {
e.preventDefault();
const rect = canvas.getBoundingClientRect();
const cx = e.clientX - rect.left;
const cy = e.clientY - rect.top;
// Wheel up (deltaY < 0) → α > 1 → n grows, features magnify around cursor.
const alpha = Math.exp(-e.deltaY * 0.0015);
zoomAround(alpha, cx, cy);
}, { passive: false });
// --- Animation loop ------------------------------------------------------
function tick() {
if (document.activeElement !== nInput) {
nInput.value = state.n.toFixed(state.n < 10 ? 4 : 2);
}
if (!state.paused) {
state.phase = positiveMod(state.phase + state.speed / CYCLE_FRAMES, 1);
}
const step = state.phase * state.n;
const c0 = positiveMod(state.tx * state.ty, state.n);
gl.uniform1f(uniforms.c0, c0);
gl.uniform1f(uniforms.canvas_w, canvas.clientWidth);
gl.uniform1f(uniforms.canvas_h, canvas.clientHeight);
gl.uniform1f(uniforms.tx, state.tx);
gl.uniform1f(uniforms.ty, state.ty);
gl.uniform1f(uniforms.n, state.n);
gl.uniform1f(uniforms.step, step);
gl.uniform1i(uniforms.palette, state.palette);
gl.drawArrays(gl.TRIANGLES, 0, 6);
updateTileBox();
updateReadout();
requestAnimationFrame(tick);
}
function fmt(x) {
if (!Number.isFinite(x)) return '∞';
const a = Math.abs(x);
if (a !== 0 && (a < 1e-3 || a >= 1e6)) return x.toExponential(3);
return x.toFixed(a < 1 ? 4 : 2);
}
// Cursor's relative position within the tile it's in. This is the
// invariant zoomAround is supposed to preserve.
function cursorTileRel() {
const a = positiveMod(cursorCx + state.tx, state.n) / state.n;
const b = positiveMod(cursorCy + state.ty, state.n) / state.n;
return [a, b];
}
function updateTileBox() {
if (!state.debug) return;
// Draw the tile whose intrinsic origin (0, 0) sits at canvas pixel
// (-tx, -ty). Position uses CSS pixels relative to the viewport (canvas
// fills the viewport, so canvas-pixel and viewport-pixel coords match).
tileBox.style.left = (-state.tx) + 'px';
tileBox.style.top = (-state.ty) + 'px';
tileBox.style.width = state.n + 'px';
tileBox.style.height = state.n + 'px';
}
function updateReadout() {
let cursor = '';
if (state.debug && Number.isFinite(cursorCx)) {
const [u, v] = cursorTileRel();
cursor = ` cursor (${cursorCx.toFixed(1)}, ${cursorCy.toFixed(1)}) tile-rel (${u.toFixed(3)}, ${v.toFixed(3)})`;
}
readout.textContent =
`tx ${fmt(state.tx)} ty ${fmt(state.ty)} n ${fmt(state.n)}${cursor}`;
}
// --- Init ----------------------------------------------------------------
resizeCanvas();
nInput.value = String(state.n);
window.addEventListener('resize', resizeCanvas);
requestAnimationFrame(tick);