@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.
Files changed (56) hide show
  1. package/README.md +3 -2
  2. package/package.json +1 -1
  3. package/skills/bt-blender/SKILL.md +386 -0
  4. package/skills/bt-blender/THIRD_PARTY_NOTICES.md +141 -0
  5. package/skills/bt-blender/references/art-style-and-genre.md +173 -0
  6. package/skills/bt-blender/references/characters-and-creatures.md +644 -0
  7. package/skills/bt-blender/references/environments.md +478 -0
  8. package/skills/bt-blender/references/game-engine-export.md +284 -0
  9. package/skills/bt-blender/references/geometry-nodes.md +447 -0
  10. package/skills/bt-blender/references/hard-surface.md +720 -0
  11. package/skills/bt-blender/references/procedural-generation.md +358 -0
  12. package/skills/bt-blender/references/rigging-and-animation.md +1080 -0
  13. package/skills/bt-blender/references/sculpting-and-retopology.md +544 -0
  14. package/skills/bt-blender/references/uv-and-pbr-materials.md +381 -0
  15. package/skills/bt-blender/references/vehicles.md +632 -0
  16. package/skills/bt-blender/scripts/blender/assembly_check.py +420 -0
  17. package/skills/bt-blender/scripts/blender/character_blockout.py +462 -0
  18. package/skills/bt-blender/scripts/blender/construction_kit.py +1710 -0
  19. package/skills/bt-blender/scripts/blender/environment_kit.py +525 -0
  20. package/skills/bt-blender/scripts/blender/export_asset.py +623 -0
  21. package/skills/bt-blender/scripts/blender/geometry_nodes_builders.py +575 -0
  22. package/skills/bt-blender/scripts/blender/hard_surface_panels.py +374 -0
  23. package/skills/bt-blender/scripts/blender/hard_surface_trims.py +200 -0
  24. package/skills/bt-blender/scripts/blender/image_measure.py +568 -0
  25. package/skills/bt-blender/scripts/blender/materials_pbr.py +439 -0
  26. package/skills/bt-blender/scripts/blender/measure_stations.py +486 -0
  27. package/skills/bt-blender/scripts/blender/ortho_views.py +309 -0
  28. package/skills/bt-blender/scripts/blender/procedural_game_ready.py +258 -0
  29. package/skills/bt-blender/scripts/blender/procedural_generators.py +842 -0
  30. package/skills/bt-blender/scripts/blender/qa_check.py +729 -0
  31. package/skills/bt-blender/scripts/blender/retopology_tools.py +781 -0
  32. package/skills/bt-blender/scripts/blender/review_render.py +358 -0
  33. package/skills/bt-blender/scripts/blender/rigging_tools.py +1170 -0
  34. package/skills/bt-blender/scripts/blender/style_palette.py +190 -0
  35. package/skills/bt-blender/scripts/blender/tool_common.py +289 -0
  36. package/skills/bt-blender/scripts/blender/uv_layout.py +555 -0
  37. package/skills/bt-blender/scripts/blender/vehicle_parts.py +370 -0
  38. package/skills/bt-blender/scripts/blender/view_consistency.py +133 -0
  39. package/skills/bt-blender/scripts/blender/world_gate.py +219 -0
  40. package/skills/bt-blender/scripts/bt-blender.mjs +329 -0
  41. package/skills/bt-blender/scripts/validate_gltf.mjs +204 -0
  42. package/skills/bt-gauntlet/SKILL.md +6 -6
  43. package/skills/bt-gauntlet/references/critic-rubrics.md +71 -4
  44. package/skills/bt-gauntlet/references/spec-composition.md +13 -0
  45. package/skills/bt-gauntlet/references/unity-pipeline.md +18 -2
  46. package/skills/bt-unwrap/scripts/blender/__pycache__/bt_unwrap.cpython-313.pyc +0 -0
  47. package/skills/bt-unwrap/scripts/blender/__pycache__/image_utils.cpython-313.pyc +0 -0
  48. package/skills/bt-unwrap/scripts/blender/__pycache__/mesh_tools.cpython-313.pyc +0 -0
  49. package/skills/bt-unwrap/scripts/blender/__pycache__/model_io.cpython-313.pyc +0 -0
  50. package/skills/bt-unwrap/scripts/blender/__pycache__/previews.cpython-313.pyc +0 -0
  51. package/skills/bt-unwrap/scripts/blender/__pycache__/rasterizer.cpython-313.pyc +0 -0
  52. package/skills/bt-unwrap/scripts/blender/__pycache__/reference_views.cpython-313.pyc +0 -0
  53. package/skills/bt-unwrap/scripts/blender/__pycache__/reference_warp.cpython-313.pyc +0 -0
  54. package/skills/bt-unwrap/scripts/blender/__pycache__/texture_bake.cpython-313.pyc +0 -0
  55. package/skills/bt-unwrap/scripts/blender/__pycache__/texture_compose.cpython-313.pyc +0 -0
  56. package/skills/bt-unwrap/scripts/blender/__pycache__/uv_layout.cpython-313.pyc +0 -0
