@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/cli.js CHANGED
@@ -14,12 +14,12 @@ var __copyProps = (to, from, except, desc) => {
14
14
  }
15
15
  return to;
16
16
  };
17
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
17
+ var __toESM = (mod, isNodeMode, target2) => (target2 = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
18
18
  // If the importer is in node compatibility mode or this is not an ESM
19
19
  // file that has been converted to a CommonJS file using a Babel-
20
20
  // compatible transform (i.e. "__esModule" has not been set), then set
21
21
  // "default" to the CommonJS "module.exports" for node compatibility.
22
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target2, "default", { value: mod, enumerable: true }) : target2,
23
23
  mod
24
24
  ));
25
25
 
@@ -37,9 +37,6 @@ var import_node_path4 = __toESM(require("path"));
37
37
  var import_format7 = require("@ikijs/format");
38
38
  var import_editor3 = require("@ikijs/editor");
39
39
 
40
- // src/fold-report.ts
41
- var import_editor = require("@ikijs/editor");
42
-
43
40
  // ../engine/src/math.ts
44
41
  function clamp(value, min, max) {
45
42
  return Math.max(min, Math.min(max, value));
@@ -47,6 +44,10 @@ function clamp(value, min, max) {
47
44
  function lerp(a, b, t) {
48
45
  return a + (b - a) * t;
49
46
  }
47
+ function smoothstep(x) {
48
+ const t = clamp(x, 0, 1);
49
+ return t * t * (3 - 2 * t);
50
+ }
50
51
 
51
52
  // ../engine/src/parameter-store.ts
52
53
  var ParameterStore = class {
@@ -452,17 +453,472 @@ function resolveDeformers(deformers, params) {
452
453
  var import_format = require("@ikijs/format");
453
454
 
454
455
  // ../engine/src/frame-clock.ts
456
+ var MAX_DT_MS = 100;
455
457
  var FIXED_DT_S = 1 / 60;
458
+ var MAX_SUBSTEPS = 6;
459
+ var FixedStepClock = class {
460
+ prevNowMs = void 0;
461
+ accumulatorS = 0;
462
+ /**
463
+ * True until the first {@link advance}. Drivers seed their rest pose on that
464
+ * frame and integrate nothing, so a model loaded mid-motion does not kick.
465
+ */
466
+ get isSeedFrame() {
467
+ return this.prevNowMs === void 0;
468
+ }
469
+ /**
470
+ * Fold `nowMs` into the accumulator and return how many {@link FIXED_DT_S}
471
+ * sub-steps to run this frame. On the seed frame it only records the
472
+ * timestamp and returns 0. A non-monotonic `nowMs` floors to 0 — no rewind.
473
+ */
474
+ advance(nowMs) {
475
+ if (!Number.isFinite(nowMs)) return 0;
476
+ if (this.prevNowMs === void 0) {
477
+ this.prevNowMs = nowMs;
478
+ return 0;
479
+ }
480
+ const dtMs = clamp(nowMs - this.prevNowMs, 0, MAX_DT_MS);
481
+ this.prevNowMs = nowMs;
482
+ this.accumulatorS += dtMs / 1e3;
483
+ let steps = 0;
484
+ while (this.accumulatorS >= FIXED_DT_S && steps < MAX_SUBSTEPS) {
485
+ this.accumulatorS -= FIXED_DT_S;
486
+ steps++;
487
+ }
488
+ return steps;
489
+ }
490
+ };
456
491
 
457
492
  // ../engine/src/idle-motion.ts
493
+ var BLINK_INTERVAL_MIN_MS = 1500;
494
+ var BLINK_INTERVAL_MAX_MS = 6e3;
458
495
  var BLINK_CLOSE_MS = 60;
459
496
  var BLINK_HOLD_MS = 20;
460
497
  var BLINK_OPEN_MS = 100;
461
498
  var BLINK_DURATION_MS = BLINK_CLOSE_MS + BLINK_HOLD_MS + BLINK_OPEN_MS;
499
+ var BREATH_PERIOD_MS = 3500;
500
+ var GAZE_RADIUS = 0.3;
501
+ var GAZE_RETARGET_MIN_MS = 1200;
502
+ var GAZE_RETARGET_MAX_MS = 3e3;
503
+ var GAZE_EASE_RATE = 1e-3;
504
+ var SWAY_X_AMP_A_DEG = 2.2;
505
+ var SWAY_X_PERIOD_A_MS = 6100;
506
+ var SWAY_X_AMP_B_DEG = 1.3;
507
+ var SWAY_X_PERIOD_B_MS = 9700;
508
+ var SWAY_Y_AMP_DEG = 1.6;
509
+ var SWAY_Y_PERIOD_MS = 7300;
510
+ var SWAY_Z_AMP_DEG = 1.1;
511
+ var SWAY_Z_PERIOD_MS = 11300;
512
+ function blinkEnvelope(phase) {
513
+ const ms = phase * BLINK_DURATION_MS;
514
+ if (ms <= 0) return 1;
515
+ if (ms < BLINK_CLOSE_MS) return 1 - smoothstep(ms / BLINK_CLOSE_MS);
516
+ if (ms <= BLINK_CLOSE_MS + BLINK_HOLD_MS) return 0;
517
+ if (ms < BLINK_DURATION_MS) {
518
+ const t = (ms - BLINK_CLOSE_MS - BLINK_HOLD_MS) / BLINK_OPEN_MS;
519
+ return 1 - (1 - t) * (1 - t);
520
+ }
521
+ return 1;
522
+ }
523
+ function randomInDisk(rng, radius) {
524
+ const r = Math.sqrt(rng()) * radius;
525
+ const theta = rng() * 2 * Math.PI;
526
+ return [r * Math.cos(theta), r * Math.sin(theta)];
527
+ }
528
+ var IdleMotion = class {
529
+ /**
530
+ * Every parameter id {@link update} and `emitRestingPose` write, in write
531
+ * order. Published so a host (or IkiMotion) can restore them after it
532
+ * stops driving — keep in step with those two methods; the test suite
533
+ * pins this list to the actual emissions.
534
+ */
535
+ drivenParameterIds = [
536
+ import_format.StandardParameter.EyeOpenLeft,
537
+ import_format.StandardParameter.EyeOpenRight,
538
+ import_format.StandardParameter.Breath,
539
+ import_format.StandardParameter.EyeballX,
540
+ import_format.StandardParameter.EyeballY,
541
+ import_format.StandardParameter.AngleX,
542
+ import_format.StandardParameter.AngleY,
543
+ import_format.StandardParameter.AngleZ
544
+ ];
545
+ sink;
546
+ rng;
547
+ // Internal clock: advances by clamped dt, NOT by raw wall-clock jumps.
548
+ // This is the only clock blink/breath/gaze scheduling reads.
549
+ clockMs = 0;
550
+ prevNowMs = void 0;
551
+ // Blink state
552
+ nextBlinkAtMs;
553
+ blinkStartMs = -1;
554
+ // -1 means not currently blinking
555
+ // Gaze state
556
+ gazeCurrentX = 0;
557
+ gazeCurrentY = 0;
558
+ gazeTargetX = 0;
559
+ gazeTargetY = 0;
560
+ nextGazeRetargetMs;
561
+ constructor(sink, options) {
562
+ this.sink = sink;
563
+ this.rng = options?.rng ?? Math.random;
564
+ this.nextBlinkAtMs = lerp(
565
+ BLINK_INTERVAL_MIN_MS,
566
+ BLINK_INTERVAL_MAX_MS,
567
+ this.rng()
568
+ );
569
+ this.nextGazeRetargetMs = lerp(
570
+ GAZE_RETARGET_MIN_MS,
571
+ GAZE_RETARGET_MAX_MS,
572
+ this.rng()
573
+ );
574
+ }
575
+ /**
576
+ * Advance the idle animation to the given wall-clock timestamp (milliseconds).
577
+ *
578
+ * On the first call: record prevNowMs, emit the resting pose, and return —
579
+ * no animation advance happens so there is no jump from time 0.
580
+ *
581
+ * On subsequent calls: compute dt = clamp(nowMs - prevNowMs, 0, MAX_DT_MS)
582
+ * and advance the internal clock by dt. A non-monotonic nowMs produces a
583
+ * negative raw delta that the clamp floors to 0 — no rewind.
584
+ */
585
+ update(nowMs) {
586
+ if (!Number.isFinite(nowMs)) return;
587
+ if (this.prevNowMs === void 0) {
588
+ this.prevNowMs = nowMs;
589
+ this.emitRestingPose();
590
+ return;
591
+ }
592
+ const rawDt = nowMs - this.prevNowMs;
593
+ const dt = clamp(rawDt, 0, MAX_DT_MS);
594
+ this.prevNowMs = nowMs;
595
+ this.clockMs += dt;
596
+ const eyeVal = this.advanceBlink();
597
+ this.sink(import_format.StandardParameter.EyeOpenLeft, eyeVal);
598
+ this.sink(import_format.StandardParameter.EyeOpenRight, eyeVal);
599
+ const breath = this.advanceBreath();
600
+ this.advanceGaze(dt);
601
+ this.sink(import_format.StandardParameter.Breath, breath);
602
+ this.sink(import_format.StandardParameter.EyeballX, this.gazeCurrentX);
603
+ this.sink(import_format.StandardParameter.EyeballY, this.gazeCurrentY);
604
+ this.sink(import_format.StandardParameter.AngleX, this.swayX());
605
+ this.sink(import_format.StandardParameter.AngleY, this.swayY());
606
+ this.sink(import_format.StandardParameter.AngleZ, this.swayZ());
607
+ }
608
+ // ---------------------------------------------------------------------------
609
+ // Private helpers
610
+ // ---------------------------------------------------------------------------
611
+ emitRestingPose() {
612
+ this.sink(import_format.StandardParameter.EyeOpenLeft, 1);
613
+ this.sink(import_format.StandardParameter.EyeOpenRight, 1);
614
+ this.sink(import_format.StandardParameter.Breath, 0.5);
615
+ this.sink(import_format.StandardParameter.EyeballX, 0);
616
+ this.sink(import_format.StandardParameter.EyeballY, 0);
617
+ this.sink(import_format.StandardParameter.AngleX, 0);
618
+ this.sink(import_format.StandardParameter.AngleY, 0);
619
+ this.sink(import_format.StandardParameter.AngleZ, 0);
620
+ }
621
+ /** Returns the current eye-open value (0..1) and advances blink state. */
622
+ advanceBlink() {
623
+ const { clockMs } = this;
624
+ if (this.blinkStartMs >= 0) {
625
+ const phase = (clockMs - this.blinkStartMs) / BLINK_DURATION_MS;
626
+ if (phase >= 1) {
627
+ this.blinkStartMs = -1;
628
+ this.nextBlinkAtMs = clockMs + lerp(BLINK_INTERVAL_MIN_MS, BLINK_INTERVAL_MAX_MS, this.rng());
629
+ return 1;
630
+ }
631
+ return blinkEnvelope(phase);
632
+ }
633
+ if (clockMs >= this.nextBlinkAtMs) {
634
+ this.blinkStartMs = clockMs;
635
+ return blinkEnvelope(0);
636
+ }
637
+ return 1;
638
+ }
639
+ advanceBreath() {
640
+ return 0.5 + 0.5 * Math.sin(2 * Math.PI * this.clockMs / BREATH_PERIOD_MS);
641
+ }
642
+ /** Horizontal head sway in degrees, pure function of the internal clock. */
643
+ swayX() {
644
+ const t = 2 * Math.PI * this.clockMs;
645
+ 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);
646
+ }
647
+ /** Vertical head sway in degrees, pure function of the internal clock. */
648
+ swayY() {
649
+ return SWAY_Y_AMP_DEG * Math.sin(2 * Math.PI * this.clockMs / SWAY_Y_PERIOD_MS);
650
+ }
651
+ /** Head roll sway in degrees, pure function of the internal clock. */
652
+ swayZ() {
653
+ return SWAY_Z_AMP_DEG * Math.sin(2 * Math.PI * this.clockMs / SWAY_Z_PERIOD_MS);
654
+ }
655
+ /** Ease gaze current toward target; pick a new target on the internal clock. */
656
+ advanceGaze(dt) {
657
+ if (this.clockMs >= this.nextGazeRetargetMs) {
658
+ const [tx, ty] = randomInDisk(this.rng, GAZE_RADIUS);
659
+ this.gazeTargetX = tx;
660
+ this.gazeTargetY = ty;
661
+ this.nextGazeRetargetMs = this.clockMs + lerp(GAZE_RETARGET_MIN_MS, GAZE_RETARGET_MAX_MS, this.rng());
662
+ }
663
+ const factor = 1 - Math.pow(1 - GAZE_EASE_RATE, dt);
664
+ this.gazeCurrentX = lerp(this.gazeCurrentX, this.gazeTargetX, factor);
665
+ this.gazeCurrentY = lerp(this.gazeCurrentY, this.gazeTargetY, factor);
666
+ }
667
+ };
668
+
669
+ // ../engine/src/physics-motion.ts
670
+ function signedNormalized(value, param) {
671
+ const rest = clamp(param.default, param.min, param.max);
672
+ const den = Math.max(Math.abs(param.max - rest), Math.abs(rest - param.min));
673
+ if (den === 0) return 0;
674
+ return clamp((value - rest) / den, -1, 1);
675
+ }
676
+ var PhysicsMotion = class {
677
+ /** The output parameter of every rig, in rig order — what `emit` writes. */
678
+ drivenParameterIds;
679
+ /**
680
+ * Per rig: how many times the finiteness guard reset its state or `emit`
681
+ * replaced its non-finite product. Up to two per frame, so guard activations,
682
+ * not repaired frames. A diagnostic; emitted values are unchanged.
683
+ */
684
+ resets;
685
+ resetCounts;
686
+ rigs;
687
+ read;
688
+ sink;
689
+ params;
690
+ // Integrator state, owned here — never stored in a ParameterStore.
691
+ state;
692
+ clock = new FixedStepClock();
693
+ constructor(rigs, params, read, sink) {
694
+ this.rigs = rigs;
695
+ this.read = read;
696
+ this.sink = sink;
697
+ this.params = new Map(params.map((p) => [p.id, p]));
698
+ this.state = rigs.map(() => ({ x: 0, v: 0 }));
699
+ this.drivenParameterIds = rigs.map((rig) => rig.output.parameter);
700
+ this.resetCounts = rigs.map(() => 0);
701
+ this.resets = this.resetCounts;
702
+ }
703
+ /**
704
+ * Advance every rig to the given wall-clock timestamp (milliseconds).
705
+ *
706
+ * First call: seed each spring to rest AT its current target (so a model
707
+ * loaded with a nonzero input does not kick), emit the resting output, and
708
+ * return without integrating — mirroring IdleMotion's first-frame behavior.
709
+ *
710
+ * Subsequent calls: {@link FixedStepClock} folds the clamped frame delta into
711
+ * its accumulator and returns how many {@link FIXED_DT_S} sub-steps are due;
712
+ * the spring advances that many semi-implicit Euler steps, then each rig emits
713
+ * its output once. The clock's dt clamp and sub-step cap plus the symplectic
714
+ * integrator are what keep it stable across hitches.
715
+ */
716
+ update(nowMs) {
717
+ if (this.clock.isSeedFrame) {
718
+ this.clock.advance(nowMs);
719
+ for (let i = 0; i < this.rigs.length; i++) {
720
+ const st = this.state[i];
721
+ st.x = this.targetFor(this.rigs[i]);
722
+ st.v = 0;
723
+ this.emit(i, st);
724
+ }
725
+ return;
726
+ }
727
+ const steps = this.clock.advance(nowMs);
728
+ const targets = this.rigs.map((rig) => this.targetFor(rig));
729
+ for (let s = 0; s < steps; s++) {
730
+ for (let i = 0; i < this.rigs.length; i++) {
731
+ this.step(this.rigs[i], this.state[i], targets[i]);
732
+ }
733
+ }
734
+ for (let i = 0; i < this.rigs.length; i++) {
735
+ const st = this.state[i];
736
+ if (!Number.isFinite(st.x) || !Number.isFinite(st.v)) {
737
+ st.x = Number.isFinite(targets[i]) ? targets[i] : 0;
738
+ st.v = 0;
739
+ this.resetCounts[i]++;
740
+ }
741
+ this.emit(i, st);
742
+ }
743
+ }
744
+ /** Spring target = signed-normalized input value × weight. */
745
+ targetFor(rig) {
746
+ const param = this.params.get(rig.input.parameter);
747
+ const value = this.read(rig.input.parameter);
748
+ const norm = param ? signedNormalized(value, param) : 0;
749
+ return norm * rig.input.weight;
750
+ }
751
+ /** One semi-implicit (symplectic) Euler sub-step of FIXED_DT_S seconds. */
752
+ step(rig, st, target2) {
753
+ const accel = (rig.stiffness * (target2 - st.x) - rig.damping * st.v) / rig.mass;
754
+ st.v += accel * FIXED_DT_S;
755
+ st.x += st.v * FIXED_DT_S;
756
+ }
757
+ /** Write outputDefault + x * scale onto the output param via the sink. */
758
+ emit(index, st) {
759
+ const rig = this.rigs[index];
760
+ const outParam = this.params.get(rig.output.parameter);
761
+ const outDefault = outParam ? clamp(outParam.default, outParam.min, outParam.max) : 0;
762
+ const value = outDefault + st.x * rig.output.scale;
763
+ const finite = Number.isFinite(value);
764
+ if (!finite) this.resetCounts[index]++;
765
+ this.sink(rig.output.parameter, finite ? value : outDefault);
766
+ }
767
+ };
462
768
 
463
769
  // ../engine/src/hair-chain-motion.ts
464
770
  var DEG2RAD = Math.PI / 180;
465
771
  var RAD2DEG = 180 / Math.PI;
772
+ var HairChainMotion = class {
773
+ /** Every segment's output, chain by chain — what `emitSegment` writes. */
774
+ drivenParameterIds;
775
+ /**
776
+ * Per segment, in `drivenParameterIds` order: how many times the finiteness
777
+ * guard reset its state or `emitSegment` replaced its non-finite product. Up
778
+ * to two per frame, so guard activations, not repaired frames. A diagnostic;
779
+ * emitted values are unchanged.
780
+ */
781
+ resets;
782
+ resetCounts;
783
+ chainData;
784
+ params;
785
+ deformers;
786
+ store;
787
+ read;
788
+ sink;
789
+ clock = new FixedStepClock();
790
+ constructor(chains, params, deformers, read, sink) {
791
+ this.params = new Map(params.map((p) => [p.id, p]));
792
+ this.deformers = deformers;
793
+ this.store = new ParameterStore(params);
794
+ this.read = read;
795
+ this.sink = sink;
796
+ this.chainData = chains.map((chain) => ({
797
+ chain,
798
+ restAnglesRad: chain.segments.map(
799
+ (seg) => seg.restAngle !== void 0 ? seg.restAngle * DEG2RAD : 0
800
+ ),
801
+ state: chain.segments.map(() => ({ angle: 0, angularVelocity: 0 }))
802
+ }));
803
+ this.drivenParameterIds = chains.flatMap(
804
+ (c) => c.segments.map((s) => s.output.parameter)
805
+ );
806
+ this.resetCounts = this.drivenParameterIds.map(() => 0);
807
+ this.resets = this.resetCounts;
808
+ }
809
+ /**
810
+ * Advance every chain to the given wall-clock timestamp (milliseconds).
811
+ *
812
+ * First call: seed every segment to θ=0/ω=0 (rest), emit the rest output
813
+ * (outDefault + 0), and return without integrating — mirrors PhysicsMotion's
814
+ * first-frame behavior so a model loaded in motion does not kick.
815
+ *
816
+ * Subsequent calls: dt = clamp(nowMs - prevNowMs, 0, MAX_DT_MS) → seconds into
817
+ * accumulator. The per-frame world snapshot (anchor world angles) is taken ONCE
818
+ * per update() — NOT per chain — so all chains share a consistent frame snapshot.
819
+ * Fixed FIXED_DT_S sub-steps are run root→tip, capped at MAX_SUBSTEPS; leftover
820
+ * time is carried to the next frame. Segments emit after substeps (even on zero
821
+ * substeps) with a non-finite guard.
822
+ */
823
+ update(nowMs) {
824
+ if (this.chainData.length === 0) return;
825
+ if (this.clock.isSeedFrame) {
826
+ this.clock.advance(nowMs);
827
+ let flat2 = 0;
828
+ for (const cd of this.chainData) {
829
+ for (let i = 0; i < cd.chain.segments.length; i++) {
830
+ cd.state[i].angle = 0;
831
+ cd.state[i].angularVelocity = 0;
832
+ this.emitSegment(flat2++, cd.chain.segments[i], cd.state[i]);
833
+ }
834
+ }
835
+ return;
836
+ }
837
+ const steps = this.clock.advance(nowMs);
838
+ for (const param of this.params.values()) {
839
+ this.store.set(param.id, this.read(param.id));
840
+ }
841
+ const worldMap = resolveDeformers(this.deformers, this.store).worlds;
842
+ const anchorAnglesRad = this.chainData.map(
843
+ (cd) => this.anchorWorldAngleRad(worldMap, cd.chain.anchorDeformer)
844
+ );
845
+ for (let s = 0; s < steps; s++) {
846
+ for (let c = 0; c < this.chainData.length; c++) {
847
+ this.stepChain(this.chainData[c], anchorAnglesRad[c]);
848
+ }
849
+ }
850
+ let flat = 0;
851
+ for (const cd of this.chainData) {
852
+ for (let i = 0; i < cd.chain.segments.length; i++) {
853
+ const st = cd.state[i];
854
+ if (!Number.isFinite(st.angle) || !Number.isFinite(st.angularVelocity)) {
855
+ st.angle = 0;
856
+ st.angularVelocity = 0;
857
+ this.resetCounts[flat]++;
858
+ }
859
+ this.emitSegment(flat++, cd.chain.segments[i], st);
860
+ }
861
+ }
862
+ }
863
+ /**
864
+ * Extract world rotation (radians) from the anchor's Affine tuple.
865
+ * Affine = [a,b,c,d,e,f]; rotation column = (a,b) → atan2(b,a).
866
+ *
867
+ * If the anchor id is absent from the map, THROWS an internal Error — the
868
+ * format validator guarantees the anchor exists, so absence is an invariant
869
+ * break (mirrors resolveDeformers' throw on an unresolved parent).
870
+ */
871
+ anchorWorldAngleRad(worldMap, anchorId) {
872
+ const world = worldMap.get(anchorId);
873
+ if (!world) {
874
+ throw new Error(
875
+ `HairChainMotion: anchor deformer "${anchorId}" not found in resolved world map \u2014 model not validated?`
876
+ );
877
+ }
878
+ return Math.atan2(world[1], world[0]);
879
+ }
880
+ /**
881
+ * One fixed sub-step of FIXED_DT_S seconds for all segments in a chain.
882
+ *
883
+ * Segments are integrated ROOT→TIP so each segment can read its upstream
884
+ * neighbor's current-substep state when computing the world angle Φ_i.
885
+ * (The chain is causal root-to-tip; reversing the order would use stale θ
886
+ * values from the previous substep for Φ_i computation.)
887
+ *
888
+ * Per-segment semi-implicit (symplectic) Euler:
889
+ * Φ_i = anchorWorldAngleRad + Σ_{j≤i}(restAngle_j + θ_j)
890
+ * α_i = (−stiffness_i·θ_i − strength·sin(Φ_i − gravityAngle_rad) − damping_i·ω_i) / mass_i
891
+ * ω_i += α_i · FIXED_DT_S (velocity updated FIRST = semi-implicit)
892
+ * θ_i += ω_i · FIXED_DT_S (position updated from NEW velocity)
893
+ *
894
+ * The spring term is −stiffness·θ (restoring θ→0); restAngle does NOT appear
895
+ * in the spring term, only in Φ_i for the gravity torque.
896
+ */
897
+ stepChain(cd, anchorAngleRad) {
898
+ const { chain, restAnglesRad, state } = cd;
899
+ const gravityAngleRad = chain.gravity.angle * DEG2RAD;
900
+ const strength = chain.gravity.strength;
901
+ let worldAngleAccumRad = anchorAngleRad;
902
+ for (let i = 0; i < chain.segments.length; i++) {
903
+ const seg = chain.segments[i];
904
+ const st = state[i];
905
+ worldAngleAccumRad += restAnglesRad[i] + st.angle;
906
+ const phi = worldAngleAccumRad;
907
+ const alpha = (-seg.stiffness * st.angle - strength * Math.sin(phi - gravityAngleRad) - seg.damping * st.angularVelocity) / seg.mass;
908
+ st.angularVelocity += alpha * FIXED_DT_S;
909
+ st.angle += st.angularVelocity * FIXED_DT_S;
910
+ }
911
+ }
912
+ /** Emit outDefault + (θ_i · RAD2DEG) · scale for one segment. */
913
+ emitSegment(flat, seg, st) {
914
+ const outParam = this.params.get(seg.output.parameter);
915
+ const outDefault = outParam ? clamp(outParam.default, outParam.min, outParam.max) : 0;
916
+ const value = outDefault + st.angle * RAD2DEG * seg.output.scale;
917
+ const finite = Number.isFinite(value);
918
+ if (!finite) this.resetCounts[flat]++;
919
+ this.sink(seg.output.parameter, finite ? value : outDefault);
920
+ }
921
+ };
466
922
 
467
923
  // ../engine/src/iki-motion.ts
468
924
  var import_format4 = require("@ikijs/format");
@@ -484,6 +940,62 @@ var HEAD_AND_GAZE = /* @__PURE__ */ new Set([
484
940
 
485
941
  // ../engine/src/folds.ts
486
942
  var import_format5 = require("@ikijs/format");
943
+
944
+ // ../engine/src/land.ts
945
+ function staticDeformers(model) {
946
+ return (model.deformers ?? []).map(
947
+ (d) => d.kind === "warp" ? { ...d, warps: void 0, warp2d: void 0 } : { ...d, bindings: void 0 }
948
+ );
949
+ }
950
+ function placement(part, t) {
951
+ return multiply(
952
+ multiply(translate(t.x, t.y), rotate(t.rotation)),
953
+ scale(part.width * t.scaleX, part.height * t.scaleY)
954
+ );
955
+ }
956
+ function landedPart(part, vertices, deformers, worlds, store) {
957
+ const warpDeformer = deformers.find(
958
+ (d) => d.kind === "warp" && d.id === part.deformer
959
+ );
960
+ const frame = warpDeformer ? warpDeformer.parent : part.deformer;
961
+ const placed = placement(
962
+ part,
963
+ evaluateTransform(part.transform, void 0, store)
964
+ );
965
+ const restPoints = transformGridPoints(
966
+ vertices,
967
+ frame === void 0 ? placed : multiply(worlds.get(frame), placed),
968
+ new Float64Array(vertices.length)
969
+ );
970
+ return {
971
+ part,
972
+ warpDeformer,
973
+ vertices: Float32Array.from(vertices),
974
+ local: new Float32Array(vertices.length),
975
+ landed: new Float32Array(vertices.length),
976
+ restPoints
977
+ };
978
+ }
979
+ function landPart(landing, store, { worlds, grids }) {
980
+ const { part, warpDeformer, local, landed } = landing;
981
+ applyWarps(landing.vertices, part.warps, store, local);
982
+ const placed = placement(
983
+ part,
984
+ evaluateTransform(part.transform, part.bindings, store)
985
+ );
986
+ if (warpDeformer) {
987
+ const grid = grids.get(warpDeformer.id);
988
+ applyWarpToChild(local, placed, warpDeformer.grid, grid, landed);
989
+ } else if (part.deformer !== void 0) {
990
+ const world = worlds.get(part.deformer);
991
+ transformGridPoints(local, multiply(world, placed), landed);
992
+ } else {
993
+ transformGridPoints(local, placed, landed);
994
+ }
995
+ return landed;
996
+ }
997
+
998
+ // ../engine/src/folds.ts
487
999
  var FLIP = 0;
488
1000
  var COLLAPSE = 0.1;
489
1001
  var ANGLES = [
@@ -547,11 +1059,6 @@ function poseName(values) {
547
1059
  if (ids.length === 0) return "rest";
548
1060
  return ids.map((id) => `${id}=${values[id]}`).join(" ");
549
1061
  }
550
- function staticDeformers(model) {
551
- return (model.deformers ?? []).map(
552
- (d) => d.kind === "warp" ? { ...d, warps: void 0, warp2d: void 0 } : { ...d, bindings: void 0 }
553
- );
554
- }
555
1062
  function cornerAreas(points, cols, rows) {
556
1063
  const stride = cols + 1;
557
1064
  const out = new Float64Array(cols * rows * 4);
@@ -583,12 +1090,6 @@ function triangleAreas(points, indices) {
583
1090
  }
584
1091
  return out;
585
1092
  }
586
- function placement(part, t) {
587
- return multiply(
588
- multiply(translate(t.x, t.y), rotate(t.rotation)),
589
- scale(part.width * t.scaleX, part.height * t.scaleY)
590
- );
591
- }
592
1093
  function keepLeast(sweep, areas, pose, expected) {
593
1094
  const slot = expected(sweep.target) ? "expected" : "worst";
594
1095
  for (let i = 0; i < areas.length; i++) {
@@ -601,50 +1102,15 @@ function keepLeast(sweep, areas, pose, expected) {
601
1102
  }
602
1103
  }
603
1104
  function partSweep(part, mesh, deformers, worlds, store) {
604
- const warpDeformer = deformers.find(
605
- (d) => d.kind === "warp" && d.id === part.deformer
606
- );
607
- const frame = warpDeformer ? warpDeformer.parent : part.deformer;
608
- const placed = placement(
609
- part,
610
- evaluateTransform(part.transform, void 0, store)
611
- );
612
- const restPoints = transformGridPoints(
613
- mesh.vertices,
614
- frame === void 0 ? placed : multiply(worlds.get(frame), placed),
615
- new Float64Array(mesh.vertices.length)
616
- );
1105
+ const landing = landedPart(part, mesh.vertices, deformers, worlds, store);
617
1106
  return {
1107
+ ...landing,
618
1108
  target: { kind: "part", id: part.id },
619
- restAreas: triangleAreas(restPoints, mesh.indices),
1109
+ restAreas: triangleAreas(landing.restPoints, mesh.indices),
620
1110
  tiny: 1e-9 * part.width * part.height,
621
- part,
622
- indices: mesh.indices,
623
- warpDeformer,
624
- vertices: Float32Array.from(mesh.vertices),
625
- local: new Float32Array(mesh.vertices.length),
626
- landed: new Float32Array(mesh.vertices.length),
627
- restPoints
1111
+ indices: mesh.indices
628
1112
  };
629
1113
  }
630
- function landPart(sweep, store, { worlds, grids }) {
631
- const { part, warpDeformer, local, landed } = sweep;
632
- applyWarps(sweep.vertices, part.warps, store, local);
633
- const placed = placement(
634
- part,
635
- evaluateTransform(part.transform, part.bindings, store)
636
- );
637
- if (warpDeformer) {
638
- const grid = grids.get(warpDeformer.id);
639
- applyWarpToChild(local, placed, warpDeformer.grid, grid, landed);
640
- } else if (part.deformer !== void 0) {
641
- const world = worlds.get(part.deformer);
642
- transformGridPoints(local, multiply(world, placed), landed);
643
- } else {
644
- transformGridPoints(local, placed, landed);
645
- }
646
- return landed;
647
- }
648
1114
  function checkFolds(model, options = {}) {
649
1115
  const poses = options.poses ?? foldPoses(model);
650
1116
  const deformers = model.deformers ?? [];
@@ -671,7 +1137,7 @@ function checkFolds(model, options = {}) {
671
1137
  const store = new ParameterStore(model.parameters);
672
1138
  for (const [id, v] of Object.entries(pose.values)) store.set(id, v);
673
1139
  const value = (id) => store.get(id);
674
- const expected = (target) => options.expected?.(target, pose, value) === true;
1140
+ const expected = (target2) => options.expected?.(target2, pose, value) === true;
675
1141
  for (const sweep of gridSweeps) {
676
1142
  const { cols, rows } = sweep.deformer.grid;
677
1143
  const areas = cornerAreas(
@@ -762,7 +1228,403 @@ function classify(worst) {
762
1228
  return "ok";
763
1229
  }
764
1230
 
1231
+ // ../engine/src/physics-runs.ts
1232
+ var FRAME_MS = FIXED_DT_S * 1e3 * (1 + 1e-9);
1233
+ var STEP_FRAMES = 300;
1234
+ var IDLE_FRAMES = 1800;
1235
+ var IDLE_SEED = 1;
1236
+ var MIN_TURN = 1e-9;
1237
+ function run(model, store, rigs, chains, frames, excite) {
1238
+ const raw = /* @__PURE__ */ new Map();
1239
+ const read = (id) => store.get(id);
1240
+ const sink = (id, value) => {
1241
+ let trace = raw.get(id);
1242
+ if (trace === void 0) raw.set(id, trace = []);
1243
+ trace.push(value);
1244
+ store.set(id, value);
1245
+ };
1246
+ const { parameters } = model;
1247
+ const drivers = [
1248
+ new PhysicsMotion(rigs, parameters, read, sink),
1249
+ new HairChainMotion(chains, parameters, model.deformers ?? [], read, sink)
1250
+ ];
1251
+ for (let frame = 0; frame <= frames; frame++) {
1252
+ const nowMs = frame * FRAME_MS;
1253
+ excite(frame, nowMs);
1254
+ for (const driver of drivers) driver.update(nowMs);
1255
+ }
1256
+ const readings = /* @__PURE__ */ new Map();
1257
+ for (const driver of drivers) {
1258
+ driver.drivenParameterIds.forEach((id, i) => {
1259
+ const param = parameters.find((p) => p.id === id);
1260
+ readings.set(id, readTrace(raw.get(id), param, driver.resets[i]));
1261
+ });
1262
+ }
1263
+ return readings;
1264
+ }
1265
+ function readTrace(raw, param, resets) {
1266
+ const rest = clamp(param.default, param.min, param.max);
1267
+ const reading = {
1268
+ peak: 0,
1269
+ at: 0,
1270
+ final: rest,
1271
+ values: [],
1272
+ lo: rest,
1273
+ hi: rest,
1274
+ pinned: { frames: 0, end: "max" },
1275
+ resets
1276
+ };
1277
+ const seen = /* @__PURE__ */ new Set([rest]);
1278
+ let outside = 0;
1279
+ let end = "max";
1280
+ raw.forEach((value, frame) => {
1281
+ const held = clamp(value, param.min, param.max);
1282
+ if (Math.abs(held - rest) > Math.abs(reading.peak)) {
1283
+ reading.peak = held - rest;
1284
+ reading.at = frame * FIXED_DT_S;
1285
+ }
1286
+ if (!seen.has(held)) {
1287
+ seen.add(held);
1288
+ reading.values.push(held);
1289
+ }
1290
+ reading.lo = Math.min(reading.lo, held);
1291
+ reading.hi = Math.max(reading.hi, held);
1292
+ reading.final = held;
1293
+ if (value >= param.min && value <= param.max) {
1294
+ outside = 0;
1295
+ return;
1296
+ }
1297
+ const side = value < param.min ? "min" : "max";
1298
+ if (outside === 0 || side !== end) {
1299
+ outside = 0;
1300
+ end = side;
1301
+ }
1302
+ outside++;
1303
+ if (outside > reading.pinned.frames) {
1304
+ reading.pinned = { frames: outside, end };
1305
+ }
1306
+ });
1307
+ return reading;
1308
+ }
1309
+ function farEnd(param) {
1310
+ if (param.min === param.max) return void 0;
1311
+ const rest = clamp(param.default, param.min, param.max);
1312
+ return param.max - rest >= rest - param.min ? param.max : param.min;
1313
+ }
1314
+ function stepRun(model, rigs, chains, values) {
1315
+ const store = new ParameterStore(model.parameters);
1316
+ return run(model, store, rigs, chains, STEP_FRAMES, (frame) => {
1317
+ if (frame !== 1) return;
1318
+ for (const [id, v] of Object.entries(values)) store.set(id, v);
1319
+ });
1320
+ }
1321
+ function idleRun(model) {
1322
+ const store = new ParameterStore(model.parameters);
1323
+ const idle = new IdleMotion((id, v) => store.set(id, v), {
1324
+ rng: lcg(IDLE_SEED)
1325
+ });
1326
+ return run(
1327
+ model,
1328
+ store,
1329
+ model.physics ?? [],
1330
+ model.physicsChains ?? [],
1331
+ IDLE_FRAMES,
1332
+ (_, nowMs) => idle.update(nowMs)
1333
+ );
1334
+ }
1335
+ function lcg(seed) {
1336
+ let state = seed >>> 0;
1337
+ return () => {
1338
+ state = Math.imul(state, 1664525) + 1013904223 >>> 0;
1339
+ return state / 2 ** 32;
1340
+ };
1341
+ }
1342
+ function anchorInputs(model, chain) {
1343
+ const store = new ParameterStore(model.parameters);
1344
+ const angle = () => {
1345
+ const { worlds } = resolveDeformers(model.deformers ?? [], store);
1346
+ const world = worlds.get(chain.anchorDeformer);
1347
+ return Math.atan2(world[1], world[0]);
1348
+ };
1349
+ const rest = angle();
1350
+ const found = [];
1351
+ for (const p of model.parameters) {
1352
+ const probes = new Set(
1353
+ [p.max, p.min, ...stopsOf(model, p.id)].map(
1354
+ (v) => clamp(v, p.min, p.max)
1355
+ )
1356
+ );
1357
+ probes.delete(store.get(p.id));
1358
+ let most = 0;
1359
+ let best;
1360
+ for (const value of probes) {
1361
+ store.set(p.id, value);
1362
+ const d = angle() - rest;
1363
+ const turn = Math.abs(Math.atan2(Math.sin(d), Math.cos(d)));
1364
+ if (turn <= most + MIN_TURN) continue;
1365
+ [most, best] = [turn, { parameter: p.id, value }];
1366
+ }
1367
+ store.reset();
1368
+ if (best) found.push(best);
1369
+ }
1370
+ return found;
1371
+ }
1372
+ function stopsOf(model, parameter) {
1373
+ const stops = /* @__PURE__ */ new Set();
1374
+ for (const d of model.deformers ?? []) {
1375
+ if (d.kind !== "warp") continue;
1376
+ for (const w of d.warps ?? []) {
1377
+ if (w.parameter !== parameter) continue;
1378
+ for (const k of w.keyforms) stops.add(k.value);
1379
+ }
1380
+ const { warp2d } = d;
1381
+ if (warp2d?.parameter === parameter) {
1382
+ for (const v of warp2d.valuesX) stops.add(v);
1383
+ }
1384
+ if (warp2d?.parameterY === parameter) {
1385
+ for (const v of warp2d.valuesY) stops.add(v);
1386
+ }
1387
+ }
1388
+ return [...stops].sort((a, b) => a - b);
1389
+ }
1390
+
1391
+ // ../engine/src/physics-check.ts
1392
+ var DISPLACEMENT_PX = 1;
1393
+ var PINNED_FRAMES = 60;
1394
+ var TOLERANCE = 1e-9;
1395
+ var UNIT_QUAD = [-0.5, -0.5, 0.5, -0.5, -0.5, 0.5, 0.5, 0.5];
1396
+ function checkPhysics(model) {
1397
+ const idle = idleRun(model);
1398
+ const displace = displacer(model);
1399
+ const idleExcitation = (output) => {
1400
+ const reading = idle.get(output.id);
1401
+ return {
1402
+ name: "the idle",
1403
+ reading,
1404
+ displacementPx: displace(output, reading.values)
1405
+ };
1406
+ };
1407
+ const param = (id) => model.parameters.find((p) => p.id === id);
1408
+ const springs = (model.physics ?? []).map((rig) => {
1409
+ const input = param(rig.input.parameter);
1410
+ const output = param(rig.output.parameter);
1411
+ const far = farEnd(input);
1412
+ const values = far === void 0 ? {} : { [input.id]: far };
1413
+ const reading = stepRun(model, [rig], [], values).get(output.id);
1414
+ const step = {
1415
+ name: "the step",
1416
+ reading,
1417
+ displacementPx: displace(output, reading.values),
1418
+ values
1419
+ };
1420
+ const atIdle = idleExcitation(output);
1421
+ return target(model, {
1422
+ rig: { kind: "spring", id: rig.id },
1423
+ input: [input.id],
1424
+ output,
1425
+ step,
1426
+ idle: atIdle,
1427
+ unstable: springWhy(rig) ?? unstableWhy(output, [step, atIdle]),
1428
+ inert: far === void 0 ? `${input.id} has no range` : void 0
1429
+ });
1430
+ });
1431
+ const chains = (model.physicsChains ?? []).flatMap((chain) => {
1432
+ const candidates = anchorInputs(model, chain);
1433
+ const settings = candidates.length === 0 ? [{}] : candidates.map((c) => ({ [c.parameter]: c.value }));
1434
+ const runs = settings.map((values) => ({
1435
+ values,
1436
+ readings: stepRun(model, [], [chain], values)
1437
+ }));
1438
+ return chain.segments.map((segment, i) => {
1439
+ const output = param(segment.output.parameter);
1440
+ const steps = runs.map(({ values, readings }) => {
1441
+ const reading = readings.get(output.id);
1442
+ const setting = Object.entries(values).map(([id, v]) => `${id}=${v}`);
1443
+ return {
1444
+ name: ["the step", ...setting].join(" "),
1445
+ reading,
1446
+ displacementPx: displace(output, reading.values),
1447
+ values
1448
+ };
1449
+ });
1450
+ const atIdle = idleExcitation(output);
1451
+ const clean = steps.filter((s) => !unstableWhy(output, [s]));
1452
+ return target(model, {
1453
+ rig: { kind: "chain", id: chain.id, segment: i },
1454
+ input: candidates.map((c) => c.parameter),
1455
+ output,
1456
+ step: mostMoving(clean.length > 0 ? clean : steps),
1457
+ idle: atIdle,
1458
+ unstable: unstableWhy(output, [...steps, atIdle]),
1459
+ inert: candidates.length === 0 ? `nothing turns anchor ${chain.anchorDeformer}` : void 0
1460
+ });
1461
+ });
1462
+ });
1463
+ const targets = [...springs, ...chains];
1464
+ return {
1465
+ thresholds: {
1466
+ displacementPx: DISPLACEMENT_PX,
1467
+ pinnedFrames: PINNED_FRAMES
1468
+ },
1469
+ targets,
1470
+ offenders: [
1471
+ ...targets.filter((t) => t.kind === "unstable"),
1472
+ ...targets.filter((t) => t.kind === "frozen")
1473
+ ]
1474
+ };
1475
+ }
1476
+ function target(model, t) {
1477
+ const { step, idle, output } = t;
1478
+ const drives = drivesOf(model, output.id);
1479
+ const px2 = Math.floor(step.displacementPx * 10) / 10;
1480
+ const still = step.displacementPx < DISPLACEMENT_PX ? `moves ${px2.toFixed(1)} model px over ${step.name}` : void 0;
1481
+ const frozen = drives.length === 0 ? "drives nothing" : t.inert ?? still;
1482
+ const { peak, at, final } = step.reading;
1483
+ return {
1484
+ rig: t.rig,
1485
+ input: t.input,
1486
+ output: output.id,
1487
+ drives,
1488
+ kind: t.unstable ? "unstable" : frozen ? "frozen" : "ok",
1489
+ why: t.unstable ?? frozen,
1490
+ step: {
1491
+ values: step.values,
1492
+ peak,
1493
+ at,
1494
+ final,
1495
+ displacementPx: step.displacementPx
1496
+ },
1497
+ idle: {
1498
+ peak: Math.abs(idle.reading.peak),
1499
+ at: idle.reading.at,
1500
+ displacementPx: idle.displacementPx
1501
+ }
1502
+ };
1503
+ }
1504
+ function mostMoving(steps) {
1505
+ return steps.reduce((best, s) => {
1506
+ if (s.displacementPx !== best.displacementPx) {
1507
+ return s.displacementPx > best.displacementPx ? s : best;
1508
+ }
1509
+ return Math.abs(s.reading.peak) > Math.abs(best.reading.peak) ? s : best;
1510
+ });
1511
+ }
1512
+ function drivesOf(model, output) {
1513
+ const parts = model.parts.filter(
1514
+ (p) => [
1515
+ ...(p.bindings ?? []).map((b) => b.parameter),
1516
+ ...(p.warps ?? []).map((w) => w.parameter)
1517
+ ].includes(output)
1518
+ );
1519
+ const deformers = (model.deformers ?? []).filter(
1520
+ (d) => (d.kind === "warp" ? [
1521
+ ...(d.warps ?? []).map((w) => w.parameter),
1522
+ d.warp2d?.parameter,
1523
+ d.warp2d?.parameterY
1524
+ ] : (d.bindings ?? []).map((b) => b.parameter)).includes(output)
1525
+ );
1526
+ return [
1527
+ ...parts.map((p) => ({ kind: "part", id: p.id })),
1528
+ ...deformers.map((d) => ({ kind: "deformer", id: d.id }))
1529
+ ];
1530
+ }
1531
+ function springStepRadius({ mass, stiffness, damping }) {
1532
+ const k = FIXED_DT_S * FIXED_DT_S * stiffness / mass;
1533
+ const c = FIXED_DT_S * damping / mass;
1534
+ const trace = 2 - k - c;
1535
+ const det = 1 - c;
1536
+ const disc = trace * trace - 4 * det;
1537
+ const radius = disc >= 0 ? (Math.abs(trace) + Math.sqrt(disc)) / 2 : Math.sqrt(det);
1538
+ return { radius, k };
1539
+ }
1540
+ function springWhy(rig) {
1541
+ const { radius, k } = springStepRadius(rig);
1542
+ if (radius > 1 + TOLERANCE) {
1543
+ let digits = 2;
1544
+ while (Number(radius.toFixed(digits)) <= 1) digits++;
1545
+ return `spring step map radius ${radius.toFixed(digits)} over 1 at 1/60 s`;
1546
+ }
1547
+ if (rig.damping === 0 && k >= 4 - TOLERANCE) {
1548
+ return `spring on its undamped boundary, dt\xB2k/m ${k.toFixed(2)}`;
1549
+ }
1550
+ return void 0;
1551
+ }
1552
+ function unstableWhy(output, excitations) {
1553
+ for (const { name, reading } of excitations) {
1554
+ const n = reading.resets;
1555
+ if (n === 0) continue;
1556
+ return `finiteness guard reset it ${n} time${n === 1 ? "" : "s"} in ${name}`;
1557
+ }
1558
+ for (const { name, reading } of excitations) {
1559
+ const { frames, end } = reading.pinned;
1560
+ if (frames < PINNED_FRAMES) continue;
1561
+ return `pinned at ${output.id} ${end} ${output[end]} for ${frames} frames of ${name}`;
1562
+ }
1563
+ return void 0;
1564
+ }
1565
+ function displacer(model) {
1566
+ const deformers = model.deformers ?? [];
1567
+ const store = new ParameterStore(model.parameters);
1568
+ const { worlds } = resolveDeformers(staticDeformers(model), store);
1569
+ const landings = model.parts.map(
1570
+ (part) => landedPart(
1571
+ part,
1572
+ part.mesh?.vertices ?? UNIT_QUAD,
1573
+ deformers,
1574
+ worlds,
1575
+ store
1576
+ )
1577
+ );
1578
+ const atRest = resolveDeformers(deformers, store);
1579
+ const baselines = landings.map(
1580
+ (l) => Float32Array.from(landPart(l, store, atRest))
1581
+ );
1582
+ return (output, values) => {
1583
+ let most = 0;
1584
+ const affected = affectedParts(model, output.id);
1585
+ for (const value of values) {
1586
+ store.set(output.id, value);
1587
+ const resolved = resolveDeformers(deformers, store);
1588
+ landings.forEach((landing, i) => {
1589
+ if (!affected.has(landing.part)) return;
1590
+ const landed = landPart(landing, store, resolved);
1591
+ const base = baselines[i];
1592
+ for (let j = 0; j < landed.length; j += 2) {
1593
+ const dx = landed[j] - base[j];
1594
+ const dy = landed[j + 1] - base[j + 1];
1595
+ most = Math.max(most, dx * dx + dy * dy);
1596
+ }
1597
+ });
1598
+ }
1599
+ store.reset();
1600
+ return Math.sqrt(most);
1601
+ };
1602
+ }
1603
+ function affectedParts(model, output) {
1604
+ const deformers = new Map((model.deformers ?? []).map((d) => [d.id, d]));
1605
+ const reads = (d) => (d.kind === "warp" ? [
1606
+ ...(d.warps ?? []).map((w) => w.parameter),
1607
+ d.warp2d?.parameter,
1608
+ d.warp2d?.parameterY
1609
+ ] : (d.bindings ?? []).map((b) => b.parameter)).includes(output);
1610
+ const hung = (id) => {
1611
+ for (let d = id && deformers.get(id); d; d = d.parent && deformers.get(d.parent)) {
1612
+ if (reads(d)) return true;
1613
+ }
1614
+ return false;
1615
+ };
1616
+ return new Set(
1617
+ model.parts.filter(
1618
+ (p) => [
1619
+ ...(p.bindings ?? []).map((b) => b.parameter),
1620
+ ...(p.warps ?? []).map((w) => w.parameter)
1621
+ ].includes(output) || hung(p.deformer)
1622
+ )
1623
+ );
1624
+ }
1625
+
765
1626
  // src/fold-report.ts
1627
+ var import_editor = require("@ikijs/editor");
766
1628
  function checkModelFolds(model, extraValues = []) {
767
1629
  const declared = new Set(model.parameters.map((p) => p.id));
768
1630
  return checkFolds(model, {
@@ -770,9 +1632,9 @@ function checkModelFolds(model, extraValues = []) {
770
1632
  // The effective value, not the pose's overrides: the auto-rig's mouth
771
1633
  // rests shut at its default, so `rest` and the other parameters' singles
772
1634
  // are shut-mouth poses too.
773
- expected: (target, _pose, value) => {
774
- if (target.kind !== "part") return false;
775
- const shutBy = import_editor.SHUT_BY.get(target.id);
1635
+ expected: (target2, _pose, value) => {
1636
+ if (target2.kind !== "part") return false;
1637
+ const shutBy = import_editor.SHUT_BY.get(target2.id);
776
1638
  return shutBy !== void 0 && declared.has(shutBy) && value(shutBy) === 0;
777
1639
  }
778
1640
  });
@@ -1474,6 +2336,7 @@ async function renderPoses(input) {
1474
2336
  model,
1475
2337
  input.poses?.map((p) => p.values)
1476
2338
  );
2339
+ const physics = checkPhysics(model);
1477
2340
  const { failedTextures, poses } = await withBrowser(
1478
2341
  browser,
1479
2342
  async (evaluate) => {
@@ -1510,7 +2373,8 @@ async function renderPoses(input) {
1510
2373
  failedTextures,
1511
2374
  poses,
1512
2375
  modelCanvas: model.canvas,
1513
- folds
2376
+ folds,
2377
+ physics
1514
2378
  };
1515
2379
  } catch (error) {
1516
2380
  if (error instanceof AutoRigInputError || error instanceof import_format6.IkiFormatError) {
@@ -2021,6 +2885,7 @@ async function autoRigFromLayers(input) {
2021
2885
  const finalModel = (0, import_format7.parseIkiModel)(patched);
2022
2886
  writeFileAtomic(outPath, JSON.stringify(finalModel));
2023
2887
  const folds = checkModelFolds(finalModel);
2888
+ const physics = checkPhysics(finalModel);
2024
2889
  return {
2025
2890
  ok: true,
2026
2891
  path: outPath,
@@ -2034,6 +2899,7 @@ async function autoRigFromLayers(input) {
2034
2899
  ...noseCore === void 0 ? {} : { noseCore },
2035
2900
  ...turn === void 0 ? {} : { turn },
2036
2901
  folds,
2902
+ physics,
2037
2903
  ...patches === void 0 ? {} : { patches }
2038
2904
  };
2039
2905
  } catch (err) {
@@ -3453,16 +4319,16 @@ async function layerStats(filePath) {
3453
4319
  let flatCutRun = 0;
3454
4320
  let flatCutY = -1;
3455
4321
  for (let y = minY + 1; y <= maxY; y++) {
3456
- let run = 0;
4322
+ let run2 = 0;
3457
4323
  for (let x = minX; x <= maxX; x++) {
3458
4324
  if (alpha(x, y - 1) < FLAT_CUT_ALPHA_ABOVE && alpha(x, y) > FLAT_CUT_ALPHA_BELOW) {
3459
- run++;
3460
- if (run > flatCutRun) {
3461
- flatCutRun = run;
4325
+ run2++;
4326
+ if (run2 > flatCutRun) {
4327
+ flatCutRun = run2;
3462
4328
  flatCutY = y;
3463
4329
  }
3464
4330
  } else {
3465
- run = 0;
4331
+ run2 = 0;
3466
4332
  }
3467
4333
  }
3468
4334
  }
@@ -3793,6 +4659,7 @@ var IRIS_W = 50;
3793
4659
  var EYEWHITE_SRC = "eyewhite.png";
3794
4660
  var EYE_LASH_LUMA = 120;
3795
4661
  var LASH_KEEP_FRACTION = 0.5;
4662
+ var EYE_LID_WARMTH = 30;
3796
4663
  var NOSE_TIP_AT = 0.66;
3797
4664
  var DEFAULT_LAYOUT = {
3798
4665
  // Back hair and body sit behind the face. Both are OPTIONAL: a parts dir
@@ -4276,6 +5143,36 @@ async function prepEyeSplit(partsDir) {
4276
5143
  }
4277
5144
  const lashCutoffY = minY + LASH_KEEP_FRACTION * (maxY - minY + 1);
4278
5145
  const detached = detachedAboveWhite(data, W, H);
5146
+ const isDark = (i) => data[i + 3] > 0 && luma(data, i) < EYE_LASH_LUMA;
5147
+ const isLight = (i) => data[i + 3] >= import_editor12.ALPHA_OPAQUE && luma(data, i) >= EYE_LASH_LUMA;
5148
+ const isWarm = (i) => data[i] - data[i + 2] >= EYE_LID_WARMTH;
5149
+ const whiteTop = new Int32Array(W).fill(-1);
5150
+ for (let x = 0; x < W; x++) {
5151
+ for (let y = 0; y < H; y++) {
5152
+ const i = (y * W + x) * 4;
5153
+ if (!detached[y * W + x] && isLight(i) && !isWarm(i)) {
5154
+ whiteTop[x] = y;
5155
+ break;
5156
+ }
5157
+ }
5158
+ }
5159
+ let first = 0;
5160
+ while (first < W && whiteTop[first] === -1) first++;
5161
+ if (first < W) {
5162
+ let last = W - 1;
5163
+ while (whiteTop[last] === -1) last--;
5164
+ whiteTop.fill(whiteTop[first], 0, first);
5165
+ whiteTop.fill(whiteTop[last], last + 1);
5166
+ }
5167
+ const lidStop = new Int32Array(W).fill(-1);
5168
+ for (let x = 0; x < W; x++) {
5169
+ for (let y = whiteTop[x] - 1; y >= 0; y--) {
5170
+ if (isDark((y * W + x) * 4)) {
5171
+ lidStop[x] = y;
5172
+ break;
5173
+ }
5174
+ }
5175
+ }
4279
5176
  const sclera = Buffer.from(data);
4280
5177
  const lash = Buffer.from(data);
4281
5178
  const lashLower = Buffer.from(data);
@@ -4283,12 +5180,13 @@ async function prepEyeSplit(partsDir) {
4283
5180
  for (let y = 0; y < H; y++) {
4284
5181
  for (let x = 0; x < W; x++) {
4285
5182
  const i = (y * W + x) * 4;
4286
- const isDark = data[i + 3] > 0 && luma(data, i) < EYE_LASH_LUMA;
5183
+ const dark = isDark(i);
4287
5184
  const upper = y <= lashCutoffY;
4288
- if (isDark && upper) sclera[i] = sclera[i + 1] = sclera[i + 2] = 255;
5185
+ if (dark && upper) sclera[i] = sclera[i + 1] = sclera[i + 2] = 255;
4289
5186
  if (detached[y * W + x]) sclera[i + 3] = 0;
4290
- if (!(isDark && upper)) lash[i + 3] = 0;
4291
- if (isDark && !upper) lowerInk = true;
5187
+ if (y < lidStop[x] && isLight(i) && isWarm(i)) sclera[i + 3] = 0;
5188
+ if (!(dark && upper)) lash[i + 3] = 0;
5189
+ if (dark && !upper) lowerInk = true;
4292
5190
  else lashLower[i + 3] = 0;
4293
5191
  }
4294
5192
  }
@@ -4678,6 +5576,22 @@ async function composeLayersFromParts(input) {
4678
5576
  }
4679
5577
  }
4680
5578
 
5579
+ // src/physics-report.ts
5580
+ function formatPhysicsReport(report) {
5581
+ if (report.targets.length === 0) return ["PHYSICS: no rigs"];
5582
+ return report.targets.map(targetLine);
5583
+ }
5584
+ function targetLine(t) {
5585
+ const inputs = t.input.join(", ");
5586
+ const rig = t.rig.kind === "chain" ? `${t.rig.id}/${t.rig.segment} [${inputs}]` : `${t.rig.id} ${inputs}`;
5587
+ const drives = t.drives.length === 0 ? "" : ` (${t.drives.map((d) => d.id).join(", ")})`;
5588
+ const { step, idle } = t;
5589
+ 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}`);
5590
+ }
5591
+ function pxText(px2) {
5592
+ return (Math.floor(px2 * 10) / 10).toFixed(1);
5593
+ }
5594
+
4681
5595
  // src/server.ts
4682
5596
  function formatPatchReports(reports) {
4683
5597
  return reports.map((r) => {
@@ -4687,7 +5601,7 @@ function formatPatchReports(reports) {
4687
5601
  });
4688
5602
  }
4689
5603
  function createIkiMcpServer() {
4690
- const server = new import_mcp.McpServer({ name: "iki", version: "0.26.0" });
5604
+ const server = new import_mcp.McpServer({ name: "iki", version: "0.27.0" });
4691
5605
  server.registerTool(
4692
5606
  "validate_iki",
4693
5607
  {
@@ -4762,7 +5676,7 @@ function createIkiMcpServer() {
4762
5676
  server.registerTool(
4763
5677
  "auto_rig_from_layers",
4764
5678
  {
4765
- 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.",
5679
+ 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.",
4766
5680
  inputSchema: {
4767
5681
  layers: import_zod.z.array(
4768
5682
  import_zod.z.object({
@@ -4828,7 +5742,8 @@ function createIkiMcpServer() {
4828
5742
  const text = r.ok ? [
4829
5743
  r.path,
4830
5744
  ...formatPatchReports(r.patches ?? []),
4831
- ...formatFoldReport(r.folds, r.canvas)
5745
+ ...formatFoldReport(r.folds, r.canvas),
5746
+ ...formatPhysicsReport(r.physics)
4832
5747
  ].join("\n") : `INVALID: ${r.error}`;
4833
5748
  return { content: [{ type: "text", text }], structuredContent: r };
4834
5749
  } catch (err) {
@@ -4957,7 +5872,7 @@ function createIkiMcpServer() {
4957
5872
  server.registerTool(
4958
5873
  "render_poses",
4959
5874
  {
4960
- 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.",
5875
+ 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.",
4961
5876
  inputSchema: {
4962
5877
  modelPath: import_zod.z.string().describe(
4963
5878
  "Rigged .iki file path (resolved against cwd; must sit under the working directory)."
@@ -4986,7 +5901,8 @@ function createIkiMcpServer() {
4986
5901
  const r = await renderPoses(args);
4987
5902
  const text = r.ok ? [
4988
5903
  ...r.poses.map((p) => p.path),
4989
- ...formatFoldReport(r.folds, r.modelCanvas)
5904
+ ...formatFoldReport(r.folds, r.modelCanvas),
5905
+ ...formatPhysicsReport(r.physics)
4990
5906
  ].join("\n") : `INVALID: ${r.error}`;
4991
5907
  return { content: [{ type: "text", text }], structuredContent: r };
4992
5908
  } catch (err) {