rig-parts 2.52.1 → 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 +316 -55
- package/docs/STABILITY.md +108 -12
- package/package.json +1 -1
- package/src/assemble.ts +155 -63
- package/src/build.ts +55 -12
- package/src/check.ts +12 -1
- 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
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
/** Contributor identities and state sets, carried only while assembling a recorded run. */
|
|
2
|
+
import { OPAQUE_ALPHA_ABOVE } from './layers.ts';
|
|
3
|
+
import type { PartSourceOverlap, PartSourceVisibility } from './parts.ts';
|
|
4
|
+
import { visitWarpSupport, type ScaleTranslate, type WarpFilter } from './raster/warp.ts';
|
|
5
|
+
import type { Raster } from './raster/types.ts';
|
|
6
|
+
import { VISIBILITY_STATE } from './visibility.ts';
|
|
7
|
+
import { SOURCE_STATE, sourceStateCounts } from './sourcestates.ts';
|
|
8
|
+
|
|
9
|
+
const UNRECORDED = 1 << VISIBILITY_STATE.unrecorded;
|
|
10
|
+
const VISIBLE = 1 << VISIBILITY_STATE.visible;
|
|
11
|
+
const OCCLUDED = 1 << VISIBILITY_STATE.occluded;
|
|
12
|
+
const PARTIAL_TOP = 1 << VISIBILITY_STATE.partialTop;
|
|
13
|
+
const DEPTH_TIE = 1 << VISIBILITY_STATE.depthTie;
|
|
14
|
+
const decided = (states: number): boolean => states === VISIBLE || states === OCCLUDED;
|
|
15
|
+
|
|
16
|
+
interface Material { states: number; layers: readonly string[] }
|
|
17
|
+
interface Box { x0: number; y0: number; x1: number; y1: number }
|
|
18
|
+
interface NativeSource extends Box { states: Uint8Array }
|
|
19
|
+
interface Registration {
|
|
20
|
+
map: ScaleTranslate;
|
|
21
|
+
sourceWidth: number;
|
|
22
|
+
sourceHeight: number;
|
|
23
|
+
width: number;
|
|
24
|
+
height: number;
|
|
25
|
+
area: number;
|
|
26
|
+
xs: Uint32Array;
|
|
27
|
+
ys: Uint32Array;
|
|
28
|
+
sources: NativeSource[];
|
|
29
|
+
}
|
|
30
|
+
interface DirectPixels { registration: Registration; refs: Uint32Array }
|
|
31
|
+
interface Pixels {
|
|
32
|
+
rgb: Uint32Array;
|
|
33
|
+
alpha: Uint32Array;
|
|
34
|
+
origin?: Box;
|
|
35
|
+
direct?: DirectPixels;
|
|
36
|
+
}
|
|
37
|
+
type NativeSamples = NonNullable<PartSourceOverlap['native_samples']>;
|
|
38
|
+
|
|
39
|
+
/** Boundaries of the native integer sample origins in each half-open rig cell. */
|
|
40
|
+
function cellStarts(sourceSize: number, size: number, scale: number, translate: number): Uint32Array {
|
|
41
|
+
const starts = new Uint32Array(size + 1);
|
|
42
|
+
let sample = 0;
|
|
43
|
+
for (let boundary = 0; boundary <= size; boundary++) {
|
|
44
|
+
while (sample < sourceSize && scale * sample + translate < boundary) sample++;
|
|
45
|
+
starts[boundary] = sample;
|
|
46
|
+
}
|
|
47
|
+
return starts;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function rgba(image: Raster, p: number): number {
|
|
51
|
+
const i = p * 4, d = image.data;
|
|
52
|
+
return d[i] | (d[i + 1] << 8) | (d[i + 2] << 16) | (d[i + 3] << 24);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function countNative(counts: NativeSamples, back: DirectPixels, b: number, front: DirectPixels, f: number, x: number, y: number): void {
|
|
56
|
+
const { width, height, area, sources, xs, ys } = back.registration;
|
|
57
|
+
const br = back.refs[b] - 1, fr = front.refs[f] - 1;
|
|
58
|
+
if (br < 0 || fr < 0 || x < 0 || y < 0 || x >= width || y >= height) return;
|
|
59
|
+
const p = y * width + x;
|
|
60
|
+
if (br % area !== p || fr % area !== p) return;
|
|
61
|
+
const rear = sources[Math.floor(br / area)], ahead = sources[Math.floor(fr / area)];
|
|
62
|
+
// Each native coordinate belongs to one rig cell, so scanning each accepted
|
|
63
|
+
// cell once also deduplicates physical coordinates within this part pair.
|
|
64
|
+
const x0 = Math.max(xs[x], rear.x0, ahead.x0), x1 = Math.min(xs[x + 1], rear.x1, ahead.x1);
|
|
65
|
+
const y0 = Math.max(ys[y], rear.y0, ahead.y0), y1 = Math.min(ys[y + 1], rear.y1, ahead.y1);
|
|
66
|
+
for (let sy = y0; sy < y1; sy++) for (let sx = x0; sx < x1; sx++) {
|
|
67
|
+
const rs = rear.states[(sy - rear.y0) * (rear.x1 - rear.x0) + sx - rear.x0];
|
|
68
|
+
const fs = ahead.states[(sy - ahead.y0) * (ahead.x1 - ahead.x0) + sx - ahead.x0];
|
|
69
|
+
if (rs === 0 || fs === 0) continue;
|
|
70
|
+
counts.overlap_px++;
|
|
71
|
+
if (rs === VISIBLE && fs === OCCLUDED) counts.inverted_px++;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** A placed part in draw order: its rig-space box and its output image. */
|
|
76
|
+
export interface PlacedImage { name: string; x: number; y: number; image: Raster }
|
|
77
|
+
|
|
78
|
+
/** ID zero denotes material outside the record, with no known layer. */
|
|
79
|
+
export class PartVisibility {
|
|
80
|
+
private readonly materials: Material[] = [{ states: UNRECORDED, layers: [] }];
|
|
81
|
+
private readonly ids = new Map([[JSON.stringify([UNRECORDED, []]), 0]]);
|
|
82
|
+
private readonly combinations = new Map<number, Map<number, number>>();
|
|
83
|
+
private readonly images = new WeakMap<Raster, Pixels>();
|
|
84
|
+
private readonly registrations = new WeakMap<object, Registration>();
|
|
85
|
+
private readonly directSamples = new WeakMap<readonly [number, number], { registration: Registration; ref: number; rgba: number }>();
|
|
86
|
+
|
|
87
|
+
private id(states: number, layers: readonly string[]): number {
|
|
88
|
+
const key = JSON.stringify([states, layers]);
|
|
89
|
+
const previous = this.ids.get(key);
|
|
90
|
+
if (previous !== undefined) return previous;
|
|
91
|
+
const id = this.materials.length;
|
|
92
|
+
this.materials.push({ states, layers });
|
|
93
|
+
this.ids.set(key, id);
|
|
94
|
+
return id;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
union(a: number, b: number): number {
|
|
98
|
+
if (a === b) return a;
|
|
99
|
+
const first = Math.min(a, b), second = Math.max(a, b);
|
|
100
|
+
let row = this.combinations.get(first);
|
|
101
|
+
if (row === undefined) this.combinations.set(first, row = new Map());
|
|
102
|
+
const previous = row.get(second);
|
|
103
|
+
if (previous !== undefined) return previous;
|
|
104
|
+
const am = this.materials[a], bm = this.materials[b];
|
|
105
|
+
const combined = this.id(am.states | bm.states, [...new Set([...am.layers, ...bm.layers])].sort());
|
|
106
|
+
row.set(second, combined);
|
|
107
|
+
return combined;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
private plane(image: Raster): Pixels {
|
|
111
|
+
let pixels = this.images.get(image);
|
|
112
|
+
if (pixels === undefined) {
|
|
113
|
+
const size = image.width * image.height;
|
|
114
|
+
pixels = { rgb: new Uint32Array(size), alpha: new Uint32Array(size) };
|
|
115
|
+
this.images.set(image, pixels);
|
|
116
|
+
}
|
|
117
|
+
return pixels;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
layer(image: Raster, name: string, states?: Uint8Array): void {
|
|
121
|
+
const pixels = this.plane(image);
|
|
122
|
+
this.forgetNative(image);
|
|
123
|
+
if (states?.length === pixels.alpha.length) pixels.origin = { x0: 0, y0: 0, x1: image.width, y1: image.height };
|
|
124
|
+
const ids = Object.values(VISIBILITY_STATE).map(state => this.id(1 << state, [name]));
|
|
125
|
+
if (states === undefined) {
|
|
126
|
+
pixels.rgb.fill(ids[0]);
|
|
127
|
+
pixels.alpha.fill(ids[0]);
|
|
128
|
+
} else for (let p = 0; p < states.length; p++) {
|
|
129
|
+
pixels.rgb[p] = pixels.alpha[p] = ids[states[p]];
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
clone(from: Raster, to: Raster): void {
|
|
134
|
+
const source = this.images.get(from);
|
|
135
|
+
if (source === undefined) return;
|
|
136
|
+
const target: Pixels = { rgb: source.rgb.slice(), alpha: source.alpha.slice() };
|
|
137
|
+
if (from.width === to.width && from.height === to.height) {
|
|
138
|
+
if (source.origin !== undefined) target.origin = source.origin;
|
|
139
|
+
const direct = source.direct;
|
|
140
|
+
if (direct !== undefined) target.direct = { registration: direct.registration, refs: direct.refs.slice() };
|
|
141
|
+
}
|
|
142
|
+
this.images.set(to, target);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Drop native evidence for edits that leave the existing material tally intact. */
|
|
146
|
+
forgetNative(image: Raster, p?: number): void {
|
|
147
|
+
const target = this.images.get(image);
|
|
148
|
+
if (target === undefined) return;
|
|
149
|
+
delete target.origin;
|
|
150
|
+
if (p === undefined) delete target.direct;
|
|
151
|
+
else if (target.direct !== undefined) target.direct.refs[p] = 0;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
private directPlane(image: Raster, target: Pixels, registration: Registration): DirectPixels {
|
|
155
|
+
return target.direct ??= { registration, refs: new Uint32Array(image.width * image.height) };
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
private writeDirect(image: Raster, target: Pixels, p: number, registration?: Registration, ref = 0): void {
|
|
159
|
+
delete target.origin;
|
|
160
|
+
if (registration !== undefined && ref !== 0) this.directPlane(image, target, registration);
|
|
161
|
+
if (target.direct !== undefined) target.direct.refs[p] = target.direct.registration === registration ? ref : 0;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
copy(to: Raster, p: number, from: Raster, q = p, channels: 'both' | 'rgb' | 'alpha' = 'both'): void {
|
|
165
|
+
const source = this.images.get(from);
|
|
166
|
+
const target = this.plane(to);
|
|
167
|
+
if (channels !== 'alpha') target.rgb[p] = source?.rgb[q] ?? 0;
|
|
168
|
+
if (channels !== 'rgb') target.alpha[p] = source?.alpha[q] ?? 0;
|
|
169
|
+
const direct = channels === 'both' ? source?.direct : undefined;
|
|
170
|
+
this.writeDirect(to, target, p, direct?.registration, direct?.refs[q]);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
rows(to: Raster, from: Raster, x: number, y: number, width: number, height: number, dx = 0, dy = 0): void {
|
|
174
|
+
const source = this.images.get(from);
|
|
175
|
+
const fresh = !this.images.has(to);
|
|
176
|
+
if (source === undefined) {
|
|
177
|
+
const target = this.images.get(to);
|
|
178
|
+
if (target !== undefined) {
|
|
179
|
+
delete target.origin;
|
|
180
|
+
for (let row = 0; row < height; row++) {
|
|
181
|
+
const at = (row + dy) * to.width + dx;
|
|
182
|
+
target.direct?.refs.fill(0, at, at + width);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
const target = this.plane(to);
|
|
188
|
+
const origin = source.origin;
|
|
189
|
+
delete target.origin;
|
|
190
|
+
if (fresh && origin !== undefined) {
|
|
191
|
+
const box = {
|
|
192
|
+
x0: Math.max(x, origin.x0) - x + dx, y0: Math.max(y, origin.y0) - y + dy,
|
|
193
|
+
x1: Math.min(x + width, origin.x1) - x + dx, y1: Math.min(y + height, origin.y1) - y + dy,
|
|
194
|
+
};
|
|
195
|
+
if (box.x1 > box.x0 && box.y1 > box.y0) target.origin = box;
|
|
196
|
+
}
|
|
197
|
+
const direct = source.direct;
|
|
198
|
+
if (direct !== undefined) this.directPlane(to, target, direct.registration);
|
|
199
|
+
const dest = target.direct;
|
|
200
|
+
for (let row = 0; row < height; row++) {
|
|
201
|
+
const start = (row + y) * from.width + x;
|
|
202
|
+
const at = (row + dy) * to.width + dx;
|
|
203
|
+
target.rgb.set(source.rgb.subarray(start, start + width), at);
|
|
204
|
+
target.alpha.set(source.alpha.subarray(start, start + width), at);
|
|
205
|
+
if (dest === undefined) continue;
|
|
206
|
+
if (direct?.registration === dest.registration) dest.refs.set(direct.refs.subarray(start, start + width), at);
|
|
207
|
+
else dest.refs.fill(0, at, at + width);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
sample(image: Raster, p: number): readonly [number, number] {
|
|
212
|
+
const pixels = this.images.get(image);
|
|
213
|
+
const sample = [pixels?.rgb[p] ?? 0, pixels?.alpha[p] ?? 0] as const;
|
|
214
|
+
const direct = pixels?.direct, ref = direct?.refs[p] ?? 0;
|
|
215
|
+
if (direct !== undefined && ref !== 0) this.directSamples.set(sample, { registration: direct.registration, ref, rgba: rgba(image, p) });
|
|
216
|
+
return sample;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
write(image: Raster, p: number, material: readonly [number, number]): void {
|
|
220
|
+
const pixels = this.plane(image);
|
|
221
|
+
pixels.rgb[p] = material[0];
|
|
222
|
+
pixels.alpha[p] = material[1];
|
|
223
|
+
const direct = this.directSamples.get(material);
|
|
224
|
+
if (direct !== undefined && direct.rgba === rgba(image, p)) this.writeDirect(image, pixels, p, direct.registration, direct.ref);
|
|
225
|
+
else this.forgetNative(image, p);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
painting(to: Raster, p: number, channels: 'both' | 'rgb', blend = false): void {
|
|
229
|
+
const target = this.images.get(to);
|
|
230
|
+
if (target === undefined) return;
|
|
231
|
+
target.rgb[p] = blend ? this.union(target.rgb[p], 0) : 0;
|
|
232
|
+
if (channels === 'both') target.alpha[p] = 0;
|
|
233
|
+
this.forgetNative(to, p);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
underfill(to: Raster, p: number, head: Raster, full: Raster, headAlpha: number, fullAlpha: number): void {
|
|
237
|
+
const h = this.images.get(head), f = this.images.get(full), target = this.plane(to);
|
|
238
|
+
const hr = h?.rgb[p] ?? 0, fr = f?.rgb[p] ?? 0;
|
|
239
|
+
const fullColor = fullAlpha > 0 || fr !== 0;
|
|
240
|
+
target.rgb[p] = headAlpha === 255 || !fullColor ? hr : headAlpha === 0 ? fr : this.union(hr, fr);
|
|
241
|
+
const ha = h?.alpha[p] ?? 0, fa = f?.alpha[p] ?? 0;
|
|
242
|
+
target.alpha[p] = headAlpha === 255 || headAlpha > fullAlpha ? ha : fullAlpha > headAlpha ? fa : this.union(ha, fa);
|
|
243
|
+
this.forgetNative(to, p);
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
private nativeWarp(from: Raster, to: Raster, source: Pixels, target: Pixels, map: ScaleTranslate, fullFrame: object): void {
|
|
247
|
+
const box = source.origin;
|
|
248
|
+
if (box === undefined || map.sx <= 0 || map.sy <= 0 || (map.sx === 1 && map.sy === 1)) return;
|
|
249
|
+
let registration = this.registrations.get(fullFrame);
|
|
250
|
+
if (registration === undefined) {
|
|
251
|
+
registration = {
|
|
252
|
+
map, sourceWidth: from.width, sourceHeight: from.height, width: to.width, height: to.height, area: to.width * to.height,
|
|
253
|
+
xs: cellStarts(from.width, to.width, map.sx, map.tx), ys: cellStarts(from.height, to.height, map.sy, map.ty), sources: [],
|
|
254
|
+
};
|
|
255
|
+
this.registrations.set(fullFrame, registration);
|
|
256
|
+
}
|
|
257
|
+
const { sourceWidth, sourceHeight, width, height, area, sources } = registration;
|
|
258
|
+
const m = registration.map;
|
|
259
|
+
if (sourceWidth !== from.width || sourceHeight !== from.height || width !== to.width || height !== to.height ||
|
|
260
|
+
m.sx !== map.sx || m.sy !== map.sy || m.tx !== map.tx || m.ty !== map.ty) return;
|
|
261
|
+
// Zero is untracked. Each other code identifies one source plane and the
|
|
262
|
+
// raw rig pixel, even after that pixel is cropped or copied elsewhere.
|
|
263
|
+
const base = sources.length * area + 1;
|
|
264
|
+
if (base + area - 1 > 0xffffffff) return;
|
|
265
|
+
const stride = box.x1 - box.x0;
|
|
266
|
+
const states = new Uint8Array(stride * (box.y1 - box.y0));
|
|
267
|
+
for (let y = box.y0; y < box.y1; y++) for (let x = box.x0; x < box.x1; x++) {
|
|
268
|
+
const p = y * sourceWidth + x;
|
|
269
|
+
if (from.data[p * 4 + 3] > OPAQUE_ALPHA_ABOVE) {
|
|
270
|
+
states[(y - box.y0) * stride + x - box.x0] = this.materials[source.alpha[p]].states;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
sources.push({ ...box, states });
|
|
274
|
+
const { refs } = this.directPlane(to, target, registration);
|
|
275
|
+
for (let p = 0; p < area; p++) if (to.data[p * 4 + 3] > OPAQUE_ALPHA_ABOVE) refs[p] = base + p;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
warp(from: Raster, to: Raster, map: ScaleTranslate, filter: WarpFilter, hasColor?: (pixel: number) => boolean, fullFrame?: object): void {
|
|
279
|
+
const source = this.images.get(from);
|
|
280
|
+
this.forgetNative(to);
|
|
281
|
+
if (source === undefined) return;
|
|
282
|
+
const target = this.plane(to);
|
|
283
|
+
visitWarpSupport(from, map, to.width, to.height, filter, (p, taps) => {
|
|
284
|
+
if (to.data[p * 4 + 3] === 0 && hasColor?.(p) !== true) return;
|
|
285
|
+
let rgb: number | undefined;
|
|
286
|
+
let alpha: number | undefined;
|
|
287
|
+
for (const q of taps) {
|
|
288
|
+
if (from.data[q * 4 + 3] === 0) continue;
|
|
289
|
+
const a = source.alpha[q];
|
|
290
|
+
const premultiplied = this.union(source.rgb[q], a);
|
|
291
|
+
rgb = rgb === undefined ? premultiplied : this.union(rgb, premultiplied);
|
|
292
|
+
alpha = alpha === undefined ? a : this.union(alpha, a);
|
|
293
|
+
}
|
|
294
|
+
target.rgb[p] = rgb ?? 0;
|
|
295
|
+
target.alpha[p] = alpha ?? 0;
|
|
296
|
+
});
|
|
297
|
+
if (fullFrame !== undefined) this.nativeWarp(from, to, source, target, map, fullFrame);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** The material of an output pixel: the union of its colour and alpha contributors. */
|
|
301
|
+
private material(image: Raster, p: number): number {
|
|
302
|
+
const pixels = this.images.get(image);
|
|
303
|
+
return this.union(pixels?.rgb[p] ?? 0, pixels?.alpha[p] ?? 0);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* Issue #1474: for each part, every later part (drawn in front of it) whose
|
|
308
|
+
* opaque output pixels (alpha above 8, as `opaque_px`) meet its own. A pixel
|
|
309
|
+
* is inverted when every contributor of the part drawn behind is visible in
|
|
310
|
+
* the record and every contributor of the part drawn in front is occluded:
|
|
311
|
+
* the painting shows the back part there and the draw order shows the front.
|
|
312
|
+
*/
|
|
313
|
+
overlaps(parts: readonly PlacedImage[]): PartSourceOverlap[][] {
|
|
314
|
+
return parts.map((back, i) => parts.slice(i + 1).flatMap((front): PartSourceOverlap[] => {
|
|
315
|
+
const x0 = Math.max(back.x, front.x), y0 = Math.max(back.y, front.y);
|
|
316
|
+
const x1 = Math.min(back.x + back.image.width, front.x + front.image.width);
|
|
317
|
+
const y1 = Math.min(back.y + back.image.height, front.y + front.image.height);
|
|
318
|
+
const row: PartSourceOverlap = {
|
|
319
|
+
front: front.name, source_layers: [], overlap_px: 0, inverted_px: 0, agreeing_px: 0, unordered_px: 0,
|
|
320
|
+
undecided_px: { 'partial-top': 0, 'depth-tie': 0, 'mixed-source-states': 0 }, unrecorded_px: 0,
|
|
321
|
+
};
|
|
322
|
+
const layers = new Set<string>();
|
|
323
|
+
const bd = this.images.get(back.image)?.direct, fd = this.images.get(front.image)?.direct;
|
|
324
|
+
const native = bd !== undefined && fd !== undefined && bd.registration === fd.registration
|
|
325
|
+
? { back: bd, front: fd, counts: { overlap_px: 0, inverted_px: 0 } } : undefined;
|
|
326
|
+
for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) {
|
|
327
|
+
const b = (y - back.y) * back.image.width + x - back.x;
|
|
328
|
+
const f = (y - front.y) * front.image.width + x - front.x;
|
|
329
|
+
if (back.image.data[b * 4 + 3] <= OPAQUE_ALPHA_ABOVE || front.image.data[f * 4 + 3] <= OPAQUE_ALPHA_ABOVE) continue;
|
|
330
|
+
row.overlap_px++;
|
|
331
|
+
if (native !== undefined) countNative(native.counts, native.back, b, native.front, f, x, y);
|
|
332
|
+
const bm = this.materials[this.material(back.image, b)], fm = this.materials[this.material(front.image, f)];
|
|
333
|
+
const bs = bm.states, fs = fm.states;
|
|
334
|
+
if (((bs | fs) & UNRECORDED) !== 0) row.unrecorded_px++;
|
|
335
|
+
else if (bs === VISIBLE && fs === OCCLUDED) {
|
|
336
|
+
row.inverted_px++;
|
|
337
|
+
for (const layer of [...bm.layers, ...fm.layers]) layers.add(layer);
|
|
338
|
+
} else if (bs === OCCLUDED && fs === VISIBLE) row.agreeing_px++;
|
|
339
|
+
else if (decided(bs) && decided(fs)) row.unordered_px++;
|
|
340
|
+
else if (bs === PARTIAL_TOP && fs === PARTIAL_TOP) row.undecided_px['partial-top']++;
|
|
341
|
+
else if (bs === DEPTH_TIE && fs === DEPTH_TIE) row.undecided_px['depth-tie']++;
|
|
342
|
+
else row.undecided_px['mixed-source-states']++;
|
|
343
|
+
}
|
|
344
|
+
row.source_layers = [...layers].sort();
|
|
345
|
+
if (native !== undefined && native.counts.overlap_px > 0) row.native_samples = native.counts;
|
|
346
|
+
return row.overlap_px === 0 ? [] : [row];
|
|
347
|
+
}));
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* Each texel's source state (#1473): `SOURCE_STATE.none` at alpha 8 or less,
|
|
352
|
+
* otherwise the one state its material's contributors share — unrecorded
|
|
353
|
+
* when any is outside the record, `mixed-source-states` when they differ.
|
|
354
|
+
*/
|
|
355
|
+
states(image: Raster): { codes: Uint8Array; layers: string[] } {
|
|
356
|
+
const codes = new Uint8Array(image.width * image.height);
|
|
357
|
+
const used = new Set<number>();
|
|
358
|
+
for (let p = 0; p < codes.length; p++) {
|
|
359
|
+
if (image.data[p * 4 + 3] <= OPAQUE_ALPHA_ABOVE) continue;
|
|
360
|
+
const id = this.material(image, p);
|
|
361
|
+
used.add(id);
|
|
362
|
+
const { states } = this.materials[id];
|
|
363
|
+
codes[p] = (states & UNRECORDED) !== 0 ? SOURCE_STATE.unrecorded
|
|
364
|
+
: states === VISIBLE ? SOURCE_STATE.visible
|
|
365
|
+
: states === OCCLUDED ? SOURCE_STATE.occluded
|
|
366
|
+
: states === PARTIAL_TOP ? SOURCE_STATE['partial-top']
|
|
367
|
+
: states === DEPTH_TIE ? SOURCE_STATE['depth-tie']
|
|
368
|
+
: SOURCE_STATE['mixed-source-states'];
|
|
369
|
+
}
|
|
370
|
+
const layers = new Set<string>();
|
|
371
|
+
for (const id of used) for (const layer of this.materials[id].layers) layers.add(layer);
|
|
372
|
+
return { codes, layers: [...layers].sort() };
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/** The counts are read off {@link states}, so the map assemble writes beside them holds them exactly. */
|
|
376
|
+
summarize(image: Raster): PartSourceVisibility {
|
|
377
|
+
const { codes, layers } = this.states(image);
|
|
378
|
+
return { source_layers: layers, ...sourceStateCounts(codes) };
|
|
379
|
+
}
|
|
380
|
+
}
|
package/src/plate.ts
CHANGED
|
@@ -7,8 +7,7 @@
|
|
|
7
7
|
* inpainting run, lives in `src/comfy/plate.ts` and carries the graphs this
|
|
8
8
|
* file builds.
|
|
9
9
|
*
|
|
10
|
-
* 🔒 **The mask comes from a source, never a hand polygon.**
|
|
11
|
-
* read, and nothing else:
|
|
10
|
+
* 🔒 **The mask comes from a source, never a hand polygon.**
|
|
12
11
|
*
|
|
13
12
|
* - `seethrough:<dir>`: a See-through run in the wrapper form (`layers.json`
|
|
14
13
|
* and `parts/`), the figure being every drawn layer's alpha above
|
|
@@ -18,13 +17,14 @@
|
|
|
18
17
|
* (opaque white inside the figure, opaque black outside);
|
|
19
18
|
* - `matte:<dir>`: a model mask whose receipt binds both raw and final masks
|
|
20
19
|
* to the exact painting bytes and the recorded threshold/transform;
|
|
20
|
+
* - `classified:<manifest.json>`: an assemble scene mask with explicitly
|
|
21
|
+
* labeled outside-parts components and declared prop pixels excluded;
|
|
21
22
|
* - `--occluder <png>` (`--mode occluder`, issue #1230): a declared RGBA
|
|
22
23
|
* image of what stands in front of the character, on the painting's grid,
|
|
23
24
|
* the mask being its alpha above 0 (enclosed holes filled under `--holes`).
|
|
24
25
|
*
|
|
25
|
-
* The
|
|
26
|
-
*
|
|
27
|
-
* refuses before it writes anything or reaches a box.
|
|
26
|
+
* The source must match the painting grid or define a verified mapping to it.
|
|
27
|
+
* With no source the command refuses before it writes anything or reaches a box.
|
|
28
28
|
*
|
|
29
29
|
* The receipt (`rig-parts-plate-receipt/1`) names the painting, the mask, the
|
|
30
30
|
* model, every parameter, the graph, the GPU and the output, with the sha256
|
|
@@ -42,6 +42,7 @@ import { PartsError, type Problem } from './errors.ts';
|
|
|
42
42
|
import type { Graph } from './graphs.ts';
|
|
43
43
|
import { type LayerSet, OPAQUE_ALPHA_ABOVE, readWrapperLayers } from './layers.ts';
|
|
44
44
|
import { FIGURE_MASK_FILE, PAINTING_IN_RIG_FILE } from './parts.ts';
|
|
45
|
+
import { readClassifiedPlateMask } from './platecomponents.ts';
|
|
45
46
|
import { decodePngBytes, encodePngBytes } from './raster/png.ts';
|
|
46
47
|
import { fillHoles } from './raster/morph.ts';
|
|
47
48
|
import { newMask, newRaster, type Raster } from './raster/types.ts';
|
|
@@ -64,7 +65,12 @@ export const CORE_GRID_TRANSFORM_KEYS = ['source', 'padded', 'pad', 'pad_fill',
|
|
|
64
65
|
|
|
65
66
|
export type PlateMode = 'background' | 'foreground' | 'occluder';
|
|
66
67
|
export type PlateGraph = 'lama' | 'core';
|
|
67
|
-
export type MaskSource = 'seethrough' | 'figure-mask' | 'matte' | 'occluder';
|
|
68
|
+
export type MaskSource = 'seethrough' | 'figure-mask' | 'matte' | 'classified' | 'occluder';
|
|
69
|
+
|
|
70
|
+
interface PlateMaskClassification {
|
|
71
|
+
manifest_sha256: string;
|
|
72
|
+
prop_clips: Array<{ id: string; clipped_px: number }>;
|
|
73
|
+
}
|
|
68
74
|
|
|
69
75
|
export interface CoreGridTransform {
|
|
70
76
|
source: [number, number];
|
|
@@ -94,6 +100,7 @@ export interface PlateReceipt {
|
|
|
94
100
|
/** `--mode occluder` only: the declared occluder image the mask is read from. */
|
|
95
101
|
occluder?: { path: string; sha256: string };
|
|
96
102
|
mask: { source: MaskSource; from: string; path: string; sha256: string };
|
|
103
|
+
mask_classification?: PlateMaskClassification;
|
|
97
104
|
model: { name: string; checkpoint_sha256: string; checkpoint_sha256_from: 'declared' } | null;
|
|
98
105
|
params: Record<string, string | number | boolean>;
|
|
99
106
|
graph: string;
|
|
@@ -132,13 +139,16 @@ export function coreCfg(value: number | string | undefined, graph: PlateGraph):
|
|
|
132
139
|
return n;
|
|
133
140
|
}
|
|
134
141
|
|
|
135
|
-
/** `--mask-from <source>:<
|
|
142
|
+
/** `--mask-from <source>:<path>`, parsed; an absent or unknown source is refused by name. */
|
|
136
143
|
export function parseMaskFrom(value: string | undefined): { source: MaskSource; dir: string } {
|
|
137
144
|
if (value === undefined) {
|
|
138
|
-
fail('PLATE_MASK_SOURCE', '--mask-from',
|
|
145
|
+
fail('PLATE_MASK_SOURCE', '--mask-from',
|
|
146
|
+
'is absent; a source mask is required — seethrough:<run dir> (run comfy seethrough on the painting), ' +
|
|
147
|
+
'figure-mask:<assemble rig dir> (run assemble with config.scene), matte:<matte out dir> (run comfy matte), ' +
|
|
148
|
+
'or classified:<manifest.json> (declare roles for the assemble mask); a hand-drawn mask is not taken');
|
|
139
149
|
}
|
|
140
|
-
const m = /^(seethrough|figure-mask|matte):(.+)$/.exec(value);
|
|
141
|
-
if (m === null) fail('PLATE_MASK_SOURCE', '--mask-from', `is ${JSON.stringify(value)}; seethrough:<dir>, figure-mask:<dir> or
|
|
150
|
+
const m = /^(seethrough|figure-mask|matte|classified):(.+)$/.exec(value);
|
|
151
|
+
if (m === null) fail('PLATE_MASK_SOURCE', '--mask-from', `is ${JSON.stringify(value)}; seethrough:<dir>, figure-mask:<dir>, matte:<dir> or classified:<manifest.json> is required`);
|
|
142
152
|
return { source: m[1] as MaskSource, dir: m[2] };
|
|
143
153
|
}
|
|
144
154
|
|
|
@@ -147,6 +157,7 @@ export interface FigureMask {
|
|
|
147
157
|
width: number;
|
|
148
158
|
height: number;
|
|
149
159
|
inside: Uint8Array;
|
|
160
|
+
classification?: ReturnType<typeof readClassifiedPlateMask>['classification'];
|
|
150
161
|
}
|
|
151
162
|
|
|
152
163
|
function maskRecord(path: string, code: string, remedy = 're-run assemble'): { record: Record<string, unknown>; bytes: Uint8Array } {
|
|
@@ -266,6 +277,13 @@ function bindFigureSource(dir: string, parts: Record<string, unknown>, partsByte
|
|
|
266
277
|
* writes, and a mask with no figure pixel.
|
|
267
278
|
*/
|
|
268
279
|
export function readSourceMask(source: MaskSource, dir: string, width: number, height: number, painting?: Raster, paintingBytes?: Uint8Array): FigureMask {
|
|
280
|
+
if (source === 'classified') {
|
|
281
|
+
const mask = readClassifiedPlateMask(dir, width, height, paintingBytes);
|
|
282
|
+
if (!mask.inside.includes(1)) {
|
|
283
|
+
fail('PLATE_MASK_EMPTY', `classified:${dir}`, 'holds no figure pixel after excluding the declared props; verify the component roles');
|
|
284
|
+
}
|
|
285
|
+
return mask;
|
|
286
|
+
}
|
|
269
287
|
if (!existsSync(dir) || !statSync(dir).isDirectory()) {
|
|
270
288
|
fail('PLATE_MASK_SOURCE', `${source}:${dir}`, `is not a directory; ${source === 'seethrough' ? 'a See-through run directory (from `rig-parts comfy seethrough`)' : source === 'matte' ? 'a comfy matte directory with receipt.json, model-mask.png and mask.png' : 'an assemble output directory with parts.json and figure_rig.png'} is required`);
|
|
271
289
|
}
|
|
@@ -388,6 +406,23 @@ export function growMask(mask: FigureMask, r: number): FigureMask {
|
|
|
388
406
|
return { width: W, height: H, inside: out };
|
|
389
407
|
}
|
|
390
408
|
|
|
409
|
+
/** Clip declared prop pixels from the final background mask, on the painting grid before graph padding. */
|
|
410
|
+
export function clipClassifiedProps(source: FigureMask, grown?: FigureMask): PlateMaskClassification | undefined {
|
|
411
|
+
const classification = source.classification;
|
|
412
|
+
if (classification === undefined) return undefined;
|
|
413
|
+
return {
|
|
414
|
+
manifest_sha256: classification.manifest_sha256,
|
|
415
|
+
prop_clips: classification.props.map(({ id, indices }) => {
|
|
416
|
+
let clipped_px = 0;
|
|
417
|
+
if (grown !== undefined) for (const index of indices) {
|
|
418
|
+
clipped_px += grown.inside[index];
|
|
419
|
+
grown.inside[index] = 0;
|
|
420
|
+
}
|
|
421
|
+
return { id, clipped_px };
|
|
422
|
+
}),
|
|
423
|
+
};
|
|
424
|
+
}
|
|
425
|
+
|
|
391
426
|
/** The mask as the PNG written beside the plate and uploaded to the box: opaque white inside, opaque black outside (LoadImageMask reads its red channel). */
|
|
392
427
|
export function maskImage(mask: FigureMask): Raster {
|
|
393
428
|
const r = newRaster(mask.width, mask.height);
|
|
@@ -562,15 +597,18 @@ export function cropCoreGrid(padded: Raster, transform: CoreGridTransform): Rast
|
|
|
562
597
|
// ---------------------------------------------------------------------------
|
|
563
598
|
|
|
564
599
|
/** The receipt's key order: occluder mode binds the occluder, an off-grid `core` run its `grid_transform`. */
|
|
565
|
-
export function receiptKeys(occluder: boolean, gridTransform: boolean): readonly string[] {
|
|
600
|
+
export function receiptKeys(occluder: boolean, gridTransform: boolean, classified = false): readonly string[] {
|
|
566
601
|
if (occluder) return gridTransform ? PLATE_RECEIPT_OCCLUDER_GRID_TRANSFORM_KEYS : PLATE_RECEIPT_OCCLUDER_KEYS;
|
|
567
|
-
|
|
602
|
+
const keys = gridTransform ? PLATE_RECEIPT_GRID_TRANSFORM_KEYS : PLATE_RECEIPT_KEYS;
|
|
603
|
+
return classified ? keys.flatMap(key => key === 'mask' ? [key, 'mask_classification'] : [key]) : keys;
|
|
568
604
|
}
|
|
569
605
|
|
|
570
606
|
/** The receipt's JSON text, its keys in `PLATE_RECEIPT_KEYS` (or `PLATE_RECEIPT_GRID_TRANSFORM_KEYS` when `grid_transform` is present) order. */
|
|
571
607
|
export function receiptText(r: PlateReceipt): string {
|
|
572
608
|
const ordered: Record<string, unknown> = {};
|
|
573
|
-
for (const k of receiptKeys(r.mode === 'occluder', r.grid_transform !== undefined
|
|
609
|
+
for (const k of receiptKeys(r.mode === 'occluder', r.grid_transform !== undefined, r.mask.source === 'classified')) {
|
|
610
|
+
ordered[k] = (r as unknown as Record<string, unknown>)[k];
|
|
611
|
+
}
|
|
574
612
|
return `${JSON.stringify(ordered, null, 2)}\n`;
|
|
575
613
|
}
|
|
576
614
|
|
|
@@ -579,6 +617,20 @@ export function receiptPath(receiptDir: string, path: string): string {
|
|
|
579
617
|
return relative(resolve(receiptDir), resolve(path)).split('\\').join('/');
|
|
580
618
|
}
|
|
581
619
|
|
|
620
|
+
function validMaskClassification(value: unknown): value is PlateMaskClassification {
|
|
621
|
+
const digest = (v: unknown): v is string => typeof v === 'string' && /^[0-9a-f]{64}$/.test(v);
|
|
622
|
+
if (typeof value !== 'object' || value === null || !('manifest_sha256' in value) || !digest(value.manifest_sha256) ||
|
|
623
|
+
!('prop_clips' in value) || !Array.isArray(value.prop_clips) || Object.keys(value).join(',') !== 'manifest_sha256,prop_clips') return false;
|
|
624
|
+
const seen = new Set<string>();
|
|
625
|
+
return value.prop_clips.every((clip: unknown) => {
|
|
626
|
+
if (typeof clip !== 'object' || clip === null || !('id' in clip) || !digest(clip.id) || seen.has(clip.id) ||
|
|
627
|
+
!('clipped_px' in clip) || typeof clip.clipped_px !== 'number' || !Number.isSafeInteger(clip.clipped_px) ||
|
|
628
|
+
clip.clipped_px < 0 || Object.keys(clip).join(',') !== 'id,clipped_px') return false;
|
|
629
|
+
seen.add(clip.id);
|
|
630
|
+
return true;
|
|
631
|
+
});
|
|
632
|
+
}
|
|
633
|
+
|
|
582
634
|
/**
|
|
583
635
|
* Every problem between a receipt and the bytes on disk: its spec and key
|
|
584
636
|
* order, each of the painting, mask and output whose sha256 is not that of
|
|
@@ -599,9 +651,33 @@ export function verifyPlateReceipt(receiptFile: string): Problem[] {
|
|
|
599
651
|
}
|
|
600
652
|
if (r.spec !== PLATE_RECEIPT_SPEC) problems.push({ code: 'PLATE_RECEIPT_SPEC', object: receiptFile, detail: `has spec ${JSON.stringify(r.spec)}; "${PLATE_RECEIPT_SPEC}" is required` });
|
|
601
653
|
const keys = Object.keys(r).join(',');
|
|
602
|
-
const
|
|
654
|
+
const mask = r.mask as { source?: unknown; from?: unknown } | undefined;
|
|
655
|
+
const classified = mask?.source === 'classified';
|
|
656
|
+
const expectedKeys = receiptKeys(r.mode === 'occluder', 'grid_transform' in r, classified);
|
|
603
657
|
if (keys !== expectedKeys.join(',')) problems.push({ code: 'PLATE_RECEIPT_KEYS', object: receiptFile, detail: `has keys ${keys}; ${expectedKeys.join(',')} in that order is required` });
|
|
604
658
|
const base = dirname(receiptFile);
|
|
659
|
+
if (classified) {
|
|
660
|
+
const classification = r.mask_classification;
|
|
661
|
+
const from = mask?.from;
|
|
662
|
+
if (!validMaskClassification(classification) || typeof from !== 'string' || from === '') {
|
|
663
|
+
problems.push({
|
|
664
|
+
code: 'PLATE_RECEIPT_KEYS', object: `${receiptFile} mask_classification`,
|
|
665
|
+
detail: 'requires a manifest path, its lowercase SHA-256, and per-prop id and clipped_px counts',
|
|
666
|
+
});
|
|
667
|
+
} else {
|
|
668
|
+
const manifest = join(base, from);
|
|
669
|
+
let found: string | undefined;
|
|
670
|
+
try { found = sha256(readFileSync(manifest)); } catch { /* checked below */ }
|
|
671
|
+
if (found === undefined) {
|
|
672
|
+
problems.push({ code: 'PLATE_RECEIPT_FILE', object: manifest, detail: 'cannot read the classified plate manifest named by mask.from' });
|
|
673
|
+
} else if (found !== classification.manifest_sha256) {
|
|
674
|
+
problems.push({
|
|
675
|
+
code: 'PLATE_RECEIPT_HASH', object: manifest,
|
|
676
|
+
detail: `has sha256 ${found}; mask_classification declares ${classification.manifest_sha256}`,
|
|
677
|
+
});
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
}
|
|
605
681
|
let paintingRaster: Raster | undefined;
|
|
606
682
|
for (const field of r.mode === 'occluder' ? ['painting', 'occluder', 'mask', 'output'] as const : ['painting', 'mask', 'output'] as const) {
|
|
607
683
|
const f = r[field] as { path?: unknown; sha256?: unknown } | undefined;
|
|
@@ -689,6 +765,7 @@ export interface PlateWrite {
|
|
|
689
765
|
graph: string;
|
|
690
766
|
gpu: string | null;
|
|
691
767
|
gridTransform?: CoreGridTransform;
|
|
768
|
+
maskClassification?: PlateMaskClassification | undefined;
|
|
692
769
|
/** `--mode occluder` only: the occluder file, bound into the receipt by path and sha256. */
|
|
693
770
|
occluder?: { path: string; bytes: Uint8Array };
|
|
694
771
|
}
|
|
@@ -716,6 +793,7 @@ export function publishPlate(w: PlateWrite): PlateReceipt {
|
|
|
716
793
|
painting: { path: receiptPath(w.out, w.paintingPath), sha256: sha256(w.paintingBytes) },
|
|
717
794
|
...(w.occluder === undefined ? {} : { occluder: { path: receiptPath(w.out, w.occluder.path), sha256: sha256(w.occluder.bytes) } }),
|
|
718
795
|
mask: { source: w.source, from: receiptPath(w.out, w.sourceDir), path: PLATE_MASK_FILE, sha256: mask.sha256 },
|
|
796
|
+
...(w.maskClassification === undefined ? {} : { mask_classification: w.maskClassification }),
|
|
719
797
|
model: w.model,
|
|
720
798
|
params: w.params,
|
|
721
799
|
graph: w.graph,
|
|
@@ -777,6 +855,7 @@ export function runForeground(run: ForegroundRun): PlateReceipt {
|
|
|
777
855
|
source: from.source,
|
|
778
856
|
sourceDir: from.dir,
|
|
779
857
|
mask,
|
|
858
|
+
maskClassification: clipClassifiedProps(mask),
|
|
780
859
|
plate: foregroundMatte(painting.raster, mask),
|
|
781
860
|
model: null,
|
|
782
861
|
params: { mask_alpha_above: OPAQUE_ALPHA_ABOVE },
|