@rig-c/parts 1.60.1 → 1.60.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/build.ts CHANGED
@@ -338,6 +338,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
338
338
  head_box?: [number, number, number, number];
339
339
  cuts?: Cut[];
340
340
  skeleton?: string;
341
+ anchor?: NonNullable<typeof cfg.assemble.alternates>[number]['anchor'];
341
342
  drawn?: Record<string, number>;
342
343
  tips?: Record<string, [number, number]>;
343
344
  front?: string[];
@@ -355,6 +356,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
355
356
  head_box: a.head_box,
356
357
  cuts: a.cuts,
357
358
  skeleton: a.skeleton === undefined ? undefined : resolve(configDir, a.skeleton),
359
+ anchor: a.anchor,
358
360
  drawn: a.drawn,
359
361
  tips: a.tips,
360
362
  front: a.front,
@@ -544,7 +546,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
544
546
  const placedBySkeleton = altSkeleton !== undefined && input.altPlacement !== 'angles' && SKELETON_LIMB_BONES.some(([b]) => coveredLimbBones.has(b));
545
547
  if (placedBySkeleton && altSkeleton !== undefined) {
546
548
  // Issue #539: the painting must sit where the base figure sits before its own joints are cut at.
547
- const reg = registerSkeleton(fields.bones, altSkeleton);
549
+ const reg = registerSkeleton(fields.bones, altSkeleton, alt.anchor);
548
550
  if (!reg.ok) {
549
551
  const read = reg.anchors.map((a) => `${a.keypoint} on "${a.bone}"`).join(', ') || 'none';
550
552
  altProblems.push({
@@ -2195,9 +2197,18 @@ export function suppliedCheckFlag(flag: string): string | null {
2195
2197
  * rig-c's launcher answers for; they are two fields so a caller can tell
2196
2198
  * the stages' calls apart (the selftest counts them).
2197
2199
  */
2200
+ /** Stage implementations may run outside this process; only check has a returned value the driver reads. */
2201
+ export interface BuildStages {
2202
+ assemble: (input: AssembleStageInput, outputs: AssembleOutputs, log: Log) => void;
2203
+ rig: (input: RigStageInput, rigc: RigcRunner, scratch: string, log: Log) => void;
2204
+ check: typeof checkStage;
2205
+ }
2206
+
2198
2207
  export interface BuildRunners {
2199
2208
  rig: RigcRunner;
2200
2209
  check: RigcRunner;
2210
+ /** The CLI isolates stages; API callers keep the same in-process functions by default. */
2211
+ stages?: BuildStages;
2201
2212
  /** Where the check's rigc binary is, for its header line. */
2202
2213
  checkBin: string;
2203
2214
  /** A directory the rig stage may stage its gate in, and the loop its lead-in render after it; emptied before and after each. */
@@ -2248,6 +2259,7 @@ export function artifactPaths(buildDir: string, pack: readonly PackLine[]): stri
2248
2259
  * rethrown: it is not a stage's message and must not be printed as one.
2249
2260
  */
2250
2261
  export function build(input: BuildInput, run: BuildRunners, log: Log): BuildResult {
2262
+ const stages: BuildStages = run.stages ?? { assemble: assembleStage, rig: rigStage, check: checkStage };
2251
2263
  const prefixed = (stage: BuildStage): Log => (line) => log(`[${stage}] ${line}`);
2252
2264
  const refused = (stage: BuildStage, err: unknown, check: CheckReport | null = null): BuildResult => {
2253
2265
  if (!(err instanceof PartsError)) throw err;
@@ -2282,7 +2294,7 @@ export function build(input: BuildInput, run: BuildRunners, log: Log): BuildResu
2282
2294
  if (req !== null) readRequirements(req.read);
2283
2295
  // And the schedule (issue #538), by rigc's own reader, as check reads it.
2284
2296
  if (input.environment !== undefined) readCheckEnvironment(input.environment);
2285
- assembleStage(
2297
+ stages.assemble(
2286
2298
  { source: input.source, full: input.full, head: input.head, config: input.config, seam: input.seam, project: input.project, ...(input.alts === undefined ? {} : { alts: input.alts }) },
2287
2299
  { partsJson: join(out, 'parts.json'), partsDir: join(out, 'parts'), recomposite: join(out, 'recomposite_rig.png'), errorMap: join(out, ERROR_MAP_FILE) },
2288
2300
  prefixed('assemble'),
@@ -2292,14 +2304,14 @@ export function build(input: BuildInput, run: BuildRunners, log: Log): BuildResu
2292
2304
  }
2293
2305
 
2294
2306
  try {
2295
- rigStage({ config: input.config, parts: out, out: join(out, 'rig'), idleKeys, pageEdges: input.pageEdges, packShape: input.packShape, command: 'build' }, run.rig, run.scratch, prefixed('rig'));
2307
+ stages.rig({ config: input.config, parts: out, out: join(out, 'rig'), idleKeys, pageEdges: input.pageEdges, packShape: input.packShape, command: 'build' }, run.rig, run.scratch, prefixed('rig'));
2296
2308
  } catch (err) {
2297
2309
  return refused('rig', err);
2298
2310
  }
2299
2311
 
2300
2312
  let report: CheckReport;
2301
2313
  try {
2302
- report = checkStage({ rig: join(out, 'rig'), parts: out, out: join(out, 'check'), pageEdges: input.pageEdges, packShape: input.packShape, ...(req === null ? {} : { requirements: req.read, requirementsAs: req.recorded }), seamPairs: input.seamPairs === true, keepStills: input.keepStills === true, ...(input.set === undefined ? {} : { set: input.set }), allSets: input.allSets === true, ...(input.environment === undefined ? {} : { environment: input.environment }), ...(configRecord === null ? {} : { config: configRecord }) }, run.check, run.checkBin, prefixed('check'));
2314
+ report = stages.check({ rig: join(out, 'rig'), parts: out, out: join(out, 'check'), pageEdges: input.pageEdges, packShape: input.packShape, ...(req === null ? {} : { requirements: req.read, requirementsAs: req.recorded }), seamPairs: input.seamPairs === true, keepStills: input.keepStills === true, ...(input.set === undefined ? {} : { set: input.set }), allSets: input.allSets === true, ...(input.environment === undefined ? {} : { environment: input.environment }), ...(configRecord === null ? {} : { config: configRecord }) }, run.check, run.checkBin, prefixed('check'));
2303
2315
  } catch (err) {
2304
2316
  return refused('check', err);
2305
2317
  }
package/src/check.ts CHANGED
@@ -79,7 +79,7 @@
79
79
  */
80
80
  import { createHash } from 'node:crypto';
81
81
  import { copyFileSync, cpSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
82
- import { basename, delimiter, dirname, isAbsolute, join, relative, resolve } from 'node:path';
82
+ import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
83
83
  import { measureRecomposite, type RecompositeFigures, recompositeRecord, scenePhrase, sourceInRig } from './assemble.ts';
84
84
  import { type BoneTransform, computeExactFrameTransforms, cropToSpineY, normaliseDegrees, toBoneLocal } from './coords.ts';
85
85
  import { capBox, inDisc } from './limbs.ts';
@@ -465,53 +465,64 @@ export function readRigcEntry(versionOut: string): RigcEntryRecord {
465
465
  throw new Error('unreachable');
466
466
  }
467
467
 
468
+ /** Executable names, in selection order. Bun's rigc.bunx is a companion, never a command. */
469
+ function rigcPaths(directory: string, platform: 'win32' | 'posix'): string[] {
470
+ return (platform === 'win32' ? ['rigc', 'rigc.exe'] : ['rigc']).map(name => join(directory, name));
471
+ }
472
+
468
473
  /**
469
- * This package's own rigc: `node_modules/.bin/rigc` under `root` and nowhere else — no directory above it and no
470
- * PATH, which {@link findRigc} walks (issue #337). The selftest's suites run rigc through it from the package root,
471
- * so a fixture in a temp directory, or a tree nested inside another checkout (a harness worktree under
472
- * `.claude/worktrees/`) whose own install is missing, cannot reach another tree's rigc. A miss is refused naming
473
- * the one path looked at.
474
+ * This package's own rigc under root/node_modules/.bin and nowhere else: no ancestor or PATH.
475
+ * Windows Bun supplies rigc.exe and rigc.bunx; the executable keeps its own launcher's runtime gates.
476
+ * The optional platform argument lets the same discovery controls plant both install shapes.
474
477
  */
475
- export function packageRigc(root: string): string {
476
- const bin = join(resolve(root), 'node_modules', '.bin', 'rigc');
477
- if (!existsSync(bin)) {
478
- refuseIfAny([
479
- {
480
- code: 'CHECK_RIGC_PACKAGE',
481
- object: bin,
482
- detail: `does not exist; this package's own rigc is required here and no other is looked for — not in a directory above ${resolve(root)}, not on PATH (\`bun install\` puts it there)`,
483
- },
484
- ]);
485
- }
486
- return bin;
478
+ export function packageRigc(root: string, platform: 'win32' | 'posix' = sep === '\\' ? 'win32' : 'posix'): string {
479
+ const paths = rigcPaths(join(resolve(root), 'node_modules', '.bin'), platform);
480
+ const bin = paths.find(path => existsSync(path));
481
+ if (bin !== undefined) return bin;
482
+ refuseIfAny([
483
+ {
484
+ code: 'CHECK_RIGC_PACKAGE',
485
+ object: paths[0],
486
+ detail: platform === 'win32'
487
+ ? "none of " + paths.join(", ") + " exists; rigc.bunx alone is not executable; this package's own rigc is required here and no ancestor or PATH is searched (bun install puts it there)"
488
+ : `does not exist; this package's own rigc is required here and no other is looked for — not in a directory above ${resolve(root)}, not on PATH (\`bun install\` puts it there)`,
489
+ },
490
+ ]);
491
+ return '';
487
492
  }
488
493
 
489
494
  /**
490
- * Where the `rigc` binary is: `node_modules/.bin/rigc` in `from` or any
491
- * directory above it (a clone has it beside the package; an install has it in
492
- * the consumer's `node_modules/.bin`), then every directory on `PATH`. A miss
493
- * is refused naming every place looked.
495
+ * Find rigc beside from or its ancestors, then on PATH. Windows also looks for rigc.exe;
496
+ * selecting it does not replace it with a compiler entry or another package's launcher.
494
497
  */
495
- export function findRigc(from: string, pathVar: string): string {
498
+ export function findRigc(from: string, pathVar: string, platform: 'win32' | 'posix' = sep === '\\' ? 'win32' : 'posix'): string {
496
499
  const looked: string[] = [];
500
+ let directories = 0;
497
501
  let dir = resolve(from);
498
502
  for (;;) {
499
- const bin = join(dir, 'node_modules', '.bin', 'rigc');
500
- looked.push(bin);
501
- if (existsSync(bin)) return bin;
503
+ directories++;
504
+ for (const bin of rigcPaths(join(dir, 'node_modules', '.bin'), platform)) {
505
+ looked.push(bin);
506
+ if (existsSync(bin)) return bin;
507
+ }
502
508
  const up = dirname(dir);
503
509
  if (up === dir) break;
504
510
  dir = up;
505
511
  }
506
- for (const p of pathVar.split(delimiter).filter((s) => s !== '')) {
507
- const bin = join(p, 'rigc');
508
- if (existsSync(bin)) return bin;
512
+ const onPath: string[] = [];
513
+ for (const p of pathVar.split(delimiter).filter(s => s !== '')) {
514
+ for (const bin of rigcPaths(p, platform)) {
515
+ onPath.push(bin);
516
+ if (existsSync(bin)) return bin;
517
+ }
509
518
  }
510
519
  refuseIfAny([
511
520
  {
512
521
  code: 'CHECK_RIGC_PRESENT',
513
522
  object: 'the rig-c CLI `rigc`',
514
- detail: `found at none of ${looked.length} node_modules/.bin/rigc path(s) from ${resolve(from)} up (nearest ${looked[0]}) nor on PATH; rig-c is this package's dependency — \`bun install\` puts it at node_modules/.bin/rigc`,
523
+ detail: platform === 'win32'
524
+ ? 'found at none of ' + looked.join(', ') + ' nor PATH candidates [' + onPath.join(', ') + ']; executable shapes rigc, rigc.exe were looked for; rigc.bunx alone is not executable; bun install supplies this dependency'
525
+ : `found at none of ${directories} node_modules/.bin/rigc path(s) from ${resolve(from)} up (nearest ${looked[0]}) nor on PATH; rig-c is this package's dependency — \`bun install\` puts it at node_modules/.bin/rigc`,
515
526
  },
516
527
  ]);
517
528
  return '';
@@ -31,7 +31,7 @@ import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
31
31
  import { join } from 'node:path';
32
32
  import type { ControlPose, PaintConfig } from '../config.ts';
33
33
  import { type Problem, refuseIfAny } from '../errors.ts';
34
- import { buildPrompts, checkGraph, paintingGraph, resolvedControl, resolvedLoras, resolvedSampler } from '../graphs.ts';
34
+ import { buildPrompts, checkGraph, paintingGraph, resolvedControl, resolvedLoras, resolvedSampler, UPSCALE_MODEL, UPSCALE_THEN } from '../graphs.ts';
35
35
  import { decodePngBytes, encodePngBytes } from '../raster/png.ts';
36
36
  import { isSkeletonName, renderSkeleton } from '../skeleton.ts';
37
37
  import { ComfyClient, historyImages, refuse } from './client.ts';
@@ -112,6 +112,7 @@ export async function runPainting(client: ComfyClient, run: PaintRun, say: (line
112
112
  checkpoint: g.checkpoint,
113
113
  loras: resolvedLoras(g.loras),
114
114
  sampler: resolvedSampler(g.sampler),
115
+ upscale: { model: UPSCALE_MODEL, then: UPSCALE_THEN },
115
116
  control,
116
117
  pose_from: prompts.poseFrom,
117
118
  dropped: prompts.dropped,
package/src/config.ts CHANGED
@@ -100,6 +100,19 @@ import { FLOOR_FORMS, type FloorForm, type MeshInfluences } from './weights.ts';
100
100
 
101
101
  export type Point = [number, number];
102
102
 
103
+ /** A rigid binding; the object form can keep an exclusive rider in authored order (#680). */
104
+ export type RegionSpec = string | { bone: string; gather?: false };
105
+
106
+ /** Read a declared region binding without changing the authored representation. */
107
+ export function regionBone(region: RegionSpec): string {
108
+ return typeof region === 'string' ? region : region.bone;
109
+ }
110
+
111
+ /** The raw reader keeps invalid values intact for their own named refusal. */
112
+ function rawRegionBone(region: Json): Json {
113
+ return isPlainObject(region) ? region.bone : region;
114
+ }
115
+
103
116
  export interface Lora {
104
117
  name: string;
105
118
  strength: number;
@@ -259,6 +272,8 @@ export interface AlternateSetConfig {
259
272
  head_box?: [number, number, number, number];
260
273
  cuts?: Cut[];
261
274
  skeleton?: string;
275
+ /** One or two skeleton keypoints paired with declared base-bone origins (issue #543). */
276
+ anchor?: Partial<Record<KeypointName, string>>;
262
277
  drawn?: Record<string, number>;
263
278
  /** Explicit bone endpoints on this alternate painting, full source-crop pixels, x right/y down. */
264
279
  tips?: Record<string, Point>;
@@ -329,7 +344,7 @@ export type Segment = string | [string, Point, Point];
329
344
  * locally refined by rig-c's `reduceMesh` under the author's declared
330
345
  * bounds (`src/automesh.ts`).
331
346
  */
332
- export type MeshSpec = LatticeMeshSpec | ContourMeshSpec | AutoMeshSpec | InfluenceMeshSpec;
347
+ export type MeshSpec = (LatticeMeshSpec | ContourMeshSpec | AutoMeshSpec | InfluenceMeshSpec) & { gather?: false };
333
348
 
334
349
  /**
335
350
  * One mesh in the influence mode (issue #378): rig-c's `segments` lattice over the part at `cell` px, every vertex
@@ -701,7 +716,7 @@ export function weightsABone(rg: AutoRegionSpec): rg is AutoWeightRegionSpec {
701
716
  export interface PartBinding {
702
717
  bones: readonly BoneEntry[];
703
718
  meshes: Readonly<Record<string, MeshSpec>>;
704
- regions: Readonly<Record<string, string>>;
719
+ regions: Readonly<Record<string, RegionSpec>>;
705
720
  }
706
721
 
707
722
  /**
@@ -732,7 +747,7 @@ export function partBoundBones(b: PartBinding): Map<string, string[]> {
732
747
  if ('contour' in m) for (const rg of contourRegionsOf(m.contour)) bind(part, rg.bone);
733
748
  if ('auto' in m) for (const rg of m.auto.regions ?? []) if (weightsABone(rg)) bind(part, rg.bone);
734
749
  }
735
- for (const [part, bone] of Object.entries(b.regions)) bind(part, bone);
750
+ for (const [part, region] of Object.entries(b.regions)) bind(part, regionBone(region));
736
751
  return out;
737
752
  }
738
753
 
@@ -971,7 +986,7 @@ export interface CharacterConfig {
971
986
  limbs?: Record<string, Limb>;
972
987
  bones: BoneEntry[];
973
988
  meshes: Record<string, MeshSpec>;
974
- regions: Record<string, string>;
989
+ regions: Record<string, RegionSpec>;
975
990
  motion: Motion;
976
991
  constraints?: ConfigConstraint[];
977
992
  /** Leg stops (issue #404, rig-c 2.56.0's `RigStop`): absent, no stop is added and no byte of any output moves. */
@@ -1796,7 +1811,7 @@ export function repeatedKeys(text: string): Array<{ at: string; key: string; cou
1796
1811
  export interface SkeletonSections {
1797
1812
  bones: BoneEntry[];
1798
1813
  meshes: Record<string, MeshSpec>;
1799
- regions: Record<string, string>;
1814
+ regions: Record<string, RegionSpec>;
1800
1815
  motion: Motion;
1801
1816
  }
1802
1817
 
@@ -1860,7 +1875,7 @@ function checkBlinkStill(c: Check, v: Json, eyes: Json, bones: Set<string>, regi
1860
1875
  c.fail('CONFIG_STILL_OFF_THE_BLINK', `${at}.${part}.bone`, `is "${e.bone}", which config.motion.blink.eyes names, so the still piece would blink too; a bone the blink does not key is required (the eye bone's parent, as propose writes it)`);
1861
1876
  }
1862
1877
  }
1863
- const rb = Object.prototype.hasOwnProperty.call(regionOf, part) ? regionOf[part] : undefined;
1878
+ const rb = Object.prototype.hasOwnProperty.call(regionOf, part) ? rawRegionBone(regionOf[part]) : undefined;
1864
1879
  if (typeof rb !== 'string') {
1865
1880
  c.fail('CONFIG_NAME_RESOLVES', `${at}.${part}`, `names "${part}", which config.regions does not attach; a region part is required — a mesh is not cut`);
1866
1881
  } else if (!eyeList.includes(rb)) {
@@ -2156,7 +2171,7 @@ function checkAlternates(
2156
2171
  const seenNames = new Map<string, number>();
2157
2172
  (v as Json[]).forEach((entry, i) => {
2158
2173
  const at = `${p}[${i}]`;
2159
- const e = c.object(at, entry, ['name'], ['source', 'full', 'head', 'parts', 'hides', 'head_box', 'cuts', 'skeleton', 'drawn', 'tips', 'front']);
2174
+ const e = c.object(at, entry, ['name'], ['source', 'full', 'head', 'parts', 'hides', 'head_box', 'cuts', 'skeleton', 'anchor', 'drawn', 'tips', 'front']);
2160
2175
  if (e === null) return;
2161
2176
  if ('name' in e && c.string(`${at}.name`, e.name)) {
2162
2177
  if (!partNameOk(e.name)) c.fail('CONFIG_PART_NAME', `${at}.name`, `names the set ${show(e.name)}; a set name is a file prefix, so it may not be empty, start with "." or hold a slash`);
@@ -2166,6 +2181,16 @@ function checkAlternates(
2166
2181
  for (const k of ['source', 'full', 'head', 'skeleton'] as const) {
2167
2182
  if (k in e) c.string(`${at}.${k}`, e[k]);
2168
2183
  }
2184
+ if ('anchor' in e) {
2185
+ if (!('skeleton' in e)) c.fail('CONFIG_FIELD_PRESENT', `${at}.skeleton`, 'is absent; anchor registers a skeleton set and requires its skeleton file');
2186
+ const a = e.anchor;
2187
+ if (!isPlainObject(a) || Object.keys(a).length < 1 || Object.keys(a).length > 2) {
2188
+ c.fail('CONFIG_FIELD_TYPE', `${at}.anchor`, `is ${show(a)}; one or two keypoint name -> declared base bone entries are required`);
2189
+ } else for (const [keypoint, bone] of Object.entries(a)) {
2190
+ if (!(KEYPOINT_NAMES as readonly string[]).includes(keypoint)) c.fail('CONFIG_KEY_KNOWN', `${at}.anchor.${keypoint}`, `is not a body-18 keypoint; one of ${KEYPOINT_NAMES.join(', ')} is required`);
2191
+ if (typeof bone !== 'string' || (bones !== null && !bones.has(bone))) c.fail('CONFIG_NAME_RESOLVES', `${at}.anchor.${keypoint}`, `names ${show(bone)}; a bone config.bones declares is required`);
2192
+ }
2193
+ }
2169
2194
  if ('drawn' in e) {
2170
2195
  const d = e.drawn;
2171
2196
  if (!isPlainObject(d) || Object.keys(d).length === 0) {
@@ -2295,8 +2320,8 @@ function checkAlternates(
2295
2320
  const limbSeg = limbs?.parts.get(pn);
2296
2321
  if (limbSeg !== undefined) {
2297
2322
  coveredBones.add(limbSeg.bone);
2298
- } else if (isPlainObject(regions) && typeof regions[pn] === 'string') {
2299
- coveredBones.add(regions[pn]);
2323
+ } else if (isPlainObject(regions) && typeof rawRegionBone(regions[pn]) === 'string') {
2324
+ coveredBones.add(rawRegionBone(regions[pn]) as string);
2300
2325
  } else if (isPlainObject(meshes) && isPlainObject(meshes[pn])) {
2301
2326
  const m = meshes[pn] as Record<string, Json>;
2302
2327
  if (Array.isArray(m.segments)) {
@@ -2491,8 +2516,9 @@ function checkMeshes(c: Check, v: Json, bones: Set<string>, chains: Map<string,
2491
2516
  const at = `config.meshes.${part}`;
2492
2517
  // The known keys keep their old order (grid, r, segments) with contour after them, and `r` and `segments` are
2493
2518
  // required in the place and words the object check uses, so a lattice mesh's refusals read as they did.
2494
- const m = c.object(at, spec, [], ['grid', 'r', 'segments', 'contour', 'auto', 'exponent', 'rule', 'ribs', 'influences', 'stray', 'influence']);
2519
+ const m = c.object(at, spec, [], ['grid', 'r', 'segments', 'contour', 'auto', 'exponent', 'rule', 'ribs', 'influences', 'stray', 'influence', 'gather']);
2495
2520
  if (m === null) continue;
2521
+ checkGather(c, at, m);
2496
2522
  // issue #378: the influence mode weights by rig-c's own pull, so `r` (the distance rule's softening) is not one of its
2497
2523
  // fields — it is refused there below, and required in every other mode as it always was.
2498
2524
  for (const key of 'influence' in m ? ['segments'] : ['r', 'segments']) if (!(key in m)) c.fail('CONFIG_FIELD_PRESENT', `${at}.${key}`, 'is absent and required');
@@ -2800,11 +2826,34 @@ function checkContour(c: Check, at: string, v: Json, bones: Set<string>): void {
2800
2826
  const bandR = RR - rR;
2801
2827
  const bandL = RL - rL;
2802
2828
  if (clearance <= 0 || RR + RL >= D || rR <= 0 || rL <= 0 || bandR < 0 || bandL < 0) {
2803
- const minClearance = Math.max(0, (dR + dL - D) / 2);
2829
+ // Invalid coordinates already have named problems, but c.point accepts any finite pair.
2830
+ // Restrict only this diagnostic search to onGrid's existing domain, not the refusal rule.
2831
+ let remedy = `clearance hint unavailable: correct the CONFIG_FIELD_TYPE landmark coordinates to the 1/${GRID} px grid within ±${MAX_SIDE} px first`;
2832
+ if ([rx, ry, lx, ly, kx, ky].every((n) => Number.isInteger(n * GRID) && Math.abs(n) <= MAX_SIDE)) {
2833
+ let low = 1;
2834
+ let high = Math.ceil(Math.max(dR, dL) * 100) + 100;
2835
+ // The coordinate domain bounds high below 2^24; binary search needs at most 24 steps.
2836
+ const maxSteps = Math.ceil(Math.log2(high));
2837
+ for (let step = 0; low < high && step < maxSteps; step++) {
2838
+ const mid = low + Math.floor((high - low) / 2);
2839
+ if (Math.round(dR - mid / 100) + Math.round(dL - mid / 100) < D) high = mid;
2840
+ else low = mid + 1;
2841
+ }
2842
+ if (low === high) {
2843
+ const candidate = low / 100;
2844
+ const nextRR = Math.round(dR - candidate);
2845
+ const nextRL = Math.round(dL - candidate);
2846
+ const nextR = Math.round(alpha * nextRR);
2847
+ const nextL = Math.round(alpha * nextRL);
2848
+ remedy = nextRR + nextRL < D && nextR > 0 && nextL > 0 && nextRR - nextR >= 0 && nextRL - nextL >= 0
2849
+ ? `the first passing clearance in 0.01 px steps is ${candidate} px for these landmarks and alpha; set clearance to that value`
2850
+ : 'no clearance in 0.01 px steps meets all these rounded-radius checks; move cleavage or the apices, or change alpha, and retry';
2851
+ }
2852
+ }
2804
2853
  c.fail(
2805
2854
  'CONFIG_BUST_CLEARANCE',
2806
2855
  `${bat}.clearance`,
2807
- `is ${clearance} (giving R_r = ${RR}, R_l = ${RL}, R_r + R_l = ${RR + RL} px against apex distance D = ${pyRound(D, 2)} px, r_r = ${rR}, band_r = ${bandR}, r_l = ${rL}, band_l = ${bandL}); a clearance > 0 with R_r + R_l < D (clearance > ${pyRound(minClearance, 2)} px) and positive radii is required`,
2856
+ `is ${clearance} (giving R_r = ${RR}, R_l = ${RL}, R_r + R_l = ${RR + RL} px against apex distance D = ${pyRound(D, 2)} px, r_r = ${rR}, band_r = ${bandR}, r_l = ${rL}, band_l = ${bandL}); a clearance > 0 with R_r + R_l < D and positive core radii and non-negative bands is required; ${remedy}`,
2808
2857
  );
2809
2858
  }
2810
2859
  }
@@ -2991,12 +3040,23 @@ function checkAuto(c: Check, at: string, v: Json, bones: Set<string>): void {
2991
3040
  }
2992
3041
  }
2993
3042
 
3043
+ /** Only false opts out; remove the key for the historical gathering rule. */
3044
+ function checkGather(c: Check, at: string, entry: Record<string, Json>): void {
3045
+ if ('gather' in entry && entry.gather !== false) c.fail('CONFIG_FIELD_TYPE', `${at}.gather`, `is ${show(entry.gather)}; false is required to keep a limb rider at its authored draw position — remove gather for normal gathering`);
3046
+ }
3047
+
2994
3048
  function checkRegions(c: Check, v: Json, bones: Set<string>): void {
2995
3049
  if (typeof v !== 'object' || v === null || Array.isArray(v)) {
2996
3050
  c.fail('CONFIG_FIELD_TYPE', 'config.regions', `is ${show(v)}; an object of part name -> bone name is required`);
2997
3051
  return;
2998
3052
  }
2999
- for (const [part, bone] of Object.entries(v as Record<string, Json>)) {
3053
+ for (const [part, entry] of Object.entries(v as Record<string, Json>)) {
3054
+ const at = `config.regions.${part}`;
3055
+ if (isPlainObject(entry)) {
3056
+ const o = c.object(at, entry, ['bone'], ['gather']);
3057
+ if (o !== null) checkGather(c, at, o);
3058
+ }
3059
+ const bone = rawRegionBone(entry);
3000
3060
  if (typeof bone !== 'string') c.fail('CONFIG_NAME_RESOLVES', `config.regions.${part}`, `is ${show(bone)}; a bone name is required`);
3001
3061
  // Issue #671: the part and the bone by name, so an entry `propose --only-missing` drafted on a bone the config
3002
3062
  // does not declare says which.
@@ -3295,7 +3355,7 @@ function checkCoverage(c: Check, made: string[], patches: string[], meshes: Json
3295
3355
  }
3296
3356
  }
3297
3357
  for (const [part, seg] of limbs.parts) {
3298
- const bone = isPlainObject(regions) ? regions[part] : undefined;
3358
+ const bone = isPlainObject(regions) ? rawRegionBone(regions[part]) : undefined;
3299
3359
  if (typeof bone === 'string' && bone !== seg.bone) {
3300
3360
  c.fail('CONFIG_LIMB_BONE', `config.regions.${part}`, `is "${bone}"; "${part}" is ${seg.at}, which rides "${seg.bone}" with weight 1, so config.regions.${part} "${seg.bone}" is required`);
3301
3361
  }
@@ -1,16 +1,18 @@
1
1
  /**
2
- * The three config updates proposed by the CLI (issue #356). Pure JSON merge:
2
+ * The config updates proposed by the CLI (issues #356, #671, #679):
3
3
  * no file reads/writes and no substitute for the stage's existing validator.
4
4
  * A present proposal section replaces that whole field; an absent optional
5
5
  * section is retained. `proposal-missing` (issue #671, `--only-missing`) instead
6
- * adds only the `meshes` / `regions` entries of proposed parts the config attaches
7
- * by neither, one edit per entry, and leaves every existing entry as it is. The caller supplies the proposer's own section tuple,
6
+ * adds only resolvable `meshes` / `regions` entries for parts not already attached
7
+ * by meshes, regions, limbs or patches, and appends skip diagnostics to the
8
+ * proposal notes. The caller supplies the proposer's own section tuple,
8
9
  * avoiding a second policy list or a runtime import of the proposer graph.
9
10
  */
10
11
  import type { PlanProposal } from './assemble.ts';
11
12
  import type { HeadBoxProposal } from './headbox.ts';
12
13
  import type { Proposal, PROPOSAL_CONFIG_SECTIONS } from './propose.ts';
13
14
  import { PartsError } from './errors.ts';
15
+ import { parseProposalSections } from './config.ts';
14
16
  import type { ConfigEdit } from './meshdraft.ts';
15
17
 
16
18
  export type ConfigJson = null | boolean | number | string | ConfigJson[] | ConfigObject;
@@ -19,7 +21,7 @@ export type ConfigWritePatch =
19
21
  | { kind: 'head-box'; head_box: HeadBoxProposal['head_box'] }
20
22
  | { kind: 'assemble-plan'; plan: PlanProposal['plan']; extend_below_crop: PlanProposal['extend_below_crop'] }
21
23
  | { kind: 'proposal'; proposal: Proposal; sections: typeof PROPOSAL_CONFIG_SECTIONS }
22
- /** Issue #671 (`--only-missing`): only `meshes.<part>` / `regions.<part>` for a proposed part the config attaches by neither. */
24
+ /** Issues #671/#679: add unattached, resolvable entries; append skip explanations to the proposal's notes for the caller to print. */
23
25
  | { kind: 'proposal-missing'; proposal: Proposal; parts: ReadonlyArray<{ name: string; from: string }> };
24
26
  export interface ConfigWriteChange {
25
27
  path: string;
@@ -118,13 +120,52 @@ export function mergeConfigProposal(raw: unknown, patch: ConfigWritePatch): Conf
118
120
  break;
119
121
  }
120
122
  case 'proposal-missing': {
121
- // Issue #671: a config proposed before a part existed (the #490 arm split's drape_<s> and hand_<s>) gains its
122
- // plan row (split parts only) and an entry for that part alone, entry by entry, in the section the proposal drafts
123
- // it in. A part the config already attaches, by either section, keeps its entry as written; nothing else of the
124
- // proposal is read.
125
- const attached = (part: string): boolean => (object(config.meshes) && own(config.meshes, part)) || (object(config.regions) && own(config.regions, part));
123
+ // Read attachment ownership from the destination, even without --keypoints. A limb's source is consumed;
124
+ // the loader requires regions for its segment parts instead. Patches are always regions.
125
+ const attachments = new Map<string, string>();
126
126
  for (const section of ['meshes', 'regions'] as const) {
127
127
  if (config[section] !== undefined && !object(config[section])) return refuse(`config.${section}`, 'is not an object; an object of part entries is required before an entry is added to it');
128
+ if (object(config[section])) for (const part of Object.keys(config[section])) attachments.set(part, field(`config.${section}`, part));
129
+ }
130
+ if (object(config.limbs)) for (const [limb, spec] of Object.entries(config.limbs)) {
131
+ if (object(spec) && Array.isArray(spec.segments)) for (const segment of spec.segments) {
132
+ if (object(segment) && typeof segment.from === 'string') attachments.set(segment.from, `${field('config.limbs', limb)} (source cut into its segment parts)`);
133
+ }
134
+ }
135
+ if (object(config.assemble) && Array.isArray(config.assemble.patches)) for (const patch of config.assemble.patches) {
136
+ if (object(patch) && typeof patch.name === 'string') attachments.set(patch.name, 'config.assemble.patches (a patch is always a region)');
137
+ }
138
+ // This mode appends diagnostics to the proposal's existing notes output, never to the destination config.
139
+ const note = (part: string, why: string): void => {
140
+ const line = `--only-missing: skipped part "${part}" — ${why}; no entry or plan row added`;
141
+ if (!patch.proposal.notes.includes(line)) patch.proposal.notes.push(line);
142
+ };
143
+ const proposed = new Set([...patch.parts.map((p) => p.name), ...Object.keys(patch.proposal.meshes), ...Object.keys(patch.proposal.regions), ...Object.values(patch.proposal.limbs ?? {}).flatMap((l) => l.segments.map((s) => s.from))]);
144
+ for (const part of proposed) {
145
+ const by = attachments.get(part);
146
+ if (by !== undefined) note(part, `already attached by ${by}`);
147
+ }
148
+ const entries: Array<{ section: 'meshes' | 'regions'; part: string; value: ConfigJson }> = [];
149
+ const accepted = new Set<string>();
150
+ for (const section of ['meshes', 'regions'] as const) for (const [part, entry] of Object.entries(patch.proposal[section])) {
151
+ if (attachments.has(part) || accepted.has(part)) continue;
152
+ const value = clone(entry, field(`proposal.${section}`, part));
153
+ // Reuse the loader's own bone/chain expansion and mesh reference checks (including auto region names),
154
+ // against CONFIG bones, never the draft's bones. Coverage and all retained fields still pass through the
155
+ // caller's full config gate. Other entries are absent here so a forward dependency cannot leak from a draft.
156
+ try {
157
+ parseProposalSections({ bones: config.bones, meshes: section === 'meshes' ? { [part]: value } : {}, regions: section === 'regions' ? { [part]: value } : {}, motion: config.motion });
158
+ } catch (error) {
159
+ if (!(error instanceof PartsError)) throw error;
160
+ const at = `proposal.${section}.${part}`;
161
+ const problems = error.problems.filter((p) => p.object === at || p.object.startsWith(`${at}.`) || p.object.startsWith(`${at}[`));
162
+ if (problems.length > 0) {
163
+ note(part, problems.map((p) => `${p.code}: ${p.object.replace(/^proposal\./, 'config.')} — ${p.detail}`).join('; '));
164
+ continue;
165
+ }
166
+ }
167
+ entries.push({ section, part, value });
168
+ accepted.add(part);
128
169
  }
129
170
  const added: ConfigWriteChange[] = [];
130
171
  // The #490 split's parts the plan does not name, each row where `mergedArmSplitPlan` puts it: the drape just
@@ -135,6 +176,7 @@ export function mergeConfigProposal(raw: unknown, patch: ConfigWritePatch): Conf
135
176
  const row = (e: ConfigJson): [string, string, string] | null =>
136
177
  Array.isArray(e) && e.length === 3 && e.every((x) => typeof x === 'string') ? (e as [string, string, string]) : null;
137
178
  for (const part of patch.parts) {
179
+ if (!accepted.has(part.name)) continue;
138
180
  const m = /^full:(drape|hand)-([rl])$/.exec(part.from);
139
181
  if (m === null) continue;
140
182
  if (plan.some((e) => { const r = row(e); return r !== null && (r[0] === part.name || (r[1] === 'full' && r[2] === `${m[1]}-${m[2]}`)); })) continue;
@@ -147,15 +189,11 @@ export function mergeConfigProposal(raw: unknown, patch: ConfigWritePatch): Conf
147
189
  added.push({ path: `assemble.plan[${at}]`, kind: 'added', value: JSON.stringify(value) });
148
190
  }
149
191
  }
150
- for (const section of ['meshes', 'regions'] as const) {
151
- for (const [part, entry] of Object.entries(patch.proposal[section])) {
152
- if (attached(part)) continue;
153
- const value = clone(entry, field(`proposal.${section}`, part));
154
- if (!object(config[section])) config[section] = {};
155
- (config[section] as ConfigObject)[part] = value;
156
- edits.push({ path: [section, part], value });
157
- added.push({ path: field(section, part), kind: 'added' });
158
- }
192
+ for (const { section, part, value } of entries) {
193
+ if (!object(config[section])) config[section] = {};
194
+ (config[section] as ConfigObject)[part] = value;
195
+ edits.push({ path: [section, part], value });
196
+ added.push({ path: field(section, part), kind: 'added' });
159
197
  }
160
198
  return { config, changes: added, edits };
161
199
  }
@@ -1,3 +1,4 @@
1
+ import { regionBone, type RegionSpec } from './config.ts';
1
2
  /**
2
3
  * What `propose` looked at, said (issue #86): the coverage lines lint's
3
4
  * per-bone record prints, and the basis file written beside the proposal.
@@ -186,7 +187,7 @@ export interface LegChainChoice {
186
187
  none: string | null;
187
188
  }
188
189
 
189
- export function legChainChoice(P: PartSet, spec: { bones: readonly BoneEntry[]; meshes: Proposal['meshes']; regions?: Proposal['regions']; limbs?: Readonly<Record<string, Limb>>; notes?: readonly string[] }, joints?: RigJoints): LegChainChoice {
190
+ export function legChainChoice(P: PartSet, spec: { bones: readonly BoneEntry[]; meshes: Proposal['meshes']; regions?: Readonly<Record<string, RegionSpec>>; limbs?: Readonly<Record<string, Limb>>; notes?: readonly string[] }, joints?: RigJoints): LegChainChoice {
190
191
  const chains: LegChainChoice['chains'] = [];
191
192
  for (const entry of spec.bones) {
192
193
  if (!('chain' in entry) || !/^leg_[rl]$/.test(entry.chain)) continue;
@@ -207,7 +208,7 @@ export function legChainChoice(P: PartSet, spec: { bones: readonly BoneEntry[];
207
208
  for (const [part, mesh] of Object.entries(spec.meshes)) {
208
209
  if (mesh.segments.some((s) => typeof s === 'string' ? s === entry.chain || links.has(s) : links.has(s[0]))) bound(part);
209
210
  }
210
- for (const [part, bone] of Object.entries(spec.regions ?? {})) if (links.has(bone)) bound(part);
211
+ for (const [part, bone] of Object.entries(spec.regions ?? {})) if (links.has(regionBone(bone))) bound(part);
211
212
  chains.push({ chain: entry.chain, sources: [...sources], parts: [...parts] });
212
213
  }
213
214
  if (chains.length > 0) return { chains, none: null };
package/src/limblayout.ts CHANGED
@@ -23,6 +23,8 @@ export interface LayoutPlan {
23
23
  limbs: Readonly<Record<string, Limb>>;
24
24
  families: ReadonlyMap<string, readonly string[]>;
25
25
  originalOrder: string[];
26
+ /** Authored rider families excluded from implicit closure, including replay. */
27
+ ungathered?: readonly string[];
26
28
  }
27
29
  export interface LayoutCompanion {
28
30
  spec: typeof LAYOUT_SPEC;
@@ -88,14 +90,14 @@ export function placeLimbLayouts(limbs: Readonly<Record<string, Limb>> | undefin
88
90
  const d = l.layout;
89
91
  if (d === undefined) continue;
90
92
  const at = `config.limbs.${limb}.layout`, parts = l.segments.map((s) => s.part).filter((p) => d.parts === undefined || d.parts.includes(p));
91
- const subject = base.slots.filter((s) => owned(s, skin, sources, limb, parts));
93
+ const subject = base.slots.filter((s) => !base.ungathered?.includes(s.name) && owned(s, skin, sources, limb, parts));
92
94
  const authored = d.before ?? d.after as LimbLayoutTarget;
93
95
  const target: LimbLayoutTarget = authored.limb === undefined ? { part: authored.part } : { limb: authored.limb };
94
96
  let targets: RigSpec['slots'];
95
97
  if (target.limb !== undefined) {
96
98
  const other = limbs[target.limb];
97
99
  const all = other?.segments.map((s) => s.part) ?? [];
98
- targets = base.slots.filter((s) => owned(s, skin, sources, target.limb as string, all));
100
+ targets = base.slots.filter((s) => !base.ungathered?.includes(s.name) && owned(s, skin, sources, target.limb as string, all));
99
101
  for (const p of all) {
100
102
  if ((families.get(p) ?? []).length === 0) problems.push({ code: 'RIG_LAYOUT_UNREPRESENTABLE', object: at, detail: `target limb "${target.limb}" segment part "${p}" has no emitted family` });
101
103
  for (const n of families.get(p) ?? []) if (!targets.some((s) => s.name === n)) problems.push({ code: 'RIG_LAYOUT_NONEXCLUSIVE', object: `${at} target limb "${target.limb}" slot "${n}"`, detail: `requires exclusive target ownership across every attachment; found ${bindingDetail(base.slots.filter((s) => s.name === n), skin, sources)}` });
@@ -128,7 +130,7 @@ export function placeLimbLayouts(limbs: Readonly<Record<string, Limb>> | undefin
128
130
  result.push(s);
129
131
  for (const p of placements) if (p.after !== undefined && p.target_slots[p.target_slots.length - 1] === s.name) result.push(...base.slots.filter((x) => p.slots.includes(x.name)));
130
132
  }
131
- const plan = { placements, sources, limbs, families, originalOrder: names };
133
+ const plan = { placements, sources, limbs, families, originalOrder: names, ...(base.ungathered === undefined ? {} : { ungathered: base.ungathered }) };
132
134
  validateLimbLayout(plan, { slots: result, skins: { default: skin } });
133
135
  return { slots: result, plan };
134
136
  }
@@ -138,7 +140,7 @@ export function refreshLimbLayout(plan: LayoutPlan, rig: RigSpec): LayoutPlan {
138
140
  const byName = new Map(rig.slots.map((s) => [s.name, s]));
139
141
  const slots = plan.originalOrder.flatMap((n) => { const s = byName.get(n); return s === undefined ? [] : [s]; });
140
142
  if (slots.length !== rig.slots.length || new Set(rig.slots.map((s) => s.name)).size !== slots.length) refuseIfAny([{ code: 'RIG_LAYOUT_UNREPRESENTABLE', object: 'rig.slots', detail: 'accepted candidate changed the source slot population; an exact permutation is required' }]);
141
- const next = placeLimbLayouts(plan.limbs, rig.bones, { slots, owners: [], anchors: [] }, rig.skins.default, plan.families, plan.sources);
143
+ const next = placeLimbLayouts(plan.limbs, rig.bones, { slots, owners: [], anchors: [], ...(plan.ungathered === undefined ? {} : { ungathered: plan.ungathered }) }, rig.skins.default, plan.families, plan.sources);
142
144
  rig.slots = next.slots;
143
145
  return next.plan as LayoutPlan;
144
146
  }
package/src/limbs.ts CHANGED
@@ -118,7 +118,7 @@ import type { BoneEntry, Limb, LimbSplit } from './config.ts';
118
118
  import { refuseIfAny, type Problem } from './errors.ts';
119
119
  import { edgeLength } from './length.ts';
120
120
  import { pyRound } from './round.ts';
121
- import type { KeypointName, PosePoints } from './skeleton.ts';
121
+ import { KEYPOINT_NAMES, type KeypointName, type PosePoints } from './skeleton.ts';
122
122
 
123
123
  export type Pt = [number, number];
124
124
 
@@ -301,10 +301,25 @@ export type SkeletonRegistration =
301
301
  * base's the mean of those bones' origins; `scale` is the base torso's length
302
302
  * over the skeleton's, and `offset` takes the skeleton torso's midpoint, so
303
303
  * scaled, onto the base's. Both to 6 places. Not ok when the base declares no
304
- * bone at one end, or the skeleton's torso has no length.
304
+ * bone at one end, or the skeleton's torso has no length. An explicit anchor
305
+ * (issue #543) replaces torso discovery: one pair holds scale at 1; two pairs
306
+ * read scale from their distance and offset from their midpoint.
305
307
  */
306
- export function registerSkeleton(bones: readonly BoneEntry[], pts: PosePoints): SkeletonRegistration {
308
+ export function registerSkeleton(bones: readonly BoneEntry[], pts: PosePoints, anchor?: Partial<Record<KeypointName, string>>): SkeletonRegistration {
307
309
  const places = bonePlaces(bones);
310
+ if (anchor !== undefined) {
311
+ const named = KEYPOINT_NAMES.flatMap((keypoint) => typeof anchor[keypoint] === 'string' ? [{ keypoint, bone: anchor[keypoint] as string }] : []);
312
+ if (named.length < 1 || named.length > 2 || named.some((a) => !places.has(a.bone))) return { ok: false, missing: [], anchors: named };
313
+ const source = named.map((a) => pts[a.keypoint]);
314
+ const target = named.map((a) => (places.get(a.bone) as BonePlace).at);
315
+ const length = source.length === 1 ? 1 : edgeLength(source[1][0] - source[0][0], source[1][1] - source[0][1]);
316
+ if (length === 0) return { ok: false, missing: [], anchors: named };
317
+ const scale = source.length === 1 ? 1 : edgeLength(target[1][0] - target[0][0], target[1][1] - target[0][1]) / length;
318
+ const offset: Pt = [0, 0];
319
+ for (let i = 0; i < source.length; i++) for (const axis of [0, 1] as const) offset[axis] += (target[i][axis] - scale * source[i][axis]) / source.length;
320
+ const rounded = (v: number): number => { const n = pyRound(v, 6); return n === 0 ? 0 : n; };
321
+ return { ok: true, offset: [rounded(offset[0]), rounded(offset[1])], scale: rounded(scale), anchors: named };
322
+ }
308
323
  const anchors: Array<{ keypoint: KeypointName; bone: string; end: 'top' | 'bottom' }> = [];
309
324
  for (const t of SKELETON_TORSO) {
310
325
  const bone = t.bones.find((b) => places.has(b));