@rig-c/parts 1.57.1 → 1.59.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/build.ts CHANGED
@@ -73,14 +73,14 @@ import {
73
73
  } from './autoreplay.ts';
74
74
  import { besideIdleLine, checkSummaryLine, inputFileRecord, type InputFileRecord, CLOTH_LINE, type ClothLine, clothWarnText, frameRuns, MOTION_SEAM_LINE, type MotionSeamLine, type MotionSeamPlant, motionSeamWarnText, FOLD_LINE, type FoldsLine, LEVEL_LINE, type LevelLine, LIMB_LINE, type LimbLine, STRESS_LINE, SWEEP_LINE, type SweepLine, buildGateLines, causeLines, environmentLine, IDLE_FPS, IDLE_MAX_PX, maxRgbDiff, REQUIREMENTS_DIR, type CheckReport, type PackLine, DEFAULT_PACK_SHAPE, DEFAULT_PAGE_EDGES, GATE_PROFILE, JUDGEMENT_LINES, type JudgementLine, packedBuildArgs, packedBuildLabel, type PackMode, readCheckEnvironment, type PackShape, type PageEdges, readFrameSet, rigcFailed, rigcIdentity, rigcRanClause, REPORTED_LINES, type ReportedLine, type RigcRunner, runCheck, SEAM_DIR, SEAM_MEAN_BAR, seamPairText, seamRigPxText, SOURCE_LINE, SEAM_PX_BAR, SEAM_PX_LEVEL, SEAM_PX_LEVEL_HIGH, SPINEBOY_YARDSTICK, STILL_DIR } from './check.ts';
75
75
  import { type Cut, type Extend, type Limb, loadConfigAndAnimations, loadConfigWithBytes, loadEarlyConfig, type Patch, type PlanEntry } from './config.ts';
76
- import { failLine, PartsError, type Problem, refuseIfAny } from './errors.ts';
76
+ import { coreCompileGuideLine, failLine, PartsError, type Problem, refuseIfAny } from './errors.ts';
77
77
  import type { MeshQualityReport, MotionSchedule } from 'rig-c/mesh';
78
78
  import { encodeGif } from './gif.ts';
79
79
  import { CONTROL_SUFFIX, withAnimations } from './motion.ts';
80
80
  import type { PaletteError } from './palette.ts';
81
81
  import { type LayerSet, readLayers } from './layers.ts';
82
82
  import { placeBoneEntriesForSkeleton, poseBoneEntriesForDrawn, REGISTER_OFFSET_BAR, REGISTER_SCALE_BAR, registeredWithinBar, registerSkeleton, SKELETON_LIMB_BONES, skeletonDrawnLength, skeletonLimbJoints } from './limbs.ts';
83
- import { type AlternatePartsRecord, type PartRecord, readParts, type RecompositeRecord, type SingleRunPad, tagOf, writeParts } from './parts.ts';
83
+ import { type AlternatePartsRecord, FRONT_SUFFIX, type PartRecord, readParts, type RecompositeRecord, type SingleRunPad, tagOf, writeParts } from './parts.ts';
84
84
  import { encodePngBytes, readPng, writePng } from './raster/png.ts';
85
85
  import type { Raster } from './raster/types.ts';
86
86
  import { type Mask, newMask } from './raster/types.ts';
@@ -287,6 +287,28 @@ export function readCaps(configPath: string, limbs: Readonly<Record<string, Limb
287
287
  return out;
288
288
  }
289
289
 
290
+ /**
291
+ * Issue #664: `items` (in parts.json's order) with each part named in `front`
292
+ * moved to just after the part `after` maps it to — where its front slot draws
293
+ * it. Several front parts after one target keep `items`' order. A part whose
294
+ * target is not among `items` stays where it is. With `front` empty, `items`.
295
+ */
296
+ export function frontOrdered<T extends { record: { name: string } }>(items: readonly T[], front: ReadonlySet<string>, after: ReadonlyMap<string, string>): T[] {
297
+ if (front.size === 0) return [...items];
298
+ const names = new Set(items.map((x) => x.record.name));
299
+ const moving = items.filter((x) => front.has(x.record.name) && names.has(after.get(x.record.name) ?? '') && after.get(x.record.name) !== x.record.name);
300
+ const out: T[] = [];
301
+ const place = (x: T): void => {
302
+ if (out.includes(x)) return;
303
+ out.push(x);
304
+ for (const m of moving) if (after.get(m.record.name) === x.record.name) place(m);
305
+ };
306
+ for (const x of items) if (!moving.includes(x)) place(x);
307
+ // Front parts whose targets form a cycle have no anchor: they are appended at the end, in items' order.
308
+ for (const x of items) place(x);
309
+ return out;
310
+ }
311
+
290
312
  /** Read, assemble, and write only after every refusal has had its chance. Throws a PartsError on a refusal, having written nothing. */
291
313
  export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs, log: Log): AssembleResult {
292
314
  // The early door: assemble runs before propose has drafted bones, meshes,
@@ -318,6 +340,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
318
340
  skeleton?: string;
319
341
  drawn?: Record<string, number>;
320
342
  tips?: Record<string, [number, number]>;
343
+ front?: string[];
321
344
  }> = cfgAlts.map((a, i) => {
322
345
  const cli = cliByName.get(a.name);
323
346
  if (cli !== undefined) cliByName.delete(a.name);
@@ -334,6 +357,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
334
357
  skeleton: a.skeleton === undefined ? undefined : resolve(configDir, a.skeleton),
335
358
  drawn: a.drawn,
336
359
  tips: a.tips,
360
+ front: a.front,
337
361
  };
338
362
  });
