wallhammer-web 0.0.0-stage → 0.4.1

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 (408) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +92 -2
  3. package/dist/base/data.d.ts +67 -0
  4. package/dist/base/data.js +10 -0
  5. package/dist/base/destructible.d.ts +167 -0
  6. package/dist/base/destructible.js +47 -0
  7. package/dist/base/env-slot.d.ts +101 -0
  8. package/dist/base/env-slot.js +8 -0
  9. package/dist/base/frames.d.ts +138 -0
  10. package/dist/base/frames.js +459 -0
  11. package/dist/base/index.d.ts +21 -0
  12. package/dist/base/index.js +11 -0
  13. package/dist/base/mat34.d.ts +46 -0
  14. package/dist/base/mat34.js +173 -0
  15. package/dist/base/material.d.ts +87 -0
  16. package/dist/base/material.js +6 -0
  17. package/dist/base/math.d.ts +27 -0
  18. package/dist/base/math.js +60 -0
  19. package/dist/base/progress.d.ts +38 -0
  20. package/dist/base/progress.js +81 -0
  21. package/dist/base/rig.d.ts +177 -0
  22. package/dist/base/rig.js +97 -0
  23. package/dist/base/trig.d.ts +29 -0
  24. package/dist/base/trig.js +169 -0
  25. package/dist/base/up.d.ts +26 -0
  26. package/dist/base/up.js +40 -0
  27. package/dist/base/view.d.ts +128 -0
  28. package/dist/base/view.js +136 -0
  29. package/dist/camera/camera.d.ts +99 -0
  30. package/dist/camera/camera.js +228 -0
  31. package/dist/camera/follow.d.ts +120 -0
  32. package/dist/camera/follow.js +320 -0
  33. package/dist/camera/free.d.ts +153 -0
  34. package/dist/camera/free.js +359 -0
  35. package/dist/camera/index.d.ts +10 -0
  36. package/dist/camera/index.js +6 -0
  37. package/dist/camera/orbit.d.ts +93 -0
  38. package/dist/camera/orbit.js +261 -0
  39. package/dist/camera/path.d.ts +48 -0
  40. package/dist/camera/path.js +179 -0
  41. package/dist/core/ballistic.d.ts +66 -0
  42. package/dist/core/ballistic.js +104 -0
  43. package/dist/core/bodies.d.ts +77 -0
  44. package/dist/core/bodies.js +125 -0
  45. package/dist/core/clock.d.ts +37 -0
  46. package/dist/core/clock.js +87 -0
  47. package/dist/core/cover-fade.d.ts +14 -0
  48. package/dist/core/cover-fade.js +38 -0
  49. package/dist/core/index.d.ts +13 -0
  50. package/dist/core/index.js +8 -0
  51. package/dist/core/kepler.d.ts +74 -0
  52. package/dist/core/kepler.js +108 -0
  53. package/dist/core/level-fade.d.ts +66 -0
  54. package/dist/core/level-fade.js +123 -0
  55. package/dist/core/palette.d.ts +15 -0
  56. package/dist/core/palette.js +47 -0
  57. package/dist/env/atmosphere.d.ts +129 -0
  58. package/dist/env/atmosphere.js +707 -0
  59. package/dist/env/cloud-field.d.ts +44 -0
  60. package/dist/env/cloud-field.js +111 -0
  61. package/dist/env/environment.d.ts +217 -0
  62. package/dist/env/environment.js +441 -0
  63. package/dist/env/frame-block.d.ts +29 -0
  64. package/dist/env/frame-block.js +152 -0
  65. package/dist/env/glsl.d.ts +35 -0
  66. package/dist/env/glsl.js +246 -0
  67. package/dist/env/index.d.ts +13 -0
  68. package/dist/env/index.js +9 -0
  69. package/dist/env/sky.d.ts +48 -0
  70. package/dist/env/sky.js +227 -0
  71. package/dist/env/sun.d.ts +31 -0
  72. package/dist/env/sun.js +42 -0
  73. package/dist/gen-arch/build.d.ts +17 -0
  74. package/dist/gen-arch/build.js +414 -0
  75. package/dist/gen-arch/damage/damaged.d.ts +44 -0
  76. package/dist/gen-arch/damage/damaged.js +1119 -0
  77. package/dist/gen-arch/damage/fall-material.d.ts +10 -0
  78. package/dist/gen-arch/damage/fall-material.js +47 -0
  79. package/dist/gen-arch/damage/fall.d.ts +78 -0
  80. package/dist/gen-arch/damage/fall.js +797 -0
  81. package/dist/gen-arch/damage/rubble.d.ts +22 -0
  82. package/dist/gen-arch/damage/rubble.js +188 -0
  83. package/dist/gen-arch/index.d.ts +25 -0
  84. package/dist/gen-arch/index.js +16 -0
  85. package/dist/gen-arch/interior/interior-plan.d.ts +114 -0
  86. package/dist/gen-arch/interior/interior-plan.js +615 -0
  87. package/dist/gen-arch/interior/interior.d.ts +97 -0
  88. package/dist/gen-arch/interior/interior.js +966 -0
  89. package/dist/gen-arch/structure/building-shader.d.ts +25 -0
  90. package/dist/gen-arch/structure/building-shader.js +946 -0
  91. package/dist/gen-arch/structure/buildings.d.ts +248 -0
  92. package/dist/gen-arch/structure/buildings.js +294 -0
  93. package/dist/gen-arch/structure/dims.d.ts +77 -0
  94. package/dist/gen-arch/structure/dims.js +39 -0
  95. package/dist/gen-arch/structure/distant.d.ts +62 -0
  96. package/dist/gen-arch/structure/distant.js +316 -0
  97. package/dist/gen-arch/structure/env-slots.d.ts +18 -0
  98. package/dist/gen-arch/structure/env-slots.js +47 -0
  99. package/dist/gen-arch/structure/facade.d.ts +193 -0
  100. package/dist/gen-arch/structure/facade.js +159 -0
  101. package/dist/gen-arch/structure/parts.d.ts +31 -0
  102. package/dist/gen-arch/structure/parts.js +69 -0
  103. package/dist/gen-arch/structure/roof.d.ts +76 -0
  104. package/dist/gen-arch/structure/roof.js +568 -0
  105. package/dist/gen-arch/structure/structure-material.d.ts +23 -0
  106. package/dist/gen-arch/structure/structure-material.js +55 -0
  107. package/dist/gen-arch/structure/writer.d.ts +94 -0
  108. package/dist/gen-arch/structure/writer.js +195 -0
  109. package/dist/gen-core/cell.d.ts +138 -0
  110. package/dist/gen-core/cell.js +150 -0
  111. package/dist/gen-core/cube-sphere.d.ts +57 -0
  112. package/dist/gen-core/cube-sphere.js +159 -0
  113. package/dist/gen-core/field.d.ts +55 -0
  114. package/dist/gen-core/field.js +154 -0
  115. package/dist/gen-core/geometry.d.ts +31 -0
  116. package/dist/gen-core/geometry.js +231 -0
  117. package/dist/gen-core/hash.d.ts +18 -0
  118. package/dist/gen-core/hash.js +58 -0
  119. package/dist/gen-core/height-field.d.ts +33 -0
  120. package/dist/gen-core/height-field.js +137 -0
  121. package/dist/gen-core/index.d.ts +22 -0
  122. package/dist/gen-core/index.js +17 -0
  123. package/dist/gen-core/instance-cells.d.ts +37 -0
  124. package/dist/gen-core/instance-cells.js +72 -0
  125. package/dist/gen-core/near-scatter.d.ts +56 -0
  126. package/dist/gen-core/near-scatter.js +120 -0
  127. package/dist/gen-core/noise.d.ts +23 -0
  128. package/dist/gen-core/noise.js +72 -0
  129. package/dist/gen-core/occupancy.d.ts +21 -0
  130. package/dist/gen-core/occupancy.js +104 -0
  131. package/dist/gen-core/sphere-patch.d.ts +138 -0
  132. package/dist/gen-core/sphere-patch.js +544 -0
  133. package/dist/gen-core/strip-surface.d.ts +34 -0
  134. package/dist/gen-core/strip-surface.js +246 -0
  135. package/dist/gen-core/strip.d.ts +102 -0
  136. package/dist/gen-core/strip.js +817 -0
  137. package/dist/gen-ground/env-slots.d.ts +48 -0
  138. package/dist/gen-ground/env-slots.js +78 -0
  139. package/dist/gen-ground/ground.d.ts +78 -0
  140. package/dist/gen-ground/ground.js +208 -0
  141. package/dist/gen-ground/index.d.ts +9 -0
  142. package/dist/gen-ground/index.js +7 -0
  143. package/dist/gen-ground/markings.d.ts +46 -0
  144. package/dist/gen-ground/markings.js +124 -0
  145. package/dist/gen-ground/materials.d.ts +18 -0
  146. package/dist/gen-ground/materials.js +22 -0
  147. package/dist/gen-ground/terrain-shader.d.ts +5 -0
  148. package/dist/gen-ground/terrain-shader.js +151 -0
  149. package/dist/gen-mesh/bare-shapes.d.ts +194 -0
  150. package/dist/gen-mesh/bare-shapes.js +596 -0
  151. package/dist/gen-mesh/bisect-surface.d.ts +47 -0
  152. package/dist/gen-mesh/bisect-surface.js +261 -0
  153. package/dist/gen-mesh/box.d.ts +18 -0
  154. package/dist/gen-mesh/box.js +2 -0
  155. package/dist/gen-mesh/cell-morph-mesh.d.ts +52 -0
  156. package/dist/gen-mesh/cell-morph-mesh.js +258 -0
  157. package/dist/gen-mesh/cell-surface-mesh.d.ts +32 -0
  158. package/dist/gen-mesh/cell-surface-mesh.js +140 -0
  159. package/dist/gen-mesh/chunk-mesh.d.ts +25 -0
  160. package/dist/gen-mesh/chunk-mesh.js +112 -0
  161. package/dist/gen-mesh/drape-mesh.d.ts +36 -0
  162. package/dist/gen-mesh/drape-mesh.js +98 -0
  163. package/dist/gen-mesh/height-field-mesh.d.ts +14 -0
  164. package/dist/gen-mesh/height-field-mesh.js +98 -0
  165. package/dist/gen-mesh/index.d.ts +26 -0
  166. package/dist/gen-mesh/index.js +15 -0
  167. package/dist/gen-mesh/line-mesh.d.ts +25 -0
  168. package/dist/gen-mesh/line-mesh.js +62 -0
  169. package/dist/gen-mesh/mesh-builder.d.ts +115 -0
  170. package/dist/gen-mesh/mesh-builder.js +315 -0
  171. package/dist/gen-mesh/packed-mesh.d.ts +53 -0
  172. package/dist/gen-mesh/packed-mesh.js +205 -0
  173. package/dist/gen-mesh/prism-mesh.d.ts +33 -0
  174. package/dist/gen-mesh/prism-mesh.js +176 -0
  175. package/dist/gen-mesh/rig-mesh.d.ts +9 -0
  176. package/dist/gen-mesh/rig-mesh.js +135 -0
  177. package/dist/gen-mesh/strip-mesh.d.ts +45 -0
  178. package/dist/gen-mesh/strip-mesh.js +258 -0
  179. package/dist/gen-plan/drain.d.ts +58 -0
  180. package/dist/gen-plan/drain.js +270 -0
  181. package/dist/gen-plan/grid.d.ts +37 -0
  182. package/dist/gen-plan/grid.js +182 -0
  183. package/dist/gen-plan/horizon.d.ts +50 -0
  184. package/dist/gen-plan/horizon.js +185 -0
  185. package/dist/gen-plan/index.d.ts +15 -0
  186. package/dist/gen-plan/index.js +13 -0
  187. package/dist/gen-plan/line-tiles.d.ts +35 -0
  188. package/dist/gen-plan/line-tiles.js +190 -0
  189. package/dist/gen-plan/lines.d.ts +31 -0
  190. package/dist/gen-plan/lines.js +183 -0
  191. package/dist/gen-plan/plots.d.ts +40 -0
  192. package/dist/gen-plan/plots.js +282 -0
  193. package/dist/gen-plan/route.d.ts +55 -0
  194. package/dist/gen-plan/route.js +297 -0
  195. package/dist/gen-plan/sites.d.ts +32 -0
  196. package/dist/gen-plan/sites.js +209 -0
  197. package/dist/gen-tex/code-stamp.d.ts +31 -0
  198. package/dist/gen-tex/code-stamp.js +137 -0
  199. package/dist/gen-tex/index.d.ts +7 -0
  200. package/dist/gen-tex/index.js +5 -0
  201. package/dist/gen-tex/light-horizon.d.ts +47 -0
  202. package/dist/gen-tex/light-horizon.js +180 -0
  203. package/dist/gen-tex/textures.d.ts +8 -0
  204. package/dist/gen-tex/textures.js +49 -0
  205. package/dist/gen-tex/value-textures.d.ts +46 -0
  206. package/dist/gen-tex/value-textures.js +102 -0
  207. package/dist/gen-vegetation/env-slots.d.ts +20 -0
  208. package/dist/gen-vegetation/env-slots.js +29 -0
  209. package/dist/gen-vegetation/index.d.ts +8 -0
  210. package/dist/gen-vegetation/index.js +7 -0
  211. package/dist/gen-vegetation/materials.d.ts +7 -0
  212. package/dist/gen-vegetation/materials.js +17 -0
  213. package/dist/gen-vegetation/planting.d.ts +170 -0
  214. package/dist/gen-vegetation/planting.js +363 -0
  215. package/dist/gen-vegetation/tree-shader.d.ts +23 -0
  216. package/dist/gen-vegetation/tree-shader.js +229 -0
  217. package/dist/gen-vegetation/trees.d.ts +59 -0
  218. package/dist/gen-vegetation/trees.js +329 -0
  219. package/dist/gpu/device.d.ts +286 -0
  220. package/dist/gpu/device.js +1157 -0
  221. package/dist/gpu/gl.d.ts +134 -0
  222. package/dist/gpu/gl.js +276 -0
  223. package/dist/gpu/index.d.ts +4 -0
  224. package/dist/gpu/index.js +3 -0
  225. package/dist/index.d.ts +11 -0
  226. package/dist/index.js +13 -0
  227. package/dist/motion/graph.d.ts +244 -0
  228. package/dist/motion/graph.js +739 -0
  229. package/dist/motion/index.d.ts +8 -0
  230. package/dist/motion/index.js +8 -0
  231. package/dist/motion/pose-ops.d.ts +30 -0
  232. package/dist/motion/pose-ops.js +232 -0
  233. package/dist/motion/reach.d.ts +45 -0
  234. package/dist/motion/reach.js +264 -0
  235. package/dist/motion/skeleton.d.ts +49 -0
  236. package/dist/motion/skeleton.js +99 -0
  237. package/dist/platform/byte-store.d.ts +21 -0
  238. package/dist/platform/byte-store.js +137 -0
  239. package/dist/platform/canvas.d.ts +29 -0
  240. package/dist/platform/canvas.js +76 -0
  241. package/dist/platform/context-loss.d.ts +8 -0
  242. package/dist/platform/context-loss.js +17 -0
  243. package/dist/platform/free-input.d.ts +51 -0
  244. package/dist/platform/free-input.js +100 -0
  245. package/dist/platform/index.d.ts +18 -0
  246. package/dist/platform/index.js +10 -0
  247. package/dist/platform/input.d.ts +48 -0
  248. package/dist/platform/input.js +117 -0
  249. package/dist/platform/keys.d.ts +12 -0
  250. package/dist/platform/keys.js +29 -0
  251. package/dist/platform/loop.d.ts +41 -0
  252. package/dist/platform/loop.js +84 -0
  253. package/dist/platform/walk-input.d.ts +74 -0
  254. package/dist/platform/walk-input.js +226 -0
  255. package/dist/platform/worker.d.ts +51 -0
  256. package/dist/platform/worker.js +170 -0
  257. package/dist/render/bone-instances.d.ts +24 -0
  258. package/dist/render/bone-instances.js +74 -0
  259. package/dist/render/cells.d.ts +70 -0
  260. package/dist/render/cells.js +144 -0
  261. package/dist/render/glsl.d.ts +66 -0
  262. package/dist/render/glsl.js +173 -0
  263. package/dist/render/index.d.ts +26 -0
  264. package/dist/render/index.js +16 -0
  265. package/dist/render/instance-sets.d.ts +97 -0
  266. package/dist/render/instance-sets.js +241 -0
  267. package/dist/render/near-instances.d.ts +75 -0
  268. package/dist/render/near-instances.js +219 -0
  269. package/dist/render/particles.d.ts +63 -0
  270. package/dist/render/particles.js +215 -0
  271. package/dist/render/pieces.d.ts +57 -0
  272. package/dist/render/pieces.js +151 -0
  273. package/dist/render/point-lights.d.ts +97 -0
  274. package/dist/render/point-lights.js +243 -0
  275. package/dist/render/renderer.d.ts +447 -0
  276. package/dist/render/renderer.js +1100 -0
  277. package/dist/render/rig.d.ts +74 -0
  278. package/dist/render/rig.js +576 -0
  279. package/dist/render/shadow-areas.d.ts +49 -0
  280. package/dist/render/shadow-areas.js +125 -0
  281. package/dist/render/shadow-glsl.d.ts +12 -0
  282. package/dist/render/shadow-glsl.js +146 -0
  283. package/dist/render/transient.d.ts +61 -0
  284. package/dist/render/transient.js +213 -0
  285. package/dist/render/value-glsl.d.ts +17 -0
  286. package/dist/render/value-glsl.js +208 -0
  287. package/dist/render/value-layers.d.ts +180 -0
  288. package/dist/render/value-layers.js +333 -0
  289. package/dist/runtime/atmosphere.d.ts +37 -0
  290. package/dist/runtime/atmosphere.js +304 -0
  291. package/dist/runtime/cloud-shell.d.ts +29 -0
  292. package/dist/runtime/cloud-shell.js +158 -0
  293. package/dist/runtime/engine.d.ts +155 -0
  294. package/dist/runtime/engine.js +305 -0
  295. package/dist/runtime/environment-link.d.ts +22 -0
  296. package/dist/runtime/environment-link.js +49 -0
  297. package/dist/runtime/index.d.ts +13 -0
  298. package/dist/runtime/index.js +12 -0
  299. package/dist/runtime/precipitation-glsl.d.ts +2 -0
  300. package/dist/runtime/precipitation-glsl.js +70 -0
  301. package/dist/runtime/precipitation.d.ts +11 -0
  302. package/dist/runtime/precipitation.js +78 -0
  303. package/dist/runtime/sky.d.ts +30 -0
  304. package/dist/runtime/sky.js +114 -0
  305. package/dist/runtime/streaming.d.ts +245 -0
  306. package/dist/runtime/streaming.js +602 -0
  307. package/dist/sim/agenda.d.ts +167 -0
  308. package/dist/sim/agenda.js +425 -0
  309. package/dist/sim/bytes.d.ts +34 -0
  310. package/dist/sim/bytes.js +125 -0
  311. package/dist/sim/destruction/apply.d.ts +59 -0
  312. package/dist/sim/destruction/apply.js +243 -0
  313. package/dist/sim/destruction/cell-states.d.ts +54 -0
  314. package/dist/sim/destruction/cell-states.js +198 -0
  315. package/dist/sim/destruction/index.d.ts +11 -0
  316. package/dist/sim/destruction/index.js +10 -0
  317. package/dist/sim/destruction/int-geometry.d.ts +17 -0
  318. package/dist/sim/destruction/int-geometry.js +131 -0
  319. package/dist/sim/destruction/pick.d.ts +13 -0
  320. package/dist/sim/destruction/pick.js +59 -0
  321. package/dist/sim/destruction/rubble.d.ts +8 -0
  322. package/dist/sim/destruction/rubble.js +159 -0
  323. package/dist/sim/destruction/state.d.ts +15 -0
  324. package/dist/sim/destruction/state.js +83 -0
  325. package/dist/sim/destruction/structure.d.ts +30 -0
  326. package/dist/sim/destruction/structure.js +139 -0
  327. package/dist/sim/events.d.ts +37 -0
  328. package/dist/sim/events.js +106 -0
  329. package/dist/sim/fixed.d.ts +21 -0
  330. package/dist/sim/fixed.js +64 -0
  331. package/dist/sim/flow-probe.d.ts +58 -0
  332. package/dist/sim/flow-probe.js +158 -0
  333. package/dist/sim/flow.d.ts +257 -0
  334. package/dist/sim/flow.js +967 -0
  335. package/dist/sim/index.d.ts +28 -0
  336. package/dist/sim/index.js +20 -0
  337. package/dist/sim/interlock.d.ts +47 -0
  338. package/dist/sim/interlock.js +252 -0
  339. package/dist/sim/movers.d.ts +228 -0
  340. package/dist/sim/movers.js +1083 -0
  341. package/dist/sim/nav.d.ts +72 -0
  342. package/dist/sim/nav.js +292 -0
  343. package/dist/sim/paths.d.ts +80 -0
  344. package/dist/sim/paths.js +197 -0
  345. package/dist/sim/regions.d.ts +87 -0
  346. package/dist/sim/regions.js +517 -0
  347. package/dist/sim/simulation.d.ts +114 -0
  348. package/dist/sim/simulation.js +291 -0
  349. package/dist/sim/states.d.ts +23 -0
  350. package/dist/sim/states.js +54 -0
  351. package/dist/sim/table.d.ts +49 -0
  352. package/dist/sim/table.js +126 -0
  353. package/dist/sim/zones.d.ts +11 -0
  354. package/dist/sim/zones.js +196 -0
  355. package/dist/tools/collision-lines.d.ts +12 -0
  356. package/dist/tools/collision-lines.js +50 -0
  357. package/dist/tools/data-view-glsl.d.ts +3 -0
  358. package/dist/tools/data-view-glsl.js +63 -0
  359. package/dist/tools/data-view-layers.d.ts +20 -0
  360. package/dist/tools/data-view-layers.js +60 -0
  361. package/dist/tools/debug-view.d.ts +30 -0
  362. package/dist/tools/debug-view.js +4 -0
  363. package/dist/tools/index.d.ts +10 -0
  364. package/dist/tools/index.js +7 -0
  365. package/dist/tools/mesh-checks.d.ts +67 -0
  366. package/dist/tools/mesh-checks.js +188 -0
  367. package/dist/tools/profile.d.ts +85 -0
  368. package/dist/tools/profile.js +173 -0
  369. package/dist/world/cell-cache.d.ts +32 -0
  370. package/dist/world/cell-cache.js +60 -0
  371. package/dist/world/cell-format.d.ts +25 -0
  372. package/dist/world/cell-format.js +232 -0
  373. package/dist/world/collide.d.ts +192 -0
  374. package/dist/world/collide.js +822 -0
  375. package/dist/world/index.d.ts +16 -0
  376. package/dist/world/index.js +12 -0
  377. package/dist/world/mesh-solids.d.ts +48 -0
  378. package/dist/world/mesh-solids.js +169 -0
  379. package/dist/world/pick.d.ts +34 -0
  380. package/dist/world/pick.js +177 -0
  381. package/dist/world/providers.d.ts +66 -0
  382. package/dist/world/providers.js +83 -0
  383. package/dist/world/sphere.d.ts +69 -0
  384. package/dist/world/sphere.js +271 -0
  385. package/dist/world/streaming.d.ts +288 -0
  386. package/dist/world/streaming.js +801 -0
  387. package/dist/world/walker.d.ts +145 -0
  388. package/dist/world/walker.js +502 -0
  389. package/docs/architecture.md +111 -0
  390. package/docs/cameras.md +302 -0
  391. package/docs/concepts.md +123 -0
  392. package/docs/destruction.md +127 -0
  393. package/docs/frames.md +199 -0
  394. package/docs/generators.md +575 -0
  395. package/docs/getting-started.md +123 -0
  396. package/docs/headless.md +50 -0
  397. package/docs/motion.md +160 -0
  398. package/docs/planet.md +152 -0
  399. package/docs/recipes.md +521 -0
  400. package/docs/reference.md +364 -0
  401. package/docs/rendering.md +823 -0
  402. package/docs/rigs.md +203 -0
  403. package/docs/simulation.md +235 -0
  404. package/docs/streaming.md +590 -0
  405. package/docs/system.md +166 -0
  406. package/docs/tools.md +175 -0
  407. package/docs/walking.md +262 -0
  408. package/package.json +131 -3
