@asiyst/sdk 0.1.34 → 0.1.36

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.
package/dist/index.cjs CHANGED
@@ -107,7 +107,7 @@ var ALL_ACTION_KINDS = [
107
107
  // src/core/constants.ts
108
108
  function resolveSdkVersion() {
109
109
  {
110
- return "0.1.34";
110
+ return "0.1.36";
111
111
  }
112
112
  }
113
113
  var SDK_VERSION = resolveSdkVersion();
@@ -634,9 +634,30 @@ var HttpTransport = class {
634
634
  if (req.body !== void 0) {
635
635
  defaultHeaders["Content-Type"] = "application/json";
636
636
  }
637
+ const mergedHeaders = new Headers();
638
+ for (const [key, value] of Object.entries(defaultHeaders)) {
639
+ mergedHeaders.set(key, value);
640
+ }
641
+ if (req.headers) {
642
+ if (typeof req.headers.forEach === "function" && !Array.isArray(req.headers)) {
643
+ req.headers.forEach((value, key) => {
644
+ mergedHeaders.set(key, value);
645
+ });
646
+ } else if (Array.isArray(req.headers)) {
647
+ for (const [key, value] of req.headers) {
648
+ mergedHeaders.set(key, value);
649
+ }
650
+ } else if (typeof req.headers === "object") {
651
+ for (const [key, value] of Object.entries(req.headers)) {
652
+ if (value !== void 0 && value !== null) {
653
+ mergedHeaders.set(key, String(value));
654
+ }
655
+ }
656
+ }
657
+ }
637
658
  const response = await fetch(url, {
638
659
  method: req.method,
639
- headers: req.headers ?? defaultHeaders,
660
+ headers: mergedHeaders,
640
661
  body: req.body === void 0 ? void 0 : JSON.stringify(req.body),
641
662
  signal: controller.signal
642
663
  });
@@ -854,9 +875,18 @@ var CloudClient = class {
854
875
  avatarId: this.avatarId || void 0
855
876
  }
856
877
  );
857
- let response;
858
- try {
859
- response = await this.transport.request({
878
+ let token;
879
+ if (this.runtimeAuth) {
880
+ try {
881
+ token = await this.getAuthToken();
882
+ } catch {
883
+ token = this.activeToken;
884
+ }
885
+ } else {
886
+ token = this.activeToken;
887
+ }
888
+ const executeRequest = async (authToken) => {
889
+ return this.transport.request({
860
890
  path: runtimeAvatarUrl,
861
891
  method: "GET",
862
892
  idempotent: true,
@@ -866,10 +896,26 @@ var CloudClient = class {
866
896
  "X-Asiyst-Public-Key": this.publicKey,
867
897
  "X-Asiyst-Project-Key": this.publicKey,
868
898
  "X-Asiyst-Project-Id": this.projectId,
899
+ "X-Asiyst-SDK-Version": SDK_VERSION,
869
900
  ...this.avatarId ? { "X-Asiyst-Avatar-Id": this.avatarId } : {},
870
- ...etag ? { "If-None-Match": etag } : {}
901
+ ...etag ? { "If-None-Match": etag } : {},
902
+ ...authToken ? { Authorization: `Bearer ${authToken}` } : {},
903
+ ...this.sessionId ? { "X-Asiyst-Session-Id": this.sessionId } : {}
871
904
  }
872
905
  });
906
+ };
907
+ let response;
908
+ try {
909
+ response = await executeRequest(token);
910
+ if (response.status === 401 && this.runtimeAuth) {
911
+ this.runtimeAuth.invalidate();
912
+ try {
913
+ token = await this.runtimeAuth.getToken();
914
+ this.activeToken = token;
915
+ response = await executeRequest(token);
916
+ } catch {
917
+ }
918
+ }
873
919
  } catch (err) {
874
920
  throw new AsiystError({
875
921
  code: "CORS_OR_NETWORK_FAILURE",
@@ -3325,27 +3371,57 @@ var RigDetector = class {
3325
3371
  return rawName.trim().replace(/^.*[:|/]/, "").replace(/^(mixamorig\d*|bip01|armature|root)[:_ ]?/i, "").replace(/[^a-zA-Z0-9._-]/g, "").toLowerCase();
3326
3372
  }
3327
3373
  /**
3328
- * Analyzes an imported 3D model root, identifies all bones, maps them to canonical AUBR,
3329
- * validates hierarchy, and reports capability profile.
3374
+ * Analyzes an imported 3D model root, identifies all bones and skinned meshes,
3375
+ * maps them to canonical AUBR, validates hierarchy, and reports capability profile.
3330
3376
  */
3331
- static detect(modelRoot) {
3377
+ static detect(modelRoot, options) {
3332
3378
  const allBones = [];
3379
+ const seenBones = /* @__PURE__ */ new Set();
3380
+ const skinnedMeshes = [];
3333
3381
  modelRoot.traverse((node) => {
3334
- if (node.isBone) {
3382
+ if (node.isSkinnedMesh) {
3383
+ const sm = node;
3384
+ skinnedMeshes.push(sm);
3385
+ if (sm.skeleton?.bones) {
3386
+ for (const b of sm.skeleton.bones) {
3387
+ if (b && !seenBones.has(b)) {
3388
+ seenBones.add(b);
3389
+ allBones.push(b);
3390
+ }
3391
+ }
3392
+ }
3393
+ }
3394
+ if (node.isBone && !seenBones.has(node)) {
3395
+ seenBones.add(node);
3335
3396
  allBones.push(node);
3336
3397
  }
3337
3398
  });
3338
3399
  if (allBones.length === 0) {
3339
3400
  modelRoot.traverse((node) => {
3401
+ if (node.isMesh) return;
3340
3402
  if (node.name && (node.type === "Bone" || /bone|joint|limb|hips|spine|arm|leg|head/i.test(node.name))) {
3341
- if (!allBones.includes(node)) {
3403
+ if (!seenBones.has(node)) {
3404
+ seenBones.add(node);
3342
3405
  allBones.push(node);
3343
3406
  }
3344
3407
  }
3345
3408
  });
3346
3409
  }
3410
+ const embeddedAnimationCount = typeof options?.embeddedAnimationCount === "number" && Number.isFinite(options.embeddedAnimationCount) ? Math.max(0, Math.floor(options.embeddedAnimationCount)) : Array.isArray(modelRoot.animations) ? modelRoot.animations.length : 0;
3411
+ const hasEmbeddedAnimations = embeddedAnimationCount > 0;
3412
+ const skinnedMeshCount = skinnedMeshes.length;
3413
+ const hasSkinnedMesh = skinnedMeshCount > 0;
3414
+ const boneCount = allBones.length;
3415
+ const hasSkeleton = boneCount > 0;
3347
3416
  if (allBones.length === 0) {
3348
- const caps = this.createUnsupportedCapabilities("unsupported", ["hips", "spine", "head"]);
3417
+ const caps = this.createUnsupportedCapabilities("unsupported", ["hips", "spine", "head"], {
3418
+ hasSkeleton,
3419
+ hasSkinnedMesh,
3420
+ boneCount,
3421
+ skinnedMeshCount,
3422
+ embeddedAnimationCount,
3423
+ hasEmbeddedAnimations
3424
+ });
3349
3425
  return {
3350
3426
  rigType: "unsupported",
3351
3427
  capabilities: caps,
@@ -3386,26 +3462,43 @@ var RigDetector = class {
3386
3462
  const hasArms = matchedBones.has("leftUpperArm") && matchedBones.has("leftLowerArm") && matchedBones.has("rightUpperArm") && matchedBones.has("rightLowerArm");
3387
3463
  const isHumanoid = hasHipsAndSpine && (hasLegs || hasArms);
3388
3464
  let finalRigType = rigFlavor;
3465
+ const detectedRigFlavor = isHumanoid ? rigFlavor : "unsupported";
3389
3466
  if (!isHumanoid) {
3390
3467
  finalRigType = "unsupported";
3391
3468
  } else if (missingRequired.length > 0) {
3392
3469
  finalRigType = "partial_humanoid";
3393
3470
  }
3471
+ const proceduralIdle = isHumanoid && hasHipsAndSpine && hasHead;
3472
+ const proceduralLocomotion = isHumanoid && hasLegs;
3473
+ const proceduralRunning = isHumanoid && hasLegs;
3474
+ const upperBodyGestures = isHumanoid && hasArms && hasHipsAndSpine;
3475
+ const proceduralAnimationAvailable = proceduralIdle || proceduralLocomotion || upperBodyGestures;
3476
+ const clipPlayback = hasSkeleton && allBones.length > 5 || hasEmbeddedAnimations;
3477
+ const animationSourceMode = proceduralAnimationAvailable && hasEmbeddedAnimations ? "embedded_and_procedural" : proceduralAnimationAvailable ? "procedural_only" : hasEmbeddedAnimations ? "embedded_only" : "static";
3394
3478
  const capabilities = {
3395
3479
  rigType: finalRigType,
3480
+ detectedRigFlavor,
3396
3481
  isHumanoid,
3482
+ hasSkeleton,
3483
+ hasSkinnedMesh,
3484
+ boneCount,
3485
+ skinnedMeshCount,
3397
3486
  confidence: Math.round(confidence * 100) / 100,
3398
- proceduralIdle: hasHipsAndSpine && hasHead,
3399
- proceduralLocomotion: isHumanoid && hasLegs,
3400
- proceduralRunning: isHumanoid && hasLegs,
3487
+ proceduralAnimationAvailable,
3488
+ proceduralIdle,
3489
+ proceduralLocomotion,
3490
+ proceduralRunning,
3401
3491
  turning: isHumanoid,
3402
- legIK: hasLegs,
3403
- armIK: hasArms,
3404
- footPlacement: hasLegs,
3405
- headLookAt: hasHead,
3406
- upperBodyGestures: hasArms && hasHipsAndSpine,
3492
+ legIK: isHumanoid && hasLegs,
3493
+ armIK: isHumanoid && hasArms,
3494
+ footPlacement: isHumanoid && hasLegs,
3495
+ headLookAt: isHumanoid && hasHead,
3496
+ upperBodyGestures,
3407
3497
  facialAnimation: this.detectFacialCapabilities(modelRoot),
3408
- clipPlayback: allBones.length > 5,
3498
+ hasEmbeddedAnimations,
3499
+ embeddedAnimationCount,
3500
+ clipPlayback,
3501
+ animationSourceMode,
3409
3502
  missingRequiredBones: missingRequired,
3410
3503
  missingOptionalBones: missingOptional
3411
3504
  };
@@ -3420,15 +3513,15 @@ var RigDetector = class {
3420
3513
  /**
3421
3514
  * Alias for detect()
3422
3515
  */
3423
- static detectRig(modelRoot) {
3424
- return this.detect(modelRoot);
3516
+ static detectRig(modelRoot, options) {
3517
+ return this.detect(modelRoot, options);
3425
3518
  }
3426
3519
  /**
3427
3520
  * Assesses avatar rig capabilities from detection result or model.
3428
3521
  */
3429
- static assessCapabilities(detection, modelRoot) {
3522
+ static assessCapabilities(detection, modelRoot, options) {
3430
3523
  if (modelRoot) {
3431
- return this.detect(modelRoot).capabilities;
3524
+ return this.detect(modelRoot, options).capabilities;
3432
3525
  }
3433
3526
  return detection.capabilities;
3434
3527
  }
@@ -3493,6 +3586,24 @@ var RigDetector = class {
3493
3586
  if (rightLow && rightFoot && !this.isDescendantOf(rightFoot, rightLow)) {
3494
3587
  matched.delete("rightFoot");
3495
3588
  }
3589
+ const leftUpArm = matched.get("leftUpperArm");
3590
+ const leftLowArm = matched.get("leftLowerArm");
3591
+ const leftHand = matched.get("leftHand");
3592
+ if (leftUpArm && leftLowArm && !this.isDescendantOf(leftLowArm, leftUpArm)) {
3593
+ matched.delete("leftLowerArm");
3594
+ }
3595
+ if (leftLowArm && leftHand && !this.isDescendantOf(leftHand, leftLowArm)) {
3596
+ matched.delete("leftHand");
3597
+ }
3598
+ const rightUpArm = matched.get("rightUpperArm");
3599
+ const rightLowArm = matched.get("rightLowerArm");
3600
+ const rightHand = matched.get("rightHand");
3601
+ if (rightUpArm && rightLowArm && !this.isDescendantOf(rightLowArm, rightUpArm)) {
3602
+ matched.delete("rightLowerArm");
3603
+ }
3604
+ if (rightLowArm && rightHand && !this.isDescendantOf(rightHand, rightLowArm)) {
3605
+ matched.delete("rightHand");
3606
+ }
3496
3607
  const hips = matched.get("hips");
3497
3608
  const spine = matched.get("spine");
3498
3609
  const head = matched.get("head");
@@ -3521,11 +3632,19 @@ var RigDetector = class {
3521
3632
  });
3522
3633
  return hasMorphTargets;
3523
3634
  }
3524
- static createUnsupportedCapabilities(rigType, missingReq) {
3635
+ static createUnsupportedCapabilities(rigType, missingReq, meta) {
3636
+ const hasEmbeddedAnimations = meta?.hasEmbeddedAnimations ?? false;
3637
+ const embeddedAnimationCount = meta?.embeddedAnimationCount ?? 0;
3525
3638
  return {
3526
3639
  rigType,
3640
+ detectedRigFlavor: rigType,
3527
3641
  isHumanoid: false,
3642
+ hasSkeleton: meta?.hasSkeleton ?? false,
3643
+ hasSkinnedMesh: meta?.hasSkinnedMesh ?? false,
3644
+ boneCount: meta?.boneCount ?? 0,
3645
+ skinnedMeshCount: meta?.skinnedMeshCount ?? 0,
3528
3646
  confidence: 0,
3647
+ proceduralAnimationAvailable: false,
3529
3648
  proceduralIdle: false,
3530
3649
  proceduralLocomotion: false,
3531
3650
  proceduralRunning: false,
@@ -3536,7 +3655,10 @@ var RigDetector = class {
3536
3655
  headLookAt: false,
3537
3656
  upperBodyGestures: false,
3538
3657
  facialAnimation: false,
3539
- clipPlayback: false,
3658
+ hasEmbeddedAnimations,
3659
+ embeddedAnimationCount,
3660
+ clipPlayback: hasEmbeddedAnimations,
3661
+ animationSourceMode: hasEmbeddedAnimations ? "embedded_only" : "static",
3540
3662
  missingRequiredBones: missingReq,
3541
3663
  missingOptionalBones: [...OPTIONAL_CANONICAL_BONES]
3542
3664
  };
@@ -3597,12 +3719,16 @@ ScratchMath.v4 = new THREE__namespace.Vector3();
3597
3719
  ScratchMath.v5 = new THREE__namespace.Vector3();
3598
3720
  ScratchMath.v6 = new THREE__namespace.Vector3();
3599
3721
  ScratchMath.v7 = new THREE__namespace.Vector3();
3722
+ ScratchMath.v8 = new THREE__namespace.Vector3();
3723
+ ScratchMath.v9 = new THREE__namespace.Vector3();
3600
3724
  // Quaternion scratch pool
3601
3725
  ScratchMath.q0 = new THREE__namespace.Quaternion();
3602
3726
  ScratchMath.q1 = new THREE__namespace.Quaternion();
3603
3727
  ScratchMath.q2 = new THREE__namespace.Quaternion();
3604
3728
  ScratchMath.q3 = new THREE__namespace.Quaternion();
3605
3729
  ScratchMath.q4 = new THREE__namespace.Quaternion();
3730
+ ScratchMath.q5 = new THREE__namespace.Quaternion();
3731
+ ScratchMath.q6 = new THREE__namespace.Quaternion();
3606
3732
  // Matrix4 scratch pool
3607
3733
  ScratchMath.m0 = new THREE__namespace.Matrix4();
3608
3734
  ScratchMath.m1 = new THREE__namespace.Matrix4();
@@ -3619,16 +3745,29 @@ ScratchMath.LEFT = new THREE__namespace.Vector3(-1, 0, 0);
3619
3745
 
3620
3746
  // src/avatar/procedural/AUBRSkeleton.ts
3621
3747
  var AUBRSkeleton = class {
3622
- constructor(modelRoot) {
3748
+ constructor(modelRoot, options) {
3623
3749
  this.joints = /* @__PURE__ */ new Map();
3750
+ /** Rest foot positions in modelRoot local space */
3751
+ this.restLeftFootModelPos = new THREE__namespace.Vector3();
3752
+ this.restRightFootModelPos = new THREE__namespace.Vector3();
3624
3753
  this.boneToCanonical = /* @__PURE__ */ new Map();
3754
+ this.restModelQuat = /* @__PURE__ */ new Map();
3755
+ this.restModelQuatInv = /* @__PURE__ */ new Map();
3625
3756
  this.modelRoot = modelRoot;
3626
- const detection = RigDetector.detect(modelRoot);
3757
+ this.modelRoot.updateMatrixWorld(true);
3758
+ const detection = RigDetector.detect(modelRoot, options);
3627
3759
  this.capabilities = detection.capabilities;
3760
+ const rootWorldQuatInv = new THREE__namespace.Quaternion();
3761
+ this.modelRoot.getWorldQuaternion(rootWorldQuatInv).invert();
3628
3762
  for (const [canonicalName, bone] of detection.matchedBones.entries()) {
3629
3763
  const restPos = bone.position.clone();
3630
3764
  const restQuat = bone.quaternion.clone();
3631
3765
  const restScale = bone.scale.clone();
3766
+ const boneWorldQuat = new THREE__namespace.Quaternion();
3767
+ bone.getWorldQuaternion(boneWorldQuat);
3768
+ const boneModelQuat = rootWorldQuatInv.clone().multiply(boneWorldQuat).normalize();
3769
+ this.restModelQuat.set(canonicalName, boneModelQuat);
3770
+ this.restModelQuatInv.set(canonicalName, boneModelQuat.clone().invert());
3632
3771
  let restDir = new THREE__namespace.Vector3(0, 1, 0);
3633
3772
  let boneLen = 0.2;
3634
3773
  if (bone.children.length > 0) {
@@ -3657,6 +3796,79 @@ var AUBRSkeleton = class {
3657
3796
  this.boneToCanonical.set(bone, canonicalName);
3658
3797
  }
3659
3798
  this.proportions = this.calculateProportions(detection.matchedBones);
3799
+ this.worldUnitsPerMeter = this.proportions.totalHeight / 1.8;
3800
+ const hipsBone = detection.matchedBones.get("hips");
3801
+ let hipsParentScale = 1;
3802
+ if (hipsBone?.parent) {
3803
+ const parentScaleVec = new THREE__namespace.Vector3();
3804
+ hipsBone.parent.getWorldScale(parentScaleVec);
3805
+ const avg = (Math.abs(parentScaleVec.x) + Math.abs(parentScaleVec.y) + Math.abs(parentScaleVec.z)) / 3;
3806
+ if (Number.isFinite(avg) && avg > 1e-5) {
3807
+ hipsParentScale = avg;
3808
+ }
3809
+ }
3810
+ this.hipsLocalPerMeter = this.worldUnitsPerMeter / hipsParentScale;
3811
+ const leftArmRest = this.measureArmRest("leftUpperArm", "leftLowerArm", 1);
3812
+ const rightArmRest = this.measureArmRest("rightUpperArm", "rightLowerArm", -1);
3813
+ this.leftArmRestAngleFromDown = leftArmRest.angleFromDown;
3814
+ this.leftArmLowerSign = leftArmRest.lowerSign;
3815
+ this.rightArmRestAngleFromDown = rightArmRest.angleFromDown;
3816
+ this.rightArmLowerSign = rightArmRest.lowerSign;
3817
+ const leftFoot = detection.matchedBones.get("leftFoot");
3818
+ const rightFoot = detection.matchedBones.get("rightFoot");
3819
+ if (leftFoot && rightFoot) {
3820
+ leftFoot.getWorldPosition(this.restLeftFootModelPos);
3821
+ this.modelRoot.worldToLocal(this.restLeftFootModelPos);
3822
+ rightFoot.getWorldPosition(this.restRightFootModelPos);
3823
+ this.modelRoot.worldToLocal(this.restRightFootModelPos);
3824
+ this.hasRestFootPositions = true;
3825
+ } else {
3826
+ this.hasRestFootPositions = false;
3827
+ }
3828
+ }
3829
+ measureArmRest(upperName, lowerName, defaultLateralX) {
3830
+ const upper = this.joints.get(upperName)?.bone;
3831
+ const lower = this.joints.get(lowerName)?.bone;
3832
+ if (!upper || !lower) {
3833
+ return { angleFromDown: 0, lowerSign: defaultLateralX >= 0 ? -1 : 1 };
3834
+ }
3835
+ upper.getWorldPosition(ScratchMath.v0);
3836
+ lower.getWorldPosition(ScratchMath.v1);
3837
+ this.modelRoot.worldToLocal(ScratchMath.v0);
3838
+ this.modelRoot.worldToLocal(ScratchMath.v1);
3839
+ const dir = ScratchMath.v2.subVectors(ScratchMath.v1, ScratchMath.v0);
3840
+ if (dir.lengthSq() < 1e-8) {
3841
+ return { angleFromDown: 0, lowerSign: defaultLateralX >= 0 ? -1 : 1 };
3842
+ }
3843
+ dir.normalize();
3844
+ const dotDown = Math.max(-1, Math.min(1, dir.dot(ScratchMath.DOWN)));
3845
+ const lateralX = Math.abs(dir.x) > 0.05 ? dir.x : defaultLateralX;
3846
+ return {
3847
+ angleFromDown: Math.acos(dotDown),
3848
+ lowerSign: lateralX >= 0 ? -1 : 1
3849
+ };
3850
+ }
3851
+ /**
3852
+ * Applies a rotation delta defined in character model space (+Y up, +Z forward, +X right/left)
3853
+ * relative to the joint's rest pose, converted cleanly into the bone's local coordinate frame.
3854
+ * Allocation-free and rig-agnostic across Mixamo, Rigify, Unreal, VRM, and generic humanoids.
3855
+ */
3856
+ applyModelDeltaRotation(name, modelDeltaQuat, weight = 1, additive = false) {
3857
+ const joint = this.joints.get(name);
3858
+ const restModel = this.restModelQuat.get(name);
3859
+ const restModelInv = this.restModelQuatInv.get(name);
3860
+ if (!joint || !restModel || !restModelInv || weight <= 1e-3) return;
3861
+ ScratchMath.q5.copy(restModelInv).multiply(modelDeltaQuat).multiply(restModel);
3862
+ if (additive) {
3863
+ ScratchMath.q6.copy(joint.targetQuaternion).multiply(ScratchMath.q5);
3864
+ } else {
3865
+ ScratchMath.q6.copy(joint.restQuaternion).multiply(ScratchMath.q5);
3866
+ }
3867
+ if (weight >= 0.999) {
3868
+ joint.targetQuaternion.copy(ScratchMath.q6);
3869
+ } else {
3870
+ joint.targetQuaternion.slerp(ScratchMath.q6, Math.max(0, Math.min(1, weight)));
3871
+ }
3660
3872
  }
3661
3873
  getJoint(name) {
3662
3874
  return this.joints.get(name);
@@ -3723,67 +3935,102 @@ var AUBRSkeleton = class {
3723
3935
  }
3724
3936
  }
3725
3937
  calculateProportions(bones) {
3726
- const box = new THREE__namespace.Box3().setFromObject(this.modelRoot);
3727
- const size = box.getSize(new THREE__namespace.Vector3());
3728
- const totalHeight = size.y > 0 ? size.y : 1.78;
3938
+ const box = new THREE__namespace.Box3();
3939
+ try {
3940
+ box.setFromObject(this.modelRoot);
3941
+ } catch {
3942
+ box.makeEmpty();
3943
+ }
3944
+ const size = box.isEmpty() ? new THREE__namespace.Vector3(0, 0, 0) : box.getSize(new THREE__namespace.Vector3());
3945
+ let totalHeight = size.y > 0.01 ? size.y : 0;
3946
+ const head = bones.get("head");
3947
+ const leftFoot = bones.get("leftFoot");
3948
+ const rightFoot = bones.get("rightFoot");
3949
+ const hips = bones.get("hips");
3950
+ if (totalHeight <= 0.01 && head && (leftFoot || rightFoot)) {
3951
+ head.getWorldPosition(ScratchMath.v0);
3952
+ (leftFoot || rightFoot).getWorldPosition(ScratchMath.v1);
3953
+ const headToFoot = Math.abs(ScratchMath.v0.y - ScratchMath.v1.y);
3954
+ if (headToFoot > 0.01) {
3955
+ totalHeight = headToFoot * 1.15;
3956
+ }
3957
+ }
3958
+ if (totalHeight <= 0.01 && head && hips) {
3959
+ head.getWorldPosition(ScratchMath.v0);
3960
+ hips.getWorldPosition(ScratchMath.v1);
3961
+ const headToHips = ScratchMath.v0.distanceTo(ScratchMath.v1);
3962
+ if (headToHips > 0.01) {
3963
+ totalHeight = headToHips * 2.2;
3964
+ }
3965
+ }
3966
+ if (totalHeight <= 0.01) {
3967
+ totalHeight = 1.78;
3968
+ }
3729
3969
  const leftUp = bones.get("leftUpperLeg");
3730
3970
  const leftLow = bones.get("leftLowerLeg");
3731
- const leftFoot = bones.get("leftFoot");
3732
- let thighLength = 0.45;
3733
- let shinLength = 0.43;
3734
- let footHeight = 0.08;
3971
+ let thighLength = totalHeight * 0.25;
3972
+ let shinLength = totalHeight * 0.24;
3973
+ let footHeight = totalHeight * 0.045;
3735
3974
  if (leftUp && leftLow) {
3736
3975
  leftUp.getWorldPosition(ScratchMath.v0);
3737
3976
  leftLow.getWorldPosition(ScratchMath.v1);
3738
- thighLength = ScratchMath.v0.distanceTo(ScratchMath.v1);
3977
+ const d = ScratchMath.v0.distanceTo(ScratchMath.v1);
3978
+ if (d > 1e-4) thighLength = d;
3739
3979
  }
3740
3980
  if (leftLow && leftFoot) {
3741
3981
  leftLow.getWorldPosition(ScratchMath.v0);
3742
3982
  leftFoot.getWorldPosition(ScratchMath.v1);
3743
- shinLength = ScratchMath.v0.distanceTo(ScratchMath.v1);
3744
- footHeight = Math.max(leftFoot.position.y, 0.08);
3983
+ const d = ScratchMath.v0.distanceTo(ScratchMath.v1);
3984
+ if (d > 1e-4) shinLength = d;
3985
+ if (!box.isEmpty()) {
3986
+ const rawFootY = ScratchMath.v1.y - box.min.y;
3987
+ footHeight = Math.max(totalHeight * 0.03, Math.min(totalHeight * 0.12, rawFootY));
3988
+ }
3745
3989
  }
3746
3990
  const legLength = thighLength + shinLength + footHeight;
3747
3991
  const spine = bones.get("spine");
3748
- const head = bones.get("head");
3749
- let spineLength = 0.52;
3992
+ let spineLength = totalHeight * 0.29;
3750
3993
  if (spine && head) {
3751
3994
  spine.getWorldPosition(ScratchMath.v0);
3752
3995
  head.getWorldPosition(ScratchMath.v1);
3753
- spineLength = ScratchMath.v0.distanceTo(ScratchMath.v1);
3996
+ const d = ScratchMath.v0.distanceTo(ScratchMath.v1);
3997
+ if (d > 1e-4) spineLength = d;
3754
3998
  }
3755
3999
  const leftArm = bones.get("leftUpperArm");
3756
4000
  const rightArm = bones.get("rightUpperArm");
3757
- let shoulderWidth = 0.42;
4001
+ let shoulderWidth = totalHeight * 0.23;
3758
4002
  if (leftArm && rightArm) {
3759
4003
  leftArm.getWorldPosition(ScratchMath.v0);
3760
4004
  rightArm.getWorldPosition(ScratchMath.v1);
3761
- shoulderWidth = ScratchMath.v0.distanceTo(ScratchMath.v1);
4005
+ const d = ScratchMath.v0.distanceTo(ScratchMath.v1);
4006
+ if (d > 1e-4) shoulderWidth = d;
3762
4007
  }
3763
4008
  const rightUp = bones.get("rightUpperLeg");
3764
- let hipWidth = 0.28;
4009
+ let hipWidth = totalHeight * 0.15;
3765
4010
  if (leftUp && rightUp) {
3766
4011
  leftUp.getWorldPosition(ScratchMath.v0);
3767
4012
  rightUp.getWorldPosition(ScratchMath.v1);
3768
- hipWidth = ScratchMath.v0.distanceTo(ScratchMath.v1);
4013
+ const d = ScratchMath.v0.distanceTo(ScratchMath.v1);
4014
+ if (d > 1e-4) hipWidth = d;
3769
4015
  }
3770
4016
  const leftHand = bones.get("leftHand");
3771
- let armLength = 0.65;
4017
+ let armLength = totalHeight * 0.36;
3772
4018
  if (leftArm && leftHand) {
3773
4019
  leftArm.getWorldPosition(ScratchMath.v0);
3774
4020
  leftHand.getWorldPosition(ScratchMath.v1);
3775
- armLength = ScratchMath.v0.distanceTo(ScratchMath.v1);
4021
+ const d = ScratchMath.v0.distanceTo(ScratchMath.v1);
4022
+ if (d > 1e-4) armLength = d;
3776
4023
  }
3777
4024
  return {
3778
4025
  totalHeight,
3779
- legLength: Math.max(legLength, 0.4),
3780
- thighLength: Math.max(thighLength, 0.2),
3781
- shinLength: Math.max(shinLength, 0.2),
3782
- footHeight: Math.max(footHeight, 0.05),
3783
- spineLength: Math.max(spineLength, 0.3),
3784
- shoulderWidth: Math.max(shoulderWidth, 0.25),
3785
- hipWidth: Math.max(hipWidth, 0.15),
3786
- armLength: Math.max(armLength, 0.35)
4026
+ legLength: Math.max(legLength, totalHeight * 0.25),
4027
+ thighLength: Math.max(thighLength, totalHeight * 0.12),
4028
+ shinLength: Math.max(shinLength, totalHeight * 0.12),
4029
+ footHeight: Math.max(footHeight, totalHeight * 0.025),
4030
+ spineLength: Math.max(spineLength, totalHeight * 0.15),
4031
+ shoulderWidth: Math.max(shoulderWidth, totalHeight * 0.12),
4032
+ hipWidth: Math.max(hipWidth, totalHeight * 0.08),
4033
+ armLength: Math.max(armLength, totalHeight * 0.2)
3787
4034
  };
3788
4035
  }
3789
4036
  };
@@ -3877,35 +4124,91 @@ var TwoBoneIK = class {
3877
4124
  };
3878
4125
  }
3879
4126
  /**
3880
- * Applies solved two-bone IK rotations to the target AUBR joints in-place.
4127
+ * Applies solved two-bone IK rotations to the target AUBR leg joints in-place
4128
+ * using rest-pose-preserving world-space delta rotations so Mixamo, Rigify, Unreal,
4129
+ * VRM, and generic humanoid bone orientations are never distorted.
4130
+ *
4131
+ * `targetFootPosWorld` and `poleDirWorld` are in world space (or model space when
4132
+ * `modelRoot` is omitted and bones are evaluated in local space).
3881
4133
  */
3882
- static applyLegIK(thighBone, shinBone, footBone, thighLength, shinLength, targetFootPosModel, poleVector, weight = 1, modelRoot) {
4134
+ static applyLegIK(thighBone, shinBone, footBone, thighLength, shinLength, targetFootPosWorld, poleDirWorld, weight = 1, _modelRoot) {
3883
4135
  if (weight <= 1e-3) return;
3884
- const rootPos = ScratchMath.v3;
3885
- thighBone.getWorldPosition(rootPos);
3886
- if (modelRoot) {
3887
- modelRoot.worldToLocal(rootPos);
3888
- } else if (thighBone.parent) {
3889
- thighBone.parent.worldToLocal(rootPos);
3890
- }
3891
- const chain = {
3892
- rootBone: thighBone,
3893
- midBone: shinBone,
3894
- endBone: footBone,
3895
- poleVector,
3896
- length1: thighLength,
3897
- length2: shinLength
3898
- };
3899
- const result = this.solveAnalytical(chain, targetFootPosModel, rootPos, poleVector);
3900
- if (weight >= 0.999) {
3901
- thighBone.quaternion.copy(result.rootRotation);
3902
- shinBone.quaternion.copy(result.midRotation);
4136
+ const clampedWeight = Math.max(0, Math.min(1, weight));
4137
+ const hipPos = ScratchMath.v0;
4138
+ const kneePos = ScratchMath.v1;
4139
+ const anklePos = ScratchMath.v2;
4140
+ thighBone.getWorldPosition(hipPos);
4141
+ shinBone.getWorldPosition(kneePos);
4142
+ footBone.getWorldPosition(anklePos);
4143
+ let l1 = hipPos.distanceTo(kneePos);
4144
+ let l2 = kneePos.distanceTo(anklePos);
4145
+ if (l1 < 1e-5) l1 = Math.max(thighLength, 0.05);
4146
+ if (l2 < 1e-5) l2 = Math.max(shinLength, 0.05);
4147
+ const maxReach = l1 + l2;
4148
+ const minReach = Math.abs(l1 - l2);
4149
+ const toTarget = ScratchMath.v3.subVectors(targetFootPosWorld, hipPos);
4150
+ const dist = toTarget.length();
4151
+ const clampedDist = Math.max(minReach + 1e-4, Math.min(dist, maxReach * 0.99999));
4152
+ if (dist < 1e-6) {
4153
+ toTarget.copy(ScratchMath.DOWN);
4154
+ } else {
4155
+ toTarget.divideScalar(dist);
4156
+ }
4157
+ const bendDir = ScratchMath.v4.copy(poleDirWorld);
4158
+ const poleProj = bendDir.dot(toTarget);
4159
+ bendDir.addScaledVector(toTarget, -poleProj);
4160
+ if (bendDir.lengthSq() < 1e-6) {
4161
+ bendDir.crossVectors(toTarget, ScratchMath.RIGHT);
4162
+ if (bendDir.lengthSq() < 1e-6) {
4163
+ bendDir.crossVectors(toTarget, ScratchMath.FORWARD);
4164
+ }
4165
+ }
4166
+ bendDir.normalize();
4167
+ const cosAlpha = Math.max(
4168
+ -1,
4169
+ Math.min(1, (l1 * l1 + clampedDist * clampedDist - l2 * l2) / (2 * l1 * clampedDist))
4170
+ );
4171
+ const sinAlpha = Math.sqrt(Math.max(0, 1 - cosAlpha * cosAlpha));
4172
+ const desiredThighDir = ScratchMath.v5.copy(toTarget).multiplyScalar(cosAlpha).addScaledVector(bendDir, sinAlpha).normalize();
4173
+ const desiredKneePos = ScratchMath.v6.copy(hipPos).addScaledVector(desiredThighDir, l1);
4174
+ const desiredShinDir = ScratchMath.v7.subVectors(targetFootPosWorld, desiredKneePos);
4175
+ if (desiredShinDir.lengthSq() < 1e-8) {
4176
+ desiredShinDir.copy(toTarget);
3903
4177
  } else {
3904
- thighBone.quaternion.slerp(result.rootRotation, weight);
3905
- shinBone.quaternion.slerp(result.midRotation, weight);
4178
+ desiredShinDir.normalize();
4179
+ }
4180
+ const currentThighDir = ScratchMath.v8.subVectors(kneePos, hipPos);
4181
+ if (currentThighDir.lengthSq() > 1e-10) {
4182
+ currentThighDir.normalize();
4183
+ ScratchMath.q0.setFromUnitVectors(currentThighDir, desiredThighDir);
4184
+ thighBone.getWorldQuaternion(ScratchMath.q1);
4185
+ ScratchMath.q2.copy(ScratchMath.q1).invert();
4186
+ ScratchMath.q3.copy(ScratchMath.q2).multiply(ScratchMath.q0).multiply(ScratchMath.q1);
4187
+ ScratchMath.q4.copy(thighBone.quaternion).multiply(ScratchMath.q3);
4188
+ if (clampedWeight >= 0.999) {
4189
+ thighBone.quaternion.copy(ScratchMath.q4);
4190
+ } else {
4191
+ thighBone.quaternion.slerp(ScratchMath.q4, clampedWeight);
4192
+ }
4193
+ thighBone.updateMatrixWorld(true);
4194
+ }
4195
+ shinBone.getWorldPosition(kneePos);
4196
+ footBone.getWorldPosition(anklePos);
4197
+ const currentShinDir = ScratchMath.v8.subVectors(anklePos, kneePos);
4198
+ if (currentShinDir.lengthSq() > 1e-10) {
4199
+ currentShinDir.normalize();
4200
+ ScratchMath.q0.setFromUnitVectors(currentShinDir, desiredShinDir);
4201
+ shinBone.getWorldQuaternion(ScratchMath.q1);
4202
+ ScratchMath.q2.copy(ScratchMath.q1).invert();
4203
+ ScratchMath.q3.copy(ScratchMath.q2).multiply(ScratchMath.q0).multiply(ScratchMath.q1);
4204
+ ScratchMath.q4.copy(shinBone.quaternion).multiply(ScratchMath.q3);
4205
+ if (clampedWeight >= 0.999) {
4206
+ shinBone.quaternion.copy(ScratchMath.q4);
4207
+ } else {
4208
+ shinBone.quaternion.slerp(ScratchMath.q4, clampedWeight);
4209
+ }
4210
+ shinBone.updateMatrixWorld(true);
3906
4211
  }
3907
- ScratchMath.q2.setFromAxisAngle(ScratchMath.RIGHT, 0);
3908
- footBone.quaternion.slerp(ScratchMath.q2, weight * 0.85);
3909
4212
  }
3910
4213
  };
3911
4214
  var _FABRIKSolver = class _FABRIKSolver {
@@ -4058,43 +4361,52 @@ var _FABRIKSolver = class _FABRIKSolver {
4058
4361
  };
4059
4362
  }
4060
4363
  /**
4061
- * Projects middle hinge joint onto plane defined by pole vector.
4364
+ * Projects middle hinge joint onto the half-plane defined by the pole direction vector.
4062
4365
  */
4063
4366
  static applyPoleVector(root, hinge, end, pole) {
4064
- const line = ScratchMath.v1.subVectors(end, root).normalize();
4367
+ const line = ScratchMath.v1.subVectors(end, root);
4368
+ if (line.lengthSq() < 1e-10) return;
4369
+ line.normalize();
4065
4370
  const toHinge = ScratchMath.v2.subVectors(hinge, root);
4066
4371
  const projDist = toHinge.dot(line);
4067
4372
  const projPoint = ScratchMath.v3.copy(root).addScaledVector(line, projDist);
4068
- const currentNormal = ScratchMath.v4.subVectors(hinge, projPoint).normalize();
4069
- const desiredNormal = ScratchMath.v5.subVectors(pole, projPoint).normalize();
4070
- if (currentNormal.lengthSq() > 1e-3 && desiredNormal.lengthSq() > 1e-3) {
4373
+ const desiredNormal = ScratchMath.v5.copy(pole).addScaledVector(line, -pole.dot(line));
4374
+ if (desiredNormal.lengthSq() > 1e-6) {
4375
+ desiredNormal.normalize();
4071
4376
  const hingeDist = hinge.distanceTo(projPoint);
4072
- hinge.copy(projPoint).addScaledVector(desiredNormal, Math.max(hingeDist, 0.05));
4377
+ hinge.copy(projPoint).addScaledVector(desiredNormal, Math.max(hingeDist, 0.02));
4073
4378
  }
4074
4379
  }
4075
4380
  /**
4076
4381
  * Converts solved world positions back into local bone rotations for the Three.js hierarchy.
4382
+ * Calculates delta rotation in world space from current bone direction to solved target direction,
4383
+ * transforming into local bone space to guarantee zero deformation when positions match rest pose.
4077
4384
  */
4078
4385
  static applyPositionsToBones(chain, solvedPositions, weight = 1) {
4079
4386
  if (solvedPositions.length < 2 || weight <= 1e-3) return;
4080
4387
  for (let i = 0; i < chain.bones.length - 1; i++) {
4081
4388
  const bone = chain.bones[i];
4389
+ const nextBone = chain.bones[i + 1];
4082
4390
  const nextPos = solvedPositions[i + 1];
4083
- if (!bone || !nextPos) continue;
4391
+ if (!bone || !nextBone || !nextPos) continue;
4084
4392
  bone.getWorldPosition(ScratchMath.v0);
4393
+ nextBone.getWorldPosition(ScratchMath.v2);
4394
+ const currentDirWorld = ScratchMath.v3.subVectors(ScratchMath.v2, ScratchMath.v0);
4395
+ if (currentDirWorld.lengthSq() < 1e-10) continue;
4396
+ currentDirWorld.normalize();
4085
4397
  const targetDirWorld = ScratchMath.v1.subVectors(nextPos, ScratchMath.v0);
4086
4398
  if (targetDirWorld.lengthSq() < 1e-10) continue;
4087
4399
  targetDirWorld.normalize();
4088
- if (bone.parent) {
4089
- ScratchMath.m0.copy(bone.parent.matrixWorld).invert();
4090
- targetDirWorld.transformDirection(ScratchMath.m0).normalize();
4091
- }
4092
- const restDir = ScratchMath.RIGHT;
4093
- ScratchMath.q0.setFromUnitVectors(restDir, targetDirWorld);
4400
+ ScratchMath.q0.setFromUnitVectors(currentDirWorld, targetDirWorld);
4401
+ bone.getWorldQuaternion(ScratchMath.q1);
4402
+ ScratchMath.q2.copy(ScratchMath.q1).invert();
4403
+ ScratchMath.q3.copy(ScratchMath.q2).multiply(ScratchMath.q0).multiply(ScratchMath.q1);
4404
+ const currentLocalQuat = ScratchMath.q4.copy(bone.quaternion);
4405
+ const targetLocalQuat = ScratchMath.q3.premultiply(currentLocalQuat);
4094
4406
  if (weight >= 0.999) {
4095
- bone.quaternion.copy(ScratchMath.q0);
4407
+ bone.quaternion.copy(targetLocalQuat);
4096
4408
  } else {
4097
- bone.quaternion.slerp(ScratchMath.q0, weight);
4409
+ bone.quaternion.copy(currentLocalQuat).slerp(targetLocalQuat, weight);
4098
4410
  }
4099
4411
  bone.updateMatrixWorld(true);
4100
4412
  }
@@ -4126,21 +4438,25 @@ var IKCoordinator = class {
4126
4438
  }
4127
4439
  /**
4128
4440
  * Solves and applies left leg Two-Bone IK.
4441
+ * `targetFootPosModel` is in `skeleton.modelRoot` local space.
4129
4442
  */
4130
4443
  solveLeftLeg(targetFootPosModel, weight = 1) {
4131
4444
  const thigh = this.skeleton.getJoint("leftUpperLeg");
4132
4445
  const shin = this.skeleton.getJoint("leftLowerLeg");
4133
4446
  const foot = this.skeleton.getJoint("leftFoot");
4134
- if (!thigh || !shin || !foot) return;
4135
- const pole = ScratchMath.v6.copy(ScratchMath.FORWARD);
4447
+ if (!thigh || !shin || !foot || weight <= 1e-3) return;
4448
+ const targetWorld = ScratchMath.v9.copy(targetFootPosModel);
4449
+ this.skeleton.modelRoot.localToWorld(targetWorld);
4450
+ this.skeleton.modelRoot.getWorldQuaternion(ScratchMath.q5);
4451
+ const poleWorld = ScratchMath.v8.copy(ScratchMath.FORWARD).applyQuaternion(ScratchMath.q5).normalize();
4136
4452
  TwoBoneIK.applyLegIK(
4137
4453
  thigh.bone,
4138
4454
  shin.bone,
4139
4455
  foot.bone,
4140
4456
  this.skeleton.proportions.thighLength,
4141
4457
  this.skeleton.proportions.shinLength,
4142
- targetFootPosModel,
4143
- pole,
4458
+ targetWorld,
4459
+ poleWorld,
4144
4460
  weight,
4145
4461
  this.skeleton.modelRoot
4146
4462
  );
@@ -4150,21 +4466,25 @@ var IKCoordinator = class {
4150
4466
  }
4151
4467
  /**
4152
4468
  * Solves and applies right leg Two-Bone IK.
4469
+ * `targetFootPosModel` is in `skeleton.modelRoot` local space.
4153
4470
  */
4154
4471
  solveRightLeg(targetFootPosModel, weight = 1) {
4155
4472
  const thigh = this.skeleton.getJoint("rightUpperLeg");
4156
4473
  const shin = this.skeleton.getJoint("rightLowerLeg");
4157
4474
  const foot = this.skeleton.getJoint("rightFoot");
4158
- if (!thigh || !shin || !foot) return;
4159
- const pole = ScratchMath.v6.copy(ScratchMath.FORWARD);
4475
+ if (!thigh || !shin || !foot || weight <= 1e-3) return;
4476
+ const targetWorld = ScratchMath.v9.copy(targetFootPosModel);
4477
+ this.skeleton.modelRoot.localToWorld(targetWorld);
4478
+ this.skeleton.modelRoot.getWorldQuaternion(ScratchMath.q5);
4479
+ const poleWorld = ScratchMath.v8.copy(ScratchMath.FORWARD).applyQuaternion(ScratchMath.q5).normalize();
4160
4480
  TwoBoneIK.applyLegIK(
4161
4481
  thigh.bone,
4162
4482
  shin.bone,
4163
4483
  foot.bone,
4164
4484
  this.skeleton.proportions.thighLength,
4165
4485
  this.skeleton.proportions.shinLength,
4166
- targetFootPosModel,
4167
- pole,
4486
+ targetWorld,
4487
+ poleWorld,
4168
4488
  weight,
4169
4489
  this.skeleton.modelRoot
4170
4490
  );
@@ -4178,7 +4498,8 @@ var IKCoordinator = class {
4178
4498
  solveArmReach(side, targetPosWorld, weight = 1) {
4179
4499
  const chain = side === "left" ? this.leftArmChain : this.rightArmChain;
4180
4500
  if (!chain || weight <= 1e-3) return;
4181
- const pole = side === "left" ? ScratchMath.v7.set(-0.5, 0, -1).normalize() : ScratchMath.v7.set(0.5, 0, -1).normalize();
4501
+ this.skeleton.modelRoot.getWorldQuaternion(ScratchMath.q5);
4502
+ const pole = (side === "left" ? ScratchMath.v7.set(-0.5, 0, -1).normalize() : ScratchMath.v7.set(0.5, 0, -1).normalize()).applyQuaternion(ScratchMath.q5);
4182
4503
  const result = FABRIKSolver.solve(chain, targetPosWorld, pole);
4183
4504
  FABRIKSolver.applyPositionsToBones(chain, result.solvedPositions, weight);
4184
4505
  const upper = this.skeleton.getJoint(side === "left" ? "leftUpperArm" : "rightUpperArm");
@@ -4202,63 +4523,86 @@ var IdleEngine = class {
4202
4523
  this.targetWeightShift = 0;
4203
4524
  this.nextWeightShiftTime = 3.5;
4204
4525
  }
4526
+ reset() {
4527
+ this.clock = 0;
4528
+ this.breathPhase = 0;
4529
+ this.swayPhase = 0;
4530
+ this.weightShift = 0;
4531
+ this.targetWeightShift = 0;
4532
+ this.nextWeightShiftTime = 3.5;
4533
+ }
4205
4534
  update(delta, weight = 1) {
4206
4535
  if (weight <= 1e-3) return;
4536
+ const w = Math.max(0, Math.min(1, weight));
4207
4537
  this.clock += delta;
4208
4538
  this.breathPhase += delta * 0.28;
4209
- this.swayPhase += delta * 0.12;
4539
+ this.swayPhase += delta * 0.14;
4210
4540
  if (this.clock > this.nextWeightShiftTime) {
4211
- this.targetWeightShift = (Math.random() - 0.5) * 1.6;
4541
+ this.targetWeightShift = (Math.random() - 0.5) * 1.4;
4212
4542
  this.nextWeightShiftTime = this.clock + 4 + Math.random() * 4;
4213
4543
  }
4214
- this.weightShift = ScratchMath.damp(this.weightShift, this.targetWeightShift, 1.2, delta);
4544
+ this.weightShift = ScratchMath.damp(this.weightShift, this.targetWeightShift, 1.4, delta);
4545
+ const localScale = this.skeleton.hipsLocalPerMeter;
4215
4546
  const breathSin = Math.sin(this.breathPhase * Math.PI * 2);
4216
- const spinePitch = breathSin * 0.015;
4217
- const chestPitch = breathSin * 0.022;
4547
+ const spinePitch = breathSin * 0.022 * w;
4548
+ const chestPitch = breathSin * 0.028 * w;
4218
4549
  const swaySin = Math.sin(this.swayPhase * Math.PI * 2);
4219
- const pelvicX = (swaySin * 6e-3 + this.weightShift * 0.012) * weight;
4220
- const pelvicY = breathSin * 4e-3 * weight;
4221
- const pelvicRoll = -this.weightShift * 0.018 * weight;
4550
+ const pelvicX = (swaySin * 8e-3 + this.weightShift * 0.014) * localScale * w;
4551
+ const pelvicY = breathSin * 5e-3 * localScale * w;
4552
+ const pelvicRoll = -this.weightShift * 0.022 * w;
4222
4553
  const hips = this.skeleton.getJoint("hips");
4223
4554
  if (hips) {
4224
4555
  hips.targetPosition.x = hips.restPosition.x + pelvicX;
4225
4556
  hips.targetPosition.y = hips.restPosition.y + pelvicY;
4226
4557
  ScratchMath.e0.set(0, 0, pelvicRoll, "YXZ");
4227
4558
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4228
- hips.targetQuaternion.copy(hips.restQuaternion).multiply(ScratchMath.q0);
4559
+ this.skeleton.applyModelDeltaRotation("hips", ScratchMath.q0, w);
4229
4560
  }
4230
- const spine = this.skeleton.getJoint("spine");
4231
- if (spine) {
4232
- ScratchMath.e0.set(spinePitch * weight, 0, 0, "YXZ");
4561
+ if (this.skeleton.hasJoint("spine")) {
4562
+ ScratchMath.e0.set(spinePitch, swaySin * 0.012 * w, -pelvicRoll * 0.4, "YXZ");
4233
4563
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4234
- spine.targetQuaternion.copy(spine.restQuaternion).multiply(ScratchMath.q0);
4564
+ this.skeleton.applyModelDeltaRotation("spine", ScratchMath.q0, w);
4235
4565
  }
4236
- const chest = this.skeleton.getJoint("chest") || this.skeleton.getJoint("upperChest");
4237
- if (chest) {
4238
- ScratchMath.e0.set(chestPitch * weight, 0, 0, "YXZ");
4566
+ const chestName = this.skeleton.hasJoint("chest") ? "chest" : this.skeleton.hasJoint("upperChest") ? "upperChest" : null;
4567
+ if (chestName) {
4568
+ ScratchMath.e0.set(chestPitch, 0, 0, "YXZ");
4239
4569
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4240
- chest.targetQuaternion.copy(chest.restQuaternion).multiply(ScratchMath.q0);
4570
+ this.skeleton.applyModelDeltaRotation(chestName, ScratchMath.q0, w);
4241
4571
  }
4242
- const head = this.skeleton.getJoint("head");
4243
- if (head) {
4244
- const headCounterRoll = -pelvicRoll * 0.6;
4245
- const headCounterPitch = -spinePitch * 0.5;
4572
+ if (this.skeleton.hasJoint("head")) {
4573
+ const headCounterRoll = -pelvicRoll * 0.5;
4574
+ const headCounterPitch = -spinePitch * 0.45;
4246
4575
  ScratchMath.e0.set(headCounterPitch, 0, headCounterRoll, "YXZ");
4247
4576
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4248
- head.targetQuaternion.copy(head.restQuaternion).multiply(ScratchMath.q0);
4249
- }
4250
- const lArm = this.skeleton.getJoint("leftUpperArm");
4251
- const rArm = this.skeleton.getJoint("rightUpperArm");
4252
- const armSway = breathSin * 0.012 * weight;
4253
- if (lArm) {
4254
- ScratchMath.e0.set(armSway, 0, armSway * 0.5, "YXZ");
4255
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4256
- lArm.targetQuaternion.copy(lArm.restQuaternion).multiply(ScratchMath.q0);
4257
- }
4258
- if (rArm) {
4259
- ScratchMath.e0.set(armSway, 0, -armSway * 0.5, "YXZ");
4260
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4261
- rArm.targetQuaternion.copy(rArm.restQuaternion).multiply(ScratchMath.q0);
4577
+ this.skeleton.applyModelDeltaRotation("head", ScratchMath.q0, w);
4578
+ }
4579
+ const targetStandingArmAngle = 0.28;
4580
+ const armBreathSway = breathSin * 0.025;
4581
+ const armOutSway = breathSin * 0.018;
4582
+ if (this.skeleton.hasJoint("leftUpperArm")) {
4583
+ const relaxAngle = Math.max(0, this.skeleton.leftArmRestAngleFromDown - targetStandingArmAngle);
4584
+ const lowerZ = this.skeleton.leftArmLowerSign * (relaxAngle - armOutSway);
4585
+ ScratchMath.q1.setFromAxisAngle(ScratchMath.FORWARD, lowerZ);
4586
+ ScratchMath.q2.setFromAxisAngle(ScratchMath.RIGHT, -armBreathSway);
4587
+ ScratchMath.q0.copy(ScratchMath.q2).multiply(ScratchMath.q1);
4588
+ this.skeleton.applyModelDeltaRotation("leftUpperArm", ScratchMath.q0, w);
4589
+ }
4590
+ if (this.skeleton.hasJoint("rightUpperArm")) {
4591
+ const relaxAngle = Math.max(0, this.skeleton.rightArmRestAngleFromDown - targetStandingArmAngle);
4592
+ const lowerZ = this.skeleton.rightArmLowerSign * (relaxAngle - armOutSway);
4593
+ ScratchMath.q1.setFromAxisAngle(ScratchMath.FORWARD, lowerZ);
4594
+ ScratchMath.q2.setFromAxisAngle(ScratchMath.RIGHT, -armBreathSway);
4595
+ ScratchMath.q0.copy(ScratchMath.q2).multiply(ScratchMath.q1);
4596
+ this.skeleton.applyModelDeltaRotation("rightUpperArm", ScratchMath.q0, w);
4597
+ }
4598
+ const elbowRelaxFlex = 0.16 + breathSin * 0.015;
4599
+ if (this.skeleton.hasJoint("leftLowerArm")) {
4600
+ ScratchMath.q0.setFromAxisAngle(ScratchMath.RIGHT, -elbowRelaxFlex);
4601
+ this.skeleton.applyModelDeltaRotation("leftLowerArm", ScratchMath.q0, w);
4602
+ }
4603
+ if (this.skeleton.hasJoint("rightLowerArm")) {
4604
+ ScratchMath.q0.setFromAxisAngle(ScratchMath.RIGHT, -elbowRelaxFlex);
4605
+ this.skeleton.applyModelDeltaRotation("rightLowerArm", ScratchMath.q0, w);
4262
4606
  }
4263
4607
  }
4264
4608
  };
@@ -4301,9 +4645,10 @@ var LocomotionEngine = class {
4301
4645
  return this.phase;
4302
4646
  }
4303
4647
  calibrateStride() {
4304
- const legLen = this.skeleton.proportions.legLength;
4305
- this.strideLength = Math.max(0.35, legLen * 0.78);
4306
- this.stepHeight = Math.max(0.04, legLen * 0.095);
4648
+ const unitScale = this.skeleton.hipsLocalPerMeter;
4649
+ const legLenLocal = Math.max(0.4 * unitScale, this.skeleton.proportions.legLength / Math.max(this.skeleton.worldUnitsPerMeter, 1e-4) * unitScale);
4650
+ this.strideLength = Math.max(0.35 * unitScale, legLenLocal * 0.72);
4651
+ this.stepHeight = Math.max(0.04 * unitScale, legLenLocal * 0.11);
4307
4652
  }
4308
4653
  setMotion(params) {
4309
4654
  this.targetSpeed = Math.max(0, params.speed);
@@ -4313,113 +4658,128 @@ var LocomotionEngine = class {
4313
4658
  const stridesPerSecond = params.screenVelocityPx / 180;
4314
4659
  this.baseFrequency = Math.max(0.8, Math.min(3.2, stridesPerSecond * 2));
4315
4660
  } else {
4316
- this.baseFrequency = this.isRunning ? 2.6 : 1.5;
4661
+ this.baseFrequency = this.isRunning ? 2.4 : 1.35;
4317
4662
  }
4318
4663
  }
4319
4664
  stop() {
4320
4665
  this.targetSpeed = 0;
4321
4666
  this.moving = false;
4322
4667
  }
4668
+ cancel() {
4669
+ this.targetSpeed = 0;
4670
+ this.currentSpeed = 0;
4671
+ this.moving = false;
4672
+ this.isRunning = false;
4673
+ }
4323
4674
  update(delta, weight = 1) {
4324
- this.currentSpeed = ScratchMath.damp(this.currentSpeed, this.targetSpeed, 4, delta);
4675
+ const speedDamp = this.moving ? 6.5 : 8;
4676
+ this.currentSpeed = ScratchMath.damp(this.currentSpeed, this.targetSpeed, speedDamp, delta);
4325
4677
  if (this.currentSpeed <= 0.01 && weight <= 1e-3) return;
4326
- const effectiveFreq = this.baseFrequency * Math.max(0.3, this.currentSpeed);
4678
+ const w = Math.max(0, Math.min(1, weight));
4679
+ const speedRatio = Math.min(this.currentSpeed, 2.2);
4680
+ const activeAmplitude = Math.min(1, this.currentSpeed / 0.35) * w;
4681
+ if (activeAmplitude <= 1e-3) return;
4682
+ const effectiveFreq = this.baseFrequency * Math.max(0.35, Math.min(1.6, this.currentSpeed));
4327
4683
  this.phase = (this.phase + effectiveFreq * delta) % 1;
4328
4684
  const phi = this.phase;
4329
4685
  const twoPiPhi = phi * Math.PI * 2;
4330
- const speedRatio = Math.min(this.currentSpeed, 2);
4331
- const bobAmplitude = (this.isRunning ? 0.045 : 0.024) * speedRatio;
4686
+ const localScale = this.skeleton.hipsLocalPerMeter;
4687
+ const bobAmplitude = (this.isRunning ? 0.05 : 0.028) * speedRatio * localScale;
4332
4688
  const pelvicY = -bobAmplitude * Math.abs(Math.sin(twoPiPhi));
4333
- const swayAmplitude = (this.isRunning ? 0.018 : 0.028) * speedRatio;
4689
+ const swayAmplitude = (this.isRunning ? 0.02 : 0.03) * speedRatio * localScale;
4334
4690
  const pelvicX = swayAmplitude * Math.sin(twoPiPhi);
4335
4691
  const yawAmplitude = (this.isRunning ? 0.14 : 0.09) * speedRatio;
4336
4692
  const pelvicYaw = yawAmplitude * Math.cos(twoPiPhi);
4337
- const rollAmplitude = 0.035 * speedRatio;
4693
+ const rollAmplitude = 0.04 * speedRatio;
4338
4694
  const pelvicRoll = -rollAmplitude * Math.sin(twoPiPhi);
4339
4695
  const hips = this.skeleton.getJoint("hips");
4340
4696
  if (hips) {
4341
- hips.targetPosition.x = hips.restPosition.x + pelvicX * weight;
4342
- hips.targetPosition.y = hips.restPosition.y + pelvicY * weight;
4343
- ScratchMath.e0.set(0.04 * speedRatio, pelvicYaw * weight, pelvicRoll * weight, "YXZ");
4697
+ hips.targetPosition.x = hips.restPosition.x + pelvicX * w;
4698
+ hips.targetPosition.y = hips.restPosition.y + pelvicY * w;
4699
+ ScratchMath.e0.set((this.isRunning ? 0.08 : 0.04) * speedRatio, pelvicYaw, pelvicRoll, "YXZ");
4344
4700
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4345
- hips.targetQuaternion.copy(hips.restQuaternion).multiply(ScratchMath.q0);
4701
+ this.skeleton.applyModelDeltaRotation("hips", ScratchMath.q0, activeAmplitude);
4346
4702
  }
4347
- const spine = this.skeleton.getJoint("spine");
4348
- if (spine) {
4349
- const spineCounterYaw = -pelvicYaw * 0.65 * weight;
4350
- ScratchMath.e0.set(-0.02 * speedRatio, spineCounterYaw, 0, "YXZ");
4703
+ if (this.skeleton.hasJoint("spine")) {
4704
+ const spineCounterYaw = -pelvicYaw * 0.65;
4705
+ ScratchMath.e0.set((this.isRunning ? 0.08 : 0.03) * speedRatio, spineCounterYaw, -pelvicRoll * 0.35, "YXZ");
4351
4706
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4352
- spine.targetQuaternion.copy(spine.restQuaternion).multiply(ScratchMath.q0);
4707
+ this.skeleton.applyModelDeltaRotation("spine", ScratchMath.q0, activeAmplitude);
4353
4708
  }
4354
- const chest = this.skeleton.getJoint("chest") || this.skeleton.getJoint("upperChest");
4355
- if (chest) {
4356
- const chestCounterYaw = -pelvicYaw * 0.35 * weight;
4357
- ScratchMath.e0.set(0.01, chestCounterYaw, 0, "YXZ");
4709
+ const chestName = this.skeleton.hasJoint("chest") ? "chest" : this.skeleton.hasJoint("upperChest") ? "upperChest" : null;
4710
+ if (chestName) {
4711
+ const chestCounterYaw = -pelvicYaw * 0.35;
4712
+ ScratchMath.e0.set(0.02 * speedRatio, chestCounterYaw, 0, "YXZ");
4358
4713
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4359
- chest.targetQuaternion.copy(chest.restQuaternion).multiply(ScratchMath.q0);
4360
- }
4361
- const hipWidthHalf = this.skeleton.proportions.hipWidth * 0.5;
4362
- const groundY = 0;
4363
- const halfStride = this.strideLength * 0.5 * speedRatio;
4364
- let leftX = -hipWidthHalf;
4365
- let leftY = groundY;
4366
- let leftZ = 0;
4714
+ this.skeleton.applyModelDeltaRotation(chestName, ScratchMath.q0, activeAmplitude);
4715
+ }
4716
+ const halfStride = this.strideLength * 0.5 * Math.min(speedRatio, 1.45);
4717
+ const liftHeight = this.stepHeight * Math.min(speedRatio, 1.5);
4718
+ const baseLeftX = this.skeleton.hasRestFootPositions ? this.skeleton.restLeftFootModelPos.x : -this.skeleton.proportions.hipWidth * 0.5;
4719
+ const baseLeftY = this.skeleton.hasRestFootPositions ? this.skeleton.restLeftFootModelPos.y : 0;
4720
+ const baseLeftZ = this.skeleton.hasRestFootPositions ? this.skeleton.restLeftFootModelPos.z : 0;
4721
+ const baseRightX = this.skeleton.hasRestFootPositions ? this.skeleton.restRightFootModelPos.x : this.skeleton.proportions.hipWidth * 0.5;
4722
+ const baseRightY = this.skeleton.hasRestFootPositions ? this.skeleton.restRightFootModelPos.y : 0;
4723
+ const baseRightZ = this.skeleton.hasRestFootPositions ? this.skeleton.restRightFootModelPos.z : 0;
4724
+ let leftY = baseLeftY;
4725
+ let leftZ = baseLeftZ;
4367
4726
  if (phi < 0.5) {
4368
4727
  const s = phi / 0.5;
4369
- leftZ = halfStride * (1 - 2 * s);
4370
- leftY = groundY;
4728
+ leftZ = baseLeftZ + halfStride * (1 - 2 * s);
4371
4729
  } else {
4372
4730
  const s = (phi - 0.5) / 0.5;
4373
- leftZ = halfStride * (2 * s - 1);
4374
- leftY = groundY + this.stepHeight * speedRatio * (4 * s * (1 - s));
4731
+ leftZ = baseLeftZ + halfStride * (2 * s - 1);
4732
+ leftY = baseLeftY + liftHeight * (4 * s * (1 - s));
4375
4733
  }
4376
- let rightX = hipWidthHalf;
4377
- let rightY = groundY;
4378
- let rightZ = 0;
4734
+ let rightY = baseRightY;
4735
+ let rightZ = baseRightZ;
4379
4736
  if (phi < 0.5) {
4380
4737
  const s = phi / 0.5;
4381
- rightZ = halfStride * (2 * s - 1);
4382
- rightY = groundY + this.stepHeight * speedRatio * (4 * s * (1 - s));
4738
+ rightZ = baseRightZ + halfStride * (2 * s - 1);
4739
+ rightY = baseRightY + liftHeight * (4 * s * (1 - s));
4383
4740
  } else {
4384
4741
  const s = (phi - 0.5) / 0.5;
4385
- rightZ = halfStride * (1 - 2 * s);
4386
- rightY = groundY;
4742
+ rightZ = baseRightZ + halfStride * (1 - 2 * s);
4387
4743
  }
4388
- this.leftFootTarget.set(leftX, leftY, leftZ);
4389
- this.rightFootTarget.set(rightX, rightY, rightZ);
4744
+ this.leftFootTarget.set(baseLeftX, leftY, leftZ);
4745
+ this.rightFootTarget.set(baseRightX, rightY, rightZ);
4390
4746
  if (this.ik) {
4391
- this.ik.solveLeftLeg(this.leftFootTarget, weight);
4392
- this.ik.solveRightLeg(this.rightFootTarget, weight);
4393
- }
4394
- const armSwingAngle = (this.isRunning ? 0.65 : 0.38) * speedRatio * weight;
4395
- const lArmAngle = -Math.sin(twoPiPhi) * armSwingAngle;
4396
- const rArmAngle = Math.sin(twoPiPhi) * armSwingAngle;
4397
- const lArm = this.skeleton.getJoint("leftUpperArm");
4398
- const rArm = this.skeleton.getJoint("rightUpperArm");
4399
- const lForeArm = this.skeleton.getJoint("leftLowerArm");
4400
- const rForeArm = this.skeleton.getJoint("rightLowerArm");
4401
- if (lArm) {
4402
- ScratchMath.e0.set(lArmAngle, 0, 0.05, "YXZ");
4403
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4404
- lArm.targetQuaternion.copy(lArm.restQuaternion).multiply(ScratchMath.q0);
4405
- }
4406
- if (rArm) {
4407
- ScratchMath.e0.set(rArmAngle, 0, -0.05, "YXZ");
4408
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4409
- rArm.targetQuaternion.copy(rArm.restQuaternion).multiply(ScratchMath.q0);
4410
- }
4411
- const elbowFlexBase = this.isRunning ? 0.55 : 0.25;
4412
- if (lForeArm) {
4413
- const flex = elbowFlexBase + Math.max(0, -Math.sin(twoPiPhi)) * 0.35;
4414
- ScratchMath.e0.set(flex * weight, 0, 0, "YXZ");
4415
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4416
- lForeArm.targetQuaternion.copy(lForeArm.restQuaternion).multiply(ScratchMath.q0);
4417
- }
4418
- if (rForeArm) {
4419
- const flex = elbowFlexBase + Math.max(0, Math.sin(twoPiPhi)) * 0.35;
4420
- ScratchMath.e0.set(flex * weight, 0, 0, "YXZ");
4421
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4422
- rForeArm.targetQuaternion.copy(rForeArm.restQuaternion).multiply(ScratchMath.q0);
4747
+ if (hips) {
4748
+ hips.bone.position.copy(hips.targetPosition);
4749
+ hips.bone.quaternion.copy(hips.targetQuaternion);
4750
+ hips.bone.updateMatrixWorld(true);
4751
+ }
4752
+ this.ik.solveLeftLeg(this.leftFootTarget, activeAmplitude);
4753
+ this.ik.solveRightLeg(this.rightFootTarget, activeAmplitude);
4754
+ }
4755
+ const targetStandingArmAngle = 0.25;
4756
+ const armSwingAngle = (this.isRunning ? 0.72 : 0.42) * Math.min(speedRatio, 1.5);
4757
+ const lArmForward = -Math.sin(twoPiPhi) * armSwingAngle;
4758
+ const rArmForward = Math.sin(twoPiPhi) * armSwingAngle;
4759
+ if (this.skeleton.hasJoint("leftUpperArm")) {
4760
+ const relaxAngle = Math.max(0, this.skeleton.leftArmRestAngleFromDown - targetStandingArmAngle);
4761
+ ScratchMath.q1.setFromAxisAngle(ScratchMath.FORWARD, this.skeleton.leftArmLowerSign * relaxAngle);
4762
+ ScratchMath.q2.setFromAxisAngle(ScratchMath.RIGHT, -lArmForward);
4763
+ ScratchMath.q0.copy(ScratchMath.q2).multiply(ScratchMath.q1);
4764
+ this.skeleton.applyModelDeltaRotation("leftUpperArm", ScratchMath.q0, activeAmplitude);
4765
+ }
4766
+ if (this.skeleton.hasJoint("rightUpperArm")) {
4767
+ const relaxAngle = Math.max(0, this.skeleton.rightArmRestAngleFromDown - targetStandingArmAngle);
4768
+ ScratchMath.q1.setFromAxisAngle(ScratchMath.FORWARD, this.skeleton.rightArmLowerSign * relaxAngle);
4769
+ ScratchMath.q2.setFromAxisAngle(ScratchMath.RIGHT, -rArmForward);
4770
+ ScratchMath.q0.copy(ScratchMath.q2).multiply(ScratchMath.q1);
4771
+ this.skeleton.applyModelDeltaRotation("rightUpperArm", ScratchMath.q0, activeAmplitude);
4772
+ }
4773
+ const elbowFlexBase = this.isRunning ? 0.85 : 0.28;
4774
+ if (this.skeleton.hasJoint("leftLowerArm")) {
4775
+ const flex = elbowFlexBase + Math.max(0, lArmForward) * 0.45;
4776
+ ScratchMath.q0.setFromAxisAngle(ScratchMath.RIGHT, -flex);
4777
+ this.skeleton.applyModelDeltaRotation("leftLowerArm", ScratchMath.q0, activeAmplitude);
4778
+ }
4779
+ if (this.skeleton.hasJoint("rightLowerArm")) {
4780
+ const flex = elbowFlexBase + Math.max(0, rArmForward) * 0.45;
4781
+ ScratchMath.q0.setFromAxisAngle(ScratchMath.RIGHT, -flex);
4782
+ this.skeleton.applyModelDeltaRotation("rightLowerArm", ScratchMath.q0, activeAmplitude);
4423
4783
  }
4424
4784
  }
4425
4785
  getPhase() {
@@ -4432,18 +4792,26 @@ var LocomotionEngine = class {
4432
4792
 
4433
4793
  // src/avatar/procedural/TurnEngine.ts
4434
4794
  var TurnEngine = class {
4435
- constructor(skeleton) {
4795
+ constructor(skeleton, turnTarget) {
4436
4796
  this.skeleton = skeleton;
4437
4797
  this.currentYaw = 0;
4438
- // Current character yaw in radians
4798
+ // Current character yaw offset in radians
4439
4799
  this.targetYaw = 0;
4440
- // Target desired yaw in radians
4800
+ // Target desired yaw offset in radians
4441
4801
  this.isTurning = false;
4442
4802
  this.turnAngularVelocity = 0;
4803
+ this.turnTarget = turnTarget ?? skeleton.modelRoot;
4804
+ this.baseYaw = this.turnTarget.rotation.y;
4443
4805
  }
4444
4806
  setTargetHeading(targetYawRad) {
4445
4807
  this.targetYaw = targetYawRad;
4446
4808
  }
4809
+ turnLeft(stepRad = Math.PI / 4) {
4810
+ this.targetYaw -= Math.abs(stepRad);
4811
+ }
4812
+ turnRight(stepRad = Math.PI / 4) {
4813
+ this.targetYaw += Math.abs(stepRad);
4814
+ }
4447
4815
  setFacingDirection(direction) {
4448
4816
  switch (direction) {
4449
4817
  case "left":
@@ -4454,32 +4822,45 @@ var TurnEngine = class {
4454
4822
  break;
4455
4823
  case "center":
4456
4824
  case "forward":
4825
+ case "front":
4457
4826
  default:
4458
4827
  this.targetYaw = 0;
4459
4828
  break;
4460
4829
  }
4461
4830
  }
4831
+ reset() {
4832
+ this.currentYaw = 0;
4833
+ this.targetYaw = 0;
4834
+ this.isTurning = false;
4835
+ this.turnAngularVelocity = 0;
4836
+ this.turnTarget.rotation.y = this.baseYaw;
4837
+ }
4462
4838
  update(delta, isLocomoting = false) {
4463
4839
  const diff = ((this.targetYaw - this.currentYaw) % (Math.PI * 2) + Math.PI * 3) % (Math.PI * 2) - Math.PI;
4464
4840
  this.isTurning = Math.abs(diff) > 0.02;
4465
- const damping = isLocomoting ? 6.5 : 4;
4841
+ const damping = isLocomoting ? 6.5 : 5;
4466
4842
  const prevYaw = this.currentYaw;
4467
4843
  this.currentYaw = ScratchMath.dampAngle(this.currentYaw, this.targetYaw, damping, delta);
4468
4844
  this.turnAngularVelocity = (this.currentYaw - prevYaw) / Math.max(delta, 1e-3);
4469
- this.skeleton.modelRoot.rotation.y = this.currentYaw;
4470
- if (isLocomoting && Math.abs(this.turnAngularVelocity) > 0.2) {
4471
- const bankRoll = -Math.max(-0.06, Math.min(0.06, this.turnAngularVelocity * 0.04));
4472
- const hips = this.skeleton.getJoint("hips");
4473
- if (hips) {
4845
+ this.turnTarget.rotation.y = this.baseYaw + this.currentYaw;
4846
+ if (Math.abs(this.turnAngularVelocity) > 0.15) {
4847
+ const bankRoll = -Math.max(-0.06, Math.min(0.06, this.turnAngularVelocity * (isLocomoting ? 0.04 : 0.02)));
4848
+ if (this.skeleton.hasJoint("hips")) {
4474
4849
  ScratchMath.e0.set(0, 0, bankRoll, "YXZ");
4475
4850
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4476
- hips.targetQuaternion.multiply(ScratchMath.q0);
4851
+ this.skeleton.applyModelDeltaRotation("hips", ScratchMath.q0, 1, true);
4477
4852
  }
4478
4853
  }
4479
4854
  }
4480
4855
  getYaw() {
4481
4856
  return this.currentYaw;
4482
4857
  }
4858
+ getTargetYaw() {
4859
+ return this.targetYaw;
4860
+ }
4861
+ getAngularVelocity() {
4862
+ return this.turnAngularVelocity;
4863
+ }
4483
4864
  isTurnActive() {
4484
4865
  return this.isTurning;
4485
4866
  }
@@ -4495,23 +4876,24 @@ var BalanceEngine = class {
4495
4876
  */
4496
4877
  applyCompensation(reachOffset, weight = 1) {
4497
4878
  if (weight <= 1e-3) return;
4879
+ const localScale = this.skeleton.hipsLocalPerMeter;
4498
4880
  this.targetOffset.set(
4499
- -reachOffset.x * 0.22,
4500
- -Math.abs(reachOffset.z) * 0.05,
4501
- -reachOffset.z * 0.25
4881
+ -reachOffset.x * 0.18 * localScale,
4882
+ -Math.abs(reachOffset.z) * 0.03 * localScale,
4883
+ -reachOffset.z * 0.18 * localScale
4502
4884
  );
4503
4885
  this.centerOfMassOffset.lerp(this.targetOffset, Math.min(1, weight));
4504
4886
  const hips = this.skeleton.getJoint("hips");
4505
4887
  if (hips) {
4506
4888
  hips.targetPosition.add(this.centerOfMassOffset);
4507
4889
  }
4508
- const spine = this.skeleton.getJoint("spine");
4509
- if (spine && this.centerOfMassOffset.lengthSq() > 1e-4) {
4510
- const counterPitch = this.centerOfMassOffset.z * 0.35;
4511
- const counterRoll = -this.centerOfMassOffset.x * 0.35;
4890
+ if (this.skeleton.hasJoint("spine") && this.centerOfMassOffset.lengthSq() > 1e-6) {
4891
+ const invScale = localScale > 1e-4 ? 1 / localScale : 1;
4892
+ const counterPitch = Math.max(-0.12, Math.min(0.12, this.centerOfMassOffset.z * invScale * 0.35));
4893
+ const counterRoll = Math.max(-0.12, Math.min(0.12, -this.centerOfMassOffset.x * invScale * 0.35));
4512
4894
  ScratchMath.e0.set(counterPitch, 0, counterRoll, "YXZ");
4513
4895
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4514
- spine.targetQuaternion.multiply(ScratchMath.q0);
4896
+ this.skeleton.applyModelDeltaRotation("spine", ScratchMath.q0, 1, true);
4515
4897
  }
4516
4898
  }
4517
4899
  reset() {
@@ -4731,177 +5113,146 @@ var GestureEngine = class {
4731
5113
  return "right";
4732
5114
  }
4733
5115
  }
5116
+ /**
5117
+ * Helper: rotates an upper arm from its rest orientation to a target standing-relative Euler pose in model space.
5118
+ */
5119
+ applyStandingArmDelta(side, pitchForwardRad, yawRad, abductOutRad, weight) {
5120
+ const boneName = side === "left" ? "leftUpperArm" : "rightUpperArm";
5121
+ if (!this.skeleton.hasJoint(boneName)) return;
5122
+ const restAngle = side === "left" ? this.skeleton.leftArmRestAngleFromDown : this.skeleton.rightArmRestAngleFromDown;
5123
+ const lowerSign = side === "left" ? this.skeleton.leftArmLowerSign : this.skeleton.rightArmLowerSign;
5124
+ const relaxToDown = Math.max(0, restAngle - abductOutRad);
5125
+ ScratchMath.q1.setFromAxisAngle(ScratchMath.FORWARD, lowerSign * relaxToDown);
5126
+ ScratchMath.e0.set(-pitchForwardRad, yawRad, 0, "YXZ");
5127
+ ScratchMath.q2.setFromEuler(ScratchMath.e0);
5128
+ ScratchMath.q0.copy(ScratchMath.q2).multiply(ScratchMath.q1);
5129
+ this.skeleton.applyModelDeltaRotation(boneName, ScratchMath.q0, weight);
5130
+ }
4734
5131
  // 1. Wave (right hand oscillates back and forth at shoulder height)
4735
5132
  synthesizeWave(progress, weight) {
4736
- const rUpper = this.skeleton.getJoint("rightUpperArm");
4737
- const rLower = this.skeleton.getJoint("rightLowerArm");
4738
- const rHand = this.skeleton.getJoint("rightHand");
4739
- if (rUpper && rLower) {
4740
- ScratchMath.e0.set(-0.6, 0.4, -1.35 * weight, "YXZ");
5133
+ this.applyStandingArmDelta("right", 0.35, -0.25, 1.35, weight);
5134
+ if (this.skeleton.hasJoint("rightLowerArm")) {
5135
+ const waveOsc = Math.sin(progress * Math.PI * 8) * 0.35;
5136
+ ScratchMath.e0.set(-1.35, 0, waveOsc, "YXZ");
4741
5137
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4742
- rUpper.targetQuaternion.slerp(ScratchMath.q0, weight);
4743
- ScratchMath.e0.set(1.4 * weight, 0, 0, "YXZ");
5138
+ this.skeleton.applyModelDeltaRotation("rightLowerArm", ScratchMath.q0, weight);
5139
+ }
5140
+ if (this.skeleton.hasJoint("rightHand")) {
5141
+ const handWave = Math.sin(progress * Math.PI * 8) * 0.3;
5142
+ ScratchMath.e0.set(0, 0, handWave, "YXZ");
4744
5143
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4745
- rLower.targetQuaternion.slerp(ScratchMath.q0, weight);
4746
- if (rHand) {
4747
- const waveAngle = Math.sin(progress * Math.PI * 8) * 0.45 * weight;
4748
- ScratchMath.e0.set(0, 0, waveAngle, "YXZ");
4749
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4750
- rHand.targetQuaternion.slerp(ScratchMath.q0, weight);
4751
- }
5144
+ this.skeleton.applyModelDeltaRotation("rightHand", ScratchMath.q0, weight);
4752
5145
  }
4753
5146
  }
4754
5147
  // 2. Pointing (arm extends toward target using IK or forward angle)
4755
5148
  synthesizePoint(_progress, weight, targetPos) {
4756
5149
  const isLeft = this.activeGesture?.type === "point_left";
4757
- const armName = isLeft ? "leftUpperArm" : "rightUpperArm";
4758
- const foreName = isLeft ? "leftLowerArm" : "rightLowerArm";
5150
+ const side = isLeft ? "left" : "right";
4759
5151
  if (targetPos && this.ik) {
4760
- this.ik.solveArmReach(isLeft ? "left" : "right", targetPos, weight);
5152
+ this.ik.solveArmReach(side, targetPos, weight);
4761
5153
  } else {
4762
- const upper = this.skeleton.getJoint(armName);
4763
- const fore = this.skeleton.getJoint(foreName);
4764
5154
  const sign = isLeft ? 1 : -1;
4765
- if (upper && fore) {
4766
- ScratchMath.e0.set(-1.45 * weight, sign * 0.25 * weight, sign * 0.15 * weight, "YXZ");
4767
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4768
- upper.targetQuaternion.slerp(ScratchMath.q0, weight);
4769
- ScratchMath.e0.set(0.15 * weight, 0, 0, "YXZ");
4770
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4771
- fore.targetQuaternion.slerp(ScratchMath.q0, weight);
5155
+ this.applyStandingArmDelta(side, 1.35, sign * 0.2, 0.25, weight);
5156
+ const foreName = isLeft ? "leftLowerArm" : "rightLowerArm";
5157
+ if (this.skeleton.hasJoint(foreName)) {
5158
+ ScratchMath.q0.setFromAxisAngle(ScratchMath.RIGHT, -0.15);
5159
+ this.skeleton.applyModelDeltaRotation(foreName, ScratchMath.q0, weight);
4772
5160
  }
4773
5161
  }
4774
5162
  }
4775
5163
  // 3. Agree (nod head twice)
4776
5164
  synthesizeAgree(progress, weight) {
4777
- const head = this.skeleton.getJoint("head");
4778
- if (head) {
5165
+ if (this.skeleton.hasJoint("head")) {
4779
5166
  const nodPitch = Math.sin(progress * Math.PI * 4) * 0.24 * weight;
4780
5167
  ScratchMath.e0.set(nodPitch, 0, 0, "YXZ");
4781
5168
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4782
- head.targetQuaternion.copy(head.restQuaternion).multiply(ScratchMath.q0);
5169
+ this.skeleton.applyModelDeltaRotation("head", ScratchMath.q0, weight);
4783
5170
  }
4784
5171
  }
4785
5172
  // 4. Disagree (shake head side to side)
4786
5173
  synthesizeDisagree(progress, weight) {
4787
- const head = this.skeleton.getJoint("head");
4788
- if (head) {
5174
+ if (this.skeleton.hasJoint("head")) {
4789
5175
  const shakeYaw = Math.sin(progress * Math.PI * 4) * 0.32 * weight;
4790
5176
  ScratchMath.e0.set(0, shakeYaw, 0, "YXZ");
4791
5177
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4792
- head.targetQuaternion.copy(head.restQuaternion).multiply(ScratchMath.q0);
5178
+ this.skeleton.applyModelDeltaRotation("head", ScratchMath.q0, weight);
4793
5179
  }
4794
5180
  }
4795
5181
  // 5. Shrug (raise shoulders, turn palms up, tilt head)
4796
5182
  synthesizeShrug(_progress, weight) {
4797
- const lUpper = this.skeleton.getJoint("leftUpperArm");
4798
- const rUpper = this.skeleton.getJoint("rightUpperArm");
4799
- const lFore = this.skeleton.getJoint("leftLowerArm");
4800
- const rFore = this.skeleton.getJoint("rightLowerArm");
4801
- const head = this.skeleton.getJoint("head");
4802
- const lift = 0.28 * weight;
4803
- if (lUpper && rUpper) {
4804
- ScratchMath.e0.set(-0.25 * weight, 0, lift, "YXZ");
5183
+ this.applyStandingArmDelta("left", 0.2, 0, 0.48, weight);
5184
+ this.applyStandingArmDelta("right", 0.2, 0, 0.48, weight);
5185
+ if (this.skeleton.hasJoint("leftLowerArm")) {
5186
+ ScratchMath.e0.set(-0.95, 0.35, 0, "YXZ");
4805
5187
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4806
- lUpper.targetQuaternion.slerp(ScratchMath.q0, weight);
4807
- ScratchMath.e0.set(-0.25 * weight, 0, -lift, "YXZ");
4808
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4809
- rUpper.targetQuaternion.slerp(ScratchMath.q0, weight);
5188
+ this.skeleton.applyModelDeltaRotation("leftLowerArm", ScratchMath.q0, weight);
4810
5189
  }
4811
- if (lFore && rFore) {
4812
- ScratchMath.e0.set(0.85 * weight, 0.4 * weight, 0, "YXZ");
4813
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4814
- lFore.targetQuaternion.slerp(ScratchMath.q0, weight);
4815
- ScratchMath.e0.set(0.85 * weight, -0.4 * weight, 0, "YXZ");
5190
+ if (this.skeleton.hasJoint("rightLowerArm")) {
5191
+ ScratchMath.e0.set(-0.95, -0.35, 0, "YXZ");
4816
5192
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4817
- rFore.targetQuaternion.slerp(ScratchMath.q0, weight);
5193
+ this.skeleton.applyModelDeltaRotation("rightLowerArm", ScratchMath.q0, weight);
4818
5194
  }
4819
- if (head) {
5195
+ if (this.skeleton.hasJoint("head")) {
4820
5196
  ScratchMath.e0.set(0.08 * weight, 0, 0.12 * weight, "YXZ");
4821
5197
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4822
- head.targetQuaternion.copy(head.restQuaternion).multiply(ScratchMath.q0);
5198
+ this.skeleton.applyModelDeltaRotation("head", ScratchMath.q0, weight);
4823
5199
  }
4824
5200
  }
4825
5201
  // 6. Think (hand to chin / temple, look upward slightly)
4826
5202
  synthesizeThink(_progress, weight) {
4827
- const rUpper = this.skeleton.getJoint("rightUpperArm");
4828
- const rFore = this.skeleton.getJoint("rightLowerArm");
4829
- const head = this.skeleton.getJoint("head");
4830
- if (rUpper && rFore) {
4831
- ScratchMath.e0.set(-1.1 * weight, -0.4 * weight, -0.5 * weight, "YXZ");
4832
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4833
- rUpper.targetQuaternion.slerp(ScratchMath.q0, weight);
4834
- ScratchMath.e0.set(1.6 * weight, 0, 0, "YXZ");
5203
+ this.applyStandingArmDelta("right", 0.95, 0.35, 0.35, weight);
5204
+ if (this.skeleton.hasJoint("rightLowerArm")) {
5205
+ ScratchMath.e0.set(-1.55, 0, 0, "YXZ");
4835
5206
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4836
- rFore.targetQuaternion.slerp(ScratchMath.q0, weight);
5207
+ this.skeleton.applyModelDeltaRotation("rightLowerArm", ScratchMath.q0, weight);
4837
5208
  }
4838
- if (head) {
5209
+ if (this.skeleton.hasJoint("head")) {
4839
5210
  ScratchMath.e0.set(-0.15 * weight, 0.18 * weight, 0.08 * weight, "YXZ");
4840
5211
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4841
- head.targetQuaternion.copy(head.restQuaternion).multiply(ScratchMath.q0);
5212
+ this.skeleton.applyModelDeltaRotation("head", ScratchMath.q0, weight);
4842
5213
  }
4843
5214
  }
4844
5215
  // 7. Explain / Conversational gestures (gentle rhythmic hand gesturing)
4845
5216
  synthesizeExplain(progress, weight) {
4846
- const lUpper = this.skeleton.getJoint("leftUpperArm");
4847
- const rUpper = this.skeleton.getJoint("rightUpperArm");
4848
- const lFore = this.skeleton.getJoint("leftLowerArm");
4849
- const rFore = this.skeleton.getJoint("rightLowerArm");
4850
- const osc = Math.sin(progress * Math.PI * 3) * 0.15 * weight;
4851
- if (lUpper && rUpper) {
4852
- ScratchMath.e0.set(-0.35 * weight + osc, 0.25 * weight, 0.2 * weight, "YXZ");
4853
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4854
- lUpper.targetQuaternion.slerp(ScratchMath.q0, weight);
4855
- ScratchMath.e0.set(-0.35 * weight - osc, -0.25 * weight, -0.2 * weight, "YXZ");
4856
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4857
- rUpper.targetQuaternion.slerp(ScratchMath.q0, weight);
5217
+ const osc = Math.sin(progress * Math.PI * 3) * 0.18;
5218
+ this.applyStandingArmDelta("left", 0.35 + osc, 0.2, 0.35, weight);
5219
+ this.applyStandingArmDelta("right", 0.35 - osc, -0.2, 0.35, weight);
5220
+ if (this.skeleton.hasJoint("leftLowerArm")) {
5221
+ ScratchMath.q0.setFromAxisAngle(ScratchMath.RIGHT, -0.9);
5222
+ this.skeleton.applyModelDeltaRotation("leftLowerArm", ScratchMath.q0, weight);
4858
5223
  }
4859
- if (lFore && rFore) {
4860
- ScratchMath.e0.set(0.9 * weight, 0, 0, "YXZ");
4861
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4862
- lFore.targetQuaternion.slerp(ScratchMath.q0, weight);
4863
- ScratchMath.e0.set(0.9 * weight, 0, 0, "YXZ");
4864
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4865
- rFore.targetQuaternion.slerp(ScratchMath.q0, weight);
5224
+ if (this.skeleton.hasJoint("rightLowerArm")) {
5225
+ ScratchMath.q0.setFromAxisAngle(ScratchMath.RIGHT, -0.9);
5226
+ this.skeleton.applyModelDeltaRotation("rightLowerArm", ScratchMath.q0, weight);
4866
5227
  }
4867
5228
  }
4868
5229
  // 8. Open Hands (Welcome / Present / Invite)
4869
5230
  synthesizeOpenHands(_progress, weight) {
4870
- const lUpper = this.skeleton.getJoint("leftUpperArm");
4871
- const rUpper = this.skeleton.getJoint("rightUpperArm");
4872
- const lFore = this.skeleton.getJoint("leftLowerArm");
4873
- const rFore = this.skeleton.getJoint("rightLowerArm");
4874
- if (lUpper && rUpper) {
4875
- ScratchMath.e0.set(-0.45 * weight, 0.35 * weight, 0.45 * weight, "YXZ");
5231
+ this.applyStandingArmDelta("left", 0.45, 0.35, 0.55, weight);
5232
+ this.applyStandingArmDelta("right", 0.45, -0.35, 0.55, weight);
5233
+ if (this.skeleton.hasJoint("leftLowerArm")) {
5234
+ ScratchMath.e0.set(-0.75, 0.35, 0, "YXZ");
4876
5235
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4877
- lUpper.targetQuaternion.slerp(ScratchMath.q0, weight);
4878
- ScratchMath.e0.set(-0.45 * weight, -0.35 * weight, -0.45 * weight, "YXZ");
4879
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4880
- rUpper.targetQuaternion.slerp(ScratchMath.q0, weight);
5236
+ this.skeleton.applyModelDeltaRotation("leftLowerArm", ScratchMath.q0, weight);
4881
5237
  }
4882
- if (lFore && rFore) {
4883
- ScratchMath.e0.set(0.75 * weight, 0.45 * weight, 0, "YXZ");
4884
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4885
- lFore.targetQuaternion.slerp(ScratchMath.q0, weight);
4886
- ScratchMath.e0.set(0.75 * weight, -0.45 * weight, 0, "YXZ");
5238
+ if (this.skeleton.hasJoint("rightLowerArm")) {
5239
+ ScratchMath.e0.set(-0.75, -0.35, 0, "YXZ");
4887
5240
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4888
- rFore.targetQuaternion.slerp(ScratchMath.q0, weight);
5241
+ this.skeleton.applyModelDeltaRotation("rightLowerArm", ScratchMath.q0, weight);
4889
5242
  }
4890
5243
  }
4891
5244
  // 9. Acknowledge (slight bow of head / chest)
4892
5245
  synthesizeAcknowledge(progress, weight) {
4893
- const spine = this.skeleton.getJoint("spine");
4894
- const head = this.skeleton.getJoint("head");
4895
5246
  const bow = Math.sin(progress * Math.PI) * 0.16 * weight;
4896
- if (spine) {
5247
+ if (this.skeleton.hasJoint("spine")) {
4897
5248
  ScratchMath.e0.set(bow, 0, 0, "YXZ");
4898
5249
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4899
- spine.targetQuaternion.copy(spine.restQuaternion).multiply(ScratchMath.q0);
5250
+ this.skeleton.applyModelDeltaRotation("spine", ScratchMath.q0, weight);
4900
5251
  }
4901
- if (head) {
5252
+ if (this.skeleton.hasJoint("head")) {
4902
5253
  ScratchMath.e0.set(bow * 0.5, 0, 0, "YXZ");
4903
5254
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4904
- head.targetQuaternion.copy(head.restQuaternion).multiply(ScratchMath.q0);
5255
+ this.skeleton.applyModelDeltaRotation("head", ScratchMath.q0, weight);
4905
5256
  }
4906
5257
  }
4907
5258
  // 10. Reach
@@ -4912,21 +5263,12 @@ var GestureEngine = class {
4912
5263
  }
4913
5264
  // 11. Celebrate (arms raised in victory, chest open)
4914
5265
  synthesizeCelebrate(_progress, weight) {
4915
- const lUpper = this.skeleton.getJoint("leftUpperArm");
4916
- const rUpper = this.skeleton.getJoint("rightUpperArm");
4917
- const spine = this.skeleton.getJoint("spine");
4918
- if (lUpper && rUpper) {
4919
- ScratchMath.e0.set(-1.8 * weight, 0, 1.2 * weight, "YXZ");
4920
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4921
- lUpper.targetQuaternion.slerp(ScratchMath.q0, weight);
4922
- ScratchMath.e0.set(-1.8 * weight, 0, -1.2 * weight, "YXZ");
4923
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4924
- rUpper.targetQuaternion.slerp(ScratchMath.q0, weight);
4925
- }
4926
- if (spine) {
5266
+ this.applyStandingArmDelta("left", 0.35, 0, 2.45, weight);
5267
+ this.applyStandingArmDelta("right", 0.35, 0, 2.45, weight);
5268
+ if (this.skeleton.hasJoint("spine")) {
4927
5269
  ScratchMath.e0.set(-0.12 * weight, 0, 0, "YXZ");
4928
5270
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4929
- spine.targetQuaternion.copy(spine.restQuaternion).multiply(ScratchMath.q0);
5271
+ this.skeleton.applyModelDeltaRotation("spine", ScratchMath.q0, weight);
4930
5272
  }
4931
5273
  }
4932
5274
  };
@@ -5224,13 +5566,17 @@ var MotionCoordinator = _MotionCoordinator;
5224
5566
 
5225
5567
  // src/avatar/procedural/ProceduralMovementEngine.ts
5226
5568
  var ProceduralMovementEngine = class {
5227
- constructor(modelRoot) {
5569
+ constructor(modelRoot, options) {
5228
5570
  this.isEnabled = true;
5229
- this.skeleton = new AUBRSkeleton(modelRoot);
5571
+ this.paused = false;
5572
+ this.locomotionBlendWeight = 0;
5573
+ this.startingTimer = 0;
5574
+ this.balanceReachScratch = new THREE__namespace.Vector3();
5575
+ this.skeleton = new AUBRSkeleton(modelRoot, options);
5230
5576
  this.ik = new IKCoordinator(this.skeleton);
5231
5577
  this.idle = new IdleEngine(this.skeleton);
5232
5578
  this.locomotion = new LocomotionEngine(this.skeleton, this.ik);
5233
- this.turn = new TurnEngine(this.skeleton);
5579
+ this.turn = new TurnEngine(this.skeleton, options?.turnTarget);
5234
5580
  this.balance = new BalanceEngine(this.skeleton);
5235
5581
  this.lookAtEngine = new LookAtEngine(this.skeleton);
5236
5582
  this.gesture = new GestureEngine(this.skeleton, this.ik);
@@ -5241,42 +5587,110 @@ var ProceduralMovementEngine = class {
5241
5587
  getCapabilities() {
5242
5588
  return this.skeleton.capabilities;
5243
5589
  }
5590
+ getState() {
5591
+ return this.stateMachine.getState();
5592
+ }
5244
5593
  setEnabled(enabled) {
5245
5594
  this.isEnabled = enabled;
5246
5595
  }
5596
+ pause() {
5597
+ this.paused = true;
5598
+ }
5599
+ resume() {
5600
+ this.paused = false;
5601
+ }
5602
+ isPaused() {
5603
+ return this.paused;
5604
+ }
5605
+ resetToRestPose() {
5606
+ this.startingTimer = 0;
5607
+ this.locomotionBlendWeight = 0;
5608
+ this.locomotion.cancel();
5609
+ this.gesture.stopGesture();
5610
+ this.idle.reset();
5611
+ this.turn.reset();
5612
+ this.balance.reset();
5613
+ this.lookAtEngine.clearTarget();
5614
+ this.facial.setSpeaking(false);
5615
+ this.facial.setExpression("neutral");
5616
+ this.stateMachine.transitionTo("idle", 0.05);
5617
+ this.coordinator.setWeights({ locomotionWeight: 0, idleWeight: 1, gestureWeight: 0 });
5618
+ this.skeleton.resetToRestPose();
5619
+ this.skeleton.updateWorldMatrices();
5620
+ }
5247
5621
  // --- High-Level Movement API ---
5622
+ startIdle() {
5623
+ const current = this.stateMachine.getState();
5624
+ if (current === "walking" || current === "running" || current === "starting") {
5625
+ this.stopLocomotion();
5626
+ return;
5627
+ }
5628
+ this.startingTimer = 0;
5629
+ this.gesture.stopGesture();
5630
+ this.stateMachine.transitionTo("idle", 0.2);
5631
+ this.coordinator.setWeights({ locomotionWeight: 0, idleWeight: 1, gestureWeight: 0 });
5632
+ }
5633
+ startWalking(speed = 1, screenVelocityPx) {
5634
+ if (!this.skeleton.capabilities.proceduralLocomotion) return;
5635
+ this.startingTimer = 0.18;
5636
+ this.stateMachine.transitionTo("starting", 0.18);
5637
+ this.locomotion.setMotion({ speed, isRunning: false, screenVelocityPx });
5638
+ }
5248
5639
  walk(speed = 1, screenVelocityPx) {
5249
- this.clearStopTimer();
5250
- this.stateMachine.transitionTo("walking");
5640
+ if (!this.skeleton.capabilities.proceduralLocomotion) return;
5641
+ this.startingTimer = 0;
5642
+ this.stateMachine.transitionTo("walking", 0.2);
5251
5643
  this.locomotion.setMotion({ speed, isRunning: false, screenVelocityPx });
5252
- this.coordinator.setWeights({ locomotionWeight: 1, idleWeight: 0 });
5253
5644
  }
5254
5645
  run(speed = 1.8, screenVelocityPx) {
5255
- this.clearStopTimer();
5256
- this.stateMachine.transitionTo("running");
5646
+ if (!this.skeleton.capabilities.proceduralRunning) return;
5647
+ this.startingTimer = 0;
5648
+ this.stateMachine.transitionTo("running", 0.2);
5257
5649
  this.locomotion.setMotion({ speed, isRunning: true, screenVelocityPx });
5258
- this.coordinator.setWeights({ locomotionWeight: 1, idleWeight: 0 });
5650
+ }
5651
+ stop() {
5652
+ this.stopLocomotion();
5259
5653
  }
5260
5654
  stopLocomotion() {
5261
- this.clearStopTimer();
5655
+ this.startingTimer = 0;
5262
5656
  this.locomotion.stop();
5263
- this.stateMachine.transitionTo("stopping", 0.2);
5264
- this.stopTimer = setTimeout(() => {
5265
- this.stopTimer = void 0;
5266
- if (this.stateMachine.getState() === "stopping") {
5267
- this.stateMachine.transitionTo("idle", 0.25);
5268
- this.coordinator.setWeights({ locomotionWeight: 0, idleWeight: 1 });
5269
- }
5270
- }, 200);
5271
- }
5272
- dispose() {
5273
- this.clearStopTimer();
5274
- this.isEnabled = false;
5275
- }
5276
- clearStopTimer() {
5277
- if (this.stopTimer) {
5278
- clearTimeout(this.stopTimer);
5279
- this.stopTimer = void 0;
5657
+ const state = this.stateMachine.getState();
5658
+ if (state === "walking" || state === "running" || state === "starting") {
5659
+ this.stateMachine.transitionTo("stopping", 0.22);
5660
+ } else if (state !== "stopping") {
5661
+ this.stateMachine.transitionTo("idle", 0.2);
5662
+ }
5663
+ }
5664
+ cancelLocomotion() {
5665
+ this.startingTimer = 0;
5666
+ this.locomotionBlendWeight = 0;
5667
+ this.locomotion.cancel();
5668
+ this.coordinator.setWeights({ locomotionWeight: 0, idleWeight: 1 });
5669
+ this.stateMachine.transitionTo("idle", 0.05);
5670
+ }
5671
+ turnLeft(stepRad = Math.PI / 4) {
5672
+ if (!this.skeleton.capabilities.turning) return;
5673
+ this.turn.turnLeft(stepRad);
5674
+ if (this.stateMachine.getState() === "idle") {
5675
+ this.stateMachine.transitionTo("turning", 0.15);
5676
+ }
5677
+ }
5678
+ turnRight(stepRad = Math.PI / 4) {
5679
+ if (!this.skeleton.capabilities.turning) return;
5680
+ this.turn.turnRight(stepRad);
5681
+ if (this.stateMachine.getState() === "idle") {
5682
+ this.stateMachine.transitionTo("turning", 0.15);
5683
+ }
5684
+ }
5685
+ turnTo(directionOrYaw) {
5686
+ if (!this.skeleton.capabilities.turning) return;
5687
+ if (typeof directionOrYaw === "number") {
5688
+ this.turn.setTargetHeading(directionOrYaw);
5689
+ } else {
5690
+ this.turn.setFacingDirection(directionOrYaw);
5691
+ }
5692
+ if (this.stateMachine.getState() === "idle") {
5693
+ this.stateMachine.transitionTo("turning", 0.15);
5280
5694
  }
5281
5695
  }
5282
5696
  setFacing(direction) {
@@ -5285,10 +5699,26 @@ var ProceduralMovementEngine = class {
5285
5699
  setTargetHeading(yawRad) {
5286
5700
  this.turn.setTargetHeading(yawRad);
5287
5701
  }
5702
+ dispose() {
5703
+ this.isEnabled = false;
5704
+ this.paused = false;
5705
+ this.startingTimer = 0;
5706
+ this.locomotionBlendWeight = 0;
5707
+ this.locomotion.cancel();
5708
+ this.gesture.stopGesture();
5709
+ this.balance.reset();
5710
+ this.lookAtEngine.clearTarget();
5711
+ }
5288
5712
  playGesture(type, options) {
5713
+ if (!this.skeleton.capabilities.upperBodyGestures && !this.skeleton.capabilities.headLookAt) {
5714
+ return false;
5715
+ }
5289
5716
  const success = this.gesture.playGesture(type, options);
5290
5717
  if (success) {
5291
- this.stateMachine.transitionTo("gesturing");
5718
+ const current = this.stateMachine.getState();
5719
+ if (current === "idle" || current === "speaking" || current === "listening" || current === "thinking") {
5720
+ this.stateMachine.transitionTo("gesturing");
5721
+ }
5292
5722
  this.coordinator.setWeights({ gestureWeight: 1 });
5293
5723
  }
5294
5724
  return success;
@@ -5326,41 +5756,83 @@ var ProceduralMovementEngine = class {
5326
5756
  * Restores bones to reference bind pose to prevent cumulative transform drift.
5327
5757
  */
5328
5758
  preMixerUpdate() {
5329
- if (!this.isEnabled) return;
5759
+ if (!this.isEnabled || this.paused) return;
5330
5760
  this.coordinator.preMixerRestore();
5331
5761
  }
5332
5762
  /**
5333
5763
  * Main procedural pipeline tick.
5334
- * Invoked in FbxRenderer.startLoop() after mixer.update(delta) and before renderer.render().
5764
+ * Invoked in FbxRenderer.startLoop() or Avatar Studio after mixer.update(delta) and before renderer.render().
5335
5765
  */
5336
- update(delta, hasActiveMixerClip) {
5337
- if (!this.isEnabled) return;
5766
+ update(delta, hasActiveMixerClip = false) {
5767
+ if (!this.isEnabled || this.paused) return;
5768
+ const dt = Math.min(Math.max(delta, 0), 0.1);
5338
5769
  if (hasActiveMixerClip) {
5339
5770
  this.coordinator.snapshotMixerOutput();
5340
5771
  this.coordinator.setWeights({ clipWeight: 1 });
5341
5772
  } else {
5342
5773
  this.coordinator.setWeights({ clipWeight: 0 });
5343
5774
  }
5344
- const currentState = this.stateMachine.getState();
5775
+ this.stateMachine.update(dt);
5776
+ let currentState = this.stateMachine.getState();
5777
+ if (currentState === "starting") {
5778
+ this.startingTimer -= dt;
5779
+ if (this.startingTimer <= 0) {
5780
+ this.stateMachine.transitionTo("walking", 0.2);
5781
+ currentState = this.stateMachine.getState();
5782
+ }
5783
+ }
5345
5784
  const isLocomoting = currentState === "walking" || currentState === "running" || currentState === "starting";
5346
- this.stateMachine.update(delta);
5347
- this.turn.update(delta, isLocomoting);
5348
- const locoWeight = isLocomoting ? 1 : this.coordinator.getWeights().locomotionWeight;
5349
- if (locoWeight > 0.01) {
5350
- this.locomotion.update(delta, locoWeight);
5785
+ const targetLocoWeight = isLocomoting ? 1 : 0;
5786
+ const blendRate = isLocomoting ? 7.5 : 8.5;
5787
+ this.locomotionBlendWeight = ScratchMath.damp(
5788
+ this.locomotionBlendWeight,
5789
+ targetLocoWeight,
5790
+ blendRate,
5791
+ dt
5792
+ );
5793
+ if (this.locomotionBlendWeight < 5e-3 && !isLocomoting) {
5794
+ this.locomotionBlendWeight = 0;
5795
+ }
5796
+ if (currentState === "stopping" && this.locomotionBlendWeight < 0.02 && this.locomotion.getSpeed() < 0.05) {
5797
+ this.locomotionBlendWeight = 0;
5798
+ this.stateMachine.transitionTo("idle", 0.15);
5799
+ currentState = "idle";
5800
+ }
5801
+ const locoWeight = this.locomotionBlendWeight;
5802
+ const idleWeight = Math.max(0, 1 - locoWeight);
5803
+ this.coordinator.setWeights({
5804
+ locomotionWeight: locoWeight,
5805
+ idleWeight
5806
+ });
5807
+ if (idleWeight > 5e-3 && this.skeleton.capabilities.proceduralIdle) {
5808
+ this.idle.update(dt, idleWeight);
5809
+ }
5810
+ if (locoWeight > 5e-3 && this.skeleton.capabilities.proceduralLocomotion) {
5811
+ this.locomotion.update(dt, locoWeight);
5351
5812
  }
5352
- const idleWeight = !isLocomoting ? 1 : this.coordinator.getWeights().idleWeight;
5353
- if (idleWeight > 0.01) {
5354
- this.idle.update(delta, idleWeight);
5813
+ if (this.skeleton.capabilities.turning) {
5814
+ this.turn.update(dt, isLocomoting);
5815
+ if (currentState === "turning" && !this.turn.isTurnActive()) {
5816
+ this.stateMachine.transitionTo("idle", 0.15);
5817
+ }
5355
5818
  }
5356
5819
  if (this.gesture.isGestureActive()) {
5357
- this.gesture.update(delta);
5820
+ this.gesture.update(dt);
5358
5821
  this.coordinator.setWeights({ gestureWeight: 1 });
5822
+ this.balanceReachScratch.set(0, 0, 0.15);
5823
+ this.balance.applyCompensation(this.balanceReachScratch, Math.min(1, dt * 6));
5359
5824
  } else {
5360
5825
  this.coordinator.setWeights({ gestureWeight: 0 });
5826
+ if (this.stateMachine.getState() === "gesturing") {
5827
+ this.stateMachine.transitionTo("idle", 0.2);
5828
+ }
5829
+ this.balanceReachScratch.set(0, 0, 0);
5830
+ this.balance.applyCompensation(this.balanceReachScratch, Math.min(1, dt * 6));
5361
5831
  }
5362
- this.lookAtEngine.update(delta, 1);
5363
- this.facial.update(delta);
5832
+ if (this.skeleton.capabilities.headLookAt) {
5833
+ this.lookAtEngine.update(dt, 1);
5834
+ }
5835
+ this.facial.update(dt);
5364
5836
  this.coordinator.blendLayers(hasActiveMixerClip);
5365
5837
  this.skeleton.apply();
5366
5838
  this.skeleton.updateWorldMatrices();
@@ -5398,13 +5870,8 @@ var FbxRenderer = class {
5398
5870
  if (!doc) {
5399
5871
  throw new Error("Unable to access document DOM for 3D avatar viewport");
5400
5872
  }
5401
- this.canvas = doc.createElement("canvas");
5402
- this.canvas.className = "asiyst-avatar-canvas";
5403
- this.canvas.setAttribute("role", "presentation");
5404
- this.canvas.style.opacity = "0";
5405
- this.canvas.style.transition = "opacity 0.25s ease";
5406
- this.canvas.style.background = "transparent";
5407
- const glContext = this.canvas.getContext("webgl2") || this.canvas.getContext("webgl");
5873
+ const probeCanvas = doc.createElement("canvas");
5874
+ const glContext = probeCanvas.getContext("webgl2") || probeCanvas.getContext("webgl");
5408
5875
  if (!glContext) {
5409
5876
  throw new AsiystError({
5410
5877
  code: "WEBGL_UNAVAILABLE",
@@ -5412,6 +5879,12 @@ var FbxRenderer = class {
5412
5879
  hint: "Enable hardware acceleration in your browser or use a WebGL-capable device."
5413
5880
  });
5414
5881
  }
5882
+ this.canvas = doc.createElement("canvas");
5883
+ this.canvas.className = "asiyst-avatar-canvas";
5884
+ this.canvas.setAttribute("role", "presentation");
5885
+ this.canvas.style.opacity = "0";
5886
+ this.canvas.style.transition = "opacity 0.25s ease";
5887
+ this.canvas.style.background = "transparent";
5415
5888
  const isMobile = typeof window !== "undefined" && window.innerWidth <= 640;
5416
5889
  const width = options?.width || (isMobile ? 140 : 190);
5417
5890
  const height = options?.height || (isMobile ? 280 : 360);
@@ -5564,7 +6037,10 @@ var FbxRenderer = class {
5564
6037
  });
5565
6038
  this.allAnimations = [...modelAnimations];
5566
6039
  try {
5567
- this.proceduralEngine = new ProceduralMovementEngine(rawObject);
6040
+ this.proceduralEngine = new ProceduralMovementEngine(rawObject, {
6041
+ embeddedAnimationCount: modelAnimations.length,
6042
+ turnTarget: this.modelRoot
6043
+ });
5568
6044
  } catch (procErr) {
5569
6045
  if (typeof console !== "undefined" && typeof console.warn === "function") {
5570
6046
  console.warn("[asiyst] Procedural movement engine initialization notice:", procErr);
@@ -6155,6 +6631,34 @@ var FbxRenderer = class {
6155
6631
  this.mixer = null;
6156
6632
  }
6157
6633
  if (this.scene) {
6634
+ const disposedTextures = /* @__PURE__ */ new Set();
6635
+ const TEXTURE_SLOTS = [
6636
+ "map",
6637
+ "normalMap",
6638
+ "roughnessMap",
6639
+ "metalnessMap",
6640
+ "aoMap",
6641
+ "emissiveMap",
6642
+ "alphaMap",
6643
+ "bumpMap",
6644
+ "displacementMap",
6645
+ "lightMap",
6646
+ "envMap"
6647
+ ];
6648
+ const disposeMat = (m) => {
6649
+ const matRecord = m;
6650
+ for (const slot of TEXTURE_SLOTS) {
6651
+ const texCandidate = matRecord[slot];
6652
+ if (texCandidate && typeof texCandidate === "object" && texCandidate.isTexture) {
6653
+ const tex = texCandidate;
6654
+ if (!disposedTextures.has(tex)) {
6655
+ disposedTextures.add(tex);
6656
+ tex.dispose();
6657
+ }
6658
+ }
6659
+ }
6660
+ m.dispose();
6661
+ };
6158
6662
  this.scene.traverse((obj) => {
6159
6663
  const mesh = obj;
6160
6664
  if (mesh.isMesh) {
@@ -6164,14 +6668,12 @@ var FbxRenderer = class {
6164
6668
  if (mesh.material) {
6165
6669
  if (Array.isArray(mesh.material)) {
6166
6670
  mesh.material.forEach((m) => {
6167
- const mat = m;
6168
- mat.map?.dispose();
6169
- mat.dispose();
6671
+ if (m && typeof m.dispose === "function") {
6672
+ disposeMat(m);
6673
+ }
6170
6674
  });
6171
- } else {
6172
- const mat = mesh.material;
6173
- mat.map?.dispose();
6174
- mat.dispose();
6675
+ } else if (mesh.material && typeof mesh.material.dispose === "function") {
6676
+ disposeMat(mesh.material);
6175
6677
  }
6176
6678
  }
6177
6679
  }
@@ -7487,6 +7989,8 @@ var MovementEngine = class {
7487
7989
  faceDirection(direction) {
7488
7990
  if (direction === "left" || direction === "right") {
7489
7991
  this.renderer.setFacing(direction);
7992
+ } else if (typeof this.renderer.setFacing === "function") {
7993
+ this.renderer.setFacing(direction);
7490
7994
  }
7491
7995
  }
7492
7996
  viewport() {
@@ -8438,10 +8942,12 @@ var RuntimeAuth = class {
8438
8942
  if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) {
8439
8943
  throw new AuthenticationError("ASIYST runtime authorization has expired.");
8440
8944
  }
8945
+ const lifetimeMs = Math.max(0, expiresAt - Date.now());
8946
+ const refreshBufferMs = Math.min(3e4, Math.floor(lifetimeMs * 0.1));
8441
8947
  const token = {
8442
8948
  value: data.token,
8443
8949
  expiresAt,
8444
- refreshAfter: expiresAt
8950
+ refreshAfter: Math.max(Date.now(), expiresAt - refreshBufferMs)
8445
8951
  };
8446
8952
  this.token = token;
8447
8953
  return token;
@@ -10103,12 +10609,20 @@ var ActionScheduler = class {
10103
10609
  ctx.events.emit("action_started", { actionId: action.id, actionType: action.type });
10104
10610
  try {
10105
10611
  const timeoutMs = typeof action.expirationMs === "number" && action.expirationMs > 0 ? action.expirationMs : 15e3;
10106
- const result = await Promise.race([
10107
- handler(ctx),
10108
- new Promise(
10109
- (_, reject) => setTimeout(() => reject(new Error(`Action ${action.type} timed out after ${timeoutMs}ms`)), timeoutMs)
10110
- )
10111
- ]);
10612
+ let timerId;
10613
+ const timeoutPromise = new Promise((_, reject) => {
10614
+ timerId = setTimeout(() => {
10615
+ reject(new Error(`Action ${action.type} timed out after ${timeoutMs}ms`));
10616
+ }, timeoutMs);
10617
+ });
10618
+ let result;
10619
+ try {
10620
+ result = await Promise.race([handler(ctx), timeoutPromise]);
10621
+ } finally {
10622
+ if (timerId !== void 0) {
10623
+ clearTimeout(timerId);
10624
+ }
10625
+ }
10112
10626
  const durationMs = Date.now() - startTime;
10113
10627
  const ackResult = {
10114
10628
  executionDurationMs: durationMs,
@@ -10756,7 +11270,7 @@ var AsiystRuntime = class {
10756
11270
  apiBaseUrl: options.apiBaseUrl ?? DEFAULT_API_BASE_URL,
10757
11271
  projectId: options.projectId,
10758
11272
  publicKey: options.publicKey,
10759
- installationId: void 0,
11273
+ installationId: this.installationId,
10760
11274
  origin: win.location.origin,
10761
11275
  environment: this.environment
10762
11276
  }) : void 0;
@@ -10838,36 +11352,47 @@ var AsiystRuntime = class {
10838
11352
  (event) => this.cloud.sendRuntimeEvent(event),
10839
11353
  this.events
10840
11354
  );
10841
- this.tourEngine = new TourEngine(
10842
- async (route) => {
11355
+ this.tourEngine = new TourEngine({
11356
+ navigateToRoute: async (route) => {
10843
11357
  const nav = resolveNavigationAdapter(win);
10844
11358
  await nav.navigateToRoute(route);
10845
11359
  },
10846
- async (elId) => {
11360
+ moveToElement: async (elId) => {
10847
11361
  await this.movement.moveTo(elId, "developer");
10848
11362
  },
10849
- async (elId) => {
11363
+ pointAtElement: async (elId) => {
10850
11364
  await this.movement.pointAt(elId, "developer");
10851
11365
  },
10852
- async (elId, style) => {
10853
- const el = this.targetRegistry.get(elId);
10854
- if (el) {
10855
- this.highlights.show(el, style || "spotlight");
11366
+ highlightElement: async (elId, style) => {
11367
+ const resolved = this.resolver.tryResolve(elId, "developer");
11368
+ if (resolved) {
11369
+ this.highlights.show(resolved.element, style || "spotlight");
11370
+ } else {
11371
+ const el = this.targetRegistry.get(elId);
11372
+ if (el) {
11373
+ this.highlights.show(el, style || "spotlight");
11374
+ }
10856
11375
  }
10857
11376
  },
10858
- async (text) => {
11377
+ clearHighlight: () => {
11378
+ this.highlights.hide();
11379
+ },
11380
+ speak: async (text) => {
10859
11381
  await this.speechPlayer.speak(text);
10860
11382
  },
10861
- (event) => {
11383
+ playGesture: (gesture) => {
11384
+ return this.avatar.playGesture(gesture);
11385
+ },
11386
+ onStepChanged: (event) => {
10862
11387
  this.events.emit("asiyst:tour:step_changed", event);
10863
11388
  },
10864
- (tourId) => {
11389
+ onTourCompleted: (tourId) => {
10865
11390
  this.events.emit("asiyst:tour:completed", { tourId });
10866
11391
  },
10867
- (tourId, error) => {
11392
+ onTourError: (tourId, error) => {
10868
11393
  this.events.emit("asiyst:tour:error", { tourId, error });
10869
11394
  }
10870
- );
11395
+ });
10871
11396
  this.actionScheduler = new ActionScheduler(
10872
11397
  (action) => this.createActionContext(action, doc, win)
10873
11398
  );
@@ -11643,8 +12168,8 @@ var AsiystRuntime = class {
11643
12168
  origin
11644
12169
  });
11645
12170
  if (reg?.runtimeSessionId) {
11646
- this.installationId = reg.runtimeSessionId;
11647
- this.runtimeAuth?.setInstallationId(reg.runtimeSessionId);
12171
+ this.visitorSessionId = reg.runtimeSessionId;
12172
+ this.cloud.setSessionId(reg.runtimeSessionId);
11648
12173
  this.registrationSucceeded = true;
11649
12174
  this.connectionStatus = "connected";
11650
12175
  this.verificationStatus = "connected";
@@ -11693,9 +12218,107 @@ var AsiystRuntime = class {
11693
12218
  this.map.replace(inspectDocument(doc));
11694
12219
  });
11695
12220
  }
12221
+ resolveLocalBasicIntent(rawText) {
12222
+ const text = rawText.trim().toLowerCase().replace(/[.,!?;:]/g, "").replace(/\s+/g, " ");
12223
+ if (!text) return null;
12224
+ if (text === "walk" || text === "walk around" || text === "walk forward" || text === "start walking") {
12225
+ return "walk";
12226
+ }
12227
+ if (text === "run" || text === "run around" || text === "start running") {
12228
+ return "run";
12229
+ }
12230
+ if (text === "stop" || text === "stop moving" || text === "halt" || text === "freeze" || text === "pause") {
12231
+ return "stop";
12232
+ }
12233
+ if (text === "idle" || text === "reset pose" || text === "reset" || text === "stand still" || text === "stand") {
12234
+ return "idle";
12235
+ }
12236
+ if (text === "turn left" || text === "look left" || text === "face left") {
12237
+ return "turn_left";
12238
+ }
12239
+ if (text === "turn right" || text === "look right" || text === "face right") {
12240
+ return "turn_right";
12241
+ }
12242
+ if (text === "turn front" || text === "turn forward" || text === "look forward" || text === "face front" || text === "face forward") {
12243
+ return "turn_front";
12244
+ }
12245
+ if (text === "wave" || text === "wave hand" || text === "wave at me") {
12246
+ return "wave";
12247
+ }
12248
+ if (text === "greet me" || text === "say hello" || text === "say hi" || text === "greet") {
12249
+ return "greet";
12250
+ }
12251
+ return null;
12252
+ }
12253
+ executeLocalIntent(intent, doc) {
12254
+ const win = doc.defaultView || (typeof window !== "undefined" ? window : void 0);
12255
+ const width = win?.innerWidth ?? 1024;
12256
+ const height = win?.innerHeight ?? 768;
12257
+ switch (intent) {
12258
+ case "walk": {
12259
+ const targetX = Math.round(Math.max(120, Math.min(width - 120, width * 0.5 + (Math.random() * 200 - 100))));
12260
+ const targetY = Math.round(Math.max(120, Math.min(height - 120, height * 0.65 + (Math.random() * 100 - 50))));
12261
+ void this.avatar.walkTo({ x: targetX, y: targetY }, 1);
12262
+ break;
12263
+ }
12264
+ case "run": {
12265
+ const targetX = Math.round(Math.max(120, Math.min(width - 120, width * 0.5 + (Math.random() * 200 - 100))));
12266
+ const targetY = Math.round(Math.max(120, Math.min(height - 120, height * 0.65 + (Math.random() * 100 - 50))));
12267
+ void this.avatar.runTo({ x: targetX, y: targetY }, 1.5);
12268
+ break;
12269
+ }
12270
+ case "stop": {
12271
+ this.avatar.stop();
12272
+ break;
12273
+ }
12274
+ case "idle": {
12275
+ this.avatar.stopAnimation();
12276
+ this.avatar.stop();
12277
+ this.avatar.turnTo("forward");
12278
+ this.avatar.setExpression("neutral");
12279
+ break;
12280
+ }
12281
+ case "turn_left": {
12282
+ this.avatar.turnTo("left");
12283
+ break;
12284
+ }
12285
+ case "turn_right": {
12286
+ this.avatar.turnTo("right");
12287
+ break;
12288
+ }
12289
+ case "turn_front": {
12290
+ this.avatar.turnTo("front");
12291
+ break;
12292
+ }
12293
+ case "wave":
12294
+ case "greet": {
12295
+ this.avatar.playGesture("wave");
12296
+ break;
12297
+ }
12298
+ }
12299
+ }
11696
12300
  async handleUserMessage(text, doc) {
11697
12301
  this.greetingManager.markUserInteracted();
11698
12302
  this.events.emit("asiyst:conversation:message", { role: "user", text });
12303
+ const localIntent = this.resolveLocalBasicIntent(text);
12304
+ if (localIntent) {
12305
+ this.executeLocalIntent(localIntent, doc);
12306
+ const confirmations = {
12307
+ walk: "Walking.",
12308
+ run: "Running.",
12309
+ stop: "Stopped.",
12310
+ idle: "Reset to idle pose.",
12311
+ turn_left: "Turning left.",
12312
+ turn_right: "Turning right.",
12313
+ turn_front: "Facing forward.",
12314
+ wave: "Waving hello!",
12315
+ greet: "Hello! Ready to help."
12316
+ };
12317
+ const localReply = confirmations[localIntent] ?? `Executed "${text.trim()}" locally.`;
12318
+ this.panel.append("assistant", localReply);
12319
+ this.events.emit("asiyst:conversation:message", { role: "assistant", text: localReply });
12320
+ return;
12321
+ }
11699
12322
  this.avatar.think();
11700
12323
  try {
11701
12324
  const reply = await this.cloud.sendConversationMessage(
@@ -11724,8 +12347,8 @@ var AsiystRuntime = class {
11724
12347
  this.events.emit("asiyst:conversation:message", { role: "assistant", text: reply.message.text });
11725
12348
  } catch (error) {
11726
12349
  const message = error instanceof Error ? error.message : "Asiyst Cloud is unavailable";
11727
- this.panel.append("assistant", message);
11728
12350
  this.events.emit("asiyst:error", { code: "conversation_failed", message });
12351
+ this.panel.append("assistant", message);
11729
12352
  this.avatar.speak(message);
11730
12353
  }
11731
12354
  }
@@ -11828,17 +12451,11 @@ var AsiystRuntime = class {
11828
12451
  async avatarSubmitContext() {
11829
12452
  await this.submitWebsiteContext();
11830
12453
  }
11831
- async avatarHighlight(targetId, style) {
11832
- const el = this.targetRegistry.get(targetId);
11833
- if (el) {
11834
- this.highlights.show(el, style ?? "outline");
11835
- }
12454
+ async avatarHighlight(target, style) {
12455
+ await this.avatar.highlight(target, style ?? "outline", "developer");
11836
12456
  }
11837
- async avatarPointAt(targetId) {
11838
- const el = this.targetRegistry.get(targetId);
11839
- if (el) {
11840
- await this.avatar.pointAt(targetId, "developer");
11841
- }
12457
+ async avatarPointAt(target) {
12458
+ await this.avatar.pointAt(target, "developer");
11842
12459
  }
11843
12460
  async avatarNavigateTo(route) {
11844
12461
  const win = this.host?.chrome?.ownerDocument?.defaultView || (typeof window !== "undefined" ? window : void 0);
@@ -11975,15 +12592,10 @@ var AsiystInstanceImpl = class {
11975
12592
  interact: {
11976
12593
  highlight: async (targetId, options) => {
11977
12594
  const style = typeof options === "string" ? options : options?.style;
11978
- await this.requireInstanceRuntime().avatarHighlight(
11979
- typeof targetId === "string" ? targetId : targetId.id || "",
11980
- style
11981
- );
12595
+ await this.requireInstanceRuntime().avatarHighlight(targetId, style);
11982
12596
  },
11983
12597
  pointAt: async (targetId) => {
11984
- await this.requireInstanceRuntime().avatarPointAt(
11985
- typeof targetId === "string" ? targetId : targetId.id || ""
11986
- );
12598
+ await this.requireInstanceRuntime().avatarPointAt(targetId);
11987
12599
  }
11988
12600
  },
11989
12601
  navigation: {
@@ -12289,10 +12901,10 @@ var Asiyst = {
12289
12901
  interact: {
12290
12902
  async highlight(targetId, options) {
12291
12903
  const style = typeof options === "string" ? options : options?.style;
12292
- await requireRuntime().avatarHighlight(typeof targetId === "string" ? targetId : targetId.id || "", style);
12904
+ await requireRuntime().avatarHighlight(targetId, style);
12293
12905
  },
12294
12906
  async pointAt(targetId) {
12295
- await requireRuntime().avatarPointAt(typeof targetId === "string" ? targetId : targetId.id || "");
12907
+ await requireRuntime().avatarPointAt(targetId);
12296
12908
  }
12297
12909
  },
12298
12910
  navigation: {