@rig-c/parts 2.44.0 → 2.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,8 +1,12 @@
1
1
  {
2
2
  "name": "@rig-c/parts",
3
- "version": "2.44.0",
3
+ "version": "2.46.0",
4
4
  "description": "AI-authored 2D character parts from one anime painting and its See-through layer decomposition: measured parts, weighted-mesh rig specs, verified through rig-c before anything is written. A CLI for agents that cannot see the image.",
5
5
  "type": "module",
6
+ "exports": {
7
+ "./assembly-reading": "./src/assembly-reading.ts",
8
+ "./*": "./*"
9
+ },
6
10
  "bin": {
7
11
  "rig-parts": "./bin/rig-parts.cjs",
8
12
  "spine-parts": "./bin/rig-parts.cjs"
package/src/assemble.ts CHANGED
@@ -4882,7 +4882,8 @@ function cutLimbs(
4882
4882
  const art = (x: number, y: number): boolean => x >= 0 && y >= 0 && x < W && y < H && own[y * W + x] === li && source.r.data[(y * W + x) * 4 + 3] > OPAQUE_ALPHA_ABOVE;
4883
4883
  const run = limbRun(line, art, [0, 0, W - 1, H - 1]);
4884
4884
  if (run === null && emptyTargets?.has(sg.hybrid.part)) return;
4885
- const width = sg.hybrid.width ?? (run === null ? 0 : 2 * halfWidthAbout(run));
4885
+ const measuredWidth = run === null ? 0 : 2 * halfWidthAbout(run);
4886
+ const width = sg.hybrid.width ?? measuredWidth;
4886
4887
  const upper = places.get(segs[k - 1].bone) as BonePlace;
4887
4888
  const lower = places.get(sg.bone) as BonePlace;
4888
4889
  const reach = (p: readonly number[]): number => Math.abs((p[0] - line.at[0]) * line.axis[0] + (p[1] - line.at[1]) * line.axis[1]);
@@ -4923,7 +4924,11 @@ function cutLimbs(
4923
4924
  if (along < width / 2) { rasters[loAt].data.fill(0, p * 4, p * 4 + 4); regions[loAt].data[p] = 0; }
4924
4925
  }
4925
4926
  const base = parts[loAt].record;
4926
- const geometry = { upper: segs[k - 1].bone, width, radius: (base.cap as CapRecord).radius, at: [...line.at] as [number, number], axis: [...line.axis] as [number, number] };
4927
+ const geometry = {
4928
+ upper: segs[k - 1].bone, width, measured_width: measuredWidth,
4929
+ radius: (base.cap as CapRecord).radius,
4930
+ at: [...line.at] as [number, number], axis: [...line.axis] as [number, number],
4931
+ };
4927
4932
  delete base.cap;
4928
4933
  base.hybrid = { part: sg.hybrid.part, ...geometry };
4929
4934
  capFrom[loAt] = null;
@@ -0,0 +1,267 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readFileSync, statSync } from 'node:fs';
3
+ import { dirname, resolve } from 'node:path';
4
+ import { authoredUnitDepths } from './authoredunit.ts';
5
+ import { isDoorKey, loadEarlyConfig, turnMovingPartPair, type AssembleConfig, type CharacterConfig, type Cut } from './config.ts';
6
+ import type { DepthRunConfig, UserDepthSheet } from './depthsheets.ts';
7
+ import { PartsError, refuseIfAny } from './errors.ts';
8
+ import { readWrapperLayers } from './layers.ts';
9
+ import { bonePlaces } from './limbs.ts';
10
+ import type { AssemblyConfigRecord, PartsFile } from './parts.ts';
11
+ import { PLATE_RECEIPT_FILE, verifyPlateReceipt } from './plate.ts';
12
+ import { isSkeletonName } from './skeleton.ts';
13
+ import { setupPaintingFilePath, type SetupPainting } from './setuppainting.ts';
14
+ import { DEFAULT_GROUND, DEFAULT_PROJECT_RULE, type ProjectRule } from './projectrule.ts';
15
+ import { DEFAULT_SEAM_RULE, type SeamRule } from './seamrule.ts';
16
+ import { readRequirements } from './requirements.ts';
17
+
18
+ type AssemblySource = Omit<AssembleConfig, 'seethrough'> & Partial<Pick<AssembleConfig, 'seethrough'>> & Pick<CharacterConfig, 'generation'>;
19
+
20
+ export interface AssemblyRules {
21
+ seam?: SeamRule;
22
+ project?: ProjectRule;
23
+ }
24
+
25
+ export function effectiveAssemblyRules(config: AssemblyRules, overrides: AssemblyRules = {}): Required<AssemblyRules> {
26
+ return { seam: overrides.seam ?? config.seam ?? DEFAULT_SEAM_RULE, project: overrides.project ?? config.project ?? DEFAULT_PROJECT_RULE };
27
+ }
28
+
29
+ const sha256 = (text: string | Uint8Array): string => createHash('sha256').update(text).digest('hex');
30
+
31
+ function fileBytes(path: string, field: string): Buffer {
32
+ try {
33
+ if (statSync(path).isFile()) return readFileSync(path);
34
+ } catch {
35
+ // Give callers the same named refusal for missing and unreadable files.
36
+ }
37
+ throw new PartsError([{ code: 'CONFIG_FILE_PRESENT', object: `config.${field}`, detail: `names ${path}; a readable file is required` }]);
38
+ }
39
+
40
+ function layerRunDigest(path: string, field: string): unknown {
41
+ if (/\.psd$/i.test(path)) return sha256(fileBytes(path, field));
42
+ const run = readWrapperLayers(path);
43
+ return {
44
+ manifest: sha256(fileBytes(run.source, field)),
45
+ // Wrapper layers always retain a file. PSD files are handled above.
46
+ layers: [...run.layers, ...run.hidden].map(layer => sha256(fileBytes(layer.file!, field))),
47
+ };
48
+ }
49
+
50
+ function plateDigest(path: string, field: string): string {
51
+ const receipt = resolve(path, PLATE_RECEIPT_FILE);
52
+ const bytes = fileBytes(receipt, field);
53
+ refuseIfAny(verifyPlateReceipt(receipt));
54
+ return sha256(bytes);
55
+ }
56
+
57
+ // These maps use authored part, bone or layer names as keys, independently
58
+ // of the loader's metadata spelling for structural fields.
59
+ const authoredKeyMaps = new Set(['layers', 'tips', 'drawn', 'base_anchor']);
60
+
61
+ function canonical(value: unknown, authoredKeys = false): unknown {
62
+ if (Array.isArray(value)) return value.map(entry => canonical(entry));
63
+ if (value !== null && typeof value === 'object') {
64
+ const fields = value as Record<string, unknown>;
65
+ const keys = Object.keys(fields).filter(key => authoredKeys || !isDoorKey(key)).sort();
66
+ return Object.fromEntries(keys.map(key => [key, canonical(fields[key], !authoredKeys && authoredKeyMaps.has(key))]));
67
+ }
68
+ return value;
69
+ }
70
+
71
+ function movingPairs(cfg: AssemblySource, names: readonly string[]): Array<[string, string]> {
72
+ const moves = turnMovingPartPair(cfg);
73
+ if (moves === null) return [];
74
+ return names.flatMap((a, i) => names.slice(i + 1).filter(b => moves(a, b)).map((b): [string, string] => [a, b]));
75
+ }
76
+
77
+ /** Config values consumed by assembly, evaluated against the assembled names and run shape. */
78
+ export function readAssemblyConfig(
79
+ cfg: AssemblySource, parts: PartsFile, configPath: string, overrides?: AssemblyRules,
80
+ ): AssemblyConfigRecord {
81
+ const { seam, project } = effectiveAssemblyRules(cfg.assemble, overrides);
82
+ const ground = project === 'visible' ? cfg.assemble.ground ?? DEFAULT_GROUND : DEFAULT_GROUND;
83
+ const base = dirname(resolve(configPath));
84
+ const file = (path: string | undefined, field: string): string | undefined =>
85
+ path === undefined ? undefined : sha256(fileBytes(resolve(base, path), field));
86
+ const run = (path: string | undefined, field: string): unknown =>
87
+ path === undefined ? undefined : layerRunDigest(resolve(base, path), field);
88
+ const plate = (path: string | undefined, field: string): string | undefined =>
89
+ path === undefined ? undefined : plateDigest(resolve(base, path), field);
90
+ const cuts = (entries: Cut[] | undefined, field: string): unknown => entries?.length
91
+ ? entries.map((cut, i) => ({
92
+ ...cut,
93
+ under: typeof cut.under === 'string' ? file(cut.under, `${field}[${i}].under`)
94
+ : cut.under === undefined ? undefined : { plate: plate(cut.under.plate, `${field}[${i}].under.plate`) },
95
+ }))
96
+ : undefined;
97
+ const sheet = (value: UserDepthSheet, field: string): unknown => ({ ...value, image: file(value.image, field) });
98
+ const depthRun = (value: DepthRunConfig | undefined, field: string): unknown => value === undefined ? undefined : ({
99
+ atlas: value.atlas === undefined ? undefined : sheet(value.atlas, `${field}.atlas.image`),
100
+ layers: value.layers === undefined ? undefined : Object.fromEntries(Object.entries(value.layers)
101
+ .map(([name, layer]) => [name, sheet(layer, `${field}.layers.${name}.image`)])),
102
+ });
103
+ const skeleton = cfg.generation?.control?.skeleton;
104
+ const requirementsPath = ground === 'busy' && cfg.requirements !== undefined
105
+ ? resolve(base, cfg.requirements) : undefined;
106
+ const setup = requirementsPath === undefined ? undefined : readRequirements(requirementsPath).setup_painting;
107
+ const setupImage = (declaration: SetupPainting['figure_mask'] | SetupPainting['backdrop'], field: string) =>
108
+ declaration === undefined ? undefined : {
109
+ ...declaration,
110
+ path: sha256(fileBytes(setupPaintingFilePath(requirementsPath!, declaration.path), `requirements.setup_painting.${field}.path`)),
111
+ };
112
+ const edited = cfg.assemble.edited_parts;
113
+ const names = [...new Set([
114
+ ...parts.parts.map(part => part.name),
115
+ ...(parts.alternates ?? []).flatMap(set => set.records.map(part => part.name)),
116
+ ...(cfg.assemble.cuts ?? []).map(cut => cut.into),
117
+ ...(cfg.assemble.patches ?? []).map(patch => patch.name),
118
+ ...cfg.assemble.plan.map(([name]) => name),
119
+ ])].sort();
120
+ const basePairs = movingPairs({ ...cfg, constraints: undefined }, names);
121
+ const baseSet = new Set(basePairs.map(pair => JSON.stringify(pair)));
122
+ const physicsPairs = movingPairs(cfg, names).filter(pair => !baseSet.has(JSON.stringify(pair)));
123
+ const { resolution, head_box, arm_split } = cfg.seethrough ?? {};
124
+ const hasHeadRun = Object.keys(parts.ghost_px).some(name => name.startsWith('head:'));
125
+ const frontParts = new Set((cfg.assemble.alternates ?? []).flatMap(set => set.front ?? []));
126
+ const bands = [
127
+ { name: null, records: parts.parts },
128
+ ...(parts.alternates ?? []).map(({ name, records }) => ({ name, records })),
129
+ ];
130
+ const hybridWidths = new Map<string, Array<{ set: string | null; width?: number }>>();
131
+ const limbs = Object.entries(cfg.limbs ?? {}).map(([name, { segments, split, front }]) => {
132
+ const activeFront = front?.parts.filter(part => frontParts.has(part)) ?? [];
133
+ const resolvedSegments = segments.map(({ hybrid, ...declared }, i) => {
134
+ const segment = { ...declared, cap: file(declared.cap, `limbs.${name}.segments[${i}].cap`) };
135
+ if (hybrid === undefined) return segment;
136
+ hybridWidths.set(hybrid.part, bands.flatMap(({ name: set, records }) => {
137
+ const band = records.find(record => record.name === hybrid.part)?.limb?.band;
138
+ return band === undefined ? [] : [{ set, width: hybrid.width ?? band.measured_width }];
139
+ }));
140
+ return { ...segment, hybrid: { part: hybrid.part } };
141
+ });
142
+ return [name, {
143
+ segments: resolvedSegments,
144
+ split,
145
+ front: front !== undefined && activeFront.length > 0 ? { parts: activeFront, after: front.after } : undefined,
146
+ }] as const;
147
+ });
148
+ const limbBones = new Set(limbs.flatMap(([, limb]) => limb.segments.map(segment => segment.bone)));
149
+ const alternateBones = new Set((cfg.assemble.alternates ?? []).flatMap(set => Object.keys(set.tips ?? {})));
150
+ const posesAlternate = limbs.length > 0 && cfg.assemble.alternates?.some(set => set.drawn !== undefined || set.skeleton !== undefined);
151
+ const geometry = limbBones.size === 0 && alternateBones.size === 0 ? [] : [...bonePlaces(cfg.bones ?? [])]
152
+ .filter(([name]) => limbBones.has(name) || alternateBones.has(name));
153
+ // Alternate skeleton and drawn registration also use the hierarchy.
154
+ const bones = posesAlternate ? cfg.bones : geometry.length === 0 ? undefined : geometry;
155
+ const assemble = {
156
+ ...cfg.assemble,
157
+ ground,
158
+ project,
159
+ seam,
160
+ extend_below_crop: cfg.assemble.extend_below_crop?.length ? cfg.assemble.extend_below_crop : undefined,
161
+ patches: cfg.assemble.patches?.length ? cfg.assemble.patches : undefined,
162
+ cuts: cuts(cfg.assemble.cuts, 'assemble.cuts'),
163
+ keep_under_occluders: cfg.assemble.keep_under_occluders?.length ? cfg.assemble.keep_under_occluders : undefined,
164
+ require_hidden_extent: cfg.assemble.require_hidden_extent?.length ? cfg.assemble.require_hidden_extent : undefined,
165
+ head_face_underfill: hasHeadRun && cfg.assemble.head_face_underfill === true ? true : undefined,
166
+ yield_refused: cfg.assemble.yield_refused === true ? true : undefined,
167
+ stage_map: undefined,
168
+ editor_receipts: undefined,
169
+ edited_parts: edited?.receipts.length ? {
170
+ receipts: edited.receipts.map((receipt, i) => ({
171
+ ...receipt,
172
+ file: file(resolve(base, edited.dir, receipt.file), `assemble.edited_parts.receipts[${i}].file`),
173
+ })),
174
+ } : undefined,
175
+ occluders: cfg.assemble.occluders?.length ? cfg.assemble.occluders.map((item, i) => ({
176
+ ...item,
177
+ image: file(item.image, `assemble.occluders[${i}].image`),
178
+ plate: plate(item.plate, `assemble.occluders[${i}].plate`),
179
+ grow: item.grow === 0 ? undefined : item.grow,
180
+ guard: item.guard === 0 ? undefined : item.guard,
181
+ })) : undefined,
182
+ take: cfg.assemble.take?.length ? cfg.assemble.take.map((take, i) => {
183
+ const field = `assemble.take[${i}]`;
184
+ const reference = 'reference' in take ? take.reference : undefined;
185
+ return {
186
+ ...take,
187
+ run_dir: run(take.run_dir, `${field}.run_dir`),
188
+ st_input: file(take.st_input, `${field}.st_input`),
189
+ meta: 'tags' in take ? file(resolve(base, take.run_dir, 'meta.json'), `${field}.run_dir`) : undefined,
190
+ reference: reference !== undefined && 'painting' in reference
191
+ ? { ...reference, painting: file(reference.painting, `${field}.reference.painting`) } : reference,
192
+ };
193
+ }) : undefined,
194
+ alternates: cfg.assemble.alternates?.length ? cfg.assemble.alternates.map((set, i) => ({
195
+ ...set,
196
+ source: file(set.source, `assemble.alternates[${i}].source`),
197
+ full: run(set.full, `assemble.alternates[${i}].full`),
198
+ head: run(set.head, `assemble.alternates[${i}].head`),
199
+ skeleton: file(set.skeleton, `assemble.alternates[${i}].skeleton`),
200
+ cuts: cuts(set.cuts, `assemble.alternates[${i}].cuts`),
201
+ layers: Object.keys(set.layers ?? {}).length === 0 ? undefined : set.layers,
202
+ })) : undefined,
203
+ };
204
+ const inputs = {
205
+ ...Object.fromEntries(Object.entries(assemble).filter(([key]) => !isDoorKey(key)).map(([key, value]) => [`assemble.${key}`, value])),
206
+ bones,
207
+ 'constraints.physics': physicsPairs.length === 0 ? undefined : physicsPairs,
208
+ 'depth.authored_units': cfg.depth === undefined ? undefined : [...authoredUnitDepths(cfg)].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0),
209
+ depth: cfg.depth === undefined ? undefined : {
210
+ ...cfg.depth,
211
+ full: depthRun(cfg.depth.full, 'depth.full'),
212
+ head: depthRun(cfg.depth.head, 'depth.head'),
213
+ },
214
+ 'generation.control.skeleton': skeleton === undefined ? undefined : {
215
+ latent: cfg.generation?.latent,
216
+ ...(isSkeletonName(skeleton) ? { builtin: skeleton } : { file: file(skeleton, 'generation.control.skeleton') }),
217
+ },
218
+ limbs: limbs.length === 0 ? undefined : limbs,
219
+ 'limbs.hybrid_width': hybridWidths.size === 0 ? undefined : [...hybridWidths],
220
+ motion_seams: cfg.motion_seams,
221
+ 'requirements.setup_painting': setup === undefined ? undefined : {
222
+ ...setup,
223
+ figure_mask: setupImage(setup.figure_mask, 'figure_mask'),
224
+ backdrop: setupImage(setup.backdrop, 'backdrop'),
225
+ },
226
+ scene: cfg.scene === undefined ? undefined : true,
227
+ 'seethrough.resolution': resolution,
228
+ 'seethrough.head_box': hasHeadRun ? head_box : undefined,
229
+ 'seethrough.arm_split': arm_split,
230
+ turn: basePairs.length === 0 ? undefined : basePairs,
231
+ };
232
+ const fields = Object.entries(inputs).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)
233
+ .flatMap(([name, value]) => value === undefined ? [] : [{ name, sha256: sha256(JSON.stringify(canonical(value))) }]);
234
+ return { sha256: assemblyFieldDigest(fields), fields };
235
+ }
236
+
237
+ export function assemblyFieldDigest(fields: AssemblyConfigRecord['fields']): string {
238
+ return sha256(JSON.stringify(fields.map(({ name, sha256 }) => [name, sha256])));
239
+ }
240
+
241
+ export function assemblyConfigReading(configPath: string, parts: PartsFile): AssemblyConfigRecord {
242
+ return readAssemblyConfig(loadEarlyConfig(configPath, 'assemble'), parts, configPath);
243
+ }
244
+
245
+ export function changedAssemblyFields(previous: AssemblyConfigRecord, current: AssemblyConfigRecord): string[] {
246
+ if (previous.sha256 === current.sha256) return [];
247
+ const before = new Map(previous.fields.map(row => [row.name, row.sha256]));
248
+ const after = new Map(current.fields.map(row => [row.name, row.sha256]));
249
+ return [...new Set([...before.keys(), ...after.keys()])].sort().filter(name => before.get(name) !== after.get(name));
250
+ }
251
+
252
+ export function assemblyConfigChanges(configPath: string, parts: PartsFile): string[] {
253
+ if (parts.assembly_config === undefined) return [];
254
+ return changedAssemblyFields(parts.assembly_config, assemblyConfigReading(configPath, parts));
255
+ }
256
+
257
+ export function assemblyChangeDetail(changes: readonly string[]): string {
258
+ return `assembly config changed at ${changes.map(name => `config.${name}`).join(', ')}; re-run assemble from the current config`;
259
+ }
260
+
261
+ export function refuseStaleAssembly(configPath: string, parts: PartsFile, loaded?: AssemblySource, overrides?: AssemblyRules): void {
262
+ if (parts.assembly_config === undefined) return;
263
+ const cfg = loaded ?? loadEarlyConfig(configPath, 'assemble', overrides?.project);
264
+ const current = readAssemblyConfig(cfg, parts, configPath, overrides);
265
+ const changes = changedAssemblyFields(parts.assembly_config, current);
266
+ if (changes.length > 0) throw new PartsError([{ code: 'ASSEMBLY_CONFIG_STALE', object: configPath, detail: assemblyChangeDetail(changes) }]);
267
+ }
@@ -0,0 +1,113 @@
1
+ /** Opt-in scalar boundary projection. No sheet, anchor or art is rewritten. */
2
+ import { extendDepthSilhouette, sampleDepthFloat, type PartDepthReference } from './depthsheets.ts';
3
+ import type { Problem } from './errors.ts';
4
+ import type { Raster } from './raster/types.ts';
5
+
6
+ export type BoundaryDepths = Record<string, { neighbour: string; band: string }>;
7
+ type Part = { name: string; x: number; y: number; w: number; h: number; depth?: PartDepthReference };
8
+ type Point = readonly [number, number];
9
+ type Edge = readonly [Point, Point];
10
+
11
+ /** Alpha support is the union of closed native pixel cells with alpha > 0.
12
+ * Projection is onto shared cell edges, not an inferred seam width. Distinct
13
+ * equidistant projections contribute once each, with their arithmetic mean.
14
+ * Outside the band the original extended target sample is returned exactly.
15
+ */
16
+ export function boundaryDepthSamplers(
17
+ declarations: BoundaryDepths | undefined,
18
+ parts: readonly Part[],
19
+ images: ReadonlyMap<string, Raster>,
20
+ roles: Readonly<Record<string, string>>,
21
+ prefix: string,
22
+ ): { samplers: Map<string, (x: number, y: number) => number>; problems: Problem[] } {
23
+ const samplers = new Map<string, (x: number, y: number) => number>();
24
+ const problems: Problem[] = [], result = { samplers, problems };
25
+ if (declarations === undefined || Object.keys(declarations).length === 0) return result;
26
+ const records = new Map(parts.map(p => [p.name, p]));
27
+ const fail = (target: string, detail: string): void => {
28
+ problems.push({ code: 'RIG_TURN_BOUNDARY_DEPTH', object: `${prefix}.boundaryDepths.${target}`, detail });
29
+ };
30
+ const support = (p: Part, art: Raster, x: number, y: number): boolean => {
31
+ const u = x - p.x, v = y - p.y;
32
+ return Number.isInteger(u) && Number.isInteger(v) && u >= 0 && v >= 0 && u < p.w && v < p.h && art.data[(v * art.width + u) * 4 + 3] > 0;
33
+ };
34
+ const contains = (p: Part, art: Raster, x: number, y: number): boolean => {
35
+ for (const u of new Set([Math.floor(x), Math.ceil(x) - 1])) for (const v of new Set([Math.floor(y), Math.ceil(y) - 1])) if (support(p, art, u, v)) return true;
36
+ return false;
37
+ };
38
+ const cyclic = new Set<string>();
39
+ for (const target of Object.keys(declarations)) {
40
+ const seen = new Set<string>();
41
+ for (let next: string | undefined = target; next !== undefined; next = declarations[next]?.neighbour) {
42
+ if (seen.has(next)) { fail(target, `cycle reaches "${next}"; remove reciprocal or cyclic boundary declarations`); cyclic.add(target); break; }
43
+ seen.add(next);
44
+ }
45
+ }
46
+ for (const [target, declaration] of Object.entries(declarations)) {
47
+ const startProblems = problems.length;
48
+ const p = records.get(target), n = records.get(declaration.neighbour), b = records.get(declaration.band);
49
+ for (const [field, record] of [['target', p], ['neighbour', n], ['band', b]] as const) if (record === undefined) fail(target, `${field} "${field === 'target' ? target : declaration[field]}" names no parts.json part; use an exact existing part name`);
50
+ if (p !== undefined && n !== undefined && (target === n.name || roles[target] !== 'surface' || roles[n.name] !== 'surface')) fail(target, `"${target}" and neighbour "${n.name}" require different surface parts in this same turn group`);
51
+ const pa = p === undefined ? undefined : images.get(p.name), na = n === undefined ? undefined : images.get(n.name), ba = b === undefined ? undefined : images.get(b.name);
52
+ const ps = p?.depth === undefined ? undefined : images.get(p.depth.image), ns = n?.depth === undefined ? undefined : images.get(n.depth.image);
53
+ if (p !== undefined && n !== undefined && b !== undefined && (pa === undefined || na === undefined || ba === undefined || ps === undefined || ns === undefined || p.depth === undefined || n.depth === undefined)) fail(target, `target "${target}", neighbour "${n.name}" and band "${b.name}" require resolved art and both original surface sheets`);
54
+ if (p?.depth !== undefined && n?.depth !== undefined && (p.depth.near !== n.depth.near || p.depth.zScale !== n.depth.zScale)) fail(target, `neighbour "${n.name}" requires the target's near and zScale in this turn group`);
55
+ const edges: Edge[] = [];
56
+ let overlap = false;
57
+ const canAbut = p !== undefined && n !== undefined && pa !== undefined && na !== undefined;
58
+ if (canAbut) {
59
+ for (let y = p.y; y < p.y + p.h; y++) for (let x = p.x; x < p.x + p.w; x++) {
60
+ if (!support(p, pa, x, y)) continue;
61
+ if (support(n, na, x, y)) overlap = true;
62
+ if (support(n, na, x - 1, y)) edges.push([[x, y], [x, y + 1]]);
63
+ if (support(n, na, x + 1, y)) edges.push([[x + 1, y], [x + 1, y + 1]]);
64
+ if (support(n, na, x, y - 1)) edges.push([[x, y], [x + 1, y]]);
65
+ if (support(n, na, x, y + 1)) edges.push([[x, y + 1], [x + 1, y + 1]]);
66
+ }
67
+ if (overlap || edges.length === 0) fail(target, `neighbour "${n.name}" does not abut without overlap along opaque pixel-cell edges; declare an abutting surface`);
68
+ }
69
+ // Containment depends on target/band art, not on neighbour depth or abutment.
70
+ // Report the first outside cell once; the remaining declarations still run.
71
+ if (p !== undefined && b !== undefined && pa !== undefined && ba !== undefined) {
72
+ let count = 0, outside = false;
73
+ for (let y = b.y; y < b.y + b.h; y++) for (let x = b.x; x < b.x + b.w; x++) if (support(b, ba, x, y)) {
74
+ count++;
75
+ if (!outside && !support(p, pa, x, y)) { fail(target, `band "${b.name}" has support outside target "${target}" at [${x},${y}]; require contained alpha support`); outside = true; }
76
+ }
77
+ // A missing shared edge cannot establish whether an otherwise valid band
78
+ // reaches it; retain the abutment failure instead of cascading a refusal.
79
+ if (n !== undefined && (count === 0 || (canAbut && !overlap && edges.length > 0 && !edges.some(([a, z]) => contains(b, ba, (a[0] + z[0]) / 2, (a[1] + z[1]) / 2))))) fail(target, `band "${b.name}" is empty or does not reach the shared boundary with "${n.name}"; require a nonempty boundary-reaching band`);
80
+ }
81
+ // Cycles prevent sampler emission, not independent declaration checks.
82
+ if (cyclic.has(target) || problems.length > startProblems || p === undefined || n === undefined || b === undefined || pa === undefined || na === undefined || ba === undefined || ps === undefined || ns === undefined || p.depth === undefined || n.depth === undefined) continue;
83
+ const original = extendDepthSilhouette(ps, pa), neighbour = extendDepthSilhouette(ns, na);
84
+ const seeds: Point[] = [];
85
+ for (let y = p.y; y < p.y + p.h; y++) for (let x = p.x; x < p.x + p.w; x++) if (support(p, pa, x, y)) seeds.push([x + 0.5, y + 0.5]);
86
+ samplers.set(target, (x, y) => {
87
+ const rawX = x, rawY = y;
88
+ // Transparent silhouette/PAD samples inherit their nearest opaque target
89
+ // cell, just as the original scalar extension does. This also retains
90
+ // boundary ownership when setup float encoding lands just outside art.
91
+ if (!contains(p, pa, x, y)) {
92
+ let nearest = Infinity;
93
+ for (const q of seeds) {
94
+ const d = (q[0] - rawX) ** 2 + (q[1] - rawY) ** 2;
95
+ if (d < nearest) { nearest = d; x = q[0]; y = q[1]; }
96
+ }
97
+ }
98
+ if (!contains(b, ba, x, y)) return sampleDepthFloat(original, rawX - p.x, rawY - p.y);
99
+ let distance = Infinity;
100
+ const closest = new Map<string, Point>();
101
+ for (const [a, z] of edges) {
102
+ const q: Point = [Math.max(a[0], Math.min(z[0], x)), Math.max(a[1], Math.min(z[1], y))];
103
+ const d = (q[0] - x) ** 2 + (q[1] - y) ** 2;
104
+ if (d < distance) { closest.clear(); distance = d; }
105
+ if (d === distance) closest.set(`${q[0]},${q[1]}`, q);
106
+ }
107
+ let sum = 0;
108
+ for (const q of closest.values()) sum += sampleDepthFloat(neighbour, q[0] - n.x, q[1] - n.y);
109
+ return sum / closest.size;
110
+ });
111
+ }
112
+ return result;
113
+ }
package/src/build.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { changedAssemblyFields, effectiveAssemblyRules, readAssemblyConfig, refuseStaleAssembly, type AssemblyRules } from './assembly-reading.ts';
1
2
  import { editedPartFrontColourLines, readEditedParts } from './editedparts.ts';
