threedog 0.2.1 → 0.7.0

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 (725) hide show
  1. package/CHANGELOG.md +371 -1
  2. package/README.md +21 -12
  3. package/core/Animator.js +15 -12
  4. package/core/Assets.js +92 -26
  5. package/core/Audio.js +45 -38
  6. package/core/Baked.js +30 -15
  7. package/core/Batching.js +102 -15
  8. package/core/Budget.js +40 -19
  9. package/core/Clock.js +40 -80
  10. package/core/DebugOverrides.js +75 -25
  11. package/core/Describe.js +105 -45
  12. package/core/Engine.js +203 -75
  13. package/core/Events.js +4 -1
  14. package/core/I18n.js +25 -13
  15. package/core/Input.js +175 -80
  16. package/core/Inspect.js +8 -5
  17. package/core/InspectMaterials.js +84 -0
  18. package/core/InspectPerf.js +68 -0
  19. package/core/InspectScene.js +13 -2
  20. package/core/Loading.js +2 -1
  21. package/core/MaterialInfo.js +7 -5
  22. package/core/Ops.js +50 -9
  23. package/core/Random.js +9 -2
  24. package/core/Rays.js +12 -7
  25. package/core/SaveStore.js +41 -9
  26. package/core/Saves.js +71 -15
  27. package/core/Stream.js +13 -10
  28. package/core/Threads.js +26 -7
  29. package/core/UrlState.js +69 -13
  30. package/core/Views.js +10 -6
  31. package/core/actor.js +1 -1
  32. package/core/adaptive.js +93 -0
  33. package/core/assetEntry.js +27 -7
  34. package/core/assetHot.js +176 -0
  35. package/core/assetLoad.js +44 -19
  36. package/core/assetManifest.js +53 -11
  37. package/core/assetReport.js +5 -5
  38. package/core/audioRules.js +13 -11
  39. package/core/audioVoice.js +69 -42
  40. package/core/batchGroups.js +9 -1
  41. package/core/canvasBox.js +1 -2
  42. package/core/catalog.js +21 -5
  43. package/core/cells.js +62 -0
  44. package/core/checks.js +10 -8
  45. package/core/chunkStream.js +87 -0
  46. package/core/control.js +149 -0
  47. package/core/copies.js +32 -0
  48. package/core/dayTime.js +12 -6
  49. package/core/debugView.js +85 -18
  50. package/core/describeRender.js +117 -21
  51. package/core/describeText.js +41 -21
  52. package/core/engineCamera.js +32 -0
  53. package/core/errorCodes.js +478 -32
  54. package/core/errorHints.js +41 -142
  55. package/core/errors.js +31 -8
  56. package/core/events.generated.js +13 -7
  57. package/core/gameLights.js +69 -0
  58. package/core/grayMap.js +20 -0
  59. package/core/grid.js +14 -13
  60. package/core/gridLoad.js +2 -1
  61. package/core/ground.js +6 -4
  62. package/core/headlessLoad.js +55 -0
  63. package/core/holds.js +78 -50
  64. package/core/inputContext.js +11 -7
  65. package/core/inputDefaults.js +24 -21
  66. package/core/inputPad.js +1 -1
  67. package/core/inputPointer.js +1 -1
  68. package/core/inputTouch.js +2 -2
  69. package/core/lifecycle.js +46 -12
  70. package/core/lightWatch.js +9 -5
  71. package/core/loop.js +109 -43
  72. package/core/math.js +18 -3
  73. package/core/moduleSlots.js +100 -0
  74. package/core/moduleTypes.js +86 -0
  75. package/core/modules.js +147 -29
  76. package/core/movement.js +2 -2
  77. package/core/namedModel.js +74 -0
  78. package/core/opsCheck.js +3 -3
  79. package/core/opsFail.js +15 -6
  80. package/core/opsGuard.js +4 -4
  81. package/core/opsRun.js +4 -3
  82. package/core/owned.js +171 -0
  83. package/core/page.js +44 -10
  84. package/core/params.js +30 -8
  85. package/core/pictureSlots.js +33 -0
  86. package/core/pictureWriters.js +343 -0
  87. package/core/plugins.js +245 -0
  88. package/core/saveApply.js +99 -17
  89. package/core/saveFiles.js +8 -6
  90. package/core/saveValues.js +46 -0
  91. package/core/saveVersions.js +20 -3
  92. package/core/scatter.js +48 -19
  93. package/core/sceneDelta.js +211 -0
  94. package/core/sceneMethods.js +31 -33
  95. package/core/screenToGround.js +1 -1
  96. package/core/services.js +27 -11
  97. package/core/session.js +28 -25
  98. package/core/shaderCost.js +78 -0
  99. package/core/shadowTypes.js +3 -2
  100. package/core/shadows.js +405 -0
  101. package/core/sharedPoint.js +303 -0
  102. package/core/skip.js +36 -28
  103. package/core/stackFrames.js +45 -0
  104. package/core/stacks.js +166 -0
  105. package/core/startup.js +153 -13
  106. package/core/streamSources.js +0 -11
  107. package/core/targeting.js +1 -1
  108. package/core/textureBytes.js +20 -0
  109. package/core/thingExplain.js +3 -3
  110. package/core/thingOps.js +29 -6
  111. package/core/things.js +22 -12
  112. package/core/threadPure.js +7 -3
  113. package/core/threePatches.js +47 -0
  114. package/core/tier.js +21 -10
  115. package/core/time.js +236 -0
  116. package/core/uiClock.js +25 -0
  117. package/core/util.js +8 -2
  118. package/core/validate.js +66 -87
  119. package/core/view.js +43 -0
  120. package/core/wrap.js +106 -0
  121. package/docs/AI.md +95 -104
  122. package/docs/API.md +35 -31
  123. package/docs/CODEMAP.md +231 -176
  124. package/docs/COMMANDS.md +63 -39
  125. package/docs/CONVENTIONS.md +99 -31
  126. package/docs/MIGRATING-0.3.md +248 -0
  127. package/docs/MIGRATING-0.4.md +320 -0
  128. package/docs/MIGRATING-0.5.md +68 -0
  129. package/docs/MIGRATING-0.6.md +126 -0
  130. package/docs/MIGRATING-0.7.md +39 -0
  131. package/docs/PERF.md +35 -7
  132. package/docs/THREE.md +82 -28
  133. package/docs/api/ambience.md +0 -1
  134. package/docs/api/assets.md +15 -11
  135. package/docs/api/audio.md +10 -14
  136. package/docs/api/budget.md +4 -0
  137. package/docs/api/calendar.md +41 -0
  138. package/docs/api/cameraRig.md +16 -5
  139. package/docs/api/characters.md +41 -24
  140. package/docs/api/clock.md +6 -5
  141. package/docs/api/collision.md +10 -7
  142. package/docs/api/content.md +6 -4
  143. package/docs/api/dialogue.md +9 -9
  144. package/docs/api/engine.md +95 -65
  145. package/docs/api/events.md +20 -14
  146. package/docs/api/grids.md +10 -3
  147. package/docs/api/ground.md +1 -1
  148. package/docs/api/hud.md +5 -2
  149. package/docs/api/i18n.md +1 -1
  150. package/docs/api/input.md +13 -7
  151. package/docs/api/interactions.md +10 -6
  152. package/docs/api/inventory.md +17 -17
  153. package/docs/api/level.md +0 -2
  154. package/docs/api/lightPool.md +3 -1
  155. package/docs/api/music.md +1 -1
  156. package/docs/api/nav.md +3 -0
  157. package/docs/api/occlusion.md +5 -0
  158. package/docs/api/openWorld.md +2 -1
  159. package/docs/api/particles.md +6 -3
  160. package/docs/api/photo.md +0 -2
  161. package/docs/api/pickups.md +21 -0
  162. package/docs/api/post.md +8 -5
  163. package/docs/api/quests.md +2 -3
  164. package/docs/api/rigid.md +16 -14
  165. package/docs/api/saves.md +6 -4
  166. package/docs/api/settings.md +2 -3
  167. package/docs/api/sky.md +18 -49
  168. package/docs/api/stream.md +1 -1
  169. package/docs/api/terrain.md +16 -7
  170. package/docs/api/terrainDraw.md +12 -0
  171. package/docs/api/timeline.md +3 -4
  172. package/docs/api/tools.md +32 -15
  173. package/docs/api/triggers.md +7 -10
  174. package/docs/api/vegetation.md +17 -9
  175. package/docs/api/vegetationDraw.md +10 -0
  176. package/docs/api/water.md +9 -21
  177. package/docs/api/weather.md +10 -15
  178. package/docs/api/weatherDraw.md +10 -0
  179. package/docs/api/world.md +3 -2
  180. package/docs/recipes/01-new-game.md +52 -42
  181. package/docs/recipes/02-npc.md +24 -7
  182. package/docs/recipes/03-items-pickups.md +57 -22
  183. package/docs/recipes/04-quests.md +12 -5
  184. package/docs/recipes/05-props-bake.md +174 -22
  185. package/docs/recipes/06-clock-events.md +100 -52
  186. package/docs/recipes/07-flow-scenes-pause.md +50 -10
  187. package/docs/recipes/08-weather-sky.md +134 -37
  188. package/docs/recipes/09-materials-lights-models.md +185 -0
  189. package/docs/recipes/10-blender-level.md +16 -4
  190. package/docs/recipes/11-vehicles.md +67 -10
  191. package/docs/recipes/13-animation.md +23 -9
  192. package/docs/recipes/14-custom-module.md +63 -29
  193. package/docs/recipes/15-perf.md +31 -10
  194. package/docs/recipes/16-dev-bridge.md +74 -40
  195. package/docs/recipes/18-world.md +26 -14
  196. package/docs/recipes/19-shooting-picking.md +12 -10
  197. package/docs/recipes/20-content-actions-save.md +60 -18
  198. package/docs/recipes/21-camera.md +55 -17
  199. package/docs/recipes/22-shop-gold.md +3 -3
  200. package/docs/recipes/23-ops.md +17 -11
  201. package/docs/recipes/26-ui-parts.md +86 -13
  202. package/docs/recipes/27-net.md +11 -5
  203. package/docs/recipes/28-terrain.md +36 -3
  204. package/docs/recipes/29-grid.md +46 -19
  205. package/docs/recipes/30-templates.md +72 -15
  206. package/docs/recipes/31-audio.md +20 -12
  207. package/docs/recipes/32-action-game.md +51 -4
  208. package/docs/recipes/34-environment-lighting.md +108 -21
  209. package/docs/recipes/35-picture-from-reference.md +147 -0
  210. package/docs/recipes/36-sky-ground-plants.md +158 -0
  211. package/docs/recipes/{37-terrain-look-hooks.md → 37-terrain-hooks.md} +9 -12
  212. package/docs/recipes/38-environment-hooks.md +67 -0
  213. package/docs/recipes/40-scene.md +114 -32
  214. package/docs/recipes/42-terrain-shape.md +2 -2
  215. package/docs/recipes/43-shader-patches-surfaces.md +206 -0
  216. package/docs/recipes/44-water-weather-hooks.md +191 -0
  217. package/docs/recipes/45-cascaded-shadows.md +130 -23
  218. package/docs/recipes/46-blender-art-route.md +17 -20
  219. package/docs/recipes/47-island-snow-backdrop.md +13 -15
  220. package/docs/recipes/49-game-module-contract.md +30 -17
  221. package/docs/recipes/50-own-renderer.md +4 -4
  222. package/docs/recipes/51-capability-catalog.md +3 -3
  223. package/docs/recipes/52-around-the-picture.md +181 -0
  224. package/docs/recipes/53-ground-up-close.md +12 -12
  225. package/docs/recipes/54-three-idioms.md +88 -0
  226. package/docs/recipes/55-mods-time-wrap.md +124 -0
  227. package/docs/recipes/56-webgpu-tsl.md +303 -0
  228. package/docs/recipes/57-control.md +104 -0
  229. package/docs/recipes/58-input.md +60 -0
  230. package/docs/recipes/59-depth-post-effects.md +83 -0
  231. package/docs/recipes/60-judge-the-picture.md +70 -0
  232. package/docs/recipes/61-deploy.md +27 -0
  233. package/docs/recipes/62-picture-code.md +244 -0
  234. package/docs/recipes/63-third-person-start.md +77 -0
  235. package/docs/recipes/64-particles.md +35 -0
  236. package/examples/action/.threedog/content-index.json +1 -0
  237. package/examples/action/GAMEMAP.md +20 -14
  238. package/examples/action/assets.js +8 -0
  239. package/examples/action/content/actions.js +1 -1
  240. package/examples/action/content/audio.js +5 -5
  241. package/examples/action/main.js +12 -15
  242. package/examples/action/models.js +23 -24
  243. package/examples/action/picture/index.js +13 -0
  244. package/examples/action/picture/lights.js +35 -0
  245. package/examples/action/picture/materials.js +8 -0
  246. package/examples/action/picture/palette.js +33 -0
  247. package/examples/plain-picture/.threedog/content-index.json +1 -0
  248. package/examples/plain-picture/FINDINGS.md +53 -0
  249. package/examples/plain-picture/GAMEMAP.md +90 -0
  250. package/examples/plain-picture/main.js +48 -0
  251. package/examples/plain-picture/picture/index.js +21 -0
  252. package/examples/plain-picture/picture/lights.js +54 -0
  253. package/examples/plain-picture/picture/materials.js +24 -0
  254. package/examples/plain-picture/picture/palette.js +16 -0
  255. package/examples/plain-picture/picture/sky.js +37 -0
  256. package/examples/pullable.json +133 -0
  257. package/examples/rc2d/.threedog/content-index.json +1 -0
  258. package/examples/rc2d/GAMEMAP.md +88 -0
  259. package/examples/rc2d/README.md +57 -0
  260. package/examples/rc2d/main.js +55 -0
  261. package/examples/rc2d/picture/index.js +18 -0
  262. package/examples/rc2d/picture/lights.js +11 -0
  263. package/examples/rc2d/picture/materials.js +18 -0
  264. package/examples/rc2d/picture/palette.js +15 -0
  265. package/examples/rc2d/picture/post.js +11 -0
  266. package/examples/rc2d/rc2d.js +187 -0
  267. package/examples/rc2d/shaders.js +144 -0
  268. package/examples/sheepisland/.threedog/content-index.json +1 -0
  269. package/examples/sheepisland/GAMEMAP.md +22 -17
  270. package/examples/sheepisland/assets.js +5 -0
  271. package/examples/sheepisland/content/templates.js +1 -1
  272. package/examples/sheepisland/content/vegetation.js +3 -1
  273. package/examples/sheepisland/main.js +29 -18
  274. package/examples/sheepisland/{style/models.js → models.js} +13 -24
  275. package/examples/sheepisland/picture/index.js +20 -0
  276. package/examples/sheepisland/picture/lights.js +34 -0
  277. package/examples/sheepisland/picture/materials.js +61 -0
  278. package/examples/sheepisland/picture/palette.js +60 -0
  279. package/examples/sheepisland/picture/sky.js +20 -0
  280. package/examples/sheepisland/views.js +1 -1
  281. package/examples/styletest/.threedog/content-index.json +1 -0
  282. package/examples/styletest/GAMEMAP.md +25 -22
  283. package/examples/styletest/assets.js +6 -0
  284. package/examples/styletest/content/templates.js +1 -1
  285. package/examples/styletest/content/vegetation.js +1 -1
  286. package/examples/styletest/main.js +25 -34
  287. package/examples/styletest/models.js +30 -30
  288. package/examples/styletest/params.js +2 -5
  289. package/examples/styletest/picture/env.js +38 -0
  290. package/examples/styletest/picture/index.js +16 -0
  291. package/examples/styletest/picture/lights.js +9 -0
  292. package/examples/styletest/picture/materials.js +28 -0
  293. package/examples/styletest/picture/palette.js +22 -0
  294. package/examples/techniques/contact-shadows/README.md +91 -0
  295. package/examples/techniques/contact-shadows/contactShadows.js +67 -0
  296. package/examples/techniques/contact-shadows/main.js +55 -0
  297. package/examples/techniques/contact-shadows/picture/index.js +14 -0
  298. package/examples/techniques/contact-shadows/picture/lights.js +34 -0
  299. package/examples/techniques/contact-shadows/picture/materials.js +12 -0
  300. package/examples/techniques/contact-shadows/picture/palette.js +17 -0
  301. package/examples/techniques/day-night-grade/README.md +83 -0
  302. package/examples/techniques/day-night-grade/main.js +41 -0
  303. package/examples/techniques/day-night-grade/picture/index.js +20 -0
  304. package/examples/techniques/day-night-grade/picture/lights.js +45 -0
  305. package/examples/techniques/day-night-grade/picture/materials.js +15 -0
  306. package/examples/techniques/day-night-grade/picture/palette.js +59 -0
  307. package/examples/techniques/day-night-grade/picture/post.js +25 -0
  308. package/examples/techniques/day-night-grade/picture/sky.js +33 -0
  309. package/examples/techniques/interior-light/README.md +106 -0
  310. package/examples/techniques/interior-light/interiorLight.js +47 -0
  311. package/examples/techniques/interior-light/main.js +87 -0
  312. package/examples/techniques/interior-light/picture/index.js +24 -0
  313. package/examples/techniques/interior-light/picture/lights.js +52 -0
  314. package/examples/techniques/interior-light/picture/materials.js +13 -0
  315. package/examples/techniques/interior-light/picture/palette.js +32 -0
  316. package/examples/techniques/interior-light/picture/sky.js +40 -0
  317. package/examples/techniques/modular-building/README.md +126 -0
  318. package/examples/techniques/modular-building/kit.js +426 -0
  319. package/examples/techniques/modular-building/main.js +39 -0
  320. package/examples/techniques/modular-building/picture/index.js +17 -0
  321. package/examples/techniques/modular-building/picture/lights.js +26 -0
  322. package/examples/techniques/modular-building/picture/materials.js +13 -0
  323. package/examples/techniques/modular-building/picture/palette.js +23 -0
  324. package/examples/techniques/night-lights/README.md +95 -0
  325. package/examples/techniques/night-lights/main.js +47 -0
  326. package/examples/techniques/night-lights/nightLights.js +95 -0
  327. package/examples/techniques/night-lights/picture/index.js +18 -0
  328. package/examples/techniques/night-lights/picture/lights.js +44 -0
  329. package/examples/techniques/night-lights/picture/materials.js +15 -0
  330. package/examples/techniques/night-lights/picture/palette.js +34 -0
  331. package/examples/techniques/night-lights/picture/post.js +9 -0
  332. package/examples/techniques/night-lights/picture/sky.js +36 -0
  333. package/examples/techniques/outlines-and-rim/README.md +59 -0
  334. package/examples/techniques/outlines-and-rim/main.js +61 -0
  335. package/examples/techniques/outlines-and-rim/outlines.js +64 -0
  336. package/examples/techniques/outlines-and-rim/picture/index.js +16 -0
  337. package/examples/techniques/outlines-and-rim/picture/lights.js +18 -0
  338. package/examples/techniques/outlines-and-rim/picture/materials.js +11 -0
  339. package/examples/techniques/outlines-and-rim/picture/palette.js +16 -0
  340. package/examples/techniques/outlines-and-rim/picture/post.js +10 -0
  341. package/examples/techniques/procedural-animation/README.md +79 -0
  342. package/examples/techniques/procedural-animation/creature.js +44 -0
  343. package/examples/techniques/procedural-animation/main.js +47 -0
  344. package/examples/techniques/procedural-animation/picture/index.js +15 -0
  345. package/examples/techniques/procedural-animation/picture/lights.js +35 -0
  346. package/examples/techniques/procedural-animation/picture/materials.js +10 -0
  347. package/examples/techniques/procedural-animation/picture/palette.js +16 -0
  348. package/examples/techniques/procedural-animation/picture/sky.js +31 -0
  349. package/examples/techniques/procedural-animation/proceduralAnim.js +118 -0
  350. package/examples/techniques/procedural-surface/README.md +69 -0
  351. package/examples/techniques/procedural-surface/main.js +65 -0
  352. package/examples/techniques/procedural-surface/picture/index.js +14 -0
  353. package/examples/techniques/procedural-surface/picture/lights.js +18 -0
  354. package/examples/techniques/procedural-surface/picture/materials.js +34 -0
  355. package/examples/techniques/procedural-surface/picture/palette.js +15 -0
  356. package/examples/techniques/procedural-surface/surface.js +120 -0
  357. package/examples/techniques/stylized-shading/README.md +74 -0
  358. package/examples/techniques/stylized-shading/main.js +62 -0
  359. package/examples/techniques/stylized-shading/picture/index.js +14 -0
  360. package/examples/techniques/stylized-shading/picture/lights.js +23 -0
  361. package/examples/techniques/stylized-shading/picture/materials.js +18 -0
  362. package/examples/techniques/stylized-shading/picture/palette.js +19 -0
  363. package/examples/techniques/stylized-shading/shading.js +131 -0
  364. package/examples/techniques/sun-and-key-light/README.md +133 -0
  365. package/examples/techniques/sun-and-key-light/keyLight.js +71 -0
  366. package/examples/techniques/sun-and-key-light/main.js +51 -0
  367. package/examples/techniques/sun-and-key-light/picture/index.js +13 -0
  368. package/examples/techniques/sun-and-key-light/picture/lights.js +33 -0
  369. package/examples/techniques/sun-and-key-light/picture/materials.js +9 -0
  370. package/examples/techniques/sun-and-key-light/picture/palette.js +29 -0
  371. package/examples/techniques/sun-and-key-light/picture/sky.js +16 -0
  372. package/examples/techniques/three-looks/README.md +21 -0
  373. package/examples/techniques/three-looks/main.js +58 -0
  374. package/examples/techniques/three-looks/picture/cartoon.js +23 -0
  375. package/examples/techniques/three-looks/picture/cinematic.js +27 -0
  376. package/examples/techniques/three-looks/picture/comic.js +27 -0
  377. package/examples/techniques/three-looks/picture/index.js +14 -0
  378. package/examples/techniques/three-looks/picture/sun.js +23 -0
  379. package/examples/techniques/wet-road/README.md +102 -0
  380. package/examples/techniques/wet-road/main.js +48 -0
  381. package/examples/techniques/wet-road/picture/index.js +17 -0
  382. package/examples/techniques/wet-road/picture/lights.js +57 -0
  383. package/examples/techniques/wet-road/picture/materials.js +16 -0
  384. package/examples/techniques/wet-road/picture/palette.js +24 -0
  385. package/examples/techniques/wet-road/picture/sky.js +46 -0
  386. package/examples/techniques/wet-road/wetRoad.js +209 -0
  387. package/examples/webgpu-tsl/.threedog/content-index.json +1 -0
  388. package/examples/webgpu-tsl/GAMEMAP.md +89 -0
  389. package/examples/webgpu-tsl/README.md +45 -0
  390. package/examples/webgpu-tsl/main.js +44 -0
  391. package/examples/webgpu-tsl/picture/index.js +18 -0
  392. package/examples/webgpu-tsl/picture/lights.js +25 -0
  393. package/examples/webgpu-tsl/picture/materials.js +36 -0
  394. package/examples/webgpu-tsl/picture/palette.js +23 -0
  395. package/examples/webgpu-tsl/picture/post.js +16 -0
  396. package/examples/webgpu-tsl/picture/sky.js +30 -0
  397. package/examples/world/.threedog/content-index.json +1 -0
  398. package/examples/world/GAMEMAP.md +31 -21
  399. package/examples/world/art/humanoid.js +38 -0
  400. package/examples/world/art/index.js +11 -0
  401. package/examples/world/art/models.js +57 -0
  402. package/examples/world/art/shapes.js +9 -0
  403. package/examples/world/assets.js +6 -0
  404. package/examples/world/content/audio.js +5 -5
  405. package/examples/world/content/items.js +1 -1
  406. package/examples/world/content/npcs.js +1 -1
  407. package/examples/world/content/props.js +1 -1
  408. package/examples/world/content/rules.js +1 -1
  409. package/examples/world/content/templates.js +1 -1
  410. package/examples/world/content/vegetation.js +1 -1
  411. package/examples/world/main.js +22 -18
  412. package/examples/world/models.js +17 -7
  413. package/examples/world/picture/index.js +20 -0
  414. package/examples/world/picture/lights.js +41 -0
  415. package/examples/world/picture/materials.js +34 -0
  416. package/examples/world/picture/palette.js +74 -0
  417. package/examples/world/picture/post.js +9 -0
  418. package/examples/world/picture/sky.js +39 -0
  419. package/index.d.ts +44 -54
  420. package/index.js +29 -25
  421. package/llms.txt +24 -15
  422. package/modules/ambience/Ambience.js +34 -23
  423. package/modules/calendar/Calendar.js +163 -0
  424. package/modules/calendar/contract.js +21 -0
  425. package/modules/calendar/index.js +82 -0
  426. package/modules/{sky → calendar}/schedule.js +17 -16
  427. package/modules/calendar/seasons.js +55 -0
  428. package/modules/camera/FirstPersonCamera.js +6 -15
  429. package/modules/camera/FixedCamera.js +33 -15
  430. package/modules/camera/FollowCamera.js +90 -16
  431. package/modules/camera/RtsCamera.js +18 -17
  432. package/modules/camera/common.js +73 -20
  433. package/modules/camera/contract.js +17 -0
  434. package/modules/camera/projection.js +11 -24
  435. package/modules/characters/Character.js +188 -48
  436. package/modules/characters/NPC.js +92 -41
  437. package/modules/characters/assetModel.js +8 -16
  438. package/modules/characters/behaviors.js +2 -1
  439. package/modules/characters/contract.js +13 -0
  440. package/modules/characters/footsteps.js +1 -1
  441. package/modules/characters/index.js +112 -49
  442. package/modules/characters/moveHelpers.js +4 -5
  443. package/modules/characters/movers/common.js +102 -19
  444. package/modules/characters/movers/manual.js +23 -0
  445. package/modules/characters/movers/rapier.js +19 -16
  446. package/modules/characters/movers/simple.js +14 -11
  447. package/modules/characters/movers/support.js +186 -0
  448. package/modules/characters/npcAvoid.js +47 -42
  449. package/modules/characters/npcSim.js +17 -9
  450. package/modules/characters/npcView.js +44 -16
  451. package/modules/characters/pathAsync.js +7 -3
  452. package/modules/characters/playerStrings.js +4 -3
  453. package/modules/characters/proceduralRig.js +19 -4
  454. package/modules/characters/useModel.js +2 -2
  455. package/modules/characters/vehicle.contract.js +21 -0
  456. package/modules/characters/walkTo.js +21 -7
  457. package/modules/collision/Collision.js +69 -27
  458. package/modules/collision/grid.js +8 -6
  459. package/modules/content/explain.js +2 -2
  460. package/modules/content/fields.js +102 -0
  461. package/modules/content/ids.js +8 -6
  462. package/modules/content/index.js +104 -27
  463. package/modules/content/loader.js +45 -33
  464. package/modules/content/models.js +58 -42
  465. package/modules/content/packs.js +6 -5
  466. package/modules/content/parts.js +41 -0
  467. package/modules/content/props.js +20 -11
  468. package/modules/content/rules.js +66 -0
  469. package/modules/content/stages.js +80 -0
  470. package/modules/content/templates.js +123 -30
  471. package/modules/debug/DebugPanel.js +24 -17
  472. package/modules/flow/contract.js +16 -0
  473. package/modules/flow/index.js +21 -15
  474. package/modules/gameplay/Container.js +41 -32
  475. package/modules/gameplay/Containers.js +30 -15
  476. package/modules/gameplay/Dialogue.js +113 -55
  477. package/modules/gameplay/Interactions.js +273 -72
  478. package/modules/gameplay/Inventory.js +72 -76
  479. package/modules/gameplay/Quests.js +75 -39
  480. package/modules/gameplay/boxOps.js +3 -3
  481. package/modules/gameplay/dialogue.contract.js +21 -0
  482. package/modules/gameplay/dialogueBox.js +4 -2
  483. package/modules/gameplay/dialogueBubbles.js +116 -0
  484. package/modules/gameplay/interactionPrompt.js +4 -1
  485. package/modules/gameplay/interactions.contract.js +16 -0
  486. package/modules/gameplay/inventory.contract.js +23 -0
  487. package/modules/gameplay/inventoryOps.js +19 -17
  488. package/modules/gameplay/pickups.js +306 -85
  489. package/modules/gameplay/questLog.js +6 -6
  490. package/modules/gameplay/quests.contract.js +17 -0
  491. package/modules/grid/Grid.js +92 -50
  492. package/modules/grid/Layer.js +27 -13
  493. package/modules/grid/index.js +96 -43
  494. package/modules/grid/ops.js +20 -18
  495. package/modules/grid/preview.js +37 -29
  496. package/modules/grid/strings.js +12 -0
  497. package/modules/grid/tiles.js +19 -22
  498. package/modules/hlod/index.js +52 -19
  499. package/modules/hud/index.js +48 -20
  500. package/modules/hud/parts.js +28 -13
  501. package/modules/level/heightfield.js +3 -1
  502. package/modules/level/index.js +49 -23
  503. package/modules/level/nodes.js +4 -3
  504. package/modules/lights/index.js +47 -19
  505. package/modules/music/Music.js +38 -21
  506. package/modules/music/rules.js +1 -1
  507. package/modules/nav/index.js +48 -42
  508. package/modules/net/Client.js +13 -6
  509. package/modules/net/Host.js +19 -5
  510. package/modules/net/Net.js +2 -1
  511. package/modules/net/index.js +13 -8
  512. package/modules/net/sync.js +9 -8
  513. package/modules/net/transports.js +77 -27
  514. package/modules/particles/Particles.js +58 -28
  515. package/modules/particles/contract.js +17 -0
  516. package/modules/particles/effect.js +54 -11
  517. package/modules/photo/Photo.js +56 -38
  518. package/modules/rigid/RigidBodies.js +194 -32
  519. package/modules/rigid/Vehicles.js +18 -15
  520. package/modules/rigid/sync.js +62 -17
  521. package/modules/settings/Settings.js +60 -55
  522. package/modules/settings/apply.js +38 -3
  523. package/modules/settings/sections.js +5 -3
  524. package/modules/settings/strings.js +3 -2
  525. package/modules/settings/view.js +5 -3
  526. package/modules/sky/Sky.js +132 -205
  527. package/modules/sky/clouds.js +37 -23
  528. package/modules/sky/dome.js +100 -0
  529. package/modules/sky/domeLayers.js +30 -15
  530. package/modules/sky/environment.js +45 -99
  531. package/modules/sky/fog.js +9 -139
  532. package/modules/sky/frame.js +60 -56
  533. package/modules/sky/season.js +21 -0
  534. package/modules/sky/shader.js +63 -35
  535. package/modules/sky/skyModule.js +52 -37
  536. package/modules/sky/tint.js +59 -0
  537. package/modules/terrain/ChunkManager.js +194 -110
  538. package/modules/terrain/chunkJob.js +1 -1
  539. package/modules/terrain/chunkQueries.js +6 -4
  540. package/modules/terrain/draw.js +154 -0
  541. package/modules/terrain/index.js +87 -54
  542. package/modules/terrain/terrainDefaults.js +2 -2
  543. package/modules/terrain/terrainEdit.js +18 -20
  544. package/modules/terrain/terrainGen.js +6 -4
  545. package/modules/terrain/terrainIsland.js +5 -4
  546. package/modules/terrain/terrainShape.js +12 -12
  547. package/modules/terrain/terrainShapeMain.js +8 -7
  548. package/modules/terrain/terrainTexture.js +21 -19
  549. package/modules/timeline/Timeline.js +95 -43
  550. package/modules/timeline/Tween.js +18 -10
  551. package/modules/timeline/letterbox.js +2 -2
  552. package/modules/timeline/shots.js +5 -1
  553. package/modules/triggers/index.js +111 -76
  554. package/modules/vegetation/Vegetation.js +229 -112
  555. package/modules/vegetation/densityMap.js +62 -0
  556. package/modules/vegetation/draw.js +191 -0
  557. package/modules/vegetation/groundChunks.js +52 -58
  558. package/modules/vegetation/index.js +32 -11
  559. package/modules/vegetation/modelGeometry.js +3 -2
  560. package/modules/vegetation/nearFade.js +8 -2
  561. package/modules/water/Water.js +157 -72
  562. package/modules/water/surface.js +86 -47
  563. package/modules/weather/Weather.js +96 -103
  564. package/modules/weather/particles.js +37 -14
  565. package/modules/weather/shaders.js +1 -1
  566. package/modules/weather/strings.js +2 -2
  567. package/modules/weather/weatherDraw.js +141 -0
  568. package/modules/world/World.js +26 -9
  569. package/modules/world/explain.js +1 -1
  570. package/modules/world/index.js +18 -4
  571. package/modules/world/persist.js +62 -2
  572. package/modules/world/pos.js +3 -2
  573. package/modules/world/records.js +8 -6
  574. package/modules/world/sim.js +60 -20
  575. package/modules/world/simFar.js +4 -3
  576. package/modules/world/state.js +3 -2
  577. package/modules/world/thingSource.js +1 -1
  578. package/modules/world/views.js +8 -6
  579. package/package.json +8 -3
  580. package/presets.js +43 -29
  581. package/render/PostFX.js +318 -135
  582. package/render/backend.js +486 -0
  583. package/render/cascades.js +195 -0
  584. package/render/cascades.tsl.js +96 -0
  585. package/render/daylight.js +39 -0
  586. package/render/detail.js +122 -41
  587. package/render/effects.js +155 -48
  588. package/render/engineUniforms.js +10 -1
  589. package/render/fuse.js +5 -4
  590. package/render/fx/cel.tsl.js +42 -0
  591. package/render/fx/cloudShadow.tsl.js +16 -0
  592. package/render/fx/detail.tsl.js +66 -0
  593. package/render/fx/index.js +28 -0
  594. package/render/fx/lighting.tsl.js +28 -0
  595. package/render/fx/nodeErrors.tsl.js +68 -0
  596. package/render/fx/noise.tsl.js +12 -0
  597. package/render/fx/objectOrigin.tsl.js +42 -0
  598. package/render/fx/particles.tsl.js +139 -0
  599. package/render/fx/patchNodes.tsl.js +403 -0
  600. package/render/fx/postWebGPU.tsl.js +181 -0
  601. package/render/fx/season.tsl.js +13 -0
  602. package/render/fx/sky.tsl.js +187 -0
  603. package/render/fx/uniforms.tsl.js +67 -0
  604. package/render/fx/water.tsl.js +53 -0
  605. package/render/fx/wind.tsl.js +22 -0
  606. package/render/fxNumbers.js +36 -0
  607. package/render/hotGlsl.js +24 -0
  608. package/render/layers.js +14 -0
  609. package/render/lighting.js +71 -18
  610. package/render/lightmap.js +142 -0
  611. package/render/lights.js +47 -6
  612. package/render/materials.js +55 -152
  613. package/render/modeling.js +73 -0
  614. package/render/neutral.js +23 -0
  615. package/render/occlusion.js +184 -0
  616. package/render/ownFrame.js +76 -0
  617. package/render/patches.js +317 -35
  618. package/render/postWebGL.js +205 -0
  619. package/render/probes.js +288 -0
  620. package/render/shaderErrors.js +154 -0
  621. package/render/slots.js +165 -0
  622. package/render/terms.js +163 -0
  623. package/render/uniformDecl.js +4 -3
  624. package/types/common.d.ts +2 -2
  625. package/types/core.d.ts +757 -346
  626. package/types/gameplay.d.ts +539 -330
  627. package/types/generated/core/Audio.d.ts +26 -42
  628. package/types/generated/core/Batching.d.ts +6 -2
  629. package/types/generated/core/Budget.d.ts +2 -8
  630. package/types/generated/core/DebugOverrides.d.ts +58 -9
  631. package/types/generated/core/I18n.d.ts +2 -2
  632. package/types/generated/core/Input.d.ts +110 -32
  633. package/types/generated/core/Ops.d.ts +31 -0
  634. package/types/generated/core/Random.d.ts +2 -2
  635. package/types/generated/core/Saves.d.ts +10 -2
  636. package/types/generated/core/Stream.d.ts +1 -1
  637. package/types/generated/core/Threads.d.ts +4 -1
  638. package/types/generated/core/Views.d.ts +0 -1
  639. package/types/generated/core/audioVoice.d.ts +17 -9
  640. package/types/generated/core/control.d.ts +55 -0
  641. package/types/generated/core/page.d.ts +9 -2
  642. package/types/generated/core/session.d.ts +2 -1
  643. package/types/generated/modules/ambience/Ambience.d.ts +0 -9
  644. package/types/generated/modules/calendar/Calendar.d.ts +84 -0
  645. package/types/generated/modules/calendar/index.d.ts +10 -0
  646. package/types/generated/modules/debug/DebugPanel.d.ts +2 -2
  647. package/types/generated/modules/grid/Grid.d.ts +61 -25
  648. package/types/generated/modules/grid/Layer.d.ts +13 -5
  649. package/types/generated/modules/grid/index.d.ts +56 -20
  650. package/types/generated/modules/music/Music.d.ts +5 -3
  651. package/types/generated/modules/net/index.d.ts +3 -3
  652. package/types/generated/modules/net/transports.d.ts +12 -3
  653. package/types/generated/modules/particles/Particles.d.ts +13 -6
  654. package/types/generated/modules/sky/Sky.d.ts +85 -110
  655. package/types/generated/modules/sky/skyModule.d.ts +1 -1
  656. package/types/generated/modules/timeline/Timeline.d.ts +8 -6
  657. package/types/generated/modules/water/Water.d.ts +50 -3
  658. package/types/generated/modules/weather/Weather.d.ts +44 -15
  659. package/types/generated/modules/weather/weatherDraw.d.ts +11 -0
  660. package/types/generated/modules/world/World.d.ts +20 -5
  661. package/types/generated/render/PostFX.d.ts +109 -29
  662. package/types/generated/render/lighting.d.ts +29 -0
  663. package/types/generated/render/materials.d.ts +31 -50
  664. package/types/generated/render/modeling.d.ts +30 -0
  665. package/types/generated/render/occlusion.d.ts +13 -0
  666. package/types/generated/render/patches.d.ts +16 -2
  667. package/types/generated/ui/UI.d.ts +6 -3
  668. package/types/nav.d.ts +6 -0
  669. package/types/physics.d.ts +140 -45
  670. package/types/tsl.d.ts +94 -0
  671. package/types/world.d.ts +489 -122
  672. package/ui/Focus.js +35 -14
  673. package/ui/LoadingScreen.js +3 -3
  674. package/ui/Parts.js +35 -15
  675. package/ui/UI.js +27 -17
  676. package/ui/cursor.js +115 -0
  677. package/ui/defaults.js +15 -11
  678. package/ui/theme.js +36 -27
  679. package/ui/touchPart.js +2 -2
  680. package/core/claims.js +0 -51
  681. package/core/look/coreParts.js +0 -112
  682. package/core/look/layers.js +0 -136
  683. package/core/look/part.js +0 -173
  684. package/core/look/report.js +0 -79
  685. package/core/look/write.js +0 -86
  686. package/core/renamed.js +0 -22
  687. package/core/styleParts.js +0 -98
  688. package/docs/api/entities.md +0 -61
  689. package/docs/api/style.md +0 -134
  690. package/docs/recipes/09-style-pack.md +0 -169
  691. package/docs/recipes/35-style-from-reference.md +0 -84
  692. package/docs/recipes/36-sky-ground-plant-looks.md +0 -118
  693. package/docs/recipes/38-environment-look-hooks.md +0 -88
  694. package/docs/recipes/41-thing-registry.md +0 -93
  695. package/docs/recipes/43-shader-patches-surface-looks.md +0 -135
  696. package/docs/recipes/44-water-weather-look-hooks.md +0 -135
  697. package/docs/recipes/48-make-material.md +0 -70
  698. package/docs/recipes/52-look.md +0 -146
  699. package/examples/action/look.js +0 -5
  700. package/examples/sheepisland/style/index.js +0 -79
  701. package/examples/styletest/look.js +0 -11
  702. package/examples/styletest/overrides.js +0 -33
  703. package/examples/styletest/panel.js +0 -135
  704. package/modules/entities/Entities.js +0 -243
  705. package/modules/entities/build.js +0 -25
  706. package/modules/entities/index.js +0 -4
  707. package/modules/sky/calendar.js +0 -80
  708. package/modules/sky/cascades.js +0 -125
  709. package/modules/sky/layers.js +0 -69
  710. package/modules/sky/look.js +0 -51
  711. package/modules/sky/lookFog.js +0 -80
  712. package/modules/sky/lookShadow.js +0 -50
  713. package/modules/sky/lookSky.js +0 -108
  714. package/modules/sky/shadow.js +0 -74
  715. package/modules/terrain/chunkLevels.js +0 -40
  716. package/modules/terrain/lookGround.js +0 -61
  717. package/modules/terrain/mountTerrain.js +0 -32
  718. package/modules/vegetation/lookWind.js +0 -37
  719. package/modules/water/look.js +0 -80
  720. package/modules/weather/look.js +0 -75
  721. package/modules/world/cells.js +0 -42
  722. package/render/lookSurface.js +0 -161
  723. package/render/postLook.js +0 -86
  724. package/render/surface.js +0 -69
  725. package/types/style.d.ts +0 -643
