@rig-c/parts 2.44.0 → 2.46.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/src/propose.ts CHANGED
@@ -151,7 +151,7 @@ import type { JointState, RigJoint, RigJoints } from './keypoints.ts';
151
151
  import { IDLE_FPS } from './motion.ts';
152
152
  import { draftMotionSeams, type MotionSeamDeclaration } from './motionseams.ts';
153
153
  export { draftMotionSeams } from './motionseams.ts';
154
- import { FORK_SMOOTH_MAX_INFLUENCES, influenceFarthest } from './rig.ts';
154
+ import { draftClothHoldRow, FORK_SMOOTH_MAX_INFLUENCES, influenceFarthest } from './rig.ts';
155
155
  import { type Segment as WeightSegment } from './weights.ts';
156
156
  import { pyRound as roundTo } from './round.ts';
157
157
  import { KEYPOINT_NAMES, type KeypointName } from './skeleton.ts';
@@ -161,7 +161,7 @@ import { TURN_BONE, TURN_CARRIER_TAG, TURN_PLACES, TURN_RIDER_OFFSET, TURN_RIDER
161
161
  import { edgeLength } from './length.ts';
162
162
  import { bonePlaces, jointLine, type JointLine, limbCrossing, limbPolyline, limbRun, limbWidth, nearestLimb, nearestOnLine, offLineFigure, segmentOf, type Pt } from './limbs.ts';
163
163
  import { type BranchSqueezeFinding, branchSqueezes, chainSqueezes, type SqueezeFinding } from './squeeze.ts';
164
- import { backHairMasses, type BackHairMass, backHairMassTrees, INFLUENCE_RADIUS_CELLS, RECIPE_BACK_HAIR_CHAINS, RECIPE_LENGTH_RATIO, chainConstraints, clothNote, type ClothRecipe, type ClothRecipes, type ClothTarget, CLOTH_TARGETS, draftTrees, spanCrosses, swingName, type Tail, tailOverlap, type TailOverlap, type TailSpan, treeConstraints, type TreeChain, type TreeInput, type TreeMassInput } from './cloth.ts';
164
+ import { backHairMasses, type BackHairMass, backHairMassTrees, INFLUENCE_RADIUS_CELLS, RECIPE_BACK_HAIR_CHAINS, RECIPE_LENGTH_RATIO, chainConstraints, clothNote, type ClothRecipe, type ClothRecipes, type ClothTarget, CLOTH_TARGETS, draftTrees, isSleeveCloth, type SleeveClothTarget, spanCrosses, swingName, type Tail, tailOverlap, type TailOverlap, type TailSpan, treeConstraints, type TreeChain, type TreeInput, type TreeMassInput } from './cloth.ts';
165
165
  import { TEXTURE_STRETCH_CEILING } from './check.ts';
166
166
  import { linePixels } from './paintcheck.ts';
167
167
 
@@ -684,10 +684,10 @@ export class PartSet {
684
684
  private readonly masks = new Map<string, Mask>();
685
685
  private preLimbs: PartSet | null = null;
686
686
 
687
- constructor(file: PartsFile, images: ReadonlyMap<string, Raster>) {
688
- [this.W, this.H] = file.rig_size;
689
- this.rigScale = file.scale_rig_per_source;
690
- this.recs = file.parts;
687
+ constructor(readonly manifest: PartsFile, images: ReadonlyMap<string, Raster>) {
688
+ [this.W, this.H] = manifest.rig_size;
689
+ this.rigScale = manifest.scale_rig_per_source;
690
+ this.recs = manifest.parts;
691
691
  this.images = images;
692
692
  }
693
693
 
@@ -1487,6 +1487,15 @@ export function proposeWithBasis(
1487
1487
  // Issue #349, #440: limbs are drafted from the parts before their cut — a complete assemble with config.limbs
1488
1488
  // reconstructs its pre-limb parts here in the same run; a standalone or incomplete limb part handed to propose
1489
1489
  // on its own is refused by name.
1490
+ const sleevePartProblem = (tag: SleeveClothTarget, detail: string): never => {
1491
+ throw new PartsError([{ code: 'PROPOSE_CLOTH_PART', object: `config.cloth.${JSON.stringify(tag)}.part`, detail }]);
1492
+ };
1493
+ for (const tag of CLOTH_TARGETS.filter(isSleeveCloth)) {
1494
+ const part = cloth?.[tag]?.part;
1495
+ if (typeof part !== 'string') continue;
1496
+ const cut = P.recs.find((record) => record.limb !== undefined && (record.name === part || record.limb.of === part));
1497
+ if (cut !== undefined) sleevePartProblem(tag, `names "${part}", whose art belongs to joint-cut limb "${cut.limb?.name}"; a Form 1 sleeve carrier is required`);
1498
+ }
1490
1499
  const limbed = P.standaloneLimbParts();
1491
1500
  refuseIfAny(
1492
1501
  limbed.length === 0
@@ -1642,6 +1651,7 @@ export function proposeWithBasis(
1642
1651
  const clothUsed = new Set<ClothTarget>();
1643
1652
  /** Issue #518: each part a recipe meshes, by the target whose recipe drafted its mesh. */
1644
1653
  const clothMeshed = new Map<string, ClothTarget>();
1654
+ const clothHeld = new Map<string, { tag: ClothTarget; trunks: TreeChain[] }>();
1645
1655
  const multiPartClaimed = new Set<string>();
1646
1656
  const recipeOf = (tag: ClothTarget): ClothRecipe | null => cloth?.[tag] ?? null;
1647
1657
  const declaredPartsOf = (tag: ClothTarget): { field: 'parts' | 'part'; list: PartRecord[] } | null => {
@@ -1665,17 +1675,38 @@ export function proposeWithBasis(
1665
1675
  };
1666
1676
  // Issue #391: the tails the back hair recipe drafts, each with its mesh's spans, which an accessory wrapped round one rides.
1667
1677
  const tails: Tail[] = [];
1668
- const T = (p: PartRecord | readonly PartRecord[], tag: ClothTarget, r: ClothRecipe, input: TreeInput): TreeChain[] => {
1678
+ const T = (p: PartRecord | readonly PartRecord[], tag: ClothTarget, r: ClothRecipe, input: TreeInput, rootJoint?: KeypointName): TreeChain[] => {
1669
1679
  const partNames = Array.isArray(p) ? p.map((x) => x.name) : [(p as PartRecord).name];
1670
1680
  const trees = draftTrees(input, r);
1681
+ if (r.extent !== undefined) {
1682
+ const object = `config.cloth.${JSON.stringify(tag)}.extent`;
1683
+ if (trees.length === 0) {
1684
+ throw new PartsError([{ code: 'PROPOSE_CLOTH_EXTENT', object, detail: `is ${r.extent}; "${partNames.join(', ')}" has no resolved root-to-tip span` }]);
1685
+ }
1686
+ for (const tree of trees) {
1687
+ const path = [...tree.points, tree.tip];
1688
+ for (let i = 1; i < path.length; i++) {
1689
+ if (path[i][1] <= path[i - 1][1]) {
1690
+ throw new PartsError([{ code: 'PROPOSE_CLOTH_EXTENT', object, detail: `is ${r.extent}; ${tree.chain} link ${i - 1} has no downward span after rounding rows ${path[i - 1][1]} and ${path[i][1]}` }]);
1691
+ }
1692
+ }
1693
+ }
1694
+ const byChain = new Map(trees.map((tree) => [tree.chain, tree]));
1695
+ const fractions = trees.filter((tree) => tree.last.some(Boolean)).map((tree) => {
1696
+ const parent = tree.parent === input.parent ? tree : byChain.get(tree.parent.slice(0, tree.parent.lastIndexOf('_') + 1)) ?? tree;
1697
+ return `${tree.chain} ${roundTo((tree.tip[1] - parent.points[0][1]) / (tree.tip[1] - input.rootY), 6)}`;
1698
+ });
1699
+ notes.push(`${partNames.join(', ')}: ${object} ${r.extent} sets the tree roots from the free end; fractions after row rounding: ${fractions.join(', ')}`);
1700
+ }
1671
1701
  const constants = [konst('cloth_chains', input.masses !== undefined ? input.masses.length : (r.chains ?? RECIPE_BACK_HAIR_CHAINS)), konst('cloth_links', r.links), konst('length_ratio', roundTo(r.length_ratio ?? RECIPE_LENGTH_RATIO, 6))];
1702
+ const refs = { parts: partNames, bones: [input.parent], constants, ...(rootJoint === undefined ? {} : { joints: [jointRef(rootJoint)] }) };
1672
1703
  for (const t of trees) {
1673
1704
  C(
1674
1705
  t.chain,
1675
1706
  t.parent,
1676
1707
  t.points,
1677
1708
  t.tip,
1678
- t.why.map((w) => placement('mask', w, { parts: partNames, bones: [input.parent], constants })),
1709
+ t.why.map((w) => placement(rootJoint === undefined ? 'mask' : 'joint', w, refs)),
1679
1710
  placement('mask', t.tipWhy, { parts: partNames, bones: [input.parent], constants }),
1680
1711
  );
1681
1712
  }
@@ -2622,6 +2653,21 @@ export function proposeWithBasis(
2622
2653
  // ---- sleeves
2623
2654
  // A cut's piece counts here (issue #230): the sleeve rule names its chains by side, not once per part, so a piece
2624
2655
  // never repeats one, and cutting one sleeve out of a both-arms part is how #199's note says to separate them.
2656
+ const sleeveParts = new Map<PartRecord, SleeveClothTarget>();
2657
+ const sleeveSides = new Set<'r' | 'l'>();
2658
+ for (const tag of CLOTH_TARGETS.filter(isSleeveCloth)) {
2659
+ const recipe = recipeOf(tag);
2660
+ if (recipe === null) continue;
2661
+ const name = recipe.part;
2662
+ const part = typeof name === 'string' ? P.recs.find((record) => record.name === name) : undefined;
2663
+ if (part === undefined || splitFrom(part.from)[1] !== tag || part.cut_from !== undefined) {
2664
+ sleevePartProblem(tag, `names ${JSON.stringify(name) ?? 'no part'}; an uncut part in parts.json tagged "${tag}" is required`);
2665
+ }
2666
+ const carrier = part as PartRecord;
2667
+ const side = tag === 'handwear-r' ? 'r' : 'l';
2668
+ sleeveParts.set(carrier, tag);
2669
+ sleeveSides.add(side);
2670
+ }
2625
2671
  const hw = [...P.byTag('handwear-r', undefined, true), ...P.byTag('handwear-l', undefined, true)].filter((p) => p.opaque_px > 500);
2626
2672
  // Issue #577: a figure of one material (a mannequin, a statue) reaches See-through as one garment, so no handwear or
2627
2673
  // legwear part carries its limbs. With joints, when the tagged route has no part for a complete limb, the one topwear
@@ -2673,6 +2719,65 @@ export function proposeWithBasis(
2673
2719
  : figPart !== null && figure !== null && figure.arms
2674
2720
  ? armsFromJoints(P, [figPart], joints as RigJoints, null, false)
2675
2721
  : null;
2722
+ if (sleeveParts.size > 0 && (clasped !== null || (armPlan?.arms == null && !(hw.length === 2 && sides.size === 2) && hw.some((p) => !sleeveParts.has(p))))) {
2723
+ const [part, tag] = [...sleeveParts][0];
2724
+ sleevePartProblem(tag, `names "${part.name}" in a mixed handwear draft; a separately resolved sleeve carrier is required`);
2725
+ }
2726
+ for (const [part, tag] of sleeveParts) {
2727
+ const side = tag === 'handwear-r' ? 'r' : 'l';
2728
+ const other = side === 'r' ? 'l' : 'r';
2729
+ const elbow = at(`${side}_elbow`);
2730
+ if (elbow === null) sleevePartProblem(tag, `names "${part.name}", but ${side}_elbow has no resolved position; supply it with --keypoints`);
2731
+ const rootY = (elbow as Point)[1];
2732
+ const mask = P.alpha(part);
2733
+ const mixed = [at(`${other}_elbow`), at(`${other}_wrist`)].some((point) => point !== null && isOn(mask, point[0], point[1]));
2734
+ if (mixed || connectedComponents(mask, 8).count !== 2 || !isOn(mask, (elbow as Point)[0], rootY)) {
2735
+ sleevePartProblem(tag, `names "${part.name}", whose alpha does not resolve to one sleeve on ${side}_elbow, or also covers the opposite arm; a separate sleeve carrier is required`);
2736
+ }
2737
+ const recipe = recipeOf(tag) as ClothRecipe;
2738
+ const cellCount = recipe.chains ?? 0;
2739
+ const xAt = (y: number, f: number, lo = part.x, hi = part.x + part.w): number | null => {
2740
+ const row = pyRound(y);
2741
+ const opaque: number[] = [];
2742
+ for (let x = lo; x < hi; x++) if (isOn(mask, x, row)) opaque.push(x);
2743
+ return opaque.length === 0 ? null : opaque[pyRound(f * (opaque.length - 1))];
2744
+ };
2745
+ const trees = T(part, tag, recipe, {
2746
+ prefix: `sleeve_${side}_`,
2747
+ parent: 'chest',
2748
+ rootY,
2749
+ tipY: part.y + part.h - 1,
2750
+ xAt,
2751
+ fallbackX: (f) => part.x + f * (part.w - 1),
2752
+ frame: `the opaque row on "${part.name}" below ${side}_elbow`,
2753
+ edges: 'both',
2754
+ columnTip: (k) => {
2755
+ const lo = Math.floor(part.x + k * part.w / cellCount);
2756
+ const hi = Math.ceil(part.x + (k + 1) * part.w / cellCount);
2757
+ for (let y = part.y + part.h - 1; y > rootY; y--) {
2758
+ if (xAt(y, 0.5, lo, hi) === null) continue;
2759
+ return { tipY: y, xAt: (row, f) => xAt(row, f * cellCount - k, lo, hi) ?? xAt(row, f) };
2760
+ }
2761
+ return null;
2762
+ },
2763
+ }, `${side}_elbow`);
2764
+ const trunks = trees.filter((tree) => tree.parent === 'chest');
2765
+ if (trunks.length !== cellCount || trunks.length === 0 || trees.some((tree) => [...tree.points, tree.tip].some(([x, y]) => !isOn(mask, x, y)))) {
2766
+ sleevePartProblem(tag, `names "${part.name}", which has no opaque root-to-free-end path for every declared tree under ${side}_elbow`);
2767
+ }
2768
+ const [g, r] = gridR(part);
2769
+ const constraints = treeConstraints(trees, recipe, null);
2770
+ clothConstraints.push(...constraints);
2771
+ clothMeshed.set(part.name, tag);
2772
+ clothHeld.set(part.name, { tag, trunks });
2773
+ meshes[part.name] = {
2774
+ grid: g,
2775
+ r: recipe.split?.hold_tip === true ? Math.max(r, g) : r,
2776
+ segments: [['chest', [xAt(rootY, 0) ?? (elbow as Point)[0], rootY], [xAt(rootY, 1) ?? (elbow as Point)[0], rootY]], ...trees.map((tree) => tree.chain)],
2777
+ fixed_above: { row: Math.min(...trunks.map((tree) => tree.points[0][1])), bones: ['chest'] },
2778
+ };
2779
+ notes.push(clothNote(part.name, tag, trees, recipe, constraints.length, ` from ${side}_elbow row ${rootY} to the last opaque row in each sleeve column`, part.from));
2780
+ }
2676
2781
  let sleeveRule = '';
2677
2782
  if (clasped !== null) {
2678
2783
  sleeveRule = 'the clasped-hands rule (the handwear is a region on hip, with no sleeve chain)';
@@ -2690,6 +2795,7 @@ export function proposeWithBasis(
2690
2795
  // as the two-blob rule's does since issue #347 (no chest stub: a stub on
2691
2796
  // chest pinned the puff, and the arm stretched it when it turned).
2692
2797
  for (const a of armPlan.arms) {
2798
+ if (sleeveParts.has(a.part)) continue;
2693
2799
  const sgn = a.side === 'r' ? 1 : -1;
2694
2800
  const used = (n: KeypointName): Placement => placement('joint', `the ${n} joint, ${usedAs((joints as RigJoints).joints[n])}`, { joints: [jointRef(n)] });
2695
2801
  const tipWhy =
@@ -2705,6 +2811,7 @@ export function proposeWithBasis(
2705
2811
  // Issue #349: each arm is a limb — the upper arm on link 0 and the forearm (with the hand) on link 1, each rigid on
2706
2812
  // its link, cut at the elbow — not a mesh blended along the chain. Its handwear part is the layer the limb takes.
2707
2813
  for (const a of armPlan.arms) {
2814
+ if (sleeveParts.has(a.part)) continue;
2708
2815
  limbs[`arm_${a.side}`] = {
2709
2816
  segments: [
2710
2817
  { part: `upperarm_${a.side}`, from: a.part.name, bone: `sleeve_${a.side}0` },
@@ -2726,6 +2833,7 @@ export function proposeWithBasis(
2726
2833
  // puff to the torso, so the sleeve stretched when its chain turned.
2727
2834
  for (const [s, sgn] of SIDES) {
2728
2835
  const p = (sides.get(s) as PartRecord[])[0];
2836
+ if (sleeveParts.has(p)) continue;
2729
2837
  const mask = P.alpha(p);
2730
2838
  const ys = rowsAny(mask);
2731
2839
  const top = ys[0];
@@ -2748,7 +2856,7 @@ export function proposeWithBasis(
2748
2856
  meshes[p.name] = { grid: g, r, segments: [`sleeve_${s}`] };
2749
2857
  }
2750
2858
  notes.push('handwear is two blobs: one sleeve chain per mesh, and nothing on chest');
2751
- } else if (hw.length > 0) {
2859
+ } else if (hw.length > 0 && sleeveParts.size === 0) {
2752
2860
  sleeveRule = `the one-blob sleeve rule (both chains in one mesh, split at the eye axis x=${pyFixed(axis, 0)})`;
2753
2861
  const segs: Segment[] = [['chest', rnd([chest[0], chest[1] - 40]), rnd([chest[0], hip[1]])]];
2754
2862
  let mask = newMask(P.W, P.H);
@@ -2807,6 +2915,13 @@ export function proposeWithBasis(
2807
2915
  if (hw.length === 1) notes.push(`handwear is one blob (${hw[0].name}): both sleeves in one mesh, split at the eye axis x=${pyFixed(axis, 0)}`);
2808
2916
  }
2809
2917
  for (const [s] of SIDES) {
2918
+ if (sleeveSides.has(s)) {
2919
+ for (const hand of P.byTag(`hand-${s}`)) {
2920
+ regions[hand.name] = 'chest';
2921
+ notes.push(`${hand.name} (${hand.from}): split hand -> region on chest, the sleeve recipe's fixed frame`);
2922
+ }
2923
+ continue;
2924
+ }
2810
2925
  const sc = bones.find((b): b is Extract<BoneEntry, { chain: string }> => 'chain' in b && b.chain === `sleeve_${s}`);
2811
2926
  if (sc === undefined) continue;
2812
2927
  const bone = `sleeve_${s}${sc.points.length - 1}`;
@@ -3273,7 +3388,7 @@ export function proposeWithBasis(
3273
3388
  const cx = or(bandX(mask, y0, { frac: 0.5 }), p.x + 0.5 * p.w);
3274
3389
  const first = trees[0].points.length > 1 ? trees[0].points[1][1] : trees[0].tip[1];
3275
3390
  const at: [number, number] = [cx, y0];
3276
- const tipAt: [number, number] = [cx, first];
3391
+ const tipAt: [number, number] = [cx, skirtRecipe.extent === undefined ? first : y0 + first - trees[0].points[0][1]];
3277
3392
  B(
3278
3393
  swingName(prefix),
3279
3394
  'hip',
@@ -3297,7 +3412,15 @@ export function proposeWithBasis(
3297
3412
  p === namedSkirt ? p.from : undefined,
3298
3413
  ),
3299
3414
  );
3300
- meshes[p.name] = { grid: g, r: skirtRecipe.split?.hold_tip === true ? Math.max(r, g) : r, segments: segs };
3415
+ const trunks = trees.filter((tree) => tree.parent === 'hip');
3416
+ if (skirtRecipe.extent !== undefined && trunks.length > 0) clothHeld.set(p.name, { tag: 'bottomwear', trunks });
3417
+ const fixedAbove = skirtRecipe.extent === undefined || trees.length === 0 ? {} : {
3418
+ fixed_above: {
3419
+ row: Math.min(...trunks.map((tree) => tree.points[0][1])),
3420
+ bones: fixed.map((segment) => typeof segment === 'string' ? segment : segment[0]),
3421
+ },
3422
+ };
3423
+ meshes[p.name] = { grid: g, r: skirtRecipe.split?.hold_tip === true ? Math.max(r, g) : r, segments: segs, ...fixedAbove };
3301
3424
  clothMeshed.set(p.name, 'bottomwear');
3302
3425
  continue;
3303
3426
  }
@@ -3571,6 +3694,7 @@ export function proposeWithBasis(
3571
3694
  : []));
3572
3695
  const onChain = segments.some(segment => chains.has(typeof segment === 'string' ? segment : segment[0]));
3573
3696
  meshes[torsoName] = {
3697
+ ...(lattice?.fixed_above === undefined ? {} : { fixed_above: lattice.fixed_above }),
3574
3698
  contour,
3575
3699
  r: lattice !== undefined && 'grid' in lattice ? lattice.r : radius,
3576
3700
  segments,
@@ -3593,6 +3717,7 @@ export function proposeWithBasis(
3593
3717
  chest: chestAlong ? { neck: neckAt, hip } : null,
3594
3718
  sleeveRule,
3595
3719
  armWhy: armPlan === null ? null : armPlan.why,
3720
+ clothSleeves: sleeveSides,
3596
3721
  legs: legPlan === null ? null : legPlan.chains,
3597
3722
  arms: armPlan === null ? null : armPlan.arms,
3598
3723
  figure: figPart,
@@ -3660,8 +3785,31 @@ export function proposeWithBasis(
3660
3785
  // A declared max above the cap is kept.
3661
3786
  const held = recipeOf(tag)?.split?.hold_tip === true;
3662
3787
  const max = held ? Math.max(decl.max, FORK_SMOOTH_MAX_INFLUENCES) : decl.max;
3663
- meshes[name] = { influence: { cell, radius, across: decl.across, max, shape: decl.shape, ...(held ? { hold_tip: true as const } : {}) }, segments };
3788
+ meshes[name] = { influence: { cell, radius, across: decl.across, max, shape: decl.shape, ...(held ? { hold_tip: true as const } : {}) }, segments, ...(m.fixed_above === undefined ? {} : { fixed_above: m.fixed_above }) };
3664
3789
  }
3790
+ const holdProblems: Problem[] = [];
3791
+ for (const [name, { tag, trunks }] of clothHeld) {
3792
+ const mesh = meshes[name];
3793
+ const fixed = mesh.fixed_above;
3794
+ if (fixed === undefined) continue;
3795
+ const part = P.recs.find((record) => record.name === name) as PartRecord;
3796
+ const held = draftClothHoldRow(part, P.images.get(name) as Raster, mesh, fixed.row);
3797
+ const field = `config.cloth.${JSON.stringify(tag)}.${recipeOf(tag)?.extent === undefined ? "part" : "extent"}`;
3798
+ if (held === null) {
3799
+ holdProblems.push({ code: 'PROPOSE_CLOTH_EXTENT', object: field, detail: `cannot measure the transition of "${name}" on its drafted mesh; choose a smaller mesh cell or a larger extent` });
3800
+ continue;
3801
+ }
3802
+ for (const trunk of trunks) {
3803
+ const root = trunk.points[0][1];
3804
+ const end = (trunk.points[1] ?? trunk.tip)[1];
3805
+ const strip = Math.max(0, held - root);
3806
+ notes.push(`${name}: ${trunk.chain} holds ${roundTo(strip, 6)} px below row ${root}; first link spans rows ${root}..${end} (${end - root} px)`);
3807
+ if (held >= end) {
3808
+ holdProblems.push({ code: 'PROPOSE_CLOTH_EXTENT', object: field, detail: `part "${name}" holds ${roundTo(strip, 6)} px below ${trunk.chain}'s root at row ${root} through row ${roundTo(held, 6)}; first link spans ${end - root} px and ends at row ${end}. Choose a smaller mesh cell or a larger extent` });
3809
+ }
3810
+ }
3811
+ }
3812
+ refuseIfAny(holdProblems);
3665
3813
  const constrained = clothConstraints.length === 0 ? {} : { constraints: clothConstraints };
3666
3814
  const motionSeams = draftMotionSeams({ bones, meshes, regions, ...drafted }, P.recs);
3667
3815
  const observed = motionSeams.length === 0 ? {} : { motion_seams: motionSeams };
@@ -4343,6 +4491,7 @@ interface JointNoteFacts {
4343
4491
  chest: { neck: [number, number]; hip: [number, number] } | null;
4344
4492
  sleeveRule: string;
4345
4493
  armWhy: string | null;
4494
+ clothSleeves: ReadonlySet<'r' | 'l'>;
4346
4495
  arms: JointArm[] | null;
4347
4496
  /** Issue #577: the figure layer the arms and legs were split from, or `null`: then every arm is on a handwear part. */
4348
4497
  figure: PartRecord | null;
@@ -4389,6 +4538,14 @@ function jointNotes(joints: RigJoints, f: JointNoteFacts): string[] {
4389
4538
  if (f.chest !== null) out.push(`chest: its rule, half way from neck to hip, taken along the line from neck ${fmtAt(f.chest.neck)} to hip ${fmtAt(f.chest.hip)} rather than down the screen`);
4390
4539
  const standIn = f.sleeveRule === '' ? 'no handwear part is over 500 px, so no sleeve chain is placed' : `${f.sleeveRule} stands in`;
4391
4540
  for (const s of ['r', 'l'] as const) {
4541
+ if (f.clothSleeves.has(s)) {
4542
+ const elbow = `${s}_elbow` as const;
4543
+ tell(elbow, `${said(elbow, J[elbow])}: ${usedAs(J[elbow])} for the sleeve recipe's original root row`);
4544
+ for (const joint of [`${s}_shoulder`, `${s}_wrist`] as const) {
4545
+ tell(joint, `${said(joint, J[joint])}: the sleeve recipe reads the elbow and the carrier's opaque rows`);
4546
+ }
4547
+ continue;
4548
+ }
4392
4549
  const arm = f.arms?.find((a) => a.side === s) ?? null;
4393
4550
  for (const [joint, role] of [
4394
4551
  [`${s}_shoulder`, 'link 0'],
@@ -0,0 +1,41 @@
1
+ import { SHA256_PATTERN } from './editreceipt.ts';
2
+ import { PartsError } from './errors.ts';
3
+
4
+ const DIGEST_KEYS = ['checkpoint_sha256', 'graph_sha256', 'script_sha256'] as const;
5
+ export type ReceiptProducer = { tool: string; model?: string } & (
6
+ | { checkpoint_sha256: string; graph_sha256?: never; script_sha256?: never }
7
+ | { graph_sha256: string; checkpoint_sha256?: never; script_sha256?: never }
8
+ | { script_sha256: string; checkpoint_sha256?: never; graph_sha256?: never }
9
+ );
10
+
11
+ export function receiptObject(value: unknown): value is Record<string, unknown> {
12
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
13
+ }
14
+
15
+ export function receiptText(value: unknown): value is string {
16
+ return typeof value === 'string' && value.trim() !== '';
17
+ }
18
+
19
+ export function parseReceiptProducer(value: unknown, object: string): ReceiptProducer {
20
+ const digests = receiptObject(value) ? DIGEST_KEYS.filter(key => Object.hasOwn(value, key)) : [];
21
+ const [digest] = digests;
22
+ if (receiptObject(value) && receiptText(value.tool) &&
23
+ (!Object.hasOwn(value, 'model') || receiptText(value.model)) &&
24
+ digests.length === 1 && Object.keys(value).every(key => key === 'tool' || key === 'model' || key === digest)) {
25
+ const hash = value[digest];
26
+ if (typeof hash === 'string' && SHA256_PATTERN.test(hash)) {
27
+ const names = { tool: value.tool, ...(typeof value.model === 'string' ? { model: value.model } : {}) };
28
+ if (digest === 'checkpoint_sha256') return { ...names, checkpoint_sha256: hash };
29
+ if (digest === 'graph_sha256') return { ...names, graph_sha256: hash };
30
+ return { ...names, script_sha256: hash };
31
+ }
32
+ }
33
+ throw new PartsError([{ code: 'RECEIPT_PRODUCER', object,
34
+ detail: 'requires a nonblank tool, optional nonblank model, and exactly one lowercase SHA-256 in checkpoint_sha256, graph_sha256 or script_sha256' }]);
35
+ }
36
+
37
+ export function receiptProducerJson(text: string, object: string): ReceiptProducer {
38
+ let value: unknown;
39
+ try { value = JSON.parse(text); } catch { /* The shared parser names the refusal. */ }
40
+ return parseReceiptProducer(value, object);
41
+ }
@@ -0,0 +1,33 @@
1
+ import { mkdtempSync, rmSync } from 'node:fs';
2
+ import { tmpdir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import partsPackage from '../package.json' with { type: 'json' };
6
+ import { processRigcRunner } from '../tools/build-process.ts';
7
+ import { findRigc, rigcRanClause } from './check.ts';
8
+ import { PartsError } from './errors.ts';
9
+ import { type ApplyMeshEditActInput, prepareMeshEditAct, type RemeshResult, remeshStage } from './remesh.ts';
10
+
11
+ export type { ApplyMeshEditActInput, RemeshResult } from './remesh.ts';
12
+
13
+ /** Apply one finalized mesh edit to a Parts rig, or return its bound revision on an exact replay. */
14
+ export function applyMeshEditAct(input: ApplyMeshEditActInput): RemeshResult {
15
+ const prepared = prepareMeshEditAct(input);
16
+ if ('provenance' in prepared) return prepared;
17
+
18
+ const root = fileURLToPath(new URL('..', import.meta.url));
19
+ const bin = findRigc(root, process.env.PATH ?? '');
20
+ const runner = processRigcRunner(bin);
21
+ const version = runner(['--version']);
22
+ const rigc = version.status === 0 ? version.out.trim().split('\n')[0] : '';
23
+ if (rigc === '') {
24
+ throw new PartsError([{ code: 'REMESH_RIGC_GREEN', object: 'rigc --version',
25
+ detail: `exited ${version.status}${rigcRanClause(version)}; the provenance names the rigc that gated the revision, so its version is required` }]);
26
+ }
27
+ const scratch = mkdtempSync(join(tmpdir(), 'rig-parts-remesh-'));
28
+ try {
29
+ return remeshStage(prepared.input, runner, bin, { parts: partsPackage.version, rigc }, scratch, () => {}, {}, prepared);
30
+ } finally {
31
+ rmSync(scratch, { recursive: true, force: true });
32
+ }
33
+ }