threedog 0.0.0-stage → 0.2.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 (506) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/LICENSE +21 -0
  3. package/README.md +39 -2
  4. package/core/Animator.js +268 -0
  5. package/core/Assets.js +256 -0
  6. package/core/Audio.js +267 -0
  7. package/core/Baked.js +72 -0
  8. package/core/Batching.js +247 -0
  9. package/core/Budget.js +221 -0
  10. package/core/Clock.js +94 -0
  11. package/core/Commits.js +77 -0
  12. package/core/DebugOverrides.js +143 -0
  13. package/core/Describe.js +145 -0
  14. package/core/Engine.js +184 -0
  15. package/core/Events.js +153 -0
  16. package/core/I18n.js +94 -0
  17. package/core/Input.js +245 -0
  18. package/core/Inspect.js +77 -0
  19. package/core/InspectScene.js +191 -0
  20. package/core/Jobs.js +146 -0
  21. package/core/Loading.js +149 -0
  22. package/core/MaterialInfo.js +32 -0
  23. package/core/Ops.js +256 -0
  24. package/core/Random.js +52 -0
  25. package/core/Rays.js +160 -0
  26. package/core/SaveStore.js +85 -0
  27. package/core/Saves.js +254 -0
  28. package/core/Stream.js +279 -0
  29. package/core/Threads.js +158 -0
  30. package/core/UrlState.js +94 -0
  31. package/core/Vars.js +35 -0
  32. package/core/Views.js +49 -0
  33. package/core/actor.js +23 -0
  34. package/core/assetEntry.js +89 -0
  35. package/core/assetLoad.js +190 -0
  36. package/core/assetManifest.js +35 -0
  37. package/core/assetReport.js +83 -0
  38. package/core/audioRules.js +121 -0
  39. package/core/audioVoice.js +225 -0
  40. package/core/batchGroups.js +116 -0
  41. package/core/canvasBox.js +63 -0
  42. package/core/catalog.js +169 -0
  43. package/core/checks.js +67 -0
  44. package/core/claims.js +51 -0
  45. package/core/dayTime.js +15 -0
  46. package/core/debugView.js +76 -0
  47. package/core/describeRender.js +45 -0
  48. package/core/describeText.js +143 -0
  49. package/core/easing.js +34 -0
  50. package/core/errorCodes.js +205 -0
  51. package/core/errorHints.js +208 -0
  52. package/core/errors.js +40 -0
  53. package/core/events.generated.js +84 -0
  54. package/core/ground.js +102 -0
  55. package/core/holds.js +106 -0
  56. package/core/inputContext.js +69 -0
  57. package/core/inputDefaults.js +22 -0
  58. package/core/inputPad.js +35 -0
  59. package/core/inputPointer.js +48 -0
  60. package/core/inputTouch.js +48 -0
  61. package/core/lifecycle.js +69 -0
  62. package/core/lightWatch.js +56 -0
  63. package/core/look/coreParts.js +112 -0
  64. package/core/look/layers.js +136 -0
  65. package/core/look/part.js +173 -0
  66. package/core/look/report.js +79 -0
  67. package/core/look/write.js +86 -0
  68. package/core/loop.js +200 -0
  69. package/core/math.js +33 -0
  70. package/core/modules.js +196 -0
  71. package/core/movement.js +19 -0
  72. package/core/mulberry32.js +14 -0
  73. package/core/opsAtomic.js +31 -0
  74. package/core/opsCheck.js +97 -0
  75. package/core/opsFail.js +20 -0
  76. package/core/opsGuard.js +26 -0
  77. package/core/opsHistory.js +27 -0
  78. package/core/opsRun.js +77 -0
  79. package/core/page.js +78 -0
  80. package/core/params.js +132 -0
  81. package/core/pureWorker.js +5 -0
  82. package/core/renamed.js +21 -0
  83. package/core/saveApply.js +128 -0
  84. package/core/saveFiles.js +139 -0
  85. package/core/saveIds.js +53 -0
  86. package/core/saveVersions.js +97 -0
  87. package/core/scatter.js +92 -0
  88. package/core/sceneMethods.js +100 -0
  89. package/core/screenToGround.js +39 -0
  90. package/core/services.js +73 -0
  91. package/core/session.js +171 -0
  92. package/core/shadowTypes.js +15 -0
  93. package/core/skip.js +104 -0
  94. package/core/startup.js +135 -0
  95. package/core/streamCells.js +24 -0
  96. package/core/streamSources.js +73 -0
  97. package/core/styleParts.js +96 -0
  98. package/core/targeting.js +64 -0
  99. package/core/thingExplain.js +68 -0
  100. package/core/thingOps.js +168 -0
  101. package/core/things.js +212 -0
  102. package/core/threadPure.js +120 -0
  103. package/core/threadServe.js +25 -0
  104. package/core/tier.js +11 -0
  105. package/core/util.js +11 -0
  106. package/core/validate.js +204 -0
  107. package/docs/AI.md +123 -0
  108. package/docs/API.md +83 -0
  109. package/docs/CODEMAP.md +347 -0
  110. package/docs/COMMANDS.md +108 -0
  111. package/docs/CONVENTIONS.md +145 -0
  112. package/docs/PERF.md +217 -0
  113. package/docs/THREE.md +86 -0
  114. package/docs/api/ambience.md +15 -0
  115. package/docs/api/assets.md +62 -0
  116. package/docs/api/audio.md +53 -0
  117. package/docs/api/budget.md +40 -0
  118. package/docs/api/cameraRig.md +120 -0
  119. package/docs/api/characters.md +144 -0
  120. package/docs/api/clock.md +7 -0
  121. package/docs/api/collision.md +39 -0
  122. package/docs/api/content.md +64 -0
  123. package/docs/api/dialogue.md +39 -0
  124. package/docs/api/engine.md +199 -0
  125. package/docs/api/entities.md +61 -0
  126. package/docs/api/events.md +95 -0
  127. package/docs/api/flow.md +27 -0
  128. package/docs/api/grids.md +11 -0
  129. package/docs/api/ground.md +16 -0
  130. package/docs/api/hlod.md +34 -0
  131. package/docs/api/hud.md +31 -0
  132. package/docs/api/i18n.md +10 -0
  133. package/docs/api/input.md +24 -0
  134. package/docs/api/interactions.md +31 -0
  135. package/docs/api/inventory.md +66 -0
  136. package/docs/api/jobs.md +10 -0
  137. package/docs/api/level.md +41 -0
  138. package/docs/api/lightPool.md +56 -0
  139. package/docs/api/music.md +34 -0
  140. package/docs/api/nav.md +26 -0
  141. package/docs/api/net.md +14 -0
  142. package/docs/api/openWorld.md +24 -0
  143. package/docs/api/particles.md +41 -0
  144. package/docs/api/photo.md +15 -0
  145. package/docs/api/post.md +10 -0
  146. package/docs/api/quests.md +36 -0
  147. package/docs/api/rays.md +26 -0
  148. package/docs/api/rigid.md +84 -0
  149. package/docs/api/saves.md +32 -0
  150. package/docs/api/settings.md +36 -0
  151. package/docs/api/sky.md +58 -0
  152. package/docs/api/stream.md +31 -0
  153. package/docs/api/style.md +134 -0
  154. package/docs/api/terrain.md +34 -0
  155. package/docs/api/timeline.md +39 -0
  156. package/docs/api/tools.md +57 -0
  157. package/docs/api/triggers.md +56 -0
  158. package/docs/api/vars.md +9 -0
  159. package/docs/api/vegetation.md +52 -0
  160. package/docs/api/water.md +48 -0
  161. package/docs/api/weather.md +29 -0
  162. package/docs/api/world.md +30 -0
  163. package/docs/recipes/01-new-game.md +148 -0
  164. package/docs/recipes/02-npc.md +167 -0
  165. package/docs/recipes/03-items-pickups.md +158 -0
  166. package/docs/recipes/04-quests.md +83 -0
  167. package/docs/recipes/05-props-bake.md +159 -0
  168. package/docs/recipes/06-clock-events.md +117 -0
  169. package/docs/recipes/07-flow-scenes-pause.md +132 -0
  170. package/docs/recipes/08-weather-sky.md +74 -0
  171. package/docs/recipes/09-style-pack.md +234 -0
  172. package/docs/recipes/10-blender-level.md +67 -0
  173. package/docs/recipes/11-vehicles.md +55 -0
  174. package/docs/recipes/12-navmesh.md +79 -0
  175. package/docs/recipes/13-animation.md +149 -0
  176. package/docs/recipes/14-custom-module.md +91 -0
  177. package/docs/recipes/15-perf.md +78 -0
  178. package/docs/recipes/16-dev-bridge.md +180 -0
  179. package/docs/recipes/18-world.md +185 -0
  180. package/docs/recipes/19-shooting-picking.md +76 -0
  181. package/docs/recipes/20-content-actions-save.md +176 -0
  182. package/docs/recipes/21-camera.md +153 -0
  183. package/docs/recipes/22-shop-gold.md +107 -0
  184. package/docs/recipes/23-ops.md +175 -0
  185. package/docs/recipes/26-ui-parts.md +138 -0
  186. package/docs/recipes/27-net.md +96 -0
  187. package/docs/recipes/28-terrain.md +80 -0
  188. package/docs/recipes/29-grid.md +87 -0
  189. package/docs/recipes/30-templates.md +131 -0
  190. package/docs/recipes/31-audio.md +126 -0
  191. package/docs/recipes/32-action-game.md +33 -0
  192. package/docs/recipes/33-stream-sources.md +37 -0
  193. package/docs/recipes/34-environment-lighting.md +36 -0
  194. package/docs/recipes/35-style-from-reference.md +89 -0
  195. package/docs/recipes/36-sky-ground-plant-looks.md +116 -0
  196. package/docs/recipes/37-terrain-look-hooks.md +97 -0
  197. package/docs/recipes/38-environment-look-hooks.md +83 -0
  198. package/docs/recipes/40-scene.md +108 -0
  199. package/docs/recipes/41-thing-registry.md +93 -0
  200. package/docs/recipes/42-terrain-shape.md +64 -0
  201. package/docs/recipes/43-shader-patches-surface-looks.md +120 -0
  202. package/docs/recipes/44-water-weather-look-hooks.md +135 -0
  203. package/docs/recipes/45-cascaded-shadows.md +51 -0
  204. package/docs/recipes/46-blender-art-route.md +114 -0
  205. package/docs/recipes/47-island-snow-backdrop.md +44 -0
  206. package/docs/recipes/48-make-material.md +70 -0
  207. package/docs/recipes/49-game-module-contract.md +71 -0
  208. package/docs/recipes/50-own-renderer.md +12 -0
  209. package/docs/recipes/51-capability-catalog.md +63 -0
  210. package/docs/recipes/52-look.md +108 -0
  211. package/examples/action/DESIGN.md +3 -0
  212. package/examples/action/GAMEMAP.md +127 -0
  213. package/examples/action/content/actions.js +8 -0
  214. package/examples/action/content/audio.js +9 -0
  215. package/examples/action/content/index.js +10 -0
  216. package/examples/action/content/items.js +4 -0
  217. package/examples/action/content/places.js +4 -0
  218. package/examples/action/content/props.js +11 -0
  219. package/examples/action/content/templates.js +10 -0
  220. package/examples/action/content/views.js +6 -0
  221. package/examples/action/look.js +5 -0
  222. package/examples/action/main.js +137 -0
  223. package/examples/action/models.js +25 -0
  224. package/examples/sheepisland/GAMEMAP.md +107 -0
  225. package/examples/sheepisland/content/index.js +6 -0
  226. package/examples/sheepisland/content/props.js +19 -0
  227. package/examples/sheepisland/content/templates.js +5 -0
  228. package/examples/sheepisland/content/vegetation.js +8 -0
  229. package/examples/sheepisland/main.js +71 -0
  230. package/examples/sheepisland/params.js +25 -0
  231. package/examples/sheepisland/style/index.js +79 -0
  232. package/examples/sheepisland/style/models.js +59 -0
  233. package/examples/sheepisland/views.js +9 -0
  234. package/examples/styletest/GAMEMAP.md +135 -0
  235. package/examples/styletest/content/index.js +9 -0
  236. package/examples/styletest/content/items.js +8 -0
  237. package/examples/styletest/content/npcs.js +8 -0
  238. package/examples/styletest/content/places.js +5 -0
  239. package/examples/styletest/content/props.js +16 -0
  240. package/examples/styletest/content/templates.js +9 -0
  241. package/examples/styletest/content/vegetation.js +31 -0
  242. package/examples/styletest/look.js +11 -0
  243. package/examples/styletest/main.js +95 -0
  244. package/examples/styletest/models.js +87 -0
  245. package/examples/styletest/overrides.js +33 -0
  246. package/examples/styletest/panel.js +135 -0
  247. package/examples/styletest/params.js +32 -0
  248. package/examples/styletest/views.js +31 -0
  249. package/examples/world/DESIGN.md +5 -0
  250. package/examples/world/GAMEMAP.md +171 -0
  251. package/examples/world/content/actions.js +8 -0
  252. package/examples/world/content/audio.js +25 -0
  253. package/examples/world/content/bodies.js +12 -0
  254. package/examples/world/content/containers.js +4 -0
  255. package/examples/world/content/dialogues.js +33 -0
  256. package/examples/world/content/index.js +17 -0
  257. package/examples/world/content/items.js +10 -0
  258. package/examples/world/content/npcs.js +14 -0
  259. package/examples/world/content/pickups.js +11 -0
  260. package/examples/world/content/places.js +6 -0
  261. package/examples/world/content/props.js +12 -0
  262. package/examples/world/content/quests.js +15 -0
  263. package/examples/world/content/rules.js +23 -0
  264. package/examples/world/content/templates.js +5 -0
  265. package/examples/world/content/vegetation.js +32 -0
  266. package/examples/world/main.js +168 -0
  267. package/examples/world/models.js +28 -0
  268. package/index.d.ts +306 -0
  269. package/index.js +122 -0
  270. package/llms.txt +61 -0
  271. package/modules/ambience/Ambience.js +186 -0
  272. package/modules/camera/FirstPersonCamera.js +131 -0
  273. package/modules/camera/FixedCamera.js +162 -0
  274. package/modules/camera/FollowCamera.js +91 -0
  275. package/modules/camera/RtsCamera.js +132 -0
  276. package/modules/camera/common.js +182 -0
  277. package/modules/camera/index.js +11 -0
  278. package/modules/camera/projection.js +34 -0
  279. package/modules/characters/Character.js +235 -0
  280. package/modules/characters/NPC.js +242 -0
  281. package/modules/characters/assetModel.js +42 -0
  282. package/modules/characters/astar.js +66 -0
  283. package/modules/characters/behaviors.js +72 -0
  284. package/modules/characters/footsteps.js +13 -0
  285. package/modules/characters/index.js +215 -0
  286. package/modules/characters/moveHelpers.js +29 -0
  287. package/modules/characters/movers/common.js +62 -0
  288. package/modules/characters/movers/rapier.js +74 -0
  289. package/modules/characters/movers/simple.js +43 -0
  290. package/modules/characters/npcAvoid.js +129 -0
  291. package/modules/characters/npcSim.js +150 -0
  292. package/modules/characters/npcView.js +42 -0
  293. package/modules/characters/pathAsync.js +113 -0
  294. package/modules/characters/pathJob.js +62 -0
  295. package/modules/characters/pathWorker.js +7 -0
  296. package/modules/characters/playerStrings.js +12 -0
  297. package/modules/characters/proceduralRig.js +58 -0
  298. package/modules/characters/useModel.js +22 -0
  299. package/modules/characters/walkTo.js +58 -0
  300. package/modules/collision/Collision.js +274 -0
  301. package/modules/collision/grid.js +63 -0
  302. package/modules/content/explain.js +13 -0
  303. package/modules/content/ids.js +95 -0
  304. package/modules/content/index.js +154 -0
  305. package/modules/content/loader.js +190 -0
  306. package/modules/content/models.js +69 -0
  307. package/modules/content/packs.js +69 -0
  308. package/modules/content/props.js +89 -0
  309. package/modules/content/rules.js +134 -0
  310. package/modules/content/templates.js +189 -0
  311. package/modules/debug/DebugPanel.js +174 -0
  312. package/modules/entities/Entities.js +243 -0
  313. package/modules/entities/build.js +25 -0
  314. package/modules/entities/index.js +4 -0
  315. package/modules/flow/index.js +101 -0
  316. package/modules/gameplay/Container.js +227 -0
  317. package/modules/gameplay/Containers.js +89 -0
  318. package/modules/gameplay/Dialogue.js +219 -0
  319. package/modules/gameplay/Interactions.js +253 -0
  320. package/modules/gameplay/Inventory.js +224 -0
  321. package/modules/gameplay/Quests.js +205 -0
  322. package/modules/gameplay/boxOps.js +60 -0
  323. package/modules/gameplay/dialogueBox.js +48 -0
  324. package/modules/gameplay/interactionPrompt.js +28 -0
  325. package/modules/gameplay/inventoryOps.js +137 -0
  326. package/modules/gameplay/pickups.js +115 -0
  327. package/modules/gameplay/questLog.js +54 -0
  328. package/modules/gameplay/questSave.js +71 -0
  329. package/modules/grid/Grid.js +184 -0
  330. package/modules/grid/Layer.js +142 -0
  331. package/modules/grid/index.js +236 -0
  332. package/modules/grid/ops.js +73 -0
  333. package/modules/grid/preview.js +85 -0
  334. package/modules/grid/tiles.js +79 -0
  335. package/modules/hlod/index.js +167 -0
  336. package/modules/hud/index.js +167 -0
  337. package/modules/hud/parts.js +80 -0
  338. package/modules/level/geometry.js +46 -0
  339. package/modules/level/heightfield.js +160 -0
  340. package/modules/level/index.js +233 -0
  341. package/modules/level/nodes.js +84 -0
  342. package/modules/lights/index.js +227 -0
  343. package/modules/music/Music.js +294 -0
  344. package/modules/music/index.js +2 -0
  345. package/modules/music/rules.js +28 -0
  346. package/modules/nav/index.js +156 -0
  347. package/modules/nav/navPath.js +17 -0
  348. package/modules/net/Client.js +137 -0
  349. package/modules/net/Host.js +117 -0
  350. package/modules/net/Net.js +49 -0
  351. package/modules/net/index.js +77 -0
  352. package/modules/net/sync.js +114 -0
  353. package/modules/net/transports.js +118 -0
  354. package/modules/particles/Particles.js +179 -0
  355. package/modules/particles/effect.js +112 -0
  356. package/modules/particles/shaders.js +28 -0
  357. package/modules/photo/Photo.js +146 -0
  358. package/modules/rigid/RigidBodies.js +265 -0
  359. package/modules/rigid/Vehicles.js +97 -0
  360. package/modules/rigid/sync.js +158 -0
  361. package/modules/settings/Settings.js +297 -0
  362. package/modules/settings/apply.js +21 -0
  363. package/modules/settings/index.js +3 -0
  364. package/modules/settings/sections.js +156 -0
  365. package/modules/settings/strings.js +53 -0
  366. package/modules/settings/view.js +65 -0
  367. package/modules/sky/Sky.js +259 -0
  368. package/modules/sky/calendar.js +80 -0
  369. package/modules/sky/cascades.js +125 -0
  370. package/modules/sky/clouds.js +79 -0
  371. package/modules/sky/domeLayers.js +33 -0
  372. package/modules/sky/environment.js +141 -0
  373. package/modules/sky/fog.js +139 -0
  374. package/modules/sky/frame.js +77 -0
  375. package/modules/sky/layers.js +69 -0
  376. package/modules/sky/look.js +51 -0
  377. package/modules/sky/lookFog.js +80 -0
  378. package/modules/sky/lookShadow.js +50 -0
  379. package/modules/sky/lookSky.js +108 -0
  380. package/modules/sky/schedule.js +80 -0
  381. package/modules/sky/shader.js +96 -0
  382. package/modules/sky/shadow.js +74 -0
  383. package/modules/sky/skyModule.js +60 -0
  384. package/modules/terrain/ChunkManager.js +260 -0
  385. package/modules/terrain/chunkJob.js +19 -0
  386. package/modules/terrain/chunkLevels.js +40 -0
  387. package/modules/terrain/chunkQueries.js +42 -0
  388. package/modules/terrain/chunkWorker.js +5 -0
  389. package/modules/terrain/index.js +118 -0
  390. package/modules/terrain/lookGround.js +61 -0
  391. package/modules/terrain/mountTerrain.js +32 -0
  392. package/modules/terrain/terrainColorMap.js +41 -0
  393. package/modules/terrain/terrainDefaults.js +39 -0
  394. package/modules/terrain/terrainEdit.js +139 -0
  395. package/modules/terrain/terrainGen.js +155 -0
  396. package/modules/terrain/terrainIsland.js +131 -0
  397. package/modules/terrain/terrainMesh.js +92 -0
  398. package/modules/terrain/terrainShape.js +108 -0
  399. package/modules/terrain/terrainShapeMain.js +41 -0
  400. package/modules/terrain/terrainTexture.js +44 -0
  401. package/modules/timeline/Timeline.js +253 -0
  402. package/modules/timeline/Tween.js +114 -0
  403. package/modules/timeline/letterbox.js +24 -0
  404. package/modules/timeline/shots.js +90 -0
  405. package/modules/triggers/index.js +268 -0
  406. package/modules/vegetation/Vegetation.js +256 -0
  407. package/modules/vegetation/groundChunks.js +177 -0
  408. package/modules/vegetation/index.js +43 -0
  409. package/modules/vegetation/lookWind.js +37 -0
  410. package/modules/vegetation/modelGeometry.js +21 -0
  411. package/modules/water/Water.js +160 -0
  412. package/modules/water/look.js +80 -0
  413. package/modules/water/surface.js +88 -0
  414. package/modules/weather/Weather.js +242 -0
  415. package/modules/weather/look.js +75 -0
  416. package/modules/weather/particles.js +92 -0
  417. package/modules/weather/shaders.js +49 -0
  418. package/modules/weather/strings.js +15 -0
  419. package/modules/world/World.js +231 -0
  420. package/modules/world/cells.js +42 -0
  421. package/modules/world/explain.js +11 -0
  422. package/modules/world/index.js +71 -0
  423. package/modules/world/persist.js +107 -0
  424. package/modules/world/pos.js +20 -0
  425. package/modules/world/records.js +89 -0
  426. package/modules/world/sim.js +175 -0
  427. package/modules/world/simFar.js +82 -0
  428. package/modules/world/state.js +115 -0
  429. package/modules/world/thingSource.js +44 -0
  430. package/modules/world/views.js +182 -0
  431. package/package.json +66 -4
  432. package/presets.js +96 -0
  433. package/render/PostFX.js +240 -0
  434. package/render/detail.js +105 -0
  435. package/render/effects.js +144 -0
  436. package/render/engineUniforms.js +23 -0
  437. package/render/fuse.js +84 -0
  438. package/render/lighting.js +100 -0
  439. package/render/lights.js +18 -0
  440. package/render/lookSurface.js +161 -0
  441. package/render/materials.js +220 -0
  442. package/render/patches.js +252 -0
  443. package/render/postLook.js +86 -0
  444. package/render/surface.js +69 -0
  445. package/render/uniformDecl.js +29 -0
  446. package/types/common.d.ts +34 -0
  447. package/types/core.d.ts +1965 -0
  448. package/types/gameplay.d.ts +1822 -0
  449. package/types/generated/core/Audio.d.ts +200 -0
  450. package/types/generated/core/Batching.d.ts +47 -0
  451. package/types/generated/core/Budget.d.ts +90 -0
  452. package/types/generated/core/Commits.d.ts +31 -0
  453. package/types/generated/core/DebugOverrides.d.ts +52 -0
  454. package/types/generated/core/Events.d.ts +89 -0
  455. package/types/generated/core/I18n.d.ts +30 -0
  456. package/types/generated/core/Input.d.ts +118 -0
  457. package/types/generated/core/Jobs.d.ts +41 -0
  458. package/types/generated/core/Ops.d.ts +203 -0
  459. package/types/generated/core/Random.d.ts +49 -0
  460. package/types/generated/core/Rays.d.ts +49 -0
  461. package/types/generated/core/Saves.d.ts +162 -0
  462. package/types/generated/core/Stream.d.ts +93 -0
  463. package/types/generated/core/Threads.d.ts +82 -0
  464. package/types/generated/core/Views.d.ts +33 -0
  465. package/types/generated/core/audioVoice.d.ts +47 -0
  466. package/types/generated/core/page.d.ts +18 -0
  467. package/types/generated/core/session.d.ts +48 -0
  468. package/types/generated/modules/ambience/Ambience.d.ts +48 -0
  469. package/types/generated/modules/debug/DebugPanel.d.ts +24 -0
  470. package/types/generated/modules/flow/index.d.ts +10 -0
  471. package/types/generated/modules/grid/Grid.d.ts +151 -0
  472. package/types/generated/modules/grid/Layer.d.ts +65 -0
  473. package/types/generated/modules/grid/index.d.ts +86 -0
  474. package/types/generated/modules/hlod/index.d.ts +11 -0
  475. package/types/generated/modules/hud/index.d.ts +10 -0
  476. package/types/generated/modules/lights/index.d.ts +13 -0
  477. package/types/generated/modules/music/Music.d.ts +111 -0
  478. package/types/generated/modules/net/Net.d.ts +34 -0
  479. package/types/generated/modules/net/index.d.ts +53 -0
  480. package/types/generated/modules/net/transports.d.ts +58 -0
  481. package/types/generated/modules/particles/Particles.d.ts +69 -0
  482. package/types/generated/modules/sky/Sky.d.ts +145 -0
  483. package/types/generated/modules/sky/skyModule.d.ts +10 -0
  484. package/types/generated/modules/timeline/Timeline.d.ts +51 -0
  485. package/types/generated/modules/water/Water.d.ts +29 -0
  486. package/types/generated/modules/weather/Weather.d.ts +62 -0
  487. package/types/generated/modules/world/World.d.ts +242 -0
  488. package/types/generated/modules/world/index.d.ts +15 -0
  489. package/types/generated/render/PostFX.d.ts +125 -0
  490. package/types/generated/render/materials.d.ts +100 -0
  491. package/types/generated/render/patches.d.ts +41 -0
  492. package/types/generated/ui/Focus.d.ts +11 -0
  493. package/types/generated/ui/LoadingScreen.d.ts +2 -0
  494. package/types/generated/ui/UI.d.ts +57 -0
  495. package/types/nav.d.ts +52 -0
  496. package/types/physics.d.ts +592 -0
  497. package/types/style.d.ts +638 -0
  498. package/types/worker.d.ts +11 -0
  499. package/types/world.d.ts +772 -0
  500. package/ui/Focus.js +51 -0
  501. package/ui/LoadingScreen.js +42 -0
  502. package/ui/Parts.js +199 -0
  503. package/ui/UI.js +167 -0
  504. package/ui/defaults.js +85 -0
  505. package/ui/theme.js +124 -0
  506. package/ui/touchPart.js +49 -0