@@ -0,0 +1,126 @@
1
+ Modular buildings on a grid: parameterized wall / window / door / roof / trim modules, an assembler for buildings and seeded streets, any style.
2
+
3
+ # Modular buildings (technique example)
4
+
5
+ A kit of building pieces made in code, snapped to a grid and assembled into buildings and whole streets, with the colours and materials left to
6
+ the game. The pieces are plain on purpose: the same kit draws a cozy town, a gray block-out or a cold sci-fi row by swapping one set of
7
+ materials and one set of trim profiles. Run it with `npm run dev` and open `/modular-building.html` (`?set=gray|warm|cool`, `seed=1`,
8
+ `count=10`, `view=street|close`, `batch=0|merge`). The engine never imports this folder; copy it and change anything.
9
+
10
+ ## The principle
11
+ A town reads from far to near: skyline first, then the rhythm of openings, then trim, then small detail. A grid makes every piece fit every
12
+ slot, and a few repeated pieces are both cheap to draw and what makes a street look built rather than noisy. These are ways to judge your own
13
+ pieces, not fixed recipes; the numbers in `kit.js` are this example's current params, picked for a street seen from a few metres to a few dozen.
14
+
15
+ 1. **Block out first: grid and silhouettes.** Decide the cell (one wall module wide) and the storey height from the player's size: block out
16
+ with the player model (or a capsule of its size) in view, or a door that looks fine alone is too short next to the player. Then place
17
+ plain boxes for whole buildings and look at the street from the game's camera. Height, width and roof shape are what read from far away;
18
+ if the skyline is dull, no window detail will save it.
19
+ 2. **Then modules.** Replace blank cells with windows and doors. Every module of one kind shares its outline with its neighbours (same cell
20
+ width, same storey height, outer face on the same plane), so any module fits any slot.
21
+ 3. **Then trim and detail, big to small.** Big: roof shape, floor count, overhangs. Medium: cornices and floor bands, pilasters on corners,
22
+ awnings, signs. Small: sills, mullions, planters. Each level should still read at the distance where the player sees it; detail smaller
23
+ than a few pixels on screen costs triangles and turns into noise or shimmer.
24
+ 4. **One texture language.** Pick one way surfaces get their pattern (flat colour, vertex AO, one kind of canvas mask) and use it everywhere.
25
+ 5. **Change style by swapping, not rewriting.** A style is a set of materials plus trim cross-sections plus window variants.
26
+ 6. **Variation from a few choices, not continuous noise.** Pick each trait from a short list (floors, width, roof, window variant, trim
27
+ profile, door position, shop front) with a seeded random, and mirror upper floors around the middle so facades look designed. A few
28
+ variants keep geometry shared while no two neighbours repeat; a random size per window makes every window unique (noise, and nothing
29
+ batches). A street of one window reads as copy-paste.
30
+ 7. **Facades follow the inside.** A door on a side wall facing another building, or windows where an interior wall would be: if the game
31
+ has interiors, derive facades from the floor plan.
32
+
33
+ How to judge it: a shot at the game's real camera, not a close-up. Does the skyline vary? Do neighbours differ? Does any detail shimmer or
34
+ vanish at that distance? Does anything flicker at seams when the camera moves?
35
+
36
+ ## Plain three.js
37
+ - Pieces: `BoxGeometry`, `RoundedBoxGeometry` (addon), and trim strips as an `ExtrudeGeometry` of a `Shape` cross-section
38
+ ([ExtrudeGeometry](https://threejs.org/docs/#api/en/geometries/ExtrudeGeometry)). Each module a `Group` placed at integer cell offsets.
39
+ - Many copies: [InstancedMesh](https://threejs.org/docs/#api/en/objects/InstancedMesh) per repeated piece
40
+ ([webgl_instancing_performance](https://threejs.org/examples/#webgl_instancing_performance)), or
41
+ [BatchedMesh](https://threejs.org/docs/#api/en/objects/BatchedMesh) for mixed geometries sharing a material
42
+ ([webgl_mesh_batch](https://threejs.org/examples/#webgl_mesh_batch)).
43
+ - Merging: `mergeGeometries` from [BufferGeometryUtils](https://threejs.org/docs/#examples/en/utils/BufferGeometryUtils) gives one draw per
44
+ material, at the cost of culling and per-piece edits.
45
+ - Seams: avoid coplanar faces; if one is unavoidable, `material.polygonOffset` is the last resort, not the plan.
46
+
47
+ ## Style routes
48
+ - **Gray block-out**: boxes and `.` cells only; judges silhouette and scale before any art. Cheapest.
49
+ - **Cozy / storybook**: soft cove trims, rounded edges, warm slot materials, awnings and planters. More trim strips (one-off geometry).
50
+ - **Cold sci-fi / brutalist**: hard stepped trims, flat roofs, faintly emissive frames. Fewer pieces, more repetition.
51
+ - **Low-poly flat**: flat colour per slot, vertex AO for depth, no textures. Very cheap.
52
+ - **Hand-painted / textured**: one texture set per slot from a DCC tool, the kit only for layout. Texture memory instead of geometry.
53
+ - **Merged hero block**: a fixed set piece merged once for the fewest draws, when it never changes.
54
+
55
+ ## The engine helper (optional convenience)
56
+ `kit.js` is the kit: modules, assembler, manifest entries; it imports only `three` and `three/addons`. `main.js` is the demo page and `picture/` its
57
+ picture in plain three.js (lights, tone curve, one Lambert material per slot, every value in `picture/palette.js`). The page builds the same seed
58
+ three ways (gray block-out, warm with soft cove trims, cool with hard stepped trims and faintly emissive frames; the two coloured
59
+ sets are demo values, not advice). In the kit, the block-out stage is `facade` strings of `.` (blank walls) and `roof`. A style is the slot
60
+ materials (`wall`, `trim`, `roof`, `frame`, `glass`, `accent`, `awning`, `sign`) plus `profiles` plus `windows`. The only textures are gray
61
+ masks (awning stripes, sign text) tinted by the slot material's colour, so a material swap recolours them too. `street` mirrors upper floors
62
+ and picks traits with a seeded `rng`.
63
+
64
+ ```js
65
+ import { createModularKit, PROFILES, WINDOWS } from './kit.js';
66
+ const kit = createModularKit({
67
+ slots: { wall, trim, roof, frame, glass, accent, awning, sign }, // the game's materials; only wall is required, the rest fall back
68
+ cell: 2, storey: 3, wall: 0.2, // grid cell, floor height, wall thickness (metres)
69
+ profiles: PROFILES, windows: WINDOWS, // trim cross-sections and window variants: swap them per style
70
+ ao: { bake: bakeVertexAO, samples: 24 }, // optional: threedog's bakeVertexAO per module (slots then need vertexColors)
71
+ });
72
+ engine.assets.manifest(kit.pack); // mb-wall, mb-window, mb-door, mb-corner, mb-trim, mb-gable, mb-flatRoof, mb-awning,
73
+ // mb-sign, mb-chimney, mb-building, mb-street; all { build, params }
74
+ // content/props.js: { model: ['mb-street', { seed: 7, count: 12 }], x: 0, z: 0 } or { model: ['mb-building', { floors: 3 }], ... }
75
+ const b = kit.building({ width: 3, depth: 2, floors: 2, front: 'SDS/WWW', back: 'W.W', roof: 'gable', trim: 'cove', sign: 'BAKERY' });
76
+ const s = kit.street({ seed: 7, count: 10, gap: 1 });
77
+ s.userData.batch = true; engine.scene.add(s); // opt in to engine.batching (recipe 05, 2b)
78
+ engine.scene.add(kit.merge(s)); // or: one mesh per material (see costs)
79
+ kit.modules.window({ width: 1.1, height: 1.5, sill: 0.8, mullions: 2, planter: true }); // any single module as a Group
80
+ ```
81
+ - Each module is a `Group` with one mesh per slot (pieces of the same slot are merged), identity transforms, geometry shared by every copy
82
+ with the same params. `userData.module = { type, side, floor, i }` names each placed module; the wall slab mesh is named `wall`.
83
+ - Because every piece is a registered `{ build, params }` entry, `threedog gallery` shows each module on a turntable, saving `kit.js` swaps
84
+ the pieces in a running game, and `?panel=1` drags the params (`threedog tune write` writes them back).
85
+ - `kit.dispose()` frees the geometries, textures and textured materials it made; the slot materials are the game's.
86
+
87
+ Costs (seed 1, 10 buildings, 960x540, `npm run shot`, 2026-11-02). Draw calls as `describe().perf` counts them (the shadow pass included),
88
+ about 74k triangles in every case:
89
+
90
+ | | draw calls |
91
+ |---|---|
92
+ | plain meshes (`?batch=0`) | 1377 |
93
+ | `engine.batching` (`userData.batch = true`, the default page) | 308 |
94
+ | `kit.merge` (`?batch=merge`) | 24 |
95
+
96
+ - `engine.batching` instances meshes that repeat at least 8 times in a 64 m cell: windows, walls, corners. What stays single is one-off
97
+ geometry: each building's roof and trim strips (their length is the building's), signs. Fewer distinct sizes = fewer draws.
98
+ - `kit.merge` gives one draw per material, but the whole merged street is drawn whenever any of it is on screen, and single pieces can no
99
+ longer be moved or swapped. Merge per block (a few buildings) in a large town so culling still works.
100
+ - Rounded edges use `RoundedBoxGeometry` with one segment (108 triangles per piece instead of 300 with two): a chamfer with smooth normals
101
+ catches the same highlight, and sills / pilasters / copings repeat hundreds of times.
102
+ - This kit's 4 cm mullions are fine up close and vanish or shimmer a few dozen metres away: size each level of detail for your camera.
103
+
104
+ Rules (correctness):
105
+ - **Every facade module spans exactly one cell and one storey, with its outer face at module z = 0**, details in front (+z), the slab behind.
106
+ A module that breaks this leaves gaps or overlaps that the assembler cannot fix.
107
+ - **Building origins land on whole cells** (`street` places each building at an integer cell offset). Off-grid origins break the snapping
108
+ the spec checks.
109
+ - **A facade row has one letter per footprint cell** (`W` window, `S` shop window with awning, `D` door, `.` blank); rows are separated by `/`,
110
+ ground floor first, and the last row repeats upward. A wrong length or a door above the ground floor throws, naming the side.
111
+ - **No two visible faces share a plane.** Two faces in one plane flicker when the camera moves; never rely on "same colour, nobody will
112
+ notice". Where pieces meet, either one covers the seam (corner pilasters cover the wall ends; front / back trims run past the corners,
113
+ side trims stop at the walls) or they are offset by a few millimetres (the sill top sits above the reveal floor).
114
+ - **Generators get every input from `params`.** The slot materials are live objects, so the kit's manifest entries are `cache: false`
115
+ (the dev cache would otherwise keep a model built with old materials). To bake a street, build the slot materials inside the
116
+ generator instead (recipe 05, section 2a) and drop `cache: false`.
117
+
118
+ Limits:
119
+ - Footprints are rectangles of cells (`width` x `depth`); an L-shaped building needs `building` extended to take a cell list (two buildings
120
+ with `gap: 0` meet wall to wall, and their corner pilasters then overlap).
121
+ - Gable ridges run along the building's width; hip roofs, dormers and balconies are not in the kit (each is one more module).
122
+ - The test is `npm test -- "modular building"` (tests/specs/modular-building.mjs): determinism per seed, grid snapping without gaps,
123
+ shared geometry, batching under 400 draw calls, params changing shape, the optional AO pass.
124
+
125
+ Sources: written for this example; no code copied. Background: the grid-snapped kit of reusable pieces is common modular level design practice
126
+ (Joel Burgess, "Skyrim's Modular Approach to Level Design", GDC 2013); `RoundedBoxGeometry` and `mergeGeometries` are three.js addons.
@@ -0,0 +1,426 @@
1
+ // @ts-check
2
+ // Modular building kit (optional technique example, see README.md). Shapes only: every module is built from parameters and drawn with the
3
+ // game's own materials, one per slot (wall, trim, roof, frame, glass, accent, awning, sign). Imports only three and three/addons, so a game can
4
+ // copy the folder and change anything.
5
+ // The pieces are deliberately plain: they teach the method (grid, modules, variation, shared geometry), not a picture.
6
+ import * as THREE from 'three';
7
+ import { RoundedBoxGeometry } from 'three/addons/geometries/RoundedBoxGeometry.js';
8
+ import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js';
9
+
10
+ export const SLOTS = ['wall', 'trim', 'roof', 'frame', 'glass', 'accent', 'awning', 'sign'];
11
+ // a slot the game leaves out borrows from the next one, so one material is enough to start (a gray block-out)
12
+ const FALLBACK = { trim: 'wall', roof: 'trim', frame: 'trim', glass: 'frame', accent: 'frame', awning: 'accent', sign: 'trim' };
13
+
14
+ /** Trim profiles: [out, up] points of a cross-section, outward from the wall face. Swap or add profiles to change a style's trim */
15
+ export const PROFILES = {
16
+ flat: [[0, 0], [1, 0], [1, 1], [0, 1]],
17
+ step: [[0, 0], [0.55, 0], [0.55, 0.45], [1, 0.45], [1, 1], [0, 1]],
18
+ cove: [[0, 0], [0.35, 0], [0.5, 0.25], [0.75, 0.45], [1, 0.75], [1, 1], [0, 1]],
19
+ };
20
+
21
+ /** Window variants a street picks from: a few shared variants (not a random size per window) keep the picture designed and the geometry shared */
22
+ export const WINDOWS = [
23
+ { width: 0.9, height: 1.4, sill: 0.9, mullions: 1, planter: false },
24
+ { width: 1.1, height: 1.5, sill: 0.8, mullions: 2, planter: true },
25
+ { width: 0.7, height: 1.6, sill: 0.8, mullions: 0, planter: false },
26
+ ];
27
+
28
+ /** Seeded random 0..1 (mulberry32): the same seed gives the same street on every machine */
29
+ export function rng(seed) {
30
+ let a = seed >>> 0;
31
+ return () => {
32
+ a = (a + 0x6D2B79F5) >>> 0;
33
+ let t = a;
34
+ t = Math.imul(t ^ (t >>> 15), t | 1);
35
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
36
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
37
+ };
38
+ }
39
+
40
+ /**
41
+ * A kit: module builders + an assembler for buildings and streets, all sharing one geometry cache and one slot set.
42
+ * @param {{ prefix?: string, cell?: number, storey?: number, wall?: number, slots: Record<string, THREE.Material>,
43
+ * profiles?: Record<string, number[][]>, windows?: typeof WINDOWS,
44
+ * ao?: { bake: (g: THREE.BufferGeometry, o: any) => any, samples?: number, strength?: number } | null }} opts
45
+ * cell: grid cell in metres (one wall module wide); storey: floor height; wall: wall thickness. slots: the game's materials.
46
+ * ao: optional vertex AO (pass threedog's bakeVertexAO as `bake`); the slot materials then need vertexColors: true.
47
+ */
48
+ export function createModularKit(opts) {
49
+ const known = ['prefix', 'cell', 'storey', 'wall', 'slots', 'profiles', 'windows', 'ao'];
50
+ for (const k of Object.keys(opts ?? {})) if (!known.includes(k)) throw new Error(`createModularKit: unknown option "${k}" (use ${known.join(', ')})`);
51
+ const { prefix = 'mb', cell = 2, storey = 3, wall: T = 0.2, profiles = PROFILES, windows = WINDOWS, ao = null } = opts;
52
+ if (!opts.slots?.wall) throw new Error('createModularKit: slots.wall is required (other slots fall back to it)');
53
+ for (const k of Object.keys(opts.slots)) if (!SLOTS.includes(k)) throw new Error(`createModularKit: unknown slot "${k}" (slots: ${SLOTS.join(', ')})`);
54
+ const slots = /** @type {Record<string, THREE.Material>} */ ({});
55
+ for (const s of SLOTS) { let k = s; while (!opts.slots[k]) k = FALLBACK[k]; slots[s] = opts.slots[k]; }
56
+
57
+ // ---- shared geometry and materials ---------------------------------------------------------------------------------------------------
58
+ // One geometry per module + params, one material per slot (+ texture): every copy of a module shares them, which is what lets
59
+ // engine.batching draw a whole street with a few dozen instanced draws instead of one draw per piece.
60
+ const geoCache = new Map(), texCache = new Map(), matCache = new Map();
61
+ const memo = (key, make) => geoCache.get(key) ?? geoCache.set(key, make()).get(key);
62
+ const textured = (slot, tex) => {
63
+ const k = slot + '|' + tex.uuid;
64
+ if (!matCache.has(k)) { const m = slots[slot].clone(); /** @type {any} */ (m).map = tex; m.polygonOffset = true; m.polygonOffsetFactor = -1; matCache.set(k, m); }
65
+ return matCache.get(k);
66
+ };
67
+
68
+ /** pieces [geometry, slot][] in module space -> { slot: one merged geometry } (non-indexed, so boxes and extrusions merge together) */
69
+ function bySlot(pieces) {
70
+ const out = {};
71
+ for (const [g, s] of pieces) (out[s] ||= []).push(g.index ? g.toNonIndexed() : g);
72
+ for (const s in out) {
73
+ const merged = mergeGeometries(out[s]);
74
+ if (!merged) throw new Error(`modular kit: pieces of slot "${s}" do not share attributes`);
75
+ out[s] = merged;
76
+ }
77
+ if (ao) for (const s in out) {
78
+ // each slot's geometry is darkened by the module's other parts too (a sill under a frame, the reveal of a window hole)
79
+ const others = Object.keys(out).filter(o => o !== s).map(o => out[o]);
80
+ ao.bake(out[s], { samples: ao.samples ?? 24, strength: ao.strength ?? 0.6, occluders: others, radius: 0.6 });
81
+ }
82
+ return out;
83
+ }
84
+ /** A module's group: one mesh per slot, identity transforms (the group is what the assembler moves) */
85
+ function group(type, geos, maps = {}) {
86
+ const g = new THREE.Group();
87
+ g.name = type;
88
+ for (const [slot, geo] of Object.entries(geos)) {
89
+ const m = new THREE.Mesh(geo, maps[slot] ? textured(slot.split(':')[0], maps[slot]) : slots[slot.split(':')[0]]);
90
+ m.name = slot; m.castShadow = m.receiveShadow = true;
91
+ g.add(m);
92
+ }
93
+ return g;
94
+ }
95
+
96
+ // ---- geometry helpers --------------------------------------------------------------------------------------------------------------
97
+ const box = (w, h, d, x = 0, y = 0, z = 0) => new THREE.BoxGeometry(w, h, d).translate(x, y, z);
98
+ // rounded edges: a raw box reads as a placeholder; a small radius catches a highlight along every edge. One segment (108 triangles, a
99
+ // chamfer with smooth normals) instead of two (300) because sills, pilasters and copings repeat hundreds of times on a street
100
+ const rbox = (w, h, d, r, x = 0, y = 0, z = 0) => new RoundedBoxGeometry(w, h, d, 1, Math.min(r, w / 2.01, h / 2.01, d / 2.01)).translate(x, y, z);
101
+ const shape = pts => new THREE.Shape(pts.map(([x, y]) => new THREE.Vector2(x, y)));
102
+ const rect = (x0, y0, x1, y1) => [[x0, y0], [x1, y0], [x1, y1], [x0, y1]];
103
+ const extrude = (s, depth) => new THREE.ExtrudeGeometry(s, { depth, bevelEnabled: false });
104
+ /** A cross-section in (out, up) extruded along x over [-len/2, len/2]: trims, roofs, gable ends */
105
+ const sweepX = (pts, len) => extrude(shape(pts), len).rotateY(-Math.PI / 2).translate(len / 2, 0, 0);
106
+ /** A wall slab of one cell, outer face at z = 0, with holes ([x0, y0, x1, y1] rectangles) */
107
+ function slab(holes = [], h = storey) {
108
+ if (!holes.length) return box(cell, h, T, 0, h / 2, -T / 2);
109
+ const s = shape(rect(-cell / 2, 0, cell / 2, h));
110
+ for (const r of holes) s.holes.push(new THREE.Path(rect(...r).map(([x, y]) => new THREE.Vector2(x, y)).reverse()));
111
+ return extrude(s, T).translate(0, 0, -T);
112
+ }
113
+ /** A wall slab with an opening cut up from the floor (a door): one U-shaped outline, since a hole may not touch the border */
114
+ function slabOpen(w, h) {
115
+ const c = cell / 2, pts = [[-c, 0], [-w / 2, 0], [-w / 2, h], [w / 2, h], [w / 2, 0], [c, 0], [c, storey], [-c, storey]];
116
+ return extrude(shape(pts), T).translate(0, 0, -T);
117
+ }
118
+
119
+ // ---- modules (each: params -> Group). Params are plain data, so the manifest can cache, tune and gallery them ---------------------------
120
+ const mod = {
121
+ wall() { return group('wall', memo('wall', () => bySlot([[slab(), 'wall']]))); },
122
+
123
+ /** A window: slab with a hole, a proud surround, an inset frame with mullions, recessed glass, a sill and optionally a planter */
124
+ window(p) {
125
+ const { width: w, height: h, sill: y0, mullions = 1, planter = false, inset = 0.08, frame: f = 0.08 } = p;
126
+ return group('window', memo('window' + JSON.stringify(p), () => {
127
+ const z = -inset, bars = [];
128
+ for (let i = 1; i <= mullions; i++) bars.push([box(0.04, h, 0.05, -w / 2 + (w * i) / (mullions + 1), y0 + h / 2, z), 'frame']);
129
+ const surround = shape(rect(-w / 2 - f, y0 - f, w / 2 + f, y0 + h + f));
130
+ surround.holes.push(new THREE.Path(rect(-w / 2, y0, w / 2, y0 + h).map(([x, y]) => new THREE.Vector2(x, y)).reverse()));
131
+ const pieces = [
132
+ [slab([[-w / 2, y0, w / 2, y0 + h]]), 'wall'],
133
+ [extrude(surround, 0.04), 'trim'], // proud of the face: catches light, hides the cut edge
134
+ [rbox(w + 2 * f + 0.12, 0.08, 0.22, 0.02, 0, y0 - 0.035, 0.07), 'trim'], // the sill sticks out further than the surround; its top 5 mm above the reveal floor so the two never share a plane
135
+ [box(w, 0.05, 0.05, 0, y0 + h / 2, z), 'frame'], // transom
136
+ ...bars,
137
+ [box(w, h, 0.01, 0, y0 + h / 2, z - 0.03), 'glass'], // recessed: the reveal reads as wall thickness
138
+ ];
139
+ if (planter) pieces.push([rbox(w * 0.9, 0.22, 0.2, 0.03, 0, y0 + 0.115, 0.1), 'accent']);
140
+ return bySlot(pieces);
141
+ }));
142
+ },
143
+
144
+ /** A door: U-cut slab, surround on three sides, recessed leaf, a step */
145
+ door(p) {
146
+ const { width: w = 1, height: h = 2.2, inset = 0.1, frame: f = 0.1 } = p;
147
+ return group('door', memo('door' + JSON.stringify(p), () => bySlot([
148
+ [slabOpen(w, h), 'wall'],
149
+ [box(f, h + f, 0.05, -w / 2 - f / 2, (h + f) / 2, 0.025), 'trim'],
150
+ [box(f, h + f, 0.05, w / 2 + f / 2, (h + f) / 2, 0.025), 'trim'],
151
+ [box(w, f, 0.05, 0, h + f / 2, 0.025), 'trim'],
152
+ [box(w, h, 0.05, 0, h / 2, -inset), 'accent'],
153
+ [rbox(w + 0.3, 0.12, 0.35, 0.03, 0, 0.06, 0.17), 'trim'],
154
+ ])));
155
+ },
156
+
157
+ /** A corner pilaster, one storey: centered on the corner, a little wider than the wall, so it covers the seam where two walls meet */
158
+ corner(p) {
159
+ const { size = T * 1.6 } = p;
160
+ return group('corner', memo('corner' + size, () => bySlot([[rbox(size, storey, size, 0.03, 0, storey / 2, 0), 'trim']])));
161
+ },
162
+
163
+ /** A trim strip of any length along x: cornice, floor band, plinth. profile = a name in profiles */
164
+ trim(p) {
165
+ const { length, profile = 'step', height = 0.25, depth = 0.15 } = p;
166
+ const pts = profiles[profile];
167
+ if (!pts) throw new Error(`modular kit: unknown trim profile "${profile}" (profiles: ${Object.keys(profiles).join(', ')})`);
168
+ return group('trim', memo('trim' + JSON.stringify(p), () => bySlot([[sweepX(pts.map(([o, u]) => [o * depth, u * height]), length), 'trim']])));
169
+ },
170
+
171
+ /** A gable roof over width x depth metres (ridge along x), bottom resting on the wall top at the eaves line; gable end walls included */
172
+ gable(p) {
173
+ const { width: W, depth: D, pitch = 0.6, overhang = 0.3, thickness = 0.15 } = p;
174
+ return group('gable', memo('gable' + JSON.stringify(p), () => {
175
+ const a = D / 2 + overhang, r = a * pitch, k = thickness * Math.hypot(1, pitch), drop = r * (1 - D / 2 / a);
176
+ const chevron = [[-a, 0], [0, r], [a, 0], [a, k], [0, r + k], [-a, k]].map(([z, y]) => [z, y - drop]);
177
+ const apex = r * (D / 2) / a; // the gable triangle under the roof, height above the wall top at the ridge
178
+ const tri = [[-D / 2, 0], [D / 2, 0], [0, apex]];
179
+ return bySlot([
180
+ [sweepX(chevron, W + 2 * overhang), 'roof'],
181
+ [extrude(shape(tri), T).rotateY(-Math.PI / 2).translate(W / 2, 0, 0), 'wall'],
182
+ [extrude(shape(tri), T).rotateY(Math.PI / 2).translate(-W / 2, 0, 0), 'wall'],
183
+ ]);
184
+ }));
185
+ },
186
+
187
+ /** A flat roof with a parapet and a coping on top */
188
+ flatRoof(p) {
189
+ const { width: W, depth: D, parapet = 0.6, coping = 0.06 } = p;
190
+ return group('flatRoof', memo('flat' + JSON.stringify(p), () => {
191
+ const t = T, c = coping, y = parapet / 2, top = parapet + 0.04;
192
+ return bySlot([
193
+ [box(W - 2 * t, 0.12, D - 2 * t, 0, 0.06, 0), 'roof'],
194
+ [box(W, parapet, t, 0, y, D / 2 - t / 2), 'wall'], [box(W, parapet, t, 0, y, -D / 2 + t / 2), 'wall'],
195
+ [box(t, parapet, D - 2 * t, W / 2 - t / 2, y, 0), 'wall'], [box(t, parapet, D - 2 * t, -W / 2 + t / 2, y, 0), 'wall'],
196
+ [rbox(W + 2 * c, 0.08, t + 2 * c, 0.02, 0, top, D / 2 - t / 2), 'trim'], [rbox(W + 2 * c, 0.08, t + 2 * c, 0.02, 0, top, -D / 2 + t / 2), 'trim'],
197
+ [rbox(t + 2 * c, 0.08, D - 2 * t - 2 * c, 0.02, W / 2 - t / 2, top, 0), 'trim'], [rbox(t + 2 * c, 0.08, D - 2 * t - 2 * c, 0.02, -W / 2 + t / 2, top, 0), 'trim'],
198
+ ]);
199
+ }));
200
+ },
201
+
202
+ /** A striped awning: sloped canvas + valance. The stripes are a gray mask made lazily here; the awning slot's color tints it */
203
+ awning(p) {
204
+ const { width: w = 1.6, depth = 0.9, drop = 0.4, stripes = 7, y = 2.6 } = p;
205
+ const key = 'stripes' + stripes;
206
+ const tex = texCache.get(key) ?? texCache.set(key, stripeTexture(stripes)).get(key);
207
+ const geos = memo('awning' + JSON.stringify(p), () => {
208
+ const len = Math.hypot(depth, drop), ang = Math.atan2(drop, depth);
209
+ const canvas = new THREE.BoxGeometry(w, 0.03, len).translate(0, 0, len / 2).rotateX(ang).translate(0, y, 0);
210
+ const valance = box(w, 0.22, 0.03, 0, y - drop - 0.11, depth);
211
+ return bySlot([[canvas, 'awning'], [valance, 'awning'], [box(0.04, 0.04, depth, -w / 2, y - drop, depth / 2), 'frame'],
212
+ [box(0.04, 0.04, depth, w / 2, y - drop, depth / 2), 'frame']]);
213
+ });
214
+ return group('awning', geos, { awning: tex });
215
+ },
216
+
217
+ /** A sign board with text painted on a canvas (white ground, dark letters: a mask the sign slot's color tints) */
218
+ sign(p) {
219
+ const { text = 'SIGN', width: w = 1.6, height: h = 0.45, y = 3.25 } = p;
220
+ const key = 'sign' + text + w + h;
221
+ const tex = texCache.get(key) ?? texCache.set(key, textTexture(text, w / h)).get(key);
222
+ const geos = memo('sign' + JSON.stringify(p), () => bySlot([
223
+ [rbox(w, h, 0.08, 0.03, 0, y, 0.04), 'sign'],
224
+ [new THREE.PlaneGeometry(w - 0.08, h - 0.08).translate(0, y, 0.081), 'sign:face'],
225
+ ]));
226
+ return group('sign', geos, { 'sign:face': tex });
227
+ },
228
+
229
+ /** A chimney: a rounded column and a wider cap */
230
+ chimney(p) {
231
+ const { width: w = 0.5, height: h = 2 } = p;
232
+ return group('chimney', memo('chimney' + JSON.stringify(p), () => bySlot([
233
+ [rbox(w, h, w, 0.04, 0, h / 2, 0), 'wall'], [rbox(w + 0.12, 0.12, w + 0.12, 0.03, 0, h + 0.06, 0), 'trim']])));
234
+ },
235
+ };
236
+
237
+ // ---- assembler -----------------------------------------------------------------------------------------------------------------------
238
+ const SIDES = ['front', 'right', 'back', 'left'];
239
+ /**
240
+ * A building: footprint W x D cells, floors, a facade pattern per side ('/' separates floors, ground floor first, the last row repeats:
241
+ * 'WDW/WWW'), a roof. Letters: W window, S shop window (window + awning), D door, . blank wall.
242
+ * Each module group carries userData.module = { type, side, floor, i } so tools and tests can find it; the wall slab mesh is named 'wall'.
243
+ */
244
+ function building(p) {
245
+ const { width = 3, depth = 2, floors = 2, roof = 'gable', pitch = 0.6, parapet = 0.6, trim = 'step', window: wv = 0,
246
+ sign = '', chimney = false } = p;
247
+ const W = width * cell, D = depth * cell, H = floors * storey, root = new THREE.Group(), win = windows[wv % windows.length];
248
+ root.name = 'building';
249
+ const facade = { front: p.front ?? 'W'.repeat(width), back: p.back ?? 'W'.repeat(width), left: p.left ?? '.'.repeat(depth), right: p.right ?? '.'.repeat(depth) };
250
+ const place = (g, x, y, z, ry, info) => { g.position.set(x, y, z); g.rotation.y = ry; g.userData.module = info; root.add(g); return g; };
251
+ // where cell i of a side sits, and which way it faces (module space: x along the facade, +z out)
252
+ const frame = (side, i) => {
253
+ const n = side === 'front' || side === 'back' ? width : depth, u = -(n * cell) / 2 + (i + 0.5) * cell;
254
+ return side === 'front' ? [u, D / 2, 0] : side === 'back' ? [-u, -D / 2, Math.PI] : side === 'right' ? [W / 2, -u, Math.PI / 2] : [-W / 2, u, -Math.PI / 2];
255
+ };
256
+ for (const side of SIDES) {
257
+ const rows = facade[side].split('/'), n = side === 'front' || side === 'back' ? width : depth;
258
+ for (const r of rows) if (r.length !== n) throw new Error(`modular kit: facade ${side} row "${r}" has ${r.length} letters, the footprint side has ${n} cells`);
259
+ let signed = false;
260
+ for (let f = 0; f < floors; f++) {
261
+ const row = rows[Math.min(f, rows.length - 1)];
262
+ for (let i = 0; i < n; i++) {
263
+ const ch = row[i], [x, z, ry] = frame(side, i), info = { type: ch, side, floor: f, i };
264
+ if (ch === 'D' && f > 0) throw new Error(`modular kit: a door (D) on floor ${f} of side ${side}; doors go on the ground floor`);
265
+ const g = ch === 'W' ? mod.window(win) : ch === 'S' ? mod.window({ ...win, width: cell * 0.75, height: storey * 0.62, sill: 0.45, planter: false })
266
+ : ch === 'D' ? mod.door({}) : ch === '.' ? mod.wall() : null;
267
+ if (!g) throw new Error(`modular kit: unknown facade letter "${ch}" (W window, S shop window, D door, . wall)`);
268
+ place(g, x, f * storey, z, ry, info);
269
+ if (ch === 'S') place(mod.awning({ width: cell * 0.85, y: storey * 0.88 }), x, f * storey, z, ry, { type: 'awning', side, floor: f, i });
270
+ if (ch === 'D' && sign && !signed && side === 'front') {
271
+ signed = true;
272
+ place(mod.sign({ text: sign, width: cell * 0.8, y: storey * 0.85 }), x, 0, z, ry, { type: 'sign', side, floor: 0, i });
273
+ }
274
+ }
275
+ }
276
+ }
277
+ // pilasters on the four corners of every floor, then trim bands: front/back strips run past the corners by their depth, side strips
278
+ // stop at the wall faces, so the strips touch without overlapping (overlapping coplanar faces would flicker)
279
+ for (let f = 0; f < floors; f++) for (const [x, z] of [[W / 2, D / 2], [-W / 2, D / 2], [W / 2, -D / 2], [-W / 2, -D / 2]]) {
280
+ place(mod.corner({}), x, f * storey, z, 0, { type: 'corner', floor: f });
281
+ }
282
+ if (trim !== 'none') for (let f = 1; f <= floors; f++) {
283
+ const top = f === floors, h = top ? 0.3 : 0.18, d = top ? 0.22 : 0.12, y = f * storey - h;
284
+ for (const side of SIDES) {
285
+ const along = side === 'front' || side === 'back', len = along ? W + 2 * d : D, [, , ry] = frame(side, 0);
286
+ const [x, z] = side === 'front' ? [0, D / 2] : side === 'back' ? [0, -D / 2] : side === 'right' ? [W / 2, 0] : [-W / 2, 0];
287
+ place(mod.trim({ length: len, profile: trim, height: h, depth: d }), x, y, z, ry, { type: 'trim', side, floor: f });
288
+ }
289
+ }
290
+ if (roof === 'gable') {
291
+ place(mod.gable({ width: W, depth: D, pitch }), 0, H, 0, 0, { type: 'roof' });
292
+ if (chimney) place(mod.chimney({ height: D / 2 * pitch + 1.2 }), W / 2 - cell / 2, H, -D / 4, 0, { type: 'chimney' });
293
+ } else if (roof === 'flat') place(mod.flatRoof({ width: W, depth: D, parapet }), 0, H, 0, 0, { type: 'roof' });
294
+ else throw new Error(`modular kit: unknown roof "${roof}" (gable, flat)`);
295
+ root.userData.building = { cells: [width, depth], floors, size: [W, H, D] };
296
+ return root;
297
+ }
298
+
299
+ /**
300
+ * A street: count buildings in a row along +x, front faces on z = 0, each snapped to whole cells with gap cells between them.
301
+ * Variation is seeded and chosen from a few options per trait (floors, width, roof, window variant, trim profile, door spot, shop
302
+ * fronts, sign), so no two neighbours repeat yet geometry stays shared.
303
+ */
304
+ function street(p) {
305
+ const { seed = 1, count = 10, gap = 1, signs = 'BAKERY,BOOKS,CAFE,TOOLS,TEA,HOTEL' } = p;
306
+ const rand = rng(seed), pick = a => a[Math.floor(rand() * a.length)], root = new THREE.Group(), names = signs.split(',').filter(Boolean);
307
+ const trims = Object.keys(profiles);
308
+ root.name = 'street';
309
+ let x = 0;
310
+ for (let b = 0; b < count; b++) {
311
+ const width = pick([2, 3, 3, 4]), depth = pick([2, 3]), floors = pick([1, 2, 2, 3]), roof = rand() < 0.6 ? 'gable' : 'flat';
312
+ const door = Math.floor(rand() * width), shop = rand() < 0.5;
313
+ // upper floors mirror around the middle: a symmetric facade reads as designed, a fully random one as noise
314
+ const half = Array.from({ length: Math.ceil(width / 2) }, () => (rand() < 0.8 ? 'W' : '.'));
315
+ const upper = [...half, ...half.slice(0, Math.floor(width / 2)).reverse()].join('');
316
+ const ground = Array.from({ length: width }, (_, i) => (i === door ? 'D' : shop ? 'S' : 'W')).join('');
317
+ const params = {
318
+ width, depth, floors, roof, pitch: pick([0.5, 0.7]), parapet: pick([0.4, 0.8]), trim: pick(trims), window: Math.floor(rand() * windows.length),
319
+ front: floors > 1 ? `${ground}/${upper}` : ground, back: upper, left: Array.from({ length: depth }, () => (rand() < 0.3 ? 'W' : '.')).join(''),
320
+ right: '.'.repeat(depth), sign: shop && names.length ? pick(names) : '', chimney: roof === 'gable' && rand() < 0.5,
321
+ };
322
+ const g = building(params);
323
+ g.position.set((x + width / 2) * cell, 0, -(depth * cell) / 2); // whole cells: every module edge lands on the grid
324
+ g.userData.params = params;
325
+ root.add(g);
326
+ x += width + gap;
327
+ }
328
+ root.userData.street = { seed, count, length: (x - gap) * cell };
329
+ return root;
330
+ }
331
+
332
+ // ---- manifest entries: { build, params } so threedog gallery, hot swap and the panel's tune work on every piece -----------------------
333
+ // cache: false because the slot materials are live objects of the game, not params (the dev cache would keep a stale material)
334
+ const n = (d, min, max) => ({ type: 'number', default: d, min, max });
335
+ const entry = (build, params) => ({ build, params, cache: false });
336
+ const w0 = windows[0];
337
+ const models = {
338
+ [`${prefix}-wall`]: entry(() => mod.wall(), {}),
339
+ [`${prefix}-window`]: entry(p => mod.window(p), { width: n(w0.width, 0.3, cell - 0.3), height: n(w0.height, 0.4, storey - 0.6), sill: n(w0.sill, 0.2, storey - 1),
340
+ mullions: { type: 'int', default: w0.mullions, min: 0, max: 4 }, planter: { type: 'bool', default: !!w0.planter }, inset: n(0.08, 0, T - 0.04) }),
341
+ [`${prefix}-door`]: entry(p => mod.door(p), { width: n(1, 0.6, cell - 0.4), height: n(2.2, 1.6, storey - 0.4) }),
342
+ [`${prefix}-corner`]: entry(p => mod.corner(p), { size: n(T * 1.6, T, 1) }),
343
+ [`${prefix}-trim`]: entry(p => mod.trim(p), { length: n(cell, 0.5, 20), profile: { type: 'string', default: 'step', values: Object.keys(profiles) },
344
+ height: n(0.25, 0.05, 1), depth: n(0.15, 0.02, 0.6) }),
345
+ [`${prefix}-gable`]: entry(p => mod.gable(p), { width: n(cell * 3, cell, 20), depth: n(cell * 2, cell, 12), pitch: n(0.6, 0.2, 1.5), overhang: n(0.3, 0, 1) }),
346
+ [`${prefix}-flatRoof`]: entry(p => mod.flatRoof(p), { width: n(cell * 3, cell, 20), depth: n(cell * 2, cell, 12), parapet: n(0.6, 0.1, 1.5) }),
347
+ [`${prefix}-awning`]: entry(p => mod.awning(p), { width: n(1.6, 0.5, 6), depth: n(0.9, 0.3, 2), drop: n(0.4, 0, 1), stripes: { type: 'int', default: 7, min: 1, max: 20 } }),
348
+ [`${prefix}-sign`]: entry(p => mod.sign(p), { text: { type: 'string', default: 'SIGN' }, width: n(1.6, 0.4, 6), height: n(0.45, 0.2, 2) }),
349
+ [`${prefix}-chimney`]: entry(p => mod.chimney(p), { width: n(0.5, 0.2, 1.5), height: n(2, 0.5, 5) }),
350
+ [`${prefix}-building`]: entry(p => building(p), {
351
+ width: { type: 'int', default: 3, min: 1, max: 8 }, depth: { type: 'int', default: 2, min: 1, max: 6 }, floors: { type: 'int', default: 2, min: 1, max: 8 },
352
+ roof: { type: 'string', default: 'gable', values: ['gable', 'flat'] }, pitch: n(0.6, 0.2, 1.5), parapet: n(0.6, 0.1, 1.5),
353
+ trim: { type: 'string', default: 'step', values: [...Object.keys(profiles), 'none'] }, window: { type: 'int', default: 0, min: 0, max: windows.length - 1 },
354
+ front: { type: 'string', default: 'SDS/WWW' }, back: { type: 'string', default: 'W.W' }, left: { type: 'string', default: '.W' }, right: { type: 'string', default: '..' },
355
+ sign: { type: 'string', default: 'SHOP' }, chimney: { type: 'bool', default: true },
356
+ }),
357
+ [`${prefix}-street`]: entry(p => street(p), { seed: { type: 'int', default: 1, min: 0, max: 99999 }, count: { type: 'int', default: 10, min: 1, max: 40 },
358
+ gap: { type: 'int', default: 1, min: 0, max: 4 }, signs: { type: 'string', default: 'BAKERY,BOOKS,CAFE,TOOLS,TEA,HOTEL' } }),
359
+ };
360
+
361
+ /**
362
+ * Merge a finished, static group into one mesh per material (world transforms baked in): the fewest draw calls (one per slot), at the price
363
+ * of culling (the whole merged mesh is drawn when any part is on screen) and of editing single pieces later. The input is left as it was.
364
+ * @param {THREE.Object3D} root
365
+ */
366
+ function merge(root) {
367
+ root.updateWorldMatrix(true, true);
368
+ const byMat = new Map(), out = new THREE.Group();
369
+ root.traverse(o => {
370
+ const m = /** @type {THREE.Mesh} */ (o);
371
+ if (!m.isMesh) return;
372
+ const g = (m.geometry.index ? m.geometry.toNonIndexed() : m.geometry.clone()).applyMatrix4(m.matrixWorld);
373
+ for (const k of Object.keys(g.attributes)) if (!['position', 'normal', 'uv', 'color'].includes(k)) g.deleteAttribute(k);
374
+ g.clearGroups();
375
+ (byMat.get(m.material) ?? byMat.set(m.material, []).get(m.material)).push(g);
376
+ });
377
+ for (const [mat, list] of byMat) {
378
+ const mesh = new THREE.Mesh(mergeGeometries(list), mat);
379
+ mesh.castShadow = mesh.receiveShadow = true;
380
+ out.add(mesh);
381
+ for (const g of list) g.dispose();
382
+ }
383
+ out.name = root.name + '-merged';
384
+ return out;
385
+ }
386
+
387
+ return {
388
+ /** asset pack: engine.assets.manifest(kit.pack) */
389
+ pack: { name: `${prefix}-kit`, models },
390
+ modules: mod, building, street, merge, cell, storey, wall: T, slots,
391
+ /** shared geometries made so far (each module + params once) */
392
+ get geometries() { return geoCache.size; },
393
+ /** Free every geometry, texture and textured material the kit made (the slot materials are the game's and stay) */
394
+ dispose() {
395
+ for (const g of geoCache.values()) for (const x of Object.values(g)) x.dispose();
396
+ for (const t of texCache.values()) t.dispose();
397
+ for (const m of matCache.values()) m.dispose();
398
+ geoCache.clear(); texCache.clear(); matCache.clear();
399
+ },
400
+ };
401
+ }
402
+
403
+ /** Vertical stripes, white and light gray: a luminance mask (the material's color supplies the hue) */
404
+ function stripeTexture(stripes) {
405
+ const c = document.createElement('canvas'); c.width = stripes * 2 * 8; c.height = 8;
406
+ const x = /** @type {CanvasRenderingContext2D} */ (c.getContext('2d'));
407
+ for (let i = 0; i < stripes * 2; i++) { x.fillStyle = i % 2 ? '#bdbdbd' : '#ffffff'; x.fillRect(i * 8, 0, 8, 8); }
408
+ const t = new THREE.CanvasTexture(c);
409
+ t.colorSpace = THREE.SRGBColorSpace; t.magFilter = THREE.NearestFilter; // crisp stripe edges up close
410
+ return t;
411
+ }
412
+ /** Text centered on white, sized to fill the board */
413
+ function textTexture(text, aspect) {
414
+ const h = 64, c = document.createElement('canvas'); c.width = Math.round(h * aspect); c.height = h;
415
+ const x = /** @type {CanvasRenderingContext2D} */ (c.getContext('2d'));
416
+ x.fillStyle = '#ffffff'; x.fillRect(0, 0, c.width, h);
417
+ x.fillStyle = '#262626'; x.textAlign = 'center'; x.textBaseline = 'middle';
418
+ let size = h * 0.62;
419
+ x.font = `bold ${size}px sans-serif`;
420
+ const fit = x.measureText(text).width;
421
+ if (fit > c.width * 0.9) { size *= (c.width * 0.9) / fit; x.font = `bold ${size}px sans-serif`; }
422
+ x.fillText(text, c.width / 2, h / 2);
423
+ const t = new THREE.CanvasTexture(c);
424
+ t.colorSpace = THREE.SRGBColorSpace; t.anisotropy = 4;
425
+ return t;
426
+ }
@@ -0,0 +1,39 @@
1
+ // @ts-check
2
+ // Modular building demo (page /modular-building.html): one seeded street from kit.js, drawn with one of three material sets.
3
+ // URL: ?set=gray|warm|cool (gray = the block-out, the default) &seed=1 &count=10 &view=street|close &batch=0 (draw every piece on its own) | merge (kit.merge: one mesh per material).
4
+ // The two coloured sets exist to show the kit is style-free: same seed, same shapes, other slots and trim profiles. They are demo values,
5
+ // not a recommended picture. Test page for tests/specs/modular-building.mjs: window.mbTest = { kit, street, createModularKit, bakeVertexAO, THREE }.
6
+ // Shapes only here; the whole picture is picture/.
7
+ import { createEngine, fixedCamera, bakeVertexAO, THREE } from 'threedog';
8
+ import { createModularKit, PROFILES } from './kit.js';
9
+ import { createPicture } from './picture/index.js';
10
+
11
+ const url = new URLSearchParams(location.search);
12
+ const set = url.get('set') ?? 'gray', seed = Number(url.get('seed') ?? 1), count = Number(url.get('count') ?? 10);
13
+ const engine = createEngine({ canvas: /** @type {HTMLCanvasElement} */ (document.getElementById('view')), lights: false, ui: { loading: false }, saveKey: 'threedog-modular-building',
14
+ batching: url.get('batch') === '0' || url.get('batch') === 'merge' ? false : undefined });
15
+ const { mat: { ground: groundMat, ...slots } } = createPicture(engine, { set });
16
+
17
+ // a style swaps trim profiles too: same names (so a seed picks the same trim slot), other cross-sections. Hard-edged for the cool set
18
+ const cutProfiles = { flat: PROFILES.flat, step: [[0, 0], [1, 0], [1, 0.35], [0.4, 0.35], [0.4, 1], [0, 1]], cove: [[0, 0], [0.6, 0], [1, 0.4], [1, 1], [0, 1]] };
19
+ const kit = createModularKit({ slots, profiles: set === 'cool' ? cutProfiles : PROFILES });
20
+ engine.assets.manifest(kit.pack); // every module, a building and the street, by name: threedog gallery, hot swap, ?panel=1 tuning
21
+
22
+ const ground = new THREE.Mesh(new THREE.PlaneGeometry(400, 400), groundMat);
23
+ ground.rotation.x = -Math.PI / 2; ground.receiveShadow = true;
24
+ engine.scene.add(ground);
25
+
26
+ const shots = /** @type {any} */ ({
27
+ street: { position: [-9, 10, 22], lookAt: [22, 3, -4], fov: 50 },
28
+ close: { position: [3, 4.5, 11], lookAt: [6, 3.2, -2], fov: 45 },
29
+ });
30
+ engine.use(fixedCamera({ shots, start: url.get('view') ?? 'street' }));
31
+
32
+ // built directly here so the URL can pick the seed; a game names it in content instead: { model: ['mb-street', { seed: 7 }], x: 0, z: 0 }
33
+ const built = kit.street({ seed, count });
34
+ built.userData.batch = true; // opt in to engine.batching before adding: identical module meshes become one InstancedMesh per cell
35
+ const street = url.get('batch') === 'merge' ? kit.merge(built) : built;
36
+ engine.scene.add(street);
37
+
38
+ Object.assign(window, { engine, mbTest: { kit, street, createModularKit, bakeVertexAO, THREE } });
39
+ engine.start();
@@ -0,0 +1,17 @@
1
+ // @ts-check
2
+ // The picture of the modular-building demo: wiring only.
3
+ import { THREE } from 'threedog';
4
+ import { BACKGROUND, EXPOSURE, TONE_MAPPING } from './palette.js';
5
+ import { createLights } from './lights.js';
6
+ import { createMaterials } from './materials.js';
7
+
8
+ /** Returns { mat, sun, hemi }. @param {any} engine @param {{ set: string }} o */
9
+ export function createPicture(engine, o) {
10
+ engine.renderer.toneMapping = TONE_MAPPING;
11
+ engine.renderer.toneMappingExposure = EXPOSURE;
12
+ engine.scene.background = new THREE.Color(BACKGROUND);
13
+ const lights = createLights(engine), { mat } = createMaterials(o.set);
14
+ // onRender, not onFrame: engine.focus is this frame's only after the camera module ran
15
+ engine.onRender(() => lights.update());
16
+ return { mat, sun: lights.sun, hemi: lights.hemi };
17
+ }