@rig-c/parts 1.86.0 → 1.88.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/cli.ts +52 -12
- package/docs/AUTHORING.md +205 -2
- package/docs/STABILITY.md +50 -5
- package/package.json +1 -1
- package/src/assemble.ts +2 -10
- package/src/build.ts +12 -8
- package/src/check.ts +5 -4
- package/src/config.ts +14 -3
- package/src/depthmaps.ts +170 -0
- package/src/depthworkflow.ts +239 -0
- package/src/rig.ts +17 -0
- package/src/seamrule.ts +11 -0
- package/src/setuppainting.ts +6 -1
package/src/build.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { DEFAULT_SEAM_RULE } from './seamrule.ts';
|
|
1
2
|
import { SETUP_PAINTING_LINE, setupPaintingLines } from './setuppainting.ts';
|
|
2
3
|
import { writeMaterialSources } from './cutmaterialio.ts';
|
|
3
4
|
import { CUT_MATERIAL_LINE, CUT_MATERIAL_SOURCES, materialLines } from './cutmaterial.ts';
|
|
@@ -164,7 +165,7 @@ export interface AssembleStageInput {
|
|
|
164
165
|
/** The head run, or null for one run that holds the face (issue #359). */
|
|
165
166
|
head: string | null;
|
|
166
167
|
config: string;
|
|
167
|
-
seam
|
|
168
|
+
seam?: SeamRule;
|
|
168
169
|
project: ProjectRule;
|
|
169
170
|
/** `--alt` entries, merged with `config.assemble.alternates` by set name (issue #454). */
|
|
170
171
|
alts?: readonly AlternateCliInput[];
|
|
@@ -327,13 +328,14 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
|
|
|
327
328
|
// The early door: assemble runs before propose has drafted bones, meshes,
|
|
328
329
|
// regions and motion, so it requires only what it reads (issue #20).
|
|
329
330
|
const cfg = loadEarlyConfig(input.config, 'assemble');
|
|
331
|
+
const seam = input.seam ?? cfg.assemble.seam ?? DEFAULT_SEAM_RULE;
|
|
330
332
|
const src = readSource(input.source);
|
|
331
333
|
const runs = applyTakenLayers(readRuns(input.full, input.head), src, cfg, input.config);
|
|
332
334
|
for (const note of runs.notes) log(`note: ${note}`);
|
|
333
335
|
const fields = stageFields(cfg, runs.single ? { w: src.width, h: src.height } : null);
|
|
334
336
|
const under = readUnders(input.config, fields.cuts);
|
|
335
337
|
const caps = fields.limbs === undefined ? undefined : readCaps(input.config, fields.limbs);
|
|
336
|
-
const result = assemble({ source: src, full: runs.full, head: runs.head, depth: cfg.depth, depthBase: dirname(resolve(input.config)), ...fields, under, ...(caps === undefined ? {} : { caps }), seamRule:
|
|
338
|
+
const result = assemble({ source: src, full: runs.full, head: runs.head, depth: cfg.depth, depthBase: dirname(resolve(input.config)), ...fields, under, ...(caps === undefined ? {} : { caps }), seamRule: seam, projectRule: input.project });
|
|
337
339
|
|
|
338
340
|
// Issue #454: alternate painting sets, assembled before any file is written.
|
|
339
341
|
const configDir = dirname(resolve(input.config));
|
|
@@ -673,7 +675,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
|
|
|
673
675
|
...(fields.yieldRefused === undefined ? {} : { yieldRefused: fields.yieldRefused }),
|
|
674
676
|
...(fields.turnMovingPair === undefined ? {} : { turnMovingPair: fields.turnMovingPair }),
|
|
675
677
|
...(fields.turn === undefined ? {} : { turn: fields.turn, regions: fields.regions, meshes: fields.meshes, motion: fields.motion }),
|
|
676
|
-
seamRule:
|
|
678
|
+
seamRule: seam,
|
|
677
679
|
projectRule: input.project,
|
|
678
680
|
...(altExclude.length === 0 ? {} : { exclude: altExclude }),
|
|
679
681
|
...(altIslands.length === 0 ? {} : { limbIslands: altIslands }),
|
|
@@ -2218,7 +2220,7 @@ export interface BuildInput {
|
|
|
2218
2220
|
/** The head run, or null for one run that holds the face (issue #359). */
|
|
2219
2221
|
head: string | null;
|
|
2220
2222
|
out: string;
|
|
2221
|
-
seam
|
|
2223
|
+
seam?: SeamRule;
|
|
2222
2224
|
project: ProjectRule;
|
|
2223
2225
|
loop: boolean;
|
|
2224
2226
|
/** `--page-edges` for both packed builds, the rig stage's gate and the check's artifact. */
|
|
@@ -2253,7 +2255,7 @@ export interface BuildInput {
|
|
|
2253
2255
|
windBand?: string;
|
|
2254
2256
|
}
|
|
2255
2257
|
|
|
2256
|
-
/** What `build` does with one flag `check` takes: hands it to its check stage, takes it as its own, or refuses it because build supplies the value itself. */
|
|
2258
|
+
/** What `build` does with one flag `check` takes: hands it to its check stage, takes it as its own, or refuses it because build supplies the value or report itself. */
|
|
2257
2259
|
export type CheckFlagInBuild =
|
|
2258
2260
|
| { as: 'forwarded' }
|
|
2259
2261
|
| { as: 'own'; why: string }
|
|
@@ -2280,6 +2282,7 @@ export const CHECK_FLAGS_IN_BUILD: Readonly<Record<string, CheckFlagInBuild>> =
|
|
|
2280
2282
|
'--no-extremes': { as: 'forwarded' },
|
|
2281
2283
|
'--environment': { as: 'forwarded' },
|
|
2282
2284
|
'--wind-band': { as: 'forwarded' },
|
|
2285
|
+
'--json': { as: 'supplied', why: 'build supplies its multi-stage text report; run check --rig <out>/rig --parts <out> --out <dir> --json for the completed check object' },
|
|
2283
2286
|
};
|
|
2284
2287
|
|
|
2285
2288
|
/** The requirements file build's check reads (issue #556): `read` is where it is opened, `recorded` what `check.json` names it by. */
|
|
@@ -2315,7 +2318,7 @@ export function buildRequirements(flag: string | undefined, declared: string | u
|
|
|
2315
2318
|
]);
|
|
2316
2319
|
}
|
|
2317
2320
|
|
|
2318
|
-
/** The `build` refusal of a `check` flag build supplies itself ({@link CHECK_FLAGS_IN_BUILD}), or null for any other flag. */
|
|
2321
|
+
/** The `build` refusal of a `check` flag whose value or report build supplies itself ({@link CHECK_FLAGS_IN_BUILD}), or null for any other flag. */
|
|
2319
2322
|
export function suppliedCheckFlag(flag: string): string | null {
|
|
2320
2323
|
const row = Object.hasOwn(CHECK_FLAGS_IN_BUILD, flag) ? CHECK_FLAGS_IN_BUILD[flag] : undefined;
|
|
2321
2324
|
return row?.as === 'supplied' ? `build does not take "${flag}"; ${row.why}` : null;
|
|
@@ -2408,7 +2411,6 @@ export function build(input: BuildInput, run: BuildRunners, log: Log): BuildResu
|
|
|
2408
2411
|
rmSync(join(out, FIGURE_MASK_FILE), { force: true });
|
|
2409
2412
|
// The idle-keys value is named only when it is not the default, so a build without the flag, or with the default, prints the line it printed before issue #95.
|
|
2410
2413
|
const idleKeys = input.idleKeys ?? DEFAULT_IDLE_KEYS;
|
|
2411
|
-
log(`rig-parts build: ${input.config} -> ${out}, seam rule ${input.seam}, projection rule ${input.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)`}` : ''}`);
|
|
2412
2414
|
|
|
2413
2415
|
let req: BuildRequirements | null = null;
|
|
2414
2416
|
let configRecord: InputFileRecord | null = null;
|
|
@@ -2420,6 +2422,8 @@ export function build(input: BuildInput, run: BuildRunners, log: Log): BuildResu
|
|
|
2420
2422
|
// Issue #556: the flag, or the config's declaration when there is none; both naming other bytes is refused here.
|
|
2421
2423
|
// Issue #607: the bytes this read parsed are the ones check.json's config record hashes, under the path as typed.
|
|
2422
2424
|
const loaded = loadConfigWithBytes(input.config);
|
|
2425
|
+
const seam = input.seam ?? loaded.config.assemble.seam ?? DEFAULT_SEAM_RULE;
|
|
2426
|
+
log(`rig-parts build: ${input.config} -> ${out}, seam rule ${seam}, projection rule ${input.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)`}` : ''}`);
|
|
2423
2427
|
configRecord = inputFileRecord(loaded.bytes, input.config);
|
|
2424
2428
|
req = buildRequirements(input.requirements, loaded.config.requirements, input.config);
|
|
2425
2429
|
// The same for the requirements file's own shape; its names resolve against the rig, in the check, before it builds.
|
|
@@ -2429,7 +2433,7 @@ export function build(input: BuildInput, run: BuildRunners, log: Log): BuildResu
|
|
|
2429
2433
|
// And the steady-wind band spec (issue #590), as check reads it.
|
|
2430
2434
|
if (input.windBand !== undefined) readWindBand(input.windBand);
|
|
2431
2435
|
stages.assemble(
|
|
2432
|
-
{ source: input.source, full: input.full, head: input.head, config: input.config, seam
|
|
2436
|
+
{ source: input.source, full: input.full, head: input.head, config: input.config, seam, project: input.project, ...(req === null ? {} : { requirements: req.read }), ...(input.alts === undefined ? {} : { alts: input.alts }) },
|
|
2433
2437
|
{ partsJson: join(out, 'parts.json'), partsDir: join(out, 'parts'), recomposite: join(out, 'recomposite_rig.png'), errorMap: join(out, ERROR_MAP_FILE) },
|
|
2434
2438
|
prefixed('assemble'),
|
|
2435
2439
|
);
|
package/src/check.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { SETUP_PAINTING_LINE, setupPaintingBounds, setupPaintingLine, type SetupPainting, type SetupPaintingLine } from './setuppainting.ts';
|
|
1
|
+
import { SETUP_PAINTING_LINE, UNDECLARED_SETUP_PAINTING_REASON, setupPaintingBounds, setupPaintingLine, type SetupPainting, type SetupPaintingLine, type SetupPaintingObservation } from './setuppainting.ts';
|
|
2
2
|
import { readMaterialSources } from './cutmaterialio.ts';
|
|
3
3
|
import { CUT_MATERIAL_LINE, checkJointMaterial, type MaterialLine } from './cutmaterial.ts';
|
|
4
4
|
import { ART_JOINT_LINE, artJointLine, type ArtJointLine } from './artjoints.ts';
|
|
@@ -2730,8 +2730,8 @@ export interface CheckFigures {
|
|
|
2730
2730
|
requirements?: RequirementsBlock;
|
|
2731
2731
|
/** Issue #880: only when requirements declares fixed_skeleton. */
|
|
2732
2732
|
[ART_JOINT_LINE]?: ArtJointLine;
|
|
2733
|
-
/**
|
|
2734
|
-
[SETUP_PAINTING_LINE]?:
|
|
2733
|
+
/** Under --source: the declared observation, or an explicit undeclared SKIP. */
|
|
2734
|
+
[SETUP_PAINTING_LINE]?: SetupPaintingObservation;
|
|
2735
2735
|
[CUT_MATERIAL_LINE]?: MaterialLine;
|
|
2736
2736
|
PASS: boolean;
|
|
2737
2737
|
}
|
|
@@ -6476,7 +6476,8 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
|
|
|
6476
6476
|
const setHints = new Map<string, string>();
|
|
6477
6477
|
const fixedSkeleton = reqFile?.fixed_skeleton;
|
|
6478
6478
|
let artJoints: ArtJointLine | null = null;
|
|
6479
|
-
let setupPainting:
|
|
6479
|
+
let setupPainting: SetupPaintingObservation | null = inp.source !== null && reqFile?.setup_painting === undefined
|
|
6480
|
+
? { status: 'SKIP', reason: UNDECLARED_SETUP_PAINTING_REASON } : null;
|
|
6480
6481
|
if (inp.parts !== null || inp.source !== null || fixedSkeleton !== undefined) {
|
|
6481
6482
|
try {
|
|
6482
6483
|
mkdirSync(stillDir, { recursive: true });
|
package/src/config.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { SEAM_RULES, type SeamRule } from './seamrule.ts';
|
|
1
2
|
import type { TakeLayers } from './takelayers.ts';
|
|
2
3
|
import { paintingExtensionProblems, type PaintingExtension } from './paintingextension.ts';
|
|
3
4
|
import { baseAnchorProblems, type BaseAnchor } from './baseanchor.ts';
|
|
@@ -300,6 +301,8 @@ export interface AlternateSetConfig {
|
|
|
300
301
|
}
|
|
301
302
|
|
|
302
303
|
export interface Assemble {
|
|
304
|
+
/** Optional per-character seam rule; an explicit CLI flag wins. */
|
|
305
|
+
seam?: SeamRule;
|
|
303
306
|
/** Verified named replacements from another See-through run (#866). */
|
|
304
307
|
take?: TakeLayers[];
|
|
305
308
|
/** Rig pixels per source pixel. */
|
|
@@ -1622,7 +1625,7 @@ export interface EarlyConfig {
|
|
|
1622
1625
|
depth?: DepthConfig;
|
|
1623
1626
|
key: string;
|
|
1624
1627
|
seethrough: SeeThrough;
|
|
1625
|
-
assemble: { rig_scale: number; take?: TakeLayers[]; head_face_underfill?: boolean; yield_refused?: boolean; keep_under_occluders?: string[]; extend_painting?: PaintingExtension[] };
|
|
1628
|
+
assemble: { rig_scale: number; seam?: SeamRule; take?: TakeLayers[]; head_face_underfill?: boolean; yield_refused?: boolean; keep_under_occluders?: string[]; extend_painting?: PaintingExtension[] };
|
|
1626
1629
|
}
|
|
1627
1630
|
|
|
1628
1631
|
/** What plain `assemble` reads: the early config plus the plan `--propose-plan` printed. */
|
|
@@ -1691,8 +1694,9 @@ function parseEarlyConfigFrom(raw: Json, door: EarlyDoor, base: string | null):
|
|
|
1691
1694
|
if (door === 'layers') {
|
|
1692
1695
|
if ('seethrough' in t) checkSeeThrough(c, t.seethrough);
|
|
1693
1696
|
if ('assemble' in t) {
|
|
1694
|
-
const a = c.object('config.assemble', t.assemble, sectionRequired(door, 'assemble'), ['plan', 'extend_below_crop', 'patches', 'cuts', 'alternates', 'head_face_underfill', 'yield_refused', 'keep_under_occluders', 'extend_painting', 'take']);
|
|
1697
|
+
const a = c.object('config.assemble', t.assemble, sectionRequired(door, 'assemble'), ['plan', 'extend_below_crop', 'patches', 'cuts', 'alternates', 'head_face_underfill', 'yield_refused', 'keep_under_occluders', 'extend_painting', 'take', 'seam']);
|
|
1695
1698
|
if (a !== null) {
|
|
1699
|
+
checkSeam(c, a);
|
|
1696
1700
|
if ('rig_scale' in a) c.number('config.assemble.rig_scale', a.rig_scale, 'positive');
|
|
1697
1701
|
if ('head_face_underfill' in a && typeof a.head_face_underfill !== 'boolean') {
|
|
1698
1702
|
c.fail('CONFIG_FIELD_TYPE', 'config.assemble.head_face_underfill', `is ${show(a.head_face_underfill)}; true or false is required`);
|
|
@@ -2457,10 +2461,17 @@ function checkTakeLayers(c: Check, value: Json): void {
|
|
|
2457
2461
|
});
|
|
2458
2462
|
}
|
|
2459
2463
|
|
|
2464
|
+
function checkSeam(c: Check, a: Record<string, Json>): void {
|
|
2465
|
+
if ('seam' in a && !(SEAM_RULES as readonly unknown[]).includes(a.seam)) {
|
|
2466
|
+
c.fail('CONFIG_FIELD_TYPE', 'config.assemble.seam', `is ${show(a.seam)}; one of ${SEAM_RULES.join(', ')} is required`);
|
|
2467
|
+
}
|
|
2468
|
+
}
|
|
2469
|
+
|
|
2460
2470
|
function checkAssemble(c: Check, v: Json, door: 'assemble' | 'full'): { parts: string[]; patches: string[]; cuts: string[] } {
|
|
2461
2471
|
const required = sectionRequired(door, 'assemble');
|
|
2462
|
-
const a = c.object('config.assemble', v, required.filter((k) => k !== 'plan'), ['plan', 'extend_below_crop', 'patches', 'cuts', 'alternates', 'head_face_underfill', 'yield_refused', 'keep_under_occluders', 'extend_painting', 'take']);
|
|
2472
|
+
const a = c.object('config.assemble', v, required.filter((k) => k !== 'plan'), ['plan', 'extend_below_crop', 'patches', 'cuts', 'alternates', 'head_face_underfill', 'yield_refused', 'keep_under_occluders', 'extend_painting', 'take', 'seam']);
|
|
2463
2473
|
if (a === null) return { parts: [], patches: [], cuts: [] };
|
|
2474
|
+
checkSeam(c, a);
|
|
2464
2475
|
if (required.includes('plan') && !('plan' in a)) {
|
|
2465
2476
|
c.fail('CONFIG_FIELD_PRESENT', 'config.assemble.plan', 'is absent and required; `assemble --propose-plan` prints one from the two runs — paste its plan and extend_below_crop into config.assemble');
|
|
2466
2477
|
}
|
package/src/depthmaps.ts
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
/** Provider-independent floating-point maps. No model or reference depth is read here. */
|
|
2
|
+
import { PartsError } from './errors.ts';
|
|
3
|
+
import { connectedComponents } from './raster/components.ts';
|
|
4
|
+
import { extendDepthSilhouette } from './depthsheets.ts';
|
|
5
|
+
import { newRaster, type Raster } from './raster/types.ts';
|
|
6
|
+
import { edgeLength } from './length.ts';
|
|
7
|
+
|
|
8
|
+
export interface NumericMap { spec: 'rig-parts-map/1'; width: number; height: number; channels: 1 | 3; data: number[] }
|
|
9
|
+
export function depthMapFail(code: string, object: string, detail: string): never {
|
|
10
|
+
throw new PartsError([{ code, object, detail }]);
|
|
11
|
+
}
|
|
12
|
+
export function readNumericMap(raw: unknown, at: string): NumericMap {
|
|
13
|
+
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return depthMapFail('DEPTH_MAP_FORMAT', at, 'requires a rig-parts-map/1 JSON object');
|
|
14
|
+
const r = raw as Record<string, unknown>;
|
|
15
|
+
if (Object.keys(r).some(k => !['spec', 'width', 'height', 'channels', 'data'].includes(k)) || r.spec !== 'rig-parts-map/1' || !Number.isSafeInteger(r.width) || !Number.isSafeInteger(r.height) || Number(r.width) < 1 || Number(r.height) < 1 || (r.channels !== 1 && r.channels !== 3) || !Array.isArray(r.data) || r.data.length !== Number(r.width) * Number(r.height) * r.channels || !r.data.every(x => typeof x === 'number' && Number.isFinite(x))) {
|
|
16
|
+
return depthMapFail('DEPTH_MAP_FORMAT', at, 'requires positive integer width/height, channels 1 or 3 and exactly width*height*channels finite row-major numbers; previews and quantized PNGs are not numeric maps');
|
|
17
|
+
}
|
|
18
|
+
return r as unknown as NumericMap;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** NumPy percentile's linear interpolation on sorted samples, including the even median. */
|
|
22
|
+
export function mapQuantile(sorted: readonly number[], q: number): number {
|
|
23
|
+
const p = (sorted.length - 1) * q, i = Math.floor(p), f = p - i;
|
|
24
|
+
return sorted[i] * (1 - f) + sorted[Math.min(i + 1, sorted.length - 1)] * f;
|
|
25
|
+
}
|
|
26
|
+
export function alphaSupport(art: Raster): Uint8Array {
|
|
27
|
+
return Uint8Array.from({ length: art.width * art.height }, (_, i) => art.data[i * 4 + 3] >= 128 ? 1 : 0);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Pillow mode-F BOX: discrete box taps, horizontal then vertical float32 passes.
|
|
31
|
+
* Unlike area coverage, BOX gives equal weights to the included pixel centres.
|
|
32
|
+
* Verification compares this operation to an independent Pillow oracle.
|
|
33
|
+
*/
|
|
34
|
+
export function floatBox(data: ArrayLike<number>, w: number, h: number, width: number, height: number): Float64Array {
|
|
35
|
+
const pass = (src: ArrayLike<number>, sw: number, sh: number, dw: number): Float32Array => {
|
|
36
|
+
const out = new Float32Array(dw * sh), scale = sw / dw;
|
|
37
|
+
for (let x = 0; x < dw; x++) {
|
|
38
|
+
const center = (x + 0.5) * scale, support = Math.max(1, scale) * 0.5;
|
|
39
|
+
const lo = Math.max(0, Math.trunc(center - support + 0.5)), hi = Math.min(sw, Math.trunc(center + support + 0.5));
|
|
40
|
+
const indices: number[] = [];
|
|
41
|
+
for (let i = lo; i < hi; i++) { const d = (i - center + 0.5) / Math.max(1, scale); if (d > -0.5 && d <= 0.5) indices.push(i); }
|
|
42
|
+
if (indices.length === 0) indices.push(Math.min(sw - 1, Math.max(0, Math.floor(center))));
|
|
43
|
+
for (let y = 0; y < sh; y++) { let v = 0; for (const i of indices) v += src[y * sw + i] / indices.length; out[y * dw + x] = v; }
|
|
44
|
+
}
|
|
45
|
+
return out;
|
|
46
|
+
};
|
|
47
|
+
const horizontal = w === width ? Float32Array.from(data) : pass(data, w, h, width);
|
|
48
|
+
if (h === height) return Float64Array.from(horizontal);
|
|
49
|
+
const transpose = new Float32Array(width * h);
|
|
50
|
+
for (let y = 0; y < h; y++) for (let x = 0; x < width; x++) transpose[x * h + y] = horizontal[y * width + x];
|
|
51
|
+
const vertical = pass(transpose, h, width, height), out = new Float64Array(width * height);
|
|
52
|
+
for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) out[y * width + x] = vertical[x * height + y];
|
|
53
|
+
return out;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function norm(v: Float64Array): number { let s = 0; for (const x of v) s += x * x; return Math.sqrt(s); }
|
|
57
|
+
function eroded(mask: Uint8Array, w: number, h: number, count: number): Uint8Array {
|
|
58
|
+
let cur = mask;
|
|
59
|
+
for (let n = 0; n < count; n++) {
|
|
60
|
+
const next = new Uint8Array(cur.length);
|
|
61
|
+
for (let y = 1; y < h - 1; y++) for (let x = 1; x < w - 1; x++) { const i = y * w + x; next[i] = cur[i] && cur[i - 1] && cur[i + 1] && cur[i - w] && cur[i + w] ? 1 : 0; }
|
|
62
|
+
cur = next;
|
|
63
|
+
}
|
|
64
|
+
return cur;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Matrix-free LSQR over right/down adjacent mask pixels, row order right then down.
|
|
68
|
+
* Paige/Saunders bidiagonalization; atol=btol=1e-6, conlim=1e8, at most 3000
|
|
69
|
+
* iterations. These are algorithm settings, not fitted depth-quality bars.
|
|
70
|
+
*/
|
|
71
|
+
function solveEdges(a: Int32Array, b: Int32Array, rhs: Float64Array, size: number): { z: Float64Array; iterations: number; residual: number } {
|
|
72
|
+
const mul = (v: Float64Array, out: Float64Array): void => { for (let i = 0; i < a.length; i++) out[i] = v[b[i]] - v[a[i]]; };
|
|
73
|
+
const trans = (u: Float64Array, out: Float64Array): void => { out.fill(0); for (let i = 0; i < a.length; i++) { out[b[i]] += u[i]; out[a[i]] -= u[i]; } };
|
|
74
|
+
const z = new Float64Array(size), u = rhs.slice(), v = new Float64Array(size);
|
|
75
|
+
let beta = norm(u); const bnorm = beta;
|
|
76
|
+
if (beta === 0) return { z, iterations: 0, residual: 0 };
|
|
77
|
+
for (let i = 0; i < u.length; i++) u[i] /= beta;
|
|
78
|
+
trans(u, v); let alpha = norm(v);
|
|
79
|
+
if (alpha === 0) return { z, iterations: 0, residual: beta };
|
|
80
|
+
for (let i = 0; i < v.length; i++) v[i] /= alpha;
|
|
81
|
+
const w = v.slice(), av = new Float64Array(u.length), atu = new Float64Array(size);
|
|
82
|
+
let rhobar = alpha, phibar = beta, anorm = 0, ddnorm = 0, xnorm = 0, xxnorm = 0, zeta = 0, cs2 = -1, sn2 = 0, iterations = 0, residual = beta;
|
|
83
|
+
for (; iterations < 3000;) {
|
|
84
|
+
iterations++; mul(v, av);
|
|
85
|
+
for (let i = 0; i < u.length; i++) u[i] = av[i] - alpha * u[i];
|
|
86
|
+
beta = norm(u);
|
|
87
|
+
if (beta > 0) {
|
|
88
|
+
for (let i = 0; i < u.length; i++) u[i] /= beta;
|
|
89
|
+
anorm = Math.sqrt(anorm * anorm + alpha * alpha + beta * beta);
|
|
90
|
+
trans(u, atu);
|
|
91
|
+
for (let i = 0; i < v.length; i++) v[i] = atu[i] - beta * v[i];
|
|
92
|
+
alpha = norm(v);
|
|
93
|
+
if (alpha > 0) for (let i = 0; i < v.length; i++) v[i] /= alpha;
|
|
94
|
+
}
|
|
95
|
+
const rho = edgeLength(rhobar, beta), cs = rhobar / rho, sn = beta / rho;
|
|
96
|
+
const theta = sn * alpha; rhobar = -cs * alpha;
|
|
97
|
+
const phi = cs * phibar; phibar = sn * phibar;
|
|
98
|
+
const tau = sn * phi;
|
|
99
|
+
for (let i = 0; i < z.length; i++) { const d = w[i] / rho; z[i] += phi * d; ddnorm += d * d; w[i] = v[i] - theta / rho * w[i]; }
|
|
100
|
+
const delta = sn2 * rho, gambar = -cs2 * rho, right = phi - delta * zeta;
|
|
101
|
+
const zbar = right / gambar; xnorm = Math.sqrt(xxnorm + zbar * zbar);
|
|
102
|
+
const gamma = edgeLength(gambar, theta); cs2 = gambar / gamma; sn2 = theta / gamma; zeta = right / gamma; xxnorm += zeta * zeta;
|
|
103
|
+
residual = Math.abs(phibar);
|
|
104
|
+
const arnorm = alpha * Math.abs(tau), acond = anorm * Math.sqrt(ddnorm);
|
|
105
|
+
if (acond >= 1e8 || arnorm <= 1e-6 * anorm * residual || residual <= 1e-6 * bnorm + 1e-6 * anorm * xnorm) break;
|
|
106
|
+
}
|
|
107
|
+
return { z, iterations, residual };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export interface NormalHeight { data: Float64Array; sign: 1 | -1; coreMinusRim: number; iterations: number; residual: number }
|
|
111
|
+
/** Normals are signed XYZ in image axes (x right/y down), not RGB previews.
|
|
112
|
+
* Half-resolution stride, step2 edge trapezoids, cross-erosion core/rim sign.
|
|
113
|
+
* Convexity selects between a height and its negation without an answer key.
|
|
114
|
+
*/
|
|
115
|
+
export function integrateNormals(map: NumericMap, art: Raster, at: string): NormalHeight {
|
|
116
|
+
const support = alphaSupport(art);
|
|
117
|
+
const islands = connectedComponents({ width: art.width, height: art.height, data: support }, 4).count - 1;
|
|
118
|
+
if (islands !== 1) return depthMapFail('DEPTH_NORMAL_ISLANDS', at, `has ${islands} four-connected alpha>=128 islands; exactly one closed convex part is required, use scalar depth for occlusion-separated parts`);
|
|
119
|
+
if (map.channels !== 3 || map.width !== art.width || map.height !== art.height) return depthMapFail('DEPTH_MAP_SIZE', at, `normal map is ${map.width}x${map.height}x${map.channels}; registered art ${art.width}x${art.height}x3 is required`);
|
|
120
|
+
const w = Math.ceil(map.width / 2), h = Math.ceil(map.height / 2), mask = new Uint8Array(w * h), px = new Float64Array(w * h), py = new Float64Array(w * h), ids = new Int32Array(w * h).fill(-1);
|
|
121
|
+
let count = 0;
|
|
122
|
+
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
|
|
123
|
+
const src = 2 * y * map.width + 2 * x, i = y * w + x;
|
|
124
|
+
mask[i] = support[src]; if (!mask[i]) continue;
|
|
125
|
+
ids[i] = count++;
|
|
126
|
+
const nx = map.data[src * 3], ny = map.data[src * 3 + 1], nz = map.data[src * 3 + 2], length = edgeLength(edgeLength(nx, ny), nz);
|
|
127
|
+
if (length < 1e-12 || !Number.isFinite(length)) return depthMapFail('DEPTH_NORMAL_VECTOR', `${at} (${x * 2},${y * 2})`, 'has zero or overflowing length; a finite nonzero representable signed XYZ vector is required');
|
|
128
|
+
const divisor = Math.max(Math.abs(nz), 0.15 * length);
|
|
129
|
+
px[i] = Math.fround(-nx / divisor); py[i] = Math.fround(-ny / divisor);
|
|
130
|
+
}
|
|
131
|
+
const sampledIslands = connectedComponents({ width: w, height: h, data: mask }, 4).count - 1;
|
|
132
|
+
if (sampledIslands !== 1) return depthMapFail('DEPTH_NORMAL_ISLANDS', at, `half-resolution mask has ${sampledIslands} islands; provide a larger registered input so stride2 keeps one island`);
|
|
133
|
+
const aa: number[] = [], bb: number[] = [], rr: number[] = [];
|
|
134
|
+
for (const [dx, dy, g] of [[1, 0, px], [0, 1, py]] as const) {
|
|
135
|
+
for (let y = 0; y < h - dy; y++) for (let x = 0; x < w - dx; x++) {
|
|
136
|
+
const i = y * w + x, j = (y + dy) * w + x + dx;
|
|
137
|
+
if (mask[i] && mask[j]) { aa.push(ids[i]); bb.push(ids[j]); rr.push(Math.fround(g[i] + g[j])); }
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
const solve = solveEdges(Int32Array.from(aa), Int32Array.from(bb), Float64Array.from(rr), count);
|
|
141
|
+
const core = eroded(mask, w, h, Math.max(3, Math.trunc(0.12 * Math.sqrt(count)))), inner = eroded(mask, w, h, 3);
|
|
142
|
+
let cv = 0, rv = 0, cn = 0, rn = 0;
|
|
143
|
+
for (let i = 0; i < mask.length; i++) { if (core[i]) { cv += solve.z[ids[i]]; cn++; } if (mask[i] && !inner[i]) { rv += solve.z[ids[i]]; rn++; } }
|
|
144
|
+
const d = cv / cn - rv / rn;
|
|
145
|
+
if (!cn || !rn || !Number.isFinite(d) || Math.abs(d) < 1e-12) return depthMapFail('DEPTH_NORMAL_CONVEXITY', at, `core ${cn}, rim ${rn}, core-minus-rim ${d}; a resolved convex interior is required, use a larger mask or scalar source`);
|
|
146
|
+
const sign = d >= 0 ? 1 : -1, data = new Float64Array(w * h);
|
|
147
|
+
for (let i = 0; i < mask.length; i++) if (mask[i]) data[i] = Math.fround(solve.z[ids[i]] * sign);
|
|
148
|
+
return { data, sign, coreMinusRim: d, iterations: solve.iterations, residual: solve.residual };
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export interface MapSheetReading { levels: number; clipFraction: number; reliefRigPixels: number; rawMedian: number; rawP5: number; rawP95: number }
|
|
152
|
+
export function mapToSheet(data: ArrayLike<number>, art: Raster, median: number, relief: number, near: 'black' | 'white', zScale: number, at: string): { sheet: Raster; reading: MapSheetReading } {
|
|
153
|
+
const support = alphaSupport(art), values: number[] = [];
|
|
154
|
+
for (let i = 0; i < support.length; i++) if (support[i]) values.push(data[i]);
|
|
155
|
+
if (!values.length) return depthMapFail('DEPTH_MAP_SUPPORT', at, 'has no alpha>=128 pixels; a part with declared support is required');
|
|
156
|
+
values.sort((a, b) => a - b);
|
|
157
|
+
const med = mapQuantile(values, 0.5), lo = mapQuantile(values, 0.05), hi = mapQuantile(values, 0.95), spread = hi - lo;
|
|
158
|
+
if (![med, lo, hi, spread].every(Number.isFinite)) return depthMapFail('DEPTH_MAP_FORMAT', at, 'normalization overflows finite arithmetic; provide finite representable median and percentile spread');
|
|
159
|
+
if (spread === 0 && relief !== 0) return depthMapFail('DEPTH_MAP_SPREAD', at, `p5=p95=${lo} but relief=${relief}; a nonflat map or explicit relief 0 is required`);
|
|
160
|
+
const sheet = newRaster(art.width, art.height), seeds = newRaster(art.width, art.height), levels = new Set<number>(); let clipped = 0;
|
|
161
|
+
for (let i = 0; i < support.length; i++) {
|
|
162
|
+
const z = median + relief * (spread === 0 ? 0 : (data[i] - med) / spread), unit = Math.max(0, Math.min(1, near === 'white' ? z / zScale : 1 - z / zScale));
|
|
163
|
+
if (!Number.isFinite(z) && support[i]) return depthMapFail('DEPTH_MAP_FORMAT', at, `world depth at support pixel ${i} overflows; declare representable median/relief and raw numbers`);
|
|
164
|
+
// Uint8ClampedArray implements ties-to-even, as numpy.round does.
|
|
165
|
+
sheet.data[i * 4] = unit * 255; sheet.data[i * 4 + 1] = sheet.data[i * 4 + 2] = sheet.data[i * 4]; sheet.data[i * 4 + 3] = 255;
|
|
166
|
+
seeds.data[i * 4 + 3] = support[i] ? 255 : 0;
|
|
167
|
+
if (support[i]) { levels.add(sheet.data[i * 4]); if (z <= 0 || z >= zScale) clipped++; }
|
|
168
|
+
}
|
|
169
|
+
return { sheet: extendDepthSilhouette(sheet, seeds), reading: { levels: levels.size, clipFraction: clipped / values.length, reliefRigPixels: relief, rawMedian: med, rawP5: lo, rawP95: hi } };
|
|
170
|
+
}
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
/** Explicit opt-in commands for provider maps on already assembled parts (#897).
|
|
2
|
+
* No existing assembly/build path calls these stages. All inputs validate before
|
|
3
|
+
* the first output is emitted; output directories must be absent or empty.
|
|
4
|
+
*/
|
|
5
|
+
import { createHash } from 'node:crypto';
|
|
6
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, statSync, writeFileSync } from 'node:fs';
|
|
7
|
+
import { basename, dirname, join, relative, resolve, sep } from 'node:path';
|
|
8
|
+
import { loadConfigAndAnimations, parseConfig } from './config.ts';
|
|
9
|
+
import { depthReading, readSourceDepth } from './depthsheets.ts';
|
|
10
|
+
import { alphaSupport, depthMapFail as fail, floatBox, integrateNormals, mapToSheet, readNumericMap, type NumericMap } from './depthmaps.ts';
|
|
11
|
+
import { readParts } from './parts.ts';
|
|
12
|
+
import { readPartSet } from './propose.ts';
|
|
13
|
+
import { decodePngBytes, encodePngBytes } from './raster/png.ts';
|
|
14
|
+
import { resize } from './raster/resize.ts';
|
|
15
|
+
import { connectedComponents } from './raster/components.ts';
|
|
16
|
+
import { isSkeletonName } from './skeleton.ts';
|
|
17
|
+
import { newRaster, type Raster } from './raster/types.ts';
|
|
18
|
+
|
|
19
|
+
type Obj = Record<string, unknown>;
|
|
20
|
+
interface PrepareOptions { longSide: number; paddingFraction: number; padding: number }
|
|
21
|
+
interface Group { median?: never; near: 'black' | 'white'; zScale: number; pivot: number; unitDepths?: Record<string, number> }
|
|
22
|
+
interface PartMap { map: string; source: 'depth' | 'normals'; frame: 'part' | 'upscaled' | 'input'; group: string; median: number; relief: number }
|
|
23
|
+
export interface DepthRecipe { spec: 'rig-parts-depth/1'; prepare: PrepareOptions; groups: Record<string, Group>; parts: Record<string, PartMap>; clear: string[] }
|
|
24
|
+
interface PreparedPart { part: string; crop: number[]; sourceSha256: string; input: string; inputSha256: string; size: number[]; upscaled: number[]; upscale: number; padding: number; inputSize: number[] }
|
|
25
|
+
interface Prepared { spec: 'rig-parts-depth-inputs/1'; partsSha256: string; recipeSha256: string; background: number; alpha: number; parts: PreparedPart[] }
|
|
26
|
+
const hash = (bytes: Uint8Array | string): string => createHash('sha256').update(bytes).digest('hex');
|
|
27
|
+
const text = (raw: unknown): string => JSON.stringify(raw, null, 2) + '\n';
|
|
28
|
+
function object(raw: unknown, at: string): Obj {
|
|
29
|
+
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return fail('DEPTH_RECIPE', at, 'requires an object with the documented fields');
|
|
30
|
+
return raw as Obj;
|
|
31
|
+
}
|
|
32
|
+
function keys(o: Obj, allowed: readonly string[], at: string): void {
|
|
33
|
+
const unknown = Object.keys(o).filter(k => !allowed.includes(k));
|
|
34
|
+
if (unknown.length) fail('DEPTH_RECIPE', at, `unknown fields ${unknown.join(', ')}; allowed: ${allowed.join(', ')}`);
|
|
35
|
+
}
|
|
36
|
+
function number(raw: unknown, at: string, min: number, inclusive = true): number {
|
|
37
|
+
if (typeof raw !== 'number' || !Number.isFinite(raw) || (inclusive ? raw < min : raw <= min)) return fail('DEPTH_RECIPE_NUMBER', at, `is ${String(raw)}; an explicit finite number ${inclusive ? '>=' : '>'} ${min} is required`);
|
|
38
|
+
return raw;
|
|
39
|
+
}
|
|
40
|
+
function readJson(file: string): unknown {
|
|
41
|
+
if (!existsSync(file) || !statSync(file).isFile()) return fail('DEPTH_INPUT_PRESENT', file, 'is missing or not a file; restore the declared input');
|
|
42
|
+
try { return JSON.parse(readFileSync(file, 'utf8')) as unknown; }
|
|
43
|
+
catch { return fail('DEPTH_INPUT_JSON', file, 'is not valid JSON; finite numeric JSON data is required'); }
|
|
44
|
+
}
|
|
45
|
+
function plain(name: string, at: string): void {
|
|
46
|
+
if (!name || name.startsWith('.') || /[\\/]/.test(name) || name.includes('\0')) fail('DEPTH_RECIPE', at, `name "${name}" is not a plain part filename`);
|
|
47
|
+
}
|
|
48
|
+
export function parseDepthRecipe(raw: unknown): DepthRecipe {
|
|
49
|
+
const o = object(raw, 'depth recipe'); keys(o, ['spec', 'prepare', 'groups', 'parts', 'clear'], 'depth recipe');
|
|
50
|
+
if (o.spec !== 'rig-parts-depth/1') fail('DEPTH_RECIPE', 'spec', 'requires rig-parts-depth/1');
|
|
51
|
+
const p = object(o.prepare, 'prepare'); keys(p, ['longSide', 'paddingFraction', 'padding'], 'prepare');
|
|
52
|
+
const prepare = { longSide: number(p.longSide, 'prepare.longSide', 1), paddingFraction: number(p.paddingFraction, 'prepare.paddingFraction', 0), padding: number(p.padding, 'prepare.padding', 0) };
|
|
53
|
+
if (!Number.isSafeInteger(prepare.longSide) || !Number.isSafeInteger(prepare.padding)) fail('DEPTH_RECIPE_NUMBER', 'prepare', 'longSide and padding must be explicit safe integers');
|
|
54
|
+
const groups: Record<string, Group> = {};
|
|
55
|
+
for (const [name, value] of Object.entries(object(o.groups, 'groups'))) {
|
|
56
|
+
if (!['head', 'body'].includes(name)) fail('DEPTH_RECIPE', `groups.${name}`, 'requires head or body, matching config.turn or config.turn.body');
|
|
57
|
+
const g = object(value, `groups.${name}`); keys(g, ['near', 'zScale', 'pivot', 'unitDepths'], `groups.${name}`);
|
|
58
|
+
if (g.near !== 'white' && g.near !== 'black') fail('DEPTH_RECIPE', `groups.${name}.near`, `is ${String(g.near)}; explicit white or black is required`);
|
|
59
|
+
const unitDepths: Record<string, number> = {};
|
|
60
|
+
if (g.unitDepths !== undefined) for (const [part, v] of Object.entries(object(g.unitDepths, `groups.${name}.unitDepths`))) unitDepths[part] = number(v, `groups.${name}.unitDepths.${part}`, -Infinity);
|
|
61
|
+
groups[name] = { near: g.near, zScale: number(g.zScale, `groups.${name}.zScale`, 0, false), pivot: number(g.pivot, `groups.${name}.pivot`, -Infinity), ...(g.unitDepths === undefined ? {} : { unitDepths }) };
|
|
62
|
+
}
|
|
63
|
+
const parts: Record<string, PartMap> = {};
|
|
64
|
+
for (const [name, value] of Object.entries(object(o.parts, 'parts'))) {
|
|
65
|
+
plain(name, `parts.${name}`); const p = object(value, `parts.${name}`); keys(p, ['map', 'source', 'frame', 'group', 'median', 'relief'], `parts.${name}`);
|
|
66
|
+
if (typeof p.map !== 'string' || !p.map) fail('DEPTH_RECIPE', `parts.${name}.map`, 'requires a declared numeric JSON map filename relative to the recipe');
|
|
67
|
+
if (p.source !== 'depth' && p.source !== 'normals') fail('DEPTH_RECIPE', `parts.${name}.source`, 'requires depth or normals');
|
|
68
|
+
if (p.frame !== 'part' && p.frame !== 'upscaled' && p.frame !== 'input') fail('DEPTH_RECIPE', `parts.${name}.frame`, 'requires part, upscaled or input; registration is never inferred from dimensions');
|
|
69
|
+
if (typeof p.group !== 'string' || !Object.hasOwn(groups, p.group)) fail('DEPTH_RECIPE', `parts.${name}.group`, 'must resolve to a declared group');
|
|
70
|
+
parts[name] = { map: p.map, source: p.source, frame: p.frame, group: p.group, median: number(p.median, `parts.${name}.median`, -Infinity), relief: number(p.relief, `parts.${name}.relief`, 0) };
|
|
71
|
+
}
|
|
72
|
+
if (!Object.keys(parts).length) fail('DEPTH_RECIPE', 'parts', 'requires at least one named part');
|
|
73
|
+
if (!Array.isArray(o.clear) || !o.clear.every(n => typeof n === 'string') || new Set(o.clear).size !== o.clear.length) fail('DEPTH_RECIPE', 'clear', 'requires an explicit array of unique part names, [] when none; no sheet is dropped implicitly');
|
|
74
|
+
for (const name of o.clear as string[]) { plain(name, 'clear'); if (Object.hasOwn(parts, name)) fail('DEPTH_RECIPE', `clear.${name}`, 'also has a new map; choose clear or apply'); }
|
|
75
|
+
return { spec: 'rig-parts-depth/1', prepare, groups, parts, clear: o.clear as string[] };
|
|
76
|
+
}
|
|
77
|
+
function emptyOutput(out: string, inputs: readonly string[]): void {
|
|
78
|
+
const canonical = (p: string): string => existsSync(p) ? realpathSync(p) : resolve(canonical(dirname(resolve(p))), basename(p));
|
|
79
|
+
const target = canonical(out);
|
|
80
|
+
for (const input of inputs) {
|
|
81
|
+
const path = canonical(input), r = relative(target, path), back = relative(path, target);
|
|
82
|
+
if (r === '' || (!r.startsWith(`..${sep}`) && r !== '..' && !r.startsWith(sep))) fail('DEPTH_OUTPUT_EMPTY', out, 'contains or is an input path; use a separate absent or empty output directory');
|
|
83
|
+
if (existsSync(input) && statSync(input).isDirectory() && back !== '..' && !back.startsWith(`..${sep}`) && !back.startsWith(sep)) fail('DEPTH_OUTPUT_EMPTY', out, 'is inside an input directory; choose a separate output so source inputs remain read-only');
|
|
84
|
+
}
|
|
85
|
+
if (existsSync(out) && (!statSync(out).isDirectory() || readdirSync(out).length !== 0)) fail('DEPTH_OUTPUT_EMPTY', out, 'is not an empty directory; choose an absent or empty output, never overwrite inputs or old evidence');
|
|
86
|
+
}
|
|
87
|
+
function preparedParts(partsDir: string, recipe: DepthRecipe): { manifest: Prepared; images: Map<string, Uint8Array> } {
|
|
88
|
+
const set = readPartSet(partsDir), images = new Map<string, Uint8Array>(), parts: PreparedPart[] = [];
|
|
89
|
+
for (const name of [...Object.keys(recipe.parts), ...recipe.clear]) if (!set.recs.some(p => p.name === name)) fail('DEPTH_PART_RESOLVES', name, 'names no assembled part; use exact parts.json names');
|
|
90
|
+
for (const part of set.recs.filter(p => Object.hasOwn(recipe.parts, p.name))) {
|
|
91
|
+
const art = set.images.get(part.name) as Raster, { longSide, paddingFraction, padding } = recipe.prepare;
|
|
92
|
+
const upscale = Math.max(1, Math.ceil(longSide / Math.max(art.width, art.height))), w = art.width * upscale, h = art.height * upscale;
|
|
93
|
+
const pad = Math.floor(Math.max(w, h) * paddingFraction) + padding, big = resize(art, w, h, 'lanczos3'), input = newRaster(w + pad * 2, h + pad * 2);
|
|
94
|
+
for (let i = 0; i < input.width * input.height; i++) input.data.set([128, 128, 128, 255], i * 4);
|
|
95
|
+
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
|
|
96
|
+
const i = (y * w + x) * 4, j = ((y + pad) * input.width + x + pad) * 4, a = big.data[i + 3];
|
|
97
|
+
for (let c = 0; c < 3; c++) input.data[j + c] = Math.floor((big.data[i + c] * a + 128 * (255 - a) + 127) / 255);
|
|
98
|
+
}
|
|
99
|
+
if (!alphaSupport(art).some(Boolean)) fail('DEPTH_MAP_SUPPORT', part.name, 'has no alpha>=128 pixels; a supported part is required');
|
|
100
|
+
const bytes = encodePngBytes(input), file = `${part.name}.png`; images.set(file, bytes);
|
|
101
|
+
parts.push({ part: part.name, crop: [part.x, part.y, part.w, part.h], sourceSha256: hash(readFileSync(join(partsDir, 'parts', file))), input: file, inputSha256: hash(bytes), size: [art.width, art.height], upscaled: [w, h], upscale, padding: pad, inputSize: [input.width, input.height] });
|
|
102
|
+
}
|
|
103
|
+
return { manifest: { spec: 'rig-parts-depth-inputs/1', partsSha256: hash(readFileSync(join(partsDir, 'parts.json'))), recipeSha256: hash(text(recipe)), background: 128, alpha: 128, parts }, images };
|
|
104
|
+
}
|
|
105
|
+
export function prepareDepth(input: { parts: string; config: string; out: string }): Prepared {
|
|
106
|
+
const recipe = parseDepthRecipe(readJson(input.config));
|
|
107
|
+
emptyOutput(input.out, [input.parts, input.config]);
|
|
108
|
+
const { manifest, images } = preparedParts(input.parts, recipe);
|
|
109
|
+
mkdirSync(input.out, { recursive: true });
|
|
110
|
+
for (const [file, bytes] of images) writeFileSync(join(input.out, file), bytes);
|
|
111
|
+
writeFileSync(join(input.out, 'manifest.json'), text(manifest));
|
|
112
|
+
return manifest;
|
|
113
|
+
}
|
|
114
|
+
function registeredMap(map: NumericMap, p: PreparedPart, frame: PartMap['frame'], at: string): NumericMap {
|
|
115
|
+
const [w, h] = frame === 'part' ? p.size : frame === 'input' ? p.inputSize : p.upscaled;
|
|
116
|
+
if (map.width !== w || map.height !== h) return fail('DEPTH_MAP_SIZE', at, `is ${map.width}x${map.height}; declared ${frame} frame is ${w}x${h}`);
|
|
117
|
+
if (frame !== 'input') return map;
|
|
118
|
+
const data: number[] = [];
|
|
119
|
+
for (let y = 0; y < p.upscaled[1]; y++) for (let x = 0; x < p.upscaled[0]; x++) for (let c = 0; c < map.channels; c++) data.push(map.data[((y + p.padding) * map.width + x + p.padding) * map.channels + c]);
|
|
120
|
+
return { ...map, width: p.upscaled[0], height: p.upscaled[1], data };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Extend the float field from its OWN stride2 integration support before BOX.
|
|
124
|
+
* Keep every supported height unchanged; Euclidean nearest seeds use row-major
|
|
125
|
+
* ties. A nearest seed must be on the four-neighbour boundary: an interior
|
|
126
|
+
* seed always has a strictly closer axis neighbour toward an unsupported point.
|
|
127
|
+
* No gray encoding or native-art mask is used on this integration grid.
|
|
128
|
+
*/
|
|
129
|
+
function extendIntegratedHeight(data: Float64Array, art: Raster): Float64Array {
|
|
130
|
+
const w = Math.ceil(art.width / 2), h = Math.ceil(art.height / 2);
|
|
131
|
+
const support = Uint8Array.from({ length: w * h }, (_, i) => art.data[((2 * Math.floor(i / w)) * art.width + 2 * (i % w)) * 4 + 3] >= 128 ? 1 : 0);
|
|
132
|
+
const boundary: number[] = [];
|
|
133
|
+
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
|
|
134
|
+
const i = y * w + x;
|
|
135
|
+
if (support[i] && (x === 0 || y === 0 || x === w - 1 || y === h - 1 || !support[i - 1] || !support[i + 1] || !support[i - w] || !support[i + w])) boundary.push(i);
|
|
136
|
+
}
|
|
137
|
+
// integrateNormals already refused empty/disconnected support before this call.
|
|
138
|
+
const filled = data.slice();
|
|
139
|
+
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
|
|
140
|
+
const i = y * w + x; if (support[i]) continue;
|
|
141
|
+
let distance = Infinity, seed = -1;
|
|
142
|
+
for (const j of boundary) {
|
|
143
|
+
const dx = x - j % w, dy = y - Math.floor(j / w), d = dx * dx + dy * dy;
|
|
144
|
+
if (d < distance) { distance = d; seed = j; }
|
|
145
|
+
}
|
|
146
|
+
filled[i] = data[seed];
|
|
147
|
+
}
|
|
148
|
+
return filled;
|
|
149
|
+
}
|
|
150
|
+
export function applyDepth(input: { parts: string; manifest: string; config: string; rigConfig: string; out: string }): Obj {
|
|
151
|
+
const recipe = parseDepthRecipe(readJson(input.config)), expected = preparedParts(input.parts, recipe);
|
|
152
|
+
const supplied = readJson(input.manifest);
|
|
153
|
+
if (text(supplied) !== text(expected.manifest)) fail('DEPTH_INPUT_BINDING', input.manifest, 'does not match the recipe, parts.json, art hashes, crop or padding; run depth-prepare again for these exact inputs');
|
|
154
|
+
for (const p of expected.manifest.parts) {
|
|
155
|
+
const file = join(dirname(input.manifest), p.input);
|
|
156
|
+
if (!existsSync(file) || hash(readFileSync(file)) !== p.inputSha256) fail('DEPTH_INPUT_BINDING', p.part, 'prepared inference PNG is missing or changed; restore its exact bytes or prepare again');
|
|
157
|
+
}
|
|
158
|
+
emptyOutput(input.out, [input.parts, input.config, input.manifest, input.rigConfig, ...Object.values(recipe.parts).map(p => resolve(dirname(input.config), p.map))]);
|
|
159
|
+
const rawParts = object(readJson(join(input.parts, 'parts.json')), 'parts.json'), file = readParts(join(input.parts, 'parts.json'));
|
|
160
|
+
for (const p of file.parts) if (Object.hasOwn(recipe.parts, p.name) && p.provenance?.depth?.kind === 'authored-unit') fail('DEPTH_AUTHORED_UNIT_CONFLICT', `part "${p.name}"`, 'has provenance.depth.kind "authored-unit"; a transported scalar reference cannot coexist with authored unit depth — retain the unit declaration or supply an explicitly reassembled scalar-compatible input; no automatic transition is made');
|
|
161
|
+
loadConfigAndAnimations(input.rigConfig);
|
|
162
|
+
const raw = object(readJson(input.rigConfig), 'rig config'), turn = object(raw.turn, 'config.turn');
|
|
163
|
+
for (const [name, group] of Object.entries(recipe.groups)) {
|
|
164
|
+
const target = name === 'head' ? turn : object(turn.body, 'config.turn.body'); target.pivot = group.pivot;
|
|
165
|
+
if (group.unitDepths !== undefined) target.unitDepths = group.unitDepths;
|
|
166
|
+
}
|
|
167
|
+
// Keep relative paths portable when relocating the output directory with its inputs.
|
|
168
|
+
const motion = raw.motion as Obj | undefined;
|
|
169
|
+
if (typeof motion?.animations_from === 'string') motion.animations_from = relative(resolve(input.out), resolve(dirname(input.rigConfig), motion.animations_from));
|
|
170
|
+
const control = (raw.generation as Obj | undefined)?.control as Obj | undefined;
|
|
171
|
+
if (typeof control?.skeleton === 'string' && !isSkeletonName(control.skeleton)) control.skeleton = relative(resolve(input.out), resolve(dirname(input.rigConfig), control.skeleton));
|
|
172
|
+
if (typeof raw.requirements === 'string') raw.requirements = relative(resolve(input.out), resolve(dirname(input.rigConfig), raw.requirements));
|
|
173
|
+
parseConfig(raw);
|
|
174
|
+
const writes = new Map<string, Uint8Array>(), rows: Obj[] = [], recs = rawParts.parts as Obj[];
|
|
175
|
+
// Retain auxiliary art (including alternate sets) and diagnostics byte-for-byte.
|
|
176
|
+
// Symlink inputs would obscure ownership and can escape this assembled directory.
|
|
177
|
+
const retained = new Map<string, Uint8Array>();
|
|
178
|
+
const collect = (dir: string, prefix: string): void => {
|
|
179
|
+
for (const ent of readdirSync(dir, { withFileTypes: true })) {
|
|
180
|
+
const path = join(dir, ent.name), key = prefix + ent.name;
|
|
181
|
+
if (ent.isDirectory()) collect(path, key + '/');
|
|
182
|
+
else if (ent.isFile()) retained.set(key, readFileSync(path));
|
|
183
|
+
else fail('DEPTH_INPUT_PRESENT', path, 'is not a regular owned file/directory; supply a self-contained assembled directory without symlinks');
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
collect(input.parts, '');
|
|
187
|
+
for (const p of file.parts) {
|
|
188
|
+
const name = p.name, bytes = readFileSync(join(input.parts, 'parts', `${name}.png`)), art = decodePngBytes(bytes, name), rec = recs.find(r => r.name === name) as Obj;
|
|
189
|
+
writes.set(`${name}.png`, bytes);
|
|
190
|
+
const declaration = Object.hasOwn(recipe.parts, name) ? recipe.parts[name] : undefined;
|
|
191
|
+
if (declaration === undefined) {
|
|
192
|
+
if (recipe.clear.includes(name)) { if (p.depth !== undefined) retained.delete(`parts/${p.depth.image}`); delete rec.depth; }
|
|
193
|
+
else if (p.depth !== undefined) { readSourceDepth(join(input.parts, 'parts', p.depth.image), art, null); writes.set(p.depth.image, readFileSync(join(input.parts, 'parts', p.depth.image))); }
|
|
194
|
+
continue;
|
|
195
|
+
}
|
|
196
|
+
const g = recipe.groups[declaration.group], target = declaration.group === 'head' ? turn : object(turn.body, 'config.turn.body');
|
|
197
|
+
if (!Object.hasOwn(object(target.roles, `config.turn.${declaration.group}.roles`), name)) fail('DEPTH_GROUP_BINDING', name, `declared group ${declaration.group} does not name this part in its roles; register it explicitly`);
|
|
198
|
+
const prepared = expected.manifest.parts.find(row => row.part === name) as PreparedPart;
|
|
199
|
+
const mapPath = resolve(dirname(input.config), declaration.map), numeric = readNumericMap(readJson(mapPath), name), mapBytes = readFileSync(mapPath);
|
|
200
|
+
const map = registeredMap(numeric, prepared, declaration.frame, name);
|
|
201
|
+
let values: ArrayLike<number>, normal: ReturnType<typeof integrateNormals> | undefined;
|
|
202
|
+
if (declaration.source === 'normals') {
|
|
203
|
+
if (map.channels !== 3) fail('DEPTH_MAP_FORMAT', name, 'normals require three signed XYZ channels');
|
|
204
|
+
const islands = connectedComponents({ width: art.width, height: art.height, data: alphaSupport(art) }, 4).count - 1;
|
|
205
|
+
if (islands !== 1) fail('DEPTH_NORMAL_ISLANDS', name, `native part has ${islands} alpha>=128 islands; exactly one closed convex part is required`);
|
|
206
|
+
const maskArt = map.width === art.width && map.height === art.height ? art : resize(art, map.width, map.height, 'lanczos3');
|
|
207
|
+
normal = integrateNormals(map, maskArt, name);
|
|
208
|
+
values = floatBox(extendIntegratedHeight(normal.data, maskArt), Math.ceil(map.width / 2), Math.ceil(map.height / 2), art.width, art.height);
|
|
209
|
+
} else {
|
|
210
|
+
if (map.channels !== 1) fail('DEPTH_MAP_FORMAT', name, 'depth requires one floating-point channel');
|
|
211
|
+
values = floatBox(map.data, map.width, map.height, art.width, art.height);
|
|
212
|
+
}
|
|
213
|
+
const { sheet, reading } = mapToSheet(values, art, declaration.median, declaration.relief, g.near, g.zScale, name), image = `${name}_depth.png`, sheetBytes = encodePngBytes(sheet);
|
|
214
|
+
if (file.parts.some(p => `${p.name}.png` === image)) fail('DEPTH_GROUP_BINDING', name, `sheet filename ${image} collides with artwork; use noncolliding part names`);
|
|
215
|
+
writes.set(image, sheetBytes);
|
|
216
|
+
if (p.depth !== undefined) retained.delete(`parts/${p.depth.image}`);
|
|
217
|
+
rec.depth = { image, near: g.near, zScale: g.zScale, sources: [{ from: p.from, image: basename(declaration.map), sha256: hash(mapBytes), crop: [0, 0, art.width, art.height], reading: depthReading(sheet, art, null) }] };
|
|
218
|
+
rows.push({ part: name, group: declaration.group, source: declaration.source, frame: declaration.frame, sourceSha256: prepared.sourceSha256, mapSha256: hash(mapBytes), inputSha256: prepared.inputSha256, sheetSha256: hash(sheetBytes), median: declaration.median, relief: declaration.relief, near: g.near, zScale: g.zScale, pivot: g.pivot, ...reading, sign: normal?.sign ?? 1, ...(normal === undefined ? {} : { integration: { stride: 2, iterations: normal.iterations, residual: normal.residual, coreMinusRim: normal.coreMinusRim, maxIterations: 3000, atol: 1e-6, btol: 1e-6 } }) });
|
|
219
|
+
}
|
|
220
|
+
// A replacement must share near/zScale with every retained part in its actual group.
|
|
221
|
+
for (const [name, g] of Object.entries(recipe.groups)) {
|
|
222
|
+
const target = name === 'head' ? turn : object(turn.body, 'config.turn.body'), roles = object(target.roles, `config.turn.${name}.roles`);
|
|
223
|
+
for (const rec of recs) if (Object.hasOwn(roles, String(rec.name)) && rec.depth !== undefined) {
|
|
224
|
+
const d = rec.depth as Obj;
|
|
225
|
+
if (d.near !== g.near || d.zScale !== g.zScale) fail('DEPTH_GROUP_BINDING', String(rec.name), `retained ${name} sheet near=${String(d.near)}, zScale=${String(d.zScale)}; declared group requires ${g.near}, ${g.zScale}; replace or explicitly clear that sheet`);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
const report = { spec: 'rig-parts-depth-report/1', partsSha256: expected.manifest.partsSha256, recipeSha256: expected.manifest.recipeSha256, manifestSha256: hash(readFileSync(input.manifest)), rigConfigSha256: hash(readFileSync(input.rigConfig)), alpha: 128, normalization: 'median, linear p5..p95', extension: 'nearest alpha>=128, row-major ties', cleared: recipe.clear, parts: rows };
|
|
229
|
+
mkdirSync(join(input.out, 'parts'), { recursive: true });
|
|
230
|
+
for (const [file, bytes] of retained) {
|
|
231
|
+
if (['parts.json', 'config.json', 'depth-report.json'].includes(file)) continue;
|
|
232
|
+
const target = join(input.out, file); mkdirSync(dirname(target), { recursive: true }); writeFileSync(target, bytes);
|
|
233
|
+
}
|
|
234
|
+
for (const [file, bytes] of writes) writeFileSync(join(input.out, 'parts', file), bytes);
|
|
235
|
+
writeFileSync(join(input.out, 'parts.json'), text(rawParts));
|
|
236
|
+
writeFileSync(join(input.out, 'config.json'), text(raw));
|
|
237
|
+
writeFileSync(join(input.out, 'depth-report.json'), text(report));
|
|
238
|
+
return report;
|
|
239
|
+
}
|
package/src/rig.ts
CHANGED
|
@@ -309,6 +309,14 @@ function lineGap(a: number, b: number): number {
|
|
|
309
309
|
/** The bones the face's line runs through: rigc's A51 draws its line through their origins, and the face bones are turned to that same line. */
|
|
310
310
|
export const EYE_BONES: readonly [string, string] = ['eye_r', 'eye_l'];
|
|
311
311
|
|
|
312
|
+
/**
|
|
313
|
+
* Issue #903: midpoint of absolute setup eye-line rolls measured on the public
|
|
314
|
+
* controls (maximum 4.864514437760526 degrees across the five parts examples,
|
|
315
|
+
* dancer and the head-turn demo) and three-quarter (32.106255955117845 degrees).
|
|
316
|
+
* This separates those inputs; it is not an anatomical or visual-quality bar.
|
|
317
|
+
*/
|
|
318
|
+
const HEAD_TURN_ROLL_LIMIT = (4.864514437760526 + 32.106255955117845) / 2;
|
|
319
|
+
|
|
312
320
|
/**
|
|
313
321
|
* The eye line (issue #239). It exists when parts.json holds an eye on each
|
|
314
322
|
* side — the first part tagged `eyewhite-r` and the first tagged `eyewhite-l`
|
|
@@ -3656,6 +3664,15 @@ export function buildWaistPairSource(
|
|
|
3656
3664
|
boneLandmarks.set(bName, [bEntry.x, bEntry.y]);
|
|
3657
3665
|
}
|
|
3658
3666
|
const turnWarnings: Problem[] = [];
|
|
3667
|
+
if ((cfg.turn?.depths !== undefined || cfg.turn?.roles !== undefined) && line.degrees !== null && Math.abs(line.degrees) > HEAD_TURN_ROLL_LIMIT) {
|
|
3668
|
+
const faces = parts.parts.filter(p => tagOf(p.from) === 'face' && p.cut_from === undefined).map(p => p.name);
|
|
3669
|
+
const names = faces.length === 0 ? line.parts : faces;
|
|
3670
|
+
turnWarnings.push({
|
|
3671
|
+
code: 'RIG_TURN_HEAD_ROLL',
|
|
3672
|
+
object: `${names.length === 1 ? 'part' : 'parts'} ${names.map(n => `"${n}"`).join(', ')}`,
|
|
3673
|
+
detail: `setup eye-line roll ${pyRound(line.degrees, 6)} degrees (Spine, counter-clockwise), absolute ${pyRound(Math.abs(line.degrees), 6)} exceeds limit ${pyRound(HEAD_TURN_ROLL_LIMIT, 6)} degrees; read through authored ${EYE_BONES.join(' and ')} origins on ${line.parts.map(n => `"${n}"`).join(' and ')} (an eye-origin proxy, not painting detection); the declared head turn uses upright yaw/pitch axes on an already rolled head; inspect the neck at both turn extremes; warning only, no pose or output changed`,
|
|
3674
|
+
});
|
|
3675
|
+
}
|
|
3659
3676
|
if (cfg.turn?.roles !== undefined || cfg.turn?.body !== undefined) {
|
|
3660
3677
|
buildDepth25DTurn(rig, motion, {
|
|
3661
3678
|
warnings: turnWarnings,
|