@@ -0,0 +1,575 @@
1
+ # Generators
2
+
3
+ A generator is a pure function: input plus seed gives plain data ([Concepts](concepts.md#1-generators-return-plain-data)). Generators live in layers 2 and 3 and never touch the GPU.
4
+
5
+ ## `gen-core`: randomness, fields, geometry
6
+
7
+ **Randomness.** `streamSeed(worldSeed, name)` derives a named stream. `hashInts(seed, ...keys)` hashes integer keys. `unit(h)` maps a hash to 0..1. `rand(seed, ...keys)` and `randRange(lo, hi, seed, ...keys)` combine both. `pickWeighted(options, r)` picks by weight. `hashString`, `hashInt` and `mix32` are the building blocks.
8
+
9
+ **Noise.** `valueNoise2(x, z, cellM, seed)` is smooth 2D value noise in 0..1.
10
+
11
+ `valueNoise3(x, y, z, cellM, seed)` is the same in space, and `fractalNoise3(x, y, z, { cellM, octaves, lacunarity?, gain? }, seed)` sums octaves of it (0..1, each octave with its own seed and offset). Sampled at the points of a curved surface they have no seam and no pole: the value depends on the point alone. Both are built from the integer hash, `Math.floor` and arithmetic, so the bits are the same everywhere.
12
+
13
+ **A cube blown up to a sphere.** `cube-sphere.ts` holds the geometry of a sphere made of six square grids, without any radius: `CUBE_FACE_AXES` (faces 0 +x, 1 −x, 2 +y, 3 −y, 4 +z, 5 −z, each with axes u and v, u × v outward), `cubeGrid(g, count)` (grid index to −1..1), `cubeWarp` / `cubeUnwarp` (the even-angle spacing, from reproducible trigonometry), `cubeDirection(face, s, t)` and `cubeDirectionWarped` (the unit direction of a grid point; a point shared by two faces gets the same bits from both), `cubeFaceOf(dir)` and `cubeFaceCoords(face, dir)` (back), `cubeNeighbour(face, level, x, y, dx, dy)` (the cell next to a cell, across an edge of the cube; null over a corner) and `directionTangents(dir)` (two directions across `dir` that depend on `dir` alone).
14
+
15
+ **Surface of a sphere cell.** `spherePatchMesh({ radiusM, face, level, x, y, quads, heightAt, colorAt?, skirtDepth })` builds the mesh of one cell (`SPHERE_PATCH_LAYOUT`, attribute locations `SPHERE_PATCH_ATTRIBS`) with normals, the blend attributes toward the level above and a skirt, and returns its origin, bounds, height range and error. `spherePatchRadius(options, dir, step)` is where a direction meets the triangles of that mesh (`step` 1) or of the level above (`step` 2). `SPHERE_PATCH_GLSL` is the blend factor for the vertex shader. See [A sphere world](streaming.md#a-sphere-world).
16
+
17
+ **Fields.** Spatial structures that generators query:
18
+
19
+ | Class | Use |
20
+ | --- | --- |
21
+ | `HeightField(step, cols, rows, heights)` | A regular height grid. `heightAt(x, z)` interpolates; `minY`, `maxY`. The static `HeightField.coarseSurface(cols, rows, values, n)` gives the surface of the grid thinned to every n-th vertex, evaluated at every vertex (the shape of a coarser level of detail). |
22
+ | `SegmentField(sizeX, sizeZ, bucketM?)` | Distance to the nearest of many segments (lines such as paths). |
23
+ | `OutlineField(polygons, sizeX, sizeZ, bucketM?)` | Inside tests and distance to polygon outlines. |
24
+ | `Occupancy(sizeX, sizeZ, step?)` | A grid that marks taken ground, for placement without overlap. |
25
+
26
+ **Geometry.** `Ring` is a flat `[x, z, x, z, …]` polygon. `ringSignedArea`, `ringsArea`, `pointInRings`, `insetRing`, `distToSegment`, `orientedBox`.
27
+
28
+ **Instance cells.** `splitInstanceCells(instances, { stride, bounds, cellM, tiers?, seed? })` sorts an instance stream into square cells of `cellM` metres by base point (x, z). Each cell gets a box that holds its instances (radius widened by the widest tier) and its data per tier: tier t keeps an instance when `hash(seed, index) % keep === 0` and multiplies its radius by `widen`. `DEFAULT_INSTANCE_TIERS` keeps all, one in 4 (×1.7) and one in 12 (×2.6). Cells come ordered by row, then column. Feed the result to `InstanceCellLayer` ([Rendering](rendering.md#layers)).
29
+
30
+ **Cells.** `CellId`, `FlatWorld`, `FACE_FLAT`, `LEVEL`, `cellKey`, `shapeHash` and friends describe streamed cells. They are in `gen-core` so that generators can produce `CellContent` without depending on `world`. See [World streaming](streaming.md).
31
+
32
+ ```ts
33
+ import { HeightField, Occupancy, randRange, streamSeed, valueNoise2 } from 'wallhammer-web/gen-core';
34
+
35
+ const seed = streamSeed('7', 'stones');
36
+ const n = 33;
37
+ const heights = Float32Array.from({ length: n * n }, (_, k) => 8 * valueNoise2((k % n) * 4, Math.floor(k / n) * 4, 30, seed));
38
+ const field = new HeightField(4, n, n, heights);
39
+ const taken = new Occupancy(128, 128);
40
+ const stones: number[] = [];
41
+ for (let i = 0; i < 20; i++) {
42
+ const x = randRange(8, 120, seed, i, 0);
43
+ const z = randRange(8, 120, seed, i, 1);
44
+ stones.push(x, field.heightAt(x, z), z);
45
+ }
46
+ ```
47
+
48
+ ## `gen-mesh`: meshes
49
+
50
+ | Export | Output |
51
+ | --- | --- |
52
+ | `heightFieldMesh(field, baseY)` | Surface plus a vertical skirt down to `baseY`. Layout `HEIGHT_FIELD_LAYOUT`: position as 3 floats, normal as 3 × int16 plus a kind (0 surface, 1 skirt). |
53
+ | `lineMesh(paths, heightAt, liftM?, maxSegmentM?)` | Line segments draped over a height function. Layout `LINE_LAYOUT`. |
54
+ | `cellSurfaceMesh({ originX, originZ, size, quads, heightAt, colorAt?, skirtDepth })` | One streamed cell's surface relative to its origin, with vertex colours and a skirt that hides cracks between levels. Layout `CELL_SURFACE_LAYOUT`. |
55
+ | `cellMorphMesh(options)` | The same surface (same options, `quads` even) that can blend into the cell one level coarser: per vertex also the distance to the coarser surface and its normal and colour. Returns `{ mesh, minY, maxY, error, skirtDepth }`; the skirt is at least `skirtDepth` and at least twice what its border needs (with `quads` a multiple of four also for a cell shown away from the viewer in its parent's shape). Layout `CELL_MORPH_LAYOUT`, shader part `CELL_MORPH_GLSL`. See [World streaming](streaming.md#blending-between-levels). |
56
+ | `drapeTiles(field, { rect?, liftM?, tileQuads?, every?, origin? })` | A sheet laid on a height field: the field's own surface again, lifted by `liftM` (0.15 m), positions only, in tiles of `tileQuads` quads with their boxes. With `every` > 1 it uses every n-th vertex and the highest height around it, so it never sinks below the surface. `drapeEvery(field, maxVertices, rect?)` gives the smallest `every` that fits a vertex count. Layout `DRAPE_LAYOUT`. |
57
+ | `prismMesh(shapes, { growM? })` | Upright prisms (walls and lid) over outlines; every vertex carries its prism's table row in `a_ref`. `growM` moves the walls outward so the shell stands clear of what it wraps. No normals: the shader takes the face direction from screen derivatives. Layout `PRISM_LAYOUT`. `triangulateRing(ring)` is the ear clipping it uses for lids. |
58
+ | `packMesh(mesh, frame, { spans? })` | The same mesh with positions as 16-bit steps of `frame` (`packFrame(edgeM, origin, heightOrigin, stepY)`: 16,384 steps along the edge, `stepY` metres per vertical step) and every other attribute byte for byte. Loose triangles become indexed, equal vertices once in the order of first use; with `spans` only inside each span, so one span packed alone has the bytes it has in the whole. Indices are 16-bit up to 65,536 vertices. Returns `{ mesh, spans, clamped }`. `packedLayout(layout)` is the resulting layout, `packedMaterial(desc)` the material that reads it. See [Packed meshes](streaming.md#packed-meshes). |
59
+ | `bisectSurface(heights, options)` | A square height grid (`quads` a power of two, one extra sample all round for the normals) as a packed mesh within `toleranceM` of the grid: flat ground becomes a few large triangles. Outer edges get a skirt `skirtM` deep; a side listed in `cuts` is a cut through the ground down to a height; `clip` cuts the square off at a rectangle. Returns `{ mesh, triangles, gridTriangles, minY, maxY }`. Layout `BISECT_SURFACE_LAYOUT` (packed position, normal as 3 × int16 plus a kind), drawn by a height field material through `packedMaterial`. See [A surface within a tolerance](streaming.md#a-surface-within-a-tolerance). |
60
+ | `chunkMeshes(meshes, { cellM?, cellKey?, position?, padM? })` | Static meshes cut into spatial chunks: every triangle goes to the cell of its centroid (square cells of `cellM`, 64 m, or any cell from `cellKey(x, y, z)`), the triangles of one cell from all meshes are merged with whole vertex records copied byte for byte. All meshes share one layout with a three-float position (`a_pos`). Returns `MeshChunk[]` (`{ key, min, max, data, triangles }`, boxes widened by `padM`), ready for `PieceLayer`: one draw per visible chunk. See [Point lights, particles and instance sets](rendering.md#point-lights-particles-and-instance-sets). |
61
+ | `PropBox` (type) | A small oriented box prop. `gen-arch` re-exports the same type. |
62
+ | `MeshBuilder<V>`, `VertexFormat<V>`, `faceNormal` | Building meshes by hand in a vertex format of the caller's: a transform stack, triangles, mirroring, `append`, bounds, the positions and indices for collisions and checks. See [Building meshes in your own vertex format](#building-meshes-in-your-own-vertex-format). |
63
+ | `revolve`, `sweep`, `extrude`, `polygon`, `gridSurface`, `box`, `cylinder`, `pathFrames`, `smoothPath` | Bare shapes for `MeshBuilder<V>` that ask the caller for every vertex payload. See [Bare shapes](#bare-shapes). |
64
+
65
+ ## Building meshes in your own vertex format
66
+
67
+ What a vertex carries besides its position and normal decides what a material can draw, so it belongs to the game:
68
+ one game stores colour, occlusion and a few flag bytes, another stores panel coordinates for ink lines and a direction
69
+ for an outline. `MeshBuilder<V>` (`gen-mesh/mesh-builder.ts`) builds triangles in any such format. It knows only the
70
+ position, the normal, the transforms and the indices; the rest is a payload `V` per vertex, stored by reference and
71
+ handed back to the format when the mesh is packed. The engine never looks inside it.
72
+
73
+ <!-- check: skip -->
74
+ ```ts
75
+ interface VertexFormat<V> {
76
+ readonly layout: VertexLayout; // attributes, including position and normal; layout.stride === stride
77
+ readonly stride: number; // bytes per vertex
78
+ /** One vertex at `offset`; `p` and `n` are already in mesh space (n unit length). `index` is the vertex number. */
79
+ write(view: DataView, offset: number, p: ArrayLike<number>, n: ArrayLike<number>, v: V, index: number): void;
80
+ }
81
+ ```
82
+
83
+ | Member | What it does |
84
+ | --- | --- |
85
+ | `new MeshBuilder(format)` | An empty builder; throws when `format.layout.stride` differs from `format.stride`. |
86
+ | `push(m)`, `pop()`, `with(m, fn)` | The transform stack: `m` is a 3 × 4 matrix (12 numbers, column by column, as `Mat34` in [Concepts](concepts.md#3--4-matrices)); `push` multiplies the current transform by `m` (`m` applies first). `transform` and `mirrored` read the current state; `pop` without `push` throws. |
87
+ | `vertex(p, n, v)` | Adds a vertex through the current transform (normals by the cofactor matrix, unit length, outward also under a mirror); returns its index. |
88
+ | `tri(a, b, c)`, `quad(a, b, c, d)` | Triangles counter-clockwise seen from outside; under a mirroring transform the winding is reversed so faces stay outward. |
89
+ | `append(other, m?)` | Another builder's vertices (through the current transform, then `m`) and triangles; payloads are kept, a mirroring result flips the winding. |
90
+ | `bounds(first?)`, `vertexCount`, `indexCount`, `triangleCount` | Box and counts. |
91
+ | `position(i)`, `normal(i)`, `payload(i)`, `setPayload(i, v)`, `edit(fn, first?, end?)` | Read or change single vertices; `edit` visits a range with the position and normal to change in place and may return a new payload (displacing, recolouring, filling data that depends on the finished mesh). |
92
+ | `positions()`, `normals()`, `indices({ index? })` | New typed arrays: for collision solids (`addMeshSolid` in [Walking](walking.md)), checks ([Mesh checks](tools.md#mesh-checks)), or a second index order. |
93
+ | `positionData`, `normalData`, `indexData`, `setTriangle(t, a, b, c)` | The same numbers without a copy (read only, live), for passes over a large builder; `setTriangle` rewrites one triangle as given, for example to turn its winding after the fact (a triangle or vertex out of range throws `RangeError`). |
94
+ | `vertices()`, `build({ index? })` | The packed bytes (`write` once per vertex, in order) and the `MeshData`. Indices are 16-bit up to 65,536 vertices, else 32-bit; `index: 32` forces 32 bits. |
95
+ | `faceNormal(points, out?)` | The unit normal of a flat polygon given counter-clockwise from its front (Newell's method). |
96
+
97
+ A game defines its format once, next to its material:
98
+
99
+ ```ts
100
+ import type { VertexLayout } from 'wallhammer-web/base';
101
+ import { MeshBuilder } from 'wallhammer-web/gen-mesh';
102
+ import type { VertexFormat } from 'wallhammer-web/gen-mesh';
103
+
104
+ /** This game's payload: an albedo and a glow strength. */
105
+ interface Paint {
106
+ rgb: readonly [number, number, number];
107
+ glow: number;
108
+ }
109
+
110
+ const LAYOUT: VertexLayout = {
111
+ stride: 20,
112
+ attribs: [
113
+ { name: 'a_pos', size: 3, type: 'f32', offset: 0 },
114
+ { name: 'a_normal', size: 4, type: 'i8', normalized: true, offset: 12 },
115
+ { name: 'a_paint', size: 4, type: 'u8', normalized: true, offset: 16 },
116
+ ],
117
+ };
118
+
119
+ const byte = (x: number): number => Math.max(0, Math.min(255, Math.round(x * 255)));
120
+
121
+ const FORMAT: VertexFormat<Paint> = {
122
+ layout: LAYOUT,
123
+ stride: 20,
124
+ write(view, o, p, n, v) {
125
+ for (let k = 0; k < 3; k++) view.setFloat32(o + k * 4, p[k]!, true);
126
+ for (let k = 0; k < 3; k++) view.setInt8(o + 12 + k, Math.round(n[k]! * 127));
127
+ for (let k = 0; k < 3; k++) view.setUint8(o + 16 + k, byte(v.rgb[k]!));
128
+ view.setUint8(o + 19, byte(v.glow));
129
+ },
130
+ };
131
+
132
+ const b = new MeshBuilder(FORMAT);
133
+ const red: Paint = { rgb: [0.8, 0.2, 0.1], glow: 0 };
134
+ const a = b.vertex([0, 0, 0], [0, 1, 0], red);
135
+ const c = b.vertex([1, 0, 0], [0, 1, 0], red);
136
+ const d = b.vertex([0, 0, -1], [0, 1, 0], red);
137
+ b.tri(a, c, d);
138
+ const mesh = b.build();
139
+ ```
140
+
141
+ Data that depends on the finished mesh (a direction averaged over all faces meeting at a point, baked occlusion) is
142
+ filled afterwards: read `positions()` and `normals()`, compute, and write it into the payloads with `edit` or
143
+ `setPayload` before `build`. The format's `write` also gets the vertex number, for a format that keeps such data in an
144
+ array of its own.
145
+
146
+ ### Bare shapes
147
+
148
+ `gen-mesh/bare-shapes.ts` writes plain geometry into a `MeshBuilder<V>` at its current transform. None of these shapes
149
+ carries a look: no colour, no seams, no bevels, no irregularity. For every vertex they call the caller's payload
150
+ function with its geometric facts, a `ShapeVertex` (one object reused for the whole call: read it, do not keep it):
151
+
152
+ | Field | Meaning |
153
+ | --- | --- |
154
+ | `p`, `n` | Position and unit normal in the shape's own frame (before the builder's transform). |
155
+ | `part` | `'side'`, `'start'` / `'end'` for the caps, `'cut'` for the two meridian planes of a partial revolution (`j` 0 at `from`, 1 at `to`). |
156
+ | `i`, `j` | Grid indices: `i` across (around a revolution, along a section or an outline), `j` along (profile point, path point, 0 / 1 at the two ends of an extrusion). On a cap `i` is the rim corner. |
157
+ | `u`, `v` | Shares 0–1 matching `i` and `j` (by angle around a revolution, by arc length elsewhere). On a cap `u` runs round the rim, `v` is 1 on the rim and 0 at a fan centre. |
158
+ | `face`, `corner` | On flat faces: the face number within the call and the corner 0, 1, 2, … in winding order; −1 on smooth surfaces. |
159
+ | `centre` | True for the centre vertex of a fan. |
160
+
161
+ | Function | Shape |
162
+ | --- | --- |
163
+ | `revolve(b, profile, payload, { segments?, from?, to?, smooth?, capStart?, capEnd?, capFan?, sides?, warp? })` | A surface of revolution about +y from `[radius, y]` points; a point is `(r sin θ, y, r cos θ)`, θ from +z toward +x. A profile from bottom to top faces outward. Radius 0 is an apex. A partial angle range is open unless `sides` closes its two meridian planes; caps close the profile's ends with discs. |
164
+ | `sweep(b, path, section, payload, { closed?, loop?, caps?, capFan?, scale?, twist?, up?, smooth?, subdivide?, warp? })` | A section (`[x, y]` in the frame u–v across the path) pulled along 3D points with rotation-minimising frames (`pathFrames`). `scale` and `twist` vary with the share of the length; `subdivide` first smooths the path (`smoothPath`, centripetal Catmull–Rom through the points); `loop` closes the path into a ring. A clockwise section is turned around, so faces point away from the path. |
165
+ | `extrude(b, outline, z0, z1, payload, { capStart?, capEnd?, capFan?, smooth? })` | An outline in the x–y plane pushed along +z; flat side quads with corners (p, z0) (q, z0) (q, z1) (p, z1), or smooth sides. Push a rotation first to extrude another way. |
166
+ | `polygon(b, points, payload, { fan?, part?, face? })` | A flat simple polygon: a fan from its first corner when convex, ear clipping when concave, or a fan from an extra centre vertex with `fan`. |
167
+ | `gridSurface(b, cols, rows, at, payload, { smooth?, wrapI?, wrapJ?, flip?, u?, v?, normalAt?, part?, faceBase? })` | Any parametric grid of points stitched into quads facing d/di × d/dj; the base of the others. |
168
+ | `box(b, min, max, payload)`, `cylinder(b, radius, y0, y1, payload, { radiusTop?, segments?, capStart?, capEnd?, smooth? })` | The two special cases: an extrusion of a rectangle and a revolution of two points. |
169
+
170
+ `smooth` picks the normals: `true` (shared vertices, normals from the grid), `false` (every cell a flat face of its
171
+ own) or `'along'` (`GridSmooth`: flat across, smooth along, a section with hard corners bent along a path). `warp(p, i,
172
+ j)` may move every grid point before the normals are taken: that is where a game adds its own irregularity, from its
173
+ own seeded stream. All functions return the index of the first vertex they wrote.
174
+
175
+ A styled shape of a game is a bare shape plus a payload function. Here a game adds panel lines around a body of
176
+ revolution (its shader draws a line where a coordinate crosses an integer) and paints its start cap darker:
177
+
178
+ ```ts
179
+ import { MeshBuilder, revolve } from 'wallhammer-web/gen-mesh';
180
+ import type { ShapeVertex, VertexFormat } from 'wallhammer-web/gen-mesh';
181
+
182
+ /** This game's payload: panel coordinates and a palette index. */
183
+ interface Ink {
184
+ line: readonly [number, number];
185
+ colour: number;
186
+ }
187
+ declare const INK_FORMAT: VertexFormat<Ink>;
188
+
189
+ /** The game's styled shape: `ribs` vertical seams and a seam at every listed profile point. */
190
+ function seamedBody(b: MeshBuilder<Ink>, profile: readonly (readonly [number, number])[], ribs: number, seams: readonly number[], colour: number): void {
191
+ const along = (j: number): number => seams.filter((s) => s <= j).length - 0.5;
192
+ revolve(b, profile, (s: ShapeVertex): Ink => {
193
+ if (s.part !== 'side') return { line: [0.5, 0.5], colour: colour + 1 };
194
+ return { line: [s.u * ribs, along(s.j)], colour };
195
+ }, { segments: 32, capStart: true });
196
+ }
197
+
198
+ const b = new MeshBuilder(INK_FORMAT);
199
+ seamedBody(b, [[1, 0], [1.2, 1], [0.6, 2], [0, 2.4]], 6, [1, 2], 3);
200
+ const mesh = b.build();
201
+ ```
202
+
203
+ `pnpm check:mesh` (`tools/mesh/check.ts`) checks the core and the shapes without a browser ([Tools](tools.md)).
204
+
205
+ ## Strips along a surface
206
+
207
+ Narrow, long things that follow a broken line over the ground of a streamed world, on a plane or on a sphere. The
208
+ engine does not know what a strip stands for; it gives three parts, each pure (output = input, no seed):
209
+
210
+ - **The net** (`gen-core`, `stripNet(input)`): lines of points on the base surface (`radiusM` 0 = the plane with up
211
+ +y, else a sphere about the origin), a grade per point (the height of the section's zero above the base surface), a
212
+ half-width, a profile and optional nodes at their ends. A profile is a section (pairs across, up: across in
213
+ half-widths from −1 on the left to 1 on the right, points beyond ±1 are a hem hanging from the edge), a shoulder over
214
+ which the ground returns to its own height, and a bed the ground keeps under the section. The net measures the
215
+ lines, mitres their edges at every point and puts the corners where neighbouring lines of a node meet; it throws on
216
+ input it cannot use.
217
+ - **The height function** (`gen-core`, `stripCarve(net, x, y, z, ownHeightM)`): the ground under the lines, cut and
218
+ filled to the section minus the bed, returning to `ownHeightM` over the shoulder. It is continuous everywhere, also
219
+ where lines meet, and returns `ownHeightM` with the same bits where no line reaches. A cell generator passes it its
220
+ ground height; `stripTouches(net, x, y, z, radiusM)` says cheaply when a whole cell can skip it, and
221
+ `stripNearest` gives the line that matters most at a point (to tint or clear the ground there).
222
+ - **The mesh** (`gen-mesh`, `stripMesh(net, surface, cell, options)`): the strips of one cell at its level. Every
223
+ segment is cut where it meets the edges of the triangles the cell's level draws (`StripSurface.cuts`), so a section of
224
+ vertices stands at each cut and the strip folds exactly where the ground folds. A vertex stands at
225
+ `max(grade + up(a), drawn surface + liftM(level))`, so it is never under the ground of any level; `a_coarseShift`
226
+ holds the same for the level one coarser, and the vertex shader blends with the surface's own blend factor. Sections
227
+ on a cell border carry the same bits in both cells. `STRIP_GLSL` adds `stripWiden`, which moves the edge vertices
228
+ outward until the strip is at least `minPx` pixels wide: from afar a strip stays a thin unbroken line instead of
229
+ breaking up.
230
+
231
+ `flatStripSurface` and `sphereStripSurface` describe the surface the cells draw (`cellMorphMesh` on a `FlatWorld`,
232
+ `spherePatchMesh` on the sphere of six quadtrees). Give them the same height function as the surface mesh, the carved
233
+ one, so the strip and the ground agree.
234
+
235
+ <!-- check: wrap -->
236
+ ```ts
237
+ import { FlatWorld, flatStripSurface, stripCarve, stripNet, stripTouches, valueNoise2 } from 'wallhammer-web/gen-core';
238
+ import type { CellId } from 'wallhammer-web/gen-core';
239
+ import { stripMesh } from 'wallhammer-web/gen-mesh';
240
+
241
+ const shape = new FlatWorld();
242
+ const ground = (x: number, z: number): number => 30 * valueNoise2(x, z, 400, 7);
243
+ const net = stripNet({
244
+ radiusM: 0,
245
+ profiles: [{ section: [-1.25, -1.2, -1, 0, 0, 0.25, 1, 0, 1.25, -1.2], shoulderM: 14, bedM: 0.3 }],
246
+ nodes: [{ point: [600, 0, 400], heightM: 12 }],
247
+ lines: [
248
+ { points: [0, 0, 0, 300, 0, 150, 600, 0, 400], heights: [10, 11, 12], halfWidths: 8, profile: 0, to: 0 },
249
+ { points: [600, 0, 400, 900, 0, 380], heights: [12, 14], halfWidths: 5, profile: 0, from: 0 },
250
+ { points: [600, 0, 400, 760, 0, 700], heights: [12, 9], halfWidths: 5, profile: 0, from: 0 },
251
+ ],
252
+ });
253
+ const carved = (x: number, z: number): number => stripCarve(net, x, 0, z, ground(x, z));
254
+ const surface = flatStripSurface({ shape, quads: 32, heightAt: carved });
255
+ const cell: CellId = shape.cellAt([300, 0, 150], 7);
256
+ const o = shape.origin(cell);
257
+ const edge = shape.edgeM(cell.level);
258
+ if (stripTouches(net, o[0] + edge / 2, 0, o[2] + edge / 2, edge * 0.71)) {
259
+ // The surface mesh of the cell takes `carved` as its height; the strips are a second mesh of the cell.
260
+ const strips = stripMesh(net, surface, cell, { coarsestLevel: 4, liftM: (level) => 0.05 + 0.08 * surface.spacingM(level) });
261
+ if (strips) console.log(strips.mesh.count, strips.lengthM);
262
+ }
263
+ ```
264
+
265
+ The material of the strips includes `<header>`, then `<noise>` (for `metresPerPixelAt`), the blend code of the surface
266
+ and `STRIP_GLSL`, with the attribute locations of `STRIP_ATTRIBS`:
267
+
268
+ <!-- check: skip -->
269
+ ```ts
270
+ vec3 p = a_pos + u_cellOffset;
271
+ p += localUp(p) * (a_coarseShift * spherePatchMorph(p)); // on the plane: u_morphUp and cellMorph(p)
272
+ float grow;
273
+ p = stripWiden(p, a_side, a_strip, 1.6, grow);
274
+ ```
275
+
276
+ Limits: nodes sit at line ends only and are flat at their height; lines do not pass through a corner of the cube and
277
+ do not close into loops; there is no spatial index (a linear scan with a bounding test per line). The examples
278
+ `planet` (a strip 50 km long over an edge of the cube, forking at its end) and `endless` (`#strip=1`) use all three
279
+ parts.
280
+
281
+ ## Instances near the viewer
282
+
283
+ Small things seen only round the eye (a few per square metre, out to some tens of metres) are made per square of a fixed
284
+ fine grid by `nearScatter` (`gen-core/near-scatter.ts`). A square is named by integers, its `key`; every number of a
285
+ record is a hash of the seed, that key, the kind and the candidate's index, so a square gives the same bytes in any
286
+ order, on any thread, whatever else is made.
287
+
288
+ - Per kind, `candidates[k]` is rounded up to g², one candidate in each cell of a g × g grid over the square, jittered
289
+ inside its cell. `densityAt(kind, u, v)` keeps a share (a higher density only adds records); `fill` writes a kept
290
+ one: 12 floats (`NEAR_FLOATS`): x y z relative to the anchor of the set, order | width, height, turn, bend | r g b,
291
+ variant. `NEAR_LAYOUT` is the matching instance layout (`i_base`, `i_shape`, `i_color`).
292
+ - Within a kind the records are sorted by their order 0–1, highest first. The fade by distance (`NearFade`: `reachM`,
293
+ `band`, `softM`) lets each record leave at `nearLeaveM = gain · reach · (1 − band · (1 − order))`, shrinking over
294
+ `softM`: the lowest order leaves first, so the density thins out toward the reach instead of stopping at a line.
295
+ - What can still be seen from a distance is therefore a prefix of the records: `nearCount` finds its length by a
296
+ binary search, and a drawing layer copies only that. `NEAR_FADE_GLSL` is the same fade for a shader.
297
+
298
+ `NearInstanceLayer` of `render` draws such sets ([Instances near the viewer](rendering.md#instances-near-the-viewer)).
299
+ The system example makes small details round the camera with it (`examples/system/src/details.ts`).
300
+
301
+ ## `gen-tex`: textures
302
+
303
+ | Export | Output |
304
+ | --- | --- |
305
+ | `codeTexture(codes, cols, rows)` | An `r8ui` texture of integer class codes. |
306
+ | `colorTable(colors, fallback?)` | A 256-entry colour lookup by code. |
307
+ | `boxBlur(src, cols, rows, radius)` | A blurred `Float32Array` (CPU only). |
308
+ | `quantizeValues(values, min, max, out?)` | Numbers as 16-bit words for the value layers: `min` → 1, `max` → 65535, outside clamped, not finite → `NO_VALUE` (0). `wordValue(word, min, max)` turns a word back (NaN for `NO_VALUE`). |
309
+ | `wordTexture(words, width, height)` | Words as a two-byte `rg8` texture read with `texelFetch`. `valueTableSize(count)` is the size of a table texture for `count` rows (rows wrap at `VALUE_TABLE_WIDTH`, 1024). |
310
+ | `colorRamp(stops, bands?)` | A colour ramp as a 256 × 1 `rgba8` texture; `bands` > 0 gives that many flat steps. `rampColor(stops, t, bands?)` is the colour at one position (for a legend). `VALUE_RAMPS` holds `viridis`, `heat`, `blues`, `diverging` and `grey`. |
311
+ | `new SurfaceRaster(cols, rows, step, base?)`, `lightHorizon(surface, toLight)`, `horizonTexture(horizon, surface)` | The light horizon of a surface, the far term of the renderer's shadow modes ([Rendering](rendering.md#shadow-modes)). The raster holds a height per square cell over the x–z plane, from `base(x, z)` and raised by `raisePolygon(rings, top)` (even-odd, cell centres inside) and `raiseDisc(x, z, radius, top)`. `lightHorizon` sweeps it once, row by row away from the light: a cell's horizon is the higher of surface and horizon one row closer to the light, lowered by what the light gains in height over that step; `-Infinity` where nothing hides the cell. The cost does not depend on the light's height. `horizonTexture` packs it as two bytes per cell (`rg8`, linear) with `baseY` and `rangeM`. |
312
+ | `new CodeStamp(region, codes, seed)` | Stamps shapes into a rectangle (`CodeRegion`) of a byte raster of class codes: `polygon(rings, code, salt)` (even-odd, so later rings cut holes) and `disc(x, z, radius, code, salt)`. A cell takes the code with a probability equal to the share of it the shape covers, decided by a hash of seed, cell and salt. Many shapes smaller than a cell therefore keep their total area, and a raster stamped rectangle by rectangle (per tile, in workers) equals one stamped at once. |
313
+
314
+ ## Content module `gen-arch`
315
+
316
+ Import from `wallhammer-web/gen-arch`. It turns structure recipes into one mesh with walls, roofs, façades, entrances, balconies, cornices and chimneys, and describes the material that draws it.
317
+
318
+ | Export | Purpose |
319
+ | --- | --- |
320
+ | `buildBuildingMesh(specs, props, groundAt, dims, options?)` | One `MeshData` (`BUILDING_LAYOUT`) for all specs. Returns `{ mesh, stats, anchored, structures, spans, interiors }`. Options: `describe` (destructible descriptions), `states` (draw in a damage state), `keepOut`, `only`, `interiors`, `byParts`. Without options the output is the plain mesh. |
321
+ | `BuildingSpec`, `FacadeRecipe`, `EntranceSpec`, `WindowRecipe`, … | The recipe the project fills in. Colours are palette rows. |
322
+ | `ArchDims` (`ArchMeshDims` and `ArchShadeDims`) | Sizes the generator and the shader take from the project. `fieldRoofMaxTriangles` (optional) is a triangle budget per `field` roof, see below. |
323
+ | `structureMaterial(dims, { damage? })`, `structureUniforms(rows)` | The `MaterialDesc` and its uniforms. The damage look is a separate program, so intact structures do not pay for it. |
324
+ | `BUILDING_VS`, `buildingFs(dims)`, `BUILDING_ATTRIBS` | Shader sources and attribute locations, for your own material. |
325
+ | `buildRubbleMesh`, `rubbleColours` | Rubble from the footprints that the destruction model returns. |
326
+ | `fallPieces`, `FALL_LAYOUT`, `FALL_ATTRIBS`, `fallingMaterial` | Falling pieces of one event, for `TransientLayer`. |
327
+ | `PART_RULE`, `*Key` functions, `describeKey` | Stable part keys of the destructible description. |
328
+ | `INTERIOR_DIM`, `ROOM_TYPE`, `cellAt`, `roomAt` | Interior plans, drawn only for damaged structures. |
329
+ | `STRUCTURE_MATERIAL(S)`, `DESTRUCT_DIM` | Destructible materials and description sizes. |
330
+ | `windowLightSlot`, `windowShare`, `DEFAULT_WINDOWS` | Environment slot for lit windows at night, in the free lanes `u_time.zw`. |
331
+
332
+ **Cost of `field` roofs.** A `field` roof (an irregular pitched roof: a plane rises from every footprint edge) is refined in rounds that halve every edge longer than 1.5 m. Without a budget a large or ragged footprint becomes very expensive: one hall of a test town came out at 396 000 triangles. With `dims.fieldRoofMaxTriangles` a round that would leave more triangles than the budget is not taken, so large roofs stop at coarser edges. Roofs that stay under the budget come out exactly as without one. The cuts where planes meet are added after the refinement, so the final roof may exceed the budget by a few per cent. The default is no budget, so existing output does not change. A whole town with 537 field roofs used a budget of 1000.
333
+
334
+ The colour shader uses `#include <snow>`. Register a slot named `snow`, for example `snowSlot()` from `gen-ground`.
335
+
336
+ ### Compositions
337
+
338
+ A building made of several masses (a long body, a tall part beside it, a small part on its roof) is several ordinary `BuildingSpec`s that share a `group` number. Each part keeps its own footprint, heights, roof and façade recipe, so damage, descriptions, interiors, the massing mesh and the project's index rules treat it like any other structure. Members of a group ignore each other only in the shared-wall test (a wall toward a member keeps its windows); entrances still avoid a member, so a door never opens into a part. A part standing on another part's roof sets `groundMin = groundRef` to the height of its foot.
339
+
340
+ Roof kinds for compositions:
341
+
342
+ | Kind | Shape |
343
+ | --- | --- |
344
+ | `apex` | Every outline edge rises to one apex above the box centre (pyramid; a tall top gives a pointed roof). |
345
+ | `dome` | The same radial roof with the `ROOF_PROFILE.dome` height profile. |
346
+ | `mansard` | A hipped ridge roof with the `ROOF_PROFILE.mansard` profile (steep low, flat high). |
347
+
348
+ `BuildingSpec.roofProfile` (a `RoofProfile`: pairs of run share and height share from `[0, 0]` to `[1, 1]`) replaces the profile of `apex`, `dome` and `mansard`, and bends a `gable` or `hip` roof; a spec without it gives the bytes it gave before. `WindowRecipe.arch` rounds the head of a window; the entrance kind `arch` is a round-headed opening whose height is `FACADE_DIM.archHeightPerWidth` times its width.
349
+
350
+ Known limits:
351
+ - A part on a roof stands on its own foundation: the engine does not carry it on the roof under it. It falls only when the project's rule says so (for example when its owner is down), not when the roof under it is breached.
352
+ - A part on a neighbouring building is carried by the group it was given, not by the building it stands on.
353
+ - Coplanar walls of two members may flicker where their faces coincide.
354
+ - `apex` and `dome` need one convex outline with its box centre inside; any other footprint falls back to a flat roof and counts in `stats.roofFallbacks`.
355
+ - Bit 7 of the second `a_win` byte (arched window) and door kinds 4–7 were the last free bits of the vertex: a further opening shape needs a layout change.
356
+
357
+ `BuildingSpec.raised` marks a member that stands on other members of its group: the footprint tests of entrances, steps, balconies and bands of the other members ignore it, so a storey that stands out over the one under it does not take away the doors and the band below. `CorniceRecipe.underside` closes a band with a bottom face (two triangles per band), so the overhang reads from below. Both are off by default and give the bytes they gave before.
358
+
359
+ ### Finishes and frames
360
+
361
+ Finishes are a code in the six free bits of the vertex byte `a_mat.z` (byte 50), drawn by the fragment program; the vertex layout is unchanged. Bits 0–1 hold the window style as before, bits 2–3 the wall finish, bits 4–5 the roof cover, bit 6 shutters. A spec that sets none of them writes the byte it wrote before.
362
+
363
+ | `WALL_FINISH` | Wall |
364
+ | --- | --- |
365
+ | `render` (0) | Plain, as before. |
366
+ | `frame` | Dark timber posts about every 1.2 m, rails at the storey lines, a diagonal brace in some fields. |
367
+ | `stone` | Courses of 0.3 m, stones about 0.55 m long with staggered joints. |
368
+ | `boards` | Upright boards of 0.18 m with dark joints. |
369
+
370
+ | `ROOF_COVER` | Pitched roof |
371
+ | --- | --- |
372
+ | `courses` (0) | As before. |
373
+ | `thatch` | Soft courses of 0.5 m, streaks down the fall line, a darker ragged eave. |
374
+ | `slate` | Small dark tiles in staggered rows. |
375
+ | `shingle` | Wooden shingles in staggered rows. |
376
+
377
+ `WindowRecipe.shutters` gives each window two leaves in the façade's accent colour. The finishes are drawn only by the shader variant `finishes: true` (`structureMaterial`, `fallingMaterial`, `buildingFs`); the default material ignores the new bits and compiles the text it compiled before.
378
+
379
+ `framed: true` draws a mesh in a frame of its own: the vertex stage multiplies by the uniform `u_frame` (the frame of the mesh into render space, set per draw), the patterns stay in the mesh's own coordinates and up is the frame's y axis. A structure is built where the generator expects it (y up, x and z in the plane) and stood on a curved body by its matrix, not by turning its vertices. Lighting, snow and fog follow the local up (`WH_LOCAL_UP`) as for any other material.
380
+
381
+ `lineRing(points, halfWidth)` (`gen-core`) is the ring round a polyline: a wall along a line is an ordinary structure over it, so it gets walls, massing and damage like any other.
382
+
383
+ Known limits:
384
+ - A breached wall along a line shows a hollow shell.
385
+ - A raised member is anchored by its own foundation.
386
+ - Structures change between the massing and the full mesh without a cross-fade.
387
+ - The massing level shows colours only, no finish.
388
+
389
+ ### Distant levels of structures
390
+
391
+ A structure that covers a few pixels does not need its full mesh. `gen-arch` has two coarser levels, both made per tile:
392
+
393
+ | Level | Export | What it gives |
394
+ | --- | --- | --- |
395
+ | Middle | `buildMassingMesh(specs, dims, { only?, origin? })` | One indexed mesh (`MASSING_LAYOUT`, 28 bytes per vertex) with a prism per structure: walls from below the ground to the roof, the top flat (the roof surface of a flat roof, halfway up a pitched one), holes of the footprint kept. About 3 triangles per footprint point. Returns `{ mesh, spans, minY, maxY, structures }`. With `origin` the positions are relative to that point (a tile origin); draw with `u_cellOffset` = origin − render origin. |
396
+ | Middle | `massingMaterial(dims)` | The material: light, shadow, fog, wetness and snow as the full one, and the means of what the full shader draws (wall tint with the glazed share, mean glow of lit windows, roof covering). Uniforms `u_rows` (`structureUniforms`), `u_fade`, `u_cellOffset`. |
397
+ | Far | `stampFootprints(stamp, specs, codeOf, only?)` | Nothing to draw: the footprints go into a ground class raster through a `CodeStamp` (`gen-tex`), each with the class code `codeOf` gives it, and the ground bake paints them like any other class. |
398
+ | Far | `roofTones(color, albedoScale?)` | Three tones of a roof covering for such a class (the span of the per-structure tint of the full shader). |
399
+
400
+ The vertices of a structure are consecutive in the massing mesh (`spans`), and a structure built alone has exactly the bytes of its span. Hide one by writing zeros over its span, show it again by writing the bytes of `buildMassingMesh([spec], dims)`.
401
+
402
+ ```ts
403
+ import { buildMassingMesh, massingMaterial, roofTones, stampFootprints } from 'wallhammer-web/gen-arch';
404
+ import type { ArchDims, BuildingSpec } from 'wallhammer-web/gen-arch';
405
+ import { CodeStamp } from 'wallhammer-web/gen-tex';
406
+
407
+ declare const specs: BuildingSpec[]; // the structures of one tile
408
+ declare const dims: ArchDims;
409
+ declare const tileOrigin: [number, number, number];
410
+ declare const tileCodes: Uint8Array; // the tile's part of the ground class raster: 64 × 64 cells of 5 m
411
+
412
+ // Middle level: one mesh for the tile, positions relative to the tile origin.
413
+ const massing = buildMassingMesh(specs, dims, { origin: tileOrigin });
414
+ const material = massingMaterial(dims);
415
+
416
+ // Far level: the footprints as class 40 in the tile's rectangle of the raster, and the look of that class.
417
+ const stamp = new CodeStamp({ col0: 128, row0: 64, cols: 64, rows: 64, step: 5 }, tileCodes, 1234);
418
+ const stamped = stampFootprints(stamp, specs, () => 40);
419
+ const look = { colors: roofTones([0.5, 0.3, 0.24], 0.84), patchM: 14, grain: 0.25 };
420
+ ```
421
+
422
+ Which level is drawn, and the transition between two of them, is `LevelFade` with the screen-door fade: [Levels of detail with a fade](rendering.md#levels-of-detail-with-a-fade). The massing material already contains the fade; wrap the full structure material with `withFade`. The full material casts its shadow with the plain depth program, so its shadow does not thin out during a transition; the massing shadow does.
423
+
424
+ [Destruction](destruction.md) covers descriptions, damage and falling pieces.
425
+
426
+ Known weaknesses (from the project's own status notes): interiors divide every storey the same way; rooms are empty and dark by day; narrow rooms appear in irregular footprints.
427
+
428
+ ## Content module `gen-ground`
429
+
430
+ Import from `wallhammer-web/gen-ground`. Ground and markings.
431
+
432
+ | Export | Purpose |
433
+ | --- | --- |
434
+ | `groundBake`, `buildOcclusionMask` | A `BakeDesc` that bakes ground colour and surface kind from a class raster; `renderer.bake` runs it. |
435
+ | `buildGroundMarkings` | Painted strips draped on the terrain. |
436
+ | `TERRAIN_MATERIAL`, `MARKING_MATERIAL`, `groundUniforms` | Materials and their uniforms. |
437
+ | `seasonSlot`, `seasonAt` | Environment slot: season in `u_season` (also a shadow key), read by the terrain and the vegetation shader. |
438
+ | `snowSlot` | Environment slot: the `snow` include. |
439
+ | `TERRAIN_VS/FS`, `MARKING_VS/FS` | Shader sources. |
440
+
441
+ The module holds no colour names and no project sizes.
442
+
443
+ ## Content module `gen-vegetation`
444
+
445
+ Import from `wallhammer-web/gen-vegetation`. Vegetation and its placement.
446
+
447
+ | Export | Purpose |
448
+ | --- | --- |
449
+ | `plantTrees` | Deterministic placement from a canopy raster and placement rules. |
450
+ | `buildTreeBatches`, `buildTreeBatch`, `packTreeInstances`, `treeBatchUniforms` | Instanced vegetation with levels of detail, for `InstancedLayer`. |
451
+ | `VEGETATION_MATERIAL`, `vegetationUniforms`, `vegetationSieve` | Material and its uniforms. |
452
+ | `swaySlot`, `maxSway` | Environment slot: sway in `u_wind.zw`. |
453
+ | `TREE_VS/FS`, `DEPTH_TREE_VS/FS` | Shader sources. |
454
+
455
+ The vegetation shader reads the season slot and includes `<snow>`, both from `gen-ground`: register `seasonSlot`, `snowSlot` (from `gen-ground`) and `swaySlot` together. The module holds no colour names and no project sizes.
456
+
457
+ ## `gen-plan`: the plan of a sphere
458
+
459
+ Import from `wallhammer-web/gen-plan`. A coarse plan over a whole sphere, made once before any cell is generated, so that a cell can ask what passes through it without knowing its neighbours. The module names nothing; the code that uses it gives the lines and hollows their meaning.
460
+
461
+ - **Grid.** `sphereGrid(radiusM, level)` is one node at the middle of every cell of one level of the cube sphere (`6 · 4^level` nodes, node = `face · n² + y · n + x`). `gridNeighbours` gives the up to eight neighbours, across the seams of the faces too (a corner of the cube has seven). `gridNodeAt` finds the node of a direction, `gridDirection` the direction of a node, `gridNodeArea` its area in m², and `gridSample` reads a field of one value per node bilinearly at any direction. `gridWeights` gives the nodes and weights behind that read (three at a corner of the cube, else four, summing to 1), so a caller can blend a share of its own, for example the part of a point that belongs to one region of nodes; the sum of weight times value in their order is `gridSample` bit for bit.
462
+ - **Drainage.** `drainGrid(grid, heights, options)` fills every hollow to its sill (a priority flood from the base nodes, the nodes at or under `baseLevel`) and returns per node the filled height, the node it drains to, an order in which every node comes before the one it drains to, the gathered flow and the pool it lies in. A filled hollow counts as a pool from `minPoolNodes` nodes and `minPoolDepth` depth on. `traceChannels(grid, drainage, { minFlow })` cuts the nodes with enough flow into chains; each ends in a base node, a pool or another chain.
463
+ - **Lines.** `smoothLine(points, rounds)` smooths a line of unit directions and keeps its ends; `fallingGrade(heights, minDrop)` makes a profile that never rises along it.
464
+ - **Index.** `lineTiles({ level, radiusM, start, points, reachM })` lists per tile (a cell of `level`) every line that comes within its reach of it. `tileLinesAt` reads the lines of the tile at a direction, `tileLinesOfCell` those of any cell, finer or coarser than the tiles. A tile may list a line that does not reach it; it never misses one that does.
465
+
466
+ The results are typed arrays only, so a plan can go into a worker or a file as it is. The same inputs give the same bits.
467
+
468
+ ```ts
469
+ import { drainGrid, gridDirection, lineTiles, smoothLine, sphereGrid, tileLinesAt, traceChannels } from 'wallhammer-web/gen-plan';
470
+
471
+ const grid = sphereGrid(1_000_000, 5);
472
+ const heights = new Float32Array(grid.count);
473
+ for (let i = 0; i < grid.count; i++) {
474
+ const [x, y, z] = gridDirection(grid, i);
475
+ heights[i] = 400 * Math.sin(5 * x) * Math.cos(4 * y) + 300 * z;
476
+ }
477
+ const drainage = drainGrid(grid, heights, { baseLevel: 0, minPoolNodes: 4, minPoolDepth: 5 });
478
+ const channels = traceChannels(grid, drainage, { minFlow: 30 });
479
+
480
+ // One line per channel: the directions of its nodes, smoothed.
481
+ const start = new Uint32Array(channels.start.length);
482
+ const parts: Float64Array[] = [];
483
+ for (let c = 0; c + 1 < channels.start.length; c++) {
484
+ const from = channels.start[c]!;
485
+ const to = channels.start[c + 1]!;
486
+ const raw = new Float64Array(3 * (to - from));
487
+ for (let k = from; k < to; k++) raw.set(gridDirection(grid, channels.nodes[k]!), 3 * (k - from));
488
+ parts.push(smoothLine(raw, 4));
489
+ start[c + 1] = start[c]! + (to - from);
490
+ }
491
+ const points = new Float64Array(3 * start[start.length - 1]!);
492
+ parts.forEach((p, c) => points.set(p, 3 * start[c]!));
493
+ const reachM = new Float64Array(parts.length).fill(2_000);
494
+ const tiles = lineTiles({ level: 4, radiusM: grid.radiusM, start, points, reachM });
495
+ const here = tileLinesAt(tiles, 0, 0, 1); // { from, to } in tiles.lines, or null
496
+ ```
497
+
498
+ Choosing places and dividing them:
499
+
500
+ - **Steps and slope.** `gridSteps(grid, marks, maxSteps)` gives per node the steps over the eight neighbours to the nearest marked node, capped at `maxSteps` (at most 255). `gridSlopeAt(grid, heights, unitM, node)` is the steepest rise from a node to a neighbour, per metre of chord.
501
+ - **Picking.** `pickSites(grid, score, { count, spacingM, minScore, taken, accept })` takes nodes from the highest score down (ties: the lower node), skips any nearer than `spacingM` in a straight line to one already picked or `taken`, and asks `accept` only for a node that passed that; it stops at `count` or below `minScore`. The result is in the order of the picks.
502
+ - **Plots.** `plotsAlong(lines, { frontM, depthM, setbackM, gapM, seed, blocked })` walks both sides of each line (x z pairs in a plane, metres) and puts rectangles squared to it, `setbackM` from every line, `gapM` apart, sizes from the seed. `blocked(x, z)` refuses a plot whose middle or a corner it holds. Each plot carries its middle, the unit vector toward its line, its size and the line.
503
+
504
+ ```ts
505
+ import { gridSlopeAt, gridSteps, pickSites, plotsAlong, sphereGrid } from 'wallhammer-web/gen-plan';
506
+
507
+ const g = sphereGrid(1_000_000, 4);
508
+ const heights = new Float32Array(g.count).map((_, i) => (i * 37) % 500);
509
+ const low = Uint8Array.from(heights, (h) => (h < 50 ? 1 : 0));
510
+ const steps = gridSteps(g, low, 6);
511
+ const score = Float32Array.from(heights, (h, i) => (h < 50 ? 0 : (1 / (1 + steps[i]!)) * (1 - Math.min(1, gridSlopeAt(g, heights, 1, i)))));
512
+ const picked = pickSites(g, score, { count: 10, spacingM: 50_000, minScore: 0.05, accept: (node) => heights[node]! < 400 });
513
+
514
+ const plots = plotsAlong([[0, 0, 200, 0, 200, 150]], { frontM: [12, 20], depthM: [20, 30], setbackM: 4, gapM: 1, seed: 7, blocked: (x, z) => x * x + z * z < 400 });
515
+ ```
516
+
517
+ Joining places by ways:
518
+
519
+ - **Least cost.** A `StepCost` `(a, b) => number` prices the step from a node to its neighbour: finite and above 0, or `Infinity` for a closed step. `routeGrid(grid, { from, to, cost, maxNodes, scratch })` returns the nodes of the cheapest chain of steps, both ends included, or null when `to` cannot be reached or `maxNodes` nodes were settled first. It has no estimate of the rest of the way, so it is exact for any cost; `routeScratch(grid)` makes arrays it reuses between calls (a stamp per call, no clearing). Ties go by cost, then source, then node index, neighbours in the order of `gridNeighbours`; a predecessor changes only for a strictly lower cost.
520
+ - **Regions.** `routeRegions(grid, { sources, cost, maxNodes })` is one search from many nodes at once: per node the index of the source that reaches it most cheaply (`owner`, −1 none), that cost and the node it came from (`prev`, −1 at a source). `regionLinks(grid, regions, cost)` gives per pair of sources whose regions touch (a < b, sorted) the cheapest step between them, `regions.cost[nodeA] + cost(nodeA, nodeB) + regions.cost[nodeB]`: which places are near each other by the cost of getting there, from one pass.
521
+ - **Along a line.** `lineLengths(points, radiusM)` gives the metres along great arcs up to each point of a line of unit directions; `lineAt(points, lengths, alongM, out)` the direction and the unit heading there; `limitGrade(lengths, heights, maxGrade)` changes a profile as little as the rule allows so that no step is steeper than `maxGrade`, keeping both ends (a profile within the limit comes back unchanged; ends that break it give the straight ramp between them).
522
+
523
+ ```ts
524
+ import { gridDirection, limitGrade, lineAt, lineLengths, regionLinks, routeGrid, routeRegions, routeScratch, sphereGrid } from 'wallhammer-web/gen-plan';
525
+ import type { Vec3 } from 'wallhammer-web/base';
526
+
527
+ const g = sphereGrid(1_000_000, 4);
528
+ const h = new Float32Array(g.count).map((_, i) => (i * 53) % 300);
529
+ const pos: Vec3 = [0, 0, 0];
530
+ const at: Vec3 = [0, 0, 0];
531
+ const cost = (a: number, b: number): number => {
532
+ gridDirection(g, a, pos);
533
+ gridDirection(g, b, at);
534
+ const m = Math.hypot(at[0] - pos[0], at[1] - pos[1], at[2] - pos[2]) * g.radiusM;
535
+ const slope = Math.abs(h[b]! - h[a]!) / m;
536
+ return slope > 0.3 ? Infinity : m * (1 + slope * 10);
537
+ };
538
+ const way = routeGrid(g, { from: 10, to: 900, cost, maxNodes: g.count, scratch: routeScratch(g) });
539
+ const regions = routeRegions(g, { sources: [10, 900, 5000], cost, maxNodes: g.count });
540
+ const links = regionLinks(g, regions, cost); // links.a[i], links.b[i], links.cost[i]
541
+
542
+ if (way) {
543
+ const pts = new Float64Array(3 * way.length);
544
+ way.forEach((n, k) => pts.set(gridDirection(g, n), 3 * k));
545
+ const lengths = lineLengths(pts, g.radiusM);
546
+ const profile = limitGrade(lengths, Array.from(way, (n) => h[n]!), 0.1);
547
+ const out = { dir: [0, 0, 0] as Vec3, heading: [0, 0, 0] as Vec3 };
548
+ lineAt(pts, lengths, lengths[lengths.length - 1]! / 2, out);
549
+ console.log(profile.length, out.dir, out.heading);
550
+ }
551
+ ```
552
+
553
+ - **Skyline.** `gridHorizon(grid, heights, unitM, x, y, z, options, out)` writes the sine of the skyline's elevation, seen from the field's own height at a direction, toward each of the four `HORIZON_AXES` (a tetrahedron in the grid's axes, laid into the tangent plane there): samples along each direction up to `reachM`, closer near the point, never under 0, heights under `floorM` counted as `floorM`. A code is one byte per direction, `horizonCode(sine)` = `round(255 · sqrt(sine))`. `horizonField(grid, heights, unitM, options)` computes node codes on first use into a table of `slots` entries (65 536 by default; it only saves time), and `horizonCodeAt(field, x, y, z, out)` blends the codes of the nodes round a direction with the weights of `gridSample`, so any caller gets the same four bytes for a point. `horizonLit(code, up, toLight, soft)` turns a code into 0 (hidden) … 1 (lit) for a light far away; `HORIZON_GLSL` is the same function for a shader, with the code read from a normalized u8 attribute. Carry the code to the GPU as the sphere patch's extra channel (`extraAt`, [Streaming](streaming.md)).
554
+
555
+ ```ts
556
+ import { horizonCodeAt, horizonField, horizonLit, sphereGrid } from 'wallhammer-web/gen-plan';
557
+
558
+ const g = sphereGrid(100_000, 6);
559
+ const h = new Float32Array(g.count).map((_, i) => (i * 37) % 2000);
560
+ const field = horizonField(g, h, 1, { reachM: 20_000, steps: 32, floorM: 0 });
561
+ const code = new Uint8Array(4);
562
+ horizonCodeAt(field, 0, 0.6, 0.8, code);
563
+ const lit = horizonLit(code, [0, 0.6, 0.8], [0.6, 0, 0.8], 0.02);
564
+ console.log(code, lit);
565
+ ```
566
+
567
+ ## Rules for a new generator
568
+
569
+ 1. Output plain data from `base`. No GPU, no DOM.
570
+ 2. Take a seed and derive randomness with `hashInts` over **input** keys.
571
+ 3. No `Math.random`, no `Date`, no `performance.now`. Not checked outside `sim`, so review it.
572
+ 4. Put a generic generator in `gen-mesh` or `gen-tex` (no use-case words). Put a content generator in `gen-arch`, `gen-ground` or `gen-vegetation`. Content of one project (people, vehicles, street furniture) stays in the app.
573
+ 5. Add a golden recipe ([Tools](tools.md#golden-hashes)).
574
+
575
+ [Recipes](recipes.md#add-a-generator) has a worked example.