assemble-cad-bim.py 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896
  1. """Export a CAD/BIM seated plan as a spatial-LOD 3D Tiles tree.
  2. Run with Blender: blender --background --factory-startup --python-exit-code 1 \
  3. --python tools/city-massing/assemble-cad-bim.py -- \
  4. --plan tools/city-massing/cad-bim/seated-plan.json \
  5. --output tools/city-massing/cad-bim/lod-preview --grid 32 --coarse-grid 8
  6. Same output conventions as assemble-lod-district.py (GLB cells, `box()` bounding volumes,
  7. tileset.json/manifest.json, root-anchor.glb), so verify-lod-district.mjs still gates it.
  8. Difference: input footprints are surveyed polygons, so `kind == "massing"` buildings are
  9. built here as extruded prisms instead of being copied from the house library.
  10. """
  11. import json
  12. import math
  13. import struct
  14. import argparse
  15. import sys
  16. from pathlib import Path
  17. import bpy
  18. import bmesh
  19. from mathutils import Vector
  20. from mathutils.geometry import tessellate_polygon
  21. ROOT = Path(__file__).resolve().parents[2]
  22. parser = argparse.ArgumentParser()
  23. parser.add_argument('--plan', required=True)
  24. parser.add_argument('--output', required=True)
  25. parser.add_argument('--grid', type=int, default=32)
  26. parser.add_argument('--coarse-grid', type=int, default=0)
  27. parser.add_argument('--limit', type=int, default=0, help='export only the first N buildings')
  28. parser.add_argument('--decimate-lod1', type=float, default=1.0,
  29. help='Decimate ratio applied to library asset meshes at LOD1 (1.0 = off)')
  30. parser.add_argument('--decimate-lod0', type=float, default=1.0,
  31. help='Decimate ratio applied to library asset meshes at LOD0 (1.0 = off)')
  32. parser.add_argument('--merge-buildings', action='store_true',
  33. help='Bake each cell into ONE merged mesh (per-material primitives) instead of one node per building')
  34. parser.add_argument('--lod1-footprint-only', action='store_true',
  35. help='Use each surveyed GIS footprint for LOD1/coarse geometry, including asset buildings')
  36. parser.add_argument('--near-architecture', action='store_true', help='Add bounded window reveals and storey bands at LOD0')
  37. parser.add_argument('--roof-textures', help='JSON mapping building IDs to sourced roof image paths and ENU UV bounds')
  38. parser.add_argument('--draco', action='store_true', help='Enable Draco mesh compression in GLB export')
  39. args = parser.parse_args(sys.argv[sys.argv.index('--') + 1:] if '--' in sys.argv else [])
  40. for ratio in (args.decimate_lod1, args.decimate_lod0):
  41. if not (0.0 < ratio <= 1.0):
  42. raise RuntimeError('--decimate-lod* ratios must be in (0, 1]')
  43. if args.grid < 2:
  44. raise RuntimeError('--grid must be at least 2')
  45. if args.coarse_grid and (args.coarse_grid < 2 or args.coarse_grid >= args.grid):
  46. raise RuntimeError('--coarse-grid must be at least 2 and smaller than --grid')
  47. PLAN = Path(args.plan).resolve()
  48. OUT = Path(args.output).resolve()
  49. LIBRARY_DIR = ROOT / 'tools/city-massing/house-library'
  50. plan = json.loads(PLAN.read_text(encoding='utf-8'))
  51. lib = json.loads((LIBRARY_DIR / 'library.json').read_text(encoding='utf-8'))
  52. entries = lib['archetypes']
  53. # Same asset-fit contract the placement generator used, so the two stages cannot disagree about
  54. # what counts as an acceptable match.
  55. ASSET_FIT = json.loads((ROOT / 'tools/city-massing/asset-fit.json').read_text(encoding='utf-8'))['variants']
  56. # Scene variety without random re-rolls: a stable hash of the building id picks one wall tone and
  57. # one roof tone, so neighbours differ while the whole extrusion stays coherent.
  58. WALL_TONES = ('Plaster_Cream', 'Plaster_Ivory', 'Plaster_Sand', 'Concrete_Warm')
  59. ROOF_TONES = ('Roof_Slate', 'Roof_Slate_Light', 'Roof_Terracotta', 'Roof_Terra_Light')
  60. ROOF_TEXTURES = json.loads(Path(args.roof_textures).read_text(encoding='utf-8')) if args.roof_textures else {}
  61. ARCHITECTURE = args.near_architecture
  62. def select_asset(building):
  63. family = building.get('archetype') or 'house'
  64. prefix = {'house': 'house', 'apartment': 'slab', 'midrise': 'midrise'}.get(family, 'house')
  65. # A building may name the exact approved variants it was planned for; otherwise any variant of
  66. # its family that fits the shared scale window is eligible.
  67. preferred = building.get('preferredAssets') or []
  68. family_key = family if family in ASSET_FIT else prefix
  69. limits = ASSET_FIT.get(family_key) or ASSET_FIT.get(prefix) or ASSET_FIT['house']
  70. min_x, min_y = limits['minScale']
  71. max_x, max_y = limits['maxScale']
  72. candidates = []
  73. for entry in entries:
  74. if preferred:
  75. if entry['id'] not in preferred:
  76. continue
  77. elif not entry['id'].startswith(prefix):
  78. continue
  79. width, depth = entry['nominal_footprint_m']
  80. sx, sy = building['width'] / width, building['depth'] / depth
  81. if not (min_x <= sx <= max_x and min_y <= sy <= max_y):
  82. continue
  83. preference = preferred.index(entry['id']) if entry['id'] in preferred else len(preferred) + 1
  84. score = preference * 0.25 + abs(entry['floors'] - building['floors']) * 0.8 + abs(math.log(sx)) + abs(math.log(sy))
  85. candidates.append((score, entry, sx, sy))
  86. return min(candidates, key=lambda item: item[0]) if candidates else None
  87. # ---------------------------------------------------------------- polygon helpers
  88. def ring_area(points):
  89. """Signed XY area; positive means counter-clockwise."""
  90. return 0.5 * sum(points[i][0] * points[(i + 1) % len(points)][1]
  91. - points[(i + 1) % len(points)][0] * points[i][1] for i in range(len(points)))
  92. def as_ccw(points):
  93. """Keep surveyed coordinates, removing consecutive duplicates at CAD centimetre precision."""
  94. ring = []
  95. for point in points:
  96. if not ring or math.hypot(point[0] - ring[-1][0], point[1] - ring[-1][1]) > 0.011:
  97. ring.append(point)
  98. if len(ring) > 1 and math.hypot(ring[0][0] - ring[-1][0], ring[0][1] - ring[-1][1]) <= 0.011:
  99. ring.pop()
  100. return ring if ring_area(ring) > 0 else list(reversed(ring))
  101. def convex_hull(points):
  102. """Monotone chain; used as the cheap LOD1 outline for a massing prism."""
  103. ordered = sorted({(round(x, 6), round(y, 6)) for x, y in points})
  104. if len(ordered) < 3:
  105. return ordered
  106. def half(seq):
  107. out = []
  108. for point in seq:
  109. while len(out) >= 2 and ((out[-1][0] - out[-2][0]) * (point[1] - out[-2][1])
  110. - (out[-1][1] - out[-2][1]) * (point[0] - out[-2][0])) <= 0:
  111. out.pop()
  112. out.append(point)
  113. return out
  114. return half(ordered)[:-1] + half(reversed(ordered))[:-1]
  115. def prism_triangles(n):
  116. """n-gon prism: two n-gon caps plus n wall quads."""
  117. return 4 * n - 4
  118. def facade_window_count(edge_length, level):
  119. """Small, bounded facade detail count; LOD1 keeps one readable window per edge."""
  120. if level == 'lod1':
  121. return 1
  122. # Near architecture gets a denser, still bounded facade rhythm; coarse LOD stays intentionally sparse.
  123. return max(1, min(16 if ARCHITECTURE else 3, int(edge_length / (2.8 if ARCHITECTURE else 3.5))))
  124. def massing_triangles(footprint, floors, level):
  125. """Reference triangles for a massing prism plus lightweight facade details."""
  126. base = prism_triangles(len(footprint))
  127. windows = 0
  128. for i in range(len(footprint)):
  129. a, b = footprint[i], footprint[(i + 1) % len(footprint)]
  130. length = math.hypot(b[0] - a[0], b[1] - a[1])
  131. count = facade_window_count(length, level)
  132. # add_panel/add_window_reveal reject a sub-0.35m window span. Surveyed
  133. # cornices/notches have short edges; they remain in the solid, without windows.
  134. if length / (count + 1) * 0.68 >= 0.35:
  135. windows += 2 * count * floors
  136. architectural = (windows * 4 + 2 * len(footprint) * max(0, floors - 1)) if ARCHITECTURE and level == 'lod0' else 0
  137. return base + windows + architectural + 12 # bounded reveals/bands and one closed entrance
  138. def poly_prism(footprint, bottom, top, wall_material, roof_material, anchor, floors, level,
  139. window_material, door_material):
  140. """Build a surveyed-outline building with bounded facade details.
  141. The solid uses the exact GIS ring. Windows are shallow, outward-facing quads repeated per
  142. floor and door is one first-floor quad on the longest wall. They add a readable facade without
  143. adding separate Blender objects or changing the building footprint.
  144. """
  145. # Create the mesh directly: repeated scene-wide select/cube operators make city exports quadratic.
  146. # This is an exterior-only massing shell: no rooms, floors, ceilings, or interior props.
  147. mesh = bpy.data.meshes.new('Surveyed_building')
  148. obj = bpy.data.objects.new('Surveyed_building', mesh)
  149. n = len(footprint)
  150. ax, ay, az = anchor
  151. vertices = [(x - ax, y - ay, bottom - az) for x, y in footprint] + \
  152. [(x - ax, y - ay, top - az) for x, y in footprint]
  153. faces = [(i, (i + 1) % n, n + (i + 1) % n, n + i) for i in range(n)]
  154. materials = [0] * n
  155. # Explicit caps survive merging/export and also handle concave surveyed outlines.
  156. # Use the same footprint vertices; no hull, overhang or XY displacement is introduced.
  157. cap_points = [Vector((x - ax, y - ay, 0)) for x, y in footprint]
  158. cap_indices = {tuple(point): i for i, point in enumerate(cap_points)}
  159. roof_area = 0.0
  160. for triangle in tessellate_polygon([cap_points]):
  161. # Blender 5.2 returns point indices; earlier versions returned Vector triples.
  162. indices = [point if isinstance(point, int) else cap_indices[tuple(point)] for point in triangle]
  163. area = ring_area([footprint[index] for index in indices])
  164. if abs(area) < 1e-10:
  165. continue
  166. if area < 0:
  167. indices.reverse()
  168. faces.append(tuple(n + index for index in indices)) # roof points up
  169. materials.append(1)
  170. faces.append(tuple(reversed(indices))) # buried bottom points down
  171. materials.append(0)
  172. roof_area += abs(area)
  173. # GIS vertices are rounded to centimetres. One real ring contains a 1cm backtrack and its
  174. # signed area differs by 0.08m² from the filled roof. Bound that tolerance by source precision,
  175. # instead of accepting missing caps or moving the whole surveyed footprint.
  176. perimeter = sum(math.hypot(footprint[(i + 1) % n][0] - p[0],
  177. footprint[(i + 1) % n][1] - p[1]) for i, p in enumerate(footprint))
  178. tolerance = max(0.001, roof_area * 1e-6, perimeter * 0.01)
  179. if abs(roof_area - ring_area(footprint)) > tolerance:
  180. raise RuntimeError('Triangulated roof does not cover its GIS footprint')
  181. floor_base = max(bottom, az) if ARCHITECTURE else bottom
  182. floor_height = max(2.4, (top - floor_base) / max(1, floors))
  183. def edge_panel_points(a, b, z0, z1, inset, width_ratio=0.42):
  184. dx, dy = b[0] - a[0], b[1] - a[1]
  185. length = math.hypot(dx, dy)
  186. if length < 0.35 or z1 <= z0:
  187. return None
  188. nx, ny = dy / length, -dx / length
  189. half = min(length * 0.22, max(0.45, length / 3.5 * width_ratio))
  190. cx, cy = (a[0] + b[0]) * 0.5, (a[1] + b[1]) * 0.5
  191. tx, ty = dx / length, dy / length
  192. return [(cx - tx * half + nx * inset, cy - ty * half + ny * inset),
  193. (cx + tx * half + nx * inset, cy + ty * half + ny * inset)]
  194. def add_panel(a, b, z0, z1, material_index, inset=0.035):
  195. points = edge_panel_points(a, b, z0, z1, inset)
  196. if not points:
  197. return
  198. base = len(vertices)
  199. vertices.extend([(x - ax, y - ay, z - az) for x, y in
  200. [(points[0][0], points[0][1]), (points[1][0], points[1][1])]
  201. for z in (z0, z1)])
  202. faces.append((base, base + 2, base + 3, base + 1))
  203. materials.append(material_index)
  204. def add_window_reveal(a, b, z0, z1):
  205. # Four solid-depth reveal strips around glass; no unsupported balcony/roof invention.
  206. inner = edge_panel_points(a, b, z0, z1, 0.035)
  207. outer = edge_panel_points(a, b, z0, z1, 0.16, 0.52)
  208. if not inner or not outer:
  209. return
  210. base = len(vertices)
  211. vertices.extend([(x - ax, y - ay, z - az) for points, low, high in
  212. ((outer, z0 - 0.10, z1 + 0.10), (inner, z0, z1))
  213. for x, y in points for z in (low, high)])
  214. faces.extend([(base, base + 2, base + 6, base + 4),
  215. (base + 1, base + 5, base + 7, base + 3),
  216. (base, base + 4, base + 5, base + 1),
  217. (base + 2, base + 3, base + 7, base + 6)])
  218. materials.extend([0] * 4)
  219. def add_box_panel(a, b, z0, z1, material_index):
  220. """Closed shallow door box; keeps a door material through merged GLB export."""
  221. if ARCHITECTURE:
  222. # Entrance width is architectural scale, not a fraction of a 70m apartment facade.
  223. dx, dy = b[0] - a[0], b[1] - a[1]
  224. length = math.hypot(dx, dy) or 1
  225. cx, cy = (a[0] + b[0]) / 2, (a[1] + b[1]) / 2
  226. half = min(length, 3.5) / 2
  227. a = (cx - dx / length * half, cy - dy / length * half)
  228. b = (cx + dx / length * half, cy + dy / length * half)
  229. points = edge_panel_points(a, b, z0, z1, 0.055, 0.72)
  230. if not points:
  231. return
  232. dx, dy = b[0] - a[0], b[1] - a[1]
  233. length = math.hypot(dx, dy) or 1
  234. nx, ny = dy / length, -dx / length
  235. outer = 0.14
  236. inner = 0.045
  237. p = points
  238. base = len(vertices)
  239. for depth in (inner, outer):
  240. vertices.extend([(p[0][0] - ax + nx * depth, p[0][1] - ay + ny * depth, z - az)
  241. for z in (z0, z1)])
  242. vertices.extend([(p[1][0] - ax + nx * depth, p[1][1] - ay + ny * depth, z - az)
  243. for z in (z0, z1)])
  244. faces.extend([(base, base + 1, base + 3, base + 2),
  245. (base + 4, base + 6, base + 7, base + 5),
  246. (base, base + 4, base + 5, base + 1),
  247. (base + 2, base + 3, base + 7, base + 6),
  248. (base, base + 2, base + 6, base + 4),
  249. (base + 1, base + 5, base + 7, base + 3)])
  250. materials.extend([material_index] * 6)
  251. # One or a few windows per wall and floor, with a dark blue material that cannot read as a flat cube.
  252. for i in range(n):
  253. a, b = footprint[i], footprint[(i + 1) % n]
  254. count = facade_window_count(math.hypot(b[0] - a[0], b[1] - a[1]), level)
  255. dx, dy = b[0] - a[0], b[1] - a[1]
  256. for floor in range(max(1, floors)):
  257. z0 = floor_base + floor * floor_height + floor_height * 0.34
  258. z1 = min(top - 0.08, z0 + floor_height * 0.36)
  259. for window in range(count):
  260. t = (window + 1) / (count + 1)
  261. center = (a[0] + dx * t, a[1] + dy * t)
  262. span = math.hypot(dx, dy) / (count + 1) * 0.34
  263. wa = (center[0] - dx / (math.hypot(dx, dy) or 1) * span,
  264. center[1] - dy / (math.hypot(dx, dy) or 1) * span)
  265. wb = (center[0] + dx / (math.hypot(dx, dy) or 1) * span,
  266. center[1] + dy / (math.hypot(dx, dy) or 1) * span)
  267. add_panel(wa, wb, z0, z1, 2)
  268. if ARCHITECTURE and level == 'lod0':
  269. add_window_reveal(wa, wb, z0, z1)
  270. if ARCHITECTURE and level == 'lod0':
  271. for floor in range(1, max(1, floors)):
  272. z = floor_base + floor * floor_height
  273. # A thin full-edge storey band uses the darker door tone, not extra objects.
  274. length = math.hypot(dx, dy) or 1
  275. nx, ny = dy / length, -dx / length
  276. base = len(vertices)
  277. vertices.extend([(p[0] - ax + nx * 0.025, p[1] - ay + ny * 0.025, zz - az)
  278. for p in (a, b) for zz in (z - 0.045, z + 0.045)])
  279. faces.append((base, base + 2, base + 3, base + 1))
  280. materials.append(3)
  281. # One door on the longest wall, visible from at least one approach direction.
  282. longest = max(range(n), key=lambda i: math.hypot(footprint[(i + 1) % n][0] - footprint[i][0],
  283. footprint[(i + 1) % n][1] - footprint[i][1]))
  284. edge_a = footprint[longest]
  285. edge_b = footprint[(longest + 1) % n]
  286. door_h = min(2.2, max(1.8, floor_height * 0.76))
  287. add_box_panel(edge_a, edge_b, floor_base + 0.08, min(top - 0.05, floor_base + door_h), 3)
  288. mesh.from_pydata(vertices, [], faces)
  289. obj.location = anchor
  290. edit = bmesh.new()
  291. edit.from_mesh(mesh)
  292. bmesh.ops.recalc_face_normals(edit, faces=edit.faces)
  293. edit.to_mesh(mesh)
  294. edit.free()
  295. mesh.update()
  296. for material in (wall_material, roof_material, window_material, door_material):
  297. mesh.materials.append(material)
  298. mesh.polygons.foreach_set('material_index', materials)
  299. mesh.update()
  300. return obj
  301. def prism_volume_sign(obj):
  302. """Volume of obj's closed surface read from Blender's own face normals.
  303. V = sum(centre . normal * area) / 3 is positive exactly when the normals point outward, which is
  304. the property the GLB export and every downstream renderer depend on. Local space is enough: the
  305. prisms are built unrotated and unscaled, and reading Blender's normals avoids re-deriving the
  306. winding sign by hand.
  307. """
  308. return sum(polygon.center.dot(polygon.normal) * polygon.area
  309. for polygon in obj.data.polygons) / 3
  310. def box(bounds):
  311. low, high = bounds
  312. centre = [(a + b) / 2 for a, b in zip(low, high)]
  313. half = [(b - a) / 2 for a, b in zip(low, high)]
  314. return [centre[0], centre[1], centre[2], half[0], 0, 0, 0, half[1], 0, 0, 0, half[2]]
  315. # ---------------------------------------------------------------- plan intake
  316. def build_geometry(building):
  317. """Return (level -> (outline, triangles)) for one building, validating its outline."""
  318. outline = [(float(x), float(y)) for x, y in building['footprintENU']]
  319. if len(outline) < 3:
  320. raise RuntimeError(building['id'] + ' has fewer than 3 outline points')
  321. outline = as_ccw(outline)
  322. if building['kind'] == 'asset' and not args.lod1_footprint_only:
  323. # The library mesh is already authored in this ring; only the transform differs per level.
  324. return {level: (None, None) for level in ('lod0', 'lod1')}
  325. if ring_area(outline) <= 0:
  326. raise RuntimeError(building['id'] + ' outline is degenerate')
  327. if building['positionENU'][2] + building['heightM'] <= building['foundationBottom']:
  328. raise RuntimeError(building['id'] + ' massing prism has zero volume')
  329. # Both runtime levels use the surveyed ring. LOD1 reduces facade detail, not the GIS footprint;
  330. # replacing an irregular ring with its hull was the source of visibly misplaced road-covering mass.
  331. return {'lod0': (outline, massing_triangles(outline, building['floors'], 'lod0')),
  332. 'lod1': (outline, massing_triangles(outline, building['floors'], 'lod1'))}
  333. placements, rejected, expected_triangles = [], [], {}
  334. library_ids = {entry['id'] for entry in entries}
  335. for building in plan['buildings'][:args.limit or None]:
  336. if building['kind'] == 'asset':
  337. # A named variant that is not in the library is a broken plan, not a building to skip.
  338. unknown = set(building.get('preferredAssets') or []).difference(library_ids)
  339. if unknown:
  340. raise RuntimeError(f"{building['id']} names missing library objects: " + ', '.join(sorted(unknown)))
  341. choice = select_asset(building)
  342. if not choice:
  343. rejected.append(building['id'])
  344. continue
  345. _, entry, sx, sy = choice
  346. expected_triangles[building['id']] = None # filled from the library once templates load
  347. placements.append((building, entry, sx, sy))
  348. elif building['kind'] == 'massing':
  349. geometry = build_geometry(building)
  350. expected_triangles[building['id']] = {level: geometry[level][1] for level in geometry}
  351. placements.append((building, None, None, None))
  352. else:
  353. raise RuntimeError(building['id'] + ' has unknown kind ' + str(building['kind']))
  354. if not placements or len({b['id'] for b, _, _, _ in placements}) != len(placements):
  355. raise RuntimeError('The seated plan does not yield unique, nonempty placements')
  356. # ---------------------------------------------------------------- scene setup
  357. bpy.ops.wm.read_factory_settings(use_empty=True)
  358. bpy.context.scene.unit_settings.system = 'METRIC'
  359. bpy.context.scene.unit_settings.scale_length = 1
  360. OUT.mkdir(parents=True, exist_ok=True)
  361. for pattern in ('*-lod0.glb', '*-lod1.glb'):
  362. for stale in OUT.glob(pattern):
  363. stale.unlink()
  364. for stale in (OUT / 'root-anchor.glb', OUT / 'tileset.json', OUT / 'manifest.json'):
  365. if stale.exists():
  366. stale.unlink()
  367. stone = bpy.data.materials.new('Buried_foundation_stone')
  368. stone.diffuse_color = (0.32, 0.33, 0.32, 1)
  369. stone.use_nodes = True
  370. stone.node_tree.nodes['Principled BSDF'].inputs['Base Color'].default_value = stone.diffuse_color
  371. stone.node_tree.nodes['Principled BSDF'].inputs['Roughness'].default_value = 0.92
  372. # The dimensions/height vary per foundation; scale a shared unit cube mesh per instance.
  373. foundation_mesh = bpy.data.meshes.new('Seated_foundation_unit_cube')
  374. foundation_mesh.from_pydata(
  375. [(-.5, -.5, -.5), (.5, -.5, -.5), (.5, .5, -.5), (-.5, .5, -.5),
  376. (-.5, -.5, .5), (.5, -.5, .5), (.5, .5, .5), (-.5, .5, .5)],
  377. [],
  378. [(3, 2, 1, 0), (4, 5, 6, 7), (0, 1, 5, 4),
  379. (1, 2, 6, 5), (2, 3, 7, 6), (3, 0, 4, 7)],
  380. )
  381. foundation_mesh.materials.append(stone)
  382. # Load the placed library templates together so common materials retain their names. Massing
  383. # buildings reuse those same material datablocks, so no extra palette has to be authored here.
  384. required = {entry['joined_object'] for _, entry, _, _ in placements if entry}
  385. required.update(entry['lod1']['joined_object'] for _, entry, _, _ in placements if entry)
  386. with bpy.data.libraries.load(str(LIBRARY_DIR / 'house-library.blend'), link=False) as (src, dst):
  387. missing = required.difference(src.objects)
  388. if missing:
  389. raise RuntimeError('Missing Blender library templates: ' + ', '.join(sorted(missing)))
  390. dst.objects = sorted(required)
  391. templates = {obj.name: obj for obj in dst.objects if obj is not None}
  392. if len(templates) != len(required) or any(obj.type != 'MESH' or not obj.data.polygons
  393. for obj in templates.values()):
  394. raise RuntimeError('A required Blender template is empty')
  395. # Asset-level reduction: a Decimate modifier on the TEMPLATE mesh collapses every placed instance
  396. # at once (object copies share mesh data). Ratios come from the CLI; 1.0 (default) leaves meshes
  397. # untouched. Collapsing an inset window frame to one sheet is acceptable at these viewing
  398. # distances; what must survive is the building silhouette, its openings as dark insets, and the
  399. # storey rhythm — the maintainer's acceptance bar for "looks like a building".
  400. DECIMATE_RATIOS = {'lod0': args.decimate_lod0, 'lod1': args.decimate_lod1}
  401. decimated_templates = {}
  402. if any(ratio < 1.0 for ratio in DECIMATE_RATIOS.values()):
  403. for name, obj in templates.items():
  404. level = 'lod0' if name.endswith('_LOD0') else 'lod1' if name.endswith('_LOD1') else None
  405. ratio = DECIMATE_RATIOS.get(level, 1.0)
  406. if ratio < 1.0:
  407. modifier = obj.modifiers.new('AssetDecimate', 'DECIMATE')
  408. modifier.ratio = ratio
  409. modifier.use_collapse_triangulate = True
  410. decimated_templates[name] = modifier
  411. has_asset_placements = any(entry for _, entry, _, _ in placements)
  412. if not decimated_templates and has_asset_placements:
  413. raise RuntimeError('Decimate requested but no template name ends with _LOD0/_LOD1')
  414. # A massing-only batch (no asset placements, e.g. the unfitted-rectangle tail) has no templates
  415. # to decimate — its prisms are already minimal, so Draco-only export is the correct behavior.
  416. if decimated_templates:
  417. # Library.json triangle counts no longer describe the decimated meshes: link the decimated
  418. # templates into the view layer, evaluate them, and measure the real triangulated counts.
  419. scratch = bpy.data.collections.new('Template_eval_scratch')
  420. bpy.context.scene.collection.children.link(scratch)
  421. for name in decimated_templates:
  422. scratch.objects.link(templates[name])
  423. bpy.context.view_layer.update()
  424. depsgraph = bpy.context.evaluated_depsgraph_get()
  425. evaluated_triangles = {}
  426. for name in decimated_templates:
  427. evaluated = templates[name].evaluated_get(depsgraph)
  428. mesh = evaluated.to_mesh()
  429. evaluated_triangles[name] = sum(len(polygon.vertices) - 2 for polygon in mesh.polygons)
  430. evaluated.to_mesh_clear()
  431. for building, entry, _, _ in placements:
  432. if entry:
  433. expected_triangles[building['id']] = {}
  434. for level in ('lod0', 'lod1'):
  435. if args.lod1_footprint_only and level == 'lod1':
  436. expected_triangles[building['id']][level] = build_geometry(building)[level][1]
  437. continue
  438. template_name = entry['joined_object'] if level == 'lod0' else entry['lod1']['joined_object']
  439. fallback = (entry['validation'] if level == 'lod0' else entry['lod1']['validation'])['triangles']
  440. expected_triangles[building['id']][level] = evaluated_triangles.get(template_name, fallback)
  441. else:
  442. for building, entry, _, _ in placements:
  443. if entry:
  444. expected_triangles[building['id']] = {
  445. level: (build_geometry(building)[level][1] if args.lod1_footprint_only and level == 'lod1'
  446. else (entry['validation'] if level == 'lod0' else entry['lod1']['validation'])['triangles'])
  447. for level in ('lod0', 'lod1')}
  448. # Append the whole library palette on top of the templates: templates that happen to share no
  449. # material would otherwise leave a massing tone name unavailable.
  450. with bpy.data.libraries.load(str(LIBRARY_DIR / 'house-library.blend'), link=False) as (src, dst):
  451. dst.materials = list(src.materials)
  452. missing_tones = set(WALL_TONES + ROOF_TONES + ('Glass_Dark', 'Door_Walnut')).difference(bpy.data.materials.keys())
  453. if missing_tones:
  454. raise RuntimeError('Library is missing material tones: ' + ', '.join(sorted(missing_tones)))
  455. def id_seed(building_id):
  456. value = 2166136261
  457. for character in str(building_id):
  458. value = ((value ^ ord(character)) * 16777619) % 4294967296
  459. return value
  460. def massing_tone(building_id):
  461. seed = id_seed(building_id)
  462. return (bpy.data.materials[WALL_TONES[seed % len(WALL_TONES)]],
  463. bpy.data.materials[ROOF_TONES[(seed // len(WALL_TONES)) % len(ROOF_TONES)]],
  464. bpy.data.materials['Glass_Dark'], bpy.data.materials['Door_Walnut'])
  465. def sourced_roof(building_id, fallback):
  466. record = ROOF_TEXTURES.get(building_id)
  467. if not record:
  468. return fallback
  469. name = 'SatelliteRoof_' + building_id
  470. material = bpy.data.materials.get(name)
  471. if material:
  472. return material
  473. material = bpy.data.materials.new(name)
  474. material.use_nodes = True
  475. shader = material.node_tree.nodes.get('Principled BSDF')
  476. shader.inputs['Roughness'].default_value = 0.85
  477. shader.inputs['Metallic'].default_value = 0.0
  478. texture = material.node_tree.nodes.new('ShaderNodeTexImage')
  479. texture.image = bpy.data.images.load(record['path'], check_existing=True)
  480. texture.extension = 'CLIP'
  481. material.node_tree.links.new(texture.outputs['Color'], shader.inputs['Base Color'])
  482. return material
  483. def apply_roof_uv(obj, building_id):
  484. record = ROOF_TEXTURES.get(building_id)
  485. if not record:
  486. return
  487. low, high = record['boundsENU']
  488. uv = obj.data.uv_layers.new(name='UVMap')
  489. for loop in obj.data.loops:
  490. point = obj.data.vertices[loop.vertex_index].co + obj.location
  491. uv.data[loop.index].uv = ((point.x - low[0]) / (high[0] - low[0]),
  492. (point.y - low[1]) / (high[1] - low[1]))
  493. def material_remap(building_id):
  494. """Asset palette rotation, keyed by the same stable hash as the massing tones."""
  495. seed = id_seed(building_id)
  496. roof_shift = (seed // 3) % len(ROOF_TONES)
  497. wall_shift = seed % len(WALL_TONES)
  498. remap = {name: ROOF_TONES[(index + roof_shift) % len(ROOF_TONES)]
  499. for index, name in enumerate(ROOF_TONES)}
  500. remap.update({name: WALL_TONES[(index + wall_shift) % len(WALL_TONES)]
  501. for index, name in enumerate(WALL_TONES)})
  502. remap['Roof_Membrane'] = ROOF_TONES[roof_shift]
  503. return remap
  504. def template(entry, level):
  505. return templates[entry['joined_object'] if level == 'lod0' else entry['lod1']['joined_object']]
  506. def make_cell(group, level):
  507. collection = bpy.data.collections.new('Cad_' + level)
  508. bpy.context.scene.collection.children.link(collection)
  509. for building, entry, sx, sy in group:
  510. x, y, top = building['positionENU']
  511. bottom = building['foundationBottom']
  512. if entry and not (args.lod1_footprint_only and level == 'lod1'):
  513. obj = template(entry, level).copy() # Object copy shares mesh data with siblings.
  514. obj.name = building['id']
  515. collection.objects.link(obj)
  516. obj.location = building['positionENU']
  517. obj.rotation_euler = (0, 0, building['heading'])
  518. obj.scale = (sx, sy, 1)
  519. obj['source_footprint'] = building.get('sourceId', building['id'])
  520. remap = material_remap(building['id'])
  521. for slot in obj.material_slots:
  522. if slot.material and slot.material.name in remap:
  523. material = bpy.data.materials.get(remap[slot.material.name])
  524. if material:
  525. slot.link = 'OBJECT'
  526. slot.material = material
  527. else:
  528. geometry = build_geometry(building)[level]
  529. outline = geometry[0]
  530. wall, roof, window, door = massing_tone(building['id'])
  531. if level == 'lod0':
  532. roof = sourced_roof(building['id'], roof)
  533. top_z = top + building['heightM']
  534. obj = poly_prism(outline, bottom, top_z, wall, roof, building['positionENU'],
  535. max(1, int(building.get('floors') or round(building['heightM'] / 3.2))), level,
  536. window, door)
  537. # Self-check the prism is a solid with outward normals. If the ring somehow came out
  538. # clockwise, rebuild once reversed instead of silently emitting an inside-out building.
  539. if prism_volume_sign(obj) <= 0:
  540. bpy.data.meshes.remove(obj.data, do_unlink=True)
  541. obj = poly_prism(list(reversed(outline)), bottom, top_z, wall, roof, building['positionENU'],
  542. max(1, int(building.get('floors') or round(building['heightM'] / 3.2))), level,
  543. window, door)
  544. if prism_volume_sign(obj) <= 0:
  545. raise RuntimeError(building['id'] + ' massing prism is inside-out or flat')
  546. if level == 'lod0':
  547. apply_roof_uv(obj, building['id'])
  548. obj.name = building['id']
  549. for collection_link in list(obj.users_collection):
  550. collection_link.objects.unlink(obj)
  551. collection.objects.link(obj)
  552. # Buried foundation. An asset instance is a library mesh seated at floor level, so it needs
  553. # its own box down to foundationBottom. A massing prism already spans foundationBottom to the
  554. # roof, i.e. its buried foundation IS the prism; a rectangular box under an L-shaped or
  555. # rotated outline would poke outside the building and z-fight its walls. So one cell holds
  556. # two mesh nodes per asset placement and one per massing building.
  557. if entry and not (args.lod1_footprint_only and level == 'lod1'):
  558. foundation = bpy.data.objects.new(building['id'] + '_buried_foundation', foundation_mesh)
  559. collection.objects.link(foundation)
  560. foundation.location = (x, y, (bottom + top) / 2)
  561. foundation.rotation_euler.z = building['heading']
  562. foundation.scale = (building['width'], building['depth'], top - bottom)
  563. bpy.context.view_layer.update()
  564. objects = list(collection.objects)
  565. if args.merge_buildings and objects:
  566. objects = merge_cell_objects(objects, collection)
  567. corners = [obj.matrix_world @ Vector(corner) for obj in objects for corner in obj.bound_box]
  568. bounds = [[min(p[axis] for p in corners) for axis in range(3)],
  569. [max(p[axis] for p in corners) for axis in range(3)]]
  570. return collection, objects, bounds
  571. def merge_cell_objects(objects, collection):
  572. """Bake every building/foundation in the cell into ONE mesh.
  573. The per-building export produces a separate node and material primitives per placement.
  574. Merging reduces that structural cost to one primitive per used material; actual frame-time
  575. improvement still requires a runtime measurement. The decimate modifier is baked via the
  576. depsgraph. Transforms are baked into ENU vertices; normals are recalculated with flat shading.
  577. Material slots are preserved. Roof/window appearance must still be visually reviewed.
  578. """
  579. bpy.context.view_layer.update()
  580. depsgraph = bpy.context.evaluated_depsgraph_get()
  581. vertices, faces, face_material_names, face_uvs = [], [], [], []
  582. material_names = {}
  583. for obj in objects:
  584. evaluated = obj.evaluated_get(depsgraph)
  585. mesh = evaluated.to_mesh()
  586. matrix = obj.matrix_world.copy()
  587. base = len(vertices)
  588. for vertex in mesh.vertices:
  589. vertices.append(tuple(matrix @ vertex.co))
  590. for polygon in mesh.polygons:
  591. corner_indices = tuple(base + index for index in polygon.vertices)
  592. # Reject invalid faces with fewer than three distinct indices before rebuilding.
  593. if len(set(corner_indices)) < 3:
  594. continue
  595. faces.append(corner_indices)
  596. uv_layer = mesh.uv_layers.active
  597. face_uvs.append([tuple(uv_layer.data[i].uv) if uv_layer else (0.0, 0.0)
  598. for i in polygon.loop_indices])
  599. material = obj.material_slots[polygon.material_index].material if obj.material_slots else None
  600. key = material.name if material else ''
  601. if key not in material_names:
  602. material_names[key] = len(material_names)
  603. face_material_names.append(key)
  604. evaluated.to_mesh_clear()
  605. merged_mesh = bpy.data.meshes.new('cell_merged')
  606. merged_mesh.from_pydata(vertices, [], faces)
  607. if ROOF_TEXTURES:
  608. uv_layer = merged_mesh.uv_layers.new(name='UVMap')
  609. for polygon, values in zip(merged_mesh.polygons, face_uvs):
  610. for loop_index, value in zip(polygon.loop_indices, values):
  611. uv_layer.data[loop_index].uv = value
  612. for name in material_names:
  613. merged_mesh.materials.append(bpy.data.materials[name])
  614. merged_mesh.polygons.foreach_set('material_index', [material_names[n] for n in face_material_names])
  615. edit = bmesh.new()
  616. edit.from_mesh(merged_mesh)
  617. bmesh.ops.recalc_face_normals(edit, faces=edit.faces)
  618. edit.to_mesh(merged_mesh)
  619. edit.free()
  620. merged_mesh.update()
  621. merged = bpy.data.objects.new('cell_merged', merged_mesh)
  622. collection.objects.link(merged)
  623. for obj in objects:
  624. bpy.data.objects.remove(obj, do_unlink=True)
  625. return [merged]
  626. def export_cell(path, objects, group, level):
  627. bpy.ops.object.select_all(action='DESELECT')
  628. for obj in objects:
  629. obj.select_set(True)
  630. bpy.context.view_layer.objects.active = objects[0]
  631. export_options = dict(filepath=str(path), export_format='GLB', use_selection=True,
  632. export_yup=True, export_materials='EXPORT', export_extras=True,
  633. # Bake modifiers (the asset Decimate) into the exported mesh; without
  634. # this the GLB would carry the full-detail template meshes again.
  635. export_apply=True)
  636. if args.draco:
  637. export_options['export_draco_mesh_compression_enable'] = True
  638. if ARCHITECTURE:
  639. # Surveyed roofs include near-collinear centimetre edges: default quantization can invert slivers.
  640. export_options['export_draco_position_quantization'] = 24
  641. bpy.ops.export_scene.gltf(**export_options)
  642. with path.open('rb') as stream:
  643. header = stream.read(20)
  644. if len(header) != 20 or header[:4] != b'glTF':
  645. raise RuntimeError('Invalid GLB export ' + str(path))
  646. _, version, length, chunk_length, chunk_type = struct.unpack('<4s4I', header)
  647. if version != 2 or length != path.stat().st_size or chunk_type != 0x4E4F534A:
  648. raise RuntimeError('Invalid GLB header ' + str(path))
  649. doc = json.loads(stream.read(chunk_length))
  650. # Asset instances are one node plus their buried foundation; a massing prism is a single node.
  651. if args.merge_buildings:
  652. # Merged cell: exactly one mesh node carries the whole cell. Per-building node identity
  653. # and seated transforms are baked into world-space vertices, so only the triangle total
  654. # (below) and the scene-root shape remain meaningful here.
  655. names = [n.get('name') for n in doc['nodes'] if 'mesh' in n]
  656. if len(names) != 1:
  657. raise RuntimeError(f'{path.name}: merged cell must contain exactly one mesh node')
  658. else:
  659. expected_names = []
  660. for building, entry, _, _ in group:
  661. expected_names.append(building['id'])
  662. if entry and not (args.lod1_footprint_only and level == 'lod1'):
  663. expected_names.append(building['id'] + '_buried_foundation')
  664. names = [n.get('name') for n in doc['nodes'] if 'mesh' in n]
  665. # One node per massing prism, two per asset placement (instance + buried foundation).
  666. if len(names) != len(expected_names):
  667. raise RuntimeError(f'{path.name}: {len(names)} mesh nodes for {len(expected_names)} '
  668. 'expected building/foundation nodes')
  669. if sorted(names) != sorted(expected_names):
  670. raise RuntimeError('GLB mesh nodes do not match placed buildings and foundations: ' + str(path))
  671. nodes = {node['name']: node for node in doc['nodes']}
  672. for building, entry, sx, sy in group:
  673. x, y, top = building['positionENU']
  674. bottom = building['foundationBottom']
  675. use_asset = entry and not (args.lod1_footprint_only and level == 'lod1')
  676. checks = [(building['id'], top, (sx, 1, sy) if use_asset else None)]
  677. if use_asset:
  678. checks.append((building['id'] + '_buried_foundation', (bottom + top) / 2,
  679. (building['width'], top - bottom, building['depth'])))
  680. for name, centre, scale in checks:
  681. node = nodes[name]
  682. expected_pos = (x, centre, -y) # Blender Z-up to glTF Y-up, only once.
  683. if 'matrix' in node or any(abs(a - b) > .002 for a, b in zip(
  684. node.get('translation', (0, 0, 0)), expected_pos)):
  685. raise RuntimeError('Incorrect seated transform for ' + name + ' in ' + str(path))
  686. if scale and any(abs(a - b) > .002 for a, b in zip(node.get('scale', (1, 1, 1)), scale)):
  687. raise RuntimeError('Incorrect seated scale for ' + name + ' in ' + str(path))
  688. if set(doc['scenes'][doc.get('scene', 0)]['nodes']) != set(range(len(doc['nodes']))):
  689. raise RuntimeError('Unexpected parent transform in ' + str(path))
  690. def triangles(mesh):
  691. return sum(doc['accessors'][part['indices']]['count'] // 3 if 'indices' in part
  692. else doc['accessors'][part['attributes']['POSITION']]['count'] // 3
  693. for part in mesh['primitives'])
  694. count = sum(triangles(doc['meshes'][node['mesh']]) for node in doc['nodes'] if 'mesh' in node)
  695. if args.merge_buildings:
  696. # Merged mode: the reference is the authored merged mesh itself (degenerate faces were
  697. # dropped at collection time, so export must reproduce it one-for-one). Per-building
  698. # seated transforms were verified by the identical make_cell code path in unmerged runs.
  699. reference = sum(len(polygon.vertices) - 2 for polygon in objects[0].data.polygons)
  700. else:
  701. # Asset placements also carry a 12-triangle buried foundation box; massing prisms do not.
  702. reference = sum(expected_triangles[b['id']][level] + (12 if entry and not (args.lod1_footprint_only and level == 'lod1') else 0)
  703. for b, entry, _, _ in group)
  704. if count != reference:
  705. raise RuntimeError(f'{path.name}: {count} triangles, expected {reference}')
  706. meshes = {node['mesh'] for node in doc['nodes'] if 'mesh' in node}
  707. # Per-building material remapping is an object-level material link, so a cell whose instances
  708. # were recoloured exports one mesh variant per building; shared mesh data is not asserted here.
  709. # `uniqueMeshes` is reported so a regression towards N meshes for N nodes stays visible.
  710. return {'uri': path.name, 'bytes': path.stat().st_size, 'triangles': count,
  711. 'meshNodes': len(names), 'uniqueMeshes': len(meshes),
  712. 'merged': bool(args.merge_buildings)}
  713. # ---------------------------------------------------------------- spatial cells
  714. # Partition by positionENU into a --grid x --grid grid, then group cells into --coarse-grid parents,
  715. # exactly like the rectangular exporter so the same verifier accepts the tree.
  716. xs = [b['positionENU'][0] for b, _, _, _ in placements]
  717. ys = [b['positionENU'][1] for b, _, _, _ in placements]
  718. min_x, max_x = min(xs), max(xs)
  719. min_y, max_y = min(ys), max(ys)
  720. span_x = max(max_x - min_x, 1e-6)
  721. span_y = max(max_y - min_y, 1e-6)
  722. cells = {}
  723. for placement in placements:
  724. x, y, _ = placement[0]['positionENU']
  725. ix = min(args.grid - 1, int((x - min_x) / span_x * args.grid))
  726. iy = min(args.grid - 1, int((y - min_y) / span_y * args.grid))
  727. cells.setdefault(f'cell-{iy:02d}-{ix:02d}', []).append(placement)
  728. cells = {name: group for name, group in sorted(cells.items()) if group}
  729. if len(cells) < 2:
  730. raise RuntimeError('Not enough geographically separate building groups to demonstrate spatial LOD')
  731. hierarchical = bool(args.coarse_grid)
  732. coarse_groups, fine_coarse = {}, {}
  733. if hierarchical:
  734. for cell_id, group in cells.items():
  735. x, y, _ = group[0][0]['positionENU']
  736. ix = min(args.coarse_grid - 1, int((x - min_x) / span_x * args.coarse_grid))
  737. iy = min(args.coarse_grid - 1, int((y - min_y) / span_y * args.coarse_grid))
  738. coarse_id = f'coarse-{iy:02d}-{ix:02d}'
  739. fine_coarse[cell_id] = coarse_id
  740. coarse_groups.setdefault(coarse_id, []).extend(group)
  741. fine_tiles, manifest_cells, all_bounds = {}, [], []
  742. for cell_id, group in cells.items():
  743. exports, bounds_per_level = {}, []
  744. for level in ('lod1', 'lod0'):
  745. collection, objects, bounds = make_cell(group, level)
  746. path = OUT / f'{cell_id}-{level}.glb'
  747. exports[level] = export_cell(path, objects, group, level)
  748. bounds_per_level.append(bounds)
  749. bpy.data.collections.remove(collection, do_unlink=True)
  750. for obj in objects:
  751. bpy.data.objects.remove(obj, do_unlink=True)
  752. bounds = [[min(b[0][axis] for b in bounds_per_level) for axis in range(3)],
  753. [max(b[1][axis] for b in bounds_per_level) for axis in range(3)]]
  754. all_bounds.append(bounds)
  755. volume = {'box': box(bounds)}
  756. if hierarchical:
  757. fine_tiles[cell_id] = {'boundingVolume': volume, 'geometricError': 0,
  758. 'content': {'uri': exports['lod0']['uri']}}
  759. else:
  760. fine_tiles[cell_id] = {'boundingVolume': volume, 'geometricError': 8,
  761. 'refine': 'REPLACE', 'content': {'uri': exports['lod1']['uri']},
  762. 'children': [{'boundingVolume': volume, 'geometricError': 0,
  763. 'content': {'uri': exports['lod0']['uri']}}]}
  764. manifest_cells.append({'id': cell_id, 'count': len(group),
  765. 'buildingIds': [b['id'] for b, _, _, _ in group],
  766. 'boundsENU': {'min': bounds[0], 'max': bounds[1]}, **exports})
  767. if hierarchical:
  768. cell_tiles, manifest_coarse = [], []
  769. for coarse_id, group in coarse_groups.items():
  770. collection, objects, bounds = make_cell(group, 'lod1')
  771. path = OUT / f'{coarse_id}-lod1.glb'
  772. coarse_export = export_cell(path, objects, group, 'lod1')
  773. bpy.data.collections.remove(collection, do_unlink=True)
  774. for obj in objects:
  775. bpy.data.objects.remove(obj, do_unlink=True)
  776. children = [fine_tiles[cell_id] for cell_id, parent in fine_coarse.items() if parent == coarse_id]
  777. cell_tiles.append({'boundingVolume': {'box': box(bounds)}, 'geometricError': 16,
  778. 'refine': 'REPLACE', 'content': {'uri': coarse_export['uri']},
  779. 'children': children})
  780. manifest_coarse.append({'id': coarse_id, 'count': len(group), **coarse_export})
  781. else:
  782. cell_tiles = list(fine_tiles.values())
  783. manifest_coarse = []
  784. root_bounds = [[min(b[0][axis] for b in all_bounds) for axis in range(3)],
  785. [max(b[1][axis] for b in all_bounds) for axis in range(3)]]
  786. # The explicit root must be renderable to keep Cesium traversing its spatial children.
  787. anchor_json = json.dumps({'asset': {'version': '2.0'}, 'scene': 0, 'scenes': [{'nodes': []}]},
  788. separators=(',', ':')).encode('utf-8')
  789. anchor_json += b' ' * ((-len(anchor_json)) % 4)
  790. anchor = b'glTF' + struct.pack('<II', 2, 20 + len(anchor_json))
  791. anchor += struct.pack('<I', len(anchor_json)) + b'JSON' + anchor_json
  792. (OUT / 'root-anchor.glb').write_bytes(anchor)
  793. tileset = {'asset': {'version': '1.1', 'generator': 'Blender CAD/BIM massing LOD'},
  794. 'geometricError': 800,
  795. 'root': {'transform': plan['transform'], 'boundingVolume': {'box': box(root_bounds)},
  796. 'geometricError': 200, 'refine': 'REPLACE',
  797. 'content': {'uri': 'root-anchor.glb'}, 'children': cell_tiles}}
  798. lod1_records = manifest_coarse if hierarchical else [cell['lod1'] for cell in manifest_cells]
  799. lod0_records = [cell['lod0'] for cell in manifest_cells]
  800. manifest = {'scope': plan.get('scope', 'surveyed CAD/BIM massing sample; not full-city reconstruction'),
  801. 'origin': plan['origin'], 'notice': plan.get('notice'),
  802. 'provenance': {'source': plan.get('source'), 'plan': PLAN.name, 'planPath': str(PLAN),
  803. 'nearArchitecture': ARCHITECTURE, 'satelliteRoofTextures': len(ROOF_TEXTURES),
  804. 'facadeFidelity': 'procedural estimate; not facade photography or surveyed BIM',
  805. 'gisFootprints': True, 'lod1FootprintOnly': bool(args.lod1_footprint_only),
  806. 'facadeDetails': True, 'roadsProcedural': False, 'closedRoofCaps': True},
  807. 'reduction': {'decimateLod0': args.decimate_lod0, 'decimateLod1': args.decimate_lod1,
  808. 'draco': bool(args.draco)},
  809. 'count': len(placements), 'cellCount': len(cells), 'cellIds': list(cells),
  810. 'hierarchy': {'enabled': hierarchical, 'coarseGrid': args.coarse_grid if hierarchical else None,
  811. 'coarseCellCount': len(manifest_coarse)},
  812. 'excludedUnfittedIds': rejected,
  813. 'boundsENU': {'min': root_bounds[0], 'max': root_bounds[1]},
  814. 'totals': {level: {'bytes': sum(item['bytes'] for item in (lod1_records if level == 'lod1' else lod0_records)),
  815. 'triangles': sum(item['triangles'] for item in (lod1_records if level == 'lod1' else lod0_records))}
  816. for level in ('lod1', 'lod0')},
  817. 'coarseCells': manifest_coarse,
  818. 'cells': manifest_cells}
  819. (OUT / 'tileset.json').write_text(json.dumps(tileset, indent=2), encoding='utf-8')
  820. (OUT / 'manifest.json').write_text(json.dumps(manifest, indent=2), encoding='utf-8')
  821. print('CAD_BIM_LOD', json.dumps({'count': manifest['count'], 'cells': manifest['cellCount'],
  822. 'coarse': len(manifest_coarse), 'totals': manifest['totals'],
  823. 'output': str(OUT)}))