Files
osmWorkflow/.trellis/tasks/09-17-cesium-export-performance/research/triangulation-semantics.md
T

7.6 KiB

Research: Triangulation semantics and output-preserving optimization

  • Query: Explain the temporary direct-BMesh experiment's different GLB vertex counts and identify source-backed faster alternatives.
  • Scope: mixed (project source, installed exporter, official Blender 4.5.0 source)
  • Date: 2026-09-17

Findings

Confirmed algorithm mismatch in the experiment

blender/export_cesium.py:531 creates a Triangulate modifier and only overrides min_vertices = 4. The temporary /private/tmp/cesium-profile.9ODFNa/profile_export.py:42 instead passes quad_method='BEAUTY', ngon_method='BEAUTY' to BMesh.

Blender 4.5.0 source/blender/makesdna/DNA_modifier_defaults.h:643-649 defines the modifier defaults as:

flag = 0
quad_method = MOD_TRIANGULATE_QUAD_SHORTEDGE
ngon_method = MOD_TRIANGULATE_NGON_BEAUTY
min_vertices = 4

Thus the experiment is not algorithm-equivalent: quads use shortest diagonal in the baseline and beauty in the experiment. This is a concrete reason to correct the experiment, not speculative parameter tuning. Do not rely on older Blender documentation's defaults; read a temporary modifier's RNA properties on the actual running version if supporting multiple Blender versions.

Both routes ultimately call BM_mesh_triangulate (official MOD_triangulate.cc, bmo_triangulate.cc:29-44). The modifier passes tag_only=false; the BMesh operator tags its supplied faces and passes tag_only=true. Supplying all eligible faces and matching quad/ngon methods aligns the core algorithm.

Why GLB vertex counts can differ with equal triangles

Installed /Applications/Blender.app/Contents/Resources/4.5/scripts/addons_core/io_scene_gltf2/blender/exp/primitive_extract.py:336-344 explicitly explains that Blender corner attributes are packed into per-vertex records for glTF. Deduplication at lines 825 and 900-901 uses the attribute record, not position alone. Normals, tangents and UV discontinuities therefore split vertices without changing triangle count. Changing the quad diagonal can change subsequent normals and UV unwrap even when all positions and triangle totals remain unchanged.

Project preparation order (blender/export_cesium.py:670-676) is triangulate then unwrap. Hence changing topology before smart_project can also change UV islands. Counts alone do not establish visual parity or identify which attribute actually changed in the existing artifacts; inspect decoded attribute arrays per mesh to attribute the observed count difference definitively.

Remaining BMesh conversion differences

Official MOD_triangulate.cc sets calc_face_normal=true, calc_vert_normal=false and carries original-index custom-data masks through conversion. Python BMesh.from_mesh (bmesh_py_types.cc:1376-1414) defaults both normal flags to true; pass face_normals=True, vertex_normals=False to match the modifier's inputs more closely.

Modifier flag=0 means keep_custom_normals is false by default in 4.5.0. Therefore do not claim custom-normal preservation is the established reason for this scene's discrepancy. If enabled, the modifier explicitly copies evaluated corner normals into a temporary CD_NORMAL layer and restores normalized custom normals after triangulation. Direct BMesh does not reproduce that explicit procedure automatically.

Python BMesh.to_mesh (bmesh_py_types.cc:1201-1240) uses BM_mesh_bm_to_me, updates shape-key indices/object remaps and tags geometry dirty; modifier output uses BKE_mesh_from_bmesh_for_eval_nomain. These are distinct conversion paths. Matching triangulation settings does not constitute a proof of byte-identical mesh output, ordering or custom data. Preserve the baseline fallback for multi-user meshes (modifier_apply refuses them); do not change shared topology as a performance side effect.

Strongest semantic route: keep the actual modifier, batch evaluation

For simple single-user meshes without pre-existing modifiers or shape keys, add the same Triangulate modifier through the data API for all eligible objects, evaluate the dependency graph once, then obtain persistent meshes with bpy.data.meshes.new_from_object(obj.evaluated_get(depsgraph), preserve_all_data_layers=True, depsgraph=depsgraph). Stage every result before replacing source data/removing modifiers, because mutation can invalidate evaluated state. This executes the actual modifier implementation instead of duplicating it in Python.

Official rna_main_api.cc:1103-1123 says an original object produces undeformed geometry while an evaluated object produces final geometry with all modifiers; preserving all data layers requires a dependency graph. Official rna_ID.cc:2447-2452 says evaluated_get only retrieves the last evaluation and does not ensure the graph is up to date. An explicit graph evaluation barrier after adding modifiers is mandatory; repeated evaluation per object defeats the optimization.

Limit this fast path to proven equivalent cases. Existing modifier stacks, hidden modifiers, failing modifiers, shape keys, shared meshes and inter-object dependencies are not generally equivalent to the current sequential modifier_apply loop. Keep the existing operator fallback for those cases until separately justified. New datablocks must preserve material slots, required custom properties and semantic names; parity must detect unintended instance splitting or GLB naming differences.

  1. Correct the demonstrated quad-method mismatch before drawing conclusions from direct-BMesh measurements.
  2. Prefer batched evaluation of the original modifier if exact parity remains the requirement; its geometric semantics have a stronger equivalence basis.
  3. Keep graph updates at real dependency boundaries; never ship the temporary global _view_layer_update monkey patch.
  4. Require decoded triangle attributes and existing project structure parity, including UVs/normals/tangents and dynamic/shared assets. Do not accept matching counts as sufficient evidence.

Files found

  • blender/export_cesium.py — preparation order and baseline modifier/UV operations.
  • /private/tmp/cesium-profile.9ODFNa/profile_export.py — temporary monkey-patch and direct-BMesh experiment.
  • /Applications/Blender.app/Contents/Resources/4.5/scripts/addons_core/io_scene_gltf2/blender/exp/primitive_extract.py — glTF corner-attribute splitting and deduplication.

External references

All source references pinned to Blender v4.5.0:

  • .trellis/spec/blender/index.md — Blender/standard-Python boundary and parity requirements.
  • .trellis/spec/blender/asset-generation.md — deterministic geometry, shared meshes and dynamic export assets.
  • .trellis/spec/blender/testing.md — mathematical expectations and real Blender parity.

Caveats / Not Found

  • Research only: no Blender runs or changes to product code were performed.
  • The algorithm mismatch is proven from source; the exact per-attribute cause of every previously observed vertex-count change is not measured here.
  • Batch evaluated-mesh conversion is a source-backed candidate, not a claim of verified output parity or measured speedup.