@babylonjs-toolkit/agent 1.2.16 → 1.2.21

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 (70) hide show
  1. package/README.md +3 -2
  2. package/package.json +1 -1
  3. package/skills/bt-blender/SKILL.md +448 -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 +724 -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 +637 -0
  16. package/skills/bt-blender/scripts/blender/__pycache__/construction_kit.cpython-313.pyc +0 -0
  17. package/skills/bt-blender/scripts/blender/__pycache__/geometry_nodes_builders.cpython-313.pyc +0 -0
  18. package/skills/bt-blender/scripts/blender/__pycache__/image_measure.cpython-313.pyc +0 -0
  19. package/skills/bt-blender/scripts/blender/__pycache__/reference_traces.cpython-313.pyc +0 -0
  20. package/skills/bt-blender/scripts/blender/assembly_check.py +420 -0
  21. package/skills/bt-blender/scripts/blender/blueprint.py +293 -0
  22. package/skills/bt-blender/scripts/blender/character_blockout.py +462 -0
  23. package/skills/bt-blender/scripts/blender/construction_kit.py +1770 -0
  24. package/skills/bt-blender/scripts/blender/coverage_check.py +221 -0
  25. package/skills/bt-blender/scripts/blender/environment_kit.py +525 -0
  26. package/skills/bt-blender/scripts/blender/evidence_sheet.py +243 -0
  27. package/skills/bt-blender/scripts/blender/export_asset.py +623 -0
  28. package/skills/bt-blender/scripts/blender/geometry_nodes_builders.py +575 -0
  29. package/skills/bt-blender/scripts/blender/hard_surface_panels.py +374 -0
  30. package/skills/bt-blender/scripts/blender/hard_surface_trims.py +200 -0
  31. package/skills/bt-blender/scripts/blender/image_measure.py +917 -0
  32. package/skills/bt-blender/scripts/blender/materials_pbr.py +439 -0
  33. package/skills/bt-blender/scripts/blender/measure_stations.py +496 -0
  34. package/skills/bt-blender/scripts/blender/ortho_views.py +309 -0
  35. package/skills/bt-blender/scripts/blender/overlay_sheet.py +238 -0
  36. package/skills/bt-blender/scripts/blender/procedural_game_ready.py +258 -0
  37. package/skills/bt-blender/scripts/blender/procedural_generators.py +842 -0
  38. package/skills/bt-blender/scripts/blender/qa_check.py +729 -0
  39. package/skills/bt-blender/scripts/blender/reference_traces.py +344 -0
  40. package/skills/bt-blender/scripts/blender/retopology_tools.py +781 -0
  41. package/skills/bt-blender/scripts/blender/review_render.py +358 -0
  42. package/skills/bt-blender/scripts/blender/rigging_tools.py +1170 -0
  43. package/skills/bt-blender/scripts/blender/style_palette.py +190 -0
  44. package/skills/bt-blender/scripts/blender/tool_common.py +289 -0
  45. package/skills/bt-blender/scripts/blender/trace.py +283 -0
  46. package/skills/bt-blender/scripts/blender/uv_layout.py +555 -0
  47. package/skills/bt-blender/scripts/blender/vehicle_parts.py +370 -0
  48. package/skills/bt-blender/scripts/blender/view_consistency.py +133 -0
  49. package/skills/bt-blender/scripts/blender/world_gate.py +231 -0
  50. package/skills/bt-blender/scripts/bt-blender.mjs +333 -0
  51. package/skills/bt-blender/scripts/validate_gltf.mjs +204 -0
  52. package/skills/bt-execute/SKILL.md +2 -1
  53. package/skills/bt-gauntlet/SKILL.md +30 -20
  54. package/skills/bt-gauntlet/references/critic-rubrics.md +106 -7
  55. package/skills/bt-gauntlet/references/loop-templates.md +23 -3
  56. package/skills/bt-gauntlet/references/spec-composition.md +20 -1
  57. package/skills/bt-gauntlet/references/target-images.md +27 -0
  58. package/skills/bt-gauntlet/references/unity-pipeline.md +41 -4
  59. package/skills/bt-gauntlet/references/workspace.md +90 -6
  60. package/skills/bt-unwrap/scripts/blender/__pycache__/bt_unwrap.cpython-313.pyc +0 -0
  61. package/skills/bt-unwrap/scripts/blender/__pycache__/image_utils.cpython-313.pyc +0 -0
  62. package/skills/bt-unwrap/scripts/blender/__pycache__/mesh_tools.cpython-313.pyc +0 -0
  63. package/skills/bt-unwrap/scripts/blender/__pycache__/model_io.cpython-313.pyc +0 -0
  64. package/skills/bt-unwrap/scripts/blender/__pycache__/previews.cpython-313.pyc +0 -0
  65. package/skills/bt-unwrap/scripts/blender/__pycache__/rasterizer.cpython-313.pyc +0 -0
  66. package/skills/bt-unwrap/scripts/blender/__pycache__/reference_views.cpython-313.pyc +0 -0
  67. package/skills/bt-unwrap/scripts/blender/__pycache__/reference_warp.cpython-313.pyc +0 -0
  68. package/skills/bt-unwrap/scripts/blender/__pycache__/texture_bake.cpython-313.pyc +0 -0
  69. package/skills/bt-unwrap/scripts/blender/__pycache__/texture_compose.cpython-313.pyc +0 -0
  70. package/skills/bt-unwrap/scripts/blender/__pycache__/uv_layout.cpython-313.pyc +0 -0
