@babylonjs-toolkit/agent 1.2.15 → 1.2.18

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 (58) hide show
  1. package/README.md +8 -2
  2. package/lib/diskinfo/cli.js +40 -6
  3. package/lib/diskinfo/report.js +28 -15
  4. package/package.json +1 -1
  5. package/skills/bt-blender/SKILL.md +386 -0
  6. package/skills/bt-blender/THIRD_PARTY_NOTICES.md +141 -0
  7. package/skills/bt-blender/references/art-style-and-genre.md +173 -0
  8. package/skills/bt-blender/references/characters-and-creatures.md +644 -0
  9. package/skills/bt-blender/references/environments.md +478 -0
  10. package/skills/bt-blender/references/game-engine-export.md +284 -0
  11. package/skills/bt-blender/references/geometry-nodes.md +447 -0
  12. package/skills/bt-blender/references/hard-surface.md +720 -0
  13. package/skills/bt-blender/references/procedural-generation.md +358 -0
  14. package/skills/bt-blender/references/rigging-and-animation.md +1080 -0
  15. package/skills/bt-blender/references/sculpting-and-retopology.md +544 -0
  16. package/skills/bt-blender/references/uv-and-pbr-materials.md +381 -0
  17. package/skills/bt-blender/references/vehicles.md +632 -0
  18. package/skills/bt-blender/scripts/blender/assembly_check.py +420 -0
  19. package/skills/bt-blender/scripts/blender/character_blockout.py +462 -0
  20. package/skills/bt-blender/scripts/blender/construction_kit.py +1710 -0
  21. package/skills/bt-blender/scripts/blender/environment_kit.py +525 -0
  22. package/skills/bt-blender/scripts/blender/export_asset.py +623 -0
  23. package/skills/bt-blender/scripts/blender/geometry_nodes_builders.py +575 -0
  24. package/skills/bt-blender/scripts/blender/hard_surface_panels.py +374 -0
  25. package/skills/bt-blender/scripts/blender/hard_surface_trims.py +200 -0
  26. package/skills/bt-blender/scripts/blender/image_measure.py +568 -0
  27. package/skills/bt-blender/scripts/blender/materials_pbr.py +439 -0
  28. package/skills/bt-blender/scripts/blender/measure_stations.py +486 -0
  29. package/skills/bt-blender/scripts/blender/ortho_views.py +309 -0
  30. package/skills/bt-blender/scripts/blender/procedural_game_ready.py +258 -0
  31. package/skills/bt-blender/scripts/blender/procedural_generators.py +842 -0
  32. package/skills/bt-blender/scripts/blender/qa_check.py +729 -0
  33. package/skills/bt-blender/scripts/blender/retopology_tools.py +781 -0
  34. package/skills/bt-blender/scripts/blender/review_render.py +358 -0
  35. package/skills/bt-blender/scripts/blender/rigging_tools.py +1170 -0
  36. package/skills/bt-blender/scripts/blender/style_palette.py +190 -0
  37. package/skills/bt-blender/scripts/blender/tool_common.py +289 -0
  38. package/skills/bt-blender/scripts/blender/uv_layout.py +555 -0
  39. package/skills/bt-blender/scripts/blender/vehicle_parts.py +370 -0
  40. package/skills/bt-blender/scripts/blender/view_consistency.py +133 -0
  41. package/skills/bt-blender/scripts/blender/world_gate.py +219 -0
  42. package/skills/bt-blender/scripts/bt-blender.mjs +329 -0
  43. package/skills/bt-blender/scripts/validate_gltf.mjs +204 -0
  44. package/skills/bt-gauntlet/SKILL.md +6 -6
  45. package/skills/bt-gauntlet/references/critic-rubrics.md +71 -4
  46. package/skills/bt-gauntlet/references/spec-composition.md +13 -0
  47. package/skills/bt-gauntlet/references/unity-pipeline.md +18 -2
  48. package/skills/bt-unwrap/scripts/blender/__pycache__/bt_unwrap.cpython-313.pyc +0 -0
  49. package/skills/bt-unwrap/scripts/blender/__pycache__/image_utils.cpython-313.pyc +0 -0
  50. package/skills/bt-unwrap/scripts/blender/__pycache__/mesh_tools.cpython-313.pyc +0 -0
  51. package/skills/bt-unwrap/scripts/blender/__pycache__/model_io.cpython-313.pyc +0 -0
  52. package/skills/bt-unwrap/scripts/blender/__pycache__/previews.cpython-313.pyc +0 -0
  53. package/skills/bt-unwrap/scripts/blender/__pycache__/rasterizer.cpython-313.pyc +0 -0
  54. package/skills/bt-unwrap/scripts/blender/__pycache__/reference_views.cpython-313.pyc +0 -0
  55. package/skills/bt-unwrap/scripts/blender/__pycache__/reference_warp.cpython-313.pyc +0 -0
  56. package/skills/bt-unwrap/scripts/blender/__pycache__/texture_bake.cpython-313.pyc +0 -0
  57. package/skills/bt-unwrap/scripts/blender/__pycache__/texture_compose.cpython-313.pyc +0 -0
  58. package/skills/bt-unwrap/scripts/blender/__pycache__/uv_layout.cpython-313.pyc +0 -0
