@babylonjs-toolkit/agent 1.2.0 → 1.2.1

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.
Files changed (36) hide show
  1. package/README.md +3 -2
  2. package/package.json +1 -1
  3. package/skills/bt-atlas/SKILL.md +22 -5
  4. package/skills/bt-design/references/3d-hero-docs.md +10 -3
  5. package/skills/bt-design/references/3d-hero-scroll.md +30 -5
  6. package/skills/bt-gauntlet/SKILL.md +4 -4
  7. package/skills/bt-gauntlet/references/spec-composition.md +4 -2
  8. package/skills/bt-gauntlet/references/target-images.md +28 -4
  9. package/skills/bt-gauntlet/references/unity-pipeline.md +30 -8
  10. package/skills/bt-hero/SKILL.md +3 -3
  11. package/skills/bt-landing/SKILL.md +1 -1
  12. package/skills/bt-prototype/SKILL.md +3 -3
  13. package/skills/bt-unwrap/SKILL.md +396 -0
  14. package/skills/bt-unwrap/scripts/blender/__pycache__/bt_unwrap.cpython-313.pyc +0 -0
  15. package/skills/bt-unwrap/scripts/blender/__pycache__/image_utils.cpython-313.pyc +0 -0
  16. package/skills/bt-unwrap/scripts/blender/__pycache__/mesh_tools.cpython-313.pyc +0 -0
  17. package/skills/bt-unwrap/scripts/blender/__pycache__/model_io.cpython-313.pyc +0 -0
  18. package/skills/bt-unwrap/scripts/blender/__pycache__/previews.cpython-313.pyc +0 -0
  19. package/skills/bt-unwrap/scripts/blender/__pycache__/rasterizer.cpython-313.pyc +0 -0
  20. package/skills/bt-unwrap/scripts/blender/__pycache__/reference_views.cpython-313.pyc +0 -0
  21. package/skills/bt-unwrap/scripts/blender/__pycache__/reference_warp.cpython-313.pyc +0 -0
  22. package/skills/bt-unwrap/scripts/blender/__pycache__/texture_bake.cpython-313.pyc +0 -0
  23. package/skills/bt-unwrap/scripts/blender/__pycache__/texture_compose.cpython-313.pyc +0 -0
  24. package/skills/bt-unwrap/scripts/blender/__pycache__/uv_layout.cpython-313.pyc +0 -0
  25. package/skills/bt-unwrap/scripts/blender/bt_unwrap.py +678 -0
  26. package/skills/bt-unwrap/scripts/blender/image_utils.py +264 -0
  27. package/skills/bt-unwrap/scripts/blender/mesh_tools.py +508 -0
  28. package/skills/bt-unwrap/scripts/blender/model_io.py +135 -0
  29. package/skills/bt-unwrap/scripts/blender/previews.py +205 -0
  30. package/skills/bt-unwrap/scripts/blender/rasterizer.py +217 -0
  31. package/skills/bt-unwrap/scripts/blender/reference_views.py +945 -0
  32. package/skills/bt-unwrap/scripts/blender/reference_warp.py +571 -0
  33. package/skills/bt-unwrap/scripts/blender/texture_bake.py +390 -0
  34. package/skills/bt-unwrap/scripts/blender/texture_compose.py +596 -0
  35. package/skills/bt-unwrap/scripts/blender/uv_layout.py +605 -0
  36. package/skills/bt-unwrap/scripts/bt-unwrap.mjs +165 -0
