File size: 169,720 Bytes
2d7703f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4507f29
 
 
 
 
1e6f719
 
 
 
 
2d7703f
 
4507f29
 
 
 
 
 
 
 
 
 
d2eab41
4507f29
2d7703f
 
 
 
1e6f719
 
 
4507f29
1e6f719
4507f29
 
2d7703f
 
 
 
4507f29
 
 
d2eab41
 
4507f29
2d7703f
4507f29
d2eab41
2d7703f
 
 
 
 
 
 
 
1e6f719
 
 
2d7703f
 
d2eab41
 
 
 
 
2d7703f
d2eab41
 
 
 
 
2d7703f
d2eab41
 
 
 
 
 
 
 
2d7703f
d2eab41
2d7703f
4507f29
d2eab41
 
 
2d7703f
d2eab41
4507f29
d2eab41
 
 
 
 
2d7703f
 
4507f29
1bdc3d6
 
 
 
 
 
 
 
 
 
 
1e6f719
 
 
1bdc3d6
 
1e6f719
 
 
 
 
1bdc3d6
 
 
1e6f719
 
 
 
 
 
 
1bdc3d6
 
 
 
4507f29
1bdc3d6
 
 
 
 
 
 
 
 
1e6f719
 
 
1bdc3d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e6f719
1bdc3d6
 
 
 
 
 
 
 
 
 
1e6f719
1bdc3d6
 
4507f29
1bdc3d6
2d7703f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2dded6a
2d7703f
2dded6a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc19f42
703f6e6
dc19f42
 
 
 
7d1f3fd
6d8676e
 
 
 
 
 
9164329
 
 
 
 
 
8a75fa2
6d8676e
dc19f42
8a75fa2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9164329
384716d
8a75fa2
8b30697
 
 
 
 
 
 
 
 
 
 
 
 
 
9164329
dc19f42
8a75fa2
dc19f42
 
384716d
8a75fa2
384716d
 
8a75fa2
384716d
 
 
 
8a75fa2
384716d
8a75fa2
 
 
 
384716d
 
9164329
dc19f42
384716d
8a75fa2
 
384716d
8a75fa2
384716d
8a75fa2
 
 
 
 
 
 
 
 
 
 
 
 
 
384716d
8a75fa2
 
384716d
8a75fa2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
384716d
dc19f42
8a75fa2
 
dc19f42
6d8676e
8a75fa2
6d8676e
 
384716d
8a75fa2
 
384716d
8a75fa2
384716d
8a75fa2
 
384716d
8a75fa2
 
 
 
 
384716d
8a75fa2
 
 
 
 
384716d
8a75fa2
 
 
 
 
384716d
8a75fa2
 
384716d
 
 
 
8a75fa2
 
 
384716d
 
 
8a75fa2
384716d
 
6d8676e
 
dc19f42
384716d
8a75fa2
 
6d8676e
 
384716d
8a75fa2
 
 
384716d
 
8a75fa2
 
 
 
 
384716d
 
8a75fa2
 
 
 
384716d
8a75fa2
 
 
384716d
 
 
8a75fa2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66817c7
384716d
8a75fa2
6d8676e
 
dc19f42
384716d
8a75fa2
384716d
dc19f42
8a75fa2
 
 
 
 
 
 
 
 
 
384716d
8a75fa2
 
 
384716d
8a75fa2
 
 
 
 
 
384716d
8a75fa2
384716d
8a75fa2
 
 
 
 
 
 
 
 
 
384716d
 
 
8a75fa2
 
384716d
dc19f42
 
384716d
e64d8cb
8a75fa2
 
e64d8cb
 
8a75fa2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e26e6e6
 
 
8a75fa2
 
 
 
 
 
66817c7
8a75fa2
 
 
 
 
 
 
e64d8cb
 
 
dc19f42
8a75fa2
dc19f42
466ed62
 
 
38b192e
2d7703f
 
2dded6a
38b192e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
466ed62
38b192e
466ed62
 
 
 
 
 
38b192e
 
 
 
 
 
 
 
 
466ed62
 
 
7d25c6c
 
 
 
 
 
 
38b192e
 
 
7d25c6c
 
 
 
 
466ed62
7d25c6c
 
 
 
466ed62
 
7d25c6c
 
 
466ed62
 
7d25c6c
 
 
 
 
 
 
466ed62
7d25c6c
 
 
 
38b192e
 
 
 
7d25c6c
 
466ed62
7d25c6c
38b192e
 
 
 
 
 
 
 
 
 
2dded6a
259c009
 
 
 
 
 
 
63a8a93
38b192e
 
 
 
 
 
6f7289d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
466ed62
 
 
6f7289d
 
 
 
 
 
466ed62
 
6f7289d
 
 
 
 
63a8a93
38b192e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2dded6a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38b192e
 
2dded6a
 
2d7703f
38b192e
 
 
2d7703f
38b192e
 
 
 
 
 
 
 
 
 
 
 
2d7703f
 
 
38b192e
 
 
 
 
 
 
 
 
 
 
2d7703f
38b192e
 
2d7703f
38b192e
 
 
 
 
 
 
 
 
 
 
2d7703f
38b192e
 
2d7703f
38b192e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d7703f
38b192e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d7703f
38b192e
 
 
 
2d7703f
38b192e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d7703f
 
 
 
 
38b192e
d9c99e5
2d7703f
 
 
 
 
 
 
 
d9c99e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d7703f
d9c99e5
 
 
 
2d7703f
d9c99e5
 
 
2d7703f
d9c99e5
 
 
 
 
 
 
 
2d7703f
595bb43
 
 
2d7703f
595bb43
 
 
 
2d7703f
595bb43
 
 
 
 
 
2d7703f
595bb43
e26e6e6
595bb43
 
 
 
 
 
 
 
2d7703f
 
 
 
d9c99e5
 
2d7703f
 
d9c99e5
 
 
2d7703f
 
4507f29
2d7703f
 
 
 
 
 
4507f29
2d7703f
 
d9c99e5
2d7703f
8a56d8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d7703f
 
 
4507f29
2d7703f
 
4507f29
 
595bb43
38b192e
595bb43
38b192e
595bb43
 
 
38b192e
595bb43
 
 
 
 
 
38b192e
595bb43
 
 
38b192e
595bb43
 
 
 
 
 
 
4507f29
595bb43
 
 
 
 
 
 
38b192e
595bb43
 
38b192e
595bb43
 
 
 
 
38b192e
595bb43
38b192e
595bb43
 
 
 
 
 
 
 
 
 
 
4507f29
595bb43
d9c99e5
 
595bb43
 
 
 
 
 
 
 
 
 
 
d9c99e5
4507f29
595bb43
 
2d7703f
 
 
 
 
 
4507f29
2d7703f
 
 
 
 
 
4507f29
 
2d7703f
d9c99e5
 
 
 
 
 
 
2d7703f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38b192e
 
 
 
2d7703f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2033ff2
 
2d7703f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7d25c6c
2d7703f
7d25c6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d7703f
 
7d25c6c
2d7703f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
015cd0c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d7703f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc2fdde
 
 
765b79c
 
cc2fdde
 
765b79c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc2fdde
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
765b79c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc2fdde
 
 
 
765b79c
 
cc2fdde
 
 
765b79c
cc2fdde
2d7703f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2033ff2
7d25c6c
 
 
cc2fdde
7d25c6c
8f15045
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc2fdde
8f15045
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7d25c6c
 
 
 
 
 
 
 
 
466ed62
7d25c6c
 
466ed62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2033ff2
466ed62
 
 
 
 
 
 
 
7d25c6c
466ed62
 
 
 
7d25c6c
 
466ed62
 
 
 
 
 
 
 
 
 
 
 
7d25c6c
466ed62
 
7d25c6c
466ed62
 
 
 
 
 
 
2033ff2
7d25c6c
466ed62
 
 
 
 
 
 
 
 
 
 
7d25c6c
466ed62
 
 
 
 
 
 
 
 
 
7d25c6c
2d7703f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2033ff2
2d7703f
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
// apps/preprocess/preprocess_manual.js
// 2025/12/12 18:08 manual mode for human completed
// 2025/12/12 20:55 manual mode for statue completed

import * as THREE from 'three';
import { GVRM } from '../../gvrm-format/gvrm.js';
import { PLYParser } from '../../gvrm-format/ply.js';
import * as GVRMUtils from '../../gvrm-format/utils.js';
import { DropInViewer } from 'gaussian-splats-3d';
// ==========================================
// ADD THESE IMPORTS AT THE TOP
// ==========================================

import { OrbitControls } from '../../lib/OrbitControls.js';

console.log('[preprocess_manual.js] ===== MODULE LOADING =====');

/**
 * Manual UI作成関数
 * 手動でのBOX設定と部位割り当て用のUIを提供
 */

// プリセット定義
// プリセット定義 - 必須18ボーンをすべてカバー
const PRESET_BONE_GROUPS = {
  'required19': [
    { name: '1. Head', bones: ['head'], color: [255, 0, 0] },
    { name: '2. Neck', bones: ['neck'], color: [255, 100, 100] },
    { name: '3. Chest', bones: ['chest'], color: [0, 255, 0] },
    { name: '4. Upper Chest', bones: ['upperChest'], color: [50, 255, 50] },
    { name: '5. Spine', bones: ['spine'], color: [100, 255, 100] },
    { name: '6. Hips', bones: ['hips'], color: [150, 255, 150] },
    { name: '7. Left Shoulder', bones: ['leftShoulder'], color: [0, 0, 255] },
    { name: '8. Left Upper Arm', bones: ['leftUpperArm'], color: [50, 50, 255] },
    { name: '9. Left Lower Arm', bones: ['leftLowerArm'], color: [100, 100, 255] },
    { name: '10. Left Hand', bones: ['leftHand'], color: [150, 150, 255] },
    { name: '11. Right Shoulder', bones: ['rightShoulder'], color: [255, 255, 0] },
    { name: '12. Right Upper Arm', bones: ['rightUpperArm'], color: [255, 200, 0] },
    { name: '13. Right Lower Arm', bones: ['rightLowerArm'], color: [255, 150, 0] },
    { name: '14. Right Hand', bones: ['rightHand'], color: [255, 100, 0] },
    { name: '15. Left Upper Leg', bones: ['leftUpperLeg'], color: [255, 0, 255] },
    { name: '16. Left Lower Leg', bones: ['leftLowerLeg'], color: [255, 100, 255] },
    { name: '17. Left Foot', bones: ['leftFoot'], color: [255, 150, 255] },
    { name: '18. Right Upper Leg', bones: ['rightUpperLeg'], color: [0, 255, 255] },
    { name: '19. Right Lower Leg', bones: ['rightLowerLeg'], color: [100, 255, 255] },
    { name: '20. Right Foot', bones: ['rightFoot'], color: [150, 255, 255] }
  ]
};



// ==========================================
// FIX 3: Add Camera Controls Setup
// Add this function before createManualUI
// ==========================================

function setupCameraControls(camera, renderer) {
  const controls = new OrbitControls(camera, renderer.domElement);
  controls.enableDamping = true;
  controls.dampingFactor = 0.05;
  controls.screenSpacePanning = false;
  controls.minDistance = 1;
  controls.maxDistance = 20;
  controls.maxPolarAngle = Math.PI;
  
  return { controls };
}



// ==========================================
// FIX 4: Enhanced UI with Paint Mode
// Replace the createManualUI function 2025/12/07
// ==========================================

//////////////////////////////////////////12/13 17:30

// ========================================
// 完全に修正された createManualUI 関数
// Line 75 から Line 537 までを、この全体で置き換えてください
// ========================================

function createManualUI(scene, camera, renderer) {
  console.log('[createManualUI] Creating manual preprocessing UI...');
  
  const uiContainer = document.createElement('div');
  uiContainer.id = 'manual-ui-container';
  uiContainer.style.cssText = `
    position: fixed;
    top: 20px;
    right: 20px;
    background: rgba(0, 0, 0, 0.85);
    padding: 20px;
    border-radius: 10px;
    color: white;
    z-index: 10000;
    max-width: 350px;
    max-height: 90vh;
    overflow-y: auto;
    display: none;
    box-shadow: 0 4px 20px rgba(0,0,0,0.5);
  `;
  
  uiContainer.innerHTML = `
    <h2 style="margin-top: 0;">Manual Preprocessing</h2>
    <div id="manual-status">Loading PLY file...</div>
    
    <!-- Camera Controls Info -->
    <div style="
      margin: 15px 0;
      padding: 10px;
      background: #1a1a2e;
      border-radius: 5px;
      border-left: 3px solid #4CAF50;
      font-size: 12px;
    ">
      <strong>🎮 Camera Controls:</strong><br>
      • Left Mouse: Rotate view<br>
      • Right Mouse: Pan<br>
      • Scroll: Zoom in/out
    </div>
    
    <!-- Step 0: Adjust PLY and Box -->
    <div id="position-adjustment-section" style="display: none; margin-top: 20px;">
      <h3>Step 0: Adjust Position and Bounding Box</h3>
      <p style="font-size: 12px; color: #aaa;">
        First adjust the bounding box to frame your object, then fine-tune position if needed
      </p>
      
      <!-- Bounding Box Info Display -->
      <div id="bbox-info" style="
        margin: 10px 0;
        padding: 10px;
        background: #1a1a2e;
        border-radius: 5px;
        font-size: 11px;
        color: #aaa;
      ">
        <strong>Scene Bounds:</strong><br>
        Size: <span id="scene-size">-</span><br>
        Center: <span id="scene-center">-</span>
      </div>
      
      <!-- Bounding Box Controls -->
      <h4 style="margin: 15px 0 10px 0; color: #4CAF50;">📦 Bounding Box</h4>
      
      <!-- Box Rotation Controls -->
      <h4 style="margin: 15px 0 10px 0; color: #FF9800;">🔄 Box Rotation</h4>
      
      <div style="margin: 10px 0;">
        <label>Rotate Y (Yaw): <span id="box-rot-y-value-step0">0</span>°</label><br>
        <input type="range" id="box-rot-y-step0" min="-180" max="180" step="1" value="0" style="width: 100%;">
      </div>
      <div style="margin: 10px 0;">
        <label>Rotate X (Pitch): <span id="box-rot-x-value-step0">0</span>°</label><br>
        <input type="range" id="box-rot-x-step0" min="-90" max="90" step="1" value="0" style="width: 100%;">
      </div>
      <div style="margin: 10px 0;">
        <label>Rotate Z (Roll): <span id="box-rot-z-value-step0">0</span>°</label><br>
        <input type="range" id="box-rot-z-step0" min="-180" max="180" step="1" value="0" style="width: 100%;">
      </div>





      <div style="margin: 10px 0;">
        <label>Box X Size: <span id="box-x-value-step0">3.0</span>m</label><br>
        <input type="range" id="box-x-step0" min="0.5" max="50.0" step="0.1" value="3.0" style="width: 100%;">
      </div>
      <div style="margin: 10px 0;">
        <label>Box Y Size: <span id="box-y-value-step0">3.0</span>m</label><br>
        <input type="range" id="box-y-step0" min="0.5" max="50.0" step="0.1" value="3.0" style="width: 100%;">
      </div>
      <div style="margin: 10px 0;">
        <label>Box Z Size: <span id="box-z-value-step0">3.0</span>m</label><br>
        <input type="range" id="box-z-step0" min="0.5" max="50.0" step="0.1" value="3.0" style="width: 100%;">
      </div>
      

      <div style="margin: 10px 0;">
        <label>Box X Position: <span id="box-x-pos-value-step0">0.0</span>m</label><br>
        <input type="range" id="box-x-pos-step0" min="-25.0" max="25.0" step="0.1" value="0.0" style="width: 100%;">
      </div>
      <div style="margin: 10px 0;">
        <label>Box Y Position: <span id="box-y-pos-value-step0">0.0</span>m</label><br>
        <input type="range" id="box-y-pos-step0" min="-25.0" max="25.0" step="0.1" value="0.0" style="width: 100%;">
      </div>
      <div style="margin: 10px 0;">
        <label>Box Z Position: <span id="box-z-pos-value-step0">0.0</span>m</label><br>
        <input type="range" id="box-z-pos-step0" min="-25.0" max="25.0" step="0.1" value="0.0" style="width: 100%;">
      </div>
      

      
      <!-- PLY Offset Controls (Optional Fine-Tuning) -->
      <h4 style="margin: 15px 0 10px 0; color: #2196F3;">🎯 Fine-tune PLY Position (Optional)</h4>
      
      <div style="margin: 10px 0;">
        <label>PLY X Offset: <span id="ply-x-value">0.0</span>m</label><br>
        <input type="range" id="ply-x" min="-50.0" max="50.0" step="0.1" value="0.0" style="width: 100%;">
      </div>
      <div style="margin: 10px 0;">
        <label>PLY Y Offset: <span id="ply-y-value">0.0</span>m</label><br>
        <input type="range" id="ply-y" min="-50.0" max="50.0" step="0.1" value="0.0" style="width: 100%;">
      </div>
      <div style="margin: 10px 0;">
        <label>PLY Z Offset: <span id="ply-z-value">0.0</span>m</label><br>
        <input type="range" id="ply-z" min="-50.0" max="50.0" step="0.1" value="0.0" style="width: 100%;">
      </div>

      <button id="reset-all-btn" style="
        margin-top: 10px;
        padding: 8px 15px;
        background: #FF9800;
        color: white;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        width: 48%;
        margin-right: 2%;
      ">Reset All</button>


      <!-- 保存状態表示 -->
      <div id="save-status" style="
        margin: 10px 0;
        padding: 8px;
        background: #1a1a2e;
        border-radius: 5px;
        font-size: 11px;
        color: #4CAF50;
        display: none;
        border-left: 3px solid #4CAF50;
      ">
        💾 Filtered PLY will be saved on confirm
      </div>


      <button id="confirm-box-btn" style="
        margin-top: 10px;
        padding: 8px 15px;
        background: #4CAF50;
        color: white;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        width: 48%;
      ">✓ Confirm & Filter</button>
    </div>

    <!-- ⭐ Step 2のセクションをここに移動(manual-controlsの外へ) -->
    <div id="bone-assignment-section" style="display: none; margin-top: 30px;">
      <h3>Step 2: Assign Splats to Bones</h3>
      
      <!-- Paint Mode Toggle -->
      <div style="
        margin: 15px 0;
        padding: 10px;
        background: #1a1a2e;
        border-radius: 5px;
        border-left: 3px solid #2196F3;
      ">
        <label style="display: flex; align-items: center; cursor: pointer;">
          <input type="checkbox" id="paint-mode-toggle" style="margin-right: 10px;">
          <span>🎨 <strong>Paint Mode</strong> - Click and drag to paint over selections</span>
        </label>
        <div id="paint-mode-hint" style="
          font-size: 11px;
          color: #aaa;
          margin-top: 5px;
          display: none;
        ">
          Hold Shift to erase (unassign splats)
        </div>
      </div>

      <!-- Preset Selection -->
      <div style="margin: 15px 0;">
        <label style="display: block; margin-bottom: 5px; font-weight: bold;">Assignment Mode:</label>
        <select id="preset-selector" style="
          width: 100%;
          padding: 8px;
          font-size: 14px;
          border-radius: 5px;
          background: #333;
          color: white;
          border: 1px solid #555;
          margin-bottom: 10px;
        ">
          <option value="required19">✓ Required (19 parts) - All Essential Bones</option>
        </select>
        <div id="preset-description" style="
          font-size: 11px;
          color: #aaa;
          padding: 8px;
          background: #222;
          border-radius: 5px;
          margin-bottom: 10px;
        "></div>
      </div>
      
      <!-- Bone/Group Selector -->
      <div id="bone-selector-container" style="margin: 15px 0;">
        <label style="display: block; margin-bottom: 5px;">Select Target:</label>
        <select id="bone-selector" style="
          width: 100%;
          padding: 8px;
          font-size: 14px;
          border-radius: 5px;
          background: #333;
          color: white;
          border: 1px solid #555;
        ">
          <option value="">-- Select target --</option>
        </select>
      </div>
      
      <!-- Selection Tools -->
      <div style="margin: 15px 0;">
        <h4 style="margin-bottom: 10px;">Selection Method:</h4>
        
        <div style="margin: 10px 0;">
          <button id="select-sphere-btn" style="
            padding: 8px 15px;
            background: #FF9800;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            width: 100%;
          ">🎯 Select by Sphere (Click on GS)</button>
        </div>
        
      <div style="margin: 10px 0;">
        <label>Selection Radius: <span id="selection-radius-value">0.5</span>m</label><br>
        <input type="range" id="selection-radius" min="0.1" max="10.0" step="0.1" value="0.5" style="width: 100%;">
        <div style="font-size: 10px; color: #888; margin-top: 3px;">
          Range: 0.1m - 10m (適切なサイズに調整してください)
        </div>
      </div>
      
      <!-- Camera Lock Button -->
      <div style="margin: 15px 0; padding: 10px; background: #1a1a2e; border-radius: 5px;">
        <button id="camera-lock-btn" style="
          padding: 10px 15px;
          background: #9C27B0;
          color: white;
          border: none;
          border-radius: 5px;
          cursor: pointer;
          width: 100%;
          font-weight: bold;
        ">🔓 Camera Unlocked (Can Rotate)</button>
        <div style="font-size: 11px; color: #aaa; margin-top: 5px;">
          Lock camera to prevent accidental movement while painting
        </div>
      </div>

      <!-- Statistics -->
      <div id="assignment-info" style="
        margin: 15px 0;
        padding: 10px;
        background: #222;
        border-radius: 5px;
        font-size: 12px;
      ">
        <div>Total Splats: <span id="total-splats">0</span></div>
        <div>Assigned: <span id="assigned-splats">0</span></div>
        <div>Unassigned: <span id="unassigned-splats">0</span></div>
        <div style="margin-top: 5px; padding-top: 5px; border-top: 1px solid #444;">
          Progress: <span id="assignment-progress">0%</span>
        </div>
      </div>
      
      <!-- Assignment List -->
      <div id="bone-assignment-list" style="
        max-height: 150px;
        overflow-y: auto;
        margin: 15px 0;
        padding: 10px;
        background: #222;
        border-radius: 5px;
        font-size: 11px;
      ">
        <div style="color: #888;">No assignments yet</div>
      </div>
      
      <!-- Control Buttons -->
      <div style="margin: 15px 0;">
        <button id="clear-selection-btn" style="
          padding: 8px 15px;
          background: #f44336;
          color: white;
          border: none;
          border-radius: 5px;
          cursor: pointer;
          width: 48%;
          margin-right: 2%;
        ">↶ Undo Last</button>
        
        <button id="undo-all-btn" style="
          padding: 8px 15px;
          background: #FF5722;
          color: white;
          border: none;
          border-radius: 5px;
          cursor: pointer;
          width: 48%;
        ">⟲ Reset All</button>
      </div>
      
      <button id="finalize-btn" style="
        margin-top: 20px;
        padding: 10px 20px;
        background: #2196F3;
        color: white;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        font-size: 16px;
        width: 100%;
      ">✓ Finalize and Save</button>
    </div>
  `;
  
  document.body.appendChild(uiContainer);
  
  let boundingBoxHelper = null;
  
  return {
    container: uiContainer,
    
    initialize: function() {
      console.log('[ManualUI] initialize called');
      return Promise.resolve({ success: true });
    },
    
    show: function() {
      uiContainer.style.display = 'block';
    },
    
    hide: function() {
      uiContainer.style.display = 'none';
    },
    
    setStatus: function(message) {
      const statusEl = document.getElementById('manual-status');
      if (statusEl) statusEl.textContent = message;
    },
    
    showPositionAdjustment: function() {
      const section = document.getElementById('position-adjustment-section');
      if (section) section.style.display = 'block';
    },
    
    hidePositionAdjustment: function() {
      const section = document.getElementById('position-adjustment-section');
      if (section) section.style.display = 'none';
    },
    
    showControls: function() {
      const controlsEl = document.getElementById('manual-controls');
      if (controlsEl) controlsEl.style.display = 'block';
    },
    
    createBoundingBox: function(size = { x: 2, y: 2, z: 2 }, position = { x: 0, y: 0, z: 0 }, rotation = { x: 0, y: 0, z: 0 }) {
      if (boundingBoxHelper) {
        scene.remove(boundingBoxHelper);
      }
      
      const geometry = new THREE.BoxGeometry(size.x, size.y, size.z);
      const edges = new THREE.EdgesGeometry(geometry);
      const material = new THREE.LineBasicMaterial({ color: 0x00ff00, linewidth: 2 });
      boundingBoxHelper = new THREE.LineSegments(edges, material);
      boundingBoxHelper.position.set(position.x, position.y, position.z);
      
      // ⭐ 回転を追加 (Euler angles in radians)
      boundingBoxHelper.rotation.set(rotation.x, rotation.y, rotation.z);
      
      scene.add(boundingBoxHelper);
      
      return boundingBoxHelper;
    },
    
    updateBoundingBox: function(size, position, rotation = { x: 0, y: 0, z: 0 }) {
      if (boundingBoxHelper) {
        scene.remove(boundingBoxHelper);
      }
      return this.createBoundingBox(size, position, rotation);
    },
    
    removeBoundingBox: function() {
      if (boundingBoxHelper) {
        scene.remove(boundingBoxHelper);
        boundingBoxHelper.geometry.dispose();
        boundingBoxHelper.material.dispose();
        boundingBoxHelper = null;
      }
    },
    
    showBoneAssignment: function() {
      const section = document.getElementById('bone-assignment-section');
      if (section) section.style.display = 'block';
    },
    
    cleanup: function() {
      this.removeBoundingBox();
      if (uiContainer && uiContainer.parentNode) {
        document.body.removeChild(uiContainer);
      }
    }
  };
}
/**
 * Bounding Box内のスプラットのみをフィルタリング
 */