@@ -0,0 +1,842 @@
1
+ """
2
+ bt-blender procedural generators: seeded, deterministic bpy / bmesh generators for game props and set
3
+ dressing, and the bookkeeping that makes a variation set reproducible.
4
+
5
+ import procedural_generators as procedural
6
+
7
+ rocks = [procedural.rock(f"Rock_{seed:03d}", seed) for seed in (1, 2, 3)]
8
+ manifest = procedural.variation_manifest(rocks, {"generator": "rock"})
9
+
10
+ What is in it:
11
+ - randomness: SeededRandom (only Random.random() is used, the one call Python guarantees reproducible across
12
+ versions; streams are split by label with SHA-256, never with hash(), which changes per process);
13
+ - generators: rock (planar cleavage cuts + fractal displacement, voxel remesh, decimated to a budget, grounded),
14
+ building (bay-grid facade with recessed windows, parapet, embedded roof greebles, three material slots,
15
+ world-scale box UVs), space_colonization (Runions et al. 2007 tree skeletons), lsystem_expand +
16
+ lsystem_skeleton (bracketed, optionally stochastic L-systems with a 3D turtle), skin_skeleton (tubes with
17
+ pipe-model radii), closed_track_centerline + road_ribbon (a closed racing line and a banked road strip with
18
+ metre UVs);
19
+ - determinism: geometry_fingerprint (SHA-256 of the evaluated mesh), variation_manifest (seed, parameters,
20
+ versions and fingerprint of every variant).
21
+
22
+ Lengths are metres, Blender Z up, -Y forward; every generator returns a new object with its origin at the
23
+ bottom centre (ground contact at Z = 0) unless it says otherwise.
24
+ """
25
+ import hashlib
26
+ import math
27
+ import random as python_random
28
+ import sys
29
+
30
+ import bmesh
31
+ import bpy
32
+ import numpy as np
33
+ from mathutils import Matrix, Vector, noise
34
+ from mathutils.kdtree import KDTree
35
+
36
+ import construction_kit as kit
37
+ import uv_layout
38
+
39
+ # Decimal places kept when fingerprinting coordinates (0.1 micrometre): below float noise between runs,
40
+ # far above any real change.
41
+ FINGERPRINT_DECIMALS = 7
42
+
43
+ # Bytes of a SHA-256 digest turned into a child seed.
44
+ CHILD_SEED_BYTES = 8
45
+
46
+ # Rock: icosphere subdivisions of the starting blob, voxel resolution (divisions of the smallest dimension),
47
+ # and the noise lacunarity and gain.
48
+ ROCK_SPHERE_SUBDIVISIONS = 5
49
+ ROCK_VOXEL_DIVISIONS = 40
50
+ ROCK_NOISE_LACUNARITY = 2.0
51
+ ROCK_NOISE_GAIN = 0.5
52
+
53
+ # Rock shading: edges sharper than this become hard (the cleavage facets); rounder ones stay smooth.
54
+ ROCK_SHARP_ANGLE_DEGREES = 50.0
55
+
56
+ # Building: frame width around each window, how deep a greeble sinks into the roof (so it touches instead
57
+ # of floating or z-fighting), and the greeble size range in metres.
58
+ WINDOW_FRAME_WIDTH = 0.12
59
+ GREEBLE_EMBED_DEPTH = 0.02
60
+ GREEBLE_SIZE_RANGE = (0.6, 1.6)
61
+ GREEBLE_HEIGHT_RANGE = (0.4, 1.0)
62
+
63
+ # Rooftop units keep this gap (metres) from each other and from the parapet; a unit that cannot be placed
64
+ # after this many tries is left out.
65
+ GREEBLE_CLEARANCE = 0.3
66
+ GREEBLE_PLACEMENT_ATTEMPTS = 24
67
+
68
+ # Building material slots, in order (material_index values).
69
+ BUILDING_SLOTS = ("Wall", "Glass", "Trim")
70
+
71
+ # Pipe model exponent for branch radii: r_parent^n = sum(r_child^n); 2 conserves area (da Vinci), 3 matches
72
+ # measured trees better at the tips; 2.5 sits between.
73
+ PIPE_MODEL_EXPONENT = 2.5
74
+
75
+ # A side branch starts inside its parent at this share of its own radius (see skin_skeleton).
76
+ BRANCH_BASE_SCALE = 0.5
77
+
78
+ # A growth step whose summed pull is shorter than this is a tie between opposite attraction points; skip it.
79
+ GROWTH_TIE_EPSILON = 1e-6
80
+
81
+ # Road: centripetal Catmull-Rom exponent and the up vector the road's side direction is taken against.
82
+ CENTRIPETAL_EXPONENT = 0.5
83
+ WORLD_UP = Vector((0.0, 0.0, 1.0))
84
+
85
+ # Merge distance that welds a closed road's duplicated seam ring (positions only; UVs keep their seam).
86
+ SEAM_WELD_DISTANCE = 1e-5
87
+
88
+
89
+ # --- randomness ---------------------------------------------------------------------------------------------
90
+
91
+ class SeededRandom:
92
+ """
93
+ Deterministic random numbers for generators. Everything derives from `random.Random(seed).random()`,
94
+ the one method Python promises gives the same sequence for the same seed across versions (`randint`,
95
+ `choice`, `shuffle` and `gauss` may change). Independent streams come from `child(label)`, so adding a
96
+ new random call in one part of a generator does not shift every number in the others.
97
+ """
98
+
99
+ def __init__(self, seed: int):
100
+ """:param seed: Any integer; record it with the asset."""
101
+ self.seed = int(seed)
102
+ self._generator = python_random.Random(self.seed)
103
+
104
+ def child(self, label: str) -> "SeededRandom":
105
+ """
106
+ An independent stream for one part of a generator.
107
+
108
+ :param label: Stream name, e.g. "cuts" or "windows".
109
+ :returns: A SeededRandom seeded from SHA-256(seed, label) - stable across processes and versions.
110
+ """
111
+ digest = hashlib.sha256(f"{self.seed}:{label}".encode("utf-8")).digest()
112
+ return SeededRandom(int.from_bytes(digest[:CHILD_SEED_BYTES], "big"))
113
+
114
+ def random(self) -> float:
115
+ """A float in [0, 1)."""
116
+ return self._generator.random()
117
+
118
+ def uniform(self, low: float, high: float) -> float:
119
+ """A float in [low, high)."""
120
+ return low + (high - low) * self.random()
121
+
122
+ def integer(self, low: int, high: int) -> int:
123
+ """An integer in [low, high], both included."""
124
+ return low + min(int(self.random() * (high - low + 1)), high - low)
125
+
126
+ def chance(self, probability: float) -> bool:
127
+ """True with the given probability."""
128
+ return self.random() < probability
129
+
130
+ def choice(self, items):
131
+ """One item of a non-empty sequence."""
132
+ return items[self.integer(0, len(items) - 1)]
133
+
134
+ def unit_vector(self) -> Vector:
135
+ """A direction uniformly distributed over the sphere."""
136
+ height = self.uniform(-1.0, 1.0)
137
+ angle = self.uniform(0.0, 2.0 * math.pi)
138
+ ring = math.sqrt(max(0.0, 1.0 - height * height))
139
+ return Vector((ring * math.cos(angle), ring * math.sin(angle), height))
140
+
141
+ def point_in_ellipsoid(self, center, radii) -> Vector:
142
+ """A point uniformly distributed inside an axis-aligned ellipsoid (rejection sampling)."""
143
+ while True:
144
+ sample = Vector((self.uniform(-1, 1), self.uniform(-1, 1), self.uniform(-1, 1)))
145
+ if sample.length_squared <= 1.0:
146
+ return Vector(center) + Vector((sample.x * radii[0], sample.y * radii[1], sample.z * radii[2]))
147
+
148
+
149
+ # --- shared helpers -----------------------------------------------------------------------------------------
150
+
151
+ def _mesh_object(name: str, edit_mesh: bmesh.types.BMesh) -> bpy.types.Object:
152
+ """Writes a bmesh into a new mesh object linked to the scene (replacing one of that name), freeing the bmesh."""
153
+ old = bpy.data.objects.get(name)
154
+ if old is not None:
155
+ old_mesh = old.data if old.type == "MESH" else None
156
+ bpy.data.objects.remove(old)
157
+ if old_mesh is not None and old_mesh.users == 0:
158
+ bpy.data.meshes.remove(old_mesh)
159
+ mesh = bpy.data.meshes.new(name)
160
+ edit_mesh.to_mesh(mesh)
161
+ edit_mesh.free()
162
+ obj = bpy.data.objects.new(name, mesh)
163
+ bpy.context.scene.collection.objects.link(obj)
164
+ return obj
165
+
166
+
167
+ def _ground(obj: bpy.types.Object, sink: float = 0.0) -> None:
168
+ """Moves the mesh so its lowest point sits at Z = -sink and its XY bounds are centred on the origin."""
169
+ coordinates = np.empty(len(obj.data.vertices) * 3)
170
+ obj.data.vertices.foreach_get("co", coordinates)
171
+ points = coordinates.reshape(-1, 3)
172
+ center = (points.min(axis=0) + points.max(axis=0)) / 2.0
173
+ offset = Vector((-center[0], -center[1], -points[:, 2].min() - sink))
174
+ obj.data.transform(Matrix.Translation(offset))
175
+ obj.data.update()
176
+
177
+
178
+ def assign_slots(obj: bpy.types.Object, slot_names) -> list:
179
+ """
180
+ Gives the object one material per slot name, reusing materials of the same name (so variants share
181
+ materials and batch together). Slots are filled in place: `materials.clear()` would also reset every
182
+ face's material index to 0.
183
+
184
+ :returns: The materials, in slot order.
185
+ """
186
+ materials = []
187
+ for slot_index, slot_name in enumerate(slot_names):
188
+ material = bpy.data.materials.get(slot_name) or bpy.data.materials.new(slot_name)
189
+ if slot_index < len(obj.data.materials):
190
+ obj.data.materials[slot_index] = material
191
+ else:
192
+ obj.data.materials.append(material)
193
+ materials.append(material)
194
+ return materials
195
+
196
+
197
+ # --- rock ---------------------------------------------------------------------------------------------------
198
+
199
+ def rock(name: str, seed: int, size=(1.0, 0.8, 0.6), cuts: int = 7, cut_depth=(0.08, 0.3),
200
+ noise_scale: float = 1.6, noise_strength: float = 0.08, octaves: int = 4, target_triangles: int = 1200,
201
+ material: str = "Rock", sink: float = 0.0) -> bpy.types.Object:
202
+ """
203
+ A boulder: an ellipsoid cleaved by random planes (the flat fracture faces that read as rock rather than
204
+ blob), roughened with fractal noise along the normals, voxel-remeshed into even, manifold topology,
205
+ decimated to a triangle budget, shaded hard on the fracture edges only, unwrapped, and grounded (origin at
206
+ the bottom centre). Rocks sit in the ground rather than balance on it: bury them when placing (a scatter
207
+ offset), or pass `sink` to bake the burial into the asset.
208
+
209
+ :param name: Object name (an existing object of that name is replaced).
210
+ :param seed: Variation seed.
211
+ :param size: Bounding size in metres before cuts (x, y, z).
212
+ :param cuts: Number of cleavage planes.
213
+ :param cut_depth: Range of how deep each plane cuts, as a share of the radius along its normal.
214
+ :param noise_scale: Noise frequency per metre (bigger = smaller lumps).
215
+ :param noise_strength: Displacement amplitude in metres at unit size (scaled by the rock's mean radius).
216
+ :param octaves: Fractal octaves.
217
+ :param target_triangles: Triangle budget after decimation (what the engine draws).
218
+ :param material: Material slot name.
219
+ :param sink: Metres the base goes below Z = 0 (about 5 % of the height reads as embedded).
220
+ :returns: The rock object.
221
+ """
222
+ stream = SeededRandom(seed)
223
+ radii = Vector(size) / 2.0
224
+ edit_mesh = bmesh.new()
225
+ bmesh.ops.create_icosphere(edit_mesh, subdivisions=ROCK_SPHERE_SUBDIVISIONS, radius=1.0)
226
+ for vertex in edit_mesh.verts:
227
+ vertex.co = Vector((vertex.co.x * radii.x, vertex.co.y * radii.y, vertex.co.z * radii.z))
228
+ _cleave(edit_mesh, radii, stream.child("cuts"), cuts, cut_depth)
229
+ _displace(edit_mesh, stream.child("noise"), noise_scale, noise_strength * sum(radii) / 3.0, octaves)
230
+ obj = _mesh_object(name, edit_mesh)
231
+ remesh = obj.modifiers.new("Remesh", "REMESH")
232
+ remesh.mode = "VOXEL"
233
+ remesh.voxel_size = min(size) / ROCK_VOXEL_DIVISIONS
234
+ kit.apply_modifiers(obj)
235
+ decimate = obj.modifiers.new("Decimate", "DECIMATE")
236
+ decimate.decimate_type = "COLLAPSE"
237
+ decimate.ratio = min(1.0, target_triangles / max(_triangle_count(obj), 1))
238
+ kit.apply_modifiers(obj)
239
+ _ground(obj, sink=sink)
240
+ kit.shade_smooth(obj, sharp_angle_degrees=ROCK_SHARP_ANGLE_DEGREES)
241
+ assign_slots(obj, [material])
242
+ kit.smart_unwrap(obj, angle_limit_degrees=ROCK_SHARP_ANGLE_DEGREES, island_margin=0.01)
243
+ obj["bt_seed"] = seed
244
+ obj["bt_generator"] = "rock"
245
+ return obj
246
+
247
+
248
+ def _triangle_count(obj: bpy.types.Object) -> int:
249
+ """Triangles the mesh draws as (an n-gon is n - 2)."""
250
+ return sum(len(polygon.vertices) - 2 for polygon in obj.data.polygons)
251
+
252
+
253
+ def _cleave(edit_mesh, radii: Vector, stream: SeededRandom, cuts: int, cut_depth) -> None:
254
+ """Flattens everything beyond `cuts` random planes onto them (fracture faces). The underside is spared."""
255
+ for _ in range(cuts):
256
+ normal = stream.unit_vector()
257
+ if normal.z < -0.5: # the buried underside keeps its shape
258
+ normal.z = -normal.z
259
+ reach = math.sqrt((normal.x * radii.x) ** 2 + (normal.y * radii.y) ** 2 + (normal.z * radii.z) ** 2)
260
+ plane = reach * (1.0 - stream.uniform(*cut_depth))
261
+ for vertex in edit_mesh.verts:
262
+ beyond = vertex.co.dot(normal) - plane
263
+ if beyond > 0.0:
264
+ vertex.co -= normal * beyond
265
+
266
+
267
+ def _displace(edit_mesh, stream: SeededRandom, frequency: float, amplitude: float, octaves: int) -> None:
268
+ """Moves each vertex along its normal by fractal Perlin noise sampled at a seed-dependent offset."""
269
+ offset = Vector((stream.uniform(-500, 500), stream.uniform(-500, 500), stream.uniform(-500, 500)))
270
+ edit_mesh.normal_update()
271
+ moves = []
272
+ for vertex in edit_mesh.verts:
273
+ sample = vertex.co * frequency + offset
274
+ value = noise.fractal(sample, ROCK_NOISE_GAIN, ROCK_NOISE_LACUNARITY, octaves, noise_basis="PERLIN_ORIGINAL")
275
+ moves.append(vertex.normal * (value * amplitude))
276
+ for vertex, move in zip(edit_mesh.verts, moves):
277
+ vertex.co += move
278
+
279
+
280
+ # --- building -----------------------------------------------------------------------------------------------
281
+
282
+ def building(name: str, seed: int, width_range=(8.0, 14.0), depth_range=(8.0, 14.0), floors_range=(2, 6),
283
+ floor_height: float = 3.2, bay_width: float = 2.6, window_size=(1.4, 1.7), window_depth: float = 0.18,
284
+ window_chance: float = 0.85, parapet_height: float = 0.6, parapet_width: float = 0.3,
285
+ greebles_range=(1, 4), texture_metres: float = 4.0) -> bpy.types.Object:
286
+ """
287
+ A low-rise block: a closed wall shell on a bay grid (corners shared, so it is manifold), windows inset
288
+ and recessed per bay, a parapet roof well, and rooftop units sunk a little into the roof deck. Materials:
289
+ slot 0 Wall, 1 Glass, 2 Trim (frames and parapet cap). UVs are world-scale box projection
290
+ (`texture_metres` per tile), so every variant has the same texel density on a tiling or trim material.
291
+
292
+ :param name: Object name (replaced if it exists).
293
+ :param seed: Variation seed.
294
+ :param width_range: Footprint width range in metres (snapped to whole bays).
295
+ :param depth_range: Footprint depth range in metres (snapped to whole bays).
296
+ :param floors_range: Floor count range, both included.
297
+ :param floor_height: Metres per floor.
298
+ :param bay_width: Facade bay width in metres.
299
+ :param window_size: Window (width, height) in metres.
300
+ :param window_depth: How far the glass sits behind the wall.
301
+ :param window_chance: Probability that an upper-floor bay has a window.
302
+ :param parapet_height: Roof well depth in metres.
303
+ :param parapet_width: Parapet wall thickness in metres.
304
+ :param greebles_range: Rooftop unit count range.
305
+ :param texture_metres: Metres per UV tile.
306
+ :returns: The building object.
307
+ """
308
+ stream = SeededRandom(seed)
309
+ shape = stream.child("shape")
310
+ bays_x = max(2, round(shape.uniform(*width_range) / bay_width))
311
+ bays_y = max(2, round(shape.uniform(*depth_range) / bay_width))
312
+ floors = shape.integer(*floors_range)
313
+ edit_mesh = bmesh.new()
314
+ rings = _wall_rings(edit_mesh, bays_x, bays_y, floors, bay_width, floor_height)
315
+ wall_faces = _wall_faces(edit_mesh, rings)
316
+ edit_mesh.normal_update() # bmesh insets offset along face normals: compute them first
317
+ _cut_windows(edit_mesh, wall_faces, stream.child("windows"), bay_width, floor_height, window_size,
318
+ window_depth, window_chance)
319
+ roof = _roof(edit_mesh, rings[-1], parapet_width, parapet_height)
320
+ bottom = edit_mesh.faces.new(list(reversed(rings[0])))
321
+ bottom.material_index = 0
322
+ roof_height = floors * floor_height - parapet_height
323
+ _roof_units(edit_mesh, roof, stream.child("greebles"), greebles_range, roof_height)
324
+ bmesh.ops.recalc_face_normals(edit_mesh, faces=edit_mesh.faces[:])
325
+ obj = _mesh_object(name, edit_mesh)
326
+ assign_slots(obj, BUILDING_SLOTS)
327
+ kit.shade_smooth(obj, sharp_angle_degrees=30.0)
328
+ uv_layout.box_project(obj, texture_metres)
329
+ obj["bt_seed"] = seed
330
+ obj["bt_generator"] = "building"
331
+ return obj
332
+
333
+
334
+ def _perimeter(bays_x: int, bays_y: int, bay_width: float) -> list:
335
+ """Counter-clockwise footprint points on the bay grid, centred on the origin, corners shared."""
336
+ half_x, half_y = bays_x * bay_width / 2.0, bays_y * bay_width / 2.0
337
+ points = [(-half_x + i * bay_width, -half_y) for i in range(bays_x)]
338
+ points += [(half_x, -half_y + i * bay_width) for i in range(bays_y)]
339
+ points += [(half_x - i * bay_width, half_y) for i in range(bays_x)]
340
+ points += [(-half_x, half_y - i * bay_width) for i in range(bays_y)]
341
+ return points
342
+
343
+
344
+ def _wall_rings(edit_mesh, bays_x: int, bays_y: int, floors: int, bay_width: float, floor_height: float) -> list:
345
+ """One ring of perimeter vertices per floor line."""
346
+ perimeter = _perimeter(bays_x, bays_y, bay_width)
347
+ return [[edit_mesh.verts.new((x, y, level * floor_height)) for x, y in perimeter] for level in range(floors + 1)]
348
+
349
+
350
+ def _wall_faces(edit_mesh, rings: list) -> list:
351
+ """One quad per bay per floor; returns [(floor, face)]."""
352
+ faces = []
353
+ for floor, (lower, upper) in enumerate(zip(rings, rings[1:])):
354
+ count = len(lower)
355
+ for i in range(count):
356
+ face = edit_mesh.faces.new((lower[i], lower[(i + 1) % count], upper[(i + 1) % count], upper[i]))
357
+ face.material_index = 0
358
+ faces.append((floor, face))
359
+ return faces
360
+
361
+
362
+ def _cut_windows(edit_mesh, wall_faces, stream: SeededRandom, bay_width: float, floor_height: float,
363
+ window_size, window_depth: float, window_chance: float) -> None:
364
+ """Insets a window into chosen bays (ground floor: every other bay, as shop fronts) and recesses the glass."""
365
+ side_inset = max(WINDOW_FRAME_WIDTH, (bay_width - window_size[0]) / 2.0)
366
+ vertical_inset = max(WINDOW_FRAME_WIDTH, (floor_height - window_size[1]) / 2.0)
367
+ inset = min(side_inset, vertical_inset)
368
+ for floor, face in wall_faces:
369
+ has_window = _alternate_bay(face, bay_width) if floor == 0 else stream.chance(window_chance)
370
+ if not has_window:
371
+ continue
372
+ result = bmesh.ops.inset_individual(edit_mesh, faces=[face], thickness=inset, depth=-window_depth,
373
+ use_even_offset=True)
374
+ face.material_index = 1
375
+ for frame in result["faces"]:
376
+ frame.material_index = 2
377
+
378
+
379
+ def _alternate_bay(face, bay_width: float) -> bool:
380
+ """True on every other bay along each facade, read from the bay's position, not from creation order."""
381
+ center = face.calc_center_median()
382
+ bay_index = math.floor((center.x + center.y) / bay_width)
383
+ return bay_index % 2 == 0
384
+
385
+
386
+ def _roof(edit_mesh, top_ring: list, parapet_width: float, parapet_height: float):
387
+ """
388
+ Caps the shell with a parapet: a flat inset ring on top (Trim, the coping), then a straight drop into the
389
+ roof well (Wall, vertical inner faces), whose floor is the roof deck. Returns the deck face.
390
+ """
391
+ cap = edit_mesh.faces.new(top_ring)
392
+ cap.normal_update()
393
+ coping = bmesh.ops.inset_individual(edit_mesh, faces=[cap], thickness=parapet_width, depth=0.0,
394
+ use_even_offset=True)
395
+ for face in coping["faces"]:
396
+ face.material_index = 2
397
+ cap.normal_update()
398
+ well = bmesh.ops.inset_individual(edit_mesh, faces=[cap], thickness=0.0, depth=-parapet_height)
399
+ for face in well["faces"]:
400
+ face.material_index = 0
401
+ cap.material_index = 0
402
+ return cap
403
+
404
+
405
+ def _roof_units(edit_mesh, roof_face, stream: SeededRandom, count_range, roof_height: float) -> None:
406
+ """
407
+ Adds rooftop boxes (vents, AC units) sunk GREEBLE_EMBED_DEPTH into the deck, inside the deck and apart
408
+ from each other (overlapping boxes would leave coplanar faces that z-fight). Candidates that collide are
409
+ redrawn up to GREEBLE_PLACEMENT_ATTEMPTS times each, then skipped. The buried bottom face is deleted: it
410
+ can never be seen, and it would sit back-to-back with the deck.
411
+ """
412
+ xs = [vertex.co.x for vertex in roof_face.verts]
413
+ ys = [vertex.co.y for vertex in roof_face.verts]
414
+ placed = []
415
+ for _ in range(stream.integer(*count_range)):
416
+ for _attempt in range(GREEBLE_PLACEMENT_ATTEMPTS):
417
+ size_x, size_y = stream.uniform(*GREEBLE_SIZE_RANGE), stream.uniform(*GREEBLE_SIZE_RANGE)
418
+ height = stream.uniform(*GREEBLE_HEIGHT_RANGE)
419
+ x = stream.uniform(min(xs) + size_x / 2 + GREEBLE_CLEARANCE, max(xs) - size_x / 2 - GREEBLE_CLEARANCE)
420
+ y = stream.uniform(min(ys) + size_y / 2 + GREEBLE_CLEARANCE, max(ys) - size_y / 2 - GREEBLE_CLEARANCE)
421
+ footprint = (x - size_x / 2, y - size_y / 2, x + size_x / 2, y + size_y / 2)
422
+ if not any(_rectangles_near(footprint, other, GREEBLE_CLEARANCE) for other in placed):
423
+ break
424
+ else:
425
+ continue
426
+ placed.append(footprint)
427
+ matrix = Matrix.Translation((x, y, roof_height + height / 2.0 - GREEBLE_EMBED_DEPTH)) @ \
428
+ Matrix.Diagonal((size_x, size_y, height, 1.0))
429
+ result = bmesh.ops.create_cube(edit_mesh, size=1.0, matrix=matrix)
430
+ unit_faces = {face for vertex in result["verts"] for face in vertex.link_faces}
431
+ hidden_bottom = min(unit_faces, key=lambda face: face.calc_center_median().z)
432
+ bmesh.ops.delete(edit_mesh, geom=[hidden_bottom], context="FACES_ONLY")
433
+ for face in unit_faces - {hidden_bottom}:
434
+ face.material_index = 2
435
+
436
+
437
+ def _rectangles_near(first, second, clearance: float) -> bool:
438
+ """True when two (min x, min y, max x, max y) rectangles overlap or come closer than `clearance`."""
439
+ return not (first[2] + clearance <= second[0] or second[2] + clearance <= first[0] or
440
+ first[3] + clearance <= second[1] or second[3] + clearance <= first[1])
441
+
442
+
443
+ # --- branching structures -------------------------------------------------------------------------------------
444
+
445
+ def space_colonization(seed: int, crown_center=(0.0, 0.0, 4.5), crown_radii=(2.2, 2.2, 1.8),
446
+ attraction_points: int = 600, segment_length: float = 0.25, influence_radius=None,
447
+ kill_distance=None, max_iterations: int = 400, tip_radius: float = 0.012) -> dict:
448
+ """
449
+ A tree skeleton grown by space colonisation (Runions, Lane and Prusinkiewicz, 2007): attraction points
450
+ fill the crown; each pulls the nearest skeleton node within the influence radius; every pulled node grows
451
+ one segment along the normalised sum of its pulls; points closer than the kill distance to a node are
452
+ used up. Branches therefore compete for space instead of following a recursive rule. The trunk grows
453
+ straight up from the origin until the crown starts pulling it.
454
+
455
+ :param seed: Variation seed (places the attraction points).
456
+ :param crown_center: Crown ellipsoid centre in metres.
457
+ :param crown_radii: Crown ellipsoid radii in metres.
458
+ :param attraction_points: How many points fill the crown (more = denser, finer branching).
459
+ :param segment_length: D, the node spacing in metres.
460
+ :param influence_radius: d_i (default 8 D: smooth, open branching; small values give gnarled, wandering tips).
461
+ :param kill_distance: d_k (default 2 D, as in the paper's figures).
462
+ :param max_iterations: Growth step limit.
463
+ :param tip_radius: Branch tip radius in metres; parents follow the pipe model.
464
+ :returns: {"positions": [Vector], "parents": [int, -1 for the root], "radii": [float]}.
465
+ """
466
+ stream = SeededRandom(seed).child("attractors")
467
+ influence = influence_radius or 8.0 * segment_length
468
+ kill = kill_distance or 2.0 * segment_length
469
+ attractors = [stream.point_in_ellipsoid(crown_center, crown_radii) for _ in range(attraction_points)]
470
+ positions, parents = [Vector((0.0, 0.0, 0.0))], [-1]
471
+ _grow_trunk(positions, parents, attractors, influence, segment_length, crown_center)
472
+ for _ in range(max_iterations):
473
+ if not attractors:
474
+ break
475
+ grown = _colonize_step(positions, parents, attractors, influence, segment_length)
476
+ attractors = _remove_reached(attractors, positions, kill)
477
+ if not grown:
478
+ break
479
+ return {"positions": positions, "parents": parents,
480
+ "radii": _pipe_radii(parents, tip_radius, PIPE_MODEL_EXPONENT)}
481
+
482
+
483
+ def _grow_trunk(positions, parents, attractors, influence: float, segment_length: float, crown_center) -> None:
484
+ """Grows the root straight up until some attraction point is within reach."""
485
+ limit = Vector(crown_center).z
486
+ while positions[-1].z < limit and all((point - positions[-1]).length > influence for point in attractors):
487
+ positions.append(positions[-1] + Vector((0.0, 0.0, segment_length)))
488
+ parents.append(len(positions) - 2)
489
+
490
+
491
+ def _node_tree(positions) -> KDTree:
492
+ """A balanced KD-tree over the skeleton nodes."""
493
+ tree = KDTree(len(positions))
494
+ for index, position in enumerate(positions):
495
+ tree.insert(position, index)
496
+ tree.balance()
497
+ return tree
498
+
499
+
500
+ def _colonize_step(positions, parents, attractors, influence: float, segment_length: float) -> int:
501
+ """One iteration: every attraction point pulls its nearest node within reach; returns the nodes added."""
502
+ tree = _node_tree(positions)
503
+ pulls = {}
504
+ for point in attractors:
505
+ _, nearest, distance = tree.find(point)
506
+ if distance <= influence:
507
+ pull = (point - positions[nearest]).normalized()
508
+ pulls[nearest] = pulls[nearest] + pull if nearest in pulls else pull
509
+ added = 0
510
+ for node in sorted(pulls):
511
+ direction = pulls[node]
512
+ if direction.length < GROWTH_TIE_EPSILON:
513
+ continue
514
+ candidate = positions[node] + direction.normalized() * segment_length
515
+ if tree.find(candidate)[2] < segment_length * 0.5: # would land on an existing node: a stall
516
+ continue
517
+ positions.append(candidate)
518
+ parents.append(node)
519
+ added += 1
520
+ return added
521
+
522
+
523
+ def _remove_reached(attractors, positions, kill: float) -> list:
524
+ """Drops every attraction point within the kill distance of a node."""
525
+ tree = _node_tree(positions)
526
+ return [point for point in attractors if tree.find(point)[2] > kill]
527
+
528
+
529
+ def _pipe_radii(parents, tip_radius: float, exponent: float) -> list:
530
+ """Branch radii by the pipe model, from the tips down: r^n of a node = sum of r^n of its children."""
531
+ children = [[] for _ in parents]
532
+ for index, parent in enumerate(parents):
533
+ if parent >= 0:
534
+ children[parent].append(index)
535
+ radii = [0.0] * len(parents)
536
+ for index in reversed(range(len(parents))): # children always come after their parent
537
+ if not children[index]:
538
+ radii[index] = tip_radius
539
+ else:
540
+ radii[index] = sum(radii[child] ** exponent for child in children[index]) ** (1.0 / exponent)
541
+ return radii
542
+
543
+
544
+ def lsystem_expand(axiom: str, rules: dict, iterations: int, seed: int = 0) -> str:
545
+ """
546
+ Rewrites an L-system string in parallel `iterations` times.
547
+
548
+ :param axiom: Start string, e.g. "X".
549
+ :param rules: {symbol: replacement} for a deterministic system, or {symbol: [(weight, replacement), ...]}
550
+ for a stochastic one (a weighted choice per symbol occurrence, from the seed).
551
+ :param iterations: Rewrite count.
552
+ :param seed: Seed for stochastic rules.
553
+ :returns: The expanded string.
554
+ """
555
+ stream = SeededRandom(seed).child("lsystem")
556
+ current = axiom
557
+ for _ in range(iterations):
558
+ pieces = []
559
+ for symbol in current:
560
+ rule = rules.get(symbol, symbol)
561
+ pieces.append(rule if isinstance(rule, str) else _weighted_choice(rule, stream))
562
+ current = "".join(pieces)
563
+ return current
564
+
565
+
566
+ def _weighted_choice(options, stream: SeededRandom) -> str:
567
+ """Picks one replacement from [(weight, replacement)]."""
568
+ total = sum(weight for weight, _ in options)
569
+ target = stream.uniform(0.0, total)
570
+ for weight, replacement in options:
571
+ target -= weight
572
+ if target < 0.0:
573
+ return replacement
574
+ return options[-1][1]
575
+
576
+
577
+ def lsystem_skeleton(commands: str, step: float = 0.4, angle_degrees: float = 25.0, step_decay: float = 0.9,
578
+ tip_radius: float = 0.01) -> dict:
579
+ """
580
+ Interprets a bracketed L-system string with a 3D turtle (Prusinkiewicz and Lindenmayer, The Algorithmic
581
+ Beauty of Plants): F moves forward drawing a segment, f moves without drawing, + and - turn about the up
582
+ axis, & and ^ pitch, \\ and / roll, | turns around, [ pushes the state (and shortens later steps by
583
+ step_decay), ] pops it. Any other symbol is ignored. The turtle starts at the origin heading +Z.
584
+
585
+ :returns: {"positions", "parents", "radii"} like space_colonization (pipe-model radii).
586
+ """
587
+ angle = math.radians(angle_degrees)
588
+ position, orientation, length = Vector(), Matrix.Identity(3), step
589
+ positions, parents = [Vector()], [-1]
590
+ current, stack = 0, []
591
+ # The turtle heads along its local Z: + and - yaw about local Y, & and ^ pitch about local X, \ and / roll
592
+ # about the heading itself, | turns back about local Y.
593
+ turns = {"+": ("Y", angle), "-": ("Y", -angle), "&": ("X", angle), "^": ("X", -angle),
594
+ "\\": ("Z", angle), "/": ("Z", -angle), "|": ("Y", math.pi)}
595
+ for symbol in commands:
596
+ if symbol in ("F", "f"):
597
+ position = position + orientation @ Vector((0.0, 0.0, length))
598
+ if symbol == "F":
599
+ positions.append(position.copy())
600
+ parents.append(current)
601
+ current = len(positions) - 1
602
+ elif symbol in turns:
603
+ axis, turn = turns[symbol]
604
+ orientation = orientation @ Matrix.Rotation(turn, 3, axis)
605
+ elif symbol == "[":
606
+ stack.append((position.copy(), orientation.copy(), length, current))
607
+ length *= step_decay
608
+ elif symbol == "]" and stack:
609
+ position, orientation, length, current = stack.pop()
610
+ return {"positions": positions, "parents": parents, "radii": _pipe_radii(parents, tip_radius, PIPE_MODEL_EXPONENT)}
611
+
612
+
613
+ def skin_skeleton(name: str, skeleton: dict, sides: int = 6, material: str = "Bark") -> bpy.types.Object:
614
+ """
615
+ Turns a skeleton into one mesh: each limb becomes a tapered tube (construction_kit.curve_tube). A limb
616
+ runs on through every fork along its thickest child, so a trunk or main branch is one unbroken tube;
617
+ side branches start on the parent's axis at the fork, narrowed to BRANCH_BASE_SCALE of their own radius,
618
+ so they leave the parent through its wall at an angle instead of running along it (tube walls lying on
619
+ top of each other z-fight). Fine for real-time trees and LODs; voxel-remesh
620
+ the result when one watertight shell is needed (a bake source).
621
+
622
+ :param name: Object name.
623
+ :param skeleton: {"positions", "parents", "radii"} from space_colonization or lsystem_skeleton.
624
+ :param sides: Tube sides (6 near, 4 or 3 for far LODs).
625
+ :param material: Material slot name.
626
+ :returns: The joined mesh object.
627
+ """
628
+ positions, parents, radii = skeleton["positions"], skeleton["parents"], skeleton["radii"]
629
+ combined = bmesh.new()
630
+ for limb in _limbs(parents, radii):
631
+ limb_radii = [radii[node] for node in limb]
632
+ if parents[limb[0]] >= 0:
633
+ limb_radii[0] = limb_radii[1] * BRANCH_BASE_SCALE
634
+ tube = kit.curve_tube(f"_{name}_limb", [tuple(positions[node]) for node in limb], limb_radii,
635
+ resolution=sides, path_subdivisions=1)
636
+ mesh = tube.data
637
+ if parents[limb[0]] >= 0:
638
+ _remove_cap_at(mesh, positions[limb[0]])
639
+ combined.from_mesh(mesh)
640
+ bpy.data.objects.remove(tube)
641
+ bpy.data.meshes.remove(mesh)
642
+ obj = _mesh_object(name, combined)
643
+ assign_slots(obj, [material])
644
+ kit.shade_smooth(obj)
645
+ kit.smart_unwrap(obj, island_margin=0.005)
646
+ return obj
647
+
648
+
649
+ def _remove_cap_at(mesh: bpy.types.Mesh, point: Vector) -> None:
650
+ """
651
+ Deletes a tube's end cap whose fan centre is at `point`: a side branch's base cap is buried in its parent,
652
+ never seen, and its centre vertex would coincide with a sibling's at the same fork.
653
+ """
654
+ edit_mesh = bmesh.new()
655
+ edit_mesh.from_mesh(mesh)
656
+ centre = [vertex for vertex in edit_mesh.verts if (vertex.co - point).length < SEAM_WELD_DISTANCE]
657
+ bmesh.ops.delete(edit_mesh, geom=centre, context="VERTS")
658
+ edit_mesh.to_mesh(mesh)
659
+ edit_mesh.free()
660
+
661
+
662
+ def _limbs(parents, radii) -> list:
663
+ """
664
+ Node chains for skinning: each starts at the root or at the fork it branches from and follows the
665
+ thickest child through every fork until a tip. Chains of a single segment are kept (twigs).
666
+ """
667
+ children = [[] for _ in parents]
668
+ for index, parent in enumerate(parents):
669
+ if parent >= 0:
670
+ children[parent].append(index)
671
+ limbs = []
672
+ starts = [0]
673
+ while starts:
674
+ node = starts.pop()
675
+ limb = [node] if parents[node] < 0 else [parents[node], node]
676
+ while children[node]:
677
+ thickest = max(children[node], key=lambda child: (radii[child], -child))
678
+ starts.extend(child for child in children[node] if child != thickest)
679
+ node = thickest
680
+ limb.append(node)
681
+ if len(limb) >= 2:
682
+ limbs.append(limb)
683
+ return limbs
684
+
685
+
686
+ # --- roads and tracks ---------------------------------------------------------------------------------------
687
+
688
+ def closed_track_centerline(seed: int, radius: float = 60.0, control_points: int = 10,
689
+ irregularity: float = 0.35, samples_per_span: int = 12, elevation: float = 0.0) -> list:
690
+ """
691
+ A closed racing line: control points on a circle, pushed in and out by the seed, joined by a closed
692
+ centripetal Catmull-Rom spline (no cusps or self-loops on uneven spacing).
693
+
694
+ :param seed: Layout seed.
695
+ :param radius: Mean radius in metres.
696
+ :param control_points: Control points around the loop (more = twistier).
697
+ :param irregularity: Radial variation as a share of the radius (0 = a circle; keep below 0.5).
698
+ :param samples_per_span: Samples between two control points.
699
+ :param elevation: Height variation in metres (hills).
700
+ :returns: [(x, y, z)] sampled points, the loop not repeated at the end.
701
+ """
702
+ stream = SeededRandom(seed).child("track")
703
+ controls = []
704
+ for index in range(control_points):
705
+ angle = 2.0 * math.pi * index / control_points
706
+ reach = radius * (1.0 + stream.uniform(-irregularity, irregularity))
707
+ controls.append(np.array((reach * math.cos(angle), reach * math.sin(angle), stream.uniform(0.0, elevation))))
708
+ return [tuple(point) for point in _closed_catmull_rom(controls, samples_per_span)]
709
+
710
+
711
+ def _closed_catmull_rom(controls: list, samples_per_span: int) -> list:
712
+ """Samples a closed centripetal Catmull-Rom spline through every control point."""
713
+ count = len(controls)
714
+ samples = []
715
+ for index in range(count):
716
+ points = [controls[(index + offset) % count] for offset in (-1, 0, 1, 2)]
717
+ knots = [0.0]
718
+ for first, second in zip(points, points[1:]):
719
+ knots.append(knots[-1] + max(float(np.linalg.norm(second - first)) ** CENTRIPETAL_EXPONENT, 1e-9))
720
+ for step in range(samples_per_span):
721
+ parameter = knots[1] + (knots[2] - knots[1]) * step / samples_per_span
722
+ samples.append(_barry_goldman(points, knots, parameter))
723
+ return samples
724
+
725
+
726
+ def _barry_goldman(points, knots, parameter: float) -> np.ndarray:
727
+ """Evaluates one Catmull-Rom span by the Barry-Goldman pyramid of linear blends."""
728
+ def blend(first, second, start, end):
729
+ return ((end - parameter) * first + (parameter - start) * second) / (end - start)
730
+ level_one = [blend(points[i], points[i + 1], knots[i], knots[i + 1]) for i in range(3)]
731
+ level_two = [blend(level_one[i], level_one[i + 1], knots[i], knots[i + 2]) for i in range(2)]
732
+ return blend(level_two[0], level_two[1], knots[1], knots[2])
733
+
734
+
735
+ def road_ribbon(name: str, centerline: list, width: float, closed: bool = True, lanes: int = 4,
736
+ bank_degrees=0.0, texture_metres: float = None, material: str = "Road") -> bpy.types.Object:
737
+ """
738
+ A road surface strip along a centre line: rings across the road at every centre-line point, sideways
739
+ taken against world up (the road stays level unless banked), UVs in metres (U across 0..1 over the
740
+ width, V along = distance / texture_metres). A closed road duplicates its first ring at the end, so V runs
741
+ on to the full length, then welds the two rings: the positions join, the UV seam stays.
742
+
743
+ :param name: Object name.
744
+ :param centerline: [(x, y, z)] points (closed loops: do not repeat the first point).
745
+ :param width: Road width in metres.
746
+ :param closed: Whether the road is a loop.
747
+ :param lanes: Quads across the road (vertex columns - 1).
748
+ :param bank_degrees: Bank angle, one value or one per point (positive tilts the left edge up).
749
+ :param texture_metres: Metres of road per V tile (default the width, so the texture is not stretched).
750
+ :param material: Material slot name.
751
+ :returns: The road object.
752
+ """
753
+ points = [Vector(point) for point in centerline]
754
+ banks = [bank_degrees] * len(points) if np.isscalar(bank_degrees) else list(bank_degrees)
755
+ tile = texture_metres or width
756
+ if closed:
757
+ points.append(points[0].copy())
758
+ banks.append(banks[0])
759
+ edit_mesh = bmesh.new()
760
+ uv_layer = edit_mesh.loops.layers.uv.new("UVMap")
761
+ rings, distances = [], [0.0]
762
+ for index, point in enumerate(points):
763
+ if index:
764
+ distances.append(distances[-1] + (point - points[index - 1]).length)
765
+ side = _road_side(points, index, closed, banks[index])
766
+ rings.append([edit_mesh.verts.new(point + side * (width * (column / lanes - 0.5)))
767
+ for column in range(lanes + 1)])
768
+ for index in range(len(rings) - 1):
769
+ for column in range(lanes):
770
+ face = edit_mesh.faces.new((rings[index][column], rings[index][column + 1],
771
+ rings[index + 1][column + 1], rings[index + 1][column]))
772
+ corner_uvs = ((column / lanes, distances[index] / tile), ((column + 1) / lanes, distances[index] / tile),
773
+ ((column + 1) / lanes, distances[index + 1] / tile), (column / lanes, distances[index + 1] / tile))
774
+ for loop, uv in zip(face.loops, corner_uvs):
775
+ loop[uv_layer].uv = uv
776
+ face.smooth = True
777
+ if closed:
778
+ bmesh.ops.remove_doubles(edit_mesh, verts=rings[0] + rings[-1], dist=SEAM_WELD_DISTANCE)
779
+ bmesh.ops.recalc_face_normals(edit_mesh, faces=edit_mesh.faces[:])
780
+ if edit_mesh.faces and edit_mesh.faces[0].normal.z < 0.0:
781
+ bmesh.ops.reverse_faces(edit_mesh, faces=edit_mesh.faces[:])
782
+ obj = _mesh_object(name, edit_mesh)
783
+ assign_slots(obj, [material])
784
+ obj["bt_road_length_m"] = distances[-1]
785
+ return obj
786
+
787
+
788
+ def _road_side(points, index: int, closed: bool, bank_degrees: float) -> Vector:
789
+ """Unit vector across the road (to the right of travel) at a centre-line point, banked about the tangent."""
790
+ last = len(points) - 1
791
+ if closed and index in (0, last):
792
+ tangent = points[1] - points[last - 1]
793
+ else:
794
+ tangent = points[min(index + 1, last)] - points[max(index - 1, 0)]
795
+ tangent.normalize()
796
+ side = tangent.cross(WORLD_UP).normalized()
797
+ return Matrix.Rotation(math.radians(bank_degrees), 3, tangent) @ side
798
+
799
+
800
+ # --- determinism ----------------------------------------------------------------------------------------------
801
+
802
+ def geometry_fingerprint(obj: bpy.types.Object) -> str:
803
+ """
804
+ SHA-256 of the evaluated mesh: vertex positions (rounded to FINGERPRINT_DECIMALS), face vertex indices
805
+ and material indices. Two builds with the same seed must give the same string.
806
+ """
807
+ depsgraph = bpy.context.evaluated_depsgraph_get()
808
+ evaluated = obj.evaluated_get(depsgraph)
809
+ mesh = evaluated.to_mesh()
810
+ try:
811
+ coordinates = np.empty(len(mesh.vertices) * 3)
812
+ mesh.vertices.foreach_get("co", coordinates)
813
+ corner_vertices = np.empty(len(mesh.loops), dtype=np.int64)
814
+ mesh.loops.foreach_get("vertex_index", corner_vertices)
815
+ materials = np.empty(len(mesh.polygons), dtype=np.int64)
816
+ mesh.polygons.foreach_get("material_index", materials)
817
+ digest = hashlib.sha256()
818
+ digest.update(np.round(coordinates, FINGERPRINT_DECIMALS).tobytes())
819
+ digest.update(corner_vertices.tobytes())
820
+ digest.update(materials.tobytes())
821
+ return digest.hexdigest()
822
+ finally:
823
+ evaluated.to_mesh_clear()
824
+
825
+
826
+ def variation_manifest(objects: list, parameters: dict) -> dict:
827
+ """
828
+ The record that makes a variation set reproducible: for each variant its seed, size, face count and
829
+ fingerprint, plus the generator parameters and the Blender and Python versions it was built with.
830
+
831
+ :param objects: Variants carrying a `bt_seed` custom property.
832
+ :param parameters: The generator name and the arguments shared by the set.
833
+ :returns: A JSON-ready dict; write it beside the exported files.
834
+ """
835
+ variants = []
836
+ for obj in objects:
837
+ points = kit.world_vertices(obj)
838
+ variants.append({"name": obj.name, "seed": int(obj.get("bt_seed", -1)),
839
+ "size_m": [round(float(value), 4) for value in np.ptp(points, axis=0)],
840
+ "faces": len(obj.data.polygons), "fingerprint": geometry_fingerprint(obj)})
841
+ return {"parameters": parameters, "blender": bpy.app.version_string,
842
+ "python": sys.version.split()[0], "variants": variants}