@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.
- package/README.md +3 -2
- package/package.json +1 -1
- package/skills/bt-atlas/SKILL.md +22 -5
- package/skills/bt-design/references/3d-hero-docs.md +10 -3
- package/skills/bt-design/references/3d-hero-scroll.md +30 -5
- package/skills/bt-gauntlet/SKILL.md +4 -4
- package/skills/bt-gauntlet/references/spec-composition.md +4 -2
- package/skills/bt-gauntlet/references/target-images.md +28 -4
- package/skills/bt-gauntlet/references/unity-pipeline.md +30 -8
- package/skills/bt-hero/SKILL.md +3 -3
- package/skills/bt-landing/SKILL.md +1 -1
- package/skills/bt-prototype/SKILL.md +3 -3
- package/skills/bt-unwrap/SKILL.md +396 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/bt_unwrap.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/image_utils.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/mesh_tools.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/model_io.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/previews.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/rasterizer.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/reference_views.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/reference_warp.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/texture_bake.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/texture_compose.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/__pycache__/uv_layout.cpython-313.pyc +0 -0
- package/skills/bt-unwrap/scripts/blender/bt_unwrap.py +678 -0
- package/skills/bt-unwrap/scripts/blender/image_utils.py +264 -0
- package/skills/bt-unwrap/scripts/blender/mesh_tools.py +508 -0
- package/skills/bt-unwrap/scripts/blender/model_io.py +135 -0
- package/skills/bt-unwrap/scripts/blender/previews.py +205 -0
- package/skills/bt-unwrap/scripts/blender/rasterizer.py +217 -0
- package/skills/bt-unwrap/scripts/blender/reference_views.py +945 -0
- package/skills/bt-unwrap/scripts/blender/reference_warp.py +571 -0
- package/skills/bt-unwrap/scripts/blender/texture_bake.py +390 -0
- package/skills/bt-unwrap/scripts/blender/texture_compose.py +596 -0
- package/skills/bt-unwrap/scripts/blender/uv_layout.py +605 -0
- package/skills/bt-unwrap/scripts/bt-unwrap.mjs +165 -0
|
@@ -0,0 +1,508 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Mesh helpers for bt-unwrap: read triangles into numpy, find connected parts, clean up AI-generated
|
|
3
|
+
geometry, decimate to a face budget, set shading, and move / rotate / scale whole models.
|
|
4
|
+
"""
|
|
5
|
+
import math
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from typing import Optional
|
|
8
|
+
|
|
9
|
+
import bmesh
|
|
10
|
+
import bpy
|
|
11
|
+
import numpy as np
|
|
12
|
+
from mathutils import Euler, Matrix, Vector
|
|
13
|
+
|
|
14
|
+
# Rotation about +Z that turns a model whose front faces the given axis so it faces Blender -Y
|
|
15
|
+
# (Blender -Y is glTF +Z, the glTF and BabylonJS forward direction).
|
|
16
|
+
FORWARD_ROTATION_DEGREES = {"-y": 0.0, "+x": -90.0, "+y": 180.0, "-x": 90.0}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass
|
|
20
|
+
class TriangleSet:
|
|
21
|
+
"""Every triangle of a group of mesh objects, in world space."""
|
|
22
|
+
|
|
23
|
+
positions: np.ndarray # float64 (count, 3, 3) corner positions
|
|
24
|
+
corner_normals: np.ndarray # float32 (count, 3, 3) shading normals per corner
|
|
25
|
+
face_normals: np.ndarray # float32 (count, 3) geometric normals
|
|
26
|
+
material_index: np.ndarray # int32 (count,) material slot per triangle
|
|
27
|
+
object_index: np.ndarray # int32 (count,) index into the object list
|
|
28
|
+
polygon_index: np.ndarray # int64 (count,) source polygon in its own mesh
|
|
29
|
+
vertex_index: np.ndarray # int64 (count, 3) vertices, numbered across all objects in order
|
|
30
|
+
uvs: dict = field(default_factory=dict) # uv layer name -> float32 (count, 3, 2)
|
|
31
|
+
|
|
32
|
+
@property
|
|
33
|
+
def count(self) -> int:
|
|
34
|
+
"""Number of triangles."""
|
|
35
|
+
return self.positions.shape[0]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def mesh_objects(objects: list) -> list:
|
|
39
|
+
"""
|
|
40
|
+
Filters a list down to mesh objects.
|
|
41
|
+
|
|
42
|
+
:param objects: Any Blender objects.
|
|
43
|
+
:returns: Only the objects whose type is MESH.
|
|
44
|
+
"""
|
|
45
|
+
return [obj for obj in objects if obj.type == "MESH"]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def count_triangles(objects: list) -> int:
|
|
49
|
+
"""
|
|
50
|
+
Counts the triangles the given meshes will have once triangulated.
|
|
51
|
+
|
|
52
|
+
:param objects: Mesh objects.
|
|
53
|
+
:returns: Total triangle count.
|
|
54
|
+
"""
|
|
55
|
+
total = 0
|
|
56
|
+
for obj in mesh_objects(objects):
|
|
57
|
+
loop_totals = np.empty(len(obj.data.polygons), dtype=np.int64)
|
|
58
|
+
obj.data.polygons.foreach_get("loop_total", loop_totals)
|
|
59
|
+
total += int((loop_totals - 2).sum())
|
|
60
|
+
return total
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def collect_triangles(objects: list, uv_layer_names: tuple = ()) -> TriangleSet:
|
|
64
|
+
"""
|
|
65
|
+
Reads every triangle of the given meshes into world-space numpy arrays.
|
|
66
|
+
|
|
67
|
+
:param objects: Mesh objects (others are skipped).
|
|
68
|
+
:param uv_layer_names: UV layers to read per corner; a missing layer reads as zeros.
|
|
69
|
+
:returns: A TriangleSet with positions, normals, material and source indices.
|
|
70
|
+
"""
|
|
71
|
+
parts = {"positions": [], "corner_normals": [], "face_normals": [], "material_index": [],
|
|
72
|
+
"object_index": [], "polygon_index": [], "vertex_index": []}
|
|
73
|
+
uv_parts = {name: [] for name in uv_layer_names}
|
|
74
|
+
vertex_offset = 0
|
|
75
|
+
for object_number, obj in enumerate(mesh_objects(objects)):
|
|
76
|
+
mesh = obj.data
|
|
77
|
+
mesh.calc_loop_triangles()
|
|
78
|
+
triangle_count = len(mesh.loop_triangles)
|
|
79
|
+
if triangle_count == 0:
|
|
80
|
+
vertex_offset += len(mesh.vertices)
|
|
81
|
+
continue
|
|
82
|
+
vertex_index = np.empty(triangle_count * 3, dtype=np.int64)
|
|
83
|
+
loop_index = np.empty(triangle_count * 3, dtype=np.int64)
|
|
84
|
+
polygon_index = np.empty(triangle_count, dtype=np.int64)
|
|
85
|
+
mesh.loop_triangles.foreach_get("vertices", vertex_index)
|
|
86
|
+
mesh.loop_triangles.foreach_get("loops", loop_index)
|
|
87
|
+
mesh.loop_triangles.foreach_get("polygon_index", polygon_index)
|
|
88
|
+
|
|
89
|
+
coordinates = np.empty(len(mesh.vertices) * 3, dtype=np.float64)
|
|
90
|
+
mesh.vertices.foreach_get("co", coordinates)
|
|
91
|
+
world_matrix = np.array(obj.matrix_world, dtype=np.float64)
|
|
92
|
+
world_coordinates = coordinates.reshape(-1, 3) @ world_matrix[:3, :3].T + world_matrix[:3, 3]
|
|
93
|
+
|
|
94
|
+
normal_matrix = np.array(obj.matrix_world.to_3x3().inverted_safe().transposed(), dtype=np.float64)
|
|
95
|
+
loop_normals = np.empty(len(mesh.loops) * 3, dtype=np.float32)
|
|
96
|
+
mesh.corner_normals.foreach_get("vector", loop_normals)
|
|
97
|
+
world_normals = _normalize(loop_normals.reshape(-1, 3) @ normal_matrix.T)
|
|
98
|
+
|
|
99
|
+
positions = world_coordinates[vertex_index].reshape(triangle_count, 3, 3)
|
|
100
|
+
edge_one = positions[:, 1] - positions[:, 0]
|
|
101
|
+
edge_two = positions[:, 2] - positions[:, 0]
|
|
102
|
+
parts["positions"].append(positions)
|
|
103
|
+
parts["corner_normals"].append(world_normals[loop_index].reshape(triangle_count, 3, 3).astype(np.float32))
|
|
104
|
+
parts["face_normals"].append(_normalize(np.cross(edge_one, edge_two)).astype(np.float32))
|
|
105
|
+
|
|
106
|
+
material_per_polygon = np.empty(len(mesh.polygons), dtype=np.int32)
|
|
107
|
+
mesh.polygons.foreach_get("material_index", material_per_polygon)
|
|
108
|
+
parts["material_index"].append(material_per_polygon[polygon_index])
|
|
109
|
+
parts["object_index"].append(np.full(triangle_count, object_number, dtype=np.int32))
|
|
110
|
+
parts["polygon_index"].append(polygon_index)
|
|
111
|
+
parts["vertex_index"].append(vertex_index.reshape(triangle_count, 3) + vertex_offset)
|
|
112
|
+
vertex_offset += len(mesh.vertices)
|
|
113
|
+
|
|
114
|
+
for name in uv_layer_names:
|
|
115
|
+
layer = mesh.uv_layers.get(name)
|
|
116
|
+
corner_uvs = np.zeros(len(mesh.loops) * 2, dtype=np.float32)
|
|
117
|
+
if layer is not None:
|
|
118
|
+
layer.data.foreach_get("uv", corner_uvs)
|
|
119
|
+
uv_parts[name].append(corner_uvs.reshape(-1, 2)[loop_index].reshape(triangle_count, 3, 2))
|
|
120
|
+
|
|
121
|
+
if not parts["positions"]:
|
|
122
|
+
raise RuntimeError("the model has no triangles")
|
|
123
|
+
return TriangleSet(
|
|
124
|
+
positions=np.concatenate(parts["positions"]),
|
|
125
|
+
corner_normals=np.concatenate(parts["corner_normals"]),
|
|
126
|
+
face_normals=np.concatenate(parts["face_normals"]),
|
|
127
|
+
material_index=np.concatenate(parts["material_index"]),
|
|
128
|
+
object_index=np.concatenate(parts["object_index"]),
|
|
129
|
+
polygon_index=np.concatenate(parts["polygon_index"]),
|
|
130
|
+
vertex_index=np.concatenate(parts["vertex_index"]),
|
|
131
|
+
uvs={name: np.concatenate(chunks) for name, chunks in uv_parts.items()},
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def smoothed_vertex_normals(objects: list, iterations: int) -> np.ndarray:
|
|
136
|
+
"""
|
|
137
|
+
Vertex normals averaged over their neighbourhood, so a lumpy AI-generated surface reports the overall
|
|
138
|
+
direction a panel faces instead of every bump. Numbered like TriangleSet.vertex_index.
|
|
139
|
+
|
|
140
|
+
:param objects: Mesh objects, in the same order as given to collect_triangles.
|
|
141
|
+
:param iterations: Averaging passes; each widens the neighbourhood by one edge ring.
|
|
142
|
+
:returns: float32 array (vertex_count, 3) of unit world-space normals.
|
|
143
|
+
"""
|
|
144
|
+
chunks = []
|
|
145
|
+
for obj in mesh_objects(objects):
|
|
146
|
+
mesh = obj.data
|
|
147
|
+
normals = np.empty(len(mesh.vertices) * 3, dtype=np.float64)
|
|
148
|
+
mesh.vertices.foreach_get("normal", normals)
|
|
149
|
+
normal_matrix = np.array(obj.matrix_world.to_3x3().inverted_safe().transposed(), dtype=np.float64)
|
|
150
|
+
normals = _normalize(normals.reshape(-1, 3) @ normal_matrix.T)
|
|
151
|
+
edges = np.empty(len(mesh.edges) * 2, dtype=np.int64)
|
|
152
|
+
mesh.edges.foreach_get("vertices", edges)
|
|
153
|
+
edges = edges.reshape(-1, 2)
|
|
154
|
+
for _ in range(iterations):
|
|
155
|
+
summed = normals.copy()
|
|
156
|
+
np.add.at(summed, edges[:, 0], normals[edges[:, 1]])
|
|
157
|
+
np.add.at(summed, edges[:, 1], normals[edges[:, 0]])
|
|
158
|
+
normals = _normalize(summed)
|
|
159
|
+
chunks.append(normals.astype(np.float32))
|
|
160
|
+
return np.concatenate(chunks) if chunks else np.zeros((0, 3), dtype=np.float32)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _normalize(vectors: np.ndarray) -> np.ndarray:
|
|
164
|
+
"""Scales each row vector to unit length; zero vectors stay zero."""
|
|
165
|
+
lengths = np.linalg.norm(vectors, axis=1, keepdims=True)
|
|
166
|
+
return vectors / np.maximum(lengths, 1e-20)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def polygon_adjacency(mesh: bpy.types.Mesh) -> np.ndarray:
|
|
170
|
+
"""
|
|
171
|
+
Lists pairs of polygons that share an edge.
|
|
172
|
+
|
|
173
|
+
:param mesh: The mesh to read.
|
|
174
|
+
:returns: int64 array (pair_count, 2) of polygon indices.
|
|
175
|
+
"""
|
|
176
|
+
pairs, _ = polygon_adjacency_with_edges(mesh)
|
|
177
|
+
return pairs
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def polygon_adjacency_with_edges(mesh: bpy.types.Mesh) -> tuple:
|
|
181
|
+
"""
|
|
182
|
+
Lists pairs of polygons that share an edge, together with that edge.
|
|
183
|
+
|
|
184
|
+
:param mesh: The mesh to read.
|
|
185
|
+
:returns: (int64 array (pair_count, 2) of polygon indices, int64 array (pair_count,) of edge indices).
|
|
186
|
+
"""
|
|
187
|
+
loop_edge = np.empty(len(mesh.loops), dtype=np.int64)
|
|
188
|
+
mesh.loops.foreach_get("edge_index", loop_edge)
|
|
189
|
+
loop_totals = np.empty(len(mesh.polygons), dtype=np.int64)
|
|
190
|
+
mesh.polygons.foreach_get("loop_total", loop_totals)
|
|
191
|
+
polygon_of_loop = np.repeat(np.arange(len(mesh.polygons), dtype=np.int64), loop_totals)
|
|
192
|
+
order = np.argsort(loop_edge, kind="stable")
|
|
193
|
+
sorted_edges = loop_edge[order]
|
|
194
|
+
sorted_polygons = polygon_of_loop[order]
|
|
195
|
+
same_edge = sorted_edges[1:] == sorted_edges[:-1]
|
|
196
|
+
pairs = np.stack((sorted_polygons[:-1][same_edge], sorted_polygons[1:][same_edge]), axis=1)
|
|
197
|
+
return pairs, sorted_edges[1:][same_edge]
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def connected_components(element_count: int, pairs: np.ndarray) -> np.ndarray:
|
|
201
|
+
"""
|
|
202
|
+
Labels the connected components of a graph given as an edge list.
|
|
203
|
+
|
|
204
|
+
:param element_count: Number of nodes.
|
|
205
|
+
:param pairs: int64 array (pair_count, 2) of connected node indices.
|
|
206
|
+
:returns: int64 array (element_count,) — each node's component, the smallest node index in it.
|
|
207
|
+
"""
|
|
208
|
+
labels = np.arange(element_count, dtype=np.int64)
|
|
209
|
+
if pairs.size == 0:
|
|
210
|
+
return labels
|
|
211
|
+
first, second = pairs[:, 0], pairs[:, 1]
|
|
212
|
+
while True:
|
|
213
|
+
updated = labels.copy()
|
|
214
|
+
np.minimum.at(updated, first, labels[second])
|
|
215
|
+
np.minimum.at(updated, second, labels[first])
|
|
216
|
+
updated = updated[updated]
|
|
217
|
+
if np.array_equal(updated, labels):
|
|
218
|
+
return labels
|
|
219
|
+
labels = updated
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def temp_override_for(objects: list, active=None):
|
|
223
|
+
"""
|
|
224
|
+
Builds a context override that makes operators see the given objects as selected and the given (or
|
|
225
|
+
first) one as active.
|
|
226
|
+
|
|
227
|
+
:param objects: Objects to treat as selected.
|
|
228
|
+
:param active: Object to treat as active; defaults to the first.
|
|
229
|
+
:returns: A context manager for `with`.
|
|
230
|
+
"""
|
|
231
|
+
active_object = active or objects[0]
|
|
232
|
+
return bpy.context.temp_override(object=active_object, active_object=active_object,
|
|
233
|
+
selected_objects=objects, selected_editable_objects=objects)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def join_meshes(objects: list) -> bpy.types.Object:
|
|
237
|
+
"""
|
|
238
|
+
Joins all mesh objects into one, bakes its world transform into the vertices and deletes the empty
|
|
239
|
+
hierarchy left behind. AI generators often export one mesh under several empty nodes.
|
|
240
|
+
|
|
241
|
+
:param objects: Every object in the scene.
|
|
242
|
+
:returns: The single joined mesh object, with an identity transform.
|
|
243
|
+
"""
|
|
244
|
+
meshes = mesh_objects(objects)
|
|
245
|
+
target = meshes[0]
|
|
246
|
+
for obj in meshes:
|
|
247
|
+
world_matrix = obj.matrix_world.copy()
|
|
248
|
+
obj.parent = None
|
|
249
|
+
obj.matrix_world = world_matrix
|
|
250
|
+
if len(meshes) > 1:
|
|
251
|
+
with temp_override_for(meshes, target):
|
|
252
|
+
bpy.ops.object.join()
|
|
253
|
+
with temp_override_for([target]):
|
|
254
|
+
bpy.ops.object.transform_apply(location=True, rotation=True, scale=True)
|
|
255
|
+
for obj in list(bpy.context.scene.objects):
|
|
256
|
+
if obj != target and obj.type != "MESH":
|
|
257
|
+
bpy.data.objects.remove(obj, do_unlink=True)
|
|
258
|
+
target.name = "Model"
|
|
259
|
+
return target
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def cleanup_mesh(obj: bpy.types.Object, merge_distance: float, debris_faces: int, fix_normals: bool,
|
|
263
|
+
fill_hole_sides: int) -> dict:
|
|
264
|
+
"""
|
|
265
|
+
Repairs the usual AI-mesh faults in place: duplicate vertices, zero-area faces, loose vertices and
|
|
266
|
+
edges, small floating debris, open holes and inconsistent face winding.
|
|
267
|
+
|
|
268
|
+
:param obj: A mesh object.
|
|
269
|
+
:param merge_distance: Vertices closer than this (meters) are merged.
|
|
270
|
+
:param debris_faces: Connected parts with fewer faces than this are deleted (0 keeps everything).
|
|
271
|
+
:param fix_normals: Recalculate face winding so every normal points outward.
|
|
272
|
+
:param fill_hole_sides: Fill open holes with at most this many edges (0 leaves holes open).
|
|
273
|
+
:returns: Counts of what was removed or changed.
|
|
274
|
+
"""
|
|
275
|
+
mesh = obj.data
|
|
276
|
+
vertices_before = len(mesh.vertices)
|
|
277
|
+
faces_before = len(mesh.polygons)
|
|
278
|
+
|
|
279
|
+
editor = bmesh.new()
|
|
280
|
+
editor.from_mesh(mesh)
|
|
281
|
+
bmesh.ops.remove_doubles(editor, verts=editor.verts, dist=merge_distance)
|
|
282
|
+
bmesh.ops.dissolve_degenerate(editor, dist=merge_distance, edges=editor.edges)
|
|
283
|
+
_delete_loose(editor)
|
|
284
|
+
editor.to_mesh(mesh)
|
|
285
|
+
editor.free()
|
|
286
|
+
|
|
287
|
+
debris_removed = 0
|
|
288
|
+
if debris_faces > 0 and len(mesh.polygons) > 0:
|
|
289
|
+
components = connected_components(len(mesh.polygons), polygon_adjacency(mesh))
|
|
290
|
+
_, inverse, sizes = np.unique(components, return_inverse=True, return_counts=True)
|
|
291
|
+
is_debris = sizes[inverse] < debris_faces
|
|
292
|
+
if is_debris.any() and not is_debris.all():
|
|
293
|
+
debris_removed = int(is_debris.sum())
|
|
294
|
+
editor = bmesh.new()
|
|
295
|
+
editor.from_mesh(mesh)
|
|
296
|
+
editor.faces.ensure_lookup_table()
|
|
297
|
+
doomed = [editor.faces[index] for index in np.flatnonzero(is_debris)]
|
|
298
|
+
bmesh.ops.delete(editor, geom=doomed, context="FACES")
|
|
299
|
+
_delete_loose(editor)
|
|
300
|
+
editor.to_mesh(mesh)
|
|
301
|
+
editor.free()
|
|
302
|
+
|
|
303
|
+
holes_filled = 0
|
|
304
|
+
editor = bmesh.new()
|
|
305
|
+
editor.from_mesh(mesh)
|
|
306
|
+
if fill_hole_sides > 0:
|
|
307
|
+
boundary = [edge for edge in editor.edges if edge.is_boundary]
|
|
308
|
+
result = bmesh.ops.holes_fill(editor, edges=boundary, sides=fill_hole_sides)
|
|
309
|
+
holes_filled = len(result.get("faces", []))
|
|
310
|
+
if fix_normals:
|
|
311
|
+
bmesh.ops.recalc_face_normals(editor, faces=editor.faces)
|
|
312
|
+
editor.to_mesh(mesh)
|
|
313
|
+
editor.free()
|
|
314
|
+
mesh.update()
|
|
315
|
+
|
|
316
|
+
return {
|
|
317
|
+
"vertices_merged": vertices_before - len(mesh.vertices),
|
|
318
|
+
"faces_before": faces_before,
|
|
319
|
+
"faces_after": len(mesh.polygons),
|
|
320
|
+
"debris_faces_removed": debris_removed,
|
|
321
|
+
"hole_faces_added": holes_filled,
|
|
322
|
+
"normals_recalculated": fix_normals,
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def _delete_loose(editor: bmesh.types.BMesh) -> None:
|
|
327
|
+
"""Deletes edges and vertices that belong to no face."""
|
|
328
|
+
loose_edges = [edge for edge in editor.edges if not edge.link_faces]
|
|
329
|
+
if loose_edges:
|
|
330
|
+
bmesh.ops.delete(editor, geom=loose_edges, context="EDGES")
|
|
331
|
+
loose_vertices = [vertex for vertex in editor.verts if not vertex.link_faces]
|
|
332
|
+
if loose_vertices:
|
|
333
|
+
bmesh.ops.delete(editor, geom=loose_vertices, context="VERTS")
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def duplicate_object(obj: bpy.types.Object, name: str) -> bpy.types.Object:
|
|
337
|
+
"""
|
|
338
|
+
Copies an object with its own mesh data (materials are shared) into the scene.
|
|
339
|
+
|
|
340
|
+
:param obj: The object to copy.
|
|
341
|
+
:param name: Name for the copy.
|
|
342
|
+
:returns: The new object.
|
|
343
|
+
"""
|
|
344
|
+
copy = obj.copy()
|
|
345
|
+
copy.data = obj.data.copy()
|
|
346
|
+
copy.name = name
|
|
347
|
+
for collection in obj.users_collection:
|
|
348
|
+
collection.objects.link(copy)
|
|
349
|
+
return copy
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def detached_copy(obj: bpy.types.Object, name: str) -> bpy.types.Object:
|
|
353
|
+
"""
|
|
354
|
+
Copies an object with its own mesh data, unparented but in the same world place, so removing or joining
|
|
355
|
+
the original hierarchy later cannot move it.
|
|
356
|
+
|
|
357
|
+
:param obj: The object to copy.
|
|
358
|
+
:param name: Name for the copy.
|
|
359
|
+
:returns: The new object.
|
|
360
|
+
"""
|
|
361
|
+
world_matrix = obj.matrix_world.copy()
|
|
362
|
+
copy = duplicate_object(obj, name)
|
|
363
|
+
copy.parent = None
|
|
364
|
+
copy.matrix_world = world_matrix
|
|
365
|
+
return copy
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def decimate_to_triangles(obj: bpy.types.Object, target_triangles: int) -> int:
|
|
369
|
+
"""
|
|
370
|
+
Reduces a mesh to about the target triangle count with a collapse decimation, keeping UVs.
|
|
371
|
+
Nothing happens when the mesh already has fewer triangles.
|
|
372
|
+
|
|
373
|
+
:param obj: A mesh object.
|
|
374
|
+
:param target_triangles: Desired triangle count.
|
|
375
|
+
:returns: The triangle count afterwards.
|
|
376
|
+
"""
|
|
377
|
+
current = count_triangles([obj])
|
|
378
|
+
if target_triangles <= 0 or current <= target_triangles:
|
|
379
|
+
return current
|
|
380
|
+
modifier = obj.modifiers.new("BtUnwrapDecimate", "DECIMATE")
|
|
381
|
+
modifier.decimate_type = "COLLAPSE"
|
|
382
|
+
modifier.ratio = target_triangles / current
|
|
383
|
+
modifier.use_collapse_triangulate = True
|
|
384
|
+
with temp_override_for([obj]):
|
|
385
|
+
bpy.ops.object.modifier_apply(modifier=modifier.name)
|
|
386
|
+
return count_triangles([obj])
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def apply_shading(objects: list, mode: str, smooth_angle_degrees: float) -> None:
|
|
390
|
+
"""
|
|
391
|
+
Sets face shading. AI meshes usually ship broken or missing split normals, so any mode other than
|
|
392
|
+
'keep' clears custom normals first.
|
|
393
|
+
|
|
394
|
+
:param objects: Mesh objects.
|
|
395
|
+
:param mode: auto (smooth with sharp edges above the angle), smooth, flat, or keep.
|
|
396
|
+
:param smooth_angle_degrees: Edge angle above which 'auto' keeps a hard edge.
|
|
397
|
+
"""
|
|
398
|
+
if mode == "keep":
|
|
399
|
+
return
|
|
400
|
+
for obj in mesh_objects(objects):
|
|
401
|
+
with temp_override_for([obj]):
|
|
402
|
+
if obj.data.has_custom_normals:
|
|
403
|
+
bpy.ops.mesh.customdata_custom_splitnormals_clear()
|
|
404
|
+
if mode == "auto":
|
|
405
|
+
bpy.ops.object.shade_smooth_by_angle(angle=math.radians(smooth_angle_degrees), keep_sharp_edges=True)
|
|
406
|
+
elif mode == "smooth":
|
|
407
|
+
bpy.ops.object.shade_smooth()
|
|
408
|
+
elif mode == "flat":
|
|
409
|
+
bpy.ops.object.shade_flat()
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def world_vertex_positions(objects: list) -> np.ndarray:
|
|
413
|
+
"""
|
|
414
|
+
Reads every vertex of the given meshes in world space.
|
|
415
|
+
|
|
416
|
+
:param objects: Mesh objects.
|
|
417
|
+
:returns: float64 array (vertex_count, 3).
|
|
418
|
+
"""
|
|
419
|
+
chunks = []
|
|
420
|
+
for obj in mesh_objects(objects):
|
|
421
|
+
coordinates = np.empty(len(obj.data.vertices) * 3, dtype=np.float64)
|
|
422
|
+
obj.data.vertices.foreach_get("co", coordinates)
|
|
423
|
+
world_matrix = np.array(obj.matrix_world, dtype=np.float64)
|
|
424
|
+
chunks.append(coordinates.reshape(-1, 3) @ world_matrix[:3, :3].T + world_matrix[:3, 3])
|
|
425
|
+
return np.concatenate(chunks) if chunks else np.zeros((0, 3))
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def model_bounds(objects: list) -> tuple:
|
|
429
|
+
"""
|
|
430
|
+
Computes the world-space axis-aligned bounds of the given meshes.
|
|
431
|
+
|
|
432
|
+
:param objects: Mesh objects.
|
|
433
|
+
:returns: (minimum, maximum) as numpy float64 3-vectors.
|
|
434
|
+
"""
|
|
435
|
+
positions = world_vertex_positions(objects)
|
|
436
|
+
return positions.min(axis=0), positions.max(axis=0)
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def transform_model(objects: list, matrix: Matrix) -> None:
|
|
440
|
+
"""
|
|
441
|
+
Applies a world-space transform to a whole model by moving its top-level objects, so parent / child
|
|
442
|
+
pivots (wheels, doors) keep their local transforms.
|
|
443
|
+
|
|
444
|
+
:param objects: Every object of the model.
|
|
445
|
+
:param matrix: 4x4 world transform to apply on top of the current placement.
|
|
446
|
+
"""
|
|
447
|
+
object_set = set(objects)
|
|
448
|
+
for obj in objects:
|
|
449
|
+
if obj.parent is None or obj.parent not in object_set:
|
|
450
|
+
obj.matrix_world = matrix @ obj.matrix_world
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def rotation_from_euler_degrees(text: Optional[str]) -> Matrix:
|
|
454
|
+
"""
|
|
455
|
+
Parses an "x,y,z" rotation in degrees.
|
|
456
|
+
|
|
457
|
+
:param text: Comma-separated degrees, or None for no rotation.
|
|
458
|
+
:returns: A 4x4 rotation matrix.
|
|
459
|
+
:raises ValueError: when the text is not three numbers.
|
|
460
|
+
"""
|
|
461
|
+
if not text:
|
|
462
|
+
return Matrix.Identity(4)
|
|
463
|
+
values = [float(part) for part in text.split(",")]
|
|
464
|
+
if len(values) != 3:
|
|
465
|
+
raise ValueError(f"--rotate expects three comma-separated degrees, got '{text}'")
|
|
466
|
+
radians = tuple(math.radians(value) for value in values)
|
|
467
|
+
return Euler(radians, "XYZ").to_matrix().to_4x4()
|
|
468
|
+
|
|
469
|
+
|
|
470
|
+
def forward_rotation(forward_axis: str) -> Matrix:
|
|
471
|
+
"""
|
|
472
|
+
Builds the rotation that turns a model facing the given axis so it faces Blender -Y (glTF +Z).
|
|
473
|
+
|
|
474
|
+
:param forward_axis: One of +x, -x, +y, -y.
|
|
475
|
+
:returns: A 4x4 rotation about +Z.
|
|
476
|
+
"""
|
|
477
|
+
return Matrix.Rotation(math.radians(FORWARD_ROTATION_DEGREES[forward_axis]), 4, "Z")
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
def scale_and_origin_matrix(objects: list, length: float, width: float, height: float, origin: str) -> tuple:
|
|
481
|
+
"""
|
|
482
|
+
Builds the transform that scales a model already facing -Y to a real-world size and moves its origin.
|
|
483
|
+
|
|
484
|
+
:param objects: Mesh objects of the model.
|
|
485
|
+
:param length: Front-to-back size in meters along Y (0 = keep).
|
|
486
|
+
:param width: Side-to-side size in meters along X (0 = keep).
|
|
487
|
+
:param height: Vertical size in meters along Z (0 = keep).
|
|
488
|
+
:param origin: bottom (center of the footprint at floor level), center, or keep.
|
|
489
|
+
:returns: (4x4 matrix, the uniform scale factor used).
|
|
490
|
+
"""
|
|
491
|
+
minimum, maximum = model_bounds(objects)
|
|
492
|
+
size = maximum - minimum
|
|
493
|
+
scale_factor = 1.0
|
|
494
|
+
if length > 0 and size[1] > 0:
|
|
495
|
+
scale_factor = length / size[1]
|
|
496
|
+
elif height > 0 and size[2] > 0:
|
|
497
|
+
scale_factor = height / size[2]
|
|
498
|
+
elif width > 0 and size[0] > 0:
|
|
499
|
+
scale_factor = width / size[0]
|
|
500
|
+
center = (minimum + maximum) / 2.0
|
|
501
|
+
if origin == "bottom":
|
|
502
|
+
anchor = Vector((center[0], center[1], minimum[2]))
|
|
503
|
+
elif origin == "center":
|
|
504
|
+
anchor = Vector(center.tolist())
|
|
505
|
+
else:
|
|
506
|
+
anchor = Vector((0.0, 0.0, 0.0))
|
|
507
|
+
matrix = Matrix.Scale(scale_factor, 4) @ Matrix.Translation(-anchor)
|
|
508
|
+
return matrix, scale_factor
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Model import and export for bt-unwrap. The input and output formats are picked from the file extension, so
|
|
3
|
+
the pipeline works the same on GLB, glTF, FBX, OBJ, USD, PLY, STL, Alembic and .blend files.
|
|
4
|
+
"""
|
|
5
|
+
import os
|
|
6
|
+
|
|
7
|
+
import bpy
|
|
8
|
+
|
|
9
|
+
IMPORT_EXTENSIONS = (".glb", ".gltf", ".fbx", ".obj", ".usd", ".usda", ".usdc", ".usdz", ".ply", ".stl",
|
|
10
|
+
".abc", ".blend")
|
|
11
|
+
EXPORT_EXTENSIONS = (".glb", ".gltf", ".fbx", ".obj", ".usd", ".usda", ".usdc", ".usdz", ".blend")
|
|
12
|
+
|
|
13
|
+
# glTF exporter image formats by the --image-format option.
|
|
14
|
+
GLTF_IMAGE_FORMAT = {"png": "AUTO", "jpeg": "JPEG", "webp": "WEBP"}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _operator_keywords(operator, wanted: dict) -> dict:
|
|
18
|
+
"""Keeps only the keyword arguments this Blender build's operator actually has (names move between
|
|
19
|
+
versions)."""
|
|
20
|
+
available = {prop.identifier for prop in operator.get_rna_type().properties}
|
|
21
|
+
return {name: value for name, value in wanted.items() if name in available}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _call_operator(operator, description: str, **keywords) -> None:
|
|
25
|
+
"""Runs an operator and raises when Blender reports it did not finish (operators do not raise on
|
|
26
|
+
cancel)."""
|
|
27
|
+
result = operator(**_operator_keywords(operator, keywords))
|
|
28
|
+
if "FINISHED" not in result:
|
|
29
|
+
raise RuntimeError(f"{description} failed: {result}")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def import_model(path: str) -> list:
|
|
33
|
+
"""
|
|
34
|
+
Imports a model into an empty scene.
|
|
35
|
+
|
|
36
|
+
:param path: Model file; the extension picks the importer.
|
|
37
|
+
:returns: Every object the import created.
|
|
38
|
+
:raises ValueError: for an unsupported extension.
|
|
39
|
+
:raises RuntimeError: when the importer fails or brings in no mesh.
|
|
40
|
+
"""
|
|
41
|
+
extension = os.path.splitext(path)[1].lower()
|
|
42
|
+
if extension not in IMPORT_EXTENSIONS:
|
|
43
|
+
raise ValueError(f"unsupported input format '{extension}'. Supported: {', '.join(IMPORT_EXTENSIONS)}")
|
|
44
|
+
if not os.path.isfile(path):
|
|
45
|
+
raise RuntimeError(f"input file not found: {path}")
|
|
46
|
+
|
|
47
|
+
if extension == ".blend":
|
|
48
|
+
bpy.ops.wm.open_mainfile(filepath=path)
|
|
49
|
+
else:
|
|
50
|
+
bpy.ops.wm.read_factory_settings(use_empty=True)
|
|
51
|
+
_import_by_extension(path, extension)
|
|
52
|
+
|
|
53
|
+
objects = list(bpy.context.scene.objects)
|
|
54
|
+
if not any(obj.type == "MESH" for obj in objects):
|
|
55
|
+
raise RuntimeError(f"'{path}' contains no mesh objects")
|
|
56
|
+
return objects
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _import_by_extension(path: str, extension: str) -> None:
|
|
60
|
+
"""Dispatches to the importer for one file type."""
|
|
61
|
+
if extension in (".glb", ".gltf"):
|
|
62
|
+
_call_operator(bpy.ops.import_scene.gltf, "glTF import", filepath=path)
|
|
63
|
+
elif extension == ".fbx":
|
|
64
|
+
_call_operator(bpy.ops.import_scene.fbx, "FBX import", filepath=path, use_custom_normals=True)
|
|
65
|
+
elif extension == ".obj":
|
|
66
|
+
_call_operator(bpy.ops.wm.obj_import, "OBJ import", filepath=path)
|
|
67
|
+
elif extension in (".usd", ".usda", ".usdc", ".usdz"):
|
|
68
|
+
_call_operator(bpy.ops.wm.usd_import, "USD import", filepath=path)
|
|
69
|
+
elif extension == ".ply":
|
|
70
|
+
_call_operator(bpy.ops.wm.ply_import, "PLY import", filepath=path)
|
|
71
|
+
elif extension == ".stl":
|
|
72
|
+
_call_operator(bpy.ops.wm.stl_import, "STL import", filepath=path)
|
|
73
|
+
elif extension == ".abc":
|
|
74
|
+
_call_operator(bpy.ops.wm.alembic_import, "Alembic import", filepath=path)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def export_model(path: str, objects: list, image_format: str, jpeg_quality: int, draco: bool = False,
|
|
78
|
+
tangents: bool = False) -> str:
|
|
79
|
+
"""
|
|
80
|
+
Exports the given objects (and nothing else) to one file.
|
|
81
|
+
|
|
82
|
+
:param path: Output file; the extension picks the exporter. .glb embeds textures, .gltf writes them beside it.
|
|
83
|
+
:param objects: Objects to export; their parents and children must be in the list too.
|
|
84
|
+
:param image_format: png, jpeg or webp — how glTF stores its textures.
|
|
85
|
+
:param jpeg_quality: 0..100 quality for JPEG / WebP textures.
|
|
86
|
+
:param draco: Draco-compress glTF / GLB geometry.
|
|
87
|
+
:param tangents: Write MikkTSpace tangents (glTF), so engines read the baked normal map exactly as it
|
|
88
|
+
was baked instead of generating their own tangents.
|
|
89
|
+
:returns: The path written.
|
|
90
|
+
:raises ValueError: for an unsupported extension.
|
|
91
|
+
"""
|
|
92
|
+
extension = os.path.splitext(path)[1].lower()
|
|
93
|
+
if extension not in EXPORT_EXTENSIONS:
|
|
94
|
+
raise ValueError(f"unsupported output format '{extension}'. Supported: {', '.join(EXPORT_EXTENSIONS)}")
|
|
95
|
+
os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
|
|
96
|
+
|
|
97
|
+
bpy.ops.object.select_all(action="DESELECT")
|
|
98
|
+
for obj in objects:
|
|
99
|
+
obj.select_set(True)
|
|
100
|
+
bpy.context.view_layer.objects.active = next((obj for obj in objects if obj.type == "MESH"), None)
|
|
101
|
+
|
|
102
|
+
if extension in (".glb", ".gltf"):
|
|
103
|
+
_call_operator(
|
|
104
|
+
bpy.ops.export_scene.gltf, "glTF export",
|
|
105
|
+
filepath=path,
|
|
106
|
+
export_format="GLB" if extension == ".glb" else "GLTF_SEPARATE",
|
|
107
|
+
use_selection=True,
|
|
108
|
+
export_apply=True,
|
|
109
|
+
export_yup=True,
|
|
110
|
+
export_texcoords=True,
|
|
111
|
+
export_normals=True,
|
|
112
|
+
export_tangents=tangents,
|
|
113
|
+
export_materials="EXPORT",
|
|
114
|
+
export_image_format=GLTF_IMAGE_FORMAT.get(image_format, "AUTO"),
|
|
115
|
+
export_jpeg_quality=jpeg_quality,
|
|
116
|
+
export_image_quality=jpeg_quality,
|
|
117
|
+
export_draco_mesh_compression_enable=draco,
|
|
118
|
+
export_extras=True,
|
|
119
|
+
)
|
|
120
|
+
elif extension == ".fbx":
|
|
121
|
+
_call_operator(
|
|
122
|
+
bpy.ops.export_scene.fbx, "FBX export",
|
|
123
|
+
filepath=path, use_selection=True, add_leaf_bones=False, path_mode="COPY", embed_textures=True,
|
|
124
|
+
apply_unit_scale=True, bake_space_transform=False,
|
|
125
|
+
)
|
|
126
|
+
elif extension == ".obj":
|
|
127
|
+
_call_operator(bpy.ops.wm.obj_export, "OBJ export", filepath=path, export_selected_objects=True,
|
|
128
|
+
export_materials=True, path_mode="COPY")
|
|
129
|
+
elif extension in (".usd", ".usda", ".usdc", ".usdz"):
|
|
130
|
+
_call_operator(bpy.ops.wm.usd_export, "USD export", filepath=path, selected_objects_only=True,
|
|
131
|
+
export_textures=True, relative_paths=True)
|
|
132
|
+
elif extension == ".blend":
|
|
133
|
+
bpy.ops.file.pack_all()
|
|
134
|
+
bpy.ops.wm.save_as_mainfile(filepath=path, copy=True)
|
|
135
|
+
return path
|