@@ -0,0 +1,381 @@
1
+ # UV layout and PBR materials: seams, texel density, lightmap UVs, bakes and channel packing
2
+
3
+ **Load this when** a mesh needs UVs that will carry a texture, when a procedural or node material must become
4
+ textures an engine can use, or when a texture set must be packed for a specific engine. That covers:
5
+ - unwrapping generated or modelled meshes;
6
+ - making texel density consistent;
7
+ - adding a lightmap UV;
8
+ - baking base colour, ORM and normal maps;
9
+ - choosing colour spaces;
10
+ - wiring a material so the glTF exporter writes the texture set you expect;
11
+ - counting material slots as draw calls.
12
+
13
+ **What it assumes.** The Agent Reference's Blender guide (`references/unity-blender-cli.md`) covers the
14
+ baseline, and this file goes deeper without repeating it:
15
+ - §8.4a: the bake traps (Cycles, active image node, `save()`, base colour through Emission, packed float bakes
16
+ shipping too dark, the `lightmap_pack` margin clamp, the cage extrusion), the high-to-low checklist, the
17
+ artefact table, the PBR sanity values and metal F0 values;
18
+ - §7.1: the 5.x Principled input names.
19
+
20
+ Sibling references:
21
+ - `hard-surface.md` §6: trim sheets and decals;
22
+ - `environments.md` §8: lightmap resolution per piece in a level;
23
+ - `game-engine-export.md`: export settings.
24
+
25
+ **Helpers.**
26
+ - `scripts/blender/uv_layout.py`:
27
+ - seams and unwraps: `mark_seams_from_sharp`, `unwrap`, `box_project`;
28
+ - packing: `pack`, `add_lightmap_uv`;
29
+ - measuring: `islands`, `texel_density`, `set_texel_density`, `overlap`, `island_gap_pixels`, `bounds`.
30
+ - `scripts/blender/materials_pbr.py`:
31
+ - colour: `srgb_to_linear`, `linear_to_srgb`;
32
+ - materials: `principled_material`, `textured_material`, `gltf_material_output`, `replace_materials`;
33
+ - baking: `bake_maps`, `bake_channel`;
34
+ - packing: `pack_orm`, `unity_metallic_smoothness`, `hdrp_mask_map`, `save_png`, `load_pixels`.
35
+
36
+ Every recipe below is a complete script: run `node <skill>/scripts/bt-blender.mjs run recipe.py <out folder>`.
37
+
38
+ ---
39
+
40
+ ## 1. The professional workflow
41
+
42
+ 1. **Choose the texturing route per asset** before cutting a seam:
43
+
44
+ | Route | UVs | When |
45
+ |---|---|---|
46
+ | **Tiling material** | World-scale projection (`box_project`), may run past 0..1 and overlap | Walls, ground, generated buildings, anything large and uniform |
47
+ | **Trim sheet** | Strips mapped onto trim rows (`hard-surface.md` §6) | Manufactured detail on many assets sharing one material |
48
+ | **Unique texture / bake** | Non-overlapping 0..1 islands at one texel density | Props and heroes with baked detail, AO, or painted wear |
49
+ | **Atlas** | Several assets' unique islands packed into one 0..1 square | Many small props drawn with one material |
50
+ | **Palette / colour ID** | Islands collapsed onto flat colour swatches | Low-poly stylised; no density concerns |
51
+
52
+ 2. **Seams on hard edges** (section 2), then unwrap.
53
+ 3. **Equalise texel density** across islands, then pack **without rescaling** (section 3).
54
+ 4. **Pack with margins given in pixels** at the texture's size (section 3).
55
+ 5. **Add a lightmap UV** if the asset will be lightmapped (section 4).
56
+ 6. **Build or bake the material** (sections 5–6), pack channels for the target engine (section 7).
57
+ 7. **Export, validate, look** in the engine; check the draw calls per material slot (section 8).
58
+
59
+ ---
60
+
61
+ ## 2. Seams and unwraps
62
+
63
+ **Every hard edge must be a UV seam.** A tangent-space normal map is baked against the low poly's vertex
64
+ normals. Where the normals split (a hard edge), the bake needs a UV split too, or the two faces share texels
65
+ that must hold two different corrections: a visible seam or gradient. Seams are free on hard edges, because
66
+ the vertices are split there anyway. `mark_seams_from_sharp(obj, angle_degrees)` marks:
67
+ - edges already marked sharp;
68
+ - edges whose faces meet above the angle;
69
+ - open boundaries.
70
+
71
+ | Unwrap | Use for | Measured / notes |
72
+ |---|---|---|
73
+ | **Seams + `unwrap(ANGLE_BASED)`** | Hard surface, anything with straight edges and patterns | Islands follow your seams; straight panel edges stay straight |
74
+ | **Seams + `CONFORMAL`** | Hard surface where edge straightness matters more than area | Less area-faithful than angle-based |
75
+ | **Seams + `MINIMUM_STRETCH`** (SLIM) | Organic shapes, characters | Least area distortion; slowest |
76
+ | **`smart_project`** (`construction_kit.smart_unwrap`) | Generated organic meshes (rocks, roots), bake targets nobody paints by hand | Cuts by angle (50–66°); many small islands; measured on a 1,200-triangle rock: 49 islands, density spread 1.12 |
77
+ | **`box_project`** | Tiling and trim materials on architecture | Every face at `metres_per_tile`; overlap by design |
78
+
79
+ **Unwrapping does not equalise density.** Measured on a chamfered 1 m cube: angle-based unwrap then pack
80
+ left the 7 islands between 305 and 430 px/m (spread 1.41). `set_texel_density` brought every island to
81
+ exactly 256.0.
82
+
83
+ ---
84
+
85
+ ## 3. Texel density and packing
86
+
87
+ **Texel density** = sqrt(UV area / world area) x texture size, in pixels per metre, per island
88
+ (`texel_density(obj, size)` returns the mean, min, max, spread and each island). A consistent asset keeps the
89
+ spread near 1. A consistent *game* keeps every asset near the same target at its viewing distance.
90
+
91
+ | Target (px/m) | Typical use |
92
+ |---|---|
93
+ | 128–256 | Far scenery, large architecture on tiling materials, mobile |
94
+ | 256–512 | Third-person props and environment on the web (the common default is 512 for third person) |
95
+ | 1024 | First-person close-ups, hero props |
96
+
97
+ The size budget follows: an asset of surface area A m² at density D px/m needs A x D² pixels before margins.
98
+ Measured: a 1 m cube (6 m²) at 256 px/m needs 1.5 squares of a 512 texture: it cannot fit. `pack(…, scale=False)`
99
+ raises with the factor to lower the density by instead of silently spilling past 1.0. At 128 px/m it fills
100
+ 0.375 of the square.
101
+
102
+ **The workflow that keeps density:** `set_texel_density(obj, target, size)` scales each island about its own
103
+ centre, then `pack(obj, size, margin_pixels, scale=False)` arranges them without rescaling.
104
+
105
+ **Margins in pixels.** `pack` and `unwrap` take `margin_pixels` at the texture size and pass Blender a FRACTION
106
+ margin (pixels / size). Measured on 5.3.0, that margin applies **per island side**:
107
+ - islands ended 15 px apart for an 8 px margin at 1024, and 7 px apart for 4 px at 256 (the gap measure is
108
+ exact for odd gaps and one low for even ones);
109
+ - the outer islands sat exactly one margin (8/1024, 4/256) from the border.
110
+
111
+ So pass the bake's edge padding as `margin_pixels`. The gutter between islands then comes out at twice the
112
+ padding, which is the rule that stops neighbouring islands bleeding into each other's mip levels.
113
+
114
+ | Texture | Edge padding = `margin_pixels` | Gutter between islands (2x) |
115
+ |---|---|---|
116
+ | 256 | 2 | 4 |
117
+ | 512 | 4 | 8 |
118
+ | 1024 | 8 | 16 |
119
+ | 2048 | 16 | 32 |
120
+ | 4096 | 32 | 64 |
121
+
122
+ These numbers reconcile two common rules that look contradictory: 8 px at 2K counted per side, and 16 px at
123
+ 2K counted as padding.
124
+
125
+ **Pack shape and time** (measured on 5.3.0, 49 rock islands; a 7-island crate):
126
+
127
+ | `shape` | Time | Coverage | Use |
128
+ |---|---|---|---|
129
+ | `AABB` | 0.08 s (0.00 s on the crate) | 53.1 % | While iterating; as tight as the others on boxy islands |
130
+ | `CONVEX` | 2.8 s | 53.1 % | Never better than AABB in these tests |
131
+ | `CONCAVE` (default) | 3–7 s (up to 9.5 s on 7 islands) | 58.2 % | The final pack of organic islands |
132
+
133
+ Rotations are quarter turns (`CARDINAL`), so texel rows stay aligned with straight island edges.
134
+
135
+ ---
136
+
137
+ ## 4. Lightmap UVs (UV2)
138
+
139
+ Unity reads lightmap UVs from `Mesh.uv2` (the second UV channel); the glTF exporter writes the second UV map as
140
+ `TEXCOORD_1`; the Toolkit needs UV2 on every lightmapped mesh (authored, or `generateSecondaryUV` on the model
141
+ importer: `unity-authoring-recipes.md` §4). Unity's rules for a lightmap UV:
142
+ - inside 0..1;
143
+ - no overlapping charts;
144
+ - a wide enough margin between charts;
145
+ - low angle and area distortion against the mesh.
146
+
147
+ `add_lightmap_uv(obj, lightmap_size, margin_pixels, method="auto")` makes one from the texture UVs:
148
+ - copies UV0's islands, so the seams are already on hard edges, where a lightmap needs them too;
149
+ - scales every island to the same density (`average_islands_scale`);
150
+ - packs them with the margin at the **lightmap's** resolution;
151
+ - re-projects with Smart UV Project (66 degrees) when the copy overlaps itself (`self_overlap` > 0), which a
152
+ tiling or box-projected UV0 does: copied, such maps overlapped by 349-448 texels on modular kit pieces
153
+ (Blender 5.3.0). `method="copy"` or `"smart"` forces one route; a mesh without UV0 always gets `"smart"`;
154
+ - leaves UV0 the active and render map, so it stays `TEXCOORD_0`.
155
+
156
+ Size the margin for the resolution the piece will really get in the level (`environments.md` §8:
157
+ `lightmap_resolution` from the scene's texels per metre). A margin set for a 1024 lightmap bleeds on a piece
158
+ that gets 64 texels.
159
+
160
+ Verify UV2 with `overlap(obj, "UVLightmap", 1024)` (overlap texels 0, inside the unit square),
161
+ `self_overlap(obj, "UVLightmap", 1024)` (0: no chart folds over itself) and
162
+ `island_gap_pixels(obj, "UVLightmap", lightmap_size)` (≥ 2 x margin - 1). qa-check's UV test reads the active
163
+ map on a 128 x 128 raster; `--uv-map UVLightmap` (or `--uv-map 1`) gates the lightmap instead.
164
+
165
+ Measured on the crate: 0 overlapping texels at 1024, islands 7 px apart at 256 for a 4 px margin, and the
166
+ layers in order `UVMap`, `UVLightmap` with UVMap active.
167
+
168
+ ---
169
+
170
+ ## 5. Principled BSDF on 5.3, and what the glTF exporter writes
171
+
172
+ | Principled input (5.3 name) | glTF | Notes (measured on 5.3.0 unless marked) |
173
+ |---|---|---|
174
+ | Base Color | `baseColorFactor` / `baseColorTexture` | Socket values are linear: sRGB 0.6 was written as 0.3185. Image textures must be sRGB |
175
+ | Metallic, Roughness | `metallicFactor`, `roughnessFactor` / `metallicRoughnessTexture` (B, G) | From Separate Color B and G of one image, the exporter writes that image as is |
176
+ | Normal (through a Normal Map node, tangent space) | `normalTexture`, `scale` = Strength | Image Non-Color; +Y up (OpenGL) |
177
+ | (glTF Material Output group, `Occlusion`) | `occlusionTexture` | A custom node group named exactly `glTF Material Output` with a float input `Occlusion`; R of the ORM image. Measured: occlusion and metallic-roughness then share one texture index |
178
+ | Emission Color, Emission Strength | `emissiveFactor`, `KHR_materials_emissive_strength` (strength 4 -> `emissiveStrength: 4`) | Color linear |
179
+ | Alpha < 1 | `alphaMode: BLEND` | `DITHERED` render method still exported BLEND; the Blender manual's route to `MASK` is a Round or Greater Than math node on the alpha |
180
+ | Coat Weight, Coat Roughness | `KHR_materials_clearcoat` | |
181
+ | Transmission Weight | `KHR_materials_transmission` | IOR 1.5 (the default) wrote no `KHR_materials_ior` |
182
+ | Specular IOR Level, Specular Tint | `KHR_materials_specular` | |
183
+ | Sheen Weight | `KHR_materials_sheen` | |
184
+ | Anisotropic | `KHR_materials_anisotropy` | |
185
+ | Thin Film Thickness | — | Not exported |
186
+ | `use_backface_culling` False (the default for a new material) | `doubleSided: true` | Closed meshes should be single-sided; `principled_material` and `textured_material` turn culling on |
187
+
188
+ BabylonJS's glTF loader reads all of these extensions into `PBRMaterial`. When you build the material in code
189
+ instead, an ORM texture needs:
190
+ - `useAmbientOcclusionFromMetallicTextureRed`;
191
+ - `useRoughnessFromMetallicTextureGreen`;
192
+ - `useMetallnessFromMetallicTextureBlue`;
193
+ - `useRoughnessFromMetallicTextureAlpha = false`.
194
+
195
+ ---
196
+
197
+ ## 6. Baking node materials to textures
198
+
199
+ `bake_maps(obj, folder, prefix, size, margin_pixels, bake_ao)` bakes the object's own materials (procedural
200
+ noise, ramps, bump, several slots) into one glTF texture set:
201
+
202
+ | Channel | Bake | Target | Written as |
203
+ |---|---|---|---|
204
+ | Base colour | Principled `Base Color` routed through an Emission override, `EMIT` | Float image, Non-Color (raw linear) | `_BaseColor.png`, sRGB-encoded by `linear_to_srgb` |
205
+ | Roughness, metallic | Same override per input, `EMIT` | Float, Non-Color | G and B of `_ORM.png`, linear |
206
+ | Ambient occlusion | `AO`, 128 samples | Float, Non-Color | R of `_ORM.png` (1 when not baked) |
207
+ | Normal | `NORMAL`, tangent space, +X +Y +Z | Float, Non-Color | `_Normal.png`, linear |
208
+
209
+ Baking into float, Non-Color images and encoding in numpy makes the bytes on disk independent of colour
210
+ management and of the packed-float trap (§8.4a). Measured: a lid of linear base colour (0.2, 0.4, 0.6), metallic
211
+ 1, roughness 0.25 came out as base colour bytes (124, 170, 203) and ORM bytes (255, 64, 255), exactly the
212
+ expected values. The normal map's mean was (127.6, 127.6, 255).
213
+
214
+ **Bump on 5.3 defaults to a 1 mm Distance.** The Bump node's `Distance` input is 0.001. With it, a noise bump
215
+ at strength 1 baked to a normal map whose red channel varied by 0.001 (flat to the eye). Set `Distance` to the
216
+ real relief in metres (0.005–0.02 for paint chips, panel dents and wood grain).
217
+
218
+ **Edge padding is the bake margin.** `bake_maps(…, margin_pixels=)` uses the same pixel value as the UV pack
219
+ (section 3 table), with `EXTEND` margins.
220
+
221
+ ---
222
+
223
+ ## 7. Channel packing per engine
224
+
225
+ | Engine / shader | Map | R | G | B | A | Helper |
226
+ |---|---|---|---|---|---|---|
227
+ | glTF, BabylonJS | ORM | Occlusion | Roughness | Metallic | — | `pack_orm` |
228
+ | Unity URP / Built-in Lit | Metallic Map (Smoothness Source = Metallic Alpha) | Metallic | — | — | Smoothness = 1 - roughness | `unity_metallic_smoothness` |
229
+ | Unity URP / Built-in Lit | Occlusion Map | (Unity samples G) | Occlusion | — | — | Write AO to G (or to all three) |
230
+ | Unity HDRP Lit | Mask Map | Metallic | Occlusion | Detail mask | Smoothness | `hdrp_mask_map` |
231
+
232
+ The two engines meet through the Toolkit: a Unity URP material exports as glTF metallic-roughness. The
233
+ exporter bakes `_MetallicGlossMap` into a metal-roughness texture (smoothness from alpha), takes occlusion
234
+ from `_OcclusionMap`'s green channel and re-renders `_BumpMap` (`unity-authoring-recipes.md` §2). So an asset
235
+ going **Blender -> Unity -> BabylonJS** gets URP maps; an asset going **Blender -> BabylonJS** gets ORM.
236
+
237
+ ---
238
+
239
+ ## 8. Material slots are draw calls
240
+
241
+ The glTF exporter writes one primitive per material slot. BabylonJS draws each primitive (a submesh) with its
242
+ own draw call, in every pass that draws the mesh: main, shadow and depth. Five slots on a prop are five draws,
243
+ times the passes, times every copy that does not instance.
244
+
245
+ | Practice | Why |
246
+ |---|---|
247
+ | 1 material per prop, 2 at most (an opaque one plus glass or a decal) | Draws scale with slots |
248
+ | Share materials across variants and props: an atlas or trim sheet | One material can batch and instance |
249
+ | Delete unused slots | qa-check warns; some exporters still emit them |
250
+ | Bake several procedural slots into one texture set, then `replace_materials` | The recipe below turns two slots into one |
251
+ | Keep transparent parts in their own slot only when they really blend | Blended primitives are sorted and drawn separately |
252
+
253
+ ---
254
+
255
+ ### Recipe: unwrap at a fixed density, bake two materials into one ORM set, add UV2, export
256
+
257
+ ```python
258
+ # recipe: crate-bake
259
+ import os, sys
260
+ import bpy
261
+ import construction_kit as kit
262
+ import materials_pbr as pbr
263
+ import uv_layout
264
+
265
+ out = sys.argv[sys.argv.index("--") + 1]
266
+ SIZE, MARGIN, DENSITY = 512, 4, 128.0
267
+ kit.clear_default_scene()
268
+ bpy.ops.mesh.primitive_cube_add(size=1.0)
269
+ crate = bpy.context.active_object
270
+ crate.name = "Crate"
271
+ bevel = crate.modifiers.new("Bevel", "BEVEL")
272
+ bevel.width = 0.03
273
+ bevel.segments = 1
274
+ kit.apply_modifiers(crate)
275
+
276
+ uv_layout.mark_seams_from_sharp(crate, 40) # the chamfers are 45-degree hard edges
277
+ uv_layout.unwrap(crate, SIZE, MARGIN)
278
+ print("after unwrap", uv_layout.texel_density(crate, SIZE)["spread"])
279
+ uv_layout.set_texel_density(crate, DENSITY, SIZE)
280
+ uv_layout.pack(crate, SIZE, MARGIN, scale=False, shape="AABB")
281
+ print("after density", uv_layout.texel_density(crate, SIZE)["spread"])
282
+
283
+ # Two procedural materials: painted wood with a noise bump, and a metal lid.
284
+ paint = bpy.data.materials.new("Paint")
285
+ nodes, links = paint.node_tree.nodes, paint.node_tree.links
286
+ shader = nodes["Principled BSDF"]
287
+ noise = nodes.new("ShaderNodeTexNoise")
288
+ noise.inputs["Scale"].default_value = 8.0
289
+ ramp = nodes.new("ShaderNodeValToRGB")
290
+ ramp.color_ramp.elements[0].color = (*pbr.srgb_to_linear((0.55, 0.35, 0.2)), 1.0)
291
+ ramp.color_ramp.elements[1].color = (*pbr.srgb_to_linear((0.75, 0.55, 0.35)), 1.0)
292
+ links.new(noise.outputs["Fac"], ramp.inputs["Fac"])
293
+ links.new(ramp.outputs["Color"], shader.inputs["Base Color"])
294
+ roughness = nodes.new("ShaderNodeMapRange")
295
+ roughness.inputs["To Min"].default_value, roughness.inputs["To Max"].default_value = 0.45, 0.85
296
+ links.new(noise.outputs["Fac"], roughness.inputs["Value"])
297
+ links.new(roughness.outputs["Result"], shader.inputs["Roughness"])
298
+ bump = nodes.new("ShaderNodeBump")
299
+ bump.inputs["Distance"].default_value = 0.01 # metres of relief; 5.3 defaults to 0.001
300
+ links.new(noise.outputs["Fac"], bump.inputs["Height"])
301
+ links.new(bump.outputs["Normal"], shader.inputs["Normal"])
302
+ metal = pbr.principled_material("Metal", base_color_srgb=(0.78, 0.78, 0.8), metallic=1.0, roughness=0.3)
303
+ crate.data.materials.append(paint)
304
+ crate.data.materials.append(metal)
305
+ max(crate.data.polygons, key=lambda polygon: polygon.center.z).material_index = 1
306
+
307
+ maps = pbr.bake_maps(crate, os.path.join(out, "textures"), "Crate", size=SIZE, margin_pixels=MARGIN, bake_ao=True)
308
+ pbr.save_png(pbr.unity_metallic_smoothness(maps["orm_pixels"]), os.path.join(out, "textures", "Crate_MetallicSmoothness.png"))
309
+ pbr.replace_materials(crate, pbr.textured_material("Crate", maps["base_color"], maps["orm"], maps["normal"]))
310
+ uv_layout.add_lightmap_uv(crate, lightmap_size=256, margin_pixels=2, shape="AABB")
311
+ print("uv2", uv_layout.overlap(crate, "UVLightmap", 1024), uv_layout.island_gap_pixels(crate, "UVLightmap", 256))
312
+ bpy.ops.wm.save_as_mainfile(filepath=os.path.join(out, "crate.blend"))
313
+ ```
314
+
315
+ Then `export --model crate.blend --out crate.glb --tangents on`. Measured:
316
+ - texel density spread 1.47 after the unwrap, 1.00 after `set_texel_density`;
317
+ - UV2 with 0 overlapping texels, islands 3 px apart at 256 for a 2 px margin;
318
+ - the GLB carries `TANGENT`, `TEXCOORD_0` and `TEXCOORD_1`, three PNGs (base colour, ORM, normal) and one
319
+ single-sided material with occlusion and metal-roughness on the same texture;
320
+ - 0 validator errors.
321
+
322
+ ---
323
+
324
+ ## 9. Pitfalls
325
+
326
+ | Symptom | Cause | Fix |
327
+ |---|---|---|
328
+ | Normal-map seams or gradients along hard edges | A hard edge inside a UV island | `mark_seams_from_sharp`, re-unwrap |
329
+ | Some parts blurry, others crisp | Density never equalised (unwrap and pack keep relative island sizes) | `set_texel_density`, then `pack(scale=False)` |
330
+ | Islands spill past 1.0 | Density too high for the texture | `pack(scale=False)` raises with the factor: lower the density or raise the size |
331
+ | Mip-level bleeding between islands | Margin counted as the gap, not per side | `margin_pixels` = padding; the gutter comes out at twice it |
332
+ | `add_lightmap_uv` leaves no active UV map | UV layer references go stale after a layer is added or Edit Mode exits | Look layers up again by name (the helper does) |
333
+ | Lightmap bleeding in Unity | UV2 margin sized for a bigger lightmap than the piece gets | Size it at the piece's lightmap resolution (`environments.md` §8) |
334
+ | Baked base colour darker than the material | DIFFUSE colour pass (§8.4a) | `bake_maps` uses the Emission override |
335
+ | Baked normal map flat | Bump `Distance` left at 0.001 on 5.3 | Set the relief in metres |
336
+ | Roughness reads as metal in Unity | ORM fed to the URP Metallic slot | `unity_metallic_smoothness` (R metal, A smoothness) |
337
+ | AO missing in the GLB | Occlusion wired to nothing the exporter reads | `gltf_material_output(material)` and link R to `Occlusion` |
338
+ | Doubled draw calls on a closed prop | New materials are double-sided | `use_backface_culling = True` (the helpers do) |
339
+ | Alpha-tested foliage exported as BLEND | Render method alone does not choose MASK | Round / Greater Than on alpha, or set the alpha mode in the engine |
340
+
341
+ ---
342
+
343
+ ## 10. Verification checklist
344
+
345
+ 1. Seams on every hard edge: no island contains an edge sharper than the shading angle.
346
+ 2. `texel_density(obj, size)`: every island within ±10 % of the target, spread ≤ 1.1 (≤ 1.3 for organic
347
+ smart-projected assets).
348
+ 3. `bounds` inside 0..1 for unique and atlas UVs; `overlap(obj, None, size)` = 0 texels unless stacking is
349
+ intended.
350
+ 4. `island_gap_pixels(obj, uv, size)` ≥ 2 x padding - 1 for UV0 at the texture size and UV2 at the lightmap size.
351
+ 5. Image colour spaces: base colour and emission sRGB; ORM, normal, metallic-smoothness and masks Non-Color.
352
+ 6. Bake sanity: known-value probe bytes, normal map mean about (128, 128, 255), roughness standard deviation
353
+ ≥ 0.02 (§8.4a's table).
354
+ 7. Export summary: `TANGENT` present with a normal map, `TEXCOORD_1` present with a lightmap UV, the expected
355
+ texture count; occlusion and metal-roughness on one texture; `validate-gltf` 0 errors.
356
+ 8. One material per prop (two at most), no unused slots, single-sided unless the mesh is open.
357
+
358
+ ---
359
+
360
+ ## Sources
361
+
362
+ - Polycount wiki: Texture Coordinates (seams on hard edges, straight UV perimeters), Normal Map (hard edges,
363
+ tangent space), Edge Padding (padding per texture size) — http://wiki.polycount.com/wiki/Texture_Coordinates ,
364
+ http://wiki.polycount.com/wiki/Normal_map , http://wiki.polycount.com/wiki/Edge_padding
365
+ - Foundry Modo documentation, Texel Density — https://learn.foundry.com/modo/content/help/pages/uving/texel_density.html
366
+ - Vertex School, "Texel Density Guide" (512 px/m third person, 1024 first person) —
367
+ https://www.vertexschool.com/texel-density-guide
368
+ - Unity Manual, Generating lightmap UVs (rules for UV2) —
369
+ https://docs.unity.com/en-us/engine/6000.6/manual/lighting-overview/direct-and-indirect-lighting/lightmapping/lighting-gi-uvs/generating-lightmapping-uvs
370
+ - Unity Manual, URP Lit shader (Metallic Map alpha as smoothness, occlusion map) —
371
+ https://docs.unity.com/en-us/engine/6000.0/manual/materials-and-shaders/built-in/shaders-in-universalrp/reference/lit-shader
372
+ - Khronos, glTF 2.0 specification (metallicRoughness channels, occlusion R, normal +Y, colour spaces) —
373
+ https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html
374
+ - Blender Manual, glTF 2.0 add-on (custom glTF Material Output group, alpha modes, extensions) —
375
+ https://docs.blender.org/manual/en/latest/addons/import_export/scene_gltf2.html
376
+ - Babylon.js documentation, Master the PBR Material (metallic texture channel flags) —
377
+ https://doc.babylonjs.com/features/featuresDeepDive/materials/using/masterPBR/
378
+ - Adobe, "The PBR Guide, Part 2" (albedo ranges, metal reflectance, texel density and metal edges) —
379
+ https://www.adobe.com/learn/substance-3d-designer/web/the-pbr-guide-part-2
380
+ - EL4CTEO/blender-skills (MIT, © 2026 EL4CTEO): texel-density measurement per island and its spread target,
381
+ seams from sharp edges, ORM packing with numpy; ideas re-implemented and re-measured here, no code taken.