rig-parts 2.52.0 → 2.53.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli.ts +6 -4
- package/docs/AUTHORING.md +321 -55
- package/docs/STABILITY.md +108 -12
- package/package.json +1 -1
- package/src/assemble.ts +155 -63
- package/src/build.ts +62 -15
- package/src/check.ts +67 -32
- package/src/checkrow.ts +2 -0
- package/src/comfy/plate.ts +6 -0
- package/src/comfy/seethrough.ts +59 -5
- package/src/editedparts.ts +3 -0
- package/src/layers.ts +7 -3
- package/src/motion.ts +1 -0
- package/src/paintingedges.ts +56 -24
- package/src/parts.ts +196 -4
- package/src/partscheck.ts +50 -9
- package/src/partvisibility.ts +380 -0
- package/src/plate.ts +93 -14
- package/src/platecomponents.ts +269 -0
- package/src/raster/warp.ts +21 -4
- package/src/requirements.ts +6 -2
- package/src/runstamp.ts +2 -2
- package/src/scene.ts +70 -9
- package/src/sourceexposure.ts +309 -0
- package/src/sourcestates.ts +126 -0
- package/src/takelayers.ts +6 -1
- package/src/takeregion.ts +11 -5
- package/src/visibility.ts +384 -0
package/src/scene.ts
CHANGED
|
@@ -19,10 +19,12 @@
|
|
|
19
19
|
* (its name and every bone or slot it names), `stops` entry (its `chain`,
|
|
20
20
|
* its `links` and its `against`; issue #431), `invariants.detached` bone,
|
|
21
21
|
* `invariants.axes` entry (its name, its `through` and its `bones`; issue #239),
|
|
22
|
-
* track
|
|
22
|
+
* track (its `bone`, `group` or `physics` constraint target; issue #1485),
|
|
23
|
+
* group and easing of character `<id>` is renamed `<id>:<name>`
|
|
23
24
|
* ({@link prefixed}); `root` is the one shared root. A name resolves to
|
|
24
25
|
* exactly one character, and nothing resolves across characters without its
|
|
25
|
-
* prefix: a constraint or
|
|
26
|
+
* prefix: a constraint, stop or physics track naming a bone or physics
|
|
27
|
+
* constraint its own build does not declare is
|
|
26
28
|
* refused (`SCENE_NAME_PREFIXED` when another character has it,
|
|
27
29
|
* `SCENE_NAME_RESOLVES` when none does).
|
|
28
30
|
* - **Images are the one name that cannot carry `:`.** rig-c names an
|
|
@@ -58,9 +60,13 @@
|
|
|
58
60
|
* local frame ({@link scaledStop}; issue #431); the translate keys and their curves'
|
|
59
61
|
* values. Spine also scales the skeleton's `referenceScale`, which the
|
|
60
62
|
* composed skeleton holds once for every character, so a physics
|
|
61
|
-
* constraint with a nonzero `wind` or `gravity
|
|
63
|
+
* constraint with a nonzero `wind` or `gravity`, or a physics track keying
|
|
64
|
+
* `wind` or `gravity` with a nonzero value (issue #1485), cannot be scaled per
|
|
62
65
|
* character and is refused (`SCENE_SCALE_EXACT`), as is a track property
|
|
63
|
-
* this module does not know to be a length or not.
|
|
66
|
+
* this module does not know to be a length or not. Dimensionless physics
|
|
67
|
+
* track properties (`inertia`, `strength`, `damping`, `mass`, `mix`, `reset`)
|
|
68
|
+
* are not scaled by Spine's loader (`readTimeline1(..., 1)` in
|
|
69
|
+
* `SkeletonJson.js`) and stay as written. A mesh's `width` and
|
|
64
70
|
* `height` (its image's, nonessential) stay. At scale 1 nothing is
|
|
65
71
|
* computed: the bytes are the ones written before the field existed.
|
|
66
72
|
* - **The order.** `order` lists character ids (all of that character's
|
|
@@ -464,7 +470,7 @@ const STOP_LOWER_KEYS = ['inward', 'outward'];
|
|
|
464
470
|
const INVARIANT_KEYS = ['idleDrivesMeshes', 'detached', 'axes', 'meshSlots', 'meshTriangles', 'deformMayFold'];
|
|
465
471
|
const MOTION_KEYS = ['spec', 'archetype', 'cut', 'easings', 'groups', 'animations'];
|
|
466
472
|
const IDLE_KEYS = ['duration', 'loop', 'note', 'tracks', 'deform'];
|
|
467
|
-
const TRACK_KEYS = ['bone', 'group', 'property', 'keys'];
|
|
473
|
+
const TRACK_KEYS = ['bone', 'group', 'physics', 'property', 'keys'];
|
|
468
474
|
const KEY_KEYS = ['t', 'v', 'curve', 'ease', 'derive'];
|
|
469
475
|
// Only the turn producer's models, not Core's general transform vocabulary.
|
|
470
476
|
const DERIVE_KEYS = ['kind', 'degrees', 'depth', 'carried', 'about', 'narrowing'];
|
|
@@ -837,6 +843,19 @@ export const SPINE_SLIDER_SCALE_DEFAULT = 1;
|
|
|
837
843
|
export const SCALED_TRACK_PROPERTIES: readonly string[] = ['translate', 'translatex', 'translatey'];
|
|
838
844
|
export const UNSCALED_TRACK_PROPERTIES: readonly string[] = ['rotate', 'scale', 'scalex', 'scaley', 'shear', 'shearx', 'sheary', 'inherit'];
|
|
839
845
|
|
|
846
|
+
/**
|
|
847
|
+
* A physics track's properties (`SkeletonJson.js:1063-1094`): the six rate/ratio/event
|
|
848
|
+
* timelines Spine loads with `scale = 1` and steps independently of `referenceScale`
|
|
849
|
+
* (bone `length` is already scaled by `characters[].scale` at {@link composeScene}),
|
|
850
|
+
* and the two force timelines (`wind`, `gravity`) whose values Spine multiplies by
|
|
851
|
+
* `referenceScale` in translation (`wind * f`, `gravity * f`) and by `length / referenceScale`
|
|
852
|
+
* in rotation (`(ax * sn + ay * c) * (l / f)`), so a nonzero keyed force on a scaled
|
|
853
|
+
* character cannot be reproduced by a single timeline value when the constraint drives
|
|
854
|
+
* both or when `referenceScale` is shared across characters (issue #1485; see {@link physicsForce}).
|
|
855
|
+
*/
|
|
856
|
+
export const UNSCALED_PHYSICS_TRACK_PROPERTIES: readonly string[] = ['inertia', 'strength', 'damping', 'mass', 'mix', 'reset'];
|
|
857
|
+
export const FORCE_PHYSICS_TRACK_PROPERTIES: readonly string[] = ['wind', 'gravity'];
|
|
858
|
+
|
|
840
859
|
/** The two properties a transform constraint or a slider reads or drives in length (`propertyScale` in `SkeletonJson.js`). */
|
|
841
860
|
function lengthProperty(name: string): boolean {
|
|
842
861
|
return name === 'x' || name === 'y';
|
|
@@ -858,8 +877,9 @@ function physicsForce(con: Record<string, unknown>): string[] {
|
|
|
858
877
|
* Why a character at `scale` other than 1 cannot be written exactly, each a
|
|
859
878
|
* `SCENE_SCALE_EXACT` problem: a track whose property this module does not
|
|
860
879
|
* know to be a length or not, a key whose `v` is neither a list of numbers
|
|
861
|
-
* nor a map of them,
|
|
862
|
-
* (see {@link physicsForce})
|
|
880
|
+
* nor a map of them, a physics constraint carrying a wind or a gravity
|
|
881
|
+
* (see {@link physicsForce}), and a physics track keying `wind` or `gravity`
|
|
882
|
+
* with a nonzero key or curve value (issue #1485). Nothing when `scale` is 1.
|
|
863
883
|
*/
|
|
864
884
|
export function scaleProblems(c: SceneCharacter, b: CharacterBuild): Problem[] {
|
|
865
885
|
if (c.scale === 1) return [];
|
|
@@ -868,7 +888,31 @@ export function scaleProblems(c: SceneCharacter, b: CharacterBuild): Problem[] {
|
|
|
868
888
|
for (const [an, anim] of Object.entries(animationsOf(b.motion))) {
|
|
869
889
|
anim.tracks.forEach((t, k) => {
|
|
870
890
|
const where = `${who} motion.json animations.${an}.tracks[${k}]`;
|
|
891
|
+
const tr = t as unknown as Record<string, unknown>;
|
|
871
892
|
const prop = String(t.property);
|
|
893
|
+
const isPhysics = 'physics' in tr;
|
|
894
|
+
if (isPhysics) {
|
|
895
|
+
if (!UNSCALED_PHYSICS_TRACK_PROPERTIES.includes(prop) && !FORCE_PHYSICS_TRACK_PROPERTIES.includes(prop)) {
|
|
896
|
+
out.push({ code: 'SCENE_SCALE_EXACT', object: `${where}.property`, detail: `is ${show(t.property)}, which compose does not know to be a scale-free physics timeline or a force; it leaves ${UNSCALED_PHYSICS_TRACK_PROPERTIES.join(', ')} and refuses nonzero ${FORCE_PHYSICS_TRACK_PROPERTIES.join(', ')} — compose this character at scale 1, or rebuild it at another assemble.rig_scale` });
|
|
897
|
+
return;
|
|
898
|
+
}
|
|
899
|
+
if (FORCE_PHYSICS_TRACK_PROPERTIES.includes(prop)) {
|
|
900
|
+
const nonzero = (t.keys as unknown as Array<Record<string, unknown>>).some((key) => {
|
|
901
|
+
const v = key.v;
|
|
902
|
+
const hasNonzero = (xs: unknown): boolean => Array.isArray(xs) && xs.some((n) => typeof n === 'number' && n !== 0);
|
|
903
|
+
const curveNonzero = Array.isArray(key.curve) && (key.curve as unknown[]).some((n, i) => i % 2 === 1 && typeof n === 'number' && n !== 0);
|
|
904
|
+
return hasNonzero(v) || (isRecord(v) && Object.values(v).some(hasNonzero)) || curveNonzero;
|
|
905
|
+
});
|
|
906
|
+
if (nonzero) {
|
|
907
|
+
out.push({
|
|
908
|
+
code: 'SCENE_SCALE_EXACT',
|
|
909
|
+
object: `${where} (physics "${String(tr.physics)}" ${prop})`,
|
|
910
|
+
detail: `keys ${prop} with a nonzero value; Spine applies ${prop} times the skeleton's referenceScale to the bone's position and times its length over referenceScale to its rotation, and the composed skeleton has one referenceScale for every character, so no value written here draws the character at ${c.scale} — compose it at scale 1, or rebuild it at another assemble.rig_scale`,
|
|
911
|
+
});
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
return;
|
|
915
|
+
}
|
|
872
916
|
if (!SCALED_TRACK_PROPERTIES.includes(prop) && !UNSCALED_TRACK_PROPERTIES.includes(prop)) {
|
|
873
917
|
out.push({ code: 'SCENE_SCALE_EXACT', object: `${where}.property`, detail: `is ${show(t.property)}, which compose does not know to be a length or not; it scales ${SCALED_TRACK_PROPERTIES.join(', ')} and leaves ${UNSCALED_TRACK_PROPERTIES.join(', ')} — compose this character at scale 1, or rebuild it at another assemble.rig_scale` });
|
|
874
918
|
return;
|
|
@@ -1256,6 +1300,19 @@ export function composeScene(
|
|
|
1256
1300
|
fail('SCENE_NAME_PREFIXED', where, `names the bone "${name}", which character "${id}" does not declare and ${other.map((x) => `"${x}"`).join(', ')} does${other.length > 1 ? ' each' : ''}; a name crosses characters only with its prefix — ${other.map((x) => `"${prefixed(x, name)}"`).join(' or ')} — and a build's constraint may name only its own bones`);
|
|
1257
1301
|
} else fail('SCENE_NAME_RESOLVES', where, `names the bone "${name}", which no character of the scene declares`);
|
|
1258
1302
|
};
|
|
1303
|
+
const physicsOf = new Map(ready.map((b) => [b.id, new Set((b.rig.constraints ?? []).filter((c) => c.type === 'physics' && typeof c.name === 'string').map((c) => String(c.name)))]));
|
|
1304
|
+
const physicsOwners = (name: string, own: string): string[] => ready.filter((b) => b.id !== own && (physicsOf.get(b.id)?.has(name) ?? false)).map((b) => b.id);
|
|
1305
|
+
const ownPhysics = (id: string, name: unknown, where: string): void => {
|
|
1306
|
+
if (typeof name !== 'string' || name === '') {
|
|
1307
|
+
fail('SCENE_NAME_RESOLVES', where, `is ${show(name)}; a physics constraint name is required`);
|
|
1308
|
+
return;
|
|
1309
|
+
}
|
|
1310
|
+
if (physicsOf.get(id)?.has(name) ?? false) return;
|
|
1311
|
+
const other = physicsOwners(name, id);
|
|
1312
|
+
if (other.length > 0) {
|
|
1313
|
+
fail('SCENE_NAME_PREFIXED', where, `names the physics constraint "${name}", which character "${id}" does not declare and ${other.map((x) => `"${x}"`).join(', ')} does${other.length > 1 ? ' each' : ''}; a name crosses characters only with its prefix — ${other.map((x) => `"${prefixed(x, name)}"`).join(' or ')} — and a build's track may name only its own physics constraints`);
|
|
1314
|
+
} else fail('SCENE_NAME_RESOLVES', where, `names the physics constraint "${name}", which no character of the scene declares`);
|
|
1315
|
+
};
|
|
1259
1316
|
for (const b of ready) {
|
|
1260
1317
|
(b.rig.constraints ?? []).forEach((con, k) => {
|
|
1261
1318
|
const type = con.type as keyof typeof CONSTRAINT_BONE_FIELDS;
|
|
@@ -1292,12 +1349,14 @@ export function composeScene(
|
|
|
1292
1349
|
for (const [name, anim] of Object.entries(anims)) {
|
|
1293
1350
|
for (const [i, tr] of anim.tracks.entries()) {
|
|
1294
1351
|
const t = tr as unknown as Record<string, unknown>;
|
|
1295
|
-
|
|
1352
|
+
if ('physics' in t) ownPhysics(b.id, t.physics, `character "${b.id}" motion.json animations.${name}.tracks[${i}].physics`);
|
|
1353
|
+
const members = typeof t.bone === 'string' ? [t.bone] : typeof t.physics === 'string' ? [t.physics] : typeof t.group === 'string' ? b.motion.groups[t.group] : undefined;
|
|
1296
1354
|
for (const [j, key] of (t.keys as Array<Record<string, unknown>>).entries()) {
|
|
1297
1355
|
const at = `motion.json animations.${name}.tracks[${i}].keys[${j}]`;
|
|
1298
1356
|
const maps: Array<[string, unknown]> = [['v', key.v], ['derive.depth', isRecord(key.derive) ? key.derive.depth : undefined]];
|
|
1299
1357
|
for (const [field, map] of maps) if (isRecord(map)) for (const member of Object.keys(map)) {
|
|
1300
|
-
|
|
1358
|
+
if ('physics' in t) ownPhysics(b.id, member, `character "${b.id}" ${at}.${field}.${member}`);
|
|
1359
|
+
else ownBone(b.id, member, `character "${b.id}" ${at}.${field}.${member}`);
|
|
1301
1360
|
if (members === undefined || !members.includes(member)) missing(`${at}.${field}.${member}`, `names "${member}", which is not a member of this track's target; a named member of that target is required`);
|
|
1302
1361
|
}
|
|
1303
1362
|
}
|
|
@@ -1527,6 +1586,7 @@ export function composeScene(
|
|
|
1527
1586
|
const tr = { ...t } as Record<string, unknown>;
|
|
1528
1587
|
if (typeof tr.bone === 'string') tr.bone = P(id, tr.bone);
|
|
1529
1588
|
if (typeof tr.group === 'string') tr.group = prefixed(id, tr.group);
|
|
1589
|
+
if (typeof tr.physics === 'string') tr.physics = prefixed(id, tr.physics);
|
|
1530
1590
|
const memberMap = (v: Record<string, unknown>): Record<string, unknown> => Object.fromEntries(Object.entries(v).map(([n, value]) => [P(id, n), value]));
|
|
1531
1591
|
tr.keys = (t.keys as unknown as Array<Record<string, unknown>>).map((k) => ({
|
|
1532
1592
|
...k,
|
|
@@ -1697,6 +1757,7 @@ export function unprefixedNames(rig: RigSpec, motion: MotionSpec, ids: readonly
|
|
|
1697
1757
|
const tr = t as unknown as Record<string, unknown>;
|
|
1698
1758
|
if ('bone' in tr) name('track bone', tr.bone, sceneAnimations.includes(animation));
|
|
1699
1759
|
if ('group' in tr) name('track group', tr.group, false);
|
|
1760
|
+
if ('physics' in tr) name('track physics', tr.physics, false);
|
|
1700
1761
|
for (const k of (tr.keys as Array<Record<string, unknown>>) ?? []) {
|
|
1701
1762
|
if (typeof k.ease === 'string') name('key ease', k.ease, false);
|
|
1702
1763
|
for (const map of [k.v, isRecord(k.derive) ? k.derive.depth : undefined]) if (isRecord(map)) for (const member of Object.keys(map)) name('key member', member, false);
|
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Issue #1473 (#884, second half): the source texels a pose shows that the
|
|
3
|
+
* See-through run recorded as hidden or could not decide.
|
|
4
|
+
*
|
|
5
|
+
* A part with `source_visibility` carries a per-texel state map
|
|
6
|
+
* (`source_state_map`, src/sourcestates.ts). `occluded` there means the run's
|
|
7
|
+
* own layers hid that material in the painting: it is the run's guess at what
|
|
8
|
+
* lies under a front layer, not paint the artist was seen to put down.
|
|
9
|
+
* `partial-top`, `depth-tie` and `mixed-source-states` are material the record
|
|
10
|
+
* could not decide. In the setup pose a part's occluded texels normally lie
|
|
11
|
+
* under the part that hid them; a key that moves that part away shows them.
|
|
12
|
+
*
|
|
13
|
+
* The reading, frame by frame, on the gated build, through rig-c's own
|
|
14
|
+
* renderer (`@rig-c/core/render-shared`) at stage scale 1 — the setup pose and
|
|
15
|
+
* every animation of the build at the check's fps:
|
|
16
|
+
*
|
|
17
|
+
* - a stage pixel is DRAWN by a piece when `rasterisePiece` paints it at
|
|
18
|
+
* {@link DRAWN_ALPHA} of 255 or more with the piece's own page and tint —
|
|
19
|
+
* rig-c's own `drawnCells` test;
|
|
20
|
+
* - a pixel is the piece's UNCOVERED pixel when that piece is the last one in
|
|
21
|
+
* the frame's draw order to draw it: no piece drawn after it reaches half
|
|
22
|
+
* opacity there;
|
|
23
|
+
* - the pixel SHOWS a state when the same piece, re-seated through its own art
|
|
24
|
+
* UVs on an indicator page made from its map (alpha 255 on the texels of that
|
|
25
|
+
* state, 0 elsewhere, tint 1), is painted there at alpha above 0: some texel
|
|
26
|
+
* the renderer's sampler weights for that pixel holds the state.
|
|
27
|
+
*
|
|
28
|
+
* Both readings are the renderer's arithmetic on the posed frame, not a
|
|
29
|
+
* geometric estimate of where a texel lands. A count is of stage pixels at
|
|
30
|
+
* scale 1, which equals texels where a piece is drawn unscaled and pixel
|
|
31
|
+
* aligned. A pixel whose sampled texels hold two of the states counts for
|
|
32
|
+
* each. Nothing here is a pass without an authored limit.
|
|
33
|
+
*/
|
|
34
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
35
|
+
import { join } from 'node:path';
|
|
36
|
+
import { Plate } from '@rig-c/core/plate';
|
|
37
|
+
import { DRAWN_ALPHA } from '@rig-c/core/passthrough';
|
|
38
|
+
import type { Frame, Piece } from '@rig-c/core/render-shared';
|
|
39
|
+
import { seamSourceAttachment } from './check.ts';
|
|
40
|
+
import { checkRow, checkSlotParts, checkSlotRow } from './checkrow.ts';
|
|
41
|
+
import { PartsError, type Problem } from './errors.ts';
|
|
42
|
+
import { partImageReference, type PartRecord, type PartsFile } from './parts.ts';
|
|
43
|
+
import { readPng } from './raster/png.ts';
|
|
44
|
+
import { EXPOSED_SOURCE_STATES, readSourceStateMap, SOURCE_STATE, type ExposedSourceState } from './sourcestates.ts';
|
|
45
|
+
|
|
46
|
+
export const SOURCE_EXPOSURE_LINE = 'SOURCE_EXPOSURE';
|
|
47
|
+
export const SOURCE_EXPOSURE_CODE = 'CHECK_SOURCE_EXPOSURE';
|
|
48
|
+
export const SOURCE_EXPOSURE_UNMEASURED_CODE = 'CHECK_SOURCE_EXPOSURE_UNMEASURED';
|
|
49
|
+
const NO_LIMIT = 'no requirements file declares source_exposure.max_px, so this is a measurement, never a pass';
|
|
50
|
+
|
|
51
|
+
/** The one declaration: the most stage pixels of one state one part may show in one frame. No default exists. */
|
|
52
|
+
export interface SourceExposure {
|
|
53
|
+
max_px: number;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const isObject = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
57
|
+
const freeKey = (k: string, v: unknown): boolean => (k.startsWith('x-') && k.length > 2 && isObject(v)) || ((k === 'note' || k.endsWith('_note')) && typeof v === 'string');
|
|
58
|
+
|
|
59
|
+
/** Shape only: an object holding exactly an authored nonnegative safe integer `max_px` (and notes). */
|
|
60
|
+
export function sourceExposureProblems(value: unknown, at: string): Problem[] {
|
|
61
|
+
if (!isObject(value)) return [{ code: 'REQUIREMENTS_FIELD', object: at, detail: `is ${JSON.stringify(value)?.slice(0, 40)}; requires {"max_px": <an authored nonnegative integer>}` }];
|
|
62
|
+
const problems: Problem[] = [];
|
|
63
|
+
for (const k of Object.keys(value)) if (k !== 'max_px' && !freeKey(k, value[k])) problems.push({ code: 'REQUIREMENTS_FIELD', object: `${at}.${k}`, detail: 'is not a field this block reads (max_px; note or *_note as a string; x-<name> as a record)' });
|
|
64
|
+
const v = value.max_px;
|
|
65
|
+
if (typeof v !== 'number' || !Number.isSafeInteger(v) || v < 0) problems.push({ code: 'REQUIREMENTS_FIELD', object: `${at}.max_px`, detail: `is ${JSON.stringify(v)}; requires an authored nonnegative integer — the most stage pixels of one recorded-hidden or undecided state one part may show in one frame; no default is derived from the art` });
|
|
66
|
+
return problems;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** One part, one state, one frame with at least one pixel shown. */
|
|
70
|
+
export interface SourceExposureRow {
|
|
71
|
+
part: string;
|
|
72
|
+
state: ExposedSourceState;
|
|
73
|
+
px: number;
|
|
74
|
+
frame: string;
|
|
75
|
+
animation: string | null;
|
|
76
|
+
index: number;
|
|
77
|
+
time: number;
|
|
78
|
+
}
|
|
79
|
+
/** A drawing whose exposure cannot be read: its slot, the mapped part it may carry (null when none is named), the attachment the frame drew, the frame and why. */
|
|
80
|
+
export interface SourceExposureUnmeasured { slot: string; part: string | null; attachment: string; frame: string; reason: string }
|
|
81
|
+
|
|
82
|
+
export interface SourceExposureMeasured {
|
|
83
|
+
/** REPORTED without a declared limit — a measurement, never a pass. */
|
|
84
|
+
status: 'REPORTED' | 'PASS' | 'FAIL';
|
|
85
|
+
instrument: string;
|
|
86
|
+
reading: string;
|
|
87
|
+
max_px: number | null;
|
|
88
|
+
/** Primary parts whose map was read, in parts.json order. */
|
|
89
|
+
parts: string[];
|
|
90
|
+
/** How many of each mapped part's texels hold each reported state, keyed by part in parts.json order. */
|
|
91
|
+
texels: Record<string, Record<ExposedSourceState, number>>;
|
|
92
|
+
frames: number;
|
|
93
|
+
animations: string[];
|
|
94
|
+
rows: SourceExposureRow[];
|
|
95
|
+
unmeasured: SourceExposureUnmeasured[];
|
|
96
|
+
alternates: 'not measured';
|
|
97
|
+
reason?: string;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export interface SourceExposureInput {
|
|
101
|
+
build: string;
|
|
102
|
+
stage: { x: number; y: number; width: number; height: number };
|
|
103
|
+
parts: PartsFile | null;
|
|
104
|
+
/** The directory holding the part PNGs and their maps (`<--parts>/parts`). */
|
|
105
|
+
partsDir: string;
|
|
106
|
+
imagesDir: string;
|
|
107
|
+
rig: Record<string, unknown>;
|
|
108
|
+
fps: number;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
type Api = Pick<typeof import('@rig-c/core/render-shared'), 'loadCandidate' | 'throughPoser' | 'sampleSetupPose' | 'sampleAnimation' | 'projector' | 'pageFor' | 'rasterisePiece'>;
|
|
112
|
+
|
|
113
|
+
/** True when some primary part carries a map: the only case the line is measured or written without a declaration. */
|
|
114
|
+
export function hasSourceStateMaps(parts: PartsFile | null): boolean {
|
|
115
|
+
return parts !== null && parts.parts.some(p => p.source_state_map !== undefined);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Read every primary map before anything is rendered; a bad map is refused by name, all at once. */
|
|
119
|
+
export function readSourceStateMaps(parts: PartsFile, partsDir: string): Map<string, Uint8Array> {
|
|
120
|
+
const maps = new Map<string, Uint8Array>();
|
|
121
|
+
const problems: Problem[] = [];
|
|
122
|
+
for (const part of parts.parts) {
|
|
123
|
+
if (part.source_state_map === undefined) continue;
|
|
124
|
+
try { maps.set(part.name, readSourceStateMap(partsDir, part, readPng(join(partsDir, `${part.name}.png`)))); }
|
|
125
|
+
catch (e) { if (e instanceof PartsError) problems.push(...e.problems); else throw e; }
|
|
126
|
+
}
|
|
127
|
+
if (problems.length > 0) throw new PartsError(problems);
|
|
128
|
+
return maps;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const isRecord = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* The mapped part a drawing the source lookup refused may carry, or null when it is proven to carry none: every
|
|
135
|
+
* default-skin entry it can be (the one named as the drawn attachment, or every entry of the slot when the frame
|
|
136
|
+
* named none or several) names an image, and no image is a mapped part's PNG or a sequence frame of one
|
|
137
|
+
* (`<part><digits>.png`). Anything less is not proof, and the drawing is unmeasured with `part` the first mapped
|
|
138
|
+
* part an entry names, else the slot's mapped part, else "unknown".
|
|
139
|
+
*/
|
|
140
|
+
function refusedDrawingPart(rig: Record<string, unknown>, slot: string, attachment: string | null, mapped: ReadonlySet<string>, slotPart: string | undefined): string | null {
|
|
141
|
+
const skin = isRecord(rig.skins) && isRecord(rig.skins.default) ? rig.skins.default : null;
|
|
142
|
+
const drawings = skin !== null && isRecord(skin[slot]) ? skin[slot] : {};
|
|
143
|
+
const entries = Object.entries(drawings).filter(([key, value]) => isRecord(value) && (attachment === null || (typeof value.name === 'string' ? value.name : key) === attachment)).map(([, value]) => value as Record<string, unknown>);
|
|
144
|
+
const named = (image: string): string | undefined => [...mapped].find(part => image.startsWith(part) && /^\d*(\.png)?$/.test(image.slice(part.length)));
|
|
145
|
+
const hits = entries.map(e => (typeof e.image === 'string' ? named(e.image) : undefined)).filter((p): p is string => p !== undefined);
|
|
146
|
+
const proven = skin !== null && entries.length > 0 && (attachment === null || entries.length === 1) && entries.every(e => typeof e.image === 'string' && e.image.length > 0) && hits.length === 0;
|
|
147
|
+
if (proven) return null;
|
|
148
|
+
return hits[0] ?? slotPart ?? 'unknown';
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const frameLabel = (animation: string | null, frame: Frame): string =>
|
|
152
|
+
animation === null ? 'setup' : `${animation} frame ${frame.index} (t ${+frame.time.toFixed(4)} s)`;
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Measure on the gated build. With `declared`, every row over `max_px` is one
|
|
156
|
+
* CHECK_SOURCE_EXPOSURE problem and every unmeasured piece or absent map one
|
|
157
|
+
* CHECK_SOURCE_EXPOSURE_UNMEASURED problem; without it nothing is a problem.
|
|
158
|
+
*/
|
|
159
|
+
export function measureSourceExposure(api: Api, input: SourceExposureInput, declared: SourceExposure | undefined, problems: Problem[]): SourceExposureMeasured {
|
|
160
|
+
const instrument = `rigc renderer at stage scale 1: the setup pose and every animation of the build at ${input.fps} fps`;
|
|
161
|
+
const reading = `a stage pixel is shown by a part when its piece is the last in draw order the renderer paints there at ${DRAWN_ALPHA}/255 or more, and the same piece re-seated on its source-state map paints a texel of that state there; counted per part, state and frame`;
|
|
162
|
+
const base = { instrument, reading, max_px: declared?.max_px ?? null, alternates: 'not measured' as const };
|
|
163
|
+
if (input.parts === null || !hasSourceStateMaps(input.parts)) {
|
|
164
|
+
const reason = input.parts === null ? 'no parts.json was read' : 'no part in parts.json carries a source_state_map; assemble writes one for each part from a See-through run with a visibility record';
|
|
165
|
+
if (declared !== undefined) problems.push({ code: SOURCE_EXPOSURE_UNMEASURED_CODE, object: 'requirements.source_exposure', detail: `${reason}; an untaken reading is never a pass` });
|
|
166
|
+
return { status: declared === undefined ? 'REPORTED' : 'FAIL', ...base, parts: [], texels: {}, frames: 0, animations: [], rows: [], unmeasured: [], reason };
|
|
167
|
+
}
|
|
168
|
+
const parts = input.parts;
|
|
169
|
+
const maps = readSourceStateMaps(parts, input.partsDir);
|
|
170
|
+
const records = new Map(parts.parts.map(p => [p.name, p]));
|
|
171
|
+
const skeleton = join(input.build, 'skeleton.json'), atlas = join(input.build, 'skeleton.atlas');
|
|
172
|
+
const candidate = api.loadCandidate({ skeletonText: readFileSync(skeleton, 'utf8'), atlasText: existsSync(atlas) ? readFileSync(atlas, 'utf8') : null, atlasDir: input.build, label: 'source exposure' }, { skeleton, atlas }, undefined);
|
|
173
|
+
const opts = { geometry: true, texture: true };
|
|
174
|
+
const W = input.stage.width, H = input.stage.height;
|
|
175
|
+
const vp = { minX: input.stage.x, minY: input.stage.y, maxX: input.stage.x + W, maxY: input.stage.y + H, scale: 1, width: W, height: H };
|
|
176
|
+
const project = api.projector(vp);
|
|
177
|
+
const slotParts = checkSlotParts(input.rig, parts.parts.map(p => p.name), parts.alternates?.map(set => set.name) ?? []);
|
|
178
|
+
// Per image: the indicator page of each reported state the map holds, padded as the rig image is.
|
|
179
|
+
const indicators = new Map<string, { part: string; pages: Partial<Record<ExposedSourceState, Plate>> } | string>();
|
|
180
|
+
const indicatorsOf = (image: string): { part: string; pages: Partial<Record<ExposedSourceState, Plate>> } | string => {
|
|
181
|
+
const got = indicators.get(image);
|
|
182
|
+
if (got !== undefined) return got;
|
|
183
|
+
const name = image.replace(/\.png$/, '');
|
|
184
|
+
const rec: PartRecord | undefined = records.get(name);
|
|
185
|
+
const codes = maps.get(name);
|
|
186
|
+
let out: { part: string; pages: Partial<Record<ExposedSourceState, Plate>> } | string;
|
|
187
|
+
if (rec === undefined || codes === undefined) out = '';
|
|
188
|
+
else {
|
|
189
|
+
const rigPng = join(input.imagesDir, image);
|
|
190
|
+
const rigImg = existsSync(rigPng) ? readPng(rigPng) : null;
|
|
191
|
+
const dx = rigImg === null ? 0 : rigImg.width - rec.w, dy = rigImg === null ? 0 : rigImg.height - rec.h;
|
|
192
|
+
if (rigImg === null) out = `the rig image "${image}" is absent`;
|
|
193
|
+
else if (dx !== dy || dx < 0 || dx % 2 !== 0) out = `the rig image "${image}" is ${rigImg.width}x${rigImg.height}, not ${partImageReference(rec).path}'s ${rec.w}x${rec.h} with one even pad on every side`;
|
|
194
|
+
else {
|
|
195
|
+
const pad = dx / 2;
|
|
196
|
+
const pages: Partial<Record<ExposedSourceState, Plate>> = {};
|
|
197
|
+
for (const state of EXPOSED_SOURCE_STATES) {
|
|
198
|
+
const code = SOURCE_STATE[state];
|
|
199
|
+
if (!codes.includes(code)) continue;
|
|
200
|
+
const plate = new Plate(rec.w + 2 * pad, rec.h + 2 * pad);
|
|
201
|
+
for (let y = 0; y < rec.h; y++) for (let x = 0; x < rec.w; x++) {
|
|
202
|
+
if (codes[y * rec.w + x] === code) plate.data.set([255, 255, 255, 255], ((y + pad) * plate.width + x + pad) * 4);
|
|
203
|
+
}
|
|
204
|
+
pages[state] = plate;
|
|
205
|
+
}
|
|
206
|
+
out = { part: name, pages };
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
indicators.set(image, out);
|
|
210
|
+
return out;
|
|
211
|
+
};
|
|
212
|
+
const unmeasured: SourceExposureUnmeasured[] = [];
|
|
213
|
+
const unmeasuredSeen = new Set<string>();
|
|
214
|
+
const rows: SourceExposureRow[] = [];
|
|
215
|
+
const readFrame = (frame: Frame, animation: string | null): void => {
|
|
216
|
+
const label = frameLabel(animation, frame);
|
|
217
|
+
const top = new Int32Array(W * H).fill(-1);
|
|
218
|
+
frame.pieces.forEach((piece, i) => api.rasterisePiece(api.pageFor(candidate.pages, piece), piece, project, vp, (x, y, _r, _g, _b, a) => { if (a >= DRAWN_ALPHA) top[y * W + x] = i; }));
|
|
219
|
+
const counts = new Map<string, number>();
|
|
220
|
+
frame.pieces.forEach((piece, i) => {
|
|
221
|
+
const drawn = (frame.attachments ?? []).filter(a => a.slot === piece.slot);
|
|
222
|
+
const attachment = drawn.length === 1 ? String(drawn[0].attachment) : null;
|
|
223
|
+
const shownAttachment = attachment ?? (drawn.length === 0 ? '(none named by the frame)' : drawn.map(a => String(a.attachment)).join(', '));
|
|
224
|
+
const fail = (part: string | null, reason: string): void => {
|
|
225
|
+
const key = `${piece.slot}\u0000${shownAttachment}\u0000${reason}`;
|
|
226
|
+
if (!unmeasuredSeen.has(key)) { unmeasuredSeen.add(key); unmeasured.push({ slot: piece.slot, part, attachment: shownAttachment, frame: label, reason }); }
|
|
227
|
+
};
|
|
228
|
+
let image: string | null = null;
|
|
229
|
+
let refused = attachment === null ? `the frame names ${drawn.length === 0 ? 'no attachment' : `${drawn.length} attachments`} for the slot` : '';
|
|
230
|
+
if (attachment !== null) {
|
|
231
|
+
try { image = String(seamSourceAttachment(input.rig, piece.slot, attachment).image); }
|
|
232
|
+
catch (e) { refused = `the source lookup refused it (${e instanceof Error ? e.message : String(e)}): a linked mesh, a sequence or a non-image attachment has no part image to map`; }
|
|
233
|
+
}
|
|
234
|
+
if (image === null) {
|
|
235
|
+
// A refused lookup is not proof the drawing is unmapped: it is skipped only when it is proven to carry no mapped part.
|
|
236
|
+
const part = refusedDrawingPart(input.rig, piece.slot, attachment, new Set(maps.keys()), slotParts.get(piece.slot));
|
|
237
|
+
if (part !== null) fail(part, refused);
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
const source = indicatorsOf(image);
|
|
241
|
+
if (source === '') return; // a resolved image that is no mapped part: it covers, and is not read
|
|
242
|
+
if (typeof source === 'string') { fail(image.replace(/\.png$/, ''), source); return; }
|
|
243
|
+
if (piece.kind === 'mesh' && piece.source !== undefined) { fail(source.part, 'the piece is clipped; a clipped piece has no art-UV source map'); return; }
|
|
244
|
+
if (piece.texture === undefined || piece.texture.artUvs.length !== piece.uvs.length) { fail(source.part, 'the renderer gave no art UVs for the piece'); return; }
|
|
245
|
+
for (const state of EXPOSED_SOURCE_STATES) {
|
|
246
|
+
const plate = source.pages[state];
|
|
247
|
+
if (plate === undefined) continue;
|
|
248
|
+
const page = `source-exposure:${state}`;
|
|
249
|
+
const { uvWindow: _window, dark: _dark, ...rest } = piece;
|
|
250
|
+
const seated = { ...rest, page, tint: [1, 1, 1, 1], uvs: piece.texture.artUvs } as Piece;
|
|
251
|
+
// Posed triangles of one mesh can overlap, and the rasteriser then calls back once per triangle: count pixels, not fragments.
|
|
252
|
+
const touched = new Uint8Array(W * H);
|
|
253
|
+
let n = 0;
|
|
254
|
+
api.rasterisePiece(plate, seated, project, vp, (x, y, _r, _g, _b, a) => {
|
|
255
|
+
const q = y * W + x;
|
|
256
|
+
if (a > 0 && top[q] === i && touched[q] === 0) { touched[q] = 1; n++; }
|
|
257
|
+
});
|
|
258
|
+
if (n > 0) counts.set(`${source.part}\u0000${state}`, (counts.get(`${source.part}\u0000${state}`) ?? 0) + n);
|
|
259
|
+
}
|
|
260
|
+
});
|
|
261
|
+
for (const part of parts.parts) for (const state of EXPOSED_SOURCE_STATES) {
|
|
262
|
+
const px = counts.get(`${part.name}\u0000${state}`);
|
|
263
|
+
if (px !== undefined) rows.push({ part: part.name, state, px, frame: label, animation, index: frame.index, time: frame.time });
|
|
264
|
+
}
|
|
265
|
+
};
|
|
266
|
+
const setup = api.throughPoser(candidate.choice, p => api.sampleSetupPose(p, opts)).value[0];
|
|
267
|
+
readFrame(setup, null);
|
|
268
|
+
let frames = 1;
|
|
269
|
+
const animations = [...candidate.facts.animations];
|
|
270
|
+
for (const animation of animations) {
|
|
271
|
+
const sampled = api.throughPoser(candidate.choice, p => api.sampleAnimation(p, animation, input.fps, opts)).value;
|
|
272
|
+
for (const frame of sampled) readFrame(frame, animation);
|
|
273
|
+
frames += sampled.length;
|
|
274
|
+
}
|
|
275
|
+
const over = declared === undefined ? [] : rows.filter(r => r.px > declared.max_px);
|
|
276
|
+
if (declared !== undefined) {
|
|
277
|
+
for (const r of over) problems.push({ code: SOURCE_EXPOSURE_CODE, object: `part "${r.part}"`, detail: `shows ${r.px} stage px of ${r.state} source material at ${r.frame}; declared max_px ${declared.max_px} is required — keep the covering part over that material in this pose, paint the material (an under image or an edited part, so its texels leave the record), or raise source_exposure.max_px knowingly (AUTHORING, failure map)` });
|
|
278
|
+
for (const u of unmeasured) problems.push({ code: SOURCE_EXPOSURE_UNMEASURED_CODE, object: `${u.part === null ? '' : `part "${u.part}", `}slot "${u.slot}", attachment "${u.attachment}" (${u.frame})`, detail: `${u.reason}; the exposure of its mapped part cannot be read, and an untaken reading is never a pass` });
|
|
279
|
+
}
|
|
280
|
+
const mapped = parts.parts.filter(p => maps.has(p.name)).map(p => p.name);
|
|
281
|
+
const texels = Object.fromEntries(mapped.map(name => {
|
|
282
|
+
const codes = maps.get(name) as Uint8Array;
|
|
283
|
+
return [name, Object.fromEntries(EXPOSED_SOURCE_STATES.map(state => [state, codes.filter(c => c === SOURCE_STATE[state]).length])) as Record<ExposedSourceState, number>];
|
|
284
|
+
}));
|
|
285
|
+
return {
|
|
286
|
+
status: declared === undefined ? 'REPORTED' : over.length === 0 && unmeasured.length === 0 ? 'PASS' : 'FAIL',
|
|
287
|
+
...base,
|
|
288
|
+
parts: mapped,
|
|
289
|
+
texels,
|
|
290
|
+
frames,
|
|
291
|
+
animations,
|
|
292
|
+
rows: rows.map(r => ({ ...r, ...checkRow('SOURCE_EXPOSURE.rows', 'part', declared !== undefined && r.px > declared.max_px, [r.part]) })),
|
|
293
|
+
unmeasured: unmeasured.map(u => ({ ...u, ...checkSlotRow('SOURCE_EXPOSURE.unmeasured', declared !== undefined, u.slot, slotParts) })),
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/** The lines `check` prints for a written block. */
|
|
298
|
+
export function sourceExposureLines(line: SourceExposureMeasured): string[] {
|
|
299
|
+
if (line.parts.length === 0) return [`${SOURCE_EXPOSURE_LINE}: ${line.status} — not measured: ${line.reason ?? 'no mapped part'}`];
|
|
300
|
+
const worst = line.rows.reduce<SourceExposureRow | null>((w, r) => (w === null || r.px > w.px ? r : w), null);
|
|
301
|
+
const limit = line.max_px === null ? NO_LIMIT : `declared max_px ${line.max_px} per part, state and frame`;
|
|
302
|
+
const head = `${SOURCE_EXPOSURE_LINE}: ${line.status} — ${line.parts.length} part(s) with a source-state map, ${line.frames} frame(s) read (setup${line.animations.length === 0 ? '' : `, ${line.animations.join(', ')}`}); ` +
|
|
303
|
+
`${line.rows.length} row(s)${worst === null ? ', no recorded-hidden or undecided texel shown' : `, worst part "${worst.part}" ${worst.state} ${worst.px} px at ${worst.frame}`}; ${limit}`;
|
|
304
|
+
return [
|
|
305
|
+
head,
|
|
306
|
+
...line.rows.map(r => ` shown part "${r.part}" ${r.state} ${r.px} px — ${r.frame}${line.max_px !== null && r.px > line.max_px ? ` > max_px ${line.max_px}` : ''}`),
|
|
307
|
+
...line.unmeasured.map(u => ` unmeasured ${u.part === null ? '' : `part "${u.part}" `}slot "${u.slot}" attachment "${u.attachment}" — ${u.frame}: ${u.reason}`),
|
|
308
|
+
];
|
|
309
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The per-texel source-state map beside a part with `source_visibility` (#1473).
|
|
3
|
+
*
|
|
4
|
+
* `source_visibility` counts a part's opaque texels by the state the producing
|
|
5
|
+
* See-through run recorded for the material each one came from. The map puts
|
|
6
|
+
* those states where they lie: one PNG the part's size, every channel of a
|
|
7
|
+
* texel holding its state code and alpha 255 everywhere, bound into
|
|
8
|
+
* `parts.json` by SHA-256 as `source_state_map`. `check` reads it to say which
|
|
9
|
+
* of those texels a pose shows.
|
|
10
|
+
*/
|
|
11
|
+
import { createHash } from 'node:crypto';
|
|
12
|
+
import { readFileSync } from 'node:fs';
|
|
13
|
+
import { join } from 'node:path';
|
|
14
|
+
import { OPAQUE_ALPHA_ABOVE } from './layers.ts';
|
|
15
|
+
import { PartsError, type Problem } from './errors.ts';
|
|
16
|
+
import type { PartRecord, PartSourceVisibility, SOURCE_UNDECIDED_REASONS } from './parts.ts';
|
|
17
|
+
import { decodePngBytes, encodePngBytes } from './raster/png.ts';
|
|
18
|
+
import { newRaster, type Raster } from './raster/types.ts';
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* A texel's code in the map. `none` is a texel at alpha 8 or less in the part
|
|
22
|
+
* PNG, which `source_visibility` does not count; every other code is the one
|
|
23
|
+
* state `source_visibility` counted the texel under.
|
|
24
|
+
*/
|
|
25
|
+
export const SOURCE_STATE = {
|
|
26
|
+
none: 0,
|
|
27
|
+
visible: 1,
|
|
28
|
+
occluded: 2,
|
|
29
|
+
'partial-top': 3,
|
|
30
|
+
'depth-tie': 4,
|
|
31
|
+
'mixed-source-states': 5,
|
|
32
|
+
unrecorded: 6,
|
|
33
|
+
} as const;
|
|
34
|
+
export type SourceStateName = keyof typeof SOURCE_STATE;
|
|
35
|
+
/**
|
|
36
|
+
* The states `check` reports when a pose shows them, in report order: `occluded`, then `source_visibility`'s
|
|
37
|
+
* undecided reasons in their order. Spelled out rather than spread from `SOURCE_UNDECIDED_REASONS`, because
|
|
38
|
+
* parts.ts reaches this module through partvisibility.ts and a value import back would read it before it is
|
|
39
|
+
* initialised; the type below holds the two lists equal.
|
|
40
|
+
*/
|
|
41
|
+
export const EXPOSED_SOURCE_STATES = ['occluded', 'partial-top', 'depth-tie', 'mixed-source-states'] as const;
|
|
42
|
+
type Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;
|
|
43
|
+
export const EXPOSED_STATES_MATCH_RECORD: Same<typeof EXPOSED_SOURCE_STATES, readonly ['occluded', ...typeof SOURCE_UNDECIDED_REASONS]> = true;
|
|
44
|
+
export type ExposedSourceState = typeof EXPOSED_SOURCE_STATES[number];
|
|
45
|
+
|
|
46
|
+
/** The map's file name in `parts/`, beside `<part>.png`. */
|
|
47
|
+
export function sourceStateMapImage(part: string): string {
|
|
48
|
+
return `${part}_source_states.png`;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** The map as a PNG raster: each code in R, G and B, alpha 255. */
|
|
52
|
+
export function sourceStateRaster(codes: Uint8Array, width: number, height: number): Raster {
|
|
53
|
+
const r = newRaster(width, height);
|
|
54
|
+
for (let p = 0; p < width * height; p++) r.data.set([codes[p], codes[p], codes[p], 255], p * 4);
|
|
55
|
+
return r;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The PNG bytes the map is written as, and their SHA-256. */
|
|
59
|
+
export function encodeSourceStateMap(codes: Uint8Array, width: number, height: number): { image: Raster; bytes: Uint8Array; sha256: string } {
|
|
60
|
+
const image = sourceStateRaster(codes, width, height);
|
|
61
|
+
const bytes = encodePngBytes(image);
|
|
62
|
+
return { image, bytes, sha256: createHash('sha256').update(bytes).digest('hex') };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The counts `source_visibility` holds, read off the codes. */
|
|
66
|
+
export function sourceStateCounts(codes: Uint8Array): Omit<PartSourceVisibility, 'source_layers'> {
|
|
67
|
+
const n = new Array<number>(7).fill(0);
|
|
68
|
+
for (const c of codes) n[c]++;
|
|
69
|
+
return {
|
|
70
|
+
visible_px: n[SOURCE_STATE.visible],
|
|
71
|
+
occluded_px: n[SOURCE_STATE.occluded],
|
|
72
|
+
undecided_px: { 'partial-top': n[SOURCE_STATE['partial-top']], 'depth-tie': n[SOURCE_STATE['depth-tie']], 'mixed-source-states': n[SOURCE_STATE['mixed-source-states']] },
|
|
73
|
+
unrecorded_px: n[SOURCE_STATE.unrecorded],
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Read and verify a part's map: the file is present, its bytes hash to the
|
|
79
|
+
* declared SHA-256, it decodes to the part's size with alpha 255 and R = G = B
|
|
80
|
+
* holding a known code, its nonzero codes lie exactly on the part PNG's texels
|
|
81
|
+
* above alpha 8, and its counts equal `source_visibility`. Every problem is
|
|
82
|
+
* collected and thrown once. `partsDir` is the directory holding the part PNGs.
|
|
83
|
+
*/
|
|
84
|
+
export function readSourceStateMap(partsDir: string, part: PartRecord, partImage: Raster, label = `part "${part.name}"`): Uint8Array {
|
|
85
|
+
const declared = part.source_state_map;
|
|
86
|
+
const visibility = part.source_visibility;
|
|
87
|
+
if (declared === undefined || visibility === undefined) throw new Error(`readSourceStateMap: ${label} carries no source_state_map`);
|
|
88
|
+
const path = join(partsDir, declared.image);
|
|
89
|
+
const at = `${label} source_state_map (${declared.image})`;
|
|
90
|
+
const problems: Problem[] = [];
|
|
91
|
+
const fail = (code: string, detail: string): void => { problems.push({ code, object: at, detail }); };
|
|
92
|
+
let bytes: Uint8Array;
|
|
93
|
+
try { bytes = new Uint8Array(readFileSync(path)); }
|
|
94
|
+
catch {
|
|
95
|
+
throw new PartsError([{ code: 'PARTS_SOURCE_STATE_MAP_PRESENT', object: at, detail: `${path} is not readable; re-run assemble, which writes the map beside the part PNG` }]);
|
|
96
|
+
}
|
|
97
|
+
const actual = createHash('sha256').update(bytes).digest('hex');
|
|
98
|
+
if (actual !== declared.sha256) {
|
|
99
|
+
throw new PartsError([{ code: 'PARTS_SOURCE_STATE_MAP_SHA256', object: at, detail: `sha256 is ${actual}; declared ${declared.sha256} is required — the map was changed after assemble wrote it; re-run assemble` }]);
|
|
100
|
+
}
|
|
101
|
+
let image: Raster;
|
|
102
|
+
try { image = decodePngBytes(bytes, path); }
|
|
103
|
+
catch { throw new PartsError([{ code: 'PARTS_SOURCE_STATE_MAP_FORMAT', object: at, detail: 'is not a decodable PNG' }]); }
|
|
104
|
+
if (image.width !== part.w || image.height !== part.h || partImage.width !== part.w || partImage.height !== part.h) {
|
|
105
|
+
throw new PartsError([{ code: 'PARTS_SOURCE_STATE_MAP_FORMAT', object: at, detail: `is ${image.width}x${image.height} beside a ${partImage.width}x${partImage.height} part PNG; the record's ${part.w}x${part.h} is required for both` }]);
|
|
106
|
+
}
|
|
107
|
+
const codes = new Uint8Array(part.w * part.h);
|
|
108
|
+
let badCode = 0, firstBad = -1, offMaterial = 0, firstOff = -1;
|
|
109
|
+
for (let p = 0; p < codes.length; p++) {
|
|
110
|
+
const [r, g, b, a] = image.data.subarray(p * 4, p * 4 + 4);
|
|
111
|
+
if (r !== g || g !== b || a !== 255 || r > SOURCE_STATE.unrecorded) { badCode++; if (firstBad < 0) firstBad = p; continue; }
|
|
112
|
+
codes[p] = r;
|
|
113
|
+
const material = partImage.data[p * 4 + 3] > OPAQUE_ALPHA_ABOVE;
|
|
114
|
+
if (material !== (r !== SOURCE_STATE.none)) { offMaterial++; if (firstOff < 0) firstOff = p; }
|
|
115
|
+
}
|
|
116
|
+
const xy = (p: number): string => `(${p % part.w}, ${Math.floor(p / part.w)})`;
|
|
117
|
+
if (badCode > 0) fail('PARTS_SOURCE_STATE_MAP_FORMAT', `has ${badCode} texel(s) that are not R = G = B = a code 0-${SOURCE_STATE.unrecorded} at alpha 255, first ${xy(firstBad)}`);
|
|
118
|
+
if (offMaterial > 0) fail('PARTS_SOURCE_STATE_MAP_COUNTS', `has ${offMaterial} texel(s) whose code disagrees with the part PNG's alpha above ${OPAQUE_ALPHA_ABOVE}, first ${xy(firstOff)}; code 0 exactly where the part is not material is required`);
|
|
119
|
+
if (problems.length === 0) {
|
|
120
|
+
const counted = sourceStateCounts(codes);
|
|
121
|
+
const want = { visible_px: visibility.visible_px, occluded_px: visibility.occluded_px, undecided_px: { 'partial-top': visibility.undecided_px['partial-top'], 'depth-tie': visibility.undecided_px['depth-tie'], 'mixed-source-states': visibility.undecided_px['mixed-source-states'] }, unrecorded_px: visibility.unrecorded_px };
|
|
122
|
+
if (JSON.stringify(counted) !== JSON.stringify(want)) fail('PARTS_SOURCE_STATE_MAP_COUNTS', `counts ${JSON.stringify(counted)}; source_visibility's ${JSON.stringify(want)} is required`);
|
|
123
|
+
}
|
|
124
|
+
if (problems.length > 0) throw new PartsError(problems);
|
|
125
|
+
return codes;
|
|
126
|
+
}
|
package/src/takelayers.ts
CHANGED
|
@@ -13,6 +13,7 @@ import { newMask, newRaster, newFloatImage, type Raster } from './raster/types.t
|
|
|
13
13
|
import { readPng } from './raster/png.ts';
|
|
14
14
|
import type { TakeDeclaration, TakeOccluderSplit } from './takeregion.ts';
|
|
15
15
|
import { crop, pad } from './raster/composite.ts';
|
|
16
|
+
import type { PartVisibility } from './partvisibility.ts';
|
|
16
17
|
import { warpAffine, type ScaleTranslate } from './raster/warp.ts';
|
|
17
18
|
import { takenTransportProblems, type TakenLayerSource, type TakenLayerTransport } from './takesource.ts';
|
|
18
19
|
|
|
@@ -164,7 +165,7 @@ function supportOverlap(a: Layer, b: Layer): number {
|
|
|
164
165
|
export function applyTakenLayers<T extends Pick<EarlyConfig, 'depth'> & {
|
|
165
166
|
seethrough: Pick<EarlyConfig['seethrough'], 'resolution' | 'head_box'>;
|
|
166
167
|
assemble: { take?: TakeDeclaration[]; plan?: PlanEntry[]; occluders?: OccluderDeclaration[] };
|
|
167
|
-
}>(runs: { full: LayerSet; head: LayerSet; single: boolean }, painting: Raster, cfg: T, configPath: string): { full: LayerSet; head: LayerSet; single: boolean; notes: string[] } {
|
|
168
|
+
}>(runs: { full: LayerSet; head: LayerSet; single: boolean }, painting: Raster, cfg: T, configPath: string, visibility?: PartVisibility): { full: LayerSet; head: LayerSet; single: boolean; notes: string[] } {
|
|
168
169
|
const wholeDeclarations = (cfg.assemble.take ?? []).filter((item): item is TakeLayers => 'tags' in item);
|
|
169
170
|
const declarations = (cfg.assemble.take ?? []).filter((item): item is TakeLayers | TakeOccluderSplit => 'tags' in item || 'occluder' in item);
|
|
170
171
|
const occluders = cfg.assemble.occluders ?? [];
|
|
@@ -248,6 +249,7 @@ export function applyTakenLayers<T extends Pick<EarlyConfig, 'depth'> & {
|
|
|
248
249
|
};
|
|
249
250
|
const transported = geometry === undefined ? undefined : transportLayer(donorLayer, donor, set, image, d, geometry.map, geometry.exact, tagAt);
|
|
250
251
|
const donorOnSet = transported?.layer ?? donorLayer;
|
|
252
|
+
visibility?.layer(donorOnSet.pixels, `${d.run}:${donorLayer.name}`);
|
|
251
253
|
const merged = newRaster(set.canvas.w, set.canvas.h);
|
|
252
254
|
let coveredPx = 0, visiblePx = 0, opaquePx = 0;
|
|
253
255
|
for (let y = 0; y < set.canvas.h; y++) for (let x = 0; x < set.canvas.w; x++) {
|
|
@@ -256,12 +258,14 @@ export function applyTakenLayers<T extends Pick<EarlyConfig, 'depth'> & {
|
|
|
256
258
|
if (x >= baseLayer.left && x < baseLayer.right && y >= baseLayer.top && y < baseLayer.bottom) {
|
|
257
259
|
const bp = ((y - baseLayer.top) * baseLayer.pixels.width + (x - baseLayer.left)) * 4;
|
|
258
260
|
merged.data.set(baseLayer.pixels.data.subarray(bp, bp + 4), p);
|
|
261
|
+
visibility?.copy(merged, p / 4, baseLayer.pixels, bp / 4);
|
|
259
262
|
if (baseLayer.pixels.data[bp + 3] > OPAQUE_ALPHA_ABOVE) { coveredPx++; opaquePx++; }
|
|
260
263
|
}
|
|
261
264
|
} else {
|
|
262
265
|
if (x >= donorOnSet.left && x < donorOnSet.right && y >= donorOnSet.top && y < donorOnSet.bottom) {
|
|
263
266
|
const dp = ((y - donorOnSet.top) * donorOnSet.pixels.width + (x - donorOnSet.left)) * 4;
|
|
264
267
|
merged.data.set(donorOnSet.pixels.data.subarray(dp, dp + 4), p);
|
|
268
|
+
visibility?.copy(merged, p / 4, donorOnSet.pixels, dp / 4);
|
|
265
269
|
if (donorOnSet.pixels.data[dp + 3] > OPAQUE_ALPHA_ABOVE) { visiblePx++; opaquePx++; }
|
|
266
270
|
}
|
|
267
271
|
}
|
|
@@ -322,6 +326,7 @@ export function applyTakenLayers<T extends Pick<EarlyConfig, 'depth'> & {
|
|
|
322
326
|
const transported = geometry === undefined ? undefined : transportLayer(layer, donor, set, image, d, geometry.map, geometry.exact, `${at} tag "${tag}"`);
|
|
323
327
|
if (transported !== undefined) source.transport = transported.transport;
|
|
324
328
|
const replacement: Layer = { ...(transported?.layer ?? layer), takenLayers: [source] };
|
|
329
|
+
visibility?.layer(replacement.pixels, `${d.run}:${layer.name}`);
|
|
325
330
|
lists[d.run] = [...lists[d.run].filter(l => l.name !== tag), replacement];
|
|
326
331
|
origins.set(replacement, resolve(base, d.run_dir));
|
|
327
332
|
notes.push(takeLayerNote(source));
|