package/core/Audio.js ADDED
@@ -0,0 +1,267 @@
1
+ // Audio core: buses (master, music, sfx, ambience, ui + the game's own), sounds by name, ducking, and the condition table for rule lists.
2
+ // Sounds are the game's: createEngine({ audio: { sounds, ambience, music, footsteps, levels } }) or a content pack's audio table (contentPack,
3
+ // audioRules.js), merged into engine.audio.config. The engine ships none and plays nothing the game did not ask for: modules register built-in
4
+ // synths with { builtIn: true }, silent until audio.sounds names them. A sound src may be a file or a sound name from an asset pack.
5
+ // Usage: recipes/31-audio.md.
6
+ // Browsers only allow sound after the first click/keypress; this waits for it automatically.
7
+
8
+ /** @import { SynthFn, SoundDef, AudioCondition, AudioVolume } from '../types/core' */
9
+ import { codedError } from './errorHints.js';
10
+ import { missingText, warnOnce, checkOptions } from './validate.js';
11
+ import { SoundHandle, playSound, placeListener, synthNoise, synthTone, loadSound, playFile } from './audioVoice.js';
12
+ import { matchesWhen, volumeOf, checkRuleName, packAudio, applyDucks, audioInfo } from './audioRules.js';
13
+ const AUDIO_KEYS = ['levels', 'sounds', 'ambience', 'music', 'footsteps'];
14
+ const DEFAULT_LEVELS = { master: 0.8, music: 0.5, sfx: 0.8, ambience: 0.7, ui: 0.8 };
15
+
16
+ /** engine.audio: buses, sounds by name, ducking. Sfx play by name from the game's audio.sounds (file, variants or synth). */
17
+ export class Audio {
18
+ /** @internal */
19
+ constructor(engine, opts = {}) {
20
+ checkOptions('createEngine({ audio })', opts, AUDIO_KEYS);
21
+ const { levels = {}, sounds = {}, ambience = [], music = {}, footsteps = {} } = opts;
22
+ // a typo (trakcs) would just play nothing
23
+ checkOptions('createEngine({ audio: { music } })', music, ['tracks', 'rules', 'fade', 'duckDialogue', 'duckFade', 'hold', 'interval']);
24
+ /** @internal */ this.engine = engine;
25
+ /** The browser AudioContext (exists only after the first click) @type {any} */
26
+ this.ctx = null;
27
+ /** Volume per bus 0-1 ('master' is the total). Every key is a bus: levels: { voice: 1 } adds a 'voice' bus @type {Record<string, number>} */
28
+ this.levels = { ...DEFAULT_LEVELS, ...levels };
29
+ /**
30
+ * The game's sound config from createEngine({ audio }); sounds and footsteps also hold content packs' (copies: the game's object is never changed).
31
+ * Content packs' ambience / music rules go to ambience() / music(), not here
32
+ * @type {import('../types/core').AudioConfig}
33
+ */
34
+ this.config = { sounds: { ...sounds }, ambience, music, footsteps: { ...footsteps } };
35
+ /** Bus input GainNodes by name (connect your own nodes here); empty until audio unlocks @type {Record<string, any>} */
36
+ this.buses = {};
37
+ /** The game's current mode for rule lists, e.g. 'combat' / 'explore' (condition `state` in music and ambience rules) @type {string | null} */
38
+ this.state = null;
39
+ /** @internal */ this.buffers = new Map();
40
+ /** @internal */ this.synths = new Map();
41
+ /** @internal */ this.conditions = new Map([['state', v => [].concat(v).includes(this.state)]]);
42
+ /** @internal name -> (engine) => number: values rule data compares ({ daylight: { gt: 0.15 } }) and data volumes add up */
43
+ this.measures = new Map();
44
+ // names defined in code: the same name in a content pack is an error (one name, one place)
45
+ /** @internal */ this._code = { sounds: new Set(Object.keys(sounds)), footsteps: new Set(Object.keys(footsteps)), tracks: new Set(Object.keys(music.tracks || {})) };
46
+ /** @internal content packs' audio: pack key -> { ambience, music } (ambience() / music() read it at install and follow it after) */
47
+ this.packs = new Map();
48
+ /** @internal */ this._packWatch = new Set();
49
+ /** @internal */ this._duckNodes = {};
50
+ /** @internal */ this._ducks = new Set();
51
+ /** @internal */ this._voices = new Map(); // name -> live voices (voice limit, info)
52
+ /** @internal */ this._last = new Map(); // name -> { at, variant } (cooldown, no-repeat)
53
+ /** @internal */ this._spatial = new Set(); // positional voices: the listener and followed objects update only while any exist
54
+ /** @internal */ this._readySent = false;
55
+ // Create or resume audio on the first click/keypress (a context created earlier is suspended and must be resumed inside a user gesture)
56
+ const stop = new AbortController(), signal = AbortSignal.any([stop.signal, engine.signal]); // remove after unlocking once, or when the engine is disposed
57
+ const unlock = () => { this._init(); this.ctx?.resume(); stop.abort(); };
58
+ addEventListener('pointerdown', unlock, { signal }); addEventListener('keydown', unlock, { signal });
59
+ }
60
+ /** @internal Close the audio context (engine.dispose calls it): playing sounds and nodes modules attached stop together */
61
+ dispose() { this.ctx?.close(); this.ctx = null; }
62
+
63
+ /** @internal */
64
+ _init() {
65
+ if (this.ctx || this.engine.disposed) return;
66
+ const AC = window.AudioContext || window.webkitAudioContext;
67
+ if (!AC) return;
68
+ const ctx = this.ctx = new AC();
69
+ /** The master GainNode (every bus ends here) @type {any} */
70
+ this.master = ctx.createGain(); this.master.gain.value = this.levels.master; this.master.connect(ctx.destination);
71
+ for (const name of Object.keys(this.levels)) if (name !== 'master') this._makeBus(name);
72
+ this._applyDucks(0);
73
+ const len = ctx.sampleRate * 2, buf = ctx.createBuffer(1, len, ctx.sampleRate), d = buf.getChannelData(0);
74
+ for (let i = 0; i < len; i++) d[i] = Math.random() * 2 - 1; // presentation
75
+ /** 2 s of white noise, reused by synthesized sounds @type {any} */
76
+ this.noise = buf;
77
+ const ready = () => { if (ctx.state === 'running' && !this._readySent) { this._readySent = true; this.engine.events.emit('audio:ready'); } };
78
+ ctx.addEventListener('statechange', ready); ready();
79
+ }
80
+ /** @internal a bus is two gains: its level (what setVolume sets) then its duck (what duck() lowers), so the two never fight */
81
+ _makeBus(name) {
82
+ const ctx = this.ctx, g = ctx.createGain(), d = ctx.createGain();
83
+ g.gain.value = this.levels[name]; g.connect(d).connect(this.master);
84
+ this.buses[name] = g; this._duckNodes[name] = d;
85
+ }
86
+ /** Is audio usable (the player has clicked/pressed a key)? @returns {boolean} */
87
+ get running() { return this.ctx?.state === 'running'; }
88
+ /** @internal */
89
+ _warn(msg) { warnOnce(msg); }
90
+ /** @internal */
91
+ _bus(name) {
92
+ if (name in this.levels && name !== 'master') return this.buses[name];
93
+ throw codedError('unknown-name', missingText('bus', name, Object.keys(this.levels).filter(n => n !== 'master'))
94
+ + '. Add a bus with createEngine({ audio: { levels: { name: 1 } } }) or engine.audio.addBus(name)');
95
+ }
96
+
97
+ /**
98
+ * Add a bus of your own (routed to master). It gets a settings slider like the others (label key settings.vol.<name>)
99
+ * @param {string} name
100
+ * @param {number} [level]
101
+ * @returns {this}
102
+ * @example engine.audio.addBus('voice', 1); engine.audio.sfx('line-01', { bus: 'voice' });
103
+ */
104
+ addBus(name, level = 1) {
105
+ if (!(name in this.levels)) { this.levels[name] = level; if (this.ctx) this._makeBus(name); }
106
+ return this;
107
+ }
108
+ /**
109
+ * Set a bus volume 0-1 ('master' for the total)
110
+ * @param {string} bus
111
+ * @param {number} v
112
+ * @returns {void}
113
+ * @example engine.audio.setVolume('music', 0.3);
114
+ */
115
+ setVolume(bus, v) {
116
+ if (bus !== 'master') this._bus(bus);
117
+ this.levels[bus] = v; if (!this.ctx) return;
118
+ (bus === 'master' ? this.master : this.buses[bus]).gain.value = v;
119
+ }
120
+
121
+ /**
122
+ * Lower buses until the handle is removed (dialogue, pause menu, a cutscene). Several ducks stack (their levels multiply).
123
+ * @param {Record<string, number>} levels bus -> multiplier 0-1
124
+ * @param {{ fade?: number }} [opts] fade seconds both ways (0.3)
125
+ * @returns {{ remove(fade?: number): void }}
126
+ * @example const d = engine.audio.duck({ music: 0.3, ambience: 0.5 }); engine.events.once('dialogue:end', () => d.remove());
127
+ */
128
+ duck(levels, opts = {}) {
129
+ checkOptions('audio.duck()', opts, ['fade']);
130
+ for (const b of Object.keys(levels)) if (b === 'master' || !(b in this.levels)) this._bus(b);
131
+ const { fade = 0.3 } = opts, entry = { levels };
132
+ this._ducks.add(entry); this._applyDucks(fade);
133
+ return { remove: (f = fade) => { if (this._ducks.delete(entry)) this._applyDucks(f); } };
134
+ }
135
+ /** @internal */
136
+ _applyDucks(fade) { applyDucks(this, fade); }
137
+
138
+ /**
139
+ * Register a synthesized sound: synthFn(audio, params, out) connects its nodes to `out` and returns its length in seconds
140
+ * (or { stop(time) } for a loop). Plays for sounds entries that name it ('synth' or { synth: name }); a name with no sounds entry
141
+ * plays it too unless builtIn (engine modules pass builtIn: true so their synths stay silent until the game asks).
142
+ * @param {string} name
143
+ * @param {SynthFn} synthFn
144
+ * @param {{ builtIn?: boolean, bus?: string, params?: Record<string, any> }} [opts] bus: default bus ('sfx'); params: default params
145
+ * @returns {this}
146
+ * @example engine.audio.register('ding', (a, p, out) => { a.tone({ freq: 880 * p.pitch, dur: 0.2, out }); return 0.2; });
147
+ */
148
+ register(name, synthFn, opts = {}) {
149
+ checkOptions('audio.register()', opts, ['builtIn', 'bus', 'params']);
150
+ this.synths.set(name, { fn: synthFn, builtIn: !!opts.builtIn, bus: opts.bus, params: opts.params || {} }); return this;
151
+ }
152
+
153
+ /**
154
+ * Add a condition key for music / ambience rule lists: `when: { [name]: value }` calls test(value, engine). Modules add theirs
155
+ * (sky: time, weather: weather, triggers: zone); the engine has `state` (engine.audio.state).
156
+ * @param {string} name
157
+ * @param {(value: any, e: any) => boolean} test
158
+ * @returns {{ remove(): void }}
159
+ * @example engine.audio.condition('inside', v => engine.vars.flag('indoors') === v);
160
+ */
161
+ condition(name, test) { checkRuleName(this, name, false); this.conditions.set(name, test); return { remove: () => this.conditions.delete(name) }; }
162
+ /**
163
+ * Add a measure: a number rule data compares (`when: { daylight: { gt: 0.15 } }`; gt / gte / lt / lte) and adds up (`volume: { add: { wind: 0.08 } }`).
164
+ * sky adds daylight, weather rain / snow / wind, ambience nearWater / altitude. A name is a condition or a measure, not both
165
+ * @param {string} name
166
+ * @param {(e: any) => number} fn
167
+ * @returns {{ remove(): void }}
168
+ * @example engine.audio.measure('danger', e => e.vars.counter('alarm') / 10); // data: when: { danger: { gt: 0.5 } }
169
+ */
170
+ measure(name, fn) { checkRuleName(this, name, true); this.measures.set(name, fn); return { remove: () => this.measures.delete(name) }; }
171
+ /**
172
+ * The current value of a measure (debug, tests); undefined when none is registered under that name
173
+ * @param {string} name
174
+ * @returns {number | undefined}
175
+ */
176
+ value(name) { return this.measures.get(name)?.(this.engine); }
177
+ /**
178
+ * Does a rule's `when` hold now? An object needs every key to hold (condition keys, or measure comparisons); a function gets
179
+ * (engine, ...extra); missing = always.
180
+ * @param {AudioCondition | undefined} when
181
+ * @param {...any} extra
182
+ * @returns {boolean}
183
+ * @example engine.audio.matches({ time: 'night', zone: 'forest', rain: { lt: 0.2 } });
184
+ */
185
+ matches(when, ...extra) { return matchesWhen(this, when, extra); }
186
+ /**
187
+ * A rule's volume now: a number, a function (engine, ...extra), or data { base, add: { measure: factor }, min, max }; missing = 1
188
+ * @param {AudioVolume | undefined} volume
189
+ * @param {...any} extra
190
+ * @returns {number}
191
+ * @example engine.audio.volumeOf({ base: 0, add: { rain: 0.22 } }); // 0.22 in full rain
192
+ */
193
+ volumeOf(volume, ...extra) { return volumeOf(this, volume, extra); }
194
+ /**
195
+ * @internal content.load hands each pack's audio table here (audioRules.js packAudio): sounds / footsteps merge into config, rules go to
196
+ * ambience() / music() through onPack; a pack loaded again under the same key replaces its rules
197
+ * @param {any} key 'pack:<name>', or the pack's data object for an unnamed pack (loading the same object again replaces its rules)
198
+ * @param {string} from 'pack "forest"' for messages
199
+ * @param {any} data
200
+ */
201
+ contentPack(key, from, data) {
202
+ const p = packAudio(this, data, from);
203
+ Object.assign(this.config.sounds, p.sounds); Object.assign(this.config.footsteps, p.footsteps);
204
+ const pack = { from, ambience: p.ambience, music: p.music };
205
+ this.packs.set(key, pack);
206
+ for (const fn of this._packWatch) fn(key, pack);
207
+ }
208
+ /** @internal ambience() / music() follow content packs' rules: fn(key, pack) per pack, now for each loaded one and later for new ones */
209
+ onPack(fn) {
210
+ for (const [k, p] of this.packs) fn(k, p);
211
+ this._packWatch.add(fn); return { remove: () => this._packWatch.delete(fn) };
212
+ }
213
+
214
+ /**
215
+ * Play a sound by name from audio.sounds (file, variants, or a synth). Returns a SoundHandle (stop, fade, setPosition), or null when it is
216
+ * silent: not configured, audio still locked, or held back by the sound's cooldown. Over its `voices` limit the oldest voice stops.
217
+ * @param {string} name
218
+ * @param {{ volume?: number, pitch?: number, at?: any, bus?: string, loop?: boolean, params?: Record<string, any>, fadeIn?: number }} [opts]
219
+ * at: a position or an Object3D to follow (3D sound); params: extra synth params
220
+ * @returns {SoundHandle | null}
221
+ * @example engine.audio.sfx('hit', { at: enemy.root, volume: 0.8 });
222
+ */
223
+ sfx(name, opts = {}) { return playSound(this, name, opts); }
224
+ /** @internal per frame (loop.js): positional voices follow their objects and the listener follows the camera; nothing to do without them */
225
+ _tick() {
226
+ if (!this._spatial.size || !this.ctx) return;
227
+ placeListener(this.ctx, this.engine.camera);
228
+ for (const v of this._spatial) { if (!v.playing) this._spatial.delete(v); else if (v.follow) v.setPosition(v.follow); }
229
+ }
230
+ /**
231
+ * What is playing (for describe and tests): bus levels, the duck multiplier per bus, live voices per sound name
232
+ * @returns {{ running: boolean, state: string | null, levels: Record<string, number>, ducks: Record<string, number>, voices: Record<string, number> }}
233
+ */
234
+ get info() { return audioInfo(this); }
235
+
236
+ /**
237
+ * Synth building block: a burst of filtered noise (footsteps, shutter, rain, thunder). dur seconds, freq Hz, vol 0-1; out: the node to
238
+ * connect to (a synth's `out`), else the named bus
239
+ * @param {{ dur?: number, type?: string, freq?: number, vol?: number, bus?: string, out?: any, rate?: number, delay?: number }} [opts]
240
+ * @returns {void}
241
+ */
242
+ noiseBurst(opts = {}) { synthNoise(this, opts); }
243
+ /**
244
+ * Synth building block: a short tone (bird call, notification). freq/to Hz, dur seconds, pan -1..1; out as in noiseBurst
245
+ * @param {{ freq?: number, to?: number | null, dur?: number, vol?: number, type?: string, bus?: string, out?: any, delay?: number, pan?: number }} [opts]
246
+ * @returns {void}
247
+ * @example engine.audio.tone({ freq: 660, to: 880, dur: 0.15, bus: 'ui' });
248
+ */
249
+ tone(opts = {}) { synthTone(this, opts); }
250
+
251
+ // ---------- audio files ----------
252
+ /**
253
+ * Download and decode an audio file (cached). A sound name registered in an asset pack (manifest sounds) loads that file as an
254
+ * engine.loading task, so sounds entries and music tracks may name assets instead of paths
255
+ * @param {string} url a file path or an asset pack sound name
256
+ * @returns {Promise<any>}
257
+ */
258
+ load(url) { return loadSound(this, url); }
259
+ /**
260
+ * Play an audio file by path (no sounds entry needed); resolves to a SoundHandle once the file is decoded
261
+ * @param {string} url
262
+ * @param {{ bus?: string, volume?: number, loop?: boolean, fadeIn?: number, pitch?: number, at?: any }} [opts]
263
+ * @returns {Promise<SoundHandle | null>} null only without Web Audio; called before the first click it still resolves and the sound starts once audio unlocks
264
+ * @example const h = await engine.audio.play('/sfx/door.ogg', { bus: 'ui' }); h.stop(0.5);
265
+ */
266
+ play(url, opts = {}) { return playFile(this, url, opts); }
267
+ }
package/core/Baked.js ADDED
@@ -0,0 +1,72 @@
1
+ // Code-generated model <-> GLB file (shared by the auto-cache and npm run bake).
2
+ // toGLB(object or geometry) -> ArrayBuffer: uses three's GLTFExporter; names and userData (marker params) are kept as-is
3
+ // fromGLTF(gltf) -> object or geometry: restores the shadow flags, visibility and materials recorded at export
4
+ // What glTF cannot record goes in userData (glTF extras):
5
+ // object userData.threedog = { cast, receive, hidden }; material userData.threedogMat = material JSON (no textures).
6
+ // A material with userData.purpose (made by makeMaterial) is rebuilt by purpose, so style-pack texture swaps and shader injections (wind etc.) still apply;
7
+ // otherwise it is rebuilt as-is from the recorded type and params (a MeshLambertMaterial stays Lambert, not glTF's default Standard).
8
+ import * as THREE from 'three';
9
+ import { makeMaterial } from '../render/materials.js';
10
+
11
+ // When rebuilding by purpose, keep these per-material settings from the recorded params (look params such as roughness and shininess still come from the style pack)
12
+ const KEEP_KEYS = ['flatShading', 'emissive', 'emissiveIntensity', 'transparent', 'opacity', 'side', 'alphaTest', 'depthWrite', 'wireframe'];
13
+ const TEX_KEYS = ['map', 'normalMap', 'roughnessMap', 'metalnessMap', 'emissiveMap', 'aoMap', 'alphaMap', 'bumpMap', 'lightMap', 'specularMap', 'envMap', 'gradientMap', 'displacementMap'];
14
+
15
+ /** Object (or geometry) -> GLB. Marks are written on a copy; the original is untouched. */
16
+ export async function toGLB(value, engine) {
17
+ const { GLTFExporter } = await import('three/addons/exporters/GLTFExporter.js');
18
+ const geo = value.isBufferGeometry;
19
+ const root = geo ? new THREE.Mesh(value, makeMaterial('default', { vertexColors: !!value.attributes.color }, engine)) : value.clone();
20
+ if (geo) root.userData.threedogGeometry = true;
21
+ const mats = new Map();
22
+ // Export with glTF's standard material (color, textures, vertex colors); the original type and params go in userData.threedogMat and are rebuilt as-is on read-back
23
+ const tag = m => {
24
+ if (!mats.has(m)) {
25
+ const j = m.toJSON();
26
+ for (const k of ['textures', 'images', 'uuid', 'metadata', 'userData', ...TEX_KEYS]) delete j[k];
27
+ const c = new THREE.MaterialLoader().parse({ type: 'MeshStandardMaterial', name: m.name, color: m.color?.getHex() ?? 0xffffff, vertexColors: m.vertexColors,
28
+ transparent: m.transparent, opacity: m.opacity, side: m.side, roughness: 1, metalness: 0 });
29
+ for (const k of TEX_KEYS) if (m[k] && k in c) c[k] = m[k];
30
+ c.userData = { ...m.userData, threedogMat: j }; mats.set(m, c);
31
+ }
32
+ return mats.get(m);
33
+ };
34
+ root.traverse(o => {
35
+ o.userData = { ...o.userData, threedog: { cast: o.castShadow, receive: o.receiveShadow, hidden: !o.visible } };
36
+ if (o.material) o.material = Array.isArray(o.material) ? o.material.map(tag) : tag(o.material);
37
+ });
38
+ return new GLTFExporter().parseAsync(root, { binary: true, onlyVisible: false });
39
+ }
40
+
41
+ /** The part of a GLTFLoader result that toGLB exported: restores shadow flags, visibility and materials in place (other glTF files are unaffected). Returns the gltf. */
42
+ export function restoreBaked(gltf, engine) {
43
+ const mats = new Map();
44
+ const rebuild = m => {
45
+ const spec = m.userData.threedogMat; if (!spec) return m;
46
+ if (!mats.has(m)) {
47
+ const { purpose } = m.userData;
48
+ const keep = {};
49
+ for (const k of KEEP_KEYS) if (spec[k] !== undefined) keep[k] = spec[k];
50
+ const out = purpose ? makeMaterial(purpose, { color: m.color, vertexColors: m.vertexColors, ...keep }, engine) : new THREE.MaterialLoader().parse(spec);
51
+ for (const k of TEX_KEYS) if (m[k] && k in out) out[k] = m[k];
52
+ out.name = m.name;
53
+ mats.set(m, out);
54
+ }
55
+ return mats.get(m);
56
+ };
57
+ gltf.scene.traverse(o => {
58
+ const t = o.userData.threedog;
59
+ if (!t) return;
60
+ o.castShadow = t.cast; o.receiveShadow = t.receive; o.visible = !t.hidden; delete o.userData.threedog;
61
+ if (o.material) o.material = Array.isArray(o.material) ? o.material.map(rebuild) : rebuild(o.material);
62
+ });
63
+ return gltf;
64
+ }
65
+
66
+ /** A GLTFLoader result (already restoreBaked) -> the object that was exported (a geometry if toGLB was given one). */
67
+ export function fromGLTF(gltf) {
68
+ const kids = gltf.scene.children, root = kids.length === 1 ? kids[0] : gltf.scene;
69
+ if (root.userData.threedogGeometry) { let g = null; root.traverse(o => { if (!g && o.isMesh) g = o.geometry; }); return g; }
70
+ root.removeFromParent();
71
+ return root;
72
+ }
@@ -0,0 +1,247 @@
1
+ // Automatic batching, engine.batching: the same static model placed many times is drawn as one THREE.InstancedMesh per (cell, geometry, material),
2
+ // with no work from the game. It watches what is added directly to the scene (engine.add, world.present views, stream builds, grid items, props, rigid
3
+ // meshes...), so every source of placed models goes through it without knowing about it.
4
+ // Rule: once at least minCount meshes with the same geometry, material and shadow flags sit in one cell (cell meters, default engine.stream.cellSize),
5
+ // they become instances of one InstancedMesh; below that they stay plain meshes. A batch dissolves when it drops under half of minCount.
6
+ // The placed object stays in the scene as it was (its userData, record, colliders, interactions are untouched): only its meshes are hidden and marked
7
+ // moved to layer 31 (BATCH_LAYER: not drawn, not in shadows; visible stays the game's). engine.raycast / pick / photo still hit the original and
8
+ // return it, never an instance index (engine.rays tests layer 31 too). Your own THREE.Raycaster: batching.item(hit.object, hit.instanceId).
9
+ // Moving / hiding / removing the object updates its instance next frame (checked each frame on the object's own transform); recolor with tint().
10
+ // Never batched: skinned / instanced / morphing meshes, objects with animations, multi-material, transparent, ShaderMaterial, custom renderOrder /
11
+ // layers / onBeforeRender, meshes with children, anything hlod registered (userData.hlod), and anything marked userData.batch = false (itself or a parent).
12
+ // Safety net: a batched object whose meshes are changed afterwards (material swapped, shown, re-parented, a child part animated) goes back to plain meshes
13
+ // and its geometry is not batched again (dev warns once: mark such models userData.batch = false).
14
+ // Ownership with hlod: batching owns repeated things that are near enough to be built (props, views, stream entries); hlod owns the level geometry it was
15
+ // given and swaps it for merged proxies far away. A mesh belongs to whichever took it first, so they never fight over visibility.
16
+ // createEngine({ batching: false }) turns it off (nothing is watched, zero cost); engine.batching.enabled = false at runtime dissolves every batch.
17
+ /** @import { BatchingOptions, BatchingStats, BatchInfo } from '../types/core' */
18
+ import * as THREE from 'three';
19
+ import { warnOnce } from './validate.js';
20
+ import { BATCH_LAYER, build, join, leave, dissolve, color, localTint, bounds, snap, same, stored, under } from './batchGroups.js';
21
+
22
+ const OPTS = ['minCount', 'cell'];
23
+ const STRINGS = {
24
+ evicted: '[batching] a batched copy of "{name}" changed after batching ({why}); it is drawn on its own from now on. Mark models that animate parts or swap materials with userData.batch = false',
25
+ opts: 'createEngine({ batching }) takes false or { minCount, cell }; unknown key "{key}"',
26
+ };
27
+ const PROTO_BEFORE = THREE.Object3D.prototype.onBeforeRender;
28
+ const HIDDEN = (1 << BATCH_LAYER) >>> 0; // three keeps layer masks unsigned
29
+
30
+ /** engine.batching: draws repeated static models as InstancedMesh batches (see the top of core/Batching.js). */
31
+ export class Batching {
32
+ /** @internal @param {any} engine @param {BatchingOptions | false} [opts] */
33
+ constructor(engine, opts = {}) {
34
+ for (const k of Object.keys(opts || {})) if (!OPTS.includes(k)) throw new Error(STRINGS.opts.replace('{key}', k));
35
+ /** @internal */ this.engine = engine;
36
+ /** Same model at least this many times in one cell becomes a batch (default 8) @type {number} */
37
+ this.minCount = (opts && opts.minCount) || 8;
38
+ /** @internal */ this._cell = (opts && opts.cell) || null;
39
+ /** @internal key -> group */ this.groups = new Map();
40
+ /** @internal root -> info */ this.roots = new Map();
41
+ /** @internal roots with at least one batched mesh (checked every frame) */ this.live = new Set();
42
+ /** @internal */ this.list = [];
43
+ /** @internal */ this.cursor = 0;
44
+ /** @internal roots added since the last update */ this.incoming = new Set();
45
+ /** @internal mesh -> its original material while a local tint clone is on it */ this.orig = new Map();
46
+ /** @internal mesh -> tint color */ this.tints = new WeakMap();
47
+ /** @internal geometries evicted once (never batched again) */ this.banned = new WeakSet();
48
+ /** @internal batch InstancedMesh -> group */ this.byMesh = new WeakMap();
49
+ /** Geometries and materials a live batch draws (engine.remove does not dispose these) @type {Map<any, number>} */ this.held = new Map();
50
+ /** Parent of every batch InstancedMesh (in the scene) @type {THREE.Group} */
51
+ this.root = new THREE.Group();
52
+ this.root.name = 'batching'; this.root.matrixAutoUpdate = false; this.root.userData.batch = false;
53
+ /** @internal */ this._on = false;
54
+ /** @internal */ this._add = ev => { if (ev.child !== this.root) this.incoming.add(ev.child); };
55
+ /** @internal */ this._rem = ev => { this.incoming.delete(ev.child); this._untrack(ev.child); };
56
+ if (opts !== false) this.enabled = true;
57
+ }
58
+
59
+ /** Global switch: false dissolves every batch and stops watching; true starts again (scans what is already in the scene) @type {boolean} */
60
+ get enabled() { return this._on; }
61
+ set enabled(on) {
62
+ if (on === this._on) return;
63
+ const s = this.engine.scene;
64
+ this._on = on;
65
+ if (on) {
66
+ s.addEventListener('childadded', this._add); s.addEventListener('childremoved', this._rem);
67
+ s.add(this.root);
68
+ for (const c of s.children) if (c !== this.root) this.incoming.add(c);
69
+ } else {
70
+ s.removeEventListener('childadded', this._add); s.removeEventListener('childremoved', this._rem);
71
+ for (const r of [...this.roots.keys()]) this._untrack(r);
72
+ this.incoming.clear(); this.root.removeFromParent();
73
+ }
74
+ }
75
+ /** Cell edge in meters (default engine.stream.cellSize) @type {number} */
76
+ get cell() { return this._cell ?? this.engine.stream.cellSize; }
77
+ set cell(v) { this._cell = v; this._rescan(); }
78
+
79
+ /** Every batch: { mesh: InstancedMesh, cell, count, items } (items[i] is the placed object drawn by instance i) @returns {BatchInfo[]} */
80
+ get batches() {
81
+ const out = [];
82
+ for (const g of this.groups.values()) if (g.mesh) out.push({ mesh: g.mesh, cell: g.cell, count: g.items.length, items: g.items.map(e => e.info.root) });
83
+ return out;
84
+ }
85
+ /** batches: InstancedMesh count, instances: meshes drawn through them, saved: draw calls saved per pass (instances - batches) @returns {BatchingStats} */
86
+ get stats() {
87
+ let batches = 0, instances = 0;
88
+ for (const g of this.groups.values()) if (g.mesh) { batches++; instances += g.items.length; }
89
+ return { batches, instances, saved: instances - batches };
90
+ }
91
+ /**
92
+ * Where an object is drawn: [{ mesh, index }] for each of its meshes that is batched ([] when drawn on its own).
93
+ * @param {THREE.Object3D} obj placed object (or one of its meshes)
94
+ * @returns {{ mesh: THREE.InstancedMesh, index: number }[]}
95
+ */
96
+ of(obj) {
97
+ const info = this._infoOf(obj), out = [];
98
+ if (info) for (const e of info.entries) if (e.slot >= 0 && (obj === info.root || e.mesh === obj)) out.push({ mesh: e.group.mesh, index: e.slot });
99
+ return out;
100
+ }
101
+ /**
102
+ * The placed object drawn by instance `index` of a batch mesh (for a three.js Raycaster you run yourself; engine.raycast already returns the original).
103
+ * @param {THREE.Object3D} mesh batch InstancedMesh
104
+ * @param {number} index instanceId
105
+ * @returns {THREE.Object3D | null}
106
+ */
107
+ item(mesh, index) { return this.byMesh.get(mesh)?.items[index]?.info.root ?? null; }
108
+ /**
109
+ * Recolor one placed object: its color is multiplied by `color` (instance color when batched, a cloned material otherwise); null restores it.
110
+ * @param {THREE.Object3D} obj
111
+ * @param {THREE.ColorRepresentation | null} c
112
+ * @example engine.batching.tint(engine.world.view('crate_3'), 0xff8080)
113
+ */
114
+ tint(obj, c) {
115
+ obj.traverse(m => {
116
+ if (!m.isMesh) return;
117
+ if (c == null) this.tints.delete(m); else this.tints.set(m, new THREE.Color(c));
118
+ const e = this._entryOf(m);
119
+ if (e && e.slot >= 0) color(this, e); else localTint(this, m);
120
+ });
121
+ }
122
+ /** Re-check one object now (after you changed its parts by hand); normally automatic @param {THREE.Object3D} obj */
123
+ refresh(obj) { const info = this._infoOf(obj); if (info) { this._detach(info); this._untrack(info.root); } if (obj.parent === this.engine.scene) this.incoming.add(obj); }
124
+
125
+ /** @internal Called by the engine each frame after frame hooks / stream / jobs, before rendering */
126
+ update() {
127
+ if (!this._on) return;
128
+ if (this.incoming.size) { for (const r of this.incoming) if (r.parent === this.engine.scene) this._track(r); this.incoming.clear(); }
129
+ for (const info of this.live) this._check(info);
130
+ // round robin: look for parts changed behind our back (bounded per frame)
131
+ const L = this.list, n = Math.min(L.length, 256);
132
+ for (let i = 0; i < n; i++) { if (this.cursor >= L.length) this.cursor = 0; this._verify(L[this.cursor++]); }
133
+ for (const g of this.groups.values()) if (g.dirty) { g.dirty = false; bounds(g); }
134
+ }
135
+ /** @internal */
136
+ dispose() { this.enabled = false; this.groups.clear(); }
137
+
138
+ // ---------- tracking ----------
139
+ /** @internal */
140
+ _track(root) {
141
+ if (this.roots.has(root) || root.userData.batch === false || root.animations?.length) return;
142
+ const meshes = [];
143
+ let ok = true;
144
+ const walk = (o, top) => {
145
+ if (!ok) return;
146
+ if (o.isSkinnedMesh || o.isInstancedMesh || o.isBatchedMesh) { ok = false; return; }
147
+ const u = o.userData;
148
+ if (u.batched) { o.layers.set(0); delete u.batched; } // a clone of a batched mesh: draw it again
149
+ if (!top && (u.batch === false || !o.visible)) return; // a hidden root is tracked anyway (it joins when shown)
150
+ if (o.isMesh && this._eligible(o)) meshes.push(o);
151
+ for (const c of o.children) walk(c, false);
152
+ };
153
+ walk(root, true);
154
+ if (!ok || !meshes.length) return;
155
+ const info = { root, entries: [], snap: [], cell: null, shown: false, idx: this.list.length };
156
+ for (const mesh of meshes) info.entries.push({ mesh, info, group: null, slot: -1 });
157
+ this.roots.set(root, info); this.list.push(info);
158
+ snap(root, info.snap);
159
+ if (root.visible) this._attach(info);
160
+ }
161
+ /** @internal */
162
+ _eligible(m) {
163
+ const mat = this.orig.get(m) ?? m.material;
164
+ return !m.children.length && !Array.isArray(mat) && mat && !mat.transparent && !mat.isShaderMaterial && m.geometry?.attributes.position
165
+ && !m.morphTargetInfluences && !Object.keys(m.geometry.morphAttributes).length && !m.userData.hlod && !this.banned.has(m.geometry)
166
+ && m.renderOrder === 0 && m.layers.mask === 1 && m.frustumCulled && m.onBeforeRender === PROTO_BEFORE;
167
+ }
168
+ /** @internal */
169
+ _untrack(root) {
170
+ const info = this.roots.get(root); if (!info) return;
171
+ this._detach(info);
172
+ this.roots.delete(root);
173
+ const last = this.list.pop(); if (last !== info) { this.list[info.idx] = last; last.idx = info.idx; }
174
+ }
175
+ /** @internal */
176
+ _infoOf(obj) { for (let o = obj; o; o = o.parent) { const i = this.roots.get(o); if (i) return i; } return null; }
177
+ /** @internal */
178
+ _entryOf(m) { return this._infoOf(m)?.entries.find(e => e.mesh === m) ?? null; }
179
+ /** @internal */
180
+ _rescan() { if (!this._on) return; this.enabled = false; this.enabled = true; }
181
+
182
+ /** @internal put a root's meshes into the groups of its cell */
183
+ _attach(info) {
184
+ const p = info.root.position, cs = this.cell;
185
+ info.cell = Math.floor(p.x / cs) + ',' + Math.floor(p.z / cs); info.shown = true;
186
+ info.root.updateMatrixWorld(true);
187
+ for (const e of info.entries) {
188
+ const m = e.mesh, mat = this.orig.get(m) ?? m.material;
189
+ const key = `${info.cell}|${m.geometry.id}|${mat.id}|${+m.castShadow}${+m.receiveShadow}`;
190
+ let g = this.groups.get(key);
191
+ if (!g) this.groups.set(key, g = { key, cell: info.cell, geometry: m.geometry, material: mat, cast: m.castShadow, receive: m.receiveShadow, members: new Set(), items: [], mesh: null, dirty: false, colored: false });
192
+ e.group = g; g.members.add(e);
193
+ if (g.mesh) join(this, e);
194
+ else if (g.members.size >= this.minCount) build(this, g);
195
+ }
196
+ }
197
+ /** @internal take a root's meshes out of their groups (they draw on their own again) */
198
+ _detach(info) {
199
+ info.shown = false;
200
+ for (const e of info.entries) {
201
+ const g = e.group; if (!g) continue;
202
+ e.group = null; g.members.delete(e);
203
+ if (e.slot >= 0) leave(this, g, e);
204
+ if (g.mesh && g.members.size < Math.ceil(this.minCount / 2)) dissolve(this, g);
205
+ if (!g.members.size) this.groups.delete(g.key);
206
+ }
207
+ this.live.delete(info);
208
+ }
209
+
210
+ // ---------- per-frame checks ----------
211
+ /** @internal the object's own transform / visibility changed: move its instances (or regroup when it changed cell) */
212
+ _check(info) {
213
+ const r = info.root;
214
+ if (same(r, info.snap)) return;
215
+ snap(r, info.snap);
216
+ if (!r.visible) { this._detach(info); return; }
217
+ const cs = this.cell, cell = Math.floor(r.position.x / cs) + ',' + Math.floor(r.position.z / cs);
218
+ if (cell !== info.cell || !info.shown) { this._detach(info); this._attach(info); return; }
219
+ r.updateMatrixWorld(true);
220
+ for (const e of info.entries) if (e.slot >= 0) { e.group.mesh.setMatrixAt(e.slot, e.mesh.matrixWorld); e.group.mesh.instanceMatrix.needsUpdate = true; e.group.dirty = true; }
221
+ }
222
+ /** @internal slow round robin: hidden roots coming back, pending roots that moved cell, batched parts changed behind our back */
223
+ _verify(info) {
224
+ const r = info.root;
225
+ if (!this.live.has(info)) { // not batched: only keep its cell right (so counting stays honest)
226
+ if (!same(r, info.snap)) { snap(r, info.snap); this._detach(info); if (r.visible) this._attach(info); }
227
+ return;
228
+ }
229
+ for (const e of info.entries) {
230
+ if (e.slot < 0) continue;
231
+ const m = e.mesh, g = e.group;
232
+ let why = m.layers.mask !== HIDDEN ? 'layers' : !m.visible ? 'hidden' : m.material !== g.material ? 'material' : m.geometry !== g.geometry ? 'geometry' : m.children.length ? 'children'
233
+ : m.castShadow !== g.cast || m.receiveShadow !== g.receive ? 'shadow flags' : !under(m, r) ? 're-parented' : '';
234
+ if (!why) {
235
+ m.updateWorldMatrix(true, false);
236
+ if (!stored(g.mesh.instanceMatrix.array, e.slot, m.matrixWorld) && same(r, info.snap)) why = 'a part moved';
237
+ }
238
+ if (why) { this._evict(info, why); return; }
239
+ }
240
+ }
241
+ /** @internal */
242
+ _evict(info, why) {
243
+ warnOnce(STRINGS.evicted.replace('{name}', info.root.name || info.entries[0].mesh.name || 'model').replace('{why}', why));
244
+ for (const e of info.entries) this.banned.add(e.mesh.geometry);
245
+ this._untrack(info.root);
246
+ }
247
+ }