/////////////////////////////12/15 17:20 start


// ========================================
// 修正版 filterSplatsByBox 関数(詳細なデバッグ付き)
// Line 594付近を置き換え
// ======================================== 20251214 21:20 fix

// ========================================
// 修正版 filterSplatsByBox 関数
// Line 527-742 を置き換え
// ========================================

// ========================================
// 修正版 filterSplatsByBox 関数(epsilon調整)
// Line 527-742 を置き換え
// ========================================

function filterSplatsByBox(plyData, boxSize, boxPosition, boxRotation = { x: 0, y: 0, z: 0 }) {
  console.log('[filterSplatsByBox] ===== FILTERING START =====');
  console.log('[filterSplatsByBox] Input parameters:');
  console.log('  Box Size:', boxSize);
  console.log('  Box Position:', boxPosition);
  console.log('  Box Rotation (radians):', boxRotation);
  console.log('  Box Rotation (degrees):', {
    x: (boxRotation.x * 180 / Math.PI).toFixed(1) + '°',
    y: (boxRotation.y * 180 / Math.PI).toFixed(1) + '°',
    z: (boxRotation.z * 180 / Math.PI).toFixed(1) + '°'
  });
  console.log('  Total input vertices:', plyData.vertices.length);
  
  // Box半径
  const halfX = boxSize.x / 2;
  const halfY = boxSize.y / 2;
  const halfZ = boxSize.z / 2;
  
  // ⭐ epsilon を大幅に増やす(回転時の数値誤差を吸収)
  const epsilon = 0.01; // 0.0001 → 0.01 (1cm)
  
  console.log('[filterSplatsByBox] Box half-extents:', { halfX, halfY, halfZ });
  console.log('[filterSplatsByBox] Using epsilon:', epsilon);
  
  // 回転行列の作成と逆行列
  const rotationMatrix = new THREE.Matrix4();
  rotationMatrix.makeRotationFromEuler(new THREE.Euler(boxRotation.x, boxRotation.y, boxRotation.z));
  const inverseRotationMatrix = new THREE.Matrix4().copy(rotationMatrix).invert();
  
  console.log('[filterSplatsByBox] Rotation matrices created');
  
  // デバッグ: 境界付近の頂点を記録
  let insideCount = 0;
  let outsideCount = 0;
  const boundaryVertices = [];
  
  // 最初のパス: 統計収集
  plyData.vertices.forEach((vertex, index) => {
    const localPos = new THREE.Vector3(
      vertex.x - boxPosition.x,
      vertex.y - boxPosition.y,
      vertex.z - boxPosition.z
    );
    localPos.applyMatrix4(inverseRotationMatrix);
    
    const inside = (
      localPos.x >= -(halfX + epsilon) && localPos.x <= (halfX + epsilon) &&
      localPos.y >= -(halfY + epsilon) && localPos.y <= (halfY + epsilon) &&
      localPos.z >= -(halfZ + epsilon) && localPos.z <= (halfZ + epsilon)
    );
    
    if (inside) {
      insideCount++;
    } else {
      outsideCount++;
    }
    
    // 境界から0.5m以内の頂点を記録
    const distToEdgeX = Math.min(Math.abs(localPos.x + halfX), Math.abs(localPos.x - halfX));
    const distToEdgeY = Math.min(Math.abs(localPos.y + halfY), Math.abs(localPos.y - halfY));
    const distToEdgeZ = Math.min(Math.abs(localPos.z + halfZ), Math.abs(localPos.z - halfZ));
    const minDistToEdge = Math.min(distToEdgeX, distToEdgeY, distToEdgeZ);
    
    if (minDistToEdge < 0.5) {
      boundaryVertices.push({
        index,
        world: { x: vertex.x, y: vertex.y, z: vertex.z },
        local: { x: localPos.x, y: localPos.y, z: localPos.z },
        inside,
        distToEdge: minDistToEdge
      });
    }
  });
  
  console.log('[DEBUG] Pre-filter summary:');
  console.log('  Inside:', insideCount);
  console.log('  Outside:', outsideCount);
  console.log('  Boundary vertices (within 0.5m):', boundaryVertices.length);
  
  if (boundaryVertices.length > 0) {
    console.log('[DEBUG] Sample boundary vertices:');
    boundaryVertices.slice(0, 20).forEach(v => {
      console.log(`  V${v.index}: world(${v.world.x.toFixed(2)}, ${v.world.y.toFixed(2)}, ${v.world.z.toFixed(2)}) ` +
                  `→ local(${v.local.x.toFixed(2)}, ${v.local.y.toFixed(2)}, ${v.local.z.toFixed(2)}) ` +
                  `→ ${v.inside ? 'IN' : 'OUT'} (dist: ${v.distToEdge.toFixed(3)}m)`);
    });
  }
  
  // サンプル頂点表示(最初の10個)
  console.log('[filterSplatsByBox] Sample vertices (first 10):');
  for (let i = 0; i < Math.min(10, plyData.vertices.length); i++) {
    const v = plyData.vertices[i];
    const localPos = new THREE.Vector3(
      v.x - boxPosition.x,
      v.y - boxPosition.y,
      v.z - boxPosition.z
    );
    localPos.applyMatrix4(inverseRotationMatrix);
    
    const inside = (
      localPos.x >= -(halfX + epsilon) && localPos.x <= (halfX + epsilon) &&
      localPos.y >= -(halfY + epsilon) && localPos.y <= (halfY + epsilon) &&
      localPos.z >= -(halfZ + epsilon) && localPos.z <= (halfZ + epsilon)
    );
    
    // ⭐ どの軸で除外されているかを表示
    const checkX = localPos.x >= -(halfX + epsilon) && localPos.x <= (halfX + epsilon);
    const checkY = localPos.y >= -(halfY + epsilon) && localPos.y <= (halfY + epsilon);
    const checkZ = localPos.z >= -(halfZ + epsilon) && localPos.z <= (halfZ + epsilon);
    
    console.log(`  Vertex ${i}:`, {
      world: { x: v.x.toFixed(3), y: v.y.toFixed(3), z: v.z.toFixed(3) },
      local: { x: localPos.x.toFixed(3), y: localPos.y.toFixed(3), z: localPos.z.toFixed(3) },
      inside: inside,
      checks: `X:${checkX} Y:${checkY} Z:${checkZ}`,
      limits: {
        x: `[${-(halfX + epsilon).toFixed(2)}, ${(halfX + epsilon).toFixed(2)}]`,
        y: `[${-(halfY + epsilon).toFixed(2)}, ${(halfY + epsilon).toFixed(2)}]`,
        z: `[${-(halfZ + epsilon).toFixed(2)}, ${(halfZ + epsilon).toFixed(2)}]`
      }
    });
  }
  
  // ⭐⭐⭐ 実際のフィルタリング ⭐⭐⭐
  const filteredVertices = plyData.vertices.filter((vertex) => {
    const localPos = new THREE.Vector3(
      vertex.x - boxPosition.x,
      vertex.y - boxPosition.y,
      vertex.z - boxPosition.z
    );
    
    localPos.applyMatrix4(inverseRotationMatrix);
    
    const inside = (
      localPos.x >= -(halfX + epsilon) && localPos.x <= (halfX + epsilon) &&
      localPos.y >= -(halfY + epsilon) && localPos.y <= (halfY + epsilon) &&
      localPos.z >= -(halfZ + epsilon) && localPos.z <= (halfZ + epsilon)
    );
    
    return inside;
  });
  
  // フィルタリング結果の統計
  const retentionRate = (filteredVertices.length / plyData.vertices.length * 100).toFixed(1);
  
  console.log('[filterSplatsByBox] ===== FILTERING COMPLETE =====');
  console.log('[filterSplatsByBox] Results:');
  console.log('  Filtered:', filteredVertices.length, '/', plyData.vertices.length);
  console.log('  Retention rate:', retentionRate, '%');
  
  // フィルタリング後の範囲を計算
  if (filteredVertices.length > 0) {
    let minX = Infinity, minY = Infinity, minZ = Infinity;
    let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity;
    
    filteredVertices.forEach(v => {
      minX = Math.min(minX, v.x);
      minY = Math.min(minY, v.y);
      minZ = Math.min(minZ, v.z);
      maxX = Math.max(maxX, v.x);
      maxY = Math.max(maxY, v.y);
      maxZ = Math.max(maxZ, v.z);
    });
    
    console.log('[filterSplatsByBox] Filtered bounds (world space):');
    console.log('  X:', minX.toFixed(3), 'to', maxX.toFixed(3), '(size:', (maxX - minX).toFixed(3), ')');
    console.log('  Y:', minY.toFixed(3), 'to', maxY.toFixed(3), '(size:', (maxY - minY).toFixed(3), ')');
    console.log('  Z:', minZ.toFixed(3), 'to', maxZ.toFixed(3), '(size:', (maxZ - minZ).toFixed(3), ')');
    console.log('  Center:', {
      x: ((minX + maxX) / 2).toFixed(3),
      y: ((minY + maxY) / 2).toFixed(3),
      z: ((minZ + maxZ) / 2).toFixed(3)
    });
    
    console.log('[filterSplatsByBox] ℹ️ Box is rotated - World-space bounds will differ from box size');
  }
  
  // 警告
  if (filteredVertices.length < plyData.vertices.length * 0.1) {
    console.warn('[filterSplatsByBox] ⚠️ WARNING: Less than 10% of splats kept!');
    console.warn('[filterSplatsByBox]   Box may be too small or positioned incorrectly');
  }
  
  if (filteredVertices.length === 0) {
    console.error('[filterSplatsByBox] ❌ ERROR: No vertices passed the filter!');
    console.error('[filterSplatsByBox]   Check box position, size, and rotation');
  }
  
  // ⭐⭐⭐ 重要: 結果を返す ⭐⭐⭐
  return filteredVertices;
}

//////////////////////////////12/15 17:20 end


/**
 * フィルタリングされたスプラットから新しいPLYファイルを作成
 */
function createFilteredPLY(parser, originalHeader, filteredVertices, vertexSize) {
  const newHeader = originalHeader.map(line => {
    if (line.startsWith('element vertex')) {
      return `element vertex ${filteredVertices.length}`;
    }
    return line;
  });
  
  const newPlyData = parser.createPLYFile(newHeader, filteredVertices, vertexSize);
  const blob = new Blob([newPlyData], { type: 'application/octet-stream' });
  return URL.createObjectURL(blob);
}

//////////////////////////////////////////////12/14 13:40 start

/**
 * PLYファイルをダウンロード
 */
function downloadPLY(plyData, filename) {
  const blob = new Blob([plyData], { type: 'application/octet-stream' });
  const url = URL.createObjectURL(blob);
  
  const link = document.createElement('a');
  link.href = url;
  link.download = filename;
  link.style.display = 'none';
  
  document.body.appendChild(link);
  link.click();
  
  // クリーンアップ
  setTimeout(() => {
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  }, 100);
  
  console.log('[downloadPLY] Downloaded:', filename);
}


//////////////////////////////////////////////12/14 13:40 end


      // ========================================
      // Keyboard Controls - Global Variables and Helper Functions
      // ========================================
      let activeKeys = [];

      // Helper functions for matrix operations
      function invert4(a) {
        let b00 = a[0] * a[5] - a[1] * a[4];
        let b01 = a[0] * a[6] - a[2] * a[4];
        let b02 = a[0] * a[7] - a[3] * a[4];
        let b03 = a[1] * a[6] - a[2] * a[5];
        let b04 = a[1] * a[7] - a[3] * a[5];
        let b05 = a[2] * a[7] - a[3] * a[6];
        let b06 = a[8] * a[13] - a[9] * a[12];
        let b07 = a[8] * a[14] - a[10] * a[12];
        let b08 = a[8] * a[15] - a[11] * a[12];
        let b09 = a[9] * a[14] - a[10] * a[13];
        let b10 = a[9] * a[15] - a[11] * a[13];
        let b11 = a[10] * a[15] - a[11] * a[14];
        let det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
        if (!det) return null;
        return [
          (a[5] * b11 - a[6] * b10 + a[7] * b09) / det,
          (a[2] * b10 - a[1] * b11 - a[3] * b09) / det,
          (a[13] * b05 - a[14] * b04 + a[15] * b03) / det,
          (a[10] * b04 - a[9] * b05 - a[11] * b03) / det,
          (a[6] * b08 - a[4] * b11 - a[7] * b07) / det,
          (a[0] * b11 - a[2] * b08 + a[3] * b07) / det,
          (a[14] * b02 - a[12] * b05 - a[15] * b01) / det,
          (a[8] * b05 - a[10] * b02 + a[11] * b01) / det,
          (a[4] * b10 - a[5] * b08 + a[7] * b06) / det,
          (a[1] * b08 - a[0] * b10 - a[3] * b06) / det,
          (a[12] * b04 - a[13] * b02 + a[15] * b00) / det,
          (a[9] * b02 - a[8] * b04 - a[11] * b00) / det,
          (a[5] * b07 - a[4] * b09 - a[6] * b06) / det,
          (a[0] * b09 - a[1] * b07 + a[2] * b06) / det,
          (a[13] * b01 - a[12] * b03 - a[14] * b00) / det,
          (a[8] * b03 - a[9] * b01 + a[10] * b00) / det,
        ];
      }

      function rotate4(a, rad, x, y, z) {
        let len = Math.hypot(x, y, z);
        x /= len;
        y /= len;
        z /= len;
        let s = Math.sin(rad);
        let c = Math.cos(rad);
        let t = 1 - c;
        let b00 = x * x * t + c;
        let b01 = y * x * t + z * s;
        let b02 = z * x * t - y * s;
        let b10 = x * y * t - z * s;
        let b11 = y * y * t + c;
        let b12 = z * y * t + x * s;
        let b20 = x * z * t + y * s;
        let b21 = y * z * t - x * s;
        let b22 = z * z * t + c;
        return [
          a[0] * b00 + a[4] * b01 + a[8] * b02,
          a[1] * b00 + a[5] * b01 + a[9] * b02,
          a[2] * b00 + a[6] * b01 + a[10] * b02,
          a[3] * b00 + a[7] * b01 + a[11] * b02,
          a[0] * b10 + a[4] * b11 + a[8] * b12,
          a[1] * b10 + a[5] * b11 + a[9] * b12,
          a[2] * b10 + a[6] * b11 + a[10] * b12,
          a[3] * b10 + a[7] * b11 + a[11] * b12,
          a[0] * b20 + a[4] * b21 + a[8] * b22,
          a[1] * b20 + a[5] * b21 + a[9] * b22,
          a[2] * b20 + a[6] * b21 + a[10] * b22,
          a[3] * b20 + a[7] * b21 + a[11] * b22,
          ...a.slice(12, 16),
        ];
      }

      function translate4(a, x, y, z) {
        return [
          ...a.slice(0, 12),
          a[0] * x + a[4] * y + a[8] * z + a[12],
          a[1] * x + a[5] * y + a[9] * z + a[13],
          a[2] * x + a[6] * y + a[10] * z + a[14],
          a[3] * x + a[7] * y + a[11] * z + a[15],
        ];
      }

      // Camera manipulation function
      function updateCameraFromKeys(camera, cameraControls) {
        if (activeKeys.length === 0) return;
        
        // Get current camera matrix
        let inv = invert4(camera.matrixWorld.elements);
        if (!inv) return;
        
        const shiftKey = activeKeys.includes("ShiftLeft") || activeKeys.includes("ShiftRight");
        
        // Movement (arrow keys)
        if (activeKeys.includes("ArrowUp")) {
          if (shiftKey) {
            inv = translate4(inv, 0, -0.03, 0);
          } else {
            inv = translate4(inv, 0, 0, 0.1);
          }
        }
        if (activeKeys.includes("ArrowDown")) {
          if (shiftKey) {
            inv = translate4(inv, 0, 0.03, 0);
          } else {
            inv = translate4(inv, 0, 0, -0.1);
          }
        }
        if (activeKeys.includes("ArrowLeft")) {
          inv = translate4(inv, -0.03, 0, 0);
        }
        if (activeKeys.includes("ArrowRight")) {
          inv = translate4(inv, 0.03, 0, 0);
        }
        
        // Camera angle (WASD)
        if (activeKeys.includes("KeyA")) {
          inv = rotate4(inv, -0.01, 0, 1, 0);
        }
        if (activeKeys.includes("KeyD")) {
          inv = rotate4(inv, 0.01, 0, 1, 0);
        }
        if (activeKeys.includes("KeyW")) {
          inv = rotate4(inv, 0.005, 1, 0, 0);
        }
        if (activeKeys.includes("KeyS")) {
          inv = rotate4(inv, -0.005, 1, 0, 0);
        }
        if (activeKeys.includes("KeyQ")) {
          inv = rotate4(inv, 0.01, 0, 0, 1);
        }
        if (activeKeys.includes("KeyE")) {
          inv = rotate4(inv, -0.01, 0, 0, 1);
        }
        
        // Orbit (IJKL)
        if (activeKeys.includes("KeyI") || activeKeys.includes("KeyK") || 
            activeKeys.includes("KeyJ") || activeKeys.includes("KeyL")) {
          let d = 4;
          inv = translate4(inv, 0, 0, d);
          inv = rotate4(
            inv,
            activeKeys.includes("KeyJ") ? -0.05 : activeKeys.includes("KeyL") ? 0.05 : 0,
            0, 1, 0
          );
          inv = rotate4(
            inv,
            activeKeys.includes("KeyI") ? 0.05 : activeKeys.includes("KeyK") ? -0.05 : 0,
            1, 0, 0
          );
          inv = translate4(inv, 0, 0, -d);
        }
        
        // Apply transformation
        const newMatrix = invert4(inv);
        if (newMatrix) {
          camera.matrix.fromArray(newMatrix);
          camera.matrix.decompose(camera.position, camera.quaternion, camera.scale);
          camera.updateMatrixWorld(true);
          
          // Temporarily disable OrbitControls
          if (cameraControls && cameraControls.controls) {
            cameraControls.controls.enabled = false;
            setTimeout(() => {
              if (cameraControls && cameraControls.controls) {
                cameraControls.controls.enabled = true;
              }
            }, 100);
          }
        }
      }

      // Set up keyboard event listeners (call once)
      function setupKeyboardControls() {
        window.addEventListener("keydown", (e) => {
          if (!activeKeys.includes(e.code)) {
            activeKeys.push(e.code);
          }
        });

        window.addEventListener("keyup", (e) => {
          activeKeys = activeKeys.filter((k) => k !== e.code);
        });

        window.addEventListener("blur", () => {
          activeKeys = [];
        });
      }

