@npcify/web 0.7.0 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +1 -0
  2. package/dist/index.js +1196 -44
  3. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -5309,7 +5309,7 @@ var disposeSceneContext = function(ctx) {
5309
5309
 
5310
5310
  // ../vrm-renderer/src/preview-controller.ts
5311
5311
  import { VRMUtils as VRMUtils4 } from "@pixiv/three-vrm";
5312
- import { Box3, GridHelper, Vector3 as Vector34 } from "three";
5312
+ import { Box3, GridHelper, Vector3 as Vector38 } from "three";
5313
5313
 
5314
5314
  // ../vrm-renderer/src/loaders.ts
5315
5315
  import { VRMLoaderPlugin as VRMLoaderPlugin2, VRMUtils as VRMUtils2 } from "@pixiv/three-vrm";
@@ -5331,13 +5331,1160 @@ import { AnimationMixer, LoopOnce, LoopRepeat } from "three";
5331
5331
  import {
5332
5332
  createVRMAnimationClip as createPixivVRMAnimationClip
5333
5333
  } from "@pixiv/three-vrm-animation";
5334
+
5335
+ // ../vrm-renderer/src/face-reach.ts
5334
5336
  import {
5335
5337
  AnimationClip,
5336
- Euler,
5337
- Quaternion as Quaternion2,
5338
+ Quaternion as Quaternion4,
5338
5339
  QuaternionKeyframeTrack,
5340
+ Vector3 as Vector35
5341
+ } from "three";
5342
+
5343
+ // ../vrm-renderer/src/hand-body.ts
5344
+ import {
5345
+ LinearInterpolant,
5346
+ Quaternion as Quaternion3,
5339
5347
  QuaternionLinearInterpolant,
5340
- Vector3 as Vector33,
5348
+ SkinnedMesh,
5349
+ Vector3 as Vector34
5350
+ } from "three";
5351
+
5352
+ // ../vrm-renderer/src/hand-clearance-core.ts
5353
+ import { Quaternion as Quaternion2, Vector3 as Vector33 } from "three";
5354
+ var MAP_HEIGHT_STEP = 0.02;
5355
+ var MAP_ANGLE_BINS = 24;
5356
+ var perpendicular = function(axis) {
5357
+ const helper = Math.abs(axis.z) < 0.9 ? new Vector33(0, 0, 1) : new Vector33(1, 0, 0);
5358
+ return helper.sub(axis.clone().multiplyScalar(helper.dot(axis))).normalize();
5359
+ };
5360
+ var angleBin = function(angle) {
5361
+ const turn = angle / (2 * Math.PI);
5362
+ const value = (turn - Math.floor(turn)) * MAP_ANGLE_BINS;
5363
+ return value;
5364
+ };
5365
+ var buildRadialMap = function(bone, origin, axis, points) {
5366
+ const flat = points.length > 0 && typeof points[0] === "number" ? points : null;
5367
+ const count = flat ? Math.floor(flat.length / 3) : points.length;
5368
+ const pointAt = (i, target) => flat ? target.set(flat[i * 3], flat[i * 3 + 1], flat[i * 3 + 2]) : target.copy(points[i]);
5369
+ const point = new Vector33();
5370
+ if (count < 16) {
5371
+ return null;
5372
+ }
5373
+ const unit = axis.clone().normalize();
5374
+ const reference = perpendicular(unit);
5375
+ const binormal = new Vector33().crossVectors(unit, reference);
5376
+ let min = Infinity;
5377
+ let max2 = -Infinity;
5378
+ const offset = new Vector33();
5379
+ for (let i = 0; i < count; i += 1) {
5380
+ pointAt(i, point);
5381
+ const height = offset.subVectors(point, origin).dot(unit);
5382
+ min = Math.min(min, height);
5383
+ max2 = Math.max(max2, height);
5384
+ }
5385
+ const start = Math.floor(min / MAP_HEIGHT_STEP) * MAP_HEIGHT_STEP;
5386
+ const heights = Math.max(1, Math.ceil((max2 - start) / MAP_HEIGHT_STEP) + 1);
5387
+ const radius = new Float32Array(heights * MAP_ANGLE_BINS);
5388
+ const top = new Float32Array(MAP_ANGLE_BINS).fill(-Infinity);
5389
+ const bottom = new Float32Array(MAP_ANGLE_BINS).fill(Infinity);
5390
+ for (let i = 0; i < count; i += 1) {
5391
+ pointAt(i, point);
5392
+ offset.subVectors(point, origin);
5393
+ const height = offset.dot(unit);
5394
+ const x = offset.dot(reference);
5395
+ const y = offset.dot(binormal);
5396
+ const row = Math.min(
5397
+ heights - 1,
5398
+ Math.max(0, Math.round((height - start) / MAP_HEIGHT_STEP))
5399
+ );
5400
+ const column = Math.floor(angleBin(Math.atan2(y, x))) % MAP_ANGLE_BINS;
5401
+ const index = row * MAP_ANGLE_BINS + column;
5402
+ radius[index] = Math.max(radius[index], Math.hypot(x, y));
5403
+ top[column] = Math.max(top[column], height);
5404
+ bottom[column] = Math.min(bottom[column], height);
5405
+ }
5406
+ for (let column = 0; column < MAP_ANGLE_BINS; column += 1) {
5407
+ if (!Number.isFinite(top[column])) {
5408
+ top[column] = min;
5409
+ bottom[column] = min;
5410
+ }
5411
+ }
5412
+ const filled = radius.slice();
5413
+ for (let row = 0; row < heights; row += 1) {
5414
+ for (let column = 0; column < MAP_ANGLE_BINS; column += 1) {
5415
+ const index = row * MAP_ANGLE_BINS + column;
5416
+ if (radius[index] > 0) {
5417
+ continue;
5418
+ }
5419
+ const left = radius[row * MAP_ANGLE_BINS + (column + MAP_ANGLE_BINS - 1) % MAP_ANGLE_BINS];
5420
+ const right = radius[row * MAP_ANGLE_BINS + (column + 1) % MAP_ANGLE_BINS];
5421
+ filled[index] = Math.max(left, right);
5422
+ }
5423
+ }
5424
+ return {
5425
+ bone,
5426
+ origin: origin.clone(),
5427
+ axis: unit,
5428
+ reference,
5429
+ start,
5430
+ heights,
5431
+ radius: filled,
5432
+ top,
5433
+ bottom,
5434
+ maxRadius: filled.reduce((a, b) => Math.max(a, b), 0)
5435
+ };
5436
+ };
5437
+ var scratchOffset = new Vector33();
5438
+ var NO_DIRECTION = new Vector33();
5439
+ var scratchBinormal = new Vector33();
5440
+ var queryRadialMap = function(map, point) {
5441
+ const offset = scratchOffset.subVectors(point, map.origin);
5442
+ const height = offset.dot(map.axis);
5443
+ const binormal = scratchBinormal.crossVectors(map.axis, map.reference);
5444
+ const x = offset.dot(map.reference);
5445
+ const y = offset.dot(binormal);
5446
+ const distance = Math.hypot(x, y);
5447
+ const row = (height - map.start) / MAP_HEIGHT_STEP;
5448
+ if (row < -0.5 || row > map.heights - 0.5) {
5449
+ return { depth: -Infinity, direction: NO_DIRECTION };
5450
+ }
5451
+ if (distance >= map.maxRadius) {
5452
+ return { depth: map.maxRadius - distance, direction: NO_DIRECTION };
5453
+ }
5454
+ const angle = angleBin(Math.atan2(y, x)) - 0.5;
5455
+ const r0 = Math.max(0, Math.min(map.heights - 1, Math.floor(row)));
5456
+ const r1 = Math.min(map.heights - 1, r0 + 1);
5457
+ const c0 = (Math.floor(angle) % MAP_ANGLE_BINS + MAP_ANGLE_BINS) % MAP_ANGLE_BINS;
5458
+ const c1 = (c0 + 1) % MAP_ANGLE_BINS;
5459
+ const fc = angle - Math.floor(angle);
5460
+ const at = (r, c) => map.radius[r * MAP_ANGLE_BINS + c];
5461
+ const fr = Math.max(0, Math.min(1, row - r0));
5462
+ const surface = (1 - fr) * ((1 - fc) * at(r0, c0) + fc * at(r0, c1)) + fr * ((1 - fc) * at(r1, c0) + fc * at(r1, c1));
5463
+ const radial = surface - distance;
5464
+ if (radial <= 0) {
5465
+ return { depth: radial, direction: NO_DIRECTION };
5466
+ }
5467
+ const up = (1 - fc) * map.top[c0] + fc * map.top[c1] - height;
5468
+ const down = height - ((1 - fc) * map.bottom[c0] + fc * map.bottom[c1]);
5469
+ const direction = distance > 1e-6 ? map.reference.clone().multiplyScalar(x / distance).add(binormal.clone().multiplyScalar(y / distance)) : map.reference.clone();
5470
+ const side = { depth: radial, direction };
5471
+ if (up < radial && up <= down) {
5472
+ return { depth: Math.max(0, up), direction: map.axis.clone(), side };
5473
+ }
5474
+ if (down < radial) {
5475
+ return {
5476
+ depth: Math.max(0, down),
5477
+ direction: map.axis.clone().negate(),
5478
+ side
5479
+ };
5480
+ }
5481
+ return { depth: radial, direction };
5482
+ };
5483
+ var marchPoint = new Vector33();
5484
+ var escapeAlong = function(map, point, direction, maxDistance = 0.3, step = 5e-3) {
5485
+ for (let distance = step; distance <= maxDistance; distance += step) {
5486
+ marchPoint.copy(point).addScaledVector(direction, distance);
5487
+ if (queryRadialMap(map, marchPoint).depth <= 0) {
5488
+ return distance;
5489
+ }
5490
+ }
5491
+ return Infinity;
5492
+ };
5493
+ var rotationBetween = function(a, b) {
5494
+ return new Quaternion2().setFromUnitVectors(
5495
+ a.clone().normalize(),
5496
+ b.clone().normalize()
5497
+ );
5498
+ };
5499
+ var quaternionToRotationVector = function(q) {
5500
+ const w = q.w < 0 ? -q.w : q.w;
5501
+ const sign = q.w < 0 ? -1 : 1;
5502
+ const sinHalf = Math.hypot(q.x, q.y, q.z);
5503
+ if (sinHalf < 1e-9) {
5504
+ return new Vector33(2 * q.x * sign, 2 * q.y * sign, 2 * q.z * sign);
5505
+ }
5506
+ const angle = 2 * Math.atan2(sinHalf, w);
5507
+ return new Vector33(q.x, q.y, q.z).multiplyScalar(sign * angle / sinHalf);
5508
+ };
5509
+ var rotationVectorToQuaternion = function(v) {
5510
+ const angle = v.length();
5511
+ if (angle < 1e-9) {
5512
+ return new Quaternion2(v.x / 2, v.y / 2, v.z / 2, 1).normalize();
5513
+ }
5514
+ return new Quaternion2().setFromAxisAngle(v.clone().divideScalar(angle), angle);
5515
+ };
5516
+ var widenAndSmooth = function(corrections, hold, sigma) {
5517
+ const count = corrections.length;
5518
+ const held = corrections.map((_, frame) => {
5519
+ let best = corrections[frame];
5520
+ for (let k = Math.max(0, frame - hold); k <= Math.min(count - 1, frame + hold); k += 1) {
5521
+ if (corrections[k].lengthSq() > best.lengthSq()) {
5522
+ best = corrections[k];
5523
+ }
5524
+ }
5525
+ return best;
5526
+ });
5527
+ const reach = Math.ceil(3 * sigma);
5528
+ return held.map((_, frame) => {
5529
+ const sum = new Vector33();
5530
+ let weight = 0;
5531
+ for (let k = -reach; k <= reach; k += 1) {
5532
+ const index = frame + k;
5533
+ if (index < 0 || index >= count) {
5534
+ continue;
5535
+ }
5536
+ const w = Math.exp(-0.5 * (k / sigma) ** 2);
5537
+ sum.addScaledVector(held[index], w);
5538
+ weight += w;
5539
+ }
5540
+ return sum.divideScalar(weight);
5541
+ });
5542
+ };
5543
+ var distanceToSegment = function(point, a, b) {
5544
+ const ab = b.clone().sub(a);
5545
+ const t = Math.max(
5546
+ 0,
5547
+ Math.min(1, point.clone().sub(a).dot(ab) / Math.max(ab.lengthSq(), 1e-12))
5548
+ );
5549
+ return point.distanceTo(a.clone().addScaledVector(ab, t));
5550
+ };
5551
+ var HAND_SKIN_DISTANCE = 0.035;
5552
+ var handSkeletonSegments = function(wrist, elbow, fingers) {
5553
+ const segments = [];
5554
+ for (const chain of fingers) {
5555
+ let previous = wrist;
5556
+ for (const joint of chain) {
5557
+ segments.push([previous, joint]);
5558
+ previous = joint;
5559
+ }
5560
+ if (chain.length >= 2) {
5561
+ const last = chain[chain.length - 1];
5562
+ const before = chain[chain.length - 2];
5563
+ segments.push([last, last.clone().add(last.clone().sub(before))]);
5564
+ }
5565
+ }
5566
+ if (!segments.length) {
5567
+ const direction = wrist.clone().sub(elbow).normalize();
5568
+ segments.push([wrist, wrist.clone().addScaledVector(direction, 0.15)]);
5569
+ }
5570
+ return segments;
5571
+ };
5572
+ var isHandSkin = function(point, segments) {
5573
+ return segments.some(
5574
+ ([a, b]) => distanceToSegment(point, a, b) <= HAND_SKIN_DISTANCE
5575
+ );
5576
+ };
5577
+
5578
+ // ../vrm-renderer/src/hand-body.ts
5579
+ var BUST = /bust|breast|oppai/i;
5580
+ var SIDES = ["left", "right"];
5581
+ var TORSO_PARTS = [
5582
+ "hips",
5583
+ "spine",
5584
+ "chest",
5585
+ "upperChest"
5586
+ ];
5587
+ var LIMB_PARTS = [
5588
+ ["leftUpperLeg", "leftLowerLeg"],
5589
+ ["rightUpperLeg", "rightLowerLeg"],
5590
+ ["leftLowerLeg", "leftFoot"],
5591
+ ["rightLowerLeg", "rightFoot"],
5592
+ ["leftShoulder", "leftUpperArm"],
5593
+ ["rightShoulder", "rightUpperArm"]
5594
+ ];
5595
+ var FINGERS = ["Thumb", "Index", "Middle", "Ring", "Little"];
5596
+ var isHandBone = function(name, side) {
5597
+ if (!name.startsWith(side)) {
5598
+ return false;
5599
+ }
5600
+ const rest = name.slice(side.length);
5601
+ return rest === "Hand" || FINGERS.some((finger) => rest.startsWith(finger));
5602
+ };
5603
+ var MAX_HAND_POINTS = 48;
5604
+ var TRIANGLE_SAMPLE_EDGE = 0.02;
5605
+ var UP = new Vector34(0, 1, 0);
5606
+ var bodyModels = /* @__PURE__ */ new WeakMap();
5607
+ var humanBoneNames = function(vrm) {
5608
+ return Object.keys(vrm.humanoid.humanBones).filter(
5609
+ (name) => Boolean(vrm.humanoid.getNormalizedBoneNode(name))
5610
+ );
5611
+ };
5612
+ var withRestPose = function(vrm, run) {
5613
+ const names = humanBoneNames(vrm);
5614
+ const saved = names.map((name) => {
5615
+ const node = vrm.humanoid.getNormalizedBoneNode(name);
5616
+ return [node, node.position.clone(), node.quaternion.clone()];
5617
+ });
5618
+ vrm.humanoid.resetNormalizedPose();
5619
+ vrm.humanoid.update();
5620
+ vrm.scene.updateMatrixWorld(true);
5621
+ try {
5622
+ return run();
5623
+ } finally {
5624
+ for (const [node, position, quaternion] of saved) {
5625
+ node.position.copy(position);
5626
+ node.quaternion.copy(quaternion);
5627
+ }
5628
+ vrm.humanoid.update();
5629
+ vrm.scene.updateMatrixWorld(true);
5630
+ }
5631
+ };
5632
+ var restMouth = function(vrm, toRig) {
5633
+ const expression = vrm.expressionManager?.getExpression("aa");
5634
+ const sum = new Vector34();
5635
+ const vertex = new Vector34();
5636
+ let count = 0;
5637
+ for (const bind of expression?._binds ?? []) {
5638
+ if (!bind.primitives || bind.index === void 0) {
5639
+ continue;
5640
+ }
5641
+ for (const mesh of bind.primitives) {
5642
+ const morph = mesh.geometry.morphAttributes.position?.[bind.index];
5643
+ if (!morph || !mesh.isSkinnedMesh) {
5644
+ continue;
5645
+ }
5646
+ for (let i = 0; i < morph.count; i += 1) {
5647
+ if (Math.hypot(morph.getX(i), morph.getY(i), morph.getZ(i)) > 2e-3) {
5648
+ mesh.getVertexPosition(i, vertex);
5649
+ sum.add(vertex.applyMatrix4(mesh.matrixWorld).applyMatrix4(toRig));
5650
+ count += 1;
5651
+ }
5652
+ }
5653
+ }
5654
+ }
5655
+ return count ? sum.divideScalar(count) : null;
5656
+ };
5657
+ var buildBodyModel = function(vrm) {
5658
+ const humanoid = vrm.humanoid;
5659
+ const names = humanBoneNames(vrm);
5660
+ for (const required of [
5661
+ "hips",
5662
+ "leftUpperArm",
5663
+ "rightUpperArm",
5664
+ "leftHand",
5665
+ "rightHand"
5666
+ ]) {
5667
+ if (!names.includes(required)) {
5668
+ return null;
5669
+ }
5670
+ }
5671
+ return withRestPose(vrm, () => {
5672
+ const toRig = humanoid.normalizedHumanBonesRoot.matrixWorld.clone().invert();
5673
+ const rest = /* @__PURE__ */ new Map();
5674
+ const nameOfNormalized = /* @__PURE__ */ new Map();
5675
+ const nameOfRaw = /* @__PURE__ */ new Map();
5676
+ for (const name of names) {
5677
+ const node = humanoid.getNormalizedBoneNode(name);
5678
+ nameOfNormalized.set(node, name);
5679
+ rest.set(name, node.getWorldPosition(new Vector34()).applyMatrix4(toRig));
5680
+ const raw2 = humanoid.getRawBoneNode(name);
5681
+ if (raw2) {
5682
+ nameOfRaw.set(raw2, name);
5683
+ }
5684
+ }
5685
+ const parent = /* @__PURE__ */ new Map();
5686
+ const depth = /* @__PURE__ */ new Map();
5687
+ for (const name of names) {
5688
+ let node = humanoid.getNormalizedBoneNode(name).parent;
5689
+ while (node && !nameOfNormalized.has(node)) {
5690
+ node = node.parent;
5691
+ }
5692
+ parent.set(name, node ? nameOfNormalized.get(node) : null);
5693
+ }
5694
+ const depthOf = (name) => {
5695
+ const known = depth.get(name);
5696
+ if (known !== void 0) {
5697
+ return known;
5698
+ }
5699
+ const up = parent.get(name);
5700
+ const value = up ? depthOf(up) + 1 : 0;
5701
+ depth.set(name, value);
5702
+ return value;
5703
+ };
5704
+ const order = [...names].sort((a, b) => depthOf(a) - depthOf(b));
5705
+ const attachCache = /* @__PURE__ */ new Map();
5706
+ const attachOf = (bone) => {
5707
+ if (attachCache.has(bone)) {
5708
+ return attachCache.get(bone);
5709
+ }
5710
+ let node = bone;
5711
+ while (node && !nameOfRaw.has(node)) {
5712
+ node = node.parent;
5713
+ }
5714
+ const result = node ? nameOfRaw.get(node) : null;
5715
+ attachCache.set(bone, result);
5716
+ return result;
5717
+ };
5718
+ const fingerChains = (side) => FINGERS.map(
5719
+ (finger) => ["Metacarpal", "Proximal", "Intermediate", "Distal"].map(
5720
+ (segment) => rest.get(`${side}${finger}${segment}`)
5721
+ ).filter((joint) => Boolean(joint))
5722
+ ).filter((chain) => chain.length > 0);
5723
+ const handSegments = {
5724
+ left: handSkeletonSegments(
5725
+ rest.get("leftHand"),
5726
+ rest.get("leftLowerArm") ?? rest.get("leftHand"),
5727
+ fingerChains("left")
5728
+ ),
5729
+ right: handSkeletonSegments(
5730
+ rest.get("rightHand"),
5731
+ rest.get("rightLowerArm") ?? rest.get("rightHand"),
5732
+ fingerChains("right")
5733
+ )
5734
+ };
5735
+ const partPoints = /* @__PURE__ */ new Map();
5736
+ const handPoints = { left: [], right: [] };
5737
+ const vertex = new Vector34();
5738
+ const raw = new Vector34();
5739
+ const pushPoint = (key, x, y, z) => {
5740
+ let list = partPoints.get(key);
5741
+ if (!list) {
5742
+ list = [];
5743
+ partPoints.set(key, list);
5744
+ }
5745
+ list.push(x, y, z);
5746
+ };
5747
+ vrm.scene.traverse((object) => {
5748
+ if (!(object instanceof SkinnedMesh) || !object.visible) {
5749
+ return;
5750
+ }
5751
+ const geometry = object.geometry;
5752
+ const position = geometry.getAttribute("position");
5753
+ const skinIndex = geometry.getAttribute("skinIndex");
5754
+ const skinWeight = geometry.getAttribute("skinWeight");
5755
+ if (!position || !skinIndex || !skinWeight) {
5756
+ return;
5757
+ }
5758
+ const count = position.count;
5759
+ const toRigMesh = toRig.clone().multiply(object.matrixWorld);
5760
+ let bindIsRest = true;
5761
+ for (let k = 0; k < 24 && bindIsRest; k += 1) {
5762
+ const i = Math.floor(k * (count - 1) / 23);
5763
+ object.getVertexPosition(i, vertex);
5764
+ raw.fromBufferAttribute(position, i);
5765
+ bindIsRest = vertex.distanceTo(raw) < 1e-3;
5766
+ }
5767
+ const restPositions = new Float32Array(count * 3);
5768
+ for (let i = 0; i < count; i += 1) {
5769
+ if (bindIsRest) {
5770
+ vertex.fromBufferAttribute(position, i);
5771
+ } else {
5772
+ object.getVertexPosition(i, vertex);
5773
+ }
5774
+ vertex.applyMatrix4(toRigMesh);
5775
+ restPositions[i * 3] = vertex.x;
5776
+ restPositions[i * 3 + 1] = vertex.y;
5777
+ restPositions[i * 3 + 2] = vertex.z;
5778
+ }
5779
+ const keys = new Array(count).fill(null);
5780
+ for (let i = 0; i < count; i += 1) {
5781
+ let best = 0;
5782
+ let bestWeight = -1;
5783
+ for (let k = 0; k < 4; k += 1) {
5784
+ const weight = skinWeight.getComponent(i, k);
5785
+ if (weight > bestWeight) {
5786
+ bestWeight = weight;
5787
+ best = skinIndex.getComponent(i, k);
5788
+ }
5789
+ }
5790
+ const bone = object.skeleton.bones[best];
5791
+ const attach = bone ? attachOf(bone) : null;
5792
+ if (!attach) {
5793
+ continue;
5794
+ }
5795
+ const side = SIDES.find((s) => isHandBone(attach, s));
5796
+ if (side) {
5797
+ const point = new Vector34().fromArray(restPositions, i * 3);
5798
+ if (nameOfRaw.get(bone) === attach && isHandSkin(point, handSegments[side])) {
5799
+ handPoints[side].push({ bone: attach, rest: point });
5800
+ }
5801
+ continue;
5802
+ }
5803
+ const body = nameOfRaw.get(bone) === attach || BUST.test(bone.name);
5804
+ const key = `${attach}|${body ? "body" : "cloth"}`;
5805
+ keys[i] = key;
5806
+ pushPoint(
5807
+ key,
5808
+ restPositions[i * 3],
5809
+ restPositions[i * 3 + 1],
5810
+ restPositions[i * 3 + 2]
5811
+ );
5812
+ }
5813
+ const index = geometry.index;
5814
+ const triangles = index ? index.count / 3 : count / 3;
5815
+ const at = (t, k) => index ? index.getX(t * 3 + k) : t * 3 + k;
5816
+ for (let t = 0; t < triangles; t += 1) {
5817
+ const a = at(t, 0);
5818
+ const b = at(t, 1);
5819
+ const c = at(t, 2);
5820
+ const key = keys[a];
5821
+ if (!key || keys[b] !== key || keys[c] !== key) {
5822
+ continue;
5823
+ }
5824
+ const p = restPositions;
5825
+ const ax = p[a * 3], ay = p[a * 3 + 1], az = p[a * 3 + 2];
5826
+ const bx = p[b * 3], by = p[b * 3 + 1], bz = p[b * 3 + 2];
5827
+ const cx = p[c * 3], cy = p[c * 3 + 1], cz = p[c * 3 + 2];
5828
+ const longest = Math.max(
5829
+ Math.hypot(ax - bx, ay - by, az - bz),
5830
+ Math.hypot(bx - cx, by - cy, bz - cz),
5831
+ Math.hypot(cx - ax, cy - ay, cz - az)
5832
+ );
5833
+ if (longest < TRIANGLE_SAMPLE_EDGE) {
5834
+ continue;
5835
+ }
5836
+ pushPoint(
5837
+ key,
5838
+ (ax + bx + cx) / 3,
5839
+ (ay + by + cy) / 3,
5840
+ (az + bz + cz) / 3
5841
+ );
5842
+ pushPoint(key, (ax + bx) / 2, (ay + by) / 2, (az + bz) / 2);
5843
+ pushPoint(key, (bx + cx) / 2, (by + cy) / 2, (bz + cz) / 2);
5844
+ pushPoint(key, (cx + ax) / 2, (cy + ay) / 2, (cz + az) / 2);
5845
+ }
5846
+ });
5847
+ const maps = [];
5848
+ for (const kind of ["body", "cloth"]) {
5849
+ for (const bone of TORSO_PARTS) {
5850
+ const origin = rest.get(bone);
5851
+ const points = partPoints.get(`${bone}|${kind}`);
5852
+ const map = origin && points ? buildRadialMap(bone, origin, UP, points) : null;
5853
+ if (map) maps.push({ ...map, kind });
5854
+ }
5855
+ for (const [bone, end] of LIMB_PARTS) {
5856
+ const origin = rest.get(bone);
5857
+ const target = rest.get(end);
5858
+ const points = partPoints.get(`${bone}|${kind}`);
5859
+ const map = origin && target && points ? buildRadialMap(bone, origin, target.clone().sub(origin), points) : null;
5860
+ if (map) maps.push({ ...map, kind });
5861
+ }
5862
+ }
5863
+ const hands = { left: [], right: [] };
5864
+ for (const side of SIDES) {
5865
+ const list = handPoints[side];
5866
+ const step = Math.max(1, Math.floor(list.length / MAX_HAND_POINTS));
5867
+ for (let i = 0; i < list.length; i += step) {
5868
+ hands[side].push(list[i]);
5869
+ }
5870
+ const wrist = `${side}Hand`;
5871
+ hands[side].push({ bone: wrist, rest: rest.get(wrist).clone() });
5872
+ }
5873
+ if (!maps.length) {
5874
+ return null;
5875
+ }
5876
+ const forward = new Vector34(0, 0, 1);
5877
+ const foot = rest.get("leftFoot");
5878
+ const toes = rest.get("leftToes");
5879
+ if (foot && toes) {
5880
+ const step = toes.clone().sub(foot).setY(0);
5881
+ if (step.lengthSq() > 1e-6) {
5882
+ forward.copy(step.normalize());
5883
+ }
5884
+ }
5885
+ const handLength = { left: 0, right: 0 };
5886
+ for (const side of SIDES) {
5887
+ const wrist = rest.get(`${side}Hand`);
5888
+ for (const point of hands[side]) {
5889
+ handLength[side] = Math.max(
5890
+ handLength[side],
5891
+ point.rest.distanceTo(wrist)
5892
+ );
5893
+ }
5894
+ }
5895
+ const mouth = restMouth(vrm, toRig);
5896
+ return { rest, parent, order, maps, hands, forward, mouth, handLength };
5897
+ });
5898
+ };
5899
+ var bodyModelOf = function(vrm) {
5900
+ if (!bodyModels.has(vrm)) {
5901
+ const humanoid = vrm.humanoid;
5902
+ let model = null;
5903
+ if (humanoid?.humanBones && typeof humanoid.getRawBoneNode === "function" && typeof humanoid.resetNormalizedPose === "function") {
5904
+ try {
5905
+ model = buildBodyModel(vrm);
5906
+ } catch {
5907
+ model = null;
5908
+ }
5909
+ }
5910
+ bodyModels.set(vrm, model);
5911
+ }
5912
+ return bodyModels.get(vrm) ?? null;
5913
+ };
5914
+ var solvePose = function(model, local, hips, only, into) {
5915
+ const pose = into ?? { rotation: /* @__PURE__ */ new Map(), position: /* @__PURE__ */ new Map() };
5916
+ for (const name of model.order) {
5917
+ if (only && !only.has(name)) {
5918
+ continue;
5919
+ }
5920
+ const up = model.parent.get(name) ?? null;
5921
+ const q = local.get(name);
5922
+ if (!up) {
5923
+ pose.rotation.set(name, (q ?? new Quaternion3()).clone());
5924
+ pose.position.set(name, (hips ?? model.rest.get(name)).clone());
5925
+ continue;
5926
+ }
5927
+ const parentRotation = pose.rotation.get(up);
5928
+ const parentPosition = pose.position.get(up);
5929
+ pose.rotation.set(
5930
+ name,
5931
+ q ? parentRotation.clone().multiply(q) : parentRotation.clone()
5932
+ );
5933
+ pose.position.set(
5934
+ name,
5935
+ model.rest.get(name).clone().sub(model.rest.get(up)).applyQuaternion(parentRotation).add(parentPosition)
5936
+ );
5937
+ }
5938
+ return pose;
5939
+ };
5940
+ var pointInPose = function(model, pose, point) {
5941
+ return point.rest.clone().sub(model.rest.get(point.bone)).applyQuaternion(pose.rotation.get(point.bone)).add(pose.position.get(point.bone));
5942
+ };
5943
+ var trackOf = function(clip, name) {
5944
+ return clip.tracks.find(
5945
+ (track) => track.name === name && track.times.length > 0
5946
+ );
5947
+ };
5948
+ var sampleClipFrames = function(model, vrm, clip, fps) {
5949
+ if (clip.duration <= 0) {
5950
+ return null;
5951
+ }
5952
+ const nodeName = (name) => vrm.humanoid.getNormalizedBoneNode(name)?.name;
5953
+ const armTrack = ["leftUpperArm", "rightUpperArm"].map((bone) => nodeName(bone)).map((node) => node ? trackOf(clip, `${node}.quaternion`) : void 0).find((track) => track && track.times.length >= 2);
5954
+ const count = Math.max(2, Math.round(clip.duration * fps) + 1);
5955
+ const times = armTrack ? Array.from(armTrack.times) : Array.from({ length: count }, (_, i) => Math.min(clip.duration, i / fps));
5956
+ const interpolants = /* @__PURE__ */ new Map();
5957
+ for (const name of model.order) {
5958
+ const node = nodeName(name);
5959
+ const track = node ? trackOf(clip, `${node}.quaternion`) : void 0;
5960
+ if (track) {
5961
+ interpolants.set(
5962
+ name,
5963
+ new QuaternionLinearInterpolant(track.times, track.values, 4)
5964
+ );
5965
+ }
5966
+ }
5967
+ if (!interpolants.has("leftUpperArm") && !interpolants.has("rightUpperArm")) {
5968
+ return null;
5969
+ }
5970
+ const hipsNode = nodeName("hips");
5971
+ const hipsTrack = hipsNode ? trackOf(clip, `${hipsNode}.position`) : void 0;
5972
+ const hipsInterpolant = hipsTrack ? new LinearInterpolant(hipsTrack.times, hipsTrack.values, 3) : void 0;
5973
+ const frames = times.map((time) => {
5974
+ const local = /* @__PURE__ */ new Map();
5975
+ for (const [name, interpolant] of interpolants) {
5976
+ const v = interpolant.evaluate(time);
5977
+ local.set(name, new Quaternion3(v[0], v[1], v[2], v[3]).normalize());
5978
+ }
5979
+ const h = hipsInterpolant?.evaluate(time);
5980
+ return { local, hips: h ? new Vector34(h[0], h[1], h[2]) : null };
5981
+ });
5982
+ return { times, frames, nodeName };
5983
+ };
5984
+
5985
+ // ../vrm-renderer/src/face-reach.ts
5986
+ var SOMA_REST = {
5987
+ hips: [0, 1, 0],
5988
+ spine: [-1e-4, 1.05, -5e-4],
5989
+ chest: [-1e-4, 1.1213, -8e-4],
5990
+ upperChest: [-1e-4, 1.1968, -9e-3],
5991
+ neck: [-2e-3, 1.4599, -0.0145],
5992
+ head: [-11e-4, 1.5994, 0.0241],
5993
+ leftShoulder: [0.0161, 1.4292, 0.0421],
5994
+ leftUpperArm: [0.1653, 1.4292, -0.0129],
5995
+ leftLowerArm: [0.4527, 1.4292, -0.0129],
5996
+ leftHand: [0.7236, 1.4292, -0.0129],
5997
+ rightShoulder: [-0.0139, 1.4286, 0.0431],
5998
+ rightUpperArm: [-0.1643, 1.4286, -0.0123],
5999
+ rightLowerArm: [-0.4517, 1.4286, -0.0123],
6000
+ rightHand: [-0.723, 1.4286, -0.0123]
6001
+ };
6002
+ var SOMA_PARENT = {
6003
+ spine: "hips",
6004
+ chest: "spine",
6005
+ upperChest: "chest",
6006
+ neck: "upperChest",
6007
+ head: "neck",
6008
+ leftShoulder: "upperChest",
6009
+ leftUpperArm: "leftShoulder",
6010
+ leftLowerArm: "leftUpperArm",
6011
+ leftHand: "leftLowerArm",
6012
+ rightShoulder: "upperChest",
6013
+ rightUpperArm: "rightShoulder",
6014
+ rightLowerArm: "rightUpperArm",
6015
+ rightHand: "rightLowerArm"
6016
+ };
6017
+ var SOMA_ORDER = Object.keys(SOMA_REST);
6018
+ var SOMA_MOUTH = new Vector35(2e-4, -0.0257, 0.1011);
6019
+ var SOMA_HAND_LENGTH = 0.19;
6020
+ var PALM_SHARE = 0.45;
6021
+ var NEAR = 0.05;
6022
+ var FAR = 0.09;
6023
+ var isKimodoAnimation = function(animation) {
6024
+ const hips = animation.restHipsPosition;
6025
+ return Math.abs(hips.x) < 1e-3 && Math.abs(hips.y - 1) < 1e-3 && Math.abs(hips.z) < 1e-3;
6026
+ };
6027
+ var smoothstep = function(edge0, edge1, x) {
6028
+ const t = Math.max(0, Math.min(1, (x - edge0) / (edge1 - edge0)));
6029
+ return t * t * (3 - 2 * t);
6030
+ };
6031
+ var somaPose = function(frame) {
6032
+ const pose = { rotation: /* @__PURE__ */ new Map(), position: /* @__PURE__ */ new Map() };
6033
+ for (const name of SOMA_ORDER) {
6034
+ const local = frame.local.get(name) ?? new Quaternion4();
6035
+ const up = SOMA_PARENT[name];
6036
+ const rest = new Vector35().fromArray(SOMA_REST[name]);
6037
+ if (!up) {
6038
+ pose.rotation.set(name, local.clone());
6039
+ pose.position.set(name, rest);
6040
+ continue;
6041
+ }
6042
+ const parentRotation = pose.rotation.get(up);
6043
+ pose.rotation.set(name, parentRotation.clone().multiply(local));
6044
+ pose.position.set(
6045
+ name,
6046
+ rest.sub(new Vector35().fromArray(SOMA_REST[up])).applyQuaternion(parentRotation).add(pose.position.get(up))
6047
+ );
6048
+ }
6049
+ return pose;
6050
+ };
6051
+ var palmOf = function(pose, rest, side, handLength) {
6052
+ const hand = `${side}Hand`;
6053
+ const lower = `${side}LowerArm`;
6054
+ const direction = rest(hand).clone().sub(rest(lower)).normalize();
6055
+ return direction.multiplyScalar(PALM_SHARE * handLength).applyQuaternion(pose.rotation.get(hand)).add(pose.position.get(hand));
6056
+ };
6057
+ var reachTarget = function(model, frame, pose, side) {
6058
+ if (!model.mouth) {
6059
+ return null;
6060
+ }
6061
+ const soma = somaPose(frame);
6062
+ const somaRest = (bone) => new Vector35().fromArray(SOMA_REST[bone]);
6063
+ const somaPalm = palmOf(soma, somaRest, side, SOMA_HAND_LENGTH);
6064
+ const somaHead = soma.rotation.get("head");
6065
+ const somaMouth = SOMA_MOUTH.clone().applyQuaternion(somaHead).add(soma.position.get("head"));
6066
+ const distance = somaPalm.distanceTo(somaMouth);
6067
+ const weight = 1 - smoothstep(NEAR, FAR, distance);
6068
+ if (weight <= 0) {
6069
+ return null;
6070
+ }
6071
+ const head = model.rest.get("head");
6072
+ const faceOffset = model.mouth.clone().sub(head);
6073
+ const scale = faceOffset.length() / SOMA_MOUTH.length();
6074
+ const relative = somaPalm.clone().sub(somaMouth).applyQuaternion(somaHead.clone().invert()).multiplyScalar(scale);
6075
+ const headRotation = pose.rotation.get("head");
6076
+ const mouth = faceOffset.applyQuaternion(headRotation).add(pose.position.get("head"));
6077
+ return {
6078
+ weight,
6079
+ target: relative.applyQuaternion(headRotation).add(mouth)
6080
+ };
6081
+ };
6082
+ var solveReach = function(model, pose, side, target) {
6083
+ const upper = `${side}UpperArm`;
6084
+ const lower = `${side}LowerArm`;
6085
+ const s = pose.position.get(upper);
6086
+ const e = pose.position.get(lower);
6087
+ const rest = (bone) => model.rest.get(bone);
6088
+ const palm = palmOf(pose, rest, side, model.handLength[side]);
6089
+ const forearm = palm.clone().sub(e);
6090
+ const a = e.distanceTo(s);
6091
+ const b = forearm.length();
6092
+ const wanted = Math.max(
6093
+ Math.abs(a - b) + 1e-4,
6094
+ Math.min(a + b - 1e-4, target.distanceTo(s))
6095
+ );
6096
+ const current = palm.distanceTo(s);
6097
+ const angleFor = (c) => Math.acos(Math.max(-1, Math.min(1, (a * a + b * b - c * c) / (2 * a * b))));
6098
+ const bend = angleFor(wanted) - angleFor(current);
6099
+ const upperDirection = e.clone().sub(s);
6100
+ let axis = new Vector35().crossVectors(upperDirection, forearm);
6101
+ if (axis.lengthSq() < 1e-10) {
6102
+ axis = new Vector35().crossVectors(upperDirection, model.forward);
6103
+ }
6104
+ axis.normalize();
6105
+ const elbow = new Quaternion4().setFromAxisAngle(axis, -bend);
6106
+ const bentPalm = forearm.clone().applyQuaternion(elbow).add(e);
6107
+ const shoulder = rotationBetween(bentPalm.sub(s), target.clone().sub(s));
6108
+ return {
6109
+ shoulder: quaternionToRotationVector(shoulder),
6110
+ elbow: quaternionToRotationVector(elbow)
6111
+ };
6112
+ };
6113
+ var rewrite = function(model, frames, bone, corrections, before) {
6114
+ return frames.map((source, index) => {
6115
+ const frame = before ? before(source, index) : source;
6116
+ const pose = solvePose(model, frame.local, frame.hips);
6117
+ const parent = model.parent.get(bone);
6118
+ const parentRotation = pose.rotation.get(parent);
6119
+ const world = parentRotation.clone().multiply(frame.local.get(bone) ?? new Quaternion4());
6120
+ return parentRotation.clone().invert().multiply(rotationVectorToQuaternion(corrections[index]).multiply(world)).normalize();
6121
+ });
6122
+ };
6123
+ var toTrack = function(name, times, values) {
6124
+ const flat = [];
6125
+ let previous = null;
6126
+ for (const q of values) {
6127
+ if (previous && previous.dot(q) < 0) {
6128
+ q.set(-q.x, -q.y, -q.z, -q.w);
6129
+ }
6130
+ previous = q;
6131
+ flat.push(q.x, q.y, q.z, q.w);
6132
+ }
6133
+ return new QuaternionKeyframeTrack(name, [...times], flat);
6134
+ };
6135
+ var applyFaceReach = function(clip, vrm, animation, fps = 30) {
6136
+ if (!isKimodoAnimation(animation)) {
6137
+ return clip;
6138
+ }
6139
+ const model = bodyModelOf(vrm);
6140
+ if (!model?.mouth || !model.rest.get("head")) {
6141
+ return clip;
6142
+ }
6143
+ const sampled = sampleClipFrames(model, vrm, clip, fps);
6144
+ if (!sampled) {
6145
+ return clip;
6146
+ }
6147
+ const { times, frames, nodeName } = sampled;
6148
+ const replaced = /* @__PURE__ */ new Map();
6149
+ for (const side of SIDES) {
6150
+ const upper = `${side}UpperArm`;
6151
+ const lower = `${side}LowerArm`;
6152
+ const upperNode = nodeName(upper);
6153
+ const lowerNode = nodeName(lower);
6154
+ if (!upperNode || !lowerNode || !model.parent.get(upper)) {
6155
+ continue;
6156
+ }
6157
+ const elbows = [];
6158
+ const shoulders = [];
6159
+ let any = false;
6160
+ for (const frame of frames) {
6161
+ const pose = solvePose(model, frame.local, frame.hips);
6162
+ const reach = reachTarget(model, frame, pose, side);
6163
+ if (!reach) {
6164
+ elbows.push(new Vector35());
6165
+ shoulders.push(new Vector35());
6166
+ continue;
6167
+ }
6168
+ any = true;
6169
+ const solved = solveReach(model, pose, side, reach.target);
6170
+ elbows.push(solved.elbow.multiplyScalar(reach.weight));
6171
+ shoulders.push(solved.shoulder.multiplyScalar(reach.weight));
6172
+ }
6173
+ if (!any) {
6174
+ continue;
6175
+ }
6176
+ const elbow = widenAndSmooth(elbows, 0, 2);
6177
+ const shoulder = widenAndSmooth(shoulders, 0, 2);
6178
+ const lowerValues = rewrite(model, frames, lower, elbow);
6179
+ const withElbow = (frame, index) => {
6180
+ const local = new Map(frame.local);
6181
+ local.set(lower, lowerValues[index].clone());
6182
+ return { local, hips: frame.hips };
6183
+ };
6184
+ const upperValues = rewrite(model, frames, upper, shoulder, withElbow);
6185
+ replaced.set(
6186
+ `${upperNode}.quaternion`,
6187
+ toTrack(`${upperNode}.quaternion`, times, upperValues)
6188
+ );
6189
+ replaced.set(
6190
+ `${lowerNode}.quaternion`,
6191
+ toTrack(`${lowerNode}.quaternion`, times, lowerValues)
6192
+ );
6193
+ }
6194
+ if (!replaced.size) {
6195
+ return clip;
6196
+ }
6197
+ const tracks = clip.tracks.filter((track) => !replaced.has(track.name));
6198
+ tracks.push(...replaced.values());
6199
+ return new AnimationClip(clip.name, clip.duration, tracks, clip.blendMode);
6200
+ };
6201
+
6202
+ // ../vrm-renderer/src/hand-clearance.ts
6203
+ import {
6204
+ AnimationClip as AnimationClip2,
6205
+ LinearInterpolant as LinearInterpolant2,
6206
+ Quaternion as Quaternion5,
6207
+ QuaternionKeyframeTrack as QuaternionKeyframeTrack2,
6208
+ QuaternionLinearInterpolant as QuaternionLinearInterpolant2,
6209
+ Vector3 as Vector36
6210
+ } from "three";
6211
+ var MAX_CORRECTION = 35 * Math.PI / 180;
6212
+ var CLOTH_CORRECTION_CAP = 10 * Math.PI / 180;
6213
+ var MAX_ITERATIONS = 6;
6214
+ var deepestContact = function(model, pose, side, kind) {
6215
+ let best = null;
6216
+ const perMap = [];
6217
+ const points = model.hands[side].map(
6218
+ (handPoint) => pointInPose(model, pose, handPoint)
6219
+ );
6220
+ const inverse = new Quaternion5();
6221
+ const local = new Vector36();
6222
+ for (const map of model.maps) {
6223
+ if ((map.kind ?? "body") !== kind) {
6224
+ continue;
6225
+ }
6226
+ const bone = map.bone;
6227
+ const rotation = pose.rotation.get(bone);
6228
+ const position = pose.position.get(bone);
6229
+ if (!rotation || !position) {
6230
+ continue;
6231
+ }
6232
+ inverse.copy(rotation).invert();
6233
+ const rest = model.rest.get(bone);
6234
+ const torso = TORSO_PARTS.includes(bone);
6235
+ let mapBest = null;
6236
+ for (const point of points) {
6237
+ local.copy(point).sub(position).applyQuaternion(inverse).add(rest);
6238
+ const hit = queryRadialMap(map, local);
6239
+ if (hit.depth <= 0) {
6240
+ continue;
6241
+ }
6242
+ if (torso) {
6243
+ const front = escapeAlong(map, local, model.forward);
6244
+ if (front <= 1.5 * hit.depth + 0.01) {
6245
+ hit.depth = front;
6246
+ hit.direction = model.forward.clone();
6247
+ }
6248
+ }
6249
+ if (!mapBest || hit.depth > mapBest.depth) {
6250
+ mapBest = {
6251
+ bone: map.bone,
6252
+ point,
6253
+ depth: hit.depth,
6254
+ direction: hit.direction.clone().applyQuaternion(rotation),
6255
+ side: hit.side && {
6256
+ depth: hit.side.depth,
6257
+ direction: hit.side.direction.clone().applyQuaternion(rotation)
6258
+ }
6259
+ };
6260
+ }
6261
+ }
6262
+ if (mapBest) {
6263
+ perMap.push(mapBest);
6264
+ if (!best || mapBest.depth > best.depth) {
6265
+ best = mapBest;
6266
+ }
6267
+ }
6268
+ }
6269
+ if (!best || perMap.length < 2) {
6270
+ return best;
6271
+ }
6272
+ const push = new Vector36();
6273
+ for (const contact of perMap) {
6274
+ push.addScaledVector(contact.direction, contact.depth);
6275
+ }
6276
+ if (push.length() < best.depth * 0.5) {
6277
+ return best;
6278
+ }
6279
+ return {
6280
+ bone: perMap.map((contact) => contact.bone).join("+"),
6281
+ point: best.point,
6282
+ depth: push.length(),
6283
+ direction: push.normalize()
6284
+ };
6285
+ };
6286
+ var ARM_CHAIN = function(model, side) {
6287
+ const result = /* @__PURE__ */ new Set();
6288
+ for (const name of model.order) {
6289
+ let node = name;
6290
+ while (node) {
6291
+ if (node === `${side}UpperArm`) {
6292
+ result.add(name);
6293
+ break;
6294
+ }
6295
+ node = model.parent.get(node) ?? null;
6296
+ }
6297
+ }
6298
+ return result;
6299
+ };
6300
+ var frameCorrections = function(model, frames, side, start, margin, kind, debug) {
6301
+ const upper = `${side}UpperArm`;
6302
+ const chain = ARM_CHAIN(model, side);
6303
+ const upperParent = model.parent.get(upper);
6304
+ return frames.map((frame, index) => {
6305
+ const pose = solvePose(model, frame.local, frame.hips);
6306
+ const original = frame.local.get(upper) ?? new Quaternion5();
6307
+ const parentRotation = pose.rotation.get(upperParent);
6308
+ const parentInverse = parentRotation.clone().invert();
6309
+ const correction = rotationVectorToQuaternion(start[index]);
6310
+ const local = new Map(frame.local);
6311
+ const apply = () => {
6312
+ const world = parentRotation.clone().multiply(original);
6313
+ local.set(
6314
+ upper,
6315
+ parentInverse.clone().multiply(correction.clone().multiply(world))
6316
+ );
6317
+ solvePose(model, local, frame.hips, chain, pose);
6318
+ };
6319
+ apply();
6320
+ const added = new Quaternion5();
6321
+ for (let iteration = 0; iteration < MAX_ITERATIONS; iteration += 1) {
6322
+ const contact = deepestContact(model, pose, side, kind);
6323
+ if (!contact) {
6324
+ break;
6325
+ }
6326
+ const shoulder = pose.position.get(upper);
6327
+ const from = contact.point.clone().sub(shoulder);
6328
+ let way = { depth: contact.depth, direction: contact.direction };
6329
+ if (contact.side && Math.abs(from.clone().normalize().dot(contact.direction)) > 0.7) {
6330
+ way = contact.side;
6331
+ }
6332
+ const to = contact.point.clone().addScaledVector(way.direction, way.depth + margin).sub(shoulder);
6333
+ const step = rotationBetween(from, to);
6334
+ const next = step.clone().multiply(added);
6335
+ debug?.({
6336
+ side,
6337
+ kind,
6338
+ frame: index,
6339
+ iteration,
6340
+ bone: contact.bone,
6341
+ depth: contact.depth,
6342
+ direction: contact.direction.toArray(),
6343
+ stepDegrees: quaternionToRotationVector(step).length() * 180 / Math.PI,
6344
+ totalDegrees: quaternionToRotationVector(next).length() * 180 / Math.PI
6345
+ });
6346
+ const nextAngle = quaternionToRotationVector(next).length();
6347
+ if (kind === "cloth" && nextAngle > CLOTH_CORRECTION_CAP) {
6348
+ const capped = rotationVectorToQuaternion(
6349
+ quaternionToRotationVector(next).multiplyScalar(
6350
+ CLOTH_CORRECTION_CAP / nextAngle
6351
+ )
6352
+ );
6353
+ const cappedStep = capped.clone().multiply(added.clone().invert());
6354
+ const total = cappedStep.clone().multiply(correction);
6355
+ if (quaternionToRotationVector(total).length() <= MAX_CORRECTION) {
6356
+ correction.premultiply(cappedStep);
6357
+ added.copy(capped);
6358
+ apply();
6359
+ }
6360
+ break;
6361
+ }
6362
+ const combined = step.clone().multiply(correction);
6363
+ if (quaternionToRotationVector(combined).length() > MAX_CORRECTION) {
6364
+ break;
6365
+ }
6366
+ correction.premultiply(step);
6367
+ added.copy(next);
6368
+ apply();
6369
+ }
6370
+ return quaternionToRotationVector(added);
6371
+ });
6372
+ };
6373
+ var solveHandClearance = function(model, frames, options = {}) {
6374
+ const margin = options.margin ?? 8e-3;
6375
+ const result = /* @__PURE__ */ new Map();
6376
+ for (const side of SIDES) {
6377
+ const upper = `${side}UpperArm`;
6378
+ if (!model.parent.get(upper)) {
6379
+ continue;
6380
+ }
6381
+ let total = frames.map(() => new Vector36());
6382
+ let changed = false;
6383
+ const compose = (raw) => {
6384
+ const smooth = widenAndSmooth(raw, 4, 3);
6385
+ total = total.map(
6386
+ (t, i) => quaternionToRotationVector(
6387
+ rotationVectorToQuaternion(smooth[i]).multiply(
6388
+ rotationVectorToQuaternion(t)
6389
+ )
6390
+ )
6391
+ );
6392
+ };
6393
+ for (const kind of ["body", "body", "cloth"]) {
6394
+ const raw = frameCorrections(
6395
+ model,
6396
+ frames,
6397
+ side,
6398
+ total,
6399
+ margin,
6400
+ kind,
6401
+ options.onDebug
6402
+ );
6403
+ if (raw.every((v) => v.lengthSq() < 1e-10)) {
6404
+ continue;
6405
+ }
6406
+ changed = true;
6407
+ compose(raw);
6408
+ }
6409
+ if (options.onReport) {
6410
+ const left = frameCorrections(model, frames, side, total, margin, "body");
6411
+ const degrees = total.map((v) => v.length() * 180 / Math.PI);
6412
+ options.onReport({
6413
+ side,
6414
+ maps: model.maps.map((m) => `${m.bone}:${m.kind ?? "body"}`),
6415
+ handPoints: model.hands[side].length,
6416
+ maxDegrees: Math.max(0, ...degrees),
6417
+ correctedFrames: degrees.filter((d) => d > 0.5).length,
6418
+ residualDegrees: Math.max(
6419
+ 0,
6420
+ ...left.map((v) => v.length() * 180 / Math.PI)
6421
+ )
6422
+ });
6423
+ }
6424
+ if (!changed) {
6425
+ continue;
6426
+ }
6427
+ let previous = null;
6428
+ result.set(
6429
+ upper,
6430
+ frames.map((frame, index) => {
6431
+ const pose = solvePose(model, frame.local, frame.hips);
6432
+ const parentRotation = pose.rotation.get(model.parent.get(upper));
6433
+ const original = frame.local.get(upper) ?? new Quaternion5();
6434
+ const world = parentRotation.clone().multiply(original);
6435
+ const corrected = parentRotation.clone().invert().multiply(rotationVectorToQuaternion(total[index]).multiply(world)).normalize();
6436
+ if (previous && previous.dot(corrected) < 0) {
6437
+ corrected.set(-corrected.x, -corrected.y, -corrected.z, -corrected.w);
6438
+ }
6439
+ previous = corrected;
6440
+ return corrected;
6441
+ })
6442
+ );
6443
+ }
6444
+ return result;
6445
+ };
6446
+ var applyHandClearance = function(clip, vrm, options = {}) {
6447
+ const model = bodyModelOf(vrm);
6448
+ if (!model || clip.duration <= 0) {
6449
+ return clip;
6450
+ }
6451
+ const sampled = sampleClipFrames(model, vrm, clip, options.fps ?? 30);
6452
+ if (!sampled) {
6453
+ return clip;
6454
+ }
6455
+ const { times, frames, nodeName } = sampled;
6456
+ const solved = solveHandClearance(model, frames, options);
6457
+ const replaced = /* @__PURE__ */ new Map();
6458
+ for (const [bone, rotations] of solved) {
6459
+ const node = nodeName(bone);
6460
+ if (!node) {
6461
+ continue;
6462
+ }
6463
+ replaced.set(
6464
+ `${node}.quaternion`,
6465
+ new QuaternionKeyframeTrack2(
6466
+ `${node}.quaternion`,
6467
+ times,
6468
+ rotations.flatMap((q) => [q.x, q.y, q.z, q.w])
6469
+ )
6470
+ );
6471
+ }
6472
+ if (!replaced.size) {
6473
+ return clip;
6474
+ }
6475
+ const tracks = clip.tracks.filter((track) => !replaced.has(track.name));
6476
+ tracks.push(...replaced.values());
6477
+ return new AnimationClip2(clip.name, clip.duration, tracks, clip.blendMode);
6478
+ };
6479
+
6480
+ // ../vrm-renderer/src/animation.ts
6481
+ import {
6482
+ AnimationClip as AnimationClip3,
6483
+ Euler,
6484
+ Quaternion as Quaternion6,
6485
+ QuaternionKeyframeTrack as QuaternionKeyframeTrack3,
6486
+ QuaternionLinearInterpolant as QuaternionLinearInterpolant3,
6487
+ Vector3 as Vector37,
5341
6488
  VectorKeyframeTrack
5342
6489
  } from "three";
5343
6490
  var NPCIFY_VRM_NORMALIZATION_ROOT_NAME = "NPCifyNormalizationRoot";
@@ -5353,8 +6500,8 @@ var PARENT_OF_HEAD_BONES = [
5353
6500
  ...TORSO_BONES,
5354
6501
  "neck"
5355
6502
  ];
5356
- var IDENTITY_QUATERNION = new Quaternion2();
5357
- var UP_AXIS = new Vector33(0, 1, 0);
6503
+ var IDENTITY_QUATERNION = new Quaternion6();
6504
+ var UP_AXIS = new Vector37(0, 1, 0);
5358
6505
  var MAX_HEAD_PITCH_CORRECTION_RAD = 35 * Math.PI / 180;
5359
6506
  var NECK_CORRECTION_SHARE = 0.35;
5360
6507
  var EPSILON = 1e-5;
@@ -5424,13 +6571,13 @@ var evaluateChainOrientation = function(bones, interpolants, time, rootPreRotati
5424
6571
  };
5425
6572
  var rotateQuaternionTrackInParentSpace = function(track, parentBones, interpolants, rootPreRotation, worldCorrection) {
5426
6573
  const values = new Float32Array(track.values.length);
5427
- const parentQuat = new Quaternion2();
5428
- const parentInvQuat = new Quaternion2();
5429
- const localCorrection = new Quaternion2();
5430
- const keyframeQuat = new Quaternion2();
5431
- const prevOrigQuat = new Quaternion2();
5432
- const prevNewQuat = new Quaternion2();
5433
- const scratchQuat = new Quaternion2();
6574
+ const parentQuat = new Quaternion6();
6575
+ const parentInvQuat = new Quaternion6();
6576
+ const localCorrection = new Quaternion6();
6577
+ const keyframeQuat = new Quaternion6();
6578
+ const prevOrigQuat = new Quaternion6();
6579
+ const prevNewQuat = new Quaternion6();
6580
+ const scratchQuat = new Quaternion6();
5434
6581
  const count = track.times.length;
5435
6582
  for (let i = 0; i < count; i += 1) {
5436
6583
  const time = track.times[i] ?? 0;
@@ -5472,7 +6619,7 @@ var rotateQuaternionTrackInParentSpace = function(track, parentBones, interpolan
5472
6619
  values[offset + 2] = keyframeQuat.z;
5473
6620
  values[offset + 3] = keyframeQuat.w;
5474
6621
  }
5475
- return new QuaternionKeyframeTrack(
6622
+ return new QuaternionKeyframeTrack3(
5476
6623
  track.name,
5477
6624
  Array.from(track.times),
5478
6625
  Array.from(values)
@@ -5524,7 +6671,7 @@ var normalizeIdleAnimationClip = function(clip, vrm) {
5524
6671
  if (track) {
5525
6672
  interpolants.set(
5526
6673
  bone,
5527
- new QuaternionLinearInterpolant(track.times, track.values, 4)
6674
+ new QuaternionLinearInterpolant3(track.times, track.values, 4)
5528
6675
  );
5529
6676
  }
5530
6677
  }
@@ -5537,11 +6684,11 @@ var normalizeIdleAnimationClip = function(clip, vrm) {
5537
6684
  for (let i = 0; i < sampleCount; i += 1) {
5538
6685
  sampleTimes.push(duration > 0 ? (i + 0.5) / sampleCount * duration : 0);
5539
6686
  }
5540
- const chainQuat = new Quaternion2();
5541
- const scratchQuat = new Quaternion2();
5542
- const forwardVec = new Vector33();
6687
+ const chainQuat = new Quaternion6();
6688
+ const scratchQuat = new Quaternion6();
6689
+ const forwardVec = new Vector37();
5543
6690
  const rootTorsoBone = TORSO_BONES.find((bone) => interpolants.has(bone));
5544
- const rootPreRotation = new Quaternion2();
6691
+ const rootPreRotation = new Quaternion6();
5545
6692
  let torsoYawCorrection = 0;
5546
6693
  if (rootTorsoBone) {
5547
6694
  let sumX = 0;
@@ -5575,7 +6722,7 @@ var normalizeIdleAnimationClip = function(clip, vrm) {
5575
6722
  let neckWorldCorrection = null;
5576
6723
  let headWorldCorrection = null;
5577
6724
  if (hasNeckTrack || hasHeadTrack) {
5578
- const meanHeadForward = new Vector33();
6725
+ const meanHeadForward = new Vector37();
5579
6726
  for (const time of sampleTimes) {
5580
6727
  evaluateChainOrientation(
5581
6728
  AXIAL_BONES,
@@ -5600,11 +6747,11 @@ var normalizeIdleAnimationClip = function(clip, vrm) {
5600
6747
  Math.min(MAX_HEAD_PITCH_CORRECTION_RAD, rawHeadPitch)
5601
6748
  );
5602
6749
  if (Math.abs(meanHeadYaw) > EPSILON || Math.abs(clampedHeadPitch) > EPSILON) {
5603
- const totalWorldCorrection = new Quaternion2().setFromEuler(
6750
+ const totalWorldCorrection = new Quaternion6().setFromEuler(
5604
6751
  new Euler(-clampedHeadPitch, -meanHeadYaw, 0, "XYZ")
5605
6752
  );
5606
6753
  if (hasNeckTrack && hasHeadTrack) {
5607
- neckWorldCorrection = new Quaternion2().setFromEuler(
6754
+ neckWorldCorrection = new Quaternion6().setFromEuler(
5608
6755
  new Euler(
5609
6756
  -clampedHeadPitch * NECK_CORRECTION_SHARE,
5610
6757
  -meanHeadYaw * NECK_CORRECTION_SHARE,
@@ -5666,17 +6813,22 @@ var normalizeIdleAnimationClip = function(clip, vrm) {
5666
6813
  }
5667
6814
  return track;
5668
6815
  });
5669
- return new AnimationClip(clip.name, clip.duration, nextTracks, clip.blendMode);
6816
+ return new AnimationClip3(clip.name, clip.duration, nextTracks, clip.blendMode);
5670
6817
  };
5671
6818
  var createVRMAnimationClip = function(animation, vrm, options) {
5672
6819
  const clip = createPixivVRMAnimationClip(
5673
6820
  animation,
5674
6821
  canonicalAnimationTarget(vrm)
5675
6822
  );
5676
- if (options?.normalizeIdleOrientation) {
5677
- return normalizeIdleAnimationClip(clip, vrm);
5678
- }
5679
- return clip;
6823
+ const oriented = options?.normalizeIdleOrientation ? normalizeIdleAnimationClip(clip, vrm) : clip;
6824
+ if (options?.handClearance === false) {
6825
+ return oriented;
6826
+ }
6827
+ return applyHandClearance(
6828
+ applyFaceReach(oriented, vrm, animation),
6829
+ vrm,
6830
+ options?.handClearanceOptions
6831
+ );
5680
6832
  };
5681
6833
 
5682
6834
  // ../vrm-renderer/src/session.ts
@@ -8420,7 +9572,7 @@ var FacialPerformanceInspector = class {
8420
9572
  };
8421
9573
 
8422
9574
  // ../../clients/web-client/src/character/idle-face.ts
8423
- import { Vector3 as Vector35 } from "three";
9575
+ import { Vector3 as Vector39 } from "three";
8424
9576
  var IdleFace = class {
8425
9577
  constructor(vrm, random) {
8426
9578
  this.vrm = vrm;
@@ -8428,7 +9580,7 @@ var IdleFace = class {
8428
9580
  }
8429
9581
  time = 0;
8430
9582
  timeline;
8431
- targetPosition = new Vector35();
9583
+ targetPosition = new Vector39();
8432
9584
  /** Advances by `delta` seconds, turns the eyes, and returns the blink weight. */
8433
9585
  update(delta, frame) {
8434
9586
  if (Number.isFinite(delta) && delta > 0) {
@@ -9237,17 +10389,17 @@ import {
9237
10389
  Euler as Euler2,
9238
10390
  Mesh,
9239
10391
  Object3D,
9240
- SkinnedMesh,
9241
- Vector3 as Vector36
10392
+ SkinnedMesh as SkinnedMesh2,
10393
+ Vector3 as Vector310
9242
10394
  } from "three";
9243
10395
  var isSkinnedMesh = function(object) {
9244
- return object instanceof SkinnedMesh || object.isSkinnedMesh === true;
10396
+ return object instanceof SkinnedMesh2 || object.isSkinnedMesh === true;
9245
10397
  };
9246
10398
  var isMesh = function(object) {
9247
10399
  return isSkinnedMesh(object) || object instanceof Mesh || object.isMesh === true;
9248
10400
  };
9249
10401
  var applyVector3 = function(target, value) {
9250
- if (value instanceof Vector36) {
10402
+ if (value instanceof Vector310) {
9251
10403
  target.copy(value);
9252
10404
  return;
9253
10405
  }
@@ -9622,10 +10774,10 @@ var CharacterSceneAccess = class {
9622
10774
  };
9623
10775
 
9624
10776
  // ../../clients/web-client/src/character/listening-reflex.ts
9625
- import { Object3D as Object3D2, Vector3 as Vector38 } from "three";
10777
+ import { Object3D as Object3D2, Vector3 as Vector312 } from "three";
9626
10778
 
9627
10779
  // ../../clients/web-client/src/character/head-nod.ts
9628
- import { Quaternion as Quaternion3, Vector3 as Vector37 } from "three";
10780
+ import { Quaternion as Quaternion7, Vector3 as Vector311 } from "three";
9629
10781
  var SHARES = [
9630
10782
  ["neck", 0.4],
9631
10783
  ["head", 0.6]
@@ -9635,7 +10787,7 @@ var FREQUENCY_TIMES_LENGTH = 1.4;
9635
10787
  var PULSE_PART = 0.3;
9636
10788
  var MAX_STEP_SECONDS = 1 / 240;
9637
10789
  var REST_DEGREES = 0.01;
9638
- var X_AXIS = new Vector37(1, 0, 0);
10790
+ var X_AXIS = new Vector311(1, 0, 0);
9639
10791
  var HeadNod = class {
9640
10792
  pitch = 0;
9641
10793
  speed = 0;
@@ -9644,7 +10796,7 @@ var HeadNod = class {
9644
10796
  amplitude = 0;
9645
10797
  omega = 0;
9646
10798
  applied = [];
9647
- scratch = new Quaternion3();
10799
+ scratch = new Quaternion7();
9648
10800
  /** The current pitch in degrees; positive turns the face down. */
9649
10801
  get pitchDegrees() {
9650
10802
  return this.pitch;
@@ -9736,8 +10888,8 @@ var ListeningReflex = class {
9736
10888
  pendingNod = null;
9737
10889
  releaseGaze = null;
9738
10890
  front = new Object3D2();
9739
- origin = new Vector38();
9740
- forward = new Vector38();
10891
+ origin = new Vector312();
10892
+ forward = new Vector312();
9741
10893
  yielded = false;
9742
10894
  /** Call after the animation mixer and live motion, before the facial mixer and `vrm.update()`. */
9743
10895
  update(delta, frame) {
@@ -9812,7 +10964,7 @@ var ListeningReflex = class {
9812
10964
  };
9813
10965
 
9814
10966
  // ../../clients/web-client/src/character/live-motion.ts
9815
- import { Quaternion as Quaternion4, Vector3 as Vector39 } from "three";
10967
+ import { Quaternion as Quaternion8, Vector3 as Vector313 } from "three";
9816
10968
  var PARENTS = {
9817
10969
  spine: "hips",
9818
10970
  chest: "spine",
@@ -9854,10 +11006,10 @@ var LiveMotionPlayer = class {
9854
11006
  /** The last applied pose, to blend out of it after the frames end. */
9855
11007
  lastPose = null;
9856
11008
  scratch = {
9857
- from: new Quaternion4(),
9858
- to: new Quaternion4(),
11009
+ from: new Quaternion8(),
11010
+ to: new Quaternion8(),
9859
11011
  carry: /* @__PURE__ */ new Map(),
9860
- position: new Vector39()
11012
+ position: new Vector313()
9861
11013
  };
9862
11014
  constructor(options = {}) {
9863
11015
  this.rootMode = options.rootMode ?? "anchored";
@@ -10019,7 +11171,7 @@ var LiveMotionPlayer = class {
10019
11171
  carry.clear();
10020
11172
  track.bones.forEach((bone, slot) => {
10021
11173
  const offset = 3 + slot * 4;
10022
- const rotation = new Quaternion4(
11174
+ const rotation = new Quaternion8(
10023
11175
  values[offset] ?? 0,
10024
11176
  values[offset + 1] ?? 0,
10025
11177
  values[offset + 2] ?? 0,