@@ -0,0 +1,571 @@
1
+ """
2
+ Local alignment for bt-unwrap's reference images.
3
+
4
+ A reference image and an AI-generated mesh never agree exactly: a logo drawn at one spot in the image sits a
5
+ little elsewhere on the mesh. The source texture the generator baked onto the mesh is blurry, but its logos
6
+ and stripes ARE where the mesh expects them. So each reference is matched against a render of that source
7
+ texture from the reference's own (fitted) camera: both images are cut into overlapping patches, every patch
8
+ pair is phase-correlated to find how far the reference's content is shifted, and the shifts become a smooth
9
+ displacement field. Painting then samples the sharp reference at the displaced position, which puts its
10
+ detail exactly where the mesh's features are.
11
+
12
+ Coarse-to-fine: a low-resolution pass catches large shifts, a finer pass on the pre-warped image refines them.
13
+
14
+ The same render also checks consistency. A generated reference and a generated mesh disagree most on
15
+ complex parts (engines, suspension, cockpits): the image draws a chrome fin, a reflection or a pipe where the
16
+ mesh has something else. Where the model's own texture shows features (edges of parts, letters, stripes), a
17
+ trustworthy reference shows the same features in the same places, only sharper, so their local correlation
18
+ is high; a reference drawing different parts correlates poorly. Where the model's texture shows nothing (a
19
+ plain panel the generator left blank), there is nothing to contradict and the reference is trusted. The
20
+ agreement map records this per pixel; texture_compose decides how much it matters on each face (a lot in
21
+ cluttered parts, little on smooth panels, where a reference is simply a decal).
22
+ """
23
+ from dataclasses import dataclass
24
+ from typing import Optional
25
+
26
+ import numpy as np
27
+
28
+ import image_utils
29
+ import rasterizer
30
+ import reference_views
31
+ import uv_layout
32
+
33
+ PYRAMID_LONG_SIDES = (512, 1024) # working resolutions, coarse to fine
34
+ PATCH_SIZE = 64 # working pixels; shifts up to half of this are measurable
35
+ PATCH_STEP = 16 # spacing of patch centers in working pixels
36
+ DETAIL_BLUR_RADIUS = 1 # removes pixel noise before matching
37
+ BACKGROUND_BLUR_RADIUS = 6 # high-pass: removes shading, keeps edges (logos, stripes)
38
+ MINIMUM_PATCH_COVERAGE = 0.85 # share of a patch that must be on the subject in both images
39
+ MINIMUM_PATCH_CONTRAST = 0.01 # patches with less high-pass energy carry no alignment signal
40
+ MINIMUM_PEAK = 0.08 # phase-correlation peak below this is treated as no match
41
+ OUTLIER_PIXELS = 3.0 # a shift this far from its neighbours' median is discarded
42
+ # The measured shifts become a smooth correction: a coarse control grid fitted to them, where bending costs
43
+ # much more than a uniform stretch, shear or shift. Straight edges (a wing, a stripe) stay straight; local
44
+ # bends survive only where many patches agree on them.
45
+ CONTROL_SPACING_FRACTION = 0.15 # control grid spacing, as a share of the subject's longer side
46
+ BENDING_PENALTY = 4.0 # weight of the straightness penalty, relative to the measurements
47
+ ROBUST_PASSES = 3 # reweighting passes that discount shifts disagreeing with the fit
48
+ ROBUST_PIXELS = 2.0 # residual (working pixels) beyond which a shift's weight drops
49
+
50
+ CONSISTENCY_LONG_SIDE = 1024 # working resolution of the consistency check
51
+ CONSISTENCY_MINIMUM_PIXELS = 500 # fewer comparable pixels than this: no check (everything trusted)
52
+ # The test compares features about 0.5-2.5 % of the subject across (parts, letters, stripes): finer detail is
53
+ # what a reference should add, and a band this coarse tolerates the few pixels the warp leaves.
54
+ STRUCTURE_FINE_FRACTION = 0.0025 # band-pass inner blur radius, as a share of the subject's longer side
55
+ STRUCTURE_COARSE_FRACTION = 0.0125 # band-pass outer blur radius
56
+ STRUCTURE_WINDOW_FRACTION = 0.015 # correlation window radius
57
+ STRUCTURE_MINIMUM_ENERGY = 0.012 # source feature strength (luminance) below which there is nothing to test
58
+ # Local feature correlation that gives no trust / full trust, per unit of --ref-consistency (0.5 -> 0.05 / 0.3).
59
+ CORRELATION_RAMP_PER_STRICTNESS = (0.1, 0.6)
60
+
61
+
62
+ @dataclass
63
+ class WarpField:
64
+ """A displacement field over a reference image, in full-resolution reference pixels."""
65
+
66
+ displacement: np.ndarray # float32 (grid_height, grid_width, 2): x, y shift to add to sample positions
67
+ origin: tuple # full-resolution pixel position of grid cell (0, 0)
68
+ step: float # full-resolution pixels between grid cells
69
+ patches_used: int
70
+ median_shift: float # full-resolution pixels
71
+ maximum_shift: float
72
+
73
+ def displacement_at(self, pixel_x: np.ndarray, pixel_y: np.ndarray) -> np.ndarray:
74
+ """
75
+ Interpolates the shift at reference pixel positions.
76
+
77
+ :param pixel_x: Horizontal pixel coordinates.
78
+ :param pixel_y: Vertical pixel coordinates, bottom-up.
79
+ :returns: float array (count, 2).
80
+ """
81
+ grid_x = (pixel_x - self.origin[0]) / self.step + 0.5
82
+ grid_y = (pixel_y - self.origin[1]) / self.step + 0.5
83
+ return image_utils.sample_bilinear(self.displacement, grid_x, grid_y)
84
+
85
+ def report(self) -> dict:
86
+ """Summary for the JSON report."""
87
+ return {"patches_used": self.patches_used, "median_shift_pixels": round(self.median_shift, 1),
88
+ "maximum_shift_pixels": round(self.maximum_shift, 1)}
89
+
90
+
91
+ @dataclass
92
+ class AgreementMap:
93
+ """How far each part of a reference image can be trusted: 1 where it agrees with the source texture."""
94
+
95
+ values: np.ndarray # float32 (height, width), 0..1, at the check's working resolution
96
+ scale: float # working pixels per full-resolution reference pixel
97
+ source_render: np.ndarray # float32 (height, width, 3) what the model's own texture shows from this camera
98
+ reference_render: np.ndarray # float32 (height, width, 3) the warped reference
99
+ trusted_percent: float # share of the model's pixels in this view that agree
100
+
101
+ def at(self, pixel_x: np.ndarray, pixel_y: np.ndarray) -> np.ndarray:
102
+ """
103
+ Agreement at full-resolution reference pixel positions (already warped).
104
+
105
+ :param pixel_x: Horizontal pixel coordinates.
106
+ :param pixel_y: Vertical pixel coordinates, bottom-up.
107
+ :returns: float32 array (count,), 0..1.
108
+ """
109
+ return image_utils.sample_bilinear(self.values[:, :, None], pixel_x * self.scale, pixel_y * self.scale)[:, 0]
110
+
111
+ def report(self) -> dict:
112
+ """Summary for the JSON report."""
113
+ return {"trusted_percent": round(self.trusted_percent, 1)}
114
+
115
+
116
+ def consistency_map(reference, triangles, color: np.ndarray, strictness: float) -> Optional[AgreementMap]:
117
+ """
118
+ Compares a reference with the model's own (baked source) texture seen from the same fitted camera and
119
+ maps how far it can be trusted: wherever the source shows features, the reference's features must line
120
+ up with them.
121
+
122
+ :param reference: An aligned reference with a depth buffer (and its local warp, when there is one).
123
+ :param triangles: TriangleSet of the final mesh with the working UV layer.
124
+ :param color: float32 (size, size, 4) baked source color on the working layout.
125
+ :param strictness: 0..1; how closely the features must correlate (0.5 = the default --ref-consistency).
126
+ :returns: The agreement map, or None when too little of the model is visible to compare.
127
+ """
128
+ view = render_source_view(reference, triangles, color, CONSISTENCY_LONG_SIDE)
129
+ source_rgb, covered, scale = view.rgb, view.covered, view.scale
130
+ height, width = covered.shape
131
+ grid_x, grid_y = np.meshgrid(np.arange(width) + 0.5, np.arange(height) + 0.5)
132
+ full_x, full_y = grid_x.ravel() / scale, grid_y.ravel() / scale
133
+ if reference.warp is not None:
134
+ shift = reference.warp.displacement_at(full_x, full_y)
135
+ full_x, full_y = full_x + shift[:, 0], full_y + shift[:, 1]
136
+ reference_rgb = image_utils.sample_bilinear(reference.pixels[:, :, :3], full_x, full_y).reshape(height, width, 3)
137
+ in_subject = image_utils.sample_nearest(reference.mask, full_x, full_y).reshape(height, width)
138
+ comparable = covered & in_subject
139
+ if comparable.sum() < CONSISTENCY_MINIMUM_PIXELS:
140
+ return None
141
+ x0, y0, x1, y1 = reference.bbox
142
+ subject_pixels = max(x1 - x0, y1 - y0) * scale
143
+ agreement = _structure_trust(source_rgb, reference_rgb, covered, subject_pixels, strictness)
144
+ agreement[~covered] = 1.0 # off the model nothing is painted; keep edges from fading through the windows
145
+ return AgreementMap(values=agreement, scale=scale, source_render=source_rgb, reference_render=reference_rgb,
146
+ trusted_percent=float((agreement[comparable] >= 0.5).mean()) * 100.0)
147
+
148
+
149
+ def _structure_trust(source_rgb: np.ndarray, reference_rgb: np.ndarray, covered: np.ndarray,
150
+ subject_pixels: float, strictness: float) -> np.ndarray:
151
+ """
152
+ Local correlation of the two images' features (a band-pass of luminance, lighting removed), over windows
153
+ a little larger than the features and only over the model's own pixels. Where the source shows hardly
154
+ any features there is nothing to contradict, so the reference is trusted (it may add detail the source
155
+ lost).
156
+
157
+ :param subject_pixels: Length of the subject's longer side in working pixels; sets the feature scale.
158
+ :param strictness: 0..1 scale of the correlation thresholds.
159
+ :returns: float32 (height, width), 0..1.
160
+ """
161
+ fine = max(1, int(round(STRUCTURE_FINE_FRACTION * subject_pixels)))
162
+ coarse = max(fine + 2, int(round(STRUCTURE_COARSE_FRACTION * subject_pixels)))
163
+ radius = max(3, int(round(STRUCTURE_WINDOW_FRACTION * subject_pixels)))
164
+ source_features = _masked_structure(source_rgb, covered, fine, coarse)
165
+ reference_features = _masked_structure(reference_rgb, covered, fine, coarse)
166
+ weight = covered.astype(np.float32)
167
+
168
+ def local_mean(values: np.ndarray) -> np.ndarray:
169
+ return box_blur(box_blur(values * weight, radius), radius)
170
+
171
+ weight_mean = np.maximum(local_mean(np.ones_like(weight)), 1e-6)
172
+ source_mean = local_mean(source_features) / weight_mean
173
+ reference_mean = local_mean(reference_features) / weight_mean
174
+ source_variance = np.maximum(local_mean(source_features ** 2) / weight_mean - source_mean ** 2, 0.0)
175
+ reference_variance = np.maximum(local_mean(reference_features ** 2) / weight_mean - reference_mean ** 2, 0.0)
176
+ covariance = local_mean(source_features * reference_features) / weight_mean - source_mean * reference_mean
177
+ correlation = covariance / np.sqrt(source_variance * reference_variance + 1e-8)
178
+ low, high = (value * strictness for value in CORRELATION_RAMP_PER_STRICTNESS)
179
+ trust = np.clip((correlation - low) / max(high - low, 1e-6), 0.0, 1.0)
180
+ has_features = np.sqrt(source_variance) >= STRUCTURE_MINIMUM_ENERGY
181
+ return np.where(has_features, trust, 1.0).astype(np.float32)
182
+
183
+
184
+ def _masked_blur(image: np.ndarray, weight_mask: np.ndarray, radius: int) -> np.ndarray:
185
+ """
186
+ Blurs an image using only the pixels inside a mask (normalized convolution); outside stays as is.
187
+
188
+ :param image: float array (height, width) or (height, width, channels).
189
+ :param weight_mask: Boolean (height, width) pixels that take part.
190
+ :param radius: Box radius; applied twice for a smooth falloff.
191
+ :returns: float32 array of the same shape.
192
+ """
193
+ weight = weight_mask.astype(np.float32)
194
+ blurred_weight = np.maximum(box_blur(box_blur(weight, radius), radius), 1e-6)
195
+ planes = image[:, :, None] if image.ndim == 2 else image
196
+ channels = [box_blur(box_blur(planes[:, :, channel] * weight, radius), radius) / blurred_weight
197
+ for channel in range(planes.shape[2])]
198
+ blurred = np.where(weight_mask[:, :, None], np.stack(channels, axis=-1), planes)
199
+ return (blurred[:, :, 0] if image.ndim == 2 else blurred).astype(np.float32)
200
+
201
+
202
+ def _masked_structure(rgb: np.ndarray, covered: np.ndarray, fine_radius: int, coarse_radius: int) -> np.ndarray:
203
+ """
204
+ Band-pass grayscale (features between the two blur radii), computed over the model's own pixels only, so
205
+ the outline of the model against whatever lies behind it (black in a render, the backdrop in a photo)
206
+ adds no features.
207
+ """
208
+ luminance = rgb[:, :, 0] * 0.2126 + rgb[:, :, 1] * 0.7152 + rgb[:, :, 2] * 0.0722
209
+ detail = _masked_blur(luminance, covered, fine_radius)
210
+ background = _masked_blur(detail, covered, coarse_radius)
211
+ return np.where(covered, detail - background, 0.0).astype(np.float32)
212
+
213
+
214
+ def consistency_preview(agreement: AgreementMap) -> np.ndarray:
215
+ """
216
+ Check image for the consistency map, three panels: the source render, the warped reference, and the
217
+ reference with the areas whose features disagree with the source tinted red.
218
+
219
+ :param agreement: A computed agreement map.
220
+ :returns: float32 (height, width * 3 + gaps, 4) image, bottom-up.
221
+ """
222
+ height, width = agreement.values.shape
223
+ doubt = (1.0 - agreement.values)[:, :, None] * 0.75
224
+ tinted = np.clip(agreement.reference_render * (1.0 - doubt) + np.array((0.9, 0.0, 0.0)) * doubt, 0.0, 1.0)
225
+ gap = np.ones((height, 8, 3), dtype=np.float32)
226
+ panels = np.concatenate((agreement.source_render, gap, agreement.reference_render, gap, tinted), axis=1)
227
+ return np.concatenate((panels, np.ones(panels.shape[:2] + (1,), dtype=np.float32)), axis=2).astype(np.float32)
228
+
229
+
230
+ @dataclass
231
+ class SourceView:
232
+ """The model, textured with its own baked source color, seen through a reference's fitted camera."""
233
+
234
+ rgb: np.ndarray # float32 (height, width, 3)
235
+ covered: np.ndarray # bool (height, width): pixels on the model
236
+ depth: np.ndarray # float32 (height, width): nearest surface toward the camera, -inf off the model
237
+ scale: float # working pixels per full-resolution reference pixel
238
+
239
+
240
+ def render_source_view(reference, triangles, color: np.ndarray, long_side: int) -> SourceView:
241
+ """
242
+ Renders the model, textured with the baked source color on the new layout, through a reference's
243
+ fitted camera at a working resolution.
244
+
245
+ :param reference: An aligned reference.
246
+ :param triangles: TriangleSet of the final mesh with the working UV layer.
247
+ :param color: float32 (size, size, 4) baked source color.
248
+ :param long_side: Working resolution of the longer image side.
249
+ :returns: The rendered view.
250
+ """
251
+ full_height, full_width = reference.mask.shape
252
+ scale = long_side / max(full_width, full_height)
253
+ width, height = max(8, int(round(full_width * scale))), max(8, int(round(full_height * scale)))
254
+ pixel_points = reference_views.map_to_reference(reference, triangles.positions) * scale
255
+ triangle_depth = reference_views.depth_along(triangles.positions, reference.direction)
256
+ nearest = rasterizer.rasterize_depth(pixel_points, triangle_depth, width, height).ravel()
257
+
258
+ depth_slack = 1e-4 * float(np.ptp(triangle_depth))
259
+ texture_size = color.shape[0]
260
+ uvs = triangles.uvs[uv_layout.NEW_UV_LAYER]
261
+ image = np.zeros((width * height, 3), dtype=np.float32)
262
+ covered = np.zeros(width * height, dtype=bool)
263
+ for fragments in rasterizer.rasterize(pixel_points, width, height):
264
+ fragment_depth = (triangle_depth[fragments.triangle_index] * fragments.barycentric).sum(axis=1)
265
+ front = fragment_depth >= nearest[fragments.pixel_index] - depth_slack
266
+ if not front.any():
267
+ continue
268
+ triangle_index = fragments.triangle_index[front]
269
+ weights = fragments.barycentric[front]
270
+ texel_uv = (uvs[triangle_index] * weights[:, :, None]).sum(axis=1)
271
+ image[fragments.pixel_index[front]] = image_utils.sample_bilinear(
272
+ color[:, :, :3], texel_uv[:, 0] * texture_size, texel_uv[:, 1] * texture_size)
273
+ covered[fragments.pixel_index[front]] = True
274
+ return SourceView(rgb=image.reshape(height, width, 3), covered=covered.reshape(height, width),
275
+ depth=nearest.reshape(height, width), scale=scale)
276
+
277
+
278
+ def box_blur(image: np.ndarray, radius: int) -> np.ndarray:
279
+ """
280
+ Separable box blur with edge clamping (summed-area along each axis).
281
+
282
+ :param image: float array (height, width).
283
+ :param radius: Half-width in pixels; 0 returns the input.
284
+ :returns: Blurred array, same shape.
285
+ """
286
+ if radius <= 0:
287
+ return image
288
+ blurred = image.astype(np.float64)
289
+ for axis in (0, 1):
290
+ padded = np.concatenate((np.repeat(np.take(blurred, [0], axis=axis), radius + 1, axis=axis), blurred,
291
+ np.repeat(np.take(blurred, [-1], axis=axis), radius, axis=axis)), axis=axis)
292
+ cumulative = np.cumsum(padded, axis=axis)
293
+ length = blurred.shape[axis]
294
+ upper = np.take(cumulative, np.arange(2 * radius + 1, 2 * radius + 1 + length), axis=axis)
295
+ lower = np.take(cumulative, np.arange(0, length), axis=axis)
296
+ blurred = (upper - lower) / (2 * radius + 1)
297
+ return blurred.astype(np.float32)
298
+
299
+
300
+ def _structure(rgb: np.ndarray) -> np.ndarray:
301
+ """Edges-only grayscale: luminance, lightly denoised, minus its local average (lighting removed)."""
302
+ luminance = rgb[:, :, 0] * 0.2126 + rgb[:, :, 1] * 0.7152 + rgb[:, :, 2] * 0.0722
303
+ detail = box_blur(box_blur(luminance, DETAIL_BLUR_RADIUS), DETAIL_BLUR_RADIUS)
304
+ background = box_blur(box_blur(detail, BACKGROUND_BLUR_RADIUS), BACKGROUND_BLUR_RADIUS)
305
+ return detail - background
306
+
307
+
308
+ def _patch_centers(height: int, width: int) -> tuple:
309
+ """Grid of patch centers; returns (row centers, column centers)."""
310
+ half = PATCH_SIZE // 2
311
+ return (np.arange(half, max(half + 1, height - half), PATCH_STEP),
312
+ np.arange(half, max(half + 1, width - half), PATCH_STEP))
313
+
314
+
315
+ def _extract_patches(image: np.ndarray, rows: np.ndarray, columns: np.ndarray) -> np.ndarray:
316
+ """Cuts PATCH_SIZE squares centered on every grid point; returns (rows, columns, size, size)."""
317
+ half = PATCH_SIZE // 2
318
+ offsets = np.arange(-half, half)
319
+ row_index = rows[:, None, None, None] + offsets[None, None, :, None]
320
+ column_index = columns[None, :, None, None] + offsets[None, None, None, :]
321
+ row_index = np.clip(row_index, 0, image.shape[0] - 1)
322
+ column_index = np.clip(column_index, 0, image.shape[1] - 1)
323
+ return image[row_index, column_index]
324
+
325
+
326
+ def _phase_correlate(source_patches: np.ndarray, reference_patches: np.ndarray) -> tuple:
327
+ """
328
+ Finds, for every patch pair, the shift d with reference(x) ≈ source(x - d).
329
+
330
+ :returns: (shift float32 (..., 2) as x, y; peak float32 (...) in 0..1).
331
+ """
332
+ window = np.outer(np.hanning(PATCH_SIZE), np.hanning(PATCH_SIZE)).astype(np.float32)
333
+ source_spectrum = np.fft.rfft2(source_patches * window)
334
+ reference_spectrum = np.fft.rfft2(reference_patches * window)
335
+ cross = reference_spectrum * np.conj(source_spectrum)
336
+ cross /= np.maximum(np.abs(cross), 1e-9)
337
+ correlation = np.fft.irfft2(cross, s=(PATCH_SIZE, PATCH_SIZE))
338
+ flat = correlation.reshape(correlation.shape[:-2] + (-1,))
339
+ peak_index = flat.argmax(axis=-1)
340
+ peak = np.take_along_axis(flat, peak_index[..., None], axis=-1)[..., 0]
341
+ shift_y = peak_index // PATCH_SIZE
342
+ shift_x = peak_index % PATCH_SIZE
343
+ shift_x = np.where(shift_x >= PATCH_SIZE // 2, shift_x - PATCH_SIZE, shift_x).astype(np.float32)
344
+ shift_y = np.where(shift_y >= PATCH_SIZE // 2, shift_y - PATCH_SIZE, shift_y).astype(np.float32)
345
+ fraction_x, fraction_y = _subpixel_offsets(flat, peak_index)
346
+ return np.stack((shift_x + fraction_x, shift_y + fraction_y), axis=-1), peak.astype(np.float32)
347
+
348
+
349
+ def _subpixel_offsets(flat_correlation: np.ndarray, peak_index: np.ndarray) -> tuple:
350
+ """Parabolic refinement of each correlation peak; returns (x offset, y offset), each within ±0.5 pixel."""
351
+ row = peak_index // PATCH_SIZE
352
+ column = peak_index % PATCH_SIZE
353
+
354
+ def value_at(at_row, at_column):
355
+ wrapped = (at_row % PATCH_SIZE) * PATCH_SIZE + (at_column % PATCH_SIZE)
356
+ return np.take_along_axis(flat_correlation, wrapped[..., None], axis=-1)[..., 0]
357
+
358
+ center = value_at(row, column)
359
+ offsets = []
360
+ for before, after in ((value_at(row, column - 1), value_at(row, column + 1)),
361
+ (value_at(row - 1, column), value_at(row + 1, column))):
362
+ denominator = before - 2.0 * center + after
363
+ offset = np.where(np.abs(denominator) > 1e-9, 0.5 * (before - after) / denominator, 0.0)
364
+ offsets.append(np.clip(offset, -0.5, 0.5).astype(np.float32))
365
+ return offsets[0], offsets[1]
366
+
367
+
368
+ def _neighbour_median(field: np.ndarray, valid: np.ndarray) -> np.ndarray:
369
+ """Median of each grid cell's valid 3x3 neighbours (NaN where there are none)."""
370
+ height, width = valid.shape
371
+ stacked = np.full((9, height, width, 2), np.nan, dtype=np.float32)
372
+ padded = np.pad(np.where(valid[..., None], field, np.nan), ((1, 1), (1, 1), (0, 0)), constant_values=np.nan)
373
+ slot = 0
374
+ for row_shift in (-1, 0, 1):
375
+ for column_shift in (-1, 0, 1):
376
+ stacked[slot] = padded[1 + row_shift:1 + row_shift + height, 1 + column_shift:1 + column_shift + width]
377
+ slot += 1
378
+ with np.errstate(all="ignore"):
379
+ return np.nanmedian(stacked, axis=0)
380
+
381
+
382
+ def _fit_smooth_field(shifts: np.ndarray, valid: np.ndarray, weights: np.ndarray, rows: np.ndarray,
383
+ columns: np.ndarray, spacing: float) -> np.ndarray:
384
+ """
385
+ Fits a smooth displacement field to the measured patch shifts: values on a coarse control grid,
386
+ interpolated bilinearly, chosen to match the measurements (robustly reweighted) while keeping second
387
+ differences small — so the field stays close to a uniform stretch, shear and shift and only bends where
388
+ the data clearly asks for it.
389
+
390
+ :param shifts: float32 (grid_height, grid_width, 2) measured shifts per patch.
391
+ :param valid: Boolean (grid_height, grid_width) patches to trust.
392
+ :param weights: float32 (grid_height, grid_width) confidence per patch (correlation peak).
393
+ :param rows: Patch-center rows in working pixels.
394
+ :param columns: Patch-center columns in working pixels.
395
+ :param spacing: Control grid spacing in working pixels.
396
+ :returns: float32 (grid_height, grid_width, 2) smooth field on the patch grid.
397
+ """
398
+ control_columns = max(2, int(np.ceil((columns[-1] - columns[0]) / spacing)) + 1)
399
+ control_rows = max(2, int(np.ceil((rows[-1] - rows[0]) / spacing)) + 1)
400
+ interpolation = _bilinear_matrix(rows, columns, control_rows, control_columns)
401
+ bending = _bending_matrix(control_rows, control_columns)
402
+ targets = shifts.reshape(-1, 2).astype(np.float64)
403
+ base_weight = np.where(valid, weights, 0.0).ravel().astype(np.float64)
404
+ penalty = BENDING_PENALTY * max(float(base_weight.sum()), 1.0) / (control_rows * control_columns)
405
+ regularizer = penalty * (bending.T @ bending) + 1e-6 * np.eye(control_rows * control_columns)
406
+ robust_weight = np.ones_like(base_weight)
407
+ controls = np.zeros((control_rows * control_columns, 2))
408
+ for _ in range(ROBUST_PASSES):
409
+ weight = base_weight * robust_weight
410
+ weighted = interpolation * weight[:, None]
411
+ controls = np.linalg.solve(interpolation.T @ weighted + regularizer, weighted.T @ targets)
412
+ residual = np.linalg.norm(interpolation @ controls - targets, axis=1)
413
+ robust_weight = np.minimum(1.0, ROBUST_PIXELS / np.maximum(residual, 1e-9))
414
+ return (interpolation @ controls).reshape(shifts.shape).astype(np.float32)
415
+
416
+
417
+ def _bilinear_matrix(rows: np.ndarray, columns: np.ndarray, control_rows: int, control_columns: int) -> np.ndarray:
418
+ """Weights that interpolate a control grid (spanning the patch grid) at every patch center."""
419
+ grid_row = (rows - rows[0]) / max(float(rows[-1] - rows[0]), 1.0) * (control_rows - 1)
420
+ grid_column = (columns - columns[0]) / max(float(columns[-1] - columns[0]), 1.0) * (control_columns - 1)
421
+ row_low = np.minimum(np.floor(grid_row).astype(np.int64), control_rows - 2)
422
+ column_low = np.minimum(np.floor(grid_column).astype(np.int64), control_columns - 2)
423
+ row_fraction = grid_row - row_low
424
+ column_fraction = grid_column - column_low
425
+ matrix = np.zeros((rows.size, columns.size, control_rows * control_columns))
426
+ patch_row, patch_column = np.meshgrid(np.arange(rows.size), np.arange(columns.size), indexing="ij")
427
+ for row_step, row_weight in ((0, 1.0 - row_fraction), (1, row_fraction)):
428
+ for column_step, column_weight in ((0, 1.0 - column_fraction), (1, column_fraction)):
429
+ control = (row_low[:, None] + row_step) * control_columns + (column_low[None, :] + column_step)
430
+ matrix[patch_row, patch_column, control] += row_weight[:, None] * column_weight[None, :]
431
+ return matrix.reshape(rows.size * columns.size, control_rows * control_columns)
432
+
433
+
434
+ def _bending_matrix(control_rows: int, control_columns: int) -> np.ndarray:
435
+ """Second differences along rows and columns plus the twist term: zero exactly for affine fields."""
436
+ def index(row: int, column: int) -> int:
437
+ return row * control_columns + column
438
+
439
+ equations = []
440
+ for row in range(control_rows):
441
+ for column in range(control_columns):
442
+ if 0 < column < control_columns - 1:
443
+ equations.append({index(row, column - 1): 1.0, index(row, column): -2.0, index(row, column + 1): 1.0})
444
+ if 0 < row < control_rows - 1:
445
+ equations.append({index(row - 1, column): 1.0, index(row, column): -2.0, index(row + 1, column): 1.0})
446
+ if row < control_rows - 1 and column < control_columns - 1:
447
+ equations.append({index(row, column): 1.0, index(row, column + 1): -1.0,
448
+ index(row + 1, column): -1.0, index(row + 1, column + 1): 1.0})
449
+ matrix = np.zeros((max(len(equations), 1), control_rows * control_columns))
450
+ for equation_number, equation in enumerate(equations):
451
+ for control, value in equation.items():
452
+ matrix[equation_number, control] = value
453
+ return matrix
454
+
455
+
456
+ def _estimate_level(source_structure, source_covered, reference_structure, reference_covered, maximum_shift,
457
+ control_spacing):
458
+ """One pyramid level: patch shifts on a grid, outliers removed, then a smooth field fitted to them."""
459
+ rows, columns = _patch_centers(*source_structure.shape)
460
+ source_patches = _extract_patches(source_structure, rows, columns)
461
+ reference_patches = _extract_patches(reference_structure, rows, columns)
462
+ source_coverage = _extract_patches(source_covered.astype(np.float32), rows, columns).mean(axis=(-1, -2))
463
+ reference_coverage = _extract_patches(reference_covered.astype(np.float32), rows, columns).mean(axis=(-1, -2))
464
+ contrast = np.minimum(source_patches.std(axis=(-1, -2)), reference_patches.std(axis=(-1, -2)))
465
+ shifts, peaks = _phase_correlate(source_patches, reference_patches)
466
+ valid = (source_coverage >= MINIMUM_PATCH_COVERAGE) & (reference_coverage >= MINIMUM_PATCH_COVERAGE) & \
467
+ (contrast >= MINIMUM_PATCH_CONTRAST) & (peaks >= MINIMUM_PEAK) & \
468
+ (np.linalg.norm(shifts, axis=-1) <= maximum_shift)
469
+ if valid.sum() >= 4:
470
+ local = _neighbour_median(shifts, valid)
471
+ deviation = np.linalg.norm(shifts - np.nan_to_num(local), axis=-1)
472
+ valid &= ~np.isnan(local[..., 0]) & (deviation <= OUTLIER_PIXELS)
473
+ if not valid.any():
474
+ return np.zeros(shifts.shape, dtype=np.float32), rows, columns, 0
475
+ return _fit_smooth_field(shifts, valid, peaks, rows, columns, control_spacing), rows, columns, int(valid.sum())
476
+
477
+
478
+ def _sample_field(field, rows, columns, pixel_x, pixel_y):
479
+ """Bilinear lookup of a patch-grid field at working-resolution pixel positions."""
480
+ grid_x = (pixel_x - columns[0]) / PATCH_STEP + 0.5
481
+ grid_y = (pixel_y - rows[0]) / PATCH_STEP + 0.5
482
+ return image_utils.sample_bilinear(field, grid_x, grid_y)
483
+
484
+
485
+ def estimate_warp(reference, triangles, color: np.ndarray, maximum_shift_fraction: float):
486
+ """
487
+ Measures how far each part of a reference image is shifted from where the mesh expects it.
488
+
489
+ :param reference: An aligned, used reference with a depth buffer.
490
+ :param triangles: TriangleSet of the final mesh with the working UV layer.
491
+ :param color: float32 (size, size, 4) baked source color on the working layout.
492
+ :param maximum_shift_fraction: Largest allowed shift as a fraction of the subject's longer side.
493
+ :returns: A WarpField in full-resolution pixels, or None when no patch matched.
494
+ """
495
+ x0, y0, x1, y1 = reference.bbox
496
+ subject_long_side = max(x1 - x0, y1 - y0)
497
+ total_field = None
498
+ total_rows = total_columns = None
499
+ total_scale = 1.0
500
+ patches_used = 0
501
+ for long_side in PYRAMID_LONG_SIDES:
502
+ view = render_source_view(reference, triangles, color, long_side)
503
+ source_rgb, source_covered, scale = view.rgb, view.covered, view.scale
504
+ height, width = source_covered.shape
505
+ reference_rgb = image_utils.resize_image(reference.pixels[:, :, :3], width, height)
506
+ reference_covered = image_utils.resize_image(reference.mask.astype(np.float32), width, height) > 0.5
507
+ if total_field is not None:
508
+ # Pre-warp the reference with the coarser estimate, so this level only measures what is left.
509
+ grid_x, grid_y = np.meshgrid(np.arange(width) + 0.5, np.arange(height) + 0.5)
510
+ full_x, full_y = grid_x.ravel() / scale, grid_y.ravel() / scale
511
+ shift = _sample_field(total_field, total_rows, total_columns, full_x * total_scale,
512
+ full_y * total_scale) / total_scale
513
+ sample_x, sample_y = full_x + shift[:, 0], full_y + shift[:, 1]
514
+ reference_rgb = image_utils.sample_bilinear(reference.pixels[:, :, :3], sample_x, sample_y)\
515
+ .reshape(height, width, 3)
516
+ reference_covered = image_utils.sample_nearest(reference.mask, sample_x, sample_y).reshape(height, width)
517
+ maximum_shift = maximum_shift_fraction * subject_long_side * scale
518
+ residual, rows, columns, used = _estimate_level(_structure(source_rgb), source_covered,
519
+ _structure(reference_rgb), reference_covered, maximum_shift,
520
+ CONTROL_SPACING_FRACTION * subject_long_side * scale)
521
+ patches_used = used
522
+ if total_field is None:
523
+ total_field, total_rows, total_columns, total_scale = residual, rows, columns, scale
524
+ continue
525
+ # Combine: resample the coarse field onto this level's grid (in this level's pixels) and add the residual.
526
+ grid_x, grid_y = np.meshgrid(columns.astype(np.float64), rows.astype(np.float64))
527
+ coarse = _sample_field(total_field, total_rows, total_columns, grid_x.ravel() / scale * total_scale,
528
+ grid_y.ravel() / scale * total_scale).reshape(residual.shape) / total_scale * scale
529
+ total_field, total_rows, total_columns, total_scale = coarse + residual, rows, columns, scale
530
+
531
+ if total_field is None or patches_used == 0:
532
+ return None
533
+ limit = maximum_shift_fraction * subject_long_side * total_scale
534
+ magnitude = np.linalg.norm(total_field, axis=-1, keepdims=True)
535
+ total_field = total_field * np.minimum(1.0, limit / np.maximum(magnitude, 1e-9))
536
+ full_resolution = (total_field / total_scale).astype(np.float32)
537
+ shift_lengths = np.linalg.norm(full_resolution, axis=-1)
538
+ return WarpField(
539
+ displacement=full_resolution,
540
+ origin=(float(total_columns[0]) / total_scale, float(total_rows[0]) / total_scale),
541
+ step=PATCH_STEP / total_scale,
542
+ patches_used=patches_used,
543
+ median_shift=float(np.median(shift_lengths)),
544
+ maximum_shift=float(shift_lengths.max()),
545
+ )
546
+
547
+
548
+ def warp_preview(reference, triangles, color: np.ndarray, long_side: int = 1024) -> np.ndarray:
549
+ """
550
+ Side-by-side check image: the source render, the reference as fitted, and the reference after warping.
551
+
552
+ :param reference: A reference (its warp may be None).
553
+ :param triangles: TriangleSet of the final mesh with the working UV layer.
554
+ :param color: float32 (size, size, 4) baked source color.
555
+ :param long_side: Width of each panel's longer side.
556
+ :returns: float32 (height, width * 3 + gaps, 4) image, bottom-up.
557
+ """
558
+ view = render_source_view(reference, triangles, color, long_side)
559
+ source_rgb, scale = view.rgb, view.scale
560
+ height, width = source_rgb.shape[:2]
561
+ grid_x, grid_y = np.meshgrid(np.arange(width) + 0.5, np.arange(height) + 0.5)
562
+ full_x, full_y = grid_x.ravel() / scale, grid_y.ravel() / scale
563
+ fitted = image_utils.sample_bilinear(reference.pixels[:, :, :3], full_x, full_y).reshape(height, width, 3)
564
+ warped = fitted
565
+ if reference.warp is not None:
566
+ shift = reference.warp.displacement_at(full_x, full_y)
567
+ warped = image_utils.sample_bilinear(reference.pixels[:, :, :3], full_x + shift[:, 0], full_y + shift[:, 1])\
568
+ .reshape(height, width, 3)
569
+ gap = np.ones((height, 8, 3), dtype=np.float32)
570
+ panels = np.concatenate((source_rgb, gap, fitted, gap, warped), axis=1)
571
+ return np.concatenate((panels, np.ones(panels.shape[:2] + (1,), dtype=np.float32)), axis=2)