/////////////////////////////////////////////////

/**
 * Manual preprocessing - メイン関数
 */


export function preprocessManual(vrmPath, gsPath, scene, camera, renderer, stage, useGPU, noBG, noCheck, fileName, savePly) {
  
  console.log('[preprocessManual] ===== FUNCTION CALLED =====');
  console.log('[preprocessManual] Parameters:');
  console.log('  vrmPath:', vrmPath);
  console.log('  gsPath:', gsPath);
  console.log('  fileName:', fileName);
  
  return new Promise((resolve, reject) => {
    console.log('[preprocessManual] Creating Promise...');
    
    try {
      const ui = createManualUI(scene, camera, renderer);
      console.log('[preprocessManual] UI created');
      
      ui.initialize().then(() => {
        console.log('[preprocessManual] UI initialized, starting manual process...');
        
        ui.show();
        ui.setStatus('Loading PLY file...');
        
        // PLYファイルの読み込み
        const parser = new PLYParser();
        let loadingSpinner = new DropInViewer().viewer.loadingSpinner;
        const task = loadingSpinner.addTask('Loading PLY...');
        

        ///////////////////////12/16 12:20

parser.parsePLY(gsPath, true).then((plyData) => {
  console.log('[preprocessManual] PLY loaded:', plyData.vertices.length, 'vertices');
  loadingSpinner.removeTask(task);
  
          // ========================================
          // ⭐ PLY座標系の分析と正規化
          // ========================================
          console.log('[preprocessManual] ===== ANALYZING PLY COORDINATE SYSTEM =====');
          
          // 1. 主成分分析(PCA)を使って点群の主軸を求める
          function computePCA(vertices) {
            // 中心を計算
            const center = { x: 0, y: 0, z: 0 };
            vertices.forEach(v => {
              center.x += v.x;
              center.y += v.y;
              center.z += v.z;
            });
            center.x /= vertices.length;
            center.y /= vertices.length;
            center.z /= vertices.length;
            
            console.log('[PCA] Center:', center);
            
            // 共分散行列を計算
            let cxx = 0, cxy = 0, cxz = 0;
            let cyy = 0, cyz = 0, czz = 0;
            
            vertices.forEach(v => {
              const dx = v.x - center.x;
              const dy = v.y - center.y;
              const dz = v.z - center.z;
              
              cxx += dx * dx;
              cxy += dx * dy;
              cxz += dx * dz;
              cyy += dy * dy;
              cyz += dy * dz;
              czz += dz * dz;
            });
            
            cxx /= vertices.length;
            cxy /= vertices.length;
            cxz /= vertices.length;
            cyy /= vertices.length;
            cyz /= vertices.length;
            czz /= vertices.length;
            
            console.log('[PCA] Covariance matrix:', {
              cxx: cxx.toFixed(2),
              cxy: cxy.toFixed(2),
              cxz: cxz.toFixed(2),
              cyy: cyy.toFixed(2),
              cyz: cyz.toFixed(2),
              czz: czz.toFixed(2)
            });
            
            // 分散の比率から座標系の傾きを判定
            const totalVariance = cxx + cyy + czz;
            const xRatio = cxx / totalVariance;
            const yRatio = cyy / totalVariance;
            const zRatio = czz / totalVariance;
            
            console.log('[PCA] Variance ratios:', {
              x: (xRatio * 100).toFixed(1) + '%',
              y: (yRatio * 100).toFixed(1) + '%',
              z: (zRatio * 100).toFixed(1) + '%'
            });
            
            // 座標系が偏っているか判定
            const isAligned = (
              Math.abs(cxy) < 0.1 * Math.sqrt(cxx * cyy) &&
              Math.abs(cxz) < 0.1 * Math.sqrt(cxx * czz) &&
              Math.abs(cyz) < 0.1 * Math.sqrt(cyy * czz)
            );
            
            console.log('[PCA] Is aligned with world axes:', isAligned);
            
            return {
              center,
              isAligned,
              needsRotation: !isAligned,
              covarianceMatrix: { cxx, cxy, cxz, cyy, cyz, czz }
            };
          }
          
          // 2. 点群を分析
          const pcaResult = computePCA(plyData.vertices);
          
// 完全修正版: PLY中心化(Line 1102-1233を置き換え)

// ========================================
// 完全修正版: PLY中心化(Line 1102-1233を置き換え)
// PCAではなく単純な重心で中心化
// ========================================

//preprocess_manual.js の Line 1100-1290付近

// ========================================
// 完全修正版: PLY中心化(Line 1100-1290を置き換え)
// イミュータブルなオブジェクト生成で確実に中心化
// ========================================
// デバッグ版: PLY中心化(Line 1107-1330を置き換え)

// ========================================
// デバッグ版: PLY中心化(Line 1107-1330を置き換え)
// 各ステップで配列の参照を確認
// ========================================
///// Line 1113-1419 を以下に置き換え ///// Line 1113-1419 を以下に置き換え


// ========================================
// 1. PLYをカメラ座標系のままにする
// Line 1113-1419 を以下に置き換え
// ========================================

console.log('[preprocessManual] ===== PLY DATA LOADED =====');
console.log('[preprocessManual] PLY data is in CAMERA coordinate space');
console.log('  Total vertices:', plyData.vertices.length);

// ⭐ 重要: PLYは既にカメラ座標系なので、そのまま使用
// 中心化も移動も一切しない

// 統計情報のみ計算
let minX = Infinity, minY = Infinity, minZ = Infinity;
let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity;

for (let i = 0; i < plyData.vertices.length; i++) {
  const v = plyData.vertices[i];
  minX = Math.min(minX, v.x);
  minY = Math.min(minY, v.y);
  minZ = Math.min(minZ, v.z);
  maxX = Math.max(maxX, v.x);
  maxY = Math.max(maxY, v.y);
  maxZ = Math.max(maxZ, v.z);
}

console.log('[preprocessManual] PLY bounds (CAMERA space):');
console.log('  Min:', { x: minX.toFixed(3), y: minY.toFixed(3), z: minZ.toFixed(3) });
console.log('  Max:', { x: maxX.toFixed(3), y: maxY.toFixed(3), z: maxZ.toFixed(3) });
console.log('  Center:', { 
  x: ((minX + maxX) / 2).toFixed(3), 
  y: ((minY + maxY) / 2).toFixed(3), 
  z: ((minZ + maxZ) / 2).toFixed(3) 
});

console.log('[preprocessManual] ✓ PLY coordinates preserved (CAMERA space)');
// ⭐ ここに追加 12/17 22:00 ⭐
console.log('[preprocessManual] ===== COORDINATE SYSTEM CHECK =====');
const worldOriginInCameraSpace = new THREE.Vector3(0, 0, 0);
worldOriginInCameraSpace.applyMatrix4(camera.matrixWorldInverse);
console.log('  World origin (0,0,0) in camera space:', {
  x: worldOriginInCameraSpace.x.toFixed(3),
  y: worldOriginInCameraSpace.y.toFixed(3),
  z: worldOriginInCameraSpace.z.toFixed(3)
});
console.log('  Camera position in world space:', {
  x: camera.position.x.toFixed(3),
  y: camera.position.y.toFixed(3),
  z: camera.position.z.toFixed(3)
});

// ========================================
// 2. 世界座標→カメラ座標の変換関数
// ========================================

/**
 * 世界座標をカメラ座標に変換
 * @param {THREE.Vector3} worldPos - 世界座標の位置
 * @param {THREE.Camera} camera - カメラオブジェクト
 * @returns {THREE.Vector3} カメラ座標での位置
 */
function worldToCameraSpace(worldPos, camera) {
  const cameraPos = worldPos.clone();
  
  // カメラのビュー行列を更新
  camera.updateMatrixWorld();
  
  // 世界座標→カメラ座標の変換
  // ビュー行列 = カメラのmatrixWorldInverse
  cameraPos.applyMatrix4(camera.matrixWorldInverse);
  
  return cameraPos;
}

/**
 * 世界座標のBOXをカメラ座標のBOXに変換
 * @param {Object} worldBox - { min: {x,y,z}, max: {x,y,z} }
 * @param {THREE.Camera} camera - カメラオブジェクト
 * @returns {Object} カメラ座標のBOX { min: {x,y,z}, max: {x,y,z} }
 */
function transformBoxToCameraSpace(worldBox, camera) {
  const { min, max } = worldBox;
  
  // 8頂点を世界座標で定義
  const vertices = [
    new THREE.Vector3(min.x, min.y, min.z),
    new THREE.Vector3(max.x, min.y, min.z),
    new THREE.Vector3(max.x, max.y, min.z),
    new THREE.Vector3(min.x, max.y, min.z),
    new THREE.Vector3(min.x, min.y, max.z),
    new THREE.Vector3(max.x, min.y, max.z),
    new THREE.Vector3(max.x, max.y, max.z),
    new THREE.Vector3(min.x, max.y, max.z)
  ];
  
  // 各頂点をカメラ座標に変換
  const cameraVertices = vertices.map(v => worldToCameraSpace(v, camera));
  
  // カメラ座標での新しいAABB(軸並行境界ボックス)を計算
  let cMinX = Infinity, cMinY = Infinity, cMinZ = Infinity;
  let cMaxX = -Infinity, cMaxY = -Infinity, cMaxZ = -Infinity;
  
  cameraVertices.forEach(v => {
    cMinX = Math.min(cMinX, v.x);
    cMinY = Math.min(cMinY, v.y);
    cMinZ = Math.min(cMinZ, v.z);
    cMaxX = Math.max(cMaxX, v.x);
    cMaxY = Math.max(cMaxY, v.y);
    cMaxZ = Math.max(cMaxZ, v.z);
  });
  
  return {
    min: { x: cMinX, y: cMinY, z: cMinZ },
    max: { x: cMaxX, y: cMaxY, z: cMaxZ }
  };
}

console.log('[preprocessManual] ✓ Coordinate transformation functions defined');


// ========================================
// 3. BOXをカメラ座標系で作成・表示
// ========================================

/**
 * カメラ座標系でBOXを作成
 * @param {Object} cameraBox - { min: {x,y,z}, max: {x,y,z} } カメラ座標
 * @param {THREE.Scene} scene - Three.jsシーン
 * @returns {THREE.LineSegments} BOXオブジェクト
 */
function createCameraSpaceBox(cameraBox, scene) {
  const { min, max } = cameraBox;
  
  const size = {
    x: max.x - min.x,
    y: max.y - min.y,
    z: max.z - min.z
  };
  
  const center = {
    x: (min.x + max.x) / 2,
    y: (min.y + max.y) / 2,
    z: (min.z + max.z) / 2
  };
  
  console.log('[createCameraSpaceBox] Creating box in CAMERA space:');
  console.log('  Min:', min);
  console.log('  Max:', max);
  console.log('  Center:', center);
  console.log('  Size:', size);
  
  // BOXジオメトリを作成
  const geometry = new THREE.BoxGeometry(size.x, size.y, size.z);
  const edges = new THREE.EdgesGeometry(geometry);
  const material = new THREE.LineBasicMaterial({ color: 0x00ff00, linewidth: 2 });
  const boxHelper = new THREE.LineSegments(edges, material);
  
  // ⭐ 重要: カメラ座標系で配置
  // カメラ座標系 = ローカル座標系なので、シーンに直接追加
  boxHelper.position.set(center.x, center.y, center.z);
  
  scene.add(boxHelper);
  
  console.log('[createCameraSpaceBox] ✓ Box added in camera space');
  
  return boxHelper;
}


// ========================================
// 4. フィルタリング関数(カメラ座標系)
// Line 527-742 を以下に置き換え
// ========================================

/**
 * カメラ座標系のBOX内のスプラットをフィルタリング
 * @param {Object} plyData - PLYデータ(camera coordinates)
 * @param {Object} cameraBox - { min: {x,y,z}, max: {x,y,z} } カメラ座標
 * @returns {Array} フィルタリングされた頂点配列
 */
function filterSplatsByCameraBox(plyData, cameraBox) {
  console.log('[filterSplatsByCameraBox] ===== FILTERING START =====');
  console.log('[filterSplatsByCameraBox] CAMERA-space box:');
  console.log('  Min:', cameraBox.min);
  console.log('  Max:', cameraBox.max);
  console.log('  Total vertices:', plyData.vertices.length);
  
  const { min, max } = cameraBox;
  
  // ⭐ PLYもカメラ座標、BOXもカメラ座標なので、シンプルな範囲チェック
  const filteredVertices = plyData.vertices.filter(vertex => {
    return (
      vertex.x >= min.x && vertex.x <= max.x &&
      vertex.y >= min.y && vertex.y <= max.y &&
      vertex.z >= min.z && vertex.z <= max.z
    );
  });
  
  const retentionRate = (filteredVertices.length / plyData.vertices.length * 100).toFixed(1);
  
  console.log('[filterSplatsByCameraBox] ===== FILTERING COMPLETE =====');
  console.log('  Filtered:', filteredVertices.length, '/', plyData.vertices.length);
  console.log('  Retention rate:', retentionRate, '%');
  
  if (filteredVertices.length > 0) {
    let fMinX = Infinity, fMinY = Infinity, fMinZ = Infinity;
    let fMaxX = -Infinity, fMaxY = -Infinity, fMaxZ = -Infinity;
    
    filteredVertices.forEach(v => {
      fMinX = Math.min(fMinX, v.x);
      fMinY = Math.min(fMinY, v.y);
      fMinZ = Math.min(fMinZ, v.z);
      fMaxX = Math.max(fMaxX, v.x);
      fMaxY = Math.max(fMaxY, v.y);
      fMaxZ = Math.max(fMaxZ, v.z);
    });
    
    console.log('[filterSplatsByCameraBox] Filtered bounds (camera space):');
    console.log('  X:', fMinX.toFixed(3), 'to', fMaxX.toFixed(3));
    console.log('  Y:', fMinY.toFixed(3), 'to', fMaxY.toFixed(3));
    console.log('  Z:', fMinZ.toFixed(3), 'to', fMaxZ.toFixed(3));
  }
  

  
  return filteredVertices;
}


// ========================================
// 5. 統合処理:世界座標のBOX → フィルタリング
// ========================================

/**
 * 世界座標のBOXでPLYをフィルタリング(完全な処理)
 * @param {Object} plyData - PLYデータ(camera coordinates)
 * @param {Object} worldBox - 世界座標のBOX { min: {x,y,z}, max: {x,y,z} }
 * @param {THREE.Camera} camera - カメラオブジェクト
 * @param {THREE.Scene} scene - Three.jsシーン
 * @returns {Object} { filteredVertices: Array, cameraBox: Object, boxHelper: Object }
 */
function filterWithWorldBox(plyData, worldBox, camera, scene) {
  console.log('[filterWithWorldBox] ===== COMPLETE FILTERING PROCESS =====');
  
  // Step 1: 世界座標のBOXをカメラ座標に変換
  console.log('[filterWithWorldBox] Step 1: Transform box to camera space');
  console.log('  World box:', worldBox);
  
  const cameraBox = transformBoxToCameraSpace(worldBox, camera);
  
  console.log('[filterWithWorldBox] ✓ Transformed to camera space:', cameraBox);
  
  // Step 2: カメラ座標でBOXを表示
  console.log('[filterWithWorldBox] Step 2: Display box in camera space');
  
  const boxHelper = createCameraSpaceBox(cameraBox, scene);
  
  console.log('[filterWithWorldBox] ✓ Box displayed');
  
  // Step 3: カメラ座標でフィルタリング
  console.log('[filterWithWorldBox] Step 3: Filter splats in camera space');
  
  const filteredVertices = filterSplatsByCameraBox(plyData, cameraBox);
  
  console.log('[filterWithWorldBox] ✓ Filtering complete:', filteredVertices.length, 'vertices');
  
  console.log('[filterWithWorldBox] ===== PROCESS COMPLETE =====');
  
  return {
    filteredVertices,
    cameraBox,
    boxHelper
  };
}


// ========================================
// UI統合版: confirm-box-btn イベントリスナー
// Line 1608付近を以下に置き換え
// ========================================

const confirmBoxBtn = document.getElementById('confirm-box-btn');
if (confirmBoxBtn) {
  confirmBoxBtn.addEventListener('click', async () => {
    console.log('\n\n');
    console.log('═══════════════════════════════════════════════════════');
    console.log('           CONFIRM BOX BUTTON CLICKED');
    console.log('═══════════════════════════════════════════════════════');
    
    // ⭐ Step 1: UIから世界座標のBOX設定を取得
    const worldBoxSize = {
      x: parseFloat(document.getElementById('box-x-step0').value),
      y: parseFloat(document.getElementById('box-y-step0').value),
      z: parseFloat(document.getElementById('box-z-step0').value)
    };
    
    const worldBoxPosition = {
      x: parseFloat(document.getElementById('box-x-pos-step0').value),
      y: parseFloat(document.getElementById('box-y-pos-step0').value),
      z: parseFloat(document.getElementById('box-z-pos-step0').value)
    };
    
    // ⭐ 世界座標でのBOX範囲を計算
    const worldBox = {
      min: {
        x: worldBoxPosition.x - worldBoxSize.x / 2,
        y: worldBoxPosition.y - worldBoxSize.y / 2,
        z: worldBoxPosition.z - worldBoxSize.z / 2
      },
      max: {
        x: worldBoxPosition.x + worldBoxSize.x / 2,
        y: worldBoxPosition.y + worldBoxSize.y / 2,
        z: worldBoxPosition.z + worldBoxSize.z / 2
      }
    };
    
    console.log('[CONFIRM] World box (from UI):', worldBox);
    
    // ⭐ Step 2: 世界座標BOXをカメラ座標に変換
    console.log('[CONFIRM] Transforming box to camera space...');
    
    const cameraBox = transformBoxToCameraSpace(worldBox, camera);
    
    console.log('[CONFIRM] Camera box (transformed):', cameraBox);
    
    // ⭐ Step 3: カメラ座標でBOXを表示
    console.log('[CONFIRM] Displaying box in camera space...');
    
    ui.removeBoundingBox(); // 古いBOXを削除
    
    ///// step2におけるbox出現の理由?
    // const boxHelper = createCameraSpaceBox(cameraBox, scene);
    
    // ⭐ Step 4: カメラ座標でフィルタリング
    console.log('[CONFIRM] Filtering splats in camera space...');
    
    const filteredVertices = filterSplatsByCameraBox(plyData, cameraBox);
    
    //console.log('[CONFIRM] ✓ Filtered', filteredVertices.length, 'vertices');
    console.log('═══════════════════════════════════════════════════════');
    console.log('           BOX FILTERING COMPLETE');
    console.log('═══════════════════════════════════════════════════════');
    
    // ⭐ 以降は元のコード(STEP 5以降)と同様
    // フィルタリング後のPLY保存、GS再読み込み、VRM読み込み等...
  });
}



///// Line 1113-1419 を以下に置き換え ///// Line 1113-1419 を以下に置き換え


        /////////////////////////////ここから

        GVRM.initGS(gsPath, undefined, undefined, scene).then((gs) => {
          console.log('[preprocessManual] GS initialized');
          
          // ========================================
          // ⭐ PLY補正が適用されている場合、GSにも同じ変換を適用
          // ========================================
          if (window.plyAlignmentApplied && window.plyAlignmentMatrix) {
            console.log('[preprocessManual] Applying alignment transform to GS display...');
            
            const gsScene = gs.viewer.splatMesh.scenes[0];
            
            // 補正行列をGS Sceneに適用
            gsScene.matrixAutoUpdate = false;
            gsScene.matrix.copy(window.plyAlignmentMatrix);
            gsScene.matrixWorldNeedsUpdate = true;
            gsScene.updateMatrixWorld(true);
            
            console.log('[preprocessManual] ✓ GS display aligned with PLY data');
            console.log('[preprocessManual] GS Scene matrix:', gsScene.matrix.elements.slice(0, 4));
          } else {
            console.log('[preprocessManual] No alignment transform needed for GS');
          }

          // ========================================
          // ⭐ 1. カメラコントロールを初期化(グローバルに保存)
          // ========================================
          if (!window.globalCameraControls) {
            window.globalCameraControls = setupCameraControls(camera, renderer);
            console.log('[preprocessManual] ✓ Camera controls created and saved globally');
          } else {
            console.log('[preprocessManual] Using existing global camera controls');
          }
          
          // ========================================
          // ⭐ 2. キーボードコントロールを初期化
          // ========================================
          setupKeyboardControls();
          console.log('[preprocessManual] Keyboard controls initialized');

          // ========================================
          // ⭐ 3. アニメーションループを開始
          // ========================================
          
          // グローバルなカメラロック状態
          if (!window.cameraLockState) {
            window.cameraLockState = { 
              locked: false,
              frameCount: 0
            };
          }

          let animationId = null;
          function animateControls() {
            animationId = requestAnimationFrame(animateControls);
            
            window.cameraLockState.frameCount++;
            
            // キーボードコントロールの更新(カメラロック時は無効化)
            if (!window.cameraLockState.locked) {
              updateCameraFromKeys(camera, window.globalCameraControls);
            }
            
            // ⭐⭐⭐ 重要:カメラがロックされている場合はOrbitControlsを強制的に無効化し続ける
            if (window.cameraLockState.locked) {
              if (window.globalCameraControls && window.globalCameraControls.controls) {
                window.globalCameraControls.controls.enabled = false;
              }
            } else {
              // カメラがアンロックされている場合のみ更新
              if (window.globalCameraControls && window.globalCameraControls.controls) {
                window.globalCameraControls.controls.update();
              }
            }
            
            // 10秒ごとに状態をログ出力(デバッグ用)
            if (window.cameraLockState.frameCount % 600 === 0) {
              console.log('[animateControls] Status check:', {
                locked: window.cameraLockState.locked,
                controlsEnabled: window.globalCameraControls?.controls?.enabled,
                frame: window.cameraLockState.frameCount
              });
            }
            
            renderer.render(scene, camera);
          }

          animateControls();
          console.log('[preprocessManual] ✓ Animation loop started with camera lock support');

          ////ここまで

          // Cleanup function to stop animation
          const cleanupAnimation = () => {
            if (animationId) {
              cancelAnimationFrame(animationId);
              animationId = null;
            }
          };
          
          // ========================================
          // ⭐ 4. カメラをPLYに合わせて調整(cameraControls初期化後)
          // ========================================
          /// add 12/17 13:30

          const sceneSize = {
            x: maxX - minX,
            y: maxY - minY,
            z: maxZ - minZ
          };

          const sceneCenter = {
            x: (maxX + minX) / 2,
            y: (maxY + minY) / 2,
            z: (maxZ + minZ) / 2
          };

/////////////////////add 13:40

          // Initialize box and PLY offset variables
          let boxSize = { 
            x: sceneSize.x * 1.2,
            y: sceneSize.y * 1.2, 
            z: sceneSize.z * 1.2 
          };

          let boxPosition = { x: 0, y: 0, z: 0 };
          let boxRotation = { x: 0, y: 0, z: 0 };
          let plyOffset = { x: 0, y: 0, z: 0 };

          // Calculate camera position
          const maxDim = Math.max(sceneSize.x, sceneSize.y, sceneSize.z);
          const distance = maxDim * 2.0;

          camera.position.set(0, maxDim * 0.3, distance);
          camera.lookAt(0, 0, 0);
          camera.updateProjectionMatrix();
////
          window.globalCameraControls.controls.target.set(0, 0, 0);
          window.globalCameraControls.controls.update();

          console.log('[preprocessManual] Camera positioned at:', {
            x: camera.position.x.toFixed(2),
            y: camera.position.y.toFixed(2),
            z: camera.position.z.toFixed(2)
          });
////

          console.log('[preprocessManual] Initial box setup - size:', boxSize);


/////////////////////end of add 13:40


          // Display scene info in UI
          const sceneSizeEl = document.getElementById('scene-size');
          const sceneCenterEl = document.getElementById('scene-center');
          if (sceneSizeEl) {
            sceneSizeEl.textContent = `${sceneSize.x.toFixed(1)}m × ${sceneSize.y.toFixed(1)}m × ${sceneSize.z.toFixed(1)}m`;
          }
          if (sceneCenterEl) {
            sceneCenterEl.textContent = `(${sceneCenter.x.toFixed(1)}, ${sceneCenter.y.toFixed(1)}, ${sceneCenter.z.toFixed(1)})`;
          }

          const gsScene = gs.viewer.splatMesh.scenes[0];

          // Create initial bounding box
          ui.createBoundingBox(boxSize, boxPosition, boxRotation);

          // ========================================
          // ⭐ 7. UIスライダーの初期値を更新
          // ========================================
          if (document.getElementById('box-x-step0')) {
            document.getElementById('box-x-step0').value = boxSize.x.toFixed(1);
            document.getElementById('box-x-value-step0').textContent = boxSize.x.toFixed(1);
            
            document.getElementById('box-y-step0').value = boxSize.y.toFixed(1);
            document.getElementById('box-y-value-step0').textContent = boxSize.y.toFixed(1);
            
            document.getElementById('box-z-step0').value = boxSize.z.toFixed(1);
            document.getElementById('box-z-value-step0').textContent = boxSize.z.toFixed(1);
            
            document.getElementById('box-x-pos-step0').value = boxPosition.x.toFixed(1);
            document.getElementById('box-x-pos-value-step0').textContent = boxPosition.x.toFixed(1);
            
            document.getElementById('box-y-pos-step0').value = boxPosition.y.toFixed(1);
            document.getElementById('box-y-pos-value-step0').textContent = boxPosition.y.toFixed(1);
            
            document.getElementById('box-z-pos-step0').value = boxPosition.z.toFixed(1);
            document.getElementById('box-z-pos-value-step0').textContent = boxPosition.z.toFixed(1);
            
            console.log('[preprocessManual] UI sliders initialized to PLY-aligned values');
          }
          
          ui.setStatus('Step 0: Adjust bounding box to frame your object');
          ui.showPositionAdjustment();
          
          console.log('[preprocessManual] ✓ Camera and Box aligned to PLY');

          // ========================================
          // ⭐ 8. 以降は元のコード(スライダー設定など)
          // ========================================
          
          // Box size sliders
          const setupBoxSizeSlider = (id, valueId, axis) => {
            const slider = document.getElementById(id);
            const valueDisplay = document.getElementById(valueId);
            
            if (slider && valueDisplay) {
              slider.addEventListener('input', (e) => {
                const value = parseFloat(e.target.value);
                valueDisplay.textContent = value.toFixed(1);
                boxSize[axis] = value;
                ui.updateBoundingBox(boxSize, boxPosition, boxRotation);
              });
            }
          };

          // Box position sliders
          const setupBoxPosSlider = (id, valueId, axis) => {
            const slider = document.getElementById(id);
            const valueDisplay = document.getElementById(valueId);
            
            if (slider && valueDisplay) {
              slider.addEventListener('input', (e) => {
                const value = parseFloat(e.target.value);
                valueDisplay.textContent = value.toFixed(1);
                boxPosition[axis] = value;
                ui.updateBoundingBox(boxSize, boxPosition, boxRotation);
              });
            }
          };

          // Box rotation sliders
          const setupBoxRotSlider = (id, valueId, axis) => {
            const slider = document.getElementById(id);
            const valueDisplay = document.getElementById(valueId);
            
            if (slider && valueDisplay) {
              slider.addEventListener('input', (e) => {
                const degrees = parseFloat(e.target.value);
                valueDisplay.textContent = degrees.toFixed(0);
                boxRotation[axis] = degrees * Math.PI / 180;
                ui.updateBoundingBox(boxSize, boxPosition, boxRotation);
              });
            }
          };

          // PLY offset sliders
          const setupPlyOffsetSlider = (id, valueId, axis) => {
            const slider = document.getElementById(id);
            const valueDisplay = document.getElementById(valueId);
            
            if (slider && valueDisplay) {
              slider.addEventListener('input', (e) => {
                const value = parseFloat(e.target.value);
                valueDisplay.textContent = value.toFixed(1);
                plyOffset[axis] = value;
                gsScene.position[axis] = value;
                gsScene.updateMatrixWorld();
              });
            }
          };

          // Setup all sliders
          setupBoxSizeSlider('box-x-step0', 'box-x-value-step0', 'x');
          setupBoxSizeSlider('box-y-step0', 'box-y-value-step0', 'y');
          setupBoxSizeSlider('box-z-step0', 'box-z-value-step0', 'z');

          setupBoxPosSlider('box-x-pos-step0', 'box-x-pos-value-step0', 'x');
          setupBoxPosSlider('box-y-pos-step0', 'box-y-pos-value-step0', 'y');
          setupBoxPosSlider('box-z-pos-step0', 'box-z-pos-value-step0', 'z');

          setupBoxRotSlider('box-rot-y-step0', 'box-rot-y-value-step0', 'y');
          setupBoxRotSlider('box-rot-x-step0', 'box-rot-x-value-step0', 'x');
          setupBoxRotSlider('box-rot-z-step0', 'box-rot-z-value-step0', 'z');

          setupPlyOffsetSlider('ply-x', 'ply-x-value', 'x');
          setupPlyOffsetSlider('ply-y', 'ply-y-value', 'y');
          setupPlyOffsetSlider('ply-z', 'ply-z-value', 'z');

          // Reset button
          const resetAllBtn = document.getElementById('reset-all-btn');
          if (resetAllBtn) {
            resetAllBtn.addEventListener('click', () => {
              // Reset rotation
              boxRotation = { x: 0, y: 0, z: 0 };
              document.getElementById('box-rot-y-step0').value = 0;
              document.getElementById('box-rot-x-step0').value = 0;
              document.getElementById('box-rot-z-step0').value = 0;
              document.getElementById('box-rot-y-value-step0').textContent = '0';
              document.getElementById('box-rot-x-value-step0').textContent = '0';
              document.getElementById('box-rot-z-value-step0').textContent = '0';

              // Reset box to PLY-aligned defaults
              boxSize = { 
                x: size.x * 0.5,
                y: size.y * 0.5, 
                z: size.z * 0.5 
              };
              boxPosition = { 
                x: center.x, 
                y: center.y, 
                z: center.z 
              };
              
              // Update UI
              document.getElementById('box-x-step0').value = boxSize.x.toFixed(1);
              document.getElementById('box-y-step0').value = boxSize.y.toFixed(1);
              document.getElementById('box-z-step0').value = boxSize.z.toFixed(1);
              document.getElementById('box-x-value-step0').textContent = boxSize.x.toFixed(1);
              document.getElementById('box-y-value-step0').textContent = boxSize.y.toFixed(1);
              document.getElementById('box-z-value-step0').textContent = boxSize.z.toFixed(1);

              document.getElementById('box-x-pos-step0').value = boxPosition.x.toFixed(1);
              document.getElementById('box-y-pos-step0').value = boxPosition.y.toFixed(1);
              document.getElementById('box-z-pos-step0').value = boxPosition.z.toFixed(1);
              document.getElementById('box-x-pos-value-step0').textContent = boxPosition.x.toFixed(1);
              document.getElementById('box-y-pos-value-step0').textContent = boxPosition.y.toFixed(1);
              document.getElementById('box-z-pos-value-step0').textContent = boxPosition.z.toFixed(1);
              
              // Reset PLY offset
              plyOffset = { x: 0, y: 0, z: 0 };
              document.getElementById('ply-x').value = 0;
              document.getElementById('ply-y').value = 0;
              document.getElementById('ply-z').value = 0;
              document.getElementById('ply-x-value').textContent = '0.0';
              document.getElementById('ply-y-value').textContent = '0.0';
              document.getElementById('ply-z-value').textContent = '0.0';
              
              gsScene.position.set(0, 0, 0);
              gsScene.updateMatrixWorld();
              ui.updateBoundingBox(boxSize, boxPosition, boxRotation);
            });
          }


////////////////////////////////////////////////これの上が書き換えられる    

              const confirmBoxBtn = document.getElementById('confirm-box-btn');
              if (confirmBoxBtn) {
                confirmBoxBtn.addEventListener('click', async () => {
                  console.log('\n\n');
                  console.log('═══════════════════════════════════════════════════════');
                  console.log('           CONFIRM BOX BUTTON CLICKED');
                  console.log('═══════════════════════════════════════════════════════');
                  
                  // ⭐⭐⭐ 重要: 現在のBOX設定を明示的に取得 ⭐⭐⭐
                  const currentBoxSize = {
                    x: parseFloat(document.getElementById('box-x-step0').value),
                    y: parseFloat(document.getElementById('box-y-step0').value),
                    z: parseFloat(document.getElementById('box-z-step0').value)
                  };
                  
                  const currentBoxPosition = {
                    x: parseFloat(document.getElementById('box-x-pos-step0').value),
                    y: parseFloat(document.getElementById('box-y-pos-step0').value),
                    z: parseFloat(document.getElementById('box-z-pos-step0').value)
                  };
                  
                  const currentBoxRotation = {
                    x: parseFloat(document.getElementById('box-rot-x-step0').value) * Math.PI / 180,
                    y: parseFloat(document.getElementById('box-rot-y-step0').value) * Math.PI / 180,
                    z: parseFloat(document.getElementById('box-rot-z-step0').value) * Math.PI / 180
                  };
                  
                  const currentPlyOffset = {
                    x: parseFloat(document.getElementById('ply-x').value),
                    y: parseFloat(document.getElementById('ply-y').value),
                    z: parseFloat(document.getElementById('ply-z').value)
                  };
                  
                  // 現在のBOX設定をログ
                  console.log('[STEP 1] Current BOX Settings (from UI):');
                  console.log('  Box Size:', currentBoxSize);
                  console.log('  Box Position:', currentBoxPosition);
                  console.log('  Box Rotation (radians):', currentBoxRotation);
                  console.log('  Box Rotation (degrees):', {
                    x: (currentBoxRotation.x * 180 / Math.PI).toFixed(1) + '°',
                    y: (currentBoxRotation.y * 180 / Math.PI).toFixed(1) + '°',
                    z: (currentBoxRotation.z * 180 / Math.PI).toFixed(1) + '°'
                  });
                  console.log('  PLY Offset:', currentPlyOffset);
                  
                  // ⭐ デバッグ: 外側の変数も確認
                  console.log('[STEP 1] Outer scope variables (for comparison):');
                  console.log('  boxSize:', boxSize);
                  console.log('  boxPosition:', boxPosition);
                  console.log('  boxRotation:', boxRotation);
                  console.log('  plyOffset:', plyOffset);
                  
                  ////////////////////////////////////////////////////0123 start
                  // ⭐ 修正: 中心化後のPLYデータの範囲を確認
                  console.log('[STEP 2] Centered PLY Data (should be ~0,0,0):');
                  console.log('  Total vertices:', plyData.vertices.length);

                  let centeredMinX = Infinity, centeredMinY = Infinity, centeredMinZ = Infinity;
                  let centeredMaxX = -Infinity, centeredMaxY = -Infinity, centeredMaxZ = -Infinity;

                  plyData.vertices.forEach(v => {
                    centeredMinX = Math.min(centeredMinX, v.x);
                    centeredMinY = Math.min(centeredMinY, v.y);
                    centeredMinZ = Math.min(centeredMinZ, v.z);
                    centeredMaxX = Math.max(centeredMaxX, v.x);
                    centeredMaxY = Math.max(centeredMaxY, v.y);
                    centeredMaxZ = Math.max(centeredMaxZ, v.z);
                  });



                  const centeredCenter = {
                    x: (centeredMinX + centeredMaxX) / 2,
                    y: (centeredMinY + centeredMaxY) / 2,
                    z: (centeredMinZ + centeredMaxZ) / 2
                  };


                  
                  cleanupAnimation();
                  
                  // PLY Offsetの適用
                  if (currentPlyOffset.x !== 0 || currentPlyOffset.y !== 0 || currentPlyOffset.z !== 0) {
                    console.log('[STEP 3] Applying PLY offset:', currentPlyOffset);
                    
                    plyData.vertices.forEach(vertex => {
                      vertex.x += currentPlyOffset.x;
                      vertex.y += currentPlyOffset.y;
                      vertex.z += currentPlyOffset.z;
                    });
                    
                    console.log('[STEP 3] ✓ PLY data updated with offset');
                    
                    const newHeader = plyData.header;
                    const newPlyData = parser.createPLYFile(newHeader, plyData.vertices, plyData.vertexSize);
                    const blob = new Blob([newPlyData], { type: 'application/octet-stream' });
                    const adjustedPlyUrl = URL.createObjectURL(blob);
                    
                    await gs.viewer.dispose();
                    gs = await GVRM.initGS(adjustedPlyUrl, undefined, undefined, scene);
                    
                    // ⭐ 外側の変数も更新(念のため)
                    plyOffset = { x: 0, y: 0, z: 0 };


                    // confirm-box-btn のイベントリスナー内に追加

                    // フィルタリング後、結果を視覚化
                    if (filteredVertices.length > 0) {
                      // 色を変えて表示
                      filteredIndices.forEach(idx => {
                        filteredGs.colors[idx * 4 + 0] = 0;
                        filteredGs.colors[idx * 4 + 1] = 255;
                        filteredGs.colors[idx * 4 + 2] = 0;
                      });
                      
                      filteredGs.splatMesh.updateDataTexturesFromBaseData(0, filteredGs.splatCount - 1);
                      
                      const confirmResult = confirm(
                        `Filtered ${filteredVertices.length} splats (shown in green).\n\n` +
                        `Does the green area match the box?\n\n` +
                        `OK = Continue | Cancel = Adjust box again`
                      );
                      
                      if (!confirmResult) {
                        // Box設定に戻る
                        ui.showPositionAdjustment();
                        return;
                      }
                    }


                  } else {
                    console.log('[STEP 3] No PLY offset to apply');
                  }

                  ui.hidePositionAdjustment();
                  ui.setStatus('Filtering splats with bounding box...');


      ///////////////////////////////////////13:47 start

                  console.log('[STEP 4] ⭐ Transforming Box coordinates to GS local space');

                  // GS Scene の変換行列を取得
                  const gsScene = gs.viewer.splatMesh.scenes[0];
                  gsScene.updateMatrixWorld(true);

                  // Box Position を Three.js Vector3 に変換
                  const boxWorldPosition = new THREE.Vector3(
                    currentBoxPosition.x,
                    currentBoxPosition.y,
                    currentBoxPosition.z
                  );

                  // GS の逆行列を適用してローカル空間に変換
                  const gsInverseMatrix = new THREE.Matrix4().copy(gsScene.matrixWorld).invert();
                  const boxLocalPosition = boxWorldPosition.applyMatrix4(gsInverseMatrix);

                  console.log('[STEP 4] Box position transformation:');
                  console.log('  World space:', currentBoxPosition);
                  console.log('  GS local space:', {
                    x: boxLocalPosition.x.toFixed(3),
                    y: boxLocalPosition.y.toFixed(3),
                    z: boxLocalPosition.z.toFixed(3)
                  });

                  // Box Rotation も変換
                  const boxRotationEuler = new THREE.Euler(
                    currentBoxRotation.x,
                    currentBoxRotation.y,
                    currentBoxRotation.z
                  );
                  const boxRotationMatrix = new THREE.Matrix4().makeRotationFromEuler(boxRotationEuler);

                  // GS の回転を抽出
                  const gsRotationMatrix = new THREE.Matrix4().extractRotation(gsScene.matrixWorld);

                  // 合成: GS^-1 * Box
                  const combinedRotationMatrix = new THREE.Matrix4()
                    .copy(gsRotationMatrix)
                    .invert()
                    .multiply(boxRotationMatrix);

                  const combinedRotationEuler = new THREE.Euler().setFromRotationMatrix(combinedRotationMatrix);

                  console.log('[STEP 4] Box rotation transformation:');
                  console.log('  World space (deg):', {
                    x: (currentBoxRotation.x * 180 / Math.PI).toFixed(1) + '°',
                    y: (currentBoxRotation.y * 180 / Math.PI).toFixed(1) + '°',
                    z: (currentBoxRotation.z * 180 / Math.PI).toFixed(1) + '°'
                  });
                  console.log('  GS local space (deg):', {
                    x: (combinedRotationEuler.x * 180 / Math.PI).toFixed(1) + '°',
                    y: (combinedRotationEuler.y * 180 / Math.PI).toFixed(1) + '°',
                    z: (combinedRotationEuler.z * 180 / Math.PI).toFixed(1) + '°'
                  });

                  // ⭐⭐⭐ 変換後の座標で filterSplatsByBox を呼ぶ
                  const filteredVertices = filterSplatsByBox(
                    plyData, 
                    currentBoxSize,
                    {
                      x: boxLocalPosition.x,
                      y: boxLocalPosition.y,
                      z: boxLocalPosition.z
                    },
                    {
                      x: combinedRotationEuler.x,
                      y: combinedRotationEuler.y,
                      z: combinedRotationEuler.z
                    }
                  );

       /////////////////////////////////////13:47 end

                  if (filteredVertices.length === 0) {
                    console.error('[STEP 4] ❌ No splats found in the box!');
                    alert('⚠️ No splats found in the box!\n\nPlease adjust the box size/position and try again.\n\nCheck the browser console for detailed debug information.');
                    ui.showPositionAdjustment();
                    return;
                  }

                  if (filteredVertices.length < 10) {
                    console.warn('[STEP 4] ⚠️ Only', filteredVertices.length, 'splats found');
                    alert(`⚠️ Only ${filteredVertices.length} splats found!\n\nThis is too few. Please adjust the box.\n\nCheck the browser console for detailed debug information.`);
                    ui.showPositionAdjustment();
                    return;
                  }

                  console.log('[STEP 4] ✓ Filtering complete:', filteredVertices.length, 'splats kept');
                  
                  // ⭐ 外側の変数も更新(他のコードで使われる可能性があるため)
                  boxSize = currentBoxSize;
                  boxPosition = currentBoxPosition;
                  boxRotation = currentBoxRotation;
                  
                  // ... 残りのコード(STEP 5以降)は変更なし ...
                  
                  // スプラットを中心化
                  console.log('[STEP 5] Centering splats...');
                  
                  let newMinX = Infinity, newMinY = Infinity, newMinZ = Infinity;
                  let newMaxX = -Infinity, newMaxY = -Infinity, newMaxZ = -Infinity;
                  
                  filteredVertices.forEach(vertex => {
                    newMinX = Math.min(newMinX, vertex.x);
                    newMinY = Math.min(newMinY, vertex.y);
                    newMinZ = Math.min(newMinZ, vertex.z);
                    newMaxX = Math.max(newMaxX, vertex.x);
                    newMaxY = Math.max(newMaxY, vertex.y);
                    newMaxZ = Math.max(newMaxZ, vertex.z);
                  });
                  
                  const centerX = (newMaxX + newMinX) / 2;
                  const centerY = (newMaxY + newMinY) / 2;
                  const centerZ = (newMaxZ + newMinZ) / 2;
                  
                  console.log('[STEP 5] Before centering:', {
                    center: { x: centerX.toFixed(3), y: centerY.toFixed(3), z: centerZ.toFixed(3) }
                  });
                  
                  filteredVertices.forEach(vertex => {
                    vertex.x -= centerX;
                    vertex.y -= centerY;
                    vertex.z -= centerZ;
                  });
                  
                  console.log('[STEP 5] ✓ Splats centered to origin');
                  
                  // フィルタ済みPLYを保存
                  console.log('[STEP 6] Saving filtered PLY...');
                  try {
                    ui.setStatus('Saving filtered & centered PLY file...');
                    
                    const newHeader = plyData.header.map(line => {
                      if (line.startsWith('element vertex')) {
                        return `element vertex ${filteredVertices.length}`;
                      }
                      return line;
                    });
                    
                    const filteredPlyData = parser.createPLYFile(
                      newHeader,
                      filteredVertices,
                      plyData.vertexSize
                    );
                    
                    const originalFilename = gsPath.split('/').pop().replace('.ply', '');
                    const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, -5);
                    const filteredFilename = `${originalFilename}_filtered_${timestamp}.ply`;
                    
                    downloadPLY(filteredPlyData, filteredFilename);
                    
                    console.log('[STEP 6] ✓ PLY saved:', filteredFilename);
                    console.log('[STEP 6] Statistics:');
                    console.log('  Original:', plyData.vertices.length, 'vertices');
                    console.log('  Filtered:', filteredVertices.length, 'vertices');
                    console.log('  Reduction:', ((1 - filteredVertices.length / plyData.vertices.length) * 100).toFixed(1), '%');
                    
                    ui.setStatus(`✓ Saved: ${filteredFilename}`);
                    await new Promise(resolve => setTimeout(resolve, 1000));
                    
                  } catch (error) {
                    console.error('[STEP 6] ❌ Error saving PLY:', error);
                    alert('Failed to save filtered PLY file: ' + error.message);
                  }
                  
                  // 残りの処理
                  console.log('[STEP 7] Loading filtered splats into viewer...');
                  ui.setStatus('Loading filtered splats...');
                  
                  const filteredPlyUrl = createFilteredPLY(
                    parser,
                    plyData.header,
                    filteredVertices,
                    plyData.vertexSize
                  );
                  
                  await gs.viewer.dispose();
                  
                  const filteredGs = await GVRM.initGS(filteredPlyUrl, undefined, undefined, scene);
                  console.log('[STEP 7] ✓ Filtered GS loaded');
                  
                  ui.removeBoundingBox();
                  ui.setStatus('Loading VRM...');
                  
                  const character = await GVRM.initVRM(vrmPath, scene, camera, renderer, null);
                  console.log('[STEP 7] ✓ VRM loaded');
                  
                  const gvrm = new GVRM(character, filteredGs);
                  
                  ui.setStatus('Step 2: Assign splats to bones');
                  ui.showBoneAssignment();
                  
                  console.log('═══════════════════════════════════════════════════════');
                  console.log('           BOX FILTERING COMPLETE');
                  console.log('═══════════════════════════════════════════════════════');
                  console.log('\n\n');
                  
                  const promise2 = setupBoneAssignment(
                    ui, scene, camera, renderer,
                    gvrm, character, filteredGs, filteredPlyUrl,
                    vrmPath, useGPU, savePly, fileName,
                    { vertices: filteredVertices, header: plyData.header, vertexSize: plyData.vertexSize },
                    plyData
                  );
                  
                  resolve({
                    gvrm: gvrm,
                    promise2: promise2,
                    error: null,
                    ui: ui
                  });
                });
              }

////////////////// 12/15 18:00 全面描き直し




}); // GVRM.initGS().then()閉じる
        }); // parser.parsePLY().then()閉じる
      }); // ui.initialize().then()閉じる
      
    } catch (error) {
      console.error('[preprocessManual] Error:', error);
      reject(error);
    }
  });
}
              // ========================================
              // Step 1: Bounding Box Adjustment Deleted 
              // ========================================

