@babylonjs-toolkit/agent 1.2.16 → 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.
- package/README.md +3 -2
- package/package.json +1 -1
- package/skills/bt-blender/SKILL.md +386 -0
- package/skills/bt-blender/THIRD_PARTY_NOTICES.md +141 -0
- package/skills/bt-blender/references/art-style-and-genre.md +173 -0
- package/skills/bt-blender/references/characters-and-creatures.md +644 -0
- package/skills/bt-blender/references/environments.md +478 -0
- package/skills/bt-blender/references/game-engine-export.md +284 -0
- package/skills/bt-blender/references/geometry-nodes.md +447 -0
- package/skills/bt-blender/references/hard-surface.md +720 -0
- package/skills/bt-blender/references/procedural-generation.md +358 -0
- package/skills/bt-blender/references/rigging-and-animation.md +1080 -0
- package/skills/bt-blender/references/sculpting-and-retopology.md +544 -0
- package/skills/bt-blender/references/uv-and-pbr-materials.md +381 -0
- package/skills/bt-blender/references/vehicles.md +632 -0
- package/skills/bt-blender/scripts/blender/assembly_check.py +420 -0
- package/skills/bt-blender/scripts/blender/character_blockout.py +462 -0
- package/skills/bt-blender/scripts/blender/construction_kit.py +1710 -0
- package/skills/bt-blender/scripts/blender/environment_kit.py +525 -0
- package/skills/bt-blender/scripts/blender/export_asset.py +623 -0
- package/skills/bt-blender/scripts/blender/geometry_nodes_builders.py +575 -0
- package/skills/bt-blender/scripts/blender/hard_surface_panels.py +374 -0
- package/skills/bt-blender/scripts/blender/hard_surface_trims.py +200 -0
- package/skills/bt-blender/scripts/blender/image_measure.py +568 -0
- package/skills/bt-blender/scripts/blender/materials_pbr.py +439 -0
- package/skills/bt-blender/scripts/blender/measure_stations.py +486 -0
- package/skills/bt-blender/scripts/blender/ortho_views.py +309 -0
- package/skills/bt-blender/scripts/blender/procedural_game_ready.py +258 -0
- package/skills/bt-blender/scripts/blender/procedural_generators.py +842 -0
- package/skills/bt-blender/scripts/blender/qa_check.py +729 -0
- package/skills/bt-blender/scripts/blender/retopology_tools.py +781 -0
- package/skills/bt-blender/scripts/blender/review_render.py +358 -0
- package/skills/bt-blender/scripts/blender/rigging_tools.py +1170 -0
- package/skills/bt-blender/scripts/blender/style_palette.py +190 -0
- package/skills/bt-blender/scripts/blender/tool_common.py +289 -0
- package/skills/bt-blender/scripts/blender/uv_layout.py +555 -0
- package/skills/bt-blender/scripts/blender/vehicle_parts.py +370 -0
- package/skills/bt-blender/scripts/blender/view_consistency.py +133 -0
- package/skills/bt-blender/scripts/blender/world_gate.py +219 -0
- package/skills/bt-blender/scripts/bt-blender.mjs +329 -0
- package/skills/bt-blender/scripts/validate_gltf.mjs +204 -0
- package/skills/bt-gauntlet/SKILL.md +6 -6
- package/skills/bt-gauntlet/references/critic-rubrics.md +71 -4
- package/skills/bt-gauntlet/references/spec-composition.md +13 -0
- package/skills/bt-gauntlet/references/unity-pipeline.md +18 -2
- 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
|
@@ -0,0 +1,623 @@
|
|
|
1
|
+
"""
|
|
2
|
+
export_asset -- export an asset for an engine and prove the file is right: glTF / GLB for the web, or FBX
|
|
3
|
+
with the Unity preset.
|
|
4
|
+
|
|
5
|
+
blender --background --factory-startup --python-exit-code 1 --python export_asset.py -- \
|
|
6
|
+
--model asset.blend --out build/asset.glb [--format glb|gltf|fbx] [--objects ...]
|
|
7
|
+
[--source blender|unity] [--tangents on|auto|off] [--realize | --gpu-instances]
|
|
8
|
+
[--draco [LEVEL] | --meshopt] [--webp] [--no-convert-images] [--no-roundtrip] [--no-validate]
|
|
9
|
+
[--validator-dir DIR] [--report build/asset.export.json]
|
|
10
|
+
|
|
11
|
+
What it does, in order:
|
|
12
|
+
1. Geometry Nodes instances: an exporter writes only an object's own mesh, so instances are silently
|
|
13
|
+
dropped. --realize bakes them into the mesh; --gpu-instances turns them into linked duplicates under one
|
|
14
|
+
parent, which glTF writes as EXT_mesh_gpu_instancing (BabylonJS thin instances) and Unity imports as one
|
|
15
|
+
shared mesh. Without either, an object that still carries instances fails the gate.
|
|
16
|
+
2. Objects that evaluate to no mesh (a curve whose nodes only make instances, an empty curve) are skipped
|
|
17
|
+
and reported instead of crashing the size check.
|
|
18
|
+
3. glTF only: every float image a material uses is replaced, in memory, by an 8-bit copy with the sRGB
|
|
19
|
+
curve applied to colour images. A packed linear float image (what a bake leaves behind) otherwise
|
|
20
|
+
reaches the glTF as raw linear values and renders far too dark. The .blend is not changed.
|
|
21
|
+
4. Exports with the settings the guide's section 8.2a case table gives. glTF: modifiers applied, Y up,
|
|
22
|
+
tangents on (BabylonJS reads them; --tangents auto writes them only for normal-mapped materials),
|
|
23
|
+
optional Draco or EXT_meshopt_compression geometry and WebP textures; a rig uses
|
|
24
|
+
rigging_tools.GLTF_RIG_SETTINGS. FBX (Unity): -Z forward, Y up, FBX unit scale, no leaf bones, normals
|
|
25
|
+
only; bake_space_transform only for a static mesh built in Blender, never for an armature (the rig
|
|
26
|
+
preset rigging_tools.UNITY_FBX_RIG_SETTINGS), animation (one scene take) or a file that came from
|
|
27
|
+
Unity (--source unity).
|
|
28
|
+
5. Re-imports the file into an empty scene and compares the world size against the source (catches a
|
|
29
|
+
wrong axis or unit scale before an engine does).
|
|
30
|
+
6. glTF only: summarises the file (meshes, triangles, materials, textures, attributes, extensions) and
|
|
31
|
+
runs the Khronos glTF-Validator through ../validate_gltf.mjs when Node is installed; without Node the
|
|
32
|
+
validation is reported as skipped with the install steps, and the export still passes.
|
|
33
|
+
The gate fails (exit 1) when the export does not finish, instances would be dropped, the round trip changes
|
|
34
|
+
the size, or the validator reports errors. The report is written next to the export as <name>.export.json.
|
|
35
|
+
"""
|
|
36
|
+
import json
|
|
37
|
+
import os
|
|
38
|
+
import shutil
|
|
39
|
+
import struct
|
|
40
|
+
import subprocess
|
|
41
|
+
import sys
|
|
42
|
+
|
|
43
|
+
sys.dont_write_bytecode = True
|
|
44
|
+
SCRIPT_DIRECTORY = os.path.dirname(os.path.abspath(__file__))
|
|
45
|
+
if SCRIPT_DIRECTORY not in sys.path:
|
|
46
|
+
sys.path.insert(0, SCRIPT_DIRECTORY)
|
|
47
|
+
|
|
48
|
+
import bpy # noqa: E402
|
|
49
|
+
import numpy as np # noqa: E402
|
|
50
|
+
|
|
51
|
+
import geometry_nodes_builders as geometry_nodes # noqa: E402
|
|
52
|
+
import image_measure # noqa: E402
|
|
53
|
+
import rigging_tools # noqa: E402
|
|
54
|
+
import tool_common # noqa: E402
|
|
55
|
+
|
|
56
|
+
TOOL_NAME = "export"
|
|
57
|
+
|
|
58
|
+
# Output format by --format, with the file extension each one writes.
|
|
59
|
+
FORMAT_EXTENSIONS = {"glb": ".glb", "gltf": ".gltf", "fbx": ".fbx"}
|
|
60
|
+
|
|
61
|
+
# Where the asset was authored (--source): a file that came out of a Unity project already carries the axis
|
|
62
|
+
# conversion in its objects, so baking the space transform again rotates every mesh node.
|
|
63
|
+
SOURCES = ("blender", "unity")
|
|
64
|
+
|
|
65
|
+
# The FBX settings Unity imports at the right size and orientation, for a static mesh built in Blender.
|
|
66
|
+
# The other cases of the guide's section 8.2a table override bake_space_transform (see fbx_settings).
|
|
67
|
+
UNITY_FBX_SETTINGS = {"axis_forward": "-Z", "axis_up": "Y", "apply_scale_options": "FBX_SCALE_UNITS",
|
|
68
|
+
"bake_space_transform": True, "add_leaf_bones": False, "mesh_smooth_type": "OFF",
|
|
69
|
+
"use_mesh_modifiers": True}
|
|
70
|
+
|
|
71
|
+
# Draco compression level when --draco is given without one (Blender's default; 0 fastest .. 10 smallest).
|
|
72
|
+
DEFAULT_DRACO_LEVEL = 6
|
|
73
|
+
DRACO_LEVELS = range(0, 11)
|
|
74
|
+
|
|
75
|
+
# The meshopt extension BabylonJS reads (its glTF loader implements EXT_meshopt_compression).
|
|
76
|
+
MESHOPT_EXTENSION = "EXT_meshopt_compression"
|
|
77
|
+
|
|
78
|
+
# Object types exported when no objects are named.
|
|
79
|
+
EXPORT_TYPES = set(tool_common.GEOMETRY_TYPES) | {"ARMATURE", "EMPTY"}
|
|
80
|
+
|
|
81
|
+
# Round trip: the re-imported size may differ by this share of the size, or this many metres.
|
|
82
|
+
ROUNDTRIP_RELATIVE_TOLERANCE = 0.001
|
|
83
|
+
ROUNDTRIP_ABSOLUTE_TOLERANCE = 0.0005
|
|
84
|
+
|
|
85
|
+
# Compressed geometry is quantised, so its round trip may also differ by four quantisation steps, as a share
|
|
86
|
+
# of the largest size: Draco stores positions on a 14-bit grid over the mesh (step size / 2^14); meshopt's
|
|
87
|
+
# exponent filter keeps a 12-bit mantissa per vertex (step up to the coordinate / 2^12; measured 2.2 mm on a
|
|
88
|
+
# 10 m asset on Blender 5.3.0).
|
|
89
|
+
QUANTIZATION_TOLERANCE_SHARE = {"draco": 2.0 ** -12, "meshopt": 2.0 ** -10}
|
|
90
|
+
|
|
91
|
+
# Suffix given, in memory only, to a float image replaced by its 8-bit copy.
|
|
92
|
+
FLOAT_SOURCE_SUFFIX = ".float_source"
|
|
93
|
+
|
|
94
|
+
# Prefix given to a curve object replaced by its realised mesh (objects starting "_" are helpers to every tool).
|
|
95
|
+
REPLACED_SOURCE_PREFIX = "_"
|
|
96
|
+
|
|
97
|
+
# The validator script, beside this folder, and how long it may run (seconds).
|
|
98
|
+
VALIDATOR_SCRIPT = os.path.normpath(os.path.join(SCRIPT_DIRECTORY, "..", "validate_gltf.mjs"))
|
|
99
|
+
VALIDATOR_TIMEOUT_SECONDS = 300
|
|
100
|
+
|
|
101
|
+
# How much of the validator's stderr is quoted when it gives no result.
|
|
102
|
+
STDERR_TAIL_CHARACTERS = 400
|
|
103
|
+
|
|
104
|
+
# GLB container constants: magic, header size, chunk header size and the JSON chunk type.
|
|
105
|
+
GLB_MAGIC = b"glTF"
|
|
106
|
+
GLB_HEADER_BYTES = 12
|
|
107
|
+
GLB_CHUNK_HEADER_BYTES = 8
|
|
108
|
+
GLB_JSON_CHUNK = 0x4E4F534A
|
|
109
|
+
|
|
110
|
+
# glTF primitive mode for triangle lists, and the index count per triangle.
|
|
111
|
+
TRIANGLES_MODE = 4
|
|
112
|
+
INDICES_PER_TRIANGLE = 3
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def build_parser() -> tool_common.ToolArgumentParser:
|
|
116
|
+
"""The tool's command-line options."""
|
|
117
|
+
parser = tool_common.ToolArgumentParser(prog=TOOL_NAME, description=__doc__.strip().splitlines()[0])
|
|
118
|
+
parser.add_argument("--model", help="asset to export (.blend .glb .gltf .fbx .obj)")
|
|
119
|
+
parser.add_argument("--objects", nargs="*", help="objects to export (default every visible object)")
|
|
120
|
+
parser.add_argument("--out", required=True, help="output file")
|
|
121
|
+
parser.add_argument("--format", choices=sorted(FORMAT_EXTENSIONS),
|
|
122
|
+
help="output format (default from --out's extension)")
|
|
123
|
+
parser.add_argument("--source", choices=SOURCES, default="blender",
|
|
124
|
+
help="where the asset was authored; unity: an FBX that came out of the Unity project "
|
|
125
|
+
"(never bake the space transform)")
|
|
126
|
+
parser.add_argument("--tangents", choices=("on", "auto", "off"), default="on",
|
|
127
|
+
help="glTF tangents (on by default for BabylonJS; auto: only with a normal map)")
|
|
128
|
+
instancing = parser.add_mutually_exclusive_group()
|
|
129
|
+
instancing.add_argument("--realize", action="store_true",
|
|
130
|
+
help="bake Geometry Nodes instances into each object's mesh")
|
|
131
|
+
instancing.add_argument("--gpu-instances", action="store_true",
|
|
132
|
+
help="export Geometry Nodes instances as linked duplicates (glTF: EXT_mesh_gpu_instancing)")
|
|
133
|
+
compression = parser.add_mutually_exclusive_group()
|
|
134
|
+
compression.add_argument("--draco", nargs="?", type=int, const=DEFAULT_DRACO_LEVEL, choices=DRACO_LEVELS,
|
|
135
|
+
metavar="LEVEL", help=f"glTF: Draco geometry compression (level 0-10, default {DEFAULT_DRACO_LEVEL})")
|
|
136
|
+
compression.add_argument("--meshopt", action="store_true", help=f"glTF: {MESHOPT_EXTENSION} geometry compression")
|
|
137
|
+
parser.add_argument("--webp", action="store_true", help="glTF: write textures as WebP (EXT_texture_webp)")
|
|
138
|
+
parser.add_argument("--no-convert-images", action="store_true",
|
|
139
|
+
help="glTF: keep float images as they are")
|
|
140
|
+
parser.add_argument("--no-roundtrip", action="store_true", help="skip the re-import size check")
|
|
141
|
+
parser.add_argument("--no-validate", action="store_true", help="skip the Khronos glTF-Validator")
|
|
142
|
+
parser.add_argument("--validator-dir", help="folder holding node_modules/gltf-validator")
|
|
143
|
+
parser.add_argument("--report", help="report path (default <out>.export.json)")
|
|
144
|
+
return parser
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _select(objects: list) -> None:
|
|
148
|
+
"""
|
|
149
|
+
Selects exactly the objects and makes the first active. The view layer is updated first: objects a
|
|
150
|
+
script just made are missing from view_layer.objects until then, and a selection-only export of them
|
|
151
|
+
writes an empty file.
|
|
152
|
+
"""
|
|
153
|
+
bpy.context.view_layer.update()
|
|
154
|
+
for candidate in bpy.context.view_layer.objects:
|
|
155
|
+
candidate.select_set(candidate in objects)
|
|
156
|
+
bpy.context.view_layer.objects.active = objects[0]
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def export_objects(names) -> list:
|
|
160
|
+
"""
|
|
161
|
+
The objects to export, and only those selected.
|
|
162
|
+
|
|
163
|
+
:param names: Object names, or None for every visible object of an exportable type.
|
|
164
|
+
:returns: The objects.
|
|
165
|
+
"""
|
|
166
|
+
objects = tool_common.resolve_objects(names, types=tuple(EXPORT_TYPES))
|
|
167
|
+
_select(objects)
|
|
168
|
+
return objects
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _image_nodes(objects: list) -> list:
|
|
172
|
+
"""Every image texture node in the materials of the objects, once each."""
|
|
173
|
+
nodes, seen = [], set()
|
|
174
|
+
for obj in objects:
|
|
175
|
+
for slot in getattr(obj, "material_slots", []):
|
|
176
|
+
material = slot.material
|
|
177
|
+
if material is None or not material.use_nodes or material.name in seen:
|
|
178
|
+
continue
|
|
179
|
+
seen.add(material.name)
|
|
180
|
+
nodes.extend(node for node in material.node_tree.nodes if node.type == "TEX_IMAGE" and node.image)
|
|
181
|
+
return nodes
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def has_normal_map(objects: list) -> bool:
|
|
185
|
+
"""True when any material of the objects uses a normal map node."""
|
|
186
|
+
for obj in objects:
|
|
187
|
+
for slot in getattr(obj, "material_slots", []):
|
|
188
|
+
material = slot.material
|
|
189
|
+
if material and material.use_nodes and any(node.type == "NORMAL_MAP" for node in material.node_tree.nodes):
|
|
190
|
+
return True
|
|
191
|
+
return False
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def byte_copy(image) -> bpy.types.Image:
|
|
195
|
+
"""
|
|
196
|
+
An 8-bit copy of a float image: colour images get the sRGB curve, data images (Non-Color) keep their
|
|
197
|
+
values. Float buffers hold scene-linear values, so the curve is what an 8-bit sRGB image needs.
|
|
198
|
+
|
|
199
|
+
:param image: A float image.
|
|
200
|
+
:returns: The new, generated (unsaved) image. It takes the source's name, so the glTF image keeps it;
|
|
201
|
+
the source is renamed with FLOAT_SOURCE_SUFFIX.
|
|
202
|
+
"""
|
|
203
|
+
width, height = image.size
|
|
204
|
+
pixels = np.empty(width * height * 4, dtype=np.float32)
|
|
205
|
+
image.pixels.foreach_get(pixels)
|
|
206
|
+
pixels = pixels.reshape(-1, 4)
|
|
207
|
+
is_data = image.colorspace_settings.is_data
|
|
208
|
+
if not is_data:
|
|
209
|
+
pixels[:, :3] = image_measure.linear_to_srgb(pixels[:, :3])
|
|
210
|
+
original_name = image.name
|
|
211
|
+
image.name = f"{original_name}{FLOAT_SOURCE_SUFFIX}"
|
|
212
|
+
copy = bpy.data.images.new(original_name, width, height, alpha=True, float_buffer=False)
|
|
213
|
+
copy.colorspace_settings.name = "Non-Color" if is_data else "sRGB"
|
|
214
|
+
copy.alpha_mode = image.alpha_mode
|
|
215
|
+
copy.pixels.foreach_set(np.clip(pixels, 0.0, 1.0).ravel())
|
|
216
|
+
return copy
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def convert_float_images(objects: list) -> list:
|
|
220
|
+
"""
|
|
221
|
+
Swaps every float image the objects' materials use for an 8-bit copy (in memory only).
|
|
222
|
+
|
|
223
|
+
:param objects: The exported objects.
|
|
224
|
+
:returns: [{"image", "colorspace", "packed"}] of the replaced images.
|
|
225
|
+
"""
|
|
226
|
+
converted, copies = [], {}
|
|
227
|
+
for node in _image_nodes(objects):
|
|
228
|
+
image = node.image
|
|
229
|
+
if not image.is_float or image.size[0] == 0:
|
|
230
|
+
continue
|
|
231
|
+
key = image.as_pointer()
|
|
232
|
+
if key not in copies:
|
|
233
|
+
converted.append({"image": image.name, "colorspace": image.colorspace_settings.name,
|
|
234
|
+
"packed": image.packed_file is not None})
|
|
235
|
+
copies[key] = byte_copy(image)
|
|
236
|
+
node.image = copies[key]
|
|
237
|
+
return converted
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _has_animation_data(owner) -> bool:
|
|
241
|
+
"""True when an ID carries an active action or an NLA strip."""
|
|
242
|
+
animation_data = getattr(owner, "animation_data", None)
|
|
243
|
+
if animation_data is None:
|
|
244
|
+
return False
|
|
245
|
+
return animation_data.action is not None or any(track.strips for track in animation_data.nla_tracks)
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _is_animated(objects: list) -> bool:
|
|
249
|
+
"""True when any object, or its shape keys, carries an action or an NLA strip (stashed clips count)."""
|
|
250
|
+
return any(_has_animation_data(obj) or _has_animation_data(getattr(obj.data, "shape_keys", None))
|
|
251
|
+
for obj in objects)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _has_armature(objects: list) -> bool:
|
|
255
|
+
"""True when an armature is among the exported objects."""
|
|
256
|
+
return any(obj.type == "ARMATURE" for obj in objects)
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _evaluated_mesh_size(obj, depsgraph):
|
|
260
|
+
"""(low, high) world corners of an object's evaluated mesh, or None when it evaluates to no vertices."""
|
|
261
|
+
evaluated = obj.evaluated_get(depsgraph)
|
|
262
|
+
mesh = evaluated.to_mesh()
|
|
263
|
+
try:
|
|
264
|
+
if mesh is None or len(mesh.vertices) == 0:
|
|
265
|
+
return None
|
|
266
|
+
coordinates = np.empty(len(mesh.vertices) * 3)
|
|
267
|
+
mesh.vertices.foreach_get("co", coordinates)
|
|
268
|
+
matrix = np.array(evaluated.matrix_world)
|
|
269
|
+
world = coordinates.reshape(-1, 3) @ matrix[:3, :3].T + matrix[:3, 3]
|
|
270
|
+
return world.min(axis=0), world.max(axis=0)
|
|
271
|
+
finally:
|
|
272
|
+
evaluated.to_mesh_clear()
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def world_size(objects: list) -> list:
|
|
276
|
+
"""
|
|
277
|
+
World-space size of the evaluated mesh vertices of the objects (not bound_box, which is local).
|
|
278
|
+
Objects that evaluate to no mesh (an instance-only curve) add nothing.
|
|
279
|
+
"""
|
|
280
|
+
depsgraph = bpy.context.evaluated_depsgraph_get()
|
|
281
|
+
low, high = np.full(3, np.inf), np.full(3, -np.inf)
|
|
282
|
+
for obj in objects:
|
|
283
|
+
if obj.type not in tool_common.GEOMETRY_TYPES:
|
|
284
|
+
continue
|
|
285
|
+
corners = _evaluated_mesh_size(obj, depsgraph)
|
|
286
|
+
if corners is not None:
|
|
287
|
+
low, high = np.minimum(low, corners[0]), np.maximum(high, corners[1])
|
|
288
|
+
if not np.all(np.isfinite(low)):
|
|
289
|
+
return [0.0, 0.0, 0.0]
|
|
290
|
+
return [round(float(value), 6) for value in high - low]
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _last_nodes_modifier(obj) -> str:
|
|
294
|
+
"""Name of the object's last Geometry Nodes modifier (the one whose output the instances are)."""
|
|
295
|
+
return next(modifier.name for modifier in reversed(obj.modifiers) if modifier.type == "NODES")
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _realize_curve(obj) -> bpy.types.Object:
|
|
299
|
+
"""
|
|
300
|
+
A mesh object holding a non-mesh object's evaluated geometry with every instance realised, put in the
|
|
301
|
+
source's place (name, transform, parent, collections). The source is renamed with REPLACED_SOURCE_PREFIX
|
|
302
|
+
so every tool skips it.
|
|
303
|
+
"""
|
|
304
|
+
geometry_nodes.add_modifier(obj, geometry_nodes.realize_group(), name="Realize")
|
|
305
|
+
depsgraph = bpy.context.evaluated_depsgraph_get()
|
|
306
|
+
mesh = bpy.data.meshes.new_from_object(obj.evaluated_get(depsgraph), preserve_all_data_layers=True,
|
|
307
|
+
depsgraph=depsgraph)
|
|
308
|
+
name = obj.name
|
|
309
|
+
obj.name = f"{REPLACED_SOURCE_PREFIX}{name}"
|
|
310
|
+
replacement = bpy.data.objects.new(name, mesh)
|
|
311
|
+
for collection in obj.users_collection:
|
|
312
|
+
collection.objects.link(replacement)
|
|
313
|
+
replacement.parent = obj.parent
|
|
314
|
+
replacement.matrix_world = obj.matrix_world.copy()
|
|
315
|
+
mesh.name = name
|
|
316
|
+
return replacement
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def resolve_instances(objects: list, realize: bool, gpu_instances: bool, errors: list) -> tuple:
|
|
320
|
+
"""
|
|
321
|
+
Deals with Geometry Nodes instances, which an exporter silently drops (measured on 5.3.0: a scatter of
|
|
322
|
+
rocks on a ground exported only the ground's 200 triangles).
|
|
323
|
+
|
|
324
|
+
:param objects: The exported objects.
|
|
325
|
+
:param realize: Bake the instances into each object's mesh (curve objects get a mesh object in their place).
|
|
326
|
+
:param gpu_instances: Turn them into linked duplicates under a new parent (exported with them).
|
|
327
|
+
:param errors: List the gate failure is appended to when neither option is given.
|
|
328
|
+
:returns: (the objects to export, [{"object", "instances", "shipped"}]).
|
|
329
|
+
"""
|
|
330
|
+
bpy.context.view_layer.update()
|
|
331
|
+
exported, records = [], []
|
|
332
|
+
for obj in objects:
|
|
333
|
+
count = geometry_nodes.instance_count(obj) if obj.type in tool_common.GEOMETRY_TYPES else 0
|
|
334
|
+
if not count:
|
|
335
|
+
exported.append(obj)
|
|
336
|
+
continue
|
|
337
|
+
record = {"object": obj.name, "instances": count}
|
|
338
|
+
if realize:
|
|
339
|
+
record["shipped"] = "realized"
|
|
340
|
+
if obj.type == "MESH":
|
|
341
|
+
geometry_nodes.realize_to_mesh(obj)
|
|
342
|
+
exported.append(obj)
|
|
343
|
+
else:
|
|
344
|
+
exported.append(_realize_curve(obj))
|
|
345
|
+
elif gpu_instances:
|
|
346
|
+
shipped = geometry_nodes.instances_to_objects(obj, _last_nodes_modifier(obj))
|
|
347
|
+
parent = bpy.data.objects[shipped["parent"]]
|
|
348
|
+
record.update({"shipped": "gpu_instances", "parent": shipped["parent"], "meshes": shipped["meshes"]})
|
|
349
|
+
exported.extend([obj, parent] + list(parent.children))
|
|
350
|
+
else:
|
|
351
|
+
record["shipped"] = "dropped"
|
|
352
|
+
exported.append(obj)
|
|
353
|
+
errors.append(f"{obj.name}: {count} Geometry Nodes instances would be dropped (an exporter writes only "
|
|
354
|
+
"the object's own mesh); pass --realize or --gpu-instances")
|
|
355
|
+
records.append(record)
|
|
356
|
+
return exported, records
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def drop_meshless(objects: list, warnings: list) -> tuple:
|
|
360
|
+
"""
|
|
361
|
+
Leaves out geometry objects that evaluate to no vertices (an empty curve, a curve whose nodes only make
|
|
362
|
+
instances): an exporter writes nothing for them, and reading their mesh fails.
|
|
363
|
+
|
|
364
|
+
:returns: (the objects kept, [{"object", "type", "reason"}] of those left out).
|
|
365
|
+
"""
|
|
366
|
+
depsgraph = bpy.context.evaluated_depsgraph_get()
|
|
367
|
+
kept, skipped = [], []
|
|
368
|
+
for obj in objects:
|
|
369
|
+
if obj.type in tool_common.GEOMETRY_TYPES and _evaluated_mesh_size(obj, depsgraph) is None:
|
|
370
|
+
skipped.append({"object": obj.name, "type": obj.type, "reason": "evaluates to no mesh"})
|
|
371
|
+
warnings.append(f"{obj.name} ({obj.type}) evaluates to no mesh and was not exported")
|
|
372
|
+
continue
|
|
373
|
+
kept.append(obj)
|
|
374
|
+
return kept, skipped
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def fbx_settings(source: str, has_armature: bool, animated: bool) -> tuple:
|
|
378
|
+
"""
|
|
379
|
+
The Unity FBX settings for one export, by the guide's section 8.2a case table.
|
|
380
|
+
|
|
381
|
+
:param source: "blender" or "unity" (an FBX that came out of the Unity project).
|
|
382
|
+
:param has_armature: An armature is exported.
|
|
383
|
+
:param animated: Something exported carries an action or NLA strip.
|
|
384
|
+
:returns: (settings, the reason bake_space_transform was chosen).
|
|
385
|
+
"""
|
|
386
|
+
if has_armature:
|
|
387
|
+
settings = dict(rigging_tools.UNITY_FBX_RIG_SETTINGS, bake_anim=animated)
|
|
388
|
+
return settings, "armature: baking the space transform is broken for rigs (the armature node keeps -90 X)"
|
|
389
|
+
if animated:
|
|
390
|
+
settings = dict(UNITY_FBX_SETTINGS, bake_space_transform=False, bake_anim=True,
|
|
391
|
+
**rigging_tools.UNITY_FBX_SCENE_TAKE)
|
|
392
|
+
return settings, "animation: never baked; one scene take over the scene's frame range"
|
|
393
|
+
if source == "unity":
|
|
394
|
+
settings = dict(UNITY_FBX_SETTINGS, bake_space_transform=False, bake_anim=False)
|
|
395
|
+
return settings, "came from Unity: the axis conversion is already in the objects (baking adds +90 X)"
|
|
396
|
+
settings = dict(UNITY_FBX_SETTINGS, bake_anim=False)
|
|
397
|
+
return settings, "static mesh built in Blender: baked, so Unity reads 0 degrees on every root node"
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def gltf_settings(output_format: str, has_armature: bool, tangents: bool, options) -> dict:
|
|
401
|
+
"""
|
|
402
|
+
The glTF settings for one export: a rig gets rigging_tools.GLTF_RIG_SETTINGS (NLA tracks, 4 influences,
|
|
403
|
+
the Armature modifier kept as the skin), anything else modifiers applied; plus tangents, compression,
|
|
404
|
+
WebP textures and GPU instancing as asked.
|
|
405
|
+
|
|
406
|
+
:param output_format: "glb" or "gltf".
|
|
407
|
+
:param has_armature: An armature is exported.
|
|
408
|
+
:param tangents: Write tangents.
|
|
409
|
+
:param options: Parsed options (draco, meshopt, webp, gpu_instances).
|
|
410
|
+
:returns: The exporter keyword arguments.
|
|
411
|
+
"""
|
|
412
|
+
settings = dict(rigging_tools.GLTF_RIG_SETTINGS) if has_armature else {"export_apply": True, "export_yup": True}
|
|
413
|
+
settings.update({"export_format": "GLB" if output_format == "glb" else "GLTF_SEPARATE", "use_selection": True,
|
|
414
|
+
"export_tangents": tangents})
|
|
415
|
+
if options.draco is not None:
|
|
416
|
+
settings.update({"export_draco_mesh_compression_enable": True,
|
|
417
|
+
"export_draco_mesh_compression_level": options.draco})
|
|
418
|
+
if options.meshopt:
|
|
419
|
+
settings.update({"export_meshopt_compression_enable": True, "export_meshopt_extension": MESHOPT_EXTENSION})
|
|
420
|
+
if options.webp:
|
|
421
|
+
settings["export_image_format"] = "WEBP"
|
|
422
|
+
if options.gpu_instances:
|
|
423
|
+
settings["export_gpu_instances"] = True
|
|
424
|
+
return settings
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def export_file(path: str, output_format: str, objects: list, tangents: bool, warnings: list,
|
|
428
|
+
settings: dict = None) -> dict:
|
|
429
|
+
"""
|
|
430
|
+
Runs the exporter on the selected objects.
|
|
431
|
+
|
|
432
|
+
:param path: Output path.
|
|
433
|
+
:param output_format: glb, gltf or fbx.
|
|
434
|
+
:param objects: The exported objects (already selected).
|
|
435
|
+
:param tangents: glTF: write tangents (used when no settings are given).
|
|
436
|
+
:param warnings: List to append warnings to.
|
|
437
|
+
:param settings: Exporter keyword arguments (fbx_settings / gltf_settings); None gives the static,
|
|
438
|
+
Blender-authored defaults.
|
|
439
|
+
:returns: The settings used.
|
|
440
|
+
:raises RuntimeError: when the exporter does not finish.
|
|
441
|
+
"""
|
|
442
|
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
443
|
+
if output_format == "fbx":
|
|
444
|
+
settings = settings or dict(fbx_settings("blender", _has_armature(objects), _is_animated(objects))[0],
|
|
445
|
+
use_selection=True)
|
|
446
|
+
if _has_armature(objects):
|
|
447
|
+
warnings.append("armature exported: check the Unity rig (Rig > Animation Type) and that no leaf bones "
|
|
448
|
+
"or root offset appear after import")
|
|
449
|
+
outcome = bpy.ops.export_scene.fbx(filepath=path, **settings)
|
|
450
|
+
else:
|
|
451
|
+
settings = settings or {"export_format": "GLB" if output_format == "glb" else "GLTF_SEPARATE",
|
|
452
|
+
"use_selection": True, "export_apply": True, "export_tangents": tangents,
|
|
453
|
+
"export_yup": True}
|
|
454
|
+
outcome = bpy.ops.export_scene.gltf(filepath=path, **settings)
|
|
455
|
+
if "FINISHED" not in outcome:
|
|
456
|
+
raise RuntimeError(f"export did not finish: {outcome}")
|
|
457
|
+
return settings
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def roundtrip(path: str, source_size: list, quantization_share: float = 0.0) -> dict:
|
|
461
|
+
"""
|
|
462
|
+
Re-imports the export into an empty scene and compares its world size with the source.
|
|
463
|
+
|
|
464
|
+
:param path: The exported file.
|
|
465
|
+
:param source_size: World size before export.
|
|
466
|
+
:param quantization_share: Extra allowance for compressed (quantised) geometry, as a share of the
|
|
467
|
+
largest size (QUANTIZATION_TOLERANCE_SHARE); 0 for an uncompressed file.
|
|
468
|
+
:returns: {"source_size_m", "reimported_size_m", "quantization_tolerance_m", "ok"}.
|
|
469
|
+
"""
|
|
470
|
+
tool_common.load_model(path)
|
|
471
|
+
reimported = world_size([obj for obj in bpy.context.scene.objects if obj.type in tool_common.GEOMETRY_TYPES])
|
|
472
|
+
differences = [abs(first - second) for first, second in zip(source_size, reimported)]
|
|
473
|
+
quantization = quantization_share * max(source_size)
|
|
474
|
+
allowed = [max(ROUNDTRIP_ABSOLUTE_TOLERANCE, abs(size) * ROUNDTRIP_RELATIVE_TOLERANCE, quantization)
|
|
475
|
+
for size in source_size]
|
|
476
|
+
return {"source_size_m": source_size, "reimported_size_m": reimported,
|
|
477
|
+
"quantization_tolerance_m": round(quantization, 6),
|
|
478
|
+
"ok": all(difference <= limit for difference, limit in zip(differences, allowed))}
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
def _quantization_share(options) -> float:
|
|
482
|
+
"""The round-trip allowance for the geometry compression asked for (0 without compression)."""
|
|
483
|
+
if options.draco is not None:
|
|
484
|
+
return QUANTIZATION_TOLERANCE_SHARE["draco"]
|
|
485
|
+
if options.meshopt:
|
|
486
|
+
return QUANTIZATION_TOLERANCE_SHARE["meshopt"]
|
|
487
|
+
return 0.0
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
def read_gltf_json(path: str) -> dict:
|
|
491
|
+
"""
|
|
492
|
+
The JSON document of a .glb (its first chunk) or a .gltf.
|
|
493
|
+
|
|
494
|
+
:raises ValueError: for a GLB without a JSON chunk.
|
|
495
|
+
"""
|
|
496
|
+
with open(path, "rb") as handle:
|
|
497
|
+
data = handle.read()
|
|
498
|
+
if not data.startswith(GLB_MAGIC):
|
|
499
|
+
return json.loads(data.decode("utf-8"))
|
|
500
|
+
length, chunk_type = struct.unpack_from("<II", data, GLB_HEADER_BYTES)
|
|
501
|
+
if chunk_type != GLB_JSON_CHUNK:
|
|
502
|
+
raise ValueError(f"{path}: first GLB chunk is not JSON")
|
|
503
|
+
start = GLB_HEADER_BYTES + GLB_CHUNK_HEADER_BYTES
|
|
504
|
+
return json.loads(data[start:start + length].decode("utf-8"))
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
def _primitive_triangles(primitive: dict, accessors: list) -> int:
|
|
508
|
+
"""Triangles one primitive draws (0 for points and lines)."""
|
|
509
|
+
if primitive.get("mode", TRIANGLES_MODE) != TRIANGLES_MODE:
|
|
510
|
+
return 0
|
|
511
|
+
index = primitive.get("indices")
|
|
512
|
+
source = accessors[index] if index is not None else accessors[primitive["attributes"]["POSITION"]]
|
|
513
|
+
return source["count"] // INDICES_PER_TRIANGLE
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
def summarise_gltf(path: str) -> dict:
|
|
517
|
+
"""Counts and features of a glTF document (what an engine will receive)."""
|
|
518
|
+
document = read_gltf_json(path)
|
|
519
|
+
accessors = document.get("accessors", [])
|
|
520
|
+
triangles, attributes, primitives = 0, set(), 0
|
|
521
|
+
for mesh in document.get("meshes", []):
|
|
522
|
+
for primitive in mesh.get("primitives", []):
|
|
523
|
+
primitives += 1
|
|
524
|
+
attributes.update(primitive.get("attributes", {}))
|
|
525
|
+
triangles += _primitive_triangles(primitive, accessors)
|
|
526
|
+
return {"bytes": os.path.getsize(path), "nodes": len(document.get("nodes", [])),
|
|
527
|
+
"meshes": len(document.get("meshes", [])), "primitives": primitives, "triangles": triangles,
|
|
528
|
+
"materials": len(document.get("materials", [])), "textures": len(document.get("textures", [])),
|
|
529
|
+
"images": [image.get("mimeType") or os.path.splitext(image.get("uri", ""))[1]
|
|
530
|
+
for image in document.get("images", [])],
|
|
531
|
+
"attributes": sorted(attributes), "animations": len(document.get("animations", [])),
|
|
532
|
+
"skins": len(document.get("skins", [])), "extensions_used": document.get("extensionsUsed", []),
|
|
533
|
+
"generator": document.get("asset", {}).get("generator")}
|
|
534
|
+
|
|
535
|
+
|
|
536
|
+
def validate(path: str, validator_directory) -> dict:
|
|
537
|
+
"""
|
|
538
|
+
Runs the Khronos glTF-Validator through validate_gltf.mjs.
|
|
539
|
+
|
|
540
|
+
:returns: The validator's JSON result, or {"skipped": True, "reason"} when it cannot run.
|
|
541
|
+
"""
|
|
542
|
+
node = shutil.which("node")
|
|
543
|
+
if node is None:
|
|
544
|
+
return {"skipped": True, "reason": "Node.js is not on PATH; install Node 18+ and run "
|
|
545
|
+
"`npm install --prefix <bt-blender>/scripts gltf-validator`, then re-export"}
|
|
546
|
+
command = [node, VALIDATOR_SCRIPT, path]
|
|
547
|
+
if validator_directory:
|
|
548
|
+
command += ["--validator-dir", validator_directory]
|
|
549
|
+
completed = subprocess.run(command, capture_output=True, text=True, timeout=VALIDATOR_TIMEOUT_SECONDS)
|
|
550
|
+
lines = [line for line in completed.stdout.splitlines() if line.strip().startswith("{")]
|
|
551
|
+
if not lines:
|
|
552
|
+
return {"skipped": True, "reason": f"validator produced no result (exit {completed.returncode}): "
|
|
553
|
+
f"{completed.stderr.strip()[-STDERR_TAIL_CHARACTERS:]}"}
|
|
554
|
+
return json.loads(lines[-1])
|
|
555
|
+
|
|
556
|
+
|
|
557
|
+
def _output_format(options) -> tuple:
|
|
558
|
+
"""(absolute output path, format) from --out and --format, checking that they agree."""
|
|
559
|
+
out = os.path.abspath(options.out)
|
|
560
|
+
extension = os.path.splitext(out)[1].lower()
|
|
561
|
+
output_format = options.format or next((name for name, suffix in FORMAT_EXTENSIONS.items() if suffix == extension), None)
|
|
562
|
+
if output_format is None:
|
|
563
|
+
raise tool_common.OptionsError(f"cannot tell the format from '{extension}'; pass --format")
|
|
564
|
+
if extension != FORMAT_EXTENSIONS[output_format]:
|
|
565
|
+
raise tool_common.OptionsError(f"--out must end in {FORMAT_EXTENSIONS[output_format]} for --format {output_format}")
|
|
566
|
+
if output_format == "fbx" and (options.draco is not None or options.meshopt or options.webp):
|
|
567
|
+
raise tool_common.OptionsError("--draco, --meshopt and --webp are glTF options; FBX has no such compression")
|
|
568
|
+
return out, output_format
|
|
569
|
+
|
|
570
|
+
|
|
571
|
+
def run(options) -> dict:
|
|
572
|
+
"""
|
|
573
|
+
Exports, re-imports and validates the asset.
|
|
574
|
+
|
|
575
|
+
:param options: Parsed options.
|
|
576
|
+
:returns: The export report.
|
|
577
|
+
"""
|
|
578
|
+
out, output_format = _output_format(options)
|
|
579
|
+
tool_common.load_model(options.model)
|
|
580
|
+
warnings, errors = [], []
|
|
581
|
+
objects, instances = resolve_instances(export_objects(options.objects), options.realize,
|
|
582
|
+
options.gpu_instances, errors)
|
|
583
|
+
objects, skipped = drop_meshless(objects, warnings)
|
|
584
|
+
if not objects:
|
|
585
|
+
raise ValueError("nothing left to export: every object evaluates to no mesh")
|
|
586
|
+
_select(objects)
|
|
587
|
+
is_gltf = output_format != "fbx"
|
|
588
|
+
has_armature, animated = _has_armature(objects), _is_animated(objects)
|
|
589
|
+
converted = convert_float_images(objects) if is_gltf and not options.no_convert_images else []
|
|
590
|
+
tangents = options.tangents == "on" or (options.tangents == "auto" and has_normal_map(objects))
|
|
591
|
+
if is_gltf:
|
|
592
|
+
settings, reason = gltf_settings(output_format, has_armature, tangents, options), None
|
|
593
|
+
else:
|
|
594
|
+
settings, reason = fbx_settings(options.source, has_armature, animated)
|
|
595
|
+
settings["use_selection"] = True
|
|
596
|
+
source_size = world_size(objects)
|
|
597
|
+
settings = export_file(out, output_format, objects, tangents, warnings, settings)
|
|
598
|
+
report = {"file": out, "format": output_format, "source": options.source, "objects": [obj.name for obj in objects],
|
|
599
|
+
"rig": has_armature, "animated": animated, "settings": settings, "converted_images": converted,
|
|
600
|
+
"instances": instances, "skipped_objects": skipped, "warnings": warnings}
|
|
601
|
+
if reason:
|
|
602
|
+
report["bake_space_transform_reason"] = reason
|
|
603
|
+
if is_gltf:
|
|
604
|
+
report["summary"] = summarise_gltf(out)
|
|
605
|
+
if not options.no_roundtrip:
|
|
606
|
+
report["roundtrip"] = roundtrip(out, source_size, _quantization_share(options) if is_gltf else 0.0)
|
|
607
|
+
if not report["roundtrip"]["ok"]:
|
|
608
|
+
errors.append(f"re-imported size {report['roundtrip']['reimported_size_m']} differs from the "
|
|
609
|
+
f"source {source_size}: check axis and unit settings")
|
|
610
|
+
if is_gltf and not options.no_validate:
|
|
611
|
+
report["validation"] = validate(out, options.validator_dir)
|
|
612
|
+
if report["validation"].get("skipped"):
|
|
613
|
+
warnings.append(f"glTF validation skipped: {report['validation'].get('reason')}")
|
|
614
|
+
elif report["validation"].get("errors", 0) > 0 or report["validation"].get("ok") is False:
|
|
615
|
+
errors.append(f"glTF-Validator: {report['validation'].get('errors')} error(s); see validation.issues")
|
|
616
|
+
report["errors"] = errors
|
|
617
|
+
report["pass"] = not errors
|
|
618
|
+
report["report_json"] = tool_common.write_json(options.report or os.path.splitext(out)[0] + ".export.json", report)
|
|
619
|
+
return report
|
|
620
|
+
|
|
621
|
+
|
|
622
|
+
if __name__ == "__main__":
|
|
623
|
+
tool_common.run_tool(TOOL_NAME, build_parser(), run)
|