Repository navigation
Expand file tree
/
Copy pathshell.html
More file actions
1377 lines (1280 loc) · 53.9 KB
/
Copy pathshell.html
File metadata and controls
1377 lines (1280 loc) · 53.9 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Shell Method · 3D Explorer</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mathquill/0.10.1/mathquill.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css">
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.js"></script>
<style>
:root {
--bg: #0e1116;
--ink: #e8e6df;
--soft: #7a8794;
--gold: #ffd166;
--pill: #15181d;
--pill-border: #23272d;
}
* { box-sizing: border-box; }
html, body {
margin: 0; padding: 0; height: 100%;
background: var(--bg); color: var(--ink);
font-family: Georgia, "Source Serif Pro", serif;
overflow: hidden;
}
#app { display: grid; grid-template-rows: auto auto 1fr auto; height: 100%; }
#app > header { grid-row: 1; }
#app > #customForm { grid-row: 2; }
#app > #scene-wrap { grid-row: 3; }
#app > footer { grid-row: 4; }
header {
display: flex; align-items: center; justify-content: space-between;
padding: 14px 24px; border-bottom: 1px solid var(--pill-border);
flex-wrap: wrap; gap: 12px;
}
header h1 { margin: 0; font-size: 18px; font-weight: normal; color: #ddd; letter-spacing: 0.3px; }
header h1 b { color: var(--gold); }
.home-link {
color: var(--soft); text-decoration: none; font-size: 13px;
border: 1px solid var(--pill-border); border-radius: 14px;
padding: 5px 12px; transition: all 0.15s; white-space: nowrap;
}
.home-link:hover { color: var(--gold); border-color: var(--gold); }
.header-left { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; }
.presets { display: flex; gap: 8px; }
.presets button {
background: var(--pill); color: var(--soft);
border: 1px solid var(--pill-border); padding: 7px 16px;
border-radius: 18px; font-family: inherit; font-size: 14px;
cursor: pointer; transition: all 0.15s;
}
.presets button:hover { color: #fff; border-color: var(--gold); }
.presets button.active { color: var(--bg); background: var(--gold); border-color: var(--gold); font-weight: bold; }
#scene-wrap { position: relative; overflow: hidden; }
#scene { position: absolute; inset: 0; display: block;
width: 100% !important; height: 100% !important; }
.overlay {
position: absolute; top: 18px; left: 22px;
pointer-events: none;
background: rgba(14, 17, 22, 0.7);
backdrop-filter: blur(6px);
border: 1px solid var(--pill-border);
border-radius: 12px;
padding: 14px 18px;
max-width: 380px;
}
.overlay h2 { margin: 0 0 4px; font-size: 22px; color: var(--ink); font-weight: normal; }
.overlay h2 b { color: var(--gold); }
.overlay .formula { color: var(--soft); font-size: 13px; font-style: italic; margin-bottom: 6px; }
.overlay .vol { font-size: 14px; color: #ccc; }
.overlay .vol b { color: var(--gold); font-size: 18px; }
.overlay .legend { font-size: 12px; color: var(--soft); margin-top: 10px; line-height: 1.6; }
.overlay .legend .swatch {
display: inline-block; width: 10px; height: 10px; border-radius: 2px;
vertical-align: middle; margin-right: 6px;
}
footer { padding: 14px 24px 18px; border-top: 1px solid var(--pill-border);
background: rgba(14, 17, 22, 0.95); }
.controls { display: grid;
grid-template-columns: 1fr 1fr 1fr auto;
gap: 22px; align-items: center; }
.button-stack { display: flex; flex-direction: column; gap: 6px; }
.slider-block { display: flex; flex-direction: column; gap: 4px; }
.slider-block .label-row { display: flex; justify-content: space-between;
font-size: 13px; color: var(--soft); }
.slider-block .label-row b { color: var(--ink); font-weight: normal; }
input[type=range] {
-webkit-appearance: none; appearance: none;
width: 100%; height: 4px; background: #23272d;
border-radius: 2px; outline: none;
}
input[type=range]::-webkit-slider-thumb {
-webkit-appearance: none; appearance: none;
width: 16px; height: 16px; border-radius: 50%;
background: var(--gold); cursor: pointer;
border: 2px solid var(--bg);
}
input[type=range]::-moz-range-thumb {
width: 16px; height: 16px; border-radius: 50%;
background: var(--gold); cursor: pointer; border: 2px solid var(--bg);
}
button.action {
background: var(--gold); color: var(--bg); border: none;
padding: 9px 22px; border-radius: 22px;
font-family: inherit; font-size: 14px; font-weight: bold;
cursor: pointer; transition: transform 0.1s, background 0.15s;
letter-spacing: 0.3px;
}
button.action:hover { background: #ffe199; transform: translateY(-1px); }
button.action.ghost { background: transparent; color: var(--soft);
border: 1px solid var(--pill-border); }
button.action.ghost:hover { color: var(--ink); border-color: var(--gold); background: transparent; }
.speed-select {
background: var(--pill); color: var(--ink);
border: 1px solid var(--pill-border); border-radius: 14px;
padding: 5px 10px; font-family: inherit; font-size: 12px;
cursor: pointer; outline: none;
}
.speed-select:hover { border-color: var(--gold); }
.hint { color: var(--soft); font-size: 12px; font-style: italic;
padding: 6px 24px 0; }
/* Custom-equation form, shown below the header when "custom" is active */
#customForm {
display: none; gap: 10px; flex-wrap: wrap; align-items: center;
padding: 10px 24px; border-bottom: 1px solid var(--pill-border);
background: rgba(255, 209, 102, 0.05); font-size: 14px;
}
#customForm.shown { display: flex; }
#customForm label { color: var(--soft); }
#customForm input[type=text],
#customForm input[type=number] {
background: var(--pill); color: var(--ink);
border: 1px solid var(--pill-border); border-radius: 8px;
padding: 6px 10px; font-family: "Courier New", monospace; font-size: 13px;
outline: none;
}
#customForm input[type=text]:focus,
#customForm input[type=number]:focus { border-color: var(--gold); }
#customForm input[type=text] { width: 240px; }
#customForm input[type=number] { width: 60px; }
#customForm button {
background: var(--gold); color: var(--bg); border: none;
padding: 6px 14px; border-radius: 14px; cursor: pointer;
font-family: inherit; font-weight: bold; font-size: 13px;
}
#customError { color: #ff6f6f; font-size: 12px; font-style: italic; }
#customHelp { color: var(--soft); font-size: 11px; font-style: italic; }
@media (max-width: 720px) {
.controls { grid-template-columns: 1fr; gap: 14px; }
.overlay { max-width: 250px; padding: 10px 14px; }
.overlay h2 { font-size: 17px; }
}
button:focus-visible, a:focus-visible, input:focus-visible, select:focus-visible {
outline: 2px solid var(--gold); outline-offset: 3px;
}
/* ─── MathQuill dark-theme overrides ─── */
/* line-height: 1.0 keeps stretchy \left(\right) parens from scaling
to 1.8x for trivial content like sin(x). Fractions inside parens
still grow naturally because MQ scales to actual content height. */
#customForm .mq-editable-field {
background: var(--pill); color: var(--ink);
border: 1.5px solid var(--pill-border); border-radius: 8px;
padding: 6px 10px; min-width: 220px; min-height: 30px;
font-size: 14px; line-height: 1.0; cursor: text; vertical-align: middle;
}
#customForm .mq-editable-field.mq-focused {
border-color: var(--gold);
box-shadow: 0 0 0 2px rgba(255,209,102,0.15);
outline: none;
}
#customForm .mq-cursor { border-color: var(--gold); }
#customForm .mq-selection { background: rgba(255,209,102,0.25); }
.kbd-toggle {
background: #1c2028; color: var(--gold);
border: 1px solid var(--pill-border); border-radius: 8px;
padding: 5px 10px; font-size: 15px; cursor: pointer;
transition: border-color 0.15s, background 0.15s; line-height: 1;
}
.kbd-toggle:hover { border-color: var(--gold); background: #222832; }
.kbd-toggle.open { border-color: var(--gold); background: rgba(255,209,102,0.1); }
/* ─── Math Keyboard Popup ─── */
.kbd-popup {
position: fixed; z-index: 1000;
background: #12161c; border: 1px solid #1e2430; border-radius: 14px;
padding: 14px;
box-shadow: 0 20px 50px rgba(0,0,0,0.7), 0 0 0 1px rgba(255,255,255,0.03);
display: none;
}
.kbd-popup.open { display: block; }
.kbd-layout { display: flex; gap: 10px; align-items: flex-start; }
.kbd-card {
background: #0e1116; border: 1px solid #1e2430; border-radius: 10px;
padding: 10px; display: flex; flex-direction: column; gap: 5px;
}
.kbd-slabel {
font-size: 9px; text-transform: uppercase; letter-spacing: 1.2px;
color: #3d4857; font-weight: 600; padding-left: 2px; margin-bottom: 2px;
font-family: -apple-system, 'Segoe UI', sans-serif;
}
.kbd-row { display: flex; gap: 4px; }
.kbd-divider { height: 1px; background: #1e2430; margin: 3px 0; border: none; }
.k {
min-width: 40px; min-height: 40px; padding: 0 6px; border-radius: 7px;
border: 1px solid transparent; font-size: 13px; cursor: pointer;
display: flex; align-items: center; justify-content: center;
font-family: "Times New Roman", Georgia, serif;
transition: background 0.12s, border-color 0.12s, transform 0.08s;
user-select: none;
}
.k:hover { transform: translateY(-1px); box-shadow: 0 3px 8px rgba(0,0,0,0.3); }
.k:active { transform: scale(0.94); box-shadow: none; }
.k-op { background: #1e1e10; color: #ffd166; border-color: #2a2810; font-family: sans-serif; }
.k-op:hover { background: #26260f; border-color: #ffd166; }
.k-struct { background: #141828; color: #c8d8ff; border-color: #1e2440; font-size: 12px; min-width: 50px; }
.k-struct:hover { background: #182030; border-color: #4060b0; }
.k-var { background: #201c08; color: #ffd166; border-color: #302a10; font-style: italic; font-size: 16px; }
.k-var:hover { background: #28230a; border-color: #ffd166; }
.k-const { background: #16121e; color: #c8a4ff; border-color: #241a34; font-style: italic; font-size: 15px; }
.k-const:hover { background: #1c1828; border-color: #8060c0; }
.k-del { background: #201416; color: #ff8a8a; border-color: #301a1c; font-size: 16px; font-family: sans-serif; }
.k-del:hover { background: #28181a; border-color: #ff6060; }
.k-fn { background: #101820; color: #8ab8e8; border-color: #182030;
font-family: "Segoe UI", system-ui, sans-serif; font-size: 11px; font-weight: 500; min-width: 44px; }
.k-fn:hover { background: #142030; border-color: #4080b0; color: #b0d4f8; }
.k-frac { display: inline-flex; flex-direction: column; align-items: center; line-height: 1.2; font-size: 10px; gap: 1px; }
.k-frac span:first-child { border-bottom: 1px solid currentColor; padding: 0 4px; }
.k-frac span:last-child { padding: 0 4px; }
</style>
</head>
<body>
<div id="app">
<header>
<div class="header-left">
<a href="index.html" class="home-link">← overview</a>
<h1><b>Shell Method</b> · 3D Explorer</h1>
</div>
<div class="presets">
<button data-preset="sqrt" class="active">y = √x</button>
<button data-preset="parabola">y = x² / 2</button>
<button data-preset="sine">y = sin(x) + 0.2</button>
<button data-preset="custom">✏️ custom</button>
</div>
</header>
<div id="customForm">
<label>y = </label>
<span id="customExprMQ" class="mq-editable-field"></span>
<button id="kbdToggle" class="kbd-toggle" title="Open math keyboard">⌨</button>
<label>from x =</label>
<input id="customA" type="number" value="0" step="0.1">
<label>to</label>
<input id="customB" type="number" value="6.28" step="0.1">
<button id="customApply">apply</button>
<span id="customError"></span>
<span id="customHelp">type or use ⌨ keyboard · <b>x</b> is the variable · use <b>*</b> for multiplication · <b>^</b> for power</span>
</div>
<div id="scene-wrap">
<canvas id="scene" aria-label="Interactive 3D view of cylindrical shells wrapping around the axis of rotation"></canvas>
<div class="overlay">
<h2><b id="ovTitle">y = √x</b></h2>
<div class="formula" id="ovFormula">V = ∫ 2π · x · f(x) dx</div>
<div class="vol">Volume ≈ <b id="ovVol">80.425</b></div>
<div class="legend">
<div><span class="swatch" style="background:#ffd166"></span>2D curve in y=0 plane</div>
<div><span class="swatch" id="legendShell" style="background:linear-gradient(90deg,#1e1060,#3d28aa,#6750d8,#9270e0,#a888ee)"></span>shell where f(x) ≥ 0 (adds to integral)</div>
<div><span class="swatch" style="background:linear-gradient(90deg,#3a0a0a,#6e1515,#a82020,#c43535,#d04848)"></span>shell where f(x) < 0 (subtracts)</div>
<div><span class="swatch" style="background:transparent;border:2px solid #ffd166"></span>active shell (gold edges)</div>
<div><span class="swatch" style="background:transparent;border:1px dashed #888"></span>axis of rotation (z)</div>
</div>
</div>
</div>
<footer>
<div class="controls">
<div class="slider-block">
<div class="label-row"><span>Shell density</span><b id="lblDensity">24 shells</b></div>
<input id="densitySlider" type="range" min="4" max="60" value="24" aria-label="Shell density">
</div>
<div class="slider-block">
<div class="label-row"><span>Completed shells</span><b id="lblShells">12 / 24</b></div>
<input id="shellSlider" type="range" min="0" max="24" value="12" aria-label="Completed shells">
</div>
<div class="slider-block">
<div class="label-row"><span>Active shell sweep angle</span><b id="lblAngle">360°</b></div>
<input id="angleSlider" type="range" min="0" max="360" value="360" aria-label="Active shell sweep angle">
</div>
<div class="button-stack">
<button class="action" id="playBtn">▶ play</button>
<select id="speedSel" class="speed-select" title="play speed" aria-label="Animation speed">
<option value="2.5">🐢 slow</option>
<option value="1" selected>normal</option>
<option value="0.4">🐇 fast</option>
<option value="0.15">⚡ blitz</option>
</select>
<button class="action ghost" id="resetBtn">↺ reset view</button>
</div>
</div>
<div class="hint">drag to rotate · scroll to zoom · right-click drag to pan · density controls how finely the solid is approximated</div>
</footer>
</div>
<!-- Math Keyboard Popup -->
<div id="mathKeyboard" class="kbd-popup">
<div class="kbd-layout">
<div class="kbd-card">
<div class="kbd-slabel">Symbols</div>
<div class="kbd-row">
<button class="k k-struct" data-action="frac" title="Fraction"><span class="k-frac"><span>□</span><span>□</span></span></button>
<button class="k k-struct" data-action="pow" title="Power">□<sup style="font-size:8px">□</sup></button>
<button class="k k-struct" data-action="sqrt" title="Square root">√□</button>
<button class="k k-struct" data-action="abs" title="Absolute value">|□|</button>
<button class="k k-var" data-action="typedText" data-arg="x">x</button>
<button class="k k-const" data-action="typedText" data-arg="π">π</button>
<button class="k k-const" data-action="typedText" data-arg="e">e</button>
<button class="k k-del" data-action="keystroke" data-arg="Backspace">⌫</button>
</div>
<div class="kbd-row">
<button class="k k-op" data-action="typedText" data-arg="+">+</button>
<button class="k k-op" data-action="typedText" data-arg="-">−</button>
<button class="k k-op" data-action="typedText" data-arg="*">×</button>
<button class="k k-op" data-action="typedText" data-arg="/">÷</button>
<button class="k k-op" data-action="typedText" data-arg="(">(</button>
<button class="k k-op" data-action="typedText" data-arg=")">)</button>
</div>
</div>
<div class="kbd-card">
<div class="kbd-slabel">Trig & Logarithms</div>
<div class="kbd-row">
<button class="k k-fn" data-action="typedText" data-arg="sin(">sin</button>
<button class="k k-fn" data-action="typedText" data-arg="cos(">cos</button>
<button class="k k-fn" data-action="typedText" data-arg="tan(">tan</button>
</div>
<div class="kbd-row">
<button class="k k-fn" data-action="typedText" data-arg="csc(">csc</button>
<button class="k k-fn" data-action="typedText" data-arg="sec(">sec</button>
<button class="k k-fn" data-action="typedText" data-arg="cot(">cot</button>
</div>
<div class="kbd-row">
<button class="k k-fn" data-action="typedText" data-arg="arcsin(" style="min-width:55px">arcsin</button>
<button class="k k-fn" data-action="typedText" data-arg="arccos(" style="min-width:55px">arccos</button>
<button class="k k-fn" data-action="typedText" data-arg="arctan(" style="min-width:55px">arctan</button>
</div>
<hr class="kbd-divider">
<div class="kbd-row">
<button class="k k-fn" data-action="typedText" data-arg="ln(" style="flex:1;min-width:68px">ln</button>
<button class="k k-fn" data-action="typedText" data-arg="log(" style="flex:1;min-width:68px">log</button>
</div>
</div>
</div>
</div>
<!-- jQuery + MathQuill (regular scripts, before the module) -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathquill/0.10.1/mathquill.min.js"></script>
<script>
(function () {
'use strict';
var MQ = MathQuill.getInterface(2);
// Expose MQ field handles so the ES-module script can read values
window.mqState = {};
var mqExpr = MQ.MathField(document.getElementById('customExprMQ'), {
spaceBehavesLikeTab: false,
handlers: { enter: function () { document.getElementById('customApply').click(); } }
});
mqExpr.latex('\\sin\\left(x\\right)'); // default = sin(x)
window.mqState.expr = mqExpr;
var popup = document.getElementById('mathKeyboard');
var toggle = document.getElementById('kbdToggle');
var activeMQ = mqExpr;
function positionPopup() {
var rect = toggle.getBoundingClientRect();
var pw = popup.offsetWidth || 370;
popup.style.top = (rect.bottom + 6) + 'px';
popup.style.left = Math.max(8, Math.min(rect.left, window.innerWidth - pw - 12)) + 'px';
}
function openPopup() {
popup.classList.add('open'); toggle.classList.add('open');
positionPopup(); activeMQ = mqExpr; activeMQ.focus();
}
function closePopup() { popup.classList.remove('open'); toggle.classList.remove('open'); }
toggle.addEventListener('click', function (e) {
e.stopPropagation();
popup.classList.contains('open') ? closePopup() : openPopup();
});
document.addEventListener('click', function (e) {
if (!popup.contains(e.target) && e.target !== toggle) closePopup();
});
// Prevent popup clicks from blurring the MQ field
popup.addEventListener('mousedown', function (e) { e.preventDefault(); });
// Dispatch button actions to the active MQ field
popup.addEventListener('click', function (e) {
var btn = e.target.closest('[data-action]');
if (!btn || !activeMQ) return;
switch (btn.dataset.action) {
case 'typedText': activeMQ.typedText(btn.dataset.arg); break;
case 'cmd': activeMQ.cmd(btn.dataset.arg); break;
case 'keystroke': activeMQ.keystroke(btn.dataset.arg); break;
case 'frac': activeMQ.cmd('\\frac'); break;
case 'pow': activeMQ.cmd('^'); break;
case 'sqrt': activeMQ.cmd('\\sqrt'); break;
case 'abs':
activeMQ.write('\\left|\\right|');
activeMQ.keystroke('Left');
break;
}
activeMQ.focus();
});
document.getElementById('customExprMQ').addEventListener('click', function () {
activeMQ = mqExpr;
});
// ── LaTeX → JS expression converter ──────────────────────────────────────
// Known function names — a letter run that matches one of these does NOT
// get an implicit '*' inserted before its trailing '('. Anything else is
// treated as a variable run (so `2x` → `2*x`, `xsin(y)` → `x*sin(y)`).
// Constants like `pi`, `e` are NOT in this list — `\pi(x+1)` should
// become `pi*(x+1)`, not the function call `pi(x+1)`.
var FN_NAMES = /^(sin|cos|tan|csc|sec|cot|arcsin|arccos|arctan|sinh|cosh|tanh|ln|log|log10|exp|sqrt|cbrt|abs|pow|min|max|floor|ceil|round|sign|hypot)$/;
// Insert explicit '*' for implicit multiplication that high-school students
// routinely write but JS rejects: `2x`, `2(x+1)`, `(x+1)(x-1)`, `x(2)`, etc.
// Walk the string token-by-token so we don't insert '*' inside numbers,
// inside identifiers, or before a function call's '('.
function insertImplicitMul(s) {
var out = '', i = 0, n = s.length;
function readNum() {
var j = i;
while (j < n && /[0-9.]/.test(s[j])) j++;
var t = s.slice(i, j); i = j; return t;
}
function readIdent() {
var j = i;
while (j < n && /[a-zA-Z_]/.test(s[j])) j++;
var t = s.slice(i, j); i = j; return t;
}
var prev = ''; // last token kind: '' | 'num' | 'var' | 'fn' | 'rparen'
while (i < n) {
var c = s[i];
if (/[0-9.]/.test(c)) {
if (prev === 'num' || prev === 'var' || prev === 'rparen') out += '*';
out += readNum(); prev = 'num';
} else if (/[a-zA-Z_]/.test(c)) {
var id = readIdent();
// Function call if next non-space char is '('. `e` and `pi` count
// as variables/constants, never functions.
var k = i; while (k < n && s[k] === ' ') k++;
var isFn = FN_NAMES.test(id) && s[k] === '(';
if (prev === 'num' || prev === 'var' || prev === 'rparen') out += '*';
out += id;
prev = isFn ? 'fn' : 'var';
} else if (c === ' ') {
// Spaces from convert() act as identifier separators; copy them so
// JS still parses (`x sin(x)` is valid JS for x*sin(x)... no wait,
// it isn't — JS would parse as x sin which is two statements).
// We DON'T want to keep these spaces in the final JS — drop them
// and let prev-state drive the implicit '*'.
i++;
} else if (c === '(') {
if (prev === 'num' || prev === 'var' || prev === 'rparen') out += '*';
out += c; i++; prev = '';
} else if (c === ')') {
out += c; i++; prev = 'rparen';
} else if (c === '*' && s[i+1] === '*') {
// power operator: copy '**' then continue (next token can be num/(/var)
out += '**'; i += 2; prev = '';
} else {
out += c; i++;
// Any other operator/punct resets the "could-multiply" state.
if (/[+\-/^,]/.test(c)) prev = '';
}
}
return out;
}
window.latexToJS = function (latex) {
// Don't pre-strip whitespace: MathQuill emits `\pi x` (space-terminated
// cmd) and `\sin x`, and the cmd-reader needs that boundary. convert()
// skips spaces internally.
return insertImplicitMul(convert(latex));
function findClose(s, pos) {
var d = 0;
for (var i = pos; i < s.length; i++) {
if (s[i] === '{') d++;
else if (s[i] === '}' && --d === 0) return i;
}
return s.length - 1;
}
function convert(s) {
var out = '', i = 0;
// Emit text from a translated LaTeX cmd. Pads with spaces on either
// side when needed so adjacent typed letters/digits don't merge with
// it — e.g. `x\sin(y)` would otherwise become `xsin(y)` (one variable),
// and `2\pi x` would become `2pix`.
function emit(text) {
if (out && /[a-zA-Z0-9_]$/.test(out) && /^[a-zA-Z_]/.test(text)) out += ' ';
out += text;
if (/[a-zA-Z_]$/.test(text)) out += ' ';
}
while (i < s.length) {
var c = s[i];
if (c === '\\') {
var j = i + 1;
while (j < s.length && /[a-zA-Z]/.test(s[j])) j++;
var cmd = s.slice(i + 1, j);
i = j;
if (cmd === 'frac') {
var nc = findClose(s, i), num = s.slice(i + 1, nc); i = nc + 1;
var dc = findClose(s, i), den = s.slice(i + 1, dc); i = dc + 1;
out += '((' + convert(num) + ')/(' + convert(den) + '))';
} else if (cmd === 'sqrt') {
if (s[i] === '[') { i = s.indexOf(']', i) + 1; }
var sc = findClose(s, i), sa = s.slice(i + 1, sc); i = sc + 1;
emit('sqrt(' + convert(sa) + ')');
} else if (cmd === 'left') {
var dl = s[i++];
if (dl === '|') {
var ri = s.indexOf('\\right|', i);
if (ri !== -1) { emit('abs(' + convert(s.slice(i, ri)) + ')'); i = ri + 7; }
else { out += '|'; }
} else if (dl === '.') {
// \left. is an invisible delimiter — emit nothing
} else {
out += (dl === '(' || dl === '[') ? '(' : dl;
}
} else if (cmd === 'right') {
var dr = s[i++];
if (dr === '|' || dr === '.') {
// \right| handled above; \right. is invisible — emit nothing
} else out += ')';
} else {
var MAP = {
pi:'pi', cdot:'*', times:'*', div:'/',
sin:'sin', cos:'cos', tan:'tan',
csc:'csc', sec:'sec', cot:'cot',
arcsin:'arcsin', arccos:'arccos', arctan:'arctan',
ln:'ln', log:'log10', exp:'exp',
};
emit((MAP[cmd] !== undefined) ? MAP[cmd] : cmd);
}
} else if (c === '^') {
i++;
if (s[i] === '{') {
var ec = findClose(s, i), ep = s.slice(i + 1, ec); i = ec + 1;
out += '**(' + convert(ep) + ')';
} else { out += '**(' + s[i++] + ')'; }
} else if (c === '{') {
var gc = findClose(s, i), gp = s.slice(i + 1, gc); i = gc + 1;
out += '(' + convert(gp) + ')';
} else if (c === '}') {
i++;
} else if (c === '_') {
i++;
if (s[i] === '{') { i = findClose(s, i) + 1; } else i++;
} else if (/\s/.test(c)) {
// skip whitespace — it served as a cmd terminator already
i++;
} else {
out += c; i++;
}
}
return out;
}
};
}());
</script>
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/three@0.160.0/build/three.module.js",
"three/addons/": "https://unpkg.com/three@0.160.0/examples/jsm/"
}
}
</script>
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
// Single blue → purple ramp used for every preset's positive shells.
// Inner (axis-side) shells use the deep navy end, outer shells use the
// lavender end, so the stack reads as a smooth depth gradient.
const POSITIVE_GRADIENT = [0x1e1060, 0x3d28aa, 0x6750d8, 0x9270e0, 0xa888ee];
// Red ramp for any shell with f(r) < 0 — the part of the integral that
// subtracts from the total. Same red across all presets so the meaning
// is consistent.
const NEGATIVE_GRADIENT = [0x3a0a0a, 0x6e1515, 0xa82020, 0xc43535, 0xd04848];
const PRESETS = {
sqrt: {
label: 'y = √x',
formula: 'V = ∫₀⁴ 2π · x · √x dx',
titleLatex: 'y = \\sqrt{x}',
formulaLatex: 'V = \\int_0^4 2\\pi\\, x \\sqrt{x}\\, dx',
f: x => Math.sqrt(x),
a: 0.001, b: 4.0,
},
parabola: {
label: 'y = x² / 2',
formula: 'V = ∫₀² 2π · x · (x²/2) dx',
titleLatex: 'y = \\dfrac{x^2}{2}',
formulaLatex: 'V = \\int_0^2 2\\pi\\, x \\cdot \\dfrac{x^2}{2}\\, dx',
f: x => 0.5 * x * x,
a: 0.001, b: 2.0,
},
sine: {
label: 'y = sin(x) + 0.2',
formula: 'V = ∫₀^π 2π · x · (sin x + 0.2) dx',
titleLatex: 'y = \\sin(x) + 0.2',
formulaLatex: 'V = \\int_0^{\\pi} 2\\pi\\, x \\cdot \\bigl(\\sin x + 0.2\\bigr)\\, dx',
f: x => Math.sin(x) + 0.2,
a: 0.001, b: Math.PI,
},
custom: {
label: 'custom',
formula: 'V = ∫ 2π · x · f(x) dx',
titleLatex: 'y = \\sin(x)',
formulaLatex: 'V = \\int 2\\pi\\, x \\cdot f(x)\\, dx',
f: x => Math.sin(x), // default shows the +/- shell behavior
a: 0.001, b: 6.283,
},
};
// KaTeX render with plain-text fallback if the CDN didn't load.
function renderMath(el, latex, displayMode = false) {
if (!el) return;
if (typeof katex !== 'undefined') {
try {
katex.render(latex, el, { displayMode, throwOnError: false, output: 'html' });
return;
} catch (e) { /* fall through */ }
}
el.textContent = latex;
}
let N_SHELLS = 24; // adjustable via density slider
const canvas = document.getElementById('scene');
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, preserveDrawingBuffer: true });
renderer.setPixelRatio(window.devicePixelRatio);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0e1116);
scene.fog = new THREE.Fog(0x0e1116, 12, 28);
const camera = new THREE.PerspectiveCamera(45, 1, 0.1, 100);
camera.up.set(0, 0, 1);
const controls = new OrbitControls(camera, canvas);
controls.enableDamping = true;
controls.dampingFactor = 0.08;
controls.target.set(0, 0, 1);
// Hemisphere light = even sky/ground fill so no part of the solid
// goes pitch-black when the user rotates. Plus a camera-anchored
// directional light so the side facing the viewer is always lit.
const hemi = new THREE.HemisphereLight(0xeaf2ff, 0x1a1f28, 0.85);
hemi.position.set(0, 0, 1);
scene.add(hemi);
scene.add(new THREE.AmbientLight(0xffffff, 0.25));
const camLight = new THREE.DirectionalLight(0xffffff, 0.55);
camLight.position.set(0.3, 0.5, 1);
camera.add(camLight);
scene.add(camera);
const grid = new THREE.GridHelper(10, 20, 0x2a2f36, 0x1a1d22);
grid.rotation.x = Math.PI / 2;
scene.add(grid);
const axesHelper = new THREE.AxesHelper(0.6);
axesHelper.material.opacity = 0.55;
axesHelper.material.transparent = true;
scene.add(axesHelper);
let axisLine = null;
const stage = new THREE.Group();
scene.add(stage);
function disposeGroup(group) {
group.traverse(obj => {
if (obj.geometry) obj.geometry.dispose();
if (obj.material) {
if (Array.isArray(obj.material)) obj.material.forEach(m => m.dispose());
else obj.material.dispose();
}
});
group.clear();
}
// Compile a math expression string into a JS function f(x).
// Accepts MathQuill text() output (e.g. x^2+sin(x)) and latexToJS() output.
// Uses a rich scope so csc, sec, cot, arcsin/cos/tan, ln, log10, pi, e all work.
function compileExpression(raw) {
if (!raw || !raw.trim()) throw new Error('expression is empty');
let s = raw.trim().toLowerCase();
s = s.replace(/π/g, 'pi').replace(/\^/g, '**');
s = s.replace(/×/g, '*').replace(/÷/g, '/');
// Implicit multiplication so kids can write 2x, 3sin(x), 2(x+1), (x+1)(x-1)
// the way they would on paper. The lookahead on the first rule preserves
// scientific notation like 1e-3. (pi/e resolve via the mathScope below.)
s = s.replace(/(\d)(?!\s*e[\d+\-])([a-zA-Z(])/g, '$1*$2');
s = s.replace(/(\))(\s*[\da-zA-Z(])/g, '$1*$2');
// Disallow bare `=` or `;` to avoid surprise multi-statement bodies
if (/[=;]/.test(s)) throw new Error('use a single expression — no = or ;');
const mathScope = {
pi: Math.PI, e: Math.E,
abs: Math.abs, sqrt: Math.sqrt, cbrt: Math.cbrt,
sin: Math.sin, cos: Math.cos, tan: Math.tan,
asin: Math.asin, acos: Math.acos, atan: Math.atan,
log: Math.log, ln: Math.log, log10: Math.log10, exp: Math.exp,
pow: Math.pow, ceil: Math.ceil, floor: Math.floor, round: Math.round,
min: Math.min, max: Math.max, sign: Math.sign, hypot: Math.hypot,
csc: x => 1 / Math.sin(x),
sec: x => 1 / Math.cos(x),
cot: x => Math.cos(x) / Math.sin(x),
arcsin: Math.asin, arccos: Math.acos, arctan: Math.atan,
};
try {
const factory = new Function('__m__', `return function(x){ with(__m__){ return (${s}); }; }`);
return factory(mathScope);
} catch (e) {
throw new Error('syntax error — check your parentheses and operators');
}
}
// Convert JS expression to a readable display string (cleans up ** and nested parens).
function jsPretty(s) {
if (!s) return s;
// x**(n) → x^n (single token exponent)
s = s.replace(/\*\*\((\w+)\)/g, '^$1');
// ((a)/(b)) → a/b
s = s.replace(/\(\((.+?)\)\/\((.+?)\)\)/g, '$1/$2');
return s;
}
// Sample an N-stop gradient at parameter t ∈ [0, 1].
function gradientColor(stops, t) {
t = Math.max(0, Math.min(1, t));
const colors = stops.map(h => new THREE.Color(h));
const n = colors.length - 1;
const seg = Math.min(Math.floor(t * n), n - 1);
const u = (t * n) - seg;
return new THREE.Color().lerpColors(colors[seg], colors[seg + 1], u);
}
function trapVolume(f, a, b, n = 400) {
const dx = (b - a) / n;
let s = 0;
for (let i = 0; i <= n; i++) {
const x = a + i * dx;
const w = (i === 0 || i === n) ? 0.5 : 1;
s += w * 2 * Math.PI * x * f(x);
}
return s * dx;
}
function makeShell(r, h, theta, gradient, isActive, idx, total) {
const group = new THREE.Group();
const safeTheta = Math.max(0.0001, Math.min(theta, Math.PI * 2));
const isNegative = h < 0;
const absH = Math.abs(h);
// CylinderGeometry needs a positive height; the sign of h is kept in the
// translate so the shell drops below z=0 when f(r) is negative.
const cylGeom = new THREE.CylinderGeometry(
r, r, absH,
Math.max(24, Math.floor(safeTheta / (Math.PI * 2) * 64)),
1,
true,
0, safeTheta
);
cylGeom.rotateX(Math.PI / 2);
cylGeom.translate(0, 0, h / 2); // h/2 places base at z=0 for either sign
// Negative shells use the red ramp to signal "this part subtracts from the
// integral." Positive shells use the preset's own gradient.
const ramp = isNegative ? NEGATIVE_GRADIENT : gradient;
const t = total > 1 ? idx / (total - 1) : 0.5;
const baseColor = gradientColor(ramp, t);
const shellColor = isActive
? baseColor.clone().multiplyScalar(1.35)
: baseColor;
const mat = new THREE.MeshStandardMaterial({
color: shellColor,
side: THREE.DoubleSide,
roughness: 0.5,
metalness: 0.08,
flatShading: false,
emissive: isActive ? shellColor.clone().multiplyScalar(0.25) : 0x000000,
});
group.add(new THREE.Mesh(cylGeom, mat));
// Edge rings on top/bottom are ONLY drawn for the active (swept) shell.
// Drawing them on every shell at high density creates moiré/staircase
// artifacts; we let the gradient + lighting alone separate inactive shells.
if (isActive) {
const edgeMat = new THREE.LineBasicMaterial({ color: 0xffd166 });
const segs = Math.max(24, Math.floor(safeTheta / (Math.PI * 2) * 96));
const topPts = [], botPts = [];
for (let j = 0; j <= segs; j++) {
const t = (j / segs) * safeTheta;
const cx = r * Math.cos(t), cy = r * Math.sin(t);
topPts.push(new THREE.Vector3(cx, cy, h));
botPts.push(new THREE.Vector3(cx, cy, 0));
}
group.add(new THREE.Line(new THREE.BufferGeometry().setFromPoints(topPts), edgeMat));
group.add(new THREE.Line(new THREE.BufferGeometry().setFromPoints(botPts), edgeMat));
}
// Vertical seam lines (only when the shell is partially swept)
if (safeTheta < Math.PI * 2 - 0.01) {
[0, safeTheta].forEach(t => {
const seamMat = new THREE.LineBasicMaterial({
color: isActive ? 0xffd166 : 0x444444,
transparent: true, opacity: isActive ? 1.0 : 0.5,
});
const v = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(r * Math.cos(t), r * Math.sin(t), 0),
new THREE.Vector3(r * Math.cos(t), r * Math.sin(t), h),
]);
group.add(new THREE.Line(v, seamMat));
});
}
return group;
}
let activePresetKey = 'sqrt';
let shellCount = 12;
let sweepAngle = Math.PI * 2;
function rebuild() {
disposeGroup(stage);
if (axisLine) {
scene.remove(axisLine);
axisLine.geometry.dispose();
axisLine.material.dispose();
axisLine = null;
}
const p = PRESETS[activePresetKey];
const { f, a, b } = p;
const gradient = POSITIVE_GRADIENT;
const radii = [];
for (let i = 0; i < N_SHELLS; i++) {
radii.push(a + (b - a) * (i + 0.5) / N_SHELLS);
}
const curvePts = [];
const samples = 140;
for (let i = 0; i <= samples; i++) {
const x = a + (b - a) * i / samples;
curvePts.push(new THREE.Vector3(x, 0, f(x)));
}
const curve3 = new THREE.CatmullRomCurve3(curvePts);
const curveGeom = new THREE.TubeGeometry(curve3, samples, 0.025, 8, false);
stage.add(new THREE.Mesh(curveGeom, new THREE.MeshBasicMaterial({ color: 0xffd166 })));
const baseGeom = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(a, 0, 0), new THREE.Vector3(b, 0, 0),
]);
stage.add(new THREE.Line(baseGeom, new THREE.LineBasicMaterial({ color: 0x6a7480 })));
// Axis line spans the full vertical reach of the function — including
// any portion that dips below z=0.
const zHi = Math.max(0, ...curvePts.map(pt => pt.z)) * 1.15 + 0.2;
const zLo = Math.min(0, ...curvePts.map(pt => pt.z)) * 1.15 - 0.05;
const axisGeom = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(0, 0, zLo), new THREE.Vector3(0, 0, zHi),
]);
axisLine = new THREE.Line(axisGeom, new THREE.LineDashedMaterial({
color: 0xbbbbbb, dashSize: 0.12, gapSize: 0.07, transparent: true, opacity: 0.7,
}));
axisLine.computeLineDistances();
scene.add(axisLine);
// When the stack is at max, treat the LAST shell as the active one so the
// sweep slider still has something to act on. Otherwise the active shell
// is the one immediately past the completed run.
const atMax = shellCount >= N_SHELLS;
const activeIdx = atMax ? N_SHELLS - 1 : shellCount;
const completedCount = atMax ? N_SHELLS - 1 : shellCount;
for (let i = 0; i < N_SHELLS; i++) {
const r = radii[i];
const h = f(r);
if (Math.abs(h) < 0.0005) continue; // skip degenerate flat shells
if (i < completedCount) {
stage.add(makeShell(r, h, Math.PI * 2, gradient, false, i, N_SHELLS));
} else if (i === activeIdx && sweepAngle > 0.001) {
stage.add(makeShell(r, h, sweepAngle, gradient, true, i, N_SHELLS));
}
}
controls.target.set(0, 0, (zLo + zHi) / 2);
renderMath(document.getElementById('ovTitle'), p.titleLatex || p.label);
renderMath(document.getElementById('ovFormula'), p.formulaLatex || p.formula);
document.getElementById('ovVol').textContent = trapVolume(f, a, b).toFixed(3);
// sync legend gradient swatch to the active preset's ramp
const gradientStops = gradient.map(h => '#' + h.toString(16).padStart(6, '0'));
const sw = document.getElementById('legendShell');
if (sw) sw.style.background = `linear-gradient(90deg, ${gradientStops.join(', ')})`;
}
function frameCamera() {
const p = PRESETS[activePresetKey];
// Probe a few points to find the true vertical extent — handles
// functions that dip below the xy plane.
const samples = 24;
let zMax = 0, zMin = 0;
for (let i = 0; i <= samples; i++) {
const x = p.a + (p.b - p.a) * i / samples;
const z = p.f(x);
if (z > zMax) zMax = z;
if (z < zMin) zMin = z;
}
const radius = p.b;
const reach = Math.max(radius, zMax - zMin);
const dist = reach * 2.0 + 1.5;
const midZ = (zMin + zMax) / 2;
controls.target.set(0, 0, midZ);
camera.position.set(dist * 0.7, dist * 0.7, midZ + dist * 0.55);
camera.near = dist * 0.01;
camera.far = dist * 10;
camera.updateProjectionMatrix();
if (scene.fog) {
scene.fog.near = dist * 0.6;
scene.fog.far = dist * 2.0;
}
camera.lookAt(controls.target);
controls.update();
}
function resize() {
const w = canvas.parentElement.clientWidth;
const h = canvas.parentElement.clientHeight;
renderer.setSize(w, h, false);
camera.aspect = w / h;
camera.updateProjectionMatrix();
}
window.addEventListener('resize', resize);
function tick() {
controls.update();
renderer.render(scene, camera);
requestAnimationFrame(tick);
}
const densitySlider = document.getElementById('densitySlider');
const shellSlider = document.getElementById('shellSlider');
const angleSlider = document.getElementById('angleSlider');
const lblDensity = document.getElementById('lblDensity');
const lblShells = document.getElementById('lblShells');
const lblAngle = document.getElementById('lblAngle');
const playBtn = document.getElementById('playBtn');
const resetBtn = document.getElementById('resetBtn');
function syncLabels() {
lblDensity.textContent = `${N_SHELLS} shells`;
lblShells.textContent = `${shellCount} / ${N_SHELLS}`;
const deg = Math.round(sweepAngle * 180 / Math.PI);
lblAngle.textContent = `${deg}°`;
}
densitySlider.addEventListener('input', e => {
const newN = +e.target.value;
// Preserve roughly the same fill ratio when density changes
const ratio = N_SHELLS > 0 ? shellCount / N_SHELLS : 0.5;
N_SHELLS = newN;
shellCount = Math.min(N_SHELLS, Math.round(ratio * N_SHELLS));
shellSlider.max = N_SHELLS;
shellSlider.value = shellCount;
syncLabels();
rebuild();