////////////////////////////12/13 16:20 END

              

// ========================================
// Bone Assignment Setup Function
// ========================================

// ========================================
// Complete setupBoneAssignment Function
// Replace your entire setupBoneAssignment function with this
// ========================================
////////////////////////////////////////////////0111


function setupBoneAssignment(ui, scene, camera, renderer, gvrm, character, filteredGs, filteredPlyUrl, vrmPath, useGPU, savePly, fileName, plyData, originalPlyData) {
  return new Promise(async (resolve2) => {
    console.log('[setupBoneAssignment] Starting bone assignment...');
    
    try {
///////////////////
      // ⭐ オブジェクトのサイズから適切な初期半径を計算
      function calculateOptimalRadius(filteredGs) {
        // スプラットの範囲を計算
        let minX = Infinity, minY = Infinity, minZ = Infinity;
        let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity;
        
        for (let i = 0; i < filteredGs.splatCount; i++) {
          const x = filteredGs.centers0[i * 3 + 0];
          const y = filteredGs.centers0[i * 3 + 1];
          const z = filteredGs.centers0[i * 3 + 2];
          
          minX = Math.min(minX, x);
          minY = Math.min(minY, y);
          minZ = Math.min(minZ, z);
          maxX = Math.max(maxX, x);
          maxY = Math.max(maxY, y);
          maxZ = Math.max(maxZ, z);
        }
        
        // オブジェクトの最大サイズを取得
        const sizeX = maxX - minX;
        const sizeY = maxY - minY;
        const sizeZ = maxZ - minZ;
        const maxSize = Math.max(sizeX, sizeY, sizeZ);
        
        // 適切な初期半径 = オブジェクトサイズの5%(調整可能)
        const optimalRadius = Math.max(0.1, Math.min(10.0, maxSize * 0.05));
        
        console.log('[calculateOptimalRadius] Object size:', { sizeX, sizeY, sizeZ, maxSize });
        console.log('[calculateOptimalRadius] Optimal radius:', optimalRadius.toFixed(2), 'm');
        
        return optimalRadius;
      }

      // setupBoneAssignment関数内で使用:
      // let selectionRadius = 0.5; の代わりに:
      let selectionRadius = calculateOptimalRadius(filteredGs);

      ///////////////////

      // ========================================
      // Load default bone operations with error handling
      // ========================================
      let boneOperations = [];

      try {
        console.log('[setupBoneAssignment] Attempting to load default.json...');
        const response = await fetch("./assets/default.json");
        
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const params = await response.json();
        boneOperations = params.boneOperations || [];
        
        console.log('[setupBoneAssignment] ✓ default.json loaded successfully');
      } catch (error) {
        console.warn('[setupBoneAssignment] Could not load default.json:', error.message);
        console.warn('[setupBoneAssignment] Using default T-pose instead');
        
        // デフォルトのT-poseを使用(何も変更しない)
        boneOperations = [];
      }

      // ボーン操作を適用(boneOperationsが空でも安全)
      if (boneOperations.length > 0) {
        console.log('[setupBoneAssignment] Applying bone operations...');
        GVRMUtils.resetPose(character, boneOperations);
      } else {
        console.log('[setupBoneAssignment] No bone operations to apply, using current pose');
      }

      character.currentVrm.scene.updateMatrixWorld(true);

      // Get VRM bone information
      const humanBones = character.currentVrm.humanoid.humanBones;
      const boneNames = Object.keys(humanBones);
      const boneNameToIndex = {};
      boneNames.forEach((name, index) => {
        boneNameToIndex[name] = index;
      });
      
      console.log('[setupBoneAssignment] Available bones:', boneNames.length);
      console.log('[setupBoneAssignment] Bone names:', boneNames);
      
      // Assignment data management
      const assignmentData = {
        splatBoneIndices: new Array(filteredGs.splatCount).fill(-1),
        boneAssignments: {},
        history: [],
        currentPreset: 'required19'
      };
      
      let selectedTarget = null;
      let currentBoneGroups = PRESET_BONE_GROUPS.required19;
      let selectionMode = null;
      //let selectionRadius = 0.5;
      
      // ========================================
      // Paint Mode Variables
      // ========================================
      let isPaintMode = false;
      let isPainting = false;
      let paintModeEraser = false;
      
      // ========================================
      // Preset Selector
      // ========================================
      const presetSelector = document.getElementById('preset-selector');
      const presetDescription = document.getElementById('preset-description');
      const boneSelector = document.getElementById('bone-selector');
      
      const presetDescriptions = {
        'required19': 'Required mode: Assign to 20 individual body parts (20-30 min). All bones assigned individually.'
      };
      

      function updateBoneSelector(mode) {
        if (!boneSelector) {
          console.error('[updateBoneSelector] boneSelector not found');
          return;
        }
        
        console.log('[updateBoneSelector] Updating for mode:', mode);
        
        boneSelector.innerHTML = '<option value="">-- Select target --</option>';
        
        if (mode === 'required19') {
          const groups = PRESET_BONE_GROUPS.required19;
          groups.forEach((group, index) => {
            const option = document.createElement('option');
            option.value = `group_${index}`;
            option.textContent = group.name;
            boneSelector.appendChild(option);
          });
          console.log('[updateBoneSelector] Added', groups.length, 'groups');
        }
      }
      
      // Initialize preset selector
      if (presetSelector) {
        updateBoneSelector('required19');
        
        if (presetDescription) {
          presetDescription.textContent = presetDescriptions['required19'];
        }
        
        presetSelector.addEventListener('change', (e) => {
          const mode = e.target.value;
          assignmentData.currentPreset = mode;
          
          if (mode === 'required19') {
            currentBoneGroups = PRESET_BONE_GROUPS.required19;
          }
          
          if (presetDescription) {
            presetDescription.textContent = presetDescriptions[mode] || '';
          }
          
          updateBoneSelector(mode);
          console.log('[setupBoneAssignment] Preset mode changed to:', mode);
        });
      }
      
      // ========================================
      // Bone/Group Selector
      // ========================================
      if (boneSelector) {
        boneSelector.addEventListener('change', (e) => {
          selectedTarget = e.target.value;
          console.log('[setupBoneAssignment] Selected target:', selectedTarget);
        });
      }
      
// ========================================
// Select Sphere Button 挿入 12/18 15:40
// ========================================
const selectSphereBtn = document.getElementById('select-sphere-btn');
if (selectSphereBtn) {
  selectSphereBtn.addEventListener('click', () => {
    if (!selectedTarget) {
      alert('Please select a target bone or group first');
      return;
    }
    
    selectionMode = 'sphere';
    selectSphereBtn.style.background = '#4CAF50';
    selectSphereBtn.textContent = '✓ Sphere Mode Active (Click GS)';
    
    console.log('[setupBoneAssignment] Sphere selection mode activated');
    console.log('  Target:', selectedTarget);
    console.log('  Radius:', selectionRadius, 'm');
  });
}

// ========================================
// Selection Radius Slider
// ========================================
const selectionRadiusSlider = document.getElementById('selection-radius');
const selectionRadiusValue = document.getElementById('selection-radius-value');

if (selectionRadiusSlider && selectionRadiusValue) {
  selectionRadiusSlider.addEventListener('input', (e) => {
    selectionRadius = parseFloat(e.target.value);
    selectionRadiusValue.textContent = selectionRadius.toFixed(1);
  });
}


      // ========================================
      // Paint Mode Toggle
      // ========================================
      const paintModeToggle = document.getElementById('paint-mode-toggle');
      const paintModeHint = document.getElementById('paint-mode-hint');
      
      if (paintModeToggle && paintModeHint) {
        paintModeToggle.addEventListener('change', (e) => {
          isPaintMode = e.target.checked;
          if (isPaintMode) {
            paintModeHint.style.display = 'block';
            console.log('[setupBoneAssignment] Paint mode enabled');
          } else {
            paintModeHint.style.display = 'none';
            console.log('[setupBoneAssignment] Paint mode disabled');
          }
        });
      }
      ////helper関数挿入

// ========================================
// 🎯 挿入場所: setupBoneAssignment 関数内
// ====helper関数挿入 の直後
// ========================================

/**
 * ターゲットの色を取得
 */
function getTargetColor(target) {
  if (target.startsWith('group_')) {
    const groupIndex = parseInt(target.replace('group_', ''));
    const group = currentBoneGroups[groupIndex];
    if (group && group.color) {
      return group.color;
    }
  }
  return [255, 255, 255];
}

/**
 * ターゲットのボーンインデックスを取得
 */
function getTargetBoneIndices(target) {
  const indices = [];
  
  if (target.startsWith('group_')) {
    const groupIndex = parseInt(target.replace('group_', ''));
    const group = currentBoneGroups[groupIndex];
    
    if (group && group.bones) {
      group.bones.forEach(boneName => {
        if (boneNameToIndex[boneName] !== undefined) {
          indices.push(boneNameToIndex[boneName]);
        }
      });
    }
  }
  
  return indices;
}

/**
 * ボーンインデックスからボーン名を取得
 */
function getBoneNameFromIndex(index) {
  for (const [name, idx] of Object.entries(boneNameToIndex)) {
    if (idx === index) {
      return name;
    }
  }
  return `bone_${index}`;
}

/**
 * Splatに割り当てを適用
 */
function applyAssignmentToIndices(indices, target, isEraser) {
  if (isEraser) {
    indices.forEach(idx => {
      if (assignmentData.splatBoneIndices[idx] >= 0) {
        const oldBoneName = getBoneNameFromIndex(assignmentData.splatBoneIndices[idx]);
        if (assignmentData.boneAssignments[oldBoneName]) {
          const arrayIdx = assignmentData.boneAssignments[oldBoneName].indexOf(idx);
          if (arrayIdx >= 0) {
            assignmentData.boneAssignments[oldBoneName].splice(arrayIdx, 1);
          }
        }
        assignmentData.splatBoneIndices[idx] = -1;
        
        filteredGs.colors[idx * 4 + 0] = 255;
        filteredGs.colors[idx * 4 + 1] = 255;
        filteredGs.colors[idx * 4 + 2] = 255;
      }
    });
    console.log('[Paint] Erased', indices.length, 'splats');
  } else {
    const targetColor = getTargetColor(target);
    const boneIndices = getTargetBoneIndices(target);
    
    if (boneIndices.length === 0) {
      console.warn('[applyAssignmentToIndices] No bone indices found for target:', target);
      return;
    }
    
    indices.forEach(idx => {
      assignmentData.splatBoneIndices[idx] = boneIndices[0];
      
      filteredGs.colors[idx * 4 + 0] = targetColor[0];
      filteredGs.colors[idx * 4 + 1] = targetColor[1];
      filteredGs.colors[idx * 4 + 2] = targetColor[2];
      
      boneIndices.forEach(boneIdx => {
        const boneName = getBoneNameFromIndex(boneIdx);
        if (!assignmentData.boneAssignments[boneName]) {
          assignmentData.boneAssignments[boneName] = [];
        }
        if (!assignmentData.boneAssignments[boneName].includes(idx)) {
          assignmentData.boneAssignments[boneName].push(idx);
        }
      });
    });
    console.log('[Paint] Painted', indices.length, 'splats with', target);
  }
  
  filteredGs.splatMesh.updateDataTexturesFromBaseData(0, filteredGs.splatCount - 1);
  updateStats();
}

/**
 * 2D画面座標から最も近い3D Splatを検索
 */
function findNearestSplat(mouseX, mouseY, camera, filteredGs, maxScreenDistance = 100) {
  const canvas = renderer.domElement;
  const mousePixelX = (mouseX + 1) * canvas.width / 2;
  const mousePixelY = (-mouseY + 1) * canvas.height / 2;
  
  let nearestSplatIndex = -1;
  let nearestScreenDist = Infinity;
  
  const cameraPos = camera.position;
  const worldPos = new THREE.Vector3();
  const screenPos = new THREE.Vector3();
  
  for (let i = 0; i < filteredGs.splatCount; i++) {
    worldPos.x = filteredGs.centers0[i * 3 + 0];
    worldPos.y = filteredGs.centers0[i * 3 + 1];
    worldPos.z = filteredGs.centers0[i * 3 + 2];
    
    screenPos.copy(worldPos);
    screenPos.project(camera);
    
    if (screenPos.z > 1) continue;
    
    const screenPixelX = (screenPos.x + 1) * canvas.width / 2;
    const screenPixelY = (-screenPos.y + 1) * canvas.height / 2;
    
    const dx = screenPixelX - mousePixelX;
    const dy = screenPixelY - mousePixelY;
    const screenDist = Math.sqrt(dx * dx + dy * dy);
    
    if (screenDist < maxScreenDistance && screenDist < nearestScreenDist) {
      nearestScreenDist = screenDist;
      nearestSplatIndex = i;
    }
  }
  
  if (nearestSplatIndex >= 0) {
    return {
      index: nearestSplatIndex,
      screenDistance: nearestScreenDist
    };
  }
  
  return null;
}

/**
 * 球体範囲内の全Splatを検索
 */
function findSplatsInSphere(center, radius, filteredGs) {
  const indicesInSphere = [];
  const radiusSquared = radius * radius;
  
  for (let i = 0; i < filteredGs.splatCount; i++) {
    const x = filteredGs.centers0[i * 3 + 0];
    const y = filteredGs.centers0[i * 3 + 1];
    const z = filteredGs.centers0[i * 3 + 2];
    
    const dx = x - center.x;
    const dy = y - center.y;
    const dz = z - center.z;
    const distSquared = dx * dx + dy * dy + dz * dz;
    
    if (distSquared <= radiusSquared) {
      indicesInSphere.push(i);
    }
  }
  
  console.log('[findSplatsInSphere] Found', indicesInSphere.length, 'splats within radius', radius.toFixed(2), 'm');
  return indicesInSphere;
}

/**
 * ブラシ半径内の全Splatを返す
 */
function findNearestSplatWithRadius(mouseX, mouseY, camera, filteredGs, brushRadius) {
  const canvas = renderer.domElement;
  const mousePixelX = (mouseX + 1) * canvas.width / 2;
  const mousePixelY = (-mouseY + 1) * canvas.height / 2;
  
  const affectedIndices = [];
  const worldPos = new THREE.Vector3();
  const screenPos = new THREE.Vector3();
  
  for (let i = 0; i < filteredGs.splatCount; i++) {
    worldPos.x = filteredGs.centers0[i * 3 + 0];
    worldPos.y = filteredGs.centers0[i * 3 + 1];
    worldPos.z = filteredGs.centers0[i * 3 + 2];
    
    screenPos.copy(worldPos);
    screenPos.project(camera);
    
    if (screenPos.z > 1) continue;
    
    const screenPixelX = (screenPos.x + 1) * canvas.width / 2;
    const screenPixelY = (-screenPos.y + 1) * canvas.height / 2;
    
    const dx = screenPixelX - mousePixelX;
    const dy = screenPixelY - mousePixelY;
    const screenDist = Math.sqrt(dx * dx + dy * dy);
    
    if (screenDist < brushRadius) {
      affectedIndices.push(i);
    }
  }
  
  return affectedIndices.length > 0 ? { indices: affectedIndices } : null;
}

/**
 * ペイントモード用: マウスパスに沿ってSplatを塗る
 */
function findSplatsAlongMousePath(mouseX, mouseY, lastMouseX, lastMouseY, camera, filteredGs, brushRadius = 30) {
  const affectedSplats = new Set();
  
  const steps = 5;
  for (let step = 0; step <= steps; step++) {
    const t = step / steps;
    const interpX = lastMouseX + (mouseX - lastMouseX) * t;
    const interpY = lastMouseY + (mouseY - lastMouseY) * t;
    
    const result = findNearestSplatWithRadius(interpX, interpY, camera, filteredGs, brushRadius);
    if (result && result.indices) {
      result.indices.forEach(idx => affectedSplats.add(idx));
    }
  }
  
  return Array.from(affectedSplats);
}

/**
 * ペイント処理を実行
 */
function handlePaintAtPosition(mouseX, mouseY) {
  const result = findNearestSplatWithRadius(mouseX, mouseY, camera, filteredGs, 30);
  
  if (result && result.indices.length > 0) {
    applyAssignmentToIndices(result.indices, selectedTarget, paintModeEraser);
  } else {
    console.log('[Paint] No splats found under cursor');
  }
}

// ========================================
// マウスイベント処理
// ========================================

const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
let lastPaintMouseX = null;
let lastPaintMouseY = null;

      ////helper関数挿入 終了
      
      // ========================================
      // Statistics Update
      // ========================================
      function updateStats() {
        const totalSplats = filteredGs.splatCount;
        const assignedSplats = assignmentData.splatBoneIndices.filter(idx => idx >= 0).length;
        const unassignedSplats = totalSplats - assignedSplats;
        const progress = ((assignedSplats / totalSplats) * 100).toFixed(1);
        
        const totalEl = document.getElementById('total-splats');
        const assignedEl = document.getElementById('assigned-splats');
        const unassignedEl = document.getElementById('unassigned-splats');
        const progressEl = document.getElementById('assignment-progress');
        
        if (totalEl) totalEl.textContent = totalSplats;
        if (assignedEl) assignedEl.textContent = assignedSplats;
        if (unassignedEl) unassignedEl.textContent = unassignedSplats;
        if (progressEl) progressEl.textContent = progress + '%';
        
        // Update assignment list
        const listEl = document.getElementById('bone-assignment-list');
        if (listEl) {
          const entries = Object.entries(assignmentData.boneAssignments)
            .filter(([_, indices]) => indices.length > 0)
            .sort((a, b) => b[1].length - a[1].length);
          
          if (entries.length === 0) {
            listEl.innerHTML = '<div style="color: #888;">No assignments yet</div>';
          } else {
            listEl.innerHTML = entries.map(([name, indices]) => 
              `<div style="margin: 5px 0;">
                <strong style="color: #4CAF50;">${name}</strong>: ${indices.length} splats
              </div>`
            ).join('');
          }
        }
      }
      
      updateStats();
      
      // ========================================
      // Selection Radius
      // ========================================
      //const selectionRadiusSlider = document.getElementById('selection-radius');
      //const selectionRadiusValue = document.getElementById('selection-radius-value');
      
      if (selectionRadiusSlider && selectionRadiusValue) {
        selectionRadiusSlider.addEventListener('input', (e) => {
          selectionRadius = parseFloat(e.target.value);
          selectionRadiusValue.textContent = selectionRadius.toFixed(2);
        });
      }

        // ========================================
        // Raycaster Setup
        // ========================================


//////挿入箇所start

// ========================================
// 改善されたスプラット選択機能
// setupBoneAssignment関数内のマウスクリック処理を置き換えてください
// ========================================

/**
 * 2D画面座標から最も近い3D Splatを検索
 * @param {number} mouseX - 正規化されたマウスX座標 (-1 to 1)
 * @param {number} mouseY - 正規化されたマウスY座標 (-1 to 1)
 * @param {THREE.Camera} camera - カメラオブジェクト
 * @param {Object} filteredGs - Gaussian Splat データ
 * @param {number} maxScreenDistance - 最大許容画面距離(ピクセル、デフォルト50px)
 * @returns {Object|null} { index, screenDistance, worldDistance } or null
 */

/**
 * 球体範囲内の全Splatを検索
 * @param {THREE.Vector3} center - 球の中心座標
 * @param {number} radius - 球の半径
 * @param {Object} filteredGs - Gaussian Splat データ
 * @returns {Array<number>} Splat インデックスの配列
 */

/**
 * ペイントモード用: マウスパスに沿ってSplatを塗る
 * @param {number} mouseX - 正規化マウスX
 * @param {number} mouseY - 正規化マウスY
 * @param {number} lastMouseX - 前のマウスX
 * @param {number} lastMouseY - 前のマウスY
 * @param {THREE.Camera} camera
 * @param {Object} filteredGs
 * @param {number} brushRadius - ブラシ半径(ピクセル、デフォルト30px)
 * @returns {Array<number>} 影響を受けたSplatインデックス
 */

/**
 * ブラシ半径内の全Splatを返す
 * @param {number} mouseX - 正規化マウスX
 * @param {number} mouseY - 正規化マウスY
 * @param {THREE.Camera} camera
 * @param {Object} filteredGs
 * @param {number} brushRadius - ブラシ半径(ピクセル)
 * @returns {Object|null} { indices: Array<number> } or null
 */

// ========================================
// マウスクリック/ドラッグイベント処理の改善例
// ========================================


// マウスダウンイベント
renderer.domElement.addEventListener('mousedown', (event) => {
  if (!isPaintMode || !selectedTarget) return;
  
  isPainting = true;
  paintModeEraser = event.shiftKey;
  
  // マウス座標を正規化
  const rect = renderer.domElement.getBoundingClientRect();
  mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
  mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
  
  lastPaintMouseX = mouse.x;
  lastPaintMouseY = mouse.y;
  
  // 最初のクリック位置でペイント
  handlePaintAtPosition(mouse.x, mouse.y);
});

// マウスムーブイベント(ドラッグ中)
renderer.domElement.addEventListener('mousemove', (event) => {
  if (!isPainting || !isPaintMode) return;
  
  const rect = renderer.domElement.getBoundingClientRect();
  mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
  mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
  
  // パスに沿ってペイント
  const affectedIndices = findSplatsAlongMousePath(
    mouse.x, mouse.y,
    lastPaintMouseX, lastPaintMouseY,
    camera, filteredGs,
    30 // ブラシ半径30px
  );
  
  if (affectedIndices.length > 0) {
    applyAssignmentToIndices(affectedIndices, selectedTarget, paintModeEraser);
  }
  
  lastPaintMouseX = mouse.x;
  lastPaintMouseY = mouse.y;
});

// マウスアップイベント
renderer.domElement.addEventListener('mouseup', () => {
  isPainting = false;
  lastPaintMouseX = null;
  lastPaintMouseY = null;
});


// ========================================
// 球体選択モード(元のコード互換)
// ========================================


if (selectSphereBtn) {
  selectSphereBtn.addEventListener('click', () => {
    if (!selectedTarget) {
      alert('Please select a target bone or group first!');
      return;
    }
    
    selectionMode = 'sphere';
    console.log('[Sphere Selection] Mode activated, radius:', selectionRadius, 'm');
    console.log('[Sphere Selection] Click on a splat to select all nearby splats');
    
    // One-time click listener
    const onSphereClick = (event) => {
      const rect = renderer.domElement.getBoundingClientRect();
      mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
      mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
      
      // ⭐ 改善: 最も近いsplatを見つける
      const nearestResult = findNearestSplat(mouse.x, mouse.y, camera, filteredGs, 100);
      
      if (!nearestResult) {
        alert('No splat found near click. Please click closer to the object.');
        renderer.domElement.removeEventListener('click', onSphereClick);
        selectionMode = null;
        return;
      }
      
      const centerIdx = nearestResult.index;
      
      // 中心点の座標
      const centerX = filteredGs.centers0[centerIdx * 3 + 0];
      const centerY = filteredGs.centers0[centerIdx * 3 + 1];
      const centerZ = filteredGs.centers0[centerIdx * 3 + 2];
      const center = new THREE.Vector3(centerX, centerY, centerZ);
      
      console.log('[Sphere Selection] Center splat:', centerIdx, 'at', center);
      
      // 球体範囲内のsplatを検索
      const indicesInSphere = findSplatsInSphere(center, selectionRadius, filteredGs);
      
      if (indicesInSphere.length === 0) {
        alert('No splats found in sphere. Try increasing the radius.');
        renderer.domElement.removeEventListener('click', onSphereClick);
        selectionMode = null;
        return;
      }
      
      // 割り当てを実行
      applyAssignmentToIndices(indicesInSphere, selectedTarget, false);
      
      // 履歴に記録
      assignmentData.history.push({
        action: 'sphere_select',
        indices: [...indicesInSphere],
        target: selectedTarget
      });
      
      console.log('[Sphere Selection] Completed:', indicesInSphere.length, 'splats assigned');
      
      renderer.domElement.removeEventListener('click', onSphereClick);
      selectionMode = null;
    };
    
    renderer.domElement.addEventListener('click', onSphereClick);
  });
}

console.log('[setupBoneAssignment] ✓ Improved splat selection system initialized');
console.log('[setupBoneAssignment] Features:');
console.log('  - Finds nearest splat within 50px (adjustable)');
console.log('  - Paint mode with drag support');
console.log('  - Smooth brush strokes with interpolation');
console.log('  - Sphere selection with improved center detection');


///////挿入箇所end

        // ========================================
        // ⭐ Camera Controls Setup
        // ========================================
        const cameraControls = setupCameraControls(camera, renderer);
        console.log('[setupBoneAssignment] Camera controls initialized');

        // ========================================
        // Camera Lock Setup (完全版)
        // ========================================
   /////ここから


      // ========================================
      // Camera Lock Setup の修正版
      // Line 2479-2562 付近を以下に置き換えてください
      // ========================================

      console.log('[setupBoneAssignment] Setting up camera lock...');

      const cameraLockBtn = document.getElementById('camera-lock-btn');

      if (!cameraLockBtn) {
        console.error('[setupBoneAssignment] ❌ Camera lock button NOT FOUND!');
      } else {
        console.log('[setupBoneAssignment] ✓ Camera lock button found');
        
        // カメラロック切り替え関数
        function toggleCameraLock() {
          // グローバル状態を反転
          window.cameraLockState.locked = !window.cameraLockState.locked;
          const isLocked = window.cameraLockState.locked;
          
          console.log('');
          console.log('═══════════════════════════════════════════════');
          console.log('   CAMERA LOCK TOGGLE');
          console.log('═══════════════════════════════════════════════');
          console.log('New state:', isLocked ? '🔒 LOCKED' : '🔓 UNLOCKED');
          
          if (isLocked) {
            console.log('Locking camera...');
            
            // OrbitControlsを無効化
            if (cameraControls && cameraControls.controls) {
              cameraControls.controls.enabled = false;
              console.log('  ✓ OrbitControls.enabled = false');
            }
            
            // ⭐⭐⭐ ボタンのテキストとスタイルを更新 ⭐⭐⭐
            cameraLockBtn.textContent = '🔒 Camera Locked (Click to Unlock)';
            cameraLockBtn.style.background = '#4CAF50'; // 緑色に変更
            
            console.log('✅ Camera locked');
            console.log('ℹ️  Try to rotate the camera with mouse - it should NOT move');
            console.log('ℹ️  You can still click to paint');
            
          } else {
            console.log('Unlocking camera...');
            
            // OrbitControlsを有効化
            if (cameraControls && cameraControls.controls) {
              cameraControls.controls.enabled = true;
              console.log('  ✓ OrbitControls.enabled = true');
            }
            
            // ⭐⭐⭐ ボタンのテキストとスタイルを更新 ⭐⭐⭐
            cameraLockBtn.textContent = '🔓 Camera Unlocked (Can Rotate)';
            cameraLockBtn.style.background = '#9C27B0'; // 元の紫色に戻す
            
            console.log('✅ Camera unlocked');
            console.log('ℹ️  Camera can now be rotated with mouse');
          }
          
          // デバッグ情報を出力
          console.log('─────────────────────────────────────────────');
          console.log('Current state:');
          console.log('  window.cameraLockState.locked:', window.cameraLockState.locked);
          console.log('  cameraControls exists:', !!cameraControls);
          if (cameraControls && cameraControls.controls) {
            console.log('  cameraControls.controls.enabled:', cameraControls.controls.enabled);
          }
          console.log('  Button text:', cameraLockBtn.textContent);
          console.log('═══════════════════════════════════════════════');
          console.log('');
        }
        
        // ✅ ボタンのクリックイベントを設定
        cameraLockBtn.addEventListener('click', toggleCameraLock);
        
        console.log('[setupBoneAssignment] ✓ Camera lock button configured');
        console.log('[setupBoneAssignment] Initial state: UNLOCKED');
      }

        ////ここまで       



// Call this after OrbitControls is created
// You'll need to pass the cameraControls.controls object
// setupCameraLock(cameraControls.controls);


      // ========================================
      // Assign Splats in Sphere Function
      // ========================================
      ///////////////////////////12/13 19:14
      // ========================================
      // 完全な修正版 assignSplatsInSphere 関数
      // Line 1477 から Line 1590 までを置き換え
      // ========================================

      function assignSplatsInSphere(center, radius, target, isPaintMode = false) {
        console.log(`[setupBoneAssignment] Assigning splats around center to ${target}`);
        
        const mode = assignmentData.currentPreset;
        let targetBones = [];
        let targetColor = [128, 128, 128];
        let displayName = target;
        
        if (mode === 'required19') {
          const groupIndex = parseInt(target.replace('group_', ''));
          const group = currentBoneGroups[groupIndex];
          
          if (!group) {
            console.error('[setupBoneAssignment] Group not found:', groupIndex);
            return;
          }
          
          targetBones = group.bones;
          targetColor = group.color;
          displayName = group.name;
          
          console.log('[setupBoneAssignment] Group:', displayName, 'Bones:', targetBones);
        } else {
          console.error('[setupBoneAssignment] Unknown mode:', mode);
          return;
        }
        
        if (targetBones.length === 0) {
          console.error('[setupBoneAssignment] No bones found for target:', target);
          return;
        }
        
        // Get bone indices
        const boneIndices = targetBones
          .map(name => boneNameToIndex[name])
          .filter(idx => idx !== undefined);
        
        if (boneIndices.length === 0) {
          console.error('[setupBoneAssignment] No valid bone indices for:', targetBones);
          return;
        }
        
        // Use the first bone index
        const primaryBoneIndex = boneIndices[0];
        
        let assignedCount = 0;
        const newlyAssigned = [];
        
        for (let i = 0; i < filteredGs.splatCount; i++) {
          const splatPos = new THREE.Vector3(
            filteredGs.centers0[i * 3 + 0],
            filteredGs.centers0[i * 3 + 1],
            filteredGs.centers0[i * 3 + 2]
          );
          
          splatPos.applyMatrix4(filteredGs.viewer.splatMesh.scenes[0].matrixWorld);
          
          const distance = splatPos.distanceTo(center);
          
          if (distance <= radius) {
            // In paint mode, allow overwriting existing assignments
            if (isPaintMode || assignmentData.splatBoneIndices[i] < 0) {
              // If overwriting, remove from old assignment
              if (assignmentData.splatBoneIndices[i] >= 0 && isPaintMode) {
                for (const [name, indices] of Object.entries(assignmentData.boneAssignments)) {
                  const idx = indices.indexOf(i);
                  if (idx > -1) {
                    indices.splice(idx, 1);
                  }
                }
              }
              
              assignmentData.splatBoneIndices[i] = primaryBoneIndex;
              newlyAssigned.push(i);
              assignedCount++;
              
              // Change color
              filteredGs.colors[i * 4 + 0] = targetColor[0];
              filteredGs.colors[i * 4 + 1] = targetColor[1];
              filteredGs.colors[i * 4 + 2] = targetColor[2];
            }
          }
        }
        
        if (assignedCount > 0) {
          if (!assignmentData.boneAssignments[displayName]) {
            assignmentData.boneAssignments[displayName] = [];
          }
          
          // ⭐⭐⭐ CRITICAL FIX: concat を使用してスタックオーバーフローを回避 ⭐⭐⭐
          assignmentData.boneAssignments[displayName] = 
            assignmentData.boneAssignments[displayName].concat(newlyAssigned);
          
          // Only add to history in non-paint mode
          if (!isPaintMode) {
            assignmentData.history.push({
              targetName: displayName,
              indices: newlyAssigned,
              boneIndex: primaryBoneIndex
            });
          }
          
          filteredGs.splatMesh.updateDataTexturesFromBaseData(0, filteredGs.splatCount - 1);
          
          updateStats();
          
          if (!isPaintMode) {
            console.log(`[setupBoneAssignment] Assigned ${assignedCount} splats to ${displayName}`);
          }
        } else if (!isPaintMode) {
          console.log('[setupBoneAssignment] No splats found in selection');
        }
      }


            
      // ========================================
      // Erase Splats in Sphere Function
      // ========================================
      function eraseSplatsInSphere(center, radius) {
        let erasedCount = 0;
        const erased = [];
        
        for (let i = 0; i < filteredGs.splatCount; i++) {
          // Skip already unassigned
          if (assignmentData.splatBoneIndices[i] < 0) continue;
          
          const splatPos = new THREE.Vector3(
            filteredGs.centers0[i * 3 + 0],
            filteredGs.centers0[i * 3 + 1],
            filteredGs.centers0[i * 3 + 2]
          );
          
          splatPos.applyMatrix4(filteredGs.viewer.splatMesh.scenes[0].matrixWorld);
          
          const distance = splatPos.distanceTo(center);
          
          if (distance <= radius) {
            assignmentData.splatBoneIndices[i] = -1;
            erased.push(i);
            erasedCount++;
            
            // Change color to gray (unassigned)
            filteredGs.colors[i * 4 + 0] = 128;
            filteredGs.colors[i * 4 + 1] = 128;
            filteredGs.colors[i * 4 + 2] = 128;
          }
        }
        
        if (erasedCount > 0) {
          // Update bone assignments
          for (const [name, indices] of Object.entries(assignmentData.boneAssignments)) {
            assignmentData.boneAssignments[name] = indices.filter(idx => !erased.includes(idx));
          }
          
          filteredGs.splatMesh.updateDataTexturesFromBaseData(0, filteredGs.splatCount - 1);
          //renderer.render(scene, camera);
          
          updateStats();
          
          console.log(`[setupBoneAssignment] Erased ${erasedCount} splats`);
        }
      }
      
      // ========================================
      // Paint Mode Mouse Handlers
      // ========================================
      function paintAtMousePosition(event) {
        const rect = renderer.domElement.getBoundingClientRect();
        mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
        mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
        
        raycaster.setFromCamera(mouse, camera);
        
        const intersects = raycaster.intersectObject(filteredGs.splatMesh, true);
        
        if (intersects.length > 0) {
          const hitPoint = intersects[0].point;
          
        if (paintModeEraser) {
          // Erase mode: use full radius for larger objects
          eraseSplatsInSphere(hitPoint, selectionRadius, true);  // 0.5 → 1.0
        } else {
          // Paint mode: use full radius for larger objects
          assignSplatsInSphere(hitPoint, selectionRadius, selectedTarget, true);  // 0.5 → 1.0
        }
        }
      }
      
      function onMouseDown(event) {
        if (!isPaintMode) return;
        if (!selectedTarget) {
          alert('Please select a target first!');
          return;
        }
        
        // Check if Shift key is held for eraser mode
        paintModeEraser = event.shiftKey;
        isPainting = true;
        
        // Immediately paint at click location
        paintAtMousePosition(event);
      }
      
      function onMouseMove(event) {
        if (!isPaintMode || !isPainting) return;
        
        paintAtMousePosition(event);
      }
      
      function onMouseUp(event) {
        if (!isPaintMode) return;
        isPainting = false;
      }
      
      // ========================================
      // Regular Click Handler (non-paint mode)
      // ========================================
      function onCanvasClick(event) {
        // Paint mode handles clicks differently
        if (isPaintMode) {
          return; // Handled by mouse down/move/up
        }
        
        if (selectionMode !== 'sphere' || !selectedTarget) return;
        
        const rect = renderer.domElement.getBoundingClientRect();
        mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
        mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
        
        raycaster.setFromCamera(mouse, camera);
        
        const intersects = raycaster.intersectObject(filteredGs.splatMesh, true);
        
        if (intersects.length > 0) {
          const hitPoint = intersects[0].point;
          console.log('[setupBoneAssignment] Clicked at:', hitPoint.toArray());
          
          assignSplatsInSphere(hitPoint, selectionRadius, selectedTarget);
        }
      }
      
      // ========================================
      // Attach Event Listeners
      // ========================================
      renderer.domElement.addEventListener('mousedown', onMouseDown);
      renderer.domElement.addEventListener('mousemove', onMouseMove);
      renderer.domElement.addEventListener('mouseup', onMouseUp);
      renderer.domElement.addEventListener('click', onCanvasClick);
      
      // ========================================
      // Sphere Selection Mode Button
      // ========================================
      
      if (selectSphereBtn) {
        selectSphereBtn.addEventListener('click', () => {
          if (!selectedTarget) {
            alert('Please select a target first!');
            return;
          }
          
          selectionMode = 'sphere';
          selectSphereBtn.style.background = '#FF6F00';
          
          console.log('[setupBoneAssignment] Sphere selection mode activated');
        });
      }
      
      // ========================================
      // Undo Last Assignment
      // ========================================
      const clearSelectionBtn = document.getElementById('clear-selection-btn');
      if (clearSelectionBtn) {
        clearSelectionBtn.addEventListener('click', () => {
          if (assignmentData.history.length === 0) {
            alert('No assignments to undo');
            return;
          }
          
          const lastAssignment = assignmentData.history.pop();
          const { targetName, indices } = lastAssignment;
          
          indices.forEach(idx => {
            assignmentData.splatBoneIndices[idx] = -1;
            
            filteredGs.colors[idx * 4 + 0] = 128;
            filteredGs.colors[idx * 4 + 1] = 128;
            filteredGs.colors[idx * 4 + 2] = 128;
          });
          
          if (assignmentData.boneAssignments[targetName]) {
            assignmentData.boneAssignments[targetName] = 
              assignmentData.boneAssignments[targetName].filter(idx => !indices.includes(idx));
          }
          
          filteredGs.splatMesh.updateDataTexturesFromBaseData(0, filteredGs.splatCount - 1);
          //renderer.render(scene, camera);
          
          updateStats();
          
          console.log(`[setupBoneAssignment] Undone ${indices.length} splats from ${targetName}`);
        });
      }
      
      // ========================================
      // Reset All Assignments
      // ========================================
      const undoAllBtn = document.getElementById('undo-all-btn');
      if (undoAllBtn) {
        undoAllBtn.addEventListener('click', () => {
          if (!confirm('Reset all assignments?')) return;
          
          assignmentData.splatBoneIndices.fill(-1);
          assignmentData.boneAssignments = {};
          assignmentData.history = [];
          
          for (let i = 0; i < filteredGs.splatCount; i++) {
            filteredGs.colors[i * 4 + 0] = 128;
            filteredGs.colors[i * 4 + 1] = 128;
            filteredGs.colors[i * 4 + 2] = 128;
          }
          
          filteredGs.splatMesh.updateDataTexturesFromBaseData(0, filteredGs.splatCount - 1);
          //renderer.render(scene, camera);
          
          updateStats();
          
          console.log('[setupBoneAssignment] Reset all assignments');
        });
      }
      

 ///////////////////////////////////////////////////////////////////////////////////////////////1356////

// ========================================
// finalizeBtn 正しい構造(完全版)
// 1356行目から1818行目までを、この全体で置き換え
// ========================================


/////////////// 12/13 16:40 修正必要箇所かも

const finalizeBtn = document.getElementById('finalize-btn');
if (finalizeBtn) {
  finalizeBtn.addEventListener('click', async () => {
    const assignedCount = assignmentData.splatBoneIndices.filter(idx => idx >= 0).length;
    
    if (assignedCount === 0) {
      alert('Please assign at least some splats before finalizing!');
      return;
    }
    
    if (assignedCount < filteredGs.splatCount * 0.3) {
      if (!confirm(`Only ${assignedCount}/${filteredGs.splatCount} splats assigned. Continue?`)) {
        return;
      }
    }
    
    console.log('[setupBoneAssignment] Finalizing...');
    ui.setStatus('Validating bone assignments...');
    
    try {
      // ========================================
      // STEP 1: Create PMC FIRST
      // ========================================
      console.log('[setupBoneAssignment] Creating PMC...');
      const { pmc, capsuleBoneIndex } = GVRMUtils.getPointsMeshCapsules(character);
      GVRMUtils.addPMC(scene, pmc);
      GVRMUtils.visualizePMC(pmc, false);
      //renderer.render(scene, camera);
      
      gvrm.pmc = pmc;
      // gvrm.modelScale = 1.0;
      gvrm.boneOperations = boneOperations;
      gvrm.customType = "1"; 
      
      console.log('[setupBoneAssignment] PMC created');
      console.log('[setupBoneAssignment] capsuleBoneIndex:', capsuleBoneIndex);
      console.log('[setupBoneAssignment] Number of capsules:', Object.keys(capsuleBoneIndex).length);
      console.log('[setupBoneAssignment] ✓ Set gvrm.customType:', gvrm.customType); // ← このログを追加

///////////////


      // ========================================
      // STEP 2: Required Bones Check
      // ========================================
      const requiredBones = [
        'hips', 'spine', 'chest', 'neck', 'head',
        'leftShoulder', 'leftUpperArm', 'leftLowerArm', 'leftHand',
        'rightShoulder', 'rightUpperArm', 'rightLowerArm', 'rightHand',
        'leftUpperLeg', 'leftLowerLeg', 'leftFoot',
        'rightUpperLeg', 'rightLowerLeg', 'rightFoot'
      ];
      
      const assignedBoneIndices = new Set(assignmentData.splatBoneIndices.filter(idx => idx >= 0));
      const missingBones = [];
      
      requiredBones.forEach(boneName => {
        const boneIndex = boneNameToIndex[boneName];
        if (boneIndex !== undefined && !assignedBoneIndices.has(boneIndex)) {
          missingBones.push(boneName);
        }
      });
      
      // Auto-complete missing bones
      if (missingBones.length > 0) {
        console.warn('[setupBoneAssignment] Missing bone assignments:', missingBones);
        
        const proceed = confirm(
          `Warning: The following bones have no splats assigned:\n\n${missingBones.join(', ')}\n\n` +
          `This may cause rendering issues. The system will assign a few splats to these bones automatically.\n\n` +
          `Continue?`
        );
        
        if (!proceed) {
          ui.setStatus('Cancelled by user');
          return;
        }
        
        ui.setStatus('Auto-assigning missing bones...');
        
        for (const boneName of missingBones) {
          const boneIndex = boneNameToIndex[boneName];
          if (boneIndex === undefined) continue;
          
          const bone = humanBones[boneName];
          if (!bone || !bone.node) continue;
          
          const boneWorldPos = new THREE.Vector3();
          bone.node.getWorldPosition(boneWorldPos);
          
          let assignedToThisBone = 0;
          const maxToAssign = 5;
          
          for (let i = 0; i < filteredGs.splatCount && assignedToThisBone < maxToAssign; i++) {
            if (assignmentData.splatBoneIndices[i] >= 0) continue;
            
            const splatPos = new THREE.Vector3(
              filteredGs.centers0[i * 3 + 0],
              filteredGs.centers0[i * 3 + 1],
              filteredGs.centers0[i * 3 + 2]
            );
            splatPos.applyMatrix4(filteredGs.viewer.splatMesh.scenes[0].matrixWorld);
            
            const distance = splatPos.distanceTo(boneWorldPos);
            
            if (distance < 1.0) {
              assignmentData.splatBoneIndices[i] = boneIndex;
              assignedToThisBone++;
              
              const color = GVRMUtils.colors[boneIndex % GVRMUtils.colors.length];
              filteredGs.colors[i * 4 + 0] = color[0];
              filteredGs.colors[i * 4 + 1] = color[1];
              filteredGs.colors[i * 4 + 2] = color[2];
            }
          }
          
          if (assignedToThisBone > 0) {
            console.log(`[setupBoneAssignment] Auto-assigned ${assignedToThisBone} splats to ${boneName}`);
          } else {
            console.warn(`[setupBoneAssignment] Could not auto-assign any splats to ${boneName}`);
          }
        }
        
        filteredGs.splatMesh.updateDataTexturesFromBaseData(0, filteredGs.splatCount - 1);
        //renderer.render(scene, camera);
        updateStats();
      }
      
      // ========================================
      // STEP 3: Set Bone Assignments
      // ========================================
      ui.setStatus('Setting bone assignments...');
      filteredGs.splatBoneIndices = assignmentData.splatBoneIndices;
      
      console.log('[setupBoneAssignment] Bone assignments set:', filteredGs.splatBoneIndices.length);
      
///////////////////////////////////////////////////////////////////////////////////////////////////


      // ========================================
      // STEP 4: Map Vertices to Bones (修正版)
      // preprocess_manual.js の STEP 4 部分を置き換え
      // ========================================
      ui.setStatus('Mapping vertices to bones...');
      const skinnedMesh = character.currentVrm.scene.children[character.skinnedMeshIndex];
      const position = skinnedMesh.geometry.getAttribute('position');

      const boneVertexIndices = {};

      // ⭐ 修正: capsuleBoneIndexだけでなく、実際に割り当てられた全ボーンを含める
      const allUsedBoneIndices = new Set(Object.values(capsuleBoneIndex));

      // 割り当てられたスプラットのボーンインデックスも追加
      assignmentData.splatBoneIndices.forEach(boneIdx => {
        if (boneIdx >= 0) {
          allUsedBoneIndices.add(boneIdx);
        }
      });

      console.log('[setupBoneAssignment] Unique bone indices used:', Array.from(allUsedBoneIndices).sort((a,b) => a-b));
      console.log('[setupBoneAssignment] Bone names:', Array.from(allUsedBoneIndices).map(idx => boneNames[idx]));

      // 全使用ボーンに対して頂点リストを初期化
      allUsedBoneIndices.forEach(boneIdx => {
        boneVertexIndices[boneIdx] = [];
      });

      console.log('[setupBoneAssignment] Initialized boneVertexIndices for', 
                  Object.keys(boneVertexIndices).length, 'bones');
      console.log('[setupBoneAssignment] Mapping', position.count, 'vertices to bones...');

////////////
      // ⭐ 修正: humanBonesを取得し直す(スコープの問題を解決)
      const humanBones = character.currentVrm.humanoid.humanBones;
////////////

      // 各頂点を最も近いボーンに割り当て
      for (let vi = 0; vi < position.count; vi++) {
        const vertex = new THREE.Vector3().fromBufferAttribute(position, vi);
        const skinnedVertex = skinnedMesh.applyBoneTransform(vi, vertex);
        skinnedVertex.applyMatrix4(character.currentVrm.scene.matrixWorld);
        
        let minDistance = Infinity;
        let closestBoneIndex = 0;
        
        // 使用されている全ボーンから最も近いボーンを探す ここは、L.1536
        for (const boneIndex of allUsedBoneIndices) {
          const boneName = boneNames[boneIndex];
          const bone = humanBones[boneName];
          if (bone && bone.node) {
            const boneWorldPos = new THREE.Vector3();
            bone.node.getWorldPosition(boneWorldPos);
            
            const distance = skinnedVertex.distanceTo(boneWorldPos);
            if (distance < minDistance) {
              minDistance = distance;
              closestBoneIndex = boneIndex;
            }
          }
        }
        
        boneVertexIndices[closestBoneIndex].push(vi);
        
        if (vi % 500 === 0) {
          const progress = ((vi / position.count) * 100).toFixed(1);
          ui.setStatus(`Mapping vertices: ${progress}%`);
          await new Promise(resolve => setTimeout(resolve, 0));
        }
      }

      console.log('[setupBoneAssignment] Vertex mapping complete');

      // ⭐ デバッグ: 各ボーンの頂点数を出力
      console.log('[setupBoneAssignment] Vertices per bone:');
      for (const [boneIdx, vertices] of Object.entries(boneVertexIndices)) {
        const boneName = boneNames[parseInt(boneIdx)];
        console.log(`  ${boneName} (${boneIdx}): ${vertices.length} vertices`);
      }



///////////////////////////////////////////////////////////////////////////////////////////////////

      // ========================================
      // STEP 5: Assign Splats to Vertices (修正版)
      // ========================================
      ui.setStatus('Assigning splats to vertices...');
      filteredGs.splatVertexIndices = [];
      filteredGs.splatRelativePoses = [];

      console.log('[setupBoneAssignment] Assigning', filteredGs.splatCount, 'splats to vertices...');

      let remappedCount = 0;
      let fallbackCount = 0;

      // ⭐ グローバルフォールバック: 最も頂点数が多いボーンを特定
      let fallbackBoneIndex = 0;
      let maxVertexCount = 0;
      for (const [boneIdx, vertices] of Object.entries(boneVertexIndices)) {
        if (vertices.length > maxVertexCount) {
          maxVertexCount = vertices.length;
          fallbackBoneIndex = parseInt(boneIdx);
        }
      }

      console.log(`[setupBoneAssignment] Fallback bone: ${boneNames[fallbackBoneIndex]} (${fallbackBoneIndex}) with ${maxVertexCount} vertices`);

      const fallbackVertices = boneVertexIndices[fallbackBoneIndex] || [];

      // 最終フォールバック用の頂点
      let ultimateFallbackVertex = 0;
      if (fallbackVertices.length > 0) {
        ultimateFallbackVertex = fallbackVertices[Math.floor(fallbackVertices.length / 2)];
      }

      for (let i = 0; i < filteredGs.splatCount; i++) {
        const targetPoint = new THREE.Vector3(
          filteredGs.centers0[i * 3 + 0],
          filteredGs.centers0[i * 3 + 1],
          filteredGs.centers0[i * 3 + 2]
        );
        targetPoint.applyMatrix4(filteredGs.viewer.splatMesh.scenes[0].matrixWorld);
        
        let assignedBoneIndex = filteredGs.splatBoneIndices[i];
        
        // 未割り当てまたは無効なボーンの場合、フォールバックボーンに割り当て
        if (assignedBoneIndex < 0 || !allUsedBoneIndices.has(assignedBoneIndex)) {
          if (assignedBoneIndex >= 0) {
            remappedCount++;
          }
          assignedBoneIndex = fallbackBoneIndex;
          filteredGs.splatBoneIndices[i] = fallbackBoneIndex;
        }
        
        const vertexIndices = boneVertexIndices[assignedBoneIndex] || [];
        
        // ⭐ 修正: vertexIndicesが空の場合の処理
        if (vertexIndices.length === 0) {
          if (fallbackCount === 0) {
            console.warn(`[setupBoneAssignment] Bone ${assignedBoneIndex} (${boneNames[assignedBoneIndex]}) has no vertices, using fallback bone`);
          }
          
          // フォールバックボーンの頂点群から最も近い頂点を探す
          if (fallbackVertices.length > 0) {
            let minDistance = Infinity;
            let bestVertexIndex = fallbackVertices[0];
            
            // 高速化: サンプリング
            const step = Math.max(1, Math.floor(fallbackVertices.length / 100));
            
            for (let vi = 0; vi < fallbackVertices.length; vi += step) {
              const vertexIndex = fallbackVertices[vi];
              const vertex = new THREE.Vector3().fromBufferAttribute(position, vertexIndex);
              const skinnedVertex = skinnedMesh.applyBoneTransform(vertexIndex, vertex);
              skinnedVertex.applyMatrix4(character.currentVrm.scene.matrixWorld);
              
              const distance = skinnedVertex.distanceTo(targetPoint);
              
              if (distance < minDistance) {
                minDistance = distance;
                bestVertexIndex = vertexIndex;
              }
            }
            
            filteredGs.splatVertexIndices.push(bestVertexIndex);
            
            // 相対位置を計算
            const vertex = new THREE.Vector3().fromBufferAttribute(position, bestVertexIndex);
            const transformedVertex = skinnedMesh.applyBoneTransform(bestVertexIndex, vertex);
            
            let center0 = new THREE.Vector3(
              filteredGs.centers0[i * 3 + 0],
              filteredGs.centers0[i * 3 + 1],
              filteredGs.centers0[i * 3 + 2]
            );
            center0.applyMatrix4(filteredGs.viewer.splatMesh.scenes[0].matrixWorld);
            center0.applyMatrix4(new THREE.Matrix4().copy(character.currentVrm.scene.matrixWorld).invert());
            
            const relativePos = new THREE.Vector3().subVectors(center0, transformedVertex);
            filteredGs.splatRelativePoses.push(relativePos.x, relativePos.y, relativePos.z);
            
            fallbackCount++;
          } else {
            // 最終フォールバック: ジオメトリの任意の頂点を使用
            if (fallbackCount === 0) {
              console.error('[setupBoneAssignment] No vertices available for any bone, using vertex', ultimateFallbackVertex);
            }
            
            filteredGs.splatVertexIndices.push(ultimateFallbackVertex);
            
            const vertex = new THREE.Vector3().fromBufferAttribute(position, ultimateFallbackVertex);
            const transformedVertex = skinnedMesh.applyBoneTransform(ultimateFallbackVertex, vertex);
            
            let center0 = new THREE.Vector3(
              filteredGs.centers0[i * 3 + 0],
              filteredGs.centers0[i * 3 + 1],
              filteredGs.centers0[i * 3 + 2]
            );
            center0.applyMatrix4(filteredGs.viewer.splatMesh.scenes[0].matrixWorld);
            center0.applyMatrix4(new THREE.Matrix4().copy(character.currentVrm.scene.matrixWorld).invert());
            
            const relativePos = new THREE.Vector3().subVectors(center0, transformedVertex);
            filteredGs.splatRelativePoses.push(relativePos.x, relativePos.y, relativePos.z);
            
            fallbackCount++;
          }
          
          if (i % 100 === 0) {
            const progress = ((i / filteredGs.splatCount) * 100).toFixed(1);
            ui.setStatus(`Assigning splats: ${progress}%`);
            await new Promise(resolve => setTimeout(resolve, 0));
          }
          
          continue;
        }
        
        // ⭐ 通常処理: vertexIndicesが存在する場合
        let minDistance = Infinity;
        let bestVertexIndex = vertexIndices[0];
        
        // 高速化: サンプリング
        const step = Math.max(1, Math.floor(vertexIndices.length / 100));
        
        for (let vi = 0; vi < vertexIndices.length; vi += step) {
          const vertexIndex = vertexIndices[vi];
          const vertex = new THREE.Vector3().fromBufferAttribute(position, vertexIndex);
          const skinnedVertex = skinnedMesh.applyBoneTransform(vertexIndex, vertex);
          skinnedVertex.applyMatrix4(character.currentVrm.scene.matrixWorld);
          
          const distance = skinnedVertex.distanceTo(targetPoint);
          
          if (distance < minDistance) {
            minDistance = distance;
            bestVertexIndex = vertexIndex;
          }
        }
        
        filteredGs.splatVertexIndices.push(bestVertexIndex);
        
        // 相対位置の計算
        const vertex = new THREE.Vector3().fromBufferAttribute(position, bestVertexIndex);
        const transformedVertex = skinnedMesh.applyBoneTransform(bestVertexIndex, vertex);
        
        let center0 = new THREE.Vector3(
          filteredGs.centers0[i * 3 + 0],
          filteredGs.centers0[i * 3 + 1],
          filteredGs.centers0[i * 3 + 2]
        );
        center0.applyMatrix4(filteredGs.viewer.splatMesh.scenes[0].matrixWorld);
        center0.applyMatrix4(new THREE.Matrix4().copy(character.currentVrm.scene.matrixWorld).invert());
        
        const relativePos = new THREE.Vector3().subVectors(center0, transformedVertex);
        filteredGs.splatRelativePoses.push(relativePos.x, relativePos.y, relativePos.z);
        
        if (i % 100 === 0) {
          const progress = ((i / filteredGs.splatCount) * 100).toFixed(1);
          ui.setStatus(`Assigning splats: ${progress}%`);
          await new Promise(resolve => setTimeout(resolve, 0));
        }
      }

      console.log('[setupBoneAssignment] Splat assignment complete');
      console.log('  - splatVertexIndices:', filteredGs.splatVertexIndices.length);
      console.log('  - splatRelativePoses:', filteredGs.splatRelativePoses.length);
      console.log('  - Remapped splats:', remappedCount);
      console.log('  - Fallback assignments:', fallbackCount);

      // ⭐ データ検証
      const uniqueVertices = new Set(filteredGs.splatVertexIndices);
      console.log('  - Unique vertices used:', uniqueVertices.size);

      const zeroRelativePoses = filteredGs.splatRelativePoses.filter(v => v === 0).length;
      const zeroPercent = (zeroRelativePoses / filteredGs.splatRelativePoses.length * 100).toFixed(1);
      console.log(`  - Zero values in relativePoses: ${zeroRelativePoses} (${zeroPercent}%)`);

      // サンプルデータの出力
      console.log('  - Sample splatVertexIndices:', filteredGs.splatVertexIndices.slice(0, 10));
      console.log('  - Sample splatRelativePoses:', filteredGs.splatRelativePoses.slice(0, 30));

      if (zeroPercent > 30) {
        console.warn('[setupBoneAssignment] WARNING: High percentage of zero relative poses detected!');
      }

      if (uniqueVertices.size < 10) {
        console.warn('[setupBoneAssignment] WARNING: Very few unique vertices used! This may cause issues.');
      }



      // ========================================
      // STEP 6: Update PMC
      // ========================================
      console.log('[setupBoneAssignment] Updating PMC...');
      gvrm.updatePMC();
      console.log('[setupBoneAssignment] PMC updated');
  
  ////////////////////////20251210start2///////////////////////////////////////////////////////////////////////////    

      // ========================================
      // DIAGNOSTIC CODE - Insert BEFORE Step 6.5
      // ========================================

      console.log('========== GVRM STATE DIAGNOSTIC ==========');
      console.log('1. GVRM Object:', gvrm);
      console.log('2. GVRM properties:');
      console.log('   - modelScale:', gvrm.modelScale);
      console.log('   - boneOperations:', gvrm.boneOperations);
      console.log('   - pmc:', gvrm.pmc);
      console.log('   - gs:', gvrm.gs);

      console.log('3. filteredGs Object:', filteredGs);
      console.log('4. filteredGs properties:');
      console.log('   - splatCount:', filteredGs.splatCount);
      console.log('   - splatVertexIndices length:', filteredGs.splatVertexIndices?.length);
      console.log('   - splatBoneIndices length:', filteredGs.splatBoneIndices?.length);
      console.log('   - splatRelativePoses length:', filteredGs.splatRelativePoses?.length);
      console.log('   - gsQuaternion:', filteredGs.gsQuaternion);
      console.log('   - gsPosition:', filteredGs.gsPosition);
      console.log('   - viewer:', filteredGs.viewer);
      console.log('   - viewer.splatMesh:', filteredGs.viewer?.splatMesh);
      console.log('   - scenes:', filteredGs.viewer?.splatMesh?.scenes);

      console.log('5. Character Object:', character);
      console.log('6. Character VRM:');
      console.log('   - currentVrm:', character.currentVrm);
      console.log('   - humanoid:', character.currentVrm?.humanoid);
      console.log('   - humanBones:', character.currentVrm?.humanoid?.humanBones);

      // const humanBones = character.currentVrm?.humanoid?.humanBones;
      if (humanBones) {
        console.log('7. Available bones:', Object.keys(humanBones));
        console.log('8. Hips bone:', humanBones.hips);
        console.log('9. LeftUpperLeg bone:', humanBones.leftUpperLeg);
      }

      console.log('========== END DIAGNOSTIC ==========');


////////////////////////////////////////////////////////

      // ========================================
      // STEP 6.5: Calculate modelScale, gsQuaternion, gsPosition
      // CRITICAL: Insert AFTER "gvrm.updatePMC()" and BEFORE "gvrm.save()"
      // ========================================

      console.log('[setupBoneAssignment] ===== CALCULATING GVRM TRANSFORMS =====');
      ui.setStatus('Calculating transforms...');

      try {
        // ========================================
        // 1. Calculate gsQuaternion and gsPosition
        // ========================================


        console.log('[setupBoneAssignment] Step 1: Calculate GS transform');

        // Get the GS scene transform
        const gsScene = filteredGs.viewer.splatMesh.scenes[0];
        gsScene.updateMatrixWorld(true);

        // Clone the world matrix
        const gsWorldMatrix = gsScene.matrixWorld.clone();

        // Extract position
        const gsWorldPosition = new THREE.Vector3();
        gsWorldPosition.setFromMatrixPosition(gsWorldMatrix);

        console.log('[setupBoneAssignment] GS World Position:', {
          x: gsWorldPosition.x,
          y: gsWorldPosition.y,
          z: gsWorldPosition.z
        });

        // Extract scale
        const gsWorldScale = new THREE.Vector3();
        gsWorldScale.setFromMatrixScale(gsWorldMatrix);

        console.log('[setupBoneAssignment] GS World Scale:', {
          x: gsWorldScale.x,
          y: gsWorldScale.y,
          z: gsWorldScale.z
        });

        // ⭐ 重要: スケールを除去したmatrixからrotationを取得
        const rotationMatrix = gsWorldMatrix.clone();
        rotationMatrix.scale(new THREE.Vector3(
          1 / gsWorldScale.x,
          1 / gsWorldScale.y,
          1 / gsWorldScale.z
        ));

        // Extract rotation as quaternion
        const gsWorldQuaternion = new THREE.Quaternion();
        gsWorldQuaternion.setFromRotationMatrix(rotationMatrix);

        console.log('[setupBoneAssignment] GS World Quaternion:', {
          x: gsWorldQuaternion.x,
          y: gsWorldQuaternion.y,
          z: gsWorldQuaternion.z,
          w: gsWorldQuaternion.w
        });

        // ⭐ 修正: Identityチェックを追加
        const isIdentity = (
          Math.abs(gsWorldQuaternion.x) < 0.0001 &&
          Math.abs(gsWorldQuaternion.y) < 0.0001 &&
          Math.abs(gsWorldQuaternion.z) < 0.0001 &&
          Math.abs(gsWorldQuaternion.w - 1.0) < 0.0001
        );

        if (isIdentity) {
          console.log('[setupBoneAssignment] ✓ GS has identity rotation (no rotation applied)');
        } else {
          console.log('[setupBoneAssignment] ✓ GS has non-identity rotation');
}


////////////////////////////////

        // Assign to filteredGs
        filteredGs.gsQuaternion = [
          gsWorldQuaternion.x,
          gsWorldQuaternion.y,
          gsWorldQuaternion.z,
          gsWorldQuaternion.w
        ];

        filteredGs.gsPosition = [
          gsWorldPosition.x,
          gsWorldPosition.y,
          gsWorldPosition.z
        ];


 /////////////////////////////////////20251210

        // ========================================
        // 2. Calculate modelScale
        // ========================================

        // ========================================
        // 修正4: modelScaleの計算を修正
        // Line 1929付近
        // ========================================

        console.log('[setupBoneAssignment] Step 2: Calculate modelScale');

        const humanBones = character.currentVrm.humanoid.humanBones;

        if (!humanBones.hips || !humanBones.hips.node) {
          throw new Error('hips bone not found');
        }

        if (!humanBones.leftUpperLeg || !humanBones.leftUpperLeg.node) {
          throw new Error('leftUpperLeg bone not found');
        }

        const hipsNode = humanBones.hips.node;
        const leftUpperLegNode = humanBones.leftUpperLeg.node;

        // ⭐ 修正: matrixWorldを強制的に更新
        character.currentVrm.scene.updateMatrixWorld(true);

        // Get world positions
        const hipsWorldPos = new THREE.Vector3();
        hipsNode.getWorldPosition(hipsWorldPos);

        const leftUpperLegWorldPos = new THREE.Vector3();
        leftUpperLegNode.getWorldPosition(leftUpperLegWorldPos);

        console.log('[setupBoneAssignment] Hips world position:', {
          x: hipsWorldPos.x.toFixed(4),
          y: hipsWorldPos.y.toFixed(4),
          z: hipsWorldPos.z.toFixed(4)
        });

        console.log('[setupBoneAssignment] Left upper leg world position:', {
          x: leftUpperLegWorldPos.x.toFixed(4),
          y: leftUpperLegWorldPos.y.toFixed(4),
          z: leftUpperLegWorldPos.z.toFixed(4)
        });


/////////////////


        const legLength = hipsWorldPos.distanceTo(leftUpperLegWorldPos);
        console.log('[setupBoneAssignment] Raw leg length:', legLength);

        // ⭐ 判定: legLengthが0.2以下の場合、VRMスケールが正しいと判断
        if (legLength < 0.2) {
          console.warn('[setupBoneAssignment] ⚠️ VRM has very small leg length:', legLength);
          console.warn('[setupBoneAssignment] Using modelScale = 1.0 (no scaling needed)');
          gvrm.modelScale = 1.0;
        } else {
          // 通常の計算
          const standardLegLength = 0.45;
          const calculatedModelScale = standardLegLength / legLength;
          
          console.log('[setupBoneAssignment] Calculated modelScale:', calculatedModelScale);
          
          // 適度なクランプ
          const clampedModelScale = Math.max(0.1, Math.min(10.0, calculatedModelScale));
          
          if (clampedModelScale !== calculatedModelScale) {
            console.warn('[setupBoneAssignment] ⚠️ Clamped modelScale from', calculatedModelScale, 'to', clampedModelScale);
          }
          
          gvrm.modelScale = clampedModelScale;
        }

        console.log('[setupBoneAssignment] ✓ Final gvrm.modelScale:', gvrm.modelScale);

///////////////////////


        // ========================================
        // 3. Update boneOperations (optional but recommended)
        // ========================================
        
        console.log('[setupBoneAssignment] Step 3: Update boneOperations');
        
        // The current boneOperations already has the correct structure
        // We could update rotations based on the actual pose, but it's optional
        
        // For now, just log the current boneOperations
        console.log('[setupBoneAssignment] Current boneOperations:', gvrm.boneOperations);
        
        // ========================================
        // Verification
        // ========================================
        
        console.log('[setupBoneAssignment] ===== TRANSFORM CALCULATION COMPLETE =====');
        console.log('[setupBoneAssignment] Final values:');
        console.log('  modelScale:', gvrm.modelScale);
        console.log('  gsQuaternion:', filteredGs.gsQuaternion);
        console.log('  gsPosition:', filteredGs.gsPosition);
        console.log('  boneOperations:', gvrm.boneOperations.length, 'operations');
        
        // Sanity checks
        if (gvrm.modelScale < 0.5 || gvrm.modelScale > 2.0) {
          console.warn('[setupBoneAssignment] ⚠️ WARNING: modelScale is outside normal range (0.5-2.0)');
          console.warn('[setupBoneAssignment]   This may cause rendering issues');
        }
        
        if (filteredGs.gsQuaternion[0] === 0 && 
            filteredGs.gsQuaternion[1] === 0 && 
            filteredGs.gsQuaternion[2] === 1 && 
            filteredGs.gsQuaternion[3] === 0) {
          console.warn('[setupBoneAssignment] ⚠️ WARNING: gsQuaternion is still default value!');
        }
        
        if (filteredGs.gsPosition[0] === 0 && 
            filteredGs.gsPosition[1] === 0 && 
            filteredGs.gsPosition[2] === 0) {
          console.warn('[setupBoneAssignment] ⚠️ WARNING: gsPosition is still (0,0,0)!');
          console.warn('[setupBoneAssignment]   This means the GS has no offset from origin');
        }
        
        ui.setStatus('Transform calculation complete');
        
      } catch (error) {
        console.error('[setupBoneAssignment] ERROR in transform calculation:', error);
        console.error('[setupBoneAssignment] Error stack:', error.stack);
        alert('Error calculating transforms: ' + error.message);
        throw error;
      }


////////////////////////////////////////////////////////////////////// add 20251211 13:54


      // Key changes in STEP 6.6 section (around line 1598):

      // ========================================
      // STEP 6.6: Save matrixWorld0 for all bones
      // CRITICAL: Insert AFTER transform calculation and BEFORE gvrm.save()
      // ========================================

      console.log('[setupBoneAssignment] ===== SAVING MATRIXWORLD0 =====');
      ui.setStatus('Saving bone matrices...');

      try {
        const allBoneNames = Object.keys(humanBones); // ← humanBonesは既に定義済み
        console.log('[setupBoneAssignment] Saving matrixWorld0 for', allBoneNames.length, 'bones');
        
        // Initialize matrixWorld0 storage if it doesn't exist
        if (!gvrm.matrixWorld0) {
          gvrm.matrixWorld0 = {};
        }
        
        // Save matrixWorld for each bone
        let savedCount = 0;
        for (const boneName of allBoneNames) {
          const bone = humanBones[boneName];
          
          // ⭐ 修正: より詳細なチェック
          if (bone && bone.node && bone.node.matrixWorld) {
            // Clone the matrix to preserve the initial state
            gvrm.matrixWorld0[boneName] = bone.node.matrixWorld.clone();
            savedCount++;
            
            // Log first few bones for verification
            if (savedCount <= 3) {
              console.log(`[setupBoneAssignment] Saved matrixWorld0 for ${boneName}:`, 
                bone.node.matrixWorld.elements.slice(0, 4));
            }
          } else {
            console.warn(`[setupBoneAssignment] ⚠️ Bone ${boneName} has no valid node/matrixWorld:`, {
              bone: !!bone,
              node: !!bone?.node,
              matrixWorld: !!bone?.node?.matrixWorld
            });
          }
        }
        
        console.log(`[setupBoneAssignment] ✓ Saved matrixWorld0 for ${savedCount} bones`);
        console.log('[setupBoneAssignment] Sample matrixWorld0 keys:', 
          Object.keys(gvrm.matrixWorld0).slice(0, 5));
        
        // Verify critical bones
        const criticalBones = ['hips', 'leftUpperArm', 'rightUpperArm'];
        for (const boneName of criticalBones) {
          if (!gvrm.matrixWorld0[boneName]) {
            console.error(`[setupBoneAssignment] ❌ CRITICAL: ${boneName} matrixWorld0 not saved!`);
          } else {
            console.log(`[setupBoneAssignment] ✓ ${boneName} matrixWorld0 verified`);
          }
        }
        
        ui.setStatus('Bone matrices saved');
        
      } catch (error) {
        console.error('[setupBoneAssignment] ERROR saving matrixWorld0:', error);
        console.error('[setupBoneAssignment] Error stack:', error.stack);
        alert('Error saving bone matrices: ' + error.message);
        throw error;
      }


////////////////////////////////////////////////////////////////////////////////

      // ========================================
      // STEP 6.7: Transfer matrixWorld0 to filteredGs
      // ========================================

      console.log('[setupBoneAssignment] ===== TRANSFERRING MATRIXWORLD0 TO FILTEREDGS =====');

      // ⭐ 追加: gvrm.matrixWorld0が存在するか確認
      if (!gvrm.matrixWorld0 || Object.keys(gvrm.matrixWorld0).length === 0) {
        console.error('[setupBoneAssignment] ❌ CRITICAL: gvrm.matrixWorld0 is empty or undefined!');
        throw new Error('matrixWorld0 was not properly saved');
      }

      // Convert matrixWorld0 from Matrix4 objects to serializable arrays
      const matrixWorld0Serializable = {};

      for (const [boneName, matrix] of Object.entries(gvrm.matrixWorld0)) {
        // ⭐ 修正: matrixがnullでないことを確認
        if (matrix && matrix.elements) {
          // Convert THREE.Matrix4 to array
          matrixWorld0Serializable[boneName] = matrix.elements.slice(); // Copy array
        } else {
          console.warn(`[setupBoneAssignment] ⚠️ Invalid matrix for ${boneName}:`, matrix);
        }
      }

      // Assign to filteredGs so it gets saved
      filteredGs.matrixWorld0 = matrixWorld0Serializable;

      console.log('[setupBoneAssignment] ✓ Transferred matrixWorld0 to filteredGs');
      console.log('[setupBoneAssignment] ✓ matrixWorld0 bone count:', 
        Object.keys(filteredGs.matrixWorld0).length);
        
      // ⭐ 修正: hipsが存在するか確認してからアクセス
      if (filteredGs.matrixWorld0['hips']) {
        console.log('[setupBoneAssignment] Sample matrixWorld0 data (hips):', 
          filteredGs.matrixWorld0['hips'].slice(0, 4));
      } else {
        console.warn('[setupBoneAssignment] ⚠️ hips matrixWorld0 not found in filteredGs');
      }

  /////////////////////////20251210end2//////////////////////////////////////////////////////////////////////////
      
      // ========================================
      // STEP 7: Save GVRM File
      // ========================================
      ui.setStatus('Saving GVRM file...');
      console.log('[setupBoneAssignment] Saving GVRM...');

      // 保存直前に再確認
      console.log('[setupBoneAssignment] ===== FINAL CHECK BEFORE SAVE =====');
      console.log('  gvrm.customType:', gvrm.customType);
      console.log('  gvrm.modelScale:', gvrm.modelScale);

      // customTypeが失われていたら再設定
      if (!gvrm.customType) {
        console.warn('[setupBoneAssignment] ⚠️ customType was lost, resetting to "1"');
        gvrm.customType = "1";
      }

      // modelScaleが異常なら1.0に修正
      if (gvrm.modelScale > 2.0) {
        console.warn('[setupBoneAssignment] ⚠️ modelScale is too large:', gvrm.modelScale);
        console.warn('[setupBoneAssignment] Forcing modelScale = 1.0');
        gvrm.modelScale = 1.0;
      }

      await gvrm.save(vrmPath, filteredPlyUrl, boneOperations, gvrm.modelScale, fileName, savePly);

      console.log('[setupBoneAssignment] GVRM saved successfully');
      
      ///////////////

// ========================================
// 修正6: データ検証の修正
// Line 2199付近
// ========================================

    console.log('[setupBoneAssignment] ===== DATA VALIDATION =====');

    // 1. 点群数の確認
    console.log('1. Splat counts:');
    console.log('   - Original PLY:', originalPlyData.vertices.length);  // ⭐ originalPlyData使用
    console.log('   - After box filter:', plyData.vertices.length);      // ⭐ filteredPlyData使用
    console.log('   - In filteredGs:', filteredGs.splatCount);

    // 2. ボーン割り当ての確認
    const assignedBones = new Set(filteredGs.splatBoneIndices.filter(idx => idx >= 0));
    console.log('2. Bone assignments:');
    console.log('   - Unique bones used:', assignedBones.size);
    console.log('   - Assigned splats:', filteredGs.splatBoneIndices.filter(idx => idx >= 0).length);
    console.log('   - Unassigned splats:', filteredGs.splatBoneIndices.filter(idx => idx < 0).length);

    // 3. 頂点インデックスの確認
    //const uniqueVertices = new Set(filteredGs.splatVertexIndices);
    //const skinnedMesh = character.currentVrm.scene.children[character.skinnedMeshIndex];
    //const position = skinnedMesh.geometry.getAttribute('position');

    console.log('3. Vertex assignments:');
    console.log('   - Total vertices in mesh:', position.count);
    console.log('   - Unique vertices used:', uniqueVertices.size);
    console.log('   - Average splats per vertex:', (filteredGs.splatCount / uniqueVertices.size).toFixed(2));

    // 4. 相対位置の確認
    const nonZeroRelPoses = filteredGs.splatRelativePoses.filter(v => Math.abs(v) > 0.0001).length;
    const totalRelPoseValues = filteredGs.splatRelativePoses.length;
    console.log('4. Relative poses:');
    console.log('   - Total values:', totalRelPoseValues);
    console.log('   - Non-zero values:', nonZeroRelPoses, `(${(nonZeroRelPoses/totalRelPoseValues*100).toFixed(1)}%)`);

    // 5. Transform values
    console.log('5. Transform values:');
    console.log('   - modelScale:', gvrm.modelScale);
    console.log('   - gsQuaternion:', filteredGs.gsQuaternion);
    console.log('   - gsPosition:', filteredGs.gsPosition);

    console.log('[setupBoneAssignment] ===== END VALIDATION =====');

    ////////////////





      // ========================================
      // STEP 8: Reload GVRM
      // ========================================
      ui.setStatus('Reloading GVRM...');
      const newGvrmUrl = gvrm.url;
      
      if (gvrm.gs) {
        await gvrm.gs.viewer.dispose();
      }
      
      await new Promise(resolve => setTimeout(resolve, 100));
      
      await gvrm.load(newGvrmUrl, scene, camera, renderer, fileName);
      
      console.log('[setupBoneAssignment] GVRM reloaded successfully');
      ui.setStatus('Complete! ✓');
      
      // ========================================
      // Cleanup
      // ========================================
      setTimeout(() => {
        renderer.domElement.removeEventListener('mousedown', onMouseDown);
        renderer.domElement.removeEventListener('mousemove', onMouseMove);
        renderer.domElement.removeEventListener('mouseup', onMouseUp);
        renderer.domElement.removeEventListener('click', onCanvasClick);
        
        ui.cleanup();
        resolve2();
      }, 1500);
      
    } catch (error) {
      console.error('[setupBoneAssignment] Finalize error:', error);
      console.error('[setupBoneAssignment] Error stack:', error.stack);
      alert('Error during finalization: ' + error.message);
      ui.setStatus('Error: ' + error.message);
    }
  }); // finalize-btn click listener の終了
} // if (finalizeBtn) の終了

// ========================================
// setupBoneAssignment 関数全体の終了
// ========================================
    } catch (error) {
      console.error('[setupBoneAssignment] Error:', error);
      ui.setStatus('Error: ' + error.message);
    }

  }); // setupBoneAssignment の Promise の終了
} // setupBoneAssignment 関数の終了