rig-parts 2.59.0 → 2.61.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 +79 -2
- package/docs/AUTHORING.md +188 -57
- package/docs/DEPTH.md +40 -7
- package/docs/STABILITY.md +48 -2
- package/package.json +2 -2
- package/src/build.ts +11 -1
- package/src/check.ts +16 -2
- package/src/config.ts +12 -8
- package/src/depthworkflow.ts +292 -6
- package/src/localweights.ts +20 -12
- package/src/rig.ts +62 -28
- package/src/scene.ts +33 -4
- package/src/turn.ts +103 -14
- package/src/turnband.ts +418 -0
package/docs/DEPTH.md
CHANGED
|
@@ -41,10 +41,11 @@ use. Three things we learned the hard way are built into that path:
|
|
|
41
41
|
convexity (the middle of a face is nearer than its rim). That integration is
|
|
42
42
|
for the face only: it breaks on anything with an occlusion edge, like hair
|
|
43
43
|
strands or a collar.
|
|
44
|
-
- **
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
44
|
+
- **Placement and relief have separate controls.** The `median` sets where
|
|
45
|
+
a part sits and its `relief` sets the depth of its own shape, both in rig
|
|
46
|
+
pixels. Author both directly, or use a whole-painting map to
|
|
47
|
+
[place body medians](#optional-place-body-parts-from-a-whole-painting-map)
|
|
48
|
+
with a scale you declare. Relief is always authored separately.
|
|
48
49
|
|
|
49
50
|
Surfaces in one turn group share one depth reference: the first surface's
|
|
50
51
|
opaque-art median, preferring the face in a head group. With both eye landmarks,
|
|
@@ -78,9 +79,9 @@ measures depth discontinuity, not composite visibility.
|
|
|
78
79
|
See-through, the layer decomposition this package reads, also writes a per-layer
|
|
79
80
|
depth sheet, and a config can register those directly (`config.depth`,
|
|
80
81
|
[Per-layer depth sheets](AUTHORING.md#per-layer-depth-sheets-773)). In
|
|
81
|
-
side-by-side review, per-part maps from a depth model read better by eye
|
|
82
|
-
|
|
83
|
-
|
|
82
|
+
side-by-side review, per-part maps from a depth model read better by eye for
|
|
83
|
+
local shape. A whole-painting map can supply the relative placement of those
|
|
84
|
+
parts before you use per-part maps to shape them.
|
|
84
85
|
|
|
85
86
|
## The steps, and what you will see
|
|
86
87
|
|
|
@@ -92,6 +93,38 @@ as one piece, `rear` for what sits behind the head. A body group is declared
|
|
|
92
93
|
the same way under `turn.body.roles`. The roles, the dials and the grid the
|
|
93
94
|
surfaces are built on are in [AUTHORING §3, the `turn` row](AUTHORING.md#3-configjson-field-by-field).
|
|
94
95
|
|
|
96
|
+
### Optional: Place body parts from a whole-painting map
|
|
97
|
+
|
|
98
|
+
Use `depth-place` if you have a scalar map for the whole painting and want to
|
|
99
|
+
place assembled body parts relative to one another. Supply a one-channel
|
|
100
|
+
`rig-parts-map/1` on the assembled painting grid (`parts.json`'s `rig_size`)
|
|
101
|
+
and add `place` to the depth recipe. Set `place.near` to `black` when low raw
|
|
102
|
+
values mean near or `white` when high values mean near. Nearer samples produce
|
|
103
|
+
larger rig `z`.
|
|
104
|
+
Declare a positive `place.scale` in rig pixels per model unit and name the
|
|
105
|
+
first body surface as `place.anchor`. That surface keeps its declared median.
|
|
106
|
+
The default pivot is at the anchor depth, with an offset of `0` from the turn's
|
|
107
|
+
reference. A numeric `place.pivot` supplies an explicit offset in rig pixels.
|
|
108
|
+
|
|
109
|
+
```sh
|
|
110
|
+
rig-parts depth-place --parts assembled --config depth.json --rig-config config.json --out placed --check-turn
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
The command writes `placed/recipe.json`, `placed/config.json` and
|
|
114
|
+
`placed/depth-place-report.json`. Use the placed recipe in steps 1 and 4 and the
|
|
115
|
+
placed config in step 4. Each median comes from the pixels where that part is
|
|
116
|
+
visible in the assembled draw order. The report shows the visible pixel count
|
|
117
|
+
and fraction and the scales implied by declared reliefs and optional round
|
|
118
|
+
parts. If you omit the scale, the refusal prints the available evidence so you
|
|
119
|
+
can choose one explicitly.
|
|
120
|
+
|
|
121
|
+
`--check-turn` prepares and applies the placed recipe in scratch space and runs
|
|
122
|
+
the real rig gate. Read `turnCheck` in the report for `built` or a named refusal
|
|
123
|
+
and any available triangle-winding findings. If placement succeeds, a named check
|
|
124
|
+
refusal still leaves the three placement files and exits `0`. The usual rig
|
|
125
|
+
gate still decides whether the turn can build. See the
|
|
126
|
+
[placement fields and refusals](AUTHORING.md#place-body-depth-from-a-whole-painting-map-1570).
|
|
127
|
+
|
|
95
128
|
### 1. Prepare one inference image per part
|
|
96
129
|
|
|
97
130
|
Write a small recipe — a separate JSON file, not a field on the character
|
package/docs/STABILITY.md
CHANGED
|
@@ -578,6 +578,7 @@ 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) |
|
|
582
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) |
|
|
583
584
|
| `depth-bind` | `--map`, `--input`, `--part`; optional `--help` (`-h`) (issue #1284; exclusive receipt creation from current file bytes) |
|
|
@@ -756,7 +757,7 @@ part name, `[i]` an entry of a list):
|
|
|
756
757
|
- **meshes.<part>.influences** — optional, at least one: `maxInfluences` (a whole number, 1 or more, or null for no cap), `floor` ("cut" or "continuous")
|
|
757
758
|
- **meshes.<part>.ribs.<chain>** — required: `stations`
|
|
758
759
|
- **meshes.<part>.contour** — required: `tolerance`, `margin`, `spacing`; optional: `maxEdge`, `budget`, `stray`, `bridges`, `regions`, `bust`
|
|
759
|
-
- **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`
|
|
760
761
|
- **meshes.<part>.contour.bust** — required: `apex_r`, `apex_l`, `cleavage`; optional: `alpha`, `clearance`, `bone_r`, `bone_l`, `spacing` (issue #475)
|
|
761
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`
|
|
762
763
|
- **meshes.<part>.auto.source** — required: `tolerance`, `margin`, `spacing`; optional: `stray`
|
|
@@ -1605,7 +1606,7 @@ in the package.
|
|
|
1605
1606
|
|
|
1606
1607
|
## rig-c
|
|
1607
1608
|
|
|
1608
|
-
`dependencies` takes `@rig-c/core` `3.
|
|
1609
|
+
`dependencies` takes `@rig-c/core` `3.10.0` exactly. Bun 1.4 or later
|
|
1609
1610
|
is the declared floor (`engines.bun` `>=1.4.0`; older 1.4 releases are not tested in
|
|
1610
1611
|
CI, which runs `latest`, and compatibility with an older 1.4 release is handled when
|
|
1611
1612
|
reported as an issue). What this package relies on in rig-c, every import
|
|
@@ -1635,6 +1636,24 @@ install smoke is where that shows first. No Spine runtime is a dependency: an
|
|
|
1635
1636
|
install is gated by rigc's own validator, and `@esotericsoftware/spine-core` is a
|
|
1636
1637
|
development dependency of this repository only.
|
|
1637
1638
|
|
|
1639
|
+
### Generated turn winding
|
|
1640
|
+
|
|
1641
|
+
Core 3.10.0 adds `A53_DECLARED_SLIDER_COMBINATIONS_KEEP_WINDING` to both
|
|
1642
|
+
validators. Parts emits `invariants.deformSliderCombinations` from generated
|
|
1643
|
+
turn mappings, using each slider's actual name, including any retained name
|
|
1644
|
+
when Parts rewrites a reused slider's mapping. Head 2.5D roles generate yaw
|
|
1645
|
+
and pitch and declare all four endpoint pairs. With body yaw also generated,
|
|
1646
|
+
the declaration contains all eight endpoint triples and twelve endpoint pairs
|
|
1647
|
+
with the third dial at explicit neutral `0`, for twenty tuples. Every tuple
|
|
1648
|
+
includes all applicable names and values. With fewer than two generated dials,
|
|
1649
|
+
including body yaw alone, Parts omits the invariant and A53 reports SKIP.
|
|
1650
|
+
Legacy authored sliders alone do not create this invariant.
|
|
1651
|
+
|
|
1652
|
+
The mandatory Core gate can refuse a previously accepted rig before emission.
|
|
1653
|
+
Core's assertion total increases by one, and a rig with no combination
|
|
1654
|
+
declaration gains one skipped assertion. The existing A39 checks still cover
|
|
1655
|
+
individual dials.
|
|
1656
|
+
|
|
1638
1657
|
## What is not stable
|
|
1639
1658
|
|
|
1640
1659
|
- **The evidence documents** under `docs/evidence/`: their layout, columns and
|
|
@@ -1711,6 +1730,19 @@ against. The public examples' `expected/` files are this package's own snapshots
|
|
|
1711
1730
|
`tools/regenerate_examples.ts` writes them on Linux, and CI rebuilds the fetched
|
|
1712
1731
|
examples and compares the files whole with its `--check` (issue #1439).
|
|
1713
1732
|
|
|
1733
|
+
### Contour band weights (issue #1578)
|
|
1734
|
+
|
|
1735
|
+
With the default falloff, a region listed in `contour.regions` applies
|
|
1736
|
+
`4g²(1 − g)` to its nominal linear share `g` for `0 < g < 0.5`. An upgrade can
|
|
1737
|
+
change written weights and downstream output bytes. Geometric support and
|
|
1738
|
+
overlap refusals use the original `g`. The inner half of the band, zero-width
|
|
1739
|
+
bands, influence limits and rounding keep their prior behavior. A declared
|
|
1740
|
+
contour region accepts `falloff: "linear"` to recover its previous weights
|
|
1741
|
+
byte for byte. Other values are `CONFIG_FIELD_TYPE`. The circles derived
|
|
1742
|
+
from `contour.bust` and automatic mesh regions keep the prior linear ramp.
|
|
1743
|
+
An automatic region or a `contour.bust` block rejects `falloff` as
|
|
1744
|
+
`CONFIG_KEY_KNOWN`.
|
|
1745
|
+
|
|
1714
1746
|
### Opt-in hybrid provenance (issue #399)
|
|
1715
1747
|
|
|
1716
1748
|
A lower rigid limb piece may carry `limb.hybrid` instead of `limb.cap`:
|
|
@@ -2230,6 +2262,20 @@ byte-identical; an empty receipt list applies no replacement.
|
|
|
2230
2262
|
|
|
2231
2263
|
## Provider-map depth stages (#897)
|
|
2232
2264
|
|
|
2265
|
+
`depth-place` (#1570) accepts an optional `place` block on `rig-parts-depth/1`.
|
|
2266
|
+
The command requires the block, a body turn, and an absent or empty output
|
|
2267
|
+
directory. It emits `recipe.json`, `config.json` and `depth-place-report.json`
|
|
2268
|
+
(`rig-parts-depth-place-report/1`).
|
|
2269
|
+
Placement uses the declared polarity and a positive, explicit scale in rig
|
|
2270
|
+
pixels per model unit. It writes body placement medians and world rig `z` for
|
|
2271
|
+
body units, preserves declared reliefs and `zScale`, and resolves the body pivot
|
|
2272
|
+
to an offset from the reference depth. See the
|
|
2273
|
+
[placement contract](AUTHORING.md#place-body-depth-from-a-whole-painting-map-1570).
|
|
2274
|
+
With `--check-turn`, preparation, application and the real rig gate run in
|
|
2275
|
+
scratch space and the report adds `turnCheck`. It records any named check
|
|
2276
|
+
refusal. Successful placement emits its three files and exits `0` in either
|
|
2277
|
+
check outcome.
|
|
2278
|
+
|
|
2233
2279
|
The opt-in `depth-prepare` and `depth-apply` commands accept the separate
|
|
2234
2280
|
`rig-parts-depth/1` recipe and finite floating-point `rig-parts-map/1` JSON.
|
|
2235
2281
|
Prepared provenance is `rig-parts-depth-inputs/1`; application writes
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "rig-parts",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.61.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.
|
|
78
|
+
"@rig-c/core": "3.10.0"
|
|
79
79
|
},
|
|
80
80
|
"devDependencies": {
|
|
81
81
|
"@esotericsoftware/spine-core": "4.3.13",
|
package/src/build.ts
CHANGED
|
@@ -121,7 +121,7 @@ import { type OtherLimbs, splitLines, capOwnershipLines, type SplitCount } from
|
|
|
121
121
|
import type { BoneEntry } from './config.ts';
|
|
122
122
|
import { OPAQUE_ALPHA_ABOVE } from './layers.ts';
|
|
123
123
|
import { pinholesRequired, readRequirements, type RequirementLine, summaryText } from './requirements.ts';
|
|
124
|
-
import { type AutoMeshReport, buildRig, DEFAULT_IDLE_KEYS, type FaceAxis, type IdleKeys, type MeshReport, type RigCommand, rigJsonText, type RigOutput, type RigSpec, SETS_FILE, type StrayCleared, type TurnRow } from './rig.ts';
|
|
124
|
+
import { type AutoMeshReport, buildRig, DEFAULT_IDLE_KEYS, type FaceAxis, type IdleKeys, type MeshReport, rebindRigMotion, type RigCommand, rigJsonText, type RigOutput, type RigSpec, SETS_FILE, type StrayCleared, type TurnRow } from './rig.ts';
|
|
125
125
|
import { KEYPOINT_NAMES, type KeypointName, type PosePoints } from './skeleton.ts';
|
|
126
126
|
import { AUTHOR_NO_ROLE, isAuthorTag } from './tags.ts';
|
|
127
127
|
import { BODY_TURN_ANIM, TURN_BONE } from './turn.ts';
|
|
@@ -2016,6 +2016,11 @@ export function rigStage(input: RigStageInput, rigc: RigcRunner, scratch: string
|
|
|
2016
2016
|
const swapped = JSON.parse(rigJsonText(first.rig)) as RigSpec;
|
|
2017
2017
|
for (const k of chosen) swapped.skins.default[k.part] = { ...swapped.skins.default[k.part], [k.part]: k.candidate.attachment };
|
|
2018
2018
|
rig = { ...first, rig: swapped, meshReport: first.meshReport.map((m) => chosen.find((k) => k.part === m.part)?.candidate.row ?? m) };
|
|
2019
|
+
// The staged contour rows survive an automatic-mesh replacement. Rebind
|
|
2020
|
+
// only when the first gate actually received adjusted shared-band keys.
|
|
2021
|
+
if (first.meshReport.some(row => row.coupled_turn_bands?.some(band => band.outcome === 'adjusted'))) {
|
|
2022
|
+
rebindRigMotion(rig);
|
|
2023
|
+
}
|
|
2019
2024
|
texts = textsOf(rig);
|
|
2020
2025
|
let model: string | null = null;
|
|
2021
2026
|
finalGate = gateThroughRigc(pngs, texts, rigc, scratch, mode, (dir) => (model = modelAt(dir)));
|
|
@@ -2076,6 +2081,11 @@ export function rigStage(input: RigStageInput, rigc: RigcRunner, scratch: string
|
|
|
2076
2081
|
const stray = m.stray_cleared === undefined ? '' : ` stray ${m.stray} left out ${m.stray_cleared.islands} island(s), ${m.stray_cleared.pixels} of ${m.stray_cleared.art_pixels} art px`;
|
|
2077
2082
|
log(`${head}grid=${m.grid} ${infl} loop passes ${rig.loopPasses[m.part]}${stray}`);
|
|
2078
2083
|
}
|
|
2084
|
+
for (const band of m.coupled_turn_bands ?? []) {
|
|
2085
|
+
const target = `${band.slot ?? m.part}/${band.attachment ?? m.part}`;
|
|
2086
|
+
log(` RIG_TURN_COUPLED_BAND: "${target}" region "${band.region}" ${band.outcome}, ${band.vertices_adjusted} adjusted vertices, largest share change ${band.largest_share_change}`);
|
|
2087
|
+
for (const tuple of band.triggering_tuples) log(` mesh triggering tuple: ${tuple.map(({ slider, value }) => `${slider}=${value}`).join(', ')}`);
|
|
2088
|
+
}
|
|
2079
2089
|
}
|
|
2080
2090
|
const regions = rig.rig.slots.length - rig.meshReport.length;
|
|
2081
2091
|
const tracks = rig.motion.animations.idle.tracks;
|
package/src/check.ts
CHANGED
|
@@ -1207,15 +1207,29 @@ export interface LoopPhysics {
|
|
|
1207
1207
|
/**
|
|
1208
1208
|
* A throwaway copy of `rig` whose accompanying `motion` replaces `animations`
|
|
1209
1209
|
* with a synthetic set (`still`, `blink_shut`, `stress ...`, `sweep ...`) omits
|
|
1210
|
-
* any `slider` constraint whose target animation is not in that set
|
|
1210
|
+
* any `slider` constraint whose target animation is not in that set and the
|
|
1211
|
+
* tuples that refer to those removed sliders.
|
|
1211
1212
|
*/
|
|
1212
1213
|
function withoutSliders(rig: Record<string, unknown>, animations: Record<string, unknown>): Record<string, unknown> {
|
|
1213
1214
|
if (!Array.isArray(rig.constraints)) return rig;
|
|
1214
|
-
const
|
|
1215
|
+
const removed = new Set<string>();
|
|
1216
|
+
const kept = rig.constraints.filter((c) => {
|
|
1217
|
+
if (!isRecord(c) || c.type !== 'slider' || typeof c.animation !== 'string' || c.animation in animations) return true;
|
|
1218
|
+
if (typeof c.name === 'string') removed.add(c.name);
|
|
1219
|
+
return false;
|
|
1220
|
+
});
|
|
1215
1221
|
if (kept.length === rig.constraints.length) return rig;
|
|
1216
1222
|
const out: Record<string, unknown> = { ...rig };
|
|
1217
1223
|
if (kept.length > 0) out.constraints = kept;
|
|
1218
1224
|
else delete out.constraints;
|
|
1225
|
+
if (isRecord(rig.invariants) && Array.isArray(rig.invariants.deformSliderCombinations)) {
|
|
1226
|
+
const { deformSliderCombinations, ...invariants } = rig.invariants;
|
|
1227
|
+
const retained = deformSliderCombinations.filter(tuple => !isRecord(tuple) || !Array.isArray(tuple.inputs) ||
|
|
1228
|
+
!tuple.inputs.some(input => isRecord(input) && typeof input.slider === 'string' && removed.has(input.slider)));
|
|
1229
|
+
if (retained.length > 0) out.invariants = { ...invariants, deformSliderCombinations: retained };
|
|
1230
|
+
else if (Object.keys(invariants).length > 0) out.invariants = invariants;
|
|
1231
|
+
else delete out.invariants;
|
|
1232
|
+
}
|
|
1219
1233
|
return out;
|
|
1220
1234
|
}
|
|
1221
1235
|
|
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/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,7 +23,8 @@ 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');
|
|
@@ -57,7 +58,14 @@ function plain(name: string, at: string): void {
|
|
|
57
58
|
if (!name || name.startsWith('.') || /[\\/]/.test(name) || name.includes('\0')) fail('DEPTH_RECIPE', at, `name "${name}" is not a plain part filename`);
|
|
58
59
|
}
|
|
59
60
|
export function parseDepthRecipe(raw: unknown): DepthRecipe {
|
|
60
|
-
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');
|
|
61
69
|
if (o.spec !== 'rig-parts-depth/1') fail('DEPTH_RECIPE', 'spec', 'requires rig-parts-depth/1');
|
|
62
70
|
const p = object(o.prepare, 'prepare'); keys(p, ['longSide', 'paddingFraction', 'padding'], 'prepare');
|
|
63
71
|
const prepare = { longSide: number(p.longSide, 'prepare.longSide', 1), paddingFraction: number(p.paddingFraction, 'prepare.paddingFraction', 0), padding: number(p.padding, 'prepare.padding', 0) };
|
|
@@ -83,7 +91,27 @@ export function parseDepthRecipe(raw: unknown): DepthRecipe {
|
|
|
83
91
|
if (!Object.keys(parts).length) fail('DEPTH_RECIPE', 'parts', 'requires at least one named part');
|
|
84
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');
|
|
85
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'); }
|
|
86
|
-
|
|
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)` };
|
|
87
115
|
}
|
|
88
116
|
function emptyOutput(out: string, inputs: readonly string[]): void {
|
|
89
117
|
const canonical = (p: string): string => existsSync(p) ? realpathSync(p) : resolve(canonical(dirname(resolve(p))), basename(p));
|
|
@@ -122,6 +150,264 @@ export function prepareDepth(input: { parts: string; config: string; out: string
|
|
|
122
150
|
writeFileSync(join(input.out, 'manifest.json'), text(manifest));
|
|
123
151
|
return manifest;
|
|
124
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
|
+
|
|
125
411
|
function registeredMap(map: NumericMap, p: PreparedPart, frame: PartMap['frame'], at: string): NumericMap {
|
|
126
412
|
const [w, h] = frame === 'part' ? p.size : frame === 'input' ? p.inputSize : p.upscaled;
|
|
127
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}`);
|