@@ -0,0 +1,781 @@
1
+ """
2
+ bt-blender retopology tools: headless remeshing, retopology and the topology measurements that tell a
3
+ deforming game mesh from a sculpt. Import from a build script run with `bt-blender.mjs run`:
4
+
5
+ import retopology_tools as retopo
6
+ retopo.voxel_remesh(sculpt, voxel_size=0.012) # fuse parts, even density, manifold
7
+ report = retopo.quadriflow(sculpt, target_triangles=4800) # quads to a triangle budget
8
+ retopo.shrinkwrap_fit(cage, sculpt, offset=0.001) # hand-built cage onto a high poly
9
+ print(retopo.topology_report(cage, joints=[(0.2, 0, 1.1)])) # poles, ngons, manifold, poles at joints
10
+
11
+ Everything works on data or with a full context override; every operator's return value is checked.
12
+ Lengths are metres.
13
+ """
14
+ import math
15
+
16
+ import bmesh
17
+ import bpy
18
+ import numpy as np
19
+ from mathutils import Matrix, Vector
20
+ from mathutils.kdtree import KDTree
21
+
22
+ # QuadriFlow is approximate: it lands within about 10 % of the asked quad count. Asking this share of the
23
+ # budget leaves room, and quadriflow() retries lower when the result is still over.
24
+ QUADRIFLOW_BUDGET_SHARE = 0.92
25
+ QUADRIFLOW_RETRIES = 4
26
+ QUADRIFLOW_RETRY_SHRINK = 0.9
27
+
28
+ # A vertex counts as a pole when its valence is not 4 (interior vertices only).
29
+ REGULAR_VALENCE = 4
30
+
31
+ # Edges shorter than this (metres) are degenerate; QuadriFlow refuses meshes that have them.
32
+ DEGENERATE_EDGE_LENGTH = 1e-4
33
+
34
+ # QuadriFlow refuses edges under 1e-4 (in object units) as degenerate, so a small part (a 17 cm figure with
35
+ # a 1 mm voxel remesh, Blender 5.3.0) is CANCELLED as "not manifold". quadriflow() solves such meshes at
36
+ # this size (largest dimension, metres) and scales the result back.
37
+ QUADRIFLOW_SOLVE_SIZE = 2.0
38
+
39
+ # QuadriFlow's symmetry mode leaves the two halves unwelded on the mirror plane (Blender 5.3.0: 144 open
40
+ # edges on a character, seam vertices up to 2.7 mm off the plane at the 2 m solve size). Open-edge vertices
41
+ # this close to the plane (metres, at the solve size) are snapped onto it and welded afterwards.
42
+ MIRROR_SEAM_DISTANCE = 0.01
43
+ SEAM_WELD_DISTANCE = 1e-5
44
+
45
+
46
+ def _override(obj: bpy.types.Object) -> dict:
47
+ """A full single-object context override (a partial one cancels some operators quietly)."""
48
+ return {"object": obj, "active_object": obj, "selected_objects": [obj], "selected_editable_objects": [obj]}
49
+
50
+
51
+ def _make_active(obj: bpy.types.Object) -> None:
52
+ """
53
+ Selects only `obj` and makes it active; some operators read the view layer, not the override. The view
54
+ layer is updated first, because objects a script just linked are not in view_layer.objects until then.
55
+ """
56
+ bpy.context.view_layer.update()
57
+ for other in bpy.context.view_layer.objects:
58
+ other.select_set(other == obj)
59
+ bpy.context.view_layer.objects.active = obj
60
+
61
+
62
+ def _run(operator, obj: bpy.types.Object, **settings) -> None:
63
+ """Runs an object operator on `obj` and raises when it does not finish (operators never raise)."""
64
+ _make_active(obj)
65
+ with bpy.context.temp_override(**_override(obj)):
66
+ outcome = operator(**settings)
67
+ if "FINISHED" not in outcome:
68
+ raise RuntimeError(f"{operator.idname()} returned {outcome} on {obj.name}")
69
+
70
+
71
+ def triangle_count(obj: bpy.types.Object) -> int:
72
+ """Triangles the mesh exports as (each n-gon counts n - 2)."""
73
+ return sum(len(polygon.vertices) - 2 for polygon in obj.data.polygons)
74
+
75
+
76
+ def manifold_report(obj: bpy.types.Object) -> dict:
77
+ """
78
+ What QuadriFlow, booleans and bone-heat weighting need from a mesh: every edge shared by exactly two
79
+ faces with consistent winding, no wire edges, no degenerate edges.
80
+
81
+ :returns: {"non_manifold_edges", "boundary_edges", "wire_edges", "degenerate_edges", "inconsistent_edges",
82
+ "manifold"}.
83
+ """
84
+ edit_mesh = bmesh.new()
85
+ edit_mesh.from_mesh(obj.data)
86
+ boundary = sum(1 for edge in edit_mesh.edges if edge.is_boundary)
87
+ wire = sum(1 for edge in edit_mesh.edges if edge.is_wire)
88
+ over_shared = sum(1 for edge in edit_mesh.edges if len(edge.link_faces) > 2)
89
+ degenerate = sum(1 for edge in edit_mesh.edges if edge.calc_length() < DEGENERATE_EDGE_LENGTH)
90
+ inconsistent = sum(1 for edge in edit_mesh.edges if len(edge.link_faces) == 2 and not edge.is_contiguous)
91
+ edit_mesh.free()
92
+ return {"non_manifold_edges": boundary + wire + over_shared, "boundary_edges": boundary, "wire_edges": wire,
93
+ "degenerate_edges": degenerate, "inconsistent_edges": inconsistent,
94
+ "manifold": boundary + wire + over_shared + inconsistent == 0}
95
+
96
+
97
+ def voxel_remesh(obj: bpy.types.Object, voxel_size: float, fix_poles: bool = True,
98
+ preserve_volume: bool = True) -> dict:
99
+ """
100
+ Rebuilds the surface on a voxel grid: fuses intersecting parts into one closed, manifold shell with
101
+ even quads. It destroys UVs, vertex groups, shape keys and multires levels, so do it before any of
102
+ those exist. Voxel size sets the smallest detail that survives (about 2 voxels).
103
+
104
+ :param obj: Mesh object (modifiers are ignored: apply them first).
105
+ :param voxel_size: Grid size in metres (1/150 to 1/250 of the height for a character base).
106
+ :param fix_poles: Fewer poles, better flow (needs adaptivity 0, which is used here).
107
+ :param preserve_volume: Re-project onto the original so thin parts keep their size.
108
+ :returns: {"vertices", "triangles", "manifold"}.
109
+ :raises ValueError: for a non-positive voxel size.
110
+ """
111
+ if voxel_size <= 0:
112
+ raise ValueError("voxel_size must be positive")
113
+ mesh = obj.data
114
+ mesh.remesh_voxel_size = voxel_size
115
+ mesh.remesh_voxel_adaptivity = 0.0
116
+ mesh.use_remesh_fix_poles = fix_poles
117
+ mesh.use_remesh_preserve_volume = preserve_volume
118
+ _run(bpy.ops.object.voxel_remesh, obj)
119
+ return {"vertices": len(obj.data.vertices), "triangles": triangle_count(obj),
120
+ "manifold": manifold_report(obj)["manifold"]}
121
+
122
+
123
+ def quadriflow(obj: bpy.types.Object, target_triangles: int, symmetry_axes: tuple = (), seed: int = 0,
124
+ preserve_sharp: bool = False, smooth_normals: bool = True) -> dict:
125
+ """
126
+ QuadriFlow quad remesh to a triangle budget. QuadriFlow is approximate, so the request is made under
127
+ budget and repeated lower until the result fits. Needs a manifold, consistently wound input with no
128
+ degenerate edges: run voxel_remesh first (it also removes intersections, which QuadriFlow does not).
129
+
130
+ Headless, give the face count: the RATIO / EDGE modes are converted to a face count only by the
131
+ operator's UI pop-up.
132
+
133
+ :param obj: Mesh object (no Multires modifier, Object Mode).
134
+ :param target_triangles: The budget; the result is at or under it (quads count as 2 triangles).
135
+ :param symmetry_axes: e.g. ("X",): remesh one half and mirror it (the mesh must be symmetric about the
136
+ object's origin plane).
137
+ :param seed: Layout seed; another seed gives another quad layout.
138
+ :param preserve_sharp: Keep edges marked sharp.
139
+ :param smooth_normals: Smooth-shade the result.
140
+ :returns: {"triangles", "quads", "other_faces", "attempts", "seed", "manifold", "symmetric",
141
+ "solved_at_scale"}; "symmetric" is False when the mirrored solve never welded and the whole mesh
142
+ was solved instead.
143
+ :raises RuntimeError: when the input is not manifold, or every attempt fails, stays over budget or
144
+ leaves an open seam (a non-manifold result is retried with the next seed).
145
+ """
146
+ check = manifold_report(obj)
147
+ if check["non_manifold_edges"] or check["inconsistent_edges"]:
148
+ raise RuntimeError(f"QuadriFlow needs a manifold mesh; voxel_remesh first: {check}")
149
+ solve_scale = _solver_scale(obj)
150
+ if solve_scale != 1.0:
151
+ obj.data.transform(Matrix.Scale(solve_scale, 4))
152
+ try:
153
+ try:
154
+ result = _quadriflow_to_budget(obj, target_triangles, symmetry_axes, seed, preserve_sharp, smooth_normals)
155
+ result["symmetric"] = bool(symmetry_axes)
156
+ except RuntimeError:
157
+ if not symmetry_axes:
158
+ raise
159
+ # Some shapes (a seam running along a thin crest or a pinch on the mirror plane) never weld:
160
+ # solve the whole mesh instead. The topology is then only approximately mirrored.
161
+ result = _quadriflow_to_budget(obj, target_triangles, (), seed, preserve_sharp, smooth_normals)
162
+ result["symmetric"] = False
163
+ finally:
164
+ if solve_scale != 1.0:
165
+ obj.data.transform(Matrix.Scale(1.0 / solve_scale, 4))
166
+ obj.data.update()
167
+ result["solved_at_scale"] = round(solve_scale, 4)
168
+ return result
169
+
170
+
171
+ def _solver_scale(obj: bpy.types.Object) -> float:
172
+ """Scale that brings a small mesh to QUADRIFLOW_SOLVE_SIZE (1.0 when it is already that large)."""
173
+ coordinates = np.empty(len(obj.data.vertices) * 3)
174
+ obj.data.vertices.foreach_get("co", coordinates)
175
+ size = float(np.ptp(coordinates.reshape(-1, 3), axis=0).max()) if len(coordinates) else 0.0
176
+ return QUADRIFLOW_SOLVE_SIZE / size if 0.0 < size < QUADRIFLOW_SOLVE_SIZE else 1.0
177
+
178
+
179
+ def _quadriflow_to_budget(obj: bpy.types.Object, target_triangles: int, symmetry_axes: tuple, seed: int,
180
+ preserve_sharp: bool, smooth_normals: bool) -> dict:
181
+ """Runs QuadriFlow, retrying with fewer faces until the result is within the triangle budget."""
182
+ mesh = obj.data
183
+ for axis in "XYZ":
184
+ setattr(mesh, f"use_mirror_{axis.lower()}", axis in symmetry_axes)
185
+ source = mesh.copy()
186
+ request = int(target_triangles / 2 * QUADRIFLOW_BUDGET_SHARE)
187
+ attempt_seed = seed
188
+ for attempt in range(1, QUADRIFLOW_RETRIES + 1):
189
+ _run(bpy.ops.object.quadriflow_remesh, obj, target_faces=request, mode="FACES",
190
+ use_mesh_symmetry=bool(symmetry_axes), use_preserve_sharp=preserve_sharp,
191
+ use_preserve_boundary=False, smooth_normals=smooth_normals, seed=attempt_seed)
192
+ if symmetry_axes:
193
+ _weld_mirror_seam(obj, symmetry_axes)
194
+ triangles = triangle_count(obj)
195
+ manifold = manifold_report(obj)["manifold"]
196
+ if triangles <= target_triangles and manifold:
197
+ bpy.data.meshes.remove(source)
198
+ quads = sum(1 for polygon in obj.data.polygons if len(polygon.vertices) == REGULAR_VALENCE)
199
+ return {"triangles": triangles, "quads": quads, "other_faces": len(obj.data.polygons) - quads,
200
+ "attempts": attempt, "seed": attempt_seed, "manifold": manifold}
201
+ old_mesh = obj.data
202
+ obj.data = source.copy()
203
+ bpy.data.meshes.remove(old_mesh)
204
+ if triangles > target_triangles:
205
+ request = int(request * QUADRIFLOW_RETRY_SHRINK)
206
+ else:
207
+ attempt_seed += 1 # a different quad layout usually welds cleanly
208
+ bpy.data.meshes.remove(source)
209
+ raise RuntimeError(f"QuadriFlow gave no manifold result within {target_triangles} triangles "
210
+ f"after {QUADRIFLOW_RETRIES} attempts")
211
+
212
+
213
+ def _weld_mirror_seam(obj: bpy.types.Object, axes: tuple) -> int:
214
+ """
215
+ QuadriFlow's symmetric mode mirrors one solved half but leaves the two halves unwelded along the plane
216
+ (144 open edges on a biped, the partners up to 2.7 mm apart at the 2 m solve size). The open-edge
217
+ vertices near the plane are snapped onto it and merged with their partners. Only open-edge vertices
218
+ move: snapping interior vertices that happen to lie near the plane fuses unrelated edges (4-face edges).
219
+
220
+ :returns: How many vertices merged.
221
+ """
222
+ edit_mesh = bmesh.new()
223
+ edit_mesh.from_mesh(obj.data)
224
+ axis_indices = ["XYZ".index(axis) for axis in axes]
225
+ open_vertices = {vertex for edge in edit_mesh.edges if edge.is_boundary for vertex in edge.verts}
226
+ on_plane = []
227
+ for vertex in open_vertices:
228
+ for index in axis_indices:
229
+ if abs(vertex.co[index]) <= MIRROR_SEAM_DISTANCE:
230
+ vertex.co[index] = 0.0
231
+ on_plane.append(vertex)
232
+ before = len(edit_mesh.verts)
233
+ # Every vertex takes part: QuadriFlow also leaves the odd coincident pair on the plane away from the seam.
234
+ bmesh.ops.remove_doubles(edit_mesh, verts=edit_mesh.verts[:], dist=SEAM_WELD_DISTANCE)
235
+ merged = before - len(edit_mesh.verts)
236
+ edit_mesh.to_mesh(obj.data)
237
+ edit_mesh.free()
238
+ return merged
239
+
240
+
241
+ def decimate_to(obj: bpy.types.Object, target_triangles: int, symmetry_axis: str = None) -> dict:
242
+ """
243
+ Collapse-decimates a mesh to a triangle budget (LODs, bake sources, static props). It keeps UVs and
244
+ the silhouette but gives triangles with no edge flow: never use it as the topology of a deforming mesh.
245
+
246
+ :param obj: Mesh object.
247
+ :param target_triangles: Budget; the ratio is computed from the current triangle count.
248
+ :param symmetry_axis: "X", "Y" or "Z" to keep the result symmetric.
249
+ :returns: {"before", "after"} triangle counts.
250
+ """
251
+ before = triangle_count(obj)
252
+ modifier = obj.modifiers.new("Decimate", "DECIMATE")
253
+ modifier.decimate_type = "COLLAPSE"
254
+ modifier.ratio = min(1.0, target_triangles / max(before, 1))
255
+ modifier.use_collapse_triangulate = True
256
+ if symmetry_axis:
257
+ modifier.use_symmetry = True
258
+ modifier.symmetry_axis = symmetry_axis
259
+ _apply_modifier(obj, modifier.name)
260
+ return {"before": before, "after": triangle_count(obj)}
261
+
262
+
263
+ def _apply_modifier(obj: bpy.types.Object, name: str) -> None:
264
+ """Applies one modifier by name with a full override, raising when it is cancelled."""
265
+ _run(bpy.ops.object.modifier_apply, obj, modifier=name)
266
+
267
+
268
+ def shrinkwrap_fit(low: bpy.types.Object, high: bpy.types.Object, offset: float = 0.0,
269
+ method: str = "NEAREST_SURFACEPOINT", wrap_mode: str = "OUTSIDE_SURFACE",
270
+ vertex_group: str = None, apply: bool = True) -> bpy.types.ShrinkwrapModifier:
271
+ """
272
+ Projects a hand-built low-poly cage (a loft, a skin cage, an edited QuadriFlow result) onto the high
273
+ poly: the headless form of retopology by snapping to the surface. The cage keeps its edge loops; only
274
+ the vertex positions move onto the high poly's surface.
275
+
276
+ :param low: The retopology mesh (its loops are what you designed).
277
+ :param high: The sculpt / high poly to fit.
278
+ :param offset: Distance kept outside the surface, metres (a little helps a bake cage).
279
+ :param method: NEAREST_SURFACEPOINT (default, retopo), TARGET_PROJECT (smoother, slower), PROJECT,
280
+ NEAREST_VERTEX.
281
+ :param wrap_mode: OUTSIDE_SURFACE keeps the offset outward; ON_SURFACE, ABOVE_SURFACE also work.
282
+ :param vertex_group: Only move this group's vertices (keep a seam ring or an eye rim fixed).
283
+ :param apply: Bake the result into the mesh.
284
+ :returns: The modifier (already applied when apply=True, then no longer on the object).
285
+ """
286
+ modifier = low.modifiers.new("Shrinkwrap", "SHRINKWRAP")
287
+ modifier.target = high
288
+ modifier.wrap_method = method
289
+ if method != "NEAREST_VERTEX":
290
+ modifier.wrap_mode = wrap_mode
291
+ modifier.offset = offset
292
+ if vertex_group:
293
+ modifier.vertex_group = vertex_group
294
+ if apply:
295
+ _apply_modifier(low, modifier.name)
296
+ return modifier
297
+
298
+
299
+ def relax(obj: bpy.types.Object, iterations: int = 5, factor: float = 0.5, keep_on: bpy.types.Object = None) -> None:
300
+ """
301
+ Evens out the spacing of a retopology mesh (Laplacian smoothing of positions), then snaps it back onto
302
+ `keep_on` so relaxing never shrinks the form. Run it after a shrinkwrap pass that bunched vertices.
303
+
304
+ :param obj: Mesh object.
305
+ :param iterations: Smoothing passes.
306
+ :param factor: 0..1 per pass.
307
+ :param keep_on: The high poly to re-project onto (None: plain smoothing, which shrinks convex forms).
308
+ """
309
+ edit_mesh = bmesh.new()
310
+ edit_mesh.from_mesh(obj.data)
311
+ for _ in range(iterations):
312
+ bmesh.ops.smooth_vert(edit_mesh, verts=[vertex for vertex in edit_mesh.verts if not vertex.is_boundary],
313
+ factor=factor, use_axis_x=True, use_axis_y=True, use_axis_z=True)
314
+ edit_mesh.to_mesh(obj.data)
315
+ edit_mesh.free()
316
+ if keep_on is not None:
317
+ shrinkwrap_fit(obj, keep_on, method="NEAREST_SURFACEPOINT", wrap_mode="ON_SURFACE")
318
+
319
+
320
+ # --- headless detail: multires levels, displacement maps ------------------------------------------------------
321
+
322
+ def multires_subdivide(obj: bpy.types.Object, levels: int, mode: str = "CATMULL_CLARK") -> int:
323
+ """
324
+ Adds a Multires modifier and subdivides it `levels` times. Sculpt-mode brushes do not run headless, so
325
+ the top level is filled by multires_reshape from a displaced copy instead of by strokes.
326
+
327
+ :param obj: Mesh object (closed, all quads is best: every level multiplies the faces by 4).
328
+ :param levels: Subdivision levels to add (3 turns a 5k-triangle base into about 320k).
329
+ :param mode: "CATMULL_CLARK" (smooth), "SIMPLE" (keeps the shape) or "LINEAR".
330
+ :returns: The modifier's total levels.
331
+ :raises RuntimeError: when a subdivide step does not finish.
332
+ """
333
+ modifier = obj.modifiers.get("Multires") or obj.modifiers.new("Multires", "MULTIRES")
334
+ for _ in range(levels):
335
+ _run(bpy.ops.object.multires_subdivide, obj, modifier=modifier.name, mode=mode)
336
+ return modifier.total_levels
337
+
338
+
339
+ def multires_reshape(obj: bpy.types.Object, shaped: bpy.types.Object) -> None:
340
+ """
341
+ Copies the vertex positions of `shaped` into the top level of `obj`'s Multires modifier. `shaped` must
342
+ have exactly the top level's topology: make it from a copy of `obj` with a Subdivision modifier of the
343
+ same levels applied, then displace it.
344
+
345
+ :raises RuntimeError: when the reshape does not finish (different topology is the usual cause).
346
+ """
347
+ _make_active(obj)
348
+ shaped.select_set(True)
349
+ override = {"object": obj, "active_object": obj, "selected_objects": [obj, shaped],
350
+ "selected_editable_objects": [obj, shaped]}
351
+ with bpy.context.temp_override(**override):
352
+ outcome = bpy.ops.object.multires_reshape(modifier=obj.modifiers["Multires"].name)
353
+ if "FINISHED" not in outcome:
354
+ raise RuntimeError(f"multires_reshape returned {outcome}: is {shaped.name} the top level's topology?")
355
+
356
+
357
+ def height_image(name: str, heights: np.ndarray) -> bpy.types.Image:
358
+ """
359
+ A float, Non-Color image from a (rows, columns) array of heights in 0..1 (0.5 is no displacement with
360
+ the Displace modifier's default mid level). Row 0 is the bottom of the image (V = 0).
361
+ """
362
+ rows, columns = heights.shape
363
+ image = bpy.data.images.new(name, columns, rows, float_buffer=True)
364
+ image.colorspace_settings.name = "Non-Color"
365
+ pixels = np.dstack([heights, heights, heights, np.ones_like(heights)]).astype(np.float32)
366
+ image.pixels.foreach_set(pixels.ravel())
367
+ return image
368
+
369
+
370
+ def displace(obj: bpy.types.Object, texture: bpy.types.Texture, strength: float, coordinates: str = "UV",
371
+ vertex_group: str = None, mid_level: float = 0.5) -> bpy.types.Modifier:
372
+ """
373
+ Adds a Displace modifier along the normals: a procedural texture with LOCAL coordinates, or an image on
374
+ UVs. A vertex group limits it to a region (the headless stand-in for a masked brush stroke).
375
+
376
+ :param obj: Dense mesh object.
377
+ :param texture: bpy.data.textures entry (VORONOI, CLOUDS, MUSGRAVE-like noise, or IMAGE).
378
+ :param strength: Metres at full texture value.
379
+ :param coordinates: "UV", "LOCAL", "GLOBAL" or "OBJECT".
380
+ :param vertex_group: Mask group name, or None for the whole mesh.
381
+ :param mid_level: Texture value that leaves the surface where it is.
382
+ :returns: The modifier (apply it with construction_kit.apply_modifiers).
383
+ """
384
+ modifier = obj.modifiers.new(texture.name, "DISPLACE")
385
+ modifier.texture = texture
386
+ modifier.texture_coords = coordinates
387
+ modifier.strength = strength
388
+ modifier.mid_level = mid_level
389
+ if vertex_group:
390
+ modifier.vertex_group = vertex_group
391
+ return modifier
392
+
393
+
394
+ def _distances_to(points: np.ndarray, target: bpy.types.Object) -> np.ndarray:
395
+ """Distance (metres) from world-space points to the evaluated surface of an object."""
396
+ from mathutils.bvhtree import BVHTree
397
+
398
+ tree = BVHTree.FromObject(target, bpy.context.evaluated_depsgraph_get())
399
+ to_local = target.matrix_world.inverted()
400
+ scale = max(target.matrix_world.to_scale())
401
+ distances = []
402
+ for point in points:
403
+ nearest = tree.find_nearest(to_local @ Vector(point))
404
+ distances.append(nearest[3] * scale if nearest[0] is not None else math.inf)
405
+ return np.array(distances)
406
+
407
+
408
+ def _world_points(obj: bpy.types.Object, limit: int) -> np.ndarray:
409
+ """Up to `limit` evaluated world-space vertices of an object, evenly subsampled."""
410
+ import construction_kit
411
+
412
+ points = construction_kit.world_vertices(obj)
413
+ step = max(1, len(points) // limit)
414
+ return points[::step]
415
+
416
+
417
+ def surface_deviation(low: bpy.types.Object, high: bpy.types.Object, sample_limit: int = 20000) -> dict:
418
+ """
419
+ How closely a low poly follows a high poly, both ways (world space, metres):
420
+ - low to high: how far the low poly's vertices sit off the high surface (0 after a shrinkwrap);
421
+ - high to low: how far the high surface sits from the low poly, the silhouette and volume a bake has to
422
+ cover. The cage extrusion must exceed the high-to-low maximum.
423
+
424
+ :param low: Retopology mesh.
425
+ :param high: Sculpt / high poly.
426
+ :param sample_limit: Most vertices sampled on each side.
427
+ :returns: {"low_to_high": {"mean_m", "p95_m", "max_m"}, "high_to_low": {...}}.
428
+ """
429
+ def summary(values: np.ndarray) -> dict:
430
+ return {"mean_m": round(float(values.mean()), 6), "p95_m": round(float(np.percentile(values, 95)), 6),
431
+ "max_m": round(float(values.max()), 6)}
432
+
433
+ return {"low_to_high": summary(_distances_to(_world_points(low, sample_limit), high)),
434
+ "high_to_low": summary(_distances_to(_world_points(high, sample_limit), low))}
435
+
436
+
437
+ def topology_report(obj: bpy.types.Object, joints: list = (), joint_radius: float = 0.04) -> dict:
438
+ """
439
+ The topology numbers a character mesh is reviewed on: face types, poles (interior vertices whose
440
+ valence is not 4), manifold state, and poles that sit inside a deformation zone (within
441
+ `joint_radius` of a joint pivot), where they pinch when the joint bends.
442
+
443
+ :param obj: Mesh object.
444
+ :param joints: World-space joint pivots to keep poles away from (elbows, knees, shoulders, hips).
445
+ :param joint_radius: Radius of each deformation zone, metres.
446
+ :returns: {"triangles", "quads", "tris", "ngons", "poles", "poles_by_valence", "poles_at_joints",
447
+ "manifold", "non_manifold_edges"}.
448
+ """
449
+ edit_mesh = bmesh.new()
450
+ edit_mesh.from_mesh(obj.data)
451
+ edit_mesh.transform(obj.matrix_world)
452
+ sides = [len(face.verts) for face in edit_mesh.faces]
453
+ poles, by_valence = [], {}
454
+ for vertex in edit_mesh.verts:
455
+ if vertex.is_boundary or vertex.is_wire:
456
+ continue
457
+ valence = len(vertex.link_edges)
458
+ if valence != REGULAR_VALENCE:
459
+ poles.append(vertex.co.copy())
460
+ by_valence[valence] = by_valence.get(valence, 0) + 1
461
+ edit_mesh.free()
462
+ at_joints = 0
463
+ if poles and joints:
464
+ tree = KDTree(len(poles))
465
+ for index, position in enumerate(poles):
466
+ tree.insert(position, index)
467
+ tree.balance()
468
+ at_joints = len({index for joint in joints for _, index, _ in tree.find_range(joint, joint_radius)})
469
+ manifold = manifold_report(obj)
470
+ return {"triangles": triangle_count(obj), "quads": sides.count(4), "tris": sides.count(3),
471
+ "ngons": sum(1 for count in sides if count > 4), "poles": len(poles),
472
+ "poles_by_valence": dict(sorted(by_valence.items())), "poles_at_joints": at_joints,
473
+ "manifold": manifold["manifold"], "non_manifold_edges": manifold["non_manifold_edges"]}
474
+
475
+
476
+ # --- baking high to low ---------------------------------------------------------------------------------------
477
+
478
+ # Cycles samples for a geometry bake (normals and positions need one; AO needs many).
479
+ BAKE_SAMPLES = {"NORMAL": 1, "AO": 64}
480
+
481
+ # A correctly baked tangent-space normal map averages close to (0.5, 0.5, 1.0); blue below this means
482
+ # missed rays, flipped faces, or a map that is not a tangent-space normal map.
483
+ NORMAL_MAP_MIN_MEAN_BLUE = 0.78
484
+
485
+
486
+ def _bake_material(low: bpy.types.Object, image: bpy.types.Image) -> list:
487
+ """Puts the bake target image node, active, into every material slot of the low poly (adding one when
488
+ the low poly has none); returns the nodes added so they can be removed afterwards."""
489
+ if not low.data.materials:
490
+ low.data.materials.append(bpy.data.materials.new(low.name + "_Bake"))
491
+ added = []
492
+ for material in low.data.materials:
493
+ tree = material.node_tree
494
+ node = tree.nodes.new("ShaderNodeTexImage")
495
+ node.image = image
496
+ tree.nodes.active = node
497
+ added.append((tree, node))
498
+ return added
499
+
500
+
501
+ def bake_high_to_low(low: bpy.types.Object, high: bpy.types.Object, size: int = 1024, bake_type: str = "NORMAL",
502
+ cage_extrusion: float = 0.02, max_ray_distance: float = 0.04, margin: int = 16,
503
+ cage_object: bpy.types.Object = None) -> bpy.types.Image:
504
+ """
505
+ Bakes the high poly onto the low poly's active UV map with Cycles (selected-to-active): a tangent-space
506
+ normal map (OpenGL / +Y green, what glTF, BabylonJS and Unity read) or ambient occlusion. Rays start
507
+ `cage_extrusion` outside the low poly (or from `cage_object`, an inflated copy with the same topology)
508
+ and travel up to `max_ray_distance`. The default extrusion of 0 is a broken bake.
509
+
510
+ :param low: Low poly with non-overlapping UVs, scale applied.
511
+ :param high: High poly that the low poly encloses closely.
512
+ :param size: Square image size in pixels.
513
+ :param bake_type: "NORMAL" or "AO".
514
+ :param cage_extrusion: Metres; larger than the furthest the high poly stands out of the low.
515
+ :param max_ray_distance: Metres; about twice the extrusion.
516
+ :param margin: Padding in pixels (16 at 2K, 8 at 1K, 4 at 512).
517
+ :param cage_object: Optional cage mesh.
518
+ :returns: A float image holding the bake (save it, or convert it to 8-bit sRGB / keep Non-Color data).
519
+ :raises RuntimeError: when the bake does not finish.
520
+ """
521
+ scene = bpy.context.scene
522
+ scene.render.engine = "CYCLES"
523
+ scene.cycles.samples = BAKE_SAMPLES.get(bake_type, 16)
524
+ scene.cycles.device = "CPU"
525
+ image = bpy.data.images.new(f"{low.name}_{bake_type.lower()}", size, size, float_buffer=True)
526
+ image.colorspace_settings.name = "Non-Color"
527
+ added = _bake_material(low, image)
528
+ settings = {"type": bake_type, "use_selected_to_active": True, "cage_extrusion": cage_extrusion,
529
+ "max_ray_distance": max_ray_distance, "margin": margin, "margin_type": "ADJACENT_FACES",
530
+ "normal_space": "TANGENT", "normal_r": "POS_X", "normal_g": "POS_Y", "normal_b": "POS_Z",
531
+ "use_clear": True}
532
+ if cage_object is not None:
533
+ settings.update(use_cage=True, cage_object=cage_object.name)
534
+ bpy.context.view_layer.update()
535
+ for other in bpy.context.view_layer.objects:
536
+ other.select_set(other in (low, high))
537
+ bpy.context.view_layer.objects.active = low
538
+ with bpy.context.temp_override(object=low, active_object=low, selected_objects=[low, high],
539
+ selected_editable_objects=[low, high]):
540
+ outcome = bpy.ops.object.bake(**settings)
541
+ for tree, node in added:
542
+ tree.nodes.remove(node)
543
+ if "FINISHED" not in outcome:
544
+ raise RuntimeError(f"bake returned {outcome}")
545
+ return image
546
+
547
+
548
+ def _image_array(image: bpy.types.Image) -> np.ndarray:
549
+ """(height, width, 4) float array of an image, row 0 at the bottom (Blender's order)."""
550
+ pixels = np.empty(len(image.pixels), dtype=np.float32)
551
+ image.pixels.foreach_get(pixels)
552
+ return pixels.reshape(image.size[1], image.size[0], 4)
553
+
554
+
555
+ def normal_map_stats(image: bpy.types.Image, low: bpy.types.Object = None) -> dict:
556
+ """
557
+ Sanity numbers for a baked tangent-space normal map, over the texels inside the UV islands when `low`
558
+ is given (else the whole image): the mean colour (expect about 0.5, 0.5, 1.0) and the share of texels
559
+ whose blue is under 0.5 (rays that missed or hit back faces).
560
+
561
+ :returns: {"mean_rgb", "low_blue_share", "texels", "pass"}.
562
+ """
563
+ pixels = _image_array(image)
564
+ mask = np.ones(pixels.shape[:2], dtype=bool) if low is None else _uv_mask(low, pixels.shape[1], pixels.shape[0])
565
+ inside = pixels[mask][:, :3]
566
+ mean = inside.mean(axis=0)
567
+ low_blue = float((inside[:, 2] < 0.5).mean())
568
+ return {"mean_rgb": [round(float(value), 4) for value in mean], "low_blue_share": round(low_blue, 5),
569
+ "texels": int(mask.sum()), "pass": bool(mean[2] >= NORMAL_MAP_MIN_MEAN_BLUE and low_blue < 0.01)}
570
+
571
+
572
+ def _uv_mask(obj: bpy.types.Object, width: int, height: int) -> np.ndarray:
573
+ """Boolean (height, width) mask of the texels covered by the object's UV faces (row 0 at the bottom)."""
574
+ import image_measure
575
+
576
+ uv_loops = obj.data.uv_layers.active.data
577
+ mask = np.zeros((height, width), dtype=bool)
578
+ for polygon in obj.data.polygons:
579
+ points = np.array([tuple(uv_loops[index].uv) for index in polygon.loop_indices]) * (width, height)
580
+ mask |= image_measure.fill_polygon(height, width, points)
581
+ return mask
582
+
583
+
584
+ def _sample(pixels: np.ndarray, uv_point) -> np.ndarray:
585
+ """Bilinear sample of a (rows, columns, 4) image at a UV coordinate."""
586
+ height, width = pixels.shape[:2]
587
+ column, row = uv_point[0] * width - 0.5, uv_point[1] * height - 0.5
588
+ left, bottom_row = int(np.floor(column)), int(np.floor(row))
589
+ column_fraction, row_fraction = column - left, row - bottom_row
590
+ left, right = np.clip([left, left + 1], 0, width - 1)
591
+ bottom_row, top_row = np.clip([bottom_row, bottom_row + 1], 0, height - 1)
592
+ lower = pixels[bottom_row, left] * (1 - column_fraction) + pixels[bottom_row, right] * column_fraction
593
+ upper = pixels[top_row, left] * (1 - column_fraction) + pixels[top_row, right] * column_fraction
594
+ return lower * (1 - row_fraction) + upper * row_fraction
595
+
596
+
597
+ def _inside_polygon(point: np.ndarray, polygon: np.ndarray) -> bool:
598
+ """Even-odd test of a 2D point against a polygon (UV face)."""
599
+ inside = False
600
+ count = len(polygon)
601
+ for index in range(count):
602
+ (start_u, start_v), (end_u, end_v) = polygon[index], polygon[(index + 1) % count]
603
+ if (start_v > point[1]) != (end_v > point[1]):
604
+ crossing = start_u + (point[1] - start_v) * (end_u - start_u) / (end_v - start_v)
605
+ if point[0] < crossing:
606
+ inside = not inside
607
+ return inside
608
+
609
+
610
+ def normal_seam_report(low: bpy.types.Object, image: bpy.types.Image, high: bpy.types.Object,
611
+ inset_pixels: float = 2.0, limit_degrees: float = 5.0) -> dict:
612
+ """
613
+ Checks a tangent-space normal map along its UV seams, where bake and tangent errors show in an engine.
614
+ Along every UV seam edge (at a quarter, half and three quarters of its length) the map is sampled just
615
+ inside each of the two islands and decoded exactly as a shader does: through the MikkTSpace tangent
616
+ frame interpolated at that point (OpenGL, +Y green). Each decoded normal is compared with the high
617
+ poly's smooth normal where the bake ray from that point lands. A clean bake decodes to the high poly's
618
+ normal on both sides of every seam, so nothing shows; a wrong green channel, a different tangent basis,
619
+ missed rays or skew all show up as error. Samples that would land outside their own UV face (a sliver
620
+ thinner than the inset) are skipped.
621
+
622
+ Tangents come from Blender's MikkTSpace, the frame glTF asks for and Unity uses; ship them in the file
623
+ (export_tangents) for BabylonJS, which otherwise derives its own frame in the shader.
624
+
625
+ :param low: Low poly with the UV map the image was baked to (active).
626
+ :param image: The baked tangent-space normal map.
627
+ :param high: The high poly it was baked from.
628
+ :param inset_pixels: How far inside each island to sample.
629
+ :param limit_degrees: Errors above this count as visible.
630
+ :returns: {"seam_samples", "error_median_degrees", "error_p95_degrees", "error_over_limit_share"}.
631
+ """
632
+ mesh = low.data
633
+ mesh.calc_tangents(uvmap=mesh.uv_layers.active.name)
634
+ uv_loops = mesh.uv_layers.active.data
635
+ pixels = _image_array(image)
636
+ inset = inset_pixels / image.size[0]
637
+ truth = (_SmoothSurface(high), high.matrix_world.inverted() @ low.matrix_world,
638
+ (low.matrix_world.inverted() @ high.matrix_world).to_3x3())
639
+ corners_by_edge = {}
640
+ for polygon in mesh.polygons:
641
+ loops = list(polygon.loop_indices)
642
+ outline = np.array([tuple(uv_loops[index].uv) for index in loops])
643
+ for position, loop_index in enumerate(loops):
644
+ next_index = loops[(position + 1) % len(loops)]
645
+ key = tuple(sorted((mesh.loops[loop_index].vertex_index, mesh.loops[next_index].vertex_index)))
646
+ corners_by_edge.setdefault(key, []).append((loop_index, next_index, outline, loops))
647
+ errors = []
648
+ for corners in corners_by_edge.values():
649
+ if len(corners) != 2 or _shares_uvs(uv_loops, corners):
650
+ continue
651
+ for fraction in (0.25, 0.5, 0.75):
652
+ for corner in corners:
653
+ side = _seam_side_normal(mesh, uv_loops, pixels, corner, fraction, inset)
654
+ if side is not None:
655
+ decoded, point, ray = side
656
+ errors.append(_angle(decoded, _true_normal(truth, point, ray)))
657
+ mesh.free_tangents()
658
+ values = np.array(errors) if errors else np.zeros(1)
659
+ return {"seam_samples": len(errors), "error_median_degrees": round(float(np.median(values)), 3),
660
+ "error_p95_degrees": round(float(np.percentile(values, 95)), 3),
661
+ "error_over_limit_share": round(float((values > limit_degrees).mean()), 4)}
662
+
663
+
664
+ def _angle(first: np.ndarray, second: np.ndarray) -> float:
665
+ """Angle in degrees between two unit vectors."""
666
+ return math.degrees(math.acos(float(np.clip(np.dot(first, second), -1.0, 1.0))))
667
+
668
+
669
+ class _SmoothSurface:
670
+ """The high poly's evaluated triangles with their smooth (corner) normals, for ray casts that return the
671
+ interpolated normal a baker sees, not the flat facet normal."""
672
+
673
+ def __init__(self, obj: bpy.types.Object):
674
+ """Copies the evaluated mesh's triangles, positions and corner normals and builds a BVH over them."""
675
+ from mathutils.bvhtree import BVHTree
676
+
677
+ evaluated = obj.evaluated_get(bpy.context.evaluated_depsgraph_get())
678
+ mesh = evaluated.to_mesh()
679
+ try:
680
+ mesh.calc_loop_triangles()
681
+ self.positions = [vertex.co.copy() for vertex in mesh.vertices]
682
+ self.triangles = [tuple(triangle.vertices) for triangle in mesh.loop_triangles]
683
+ self.normals = [[mesh.corner_normals[loop].vector.copy() for loop in triangle.loops]
684
+ for triangle in mesh.loop_triangles]
685
+ finally:
686
+ evaluated.to_mesh_clear()
687
+ self.tree = BVHTree.FromPolygons(self.positions, self.triangles, epsilon=0.0)
688
+
689
+ def normal_at(self, hit) -> Vector:
690
+ """Barycentric blend of the hit triangle's corner normals at the hit location."""
691
+ location, _, index, _ = hit
692
+ corners = [self.positions[vertex] for vertex in self.triangles[index]]
693
+ weights = _barycentric(location, *corners)
694
+ blended = sum((normal * weight for normal, weight in zip(self.normals[index], weights)), Vector())
695
+ return blended.normalized()
696
+
697
+
698
+ def _barycentric(point: Vector, first: Vector, second: Vector, third: Vector) -> tuple:
699
+ """Barycentric weights of a point (on the triangle's plane) for its three corners."""
700
+ edge_one, edge_two, offset = second - first, third - first, point - first
701
+ dot_11, dot_12, dot_22 = edge_one.dot(edge_one), edge_one.dot(edge_two), edge_two.dot(edge_two)
702
+ dot_o1, dot_o2 = offset.dot(edge_one), offset.dot(edge_two)
703
+ denominator = dot_11 * dot_22 - dot_12 * dot_12
704
+ if abs(denominator) < 1e-20:
705
+ return (1.0, 0.0, 0.0)
706
+ second_weight = (dot_22 * dot_o1 - dot_12 * dot_o2) / denominator
707
+ third_weight = (dot_11 * dot_o2 - dot_12 * dot_o1) / denominator
708
+ return (1.0 - second_weight - third_weight, second_weight, third_weight)
709
+
710
+
711
+ def _true_normal(truth: tuple, point: np.ndarray, direction: np.ndarray) -> np.ndarray:
712
+ """
713
+ The high poly's smooth normal where a bake ray from a low-poly surface point lands (cast along the low
714
+ poly's normal, both ways, the nearer hit wins; the nearest surface point when both miss), in the low
715
+ poly's object space.
716
+ """
717
+ surface, to_high, to_low = truth
718
+ origin = to_high @ Vector(point)
719
+ axis = (to_high.to_3x3() @ Vector(direction)).normalized()
720
+ hits = [hit for hit in (surface.tree.ray_cast(origin, axis), surface.tree.ray_cast(origin, -axis))
721
+ if hit[0] is not None]
722
+ hit = min(hits, key=lambda item: item[3]) if hits else surface.tree.find_nearest(origin)
723
+ result = np.array(to_low @ surface.normal_at(hit))
724
+ return result / np.linalg.norm(result)
725
+
726
+
727
+ def _shares_uvs(uv_loops, corners: list) -> bool:
728
+ """True when both faces use the same UV coordinates along the edge (not a seam)."""
729
+ (first_a, second_a), (first_b, second_b) = corners[0][:2], corners[1][:2]
730
+ pairs = ((first_a, second_b), (second_a, first_b))
731
+ return all((uv_loops[left].uv - uv_loops[right].uv).length < 1e-6 for left, right in pairs)
732
+
733
+
734
+ def _seam_side_normal(mesh: bpy.types.Mesh, uv_loops, pixels: np.ndarray, corner: tuple, fraction: float,
735
+ inset: float):
736
+ """
737
+ (decoded object-space normal, object-space surface point, interpolated low-poly normal) just inside one
738
+ face along a seam edge, or None when the face is a sliver thinner than the inset. The tangent frame is
739
+ interpolated at the sample point from the face's corners, as a shader interpolates vertex attributes.
740
+ """
741
+ first, second, outline, loops = corner
742
+ start, end = np.array(uv_loops[first].uv), np.array(uv_loops[second].uv)
743
+ on_edge = start + (end - start) * fraction
744
+ direction = end - start
745
+ inward = np.array([-direction[1], direction[0]])
746
+ inward /= max(np.linalg.norm(inward), 1e-12)
747
+ if not _inside_polygon(on_edge + inward * inset, outline):
748
+ inward = -inward
749
+ sample_uv = on_edge + inward * inset
750
+ if not _inside_polygon(sample_uv, outline):
751
+ return None
752
+ weights = _uv_weights(loops, outline, sample_uv)
753
+ point = sum(weight * np.array(mesh.vertices[mesh.loops[loop].vertex_index].co) for loop, weight in weights)
754
+ normal = sum(weight * np.array(mesh.corner_normals[loop].vector) for loop, weight in weights)
755
+ tangent = sum(weight * np.array(mesh.loops[loop].tangent) for loop, weight in weights)
756
+ sign = mesh.loops[weights[0][0]].bitangent_sign
757
+ return _decode(_sample(pixels, sample_uv), tangent, normal, sign), point, normal / np.linalg.norm(normal)
758
+
759
+
760
+ def _uv_weights(loops: list, outline: np.ndarray, sample_uv: np.ndarray) -> list:
761
+ """[(loop index, barycentric weight)] of a UV point in the fan triangle of the face that holds it."""
762
+ for index in range(1, len(loops) - 1):
763
+ corners = outline[[0, index, index + 1]]
764
+ matrix = np.array([corners[1] - corners[0], corners[2] - corners[0]]).T
765
+ if abs(np.linalg.det(matrix)) < 1e-14:
766
+ continue
767
+ second, third = np.linalg.solve(matrix, sample_uv - corners[0])
768
+ if second >= -1e-6 and third >= -1e-6 and second + third <= 1.0 + 1e-6:
769
+ return [(loops[0], 1.0 - second - third), (loops[index], second), (loops[index + 1], third)]
770
+ return [(loop, 1.0 / len(loops)) for loop in loops]
771
+
772
+
773
+ def _decode(texel: np.ndarray, tangent: np.ndarray, normal: np.ndarray, sign: float) -> np.ndarray:
774
+ """Object-space normal from a tangent-space texel (OpenGL / +Y green) and an interpolated frame."""
775
+ normal = normal / np.linalg.norm(normal)
776
+ tangent = tangent - normal * np.dot(tangent, normal)
777
+ tangent /= np.linalg.norm(tangent)
778
+ bitangent = sign * np.cross(normal, tangent)
779
+ local = texel[:3] * 2.0 - 1.0
780
+ decoded = tangent * local[0] + bitangent * local[1] + normal * local[2]
781
+ return decoded / np.linalg.norm(decoded)