-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathquasi_crystals.html
2287 lines (2102 loc) · 79.6 KB
/
quasi_crystals.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<title>Quasicrystals</title>
<link rel="icon" href="res/favicon.ico">
<script src="slide_show.js"></script>
<script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
<script>
MathJax = {
tex: {inlineMath: [['$', '$']]}
};
</script>
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/[email protected]/es5/tex-mml-chtml.js"></script>
<script type="text/javascript">
// Config
const mainViewSize = 10;
const mainViewZoomRate = 1.1;
const mainDotInitSize = 0.03;
const mainLineSize = 1;
const cellViewSize = 1;
const cellDotSize = 0.01;
const cellLineSize = 2;
const cellRayLength = 4;
const contFracTerms = 10; // Max is around 30 before float errors.
const visibleContFracTerms = 6;
const zModeContFracTerms = 4;
const epsilon = 1e-6;
const alwaysRedraw = false;
const maxSeqLength = 1000; // Way more than what we display.
const genSeqLength = 100;
const timeBetweenDomUpdatesMs = 100;
const tau = 2 * Math.PI;
function randInt(n) {
return Math.floor(n * Math.random());
}
function fmod(x, y = 1) {
const z = x / y;
return (z - Math.floor(z)) * y;
}
function clamp(x, lo = 0, hi = 1) {
return Math.max(Math.min(x, hi), lo);
}
function squish(x) {
return (1 - Math.cos(x * Math.PI)) / 4 + x / 2;
}
function squishy(x, n) {
for (let i = 0; i < n; ++i) x = squish(x);
return x;
}
function isInt(x) {
return Math.floor(x) == x;
}
function validate(x, condition) {
if (condition(x)) return x;
return null;
}
function unit(x, y) {
const d = Math.sqrt(x * x + y * y);
if (d == 0) return [0, 0];
return [x / d, y / d];
}
function popSwap(a, i) {
const x = a[i];
const y = a.pop();
if (i < a.length) a[i] = y;
return x;
}
function getContFracTerms(x, maxTerms) {
const terms = [];
for (let i = 0; i < maxTerms; ++i) {
const c = Math.floor(x);
terms.push(c);
const r = x - c;
if (r < epsilon) {
if (c == 1 && terms.length > 1) {
terms.pop();
terms[terms.length - 1] += 1;
}
break;
}
x = 1 / r;
}
return terms;
}
function getContFracTermsWithTargCoeff(x, maxTerms, targCoeff) {
const terms = getContFracTerms(x, maxTerms);
// targCoeff is not allowed to target a term that doesn't exist, unless it's
// the very next term after the end of the terms array and the last element is
// greater than 1. In that case we steal a 1/1 from that last term. Otherwise
// we cap the targetCoeff.
if (targCoeff > terms.length) {
targCoeff = terms.length;
}
if (targCoeff == terms.length) {
if (terms[terms.length - 1] > 1) {
terms[terms.length - 1] -= 1;
terms.push(1);
} else {
targCoeff = terms.length - 1;
}
}
return [terms, targCoeff];
}
function getApproxFrac(terms, maxTerms, zn = 0, zd = 1) {
const first = Math.min(terms.length, maxTerms) - 1;
const frac = [zd, zn];
for (let i = first; i >= 0; --i) {
const y = frac[0];
frac[0] = terms[i] * y + frac[1];
frac[1] = y;
}
return frac;
}
function getContFracValue(terms) {
let x = Infinity;
for (let i = terms.length - 1; i >= 0; --i) {
x = terms[i] + 1 / x;
}
return x;
}
function repeatStr(s, n, max) {
let t = '';
while (n > 0) {
if (n & 1) t += s;
s += s;
n >>>= 1;
if (t.length >= max) break;
}
return t;
}
function wordFromContFracTerms(terms) {
let w = '';
let w1 = 'S';
let w2 = 'L';
for (let i = 0; i < terms.length; ++i) {
const wr = repeatStr(w1, terms[i], maxSeqLength);
w = (i % 2 == 0) ? wr + w2 : w2 + wr;
if (w.length >= maxSeqLength) return w.substr(0, maxSeqLength);
w2 = w1;
w1 = w;
}
return w;
}
function sequenceFromGrad(x, o, len) {
let m = o;
let n = 1;
const a = [];
for (let i = 0; i < len; ++i) {
if (n * x > m) {
++m;
a.push(true);
} else {
++n;
a.push(false);
}
}
return a;
}
class RateLimiter {
constructor() {
this.lastRun = null;
this.timeout = null;
}
run(delayMs, task) {
const t = performance.now();
// If it's been more than delayMs since our last task, run immediately.
if (this.lastRun == null || (this.lastRun + delayMs) < t) {
this.lastRun = t;
task();
return;
}
// We're about to set a new timeout, so cancel any existing timeouts.
if (this.timeout != null) {
window.clearTimeout(this.timeout);
}
// Set a timeout that delays the task by the extra wait time.
const dt = this.lastRun + delayMs - t;
this.timeout = window.setTimeout(() => {
this.lastRun = performance.now();
task();
}, dt);
}
}
function safeGet(node, defaultValue, isValid = (x => true)) {
const value = parseFloat(node.value);
if (isNaN(value) || !isValid(value)) return defaultValue;
return value;
}
function newElement(type, parent, classes = [], text = null) {
const n = document.createElement(type);
if (text != null) n.innerText = text;
for (const cls of classes) n.classList.add(cls);
if (parent != null) parent.appendChild(n);
return n;
}
function newDiv(parent, classes = [], text = null) {
return newElement('div', parent, classes, text);
}
function emptyDiv(n) {
while (n.hasChildNodes()) n.removeChild(n.lastChild);
}
function findCousinDivWithClass(n, className) {
while (n != null) {
for (const c of n.childNodes) {
if (c.classList != null && c.classList.contains(className)) {
return c;
}
}
n = n.parentElement;
}
return null;
}
function runUnitTests() {
let anyFails = false;
const testWord = (terms, expectedWord) => {
const word = wordFromContFracTerms(terms);
if (word != expectedWord) {
console.error(`wordFromContFracTerms([${terms}]) produced ${word} instead of ${expectedWord}`);
anyFails = true;
}
};
testWord([], '');
testWord([1], 'SL');
testWord([1, 1], 'SSL');
testWord([1, 1, 1], 'SSLSL');
testWord([1, 1, 1, 1], 'SSLSSLSL');
testWord([1, 1, 1, 1, 1], 'SSLSSLSLSSLSL');
testWord([1, 1, 1, 1, 1, 1], 'SSLSSLSLSSLSSLSLSSLSL');
testWord([1, 6, 2, 3, 1, 2], 'SSLSLSLSLSLSLSSLSLSLSLSLSLSSLSLSLSLSLSLSLSSLSLSLSLSLSLSSLSLSLSLSLSLSLSSLSLSLSLSLSLSSLSLSLSLSLSLSLSSLSLSLSLSLSLSSLSLSLSLSLSLSSLSLSLSLSLSLSLSSLSLSLSLSLSLSSLSLSLSLSLSLSLSSLSLSLSLSLSLSSLSLSLSLSLSLSLSSLSLSLSLSLSLSSLSLSLSLSLSLSLSSLSLSLSLSLSLSSLSLSLSLSLSLSSLSLSLSLSLSLSLSSLSLSLSLSLSLSSLSLSLSLSLSLSLSSLSLSLSLSLSLSSLSLSLSLSLSLSLSSLSLSLSLSLSLSSLSLSLSLSLSLSL');
testWord([0, 2, 2], 'SLLSLLL');
const testContFrac = (x) => {
const y = getContFracValue(getContFracTerms(x, 100));
if (Math.abs(x - y) > 1e-12) {
console.error(`getContFracValue(getContFracTerms(${x}, 100)) produced ${y} instead of ${x}`);
anyFails = true;
}
};
for (let i = 0; i < 1000; ++i) {
testContFrac(10 * Math.random());
testContFrac(randInt(10000) / (randInt(10000) + 1));
}
if (!anyFails) {
console.log('All tests passed :)');
}
}
function getRayCellCrossingsDist(gx, ox, len) {
if (gx == 0) return null;
const k = (1 - ox) / gx;
if (k >= len) return null
return k;
}
function getRayCellCrossings(gx, gy, ox, oy, len) {
let d = 0;
let x = ox;
let y = oy;
const a = [];
for (let i = 0; i < 100; ++i) {
const l = len - d;
const kx = getRayCellCrossingsDist(gx, x, l);
const ky = getRayCellCrossingsDist(gy, y, l);
const stop = kx == null && ky == null;
let k = 0;
let px = null;
let py = null;
let nx = null;
let ny = null;
if (stop) {
k = l;
} else if (ky == null || (kx != null && kx < ky)) {
k = kx;
px = 1;
nx = 0;
} else {
k = ky;
py = 1;
ny = 0;
}
if (ny == null) ny = py = y + k * gy;
if (nx == null) nx = px = x + k * gx;
const nd = d + k;
a.push([x, y, d / len, px, py, nd / len]);
x = nx;
y = ny;
d = nd;
if (stop) break;
}
return a;
}
function closestPointToLine(px, py, ox, oy, dx, dy) {
// q = o + kd
// (q - o) . (p - q) = 0
// kd . (p - o - kd) = 0
// d . (p - o - kd) = 0
// d . (p - o) - k(d . d) = 0
// d . (p - o) = k(d . d)
// d . (p - o) = k // d is a unit vector
const k = dx * (px - ox) + dy * (py - oy);
return [ox + k * dx, oy + k * dy];
}
function setupCanvas(canvas, viewWidth, lineWidthMul = 1) {
const ctx = canvas.getContext('2d');
ctx.setTransform(
canvas.width / viewWidth, 0,
0, -canvas.width / viewWidth,
0, canvas.height);
ctx.lineWidth = lineWidthMul * viewWidth / canvas.width;
return ctx;
}
function onLoad() {
runUnitTests();
let forceRedraw = true;
const onFrameCallbacks = [];
const domUpdateLimiter = new RateLimiter();
const allLiveValues = new Map();
const liveValue = (id, nodeIds, init = 0, validate = x => x, onchange = () => {}) => {
// Does a few things:
// - Maintains the invariant that each dom element has the same value.
// - Whenever the value changes, sets forceRedraw to true.
// - Uses validate to sanitize, a function from float to nullable float.
// - Returns an object with a value field that is kept up to date.
// - Changes to that field are also reflected on the elements.
const elements = nodeIds.map(id => document.getElementById(id));
const oldValues = []; // One for each element, and one for obj.value.
for (const e of elements) {
e.value = init;
oldValues.push(e.value);
}
const obj = { value: init, reset: null };
obj.reset = () => obj.value = init;
oldValues.push(obj.value);
onFrameCallbacks.push(() => {
let anyChange = obj.value != oldValues[elements.length];
let cause = null;
if (!anyChange) {
for (let i = 0; i < elements.length; ++i) {
const e = elements[i];
if (e.value != oldValues[i]) {
const px = parseFloat(e.value);
const x = isNaN(px) ? null : validate(px);
if (x != null) {
anyChange = true;
obj.value = x;
cause = i;
break;
}
}
}
}
if (anyChange) {
forceRedraw = true;
oldValues[elements.length] = obj.value;
for (let i = 0; i < elements.length; ++i) {
const e = elements[i];
if (i != cause) {
e.value = obj.value;
}
oldValues[i] = e.value;
}
onchange();
}
});
allLiveValues.set(id, obj);
return obj;
};
const domAdvancedOptions = document.getElementById('advanced_options');
const domFlagAdvanced = document.getElementById('flag_advanced');
domFlagAdvanced.addEventListener('change', () => {
if (domFlagAdvanced.checked) {
domAdvancedOptions.classList.remove('hidden');
} else {
domAdvancedOptions.classList.add('hidden');
}
});
const allFlags = new Map();
const makeFlag = (id, name, initValue = false, onChange = () => {}) => {
const flag = { value: initValue, setValue: null };
const div = newDiv(domAdvancedOptions, ['flag']);
const check = newElement('input', div);
check.setAttribute('type', 'checkbox');
check.checked = initValue;
flag.setValue = value => {
if (value) {
check.checked = true;
} else {
check.checked = false;
}
forceRedraw = true;
flag.value = value;
onChange();
};
check.addEventListener('change', () => flag.setValue(check.checked));
const label = newElement('span', div, [], name);
allFlags.set(id, flag);
return flag;
};
let targKeep = false;
let targX = null;
let targY = null;
const grad = liveValue('grad', ['in_grad', 'ins_grad'], 0.618033988749894,
x => x >= 0 ? x : 0, () => {
if (targKeep) {
targKeep = false;
} else {
targX = null;
targY = null;
}
});
const off = liveValue('off', ['in_off', 'ins_off'], 0, x => fmod(x), () => {
targX = null;
targY = null;
});
let targCoeff = 0;
const coeffterm = liveValue('coeff', ['coeff_slider'], 1, x => Math.floor(x),
() => {
const [terms, targCoeff_] = getContFracTermsWithTargCoeff(
grad.value, contFracTerms, targCoeff);
targCoeff = targCoeff_;
const x = coeffterm.value;
if (x == terms[targCoeff]) return;
const terms_ = terms.slice(0);
terms_[targCoeff] = x;
grad.value = getContFracValue(terms_);
});
const rawzterm = liveValue('rawz', ['z_slider'], 0, x => clamp(x, 0, 1));
const flagShowConvergents = makeFlag('aprx', 'Show approximants');
const flagShowSteps = makeFlag('step', 'Show steps');
const flagShowCrystal = makeFlag('crys', 'Show crystal');
const flagUnitCellMode = makeFlag('unit', 'Unit cell mode');
const flagShowZ = makeFlag('rem', 'Editable remainder');
const flagContFracEdit = makeFlag('cont', 'Editable continued fraction');
const flagSimpleFracEdit = makeFlag('simp', 'Editable simple fraction');
const isInZMode = () => (
flagShowZ.value && !flagContFracEdit.value && !flagSimpleFracEdit.value &&
!flagUnitCellMode.value);
const isInSimpleFracEditMode = () =>
flagSimpleFracEdit.value && !flagContFracEdit.value;
const getVisibleContFracTerms = () =>
isInZMode() ? zModeContFracTerms : visibleContFracTerms;
const getApproxContFracTerms = () =>
isInZMode() ? zModeContFracTerms : visibleContFracTerms + 1;
const canvas = document.getElementById('view');
const crystalCanvas = document.getElementById('crystal_view');
const domContFrac = document.getElementById('cont_frac');
const domApproxEqual = document.getElementById('approx_equal');
const domApproxFrac = document.getElementById('approx_frac');
const domWord = document.getElementById('word');
const domZSliderWrap = document.getElementById('z_slider_wrap');
const domCoeffSliderWrap = document.getElementById('coeff_slider_wrap');
const domAppMiddle = document.getElementById('middle');
const domAppRight = document.getElementById('right');
class SetGradient extends HTMLElement {
constructor() {
super();
const y = (x => {
if (x == 'p') return 0.618033988749894;
if (x == 'phi') return 1.618033988749894;
if (x == 'pi') return 3.141592653589793;
if (x == 'e2') return 2.549646778303845;
return parseFloat(x);
})(this.getAttribute('x'));
this.addEventListener('click', () => {
grad.value = y;
});
}
}
customElements.define('s-g', SetGradient);
const blogPageUpdater = [];
const addBlogPage = (showApp, flags, liveValues) => {
const flg = new Set(flags);
const lvs = new Map(liveValues);
blogPageUpdater.push(() => {
if (showApp) {
for (const [id, flag] of allFlags.entries()) {
flag.setValue(flg.has(id));
}
for (const [id, lv] of allLiveValues.entries()) {
if (lvs.has(id)) {
lv.value = lvs.get(id);
} else {
lv.reset();
}
}
domAppMiddle.classList.remove('hidden');
domAppRight.classList.remove('hidden');
} else {
domAppMiddle.classList.add('hidden');
domAppRight.classList.add('hidden');
}
});
};
addBlogPage(false);
addBlogPage(false);
addBlogPage(true, ['crys', 'step', 'simp']);
addBlogPage(true, ['crys', 'step', 'simp']);
addBlogPage(true, ['crys', 'step', 'simp']);
addBlogPage(true, ['crys', 'step', 'simp']);
addBlogPage(true, ['crys', 'step', 'cont']);
addBlogPage(true, ['crys', 'step', 'cont']);
addBlogPage(true, ['crys', 'step', 'aprx', 'cont']);
addBlogPage(true, ['crys', 'step', 'aprx', 'rem']);
addBlogPage(true, ['crys', 'step', 'aprx', 'cont']);
addBlogPage(true, ['crys', 'step', 'aprx', 'cont']);
addBlogPage(false);
addBlogPage(false);
const showBlog = index => blogPageUpdater[index]();
document.getElementById('blog').addEventListener(
'change', e => showBlog(e.detail));
showBlog(0);
const getZ = () => {
const x = isInZMode() ? rawzterm.value : 0;
if (x == 0) return [0, 1];
if (x == 1) return [1, 0];
if (x == 0.5) return [1, 1];
const y = squishy(x, 4);
const z = (1 / (1 - y)) - 1;
return x < 0.5 ? [1, Math.floor(1 / z)] : [Math.floor(z), 1];
};
const fillContFracDom = (terms, zn, zd) => {
const visibleTerms = getVisibleContFracTerms();
emptyDiv(domContFrac);
let n = terms.length;
const trunc = n > visibleTerms;
if (trunc) n = visibleTerms;
--n;
let node = domContFrac;
const termDivs = [];
const addTerm = (i, suffix, cls) => {
const termWrap = newDiv(node, [cls]);
const term = newDiv(termWrap, [], terms[i]);
if (flagContFracEdit.value) {
termWrap.classList.add('cont-frac-term-wrap');
term.classList.add('cont-frac-term-clickable');
if (targCoeff == i) {
termWrap.classList.add('selected');
}
term.addEventListener('click', () => {
for (const t of termDivs) {
t.classList.remove('selected');
}
termWrap.classList.add('selected');
targCoeff = i;
coeffterm.value = terms[i];
});
newDiv(termWrap, ['cont-frac-term-line']);
}
termDivs.push(termWrap);
if (suffix != '') newDiv(node, [cls], suffix);
};
for (let i = 0; i < n; ++i) {
if (flagContFracEdit.value || !(i == 0 && terms[i] == 0)) {
addTerm(i, ' + ', 'cont-frac-term');
}
const frac = newDiv(node, ['cont-frac-frac']);
newDiv(frac, ['cont-frac-num'], '1');
node = newDiv(frac, ['cont-frac-den']);
}
if (flagContFracEdit.value) {
domCoeffSliderWrap.classList.remove('hidden');
} else {
domCoeffSliderWrap.classList.add('hidden');
}
if (isInZMode()) {
domZSliderWrap.classList.remove('hidden');
const haszd = zd > 1;
addTerm(n, ' + ', haszd ? 'cont-frac-term' : 'cont-frac-term-end');
const frac = newDiv(node, ['cont-frac-frac']);
newDiv(frac, ['cont-frac-num'], zd == 0 ? '∞' : zn);
if (haszd) newDiv(frac, ['cont-frac-den'], zd);
} else {
addTerm(n, trunc ? ' + ...' : '', 'cont-frac-term-end');
domZSliderWrap.classList.add('hidden');
}
}
const fillApproxFracDom = (terms, zn, zd) => {
const [n, d] = getApproxFrac(terms, getApproxContFracTerms(), zn, zd);
emptyDiv(domApproxFrac);
if (isInSimpleFracEditMode()) {
const makeText = (val, minVal, onChange) => {
const inp = newElement('input', domApproxFrac, ['approx-frac-edit']);
inp.value = val;
inp.addEventListener('change', () => {
const val = validate(parseFloat(inp.value),
x => isFinite(x) && isInt(x) && (x >= minVal));
if (val != null) onChange(val);
});
};
makeText(n, 0, x => grad.value = x / d);
newDiv(domApproxFrac, ['approx-frac-edit-line']);
makeText(d, 1, x => grad.value = n / x);
domApproxEqual.innerText = '=';
} else {
newDiv(domApproxFrac, ['approx-frac-num'], n);
if (d != 1) newDiv(domApproxFrac, ['approx-frac-den'], d);
domApproxEqual.innerText =
getApproxContFracTerms() < terms.length ? '≈' : '=';
}
}
let mainViewZoomExp = 0;
const getMainViewSize = () =>
mainViewSize * Math.pow(mainViewZoomRate, mainViewZoomExp);
const getViewSize = () =>
flagUnitCellMode.value ? cellViewSize : getMainViewSize();
const getClickPos = e => {
const viewSize = getViewSize();
const rect = canvas.getBoundingClientRect();
const mx = e.clientX - rect.x;
const my = e.clientY - rect.y;
const x = viewSize * mx / canvas.width;
const y = viewSize * (1 - my / canvas.height);
return [x, y];
};
let mouseClicked = false;
let currentGx = 1;
let currentGy = 0;
let currentOx = 0;
let currentOy = 0;
const anchors = [];
const snapToAnchor = (x, y, alsoSnapToLine) => {
const viewSize = getViewSize();
let mx = null;
let my = null;
let mi = null;
let md = Infinity;
const maybeSnap = (px, py, pi, distmul = 1) => {
if (px >= 0 && py >= 0 && px <= viewSize && py <= viewSize) {
const dx = x - px;
const dy = y - py;
const dd = distmul * (dx * dx + dy * dy);
if (dd < md) {
mx = px;
my = py;
mi = pi;
md = dd;
}
}
};
for (let i = 0; i < anchors.length; ++i) {
const [px, py] = anchors[i];
maybeSnap(px, py, i);
}
maybeSnap(Math.floor(x + 0.5), Math.floor(y + 0.5), null, 1.1);
if (alsoSnapToLine) {
const [lx, ly] = closestPointToLine(
x, y, currentOx, currentOy, currentGx, currentGy);
maybeSnap(lx, ly, null, 2);
}
if (md > 0.05) return null;
return [mx, my, mi];
};
const onMouse = (e, click) => {
e.preventDefault();
let [x, y] = getClickPos(e);
if (!click) {
const snap = snapToAnchor(x, y, false);
if (snap != null) {
x = snap[0];
y = snap[1];
}
}
const y_ = y + off.value;
if (x <= 0) {
grad.value = 1e3;
} else if (y_ <= 0) {
grad.value = 0;
} else {
grad.value = y_ / x;
}
targX = x;
targY = y;
targKeep = true;
};
const onRightClick = e => {
forceRedraw = true;
let [x, y] = getClickPos(e);
const snap = snapToAnchor(x, y, true);
if (snap == null) {
anchors.push([x, y]);
} else if (snap[2] == null) {
anchors.push([snap[0], snap[1]]);
} else {
popSwap(anchors, snap[2]);
}
};
canvas.addEventListener('mousedown', e => {
if (e.which == 1) {
onMouse(e, mouseClicked = true);
} else if (e.which == 3) {
onRightClick(e);
}
});
document.addEventListener('mousemove', e => {
if (mouseClicked) onMouse(e, mouseClicked);
});
document.addEventListener('mouseup', e => {
if (e.which == 1 && mouseClicked) onMouse(e, mouseClicked = false);
});
canvas.addEventListener('contextmenu', e => e.preventDefault());
canvas.addEventListener('wheel', e => {
e.preventDefault();
forceRedraw = true;
mainViewZoomExp = clamp(mainViewZoomExp + (0.01 * e.deltaY), -20, 10);
});
const circle = (cc, px, py, r, clr) => {
cc.fillStyle = clr;
cc.beginPath();
cc.ellipse(px, py, r, r, 0, 0, tau);
cc.fill();
};
const line = (cc, px, py, qx, qy, clr) => {
cc.strokeStyle = clr;
cc.beginPath();
cc.moveTo(px, py);
cc.lineTo(qx, qy);
cc.stroke();
};
const ray = (cc, px, py, dx, dy, clr) => {
const len = 2 * getMainViewSize();
line(cc, px, py, px + len * dx, py + len * dy, clr);
};
const update = () => {
for (const fn of onFrameCallbacks) fn();
if (alwaysRedraw || forceRedraw) {
forceRedraw = false;
const viewSize = getViewSize();
const mainDotSize =
mainDotInitSize * Math.sqrt(getMainViewSize() / mainViewSize);
const dotSize = flagUnitCellMode.value ? cellDotSize : mainDotSize;
const lineSize = flagUnitCellMode.value ? cellLineSize : mainLineSize;
const ctx = setupCanvas(canvas, viewSize, lineSize);
const [zn, zd] = getZ();
const zmode = isInZMode();
const g = grad.value;
const o = off.value;
const gx = 1 / Math.sqrt(1 + g * g);
const gy = gx * g;
if (!flagContFracEdit.value) {
targCoeff = 0;
}
const [terms, targCoeff_] = getContFracTermsWithTargCoeff(
grad.value, contFracTerms, targCoeff);
targCoeff = targCoeff_;
const zray = (n, d) => {
if (!zmode) return [[gy, gx], g];
const [y, x] = getApproxFrac(terms, getApproxContFracTerms(), n, d);
return [unit(y, x), y / x];
};
const [[ugy, ugx], zg] = zray(zn, zd);
const [[ugy0, ugx0], zg0] = zray(0, 1);
const [[ugy1, ugx1], zg1] = zray(1, 0);
const hitRad = isFinite(zg) ? (1 + zg) / Math.sqrt(1 + zg * zg) : 1;
const hitGx = ugy;
const hitGy = -ugx;
const hitSx = hitGx * hitRad;
const hitSy = hitGy * hitRad;
const hitOx = 0;
const hitOy = -o;
const sequence = sequenceFromGrad(zg, o, genSeqLength);
currentGx = ugx;
currentGy = ugy;
currentOx = hitOx;
currentOy = hitOy;
// Clear to black.
ctx.fillStyle = 'rgba(0, 0, 0, 1)';
ctx.fillRect(-2 * viewSize, -2 * viewSize, 4 * viewSize, 4 * viewSize);
// Draw dots.
const dotClr = zmode ? 'rgba(34, 34, 34, 1)' : 'rgba(68, 68, 68, 1)';
for (let i = 0; i <= viewSize; ++i) {
for (let j = 0; j <= viewSize; ++j) {
circle(ctx, i, j, dotSize, dotClr);
}
}
// Draw kernel lines.
const kernDraw = viewSize + 1;
for (let i = -1; i <= kernDraw; ++i) {
for (let j = -1; j <= kernDraw; ++j) {
line(ctx, i, j, i + hitSx, j + hitSy, dotClr);
}
}
// Draw anchors.
for (const [x, y] of anchors) {
circle(ctx, x, y, 2 * dotSize, 'rgba(156, 39, 176, 1)');
}
// Calculate ray hits.
let px = 0;
let py = 0;
const hits = [];
for (const goUp of sequence) {
const x = px + (goUp ? 0 : 1);
const y = py + (goUp ? 1 : 0);
const k = ugx * (x - hitOx) + ugy * (y - hitOy);
const ux = hitOx + k * ugx;
const uy = hitOy + k * ugy;
hits.push([px, py, x, y, ux, uy, k]);
px = x;
py = y;
}
if (!flagUnitCellMode.value) { // Normal mode.
// Draw rays.
if (zmode) {
ray(ctx, hitOx, hitOy, gx, gy, 'rgba(255, 255, 255, 0.5)');
// Draw z, z=0, and z=inf lines, if in z mode.
ray(ctx, hitOx, hitOy, ugx, ugy, `rgba(255, 255, 255, 1)`);
ray(ctx, hitOx, hitOy, ugx0, ugy0, `rgba(255, 255, 255, 0.5)`);
ray(ctx, hitOx, hitOy, ugx1, ugy1, `rgba(255, 255, 255, 0.5)`);
} else {
ray(ctx, hitOx, hitOy, gx, gy, 'rgba(255, 255, 255, 1)');
}
// Draw hit kernel lines.
for (const [px, py, x, y, ux, uy, k] of hits) {
line(ctx, x, y, ux, uy, 'rgba(0, 136, 255, 1)');
circle(ctx, x, y, dotSize, 'rgba(0, 136, 255, 1)');
}
// Hilite the dots between the z rays, if in z mode.
if (zmode) {
for (let i = 0; i <= viewSize; ++i) {
for (let j = 0; j <= viewSize; ++j) {
const k = (j - hitOy) / (i - hitOx);
if (k >= zg1 && k <= zg0) {
circle(ctx, i, j, dotSize, 'rgba(170, 170, 170, 1)');
}
}
}
}
// Draw hit dots.
for (const [px, py, x, y, ux, uy, k] of hits) {
circle(ctx, ux, uy, 2 * dotSize, 'rgba(255, 34, 0, 1)');
}
// Draw steps.
if (flagShowSteps.value) {
for (const [px, py, x, y, ux, uy, k] of hits) {
line(ctx, px, py, x, y, 'rgba(0, 255, 0, 0.8)');
}
}
// Draw approximants, if enabled.
if (flagShowConvergents.value) {
for (let i = 1; i <= terms.length; ++i) {
const [y, x] = getApproxFrac(terms, i);
circle(ctx, x, y, 2 * dotSize, 'rgba(255, 255, 0, 1)');
}
}
} else { // Unit cell mode.
// Draw ray.
const rcc = getRayCellCrossings(ugx, ugy, hitOx, hitOy, cellRayLength);
for (const [ax, ay, ak, bx, by, bk] of rcc) {
const grd = ctx.createLinearGradient(ax, ay, bx, by);
grd.addColorStop(0, `rgba(255, 255, 0, ${1 - ak})`);
grd.addColorStop(1, `rgba(255, 255, 0, ${1 - bk})`);
line(ctx, ax, ay, bx, by, grd);
}
// Modulo all the ray hits into the unit cell.
const modhits = [];
for (const [px, py, x, y, ux, uy, k] of hits) {
if (k > cellRayLength) break;
const mux = fmod(ux);
const muy = fmod(uy);
const gux = x + mux - ux;
const guy = y + muy - uy;
const alpha = 1 - k / cellRayLength;
modhits.push([mux, muy, gux, guy, alpha])
}
// Draw hit dots.
for (const [mux, muy, gux, guy, alpha] of modhits) {
circle(ctx, mux, muy, dotSize, `rgba(255, 34, 0, 1)`);
}
}
// Draw target point, if it exists.
if (targX != null && targY != null) {
circle(ctx, targX, targY, 2 * dotSize, 'rgba(255, 255, 255, 1)');
}
domUpdateLimiter.run(timeBetweenDomUpdatesMs, () => {
// Fill continued fraction and approx fraction.
fillContFracDom(terms, zn, zd);
fillApproxFracDom(terms, zn, zd);
// Fill word.
const word = sequence.map(x => x ? 'S' : 'L').join('');
domWord.innerText = word;
});
// Draw the crystal, if enabled.
if (flagShowCrystal.value) {
const viewSize = getMainViewSize();
const crystalCtx = setupCanvas(crystalCanvas, viewSize);
crystalCanvas.classList.remove('hidden');
crystalCtx.fillStyle = 'rgba(0, 0, 0, 1)';
crystalCtx.fillRect(
-2 * viewSize, -2 * viewSize, 4 * viewSize, 4 * viewSize);
const midy = 0.025 * viewSize;
line(crystalCtx, 0, midy, viewSize, midy, 'rgba(255, 255, 255, 1)');
for (const [px, py, x, y, ux, uy, k] of hits) {
circle(crystalCtx, k, midy, 2 * mainDotSize, 'rgba(255, 34, 0, 1)');
}
} else {
crystalCanvas.classList.add('hidden');
}
}
window.requestAnimationFrame(update);
};
update();
}
window.addEventListener('load', onLoad);
class YouTubeEmbed extends HTMLElement {
constructor() {
super();
const isBig = this.getAttribute('size') == 'big';
const iframe = newElement('iframe', this);