2
3
  import { SOURCE_COVER_FILE, sourceCoverReport, type SourceCoverSet } from './sourcecover.ts';
3
4
  import { STAGE_MAP_FILE } from './provenance.ts';
@@ -6,7 +7,6 @@ import { readSetupFigureMask } from './setupfiguremask.ts';
6
7
  import { EDGE_RESIDUAL_FILE, edgeResidualLines } from './edgeresidual.ts';
7
8
  import { SUPPORT_DOMAINS_FILE, writeSupportDomains } from './supportdomains.ts';
8
9
  import { COINCIDE_LINE, supportLines } from './coincide.ts';
9
- import { DEFAULT_SEAM_RULE } from './seamrule.ts';
10
10
  import { DEFAULT_PROJECT_RULE } from './projectrule.ts';
11
11
  import { type PaintingAllocationReading, type PaintingAllocationEvent, EDGE_CONTRAST, PAINTING_ALLOCATION_FILE, PAINTING_EDGE_COVERAGE_TRANSFER } from './paintingedges.ts';
12
12
  import { SETUP_PAINTING_LINE, setupPaintingLines } from './setuppainting.ts';
@@ -108,7 +108,7 @@ import { CONTROL_SUFFIX, withAnimations } from './motion.ts';
108
108
  import type { PaletteError } from './palette.ts';