339
363
  for (const cli of cliByName.values()) {
@@ -349,6 +373,9 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
349
373
  const altProblems: Problem[] = [];
350
374
  const altBuilt: Array<{ record: AlternatePartsRecord; images: Array<{ name: string; image: Raster }>; excluded: ExcludedCount[]; islands: IslandCount[]; splits: SplitCount[]; capSplits: SplitCount[] }> = [];
351
375
  const baseSlots = result.parts.parts.map((p) => p.name);
376
+ // Issue #664: each limb segment part with a declared front slot -> the part its front slot follows.
377
+ const frontAfter = new Map<string, string>();
378
+ for (const limb of Object.values(fields.limbs ?? {})) for (const p of limb.front?.parts ?? []) frontAfter.set(p, (limb.front as { after: string }).after);
352
379
  for (const alt of mergedAlts) {
353
380
  if (alt.source === undefined || alt.full === undefined) {
354
381
  altProblems.push({
@@ -566,10 +593,17 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
566
593
  if (altOthers !== undefined && input.setSplit === 'whole-limb') altOthers.line = 'whole-limb';
567
594
  // Issue #587: a subset set's limb part takes nothing a base part it does not replace covers at setup.
568
595
  const [exW, exH] = result.parts.rig_size;
596
+ // Issue #664: a part the set draws on its front slot is drawn after its front slot's target, so only base parts
597
+ // drawn after that target cover it; every other segment part keeps the base order.
598
+ const altFront = new Set(alt.front ?? []);
599
+ const altSegParts = Object.values(altLimbs).flatMap((l) => l.segments.map((sg) => sg.part));
600
+ const replacedSet = new Set([...coveredSet, ...hidesSet]);
569
601
  const altExclude =
570
602
  alt.parts === undefined || input.setExclusion === 'none'
571
603
  ? []
572
- : setExclusions(result.images, exW, exH, Object.values(altLimbs).flatMap((l) => l.segments.map((sg) => sg.part)), new Set([...coveredSet, ...hidesSet]));
604
+ : altFront.size === 0
605
+ ? setExclusions(result.images, exW, exH, altSegParts, replacedSet)
606
+ : altSegParts.flatMap((sp) => setExclusions(altFront.has(sp) ? frontOrdered(result.images, new Set([sp]), frontAfter) : result.images, exW, exH, [sp], replacedSet));
573
607
  let altRes: ReturnType<typeof assemble>;
574
608
  try {
575
609
  altRes = assemble({
@@ -614,12 +648,12 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
614
648
  .map(({ record, image }) => ({ name: `${alt.name}_${record.name}`, image }));
615
649
  const keptRecords = altRes.parts.parts.filter((p) => coveredSet.has(p.name));
616
650
  const slots: Record<string, string> = {};
617
- for (const r of keptRecords) slots[r.name] = `${alt.name}_${r.name}`;
651
+ for (const r of keptRecords) slots[altFront.has(r.name) ? `${r.name}${FRONT_SUFFIX}` : r.name] = `${alt.name}_${r.name}`;
618
652
  let altRecomposite = altRes.parts.recomposite as RecompositeRecord;
619
653
  if (alt.parts !== undefined) {
620
654
  const [rW, rH] = result.parts.rig_size;
621
655
  const altByName = new Map(altRes.images.map((x) => [x.record.name, x]));
622
- const fullSetPlaced = result.images
656
+ const fullSetPlaced = frontOrdered(result.images, altFront, frontAfter)
623
657
  .filter(({ record }) => !hidesSet.has(record.name))
624
658
  .map((baseItem) => altByName.get(baseItem.record.name) ?? baseItem);
625
659
  const altSrcRig = sourceInRig(altSrc, rW, rH);
@@ -630,7 +664,8 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
630
664
  record: {
631
665
  name: alt.name,
632
666
  ...(alt.parts === undefined ? {} : { parts: [...alt.parts] }),
633
- ...(alt.hides === undefined || alt.hides.length === 0 ? {} : { hides: [...alt.hides] }),
667
+ ...(alt.hides === undefined || alt.hides.length === 0 ? (altFront.size === 0 ? {} : { hides: [...altFront] }) : { hides: [...alt.hides, ...[...altFront].filter((p) => !(alt.hides as string[]).includes(p))] }),
668
+ ...(altFront.size === 0 ? {} : { front: [...altFront] }),
634
669
  slots,
635
670
  records: keptRecords,
636
671
  ghost_px: altRes.parts.ghost_px,
@@ -817,7 +852,8 @@ function gateRun(label: string, rigc: RigcRunner, args: string[]): GateRun {
817
852
  const r = rigc(args);
818
853
  const lines = r.out.split('\n').filter((l) => /^ {2}FAIL {2}/.test(l) || /assertions: \d+ measured/.test(l) || /^rigc compile error/.test(l) || DECLARED_SKIP.test(l) || HERE_LINE.test(l));
819
854
  const failed = lines.some((l) => /^ {2}FAIL {2}/.test(l) || /^rigc compile error/.test(l));
820
- return { label, status: r.status, lines: r.status !== 0 && !failed ? [...lines, ...causeLines(r.out)] : lines, ...(r.ran === undefined ? {} : { ran: r.ran }) };
855
+ const quoted = r.status !== 0 && !failed ? [...lines, ...causeLines(r.out)] : lines;
856
+ return { label, status: r.status, lines: quoted.map(coreCompileGuideLine), ...(r.ran === undefined ? {} : { ran: r.ran }) };
821
857
  }
822
858
 
823
859
  /**
package/src/check.ts CHANGED
@@ -83,7 +83,7 @@ import { basename, delimiter, dirname, join, resolve } 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';
86
- import { PartsError, type Problem, refuseIfAny } from './errors.ts';
86
+ import { coreCompileGuideLine, PartsError, type Problem, refuseIfAny } from './errors.ts';
87
87
  import { framesInside, IDLE_FPS, TIME_SLACK } from './motion.ts';
88
88
  import {
89
89
  blinkFigures,
@@ -127,7 +127,7 @@ import {
127
127
  type ChainEdge,
128
128
  type WorldBox,
129
129
  } from './instruments.ts';
130
- import { type AlternatePartsRecord, type LimbRecord, type PartRecord, type PartsFile, readParts } from './parts.ts';
130
+ import { type AlternatePartsRecord, FRONT_SUFFIX, type LimbRecord, type PartRecord, type PartsFile, readParts } from './parts.ts';
131
131
  import { poseRigBonesForDrawn, type RigBone, SETS_FILE } from './rig.ts';
132
132
  import { turnTwin } from './turn.ts';
133
133
  import {
@@ -818,7 +818,8 @@ const HERE_LINE = /^\.\.\s+here: /;
818
818
  export function buildGateLines(out: string): string[] {
819
819
  return out
820
820
  .split('\n')
821
- .filter((l) => (l.trim().startsWith('..') && (l.includes(' assertions: ') || l.includes('pages=') || l.includes('pack:') || HERE_LINE.test(l.trim()))) || l.includes('FAIL') || l.includes('compile error'));
821
+ .filter((l) => (l.trim().startsWith('..') && (l.includes(' assertions: ') || l.includes('pages=') || l.includes('pack:') || HERE_LINE.test(l.trim()))) || l.includes('FAIL') || l.includes('compile error'))
822
+ .map(coreCompileGuideLine);
822
823
  }
823
824
 
824
825
  /**
@@ -1237,23 +1238,58 @@ export function flatComposite(parts: PartsFile, partsDir: string, background: re
1237
1238
  }
1238
1239
 
1239
1240
  /**
1240
- * The flat stack of parts for an alternate set (issue #454), in `parts.parts`
1241
- * slot order: hidden slots skipped, covered slots drawn from `alt.records` at
1242
- * their box, uncovered base slots drawn at their base box.
1241
+ * What an alternate set draws, in draw order (issues #454, #664): `parts.parts`
1242
+ * order, hidden slots skipped, covered slots drawn from `alt.records` at their
1243
+ * box, uncovered base slots at their base box. A part the set draws on its front
1244
+ * slot (`alt.front`) is drawn from its record although `alt.hides` names it (the
1245
+ * hide is its base slot's) — with `slotOrder`, the rig's final setup slot names,
1246
+ * right after the nearest part slot before `<part>_front` there; without it (or
1247
+ * with no such slot), in its own place, as the base slot would draw it.
1243
1248
  */
1244
- export function flatCompositeForSet(parts: PartsFile, alt: AlternatePartsRecord, partsDir: string, background: readonly [number, number, number, number]): Raster {
1245
- const [W, H] = parts.rig_size;
1246
- let canvas = newRaster(W, H);
1247
- for (let i = 0; i < W * H; i++) canvas.data.set(background, i * 4);
1249
+ export function setPlacements(parts: PartsFile, alt: AlternatePartsRecord, slotOrder?: readonly string[]): Array<{ name: string; png: string; box: PartRecord }> {
1248
1250
  const hides = new Set(alt.hides ?? []);
1251
+ const front = new Set(alt.front ?? []);
1249
1252
  const byName = new Map(alt.records.map((r) => [r.name, r]));
1253
+ const partNames = new Set(parts.parts.map((p) => p.name));
1254
+ // Each front part the slot order places -> the part it is drawn after.
1255
+ const after = new Map<string, string>();
1256
+ if (slotOrder !== undefined) {
1257
+ for (const p of front) {
1258
+ const at = slotOrder.indexOf(`${p}${FRONT_SUFFIX}`);
1259
+ for (let j = at - 1; j >= 0; j--) {
1260
+ if (partNames.has(slotOrder[j]) && !front.has(slotOrder[j])) {
1261
+ after.set(p, slotOrder[j]);
1262
+ break;
1263
+ }
1264
+ }
1265
+ }
1266
+ }
1267
+ const moved = [...after.keys()].sort((a, b) => (slotOrder as readonly string[]).indexOf(`${a}${FRONT_SUFFIX}`) - (slotOrder as readonly string[]).indexOf(`${b}${FRONT_SUFFIX}`));
1268
+ const out: Array<{ name: string; png: string; box: PartRecord }> = [];
1269
+ const draw = (name: string, base: PartRecord): void => {
1270
+ if (hides.has(name) && !front.has(name)) return;
1271
+ const rec = byName.get(name);
1272
+ out.push({ name, png: rec === undefined ? name : `${alt.name}_${rec.name}`, box: rec ?? base });
1273
+ };
1274
+ const baseOf = new Map(parts.parts.map((p) => [p.name, p]));
1250
1275
  for (const p of parts.parts) {
1251
- if (hides.has(p.name)) continue;
1252
- const rec = byName.get(p.name);
1253
- const pngName = rec === undefined ? p.name : `${alt.name}_${rec.name}`;
1254
- const box = rec ?? p;
1255
- canvas = alphaComposite(canvas, readPng(join(partsDir, `${pngName}.png`)), box.x, box.y);
1276
+ if (after.has(p.name)) continue;
1277
+ draw(p.name, p);
1278
+ for (const m of moved) if (after.get(m) === p.name) draw(m, baseOf.get(m) as PartRecord);
1256
1279
  }
1280
+ return out;
1281
+ }
1282
+
1283
+ /**
1284
+ * The flat stack of parts for an alternate set (issue #454), in the order
1285
+ * {@link setPlacements} gives: with `slotOrder`, a front part (issue #664) is
1286
+ * stacked where its front slot draws it.
1287
+ */
1288
+ export function flatCompositeForSet(parts: PartsFile, alt: AlternatePartsRecord, partsDir: string, background: readonly [number, number, number, number], slotOrder?: readonly string[]): Raster {
1289
+ const [W, H] = parts.rig_size;
1290
+ let canvas = newRaster(W, H);
1291
+ for (let i = 0; i < W * H; i++) canvas.data.set(background, i * 4);
1292
+ for (const { png, box } of setPlacements(parts, alt, slotOrder)) canvas = alphaComposite(canvas, readPng(join(partsDir, `${png}.png`)), box.x, box.y);
1257
1293
  return canvas;
1258
1294
  }
1259
1295
 
@@ -3848,7 +3884,7 @@ export function clothWarnText(r: ClothRow, duration: number): string {
3848
3884
  */
3849
3885
  export function rigcFailed(what: string, call: RigcCall, lines: readonly string[]): Problem[] {
3850
3886
  const named = lines.filter((l) => l.includes('FAIL') || l.includes('compile error'));
3851
- const quoted = named.length > 0 ? named.map((l) => l.trim()) : causeLines(call.out);
3887
+ const quoted = (named.length > 0 ? named.map((l) => l.trim()) : causeLines(call.out)).map(coreCompileGuideLine);
3852
3888
  const object = `\`rigc ${what}\``;
3853
3889
  const ran = rigcRanClause(call);
3854
3890
  if (quoted.length === 0) return [{ code: 'CHECK_RIGC_GREEN', object, detail: `exit ${call.status}, and it printed nothing${ran}` }];
@@ -4476,23 +4512,15 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
4476
4512
  if (asr.status !== 0) refuseIfAny(rigcFailed(`render (the setup-pose still of set "${alt.name}")`, asr, asr.out.split('\n').filter((l) => l.includes('FAIL'))));
4477
4513
  const altStillSet = readFrameSet(join(setDir, 'render'));
4478
4514
  if (keepStills) cpSync(join(setDir, 'render'), join(keptDir, alt.name), { recursive: true });
4479
- const altComposite = flatCompositeForSet(inp.parts, alt, inp.partsDir, altStillSet.background);
4515
+ const rigSlotOrder = (Array.isArray(inp.rig.slots) ? inp.rig.slots : []).filter(isRecord).map((sl) => String(sl.name));
4516
+ const altComposite = flatCompositeForSet(inp.parts, alt, inp.partsDir, altStillSet.background, rigSlotOrder);
4480
4517
  const altSeam = seamFigures(altComposite, altStillSet.frames[0].image, inp.stage, altStillSet.viewport, altStillSet.background, undefined, alt.scene !== undefined);
4481
4518
  const altMean = round3(altSeam.mean);
4482
4519
  const altScale = round6(altStillSet.viewport.scale);
4483
4520
  const altFailed = seamFails(altMean, altSeam.over40, altScale);
4484
4521
  let altPairs: SeamPairRow[] | null = null;
4485
4522
  if (seamPairsAsked || altFailed) {
4486
- const hides = new Set(alt.hides ?? []);
4487
- const byName = new Map(alt.records.map((r) => [r.name, r]));
4488
- const placed = inp.parts.parts
4489
- .filter((p) => !hides.has(p.name))
4490
- .map((p) => {
4491
- const rec = byName.get(p.name);
4492
- const pngName = rec === undefined ? p.name : `${alt.name}_${rec.name}`;
4493
- const box = rec ?? p;
4494
- return { name: p.name, from: box.from, x: box.x, y: box.y, image: readPng(join(inp.partsDir, `${pngName}.png`)) };
4495
- });
4523
+ const placed = setPlacements(inp.parts, alt, rigSlotOrder).map(({ name, png, box }) => ({ name, from: box.from, x: box.x, y: box.y, image: readPng(join(inp.partsDir, `${png}.png`)) }));
4496
4524
  const split = seamPairRows(altSeam, placed, inp.parts.rig_size, altStillSet.viewport);
4497
4525
  const altSeamDir = join(seamDir, alt.name);
4498
4526
  mkdirSync(altSeamDir, { recursive: true });
package/src/config.ts CHANGED
@@ -262,6 +262,13 @@ export interface AlternateSetConfig {
262
262
  drawn?: Record<string, number>;
263
263
  /** Explicit bone endpoints on this alternate painting, full source-crop pixels, x right/y down. */
264
264
  tips?: Record<string, Point>;
265
+ /**
266
+ * Issue #664: covered limb segment parts this set draws on their front slot
267
+ * (`<part>_front`, declared by `config.limbs.<limb>.front`) instead of the
268
+ * base slot, which the set hides. Absent, the set draws every covered part
269
+ * in its base slot.
270
+ */
271
+ front?: string[];
265
272
  }
266
273
 
267
274
  export interface Assemble {
@@ -935,6 +942,18 @@ export interface Limb {
935
942
  split?: LimbSplit;
936
943
  /** Explicit rig-stage adjacency; absent, the existing limb closure is unchanged. */
937
944
  layout?: LimbLayout;
945
+ /** Issue #664: a second, empty-at-setup slot per named segment part; absent, no slot is added and no byte moves. */
946
+ front?: LimbFront;
947
+ }
948
+
949
+ /**
950
+ * Issue #664: `parts` are this limb's own segment parts; each gets a slot
951
+ * `<part>_front` on its base slot's bone with no setup attachment, placed in the
952
+ * final setup slot order immediately after `after`'s whole slot family.
953
+ */
954
+ export interface LimbFront {
955
+ parts: string[];
956
+ after: string;
938
957
  }
939
958
 
940
959
  export type LimbLayoutTarget = { limb: string; part?: never } | { part: string; limb?: never };
@@ -2137,7 +2156,7 @@ function checkAlternates(
2137
2156
  const seenNames = new Map<string, number>();
2138
2157
  (v as Json[]).forEach((entry, i) => {
2139
2158
  const at = `${p}[${i}]`;
2140
- const e = c.object(at, entry, ['name'], ['source', 'full', 'head', 'parts', 'hides', 'head_box', 'cuts', 'skeleton', 'drawn', 'tips']);
2159
+ const e = c.object(at, entry, ['name'], ['source', 'full', 'head', 'parts', 'hides', 'head_box', 'cuts', 'skeleton', 'drawn', 'tips', 'front']);
2141
2160
  if (e === null) return;
2142
2161
  if ('name' in e && c.string(`${at}.name`, e.name)) {
2143
2162
  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`);
@@ -2228,6 +2247,27 @@ function checkAlternates(
2228
2247
  } else seenHides.add(hn);
2229
2248
  });
2230
2249
  }
2250
+ // Issue #664: a part the set draws on its front slot is one the set covers and a limb declares a front slot for.
2251
+ if ('front' in e) {
2252
+ if (!Array.isArray(e.front) || e.front.length === 0) {
2253
+ c.fail('CONFIG_SET_FRONT', `${at}.front`, `is ${show(e.front)}; a nonempty list of covered limb segment parts with a declared front slot is required`);
2254
+ } else {
2255
+ const seenFront = new Set<string>();
2256
+ (e.front as Json[]).forEach((fn, k) => {
2257
+ if (!c.string(`${at}.front[${k}]`, fn)) return;
2258
+ const declaredBy = limbs?.front.get(fn);
2259
+ const covered = 'parts' in e && seenParts.has(fn) && !seenHides.has(fn);
2260
+ if (seenFront.has(fn)) c.fail('CONFIG_SET_FRONT', `${at}.front[${k}]`, `repeats "${fn}"; each front part is named once`);
2261
+ else if (!covered) {
2262
+ c.fail('CONFIG_SET_FRONT', `${at}.front[${k}]`, `names "${fn}", which this set does not cover${'parts' in e ? ` (its parts less its hides: ${[...seenParts].filter((q) => !seenHides.has(q)).map((q) => `"${q}"`).join(', ') || 'none'})` : ' (a set without parts is a full set; front slots are for a subset set over a limb)'}; a set draws on a front slot only the parts it covers`);
2263
+ } else if (declaredBy === undefined) {
2264
+ const declared = [...(limbs?.front.keys() ?? [])].map((q) => `"${q}"`).join(', ') || 'none';
2265
+ c.fail('CONFIG_SET_FRONT', `${at}.front[${k}]`, `names "${fn}", which no config.limbs.<limb>.front.parts lists (front slots declared: ${declared}); declare the front slot on its limb first`);
2266
+ }
2267
+ seenFront.add(fn);
2268
+ });
2269
+ }
2270
+ }
2231
2271
  if ('parts' in e && limbs !== null) {
2232
2272
  for (const [limbName, chain] of limbs.chains) {
2233
2273
  const coveredSegs = chain.parts.filter((sp) => seenParts.has(sp) && !seenHides.has(sp));
@@ -2968,6 +3008,8 @@ interface LimbNames {
2968
3008
  parts: Map<string, { bone: string; at: string }>;
2969
3009
  consumed: Map<string, string>;
2970
3010
  chains: Map<string, { parts: string[]; bones: string[]; froms: string[] }>;
3011
+ /** Issue #664: each segment part a limb's `front.parts` names -> that limb. */
3012
+ front: Map<string, string>;
2971
3013
  }
2972
3014
 
2973
3015
  /**
@@ -2993,7 +3035,7 @@ interface LimbNames {
2993
3035
  * resolved. Returns the limb parts and the parts the limbs take.
2994
3036
  */
2995
3037
  function checkLimbs(c: Check, v: Json, made: { parts: string[]; patches: string[]; cuts: string[] }, names: { bones: Set<string>; parents: Map<string, string> } | null, resolveLayoutParts = true): LimbNames {
2996
- const out: LimbNames = { parts: new Map(), consumed: new Map(), chains: new Map() };
3038
+ const out: LimbNames = { parts: new Map(), consumed: new Map(), chains: new Map(), front: new Map() };
2997
3039
  if (!isPlainObject(v)) {
2998
3040
  c.fail('CONFIG_FIELD_TYPE', 'config.limbs', `is ${show(v)}; an object of limb name -> {"segments": [...]} is required`);
2999
3041
  return out;
@@ -3004,7 +3046,7 @@ function checkLimbs(c: Check, v: Json, made: { parts: string[]; patches: string[
3004
3046
  const splitLimbs: string[] = [];
3005
3047
  for (const [limb, spec] of Object.entries(v)) {
3006
3048
  const at = `config.limbs.${limb}`;
3007
- const o = c.object(at, spec, ['segments'], ['split', 'layout']);
3049
+ const o = c.object(at, spec, ['segments'], ['split', 'layout', 'front']);
3008
3050
  if (o === null) continue;
3009
3051
  if ('split' in o) {
3010
3052
  const sp = c.object(`${at}.split`, o.split, [], ['line', 'edge']);
@@ -3143,9 +3185,61 @@ function checkLimbs(c: Check, v: Json, made: { parts: string[]; patches: string[
3143
3185
  }
3144
3186
  }
3145
3187
  checkLimbLayouts(c, v, made, out, resolveLayoutParts);
3188
+ checkLimbFronts(c, v, made, out, resolveLayoutParts);
3146
3189
  return out;
3147
3190
  }
3148
3191
 
3192
+ /**
3193
+ * Issue #664: `config.limbs.<limb>.front` — `parts` a nonempty list of this
3194
+ * limb's own segment parts, each once (`CONFIG_FRONT_SCOPE`); `after` one
3195
+ * produced part, the same notion {@link checkLimbLayouts} holds a part target
3196
+ * to, and not a part of this limb (`CONFIG_FRONT_NAME`). A front slot and an
3197
+ * explicit layout are not composed: a config declaring both, on one limb or on
3198
+ * two, is refused (`CONFIG_FRONT_LAYOUT`).
3199
+ */
3200
+ function checkLimbFronts(c: Check, limbs: Record<string, Json>, made: { parts: string[]; patches: string[]; cuts: string[] }, names: LimbNames, resolveParts: boolean): void {
3201
+ const produced = new Set([...made.parts, ...made.patches, ...made.cuts].filter((n) => !names.consumed.has(n)));
3202
+ for (const n of names.parts.keys()) produced.add(n);
3203
+ const layouts = Object.entries(limbs).filter(([, raw]) => isPlainObject(raw) && 'layout' in raw).map(([l]) => l);
3204
+ for (const [limb, raw] of Object.entries(limbs)) {
3205
+ if (!isPlainObject(raw) || !('front' in raw)) continue;
3206
+ const at = `config.limbs.${limb}.front`;
3207
+ if (layouts.length > 0) {
3208
+ c.fail(
3209
+ 'CONFIG_FRONT_LAYOUT',
3210
+ at,
3211
+ `is declared while ${layouts.map((l) => `config.limbs.${l}.layout`).join(', ')} ${layouts.length === 1 ? 'is' : 'are'} declared; version 1 of front slots does not compose with an explicit limb layout (issue #647) — the layout's adjacency proof would have to move the front slots too — so declare one or the other on a rig`,
3212
+ );
3213
+ }
3214
+ const f = c.object(at, raw.front, ['parts', 'after'], []);
3215
+ if (f === null) continue;
3216
+ const own = names.chains.get(limb)?.parts ?? [];
3217
+ if ('parts' in f) {
3218
+ const ps = f.parts;
3219
+ if (!Array.isArray(ps) || ps.length === 0 || !ps.every((p) => typeof p === 'string' && own.includes(p))) {
3220
+ c.fail('CONFIG_FRONT_SCOPE', `${at}.parts`, `is ${show(ps)}; a nonempty list of this limb's own segment parts (${own.join(', ')}) is required — a front slot is a second slot for one of its segments`);
3221
+ } else if (new Set(ps).size !== ps.length) {
3222
+ c.fail('CONFIG_FRONT_SCOPE', `${at}.parts`, `is ${show(ps)}; each segment part is named once`);
3223
+ } else {
3224
+ for (const p of ps as string[]) {
3225
+ names.front.set(p, limb);
3226
+ // The front slot is named <part>_front; a part already made under that name would take the same slot name.
3227
+ if (produced.has(`${p}_front`)) c.fail('CONFIG_FRONT_NAME', `${at}.parts`, `names "${p}", whose front slot "${p}_front" is the name of a part this config already makes; rename that part, since a slot name is held once`);
3228
+ }
3229
+ }
3230
+ }
3231
+ if ('after' in f && c.string(`${at}.after`, f.after)) {
3232
+ const n = f.after;
3233
+ if (own.includes(n)) {
3234
+ c.fail('CONFIG_FRONT_NAME', `${at}.after`, `names "${n}", a segment part of this same limb; a front slot is placed after a part the limb is drawn behind, never after its own segment`);
3235
+ } else if (resolveParts && !produced.has(n)) {
3236
+ const consumed = names.consumed.get(n);
3237
+ c.fail('CONFIG_FRONT_NAME', `${at}.after`, `names "${n}"; a produced part (${[...produced].join(', ')}) is required${consumed === undefined ? '' : `; "${n}" is consumed by limb "${consumed}" into ${names.chains.get(consumed)?.parts.join(', ')}`}`);
3238
+ }
3239
+ }
3240
+ }
3241
+ }
3242
+
3149
3243
  /** Validate after every limb is known; a declaration may refer forward by name. */
3150
3244
  function checkLimbLayouts(c: Check, limbs: Record<string, Json>, made: { parts: string[]; patches: string[]; cuts: string[] }, names: LimbNames, resolveParts: boolean): void {
3151
3245
  const produced = new Set([...made.parts, ...made.patches, ...made.cuts].filter((n) => !names.consumed.has(n)));
@@ -0,0 +1,117 @@
1
+ /**
2
+ * The three config updates proposed by the CLI (issue #356). Pure JSON merge:
3
+ * no file reads/writes and no substitute for the stage's existing validator.
4
+ * A present proposal section replaces that whole field; an absent optional
5
+ * section is retained. The caller supplies the proposer's own section tuple,
6
+ * avoiding a second policy list or a runtime import of the proposer graph.
7
+ */
8
+ import type { PlanProposal } from './assemble.ts';
9
+ import type { HeadBoxProposal } from './headbox.ts';
10
+ import type { Proposal, PROPOSAL_CONFIG_SECTIONS } from './propose.ts';
11
+ import { PartsError } from './errors.ts';
12
+ import type { ConfigEdit } from './meshdraft.ts';
13
+
14
+ export type ConfigJson = null | boolean | number | string | ConfigJson[] | ConfigObject;
15
+ export interface ConfigObject { [key: string]: ConfigJson }
16
+ export type ConfigWritePatch =
17
+ | { kind: 'head-box'; head_box: HeadBoxProposal['head_box'] }
18
+ | { kind: 'assemble-plan'; plan: PlanProposal['plan']; extend_below_crop: PlanProposal['extend_below_crop'] }
19
+ | { kind: 'proposal'; proposal: Proposal; sections: typeof PROPOSAL_CONFIG_SECTIONS };
20
+ export interface ConfigWriteChange {
21
+ path: string;
22
+ kind: 'added' | 'replaced' | 'removed';
23
+ }
24
+ export interface ConfigWriteResult {
25
+ config: ConfigObject;
26
+ /** Semantic changes only, in destination key order, then new key order. */
27
+ changes: ConfigWriteChange[];
28
+ /** Whole owned values, applied by the same splicedEdits engine as cloth. */
29
+ edits: ConfigEdit[];
30
+ }
31
+ const own = (o: object, key: string): boolean => Object.prototype.hasOwnProperty.call(o, key);
32
+ const object = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);
33
+ function field(parent: string, key: string): string {
34
+ return /^[A-Za-z_][A-Za-z0-9_-]*$/.test(key) ? `${parent}${parent === '' ? '' : '.'}${key}` : `${parent}[${JSON.stringify(key)}]`;
35
+ }
36
+ function refuse(path: string, detail: string): never {
37
+ throw new PartsError([{ code: 'CONFIG_FIELD_TYPE', object: path, detail }]);
38
+ }
39
+ /** Clone JSON without dropping undefined, accepting non-finite numbers or following cycles. */
40
+ function clone(value: unknown, path: string, ancestors = new Set<object>()): ConfigJson {
41
+ if (value === null || typeof value === 'string' || typeof value === 'boolean') return value;
42
+ if (typeof value === 'number' && Number.isFinite(value)) return value;
43
+ if (typeof value !== 'object' || value === null) return refuse(path, `is ${typeof value}; a finite JSON value is required`);
44
+ if (ancestors.has(value)) return refuse(path, 'contains a cycle; JSON values cannot refer to their ancestors');
45
+ const proto = Object.getPrototypeOf(value);
46
+ if (!Array.isArray(value) && proto !== Object.prototype && proto !== null) return refuse(path, 'is not a plain JSON object');
47
+ ancestors.add(value);
48
+ let result: ConfigJson;
49
+ if (Array.isArray(value)) {
50
+ result = Array.from(value, (v, i) => clone(v, `${path}[${i}]`, ancestors));
51
+ } else {
52
+ // fromEntries keeps a JSON key named __proto__ as data, never as a setter.
53
+ result = Object.fromEntries(Object.entries(value).map(([k, v]) => [k, clone(v, field(path, k), ancestors)]));
54
+ }
55
+ ancestors.delete(value);
56
+ return result;
57
+ }
58
+ function equal(a: ConfigJson, b: ConfigJson): boolean {
59
+ if (a === b) return true;
60
+ if (Array.isArray(a) || Array.isArray(b)) return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((v, i) => equal(v, b[i]));
61
+ if (!object(a) || !object(b)) return false;
62
+ const ak = Object.keys(a), bk = Object.keys(b);
63
+ return ak.length === bk.length && ak.every((k) => own(b, k) && equal(a[k], b[k]));
64
+ }
65
+ function changes(before: ConfigObject, after: ConfigObject, parent = ''): ConfigWriteChange[] {
66
+ const result: ConfigWriteChange[] = [];
67
+ for (const [key, a] of Object.entries(before)) {
68
+ const path = field(parent, key);
69
+ if (!own(after, key)) result.push({ path, kind: 'removed' });
70
+ else if (!equal(a, after[key])) {
71
+ if (object(a) && object(after[key])) result.push(...changes(a, after[key] as ConfigObject, path));
72
+ else result.push({ path, kind: 'replaced' });
73
+ }
74
+ }
75
+ for (const key of Object.keys(after)) if (!own(before, key)) result.push({ path: field(parent, key), kind: 'added' });
76
+ return result;
77
+ }
78
+
79
+ /** The caller validates the returned candidate through its existing config door before saving it. */
80
+ export function mergeConfigProposal(raw: unknown, patch: ConfigWritePatch): ConfigWriteResult {
81
+ if (!object(raw)) return refuse('config', 'is not an object; an existing config JSON object is required');
82
+ const before = clone(raw, 'config') as ConfigObject;
83
+ const config = clone(before, 'config') as ConfigObject;
84
+ const edits: ConfigEdit[] = [];
85
+ switch (patch.kind) {
86
+ case 'head-box': {
87
+ if (!object(config.seethrough)) return refuse('config.seethrough', 'is absent or not an object; the existing See-through settings are required before writing head_box');
88
+ const previous = config.seethrough.head_box;
89
+ config.seethrough.head_box = clone(patch.head_box, 'proposal.head_box');
90
+ if (!equal(previous, config.seethrough.head_box)) edits.push({ path: ['seethrough', 'head_box'], value: config.seethrough.head_box });
91
+ break;
92
+ }
93
+ case 'assemble-plan': {
94
+ if (!object(config.assemble)) return refuse('config.assemble', 'is absent or not an object; the existing assembly settings are required before writing its plan');
95
+ const previousPlan = config.assemble.plan, previousExtend = config.assemble.extend_below_crop;
96
+ config.assemble.plan = clone(patch.plan, 'proposal.plan');
97
+ config.assemble.extend_below_crop = clone(patch.extend_below_crop, 'proposal.extend_below_crop');
98
+ if (!equal(previousPlan, config.assemble.plan)) edits.push({ path: ['assemble', 'plan'], value: config.assemble.plan });
99
+ if (!equal(previousExtend, config.assemble.extend_below_crop)) edits.push({ path: ['assemble', 'extend_below_crop'], value: config.assemble.extend_below_crop });
100
+ break;
101
+ }
102
+ case 'proposal': {
103
+ for (const key of patch.sections) {
104
+ // This is the caller's checked Proposal, with the proposer's own tuple.
105
+ // Optional absent fields are retained rather than erased by a narrower run.
106
+ if (patch.proposal[key] !== undefined) {
107
+ const previous = config[key];
108
+ config[key] = clone(patch.proposal[key], `proposal.${key}`);
109
+ if (!equal(previous, config[key])) edits.push({ path: [key], value: config[key] });
110
+ }
111
+ }
112
+ break;
113
+ }
114
+ default: return refuse('write-config', 'has no supported operation; head-box, assemble-plan or proposal is required');
115
+ }
116
+ return { config, changes: changes(before, config), edits };
117
+ }
@@ -32,6 +32,8 @@
32
32
  * write the same bytes.
33
33
  */
34
34
  import { type Problem, refuseIfAny } from './errors.ts';
35
+ import type { BoneEntry, Limb } from './config.ts';
36
+ import type { RigJoints } from './keypoints.ts';
35
37
  import { BASIS_KINDS, type BasisKind, type BoneBasis, type BoneCoverage, COVERAGE_OUTCOMES, coverageOutcome, expand, FRAME_KEYS, type FrameBasis, type FrameKey, type PartSet, type Placement, type Proposal, type ProposalBasis } from './propose.ts';
36
38
  import { BONE_ROLES, type BoneRole, compareStructure, readSkeleton } from './structure.ts';
37
39
 
@@ -175,8 +177,66 @@ export function basisLine(f: BasisFile, out: string): string {
175
177
  return `wrote ${BASIS_FILE} (${f.bones.length} bone record(s) by the basis of their origin: ${kinds}${cmp}) under ${out}`;
176
178
  }
177
179
 
180
+ /** The leg choice actually declared by the supplied proposal/config. Placement
181
+ * and coverage are distinct: selecting a chain never claims its links were checked.
182
+ */
183
+ export interface LegChainChoice {
184
+ chains: Array<{ chain: string; sources: string[]; parts: string[] }>;
185
+ /** Present when no chain was selected; null never stands for a guessed cause. */
186
+ none: string | null;
187
+ }
188
+
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
+ const chains: LegChainChoice['chains'] = [];
191
+ for (const entry of spec.bones) {
192
+ if (!('chain' in entry) || !/^leg_[rl]$/.test(entry.chain)) continue;
193
+ const links = new Set(entry.points.map((_, i) => `${entry.chain}${i}`));
194
+ const sources = new Set<string>();
195
+ const parts = new Set<string>();
196
+ for (const limb of Object.values(spec.limbs ?? {})) {
197
+ for (const segment of limb.segments) if (links.has(segment.bone)) {
198
+ sources.add(segment.from);
199
+ parts.add(segment.part);
200
+ }
201
+ }
202
+ const hasSourceBinding = sources.size > 0;
203
+ const bound = (part: string): void => {
204
+ parts.add(part);
205
+ if (!hasSourceBinding && P.recs.some((p) => p.name === part)) sources.add(part);
206
+ };
207
+ for (const [part, mesh] of Object.entries(spec.meshes)) {
208
+ if (mesh.segments.some((s) => typeof s === 'string' ? s === entry.chain || links.has(s) : links.has(s[0]))) bound(part);
209
+ }
210
+ for (const [part, bone] of Object.entries(spec.regions ?? {})) if (links.has(bone)) bound(part);
211
+ chains.push({ chain: entry.chain, sources: [...sources], parts: [...parts] });
212
+ }
213
+ if (chains.length > 0) return { chains, none: null };
214
+ if (joints === undefined) return { chains, none: 'no keypoints supplied; leg placement requires hip, knee and ankle positions' };
215
+ const recorded = spec.notes?.find((n) => n.includes(': no leg chain — '));
216
+ if (recorded !== undefined) return { chains, none: recorded };
217
+ const gaps: string[] = [];
218
+ for (const side of ['r', 'l'] as const) {
219
+ const missing = ([`${side}_hip`, `${side}_knee`, `${side}_ankle`] as const).filter((key) => joints.joints[key].at === null);
220
+ if (missing.length > 0) gaps.push(`${missing.join(', ')} ${missing.length === 1 ? 'has' : 'have'} no position`);
221
+ else {
222
+ const hip = joints.joints[`${side}_hip`].at as [number, number];
223
+ const knee = joints.joints[`${side}_knee`].at as [number, number];
224
+ if (hip[0] === knee[0] && hip[1] === knee[1]) gaps.push(`${side}_hip and ${side}_knee are one point; the thigh has no direction`);
225
+ }
226
+ }
227
+ if (gaps.length === 2) return { chains, none: gaps.join('; ') };
228
+ if (!P.byTag('legwear', undefined, true).some((p) => p.opaque_px > 500)) return { chains, none: 'no legwear part over 500 opaque px; the proposal declares no leg chain' };
229
+ return { chains, none: 'no leg_r or leg_l chain declared; the supplied spec records no leg-placement refusal' };
230
+ }
231
+
232
+ export function legChainChoiceLine(choice: LegChainChoice): string {
233
+ if (choice.chains.length === 0) return `coverage leg-chain choice: 0 chains — ${choice.none ?? 'no placement reason recorded'}`;
234
+ const named = (values: readonly string[]): string => values.map((v) => JSON.stringify(v)).join(', ');
235
+ return `coverage leg-chain choice: ${choice.chains.length} ${choice.chains.length === 1 ? 'chain' : 'chains'} — ${choice.chains.map((c) => `${c.chain}: source ${c.sources.length === 0 ? 'not recorded' : named(c.sources)}; parts ${c.parts.length === 0 ? 'none bound' : named(c.parts)}`).join(' | ')}; selection only, not a checked verdict`;
236
+ }
237
+
178
238
  /** One coverage line per bone, then the summary. Every line starts `coverage`. */
179
- export function coverageLines(coverage: readonly BoneCoverage[]): string[] {
239
+ export function coverageLines(coverage: readonly BoneCoverage[], legChoice?: LegChainChoice): string[] {
180
240
  const out: string[] = [];
181
241
  for (const c of coverage) {
182
242
  const role = c.role === null ? 'role not read' : c.role.role;
@@ -184,6 +244,7 @@ export function coverageLines(coverage: readonly BoneCoverage[]): string[] {
184
244
  if (outcome === 'not checked') out.push(`coverage ${c.bone} [${role}]: not checked — ${c.why.join('; ')}`);
185
245
  else out.push(`coverage ${c.bone} [${role}]: ${outcome} — read by ${c.read.join(', ')}${c.lint > 0 ? `; named by ${c.lint} LINT line(s)` : ''}`);
186
246
  }
247
+ if (legChoice !== undefined) out.push(legChainChoiceLine(legChoice));
187
248
  const by = (o: (typeof COVERAGE_OUTCOMES)[number]): number => coverage.filter((c) => coverageOutcome(c) === o).length;
188
249
  const roles: Record<BoneRole, number> = { target: 0, deforms: 0, control: 0, unclassified: 0 };
189
250
  let unread = 0;
package/src/errors.ts CHANGED
@@ -34,6 +34,18 @@ export function guidePointer(code: string): string {
34
34
  return ` (see rig-parts guide ${code})`;
35
35
  }
36
36
 
37
+ /**
38
+ * Complete only a bare relayed core compile refusal (issue #356). Current core
39
+ * names a guide rule; older callers may name the compile section or a child.
40
+ * Keep those pointers and all non-compile lines verbatim. The parts rule's
41
+ * outer pointer remains failLine's responsibility.
42
+ */
43
+ export function coreCompileGuideLine(line: string): string {
44
+ if (!/^\s*rigc compile error\b/.test(line) || /\(see rigc guide (?:§5\.1(?:\.\d+)*|[A-Z][A-Z0-9_]*)\)/.test(line)) return line;
45
+ const body = line.trimEnd();
46
+ return `${body} (see rigc guide §5.1)${line.slice(body.length)}`;
47
+ }
48
+
37
49
  /** A refusal as it is printed: ` FAIL RULE: object — detail (see rig-parts guide RULE)`. */
38
50
  export function failLine(p: Problem): string {
39
51
  return ` FAIL ${problemLine(p)}${guidePointer(p.code)}`;