@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,544 @@
1
+ # Sculpting and retopology: headless detail, remeshing, retopology routes, edge flow, baking and seam proof
2
+
3
+ **Load this when** a model needs organic detail (skin, scales, folds, wear) or a high poly turned into a game
4
+ mesh: remeshing a blockout or a generated mesh, retopologising a sculpt to a budget, building LODs, and baking
5
+ high-to-low normal and AO maps with proof that the seams will not show in an engine.
6
+
7
+ **What it assumes.** The Agent Reference's Blender guide (`references/unity-blender-cli.md`) covers the basics:
8
+ §8.4a for the bake traps, the pre-bake checklist, the artefact table and PBR sanity values; §5 for weld and
9
+ decimate with custom normals; §8.4b for measuring against references. `characters-and-creatures.md` covers
10
+ bodies and their blockouts; `hard-surface.md` covers mechanical high-to-low and weighted normals. This file goes
11
+ deeper on what headless Blender can do for organic detail and topology, and on proving a bake.
12
+
13
+ **Helpers.** `scripts/blender/retopology_tools.py` provides:
14
+ - detail: `multires_subdivide`, `multires_reshape`, `displace`, `height_image`;
15
+ - remeshing: `voxel_remesh`, `quadriflow`, `decimate_to`;
16
+ - retopology: `shrinkwrap_fit`, `relax`;
17
+ - measurement: `triangle_count`, `manifold_report`, `topology_report`, `surface_deviation`;
18
+ - baking and its proof: `bake_high_to_low`, `normal_map_stats`, `normal_seam_report`.
19
+
20
+ Every recipe below is a complete script. Run it with
21
+ `node <skill>/scripts/bt-blender.mjs run recipe.py <out folder>`.
22
+
23
+ ---
24
+
25
+ ## 1. The professional workflow, and what runs headless
26
+
27
+ | Stage | Studio practice | Headless here | Hand-off |
28
+ |---|---|---|---|
29
+ | Base | ZSpheres / Skin / box model, then dynamic topology or voxel remesh | `skin_blockout`, `metaball_blockout`, `sdf_inflate`, `voxel_remesh` | |
30
+ | Primary and secondary forms | Brush sculpting at increasing multires levels | Shape from the chart and radii; `displace` with masks; shape keys from offsets | Expressive anatomy and likeness need a sculptor |
31
+ | Tertiary detail (pores, scales, fabric) | Alphas, stencils, noise brushes | `displace` with procedural textures (LOCAL coordinates) or height images (UV) on multires | |
32
+ | Retopology | Quad Draw / Poly Build / snapping, 16-80 h per character (80.lv) | `quadriflow`, Skin cage + `shrinkwrap_fit`, `decimate_to` for non-deforming LODs | Hero faces and shoulders: hand-placed loops |
33
+ | UVs | Seams on hard edges and hidden areas | `smart_unwrap`, or bt-unwrap | |
34
+ | Bake | Marmoset / Substance / Blender, cage tuned by eye | `bake_high_to_low` with a measured extrusion | |
35
+ | Proof | Look at it lit in the engine | `normal_map_stats`, `normal_seam_report`, `review-render` | |
36
+
37
+ **Measured in Blender 5.3.0 `--background`:**
38
+
39
+ | Operation | Headless result |
40
+ |---|---|
41
+ | Sculpt-mode operators (`sculpt.mesh_filter` and brushes) | **Crash**: SIGSEGV, exit 139, in `sculpt_paint::undo::push_begin_ex`. Do not enter sculpt mode headless |
42
+ | `object.multires_subdivide` (3 levels), `object.multires_reshape` | FINISHED; 4.6k triangles to about 300k in 1.1 s with the displacement |
43
+ | Displace modifier, procedural (Voronoi, LOCAL) and image (UV), masked by vertex groups | Works; 148k-vertex detail in about 1 s |
44
+ | Voxel remesh (`object.voxel_remesh`) | Works; 54k triangles in 0.04 s at 1 cm on a 1.75 m figure |
45
+ | QuadriFlow (`object.quadriflow_remesh`) | Works with caveats (section 3): about 0.6 s at a 5k budget |
46
+ | Cycles selected-to-active bake | Works on CPU; 1024 normal map in 0.3 s |
47
+
48
+ ---
49
+
50
+ ## 2. Headless detail: what replaces the brush
51
+
52
+ - **Multires is the container.** Subdivide the retopologised (or QuadriFlow) base 2-4 levels, build the detail
53
+ on a copy with the same topology as the top level, and `multires_reshape` it in. The base stays the game mesh
54
+ and the top level is the bake source. Every level multiplies the faces by 4.
55
+ - **Displace is the brush.** `displacement = (texture value - mid level) x strength` along the normal.
56
+ - Procedural textures (Voronoi scales, Clouds noise, Musgrave-like ridges) use LOCAL or OBJECT coordinates:
57
+ no UV seams.
58
+ - Image height maps use UV coordinates. The modifier takes the first face it meets for a vertex, so a UV seam
59
+ can show a step: keep displacement images seam-aware (tile them, or keep detail away from seams).
60
+ - Height images can come from anywhere: generated with numpy (`height_image`), painted, scanned, or produced
61
+ by an image model. Store them as float, Non-Color.
62
+ - **Vertex groups are the mask.** A region's group (by height band, by bone weights, by distance to a point,
63
+ by a curvature measure) limits where the detail goes, as a masked stroke would.
64
+ - **Shape keys are the layers.** Large form changes (a heavier jaw, a bigger belly) as keys from offsets
65
+ (`rigging_tools.add_shape_key`), mixed and applied, keep each change separate and reversible.
66
+ - **Geometry Nodes** (Displace Geometry node, Blender 5.0+; Set Position with an Image Texture fed the UV
67
+ attribute) do the same on the evaluated mesh. Not measured here.
68
+ - **Multires baking** still exists for a multires-only workflow: `scene.render.bake.use_multires` with
69
+ `.type` NORMALS, DISPLACEMENT or VECTOR_DISPLACEMENT (Blender 5.0+ API; it compares the viewport level, which
70
+ must be 0, with the render level). Selected-to-active (section 6) is more flexible and is what is tested here.
71
+
72
+ ### Recipe: multires detail from masked procedural and image displacement
73
+
74
+ ```python
75
+ """Headless sculpt detail: a 5k-triangle base gets three Multires levels, and the top level is filled from a
76
+ displaced copy - procedural Voronoi scales masked to the torso, and an image height map (generated ridges)
77
+ on UVs masked to the legs. Saves sculpt.blend with the Multires stack live, ready to bake."""
78
+ import json
79
+ import math
80
+ import os
81
+ import sys
82
+ import time
83
+
84
+ import bpy
85
+ import numpy as np
86
+
87
+ import character_blockout as blockout
88
+ import construction_kit as kit
89
+ import retopology_tools as retopo
90
+
91
+ out_folder = sys.argv[sys.argv.index("--") + 1]
92
+ HEIGHT = 1.75
93
+ LEVELS = 3 # 3 levels: 4.6k triangles -> about 300k at the top
94
+ SCALE_SIZE = 0.03 # Voronoi cell size, metres
95
+ SCALE_DEPTH = 0.006 # metres at full texture value
96
+ RIDGE_COUNT = 24 # ridges across the UV height of the image
97
+ RIDGE_DEPTH = 0.004
98
+ HEIGHT_MAP_SIZE = 256
99
+ TORSO_BAND = (0.9, 1.45) # metres: where the scales go
100
+ LEG_TOP = 0.6 # metres: the ridges go below this
101
+
102
+ kit.clear_default_scene()
103
+ base = blockout.skin_blockout("Base", blockout.humanoid_chart(height=HEIGHT))
104
+ retopo.voxel_remesh(base, voxel_size=HEIGHT / 175.0)
105
+ retopo.quadriflow(base, target_triangles=5000, symmetry_axes=("X",))
106
+ kit.smart_unwrap(base, island_margin=0.01)
107
+ started = time.time()
108
+ levels = retopo.multires_subdivide(base, LEVELS)
109
+
110
+ # The shaped copy: same topology as the top multires level (a Subdivision of the same levels, applied).
111
+ shaped = base.copy()
112
+ shaped.data = base.data.copy()
113
+ shaped.name = "Shaped"
114
+ bpy.context.scene.collection.objects.link(shaped)
115
+ shaped.modifiers.clear()
116
+ smoothing = shaped.modifiers.new("Subdivision", "SUBSURF")
117
+ smoothing.levels = LEVELS
118
+ kit.apply_modifiers(shaped)
119
+
120
+ torso = shaped.vertex_groups.new(name="Torso")
121
+ torso.add([vertex.index for vertex in shaped.data.vertices if TORSO_BAND[0] < vertex.co.z < TORSO_BAND[1]],
122
+ 1.0, "REPLACE")
123
+ legs = shaped.vertex_groups.new(name="Legs")
124
+ legs.add([vertex.index for vertex in shaped.data.vertices if vertex.co.z < LEG_TOP], 1.0, "REPLACE")
125
+
126
+ scales = bpy.data.textures.new("Scales", type="VORONOI")
127
+ scales.noise_scale = SCALE_SIZE
128
+ retopo.displace(shaped, scales, SCALE_DEPTH, coordinates="LOCAL", vertex_group="Torso")
129
+
130
+ rows = np.linspace(0.0, 1.0, HEIGHT_MAP_SIZE)[:, None]
131
+ ridges = 0.5 + 0.5 * np.sin(rows * 2.0 * math.pi * RIDGE_COUNT) * np.ones((1, HEIGHT_MAP_SIZE))
132
+ ridge_texture = bpy.data.textures.new("Ridges", type="IMAGE")
133
+ ridge_texture.image = retopo.height_image("RidgesHeight", ridges)
134
+ retopo.displace(shaped, ridge_texture, RIDGE_DEPTH, coordinates="UV", vertex_group="Legs")
135
+
136
+ before = np.array([vertex.co[:] for vertex in shaped.data.vertices])
137
+ kit.apply_modifiers(shaped)
138
+ after = np.array([vertex.co[:] for vertex in shaped.data.vertices])
139
+ retopo.multires_reshape(base, shaped)
140
+ bpy.data.objects.remove(shaped)
141
+ base.name = "Sculpt"
142
+ bpy.ops.wm.save_as_mainfile(filepath=os.path.join(out_folder, "sculpt.blend"))
143
+ print(json.dumps({"levels": levels, "top_level_vertices": len(after),
144
+ "largest_offset_m": round(float(np.linalg.norm(after - before, axis=1).max()), 5),
145
+ "seconds": round(time.time() - started, 2)}))
146
+ ```
147
+
148
+ Measured: 3 levels, 147,586 vertices at the top level, largest offset 3.6 mm, 1.1 s.
149
+
150
+ ---
151
+
152
+ ## 3. Remeshing: voxel, QuadriFlow, decimate
153
+
154
+ | Tool | Gives | Destroys / needs | Use for | Never for |
155
+ |---|---|---|---|---|
156
+ | **Voxel remesh** | A closed, manifold, even quad grid; overlaps fused | UVs, vertex groups, shape keys, multires, every data layer; needs thickness (Solidify flat parts first) | Fusing a blockout or a kitbash into one shell; a sculpt base; a clean input for QuadriFlow | The final game mesh: no edge flow |
157
+ | **QuadriFlow** | Curvature-aligned quads to a face count, optional mirror symmetry | Every data layer; a manifold, consistently wound input with no edge under 0.1 mm, no Multires, Object Mode | An automatic quad retopology of an organic form; a subdivision base | Intersecting input (voxel remesh first); final loops of a hero face |
158
+ | **Decimate (Collapse)** | The closest shape at a triangle ratio; keeps UVs (seams can drift) and vertex groups | Edge flow: the result is triangles with poles everywhere | LODs, a lighter bake source, static props | The topology of a deforming mesh |
159
+ | **Decimate (Planar / Un-Subdivide)** | Dissolves flat regions / reverses a subdivision | | Hard-surface cleanup; a lower level of a grid mesh | |
160
+
161
+ **Voxel size.** About two voxels survive as the smallest detail. Use 1/150-1/250 of the height for a
162
+ character base (1 cm on 1.75 m), finer for a bake source. Preserve Volume costs time and keeps the size;
163
+ adaptivity above 0 turns Fix Poles off and adds triangles.
164
+
165
+ **QuadriFlow, measured on Blender 5.3.0:**
166
+ - **Give a face count.** Headless, only `mode="FACES"` with `target_faces` is read; the ratio and edge-length
167
+ modes are converted to a face count only by the operator's UI pop-up. `quadriflow` takes a triangle budget,
168
+ asks for 92 % of it and retries lower until the result fits.
169
+ - **It refuses small meshes** with "needs to be manifold" even when they are (a 1.75 cm figure). `quadriflow`
170
+ solves at a 2 m size and scales back.
171
+ - **Symmetry leaves the mirror seam open**: 144 open edges on a biped, seam vertices up to 2.7 mm off the plane.
172
+ `quadriflow` snaps the open-edge vertices onto the plane and welds them (welding interior vertices near the
173
+ plane instead fuses unrelated edges), retries another seed when the weld fails, and falls back to a
174
+ whole-mesh solve on shapes whose seam never welds (`"symmetric": false`). Over 30 biped runs (five body
175
+ shapes, three budgets, two scales) every result was manifold.
176
+ - **It is not deterministic**: the same input and seed gave 4,500 triangles in one run and needed a second
177
+ seed for 4,612 in the next. Gate on the measured result, not on the request.
178
+ - **It lands well under large budgets** on simple forms: asking 12k gave 6.9-11.3k. It does not add loops
179
+ where a joint bends.
180
+
181
+ ---
182
+
183
+ ## 4. Retopology routes
184
+
185
+ | Route | Loops placed by | Poles | Deviation from the high poly | Choose when |
186
+ |---|---|---|---|---|
187
+ | **QuadriFlow** | The curvature cross field | Many (59 on a 4.4k biped), none on joints in the test | p95 4.2 mm, max 27 mm (thin tips are lost) | Organic forms where clean quads matter more than exact loops; LOD0 of non-hero characters |
188
+ | **Skin cage + shrinkwrap** | The chart: one ring per joint point | Few (46), only where branches meet | Level 1 (1.6k): p95 9.5 mm; level 2 (6.3k): p95 0.9 mm | Characters and creatures built from a chart: the loop layout a rigger wants, all quads |
189
+ | **Decimate** | Nobody | Everywhere (2,302 on 5k) | p95 0.24 mm | LODs and static meshes; never a deforming LOD0 |
190
+ | **Manual (GUI)** | The artist | Placed on purpose | As drawn | Hero faces, shoulders, anything a lead will review loop by loop |
191
+
192
+ **Shrinkwrap settings for retopology** (the headless stand-in for snapping while drawing):
193
+
194
+ | Wrap method | Behaviour | Use |
195
+ |---|---|---|
196
+ | Nearest Surface Point | Each vertex to the closest point on the high poly | The default for a cage close to the surface |
197
+ | Project (along normals, both directions) | Along the vertex normal, with an optional limit | A cage that sits inside or outside the high; avoids sliding across thin parts |
198
+ | Target Normal Project | Smoother projection using the target's normals; slower | Retopology over noisy or scanned detail |
199
+ | Nearest Vertex | Snaps to vertices | Rarely: it clumps |
200
+
201
+ Snap mode: On Surface, Outside Surface (offset always outward) or Above Surface (offset along the smooth
202
+ normal) with a small offset keeps a retopology shell just outside the sculpt. After shrinkwrap, `relax`
203
+ (Laplacian smoothing, then a re-projection) evens the spacing; on the test asset it changed the deviation
204
+ by under 0.1 mm, because the skin cage was already evenly spaced.
205
+
206
+ ### Recipe: three retopology routes on one high poly, measured the same way
207
+
208
+ ```python
209
+ """Three retopology routes on one high poly, measured the same way: QuadriFlow (automatic quads), a skin
210
+ cage shrinkwrapped onto the high poly (loops placed by construction) and collapse decimation (no flow, for
211
+ contrast). Prints triangles, poles and the two-way surface deviation of each. Saves retopology.blend."""
212
+ import json
213
+ import os
214
+ import sys
215
+
216
+ import bpy
217
+
218
+ import character_blockout as blockout
219
+ import construction_kit as kit
220
+ import retopology_tools as retopo
221
+
222
+ out_folder = sys.argv[sys.argv.index("--") + 1]
223
+ HEIGHT = 1.75
224
+ HIGH_VOXEL = 0.006 # the "sculpt": a fine voxel remesh of the blockout
225
+ BUDGET = 5000
226
+ JOINT_RADIUS = 0.04
227
+
228
+
229
+ def copy_of(source, name):
230
+ """An independent copy of a mesh object, linked to the scene."""
231
+ duplicate = source.copy()
232
+ duplicate.data = source.data.copy()
233
+ duplicate.name = name
234
+ bpy.context.scene.collection.objects.link(duplicate)
235
+ return duplicate
236
+
237
+
238
+ def measure(low, high, joints):
239
+ """The numbers that compare retopology routes: budget, poles (and how many sit on a joint), deviation."""
240
+ topology = retopo.topology_report(low, joints=joints, joint_radius=JOINT_RADIUS)
241
+ deviation = retopo.surface_deviation(low, high)
242
+ return {"triangles": topology["triangles"], "poles": topology["poles"],
243
+ "poles_at_joints": topology["poles_at_joints"], "manifold": topology["manifold"],
244
+ "high_to_low_p95_mm": round(deviation["high_to_low"]["p95_m"] * 1000.0, 2),
245
+ "high_to_low_max_mm": round(deviation["high_to_low"]["max_m"] * 1000.0, 2)}
246
+
247
+
248
+ kit.clear_default_scene()
249
+ chart = blockout.humanoid_chart(height=HEIGHT)
250
+ joints = [bone.head for bone in chart if bone.name.endswith(("Arm", "ForeArm", "UpLeg", "Leg"))]
251
+ high = blockout.skin_blockout("High", chart)
252
+ retopo.voxel_remesh(high, voxel_size=HIGH_VOXEL)
253
+ routes = {"high_triangles": retopo.triangle_count(high)}
254
+
255
+ quadriflow_low = copy_of(high, "Low_QuadriFlow")
256
+ retopo.quadriflow(quadriflow_low, target_triangles=BUDGET, symmetry_axes=("X",))
257
+ routes["quadriflow"] = measure(quadriflow_low, high, joints)
258
+
259
+ # The skin cage has a ring of quads around every bone and its poles at the branch points: the loops a
260
+ # rigger wants. Shrinkwrap pulls it onto the sculpt; relax evens the spacing and re-projects.
261
+ for subdivisions in (1, 2):
262
+ cage = blockout.skin_blockout(f"Low_SkinCage{subdivisions}", chart, subdivisions=subdivisions)
263
+ retopo.shrinkwrap_fit(cage, high, method="NEAREST_SURFACEPOINT", wrap_mode="ON_SURFACE")
264
+ retopo.relax(cage, iterations=3, factor=0.5, keep_on=high)
265
+ routes[f"skin_cage_{subdivisions}"] = measure(cage, high, joints)
266
+
267
+ decimated = copy_of(high, "Low_Decimate")
268
+ retopo.decimate_to(decimated, BUDGET, symmetry_axis="X")
269
+ routes["decimate"] = measure(decimated, high, joints)
270
+ for obj in bpy.data.objects:
271
+ obj.data.materials.append(bpy.data.materials.get("Body") or bpy.data.materials.new("Body"))
272
+ bpy.ops.wm.save_as_mainfile(filepath=os.path.join(out_folder, "retopology.blend"))
273
+ print(json.dumps(routes))
274
+ ```
275
+
276
+ Measured (high poly 147k triangles):
277
+
278
+ | Route | Triangles | Poles | Poles at joints | High-to-low p95 / max |
279
+ |---|---|---|---|---|
280
+ | QuadriFlow | 4,448 | 59 | 0 | 4.2 / 27.0 mm |
281
+ | Skin cage level 1, shrinkwrapped | 1,572 | 46 | 0 | 9.5 / 20.8 mm |
282
+ | Skin cage level 2, shrinkwrapped | 6,288 | 46 | 0 | 0.9 / 6.0 mm |
283
+ | Decimate | 5,000 | 2,302 | 0 | 0.24 / 11.1 mm |
284
+
285
+ The deviation is not the only score: decimation is closest but has no flow, and QuadriFlow's poles are
286
+ where its field put them. Pick by the table above, then measure.
287
+
288
+ ---
289
+
290
+ ## 5. Edge flow for a game low poly that bakes and deforms
291
+
292
+ - **Silhouette first.** "Add more polygons where there's curvature, less where it's straight" and "don't waste
293
+ polys where they don't add to the silhouette" (Polycount). A review render at play size decides.
294
+ - **Flow follows the form.** Loops follow anatomy or the design lines of clothing and armour (80.lv); in
295
+ deforming areas, never end a loop mid-surface or drop a triangle that breaks the surrounding loops
296
+ (Frozenbyte).
297
+ - **Poles on flat, non-deforming areas**; check with `topology_report(joints=...)`.
298
+ - **Hard edges only on UV seams**, and at mechanical bends of about 45-90 degrees or more: a hard edge on a seam
299
+ costs no extra vertices (Polycount, Normal Map Modeling). Organic low polys are usually all smooth.
300
+ - **Support edges** on the low poly are the best fix for skewed bake detail (Polycount, Texture Baking).
301
+ - **Triangulate before baking**, and ship that triangulation: the engine re-triangulating quads differently
302
+ shifts the shading the map was baked for ("x-shaped smoothing errors", Marmoset). Mirror the triangulation
303
+ on mirrored halves.
304
+ - **Bake the whole mesh**, not a mirrored half; move mirrored or stacked UV islands one whole UV tile away
305
+ during the bake.
306
+
307
+ ---
308
+
309
+ ## 6. High-to-low baking, deeper than the checklist
310
+
311
+ Guide §8.4a has the pre-bake checklist and the artefact table. What it leaves to judgement:
312
+
313
+ **Size the cage from a measurement.** Run `surface_deviation(low, high)` first. The bake rays start
314
+ `cage_extrusion` outside the low poly and travel `max_ray_distance` inward; the extrusion must exceed the
315
+ furthest the high poly stands outside the low (the high-to-low maximum on convex areas), and the ray distance
316
+ must reach the deepest point inside. On the test asset the high stands up to 6 mm proud: an extrusion of 2 cm
317
+ and a ray of 4 cm baked clean; 0 (Blender's default) failed.
318
+
319
+ **Padding (Polycount, Edge padding):**
320
+
321
+ | Map size | Padding | UV gutter between islands |
322
+ |---|---|---|
323
+ | 256 | 2 px | 4 px |
324
+ | 512 | 4 px | 8 px |
325
+ | 1024 | 8 px | 16 px |
326
+ | 2048 | 16 px | 32 px |
327
+ | 4096 | 32 px | 64 px |
328
+
329
+ **Tangent basis.** "The game engine and the baking tool should use the same tangent basis" (Polycount).
330
+ Blender bakes in MikkTSpace; Unity uses MikkTSpace; the glTF specification says clients should compute
331
+ MikkTSpace when tangents are absent. **BabylonJS does not**: without a TANGENT attribute it builds a
332
+ screen-space-derivative frame in the shader (`bumpFragmentMainFunctions.fx`), which differs from MikkTSpace
333
+ most along UV seams and on stretched islands. Export tangents for BabylonJS: the skill's `export` adds them
334
+ when a material has a normal map (`--tangents auto`); for rigs exported with `rigging_tools.export_rig`, pass
335
+ `{"export_tangents": True}` (measured: +22 % on a 5k skinned character's file).
336
+
337
+ **Green channel.** Blender, Unity, glTF and BabylonJS use +Y (OpenGL). The BabylonJS glTF loader handles its
338
+ own handedness flip, so ship Blender's bake as it is. A DirectX map (3ds Max, Unreal, CryENGINE, Source)
339
+ must be flipped once on import. A flipped map passes the whole-map statistics: only the seam check (section 7)
340
+ caught it.
341
+
342
+ **AO bakes.** Cycles AO uses the World's AO distance (default 10 m, far too long for a character: set it to a
343
+ fraction of the model, 0.1-0.3 m) and ignores lights. Floating high-poly parts cast unwanted AO: bake them
344
+ exploded, or with a shorter distance than the floater's gap.
345
+
346
+ **Curvature** for wear and dirt masks: Cycles Geometry > Pointiness, or the AO node with Inside for convexity.
347
+
348
+ ### Recipe: bake a normal map and prove it, then prove two broken bakes fail
349
+
350
+ ```python
351
+ """High-to-low normal bake with proof. A detailed high poly (voxel-remeshed blockout with displaced scales) is
352
+ baked onto its 5k QuadriFlow low poly with a ray cage, then verified: whole-map statistics, and a seam
353
+ check that decodes the map through the MikkTSpace frame and compares it with the high poly's normal. The
354
+ same checks run on two classic failures - zero cage extrusion and a flipped green channel - to show they
355
+ fail. Saves bake.blend and low_normal.png."""
356
+ import json
357
+ import os
358
+ import sys
359
+
360
+ import bpy
361
+ import numpy as np
362
+
363
+ import character_blockout as blockout
364
+ import construction_kit as kit
365
+ import retopology_tools as retopo
366
+
367
+ out_folder = sys.argv[sys.argv.index("--") + 1]
368
+ HEIGHT = 1.75
369
+ MAP_SIZE = 1024
370
+ MARGIN = 8 # pixels of padding at 1K (Polycount: 2 at 256, 4 at 512, 16 at 2K)
371
+ CAGE_EXTRUSION = 0.02 # metres: more than the high poly ever stands outside the low
372
+ MAX_RAY_DISTANCE = 0.04 # about twice the extrusion
373
+ SCALE_DEPTH = 0.006
374
+ SEAM_P95_LIMIT = 3.0 # degrees: the seam gate this recipe proposes
375
+ SEAM_SHARE_LIMIT = 0.05
376
+
377
+
378
+ def flipped_green(image):
379
+ """A copy of a normal map with the green channel inverted (a DirectX map read as OpenGL)."""
380
+ pixels = np.empty(image.size[0] * image.size[1] * 4, dtype=np.float32)
381
+ image.pixels.foreach_get(pixels)
382
+ pixels = pixels.reshape(-1, 4)
383
+ pixels[:, 1] = 1.0 - pixels[:, 1]
384
+ copy = bpy.data.images.new(image.name + "_flipped", image.size[0], image.size[1], float_buffer=True)
385
+ copy.colorspace_settings.name = "Non-Color"
386
+ copy.pixels.foreach_set(pixels.ravel())
387
+ return copy
388
+
389
+
390
+ def seam_gate(report):
391
+ """True when the seams would not show: 95 % of samples within 3 degrees, under 5 % over 5 degrees."""
392
+ return report["error_p95_degrees"] <= SEAM_P95_LIMIT and report["error_over_limit_share"] <= SEAM_SHARE_LIMIT
393
+
394
+
395
+ kit.clear_default_scene()
396
+ chart = blockout.humanoid_chart(height=HEIGHT)
397
+ low = blockout.skin_blockout("Low", chart)
398
+ retopo.voxel_remesh(low, voxel_size=HEIGHT / 175.0)
399
+ retopo.quadriflow(low, target_triangles=5000, symmetry_axes=("X",))
400
+ kit.smart_unwrap(low, island_margin=0.01)
401
+
402
+ high = low.copy()
403
+ high.data = low.data.copy()
404
+ high.name = "High"
405
+ bpy.context.scene.collection.objects.link(high)
406
+ smoothing = high.modifiers.new("Subdivision", "SUBSURF")
407
+ smoothing.levels = 3
408
+ scales = bpy.data.textures.new("Scales", type="VORONOI")
409
+ scales.noise_scale = 0.03
410
+ retopo.displace(high, scales, SCALE_DEPTH, coordinates="LOCAL")
411
+ kit.apply_modifiers(high)
412
+
413
+ normal_map = retopo.bake_high_to_low(low, high, size=MAP_SIZE, cage_extrusion=CAGE_EXTRUSION,
414
+ max_ray_distance=MAX_RAY_DISTANCE, margin=MARGIN)
415
+ good = {"stats": retopo.normal_map_stats(normal_map, low), "seams": retopo.normal_seam_report(low, normal_map, high)}
416
+ good["pass"] = good["stats"]["pass"] and seam_gate(good["seams"])
417
+
418
+ no_cage = retopo.bake_high_to_low(low, high, size=MAP_SIZE // 4, cage_extrusion=0.0, max_ray_distance=0.0,
419
+ margin=MARGIN // 2)
420
+ broken = {"stats": retopo.normal_map_stats(no_cage, low),
421
+ "seams": retopo.normal_seam_report(low, no_cage, high, inset_pixels=1.0)}
422
+ broken["pass"] = broken["stats"]["pass"] and seam_gate(broken["seams"])
423
+
424
+ flipped = flipped_green(normal_map)
425
+ wrong_green = {"stats": retopo.normal_map_stats(flipped, low), "seams": retopo.normal_seam_report(low, flipped, high)}
426
+ wrong_green["pass"] = wrong_green["stats"]["pass"] and seam_gate(wrong_green["seams"])
427
+
428
+ normal_map.filepath_raw = os.path.join(out_folder, "low_normal.png")
429
+ normal_map.file_format = "PNG"
430
+ normal_map.save()
431
+ bpy.ops.wm.save_as_mainfile(filepath=os.path.join(out_folder, "bake.blend"))
432
+ print(json.dumps({"good": good, "zero_extrusion": broken, "flipped_green": wrong_green}))
433
+ ```
434
+
435
+ ---
436
+
437
+ ## 7. Proving a normal map: statistics and seams
438
+
439
+ `normal_map_stats` checks the whole map inside the UV islands: the mean must be near (0.5, 0.5, 1.0) and almost
440
+ no texel may point backwards (blue under 0.5). It catches failed rays and wrong colour spaces.
441
+
442
+ `normal_seam_report` checks where engines show errors: along every UV seam edge it samples the map just inside
443
+ each of the two islands (at a quarter, half and three quarters of the edge, `inset_pixels` in), decodes the
444
+ texel exactly as a shader does (through the MikkTSpace tangent frame interpolated at that point, +Y green),
445
+ and compares the decoded normal with the high poly's smooth normal where the bake ray from that point lands.
446
+ A clean bake decodes to the high poly on both sides, so the seam vanishes. A wrong green channel, a different
447
+ tangent basis, missed rays or skew all show as angular error.
448
+
449
+ Measured on the test asset (1024 map, 8 px margin; values are degrees):
450
+
451
+ | Bake | Mean RGB | Low-blue texels | Seam median / p95 | Seam samples over 5 degrees | Verdict |
452
+ |---|---|---|---|---|---|
453
+ | Good (extrusion 2 cm, ray 4 cm) | 0.50, 0.50, 0.996 | 0 % | 0.27 / 1.1 | 0.3 % | Pass |
454
+ | Zero extrusion (Blender's default) | 0.50, 0.50, 0.78 | 22 % | 3.9 / 167 | 41 % | Fails both checks |
455
+ | Green flipped (DirectX map read as OpenGL) | 0.50, 0.50, 0.996 | 0 % | 8.3 / 21 | 70 % | Passes the statistics, fails the seams |
456
+
457
+ Proposed gate: **seam p95 at or under 3 degrees and at most 5 % of samples over 5 degrees**, plus the statistics
458
+ pass. On a smooth (undetailed) high poly the same good bake measured a median of 0.01 degrees and a p95 of
459
+ 0.75; decoding at face centres agrees with Blender's own normals within 0.4 degrees median, which is the
460
+ floor of the method.
461
+
462
+ ---
463
+
464
+ ## 8. Budgets (web and BabylonJS first)
465
+
466
+ | Item | Web / mobile | Desktop | Notes |
467
+ |---|---|---|---|
468
+ | Sculpt / bake source | 0.2-2M triangles | 2-20M | Triangles smaller than a bake texel slow the bake without improving it: decimate the source to about one triangle per texel |
469
+ | Multires levels over a 5k base | 3 (about 300k) | 4-5 (1.2-5M) | Each level is x4 |
470
+ | Character normal map | 1024 | 2048 (4096 cinematic) | Same size as the base colour; WebP / KTX2 for delivery |
471
+ | Prop normal map | 256-512 | 512-1024 | Texel density by camera: `art-style-and-genre.md` §4 |
472
+ | Padding | 8 px at 1K, 16 px at 2K | | Section 6 table |
473
+ | Bake time (Cycles CPU, 1024) | 0.3 s normal; AO about 64 samples | | Measured on the test asset |
474
+ | Tangents in the glTF | Export them | | +22 % file size measured; correct normal mapping in BabylonJS |
475
+
476
+ ---
477
+
478
+ ## 9. Pitfalls
479
+
480
+ | Pitfall | What happens | Fix |
481
+ |---|---|---|
482
+ | Entering sculpt mode headless | Blender 5.3.0 segfaults (exit 139) | Multires + Displace + reshape instead |
483
+ | QuadriFlow with `mode="RATIO"` or `"EDGE"` from Python | The operator source converts them to a face count only in the UI pop-up | Give `target_faces` (`quadriflow` takes a triangle budget) |
484
+ | QuadriFlow on a mesh with overlaps or flipped faces | "needs to be manifold", CANCELLED, no exception | `voxel_remesh` first; check `manifold_report` |
485
+ | QuadriFlow symmetry | Open mirror seam | `quadriflow` welds it and reports `"symmetric"` |
486
+ | Voxel remesh after UVs, weights or shape keys | All lost | Remesh first, then build the rest |
487
+ | Decimated mesh used as LOD0 of a character | Poles everywhere, bad deformation and shading | QuadriFlow or a cage for LOD0; decimate for LODs only |
488
+ | Displace on a low-density mesh | Nothing visible, or spikes | Displace only after enough subdivision (multires top level) |
489
+ | Image displacement across a UV seam | A step along the seam | Procedural (LOCAL) textures there, or seam-aware images |
490
+ | Bake with the default 0 extrusion | Mean blue 0.78, 22 % backwards texels | Size the cage from `surface_deviation` |
491
+ | Green channel flipped | Passes whole-map statistics; lighting inverted on one axis | `normal_seam_report` catches it (p95 21 degrees) |
492
+ | glTF without tangents in BabylonJS | Seams and swimming highlights on curved islands | `export --tangents auto` (the default), or `export_tangents=True` for `export_rig` |
493
+ | Packed float bake in a glTF | Six times too dark (guide §8.4a) | Save to a file, or 8-bit sRGB / Non-Color data |
494
+
495
+ ---
496
+
497
+ ## 10. Verification checklist
498
+
499
+ ```bash
500
+ node <skill>/scripts/bt-blender.mjs qa-check --model low.blend --profile web
501
+ node <skill>/scripts/bt-blender.mjs assembly-check --model low.blend
502
+ node <skill>/scripts/bt-blender.mjs review-render --model low.blend --out review --pixel-height 180
503
+ node <skill>/scripts/bt-blender.mjs measure-stations --spec refs/spec.json --model low.blend # the low still matches the sheet
504
+ node <skill>/scripts/bt-blender.mjs export --model low.blend --out build/low.glb
505
+ node <skill>/scripts/bt-blender.mjs validate-gltf build/low.glb
506
+ ```
507
+
508
+ - [ ] The high poly is one manifold shell (or one per part) and the bake source is under the size limit.
509
+ - [ ] The low poly is within budget, manifold, with poles off the joints (`topology_report`).
510
+ - [ ] `surface_deviation(low, high)` is recorded; the cage extrusion exceeds its high-to-low maximum.
511
+ - [ ] `normal_map_stats` passes; `normal_seam_report` p95 at or under 3 degrees, at most 5 % over 5 degrees.
512
+ - [ ] The low poly ships with the triangulation it was baked with, and with tangents in the glTF.
513
+ - [ ] Padding matches the map size; no island closer than the gutter.
514
+ - [ ] The review render shows the detail at play size; detail that does not survive there was not worth baking.
515
+
516
+ ---
517
+
518
+ ## Sources
519
+
520
+ - Blender Manual (5.3 source): Retopology / remeshing; Remesh, Decimate, Shrinkwrap, Multiresolution and
521
+ Displace modifiers; Cycles baking; snapping; Poly Build; AO and Geometry nodes; Displace Geometry node —
522
+ https://projects.blender.org/blender/blender-manual/raw/branch/main/manual/modeling/meshes/retopology.rst ,
523
+ https://docs.blender.org/manual/en/latest/modeling/modifiers/generate/remesh.html ,
524
+ https://docs.blender.org/manual/en/5.0/modeling/geometry_nodes/geometry/operations/displace_geometry.html
525
+ - Blender Python API: bpy.ops.object (quadriflow_remesh, voxel_remesh, multires_*); BakeSettings;
526
+ WorldLighting; export_scene — https://docs.blender.org/api/current/bpy.ops.object.html ,
527
+ https://docs.blender.org/api/current/bpy.types.BakeSettings.html ,
528
+ https://docs.blender.org/api/current/bpy.types.WorldLighting.html ,
529
+ https://docs.blender.org/api/current/bpy.ops.export_scene.html
530
+ - Blender source, QuadriFlow manifold check (object_remesh.cc) —
531
+ https://projects.blender.org/blender/blender/raw/branch/main/source/blender/editors/object/object_remesh.cc
532
+ - Polycount wiki: Normal map; Texture Baking; Normal Map Technical Details; Normal Map Modeling; Edge padding;
533
+ Ambient occlusion map; Curvature map; Topology; ReTopology Modeling — http://wiki.polycount.com/wiki/Normal_map ,
534
+ http://wiki.polycount.com/wiki/Texture_Baking , http://wiki.polycount.com/wiki/Normal_Map_Technical_Details ,
535
+ http://wiki.polycount.com/wiki/Normal_Map_Modeling , http://wiki.polycount.com/wiki/Edge_padding ,
536
+ http://wiki.polycount.com/wiki/Ambient_occlusion_map , http://wiki.polycount.com/wiki/Curvature_map ,
537
+ http://wiki.polycount.com/wiki/Topology , http://wiki.polycount.com/wiki/ReTopologyModeling
538
+ - Khronos, glTF 2.0 specification (tangents, normal textures) — https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html
539
+ - BabylonJS source: glTF loader (normal-map inversions) and bumpFragmentMainFunctions.fx (cotangent frame) —
540
+ https://github.com/BabylonJS/Babylon.js/blob/master/packages/dev/loaders/src/glTF/2.0/glTFLoader.pure.ts ,
541
+ https://github.com/BabylonJS/Babylon.js/blob/master/packages/dev/core/src/Shaders/ShadersInclude/bumpFragmentMainFunctions.fx
542
+ - Marmoset, Toolbag baking tutorial — https://marmoset.co/posts/toolbag-baking-tutorial/
543
+ - 80.lv, Topology for game characters — https://80.lv/articles/topology-for-game-and-game-based-characters
544
+ - Frozenbyte wiki, 3D asset workflow: retopology — https://wiki.frozenbyte.com/index.php/3D_Asset_Workflow:_Retopology