109
109
  import { type LayerSet, readLayers } from './layers.ts';
110
110
  import { placeBoneEntriesForSkeleton, poseBoneEntriesForDrawn, REGISTER_OFFSET_BAR, REGISTER_SCALE_BAR, registeredWithinBar, registerSkeleton, SKELETON_LIMB_BONES, skeletonDrawnLength, skeletonLimbJoints } from './limbs.ts';
111
- import { type AlternatePartsRecord, PAINTING_IN_RIG_FILE, FRONT_SUFFIX, type OccluderPlateRecord, type PartRecord, partImageReference, depthImageReference, readParts, type RecompositeRecord, type SingleRunPad, tagOf, writeParts } from './parts.ts';
111
+ import { type AlternatePartsRecord, PAINTING_IN_RIG_FILE, FRONT_SUFFIX, type OccluderPlateRecord, type PartRecord, partImageReference, depthImageReference, readParts, readPartsManifest, type RecompositeRecord, type SingleRunPad, tagOf, writeParts } from './parts.ts';
112
112
  import { encodePngBytes, readPng, writePng } from './raster/png.ts';
113
113
  import type { Raster } from './raster/types.ts';
114
114
  import { type Mask, newMask } from './raster/types.ts';
@@ -392,8 +392,7 @@ export interface EmitFillMasksInput {
392
392
 
393
393
  export function emitFillMasksStage(input: EmitFillMasksInput, log: Log): Array<{ into: string; path: string; sha256: string; opaquePx: number }> {
394
394
  const cfg = loadEarlyConfig(input.config, 'assemble', input.project);
395
- const seam = input.seam ?? cfg.assemble.seam ?? DEFAULT_SEAM_RULE;
396
- const project = input.project ?? cfg.assemble.project ?? DEFAULT_PROJECT_RULE;
395
+ const { seam, project } = effectiveAssemblyRules(cfg.assemble, input);
397
396
  const src = readSource(input.source);
398
397
  const read = readRuns(input.full, input.head);
399
398
  const takenRuns = applyTakenLayers(read, src, cfg, input.config);
@@ -512,8 +511,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
512
511
  // regions and motion, so it requires only what it reads (issue #20).
513
512
  const cfg = loadEarlyConfig(input.config, 'assemble', input.project);
514
513
  const supportDeclarations = JSON.stringify(cfg.assemble.cuts ?? []);
515
- const seam = input.seam ?? cfg.assemble.seam ?? DEFAULT_SEAM_RULE;
516
- const project = input.project ?? cfg.assemble.project ?? DEFAULT_PROJECT_RULE;
514
+ const { seam, project } = effectiveAssemblyRules(cfg.assemble, input);
517
515
  const requirements = cfg.assemble.ground === 'busy' && project === 'visible'
518
516
  ? buildRequirements(input.requirements, cfg.requirements, input.config) : null;
519
517
  const src = readSource(input.source);
@@ -1071,6 +1069,14 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
1071
1069
  result.parts.alternates = altBuilt.map((b) => b.record);
1072
1070
  }
1073
1071
 
1072
+ const reading = readAssemblyConfig(cfg, result.parts, input.config, { seam, project });
1073
+ let previousAssembly = undefined;
1074
+ if (existsSync(outs.partsJson)) {
1075
+ try { previousAssembly = readPartsManifest(outs.partsJson).assembly_config; }
1076
+ catch (error) { if (!(error instanceof PartsError)) throw error; }
1077
+ }
1078
+ result.parts.assembly_config = reading;
1079
+
1074
1080
  const allocationPath = join(dirname(outs.partsJson), PAINTING_ALLOCATION_FILE);
1075
1081
  let previousAllocationFiles: string[] = [];
1076
1082
  if (existsSync(allocationPath)) {
@@ -1099,6 +1105,10 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
1099
1105
  sha256: createHash('sha256').update(paintingBytes).digest('hex'), resample: 'lanczos3-rgb-opaque' };
1100
1106
  writeFileSync(join(dirname(outs.partsJson), PAINTING_IN_RIG_FILE), paintingBytes);
1101
1107
  writeParts(outs.partsJson, result.parts);
1108
+ if (previousAssembly !== undefined) {
1109
+ const changes = changedAssemblyFields(previousAssembly, reading);
1110
+ if (changes.length > 0) log(`note: reassembled parts after changes to ${changes.map(name => `config.${name}`).join(', ')}`);
1111
+ }
1102
1112
  writeFileSync(join(dirname(outs.partsJson), SOURCE_COVER_FILE), JSON.stringify(sourceCoverReport(sourceCoverSets), null, 2) + '\n');
1103
1113
  const stageMapPath = join(dirname(outs.partsJson), STAGE_MAP_FILE);
1104
1114
  if (result.stageMap === undefined) rmSync(stageMapPath, { force: true });
@@ -1466,6 +1476,7 @@ export function contourBodyTurnRemedies(lines: readonly string[], cfg: Character
1466
1476
  }
1467
1477
 
1468
1478
  export interface RigStageInput {
1479
+ assemblyRules?: AssemblyRules;
1469
1480
  config: string;
1470
1481
  /** The directory holding parts.json and parts/<name>.png. */
1471
1482
  parts: string;
@@ -1855,9 +1866,10 @@ export interface RigInputs {
1855
1866
  * `src/meshstats.ts`) both start here, so the two read the same config, the same parts and the same images, and a
1856
1867
  * PNG that is missing is left out of the map for `buildRig` to refuse by name (`RIG_PNG_PRESENT`).
1857
1868
  */
1858
- export function readRigInputs(config: string, partsDir: string): RigInputs {
1869
+ export function readRigInputs(config: string, partsDir: string, assemblyRules?: AssemblyRules): RigInputs {
1859
1870
  const { config: cfg, animations: from } = loadConfigAndAnimations(config);
1860
1871
  const parts = readParts(join(partsDir, 'parts.json'));
1872
+ refuseStaleAssembly(config, parts, cfg, assemblyRules);
1861
1873
  const images = new Map<string, Raster>();
1862
1874
  const depthProblems: Problem[] = [];
1863
1875
  for (const p of parts.parts) {
@@ -1892,7 +1904,7 @@ export function rigOutputTexts(r: RigOutput, animations: Parameters<typeof withA
1892
1904
 
1893
1905
  export function rigStage(input: RigStageInput, rigc: RigcRunner, scratch: string, log: Log): RigOutput {
1894
1906
  const pageSize = parsePageSize(input.pageSize);
1895
- const { cfg, from, parts, images } = readRigInputs(input.config, input.parts);
1907
+ const { cfg, from, parts, images } = readRigInputs(input.config, input.parts, input.assemblyRules);
1896
1908
  const first = buildRig(cfg, parts, images, undefined, input.idleKeys ?? DEFAULT_IDLE_KEYS, input.reduce);
1897
1909
  const textsOf = (r: RigOutput): Array<[string, string]> => rigOutputTexts(r, from === null ? null : from.table);
1898
1910
  const firstTexts = textsOf(first);
@@ -2062,6 +2074,7 @@ export function rigStage(input: RigStageInput, rigc: RigcRunner, scratch: string
2062
2074
  // ---------------------------------------------------------------------------
2063
2075
 
2064
2076
  export interface CheckStageInput {
2077
+ assemblyRules?: AssemblyRules;
2065
2078
  /** The directory holding rig.json and motion.json. */
2066
2079
  rig: string;
2067
2080
  /**
@@ -2346,7 +2359,7 @@ export function checkStage(input: CheckStageInput, rigc: RigcRunner, bin: string
2346
2359
  const entryLine = versionLines.find((l) => l.startsWith('entry:'));
2347
2360
  log(` ${rigcIdentity(bin, v)}${entryLine === undefined ? '' : `; ${entryLine}`}`);
2348
2361
  const mode: PackMode = { pageEdges: input.pageEdges ?? DEFAULT_PAGE_EDGES, packShape: input.packShape ?? DEFAULT_PACK_SHAPE, ...(pageSize === undefined ? {} : { pageSize }) };
2349
- const r = runCheck(input.rig, input.out, rigc, input.parts, mode, input.source, input.requirements, input.seamPairs === true, input.keepStills === true, input.set, input.allSets === true, input.environment, input.requirementsAs, input.config, input.windBand, input.noExtremes === true, input.supportSource, input.supportFigure);
2362
+ const r = runCheck(input.rig, input.out, rigc, input.parts, mode, input.source, input.requirements, input.seamPairs === true, input.keepStills === true, input.set, input.allSets === true, input.environment, input.requirementsAs, input.config, input.windBand, input.noExtremes === true, input.supportSource, input.supportFigure, input.assemblyRules);
2350
2363
  if (r.figures.environment !== undefined) log(` ${environmentLine(r.figures.environment)}`);
2351
2364
  log(` gate rig-play (rigc ${packedBuildLabel(mode)}), verbatim:`);
2352
2365
  for (const l of r.gateHtml) log(l);
@@ -2899,6 +2912,7 @@ export function build(input: BuildInput, run: BuildRunners, log: Log): BuildResu
2899
2912
  // cannot be measured without it; a build without that declaration hands it nothing, as before, and writes the same bytes.
2900
2913
  let paintingForCheck: string | null = null;
2901
2914
  let supportFigure: Mask | undefined;
2915
+ let assemblyRules: Required<AssemblyRules>;
2902
2916
  try {
2903
2917
  pageSize = parsePageSize(input.pageSize);
2904
2918
  // build runs rig next, which needs the whole config, so the full loader is
@@ -2908,8 +2922,8 @@ export function build(input: BuildInput, run: BuildRunners, log: Log): BuildResu
2908
2922
  // Issue #556: the flag, or the config's declaration when there is none; both naming other bytes is refused here.
2909
2923
  // Issue #607: the bytes this read parsed are the ones check.json's config record hashes, under the path as typed.
2910
2924
  const loaded = loadConfigWithBytes(input.config);
2911
- const seam = input.seam ?? loaded.config.assemble.seam ?? DEFAULT_SEAM_RULE;
2912
- const project = input.project ?? loaded.config.assemble.project ?? DEFAULT_PROJECT_RULE;
2925
+ assemblyRules = effectiveAssemblyRules(loaded.config.assemble, input);
2926
+ const { seam, project } = assemblyRules;
2913
2927
  log(`rig-parts build: ${input.config} -> ${out}, seam rule ${seam}, projection rule ${project}, page edges ${input.pageEdges}, pack shape ${input.packShape ?? DEFAULT_PACK_SHAPE}${idleKeys === DEFAULT_IDLE_KEYS ? '' : `, idle keys ${idleKeys}`}${input.loop ? `, with the idle loop${input.leadIn === undefined ? '' : ` after a lead-in of ${input.leadIn} period(s)`}` : ''}`);
2914
2928
  configRecord = inputFileRecord(loaded.bytes, input.config);
2915
2929
  req = buildRequirements(input.requirements, loaded.config.requirements, input.config);
@@ -2930,14 +2944,14 @@ export function build(input: BuildInput, run: BuildRunners, log: Log): BuildResu
2930
2944
  }
2931
2945
 
2932
2946
  try {
2933
- stages.rig({ config: input.config, parts: out, out: join(out, 'rig'), idleKeys, pageEdges: input.pageEdges, packShape: input.packShape, ...(pageSize === undefined ? {} : { pageSize }), command: 'build' }, run.rig, run.scratch, prefixed('rig'));
2947
+ stages.rig({ config: input.config, assemblyRules, parts: out, out: join(out, 'rig'), idleKeys, pageEdges: input.pageEdges, packShape: input.packShape, ...(pageSize === undefined ? {} : { pageSize }), command: 'build' }, run.rig, run.scratch, prefixed('rig'));
2934
2948
  } catch (err) {
2935
2949
  return refused('rig', err);
2936
2950
  }
2937
2951
 
2938
2952
  let report: CheckReport;
2939
2953
  try {
2940
- report = stages.check({ rig: join(out, 'rig'), parts: out, supportSource: input.source, ...(supportFigure === undefined ? {} : { supportFigure }), out: join(out, 'check'), pageEdges: input.pageEdges, packShape: input.packShape, ...(pageSize === undefined ? {} : { pageSize }), ...(req === null ? {} : { requirements: req.read, requirementsAs: req.recorded }), ...(paintingForCheck === null ? {} : { source: paintingForCheck }), seamPairs: input.seamPairs === true, keepStills: input.keepStills === true, noExtremes: input.noExtremes === true, ...(input.set === undefined ? {} : { set: input.set }), allSets: input.allSets === true, ...(input.environment === undefined ? {} : { environment: input.environment }), ...(input.windBand === undefined ? {} : { windBand: input.windBand }), ...(configRecord === null ? {} : { config: configRecord }) }, run.check, run.checkBin, prefixed('check'));
2954
+ report = stages.check({ rig: join(out, 'rig'), assemblyRules, parts: out, supportSource: input.source, ...(supportFigure === undefined ? {} : { supportFigure }), out: join(out, 'check'), pageEdges: input.pageEdges, packShape: input.packShape, ...(pageSize === undefined ? {} : { pageSize }), ...(req === null ? {} : { requirements: req.read, requirementsAs: req.recorded }), ...(paintingForCheck === null ? {} : { source: paintingForCheck }), seamPairs: input.seamPairs === true, keepStills: input.keepStills === true, noExtremes: input.noExtremes === true, ...(input.set === undefined ? {} : { set: input.set }), allSets: input.allSets === true, ...(input.environment === undefined ? {} : { environment: input.environment }), ...(input.windBand === undefined ? {} : { windBand: input.windBand }), ...(configRecord === null ? {} : { config: configRecord }) }, run.check, run.checkBin, prefixed('check'));
2941
2955
  } catch (err) {
2942
2956
  return refused('check', err);
2943
2957
  }