rig-parts 2.58.0 → 2.60.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/README.md +2 -0
- package/cli.ts +145 -4
- package/docs/AUTHORING.md +163 -39
- package/docs/DEPTH.md +114 -29
- package/docs/STABILITY.md +65 -5
- package/package.json +2 -2
- package/src/config.ts +12 -8
- package/src/depthmaps.ts +14 -4
- package/src/depthworkflow.ts +322 -7
- package/src/localweights.ts +20 -12
- package/src/modelarray.ts +206 -0
- package/src/neckdraft.ts +3 -3
- package/src/rig.ts +61 -38
- package/src/turn.ts +86 -18
package/docs/STABILITY.md
CHANGED
|
@@ -578,7 +578,9 @@ and do not certify visibility. See the
|
|
|
578
578
|
| `external-receipt` | `--kind` (mask), `--file`, `--painting`, `--producer`, `--out`; or `--verify`; or `--help` (`-h`) |
|
|
579
579
|
| `diff-components` | `--stack`, `--painting`, `--parts`, `--floor`; optional `--threshold`, `--figure`, `--owners`, `--help` (`-h`); exactly one of `--out`, `--verify` (issues #1005, #1291; exhaustive native error inventory, `rig-parts-diff-components/1` by default and `rig-parts-diff-components/2` with `--owners`, and byte-bound reader for both) |
|
|
580
580
|
| `diff-drafts` | `--left`, `--right`, `--out`; optional `--help` (`-h`) (issue #1369; draft-to-draft assemble comparison, `rig-parts-draft-diff/1`) |
|
|
581
|
+
| `depth-place` | `--parts`, `--config`, `--rig-config`, `--out`; optional `--check-turn`, `--help` (`-h`) (issue #1570) |
|
|
581
582
|
| `depth-prepare` | `--parts`, `--config`, `--out`; optional `--help` (`-h`) (issue #897; separate numeric-depth recipe) |
|
|
583
|
+
| `depth-map` | `--array`, `--input`, `--kind` (`depth` or `normals`), `--part`, `--out`; optional `--padding` (`LEFT,TOP,RIGHT,BOTTOM`), `--help` (`-h`) (issue #1573; NumPy array to input-frame numeric map) |
|
|
582
584
|
| `depth-bind` | `--map`, `--input`, `--part`; optional `--help` (`-h`) (issue #1284; exclusive receipt creation from current file bytes) |
|
|
583
585
|
| `depth-apply` | `--parts`, `--manifest`, `--config`, `--rig-config`, `--out`; optional `--groups` (a comma-separated list of the recipe's groups to apply, issue #1449), `--help` (`-h`) (issue #897; original character config is read-only) |
|
|
584
586
|
| `layers` | one positional path: a wrapper directory, a `layers.json` or a `.psd` (a file literally named `-h` is reached as `./-h`); with it, optional `--export` (a directory to write the wrapper form into, issue #359); or `--template` with `--canvas` and no path; or a positional head run with `--full`, `--source`, `--config` together for `PLAN_HEAD_GARMENT_OVERLAP` (issue #826); or `--help` (`-h`) |
|
|
@@ -755,7 +757,7 @@ part name, `[i]` an entry of a list):
|
|
|
755
757
|
- **meshes.<part>.influences** — optional, at least one: `maxInfluences` (a whole number, 1 or more, or null for no cap), `floor` ("cut" or "continuous")
|
|
756
758
|
- **meshes.<part>.ribs.<chain>** — required: `stations`
|
|
757
759
|
- **meshes.<part>.contour** — required: `tolerance`, `margin`, `spacing`; optional: `maxEdge`, `budget`, `stray`, `bridges`, `regions`, `bust`
|
|
758
|
-
- **meshes.<part>.contour.regions[i]** — required: `name`, `shape`, `bone`, `spacing`, `band`, and `cx`, `cy`, `r` for a circle or `points` for a polygon; optional: `cover`
|
|
760
|
+
- **meshes.<part>.contour.regions[i]** — required: `name`, `shape`, `bone`, `spacing`, `band`, and `cx`, `cy`, `r` for a circle or `points` for a polygon; optional: `cover`, `falloff`
|
|
759
761
|
- **meshes.<part>.contour.bust** — required: `apex_r`, `apex_l`, `cleavage`; optional: `alpha`, `clearance`, `bone_r`, `bone_l`, `spacing` (issue #475)
|
|
760
762
|
- **meshes.<part>.auto** — required: `source`, `sourceBounds`, `targets`, `influences`, `budget`, `minArtSamples`, `motion`; optional: `protect`, `regions`, the three Stage B opt-ins `boundaryRuns`, `retriangulate`, `removalOrder`, and `stimulus`
|
|
761
763
|
- **meshes.<part>.auto.source** — required: `tolerance`, `margin`, `spacing`; optional: `stray`
|
|
@@ -790,7 +792,7 @@ part name, `[i]` an entry of a list):
|
|
|
790
792
|
- **turn.unitDepths.<part>** — a calibrated world depth in rig pixels (issue #763)
|
|
791
793
|
- **turn.body**, when an object — required: `roles`, `pivot` (when `turn.pivot` is absent); optional: `bone`, `slider`, `counter`, `grid`, `unitDepths`, `boundaryDepths` (issue #787)
|
|
792
794
|
- **turn.body.roles.<part>** — `"surface"`, `"unit"` or `"rear"` (issue #787)
|
|
793
|
-
- **turn.body.unitDepths.<part>** — a calibrated world depth in rig pixels (
|
|
795
|
+
- **turn.body.unitDepths.<part>** — a calibrated world depth in rig pixels; body yaw uses `-(pivot + z - zRef) * sin(a)` ([Unit depth precedence](AUTHORING.md#unit-depth-precedence))
|
|
794
796
|
- **turn.deform.<key>** — a per-degree fraction or coupling share (FACE_DEFORM_FRACTIONS, issue #436)
|
|
795
797
|
- **turn.band**, when an object — optional: `yaw`, `pitch` (issue #472)
|
|
796
798
|
- **turn.surface**, when an object — optional: `radius` (issue #479)
|
|
@@ -1710,6 +1712,19 @@ against. The public examples' `expected/` files are this package's own snapshots
|
|
|
1710
1712
|
`tools/regenerate_examples.ts` writes them on Linux, and CI rebuilds the fetched
|
|
1711
1713
|
examples and compares the files whole with its `--check` (issue #1439).
|
|
1712
1714
|
|
|
1715
|
+
### Contour band weights (issue #1578)
|
|
1716
|
+
|
|
1717
|
+
With the default falloff, a region listed in `contour.regions` applies
|
|
1718
|
+
`4g²(1 − g)` to its nominal linear share `g` for `0 < g < 0.5`. An upgrade can
|
|
1719
|
+
change written weights and downstream output bytes. Geometric support and
|
|
1720
|
+
overlap refusals use the original `g`. The inner half of the band, zero-width
|
|
1721
|
+
bands, influence limits and rounding keep their prior behavior. A declared
|
|
1722
|
+
contour region accepts `falloff: "linear"` to recover its previous weights
|
|
1723
|
+
byte for byte. Other values are `CONFIG_FIELD_TYPE`. The circles derived
|
|
1724
|
+
from `contour.bust` and automatic mesh regions keep the prior linear ramp.
|
|
1725
|
+
An automatic region or a `contour.bust` block rejects `falloff` as
|
|
1726
|
+
`CONFIG_KEY_KNOWN`.
|
|
1727
|
+
|
|
1713
1728
|
### Opt-in hybrid provenance (issue #399)
|
|
1714
1729
|
|
|
1715
1730
|
A lower rigid limb piece may carry `limb.hybrid` instead of `limb.cap`:
|
|
@@ -2229,6 +2244,20 @@ byte-identical; an empty receipt list applies no replacement.
|
|
|
2229
2244
|
|
|
2230
2245
|
## Provider-map depth stages (#897)
|
|
2231
2246
|
|
|
2247
|
+
`depth-place` (#1570) accepts an optional `place` block on `rig-parts-depth/1`.
|
|
2248
|
+
The command requires the block, a body turn, and an absent or empty output
|
|
2249
|
+
directory. It emits `recipe.json`, `config.json` and `depth-place-report.json`
|
|
2250
|
+
(`rig-parts-depth-place-report/1`).
|
|
2251
|
+
Placement uses the declared polarity and a positive, explicit scale in rig
|
|
2252
|
+
pixels per model unit. It writes body placement medians and world rig `z` for
|
|
2253
|
+
body units, preserves declared reliefs and `zScale`, and resolves the body pivot
|
|
2254
|
+
to an offset from the reference depth. See the
|
|
2255
|
+
[placement contract](AUTHORING.md#place-body-depth-from-a-whole-painting-map-1570).
|
|
2256
|
+
With `--check-turn`, preparation, application and the real rig gate run in
|
|
2257
|
+
scratch space and the report adds `turnCheck`. It records any named check
|
|
2258
|
+
refusal. Successful placement emits its three files and exits `0` in either
|
|
2259
|
+
check outcome.
|
|
2260
|
+
|
|
2232
2261
|
The opt-in `depth-prepare` and `depth-apply` commands accept the separate
|
|
2233
2262
|
`rig-parts-depth/1` recipe and finite floating-point `rig-parts-map/1` JSON.
|
|
2234
2263
|
Prepared provenance is `rig-parts-depth-inputs/1`; application writes
|
|
@@ -2246,9 +2275,40 @@ field is absent without the flag, so those reports keep their bytes, and
|
|
|
2246
2275
|
`relief` is an explicit rig-pixel value, not an implicit width multiplier.
|
|
2247
2276
|
Part-width and head-referenced calibrations are authored recipe choices;
|
|
2248
2277
|
changing a calibration requires preparing its recipe again. Compare the same
|
|
2249
|
-
provider maps and preserve their provenance.
|
|
2250
|
-
|
|
2251
|
-
|
|
2278
|
+
provider maps and preserve their provenance. The additive `DEPTH_APPLY_CLIPPED`
|
|
2279
|
+
refusal applies before any output write, including for previously accepted
|
|
2280
|
+
clipped recipes, regardless of map binding receipt presence. Every original
|
|
2281
|
+
part pixel with alpha >= 128 must satisfy
|
|
2282
|
+
`0 < z < zScale` before encoding. The clip fraction divides the number of
|
|
2283
|
+
supported pixels at or beyond either boundary by the total supported pixel
|
|
2284
|
+
count.
|
|
2285
|
+
|
|
2286
|
+
For upper clipping the refusal gives the smallest binary64 group `zScale`
|
|
2287
|
+
strictly above the maximum original supported depth in the group. For each
|
|
2288
|
+
part with lower clipping it gives the minimum authored median (the next
|
|
2289
|
+
binary64 value above the maximum negated relief offset over that part's
|
|
2290
|
+
support) and its difference from the previous authored median. When both
|
|
2291
|
+
boundaries clip, the refusal includes both remedies. If a required value has
|
|
2292
|
+
no finite binary64 representation, the refusal directs the author to revise
|
|
2293
|
+
the calibration. A median adjustment may require recomputing the group scale.
|
|
2294
|
+
|
|
2295
|
+
`rig-parts-depth-report/1` keeps its existing keys. Each successful row names
|
|
2296
|
+
the part, declared relief, group `zScale` and a zero `clipFraction` over the
|
|
2297
|
+
original alpha >= 128 support. Shape quality is assessed separately.
|
|
2298
|
+
|
|
2299
|
+
`depth-map` (issue #1573) is an additive minor-version command. It accepts
|
|
2300
|
+
C-order NumPy `.npy` 1.0, 2.0, and 3.0 arrays with little-endian `float32` or
|
|
2301
|
+
`float64` data. Depth accepts `(H, W)` or `(H, W, 1)`. Normals accept
|
|
2302
|
+
`(H, W, 3)` with signed XYZ components in image axes (X right, Y down).
|
|
2303
|
+
Declared array-edge padding is cropped before mean pooling with independent
|
|
2304
|
+
positive integral X and Y factors derived from the prepared PNG dimensions.
|
|
2305
|
+
Pooled normals are normalized to unit length. The command refuses retained
|
|
2306
|
+
nonfinite samples, retained zero normals, and pooled zero normals by pixel.
|
|
2307
|
+
`--out` must name a new file in an existing writable directory. The command
|
|
2308
|
+
writes only the `rig-parts-map/1` JSON at the PNG dimensions and prints the
|
|
2309
|
+
next `depth-bind` command with its arguments quoted for a POSIX shell.
|
|
2310
|
+
Hand-authored `rig-parts-map/1` maps continue through
|
|
2311
|
+
the same bind and apply stages. See [Convert a NumPy array](DEPTH.md#convert-a-numpy-array).
|
|
2252
2312
|
|
|
2253
2313
|
The requirements file's `fps` becomes optional when no declared measurement
|
|
2254
2314
|
reads that rate (issue #965, additive for readers). Measurements in
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "rig-parts",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.60.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
6
|
"exports": {
|
|
@@ -75,7 +75,7 @@
|
|
|
75
75
|
},
|
|
76
76
|
"dependencies": {
|
|
77
77
|
"ag-psd": "^31.0.2",
|
|
78
|
-
"@rig-c/core": "3.9.
|
|
78
|
+
"@rig-c/core": "3.9.2"
|
|
79
79
|
},
|
|
80
80
|
"devDependencies": {
|
|
81
81
|
"@esotericsoftware/spine-core": "4.3.13",
|
package/src/config.ts
CHANGED
|
@@ -628,13 +628,14 @@ export function contourRegionsOf(spec: ContourSpec): ContourRegionSpec[] {
|
|
|
628
628
|
/**
|
|
629
629
|
* A local deformation region: a shape in rig px, a control bone, the spacing
|
|
630
630
|
* the mesh is refined at inside it and its band, and the band the bone's
|
|
631
|
-
* weight falls across
|
|
632
|
-
*
|
|
633
|
-
*
|
|
631
|
+
* weight falls across. `falloff: 'linear'` keeps the nominal linear share
|
|
632
|
+
* throughout the band. By default contour weighting eases its outer half.
|
|
633
|
+
* Every coordinate and length is a multiple of 1/256 px: the nominal share's
|
|
634
|
+
* 0 and 1 are decided exactly on that grid.
|
|
634
635
|
*/
|
|
635
636
|
export type ContourRegionSpec =
|
|
636
|
-
| { name: string; shape: 'circle'; cx: number; cy: number; r: number; spacing: number; band: number; bone: string; cover?: string }
|
|
637
|
-
| { name: string; shape: 'polygon'; points: Point[]; spacing: number; band: number; bone: string; cover?: string };
|
|
637
|
+
| { name: string; shape: 'circle'; cx: number; cy: number; r: number; spacing: number; band: number; bone: string; cover?: string; falloff?: 'linear' }
|
|
638
|
+
| { name: string; shape: 'polygon'; points: Point[]; spacing: number; band: number; bone: string; cover?: string; falloff?: 'linear' };
|
|
638
639
|
|
|
639
640
|
/**
|
|
640
641
|
* One mesh in the automatic mode (issue #126, item 2): the contour mesh over
|
|
@@ -795,8 +796,8 @@ export interface ArtFitBoundsSpec {
|
|
|
795
796
|
* A region of the automatic mode, in one of two forms (issue #155).
|
|
796
797
|
*
|
|
797
798
|
* - **Weight and density** ({@link AutoWeightRegionSpec}): a shape and a
|
|
798
|
-
* control bone as a contour region has them, the bone's weight
|
|
799
|
-
*
|
|
799
|
+
* control bone as a contour region has them, the bone's linear weight
|
|
800
|
+
* `band` (`src/localweights.ts`), and the density rig-c holds the
|
|
800
801
|
* mesh to (§5 of its contract): every edge meeting the region at most
|
|
801
802
|
* `maxEdgeLength` px (L0), relaxing as `L0 + grade·d` across `transition` px
|
|
802
803
|
* outside it, and the region's art sample floor (P9).
|
|
@@ -3875,7 +3876,7 @@ function checkContour(c: Check, at: string, v: Json, bones: Set<string>): void {
|
|
|
3875
3876
|
const rat = `${at}.regions[${i}]`;
|
|
3876
3877
|
const shape = typeof rv === 'object' && rv !== null && !Array.isArray(rv) ? (rv as Record<string, Json>).shape : undefined;
|
|
3877
3878
|
const own = shape === 'circle' ? ['cx', 'cy', 'r'] : shape === 'polygon' ? ['points'] : [];
|
|
3878
|
-
const r = c.object(rat, rv, ['name', 'shape', 'bone', 'spacing', 'band', ...own], ['cover']);
|
|
3879
|
+
const r = c.object(rat, rv, ['name', 'shape', 'bone', 'spacing', 'band', ...own], ['cover', 'falloff']);
|
|
3879
3880
|
if (r === null) return;
|
|
3880
3881
|
if ('shape' in r && own.length === 0) c.fail('CONFIG_FIELD_TYPE', `${rat}.shape`, `is ${show(r.shape)}; "circle" (with cx, cy, r) or "polygon" (with points) is required`);
|
|
3881
3882
|
if ('name' in r && c.string(`${rat}.name`, r.name)) {
|
|
@@ -3888,6 +3889,9 @@ function checkContour(c: Check, at: string, v: Json, bones: Set<string>): void {
|
|
|
3888
3889
|
if ('cover' in r && (typeof r.cover !== 'string' || r.cover.length === 0)) {
|
|
3889
3890
|
c.fail('CONFIG_FIELD_TYPE', `${rat}.cover`, `is ${show(r.cover)}; a non-empty part name is required`);
|
|
3890
3891
|
}
|
|
3892
|
+
if ('falloff' in r && r.falloff !== 'linear') {
|
|
3893
|
+
c.fail('CONFIG_FIELD_TYPE', `${rat}.falloff`, `is ${show(r.falloff)}; "linear" is required for the legacy ramp, or leave falloff out to ease the outer half of the band`);
|
|
3894
|
+
}
|
|
3891
3895
|
if ('spacing' in r) c.number(`${rat}.spacing`, r.spacing, 'positive');
|
|
3892
3896
|
if ('band' in r) onGrid(`${rat}.band`, r.band, 'non-negative');
|
|
3893
3897
|
if (shape === 'circle') {
|
package/src/depthmaps.ts
CHANGED
|
@@ -149,7 +149,9 @@ export function integrateNormals(map: NumericMap, art: Raster, at: string): Norm
|
|
|
149
149
|
}
|
|
150
150
|
|
|
151
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): {
|
|
152
|
+
export function mapToSheet(data: ArrayLike<number>, art: Raster, median: number, relief: number, near: 'black' | 'white', zScale: number, at: string): {
|
|
153
|
+
sheet: Raster; reading: MapSheetReading; maxZ: number; minOffset: number; clipsLow: boolean;
|
|
154
|
+
} {
|
|
153
155
|
const support = alphaSupport(art), values: number[] = [];
|
|
154
156
|
for (let i = 0; i < support.length; i++) if (support[i]) values.push(data[i]);
|
|
155
157
|
if (!values.length) return depthMapFail('DEPTH_MAP_SUPPORT', at, 'has no alpha>=128 pixels; a part with declared support is required');
|
|
@@ -158,13 +160,21 @@ export function mapToSheet(data: ArrayLike<number>, art: Raster, median: number,
|
|
|
158
160
|
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
161
|
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
162
|
const sheet = newRaster(art.width, art.height), seeds = newRaster(art.width, art.height), levels = new Set<number>(); let clipped = 0;
|
|
163
|
+
let maxZ = -Infinity, minOffset = Infinity, clipsLow = false;
|
|
161
164
|
for (let i = 0; i < support.length; i++) {
|
|
162
|
-
const
|
|
165
|
+
const offset = relief * (spread === 0 ? 0 : (data[i] - med) / spread);
|
|
166
|
+
const z = median + offset, unit = Math.max(0, Math.min(1, near === 'white' ? z / zScale : 1 - z / zScale));
|
|
163
167
|
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
168
|
// Uint8ClampedArray implements ties-to-even, as numpy.round does.
|
|
165
169
|
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
170
|
seeds.data[i * 4 + 3] = support[i] ? 255 : 0;
|
|
167
|
-
if (support[i]) {
|
|
171
|
+
if (support[i]) {
|
|
172
|
+
levels.add(sheet.data[i * 4]);
|
|
173
|
+
maxZ = Math.max(maxZ, z);
|
|
174
|
+
minOffset = Math.min(minOffset, offset);
|
|
175
|
+
if (z <= 0) clipsLow = true;
|
|
176
|
+
if (z <= 0 || z >= zScale) clipped++;
|
|
177
|
+
}
|
|
168
178
|
}
|
|
169
|
-
return { sheet: extendDepthSilhouette(sheet, seeds), reading: { levels: levels.size, clipFraction: clipped / values.length, reliefRigPixels: relief, rawMedian: med, rawP5: lo, rawP95: hi } };
|
|
179
|
+
return { sheet: extendDepthSilhouette(sheet, seeds), reading: { levels: levels.size, clipFraction: clipped / values.length, reliefRigPixels: relief, rawMedian: med, rawP5: lo, rawP95: hi }, maxZ, minOffset, clipsLow };
|
|
170
180
|
}
|
package/src/depthworkflow.ts
CHANGED
|
@@ -4,16 +4,16 @@
|
|
|
4
4
|
*/
|
|
5
5
|
import { createHash } from 'node:crypto';
|
|
6
6
|
import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, statSync, writeFileSync } from 'node:fs';
|
|
7
|
-
import { basename, dirname, join, relative, resolve, sep } from 'node:path';
|
|
7
|
+
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
8
8
|
import { refuseStaleAssembly } from './assembly-reading.ts';
|
|
9
9
|
import { PartsError, type Problem } from './errors.ts';
|
|
10
10
|
import { loadConfigAndAnimations, parseConfig } from './config.ts';
|
|
11
11
|
import { relocateConfigReferences } from './configrelocation.ts';
|
|
12
12
|
import { depthReading, readSourceDepth } from './depthsheets.ts';
|
|
13
13
|
import { readEditorReceipts } from './editreceipt.ts';
|
|
14
|
-
import { alphaSupport, depthMapFail as fail, floatBox, integrateNormals, mapToSheet, readNumericMap, type NumericMap } from './depthmaps.ts';
|
|
14
|
+
import { alphaSupport, depthMapFail as fail, floatBox, integrateNormals, mapQuantile, mapToSheet, readNumericMap, type NumericMap } from './depthmaps.ts';
|
|
15
15
|
import { depthImageReference, partImageReference, readParts } from './parts.ts';
|
|
16
|
-
import { readPartSet } from './propose.ts';
|
|
16
|
+
import { readPartSet, type PartSet } from './propose.ts';
|
|
17
17
|
import { decodePngBytes, encodePngBytes } from './raster/png.ts';
|
|
18
18
|
import { resize } from './raster/resize.ts';
|
|
19
19
|
import { connectedComponents } from './raster/components.ts';
|
|
@@ -23,11 +23,20 @@ type Obj = Record<string, unknown>;
|
|
|
23
23
|
interface PrepareOptions { longSide: number; paddingFraction: number; padding: number }
|
|
24
24
|
interface Group { median?: never; near: 'black' | 'white'; zScale: number; pivot: number; unitDepths?: Record<string, number> }
|
|
25
25
|
interface PartMap { map: string; source: 'depth' | 'normals'; frame: 'part' | 'upscaled' | 'input'; group: string; median: number; relief: number }
|
|
26
|
-
|
|
26
|
+
interface Placement { map: string; near: Group['near']; scale: number; anchor: string; pivot?: 'anchor' | number; round?: string[] }
|
|
27
|
+
export interface DepthRecipe { spec: 'rig-parts-depth/1'; prepare: PrepareOptions; groups: Record<string, Group>; parts: Record<string, PartMap>; clear: string[]; place?: Placement }
|
|
27
28
|
interface PreparedPart { part: string; crop: number[]; sourceSha256: string; input: string; inputSha256: string; size: number[]; upscaled: number[]; upscale: number; padding: number; inputSize: number[] }
|
|
28
29
|
interface Prepared { spec: 'rig-parts-depth-inputs/1'; partsSha256: string; recipeSha256: string; background: number; alpha: number; parts: PreparedPart[] }
|
|
29
30
|
const hash = (bytes: Uint8Array | string): string => createHash('sha256').update(bytes).digest('hex');
|
|
30
31
|
const text = (raw: unknown): string => JSON.stringify(raw, null, 2) + '\n';
|
|
32
|
+
/** The next binary64 value above a finite, nonnegative depth bound. */
|
|
33
|
+
function aboveDepthBound(bound: number): number {
|
|
34
|
+
if (bound === 0) return Number.MIN_VALUE;
|
|
35
|
+
const bits = new DataView(new ArrayBuffer(8));
|
|
36
|
+
bits.setFloat64(0, bound);
|
|
37
|
+
bits.setBigUint64(0, bits.getBigUint64(0) + 1n);
|
|
38
|
+
return bits.getFloat64(0);
|
|
39
|
+
}
|
|
31
40
|
function object(raw: unknown, at: string): Obj {
|
|
32
41
|
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return fail('DEPTH_RECIPE', at, 'requires an object with the documented fields');
|
|
33
42
|
return raw as Obj;
|
|
@@ -49,7 +58,14 @@ function plain(name: string, at: string): void {
|
|
|
49
58
|
if (!name || name.startsWith('.') || /[\\/]/.test(name) || name.includes('\0')) fail('DEPTH_RECIPE', at, `name "${name}" is not a plain part filename`);
|
|
50
59
|
}
|
|
51
60
|
export function parseDepthRecipe(raw: unknown): DepthRecipe {
|
|
52
|
-
const
|
|
61
|
+
const { recipe, place } = readDepthRecipe(raw);
|
|
62
|
+
if (place === undefined) return recipe;
|
|
63
|
+
const { scale } = place;
|
|
64
|
+
if (!isPlacementScale(scale)) throw new PartsError([placementScaleProblem(scale)]);
|
|
65
|
+
return { ...recipe, place: { ...place, scale } };
|
|
66
|
+
}
|
|
67
|
+
function readDepthRecipe(raw: unknown): { recipe: DepthRecipe; place?: Omit<Placement, 'scale'> & { scale: unknown } } {
|
|
68
|
+
const o = object(raw, 'depth recipe'); keys(o, ['spec', 'prepare', 'groups', 'parts', 'clear', 'place'], 'depth recipe');
|
|
53
69
|
if (o.spec !== 'rig-parts-depth/1') fail('DEPTH_RECIPE', 'spec', 'requires rig-parts-depth/1');
|
|
54
70
|
const p = object(o.prepare, 'prepare'); keys(p, ['longSide', 'paddingFraction', 'padding'], 'prepare');
|
|
55
71
|
const prepare = { longSide: number(p.longSide, 'prepare.longSide', 1), paddingFraction: number(p.paddingFraction, 'prepare.paddingFraction', 0), padding: number(p.padding, 'prepare.padding', 0) };
|
|
@@ -75,7 +91,27 @@ export function parseDepthRecipe(raw: unknown): DepthRecipe {
|
|
|
75
91
|
if (!Object.keys(parts).length) fail('DEPTH_RECIPE', 'parts', 'requires at least one named part');
|
|
76
92
|
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');
|
|
77
93
|
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'); }
|
|
78
|
-
|
|
94
|
+
const recipe: DepthRecipe = { spec: 'rig-parts-depth/1', prepare, groups, parts, clear: o.clear as string[] };
|
|
95
|
+
if (o.place === undefined) return { recipe };
|
|
96
|
+
const at = 'place', place = object(o.place, at);
|
|
97
|
+
keys(place, ['map', 'near', 'scale', 'anchor', 'pivot', 'round'], at);
|
|
98
|
+
if (typeof place.map !== 'string' || !place.map.trim()) return fail('DEPTH_RECIPE', 'place.map', 'requires a numeric JSON map in the painting frame');
|
|
99
|
+
if (place.near !== 'black' && place.near !== 'white') return fail('DEPTH_PLACE_NEAR', 'place.near', `is ${bindingFound(place.near)}; declare black or white for the painting map`);
|
|
100
|
+
if (typeof place.anchor !== 'string' || !place.anchor) return fail('DEPTH_PLACE_ANCHOR', 'place.anchor', 'requires the name of the body turn\'s first surface');
|
|
101
|
+
plain(place.anchor, 'place.anchor');
|
|
102
|
+
const pivot = place.pivot === undefined || place.pivot === 'anchor' ? place.pivot : number(place.pivot, 'place.pivot', -Infinity);
|
|
103
|
+
const round = place.round;
|
|
104
|
+
if (round !== undefined && (!Array.isArray(round) || !round.every(n => typeof n === 'string') || new Set(round).size !== round.length)) {
|
|
105
|
+
return fail('DEPTH_PLACE_ROUND', 'place.round', 'requires an array of unique recipe part names');
|
|
106
|
+
}
|
|
107
|
+
return { recipe, place: { map: place.map, near: place.near, scale: place.scale, anchor: place.anchor,
|
|
108
|
+
...(pivot === undefined ? {} : { pivot }), ...(round === undefined ? {} : { round }) } };
|
|
109
|
+
}
|
|
110
|
+
function isPlacementScale(raw: unknown): raw is number {
|
|
111
|
+
return typeof raw === 'number' && Number.isFinite(raw) && raw > 0;
|
|
112
|
+
}
|
|
113
|
+
function placementScaleProblem(raw: unknown): Problem {
|
|
114
|
+
return { code: 'DEPTH_PLACE_SCALE', object: 'place.scale', detail: `is ${bindingFound(raw)}; declare a finite number > 0 (rig px per map unit)` };
|
|
79
115
|
}
|
|
80
116
|
function emptyOutput(out: string, inputs: readonly string[]): void {
|
|
81
117
|
const canonical = (p: string): string => existsSync(p) ? realpathSync(p) : resolve(canonical(dirname(resolve(p))), basename(p));
|
|
@@ -114,6 +150,264 @@ export function prepareDepth(input: { parts: string; config: string; out: string
|
|
|
114
150
|
writeFileSync(join(input.out, 'manifest.json'), text(manifest));
|
|
115
151
|
return manifest;
|
|
116
152
|
}
|
|
153
|
+
|
|
154
|
+
type RoundPlacement = {
|
|
155
|
+
sections: number;
|
|
156
|
+
invertedSections: number;
|
|
157
|
+
scale: number | null;
|
|
158
|
+
iqr: [number, number] | null;
|
|
159
|
+
};
|
|
160
|
+
interface PlacementSample {
|
|
161
|
+
part: string;
|
|
162
|
+
group: 'body';
|
|
163
|
+
visibleCount: number;
|
|
164
|
+
visibleFraction: number;
|
|
165
|
+
rawMedian: number;
|
|
166
|
+
rawP5: number;
|
|
167
|
+
rawP95: number;
|
|
168
|
+
reliefRatio: number | null;
|
|
169
|
+
round?: RoundPlacement;
|
|
170
|
+
}
|
|
171
|
+
export type DepthPlacementTurnCheck = { status: 'built' } | {
|
|
172
|
+
status: 'refused';
|
|
173
|
+
stage: 'prepare' | 'apply' | 'rig';
|
|
174
|
+
problems: readonly Problem[];
|
|
175
|
+
winding: readonly {
|
|
176
|
+
rule: string; animation: string; part: string; attachment: string; key: number;
|
|
177
|
+
endKey?: number; reversedTriangles: number; triangles: number; frame?: string;
|
|
178
|
+
}[];
|
|
179
|
+
};
|
|
180
|
+
export interface DepthPlacementReport {
|
|
181
|
+
spec: 'rig-parts-depth-place-report/1';
|
|
182
|
+
near: Placement['near'];
|
|
183
|
+
scale: number;
|
|
184
|
+
anchor: string;
|
|
185
|
+
pivot: number;
|
|
186
|
+
parts: Array<PlacementSample & { rigMedian: number; impliedRelief: number | null }>;
|
|
187
|
+
turnCheck?: DepthPlacementTurnCheck;
|
|
188
|
+
}
|
|
189
|
+
type DepthPlacementInput = { parts: string; config: string; rigConfig: string; out: string };
|
|
190
|
+
|
|
191
|
+
/** The projection uses the full silhouette for its axis and section widths,
|
|
192
|
+
* and only pixels owned by this part for its regression ordinates. */
|
|
193
|
+
function roundPlacement(support: readonly number[], artWidth: number, valueAt: (i: number) => number | undefined, near: Placement['near']): RoundPlacement {
|
|
194
|
+
let sx = 0, sy = 0;
|
|
195
|
+
for (const i of support) { sx += i % artWidth; sy += Math.floor(i / artWidth); }
|
|
196
|
+
const cx = sx / support.length, cy = sy / support.length;
|
|
197
|
+
let xx = 0, xy = 0, yy = 0;
|
|
198
|
+
for (const i of support) {
|
|
199
|
+
const x = i % artWidth - cx, y = Math.floor(i / artWidth) - cy;
|
|
200
|
+
xx += x * x; xy += x * y; yy += y * y;
|
|
201
|
+
}
|
|
202
|
+
if (xx === yy && xy === 0) return { sections: 0, invertedSections: 0, scale: null, iqr: null };
|
|
203
|
+
const angle = Math.atan2(2 * xy, xx - yy) / 2;
|
|
204
|
+
const [c, s] = xy === 0 ? (xx > yy ? [1, 0] : [0, 1]) : [Math.cos(angle), Math.sin(angle)];
|
|
205
|
+
const points = support.map(i => {
|
|
206
|
+
const x = i % artWidth - cx, y = Math.floor(i / artWidth) - cy;
|
|
207
|
+
return { i, along: x * c + y * s, across: -x * s + y * c };
|
|
208
|
+
});
|
|
209
|
+
const start = points.reduce((min, p) => Math.min(min, p.along), Infinity);
|
|
210
|
+
const bands = new Map<number, { lo: number; hi: number; visible: Array<{ across: number; value: number }> }>();
|
|
211
|
+
for (const { i, along, across } of points) {
|
|
212
|
+
const k = Math.floor((along - start) / 4);
|
|
213
|
+
let band = bands.get(k);
|
|
214
|
+
if (band === undefined) { band = { lo: across, hi: across, visible: [] }; bands.set(k, band); }
|
|
215
|
+
band.lo = Math.min(band.lo, across);
|
|
216
|
+
band.hi = Math.max(band.hi, across);
|
|
217
|
+
const value = valueAt(i);
|
|
218
|
+
if (value !== undefined) band.visible.push({ across, value: near === 'black' ? value : -value });
|
|
219
|
+
}
|
|
220
|
+
const scales: number[] = [];
|
|
221
|
+
let invertedSections = 0;
|
|
222
|
+
for (const { lo, hi, visible } of bands.values()) {
|
|
223
|
+
const r = (hi - lo) / 2, center = (hi + lo) / 2;
|
|
224
|
+
if (r === 0) continue;
|
|
225
|
+
const samples = visible.flatMap(({ across, value }) => {
|
|
226
|
+
const v = Math.abs(across - center);
|
|
227
|
+
if (v > 0.8 * r) return [];
|
|
228
|
+
// Rationalized r - sqrt(r*r - v*v) keeps shallow sagitta samples distinct.
|
|
229
|
+
return [{ g: v * v / (r + Math.sqrt(r * r - v * v)), value }];
|
|
230
|
+
});
|
|
231
|
+
if (samples.length < 2 || samples.every(({ g }) => g === samples[0].g)) continue;
|
|
232
|
+
const baseline = samples[0].value;
|
|
233
|
+
let sumG = 0, sumZ = 0;
|
|
234
|
+
for (const { g, value } of samples) { sumG += g; sumZ += value - baseline; }
|
|
235
|
+
const meanG = sumG / samples.length, meanZ = sumZ / samples.length;
|
|
236
|
+
let variance = 0, covariance = 0;
|
|
237
|
+
for (const { g, value } of samples) {
|
|
238
|
+
variance += (g - meanG) ** 2;
|
|
239
|
+
covariance += (g - meanG) * (value - baseline - meanZ);
|
|
240
|
+
}
|
|
241
|
+
if (variance === 0) continue;
|
|
242
|
+
const slope = covariance / variance, scale = 1 / slope;
|
|
243
|
+
if (!Number.isFinite(slope) || (slope > 0 && !Number.isFinite(scale))) {
|
|
244
|
+
return fail('DEPTH_MAP_FORMAT', 'place.map', 'round-section regression overflows; provide representable raw depths');
|
|
245
|
+
}
|
|
246
|
+
if (slope <= 0) invertedSections++;
|
|
247
|
+
else scales.push(scale);
|
|
248
|
+
}
|
|
249
|
+
scales.sort((a, b) => a - b);
|
|
250
|
+
return { sections: scales.length + invertedSections, invertedSections,
|
|
251
|
+
scale: scales.length === 0 ? null : mapQuantile(scales, 0.5),
|
|
252
|
+
iqr: scales.length === 0 ? null : [mapQuantile(scales, 0.25), mapQuantile(scales, 0.75)] };
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function placementSamples(set: PartSet, map: NumericMap, reliefs: ReadonlyMap<string, number>, place: Omit<Placement, 'scale'>, selected: ReadonlySet<string>): PlacementSample[] {
|
|
256
|
+
const roundNames = new Set(place.round);
|
|
257
|
+
// Iterate front-to-back so a pixel can be claimed only once, including by
|
|
258
|
+
// layers not selected for placement. Scan the stored crop, in rig pixels.
|
|
259
|
+
const claimed = new Uint8Array(map.data.length);
|
|
260
|
+
const rows: PlacementSample[] = [], problems: Problem[] = [];
|
|
261
|
+
for (const p of [...set.recs].reverse()) {
|
|
262
|
+
const art = set.images.get(p.name)!;
|
|
263
|
+
const support = alphaSupport(art), values: number[] = [], roundSupport: number[] = [];
|
|
264
|
+
const roundValues = roundNames.has(p.name) ? new Map<number, number>() : undefined;
|
|
265
|
+
const measure = selected.has(p.name);
|
|
266
|
+
let supportCount = 0;
|
|
267
|
+
for (let y = 0; y < p.h; y++) for (let x = 0; x < p.w; x++) {
|
|
268
|
+
const local = y * p.w + x;
|
|
269
|
+
if (!support[local]) continue;
|
|
270
|
+
if (roundValues !== undefined) roundSupport.push(local);
|
|
271
|
+
if (measure) supportCount++;
|
|
272
|
+
const pixel = (p.y + y) * map.width + p.x + x;
|
|
273
|
+
if (claimed[pixel]) continue;
|
|
274
|
+
claimed[pixel] = 1;
|
|
275
|
+
if (measure) values.push(map.data[pixel]);
|
|
276
|
+
roundValues?.set(local, map.data[pixel]);
|
|
277
|
+
}
|
|
278
|
+
if (!measure) continue;
|
|
279
|
+
if (values.length === 0) {
|
|
280
|
+
problems.push({ code: 'DEPTH_PLACE_OCCLUDED', object: `part "${p.name}"`,
|
|
281
|
+
detail: `has no visible pixels (0 of ${supportCount} with alpha>=128); at least one topmost pixel is required for a median` });
|
|
282
|
+
continue;
|
|
283
|
+
}
|
|
284
|
+
values.sort((a, b) => a - b);
|
|
285
|
+
const constant = values[0] === values[values.length - 1] ? values[0] : undefined;
|
|
286
|
+
const rawMedian = constant ?? mapQuantile(values, 0.5);
|
|
287
|
+
const rawP5 = constant ?? mapQuantile(values, 0.05), rawP95 = constant ?? mapQuantile(values, 0.95);
|
|
288
|
+
const span = rawP95 - rawP5, relief = reliefs.get(p.name);
|
|
289
|
+
const ratio = relief === undefined || span <= 0 ? null : relief / span;
|
|
290
|
+
if (!Number.isFinite(span)) return fail('DEPTH_MAP_FORMAT', `part "${p.name}"`, 'visible p5-p95 span overflows; provide representable raw depths');
|
|
291
|
+
rows.push({ part: p.name, group: 'body', visibleCount: values.length,
|
|
292
|
+
visibleFraction: values.length / supportCount, rawMedian, rawP5, rawP95, reliefRatio: Number.isFinite(ratio) ? ratio : null,
|
|
293
|
+
...(roundValues === undefined ? {} : { round: roundPlacement(roundSupport, p.w, i => roundValues.get(i), place.near) }) });
|
|
294
|
+
}
|
|
295
|
+
if (problems.length) throw new PartsError(problems);
|
|
296
|
+
return rows.reverse();
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function checkPlacementScale(scale: unknown, samples: readonly PlacementSample[], reliefs: ReadonlyMap<string, number>): number {
|
|
300
|
+
const problems: Problem[] = [];
|
|
301
|
+
const validScale = isPlacementScale(scale) ? scale : undefined;
|
|
302
|
+
if (validScale === undefined) {
|
|
303
|
+
problems.push(placementScaleProblem(scale));
|
|
304
|
+
for (const { part, reliefRatio, rawP5, rawP95, round } of samples) {
|
|
305
|
+
const relief = !reliefs.has(part) ? 'unavailable (no body recipe relief)'
|
|
306
|
+
: reliefRatio === null ? `unavailable (p5=${rawP5}, p95=${rawP95})` : String(reliefRatio);
|
|
307
|
+
const fit = round === undefined ? '' : `; implied round scale for "${part}" = ${round.scale ?? 'unavailable'}, IQR=${round.iqr?.join('..') ?? 'unavailable'}, sections=${round.sections}`;
|
|
308
|
+
problems.push({ code: 'DEPTH_PLACE_SCALE', object: 'place.scale', detail: `implied relief ratio for "${part}" = ${relief}${fit}` });
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
for (const { part, round } of samples) {
|
|
312
|
+
if (round === undefined) continue;
|
|
313
|
+
if (round.sections === 0) problems.push({ code: 'DEPTH_PLACE_ROUND', object: `part "${part}"`, detail: 'has 0 measurable round sections; visible samples at distinct sagittae are required on a resolved principal axis' });
|
|
314
|
+
else if (round.invertedSections > 0) problems.push({ code: 'DEPTH_PLACE_ROUND', object: `part "${part}"`,
|
|
315
|
+
detail: `${round.invertedSections} of ${round.sections} fitted sections (fraction ${round.invertedSections / round.sections}) have a non-positive slope; required edges farther than the centre under place.near` });
|
|
316
|
+
}
|
|
317
|
+
if (validScale === undefined || problems.length) throw new PartsError(problems);
|
|
318
|
+
return validScale;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/** Validate once, then write paths relative to each chosen destination. */
|
|
322
|
+
export function stageDepthPlacement(input: DepthPlacementInput): {
|
|
323
|
+
report: DepthPlacementReport;
|
|
324
|
+
write(out: string, turnCheck?: DepthPlacementTurnCheck): { recipe: string; config: string };
|
|
325
|
+
} {
|
|
326
|
+
const recipeDir = dirname(resolve(input.config)), configDir = dirname(resolve(input.rigConfig));
|
|
327
|
+
const { recipe, place } = readDepthRecipe(readJson(input.config));
|
|
328
|
+
if (place === undefined) return fail('DEPTH_RECIPE', 'place', 'is absent; declare the painting map, near, scale and anchor');
|
|
329
|
+
const mapFile = resolve(recipeDir, place.map);
|
|
330
|
+
const maps = Object.values(recipe.parts).flatMap(p => { const file = resolve(recipeDir, p.map); return [file, file + '.binding.json']; });
|
|
331
|
+
const sources = [resolve(input.parts), resolve(input.config), resolve(input.rigConfig), mapFile, ...maps];
|
|
332
|
+
emptyOutput(input.out, sources);
|
|
333
|
+
const set = readPartSet(input.parts), names = new Set(set.recs.map(p => p.name));
|
|
334
|
+
const missing = [...Object.keys(recipe.parts), ...recipe.clear].filter(name => !names.has(name));
|
|
335
|
+
if (missing.length) throw new PartsError(missing.map(name => ({ code: 'DEPTH_PART_RESOLVES', object: name, detail: 'names no assembled part; use exact parts.json names' })));
|
|
336
|
+
const map = readNumericMap(readJson(mapFile), 'place.map');
|
|
337
|
+
if (map.channels !== 1) return fail('DEPTH_MAP_FORMAT', 'place.map', 'requires a single scalar depth channel');
|
|
338
|
+
if (map.width !== set.W || map.height !== set.H) {
|
|
339
|
+
return fail('DEPTH_MAP_SIZE', 'place.map', `is ${map.width}x${map.height}; painting frame (parts.json rig_size) requires ${set.W}x${set.H}`);
|
|
340
|
+
}
|
|
341
|
+
const raw = object(readJson(input.rigConfig), 'rig config');
|
|
342
|
+
const config = parseConfig(raw), body = config.turn?.body;
|
|
343
|
+
if (body === undefined || !Object.hasOwn(recipe.groups, 'body')) {
|
|
344
|
+
return fail('DEPTH_PLACE_GROUP', 'config.turn.body', 'requires a declared 2.5D body turn and a body depth recipe group');
|
|
345
|
+
}
|
|
346
|
+
const firstSurface = Object.entries(body.roles).find(([, role]) => role === 'surface')?.[0];
|
|
347
|
+
if (firstSurface !== place.anchor || !Object.hasOwn(recipe.parts, place.anchor) || recipe.parts[place.anchor].group !== 'body') {
|
|
348
|
+
return fail('DEPTH_PLACE_ANCHOR', 'place.anchor', `names "${place.anchor}"; required the first body surface (${JSON.stringify(firstSurface)}) declared in recipe.parts for the body group`);
|
|
349
|
+
}
|
|
350
|
+
const reliefs = new Map(Object.entries(recipe.parts).filter(([, p]) => p.group === 'body').map(([name, p]) => [name, p.relief]));
|
|
351
|
+
const selected = new Set(reliefs.keys());
|
|
352
|
+
const groupProblems = [...selected].filter(part => !Object.hasOwn(body.roles, part)).map(part => ({
|
|
353
|
+
code: 'DEPTH_GROUP_BINDING', object: part, detail: 'declares the body group; register the part in config.turn.body.roles',
|
|
354
|
+
}));
|
|
355
|
+
for (const [part, role] of Object.entries(body.roles)) if (role === 'unit') {
|
|
356
|
+
selected.add(part);
|
|
357
|
+
if (!names.has(part)) groupProblems.push({
|
|
358
|
+
code: 'DEPTH_PART_RESOLVES', object: part, detail: 'is declared as a body turn unit but names no assembled part; use exact parts.json names',
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
for (const part of place.round ?? []) if (!selected.has(part)) groupProblems.push({
|
|
362
|
+
code: 'DEPTH_PLACE_ROUND', object: `place.round, part ${JSON.stringify(part)}`, detail: 'must resolve to a body recipe part or a body turn unit',
|
|
363
|
+
});
|
|
364
|
+
if (groupProblems.length) throw new PartsError(groupProblems);
|
|
365
|
+
const samples = placementSamples(set, map, reliefs, place, selected);
|
|
366
|
+
const scale = checkPlacementScale(place.scale, samples, reliefs);
|
|
367
|
+
const anchorMedian = samples.find(p => p.part === place.anchor)!.rawMedian;
|
|
368
|
+
const anchorZ = recipe.parts[place.anchor].median, sign = place.near === 'white' ? 1 : -1;
|
|
369
|
+
const pivot = typeof place.pivot === 'number' ? place.pivot : 0;
|
|
370
|
+
const parts = samples.map(({ rawMedian, rawP5, rawP95, ...sample }) => {
|
|
371
|
+
const rigMedian = sample.part === place.anchor ? anchorZ : anchorZ + sign * ((rawMedian - anchorMedian) * scale);
|
|
372
|
+
const impliedRelief = reliefs.has(sample.part) ? (rawP95 - rawP5) * scale : null;
|
|
373
|
+
if (!Number.isFinite(rigMedian) || (impliedRelief !== null && !Number.isFinite(impliedRelief))) return fail('DEPTH_PLACE_SCALE', `part "${sample.part}"`, 'placed median or implied relief overflows; declare a representable scale and anchor median');
|
|
374
|
+
return { ...sample, rawMedian, rawP5, rawP95, rigMedian, impliedRelief };
|
|
375
|
+
});
|
|
376
|
+
const bodyGroup = recipe.groups.body;
|
|
377
|
+
const unitRows = parts.filter(({ part }) => body.roles[part] === 'unit');
|
|
378
|
+
const turn = object(raw.turn, 'config.turn'), rawBody = object(turn.body, 'config.turn.body');
|
|
379
|
+
rawBody.pivot = pivot;
|
|
380
|
+
bodyGroup.pivot = pivot;
|
|
381
|
+
if (unitRows.length) {
|
|
382
|
+
// The body producer projects these world depths against the first surface.
|
|
383
|
+
const unitDepths = { ...(body.unitDepths ?? config.turn?.unitDepths), ...bodyGroup.unitDepths,
|
|
384
|
+
...Object.fromEntries(unitRows.map(({ part, rigMedian }) => [part, rigMedian])) };
|
|
385
|
+
rawBody.unitDepths = unitDepths;
|
|
386
|
+
// depth-apply applies a recipe's authored override after reading the rig config.
|
|
387
|
+
if (bodyGroup.unitDepths !== undefined) bodyGroup.unitDepths = unitDepths;
|
|
388
|
+
}
|
|
389
|
+
for (const { part, rigMedian } of parts) if (reliefs.has(part)) recipe.parts[part].median = rigMedian;
|
|
390
|
+
recipe.place = { ...place, scale };
|
|
391
|
+
parseConfig(raw);
|
|
392
|
+
const report: DepthPlacementReport = { spec: 'rig-parts-depth-place-report/1', near: place.near, scale, anchor: place.anchor, pivot, parts };
|
|
393
|
+
return { report, write(out, turnCheck) {
|
|
394
|
+
const dir = resolve(out);
|
|
395
|
+
emptyOutput(dir, sources);
|
|
396
|
+
const relocated = structuredClone(raw), placedRecipe = structuredClone(recipe);
|
|
397
|
+
relocateConfigReferences(relocated, configDir, dir, 'relative');
|
|
398
|
+
const mapAt = (path: string): string => isAbsolute(path) ? path : relative(dir, resolve(recipeDir, path));
|
|
399
|
+
for (const p of Object.values(placedRecipe.parts)) p.map = mapAt(p.map);
|
|
400
|
+
placedRecipe.place!.map = mapAt(place.map);
|
|
401
|
+
const paths = { recipe: join(dir, 'recipe.json'), config: join(dir, 'config.json') };
|
|
402
|
+
const reportJson = text(turnCheck === undefined ? report : { ...report, turnCheck });
|
|
403
|
+
mkdirSync(dir, { recursive: true });
|
|
404
|
+
writeFileSync(paths.recipe, text(placedRecipe), { flag: 'wx' });
|
|
405
|
+
writeFileSync(paths.config, text(relocated), { flag: 'wx' });
|
|
406
|
+
writeFileSync(join(dir, 'depth-place-report.json'), reportJson, { flag: 'wx' });
|
|
407
|
+
return paths;
|
|
408
|
+
} };
|
|
409
|
+
}
|
|
410
|
+
|
|
117
411
|
function registeredMap(map: NumericMap, p: PreparedPart, frame: PartMap['frame'], at: string): NumericMap {
|
|
118
412
|
const [w, h] = frame === 'part' ? p.size : frame === 'input' ? p.inputSize : p.upscaled;
|
|
119
413
|
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}`);
|
|
@@ -272,6 +566,8 @@ export function applyDepth(input: { parts: string; manifest: string; config: str
|
|
|
272
566
|
refuseStaleAssembly(outConfig, file, relocatedConfig);
|
|
273
567
|
const warnings: string[] = [];
|
|
274
568
|
const writes = new Map<string, Uint8Array>(), rows: Obj[] = [], recs = rawParts.parts as Obj[];
|
|
569
|
+
const groupMaxZ = new Map<string, number>();
|
|
570
|
+
const clipped: { name: string; group: string; fraction: number; clipsHigh: boolean; median: number; minMedian?: number }[] = [];
|
|
275
571
|
// Retain auxiliary art (including alternate sets) and diagnostics byte-for-byte.
|
|
276
572
|
// Symlink inputs would obscure ownership and can escape this assembled directory.
|
|
277
573
|
const retained = new Map<string, Uint8Array>();
|
|
@@ -314,13 +610,32 @@ export function applyDepth(input: { parts: string; manifest: string; config: str
|
|
|
314
610
|
if (map.channels !== 1) fail('DEPTH_MAP_FORMAT', name, 'depth requires one floating-point channel');
|
|
315
611
|
values = floatBox(map.data, map.width, map.height, art.width, art.height);
|
|
316
612
|
}
|
|
317
|
-
const { sheet, reading } = mapToSheet(values, art, declaration.median, declaration.relief, g.near, g.zScale, name)
|
|
613
|
+
const { sheet, reading, maxZ, minOffset, clipsLow } = mapToSheet(values, art, declaration.median, declaration.relief, g.near, g.zScale, name);
|
|
614
|
+
groupMaxZ.set(declaration.group, Math.max(groupMaxZ.get(declaration.group) ?? -Infinity, maxZ));
|
|
615
|
+
if (reading.clipFraction > 0) {
|
|
616
|
+
clipped.push({ name, group: declaration.group, fraction: reading.clipFraction, clipsHigh: maxZ >= g.zScale, median: declaration.median,
|
|
617
|
+
...(clipsLow ? { minMedian: aboveDepthBound(-minOffset) } : {}) });
|
|
618
|
+
continue;
|
|
619
|
+
}
|
|
620
|
+
const image = `${name}_depth.png`, sheetBytes = encodePngBytes(sheet);
|
|
318
621
|
if (file.parts.some(p => `${p.name}.png` === image)) fail('DEPTH_GROUP_BINDING', name, `sheet filename ${image} collides with artwork; use noncolliding part names`);
|
|
319
622
|
writes.set(image, sheetBytes);
|
|
320
623
|
if (p.depth !== undefined) retained.delete(depthImageReference(p.depth).path);
|
|
321
624
|
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) }] };
|
|
322
625
|
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 } }) });
|
|
323
626
|
}
|
|
627
|
+
if (clipped.length) throw new PartsError(clipped.map(({ name, group, fraction, clipsHigh, median, minMedian }) => {
|
|
628
|
+
const details = [`clip=${fraction} in group "${group}"`];
|
|
629
|
+
if (clipsHigh) {
|
|
630
|
+
const maxZ = groupMaxZ.get(group)!;
|
|
631
|
+
const required = aboveDepthBound(maxZ);
|
|
632
|
+
details.push(Number.isFinite(required) ? `required zScale=${required} (group max z=${maxZ})` : `no finite zScale exceeds group max z=${maxZ}; revise median or relief`);
|
|
633
|
+
}
|
|
634
|
+
if (minMedian !== undefined) {
|
|
635
|
+
details.push(Number.isFinite(minMedian) ? `required median=${minMedian} (rise ${minMedian - median} rig px)` : 'no finite median clears z<=0; reduce relief');
|
|
636
|
+
}
|
|
637
|
+
return { code: 'DEPTH_APPLY_CLIPPED', object: `part "${name}"`, detail: details.join('; ') };
|
|
638
|
+
}));
|
|
324
639
|
// A replacement must share near/zScale with every retained part in its actual group.
|
|
325
640
|
for (const [name, g] of Object.entries(recipe.groups)) {
|
|
326
641
|
if (!applied(name)) continue;
|