@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,309 @@
1
+ """
2
+ World-registered orthographic views for bt-blender: the named straight views, the pixel frame that ties a
3
+ reference image to world coordinates, and Workbench renders of the model through a camera that covers
4
+ exactly the reference image's world window. A model that is too short or sits off its axis therefore
5
+ renders too short or off axis; nothing is re-centred or re-scaled away.
6
+
7
+ Portions adapted from majidmanzarpour/blender-game-skills (mirrored as Godsified/blender-game-skills-for-claude,
8
+ skills/blender-image-to-3d/scripts/world_gate.py: the orthographic camera placed over the reference
9
+ matte's world window) -- Copyright (c) 2026 Majid Manzarpour, MIT License:
10
+
11
+ Permission is hereby granted, free of charge, to any person obtaining a copy
12
+ of this software and associated documentation files (the "Software"), to deal
13
+ in the Software without restriction, including without limitation the rights
14
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
+ copies of the Software, and to permit persons to whom the Software is
16
+ furnished to do so, subject to the following conditions:
17
+
18
+ The above copyright notice and this permission notice shall be included in all
19
+ copies or substantial portions of the Software.
20
+
21
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27
+ SOFTWARE.
28
+
29
+ View names follow Blender's numpad views, with the model facing -Y (the glTF / BabylonJS forward):
30
+ front looks along +Y, back along -Y, right along -X (camera on +X), left along +X, top straight down and
31
+ bottom straight up. Image right is forward x up; image up is the listed up axis.
32
+ """
33
+ import contextlib
34
+ import os
35
+ from dataclasses import dataclass
36
+
37
+ import bpy
38
+ import numpy as np
39
+ from mathutils import Matrix, Vector
40
+
41
+ import construction_kit
42
+ import tool_common
43
+
44
+ # Camera forward and image-up direction (Blender world axes) for every named straight view.
45
+ VIEW_AXES = {
46
+ "front": ((0.0, 1.0, 0.0), (0.0, 0.0, 1.0)),
47
+ "back": ((0.0, -1.0, 0.0), (0.0, 0.0, 1.0)),
48
+ "right": ((-1.0, 0.0, 0.0), (0.0, 0.0, 1.0)),
49
+ "left": ((1.0, 0.0, 0.0), (0.0, 0.0, 1.0)),
50
+ "top": ((0.0, 0.0, -1.0), (0.0, 1.0, 0.0)),
51
+ "bottom": ((0.0, 0.0, 1.0), (0.0, -1.0, 0.0)),
52
+ }
53
+
54
+ AXIS_NAMES = ("x", "y", "z")
55
+
56
+ # Silhouette renders are made this many times larger than the reference, then averaged down.
57
+ DEFAULT_SUPERSAMPLE = 2
58
+
59
+ # Extra room between the camera and the model, in metres, beyond the model's own radius.
60
+ CAMERA_CLEARANCE_METRES = 1.0
61
+
62
+ # Name of the temporary camera; the leading underscore keeps it out of every tool's object list.
63
+ CAMERA_NAME = "_bt_view_camera"
64
+
65
+ # Flat grey used for shaded (studio-lit) renders.
66
+ SHADED_COLOR = (0.8, 0.8, 0.8)
67
+
68
+ # Near clip distance of the registered orthographic camera, metres.
69
+ ORTHO_CLIP_START = 0.001
70
+
71
+
72
+ @dataclass
73
+ class ViewBasis:
74
+ """The three world directions of a straight view, as numpy unit vectors."""
75
+
76
+ forward: np.ndarray
77
+ right: np.ndarray
78
+ up: np.ndarray
79
+
80
+
81
+ @dataclass
82
+ class PixelFrame:
83
+ """
84
+ Ties an image to world space: its size, its scale and the pixel where the world origin projects.
85
+ origin_column / origin_row are continuous pixel coordinates (row 0 at the top).
86
+ """
87
+
88
+ width: int
89
+ height: int
90
+ pixels_per_metre: float
91
+ origin_column: float
92
+ origin_row: float
93
+
94
+
95
+ def view_basis(view: str) -> ViewBasis:
96
+ """
97
+ The camera directions of a named straight view.
98
+
99
+ :param view: front, back, right, left, top or bottom.
100
+ :returns: The view's basis.
101
+ :raises ValueError: for an unknown view name.
102
+ """
103
+ if view not in VIEW_AXES:
104
+ raise ValueError(f"unknown view '{view}'; use one of {sorted(VIEW_AXES)}")
105
+ forward, up = (np.array(direction, dtype=np.float64) for direction in VIEW_AXES[view])
106
+ return ViewBasis(forward=forward, right=np.cross(forward, up), up=up)
107
+
108
+
109
+ def axis_of(direction: np.ndarray) -> tuple:
110
+ """
111
+ Names the world axis a unit axis vector lies on.
112
+
113
+ :param direction: A unit vector along +/-X, Y or Z.
114
+ :returns: (axis name, sign), e.g. ("y", -1.0).
115
+ """
116
+ index = int(np.argmax(np.abs(direction)))
117
+ return AXIS_NAMES[index], float(np.sign(direction[index]))
118
+
119
+
120
+ def world_to_pixel(points: np.ndarray, basis: ViewBasis, frame: PixelFrame) -> np.ndarray:
121
+ """
122
+ Projects world points into a view's image.
123
+
124
+ :param points: (N, 3) world positions in metres.
125
+ :param basis: The view's basis.
126
+ :param frame: The image's pixel frame.
127
+ :returns: (N, 2) continuous (column, row) pixel coordinates.
128
+ """
129
+ columns = frame.origin_column + (points @ basis.right) * frame.pixels_per_metre
130
+ rows = frame.origin_row - (points @ basis.up) * frame.pixels_per_metre
131
+ return np.column_stack((columns, rows))
132
+
133
+
134
+ def coordinate_to_pixel(coordinate: float, image_axis: str, frame: PixelFrame, sign: float) -> float:
135
+ """
136
+ Converts a world coordinate along one of the view's image axes into a pixel column or row.
137
+
138
+ :param coordinate: World coordinate in metres.
139
+ :param image_axis: "right" (gives a column) or "up" (gives a row).
140
+ :param frame: The image's pixel frame.
141
+ :param sign: +1 when the world axis points along the image axis, -1 when against it.
142
+ :returns: The continuous pixel coordinate.
143
+ """
144
+ if image_axis == "right":
145
+ return frame.origin_column + sign * coordinate * frame.pixels_per_metre
146
+ return frame.origin_row - sign * coordinate * frame.pixels_per_metre
147
+
148
+
149
+ def pixel_to_coordinate(pixel: float, image_axis: str, frame: PixelFrame, sign: float) -> float:
150
+ """
151
+ Inverse of coordinate_to_pixel.
152
+
153
+ :param pixel: Continuous pixel column ("right") or row ("up").
154
+ :param image_axis: "right" or "up".
155
+ :param frame: The image's pixel frame.
156
+ :param sign: +1 when the world axis points along the image axis, -1 when against it.
157
+ :returns: The world coordinate in metres.
158
+ """
159
+ if image_axis == "right":
160
+ return sign * (pixel - frame.origin_column) / frame.pixels_per_metre
161
+ return sign * (frame.origin_row - pixel) / frame.pixels_per_metre
162
+
163
+
164
+ @contextlib.contextmanager
165
+ def render_only(objects: list):
166
+ """
167
+ Hides every other renderable object (and every light) for the duration of a render, then restores them.
168
+
169
+ :param objects: The objects to keep visible.
170
+ """
171
+ keep = {candidate.name for candidate in objects}
172
+ saved = {}
173
+ for candidate in bpy.context.scene.objects:
174
+ if candidate.type in tool_common.GEOMETRY_TYPES or candidate.type == "LIGHT":
175
+ saved[candidate.name] = candidate.hide_render
176
+ candidate.hide_render = candidate.name not in keep
177
+ try:
178
+ yield
179
+ finally:
180
+ for name, hidden in saved.items():
181
+ if name in bpy.data.objects:
182
+ bpy.data.objects[name].hide_render = hidden
183
+
184
+
185
+ def view_camera() -> bpy.types.Object:
186
+ """The tool's camera, created on first use and made the scene camera."""
187
+ camera = bpy.data.objects.get(CAMERA_NAME)
188
+ if camera is None:
189
+ camera = bpy.data.objects.new(CAMERA_NAME, bpy.data.cameras.new(CAMERA_NAME))
190
+ bpy.context.scene.collection.objects.link(camera)
191
+ bpy.context.scene.camera = camera
192
+ return camera
193
+
194
+
195
+ def place_camera(camera: bpy.types.Object, basis: ViewBasis, look_at: np.ndarray, distance: float) -> None:
196
+ """
197
+ Points a camera along a view's forward direction with the view's up as image up.
198
+
199
+ :param camera: The camera object.
200
+ :param basis: The view's basis.
201
+ :param look_at: World point at the centre of the image.
202
+ :param distance: Distance from that point back to the camera, in metres.
203
+ """
204
+ rotation = Matrix((tuple(basis.right), tuple(basis.up), tuple(-basis.forward))).transposed()
205
+ camera.matrix_world = Matrix.Translation(Vector(look_at - basis.forward * distance)) @ rotation.to_4x4()
206
+
207
+
208
+ def _configure_workbench(mode: str, width: int, height: int) -> None:
209
+ """Sets up a transparent Workbench render: flat black for silhouettes, studio grey for shaded."""
210
+ scene = bpy.context.scene
211
+ scene.render.engine = "BLENDER_WORKBENCH"
212
+ scene.render.film_transparent = True
213
+ scene.render.image_settings.file_format = "PNG"
214
+ scene.render.image_settings.color_mode = "RGBA"
215
+ scene.render.resolution_x, scene.render.resolution_y = width, height
216
+ scene.render.resolution_percentage = 100
217
+ scene.view_settings.view_transform = "Standard"
218
+ shading = scene.display.shading
219
+ shading.color_type = "SINGLE"
220
+ shading.show_cavity = False
221
+ shading.show_object_outline = False
222
+ if mode == "silhouette":
223
+ shading.light = "FLAT"
224
+ shading.single_color = (0.0, 0.0, 0.0)
225
+ shading.show_shadows = False
226
+ else:
227
+ shading.light = "STUDIO"
228
+ shading.single_color = SHADED_COLOR
229
+ shading.show_shadows = False
230
+ shading.show_specular_highlight = True
231
+
232
+
233
+ def render_view(objects: list, view: str, frame: PixelFrame, path: str, mode: str = "silhouette",
234
+ supersample: int = DEFAULT_SUPERSAMPLE) -> np.ndarray:
235
+ """
236
+ Renders objects through an orthographic camera that covers exactly the frame's world window.
237
+
238
+ :param objects: Objects to render (everything else is hidden).
239
+ :param view: Named straight view.
240
+ :param frame: The reference image's pixel frame; the render has the same size and registration.
241
+ :param path: Where the full-size render is written (PNG).
242
+ :param mode: "silhouette" (flat black, alpha is the mask) or "shaded" (studio-lit grey).
243
+ :param supersample: Render this many times larger, then average down to the frame size.
244
+ :returns: float32 RGBA (frame.height, frame.width, 4), row 0 at the top.
245
+ :raises RuntimeError: when the render does not finish.
246
+ """
247
+ basis = view_basis(view)
248
+ points = np.concatenate([construction_kit.world_vertices(candidate) for candidate in objects])
249
+ center = points.mean(axis=0)
250
+ radius = float(np.linalg.norm(points - center, axis=1).max())
251
+ image_center_column = frame.width / 2.0
252
+ image_center_row = frame.height / 2.0
253
+ look_at = (basis.right * (image_center_column - frame.origin_column) / frame.pixels_per_metre
254
+ + basis.up * (frame.origin_row - image_center_row) / frame.pixels_per_metre)
255
+ # Slide the look-at point along the view axis to the model, so the clip range brackets it.
256
+ look_at = look_at + basis.forward * float((center - look_at) @ basis.forward)
257
+ distance = radius + CAMERA_CLEARANCE_METRES
258
+ camera = view_camera()
259
+ place_camera(camera, basis, look_at, distance)
260
+ camera.data.type = "ORTHO"
261
+ camera.data.sensor_fit = "HORIZONTAL"
262
+ camera.data.ortho_scale = frame.width / frame.pixels_per_metre
263
+ camera.data.clip_start = ORTHO_CLIP_START
264
+ camera.data.clip_end = distance * 2.0 + radius
265
+ _configure_workbench(mode, frame.width * supersample, frame.height * supersample)
266
+ bpy.context.scene.render.filepath = os.path.abspath(path)
267
+ with render_only(objects):
268
+ outcome = bpy.ops.render.render(write_still=True)
269
+ if "FINISHED" not in outcome:
270
+ raise RuntimeError(f"render did not finish: {outcome}")
271
+ pixels = tool_common.load_image(path)
272
+ blocks = pixels.reshape(frame.height, supersample, frame.width, supersample, 4)
273
+ return blocks.mean(axis=(1, 3))
274
+
275
+
276
+ def silhouette_mask(objects: list, view: str, frame: PixelFrame, path: str,
277
+ supersample: int = DEFAULT_SUPERSAMPLE) -> np.ndarray:
278
+ """
279
+ The model's silhouette in a reference frame.
280
+
281
+ :param objects: Objects to render.
282
+ :param view: Named straight view.
283
+ :param frame: The reference image's pixel frame.
284
+ :param path: Where the render is written.
285
+ :param supersample: Supersampling factor.
286
+ :returns: Boolean (frame.height, frame.width), True where the model covers the pixel.
287
+ """
288
+ return render_view(objects, view, frame, path, "silhouette", supersample)[:, :, 3] > 0.5
289
+
290
+
291
+ def frame_from_spec(view_spec: dict, width: int, height: int) -> PixelFrame:
292
+ """
293
+ Builds a pixel frame from a view entry of a spec file.
294
+
295
+ :param view_spec: Needs "pixels_per_metre" and "origin_pixel": [column, row] (the pixel where the
296
+ world origin projects: the vertical axis column and the ground row for side views).
297
+ :param width: Image width in pixels.
298
+ :param height: Image height in pixels.
299
+ :returns: The frame.
300
+ :raises ValueError: when a field is missing or invalid.
301
+ """
302
+ if "pixels_per_metre" not in view_spec or "origin_pixel" not in view_spec:
303
+ raise ValueError(f"view '{view_spec.get('name', '?')}' needs pixels_per_metre and origin_pixel")
304
+ pixels_per_metre = float(view_spec["pixels_per_metre"])
305
+ if pixels_per_metre <= 0:
306
+ raise ValueError("pixels_per_metre must be positive")
307
+ origin_column, origin_row = (float(value) for value in view_spec["origin_pixel"])
308
+ return PixelFrame(width=width, height=height, pixels_per_metre=pixels_per_metre,
309
+ origin_column=origin_column, origin_row=origin_row)
@@ -0,0 +1,258 @@
1
+ """
2
+ bt-blender game-ready outputs: LOD chains that keep the LOD0 shading, the measurement that proves it, and
3
+ collision proxies (convex hulls and boxes) named for the engines. Headless on Blender 5.3.
4
+
5
+ import procedural_game_ready as game_ready
6
+
7
+ lods = game_ready.lod_chain(obj, ratios=(0.5, 0.25)) # Name_LOD0, Name_LOD1, Name_LOD2 under an Empty "Name"
8
+ print(game_ready.normal_deviation(lods[2], lods[0])) # degrees: mean, p95, max
9
+ hulls = game_ready.convex_hull_collider(lods[0], max_vertices=64)
10
+ box = game_ready.box_collider(lods[0])
11
+
12
+ What is in it:
13
+ - lod_chain: decimated copies named <Name>_LOD<i> (Unity's importer builds an LOD Group from that suffix),
14
+ with LOD0's custom normals transferred onto every level, so a lower level shades like LOD0 instead of
15
+ re-smoothing its coarser faces (it lives in construction_kit and is re-exported here);
16
+ - normal_deviation: per-corner angle between a mesh's shading normals and a reference mesh's at the same
17
+ surface point (mean, 95th percentile, max), for LODs, retopology and normal transfers;
18
+ - convex_hull_collider (UCX_<Name>_NN, one hull per loose part, vertex-limited), box_collider
19
+ (UBX_<Name>_NN, oriented on the object's axes); both have no material and no UVs.
20
+ """
21
+ import math
22
+
23
+ import bmesh
24
+ import bpy
25
+ import numpy as np
26
+ from mathutils import Vector
27
+ from mathutils.bvhtree import BVHTree
28
+
29
+ import construction_kit as kit
30
+
31
+ # Data Transfer loop mapping for custom normals: the nearest corner of the nearest face, matched by face normal
32
+ # (the kit's value, used by lod_chain).
33
+ NORMAL_TRANSFER_MAPPING = kit.LOD_NORMAL_TRANSFER_MAPPING
34
+
35
+ # How far (share of the corner-to-face-centre distance) a corner sample moves into its own face before the
36
+ # lookup, so the sample lands on the correct side of a hard edge.
37
+ CORNER_NUDGE = 0.05
38
+
39
+ # Percentile reported with the mean and max deviation.
40
+ DEVIATION_PERCENTILE = 95
41
+
42
+ # Unity's convex MeshCollider takes at most 255 triangles; a hull of V vertices has 2V - 4 triangles.
43
+ UNITY_CONVEX_TRIANGLE_LIMIT = 255
44
+
45
+ # Loose parts smaller than this (metres, largest side) get no hull of their own.
46
+ MINIMUM_HULL_PART = 0.01
47
+
48
+ # Name prefixes for collision proxies (the industry convention; Unreal requires it, other tools ignore it).
49
+ CONVEX_PREFIX = "UCX"
50
+ BOX_PREFIX = "UBX"
51
+
52
+
53
+ # --- LODs -----------------------------------------------------------------------------------------------------
54
+
55
+ def triangle_count(obj: bpy.types.Object) -> int:
56
+ """Triangles the mesh draws as."""
57
+ return sum(len(polygon.vertices) - 2 for polygon in obj.data.polygons)
58
+
59
+
60
+ # LOD chains that keep LOD0's custom normals live in construction_kit (one copy); the name keeps working here.
61
+ lod_chain = kit.lod_chain
62
+
63
+
64
+ # --- normal deviation --------------------------------------------------------------------------------------------
65
+
66
+ def _world_mesh(obj: bpy.types.Object, depsgraph) -> dict:
67
+ """
68
+ The evaluated mesh as arrays, copied out before the temporary mesh is freed: world "vertices", world unit
69
+ "normals" per corner, "corner_vertices" (vertex index per corner), and the triangulation as "triangle_loops"
70
+ (three corner indices per triangle).
71
+ """
72
+ evaluated = obj.evaluated_get(depsgraph)
73
+ mesh = evaluated.to_mesh()
74
+ try:
75
+ matrix = np.array(obj.matrix_world)
76
+ coordinates = np.empty(len(mesh.vertices) * 3)
77
+ mesh.vertices.foreach_get("co", coordinates)
78
+ normals = np.empty(len(mesh.loops) * 3)
79
+ mesh.corner_normals.foreach_get("vector", normals)
80
+ corner_vertices = np.empty(len(mesh.loops), dtype=np.int64)
81
+ mesh.loops.foreach_get("vertex_index", corner_vertices)
82
+ mesh.calc_loop_triangles()
83
+ triangle_loops = np.empty(len(mesh.loop_triangles) * 3, dtype=np.int64)
84
+ mesh.loop_triangles.foreach_get("loops", triangle_loops)
85
+ finally:
86
+ evaluated.to_mesh_clear()
87
+ world_normals = normals.reshape(-1, 3) @ np.linalg.inv(matrix[:3, :3])
88
+ world_normals /= np.maximum(np.linalg.norm(world_normals, axis=1, keepdims=True), 1e-12)
89
+ return {"vertices": coordinates.reshape(-1, 3) @ matrix[:3, :3].T + matrix[:3, 3], "normals": world_normals,
90
+ "corner_vertices": corner_vertices, "triangle_loops": triangle_loops.reshape(-1, 3)}
91
+
92
+
93
+ def _barycentric(point: np.ndarray, corners: np.ndarray) -> np.ndarray:
94
+ """Barycentric weights of a point (on or near the triangle's plane) in a (3, 3) triangle."""
95
+ edge_one, edge_two, to_point = corners[1] - corners[0], corners[2] - corners[0], point - corners[0]
96
+ d11, d12, d22 = edge_one @ edge_one, edge_one @ edge_two, edge_two @ edge_two
97
+ d1p, d2p = to_point @ edge_one, to_point @ edge_two
98
+ denominator = d11 * d22 - d12 * d12
99
+ if abs(denominator) < 1e-20:
100
+ return np.array([1.0, 0.0, 0.0])
101
+ second = (d22 * d1p - d12 * d2p) / denominator
102
+ third = (d11 * d2p - d12 * d1p) / denominator
103
+ return np.clip(np.array([1.0 - second - third, second, third]), 0.0, 1.0)
104
+
105
+
106
+ def normal_deviation(obj: bpy.types.Object, reference: bpy.types.Object) -> dict:
107
+ """
108
+ How far the shading of `obj` departs from `reference` (degrees). Every corner of `obj` is nudged into its
109
+ own triangle (so it lands on the correct side of a hard edge); both meshes' shading normals are taken at
110
+ that point, each interpolated across its triangle from the corner normals as the renderer interpolates
111
+ them, and compared. Mean, 95th percentile and max over all corners; a mesh against itself gives 0.
112
+
113
+ :param obj: The mesh to check (an LOD, a retopology).
114
+ :param reference: The mesh it should shade like (LOD0, the source).
115
+ :returns: {"mean", "p95", "max", "corners"}.
116
+ """
117
+ depsgraph = bpy.context.evaluated_depsgraph_get()
118
+ target = _world_mesh(reference, depsgraph)
119
+ checked = _world_mesh(obj, depsgraph)
120
+ target_triangles = target["corner_vertices"][target["triangle_loops"]]
121
+ tree = BVHTree.FromPolygons([Vector(vertex) for vertex in target["vertices"]], target_triangles.tolist())
122
+ angles = []
123
+ for loops in checked["triangle_loops"]:
124
+ corners = checked["vertices"][checked["corner_vertices"][loops]]
125
+ corner_normals = checked["normals"][loops]
126
+ for position in range(len(corners)):
127
+ own_weights = np.full(3, CORNER_NUDGE / 3.0)
128
+ own_weights[position] += 1.0 - CORNER_NUDGE
129
+ sample = own_weights @ corners
130
+ location, _, triangle, _ = tree.find_nearest(Vector(sample))
131
+ if triangle is None:
132
+ continue
133
+ weights = _barycentric(np.array(location), target["vertices"][target_triangles[triangle]])
134
+ shading = weights @ target["normals"][target["triangle_loops"][triangle]]
135
+ shading /= max(np.linalg.norm(shading), 1e-12)
136
+ own = own_weights @ corner_normals
137
+ own /= max(np.linalg.norm(own), 1e-12)
138
+ cosine = float(np.clip(np.dot(own, shading), -1.0, 1.0))
139
+ angles.append(math.degrees(math.acos(cosine)))
140
+ values = np.array(angles)
141
+ return {"mean": round(float(values.mean()), 3), "p95": round(float(np.percentile(values, DEVIATION_PERCENTILE)), 3),
142
+ "max": round(float(values.max()), 3), "corners": len(values)}
143
+
144
+
145
+ # --- collision proxies -------------------------------------------------------------------------------------------
146
+
147
+ def _collider_object(name: str, edit_mesh: bmesh.types.BMesh, source: bpy.types.Object) -> bpy.types.Object:
148
+ """A material-less, UV-less mesh object with the source's transform and parent."""
149
+ # matrix_world is stale after a script sets .location until the view layer updates.
150
+ bpy.context.view_layer.update()
151
+ old = bpy.data.objects.get(name)
152
+ if old is not None:
153
+ bpy.data.objects.remove(old)
154
+ mesh = bpy.data.meshes.new(name)
155
+ edit_mesh.to_mesh(mesh)
156
+ edit_mesh.free()
157
+ obj = bpy.data.objects.new(name, mesh)
158
+ for collection in source.users_collection:
159
+ collection.objects.link(obj)
160
+ obj.parent = source.parent
161
+ obj.matrix_world = source.matrix_world.copy()
162
+ return obj
163
+
164
+
165
+ def _loose_parts(obj: bpy.types.Object) -> list:
166
+ """Vertex coordinate arrays (object space) of each loose part of the evaluated mesh."""
167
+ depsgraph = bpy.context.evaluated_depsgraph_get()
168
+ evaluated = obj.evaluated_get(depsgraph)
169
+ mesh = evaluated.to_mesh()
170
+ try:
171
+ coordinates = np.empty(len(mesh.vertices) * 3)
172
+ mesh.vertices.foreach_get("co", coordinates)
173
+ points = coordinates.reshape(-1, 3)
174
+ parent = list(range(len(points)))
175
+
176
+ def root(index: int) -> int:
177
+ while parent[index] != index:
178
+ parent[index] = parent[parent[index]]
179
+ index = parent[index]
180
+ return index
181
+
182
+ for edge in mesh.edges:
183
+ first, second = root(edge.vertices[0]), root(edge.vertices[1])
184
+ parent[first] = second
185
+ groups = {}
186
+ for index in range(len(points)):
187
+ groups.setdefault(root(index), []).append(index)
188
+ return [points[indices] for indices in groups.values()]
189
+ finally:
190
+ evaluated.to_mesh_clear()
191
+
192
+
193
+ def _farthest_point_subset(points: np.ndarray, count: int) -> np.ndarray:
194
+ """`count` points spread over the set: start at the lowest-x point, then always add the farthest one."""
195
+ chosen = [int(np.argmin(points[:, 0]))]
196
+ distance = np.linalg.norm(points - points[chosen[0]], axis=1)
197
+ while len(chosen) < min(count, len(points)):
198
+ index = int(np.argmax(distance))
199
+ chosen.append(index)
200
+ distance = np.minimum(distance, np.linalg.norm(points - points[index], axis=1))
201
+ return points[chosen]
202
+
203
+
204
+ def _hull_bmesh(points: np.ndarray) -> bmesh.types.BMesh:
205
+ """The convex hull of a point set as a closed, triangulated bmesh (interior points removed)."""
206
+ edit_mesh = bmesh.new()
207
+ vertices = [edit_mesh.verts.new(point) for point in points]
208
+ result = bmesh.ops.convex_hull(edit_mesh, input=vertices, use_existing_faces=False)
209
+ leftovers = {element for element in result["geom_interior"] + result["geom_unused"]
210
+ if isinstance(element, bmesh.types.BMVert)}
211
+ bmesh.ops.delete(edit_mesh, geom=list(leftovers), context="VERTS")
212
+ bmesh.ops.triangulate(edit_mesh, faces=edit_mesh.faces[:])
213
+ bmesh.ops.recalc_face_normals(edit_mesh, faces=edit_mesh.faces[:])
214
+ return edit_mesh
215
+
216
+
217
+ def convex_hull_collider(obj: bpy.types.Object, max_vertices: int = 64, per_part: bool = True) -> list:
218
+ """
219
+ Convex hull proxies for physics, named UCX_<Name>_00, _01, ...: one hull per loose part (a concave
220
+ asset made of convex pieces becomes a compound of exact hulls), or one hull around everything. A hull
221
+ over `max_vertices` is rebuilt from a farthest-point subset of its vertices, which keeps the extremes, so it
222
+ shrinks only between them. Unity's convex MeshCollider caps a hull at 255 triangles (129 vertices).
223
+
224
+ :param obj: The mesh (its evaluated geometry, in object space; the proxies copy its transform).
225
+ :param max_vertices: Vertex budget per hull.
226
+ :param per_part: One hull per loose part (parts below MINIMUM_HULL_PART are skipped) or one in total.
227
+ :returns: The hull objects.
228
+ :raises ValueError: when max_vertices would exceed Unity's convex limit.
229
+ """
230
+ if 2 * max_vertices - 4 > UNITY_CONVEX_TRIANGLE_LIMIT:
231
+ raise ValueError(f"max_vertices {max_vertices} gives more than {UNITY_CONVEX_TRIANGLE_LIMIT} triangles")
232
+ base = kit.lod_base_name(obj.name)
233
+ parts = _loose_parts(obj) if per_part else [np.concatenate(_loose_parts(obj))]
234
+ hulls = []
235
+ for points in parts:
236
+ if np.ptp(points, axis=0).max() < MINIMUM_HULL_PART:
237
+ continue
238
+ edit_mesh = _hull_bmesh(points)
239
+ if len(edit_mesh.verts) > max_vertices:
240
+ hull_points = np.array([vertex.co[:] for vertex in edit_mesh.verts])
241
+ edit_mesh.free()
242
+ edit_mesh = _hull_bmesh(_farthest_point_subset(hull_points, max_vertices))
243
+ hulls.append(_collider_object(f"{CONVEX_PREFIX}_{base}_{len(hulls):02d}", edit_mesh, obj))
244
+ return hulls
245
+
246
+
247
+ def box_collider(obj: bpy.types.Object) -> bpy.types.Object:
248
+ """
249
+ A box proxy, UBX_<Name>_00, on the object's own axes around its evaluated geometry. A box is the cheapest
250
+ shape in every physics engine; prefer it whenever it covers the asset well (crates, walls, steps).
251
+ """
252
+ points = np.concatenate(_loose_parts(obj))
253
+ low, high = points.min(axis=0), points.max(axis=0)
254
+ edit_mesh = bmesh.new()
255
+ bmesh.ops.create_cube(edit_mesh, size=1.0)
256
+ for vertex in edit_mesh.verts:
257
+ vertex.co = Vector(low + (np.array(vertex.co) + 0.5) * (high - low))
258
+ return _collider_object(f"{BOX_PREFIX}_{kit.lod_base_name(obj.name)}_00", edit_mesh, obj)