-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.html
More file actions
1895 lines (1625 loc) · 83.7 KB
/
index.html
File metadata and controls
1895 lines (1625 loc) · 83.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
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="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>VRMアバター 全身トラッキング (設定保存機能付き)</title>
<!-- Tailwind CSS -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- Import Maps -->
<script type="importmap">
{
"imports": {
"three": "https://cdn.jsdelivr.net/npm/three@0.169.0/build/three.module.js",
"three/addons/": "https://cdn.jsdelivr.net/npm/three@0.169.0/examples/jsm/",
"@pixiv/three-vrm": "https://cdn.jsdelivr.net/npm/@pixiv/three-vrm@3.0.0/lib/three-vrm.module.js",
"@mediapipe/tasks-vision": "https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.17/+esm",
"kalidokit": "https://cdn.jsdelivr.net/npm/kalidokit@1.1.5/dist/kalidokit.es.js"
}
}
</script>
<style>
body { margin: 0; overflow: hidden; background-color: #000; font-family: 'Meiryo', 'Yu Gothic', sans-serif; }
#canvas-container { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 20; pointer-events: none; }
/* 背景描画用キャンバス */
#bg-canvas {
position: absolute;
top: 50%; left: 50%;
transform: translate(-50%, -50%) scaleX(-1); /* 鏡像反転(JSで制御) */
min-width: 100%; min-height: 100%;
object-fit: cover;
z-index: 1;
}
/* 最前面キャンバス(デバッグ&実写手オーバーレイ用) */
#overlay-canvas {
position: absolute;
top: 50%; left: 50%;
transform: translate(-50%, -50%) scaleX(-1); /* 鏡像反転(JSで制御) */
min-width: 100%; min-height: 100%;
object-fit: cover;
z-index: 30;
pointer-events: none;
}
/* 暗転用オーバーレイ (UIより下、キャンバスより上) */
#blackout-overlay {
position: absolute;
top: 0; left: 0;
width: 100%; height: 100%;
background-color: #000;
background-position: center;
background-repeat: no-repeat;
background-size: contain; /* 画像全体を表示 */
z-index: 35;
pointer-events: none;
display: none; /* デフォルトは非表示 */
}
/* 利用規約オーバーレイ (最前面) */
#terms-overlay {
position: absolute;
top: 0; left: 0;
width: 100%; height: 100%;
background-color: rgba(0, 0, 0, 0.95);
z-index: 100;
display: flex;
justify-content: center;
align-items: center;
padding: 20px;
color: #eee;
}
.terms-box {
background: #222;
border: 1px solid #444;
border-radius: 12px;
padding: 25px;
max-width: 600px;
width: 100%;
max-height: 90vh;
overflow-y: auto;
box-shadow: 0 10px 25px rgba(0,0,0,0.8);
}
.terms-content {
font-size: 0.9rem;
line-height: 1.6;
margin-bottom: 20px;
color: #ccc;
background: #111;
padding: 15px;
border-radius: 8px;
border: 1px solid #333;
height: 300px;
overflow-y: auto;
}
.terms-title {
font-size: 1.2rem;
font-weight: bold;
margin-bottom: 15px;
color: #3b82f6;
text-align: center;
}
.agree-btn {
width: 100%;
padding: 15px;
background-color: #3b82f6;
color: white;
font-weight: bold;
border-radius: 8px;
border: none;
cursor: pointer;
font-size: 1rem;
transition: background 0.2s;
}
.agree-btn:hover { background-color: #2563eb; }
/* 隠し要素 */
#video-element { display: none; }
/* UI */
#ui-container {
position: absolute;
top: 20px;
left: 20px;
width: 360px; /* 少し幅を広げる */
background: rgba(20, 20, 20, 0.9);
backdrop-filter: blur(10px);
border-radius: 12px;
padding: 20px;
color: white;
z-index: 40;
border: 1px solid rgba(255,255,255,0.1);
box-shadow: 0 4px 20px rgba(0,0,0,0.5);
max-height: 90vh;
overflow-y: auto;
font-size: 0.9rem;
display: none; /* 初期化完了まで隠す */
}
/* UI閉じるボタン */
#ui-close-btn {
position: absolute;
top: 10px;
right: 10px;
background: transparent;
border: none;
color: #aaa;
font-size: 1.2rem;
cursor: pointer;
padding: 5px;
line-height: 1;
z-index: 41;
}
#ui-close-btn:hover {
color: white;
}
/* UI再表示ボタン (右下) */
#ui-show-btn {
position: absolute;
bottom: 20px;
right: 20px;
background: rgba(20, 20, 20, 0.8);
backdrop-filter: blur(5px);
color: white;
border: 1px solid rgba(255,255,255,0.2);
border-radius: 8px;
padding: 10px 15px;
cursor: pointer;
z-index: 40;
display: none; /* 初期は非表示(UIが出ているため) */
font-size: 0.9rem;
box-shadow: 0 4px 10px rgba(0,0,0,0.5);
transition: background 0.2s;
}
#ui-show-btn:hover {
background: rgba(50, 50, 50, 0.9);
}
.slider-group { margin-bottom: 12px; }
.slider-label { display: flex; justify-content: space-between; font-size: 0.8rem; margin-bottom: 4px; color: #ccc; }
input[type=range] { width: 100%; accent-color: #3b82f6; cursor: pointer; height: 4px; }
#loading-overlay {
position: absolute; top: 0; left: 0; width: 100%; height: 100%;
background: #111; color: white;
display: none; /* 初期状態は規約の下で非表示 */
flex-direction: column;
align-items: center; justify-content: center;
z-index: 50; transition: opacity 0.5s;
}
.loader {
border: 4px solid #333; border-top: 4px solid #3b82f6;
border-radius: 50%; width: 40px; height: 40px;
animation: spin 1s linear infinite; margin-bottom: 15px;
}
@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
.drop-area-base {
border: 2px dashed #444;
border-radius: 8px;
padding: 15px;
text-align: center;
margin-top: 15px;
font-size: 0.8rem;
color: #888;
transition: background 0.3s;
cursor: pointer;
}
.drop-area-base:hover { background: rgba(255,255,255,0.05); border-color: #666; }
.capture-btn {
width: 100%;
padding: 12px;
border-radius: 8px;
font-weight: bold;
font-size: 0.9rem;
cursor: pointer;
transition: all 0.2s;
background-color: #ef4444;
color: white;
margin-bottom: 10px;
border: none;
box-shadow: 0 4px 6px rgba(0,0,0,0.3);
}
.capture-btn:hover { background-color: #dc2626; }
.capture-btn:disabled { background-color: #6b7280; cursor: not-allowed; }
h3 { font-size: 0.9rem; font-weight: bold; color: #888; margin-top: 15px; margin-bottom: 5px; border-bottom: 1px solid #444; padding-bottom: 2px; }
.status-text { font-size: 0.8rem; color: #aaa; margin-bottom: 10px; text-align: center; }
.checkbox-group {
display: flex;
align-items: center;
margin-bottom: 15px;
font-size: 0.9rem;
}
.checkbox-group input {
margin-right: 8px;
width: 16px;
height: 16px;
accent-color: #3b82f6;
}
.secondary-btn {
margin-top: 5px;
width: 100%;
background-color: #4b5563;
color: white;
font-size: 0.75rem;
padding: 6px;
border-radius: 4px;
border: none;
cursor: pointer;
font-weight: bold;
}
.secondary-btn:hover { background-color: #6b7280; }
/* Device Select Style */
.device-group {
background: #2a2a2a;
padding: 10px;
border-radius: 8px;
margin-bottom: 12px;
border: 1px solid #444;
}
.device-label {
display: block;
font-size: 0.75rem;
color: #aaa;
margin-bottom: 5px;
font-weight: bold;
}
select {
background-color: #374151;
color: white;
border: 1px solid #555;
padding: 8px;
border-radius: 6px;
cursor: pointer;
font-size: 0.8rem;
width: 100%;
outline: none;
}
select:hover { background-color: #4b5563; }
/* 設定保存ボタン群 */
.settings-io-group {
display: flex;
gap: 10px;
margin-top: 20px;
padding-top: 10px;
border-top: 1px solid #444;
}
</style>
</head>
<body>
<!-- 利用規約モーダル -->
<div id="terms-overlay">
<div class="terms-box">
<div class="terms-title">利用規約・免責事項</div>
<div class="terms-content">
<p class="mb-4">本アプリ「VRMアバターAR (VRM1.0正式対応)」のご利用前に、以下の内容をご確認・同意ください。</p>
<strong class="text-blue-400">1. VRMファイルの扱いについて</strong>
<p class="mb-4 text-sm">
読み込まれたVRMファイルおよびカメラ映像は、お使いのブラウザ内(クライアントサイド)でのみ処理されます。
外部サーバーへのアップロードや保存は一切行われません。
ページを閉じると、読み込んだデータは破棄されます。
</p>
<strong class="text-yellow-400">2. プライバシー保護について</strong>
<p class="mb-4 text-sm">
本アプリの「背景除去(マスク)」機能はAIによる推定処理であり、100%の精度を保証するものではありません。
環境や条件により、背景や人物の一部が意図せず映り込む可能性があります。
動画の配信や共有を行う際は、プライバシー保護が完全ではないことを理解した上で、十分ご注意ください。
</p>
<strong class="text-red-400">3. 免責事項(自己責任)</strong>
<p class="mb-4 text-sm">
本アプリの利用により生じた、いかなる損害、トラブル、不利益についても、開発者は一切の責任を負いません。
ご利用は利用者ご自身の責任において行ってください。
</p>
<strong class="text-orange-400">4. 誤検知・環境について</strong>
<p class="mb-4 text-sm">
カメラの画角内に、ポスターの人物、人形、フィギュア、ハンガーにかかった服など、
<span class="underline font-bold">「人の形状に見えるもの」が存在すると、AIが人物と誤認する可能性があります。</span>
これらが画角に入らないよう調整してご利用ください。
</p>
<strong class="text-green-400">5. マイク利用について</strong>
<p class="mb-4 text-sm">
リップシンク(口パク)機能のためにマイク音声の音量レベルのみを使用します。
<span class="underline font-bold">音声データの録音・保存・外部サーバーへの送信等は一切行いません。</span>
処理はすべてお使いの端末内(ブラウザ)で完結します。
</p>
</div>
<button id="agree-btn" class="agree-btn">上記に同意してカメラを起動する</button>
</div>
</div>
<div id="loading-overlay">
<div class="loader"></div>
<div id="loading-text">システム起動中... (AIモデル読込中)</div>
</div>
<!-- トラッキングロスト時の暗転レイヤー -->
<div id="blackout-overlay"></div>
<video id="video-element" playsinline muted autoplay></video>
<canvas id="bg-canvas"></canvas>
<canvas id="overlay-canvas"></canvas>
<div id="canvas-container"></div>
<!-- 右下の再表示ボタン -->
<button id="ui-show-btn">⚙️ 設定を表示</button>
<div id="ui-container">
<!-- UIを閉じるボタン -->
<button id="ui-close-btn" title="設定を閉じる">✕</button>
<h2 class="text-lg font-bold mb-4 text-blue-400">着ぐるみアバターAR</h2>
<!-- デバイス設定セクション -->
<h3 style="margin-top: 0;">デバイス設定</h3>
<div class="device-group">
<span class="device-label">📷 トラッキングカメラ</span>
<select id="camera-select">
<option value="" disabled selected>カメラ検出中...</option>
</select>
</div>
<div class="device-group">
<span class="device-label">🎤 リップシンクマイク</span>
<select id="mic-select">
<option value="" disabled selected>マイク検出中...</option>
</select>
</div>
<button id="capture-bg-btn" class="capture-btn">
📸 背景を撮影 (5秒タイマー)
<div style="font-size: 0.8em; font-weight: normal; margin-top:4px;">※フレームから外れてください!</div>
</button>
<div id="capture-status" class="status-text">ステータス: 撮影待機中...</div>
<!-- Debug Checkbox -->
<div class="checkbox-group" style="justify-content: center; margin-bottom: 20px;">
<input type="checkbox" id="debug-toggle">
<label for="debug-toggle">デバッグ表示 (ランドマーク)</label>
</div>
<!-- Real Hand Overlay Checkbox -->
<div class="checkbox-group">
<input type="checkbox" id="hand-overlay-toggle">
<label for="hand-overlay-toggle" class="text-blue-300 font-bold">手持ちアイテムを表示 (実験的機能)</label>
</div>
<div class="slider-group">
<div class="slider-label"><span>合成範囲サイズ</span><span id="val-hand-size">0.001</span></div>
<input type="range" id="input-hand-size" min="0.001" max="1.0" step="0.001" value="0.001">
</div>
<!-- Skin Removal Settings -->
<div class="checkbox-group">
<input type="checkbox" id="skin-removal-toggle">
<label for="skin-removal-toggle" class="text-green-300 font-bold">肌と背景を除去 (実験的機能)</label>
</div>
<div class="slider-group">
<div class="slider-label"><span>肌の色味調整</span><span id="val-skin-hue">0.05</span></div>
<input type="range" id="input-skin-hue" min="0.0" max="0.2" step="0.01" value="0.05">
</div>
<div class="slider-group">
<div class="slider-label"><span>背景差分判定の強さ</span><span id="val-bg-diff">0.2</span></div>
<input type="range" id="input-bg-diff" min="0.05" max="0.8" step="0.01" value="0.2">
</div>
<h3>マスク設定</h3>
<div class="slider-group">
<div class="slider-label"><span>マスクの閾値</span><span id="val-mask-thresh">0.0</span></div>
<input type="range" id="input-mask-thresh" min="0.0" max="1.0" step="0.01" value="0.0">
</div>
<div class="slider-group">
<div class="slider-label"><span>マスクの拡張</span><span id="val-mask-exp">1.0</span></div>
<input type="range" id="input-mask-exp" min="0.0" max="1.0" step="0.01" value="1.0">
</div>
<h3>アバター調整</h3>
<!-- 視線調整UI -->
<div class="slider-group">
<div class="slider-label"><span>視線追従の強さ</span><span id="val-look-intensity">0.4</span></div>
<input type="range" id="input-look-intensity" min="-2.0" max="2.0" step="0.1" value="0.4">
</div>
<div class="checkbox-group">
<input type="checkbox" id="invert-look-toggle">
<label for="invert-look-toggle">視線(左右)を反転</label>
</div>
<div class="checkbox-group">
<input type="checkbox" id="invert-look-y-toggle">
<label for="invert-look-y-toggle">視線(上下)を反転</label>
</div>
<div class="slider-group">
<div class="slider-label"><span>基本スケール (基準値)</span><span id="val-scale">1.4</span></div>
<input type="range" id="input-scale" min="0.5" max="10.0" step="0.1" value="1.4">
</div>
<!-- スムージング設定 -->
<div class="slider-group">
<div class="slider-label"><span>トラッキング平滑化</span><span id="val-smooth">0.7</span></div>
<input type="range" id="input-smooth" min="0.0" max="0.95" step="0.01" value="0.7">
</div>
<div class="slider-group">
<div class="slider-label"><span>位置調整 (上下)</span><span id="val-pos-y">0.0</span></div>
<input type="range" id="input-pos-y" min="-2.0" max="2.0" step="0.05" value="0.0">
</div>
<h3>環境設定</h3>
<div class="slider-group">
<div class="slider-label"><span>照明の明るさ</span><span id="val-light">2.2</span></div>
<input type="range" id="input-light" min="0.0" max="3.0" step="0.1" value="2.2">
</div>
<div class="slider-group">
<div class="slider-label"><span>動作感度</span><span id="val-sens">1.0</span></div>
<input type="range" id="input-sens" min="0.5" max="2.0" step="0.1" value="1.0">
</div>
<!-- 画像アップロードエリア (Lost Image) -->
<h3>ロスト時画像設定</h3>
<div id="drop-area-lost" class="drop-area-base" style="margin-top: 5px; padding: 10px;">
<span id="lost-img-text">ロスト時の画像をドロップ</span>
<input type="file" id="file-input-lost" accept="image/*" style="display: none;">
</div>
<button id="clear-lost-img-btn" class="secondary-btn" style="display: none;">画像を削除 (黒画面に戻す)</button>
<div id="drop-area" class="drop-area-base">
VRMファイルをドロップ<br>
(VRM 0.x / 1.0 両対応)
<input type="file" id="file-input" accept=".vrm" style="display: none;">
</div>
<!-- 設定保存・読込 -->
<div class="settings-io-group">
<button id="save-settings-btn" class="secondary-btn" style="background-color: #2563eb;">💾 設定を保存</button>
<button id="load-settings-btn" class="secondary-btn" style="background-color: #059669;">📂 設定を読込</button>
<input type="file" id="settings-file-input" accept=".json" style="display: none;">
</div>
<button id="reset-btn" class="mt-4 w-full bg-gray-600 hover:bg-gray-500 text-white text-xs font-bold py-2 px-4 rounded">
設定をリセット (初期化)
</button>
</div>
<script type="module">
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { VRMLoaderPlugin, VRMUtils } from '@pixiv/three-vrm';
import { FilesetResolver, FaceLandmarker, PoseLandmarker, HandLandmarker } from '@mediapipe/tasks-vision';
import * as Kalidokit from 'kalidokit';
// --- Utilities ---
const clamp = Kalidokit.Utils.clamp;
const lerp = Kalidokit.Vector.lerp;
// --- Global Variables ---
let scene, camera, renderer, clock;
let currentVrm = null;
let isVrm1 = false; // Version flag
let faceLandmarker = null;
let poseLandmarker = null;
let handLandmarker = null;
let videoElement = document.getElementById('video-element');
let blackoutOverlay = document.getElementById('blackout-overlay');
// Camera Settings
let videoDevices = [];
let currentDeviceId = null;
// Mic Settings
let audioDevices = [];
let currentMicId = null;
// Canvases
let bgCanvas = document.getElementById('bg-canvas');
let bgCtx = bgCanvas.getContext('2d', { willReadFrequently: true });
let overlayCanvas = document.getElementById('overlay-canvas');
let overlayCtx = overlayCanvas.getContext('2d', { willReadFrequently: true });
let capturedBgCanvas = null;
let capturedBgCtx = null;
// Mask Persistence
let lastMaskData = null;
// Tracking Status Logic (Debounce)
let goodFrames = 0;
let badFrames = 0;
let isTrackingActive = false;
const REQUIRED_GOOD_FRAMES = 10; // 0.3秒 @ 30fps
const REQUIRED_BAD_FRAMES = 0; // 即暗転のため0 (ロジックでも直接制御)
// Auto Brightness Variables
let capturedBrightness = 0;
const brightnessCalcCanvas = document.createElement('canvas');
brightnessCalcCanvas.width = 64;
brightnessCalcCanvas.height = 36;
const brightnessCalcCtx = brightnessCalcCanvas.getContext('2d', { willReadFrequently: true });
let lastVideoTime = -1;
let isCameraReady = false;
let oldLookTarget = new THREE.Euler();
// Bone scaling management
const initialBoneLengths = {};
// Audio Context for Lip Sync
let audioContext = null;
let analyser = null;
let microphone = null;
let dataArray = null;
let isMicInitialized = false;
// Fixed settings for simplified UI
const FIXED_MOUTH_BOOST = 1.0; // 標準
const FIXED_MIC_GAIN = 3.0; // 標準
// Default Settings
const defaultSettings = {
scaleAdjust: 1.4,
lightIntensity: 2.2,
sensitivity: 1.0,
lookAtIntensity: 0.4,
invertLookAt: false,
invertLookAtY: false,
smoothing: 0.7,
maskThreshold: 0.0,
maskExpansion: 1.0,
posY: 0.0,
showDebug: false,
showHandOverlay: false,
handOverlaySize: 0.001,
removeSkin: false,
skinThreshold: 0.4,
skinHue: 0.05,
bgDiffThreshold: 0.2
};
const settings = { ...defaultSettings };
const avatarPos = new THREE.Vector3(0, -1, 0);
let vrmHipY = 0.0;
// --- Initialization Flow ---
const termsOverlay = document.getElementById('terms-overlay');
const agreeBtn = document.getElementById('agree-btn');
const loadingOverlay = document.getElementById('loading-overlay');
const uiContainer = document.getElementById('ui-container');
const uiCloseBtn = document.getElementById('ui-close-btn');
const uiShowBtn = document.getElementById('ui-show-btn');
agreeBtn.addEventListener('click', () => {
termsOverlay.style.display = 'none';
loadingOverlay.style.display = 'flex';
init();
});
uiCloseBtn.addEventListener('click', () => {
uiContainer.style.display = 'none';
uiShowBtn.style.display = 'block';
});
uiShowBtn.addEventListener('click', () => {
uiContainer.style.display = 'block';
uiShowBtn.style.display = 'none';
});
async function init() {
const loadingText = document.getElementById('loading-text');
setupScene();
loadingText.innerText = "デバイスへのアクセスを確認中...";
// カメラとマイクを順番に初期化
await getCameraDevices();
await setupWebcam();
await setupAudio(); // 初回マイクセットアップ(デフォルト)
await refreshDeviceLists(); // 許可後にデバイスリストを更新(名前取得)
loadingText.innerText = "AIモデルをダウンロード中... (Face, Pose & Hands)";
await setupVisionTasks();
loadingText.innerText = "準備完了";
loadingOverlay.style.opacity = '0';
setTimeout(() => {
loadingOverlay.style.display = 'none';
uiContainer.style.display = 'block';
}, 500);
animate();
}
function setupScene() {
const container = document.getElementById('canvas-container');
const width = container.clientWidth;
const height = container.clientHeight;
renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true, logarithmicDepthBuffer: true });
renderer.setSize(width, height);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.shadowMap.enabled = false;
renderer.outputColorSpace = THREE.SRGBColorSpace;
container.appendChild(renderer.domElement);
camera = new THREE.PerspectiveCamera(30.0, width / height, 0.01, 200.0);
camera.position.set(0.0, 0.0, 5.0);
scene = new THREE.Scene();
const ambientLight = new THREE.AmbientLight(0xffffff, settings.lightIntensity);
scene.add(ambientLight);
window.ambientLight = ambientLight;
clock = new THREE.Clock();
window.addEventListener('resize', () => {
const w = container.clientWidth;
const h = container.clientHeight;
renderer.setSize(w, h);
camera.aspect = w / h;
camera.updateProjectionMatrix();
});
}
// --- Audio Setup ---
async function setupAudio(deviceId = undefined) {
try {
// 既存の接続を切る
if (microphone) microphone.disconnect();
if (audioContext && audioContext.state !== 'closed') {
// AudioContextは再利用するが、ソースを作り直す
} else {
audioContext = new (window.AudioContext || window.webkitAudioContext)();
}
const constraints = {
audio: deviceId ? { deviceId: { exact: deviceId } } : true
};
const stream = await navigator.mediaDevices.getUserMedia(constraints);
microphone = audioContext.createMediaStreamSource(stream);
analyser = audioContext.createAnalyser();
analyser.fftSize = 256;
dataArray = new Uint8Array(analyser.frequencyBinCount);
microphone.connect(analyser);
isMicInitialized = true;
// ストリーム取得成功後にデバイスIDを更新(初回など未指定の場合)
const track = stream.getAudioTracks()[0];
if(track) {
currentMicId = track.getSettings().deviceId;
}
} catch (err) {
console.error("Microphone Error:", err);
}
}
async function refreshDeviceLists() {
try {
const devices = await navigator.mediaDevices.enumerateDevices();
// カメラ一覧更新
videoDevices = devices.filter(device => device.kind === 'videoinput');
const cameraSelect = document.getElementById('camera-select');
cameraSelect.innerHTML = '';
if (videoDevices.length === 0) {
const option = document.createElement('option');
option.text = "カメラが見つかりません";
cameraSelect.appendChild(option);
} else {
videoDevices.forEach((device, index) => {
const option = document.createElement('option');
option.value = device.deviceId;
option.text = device.label || `カメラ ${index + 1}`;
cameraSelect.appendChild(option);
});
if(currentDeviceId) cameraSelect.value = currentDeviceId;
}
// マイク一覧更新
audioDevices = devices.filter(device => device.kind === 'audioinput');
const micSelect = document.getElementById('mic-select');
micSelect.innerHTML = '';
if (audioDevices.length === 0) {
const option = document.createElement('option');
option.text = "マイクが見つかりません";
micSelect.appendChild(option);
} else {
audioDevices.forEach((device, index) => {
const option = document.createElement('option');
option.value = device.deviceId;
option.text = device.label || `マイク ${index + 1}`;
micSelect.appendChild(option);
});
// 現在のマイクを選択状態に
if(currentMicId) micSelect.value = currentMicId;
}
// イベントリスナー再設定
micSelect.onchange = (e) => {
currentMicId = e.target.value;
setupAudio(currentMicId);
};
} catch(err) {
console.warn("Device enumeration error:", err);
}
}
async function getCameraDevices() {
// 初回のカメラ列挙(ラベルなしの可能性あり)
try {
const devices = await navigator.mediaDevices.enumerateDevices();
videoDevices = devices.filter(device => device.kind === 'videoinput');
if (videoDevices.length > 0) {
currentDeviceId = videoDevices[0].deviceId;
}
} catch (err) {
console.warn("Camera enumeration failed", err);
}
}
async function setupWebcam() {
isCameraReady = false;
try {
if (videoElement.srcObject) {
const tracks = videoElement.srcObject.getTracks();
tracks.forEach(track => track.stop());
}
const constraints = {
video: {
width: 1280,
height: 720,
deviceId: currentDeviceId ? { exact: currentDeviceId } : undefined
}
};
const stream = await navigator.mediaDevices.getUserMedia(constraints);
videoElement.srcObject = stream;
// 許可が得られたのでデバイスリストを更新(ラベル表示用)
await new Promise((resolve) => {
videoElement.onloadedmetadata = () => {
videoElement.play();
bgCanvas.width = videoElement.videoWidth;
bgCanvas.height = videoElement.videoHeight;
overlayCanvas.width = videoElement.videoWidth;
overlayCanvas.height = videoElement.videoHeight;
isCameraReady = true;
let scaleX = -1;
const currentDevice = videoDevices.find(d => d.deviceId === currentDeviceId);
if (currentDevice) {
const label = currentDevice.label.toLowerCase();
if (label.includes("back") || label.includes("rear") || label.includes("environment")) {
scaleX = 1;
}
}
const transform = `translate(-50%, -50%) scaleX(${scaleX})`;
bgCanvas.style.transform = transform;
overlayCanvas.style.transform = transform;
resolve();
};
});
} catch (err) {
console.error("Webcam Error:", err);
alert("カメラエラー: " + err.message + "\n※カメラが使用中の可能性があります");
}
}
// カメラ選択イベントリスナー
const cameraSelect = document.getElementById('camera-select');
cameraSelect.addEventListener('change', (e) => {
currentDeviceId = e.target.value;
setupWebcam();
});
async function setupVisionTasks() {
const filesetResolver = await FilesetResolver.forVisionTasks(
"https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.17/wasm"
);
faceLandmarker = await FaceLandmarker.createFromOptions(filesetResolver, {
baseOptions: {
modelAssetPath: `https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task`,
delegate: "GPU"
},
outputFaceBlendshapes: true,
outputFacialTransformationMatrixs: true,
runningMode: "VIDEO",
numFaces: 1,
minFaceDetectionConfidence: 0.7,
minFacePresenceConfidence: 0.7,
minTrackingConfidence: 0.7
});
poseLandmarker = await PoseLandmarker.createFromOptions(filesetResolver, {
baseOptions: {
modelAssetPath: `https://storage.googleapis.com/mediapipe-models/pose_landmarker/pose_landmarker_lite/float16/1/pose_landmarker_lite.task`,
delegate: "GPU"
},
runningMode: "VIDEO",
numPoses: 1,
outputSegmentationMasks: true,
minPoseDetectionConfidence: 0.85,
minPosePresenceConfidence: 0.85,
minTrackingConfidence: 0.85
});
handLandmarker = await HandLandmarker.createFromOptions(filesetResolver, {
baseOptions: {
modelAssetPath: `https://storage.googleapis.com/mediapipe-models/hand_landmarker/hand_landmarker/float16/1/hand_landmarker.task`,
delegate: "GPU"
},
runningMode: "VIDEO",
numHands: 2,
minHandDetectionConfidence: 0.6,
minHandPresenceConfidence: 0.6,
minTrackingConfidence: 0.6
});
}
function getBoneLength(vrm, boneName1, boneName2) {
const b1 = vrm.humanoid.getNormalizedBoneNode(boneName1);
const b2 = vrm.humanoid.getNormalizedBoneNode(boneName2);
if (b1 && b2) {
return b1.getWorldPosition(new THREE.Vector3()).distanceTo(b2.getWorldPosition(new THREE.Vector3()));
}
return 0;
}
async function loadVRM(url) {
const loader = new GLTFLoader();
loader.register((parser) => {
return new VRMLoaderPlugin(parser, {
helperRoot: null,
autoUpdateHumanBones: true
});
});
try {
const gltf = await loader.loadAsync(url);
const vrm = gltf.userData.vrm;
if (currentVrm) {
scene.remove(currentVrm.scene);
VRMUtils.deepDispose(currentVrm.scene);
}
currentVrm = vrm;
scene.add(vrm.scene);
// Optimize VRM
VRMUtils.removeUnnecessaryVertices(vrm.scene);
VRMUtils.removeUnnecessaryJoints(vrm.scene);
vrm.scene.traverse((obj) => {
if (obj.isMesh) {
obj.castShadow = false;
obj.receiveShadow = false;
obj.frustumCulled = false;
}
});
// Handle VRM Version Differences
if (vrm.meta.metaVersion === '1') {
console.log("VRM 1.0 Model Loaded");
isVrm1 = true;
vrm.scene.rotation.y = 0;
} else {
console.log("VRM 0.x Model Loaded");
isVrm1 = false;
vrm.scene.rotation.y = Math.PI;
}
updateUI();
const hips = vrm.humanoid.getNormalizedBoneNode('hips');
if (hips) vrmHipY = hips.position.y;
initialBoneLengths.body = getBoneLength(vrm, 'hips', 'neck');
const shoulderL = vrm.humanoid.getNormalizedBoneNode('leftShoulder');
const shoulderR = vrm.humanoid.getNormalizedBoneNode('rightShoulder');
const upperArmL = vrm.humanoid.getNormalizedBoneNode('leftUpperArm');
const upperArmR = vrm.humanoid.getNormalizedBoneNode('rightUpperArm');
if (upperArmL && upperArmR) {
initialBoneLengths.shoulderWidth = upperArmL.getWorldPosition(new THREE.Vector3())
.distanceTo(upperArmR.getWorldPosition(new THREE.Vector3()));
}
initialBoneLengths.upperArmL = getBoneLength(vrm, 'leftUpperArm', 'leftLowerArm');
initialBoneLengths.upperArmR = getBoneLength(vrm, 'rightUpperArm', 'rightLowerArm');
initialBoneLengths.lowerArmL = getBoneLength(vrm, 'leftLowerArm', 'leftHand');
initialBoneLengths.lowerArmR = getBoneLength(vrm, 'rightLowerArm', 'rightHand');
console.log("VRM Loaded");
} catch (err) {
console.error(err);
alert("VRM読み込みエラー");
}
}
function calculateBrightness(imageSource) {
brightnessCalcCtx.drawImage(imageSource, 0, 0, brightnessCalcCanvas.width, brightnessCalcCanvas.height);
const data = brightnessCalcCtx.getImageData(0, 0, brightnessCalcCanvas.width, brightnessCalcCanvas.height).data;
let sum = 0;
for (let i = 0; i < data.length; i += 4) {
sum += (data[i] + data[i+1] + data[i+2]) / 3;
}
return sum / (brightnessCalcCanvas.width * brightnessCalcCanvas.height);
}
function rgbToHsv(r, g, b) {
r /= 255, g /= 255, b /= 255;
var max = Math.max(r, g, b), min = Math.min(r, g, b);
var h, s, v = max;
var d = max - min;
s = max == 0 ? 0 : d / max;
if (max == min) {
h = 0;
} else {
switch (max) {
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
h /= 6;
}
return [h, s, v];
}
// --- Rigging Helpers ---
const rigRotation = (name, rotation = { x: 0, y: 0, z: 0 }, dampener = 1, lerpAmount = 0.3) => {
if (!currentVrm) return;
const boneName = name.charAt(0).toLowerCase() + name.slice(1);