-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path3D-Human-v3G.html
More file actions
2043 lines (1881 loc) · 98.3 KB
/
Copy path3D-Human-v3G.html
File metadata and controls
2043 lines (1881 loc) · 98.3 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>Live 3D Capture — MediaPipe + Three.js</title>
<style>
@import url('https://fonts.googleapis.com/css2?family=Anybody:wght@400;700;900&family=DM+Mono:wght@300;400;500&display=swap');
:root{
--bg:#07090e;--panel:#11151e;--panel2:#090c12;--panel3:#171d29;--border:#232b3c;
--text:#eef2f8;--muted:#7b879f;--cyan:#00e4ff;--magenta:#ff2d8a;--gold:#ffc842;
--green:#00e88c;--red:#ff4466;--violet:#9b6bff;--radius:12px;--rail:224px;
}
*{box-sizing:border-box} html,body{height:100%;margin:0} body{background:var(--bg);color:var(--text);font-family:'DM Mono',monospace;overflow:hidden}
button,select,input{font:inherit} button{border:1px solid var(--border);background:var(--panel2);color:var(--text);border-radius:10px;cursor:pointer}
button:hover:not(:disabled){border-color:var(--cyan);color:var(--cyan)} button:disabled{opacity:.4;cursor:not-allowed}
button.active{border-color:var(--cyan);color:var(--cyan);background:rgba(0,228,255,.09)}
button.primary{background:var(--cyan);border-color:var(--cyan);color:#001018;font-weight:900} button.gold{border-color:var(--gold);color:var(--gold)} button.danger{border-color:var(--red);color:var(--red)}
select{background:var(--panel2);color:var(--text);border:1px solid var(--border);border-radius:9px;padding:7px 9px;min-width:0}
input[type=range]{width:100%;accent-color:var(--cyan)} .hidden-input{display:none}
.app-shell{height:100vh;display:grid;grid-template-rows:122px minmax(0,1fr)}
.topbar{display:grid;grid-template-columns:200px minmax(190px,.72fr) minmax(430px,1.8fr);gap:8px;padding:8px;border-bottom:1px solid var(--border);background:linear-gradient(180deg,#10151f,#090c12)}
.top-camera{position:relative;min-width:0;border:1px solid var(--border);border-radius:12px;overflow:hidden;background:#000}
.preview-wrap{position:absolute;inset:0;background:#000;overflow:hidden}.preview-wrap video,.preview-wrap img{width:100%;height:100%;object-fit:contain;display:block}
#overlayCanvas{position:absolute;inset:0;width:100%;height:100%;pointer-events:none}.tag{position:absolute;top:6px;font-size:9px;letter-spacing:1px;background:rgba(0,0,0,.55);padding:3px 6px;border-radius:999px}.tag.l{left:7px;color:var(--cyan)}.tag.r{right:7px;color:var(--green)}
.frame-guide{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);pointer-events:none;border:1px dashed rgba(255,255,255,.5);border-radius:45% 45% 34% 34%;box-shadow:0 0 0 999px rgba(0,0,0,.06)}
.frame-guide.full{width:36%;height:91%}.frame-guide.portrait{width:62%;height:92%;border-radius:38% 38% 20% 20%}.frame-guide.dynamic{width:52%;height:90%;border-color:var(--green)}
.audio-bars{position:absolute;left:6px;right:6px;bottom:5px;display:flex;align-items:flex-end;gap:1px;height:20px}.audio-bars .bar{flex:1;background:var(--cyan);min-width:2px;border-radius:1px 1px 0 0}
.brand{display:flex;flex-direction:column;justify-content:center;min-width:0;padding:3px 5px}.eyebrow,.brand .sub{display:none}.brand h1{font-family:'Anybody',sans-serif;font-size:22px;line-height:1.02;margin:2px 0 5px;font-weight:900;background:linear-gradient(135deg,var(--cyan),var(--magenta));-webkit-background-clip:text;background-clip:text;-webkit-text-fill-color:transparent}
.status-row{display:flex;gap:5px;flex-wrap:wrap;margin-top:8px}.pill{display:inline-flex;align-items:center;gap:5px;padding:3px 7px;border:1px solid var(--border);background:#080b11;border-radius:999px;font-size:9px;color:var(--muted)}.pill .dot{width:6px;height:6px;border-radius:50%;background:#333}.pill.on .dot{background:var(--green);box-shadow:0 0 6px var(--green)}.pill.warn .dot{background:var(--gold)}.pill.err .dot{background:var(--red)}.pill.rec .dot{background:var(--red);box-shadow:0 0 7px var(--red);animation:blink 1s infinite}@keyframes blink{50%{opacity:.25}}
.header-controls{display:grid;grid-template-rows:auto auto;gap:6px;align-content:center;min-width:0}.header-line{display:flex;gap:5px;align-items:center;min-width:0}.source-grid{display:flex;gap:4px;flex:1;min-width:0}.source-btn{height:38px;min-width:44px;flex:1;display:flex;align-items:center;justify-content:center;border:1px solid var(--border);border-radius:9px;background:var(--panel2);color:var(--muted);cursor:pointer}.source-btn .icon{font-size:19px}.source-btn .txt{display:none}.source-btn.active{border-color:var(--cyan);color:var(--cyan);background:rgba(0,228,255,.07)}
.top-select{max-width:170px}.frame-modes{display:flex;gap:4px;flex:1}.frame-btn{padding:7px 8px;min-width:0;flex:1;font-size:9px}.top-action{padding:8px 11px;white-space:nowrap}.flip-btn{font-size:16px;padding:6px 9px}
.workspace{min-height:0;display:grid;grid-template-columns:var(--rail) minmax(0,1fr);gap:8px;padding:8px}.palette{min-height:0;overflow-y:auto;padding-right:3px;display:flex;flex-direction:column;gap:9px}.palette::-webkit-scrollbar{width:7px}.palette::-webkit-scrollbar-thumb{background:#252d40;border-radius:10px}
.panel{background:var(--panel);border:1px solid var(--border);border-radius:var(--radius);padding:8px}.panel-title{font-family:'Anybody',sans-serif;font-size:12px;font-weight:900;letter-spacing:.5px;margin-bottom:5px;display:flex;align-items:center;justify-content:space-between}.panel-title span:last-child{display:none}
.big-tools{display:grid;grid-template-columns:repeat(3,1fr);gap:4px}.emoji-tool{height:44px;padding:3px;display:flex;align-items:center;justify-content:center;gap:3px;font-size:8px;font-weight:700}.emoji-tool .e{font-size:21px}.emoji-tool small{font-size:8px}.emoji-tool.on{border-color:var(--cyan);background:rgba(0,228,255,.07);color:var(--cyan)}
.switch{display:none}.toggle-row{display:contents}.toggle-row label{display:none}.count{display:none}
.slider-block{margin-top:5px}.slider-label{display:flex;justify-content:space-between;gap:6px;align-items:baseline;font-size:9px}.slider-label strong{font-family:'Anybody';font-size:12px}.slider-label span:last-child{color:var(--cyan)}.slider-block input{margin-top:0}.ticks{display:none}
.profile-chip{display:none}.profile-chip b{color:var(--text)}
.compact-row{display:flex;gap:5px;align-items:center}.compact-row>*{min-width:0}.compact-row button{padding:7px 8px;flex:1;font-size:9px}.compact-row select{flex:1;font-size:9px}
.mini{font-size:9px;color:var(--muted);line-height:1.45}.sep{height:1px;background:var(--border);margin:8px 0}
#snapCanvas{display:none;width:100%;height:1px}.log{font-size:9px;line-height:1.45;color:var(--muted);max-height:110px;overflow:auto;white-space:pre-wrap;background:var(--panel2);border-radius:8px;padding:7px}.log .info{color:var(--cyan)}.log .warn{color:var(--gold)}.log .err{color:var(--red)}.log .ok{color:var(--green)}
details.panel{display:none;padding:0} details.panel>summary{list-style:none;cursor:pointer;padding:10px;font-family:'Anybody';font-size:11px;font-weight:800}details.panel>summary::-webkit-details-marker{display:none}.detail-body{padding:0 10px 10px}
.parts-list{display:grid;grid-template-columns:1fr 1fr;gap:4px;max-height:190px;overflow:auto}.part-chip{display:flex;gap:5px;align-items:center;background:var(--panel2);border:1px solid var(--border);padding:5px;border-radius:7px;font-size:8px}.part-chip.off{opacity:.4}.part-chip input{accent-color:var(--cyan)}
.gallery{display:flex;flex-direction:column;gap:5px;max-height:150px;overflow:auto}.gitem{display:flex;align-items:center;gap:5px;background:var(--panel2);padding:6px;border-radius:7px;font-size:8px}.gitem .nm{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.gitem button{font-size:8px;padding:4px}.gempty{font-size:9px;color:var(--muted);padding:7px}.kv{display:flex;justify-content:space-between;gap:5px;font-size:8px;padding:3px 0;border-bottom:1px dashed rgba(255,255,255,.05)}.kv span:first-child{color:var(--muted)}
.stage{min-width:0;min-height:0;position:relative}.canvas-wrap{position:absolute;inset:0;border:1px solid var(--border);border-radius:var(--radius);overflow:hidden;background:#05070d}#threeCanvas{width:100%;height:100%;display:block;background:#05070d}.loading-overlay{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;flex-direction:column;background:rgba(5,7,13,.93);z-index:10}.loading-overlay.hidden{display:none}.spinner{width:34px;height:34px;border:3px solid var(--border);border-top-color:var(--cyan);border-radius:50%;animation:spin .8s linear infinite}@keyframes spin{to{transform:rotate(360deg)}}.loading-overlay p{font-size:10px;color:var(--muted)}
.stage-hud{position:absolute;left:10px;right:10px;top:10px;z-index:4;display:flex;justify-content:space-between;pointer-events:none;gap:10px}.stats-grid{display:flex;gap:5px;flex-wrap:wrap}.stat-box{min-width:58px;padding:6px 8px;border:1px solid rgba(255,255,255,.12);border-radius:9px;background:rgba(7,9,14,.72);backdrop-filter:blur(8px);text-align:center}.stat-box .val{font-family:'Anybody';font-weight:900;font-size:15px;color:var(--cyan)}.stat-box .lbl{display:none;font-size:7px;color:var(--muted);letter-spacing:.7px}.model-readout{align-self:flex-start;padding:7px 9px;border:1px solid rgba(255,255,255,.12);border-radius:10px;background:rgba(7,9,14,.72);font-size:9px;color:var(--muted)}.model-readout b{color:var(--text)}
.viz-bar{position:absolute;z-index:4;left:10px;right:10px;bottom:10px;display:flex;gap:5px;align-items:center;padding:7px;border:1px solid rgba(255,255,255,.12);border-radius:11px;background:rgba(7,9,14,.76);backdrop-filter:blur(10px);overflow:auto}.viz-bar button{padding:7px 9px;font-size:9px;white-space:nowrap}
@media(max-width:1100px){:root{--rail:240px}.topbar{grid-template-columns:210px minmax(190px,.8fr) minmax(440px,1.5fr)}.brand h1{font-size:20px}.source-btn{min-width:46px}.source-btn .txt{display:none}.stat-box:nth-child(n+5){display:none}}
@media(max-width:780px){body{overflow:auto}.app-shell{height:auto;min-height:100vh;grid-template-rows:auto auto}.topbar{grid-template-columns:130px 1fr;grid-template-rows:112px auto}.top-camera{grid-row:1}.brand{grid-row:1}.header-controls{grid-column:1/-1;grid-row:2}.workspace{grid-template-columns:1fr;min-height:1100px}.palette{max-height:none;overflow:visible}.stage{height:68vh;min-height:520px}.big-tools{grid-template-columns:repeat(6,1fr)}.emoji-tool{min-height:52px}.emoji-tool .e{font-size:20px}.app-shell{overflow:visible}.topbar{position:sticky;top:0;z-index:20}.frame-btn{font-size:9px;padding:7px 5px}}
@media(max-width:920px){.app-shell{grid-template-rows:106px minmax(0,1fr)}.topbar{grid-template-columns:150px 1fr 1.5fr}.brand h1{font-size:17px}.top-select{display:none}.workspace{grid-template-columns:190px minmax(0,1fr)}.status-row{display:none}}
@media(max-width:680px){body{overflow:auto}.app-shell{height:auto;min-height:100vh;grid-template-rows:auto auto}.topbar{grid-template-columns:42vw 1fr;grid-template-areas:"cam brand" "controls controls"}.top-camera{grid-area:cam;min-height:100px}.brand{grid-area:brand}.header-controls{grid-area:controls}.workspace{grid-template-columns:1fr;grid-template-rows:auto 72vh}.palette{overflow:visible;display:grid;grid-template-columns:1fr 1fr}.stage{min-height:72vh}}
</style>
</head>
<body>
<div class="app-shell">
<header class="topbar">
<div class="top-camera">
<div class="preview-wrap" id="previewWrap">
<video id="videoEl" autoplay playsinline muted></video>
<img id="imageEl" style="display:none;" alt=""/>
<canvas id="overlayCanvas"></canvas>
<div class="frame-guide dynamic" id="frameGuide"></div>
<div class="tag l" id="previewLabel">camera</div>
<div class="tag r" id="previewFps">— fps</div>
<div class="audio-bars" id="audioBars" style="display:none;"></div>
</div>
</div>
<div class="brand">
<div class="eyebrow">capture</div>
<h1>LIVE 3D CAPTURE</h1>
<div class="sub">capture</div>
<div class="status-row">
<span class="pill" id="pillStatus"><span class="dot"></span>idle</span>
<span class="pill" id="pillModel" style="display:none"><span class="dot"></span>models</span>
<span class="pill" id="pillSource"><span class="dot"></span>source</span>
<span class="pill" id="pillRec" style="display:none"><span class="dot"></span>take</span>
</div>
</div>
<div class="header-controls">
<div class="header-line">
<div class="source-grid">
<div class="source-btn active" data-source="camera"><span class="icon">📷</span><span class="txt">Camera</span></div>
<div class="source-btn" data-source="video"><span class="icon">🎬</span><span class="txt">Video</span></div>
<div class="source-btn" data-source="image"><span class="icon">🖼️</span><span class="txt">Still</span></div>
<div class="source-btn" data-source="screen"><span class="icon">🖥️</span><span class="txt">Screen</span></div>
</div>
<select id="cameraSelect" class="top-select"><option value="">Looking for cameras…</option></select>
<button id="btnFlip" class="flip-btn" title="Flip camera">🔄</button>
</div>
<div class="header-line">
<div class="frame-modes" id="frameModes">
<button class="frame-btn" data-frame="full">🧍 Full</button>
<button class="frame-btn" data-frame="portrait">🪑 Seat</button>
<button class="frame-btn active" data-frame="dynamic">✨ Auto</button>
</div>
<button id="btnStartStop" class="primary top-action">▶ Track</button>
</div>
</div>
</header>
<main class="workspace">
<aside class="palette">
<section class="panel">
<div class="panel-title">🧍 Body</div>
<div class="slider-block">
<div class="slider-label"><strong>Height</strong><span id="heightVal">5′11″</span></div>
<input type="range" id="heightIn" min="56" max="80" step="1" value="71"/>
<div class="ticks"><span>4′8″</span><span>practical adult range</span><span>6′8″</span></div>
</div>
<div class="slider-block">
<div class="slider-label"><strong>Weight</strong><span id="weightVal">150 lb</span></div>
<input type="range" id="weightLb" min="90" max="320" step="1" value="150"/>
<div class="ticks"><span>90</span><span>mass / girth</span><span>320 lb</span></div>
</div>
<div class="slider-block">
<div class="slider-label"><strong>Body type</strong><span id="bodyTypeVal">Average</span></div>
<input type="range" id="bodyType" min="0" max="100" step="1" value="33"/>
<div class="ticks"><span>skinny</span><span>average</span><span>muscular</span><span>heavy</span></div>
</div>
<div class="profile-chip" id="profileSummary"><b>5′11″ · 150 lb · Average</b><br/>Tracked skeleton + anatomical surface shaping.</div>
</section>
<section class="panel">
<div class="panel-title">🎯 Detail</div>
<div class="big-tools">
<button class="emoji-tool on" id="toolPose" title="Body"><span class="e">🧍</span><small id="poseCountLabel">0</small></button>
<button class="emoji-tool on" id="toolFace" title="Face"><span class="e">🙂</span><small id="faceCountLabel">0</small></button>
<button class="emoji-tool on" id="toolHand" title="Hands"><span class="e">🖐️</span><small id="handCountLabel">0</small></button>
</div>
<div style="display:none">
<div class="toggle-row"><label>Body</label><span class="count"></span><span class="switch"><input type="checkbox" id="togglePose" checked/></span></div>
<div class="toggle-row"><label>Face</label><span class="count"></span><span class="switch"><input type="checkbox" id="toggleFace" checked/></span></div>
<div class="toggle-row"><label>Hands</label><span class="count"></span><span class="switch"><input type="checkbox" id="toggleHand" checked/></span></div>
</div>
<div class="slider-block"><div class="slider-label"><strong>Depth</strong><span id="depthVal">1.00×</span></div><input type="range" id="depthScale" min="0" max="4" step="0.05" value="1"/></div>
<div class="slider-block"><div class="slider-label"><strong>Smooth</strong><span id="smoothVal">0.35</span></div><input type="range" id="smoothing" min="0.05" max="1" step="0.05" value="0.35"/></div>
</section>
<section class="panel">
<div class="panel-title">🎨 Skin</div>
<div class="compact-row">
<select id="colormapMode"><option value="raw">As shot</option><option value="pop">Punchy</option><option value="noir">B&W</option><option value="neon">Neon</option><option value="warm">Warm skin</option></select>
<select id="texRes"><option value="512">512²</option><option value="1024" selected>1024²</option><option value="2048">2048²</option></select>
</div>
<div class="compact-row" style="margin-top:6px"><button id="btnFreezeTex">❄️ Freeze</button><button id="btnGrabTex">📸 Grab</button></div>
<canvas id="snapCanvas"></canvas><div class="mini" id="texInfo" style="display:none">Live</div>
</section>
<section class="panel">
<div class="panel-title">📦 Save</div>
<div class="compact-row"><button id="btnRecTake" class="gold">⏺ Take</button><button id="btnClearTake">🧹 Clear</button></div>
<div class="compact-row" style="margin-top:6px"><button id="btnExportGLB" class="primary">🧊 GLB</button><button id="btnExportPose">🧍 T-pose</button></div>
<div class="compact-row" style="margin-top:6px"><button id="btnExportParts">🧩 Parts</button><button id="btnExportPNG">🖼 PNG</button></div>
<div class="status-row"><span class="pill" id="pillExport"><span class="dot"></span>no export yet</span></div>
</section>
<section class="panel">
<div class="panel-title">🎥 Record</div>
<div class="compact-row"><button id="btnRecInner">🎬 3D view</button><button id="btnRecScreen">🖥 Screen</button></div>
<div class="status-row"><span class="pill" id="pillInner"><span class="dot"></span>3D</span><span class="pill" id="pillScreen"><span class="dot"></span>screen</span><span class="pill" id="pillMime"><span class="dot"></span>codec</span></div>
</section>
<details class="panel">
<summary>🧩 Body parts</summary><div class="detail-body"><div class="compact-row" style="margin-bottom:6px"><button id="btnPartsAll">All</button><button id="btnPartsNone">None</button><button id="btnPartsIsolate">Face</button></div><div class="parts-list" id="partsList"></div></div>
</details>
<details class="panel">
<summary>💾 Saved files</summary><div class="detail-body"><div class="compact-row" style="margin-bottom:6px"><button id="btnGalRefresh">Refresh</button><button id="btnGalClear" class="danger">Delete</button></div><div class="gallery" id="galleryList"><div class="gempty">Nothing saved yet.</div></div></div>
</details>
<details class="panel">
<summary>📡 Activity + telemetry</summary><div class="detail-body"><div class="log" id="logEl">Ready.\n</div><div class="sep"></div><div id="telemetry"></div></div>
</details>
<input type="file" accept="video/*" class="hidden-input" id="videoFileInput"/>
<input type="file" accept="image/*" class="hidden-input" id="imageFileInput"/>
</aside>
<section class="stage">
<div class="canvas-wrap">
<canvas id="threeCanvas"></canvas>
<div class="loading-overlay" id="threeLoading"><div class="spinner"></div></div>
<div class="stage-hud">
<div class="stats-grid">
<div class="stat-box"><div class="val" id="statFps">—</div><div class="lbl">FPS</div></div>
<div class="stat-box"><div class="val" id="statInfer">—</div><div class="lbl">INFER MS</div></div>
<div class="stat-box"><div class="val" id="statVerts">0</div><div class="lbl">VERTS</div></div>
<div class="stat-box"><div class="val" id="statTris">0</div><div class="lbl">TRIS</div></div>
<div class="stat-box"><div class="val" id="statParts">0</div><div class="lbl">PARTS</div></div>
<div class="stat-box"><div class="val" id="statTake">0.0s</div><div class="lbl">TAKE</div></div>
</div>
<div class="model-readout" id="modelReadout"><b>5′11″ · 150 lb</b><br/>Average · dynamic framing</div>
</div>
<div class="viz-bar" id="vizBar">
<button class="active" data-mode="skin">Skin</button><button data-mode="wire">Wire</button><button data-mode="xray">X-ray</button><button data-mode="points">Points</button><button data-mode="neon">Neon</button><span style="flex:1"></span><button id="btnResetView">🎯 Frame</button><button id="btnGrid" class="active"># Grid</button>
</div>
</div>
</section>
</main>
</div>
<script src="https://cdn.jsdelivr.net/npm/three@0.128.0/build/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/controls/OrbitControls.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/exporters/GLTFExporter.js"></script>
<script type="module">
// ═══════════════════════════════════════════════════════════════
// LIVE 3D CAPTURE — calibrated body × MediaPipe × video texture → GLB
// Aaron (inventor) · built with Claude
// ═══════════════════════════════════════════════════════════════
const VISION_CDN = "https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.18";
const WASM_PATH = `${VISION_CDN}/wasm`;
const MODEL_BASE = "https://storage.googleapis.com/mediapipe-models";
let PoseLandmarker, FaceLandmarker, HandLandmarker, FilesetResolver;
// ── Projection constants. Shared by BOTH directions:
// landmark(0..1) → 3D world, and 3D world → texture UV.
// This is what makes the video paint land exactly where the body is.
const MAP = { sx: 4.0, sy: 3.0, sz: 2.0 };
const S = {
source: 'camera',
running: false,
facingMode: 'user',
vizMode: 'skin',
depthScale: 1.0,
smoothing: 0.35,
colormap: 'raw',
texFrozen: false,
poseLandmarker: null, faceLandmarker: null, handLandmarker: null,
runningMode: 'VIDEO',
poseResults: null, faceResults: null, handResults: null,
stream: null, audioCtx: null, analyser: null,
inferMs: 0, frameCount: 0, fps: 0, lastFpsTime: performance.now(),
hasPose: false, hasFace: false, handSlots: [null, null],
heightIn: 71, weightLb: 150, bodyType: 0.33, frameMode: 'dynamic', autoFrameTick: 0,
};
// ── DOM ──
const $ = (id) => document.getElementById(id);
const videoEl = $('videoEl'), imageEl = $('imageEl');
const overlayCanvas = $('overlayCanvas'), overlayCtx = overlayCanvas.getContext('2d');
const previewLabel = $('previewLabel'), previewFps = $('previewFps');
const cameraSelect = $('cameraSelect'), logEl = $('logEl'), audioBars = $('audioBars');
const pillStatus = $('pillStatus'), pillModel = $('pillModel'), pillSource = $('pillSource');
const pillRec = $('pillRec'), pillExport = $('pillExport');
function log(msg, cls = 'info') {
const t = new Date().toLocaleTimeString();
logEl.innerHTML += `<span class="${cls}">[${t}]</span> ${msg}\n`;
logEl.scrollTop = logEl.scrollHeight;
}
function setPill(el, text, cls = '') {
el.className = `pill ${cls}`;
el.innerHTML = `<span class="dot"></span>${text}`;
}
// ═══════════════════════════════════════════════════════════════
// MEDIA SOURCES
// ═══════════════════════════════════════════════════════════════
async function enumerateCameras() {
try {
const tmp = await navigator.mediaDevices.getUserMedia({ video: true, audio: false });
tmp.getTracks().forEach(t => t.stop());
const devices = await navigator.mediaDevices.enumerateDevices();
const cams = devices.filter(d => d.kind === 'videoinput');
cameraSelect.innerHTML = '';
cams.forEach((c, i) => {
const o = document.createElement('option');
o.value = c.deviceId; o.textContent = c.label || `Camera ${i + 1}`;
cameraSelect.appendChild(o);
});
log(`${cams.length} camera(s) available`, 'ok');
} catch (e) {
log(`Camera list unavailable: ${e.message}`, 'err');
cameraSelect.innerHTML = '<option value="">No camera access</option>';
}
}
function stopCurrentStream() {
if (S.stream) { S.stream.getTracks().forEach(t => t.stop()); S.stream = null; }
videoEl.srcObject = null;
videoEl.removeAttribute('src');
videoEl.style.display = 'block';
imageEl.style.display = 'none';
if (S.audioCtx) { S.audioCtx.close().catch(() => {}); S.audioCtx = null; S.analyser = null; }
audioBars.style.display = 'none';
}
async function startCamera(deviceId) {
stopCurrentStream();
const c = {
video: {
width: { ideal: 1280 }, height: { ideal: 720 },
...(deviceId ? { deviceId: { exact: deviceId } } : { facingMode: S.facingMode })
},
audio: true
};
try {
S.stream = await navigator.mediaDevices.getUserMedia(c);
videoEl.srcObject = S.stream; videoEl.muted = true;
await videoEl.play();
setupAudio(S.stream);
previewLabel.textContent = 'camera';
setPill(pillSource, 'camera', 'on');
log('Camera live', 'ok');
} catch (e) {
try {
c.audio = false;
S.stream = await navigator.mediaDevices.getUserMedia(c);
videoEl.srcObject = S.stream; videoEl.muted = true;
await videoEl.play();
previewLabel.textContent = 'camera';
setPill(pillSource, 'camera, no mic', 'warn');
log('Camera live without audio', 'warn');
} catch (e2) {
log(`Camera did not start: ${e2.message}`, 'err');
setPill(pillSource, 'no camera', 'err');
}
}
}
function startVideoFile() {
stopCurrentStream();
return new Promise(resolve => {
const input = $('videoFileInput');
input.onchange = () => {
const file = input.files[0]; if (!file) return resolve();
videoEl.src = URL.createObjectURL(file);
videoEl.loop = true; videoEl.muted = false;
videoEl.play().catch(() => {});
previewLabel.textContent = file.name.slice(0, 22);
setPill(pillSource, 'video file', 'on');
log(`Loaded ${file.name}`, 'ok');
resolve();
};
input.click();
});
}
function startImageFile() {
stopCurrentStream();
return new Promise(resolve => {
const input = $('imageFileInput');
input.onchange = () => {
const file = input.files[0]; if (!file) return resolve();
imageEl.src = URL.createObjectURL(file);
imageEl.style.display = 'block';
videoEl.style.display = 'none';
imageEl.onload = () => {
previewLabel.textContent = file.name.slice(0, 22);
setPill(pillSource, 'still image', 'on');
log(`Loaded ${file.name}`, 'ok');
if (S.running) processImageFrame();
resolve();
};
};
input.click();
});
}
async function startScreenCapture() {
stopCurrentStream();
try {
S.stream = await navigator.mediaDevices.getDisplayMedia({ video: true, audio: true });
videoEl.srcObject = S.stream; videoEl.muted = true;
await videoEl.play();
if (S.stream.getAudioTracks().length) setupAudio(S.stream);
previewLabel.textContent = 'screen';
setPill(pillSource, 'screen', 'on');
log('Screen capture live', 'ok');
S.stream.getVideoTracks()[0].onended = () => {
setPill(pillSource, 'screen ended', 'warn');
log('Screen share ended', 'warn');
};
} catch (e) {
log(`Screen capture did not start: ${e.message}`, 'err');
setPill(pillSource, 'no screen', 'err');
}
}
function setupAudio(stream) {
if (!stream.getAudioTracks().length) return;
try {
S.audioCtx = new (window.AudioContext || window.webkitAudioContext)();
const src = S.audioCtx.createMediaStreamSource(stream);
S.analyser = S.audioCtx.createAnalyser();
S.analyser.fftSize = 64;
src.connect(S.analyser);
audioBars.innerHTML = '';
for (let i = 0; i < 24; i++) {
const b = document.createElement('div');
b.className = 'bar'; b.style.height = '2px';
audioBars.appendChild(b);
}
audioBars.style.display = 'flex';
} catch (e) { log(`Audio meter off: ${e.message}`, 'warn'); }
}
function updateAudioBars() {
if (!S.analyser) return;
const d = new Uint8Array(S.analyser.frequencyBinCount);
S.analyser.getByteFrequencyData(d);
const bars = audioBars.children;
for (let i = 0; i < bars.length; i++) {
const v = d[i] || 0;
bars[i].style.height = Math.max(2, (v / 255) * 30) + 'px';
bars[i].style.background = `hsl(${180 + (v / 255) * 130},90%,60%)`;
}
}
// ═══════════════════════════════════════════════════════════════
// COLORMAP CAPTURE — video frame → texture atlas
// ═══════════════════════════════════════════════════════════════
const texCanvas = document.createElement('canvas');
texCanvas.width = texCanvas.height = 1024;
const texCtx = texCanvas.getContext('2d', { willReadFrequently: false });
texCtx.fillStyle = '#8a7f76';
texCtx.fillRect(0, 0, texCanvas.width, texCanvas.height);
const snapCanvas = $('snapCanvas');
const snapCtx = snapCanvas.getContext('2d');
snapCanvas.width = 240; snapCanvas.height = 180;
const FILTERS = {
raw: 'none',
pop: 'saturate(1.45) contrast(1.14)',
noir: 'grayscale(1) contrast(1.28) brightness(1.05)',
neon: 'saturate(2.1) hue-rotate(165deg) contrast(1.2)',
warm: 'saturate(1.2) sepia(0.18) contrast(1.06) brightness(1.04)'
};
let texWidth = 0, texHeight = 0; // source pixel size actually drawn
function currentSourceEl() {
return (S.source === 'image') ? imageEl : videoEl;
}
function sourceSize() {
const el = currentSourceEl();
if (el === imageEl) return [el.naturalWidth, el.naturalHeight];
return [el.videoWidth, el.videoHeight];
}
// The atlas is drawn so the FULL frame occupies the FULL canvas.
// That means normalized landmark (x,y) maps straight to UV (x,y) with flipY off.
function grabTexture(force = false) {
if (S.texFrozen && !force) return false;
const el = currentSourceEl();
const [sw, sh] = sourceSize();
if (!sw || !sh) return false;
texWidth = sw; texHeight = sh;
texCtx.save();
texCtx.filter = FILTERS[S.colormap] || 'none';
texCtx.drawImage(el, 0, 0, sw, sh, 0, 0, texCanvas.width, texCanvas.height);
texCtx.restore();
if (videoTexture) videoTexture.needsUpdate = true;
return true;
}
function paintSnapPreview() {
snapCtx.drawImage(texCanvas, 0, 0, snapCanvas.width, snapCanvas.height);
const el = $('texInfo');
if (el) el.textContent = `${S.texFrozen ? 'Frozen' : 'Live'} · ${texCanvas.width}² atlas from ${texWidth || '—'}×${texHeight || '—'} source`;
}
function setTexRes(px) {
texCanvas.width = texCanvas.height = px;
texCtx.fillStyle = '#8a7f76';
texCtx.fillRect(0, 0, px, px);
if (videoTexture) { videoTexture.needsUpdate = true; }
grabTexture(true);
log(`Texture atlas set to ${px}×${px}`, 'ok');
}
// ═══════════════════════════════════════════════════════════════
// MEDIAPIPE
// ═══════════════════════════════════════════════════════════════
async function loadModels() {
setPill(pillModel, 'loading', 'warn');
log('Fetching MediaPipe Tasks Vision…');
const vision = await import(`${VISION_CDN}/vision_bundle.mjs`);
PoseLandmarker = vision.PoseLandmarker;
FaceLandmarker = vision.FaceLandmarker;
HandLandmarker = vision.HandLandmarker;
FilesetResolver = vision.FilesetResolver;
const fs = await FilesetResolver.forVisionTasks(WASM_PATH);
log('WASM runtime ready', 'ok');
if ($('togglePose').checked && !S.poseLandmarker) {
S.poseLandmarker = await PoseLandmarker.createFromOptions(fs, {
baseOptions: {
modelAssetPath: `${MODEL_BASE}/pose_landmarker/pose_landmarker_full/float16/1/pose_landmarker_full.task`,
delegate: 'GPU'
},
runningMode: 'VIDEO', numPoses: 1,
minPoseDetectionConfidence: 0.5, minTrackingConfidence: 0.5
});
log('Body model ready', 'ok');
}
if ($('toggleFace').checked && !S.faceLandmarker) {
S.faceLandmarker = await FaceLandmarker.createFromOptions(fs, {
baseOptions: {
modelAssetPath: `${MODEL_BASE}/face_landmarker/face_landmarker/float16/1/face_landmarker.task`,
delegate: 'GPU'
},
runningMode: 'VIDEO', numFaces: 1, outputFaceBlendshapes: true
});
buildFaceTopology();
log('Face model ready', 'ok');
}
if ($('toggleHand').checked && !S.handLandmarker) {
S.handLandmarker = await HandLandmarker.createFromOptions(fs, {
baseOptions: {
modelAssetPath: `${MODEL_BASE}/hand_landmarker/hand_landmarker/float16/1/hand_landmarker.task`,
delegate: 'GPU'
},
runningMode: 'VIDEO', numHands: 2
});
log('Hand model ready', 'ok');
}
S.runningMode = 'VIDEO';
setPill(pillModel, 'loaded', 'on');
}
async function setRunningMode(mode) {
if (S.runningMode === mode) return;
const opts = { runningMode: mode };
if (S.poseLandmarker) await S.poseLandmarker.setOptions(opts);
if (S.faceLandmarker) await S.faceLandmarker.setOptions(opts);
if (S.handLandmarker) await S.handLandmarker.setOptions(opts);
S.runningMode = mode;
}
// ── Connection tables ──
const POSE_CONNECTIONS = [
[11,12],[11,13],[13,15],[12,14],[14,16],[11,23],[12,24],[23,24],
[23,25],[25,27],[24,26],[26,28],[27,29],[29,31],[27,31],[28,30],[30,32],[28,32],
[15,17],[15,19],[15,21],[16,18],[16,20],[16,22],[17,19],[18,20],
[0,1],[1,2],[2,3],[3,7],[0,4],[4,5],[5,6],[6,8],[9,10]
];
const HAND_CONNECTIONS = [
[0,1],[1,2],[2,3],[3,4],[0,5],[5,6],[6,7],[7,8],[0,9],[9,10],[10,11],[11,12],
[0,13],[13,14],[14,15],[15,16],[0,17],[17,18],[18,19],[19,20],[5,9],[9,13],[13,17]
];
// ═══════════════════════════════════════════════════════════════
// DETECTION LOOP
// ═══════════════════════════════════════════════════════════════
let rafId = null;
function runDetectors(el, ts) {
const t0 = performance.now();
const video = (S.runningMode === 'VIDEO');
try {
if (S.poseLandmarker) S.poseResults = video ? S.poseLandmarker.detectForVideo(el, ts) : S.poseLandmarker.detect(el);
} catch (e) { S.poseResults = null; }
try {
if (S.faceLandmarker) S.faceResults = video ? S.faceLandmarker.detectForVideo(el, ts) : S.faceLandmarker.detect(el);
} catch (e) { S.faceResults = null; }
try {
if (S.handLandmarker) S.handResults = video ? S.handLandmarker.detectForVideo(el, ts) : S.handLandmarker.detect(el);
} catch (e) { S.handResults = null; }
S.inferMs = performance.now() - t0;
}
function processVideoFrame() {
if (!S.running) return;
const now = performance.now();
if (videoEl.readyState >= 2 && videoEl.videoWidth > 0) {
if (overlayCanvas.width !== videoEl.videoWidth || overlayCanvas.height !== videoEl.videoHeight) {
overlayCanvas.width = videoEl.videoWidth;
overlayCanvas.height = videoEl.videoHeight;
// keep the frame and its overlay on exactly the same box
videoEl.parentElement.style.aspectRatio = `${videoEl.videoWidth} / ${videoEl.videoHeight}`;
}
overlayCtx.clearRect(0, 0, overlayCanvas.width, overlayCanvas.height);
runDetectors(videoEl, Math.round(now));
grabTexture();
drawOverlay();
rebuildModel();
sampleTake(now);
updateStats();
}
updateAudioBars();
S.frameCount++;
if (now - S.lastFpsTime >= 1000) {
S.fps = S.frameCount; S.frameCount = 0; S.lastFpsTime = now;
previewFps.textContent = `${S.fps} fps`;
TELE.frames += S.fps;
}
rafId = requestAnimationFrame(processVideoFrame);
}
async function processImageFrame() {
if (!imageEl.complete || !imageEl.naturalWidth) return;
await setRunningMode('IMAGE');
overlayCanvas.width = imageEl.naturalWidth;
overlayCanvas.height = imageEl.naturalHeight;
imageEl.parentElement.style.aspectRatio = `${imageEl.naturalWidth} / ${imageEl.naturalHeight}`;
overlayCtx.clearRect(0, 0, overlayCanvas.width, overlayCanvas.height);
runDetectors(imageEl, 0);
grabTexture(true);
drawOverlay();
rebuildModel();
updateStats();
log('Still image solved — model is frozen at this pose', 'ok');
}
// ═══════════════════════════════════════════════════════════════
// 2D OVERLAY
// ═══════════════════════════════════════════════════════════════
function drawOverlay() {
const ctx = overlayCtx, w = overlayCanvas.width, h = overlayCanvas.height;
const pl = S.poseResults?.landmarks?.[0];
if (pl) {
ctx.strokeStyle = 'rgba(0,228,255,.55)'; ctx.lineWidth = Math.max(1, w / 400);
for (const [a, b] of POSE_CONNECTIONS) {
if (a < pl.length && b < pl.length) {
ctx.beginPath();
ctx.moveTo(pl[a].x * w, pl[a].y * h);
ctx.lineTo(pl[b].x * w, pl[b].y * h);
ctx.stroke();
}
}
ctx.fillStyle = '#00e4ff';
for (const lm of pl) { ctx.beginPath(); ctx.arc(lm.x * w, lm.y * h, Math.max(1.5, w / 320), 0, 6.283); ctx.fill(); }
}
const fl = S.faceResults?.faceLandmarks?.[0];
if (fl) {
ctx.fillStyle = 'rgba(255,45,138,.45)';
for (const lm of fl) { ctx.fillRect(lm.x * w, lm.y * h, 1.5, 1.5); }
}
const hs = S.handResults?.landmarks;
if (hs) {
const cols = ['#ffc842', '#00e88c'];
hs.forEach((lm, i) => {
const c = cols[i % 2];
ctx.strokeStyle = c + 'aa'; ctx.lineWidth = Math.max(1, w / 500);
for (const [a, b] of HAND_CONNECTIONS) {
ctx.beginPath();
ctx.moveTo(lm[a].x * w, lm[a].y * h);
ctx.lineTo(lm[b].x * w, lm[b].y * h);
ctx.stroke();
}
ctx.fillStyle = c;
for (const p of lm) { ctx.beginPath(); ctx.arc(p.x * w, p.y * h, Math.max(1.5, w / 400), 0, 6.283); ctx.fill(); }
});
}
}
// ═══════════════════════════════════════════════════════════════
// THREE.JS SCENE
// ═══════════════════════════════════════════════════════════════
const canvas3 = $('threeCanvas');
const renderer = new THREE.WebGLRenderer({ canvas: canvas3, antialias: true, preserveDrawingBuffer: true });
renderer.setPixelRatio(Math.min(2, window.devicePixelRatio));
renderer.setClearColor(0x05070d, 1);
renderer.outputEncoding = THREE.sRGBEncoding;
const scene = new THREE.Scene();
scene.fog = new THREE.FogExp2(0x05070d, 0.055);
const camera3 = new THREE.PerspectiveCamera(48, 1, 0.05, 200);
const CAM_HOME = new THREE.Vector3(0, 0.15, 4.6);
camera3.position.copy(CAM_HOME);
const controls = new THREE.OrbitControls(camera3, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.08;
controls.target.set(0, 0, 0);
const clock = new THREE.Clock();
scene.add(new THREE.AmbientLight(0x8fa4c8, 0.85));
const key = new THREE.DirectionalLight(0xffffff, 0.85); key.position.set(2, 3, 4); scene.add(key);
const rim1 = new THREE.PointLight(0x00e4ff, 1.1, 16); rim1.position.set(-3, 1.5, -2); scene.add(rim1);
const rim2 = new THREE.PointLight(0xff2d8a, 0.9, 16); rim2.position.set(3, -1, -2); scene.add(rim2);
const grid = new THREE.GridHelper(14, 28, 0x1e2436, 0x141926);
grid.position.y = -1.7;
scene.add(grid);
// Background dust
const bgGeo = new THREE.BufferGeometry();
const bgN = 1200, bgPos = new Float32Array(bgN * 3);
for (let i = 0; i < bgN; i++) {
bgPos[i * 3] = (Math.random() - .5) * 30;
bgPos[i * 3 + 1] = (Math.random() - .5) * 30;
bgPos[i * 3 + 2] = (Math.random() - .5) * 30;
}
bgGeo.setAttribute('position', new THREE.BufferAttribute(bgPos, 3));
const bgPts = new THREE.Points(bgGeo, new THREE.PointsMaterial({
size: 0.02, color: 0x2a3550, transparent: true, opacity: 0.5,
blending: THREE.AdditiveBlending, depthWrite: false
}));
scene.add(bgPts);
// ── Video-fed texture ──
const videoTexture = new THREE.CanvasTexture(texCanvas);
videoTexture.flipY = false; // glTF-safe; UV v = landmark y directly
videoTexture.encoding = THREE.sRGBEncoding;
videoTexture.minFilter = THREE.LinearFilter;
videoTexture.magFilter = THREE.LinearFilter;
videoTexture.generateMipmaps = false;
videoTexture.name = 'soma_colormap';
function makeSkinMaterial() {
return new THREE.MeshStandardMaterial({
map: videoTexture, roughness: 0.72, metalness: 0.02,
emissive: 0x15110f, emissiveIntensity: 0.18,
side: THREE.DoubleSide, transparent: false
});
}
const skinMat = makeSkinMaterial();
skinMat.name = 'soma_skin';
// ═══════════════════════════════════════════════════════════════
// PROJECTION — the two directions of the same mapping
// ═══════════════════════════════════════════════════════════════
function lmToWorld(lm, out) {
return out.set(
-(lm.x - 0.5) * MAP.sx,
-(lm.y - 0.5) * MAP.sy,
-(lm.z || 0) * MAP.sz * S.depthScale
);
}
// Inverse of the x/y half — a vertex anywhere in space knows which pixel it sits on.
function worldToUV(x, y, out) {
out[0] = 0.5 - x / MAP.sx;
out[1] = 0.5 - y / MAP.sy;
}
// ═══════════════════════════════════════════════════════════════
// RIG DEFINITION
// ═══════════════════════════════════════════════════════════════
const _mid = (a, b) => new THREE.Vector3().addVectors(a, b).multiplyScalar(0.5);
const RIG = [
{ name: 'Hips', parent: null, head: P => _mid(P[23], P[24]), tail: P => _mid(P[11], P[12]),
part: { id: 'Torso', kind: 'box', r: 0.30 } },
{ name: 'Chest', parent: 'Hips', head: P => _mid(P[11], P[12]), tail: P => P[0].clone(),
part: { id: 'Neck', kind: 'tube', r: 0.085 } },
{ name: 'Head', parent: 'Chest', head: P => P[0].clone(),
tail: P => P[0].clone().add(P[0].clone().sub(_mid(P[11], P[12])).setLength(0.4)),
part: { id: 'Skull', kind: 'ball', r: 0.20 } },
{ name: 'Shoulder_L', parent: 'Chest', head: P => P[11].clone(), tail: P => P[13].clone(),
part: { id: 'UpperArm_L', kind: 'tube', r: 0.078 } },
{ name: 'Elbow_L', parent: 'Shoulder_L', head: P => P[13].clone(), tail: P => P[15].clone(),
part: { id: 'Forearm_L', kind: 'tube', r: 0.062 } },
{ name: 'Wrist_L', parent: 'Elbow_L', head: P => P[15].clone(), tail: P => P[19].clone(),
part: { id: 'Palm_L', kind: 'tube', r: 0.050 } },
{ name: 'Shoulder_R', parent: 'Chest', head: P => P[12].clone(), tail: P => P[14].clone(),
part: { id: 'UpperArm_R', kind: 'tube', r: 0.078 } },
{ name: 'Elbow_R', parent: 'Shoulder_R', head: P => P[14].clone(), tail: P => P[16].clone(),
part: { id: 'Forearm_R', kind: 'tube', r: 0.062 } },
{ name: 'Wrist_R', parent: 'Elbow_R', head: P => P[16].clone(), tail: P => P[20].clone(),
part: { id: 'Palm_R', kind: 'tube', r: 0.050 } },
{ name: 'Hip_L', parent: 'Hips', head: P => P[23].clone(), tail: P => P[25].clone(),
part: { id: 'Thigh_L', kind: 'tube', r: 0.105 } },
{ name: 'Knee_L', parent: 'Hip_L', head: P => P[25].clone(), tail: P => P[27].clone(),
part: { id: 'Shin_L', kind: 'tube', r: 0.078 } },
{ name: 'Ankle_L', parent: 'Knee_L', head: P => P[27].clone(), tail: P => P[31].clone(),
part: { id: 'Foot_L', kind: 'tube', r: 0.055 } },
{ name: 'Hip_R', parent: 'Hips', head: P => P[24].clone(), tail: P => P[26].clone(),
part: { id: 'Thigh_R', kind: 'tube', r: 0.105 } },
{ name: 'Knee_R', parent: 'Hip_R', head: P => P[26].clone(), tail: P => P[28].clone(),
part: { id: 'Shin_R', kind: 'tube', r: 0.078 } },
{ name: 'Ankle_R', parent: 'Knee_R', head: P => P[28].clone(), tail: P => P[32].clone(),
part: { id: 'Foot_R', kind: 'tube', r: 0.055 } }
];
function anatomyTube(spec) {
const radial = 24, rings = 10;
const profiles = {
Neck: [0.92,0.96,1.00,1.00,0.96,0.92,0.90,0.88,0.86,0.84],
UpperArm_L: [1.00,1.08,1.15,1.18,1.13,1.04,0.94,0.84,0.76,0.70],
UpperArm_R: [1.00,1.08,1.15,1.18,1.13,1.04,0.94,0.84,0.76,0.70],
Forearm_L: [0.74,0.82,0.94,1.06,1.10,1.02,0.90,0.78,0.68,0.60],
Forearm_R: [0.74,0.82,0.94,1.06,1.10,1.02,0.90,0.78,0.68,0.60],
Palm_L: [0.82,0.94,1.03,1.08,1.06,1.00,0.93,0.85,0.78,0.72],
Palm_R: [0.82,0.94,1.03,1.08,1.06,1.00,0.93,0.85,0.78,0.72],
Thigh_L: [1.02,1.10,1.16,1.18,1.14,1.07,0.98,0.88,0.78,0.70],
Thigh_R: [1.02,1.10,1.16,1.18,1.14,1.07,0.98,0.88,0.78,0.70],
Shin_L: [0.72,0.78,0.88,1.02,1.10,1.08,0.98,0.84,0.70,0.58],
Shin_R: [0.72,0.78,0.88,1.02,1.10,1.08,0.98,0.84,0.70,0.58],
Foot_L: [0.72,0.82,0.96,1.08,1.10,1.04,0.92,0.78,0.64,0.48],
Foot_R: [0.72,0.82,0.96,1.08,1.10,1.04,0.92,0.78,0.64,0.48]
};
const prof = profiles[spec.id] || Array(rings).fill(1);
const pos = [], idx = [];
for (let y = 0; y < rings; y++) {
const fy = y / (rings - 1), rr = spec.r * prof[y];
for (let j = 0; j < radial; j++) {
const a = j / radial * Math.PI * 2;
pos.push(Math.cos(a) * rr, fy, Math.sin(a) * rr);
}
}
for (let y = 0; y < rings - 1; y++) for (let j = 0; j < radial; j++) {
const n = (j + 1) % radial, a = y * radial + j, b = y * radial + n, c = (y + 1) * radial + n, d = (y + 1) * radial + j;
idx.push(a,d,c,a,c,b);
}
const g = new THREE.BufferGeometry();
g.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3)); g.setIndex(idx); g.computeVertexNormals();
const uv = new Float32Array((pos.length / 3) * 2); g.setAttribute('uv', new THREE.BufferAttribute(uv, 2));
return g;
}
function torsoGeometry() {
const rings = 13, radial = 28, pos = [], idx = [];
// normalized pelvis → ribcage → shoulder silhouette; solveRig supplies tracked width/height.
const widths = [0.82,0.92,1.00,1.01,0.96,0.88,0.82,0.84,0.93,1.03,1.11,1.16,1.12];
const depths = [0.78,0.84,0.88,0.87,0.82,0.76,0.72,0.73,0.78,0.84,0.88,0.86,0.80];
for (let y = 0; y < rings; y++) {
const fy = y / (rings - 1);
for (let j = 0; j < radial; j++) {
const a = j / radial * Math.PI * 2;
pos.push(Math.cos(a) * widths[y] * 0.5, fy, Math.sin(a) * depths[y] * 0.5);
}
}
for (let y = 0; y < rings - 1; y++) for (let j = 0; j < radial; j++) {
const n=(j+1)%radial,a=y*radial+j,b=y*radial+n,c=(y+1)*radial+n,d=(y+1)*radial+j; idx.push(a,d,c,a,c,b);
}
const g=new THREE.BufferGeometry(); g.setAttribute('position',new THREE.Float32BufferAttribute(pos,3)); g.setIndex(idx); g.computeVertexNormals();
g.setAttribute('uv',new THREE.BufferAttribute(new Float32Array((pos.length/3)*2),2)); return g;
}
function makePartGeometry(spec) {
let g;
if (spec.kind === 'tube') g = anatomyTube(spec);
else if (spec.kind === 'box') g = torsoGeometry();
else {
g = new THREE.SphereGeometry(1, 36, 28);
g.translate(0, 0.82, 0);
}
return g;
}
const avatar = new THREE.Group(); avatar.name = 'SOMA_Avatar';
scene.add(avatar);
const rigRoot = new THREE.Group(); rigRoot.name = 'SOMA_Rig';
avatar.add(rigRoot);
const nodes = {};
const parts = {}; // partId -> { mesh, node, def, enabled }
for (const def of RIG) {
const node = new THREE.Object3D();
node.name = def.name;
(def.parent ? nodes[def.parent] : rigRoot).add(node);
nodes[def.name] = node;
const geo = makePartGeometry(def.part);
const mesh = new THREE.Mesh(geo, skinMat);
mesh.name = def.part.id;
mesh.frustumCulled = false;
node.add(mesh);
mesh.userData.base = Float32Array.from(geo.attributes.position.array);
parts[def.part.id] = { mesh, node, def, enabled: true, kind: 'rigid' };
}
// ── Smoothed pose targets ──
const P = []; for (let i = 0; i < 33; i++) P.push(new THREE.Vector3());
let poseSeeded = false;
// Always-visible fallback pose. Tracking deforms this body; it never creates/destroys it.
function seedNeutralPose() {
const q = [
[0,1.16,0],[-.05,1.20,.01],[-.09,1.20,.01],[-.13,1.18,.01],[.05,1.20,.01],[.09,1.20,.01],[.13,1.18,.01],[-.15,1.15,0],[.15,1.15,0],[-.07,1.08,.02],[.07,1.08,.02],
[.31,.66,0],[-.31,.66,0],[.48,.28,.01],[-.48,.28,.01],[.56,-.08,.02],[-.56,-.08,.02],[.60,-.14,.03],[-.60,-.14,.03],[.61,-.12,.02],[-.61,-.12,.02],[.58,-.10,.02],[-.58,-.10,.02],
[.19,-.08,0],[-.19,-.08,0],[.20,-.76,.02],[-.20,-.76,.02],[.20,-1.42,.01],[-.20,-1.42,.01],[.20,-1.49,-.10],[-.20,-1.49,-.10],[.22,-1.50,.15],[-.22,-1.50,.15]
];
for (let i=0;i<33;i++) P[i].set(q[i][0],q[i][1],q[i][2]);
poseSeeded = true;
bodyScale = 1;
}
const _v = new THREE.Vector3(), _v2 = new THREE.Vector3(), _v3 = new THREE.Vector3();
const _q = new THREE.Quaternion(), _pq = new THREE.Quaternion();
const _ps = new THREE.Vector3(), _pp = new THREE.Vector3();
const _m = new THREE.Matrix4();
const UP = new THREE.Vector3(0, 1, 0);
let bodyScale = 1;
const BODY_PRESETS = [
{ t:0.00, name:'Skinny', girth:.72, shoulder:.90, waist:.74, hip:.88, arm:.72, leg:.76, depth:.78 },
{ t:0.33, name:'Average', girth:1.00, shoulder:1.00, waist:1.00, hip:1.00, arm:1.00, leg:1.00, depth:1.00 },
{ t:0.67, name:'Muscular', girth:1.10, shoulder:1.16, waist:.94, hip:1.03, arm:1.26, leg:1.20, depth:1.08 },
{ t:1.00, name:'Heavy-set', girth:1.30, shoulder:1.08, waist:1.38, hip:1.25, arm:1.18, leg:1.18, depth:1.28 }
];
function bodyPresetAt(t) {
t = THREE.MathUtils.clamp(t,0,1); let a=BODY_PRESETS[0], b=BODY_PRESETS[BODY_PRESETS.length-1];
for (let i=0;i<BODY_PRESETS.length-1;i++) if (t>=BODY_PRESETS[i].t && t<=BODY_PRESETS[i+1].t){a=BODY_PRESETS[i];b=BODY_PRESETS[i+1];break;}
const k=(t-a.t)/Math.max(1e-6,b.t-a.t), out={};
for (const key of ['girth','shoulder','waist','hip','arm','leg','depth']) out[key]=THREE.MathUtils.lerp(a[key],b[key],k);
out.name = BODY_PRESETS.reduce((best,p)=>Math.abs(p.t-t)<Math.abs(best.t-t)?p:best,a).name; return out;
}
function bodyProfile() {
const h=S.heightIn/71, referenceWeight=150*h*h, mass=THREE.MathUtils.clamp(Math.sqrt(S.weightLb/referenceWeight),.72,1.52), p=bodyPresetAt(S.bodyType);
return { ...p, heightScale:h, mass, shoulder:p.shoulder*mass, waist:p.waist*mass, hip:p.hip*mass, arm:p.arm*mass, leg:p.leg*mass, depth:p.depth*mass };
}
function fmtHeight(inches){ const ft=Math.floor(inches/12), inch=inches-ft*12; return `${ft}′${inch}″`; }
function updateProfileUI(){
const p=bodyProfile(), hs=fmtHeight(S.heightIn), line=`${hs} · ${S.weightLb} lb · ${p.name}`;
$('heightVal').textContent=hs; $('weightVal').textContent=`${S.weightLb} lb`; $('bodyTypeVal').textContent=p.name;
$('profileSummary').innerHTML=`<b>${line}</b><br/>Tracked joints + ${Math.round(p.mass*100)}% mass scaling + anatomical girth.`;
$('modelReadout').innerHTML=`<b>${hs} · ${S.weightLb} lb</b><br/>${p.name} · ${S.frameMode} framing`;
avatar.scale.setScalar(p.heightScale);
}
function updatePoseTargets(landmarks) {
const k = poseSeeded ? S.smoothing : 1;
for (let i = 0; i < 33; i++) {
const lm = landmarks[i];
if (!lm) continue;
lmToWorld(lm, _v);
P[i].lerp(_v, k);
}
poseSeeded = true;
const shoulder = P[11].distanceTo(P[12]);
bodyScale = THREE.MathUtils.clamp(shoulder / 0.62, 0.3, 3.5);
}
function solveRig() {
rigRoot.updateMatrix(); rigRoot.matrixWorld.copy(rigRoot.matrix);
const spineLen=_v.subVectors(_mid(P[11],P[12]),_mid(P[23],P[24])).length();
const shoulderW=P[11].distanceTo(P[12]), hipW=P[23].distanceTo(P[24]);
const prof=bodyProfile();
for (const def of RIG) {
const node=nodes[def.name], parent=node.parent, headPos=def.head(P), tailPos=def.tail?def.tail(P):null;
parent.matrixWorld.decompose(_pp,_pq,_ps); _m.copy(parent.matrixWorld).invert(); node.position.copy(headPos).applyMatrix4(_m);
let len=.2;
if (tailPos){_v2.subVectors(tailPos,headPos);len=_v2.length();if(len>1e-5){_v2.divideScalar(len);_q.setFromUnitVectors(UP,_v2);node.quaternion.copy(_pq).invert().multiply(_q);}}
node.userData.len=len; node.updateMatrix(); node.matrixWorld.multiplyMatrices(parent.matrixWorld,node.matrix);
const mesh=parts[def.part.id].mesh, id=def.part.id;
if (def.part.kind==='box') {
const tracked=Math.max(shoulderW,hipW), width=tracked*1.08*prof.girth;
// Rounded torso shell: X follows shoulders, Z follows mass, Y follows tracked spine.
mesh.scale.set(width,Math.max(spineLen,1e-3),width*.48*prof.depth);
} else if (def.part.kind==='ball') {
const hr=def.part.r*bodyScale*(.96 + .04/prof.heightScale);
mesh.scale.set(hr*.86,hr*1.06,hr*.92);
} else {
let girth=prof.arm;
if (id.startsWith('Thigh')||id.startsWith('Shin')||id.startsWith('Foot')) girth=prof.leg;
if (id==='Neck') girth=(prof.arm*.35 + prof.girth*.65);
if (id.startsWith('Palm')) girth=THREE.MathUtils.lerp(1,prof.arm,.45);
mesh.scale.set(bodyScale*girth,Math.max(len,1e-3),bodyScale*girth*prof.depth);
}
mesh.updateMatrix(); mesh.matrixWorld.multiplyMatrices(node.matrixWorld,mesh.matrix);
}
}
// ── Bake UVs on rigid parts from their world position ──
const _uv = [0, 0];
function bakeRigidUVs() {
for (const def of RIG) {
const p = parts[def.part.id];
if (!p.enabled) continue;
const mesh = p.mesh;
const base = mesh.userData.base;
const uvAttr = mesh.geometry.attributes.uv;
const n = uvAttr.count;
const mw = mesh.matrixWorld;
for (let i = 0; i < n; i++) {
_v.set(base[i * 3], base[i * 3 + 1], base[i * 3 + 2]).applyMatrix4(mw);
worldToUV(_v.x, _v.y, _uv);
uvAttr.array[i * 2] = _uv[0];
uvAttr.array[i * 2 + 1] = _uv[1];
}
uvAttr.needsUpdate = true;
}
}
// ═══════════════════════════════════════════════════════════════
// FACE MESH — real tessellated surface, UV straight from the frame
// ═══════════════════════════════════════════════════════════════
const FACE_N = 478;
let faceMesh = null, faceIndex = null, faceBuilt = false;
function trianglesFromTriples(conns) {
const tris = []; let ok = 0, bad = 0;
for (let i = 0; i + 2 < conns.length; i += 3) {