@rig-c/parts 1.68.0 → 1.70.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/check.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { baseAnchorMoves, type AnchorRegion } from './baseanchor.ts';
1
2
  /**
2
3
  * The check stage: build a rig through rig-c, gate it under both
3
4
  * profiles, render its idle, and measure the two things the gate cannot see —
@@ -1379,6 +1380,25 @@ export function resolvePlacedAlpha(placements: readonly ReferencePlacement[], pa
1379
1380
  return { name: pl.name, from: pl.box.from, x: pl.box.x, y: pl.box.y, image: islands[pl.islandIndex] ?? raw };
1380
1381
  }
1381
1382
  return { name: pl.name, from: pl.box.from, x: pl.box.x, y: pl.box.y, image: raw };
1383
+ }).map(placed => {
1384
+ if (Number.isInteger(placed.x) && Number.isInteger(placed.y)) return placed;
1385
+ // Explicit anchored placement can be subpixel. Preserve premultiplied edge
1386
+ // colour while moving it onto the integer reference grid, never the PNG.
1387
+ const { image } = placed, premult = newFloatImage(image.width, image.height, 4);
1388
+ for (let i = 0; i < image.width * image.height; i++) {
1389
+ const alpha = image.data[i * 4 + 3];
1390
+ for (let c = 0; c < 3; c++) premult.data[i * 4 + c] = image.data[i * 4 + c] * alpha / 255;
1391
+ premult.data[i * 4 + 3] = alpha;
1392
+ }
1393
+ const x = Math.floor(placed.x) - 1, y = Math.floor(placed.y) - 1;
1394
+ const warped = warpAffine(premult, { sx: 1, sy: 1, tx: placed.x - x, ty: placed.y - y }, image.width + 2, image.height + 2, 'bilinear');
1395
+ const shifted = newRaster(warped.width, warped.height);
1396
+ for (let i = 0; i < shifted.width * shifted.height; i++) {
1397
+ const alpha = warped.data[i * 4 + 3];
1398
+ for (let c = 0; c < 3; c++) shifted.data[i * 4 + c] = alpha > 0 ? warped.data[i * 4 + c] * 255 / alpha : 0;
1399
+ shifted.data[i * 4 + 3] = alpha;
1400
+ }
1401
+ return { ...placed, x, y, image: shifted };
1382
1402
  });
1383
1403
  }
1384
1404
 
@@ -1545,6 +1565,29 @@ export function armSplitSetHint(parts: PartsFile, alt: AlternatePartsRecord): st
1545
1565
  return ` — the set covers a sleeve whose merged arm layer 1.37.0 split (issue #490), and it neither covers nor hides ${open.map((n) => `"${n}"`).join(', ')}, so the base draws ${open.length === 1 ? 'that part' : 'those parts'} beside the set's own art; a set made before 1.37.0 hides it: add ${open.map((n) => `"${n}"`).join(', ')} to the set's hides (see ${ARM_SPLIT_MIGRATION})`;
1546
1566
  }
1547
1567
 
1568
+ /** Expected placement from the authored rule and base, never the candidate alternate's offset. */
1569
+ export function baseAnchoredReference(parts: PartsFile, alt: AlternatePartsRecord, rig: Record<string, unknown>, drawn?: Record<string, number>): AlternatePartsRecord {
1570
+ if (alt.base_anchor === undefined) return alt;
1571
+ const posed = setupWorld(stillRigForSet(rig, alt, drawn ?? alt.drawn));
1572
+ const slots = new Map((Array.isArray(rig.slots) ? rig.slots : []).filter(isRecord).map(s => [String(s.name), String(s.bone)]));
1573
+ const skins = isRecord(rig.skins) && isRecord(rig.skins.default) ? rig.skins.default : {};
1574
+ const source = new Map<string, AnchorRegion>(), base = new Map<string, AnchorRegion>();
1575
+ for (const record of alt.records) {
1576
+ const slot = (alt.front ?? []).includes(record.name) ? `${record.name}${FRONT_SUFFIX}` : record.name;
1577
+ const bone = slots.get(slot), frame = bone === undefined ? undefined : posed.get(bone);
1578
+ const list = skins[record.name], original = isRecord(list) ? list[record.name] : null;
1579
+ if (bone === undefined || frame === undefined) continue;
1580
+ const local = toBoneLocal(frame, record.x + record.w / 2 - parts.rig_size[0] / 2, cropToSpineY(record.y + record.h / 2, parts.rig_size[1]));
1581
+ source.set(record.name, { bone, x: local[0], y: local[1] });
1582
+ if (isRecord(original) && typeof original.x === 'number' && typeof original.y === 'number' && (original.type === undefined || original.type === 'region')) base.set(record.name, { bone, x: original.x, y: original.y });
1583
+ }
1584
+ const moves = baseAnchorMoves(alt.base_anchor, base, source, posed);
1585
+ return { ...alt, records: alt.records.map(record => {
1586
+ const move = moves.get(record.name);
1587
+ return move === undefined ? record : { ...record, x: record.x + move.world[0], y: record.y - move.world[1] };
1588
+ }) };
1589
+ }
1590
+
1548
1591
  /**
1549
1592
  * The flat stack of parts for an alternate set (issue #454), in the order
1550
1593
  * {@link setPlacements} gives: with `slotOrder`, a front part (issue #664) is
@@ -6349,7 +6392,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
6349
6392
  writeFileSync(join(dir, 'motion.json'), JSON.stringify({ ...inp.motion, animations: setStillAnimations }));
6350
6393
  const built = rigc(['build', '--rig', join(dir, 'rig.json'), '--motion', join(dir, 'motion.json'), '--out', join(dir, 'build'), '--profile', 'spine']);
6351
6394
  if (built.status !== 0) refuseIfAny(rigcFailed(`build (the setup-pose still of set "${alt.name}")`, built, buildGateLines(built.out)));
6352
- return { alt, dir };
6395
+ return { alt, reference: baseAnchoredReference(inp.parts!, alt, inp.rig, drawn), dir };
6353
6396
  });
6354
6397
  const states: SeamStateBounds[] = [seamStateBounds(join(stillDir, 'build'), 'base')];
6355
6398
  for (const { alt, dir } of staged) states.push(seamStateBounds(join(dir, 'build'), alt.name));
@@ -6382,15 +6425,15 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
6382
6425
  }
6383
6426
  if (set !== undefined || allSets) {
6384
6427
  const baseSupport = seamSupport(join(stillDir, 'build'), join(stillDir, 'rig.json'), canonicalSet, placed, seamStacks, inp.stage);
6385
- for (const { alt, dir: setDir } of staged) {
6428
+ for (const { alt, reference, dir: setDir } of staged) {
6386
6429
  const asr = rigc(['render', '--candidate', join(setDir, 'build'), '--animation', 'still', '--fps', String(STILL_FPS), '--max', String(maxSide), '--out', join(setDir, 'render')]);
6387
6430
  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'))));
6388
6431
  const altStillSet = readFrameSet(join(setDir, 'render'));
6389
6432
  if (keepStills) cpSync(join(setDir, 'render'), join(out, 'setup_still_auto', alt.name), { recursive: true });
6390
- const altComposite = flatCompositeForSet(inp.parts, alt, inp.partsDir, altStillSet.background, rigSlotOrder);
6433
+ const altComposite = flatCompositeForSet(inp.parts, reference, inp.partsDir, altStillSet.background, rigSlotOrder);
6391
6434
  const altCanonical = canonical(join(setDir, 'build'), join(setDir, 'seam'));
6392
6435
  if (keepStills) cpSync(join(setDir, 'seam'), join(keptDir, alt.name), { recursive: true });
6393
- const altPlaced = resolvePlacedAlpha(setPlacements(inp.parts, alt, rigSlotOrder), inp.partsDir);
6436
+ const altPlaced = resolvePlacedAlpha(setPlacements(inp.parts, reference, rigSlotOrder), inp.partsDir);
6394
6437
  const altSupport = seamSupport(join(setDir, 'build'), join(setDir, 'rig.json'), altCanonical, altPlaced, seamStacks, inp.stage);
6395
6438
  const effects = seamEffectSelection(baseSupport, altSupport);
6396
6439
  const autoAltSeam = seamFigures(altComposite, altStillSet.frames[0].image, inp.stage, altStillSet.viewport, altStillSet.background, undefined, alt.scene !== undefined);
package/src/config.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { baseAnchorProblems, type BaseAnchor } from './baseanchor.ts';
1
2
  import type { DepthConfig } from './depthsheets.ts';
2
3
  /**
3
4
  * The character config: everything character-specific the CPU stages read,
@@ -267,6 +268,8 @@ export interface Cut {
267
268
 
268
269
  export interface AlternateSetConfig {
269
270
  name: string;
271
+ /** Opt-in base region offsets on explicitly selected local axes, with paired painting patches. */
272
+ base_anchor?: BaseAnchor;
270
273
  /** Authored point on this painting, x right/y down; omitted means no focus. */
