@ikijs/mcp 0.26.0 → 0.27.0

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.js CHANGED
@@ -5,9 +5,9 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
8
+ var __export = (target2, all) => {
9
9
  for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
10
+ __defProp(target2, name, { get: all[name], enumerable: true });
11
11
  };
12
12
  var __copyProps = (to, from, except, desc) => {
13
13
  if (from && typeof from === "object" || typeof from === "function") {
@@ -17,12 +17,12 @@ var __copyProps = (to, from, except, desc) => {
17
17
  }
18
18
  return to;
19
19
  };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ var __toESM = (mod, isNodeMode, target2) => (target2 = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
21
  // If the importer is in node compatibility mode or this is not an ESM
22
22
  // file that has been converted to a CommonJS file using a Babel-
23
23
  // compatible transform (i.e. "__esModule" has not been set), then set
24
24
  // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target2, "default", { value: mod, enumerable: true }) : target2,
26
26
  mod
27
27
  ));
28
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
@@ -38,6 +38,7 @@ __export(index_exports, {
38
38
  describeIkiAt: () => describeIkiAt,
39
39
  formatFoldReport: () => formatFoldReport,
40
40
  formatMeasureReport: () => formatMeasureReport,
41
+ formatPhysicsReport: () => formatPhysicsReport,
41
42
  formatTurnReport: () => formatTurnReport,
42
43
  listStandardParameters: () => listStandardParameters,
43
44
  measureLayers: () => measureLayers,
@@ -57,9 +58,6 @@ var import_node_path4 = __toESM(require("path"));
57
58
  var import_format7 = require("@ikijs/format");
58
59
  var import_editor3 = require("@ikijs/editor");
59
60
 
60
- // src/fold-report.ts
61
- var import_editor = require("@ikijs/editor");
62
-
63
61
  // ../engine/src/math.ts
64
62
  function clamp(value, min, max) {
65
63
  return Math.max(min, Math.min(max, value));
@@ -67,6 +65,10 @@ function clamp(value, min, max) {
67
65
  function lerp(a, b, t) {
68
66
  return a + (b - a) * t;
69
67
  }
68
+ function smoothstep(x) {
69
+ const t = clamp(x, 0, 1);
70
+ return t * t * (3 - 2 * t);
71
+ }
70
72
 
71
73
  // ../engine/src/parameter-store.ts
72
74
  var ParameterStore = class {
@@ -472,17 +474,472 @@ function resolveDeformers(deformers, params) {
472
474
  var import_format = require("@ikijs/format");
473
475
 
474
476
  // ../engine/src/frame-clock.ts
477
+ var MAX_DT_MS = 100;
475
478
  var FIXED_DT_S = 1 / 60;
479
+ var MAX_SUBSTEPS = 6;
480
+ var FixedStepClock = class {
481
+ prevNowMs = void 0;
482
+ accumulatorS = 0;
483
+ /**
484
+ * True until the first {@link advance}. Drivers seed their rest pose on that
485
+ * frame and integrate nothing, so a model loaded mid-motion does not kick.
486
+ */
487
+ get isSeedFrame() {
488
+ return this.prevNowMs === void 0;
489
+ }
490
+ /**
491
+ * Fold `nowMs` into the accumulator and return how many {@link FIXED_DT_S}
492
+ * sub-steps to run this frame. On the seed frame it only records the
493
+ * timestamp and returns 0. A non-monotonic `nowMs` floors to 0 — no rewind.
494
+ */
495
+ advance(nowMs) {
496
+ if (!Number.isFinite(nowMs)) return 0;
497
+ if (this.prevNowMs === void 0) {
498
+ this.prevNowMs = nowMs;
499
+ return 0;
500
+ }
501
+ const dtMs = clamp(nowMs - this.prevNowMs, 0, MAX_DT_MS);
502
+ this.prevNowMs = nowMs;
503
+ this.accumulatorS += dtMs / 1e3;
504
+ let steps = 0;
505
+ while (this.accumulatorS >= FIXED_DT_S && steps < MAX_SUBSTEPS) {
506
+ this.accumulatorS -= FIXED_DT_S;
507
+ steps++;
508
+ }
509
+ return steps;
510
+ }
511
+ };
476
512
 
477
513
  // ../engine/src/idle-motion.ts
514
+ var BLINK_INTERVAL_MIN_MS = 1500;
515
+ var BLINK_INTERVAL_MAX_MS = 6e3;
478
516
  var BLINK_CLOSE_MS = 60;
479
517
  var BLINK_HOLD_MS = 20;
480
518
  var BLINK_OPEN_MS = 100;
481
519
  var BLINK_DURATION_MS = BLINK_CLOSE_MS + BLINK_HOLD_MS + BLINK_OPEN_MS;
520
+ var BREATH_PERIOD_MS = 3500;
521
+ var GAZE_RADIUS = 0.3;
522
+ var GAZE_RETARGET_MIN_MS = 1200;
523
+ var GAZE_RETARGET_MAX_MS = 3e3;
524
+ var GAZE_EASE_RATE = 1e-3;
525
+ var SWAY_X_AMP_A_DEG = 2.2;
526
+ var SWAY_X_PERIOD_A_MS = 6100;
527
+ var SWAY_X_AMP_B_DEG = 1.3;
528
+ var SWAY_X_PERIOD_B_MS = 9700;
529
+ var SWAY_Y_AMP_DEG = 1.6;
530
+ var SWAY_Y_PERIOD_MS = 7300;
531
+ var SWAY_Z_AMP_DEG = 1.1;
532
+ var SWAY_Z_PERIOD_MS = 11300;
533
+ function blinkEnvelope(phase) {
534
+ const ms = phase * BLINK_DURATION_MS;
535
+ if (ms <= 0) return 1;
536
+ if (ms < BLINK_CLOSE_MS) return 1 - smoothstep(ms / BLINK_CLOSE_MS);
537
+ if (ms <= BLINK_CLOSE_MS + BLINK_HOLD_MS) return 0;
538
+ if (ms < BLINK_DURATION_MS) {
539
+ const t = (ms - BLINK_CLOSE_MS - BLINK_HOLD_MS) / BLINK_OPEN_MS;
540
+ return 1 - (1 - t) * (1 - t);
541
+ }
542
+ return 1;
543
+ }
544
+ function randomInDisk(rng, radius) {
545
+ const r = Math.sqrt(rng()) * radius;
546
+ const theta = rng() * 2 * Math.PI;
547
+ return [r * Math.cos(theta), r * Math.sin(theta)];
548
+ }
549
+ var IdleMotion = class {
550
+ /**
551
+ * Every parameter id {@link update} and `emitRestingPose` write, in write
552
+ * order. Published so a host (or IkiMotion) can restore them after it
553
+ * stops driving — keep in step with those two methods; the test suite
554
+ * pins this list to the actual emissions.
555
+ */
556
+ drivenParameterIds = [
557
+ import_format.StandardParameter.EyeOpenLeft,
558
+ import_format.StandardParameter.EyeOpenRight,
559
+ import_format.StandardParameter.Breath,
560
+ import_format.StandardParameter.EyeballX,
561
+ import_format.StandardParameter.EyeballY,
562
+ import_format.StandardParameter.AngleX,
563
+ import_format.StandardParameter.AngleY,
564
+ import_format.StandardParameter.AngleZ
565
+ ];
566
+ sink;
567
+ rng;
568
+ // Internal clock: advances by clamped dt, NOT by raw wall-clock jumps.
569
+ // This is the only clock blink/breath/gaze scheduling reads.
570
+ clockMs = 0;
571
+ prevNowMs = void 0;
572
+ // Blink state
573
+ nextBlinkAtMs;
574
+ blinkStartMs = -1;
575
+ // -1 means not currently blinking
576
+ // Gaze state
577
+ gazeCurrentX = 0;
578
+ gazeCurrentY = 0;
579
+ gazeTargetX = 0;
580
+ gazeTargetY = 0;
581
+ nextGazeRetargetMs;
582
+ constructor(sink, options) {
583
+ this.sink = sink;
584
+ this.rng = options?.rng ?? Math.random;
585
+ this.nextBlinkAtMs = lerp(
586
+ BLINK_INTERVAL_MIN_MS,
587
+ BLINK_INTERVAL_MAX_MS,
588
+ this.rng()
589
+ );
590
+ this.nextGazeRetargetMs = lerp(
591
+ GAZE_RETARGET_MIN_MS,
592
+ GAZE_RETARGET_MAX_MS,
593
+ this.rng()
594
+ );
595
+ }
596
+ /**
597
+ * Advance the idle animation to the given wall-clock timestamp (milliseconds).
598
+ *
599
+ * On the first call: record prevNowMs, emit the resting pose, and return —
600
+ * no animation advance happens so there is no jump from time 0.
601
+ *
602
+ * On subsequent calls: compute dt = clamp(nowMs - prevNowMs, 0, MAX_DT_MS)
603
+ * and advance the internal clock by dt. A non-monotonic nowMs produces a
604
+ * negative raw delta that the clamp floors to 0 — no rewind.
605
+ */
606
+ update(nowMs) {
607
+ if (!Number.isFinite(nowMs)) return;
608
+ if (this.prevNowMs === void 0) {
609
+ this.prevNowMs = nowMs;
610
+ this.emitRestingPose();
611
+ return;
612
+ }
613
+ const rawDt = nowMs - this.prevNowMs;
614
+ const dt = clamp(rawDt, 0, MAX_DT_MS);
615
+ this.prevNowMs = nowMs;
616
+ this.clockMs += dt;
617
+ const eyeVal = this.advanceBlink();
618
+ this.sink(import_format.StandardParameter.EyeOpenLeft, eyeVal);
619
+ this.sink(import_format.StandardParameter.EyeOpenRight, eyeVal);
620
+ const breath = this.advanceBreath();
621
+ this.advanceGaze(dt);
622
+ this.sink(import_format.StandardParameter.Breath, breath);
623
+ this.sink(import_format.StandardParameter.EyeballX, this.gazeCurrentX);
624
+ this.sink(import_format.StandardParameter.EyeballY, this.gazeCurrentY);
625
+ this.sink(import_format.StandardParameter.AngleX, this.swayX());
626
+ this.sink(import_format.StandardParameter.AngleY, this.swayY());
627
+ this.sink(import_format.StandardParameter.AngleZ, this.swayZ());
628
+ }
629
+ // ---------------------------------------------------------------------------
630
+ // Private helpers
631
+ // ---------------------------------------------------------------------------
632
+ emitRestingPose() {
633
+ this.sink(import_format.StandardParameter.EyeOpenLeft, 1);
634
+ this.sink(import_format.StandardParameter.EyeOpenRight, 1);
635
+ this.sink(import_format.StandardParameter.Breath, 0.5);
636
+ this.sink(import_format.StandardParameter.EyeballX, 0);
637
+ this.sink(import_format.StandardParameter.EyeballY, 0);
638
+ this.sink(import_format.StandardParameter.AngleX, 0);
639
+ this.sink(import_format.StandardParameter.AngleY, 0);
640
+ this.sink(import_format.StandardParameter.AngleZ, 0);
641
+ }
642
+ /** Returns the current eye-open value (0..1) and advances blink state. */
643
+ advanceBlink() {
644
+ const { clockMs } = this;
645
+ if (this.blinkStartMs >= 0) {
646
+ const phase = (clockMs - this.blinkStartMs) / BLINK_DURATION_MS;
647
+ if (phase >= 1) {
648
+ this.blinkStartMs = -1;
649
+ this.nextBlinkAtMs = clockMs + lerp(BLINK_INTERVAL_MIN_MS, BLINK_INTERVAL_MAX_MS, this.rng());
650
+ return 1;
651
+ }
652
+ return blinkEnvelope(phase);
653
+ }
654
+ if (clockMs >= this.nextBlinkAtMs) {
655
+ this.blinkStartMs = clockMs;
656
+ return blinkEnvelope(0);
657
+ }
658
+ return 1;
659
+ }
660
+ advanceBreath() {
661
+ return 0.5 + 0.5 * Math.sin(2 * Math.PI * this.clockMs / BREATH_PERIOD_MS);
662
+ }
663
+ /** Horizontal head sway in degrees, pure function of the internal clock. */
664
+ swayX() {
665
+ const t = 2 * Math.PI * this.clockMs;
666
+ return SWAY_X_AMP_A_DEG * Math.sin(t / SWAY_X_PERIOD_A_MS) + SWAY_X_AMP_B_DEG * Math.sin(t / SWAY_X_PERIOD_B_MS);
667
+ }
668
+ /** Vertical head sway in degrees, pure function of the internal clock. */
669
+ swayY() {
670
+ return SWAY_Y_AMP_DEG * Math.sin(2 * Math.PI * this.clockMs / SWAY_Y_PERIOD_MS);
671
+ }
672
+ /** Head roll sway in degrees, pure function of the internal clock. */
673
+ swayZ() {
674
+ return SWAY_Z_AMP_DEG * Math.sin(2 * Math.PI * this.clockMs / SWAY_Z_PERIOD_MS);
675
+ }
676
+ /** Ease gaze current toward target; pick a new target on the internal clock. */
677
+ advanceGaze(dt) {
678
+ if (this.clockMs >= this.nextGazeRetargetMs) {
679
+ const [tx, ty] = randomInDisk(this.rng, GAZE_RADIUS);
680
+ this.gazeTargetX = tx;
681
+ this.gazeTargetY = ty;
682
+ this.nextGazeRetargetMs = this.clockMs + lerp(GAZE_RETARGET_MIN_MS, GAZE_RETARGET_MAX_MS, this.rng());
683
+ }
684
+ const factor = 1 - Math.pow(1 - GAZE_EASE_RATE, dt);
685
+ this.gazeCurrentX = lerp(this.gazeCurrentX, this.gazeTargetX, factor);
686
+ this.gazeCurrentY = lerp(this.gazeCurrentY, this.gazeTargetY, factor);
687
+ }
688
+ };
689
+
690
+ // ../engine/src/physics-motion.ts
691
+ function signedNormalized(value, param) {
692
+ const rest = clamp(param.default, param.min, param.max);
693
+ const den = Math.max(Math.abs(param.max - rest), Math.abs(rest - param.min));
694
+ if (den === 0) return 0;
695
+ return clamp((value - rest) / den, -1, 1);
696
+ }
697
+ var PhysicsMotion = class {
698
+ /** The output parameter of every rig, in rig order — what `emit` writes. */
699
+ drivenParameterIds;
700
+ /**
701
+ * Per rig: how many times the finiteness guard reset its state or `emit`
702
+ * replaced its non-finite product. Up to two per frame, so guard activations,
703
+ * not repaired frames. A diagnostic; emitted values are unchanged.
704
+ */
705
+ resets;
706
+ resetCounts;
707
+ rigs;
708
+ read;
709
+ sink;
710
+ params;
711
+ // Integrator state, owned here — never stored in a ParameterStore.
712
+ state;
713
+ clock = new FixedStepClock();
714
+ constructor(rigs, params, read, sink) {
715
+ this.rigs = rigs;
716
+ this.read = read;
717
+ this.sink = sink;
718
+ this.params = new Map(params.map((p) => [p.id, p]));
719
+ this.state = rigs.map(() => ({ x: 0, v: 0 }));
720
+ this.drivenParameterIds = rigs.map((rig) => rig.output.parameter);
721
+ this.resetCounts = rigs.map(() => 0);
722
+ this.resets = this.resetCounts;
723
+ }
724
+ /**
725
+ * Advance every rig to the given wall-clock timestamp (milliseconds).
726
+ *
727
+ * First call: seed each spring to rest AT its current target (so a model
728
+ * loaded with a nonzero input does not kick), emit the resting output, and
729
+ * return without integrating — mirroring IdleMotion's first-frame behavior.
730
+ *
731
+ * Subsequent calls: {@link FixedStepClock} folds the clamped frame delta into
732
+ * its accumulator and returns how many {@link FIXED_DT_S} sub-steps are due;
733
+ * the spring advances that many semi-implicit Euler steps, then each rig emits
734
+ * its output once. The clock's dt clamp and sub-step cap plus the symplectic
735
+ * integrator are what keep it stable across hitches.
736
+ */
737
+ update(nowMs) {
738
+ if (this.clock.isSeedFrame) {
739
+ this.clock.advance(nowMs);
740
+ for (let i = 0; i < this.rigs.length; i++) {
741
+ const st = this.state[i];
742
+ st.x = this.targetFor(this.rigs[i]);
743
+ st.v = 0;
744
+ this.emit(i, st);
745
+ }
746
+ return;
747
+ }
748
+ const steps = this.clock.advance(nowMs);
749
+ const targets = this.rigs.map((rig) => this.targetFor(rig));
750
+ for (let s = 0; s < steps; s++) {
751
+ for (let i = 0; i < this.rigs.length; i++) {
752
+ this.step(this.rigs[i], this.state[i], targets[i]);
753
+ }
754
+ }
755
+ for (let i = 0; i < this.rigs.length; i++) {
756
+ const st = this.state[i];
757
+ if (!Number.isFinite(st.x) || !Number.isFinite(st.v)) {
758
+ st.x = Number.isFinite(targets[i]) ? targets[i] : 0;
759
+ st.v = 0;
760
+ this.resetCounts[i]++;
761
+ }
762
+ this.emit(i, st);
763
+ }
764
+ }
765
+ /** Spring target = signed-normalized input value × weight. */
766
+ targetFor(rig) {
767
+ const param = this.params.get(rig.input.parameter);
768
+ const value = this.read(rig.input.parameter);
769
+ const norm = param ? signedNormalized(value, param) : 0;
770
+ return norm * rig.input.weight;
771
+ }
772
+ /** One semi-implicit (symplectic) Euler sub-step of FIXED_DT_S seconds. */
773
+ step(rig, st, target2) {
774
+ const accel = (rig.stiffness * (target2 - st.x) - rig.damping * st.v) / rig.mass;
775
+ st.v += accel * FIXED_DT_S;
776
+ st.x += st.v * FIXED_DT_S;
777
+ }
778
+ /** Write outputDefault + x * scale onto the output param via the sink. */
779
+ emit(index, st) {
780
+ const rig = this.rigs[index];
781
+ const outParam = this.params.get(rig.output.parameter);
782
+ const outDefault = outParam ? clamp(outParam.default, outParam.min, outParam.max) : 0;
783
+ const value = outDefault + st.x * rig.output.scale;
784
+ const finite = Number.isFinite(value);
785
+ if (!finite) this.resetCounts[index]++;
786
+ this.sink(rig.output.parameter, finite ? value : outDefault);
787
+ }
788
+ };
482
789
 
483
790
  // ../engine/src/hair-chain-motion.ts
484
791
  var DEG2RAD = Math.PI / 180;
485
792
  var RAD2DEG = 180 / Math.PI;
793
+ var HairChainMotion = class {
794
+ /** Every segment's output, chain by chain — what `emitSegment` writes. */
795
+ drivenParameterIds;
796
+ /**
797
+ * Per segment, in `drivenParameterIds` order: how many times the finiteness
798
+ * guard reset its state or `emitSegment` replaced its non-finite product. Up
799
+ * to two per frame, so guard activations, not repaired frames. A diagnostic;
800
+ * emitted values are unchanged.
801
+ */
802
+ resets;
803
+ resetCounts;
804
+ chainData;
805
+ params;
806
+ deformers;
807
+ store;
808
+ read;
809
+ sink;
810
+ clock = new FixedStepClock();
811
+ constructor(chains, params, deformers, read, sink) {
812
+ this.params = new Map(params.map((p) => [p.id, p]));
813
+ this.deformers = deformers;
814
+ this.store = new ParameterStore(params);
815
+ this.read = read;
816
+ this.sink = sink;
817
+ this.chainData = chains.map((chain) => ({
818
+ chain,
819
+ restAnglesRad: chain.segments.map(
820
+ (seg) => seg.restAngle !== void 0 ? seg.restAngle * DEG2RAD : 0
821
+ ),
822
+ state: chain.segments.map(() => ({ angle: 0, angularVelocity: 0 }))
823
+ }));
824
+ this.drivenParameterIds = chains.flatMap(
825
+ (c) => c.segments.map((s) => s.output.parameter)
826
+ );
827
+ this.resetCounts = this.drivenParameterIds.map(() => 0);
828
+ this.resets = this.resetCounts;
829
+ }
830
+ /**
831
+ * Advance every chain to the given wall-clock timestamp (milliseconds).
832
+ *
833
+ * First call: seed every segment to θ=0/ω=0 (rest), emit the rest output
834
+ * (outDefault + 0), and return without integrating — mirrors PhysicsMotion's
835
+ * first-frame behavior so a model loaded in motion does not kick.
836
+ *
837
+ * Subsequent calls: dt = clamp(nowMs - prevNowMs, 0, MAX_DT_MS) → seconds into
838
+ * accumulator. The per-frame world snapshot (anchor world angles) is taken ONCE
839
+ * per update() — NOT per chain — so all chains share a consistent frame snapshot.
840
+ * Fixed FIXED_DT_S sub-steps are run root→tip, capped at MAX_SUBSTEPS; leftover
841
+ * time is carried to the next frame. Segments emit after substeps (even on zero
842
+ * substeps) with a non-finite guard.
843
+ */
844
+ update(nowMs) {
845
+ if (this.chainData.length === 0) return;
846
+ if (this.clock.isSeedFrame) {
847
+ this.clock.advance(nowMs);
848
+ let flat2 = 0;
849
+ for (const cd of this.chainData) {
850
+ for (let i = 0; i < cd.chain.segments.length; i++) {
851
+ cd.state[i].angle = 0;
852
+ cd.state[i].angularVelocity = 0;
853
+ this.emitSegment(flat2++, cd.chain.segments[i], cd.state[i]);
854
+ }
855
+ }
856
+ return;
857
+ }
858
+ const steps = this.clock.advance(nowMs);
859
+ for (const param of this.params.values()) {
860
+ this.store.set(param.id, this.read(param.id));
861
+ }
862
+ const worldMap = resolveDeformers(this.deformers, this.store).worlds;
863
+ const anchorAnglesRad = this.chainData.map(
864
+ (cd) => this.anchorWorldAngleRad(worldMap, cd.chain.anchorDeformer)
865
+ );
866
+ for (let s = 0; s < steps; s++) {
867
+ for (let c = 0; c < this.chainData.length; c++) {
868
+ this.stepChain(this.chainData[c], anchorAnglesRad[c]);
869
+ }
870
+ }
871
+ let flat = 0;
872
+ for (const cd of this.chainData) {
873
+ for (let i = 0; i < cd.chain.segments.length; i++) {
874
+ const st = cd.state[i];
875
+ if (!Number.isFinite(st.angle) || !Number.isFinite(st.angularVelocity)) {
876
+ st.angle = 0;
877
+ st.angularVelocity = 0;
878
+ this.resetCounts[flat]++;
879
+ }
880
+ this.emitSegment(flat++, cd.chain.segments[i], st);
881
+ }
882
+ }
883
+ }
884
+ /**
885
+ * Extract world rotation (radians) from the anchor's Affine tuple.
886
+ * Affine = [a,b,c,d,e,f]; rotation column = (a,b) → atan2(b,a).
887
+ *
888
+ * If the anchor id is absent from the map, THROWS an internal Error — the
889
+ * format validator guarantees the anchor exists, so absence is an invariant
890
+ * break (mirrors resolveDeformers' throw on an unresolved parent).
891
+ */
892
+ anchorWorldAngleRad(worldMap, anchorId) {
893
+ const world = worldMap.get(anchorId);
894
+ if (!world) {
895
+ throw new Error(
896
+ `HairChainMotion: anchor deformer "${anchorId}" not found in resolved world map \u2014 model not validated?`
897
+ );
898
+ }
899
+ return Math.atan2(world[1], world[0]);
900
+ }
901
+ /**
902
+ * One fixed sub-step of FIXED_DT_S seconds for all segments in a chain.
903
+ *
904
+ * Segments are integrated ROOT→TIP so each segment can read its upstream
905
+ * neighbor's current-substep state when computing the world angle Φ_i.
906
+ * (The chain is causal root-to-tip; reversing the order would use stale θ
907
+ * values from the previous substep for Φ_i computation.)
908
+ *
909
+ * Per-segment semi-implicit (symplectic) Euler:
910
+ * Φ_i = anchorWorldAngleRad + Σ_{j≤i}(restAngle_j + θ_j)
911
+ * α_i = (−stiffness_i·θ_i − strength·sin(Φ_i − gravityAngle_rad) − damping_i·ω_i) / mass_i
912
+ * ω_i += α_i · FIXED_DT_S (velocity updated FIRST = semi-implicit)
913
+ * θ_i += ω_i · FIXED_DT_S (position updated from NEW velocity)
914
+ *
915
+ * The spring term is −stiffness·θ (restoring θ→0); restAngle does NOT appear
916
+ * in the spring term, only in Φ_i for the gravity torque.
917
+ */
918
+ stepChain(cd, anchorAngleRad) {
919
+ const { chain, restAnglesRad, state } = cd;
920
+ const gravityAngleRad = chain.gravity.angle * DEG2RAD;
921
+ const strength = chain.gravity.strength;
922
+ let worldAngleAccumRad = anchorAngleRad;
923
+ for (let i = 0; i < chain.segments.length; i++) {
924
+ const seg = chain.segments[i];
925
+ const st = state[i];
926
+ worldAngleAccumRad += restAnglesRad[i] + st.angle;
927
+ const phi = worldAngleAccumRad;
928
+ const alpha = (-seg.stiffness * st.angle - strength * Math.sin(phi - gravityAngleRad) - seg.damping * st.angularVelocity) / seg.mass;
929
+ st.angularVelocity += alpha * FIXED_DT_S;
930
+ st.angle += st.angularVelocity * FIXED_DT_S;
931
+ }
932
+ }
933
+ /** Emit outDefault + (θ_i · RAD2DEG) · scale for one segment. */
934
+ emitSegment(flat, seg, st) {
935
+ const outParam = this.params.get(seg.output.parameter);
936
+ const outDefault = outParam ? clamp(outParam.default, outParam.min, outParam.max) : 0;
937
+ const value = outDefault + st.angle * RAD2DEG * seg.output.scale;
938
+ const finite = Number.isFinite(value);
939
+ if (!finite) this.resetCounts[flat]++;
940
+ this.sink(seg.output.parameter, finite ? value : outDefault);
941
+ }
942
+ };
486
943
 
487
944
  // ../engine/src/iki-motion.ts
488
945
  var import_format4 = require("@ikijs/format");
@@ -504,6 +961,62 @@ var HEAD_AND_GAZE = /* @__PURE__ */ new Set([
504
961
 
505
962
  // ../engine/src/folds.ts
506
963
  var import_format5 = require("@ikijs/format");
964
+
965
+ // ../engine/src/land.ts
966
+ function staticDeformers(model) {
967
+ return (model.deformers ?? []).map(
968
+ (d) => d.kind === "warp" ? { ...d, warps: void 0, warp2d: void 0 } : { ...d, bindings: void 0 }
969
+ );
970
+ }
971
+ function placement(part, t) {
972
+ return multiply(
973
+ multiply(translate(t.x, t.y), rotate(t.rotation)),
974
+ scale(part.width * t.scaleX, part.height * t.scaleY)
975
+ );
976
+ }
977
+ function landedPart(part, vertices, deformers, worlds, store) {
978
+ const warpDeformer = deformers.find(
979
+ (d) => d.kind === "warp" && d.id === part.deformer
980
+ );
981
+ const frame = warpDeformer ? warpDeformer.parent : part.deformer;
982
+ const placed = placement(
983
+ part,
984
+ evaluateTransform(part.transform, void 0, store)
985
+ );
986
+ const restPoints = transformGridPoints(
987
+ vertices,
988
+ frame === void 0 ? placed : multiply(worlds.get(frame), placed),
989
+ new Float64Array(vertices.length)
990
+ );
991
+ return {
992
+ part,
993
+ warpDeformer,
994
+ vertices: Float32Array.from(vertices),
995
+ local: new Float32Array(vertices.length),
996
+ landed: new Float32Array(vertices.length),
997
+ restPoints
998
+ };
999
+ }
1000
+ function landPart(landing, store, { worlds, grids }) {
1001
+ const { part, warpDeformer, local, landed } = landing;
1002
+ applyWarps(landing.vertices, part.warps, store, local);
1003
+ const placed = placement(
1004
+ part,
1005
+ evaluateTransform(part.transform, part.bindings, store)
1006
+ );
1007
+ if (warpDeformer) {
1008
+ const grid = grids.get(warpDeformer.id);
1009
+ applyWarpToChild(local, placed, warpDeformer.grid, grid, landed);
1010
+ } else if (part.deformer !== void 0) {
1011
+ const world = worlds.get(part.deformer);
1012
+ transformGridPoints(local, multiply(world, placed), landed);
1013
+ } else {
1014
+ transformGridPoints(local, placed, landed);
1015
+ }
1016
+ return landed;
1017
+ }
1018
+
1019
+ // ../engine/src/folds.ts
507
1020
  var FLIP = 0;
508
1021
  var COLLAPSE = 0.1;
509
1022
  var ANGLES = [
@@ -567,11 +1080,6 @@ function poseName(values) {
567
1080
  if (ids.length === 0) return "rest";
568
1081
  return ids.map((id) => `${id}=${values[id]}`).join(" ");
569
1082
  }
570
- function staticDeformers(model) {
571
- return (model.deformers ?? []).map(
572
- (d) => d.kind === "warp" ? { ...d, warps: void 0, warp2d: void 0 } : { ...d, bindings: void 0 }
573
- );
574
- }
575
1083
  function cornerAreas(points, cols, rows) {
576
1084
  const stride = cols + 1;
577
1085
  const out = new Float64Array(cols * rows * 4);
@@ -603,12 +1111,6 @@ function triangleAreas(points, indices) {
603
1111
  }
604
1112
  return out;
605
1113
  }
606
- function placement(part, t) {
607
- return multiply(
608
- multiply(translate(t.x, t.y), rotate(t.rotation)),
609
- scale(part.width * t.scaleX, part.height * t.scaleY)
610
- );
611
- }
612
1114
  function keepLeast(sweep, areas, pose, expected) {
613
1115
  const slot = expected(sweep.target) ? "expected" : "worst";
614
1116
  for (let i = 0; i < areas.length; i++) {
@@ -621,50 +1123,15 @@ function keepLeast(sweep, areas, pose, expected) {
621
1123
  }
622
1124
  }
623
1125
  function partSweep(part, mesh, deformers, worlds, store) {
624
- const warpDeformer = deformers.find(
625
- (d) => d.kind === "warp" && d.id === part.deformer
626
- );
627
- const frame = warpDeformer ? warpDeformer.parent : part.deformer;
628
- const placed = placement(
629
- part,
630
- evaluateTransform(part.transform, void 0, store)
631
- );
632
- const restPoints = transformGridPoints(
633
- mesh.vertices,
634
- frame === void 0 ? placed : multiply(worlds.get(frame), placed),
635
- new Float64Array(mesh.vertices.length)
636
- );
1126
+ const landing = landedPart(part, mesh.vertices, deformers, worlds, store);
637
1127
  return {
1128
+ ...landing,
638
1129
  target: { kind: "part", id: part.id },
639
- restAreas: triangleAreas(restPoints, mesh.indices),
1130
+ restAreas: triangleAreas(landing.restPoints, mesh.indices),
640
1131
  tiny: 1e-9 * part.width * part.height,
641
- part,
642
- indices: mesh.indices,
643
- warpDeformer,
644
- vertices: Float32Array.from(mesh.vertices),
645
- local: new Float32Array(mesh.vertices.length),
646
- landed: new Float32Array(mesh.vertices.length),
647
- restPoints
1132
+ indices: mesh.indices
648
1133
  };
649
1134
  }
650
- function landPart(sweep, store, { worlds, grids }) {
651
- const { part, warpDeformer, local, landed } = sweep;
652
- applyWarps(sweep.vertices, part.warps, store, local);
653
- const placed = placement(
654
- part,
655
- evaluateTransform(part.transform, part.bindings, store)
656
- );
657
- if (warpDeformer) {
658
- const grid = grids.get(warpDeformer.id);
659
- applyWarpToChild(local, placed, warpDeformer.grid, grid, landed);
660
- } else if (part.deformer !== void 0) {
661
- const world = worlds.get(part.deformer);
662
- transformGridPoints(local, multiply(world, placed), landed);
663
- } else {
664
- transformGridPoints(local, placed, landed);
665
- }
666
- return landed;
667
- }
668
1135
  function checkFolds(model, options = {}) {
669
1136
  const poses = options.poses ?? foldPoses(model);
670
1137
  const deformers = model.deformers ?? [];
@@ -691,7 +1158,7 @@ function checkFolds(model, options = {}) {
691
1158
  const store = new ParameterStore(model.parameters);
692
1159
  for (const [id, v] of Object.entries(pose.values)) store.set(id, v);
693
1160
  const value = (id) => store.get(id);
694
- const expected = (target) => options.expected?.(target, pose, value) === true;
1161
+ const expected = (target2) => options.expected?.(target2, pose, value) === true;
695
1162
  for (const sweep of gridSweeps) {
696
1163
  const { cols, rows } = sweep.deformer.grid;
697
1164
  const areas = cornerAreas(
@@ -782,7 +1249,403 @@ function classify(worst) {
782
1249
  return "ok";
783
1250
  }
784
1251
 
1252
+ // ../engine/src/physics-runs.ts
1253
+ var FRAME_MS = FIXED_DT_S * 1e3 * (1 + 1e-9);
1254
+ var STEP_FRAMES = 300;
1255
+ var IDLE_FRAMES = 1800;
1256
+ var IDLE_SEED = 1;
1257
+ var MIN_TURN = 1e-9;
1258
+ function run(model, store, rigs, chains, frames, excite) {
1259
+ const raw = /* @__PURE__ */ new Map();
1260
+ const read = (id) => store.get(id);
1261
+ const sink = (id, value) => {
1262
+ let trace = raw.get(id);
1263
+ if (trace === void 0) raw.set(id, trace = []);
1264
+ trace.push(value);
1265
+ store.set(id, value);
1266
+ };
1267
+ const { parameters } = model;
1268
+ const drivers = [
1269
+ new PhysicsMotion(rigs, parameters, read, sink),
1270
+ new HairChainMotion(chains, parameters, model.deformers ?? [], read, sink)
1271
+ ];
1272
+ for (let frame = 0; frame <= frames; frame++) {
1273
+ const nowMs = frame * FRAME_MS;
1274
+ excite(frame, nowMs);
1275
+ for (const driver of drivers) driver.update(nowMs);
1276
+ }
1277
+ const readings = /* @__PURE__ */ new Map();
1278
+ for (const driver of drivers) {
1279
+ driver.drivenParameterIds.forEach((id, i) => {
1280
+ const param = parameters.find((p) => p.id === id);
1281
+ readings.set(id, readTrace(raw.get(id), param, driver.resets[i]));
1282
+ });
1283
+ }
1284
+ return readings;
1285
+ }
1286
+ function readTrace(raw, param, resets) {
1287
+ const rest = clamp(param.default, param.min, param.max);
1288
+ const reading = {
1289
+ peak: 0,
1290
+ at: 0,
1291
+ final: rest,
1292
+ values: [],
1293
+ lo: rest,
1294
+ hi: rest,
1295
+ pinned: { frames: 0, end: "max" },
1296
+ resets
1297
+ };
1298
+ const seen = /* @__PURE__ */ new Set([rest]);
1299
+ let outside = 0;
1300
+ let end = "max";
1301
+ raw.forEach((value, frame) => {
1302
+ const held = clamp(value, param.min, param.max);
1303
+ if (Math.abs(held - rest) > Math.abs(reading.peak)) {
1304
+ reading.peak = held - rest;
1305
+ reading.at = frame * FIXED_DT_S;
1306
+ }
1307
+ if (!seen.has(held)) {
1308
+ seen.add(held);
1309
+ reading.values.push(held);
1310
+ }
1311
+ reading.lo = Math.min(reading.lo, held);
1312
+ reading.hi = Math.max(reading.hi, held);
1313
+ reading.final = held;
1314
+ if (value >= param.min && value <= param.max) {
1315
+ outside = 0;
1316
+ return;
1317
+ }
1318
+ const side = value < param.min ? "min" : "max";
1319
+ if (outside === 0 || side !== end) {
1320
+ outside = 0;
1321
+ end = side;
1322
+ }
1323
+ outside++;
1324
+ if (outside > reading.pinned.frames) {
1325
+ reading.pinned = { frames: outside, end };
1326
+ }
1327
+ });
1328
+ return reading;
1329
+ }
1330
+ function farEnd(param) {
1331
+ if (param.min === param.max) return void 0;
1332
+ const rest = clamp(param.default, param.min, param.max);
1333
+ return param.max - rest >= rest - param.min ? param.max : param.min;
1334
+ }
1335
+ function stepRun(model, rigs, chains, values) {
1336
+ const store = new ParameterStore(model.parameters);
1337
+ return run(model, store, rigs, chains, STEP_FRAMES, (frame) => {
1338
+ if (frame !== 1) return;
1339
+ for (const [id, v] of Object.entries(values)) store.set(id, v);
1340
+ });
1341
+ }
1342
+ function idleRun(model) {
1343
+ const store = new ParameterStore(model.parameters);
1344
+ const idle = new IdleMotion((id, v) => store.set(id, v), {
1345
+ rng: lcg(IDLE_SEED)
1346
+ });
1347
+ return run(
1348
+ model,
1349
+ store,
1350
+ model.physics ?? [],
1351
+ model.physicsChains ?? [],
1352
+ IDLE_FRAMES,
1353
+ (_, nowMs) => idle.update(nowMs)
1354
+ );
1355
+ }
1356
+ function lcg(seed) {
1357
+ let state = seed >>> 0;
1358
+ return () => {
1359
+ state = Math.imul(state, 1664525) + 1013904223 >>> 0;
1360
+ return state / 2 ** 32;
1361
+ };
1362
+ }
1363
+ function anchorInputs(model, chain) {
1364
+ const store = new ParameterStore(model.parameters);
1365
+ const angle = () => {
1366
+ const { worlds } = resolveDeformers(model.deformers ?? [], store);
1367
+ const world = worlds.get(chain.anchorDeformer);
1368
+ return Math.atan2(world[1], world[0]);
1369
+ };
1370
+ const rest = angle();
1371
+ const found = [];
1372
+ for (const p of model.parameters) {
1373
+ const probes = new Set(
1374
+ [p.max, p.min, ...stopsOf(model, p.id)].map(
1375
+ (v) => clamp(v, p.min, p.max)
1376
+ )
1377
+ );
1378
+ probes.delete(store.get(p.id));
1379
+ let most = 0;
1380
+ let best;
1381
+ for (const value of probes) {
1382
+ store.set(p.id, value);
1383
+ const d = angle() - rest;
1384
+ const turn = Math.abs(Math.atan2(Math.sin(d), Math.cos(d)));
1385
+ if (turn <= most + MIN_TURN) continue;
1386
+ [most, best] = [turn, { parameter: p.id, value }];
1387
+ }
1388
+ store.reset();
1389
+ if (best) found.push(best);
1390
+ }
1391
+ return found;
1392
+ }
1393
+ function stopsOf(model, parameter) {
1394
+ const stops = /* @__PURE__ */ new Set();
1395
+ for (const d of model.deformers ?? []) {
1396
+ if (d.kind !== "warp") continue;
1397
+ for (const w of d.warps ?? []) {
1398
+ if (w.parameter !== parameter) continue;
1399
+ for (const k of w.keyforms) stops.add(k.value);
1400
+ }
1401
+ const { warp2d } = d;
1402
+ if (warp2d?.parameter === parameter) {
1403
+ for (const v of warp2d.valuesX) stops.add(v);
1404
+ }
1405
+ if (warp2d?.parameterY === parameter) {
1406
+ for (const v of warp2d.valuesY) stops.add(v);
1407
+ }
1408
+ }
1409
+ return [...stops].sort((a, b) => a - b);
1410
+ }
1411
+
1412
+ // ../engine/src/physics-check.ts
1413
+ var DISPLACEMENT_PX = 1;
1414
+ var PINNED_FRAMES = 60;
1415
+ var TOLERANCE = 1e-9;
1416
+ var UNIT_QUAD = [-0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, 0.5];
1417
+ function checkPhysics(model) {
1418
+ const idle = idleRun(model);
1419
+ const displace = displacer(model);
1420
+ const idleExcitation = (output) => {
1421
+ const reading = idle.get(output.id);
1422
+ return {
1423
+ name: "the idle",
1424
+ reading,
1425
+ displacementPx: displace(output, reading.values)
1426
+ };
1427
+ };
1428
+ const param = (id) => model.parameters.find((p) => p.id === id);
1429
+ const springs = (model.physics ?? []).map((rig) => {
1430
+ const input = param(rig.input.parameter);
1431
+ const output = param(rig.output.parameter);
1432
+ const far = farEnd(input);
1433
+ const values = far === void 0 ? {} : { [input.id]: far };
1434
+ const reading = stepRun(model, [rig], [], values).get(output.id);
1435
+ const step = {
1436
+ name: "the step",
1437
+ reading,
1438
+ displacementPx: displace(output, reading.values),
1439
+ values
1440
+ };
1441
+ const atIdle = idleExcitation(output);
1442
+ return target(model, {
1443
+ rig: { kind: "spring", id: rig.id },
1444
+ input: [input.id],
1445
+ output,
1446
+ step,
1447
+ idle: atIdle,
1448
+ unstable: springWhy(rig) ?? unstableWhy(output, [step, atIdle]),
1449
+ inert: far === void 0 ? `${input.id} has no range` : void 0
1450
+ });
1451
+ });
1452
+ const chains = (model.physicsChains ?? []).flatMap((chain) => {
1453
+ const candidates = anchorInputs(model, chain);
1454
+ const settings = candidates.length === 0 ? [{}] : candidates.map((c) => ({ [c.parameter]: c.value }));
1455
+ const runs = settings.map((values) => ({
1456
+ values,
1457
+ readings: stepRun(model, [], [chain], values)
1458
+ }));
1459
+ return chain.segments.map((segment, i) => {
1460
+ const output = param(segment.output.parameter);
1461
+ const steps = runs.map(({ values, readings }) => {
1462
+ const reading = readings.get(output.id);
1463
+ const setting = Object.entries(values).map(([id, v]) => `${id}=${v}`);
1464
+ return {
1465
+ name: ["the step", ...setting].join(" "),
1466
+ reading,
1467
+ displacementPx: displace(output, reading.values),
1468
+ values
1469
+ };
1470
+ });
1471
+ const atIdle = idleExcitation(output);
1472
+ const clean = steps.filter((s) => !unstableWhy(output, [s]));
1473
+ return target(model, {
1474
+ rig: { kind: "chain", id: chain.id, segment: i },
1475
+ input: candidates.map((c) => c.parameter),
1476
+ output,
1477
+ step: mostMoving(clean.length > 0 ? clean : steps),
1478
+ idle: atIdle,
1479
+ unstable: unstableWhy(output, [...steps, atIdle]),
1480
+ inert: candidates.length === 0 ? `nothing turns anchor ${chain.anchorDeformer}` : void 0
1481
+ });
1482
+ });
1483
+ });
1484
+ const targets = [...springs, ...chains];
1485
+ return {
1486
+ thresholds: {
1487
+ displacementPx: DISPLACEMENT_PX,
1488
+ pinnedFrames: PINNED_FRAMES
1489
+ },
1490
+ targets,
1491
+ offenders: [
1492
+ ...targets.filter((t) => t.kind === "unstable"),
1493
+ ...targets.filter((t) => t.kind === "frozen")
1494
+ ]
1495
+ };
1496
+ }
1497
+ function target(model, t) {
1498
+ const { step, idle, output } = t;
1499
+ const drives = drivesOf(model, output.id);
1500
+ const px2 = Math.floor(step.displacementPx * 10) / 10;
1501
+ const still = step.displacementPx < DISPLACEMENT_PX ? `moves ${px2.toFixed(1)} model px over ${step.name}` : void 0;
1502
+ const frozen = drives.length === 0 ? "drives nothing" : t.inert ?? still;
1503
+ const { peak, at, final } = step.reading;
1504
+ return {
1505
+ rig: t.rig,
1506
+ input: t.input,
1507
+ output: output.id,
1508
+ drives,
1509
+ kind: t.unstable ? "unstable" : frozen ? "frozen" : "ok",
1510
+ why: t.unstable ?? frozen,
1511
+ step: {
1512
+ values: step.values,
1513
+ peak,
1514
+ at,
1515
+ final,
1516
+ displacementPx: step.displacementPx
1517
+ },
1518
+ idle: {
1519
+ peak: Math.abs(idle.reading.peak),
1520
+ at: idle.reading.at,
1521
+ displacementPx: idle.displacementPx
1522
+ }
1523
+ };
1524
+ }
1525
+ function mostMoving(steps) {
1526
+ return steps.reduce((best, s) => {
1527
+ if (s.displacementPx !== best.displacementPx) {
1528
+ return s.displacementPx > best.displacementPx ? s : best;
1529
+ }
1530
+ return Math.abs(s.reading.peak) > Math.abs(best.reading.peak) ? s : best;
1531
+ });
1532
+ }
1533
+ function drivesOf(model, output) {
1534
+ const parts = model.parts.filter(
1535
+ (p) => [
1536
+ ...(p.bindings ?? []).map((b) => b.parameter),
1537
+ ...(p.warps ?? []).map((w) => w.parameter)
1538
+ ].includes(output)
1539
+ );
1540
+ const deformers = (model.deformers ?? []).filter(
1541
+ (d) => (d.kind === "warp" ? [
1542
+ ...(d.warps ?? []).map((w) => w.parameter),
1543
+ d.warp2d?.parameter,
1544
+ d.warp2d?.parameterY
1545
+ ] : (d.bindings ?? []).map((b) => b.parameter)).includes(output)
1546
+ );
1547
+ return [
1548
+ ...parts.map((p) => ({ kind: "part", id: p.id })),
1549
+ ...deformers.map((d) => ({ kind: "deformer", id: d.id }))
1550
+ ];
1551
+ }
1552
+ function springStepRadius({ mass, stiffness, damping }) {
1553
+ const k = FIXED_DT_S * FIXED_DT_S * stiffness / mass;
1554
+ const c = FIXED_DT_S * damping / mass;
1555
+ const trace = 2 - k - c;
1556
+ const det = 1 - c;
1557
+ const disc = trace * trace - 4 * det;
1558
+ const radius = disc >= 0 ? (Math.abs(trace) + Math.sqrt(disc)) / 2 : Math.sqrt(det);
1559
+ return { radius, k };
1560
+ }
1561
+ function springWhy(rig) {
1562
+ const { radius, k } = springStepRadius(rig);
1563
+ if (radius > 1 + TOLERANCE) {
1564
+ let digits = 2;
1565
+ while (Number(radius.toFixed(digits)) <= 1) digits++;
1566
+ return `spring step map radius ${radius.toFixed(digits)} over 1 at 1/60 s`;
1567
+ }
1568
+ if (rig.damping === 0 && k >= 4 - TOLERANCE) {
1569
+ return `spring on its undamped boundary, dt\xB2k/m ${k.toFixed(2)}`;
1570
+ }
1571
+ return void 0;
1572
+ }
1573
+ function unstableWhy(output, excitations) {
1574
+ for (const { name, reading } of excitations) {
1575
+ const n = reading.resets;
1576
+ if (n === 0) continue;
1577
+ return `finiteness guard reset it ${n} time${n === 1 ? "" : "s"} in ${name}`;
1578
+ }
1579
+ for (const { name, reading } of excitations) {
1580
+ const { frames, end } = reading.pinned;
1581
+ if (frames < PINNED_FRAMES) continue;
1582
+ return `pinned at ${output.id} ${end} ${output[end]} for ${frames} frames of ${name}`;
1583
+ }
1584
+ return void 0;
1585
+ }
1586
+ function displacer(model) {
1587
+ const deformers = model.deformers ?? [];
1588
+ const store = new ParameterStore(model.parameters);
1589
+ const { worlds } = resolveDeformers(staticDeformers(model), store);
1590
+ const landings = model.parts.map(
1591
+ (part) => landedPart(
1592
+ part,
1593
+ part.mesh?.vertices ?? UNIT_QUAD,
1594
+ deformers,
1595
+ worlds,
1596
+ store
1597
+ )
1598
+ );
1599
+ const atRest = resolveDeformers(deformers, store);
1600
+ const baselines = landings.map(
1601
+ (l) => Float32Array.from(landPart(l, store, atRest))
1602
+ );
1603
+ return (output, values) => {
1604
+ let most = 0;
1605
+ const affected = affectedParts(model, output.id);
1606
+ for (const value of values) {
1607
+ store.set(output.id, value);
1608
+ const resolved = resolveDeformers(deformers, store);
1609
+ landings.forEach((landing, i) => {
1610
+ if (!affected.has(landing.part)) return;
1611
+ const landed = landPart(landing, store, resolved);
1612
+ const base = baselines[i];
1613
+ for (let j = 0; j < landed.length; j += 2) {
1614
+ const dx = landed[j] - base[j];
1615
+ const dy = landed[j + 1] - base[j + 1];
1616
+ most = Math.max(most, dx * dx + dy * dy);
1617
+ }
1618
+ });
1619
+ }
1620
+ store.reset();
1621
+ return Math.sqrt(most);
1622
+ };
1623
+ }
1624
+ function affectedParts(model, output) {
1625
+ const deformers = new Map((model.deformers ?? []).map((d) => [d.id, d]));
1626
+ const reads = (d) => (d.kind === "warp" ? [
1627
+ ...(d.warps ?? []).map((w) => w.parameter),
1628
+ d.warp2d?.parameter,
1629
+ d.warp2d?.parameterY
1630
+ ] : (d.bindings ?? []).map((b) => b.parameter)).includes(output);
1631
+ const hung = (id) => {
1632
+ for (let d = id && deformers.get(id); d; d = d.parent && deformers.get(d.parent)) {
1633
+ if (reads(d)) return true;
1634
+ }
1635
+ return false;
1636
+ };
1637
+ return new Set(
1638
+ model.parts.filter(
1639
+ (p) => [
1640
+ ...(p.bindings ?? []).map((b) => b.parameter),
1641
+ ...(p.warps ?? []).map((w) => w.parameter)
1642
+ ].includes(output) || hung(p.deformer)
1643
+ )
1644
+ );
1645
+ }
1646
+
785
1647
  // src/fold-report.ts
1648
+ var import_editor = require("@ikijs/editor");
786
1649
  function checkModelFolds(model, extraValues = []) {
787
1650
  const declared = new Set(model.parameters.map((p) => p.id));
788
1651
  return checkFolds(model, {
@@ -790,9 +1653,9 @@ function checkModelFolds(model, extraValues = []) {
790
1653
  // The effective value, not the pose's overrides: the auto-rig's mouth
791
1654
  // rests shut at its default, so `rest` and the other parameters' singles
792
1655
  // are shut-mouth poses too.
793
- expected: (target, _pose, value) => {
794
- if (target.kind !== "part") return false;
795
- const shutBy = import_editor.SHUT_BY.get(target.id);
1656
+ expected: (target2, _pose, value) => {
1657
+ if (target2.kind !== "part") return false;
1658
+ const shutBy = import_editor.SHUT_BY.get(target2.id);
796
1659
  return shutBy !== void 0 && declared.has(shutBy) && value(shutBy) === 0;
797
1660
  }
798
1661
  });
@@ -1494,6 +2357,7 @@ async function renderPoses(input) {
1494
2357
  model,
1495
2358
  input.poses?.map((p) => p.values)
1496
2359
  );
2360
+ const physics = checkPhysics(model);
1497
2361
  const { failedTextures, poses } = await withBrowser(
1498
2362
  browser,
1499
2363
  async (evaluate) => {
@@ -1530,7 +2394,8 @@ async function renderPoses(input) {
1530
2394
  failedTextures,
1531
2395
  poses,
1532
2396
  modelCanvas: model.canvas,
1533
- folds
2397
+ folds,
2398
+ physics
1534
2399
  };
1535
2400
  } catch (error) {
1536
2401
  if (error instanceof AutoRigInputError || error instanceof import_format6.IkiFormatError) {
@@ -2041,6 +2906,7 @@ async function autoRigFromLayers(input) {
2041
2906
  const finalModel = (0, import_format7.parseIkiModel)(patched);
2042
2907
  writeFileAtomic(outPath, JSON.stringify(finalModel));
2043
2908
  const folds = checkModelFolds(finalModel);
2909
+ const physics = checkPhysics(finalModel);
2044
2910
  return {
2045
2911
  ok: true,
2046
2912
  path: outPath,
@@ -2054,6 +2920,7 @@ async function autoRigFromLayers(input) {
2054
2920
  ...noseCore === void 0 ? {} : { noseCore },
2055
2921
  ...turn === void 0 ? {} : { turn },
2056
2922
  folds,
2923
+ physics,
2057
2924
  ...patches === void 0 ? {} : { patches }
2058
2925
  };
2059
2926
  } catch (err) {
@@ -3473,16 +4340,16 @@ async function layerStats(filePath) {
3473
4340
  let flatCutRun = 0;
3474
4341
  let flatCutY = -1;
3475
4342
  for (let y = minY + 1; y <= maxY; y++) {
3476
- let run = 0;
4343
+ let run2 = 0;
3477
4344
  for (let x = minX; x <= maxX; x++) {
3478
4345
  if (alpha(x, y - 1) < FLAT_CUT_ALPHA_ABOVE && alpha(x, y) > FLAT_CUT_ALPHA_BELOW) {
3479
- run++;
3480
- if (run > flatCutRun) {
3481
- flatCutRun = run;
4346
+ run2++;
4347
+ if (run2 > flatCutRun) {
4348
+ flatCutRun = run2;
3482
4349
  flatCutY = y;
3483
4350
  }
3484
4351
  } else {
3485
- run = 0;
4352
+ run2 = 0;
3486
4353
  }
3487
4354
  }
3488
4355
  }
@@ -3813,6 +4680,7 @@ var IRIS_W = 50;
3813
4680
  var EYEWHITE_SRC = "eyewhite.png";
3814
4681
  var EYE_LASH_LUMA = 120;
3815
4682
  var LASH_KEEP_FRACTION = 0.5;
4683
+ var EYE_LID_WARMTH = 30;
3816
4684
  var NOSE_TIP_AT = 0.66;
3817
4685
  var DEFAULT_LAYOUT = {
3818
4686
  // Back hair and body sit behind the face. Both are OPTIONAL: a parts dir
@@ -4296,6 +5164,36 @@ async function prepEyeSplit(partsDir) {
4296
5164
  }
4297
5165
  const lashCutoffY = minY + LASH_KEEP_FRACTION * (maxY - minY + 1);
4298
5166
  const detached = detachedAboveWhite(data, W, H);
5167
+ const isDark = (i) => data[i + 3] > 0 && luma(data, i) < EYE_LASH_LUMA;
5168
+ const isLight = (i) => data[i + 3] >= import_editor12.ALPHA_OPAQUE && luma(data, i) >= EYE_LASH_LUMA;
5169
+ const isWarm = (i) => data[i] - data[i + 2] >= EYE_LID_WARMTH;
5170
+ const whiteTop = new Int32Array(W).fill(-1);
5171
+ for (let x = 0; x < W; x++) {
5172
+ for (let y = 0; y < H; y++) {
5173
+ const i = (y * W + x) * 4;
5174
+ if (!detached[y * W + x] && isLight(i) && !isWarm(i)) {
5175
+ whiteTop[x] = y;
5176
+ break;
5177
+ }
5178
+ }
5179
+ }
5180
+ let first = 0;
5181
+ while (first < W && whiteTop[first] === -1) first++;
5182
+ if (first < W) {
5183
+ let last = W - 1;
5184
+ while (whiteTop[last] === -1) last--;
5185
+ whiteTop.fill(whiteTop[first], 0, first);
5186
+ whiteTop.fill(whiteTop[last], last + 1);
5187
+ }
5188
+ const lidStop = new Int32Array(W).fill(-1);
5189
+ for (let x = 0; x < W; x++) {
5190
+ for (let y = whiteTop[x] - 1; y >= 0; y--) {
5191
+ if (isDark((y * W + x) * 4)) {
5192
+ lidStop[x] = y;
5193
+ break;
5194
+ }
5195
+ }
5196
+ }
4299
5197
  const sclera = Buffer.from(data);
4300
5198
  const lash = Buffer.from(data);
4301
5199
  const lashLower = Buffer.from(data);
@@ -4303,12 +5201,13 @@ async function prepEyeSplit(partsDir) {
4303
5201
  for (let y = 0; y < H; y++) {
4304
5202
  for (let x = 0; x < W; x++) {
4305
5203
  const i = (y * W + x) * 4;
4306
- const isDark = data[i + 3] > 0 && luma(data, i) < EYE_LASH_LUMA;
5204
+ const dark = isDark(i);
4307
5205
  const upper = y <= lashCutoffY;
4308
- if (isDark && upper) sclera[i] = sclera[i + 1] = sclera[i + 2] = 255;
5206
+ if (dark && upper) sclera[i] = sclera[i + 1] = sclera[i + 2] = 255;
4309
5207
  if (detached[y * W + x]) sclera[i + 3] = 0;
4310
- if (!(isDark && upper)) lash[i + 3] = 0;
4311
- if (isDark && !upper) lowerInk = true;
5208
+ if (y < lidStop[x] && isLight(i) && isWarm(i)) sclera[i + 3] = 0;
5209
+ if (!(dark && upper)) lash[i + 3] = 0;
5210
+ if (dark && !upper) lowerInk = true;
4312
5211
  else lashLower[i + 3] = 0;
4313
5212
  }
4314
5213
  }
@@ -4698,6 +5597,22 @@ async function composeLayersFromParts(input) {
4698
5597
  }
4699
5598
  }
4700
5599
 
5600
+ // src/physics-report.ts
5601
+ function formatPhysicsReport(report) {
5602
+ if (report.targets.length === 0) return ["PHYSICS: no rigs"];
5603
+ return report.targets.map(targetLine);
5604
+ }
5605
+ function targetLine(t) {
5606
+ const inputs = t.input.join(", ");
5607
+ const rig = t.rig.kind === "chain" ? `${t.rig.id}/${t.rig.segment} [${inputs}]` : `${t.rig.id} ${inputs}`;
5608
+ const drives = t.drives.length === 0 ? "" : ` (${t.drives.map((d) => d.id).join(", ")})`;
5609
+ const { step, idle } = t;
5610
+ return `PHYSICS ${t.kind} ${rig} -> ${t.output}: step ${foldPose(step.values).name} peak ${step.peak.toFixed(2)} at ${step.at.toFixed(2)} s, final ${step.final.toFixed(2)}, moves ${pxText(step.displacementPx)} model px${drives}; idle peak ${idle.peak.toFixed(2)} at ${idle.at.toFixed(2)} s, ${pxText(idle.displacementPx)} model px` + (t.why === void 0 ? "" : ` \u2014 ${t.why}`);
5611
+ }
5612
+ function pxText(px2) {
5613
+ return (Math.floor(px2 * 10) / 10).toFixed(1);
5614
+ }
5615
+
4701
5616
  // src/server.ts
4702
5617
  var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
4703
5618
  var import_zod = require("zod");
@@ -4709,7 +5624,7 @@ function formatPatchReports(reports) {
4709
5624
  });
4710
5625
  }
4711
5626
  function createIkiMcpServer() {
4712
- const server = new import_mcp.McpServer({ name: "iki", version: "0.26.0" });
5627
+ const server = new import_mcp.McpServer({ name: "iki", version: "0.27.0" });
4713
5628
  server.registerTool(
4714
5629
  "validate_iki",
4715
5630
  {
@@ -4784,7 +5699,7 @@ function createIkiMcpServer() {
4784
5699
  server.registerTool(
4785
5700
  "auto_rig_from_layers",
4786
5701
  {
4787
- description: "Auto-rigs role-named PNG layers (face, eye_L/eye_R and either mouth or the lip set (mouth_inner + lip_lower + lip_upper, a mouth that folds open instead of crossfading) required; iris_L/R, brow_L/R, hair_front, body, arm_L/arm_R, forearm_pose_L/forearm_pose_R, mouth_tongue/mouth_teeth (only with the lip set: drawn under its lips and clipped to mouth_inner), etc. optional; an arm needs the body, a pose forearm needs its arm, and a partial lip set, one mixed with mouth/mouth_open, or mouth_tongue/mouth_teeth without it is refused) into a renderable .iki written to disk. Pass full-canvas PNG file paths; returns the output path + summary (the model is NOT inlined). Filenames map to roles unless `fileName` is given. The result's `folds` is the written rig's fold report, printed after the path the way render_poses prints it, and report-only: a fold never refuses the rig. `patches` (see its field) adds displacements to existing keyform stops of the freshly generated rig; each op then prints one line between the path and the fold report \u2014 `PATCH <i> <target> at <Param=v \u2026>: <moved> of <of> points (cols a-b, rows c-d), largest move <maxPx> model px`, with `(vertices)` in place of the columns and rows for a mesh part \u2014 and the result's `patches` carries the same reports (`index`, `target`, `at`, `moved`, `of`, `cols`/`rows` for a grid, `maxPx`), present whenever `patches` was passed, `[]` included. An op the input schema accepts but the rig refuses comes back as `INVALID: patches[i]\u2026` and nothing is written; an op with a missing field or a field of the wrong type is the SDK's input validation error.",
5702
+ description: "Auto-rigs role-named PNG layers (face, eye_L/eye_R and either mouth or the lip set (mouth_inner + lip_lower + lip_upper, a mouth that folds open instead of crossfading) required; iris_L/R, brow_L/R, hair_front, body, arm_L/arm_R, forearm_pose_L/forearm_pose_R, mouth_tongue/mouth_teeth (only with the lip set: drawn under its lips and clipped to mouth_inner), etc. optional; an arm needs the body, a pose forearm needs its arm, and a partial lip set, one mixed with mouth/mouth_open, or mouth_tongue/mouth_teeth without it is refused) into a renderable .iki written to disk. Pass full-canvas PNG file paths; returns the output path + summary (the model is NOT inlined). Filenames map to roles unless `fileName` is given. The result's `folds` is the written rig's fold report, printed after the path the way render_poses prints it, and report-only: a fold never refuses the rig. The `PHYSICS` lines follow the fold report (the result's `physics`), one per physics rig output \u2014 a spring's, or each chain segment's \u2014 reading ok, frozen or unstable with the step and idle amplitudes, or `PHYSICS: no rigs`; report-only too. `patches` (see its field) adds displacements to existing keyform stops of the freshly generated rig; each op then prints one line between the path and the fold report \u2014 `PATCH <i> <target> at <Param=v \u2026>: <moved> of <of> points (cols a-b, rows c-d), largest move <maxPx> model px`, with `(vertices)` in place of the columns and rows for a mesh part \u2014 and the result's `patches` carries the same reports (`index`, `target`, `at`, `moved`, `of`, `cols`/`rows` for a grid, `maxPx`), present whenever `patches` was passed, `[]` included. An op the input schema accepts but the rig refuses comes back as `INVALID: patches[i]\u2026` and nothing is written; an op with a missing field or a field of the wrong type is the SDK's input validation error.",
4788
5703
  inputSchema: {
4789
5704
  layers: import_zod.z.array(
4790
5705
  import_zod.z.object({
@@ -4850,7 +5765,8 @@ function createIkiMcpServer() {
4850
5765
  const text = r.ok ? [
4851
5766
  r.path,
4852
5767
  ...formatPatchReports(r.patches ?? []),
4853
- ...formatFoldReport(r.folds, r.canvas)
5768
+ ...formatFoldReport(r.folds, r.canvas),
5769
+ ...formatPhysicsReport(r.physics)
4854
5770
  ].join("\n") : `INVALID: ${r.error}`;
4855
5771
  return { content: [{ type: "text", text }], structuredContent: r };
4856
5772
  } catch (err) {
@@ -4979,7 +5895,7 @@ function createIkiMcpServer() {
4979
5895
  server.registerTool(
4980
5896
  "render_poses",
4981
5897
  {
4982
- description: "Renders a rigged .iki into the character loop's pose PNGs with the real engine, through the installed Chrome, Edge or Chromium run headless (set CHROME_PATH to pick one). The model decides the set: a bust gets 560x560 shots (rest, turns, nod, blinks, gaze, combined \u2014 ParamAngleX/Y/Z all at 30 \u2014 and stress: ParamAngleX/Y/Z all at -30, ParamMouthOpenY 1, both eyes at 0.5, the brows at opposite extremes (ParamBrowLY -1, ParamBrowRY 1, ParamBrowLAngle 1, ParamBrowRAngle -1) and each body angle the model declares at -10); a mouth adds 720x480 mouth crops; a full body (taller than wide) adds the full-canvas body, arm and elbow poses on a 1400-wide canvas, and a model with a pose forearm adds the full-pose-* shots. Given `poses` (see its field), the standard set is not rendered: only those poses are, each crop clamped to the model's canvas. Writes <pose>.png files into outDir, overwriting same-named files in place; returns the written paths one per line, then the model's fold report (the result's `folds`), checked by the engine over its own pose set plus any `poses`, each of which a `FOLD` line names by its settings, not its PNG name: a `FOLD` line per warp deformer or mesh part that flips (ratio <= 0) or collapses (under 0.1) at some pose \u2014 its cell or triangle, the ratio of its area there to at rest, the pose as its parameter settings (`rest` for none) and where it rests, in model space and in model px from the top-left (the layer PNGs' own pixels, not a render's) \u2014 or `FOLDS: none over N poses`, then a `FOLDS expected:` line naming the closures the rig draws on purpose (an eye or the mouth shut), each by part id, ratio and the parameter that shuts it. Report-only: a fold never fails the render. Fails with INVALID when no browser is found or an input is refused; a browser that cannot start is a tool error.",
5898
+ description: "Renders a rigged .iki into the character loop's pose PNGs with the real engine, through the installed Chrome, Edge or Chromium run headless (set CHROME_PATH to pick one). The model decides the set: a bust gets 560x560 shots (rest, turns, nod, blinks, gaze, combined \u2014 ParamAngleX/Y/Z all at 30 \u2014 and stress: ParamAngleX/Y/Z all at -30, ParamMouthOpenY 1, both eyes at 0.5, the brows at opposite extremes (ParamBrowLY -1, ParamBrowRY 1, ParamBrowLAngle 1, ParamBrowRAngle -1) and each body angle the model declares at -10); a mouth adds 720x480 mouth crops; a full body (taller than wide) adds the full-canvas body, arm and elbow poses on a 1400-wide canvas, and a model with a pose forearm adds the full-pose-* shots. Given `poses` (see its field), the standard set is not rendered: only those poses are, each crop clamped to the model's canvas. Writes <pose>.png files into outDir, overwriting same-named files in place; returns the written paths one per line, then the model's fold report (the result's `folds`), checked by the engine over its own pose set plus any `poses`, each of which a `FOLD` line names by its settings, not its PNG name: a `FOLD` line per warp deformer or mesh part that flips (ratio <= 0) or collapses (under 0.1) at some pose \u2014 its cell or triangle, the ratio of its area there to at rest, the pose as its parameter settings (`rest` for none) and where it rests, in model space and in model px from the top-left (the layer PNGs' own pixels, not a render's) \u2014 or `FOLDS: none over N poses`, then a `FOLDS expected:` line naming the closures the rig draws on purpose (an eye or the mouth shut), each by part id, ratio and the parameter that shuts it. Report-only: a fold never fails the render. The `PHYSICS` lines follow the fold report (the result's `physics`), one per physics rig output of the model's own rigs \u2014 `poses` do not enter it \u2014 reading ok, frozen or unstable with the step and idle amplitudes, or `PHYSICS: no rigs`; report-only too. Fails with INVALID when no browser is found or an input is refused; a browser that cannot start is a tool error.",
4983
5899
  inputSchema: {
4984
5900
  modelPath: import_zod.z.string().describe(
4985
5901
  "Rigged .iki file path (resolved against cwd; must sit under the working directory)."
@@ -5008,7 +5924,8 @@ function createIkiMcpServer() {
5008
5924
  const r = await renderPoses(args);
5009
5925
  const text = r.ok ? [
5010
5926
  ...r.poses.map((p) => p.path),
5011
- ...formatFoldReport(r.folds, r.modelCanvas)
5927
+ ...formatFoldReport(r.folds, r.modelCanvas),
5928
+ ...formatPhysicsReport(r.physics)
5012
5929
  ].join("\n") : `INVALID: ${r.error}`;
5013
5930
  return { content: [{ type: "text", text }], structuredContent: r };
5014
5931
  } catch (err) {
@@ -5033,6 +5950,7 @@ function createIkiMcpServer() {
5033
5950
  describeIkiAt,
5034
5951
  formatFoldReport,
5035
5952
  formatMeasureReport,
5953
+ formatPhysicsReport,
5036
5954
  formatTurnReport,
5037
5955
  listStandardParameters,
5038
5956
  measureLayers,