perf: batch Cesium export mesh preparation

This commit is contained in:
que01 committed 2026-09-17 17:12:42 +08:00
1 parent a4dfbf884a
commit c6cce44f60
12 files changed
+632 -11

No files matched your search

+138 -11
View File
@@ -496,6 +496,14 @@ def make_export_material(material):
return result
def select_only(obj):
"""Change selection without an operator's scene-evaluation barriers."""
for selected in bpy.context.selected_objects:
selected.select_set(False)
obj.select_set(True)
bpy.context.view_layer.objects.active = obj
def unwrap_mesh(obj):
if obj.type != "MESH" or not obj.data.polygons:
return
@@ -504,23 +512,19 @@ def unwrap_mesh(obj):
# meshes arrive without a UV layer, so that is the reliable discriminator.
if obj.data.uv_layers:
return
bpy.ops.object.select_all(action="DESELECT")
obj.select_set(True)
bpy.context.view_layer.objects.active = obj
select_only(obj)
bpy.ops.object.mode_set(mode="EDIT")
bpy.ops.mesh.select_all(action="SELECT")
try:
bpy.ops.mesh.select_all(action="SELECT")
bpy.ops.uv.smart_project(island_margin=0.025, area_weight=0.0)
finally:
bpy.ops.object.mode_set(mode="OBJECT")
def apply_mesh_modifiers(obj):
if obj.type != "MESH":
if obj.type != "MESH" or not obj.modifiers:
return
bpy.ops.object.select_all(action="DESELECT")
obj.select_set(True)
bpy.context.view_layer.objects.active = obj
select_only(obj)
for modifier in list(obj.modifiers):
try:
bpy.ops.object.modifier_apply(modifier=modifier.name)
@@ -528,6 +532,11 @@ def apply_mesh_modifiers(obj):
pass
def mesh_has_multiple_users(mesh):
# modifier_apply uses ID_REAL_USERS, excluding the fake retention user.
return mesh.users - int(mesh.use_fake_user) > 1
def triangulate_mesh(obj):
"""Split n-gons into triangles ahead of the exporter.
@@ -544,11 +553,14 @@ def triangulate_mesh(obj):
"""
if obj.type != "MESH" or not obj.data.polygons:
return
# modifier_apply rejects multi-user data before evaluating geometry. Avoid
# creating a modifier and evaluating the whole scene only to remove it in
# the failure handler below; keeping this mesh unchanged is intentional.
if mesh_has_multiple_users(obj.data):
return
if all(len(polygon.vertices) <= 3 for polygon in obj.data.polygons):
return
bpy.ops.object.select_all(action="DESELECT")
obj.select_set(True)
bpy.context.view_layer.objects.active = obj
select_only(obj)
modifier = obj.modifiers.new("ExportTriangulate", "TRIANGULATE")
modifier.min_vertices = 4
try:
@@ -559,6 +571,120 @@ def triangulate_mesh(obj):
obj.modifiers.remove(modifier)
def batch_triangulate_meshes(candidates):
"""Evaluate independent Triangulate modifiers in one dependency graph pass.
This uses the actual modifier (including the running Blender version's
defaults), not a BMesh reimplementation. new_from_object on an evaluated
object copies its final geometry; preserve_all_data_layers retains UVs and
other mesh attributes. Stage every result before editing original objects:
assigning data or removing a modifier invalidates evaluated state.
Existing stacks can depend on other objects' unmodified geometry. Leave
their sequential application order untouched, including stacks outside the
export subset. Multi-user meshes, shape keys and custom normals retain the
original operator path, whose restrictions are part of the export behavior.
"""
if any(obj.modifiers for obj in bpy.context.scene.objects):
return
pending = []
for obj in candidates:
mesh = obj.data
if (mesh.users != 1 or mesh.use_fake_user or mesh.shape_keys
or mesh.has_custom_normals or mesh.library or obj.library
or not any(len(p.vertices) > 3 for p in mesh.polygons)):
continue
modifier = obj.modifiers.new("ExportTriangulate", "TRIANGULATE")
modifier.min_vertices = 4
pending.append((obj, mesh, modifier))
if not pending:
return
staged = []
try:
# evaluated_get itself does not update the graph. This explicit barrier
# is required after adding all modifiers, and is intentionally not
# repeated for each object.
depsgraph = bpy.context.evaluated_depsgraph_get()
depsgraph.update()
for obj, source, modifier in pending:
mesh = bpy.data.meshes.new_from_object(
obj.evaluated_get(depsgraph), preserve_all_data_layers=True,
depsgraph=depsgraph)
staged.append((obj, source, modifier, mesh))
for key in source.keys():
mesh[key] = source[key]
except Exception:
for _, _, _, mesh in staged:
bpy.data.meshes.remove(mesh)
for obj, _, modifier in pending:
obj.modifiers.remove(modifier)
raise
for obj, source, modifier, mesh in staged:
name = source.name
obj.data = mesh
obj.modifiers.remove(modifier)
bpy.data.meshes.remove(source)
mesh.name = name
def unwrap_meshes_in_work_scene(candidates):
"""Run the unchanged per-object UV operator against a small scene.
UV projection operates on the original mesh in edit mode, not evaluated
scene geometry. Link the original object into a temporary scene one at a
time so operator barriers do not reevaluate every unrelated scene object.
Switch the window's scene, not just context object overrides: edit-mode
operators require a consistent window/scene/view-layer context.
"""
window = bpy.context.window
if window is None or any(obj.modifiers for obj in bpy.context.scene.objects):
return
# A later fallback triangulation must precede UV projection. Shared meshes
# are also safe here: modifier_apply refuses them, so their topology stays
# unchanged in the original preparation loop.
pending = [obj for obj in candidates if not obj.modifiers
and not obj.data.uv_layers and obj.data.polygons
and (mesh_has_multiple_users(obj.data)
or all(len(p.vertices) <= 3 for p in obj.data.polygons))]
if not pending:
return
original_scene = window.scene
original_layer = window.view_layer
work_scene = bpy.data.scenes.new("Cesium UV work scene")
try:
window.scene = work_scene
for obj in pending:
# Shared mesh UVs are already prepared by their first instance.
if obj.data.uv_layers:
continue
work_scene.collection.objects.link(obj)
try:
unwrap_mesh(obj)
finally:
work_scene.collection.objects.unlink(obj)
finally:
window.scene = original_scene
window.view_layer = original_layer
bpy.data.scenes.remove(work_scene)
def prepare_independent_meshes(candidates):
"""Keep dependency-bearing modifier stacks on the sequential legacy path."""
# Bevel reads this object's geometry and vertex groups. Unlike Boolean,
# Shrinkwrap or Geometry Nodes it cannot read another object's mesh. Apply
# it with the original operator before batching independent triangulation.
# Unknown stack types deliberately keep the original preparation order.
if any(modifier.type != "BEVEL"
for obj in bpy.context.scene.objects for modifier in obj.modifiers):
return
for obj in candidates:
apply_mesh_modifiers(obj)
batch_triangulate_meshes(candidates)
unwrap_meshes_in_work_scene(candidates)
def export_glb(filepath, meshes):
"""Export a prepared object subset without changing authoring visibility."""
bpy.ops.object.select_all(action="DESELECT")
@@ -654,6 +780,7 @@ def export(args):
and not obj.hide_viewport and not obj.hide_render]
total_candidates = max(1, len(candidates))
progress.update("prepare scene", 3, "%d mesh objects" % len(candidates))
prepare_independent_meshes(candidates)
for index, obj in enumerate(candidates, 1):
if any(c.name == "06_TrafficSignalsDynamic" for c in obj.users_collection):
groups = {slot.material.name for slot in obj.material_slots if slot.material}