271
274
  focus?: Point;
272
275
  source?: string;
@@ -1039,7 +1042,18 @@ export type LimbLayout = { parts?: string[] } & (
1039
1042
  { before: LimbLayoutTarget; after?: never } | { after: LimbLayoutTarget; before?: never }
1040
1043
  );
1041
1044
 
1045
+ export interface WaistDeclaration {
1046
+ top: string;
1047
+ bottom: string;
1048
+ upper: string;
1049
+ lower: string;
1050
+ bone: string;
1051
+ constraint: string;
1052
+ }
1053
+
1042
1054
  export interface CharacterConfig {
1055
+ /** Explicit shared-waist construction. Absent, no pair is detected or altered. */
1056
+ waist?: WaistDeclaration;
1043
1057
  depth?: DepthConfig;
1044
1058
  key: string;
1045
1059
  note?: string;
@@ -1401,7 +1415,7 @@ export interface AssembleConfig {
1401
1415
  proposed_rig_scale?: number;
1402
1416
  }
1403
1417
 
1404
- const TOP_KEYS = ['key', 'generation', 'seethrough', 'assemble', 'limbs', 'bones', 'meshes', 'regions', 'motion', 'constraints', 'stops', 'turn', 'scene', 'cloth', 'proposed_rig_scale', 'requirements', 'motion_seams', 'depth'] as const;
1418
+ const TOP_KEYS = ['key', 'generation', 'seethrough', 'assemble', 'limbs', 'bones', 'meshes', 'regions', 'motion', 'constraints', 'stops', 'turn', 'scene', 'cloth', 'proposed_rig_scale', 'requirements', 'motion_seams', 'depth', 'waist'] as const;
1405
1419
 
1406
1420
  /**
1407
1421
  * The one partial entry point. It validates exactly what its door requires —
@@ -1433,6 +1447,7 @@ function parseEarlyConfigFrom(raw: Json, door: EarlyDoor, base: string | null):
1433
1447
  if (top === null) refuseIfAny(c.problems);
1434
1448
  const t = top as Record<string, Json>;
1435
1449
  if ('depth' in t) checkDepthConfig(c, t.depth);
1450
+ if ('waist' in t) checkWaistDeclaration(c, t.waist);
1436
1451
  if ('key' in t) c.string('config.key', t.key);
1437
1452
  if ('generation' in t) checkGeneration(c, t.generation);
1438
1453
  else if (needed.includes('generation')) {
@@ -1657,6 +1672,7 @@ function parseConfigFrom(raw: Json, base: string | null): { config: CharacterCon
1657
1672
  if (top === null) refuseIfAny(c.problems);
1658
1673
  const t = top as Record<string, Json>;
1659
1674
  if ('depth' in t) checkDepthConfig(c, t.depth);
1675
+ if ('waist' in t) checkWaistDeclaration(c, t.waist);
1660
1676
  if ('key' in t) c.string('config.key', t.key);
1661
1677
  if ('generation' in t) checkGeneration(c, t.generation);
1662
1678
  if ('seethrough' in t) checkSeeThrough(c, t.seethrough);
@@ -1673,6 +1689,11 @@ function parseConfigFrom(raw: Json, base: string | null): { config: CharacterCon
1673
1689
  if ('motion' in t) checkMotion(c, t.motion, names.bones, names.chains, 'regions' in t ? t.regions : undefined);
1674
1690
  if ('constraints' in t) checkConstraints(c, t.constraints, names.bones, names.parents);
1675
1691
  if ('stops' in t) checkStops(c, t.stops, names.bones, names.chains);
1692
+ if ('waist' in t && isPlainObject(t.waist)) {
1693
+ for (const field of ['upper', 'lower'] as const) if (typeof t.waist[field] === 'string' && !names.bones.has(t.waist[field])) c.fail('CONFIG_WAIST_BINDING', `config.waist.${field}`, `names ${JSON.stringify(t.waist[field])}; a declared bone is required`);
1694
+ for (const [field, map] of [['top', t.meshes], ['bottom', t.regions]] as const) if (typeof t.waist[field] === 'string' && (!isPlainObject(map) || !Object.hasOwn(map, t.waist[field]))) c.fail('CONFIG_WAIST_BINDING', `config.waist.${field}`, `names ${JSON.stringify(t.waist[field])}; ${field === 'top' ? 'a declared mesh' : 'a declared region'} is required`);
1695
+ if (typeof t.waist.bone === 'string' && names.bones.has(t.waist.bone)) c.fail('CONFIG_WAIST_NAME_FREE', 'config.waist.bone', `bone ${JSON.stringify(t.waist.bone)} already exists; an unused generated name is required`);
1696
+ }
1676
1697
  const attached = attachedParts(t.meshes, t.regions);
1677
1698
  if ('motion_seams' in t) c.problems.push(...motionSeamProblems(t.motion_seams, attached, 'config.motion_seams', 'CONFIG_MOTION_SEAM'));
1678
1699
  const hasAltFace = hasAlternateFaceSet(t.assemble, [...parts, ...cuts]);
@@ -2267,7 +2288,7 @@ function checkAlternates(
2267
2288
  const seenNames = new Map<string, number>();
2268
2289
  (v as Json[]).forEach((entry, i) => {
2269
2290
  const at = `${p}[${i}]`;
2270
- const e = c.object(at, entry, ['name'], ['source', 'full', 'head', 'parts', 'hides', 'head_box', 'cuts', 'skeleton', 'anchor', 'drawn', 'tips', 'front', 'layers', 'focus']);
2291
+ const e = c.object(at, entry, ['name'], ['source', 'full', 'head', 'parts', 'hides', 'head_box', 'cuts', 'skeleton', 'anchor', 'drawn', 'tips', 'front', 'layers', 'focus', 'base_anchor']);
2271
2292
  if (e === null) return;
2272
2293
  if ('name' in e && c.string(`${at}.name`, e.name)) {
2273
2294
  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`);
@@ -2380,6 +2401,7 @@ function checkAlternates(
2380
2401
  if (typeof layer !== 'string' || readLayerTag(layer) === null) c.fail('CONFIG_TAG_KNOWN', path, `is ${show(layer)}; a See-through v3 tag or "${AUTHOR_PREFIX}<label>" is required; ${AUTHOR_LABEL_RULE}`);
2381
2402
  }
2382
2403
  }
2404
+ if ('base_anchor' in e) c.problems.push(...baseAnchorProblems(e.base_anchor, `${at}.base_anchor`, new Set([...('parts' in e ? seenParts : baseSlots)].filter(n => !seenHides.has(n))), new Set(made.patches), isPlainObject(regions) ? new Set(Object.keys(regions).filter(n => !isPlainObject(meshes) || !Object.hasOwn(meshes, n))) : undefined));
2383
2405
  // Issue #664: a part the set draws on its front slot is one the set covers and a limb declares a front slot for.
2384
2406
  if ('front' in e) {
2385
2407
  if (!Array.isArray(e.front) || e.front.length === 0) {
@@ -4132,6 +4154,7 @@ export function loadClothConfig(path: string): { key: string; cloth: ClothRecipe
4132
4154
  if (top === null) refuseIfAny(c.problems);
4133
4155
  const t = top as Record<string, Json>;
4134
4156
  if ('depth' in t) checkDepthConfig(c, t.depth);
4157
+ if ('waist' in t) checkWaistDeclaration(c, t.waist);
4135
4158
  if ('key' in t) c.string('config.key', t.key);
4136
4159
  if ('cloth' in t) checkCloth(c, t.cloth);
4137
4160
  refuseIfAny(c.problems);
@@ -4598,3 +4621,12 @@ function checkDepthConfig(c: Check, raw: Json): void {
4598
4621
  if ('atlas' in q && isPlainObject(q.layers) && Object.keys(q.layers).length > 0) c.fail('DEPTH_SOURCE_AMBIGUOUS', path, 'declares canvas and per-layer sheets together; choose one fallback explicitly');
4599
4622
  }
4600
4623
  }
4624
+
4625
+ /** The operation has no implicit selector, fitted position or tuning coefficient. */
4626
+ function checkWaistDeclaration(c: Check, raw: Json): void {
4627
+ const fields = ['top', 'bottom', 'upper', 'lower', 'bone', 'constraint'] as const;
4628
+ const o = c.object('config.waist', raw, ['top', 'bottom', 'upper', 'lower', 'bone', 'constraint'], []);
4629
+ if (o === null) return;
4630
+ for (const field of fields) if (field in o) c.string(`config.waist.${field}`, o[field]);
4631
+ for (const [a, b] of [['top', 'bottom'], ['upper', 'lower']] as const) if (typeof o[a] === 'string' && o[a] === o[b]) c.fail('CONFIG_WAIST_BINDING', `config.waist.${a}`, `matches ${b} ${JSON.stringify(o[b])}; two distinct names are required`);
4632
+ }
package/src/mesh.ts CHANGED
@@ -336,6 +336,12 @@ export function artCoverage(mesh: Pick<LatticeMesh, 'vertices' | 'triangles'>, a
336
336
  * still not one closed outline after the passes is refused rather than handed on.
337
337
  */
338
338
  export function latticeMesh(part: string, art: Mask, grid: number, maxPasses: number = ONE_LOOP_PASSES): LatticeMesh | Problem {
339
+ return latticeMeshRows(part, art, grid, [], maxPasses);
340
+ }
341
+
342
+ /** Refine the original kept cells at supplied image rows; no new mask/bridge decision or omitted cell. */
343
+ export function latticeMeshRows(part: string, art: Mask, grid: number, rows: readonly number[], maxPasses: number = ONE_LOOP_PASSES): LatticeMesh | Problem {
344
+ if (rows.some((y) => !Number.isFinite(y))) return { code: 'RIG_LATTICE_STATION', object: `mesh "${part}"`, detail: `station rows [${rows.join(', ')}] include a non-finite coordinate; supplied finite image rows are required` };
339
345
  const lattice = latticeCells(art, grid);
340
346
  let any = false;
341
347
  for (let i = 0; i < lattice.cells.data.length && !any; i++) any = lattice.cells.data[i] !== 0;
@@ -347,7 +353,20 @@ export function latticeMesh(part: string, art: Mask, grid: number, maxPasses: nu
347
353
  };
348
354
  }
349
355
  const loop = oneLoop(lattice.cells, maxPasses);
350
- const mesh = triangulate(lattice, loop.cells, loop.passes);
356
+ let refined = lattice;
357
+ let kept = loop.cells;
358
+ const extra = rows.filter((y) => y > 0 && y < art.height && !lattice.ys.includes(y));
359
+ if (extra.length > 0) {
360
+ const ys = [...new Set([...lattice.ys, ...extra])].sort((a, b) => a - b);
361
+ kept = newMask(lattice.nx, ys.length - 1);
362
+ let originalRow = 0;
363
+ for (let j = 0; j < ys.length - 1; j++) {
364
+ while (originalRow + 1 < lattice.ny && ys[j] >= lattice.ys[originalRow + 1]) originalRow++;
365
+ kept.data.set(loop.cells.data.subarray(originalRow * lattice.nx, (originalRow + 1) * lattice.nx), j * lattice.nx);
366
+ }
367
+ refined = { ...lattice, ys, ny: ys.length - 1, cells: kept };
368
+ }
369
+ const mesh = triangulate(refined, kept, loop.passes);
351
370
  if (mesh.loops !== 1 || mesh.pinchedVertices !== 0) {
352
371
  return {
353
372
  code: 'RIG_LATTICE_ONE_LOOP',
package/src/parts.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { baseAnchorProblems, orderedBaseAnchor, type BaseAnchor } from './baseanchor.ts';
1
2
  import { partDepthProblems, type PartDepthReference } from './depthsheets.ts';
2
3
  /**
3
4
  * The output contract of the assemble stage: `parts.json`, one record per
@@ -305,6 +306,7 @@ export interface RecompositeRecord {
305
306
  }
306
307
 
307
308
  export interface AlternateSetMap {
309
+ base_anchor?: BaseAnchor;
308
310
  /** Authored point in setup-world coordinates, only when supplied (issue #719). */
309
311
  focus?: [number, number];
310
312
  slots: Record<string, string>;
@@ -325,6 +327,7 @@ export const FRONT_SUFFIX = '_front';
325
327
 
326
328
  export interface AlternatePartsRecord {
327
329
  name: string;
330
+ base_anchor?: BaseAnchor;
328
331
  /** Original authored painting point and its source size, only when supplied. */
329
332
  focus?: [number, number];
330
333
  focus_source_size?: [number, number];
@@ -492,6 +495,7 @@ export function serializeParts(file: PartsFile): string {
492
495
  : {
493
496
  alternates: file.alternates.map((a) => ({
494
497
  name: a.name,
498
+ ...(a.base_anchor === undefined ? {} : { base_anchor: orderedBaseAnchor(a.base_anchor) }),
495
499
  ...(a.parts === undefined ? {} : { parts: a.parts }),
496
500
  ...(a.hides === undefined ? {} : { hides: a.hides }),
497
501
  ...(a.front === undefined ? {} : { front: a.front }),
@@ -702,6 +706,11 @@ function checkParts(raw: unknown, path: string): PartsFile {
702
706
  if (typeof a !== 'object' || a === null || Array.isArray(a)) return;
703
707
  const set = a as Record<string, unknown>;
704
708
  const at = `${path} alternates[${i}]${typeof set.name === 'string' ? ` (set "${set.name}")` : ''}`;
709
+ if ('base_anchor' in set) {
710
+ const names = new Set(Array.isArray(set.records) ? set.records.flatMap(v => typeof v === 'object' && v !== null && typeof v.name === 'string' ? [v.name] : []) : []);
711
+ const patches = new Set(Array.isArray(set.records) ? set.records.flatMap(v => typeof v === 'object' && v !== null && typeof v.name === 'string' && typeof v.from === 'string' && v.from.startsWith('painting:') ? [v.name] : []) : []);
712
+ problems.push(...baseAnchorProblems(set.base_anchor, `${at}.base_anchor`, names, patches, undefined, 'PARTS_ALT_BASE_ANCHOR'));
713
+ }
705
714
  if (sizeOk && typeof scale === 'number') problems.push(...recordedFocusProblems(set, `${at}.focus`, size as number[], scale));
706
715
  if ('tips' in set || 'tips_source_size' in set) {
707
716
  const sourceSize = set.tips_source_size;