-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
1490 lines (1369 loc) Β· 54.4 KB
/
Copy pathmain.js
File metadata and controls
1490 lines (1369 loc) Β· 54.4 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
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
import ShaderPad from 'shaderpad';
import { createFullscreenCanvas, save } from 'shaderpad/util';
import { tinykeys } from 'tinykeys';
import { Tween, Easing } from '@tweenjs/tween.js';
import { registerSW } from 'virtual:pwa-register';
import palettes, { paletteIds } from './palettes.js';
import { debounce, hexToNormalizedRGB, identity, parseNumber, srgbToLinear, updateHash } from './util.js';
import { getUrlCenterFractionDigits, serializeStateValueForHash } from './urlHash.js';
import {
getApproximatePositionFromCenterComponent,
getApproximateZoomScale,
getRadiusExactForZoom,
} from './viewMath.js';
import handleTouch from './touch.js';
import { DeepZoomManager } from './deepZoom.js';
import { generateDeepDisplayShader } from './deepDisplayShader.js';
import { generatePerturbationShader } from './perturbationShader.js';
import { generateStandardShader } from './standardShader.js';
import { N_COLORS } from './shaderCommon.js';
import * as profiler from './profiler.js';
// Auto-update the service worker.
registerSW({ immediate: true });
import './style.css';
const MIN_ZOOM = 1;
const STANDARD_RENDER_SAFE_MAX_ZOOM = 1e12;
const MAX_ZOOM_DECIMAL_EXPONENT = 400;
const DEEP_ZOOM_THRESHOLD = 16;
const MIN_EXPONENT = 2;
const MAX_EXPONENT = 16;
const MAX_CONSTANT_COMPONENT = 2.5;
const MIN_RESOLUTION_MULTIPLIER = 0.0625;
const MAX_RESOLUTION_MULTIPLIER = 2;
const MIN_ESCAPE_RADIUS = 0.8;
const MAX_ESCAPE_RADIUS = 2;
const MIN_COLOR_SCALE = 0.02;
// High ceiling so the G key can densify banding at deep zoom, where the per-frame
// iteration range shrinks and bands go sparse at shallow-zoom-tuned densities.
// (Automatic compensation β histogram equalization β stays on the TODO list.)
const MAX_COLOR_SCALE = 8.0;
const MIN_SLOPE_LIGHT_HEIGHT = 0.1;
const MAX_SLOPE_LIGHT_HEIGHT = 4;
const MIN_SLOPE_LIGHT_INTENSITY = 0;
const MAX_SLOPE_LIGHT_INTENSITY = 2;
const SLOPE_LIGHT_ANGLE_STEP = 5;
const SLOPE_LIGHT_HEIGHT_STEP = 0.1;
const SLOPE_LIGHT_INTENSITY_STEP = 0.05;
const MIN_SPEED = 0.1;
const MAX_SPEED = 8;
const BASE_ITERATIONS = 256;
// Floor for the deep iteration budget. Picked high enough that the iteration
// range gives palette cycling room (low values cluster everything near the
// cap and the color range collapses). Per-frame shader cost is offset by the
// palette-texture optimization moving display:draw from ~5ms to <1ms.
const DEEP_MIN_ITERATIONS = 8192;
const DEEP_MAX_ITERATIONS = 65536;
const DEEP_ITERATION_ZOOM_FACTOR = 384;
const DEEP_COMPATIBLE_REFERENCE_MAX_OFFSET = 2.5;
// Threshold past which we recompute a closer reference. Pushed up against
// DEEP_COMPATIBLE_REFERENCE_MAX_OFFSET so a single reference stays in use much
// longer before a forced recompute. Each recompute is a visible jump (the
// reference center may shift via findGoodReferenceCenter, every pixel sees a
// different per-pixel perturbation result), so trading some perturbation
// accuracy at large offsets for fewer jumps reads as much smoother.
const DEEP_REFERENCE_RECENTER_OFFSET = 2.0;
const DEEP_SETTLED_REFERENCE_RECENTER_OFFSET = 1.0;
// Start computing the deep reference orbit this many zoom units before crossing the
// deep-zoom threshold so the orbit is ready by the time the user actually needs it.
const DEEP_ZOOM_PREPARATION_MARGIN_EXPONENT = 3;
// Reference orbit is computed with iterations sufficient for this many zoom units
// of headroom past the current zoom. With u_iterations now continuous and
// DEEP_REFERENCE_ITERATION_QUANTUM keeping the recompute trigger from firing every
// zoom unit, ~12 zoom units of headroom is enough to avoid visible recompute jumps
// during normal zooming while keeping reference-orbit GMP work bounded.
const DEEP_REFERENCE_ITERATION_HEADROOM_EXPONENT = 12;
// Coarse quantum applied to the reference-orbit iteration count so the trigger
// (stored < target) doesn't fire every zoom unit. Sized to cover several zoom
// units of u_iterations growth per recompute.
const DEEP_REFERENCE_ITERATION_QUANTUM = 4096;
const DEEP_INTERACTION_MOTION_SETTLE_MS = 200;
// Reproject the held metric frame during interaction; refresh once magnification drifts
// outside these bounds (~3x in either direction).
const DEEP_PREVIEW_REFRESH_MIN_SCALE = 0.35;
const DEEP_PREVIEW_REFRESH_MAX_SCALE = 1 / DEEP_PREVIEW_REFRESH_MIN_SCALE;
const SHOW_ZOOM_MODE_NOTICES = import.meta.env.DEV;
const ORBIT_TEXTURE_OPTIONS = {
internalFormat: 'RGBA32F',
format: 'RGBA',
type: 'FLOAT',
minFilter: 'NEAREST',
magFilter: 'NEAREST',
wrapS: 'CLAMP_TO_EDGE',
wrapT: 'CLAMP_TO_EDGE',
preserveY: false,
};
const METRIC_TEXTURE_OPTIONS = {
internalFormat: 'RGBA32F',
format: 'RGBA',
type: 'FLOAT',
minFilter: 'NEAREST',
magFilter: 'NEAREST',
wrapS: 'CLAMP_TO_EDGE',
wrapT: 'CLAMP_TO_EDGE',
preserveY: false,
};
// 1D palette texture sampled by the display shader. SRGB8_ALPHA8 has the GPU
// decode each entry from sRGB to linear on sample, so LINEAR filtering blends
// adjacent entries in linear space β gamma-correct palette interpolation with
// no per-pixel pow() in the shader. REPEAT wrap makes the palette cycle
// seamlessly.
const PALETTE_TEXTURE_OPTIONS = {
internalFormat: 'SRGB8_ALPHA8',
format: 'RGBA',
type: 'UNSIGNED_BYTE',
minFilter: 'LINEAR',
magFilter: 'LINEAR',
wrapS: 'REPEAT',
wrapT: 'CLAMP_TO_EDGE',
preserveY: false,
};
const FRACTAL_TYPES = ['Julia', 'Mandelbrot', 'Burning Ship', 'Mandala'];
const MIN_ZOOM_EXPONENT = Math.log(MIN_ZOOM) / Math.log(2);
const MAX_ZOOM_EXPONENT = MAX_ZOOM_DECIMAL_EXPONENT / Math.log10(2);
const STANDARD_RENDER_SAFE_ZOOM_EXPONENT = Math.log(STANDARD_RENDER_SAFE_MAX_ZOOM) / Math.log(2);
const deepZoomManager = new DeepZoomManager({ threshold: DEEP_ZOOM_THRESHOLD });
let resolutionMultiplier = window.devicePixelRatio || 1;
let standardIterationRenderer = null;
let standardIterationVariantKey = null;
let deepIterationRenderer = null;
let deepIterationVariantKey = null;
let displayRenderer = null;
let lastStandardIterationRenderSignature = null;
let lastUploadedDeepOrbitSignature = null;
let lastDeepIterationRenderSignature = null;
let lastUnsupportedDeepZoomReason = null;
let lastDeepZoomActive = false;
let isDeepInteractionInMotion = false;
let deepMetricAnchor = null;
let deepPreviewTransformCache = null;
let colorsVersion = 0;
let displayRendererColorsVersion = -1;
let paletteFrame = 0;
let lastPaletteUpdateMs = null;
const PALETTE_SECONDS_PER_BAND = 0.3125;
tinykeys(window, {
KeyC: () => updateColors(1),
'Shift+KeyC': () => updateColors(-1),
KeyD: () => {
setResolutionMultiplier(resolutionMultiplier * 2);
showInfo(`Density: ${resolutionMultiplier * 100}%`);
},
'Shift+KeyD': () => {
setResolutionMultiplier(resolutionMultiplier / 2);
showInfo(`Density: ${resolutionMultiplier * 100}%`);
},
KeyE: () => {
setState({ exponent: Math.min(MAX_EXPONENT, state.exponent + 1) });
showInfo(`Exponent: ${state.exponent}`);
},
'Shift+KeyE': () => {
setState({ exponent: Math.max(MIN_EXPONENT, state.exponent - 1) });
showInfo(`Exponent: ${state.exponent}`);
},
KeyF: () => {
setState({ fractalType: (state.fractalType + 1) % FRACTAL_TYPES.length });
showInfo(`Fractal type: ${FRACTAL_TYPES[state.fractalType]}`);
},
'Shift+KeyF': () => {
setState({ fractalType: (FRACTAL_TYPES.length + (state.fractalType - 1)) % FRACTAL_TYPES.length });
showInfo(`Fractal type: ${FRACTAL_TYPES[state.fractalType]}`);
},
KeyG: () => {
const colorScale = Math.min(MAX_COLOR_SCALE, state.colorScale * 1.15);
setState({ colorScale });
showInfo(`Color density: ${colorScale.toFixed(3)}`);
},
'Shift+KeyG': () => {
const colorScale = Math.max(MIN_COLOR_SCALE, state.colorScale / 1.15);
setState({ colorScale });
showInfo(`Color density: ${colorScale.toFixed(3)}`);
},
KeyI: () => {
setState({ cImaginary: Math.min(MAX_CONSTANT_COMPONENT, state.cImaginary + 0.01) });
showInfo(`C (imaginary): ${state.cImaginary.toFixed(2)}`);
},
'Shift+KeyI': () => {
setState({ cImaginary: Math.max(-MAX_CONSTANT_COMPONENT, state.cImaginary - 0.01) });
showInfo(`C (imaginary): ${state.cImaginary.toFixed(2)}`);
},
KeyJ: () => {
updateSlopeLightIntensity(SLOPE_LIGHT_INTENSITY_STEP);
},
'Shift+KeyJ': () => {
updateSlopeLightIntensity(-SLOPE_LIGHT_INTENSITY_STEP);
},
KeyK: () => {
updateSlopeLightHeight(SLOPE_LIGHT_HEIGHT_STEP);
},
'Shift+KeyK': () => {
updateSlopeLightHeight(-SLOPE_LIGHT_HEIGHT_STEP);
},
KeyL: () => {
updateSlopeLightAngle(SLOPE_LIGHT_ANGLE_STEP);
},
'Shift+KeyL': () => {
updateSlopeLightAngle(-SLOPE_LIGHT_ANGLE_STEP);
},
KeyN: () => {
setState({ slopeShading: 1 - state.slopeShading });
showInfo(state.slopeShading ? 'Slope shading on' : 'Slope shading off');
},
KeyO: () => {
zoomTween.stop();
positionTween.stop();
setPreciseCenterState('0', '0', { syncSmoothed: true, persist: false });
setZoomState(MIN_ZOOM_EXPONENT, { syncSmoothed: isPreciseNavigationActive(), persist: true });
if (isPreciseNavigationActive()) return;
zoomTween.to([MIN_ZOOM_EXPONENT], 500).startFromCurrentValues();
positionTween.to([0, 0], 2000).startFromCurrentValues();
},
KeyQ: () => {
const newValue = state.escapeRadius + 0.01;
setState({ escapeRadius: Math.min(MAX_ESCAPE_RADIUS, newValue === 1 ? 1.01 : newValue) });
showInfo(`Escape radius: ${state.escapeRadius.toFixed(2)}`);
},
'Shift+KeyQ': () => {
const newValue = state.escapeRadius - 0.01;
setState({ escapeRadius: Math.max(MIN_ESCAPE_RADIUS, newValue === 0 ? 0.01 : newValue) });
showInfo(`Escape radius: ${state.escapeRadius.toFixed(2)}`);
},
KeyR: () => {
setState({ cReal: Math.min(MAX_CONSTANT_COMPONENT, state.cReal + 0.01) });
showInfo(`C (real): ${state.cReal.toFixed(2)}`);
},
'Shift+KeyR': () => {
setState({ cReal: Math.max(-MAX_CONSTANT_COMPONENT, state.cReal - 0.01) });
showInfo(`C (real): ${state.cReal.toFixed(2)}`);
},
KeyS: () => {
setState({ speed: Math.min(MAX_SPEED, state.speed + 0.1) });
showInfo(`Speed: ${state.speed.toFixed(1)}`);
},
'Shift+KeyS': () => {
setState({ speed: Math.max(MIN_SPEED, state.speed - 0.1) });
showInfo(`Speed: ${state.speed.toFixed(1)}`);
},
KeyA: () => {
setState({ stripeAverage: 1 - state.stripeAverage });
showInfo(state.stripeAverage ? 'Stripe average coloring on' : 'Stripe average coloring off');
},
KeyZ: () => {
zoomTween.stop();
if (isPreciseNavigationActive()) {
setZoomState(MAX_ZOOM_EXPONENT, { syncSmoothed: true, persist: true });
return;
}
setZoomState(MAX_ZOOM_EXPONENT, { syncSmoothed: false, persist: true });
zoomTween.to([MAX_ZOOM_EXPONENT], 20000).startFromCurrentValues();
},
'Shift+KeyZ': () => {
zoomTween.stop();
if (isPreciseNavigationActive()) {
setZoomState(MIN_ZOOM_EXPONENT, { syncSmoothed: true, persist: true });
return;
}
setZoomState(MIN_ZOOM_EXPONENT, { syncSmoothed: false, persist: true });
zoomTween.to([MIN_ZOOM_EXPONENT], 20000).startFromCurrentValues();
},
KeyX: resetState,
ArrowUp: () => {
translateViewCenter(0, 0.005);
},
'Shift+ArrowUp': () => {
translateViewCenter(0, 0.05);
},
ArrowDown: () => {
translateViewCenter(0, -0.005);
},
'Shift+ArrowDown': () => {
translateViewCenter(0, -0.05);
},
ArrowLeft: () => {
translateViewCenter(-0.005, 0);
},
'Shift+ArrowLeft': () => {
translateViewCenter(-0.05, 0);
},
ArrowRight: () => {
translateViewCenter(0.005, 0);
},
'Shift+ArrowRight': () => {
translateViewCenter(0.05, 0);
},
Space: () => {
setState({ isPlaying: 1 - state.isPlaying });
showInfo(state.isPlaying ? 'Playing' : 'Paused');
},
'Shift+Space': () => {
setState({ animationDirection: state.animationDirection * -1 });
},
'Shift+?': () => {
instructionsContainer.classList.toggle('show');
},
KeyP: () => {
const enabled = profiler.toggle();
showInfo(enabled ? 'Profiler on' : 'Profiler off');
},
Enter: () => {
if (!displayRenderer) return;
save(displayRenderer, 'fractal.png', null, { preventShare: true });
},
Escape: () => {
instructionsContainer.classList.remove('show');
},
});
const [state, shortKeys, stateParsers] = Object.entries({
paletteId: [paletteIds[0], 'C'],
animationDirection: [1, 'D', parseNumber],
exponent: [2, 'E', parseNumber],
fractalType: [0, 'F', parseNumber],
colorScale: [0.2, 'G', parseNumber],
forceHelp: [0, 'H', parseNumber],
cImaginary: [-0.43, 'I', parseNumber],
slopeShading: [1, 'K', parseNumber],
slopeLightAngle: [135, 'LA', parseNumber],
slopeLightHeight: [1.5, 'LH', parseNumber],
slopeLightIntensity: [1, 'LI', parseNumber],
stripeAverage: [0, 'SA', parseNumber],
isPlaying: [1, 'P', parseNumber],
escapeRadius: [2, 'Q', parseNumber],
cReal: [-0.71, 'R', parseNumber],
speed: [1, 'S', parseNumber],
deepCenterReal: ['0', 'A'],
deepCenterImag: ['0', 'B'],
deepRadius: ['2', 'W'],
xPosition: [0, 'X', parseNumber],
yPosition: [0, 'Y', parseNumber],
zoom: [MIN_ZOOM_EXPONENT, 'Z', parseNumber],
}).reduce(
([nextState, nextShortKeys, nextStateParsers], [key, [value, shortKey, parser]]) => {
nextState[key] = value;
nextShortKeys[key] = shortKey;
nextStateParsers[key] = parser ?? identity;
return [nextState, nextShortKeys, nextStateParsers];
},
[{}, {}, {}],
);
const defaultState = { ...state };
function syncApproximateCenterFromPreciseState({ syncSmoothed = false } = {}) {
const approximateX = getApproximatePositionFromCenterComponent(state.deepCenterReal);
const approximateY = getApproximatePositionFromCenterComponent(state.deepCenterImag);
if (approximateX !== null) {
state.xPosition = approximateX;
if (syncSmoothed) smoothedPosition[0] = approximateX;
}
if (approximateY !== null) {
state.yPosition = approximateY;
if (syncSmoothed) smoothedPosition[1] = approximateY;
}
}
function syncPreciseCenterFromApproximateState() {
state.deepCenterReal = (state.xPosition * 2).toString();
state.deepCenterImag = (state.yPosition * 2).toString();
}
function getCurrentRadiusExact() {
return Math.abs(smoothedZoom[0] - state.zoom) < 1e-9 ? state.deepRadius : getRadiusExactForZoom(smoothedZoom[0]);
}
function syncPreciseRadiusFromApproximateZoom() {
state.deepRadius = getRadiusExactForZoom(state.zoom);
}
function setApproximateCenterState(xPosition, yPosition, { syncSmoothed = false, persist = true } = {}) {
const didChangeCenter =
Math.abs(state.xPosition - xPosition) > 1e-15 || Math.abs(state.yPosition - yPosition) > 1e-15;
state.xPosition = xPosition;
state.yPosition = yPosition;
syncPreciseCenterFromApproximateState();
if (syncSmoothed) {
smoothedPosition[0] = xPosition;
smoothedPosition[1] = yPosition;
}
if (didChangeCenter) beginDeepInteractionMotion();
if (persist) persistStateToHash();
}
function setPreciseCenterState(centerReal, centerImag, { syncSmoothed = false, persist = true } = {}) {
const didChangeCenter = state.deepCenterReal !== centerReal || state.deepCenterImag !== centerImag;
state.deepCenterReal = centerReal;
state.deepCenterImag = centerImag;
syncApproximateCenterFromPreciseState({ syncSmoothed });
if (didChangeCenter) beginDeepInteractionMotion();
if (persist) persistStateToHash();
}
function isPreciseNavigationActive(zoom = state.zoom) {
return deepZoomManager.supportsState(state).supported && isDeepZoomRequested(zoom);
}
function setZoomState(zoom, { syncSmoothed = true, persist = true } = {}) {
const didChangeZoom = Math.abs(state.zoom - zoom) > 1e-9;
state.zoom = zoom;
syncPreciseRadiusFromApproximateZoom();
if (syncSmoothed) {
smoothedZoom[0] = zoom;
}
if (didChangeZoom) beginDeepInteractionMotion();
if (persist) persistStateToHash();
}
function translatePreciseCenter(deltaReal, deltaImag, radiusExact = state.deepRadius) {
if (!deepZoomManager.isInitialized) {
initializeDeepZoom();
return false;
}
const translatedCenter = deepZoomManager.translateCenter(
state.deepCenterReal,
state.deepCenterImag,
radiusExact,
deltaReal,
deltaImag,
);
setPreciseCenterState(translatedCenter.centerReal, translatedCenter.centerImag, { syncSmoothed: true });
return true;
}
function translateViewCenter(deltaReal, deltaImag) {
if (translatePreciseCenter(deltaReal, deltaImag, getCurrentRadiusExact())) {
positionTween.stop();
positionTween.to([state.xPosition, state.yPosition], 0).end();
return true;
}
setApproximateCenterState(
smoothedPosition[0] + deltaReal / Math.pow(2, smoothedZoom[0]),
smoothedPosition[1] + deltaImag / Math.pow(2, smoothedZoom[0]),
{ syncSmoothed: true },
);
positionTween.stop();
positionTween.to([state.xPosition, state.yPosition], 0).end();
return false;
}
function resetState() {
Object.assign(state, defaultState);
smoothedPosition[0] = state.xPosition;
smoothedPosition[1] = state.yPosition;
smoothedZoom[0] = state.zoom;
paletteIdx = 0;
paletteFrame = 0;
lastPaletteUpdateMs = null;
updateColors(0);
deepZoomManager.invalidate();
lastStandardIterationRenderSignature = null;
lastDeepIterationRenderSignature = null;
lastUploadedDeepOrbitSignature = null;
deepMetricAnchor = null;
deepPreviewTransformCache = null;
lastObservedZoom = smoothedZoom[0];
settleDeepInteractionMotion.clearTimeout();
setDeepInteractionInMotion(false);
updateHash('');
}
function setState(diff) {
let didUpdate = false;
let hasApproximateCenterDiff = false;
let hasPreciseCenterDiff = false;
let hasZoomDiff = false;
let hasPreciseRadiusDiff = false;
Object.entries(diff).forEach(([key, value]) => {
if (!(key in state)) {
showError(`Invalid state key: ${key}`);
return;
}
didUpdate = true;
if (key === 'xPosition' || key === 'yPosition') hasApproximateCenterDiff = true;
if (key === 'deepCenterReal' || key === 'deepCenterImag') hasPreciseCenterDiff = true;
if (key === 'zoom') hasZoomDiff = true;
if (key === 'deepRadius') hasPreciseRadiusDiff = true;
state[key] = value;
});
if (!didUpdate) return;
if (hasPreciseCenterDiff) {
syncApproximateCenterFromPreciseState();
} else if (hasApproximateCenterDiff) {
syncPreciseCenterFromApproximateState();
}
if (hasZoomDiff && !hasPreciseRadiusDiff) {
syncPreciseRadiusFromApproximateZoom();
}
persistStateToHash();
}
const persistStateToHash = debounce(function persistStateToHash() {
const urlCenterFractionDigits = getUrlCenterFractionDigits(state.zoom);
updateHash(
Object.entries(state)
.map(
([key, value]) =>
`${shortKeys[key]}=${encodeURIComponent(serializeStateValueForHash(key, value, urlCenterFractionDigits))}`,
)
.join('_'),
);
}, 200);
function updateStateFromHash() {
const hash = location.hash.substring(1);
try {
let hasApproximateCenterState = false;
let hasPreciseCenterState = false;
let hasPreciseRadiusState = false;
const entries = hash
.split('_')
.map(str => {
if (!str) return null;
const [shortKey, encodedValue] = str.split('=');
const key =
shortKey === 'V' ? 'stripeAverage' : Object.keys(shortKeys).find(k => shortKeys[k] === shortKey);
if (!key) return null;
const parser = stateParsers[key];
const value = parser(decodeURIComponent(encodedValue));
return [key, value];
})
.filter(Boolean);
entries.forEach(([key, value]) => {
state[key] = value;
switch (key) {
case 'deepCenterReal':
case 'deepCenterImag':
hasPreciseCenterState = true;
break;
case 'deepRadius':
hasPreciseRadiusState = true;
break;
case 'xPosition':
hasApproximateCenterState = true;
smoothedPosition[0] = value;
break;
case 'yPosition':
hasApproximateCenterState = true;
smoothedPosition[1] = value;
break;
case 'zoom':
smoothedZoom[0] = value;
break;
case 'paletteId':
paletteIdx = paletteIds.indexOf(value);
updateColors(0);
break;
}
});
if (hasPreciseCenterState) {
syncApproximateCenterFromPreciseState({ syncSmoothed: true });
} else if (hasApproximateCenterState) {
syncPreciseCenterFromApproximateState();
}
if (!hasPreciseRadiusState) {
syncPreciseRadiusFromApproximateZoom();
}
return entries.length;
} catch (e) {
console.error('Error parsing the hash', e);
}
}
let showLabels = true;
let paletteIdx = paletteIds.indexOf(state.paletteId);
const smoothedZoom = [state.zoom];
const smoothedPosition = [state.xPosition, state.yPosition];
const positionTween = new Tween(smoothedPosition).easing(Easing.Quadratic.InOut);
const zoomTween = new Tween(smoothedZoom).easing(Easing.Quadratic.InOut);
let lastObservedZoom = smoothedZoom[0];
let hideErrorTimeout;
const errorContainer = document.getElementById('error');
function showError(err) {
clearTimeout(hideErrorTimeout);
errorContainer.classList.add('show');
hideErrorTimeout = window.setTimeout(() => {
errorContainer.classList.remove('show');
}, 2000);
if (err) {
console.error(err);
}
}
let hideInfoTimeout;
const infoContainer = document.getElementById('info');
function showInfo(text) {
if (!showLabels) return;
clearTimeout(hideInfoTimeout);
infoContainer.textContent = text;
infoContainer.classList.add('show');
hideInfoTimeout = window.setTimeout(() => {
infoContainer.classList.remove('show');
}, 2000);
}
const canvas = createFullscreenCanvas(document.getElementById('canvas-container'));
// Hand the canvas to the profiler (not the GL context β see note in profiler.js).
profiler.setCanvas(canvas);
const colors = new Float32Array(N_COLORS * 3);
// Pack the current palette into a 1D texture of sRGB-encoded bytes. The
// SRGB8_ALPHA8 internal format on the GPU side decodes each entry to linear
// on sample, so LINEAR filtering blends in linear space (gamma-correct).
function buildPaletteTextureSource() {
const data = new Uint8Array(N_COLORS * 4);
for (let i = 0; i < N_COLORS; i++) {
const src = i * 3;
const dst = i * 4;
data[dst] = Math.round(colors[src] * 255);
data[dst + 1] = Math.round(colors[src + 1] * 255);
data[dst + 2] = Math.round(colors[src + 2] * 255);
data[dst + 3] = 255;
}
return { data, width: N_COLORS, height: 1 };
}
// Inside color (used when metric.w is low): 50/50 mix of palette[0] and
// palette[1] in linear space at 18% brightness. Uploaded as a linear-space
// uniform so the display shader can mix it directly with the linear palette
// sample.
function getInsideColor() {
const INSIDE_BRIGHTNESS = 0.18;
const r = (srgbToLinear(colors[0]) + srgbToLinear(colors[3])) * 0.5;
const g = (srgbToLinear(colors[1]) + srgbToLinear(colors[4])) * 0.5;
const b = (srgbToLinear(colors[2]) + srgbToLinear(colors[5])) * 0.5;
return [r * INSIDE_BRIGHTNESS, g * INSIDE_BRIGHTNESS, b * INSIDE_BRIGHTNESS];
}
function updateColors(direction = 0) {
paletteIdx = (paletteIds.length + paletteIdx + direction) % paletteIds.length;
const paletteId = paletteIds[paletteIdx];
const palette = palettes[paletteId];
if (direction) setState({ paletteId: paletteId });
const normalizedPalette = palette.map(hexToNormalizedRGB);
for (let i = 0; i < N_COLORS; ++i) {
const rgbComponents = [...normalizedPalette[i % normalizedPalette.length]];
if (i >= normalizedPalette.length) {
for (let j = 0; j < rgbComponents.length; ++j) {
rgbComponents[j] = Math.max(0, Math.min(1, rgbComponents[j] + Math.random() * 0.1 - 0.05));
}
}
const offset = i * 3;
colors[offset] = rgbComponents[0];
colors[offset + 1] = rgbComponents[1];
colors[offset + 2] = rgbComponents[2];
}
colorsVersion += 1;
document.documentElement.style.backgroundColor = palette[0];
}
function getShaderPadOptions(options = {}) {
return {
canvas,
...options,
};
}
function advancePaletteFrame(nowMs) {
if (lastPaletteUpdateMs !== null && state.isPlaying) {
const effectiveSpeed = state.speed * state.speed;
paletteFrame +=
((nowMs - lastPaletteUpdateMs) / 1000 / PALETTE_SECONDS_PER_BAND) *
state.animationDirection *
effectiveSpeed;
// Wrap so paletteFrame stays bounded. Unbounded growth loses float32 precision
// against u_colorScale * smoothIters and the palette can stop visibly advancing.
paletteFrame -= Math.floor(paletteFrame / N_COLORS) * N_COLORS;
}
lastPaletteUpdateMs = nowMs;
}
function getCanvasDisplaySize() {
const rect = canvas.getBoundingClientRect();
return {
width: rect.width || canvas.clientWidth || window.innerWidth,
height: rect.height || canvas.clientHeight || window.innerHeight,
};
}
function syncCanvasResolution() {
const displaySize = getCanvasDisplaySize();
const width = Math.max(1, Math.round(displaySize.width * resolutionMultiplier));
const height = Math.max(1, Math.round(displaySize.height * resolutionMultiplier));
if (canvas.width === width && canvas.height === height) return;
canvas.width = width;
canvas.height = height;
// shaderpad's MutationObserver-based texture resize fires after the current
// task, leaving u_liveMetrics bound to a deleted texture and the canvas black
// until the next signature change. Sync now and rebind the sampler.
standardIterationRenderer?.syncRes();
deepIterationRenderer?.syncRes();
displayRenderer?.syncRes();
// Force the next frame to re-run the iteration pass so the display sampler
// rebinds against the freshly recreated metric FBO.
lastStandardIterationRenderSignature = null;
lastDeepIterationRenderSignature = null;
deepMetricAnchor = null;
deepPreviewTransformCache = null;
}
function setDeepInteractionInMotion(isActive) {
isDeepInteractionInMotion = isActive;
}
const settleDeepInteractionMotion = debounce(() => {
setDeepInteractionInMotion(false);
}, DEEP_INTERACTION_MOTION_SETTLE_MS);
function beginDeepInteractionMotion() {
setDeepInteractionInMotion(true);
settleDeepInteractionMotion();
}
function updateDeepInteractionMotion() {
if (Math.abs(smoothedZoom[0] - lastObservedZoom) <= 1e-9) return;
lastObservedZoom = smoothedZoom[0];
beginDeepInteractionMotion();
}
function setResolutionMultiplier(nextResolutionMultiplier) {
const clampedResolutionMultiplier = Math.max(
MIN_RESOLUTION_MULTIPLIER,
Math.min(MAX_RESOLUTION_MULTIPLIER, nextResolutionMultiplier),
);
if (clampedResolutionMultiplier === resolutionMultiplier) return;
resolutionMultiplier = clampedResolutionMultiplier;
syncCanvasResolution();
}
function getSlopeLightDirection(angleDegrees) {
const angleRadians = (angleDegrees * Math.PI) / 180;
return [Math.cos(angleRadians), Math.sin(angleRadians)];
}
function updateSlopeLightAngle(delta) {
const slopeLightAngle = (state.slopeLightAngle + delta + 360) % 360;
setState({ slopeLightAngle });
showInfo(`Light direction: ${Math.round(slopeLightAngle)}deg`);
}
function updateSlopeLightHeight(delta) {
const slopeLightHeight = Math.max(
MIN_SLOPE_LIGHT_HEIGHT,
Math.min(MAX_SLOPE_LIGHT_HEIGHT, state.slopeLightHeight + delta),
);
setState({ slopeLightHeight });
showInfo(`Light height: ${slopeLightHeight.toFixed(1)}`);
}
function updateSlopeLightIntensity(delta) {
const slopeLightIntensity = Math.max(
MIN_SLOPE_LIGHT_INTENSITY,
Math.min(MAX_SLOPE_LIGHT_INTENSITY, state.slopeLightIntensity + delta),
);
setState({ slopeLightIntensity });
showInfo(`Light intensity: ${slopeLightIntensity.toFixed(2)}`);
}
// Iteration shaders bake fractal type and exponent into the source; recreate on change.
// Variant-dependent uniforms are compiled out, so uniform calls pass allowMissing.
const UNIFORM_OPTIONS = { allowMissing: true };
function getShaderVariant(renderState) {
return {
fractalType: renderState.fractalType,
exponent: renderState.exponent,
};
}
function getShaderVariantKey(renderState) {
return `${renderState.fractalType}|${renderState.exponent}`;
}
function initializeStandardIterationUniforms(renderState) {
standardIterationRenderer.initializeUniform(
'u_center',
'float',
[renderState.xPosition, renderState.yPosition],
UNIFORM_OPTIONS,
);
standardIterationRenderer.initializeUniform('u_zoom', 'float', renderState.zoomScale, UNIFORM_OPTIONS);
standardIterationRenderer.initializeUniform('u_cReal', 'float', renderState.cReal, UNIFORM_OPTIONS);
standardIterationRenderer.initializeUniform('u_cImaginary', 'float', renderState.cImaginary, UNIFORM_OPTIONS);
standardIterationRenderer.initializeUniform('u_escapeRadius', 'float', renderState.escapeRadius, UNIFORM_OPTIONS);
standardIterationRenderer.initializeUniform(
'u_logEscapeRadius',
'float',
renderState.logEscapeRadius,
UNIFORM_OPTIONS,
);
standardIterationRenderer.initializeUniform('u_iterations', 'int', renderState.iterations, UNIFORM_OPTIONS);
}
function ensureStandardIterationRenderer(renderState) {
const variantKey = getShaderVariantKey(renderState);
if (standardIterationRenderer && standardIterationVariantKey === variantKey) return;
standardIterationRenderer?.destroy();
standardIterationRenderer = new ShaderPad(generateStandardShader(getShaderVariant(renderState)), {
...getShaderPadOptions(),
...METRIC_TEXTURE_OPTIONS,
});
standardIterationVariantKey = variantKey;
lastStandardIterationRenderSignature = null;
initializeStandardIterationUniforms(renderState);
}
function updateStandardIterationUniforms(renderState) {
standardIterationRenderer.updateUniforms(
{
u_center: [renderState.xPosition, renderState.yPosition],
u_zoom: renderState.zoomScale,
u_cReal: renderState.cReal,
u_cImaginary: renderState.cImaginary,
u_escapeRadius: renderState.escapeRadius,
u_logEscapeRadius: renderState.logEscapeRadius,
u_iterations: renderState.iterations,
},
UNIFORM_OPTIONS,
);
}
function decomposeRadiusExact(radiusExact, fallbackRadius) {
if (deepZoomManager.isInitialized) {
const [mantissa, exponent] = deepZoomManager.decomposeValue(radiusExact);
return { mantissa, exponent };
}
if (fallbackRadius === 0) {
return { mantissa: 0, exponent: 0 };
}
const exponent = Math.floor(Math.log2(Math.abs(fallbackRadius))) + 1;
return {
mantissa: fallbackRadius / Math.pow(2, exponent),
exponent,
};
}
function getDeepShaderUniforms(renderState) {
const { mantissa, exponent } = decomposeRadiusExact(renderState.radiusExact, renderState.radius);
const referenceOffset = deepZoomManager.getReferenceOffsetFor(renderState);
return {
u_orbitLength: deepZoomManager.getReferenceOrbitLength(),
u_radiusMantissa: mantissa,
u_radiusExponent: exponent,
u_referenceOffset: [referenceOffset?.offsetReal ?? 0, referenceOffset?.offsetImag ?? 0],
};
}
function canRenderFromCurrentDeepReference(renderState) {
if (!deepZoomManager.hasRenderableReferenceFor(renderState)) return false;
const referenceOffset = deepZoomManager.getReferenceOffsetFor(renderState);
if (!referenceOffset) return false;
const maxOffset = Math.max(Math.abs(referenceOffset.offsetReal), Math.abs(referenceOffset.offsetImag));
return Number.isFinite(maxOffset) && maxOffset <= DEEP_COMPATIBLE_REFERENCE_MAX_OFFSET;
}
function shouldRecenterDeepReference(renderState) {
if (!canRenderFromCurrentDeepReference(renderState)) return true;
// Keep this explicit for preparation calls that pass a headroom-sized target
// state: even if the current frame can draw, the next reference may need a
// larger budget than the existing one.
if (deepZoomManager.referenceIterationsBelow(renderState)) return true;
if (deepZoomManager.hasReferenceFor(renderState)) return false;
const referenceOffset = deepZoomManager.getReferenceOffsetFor(renderState);
if (!referenceOffset) return true;
const maxOffset = Math.max(Math.abs(referenceOffset.offsetReal), Math.abs(referenceOffset.offsetImag));
const recenterOffset = isDeepInteractionInMotion
? DEEP_REFERENCE_RECENTER_OFFSET
: DEEP_SETTLED_REFERENCE_RECENTER_OFFSET;
return !Number.isFinite(maxOffset) || maxOffset > recenterOffset;
}
function getStandardIterationBudget(zoom) {
// Ramp iteration budget toward the deep floor across the preparation margin.
const rampStartZoom = DEEP_ZOOM_THRESHOLD - DEEP_ZOOM_PREPARATION_MARGIN_EXPONENT;
if (zoom <= rampStartZoom) return BASE_ITERATIONS;
if (zoom > DEEP_ZOOM_THRESHOLD) return getDeepIterationBudget(zoom);
const rampProgress = (zoom - rampStartZoom) / DEEP_ZOOM_PREPARATION_MARGIN_EXPONENT;
const target = Math.ceil(BASE_ITERATIONS * Math.pow(DEEP_MIN_ITERATIONS / BASE_ITERATIONS, rampProgress));
return Math.min(DEEP_MIN_ITERATIONS, target);
}
function getDeepIterationBudget(zoom) {
// Continuous so per-frame iter growth shows as 0-1 newly-escaping pixels at most,
// not as a 256-step jump that fills a band of pixels at once. The reference orbit
// is sized with DEEP_REFERENCE_ITERATION_HEADROOM_EXPONENT extra zoom units worth
// of iterations on top of this, so orbit recomputes don't fire as u_iterations
// ticks up β only when the user pans or radically shifts zoom.
const target = Math.ceil(
DEEP_MIN_ITERATIONS + Math.max(0, zoom - DEEP_ZOOM_THRESHOLD) * DEEP_ITERATION_ZOOM_FACTOR,
);
return Math.min(DEEP_MAX_ITERATIONS, Math.max(DEEP_MIN_ITERATIONS, target));
}
function initializeDeepIterationUniforms(renderState) {
const deepUniforms = getDeepShaderUniforms(renderState);
deepIterationRenderer.initializeUniform('u_iterations', 'int', renderState.deepIterations, UNIFORM_OPTIONS);
deepIterationRenderer.initializeUniform('u_orbitLength', 'int', deepUniforms.u_orbitLength, UNIFORM_OPTIONS);
deepIterationRenderer.initializeUniform(
'u_radiusMantissa',
'float',
deepUniforms.u_radiusMantissa,
UNIFORM_OPTIONS,
);
deepIterationRenderer.initializeUniform('u_radiusExponent', 'int', deepUniforms.u_radiusExponent, UNIFORM_OPTIONS);
deepIterationRenderer.initializeUniform(
'u_referenceOffset',
'float',
deepUniforms.u_referenceOffset,
UNIFORM_OPTIONS,
);
deepIterationRenderer.initializeUniform('u_escapeRadius', 'float', renderState.escapeRadius, UNIFORM_OPTIONS);
deepIterationRenderer.initializeUniform('u_logEscapeRadius', 'float', renderState.logEscapeRadius, UNIFORM_OPTIONS);
}
function updateDeepIterationUniforms(renderState) {
const deepUniforms = getDeepShaderUniforms(renderState);
deepIterationRenderer.updateUniforms(
{
u_iterations: renderState.deepIterations,
u_orbitLength: deepUniforms.u_orbitLength,
u_radiusMantissa: deepUniforms.u_radiusMantissa,
u_radiusExponent: deepUniforms.u_radiusExponent,
u_referenceOffset: deepUniforms.u_referenceOffset,
u_escapeRadius: renderState.escapeRadius,
u_logEscapeRadius: renderState.logEscapeRadius,
},
UNIFORM_OPTIONS,
);
}
function syncDeepOrbitTexture() {
if (!deepIterationRenderer) return;
const orbitTextureSource = deepZoomManager.getOrbitTextureSource();
if (!orbitTextureSource) return;
const blaTextureSource = deepZoomManager.getBLATextureSource();
const visualPrefixTextureSource = deepZoomManager.getVisualPrefixTextureSource();
if (lastUploadedDeepOrbitSignature === deepZoomManager.referenceSignature) return;
profiler.measure('deep:uploadOrbit', () => {
if (lastUploadedDeepOrbitSignature === null) {
deepIterationRenderer.initializeTexture('u_orbitTexture', orbitTextureSource, ORBIT_TEXTURE_OPTIONS);
// BLA table uses the same RGBA32F NEAREST options as the orbit texture β
// both are sampled by index, not interpolated.
if (blaTextureSource) {
deepIterationRenderer.initializeTexture('u_blaTable', blaTextureSource, ORBIT_TEXTURE_OPTIONS);
}
if (visualPrefixTextureSource) {
deepIterationRenderer.initializeTexture(
'u_visualPrefixTexture',
visualPrefixTextureSource,
ORBIT_TEXTURE_OPTIONS,
);
}
} else {
const textureUpdates = { u_orbitTexture: orbitTextureSource };
if (blaTextureSource) textureUpdates.u_blaTable = blaTextureSource;
if (visualPrefixTextureSource) textureUpdates.u_visualPrefixTexture = visualPrefixTextureSource;
deepIterationRenderer.updateTextures(textureUpdates);
}
});
lastUploadedDeepOrbitSignature = deepZoomManager.referenceSignature;
}
function ensureDeepIterationRenderer(renderState) {