threedog 0.7.0 → 0.8.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 (544) hide show
  1. package/CHANGELOG.md +196 -1
  2. package/README.md +6 -9
  3. package/core/{Animator.js → assets/Animator.js} +28 -18
  4. package/core/{Assets.js → assets/Assets.js} +98 -54
  5. package/core/{Baked.js → assets/Baked.js} +4 -4
  6. package/core/assets/assetEntry.js +237 -0
  7. package/core/{assetHot.js → assets/assetHot.js} +7 -6
  8. package/core/{assetLoad.js → assets/assetLoad.js} +55 -16
  9. package/core/assets/assetLod.js +113 -0
  10. package/core/{assetManifest.js → assets/assetManifest.js} +19 -11
  11. package/core/{assetReport.js → assets/assetReport.js} +6 -12
  12. package/core/{namedModel.js → assets/namedModel.js} +17 -13
  13. package/core/{Audio.js → audio/Audio.js} +26 -23
  14. package/core/{audioRules.js → audio/audioRules.js} +8 -5
  15. package/core/{audioVoice.js → audio/audioVoice.js} +17 -30
  16. package/core/{Events.js → base/Events.js} +3 -3
  17. package/core/{I18n.js → base/I18n.js} +10 -10
  18. package/core/{Random.js → base/Random.js} +5 -4
  19. package/core/{easing.js → base/easing.js} +1 -1
  20. package/core/{errorCodes.js → base/errorCodes.js} +98 -110
  21. package/core/{errorHints.js → base/errorHints.js} +5 -9
  22. package/core/{errors.js → base/errors.js} +6 -6
  23. package/core/{events.generated.js → base/events.generated.js} +1 -0
  24. package/core/{math.js → base/math.js} +15 -4
  25. package/core/{params.js → base/params.js} +3 -4
  26. package/core/base/util.js +32 -0
  27. package/core/{validate.js → base/validate.js} +28 -7
  28. package/core/{Engine.js → engine/Engine.js} +80 -77
  29. package/core/{Loading.js → engine/Loading.js} +4 -2
  30. package/core/{copies.js → engine/copies.js} +4 -4
  31. package/core/{headlessLoad.js → engine/headlessLoad.js} +4 -4
  32. package/core/{lifecycle.js → engine/lifecycle.js} +14 -12
  33. package/core/{loop.js → engine/loop.js} +68 -47
  34. package/core/{moduleSlots.js → engine/moduleSlots.js} +6 -6
  35. package/core/{moduleTypes.js → engine/moduleTypes.js} +13 -14
  36. package/core/{modules.js → engine/modules.js} +14 -11
  37. package/core/{page.js → engine/page.js} +36 -23
  38. package/core/{plugins.js → engine/plugins.js} +6 -9
  39. package/core/{services.js → engine/services.js} +47 -40
  40. package/core/{startup.js → engine/startup.js} +26 -24
  41. package/core/{Input.js → input/Input.js} +30 -22
  42. package/core/{inputContext.js → input/inputContext.js} +14 -5
  43. package/core/{inputPad.js → input/inputPad.js} +1 -1
  44. package/core/{inputPointer.js → input/inputPointer.js} +8 -2
  45. package/core/{inputTouch.js → input/inputTouch.js} +1 -1
  46. package/core/{Budget.js → inspect/Budget.js} +21 -20
  47. package/core/{DebugOverrides.js → inspect/DebugOverrides.js} +30 -16
  48. package/core/{Describe.js → inspect/Describe.js} +26 -22
  49. package/core/{Inspect.js → inspect/Inspect.js} +9 -7
  50. package/core/{InspectMaterials.js → inspect/InspectMaterials.js} +7 -8
  51. package/core/{InspectPerf.js → inspect/InspectPerf.js} +19 -13
  52. package/core/{InspectScene.js → inspect/InspectScene.js} +8 -5
  53. package/core/{MaterialInfo.js → inspect/MaterialInfo.js} +3 -2
  54. package/core/{UrlState.js → inspect/UrlState.js} +52 -20
  55. package/core/{catalog.js → inspect/catalog.js} +3 -3
  56. package/core/{checks.js → inspect/checks.js} +7 -5
  57. package/core/{debugView.js → inspect/debugView.js} +4 -4
  58. package/core/{describeRender.js → inspect/describeRender.js} +21 -20
  59. package/core/{describeText.js → inspect/describeText.js} +11 -6
  60. package/core/inspect/geometryWatch.js +38 -0
  61. package/core/{lightWatch.js → inspect/lightWatch.js} +8 -8
  62. package/core/{pictureWriters.js → inspect/pictureWriters.js} +15 -16
  63. package/core/{shaderCost.js → inspect/shaderCost.js} +1 -1
  64. package/core/{Ops.js → ops/Ops.js} +16 -11
  65. package/core/{control.js → ops/control.js} +13 -12
  66. package/core/ops/holds.js +139 -0
  67. package/core/{opsAtomic.js → ops/opsAtomic.js} +2 -1
  68. package/core/{opsCheck.js → ops/opsCheck.js} +4 -5
  69. package/core/{opsGuard.js → ops/opsGuard.js} +3 -3
  70. package/core/{opsRun.js → ops/opsRun.js} +7 -4
  71. package/core/{owned.js → ops/owned.js} +14 -17
  72. package/core/{sharedPoint.js → ops/sharedPoint.js} +8 -8
  73. package/core/{stackFrames.js → ops/stackFrames.js} +2 -2
  74. package/core/{stacks.js → ops/stacks.js} +12 -14
  75. package/core/{wrap.js → ops/wrap.js} +8 -6
  76. package/core/{SaveStore.js → saves/SaveStore.js} +1 -1
  77. package/core/{Saves.js → saves/Saves.js} +58 -36
  78. package/core/{saveApply.js → saves/saveApply.js} +13 -9
  79. package/core/{saveFiles.js → saves/saveFiles.js} +17 -15
  80. package/core/{saveValues.js → saves/saveValues.js} +20 -3
  81. package/core/{saveVersions.js → saves/saveVersions.js} +4 -17
  82. package/core/{session.js → saves/session.js} +31 -17
  83. package/core/{Rays.js → scene/Rays.js} +23 -25
  84. package/core/{Views.js → scene/Views.js} +14 -6
  85. package/core/{adaptive.js → scene/adaptive.js} +15 -8
  86. package/core/{canvasBox.js → scene/canvasBox.js} +2 -3
  87. package/core/{engineCamera.js → scene/engineCamera.js} +1 -1
  88. package/core/{gameLights.js → scene/gameLights.js} +17 -7
  89. package/core/{grayMap.js → scene/grayMap.js} +8 -2
  90. package/core/{grid.js → scene/grid.js} +4 -4
  91. package/core/{gridLoad.js → scene/gridLoad.js} +1 -1
  92. package/core/{ground.js → scene/ground.js} +9 -9
  93. package/core/{movement.js → scene/movement.js} +3 -3
  94. package/core/{pictureSlots.js → scene/pictureSlots.js} +2 -2
  95. package/core/{sceneDelta.js → scene/sceneDelta.js} +2 -2
  96. package/core/{sceneMethods.js → scene/sceneMethods.js} +36 -13
  97. package/core/scene/stepPoses.js +55 -0
  98. package/core/{targeting.js → scene/targeting.js} +4 -5
  99. package/core/{thingExplain.js → scene/thingExplain.js} +6 -5
  100. package/core/{thingOps.js → scene/thingOps.js} +4 -3
  101. package/core/{things.js → scene/things.js} +18 -5
  102. package/core/{threePatches.js → scene/threePatches.js} +1 -1
  103. package/core/{view.js → scene/view.js} +17 -16
  104. package/core/{Batching.js → stream/Batching.js} +85 -27
  105. package/core/{Stream.js → stream/Stream.js} +60 -30
  106. package/core/{batchGroups.js → stream/batchGroups.js} +10 -9
  107. package/core/{chunkStream.js → stream/chunkStream.js} +40 -0
  108. package/core/{scatter.js → stream/scatter.js} +2 -2
  109. package/core/{streamSources.js → stream/streamSources.js} +12 -7
  110. package/core/{Commits.js → threads/Commits.js} +6 -5
  111. package/core/{Jobs.js → threads/Jobs.js} +12 -10
  112. package/core/{Threads.js → threads/Threads.js} +16 -16
  113. package/core/{threadPure.js → threads/threadPure.js} +7 -5
  114. package/core/{threadServe.js → threads/threadServe.js} +3 -3
  115. package/core/{Clock.js → time/Clock.js} +17 -10
  116. package/core/{dayTime.js → time/dayTime.js} +5 -1
  117. package/core/{skip.js → time/skip.js} +18 -17
  118. package/core/{time.js → time/time.js} +18 -12
  119. package/core/{uiClock.js → time/uiClock.js} +4 -4
  120. package/docs/AI.md +22 -19
  121. package/docs/API.md +24 -23
  122. package/docs/CODEMAP.md +76 -183
  123. package/docs/COMMANDS.md +66 -58
  124. package/docs/CONVENTIONS.md +54 -14
  125. package/docs/MIGRATING-0.8.md +169 -0
  126. package/docs/THREE.md +78 -29
  127. package/docs/api/assets.md +12 -13
  128. package/docs/api/audio.md +6 -5
  129. package/docs/api/budget.md +4 -4
  130. package/docs/api/calendar.md +10 -11
  131. package/docs/api/cameraRig.md +29 -29
  132. package/docs/api/characters.md +23 -18
  133. package/docs/api/clock.md +1 -1
  134. package/docs/api/collision.md +12 -9
  135. package/docs/api/content.md +6 -6
  136. package/docs/api/dialogue.md +3 -3
  137. package/docs/api/engine.md +45 -43
  138. package/docs/api/events.md +3 -2
  139. package/docs/api/flow.md +1 -1
  140. package/docs/api/grids.md +1 -1
  141. package/docs/api/ground.md +4 -5
  142. package/docs/api/hud.md +2 -2
  143. package/docs/api/i18n.md +6 -6
  144. package/docs/api/input.md +7 -7
  145. package/docs/api/interactions.md +4 -4
  146. package/docs/api/inventory.md +9 -9
  147. package/docs/api/jobs.md +5 -5
  148. package/docs/api/level.md +7 -7
  149. package/docs/api/lightPool.md +1 -6
  150. package/docs/api/music.md +3 -3
  151. package/docs/api/nav.md +10 -10
  152. package/docs/api/openWorld.md +1 -1
  153. package/docs/api/particles.md +2 -2
  154. package/docs/api/photo.md +4 -2
  155. package/docs/api/pickups.md +2 -2
  156. package/docs/api/post.md +20 -3
  157. package/docs/api/quests.md +3 -3
  158. package/docs/api/rays.md +5 -7
  159. package/docs/api/rigid.md +27 -18
  160. package/docs/api/saves.md +8 -7
  161. package/docs/api/settings.md +9 -8
  162. package/docs/api/sky.md +8 -7
  163. package/docs/api/stream.md +7 -7
  164. package/docs/api/swarm.md +34 -0
  165. package/docs/api/terrain.md +7 -8
  166. package/docs/api/terrainDraw.md +1 -1
  167. package/docs/api/timeline.md +2 -2
  168. package/docs/api/tools.md +25 -22
  169. package/docs/api/vars.md +1 -1
  170. package/docs/api/vegetation.md +4 -3
  171. package/docs/api/vegetationDraw.md +1 -1
  172. package/docs/api/water.md +1 -1
  173. package/docs/api/weather.md +9 -9
  174. package/docs/api/weatherDraw.md +3 -3
  175. package/docs/api/world.md +5 -5
  176. package/docs/recipes/01-new-game.md +25 -40
  177. package/docs/recipes/02-npc.md +19 -20
  178. package/docs/recipes/03-items-pickups.md +27 -43
  179. package/docs/recipes/04-quests.md +3 -4
  180. package/docs/recipes/05-props-bake.md +29 -39
  181. package/docs/recipes/06-clock-events.md +27 -18
  182. package/docs/recipes/07-flow-scenes-pause.md +12 -17
  183. package/docs/recipes/08-weather-sky.md +88 -34
  184. package/docs/recipes/09-materials-lights-models.md +22 -36
  185. package/docs/recipes/10-blender-level.md +6 -7
  186. package/docs/recipes/11-vehicles.md +30 -22
  187. package/docs/recipes/12-navmesh.md +9 -8
  188. package/docs/recipes/13-animation.md +39 -17
  189. package/docs/recipes/14-custom-module.md +14 -13
  190. package/docs/recipes/15-perf.md +49 -26
  191. package/docs/recipes/16-dev-bridge.md +32 -52
  192. package/docs/recipes/18-world.md +36 -23
  193. package/docs/recipes/19-shooting-picking.md +4 -2
  194. package/docs/recipes/20-content-actions-save.md +30 -35
  195. package/docs/recipes/21-camera.md +33 -5
  196. package/docs/recipes/22-shop-gold.md +0 -4
  197. package/docs/recipes/23-ops.md +10 -10
  198. package/docs/recipes/26-ui-parts.md +22 -12
  199. package/docs/recipes/27-net.md +0 -2
  200. package/docs/recipes/28-terrain.md +117 -21
  201. package/docs/recipes/29-grid.md +2 -2
  202. package/docs/recipes/30-templates.md +55 -19
  203. package/docs/recipes/31-audio.md +5 -5
  204. package/docs/recipes/32-action-game.md +15 -6
  205. package/docs/recipes/33-stream-sources.md +2 -2
  206. package/docs/recipes/34-environment-lighting.md +67 -19
  207. package/docs/recipes/35-picture-from-reference.md +10 -17
  208. package/docs/recipes/36-ground-plants.md +105 -0
  209. package/docs/recipes/40-scene.md +7 -11
  210. package/docs/recipes/43-shader-patches-surfaces.md +20 -41
  211. package/docs/recipes/44-water-weather-hooks.md +48 -43
  212. package/docs/recipes/45-cascaded-shadows.md +39 -17
  213. package/docs/recipes/46-blender-art-route.md +7 -8
  214. package/docs/recipes/49-game-module-contract.md +5 -5
  215. package/docs/recipes/50-own-renderer.md +2 -2
  216. package/docs/recipes/52-around-the-picture.md +54 -98
  217. package/docs/recipes/53-ground-up-close.md +61 -24
  218. package/docs/recipes/55-mods-time-wrap.md +12 -16
  219. package/docs/recipes/56-webgpu-tsl.md +16 -14
  220. package/docs/recipes/57-control.md +9 -2
  221. package/docs/recipes/58-input.md +2 -2
  222. package/docs/recipes/59-depth-post-effects.md +1 -1
  223. package/docs/recipes/60-judge-the-picture.md +29 -24
  224. package/docs/recipes/62-picture-code.md +49 -17
  225. package/docs/recipes/63-third-person-start.md +17 -4
  226. package/docs/recipes/64-particles.md +1 -1
  227. package/docs/recipes/65-swarm.md +140 -0
  228. package/examples/action/.threedog/content-index.json +1 -1
  229. package/examples/action/GAMEMAP.md +2 -2
  230. package/examples/{sheepisland → perf-island}/.threedog/content-index.json +1 -1
  231. package/examples/{sheepisland → perf-island}/GAMEMAP.md +12 -11
  232. package/examples/{sheepisland → perf-island}/assets.js +1 -1
  233. package/examples/{sheepisland → perf-island}/main.js +8 -8
  234. package/examples/{sheepisland → perf-island}/models.js +1 -1
  235. package/examples/{sheepisland → perf-island}/params.js +1 -1
  236. package/examples/{sheepisland → perf-island}/picture/index.js +1 -1
  237. package/examples/{sheepisland → perf-island}/picture/palette.js +2 -2
  238. package/examples/{sheepisland → perf-island}/views.js +1 -1
  239. package/examples/plain-picture/GAMEMAP.md +1 -0
  240. package/examples/rc2d/GAMEMAP.md +3 -2
  241. package/examples/rc2d/main.js +1 -3
  242. package/examples/styletest/.threedog/content-index.json +1 -1
  243. package/examples/styletest/GAMEMAP.md +3 -2
  244. package/examples/techniques/contact-shadows/contactShadows.js +1 -1
  245. package/examples/techniques/contact-shadows/main.js +1 -1
  246. package/examples/techniques/interior-light/main.js +1 -1
  247. package/examples/techniques/modular-building/README.md +7 -6
  248. package/examples/techniques/outlines-and-rim/picture/post.js +1 -1
  249. package/examples/techniques/procedural-animation/README.md +1 -1
  250. package/examples/webgpu-tsl/GAMEMAP.md +1 -0
  251. package/examples/world/.threedog/content-index.json +1 -1
  252. package/examples/world/GAMEMAP.md +4 -3
  253. package/examples/world/picture/sky.js +1 -1
  254. package/index.d.ts +8 -7
  255. package/index.js +31 -31
  256. package/llms.txt +9 -13
  257. package/modules/ambience/Ambience.js +11 -8
  258. package/modules/calendar/Calendar.js +19 -19
  259. package/modules/calendar/index.js +13 -13
  260. package/modules/calendar/schedule.js +11 -6
  261. package/modules/calendar/seasons.js +7 -7
  262. package/modules/camera/FirstPersonCamera.js +2 -2
  263. package/modules/camera/FixedCamera.js +14 -15
  264. package/modules/camera/FollowCamera.js +4 -4
  265. package/modules/camera/RtsCamera.js +11 -11
  266. package/modules/camera/common.js +48 -24
  267. package/modules/camera/contract.js +1 -0
  268. package/modules/camera/projection.js +2 -2
  269. package/modules/characters/Character.js +33 -30
  270. package/modules/characters/NPC.js +27 -19
  271. package/modules/characters/assetModel.js +14 -10
  272. package/modules/characters/astar.js +7 -5
  273. package/modules/characters/behaviors.js +4 -5
  274. package/modules/characters/contract.js +2 -2
  275. package/modules/characters/index.js +168 -214
  276. package/modules/characters/moveHelpers.js +14 -3
  277. package/modules/characters/movers/common.js +16 -14
  278. package/modules/characters/movers/manual.js +1 -1
  279. package/modules/characters/movers/rapier.js +7 -6
  280. package/modules/characters/movers/simple.js +3 -3
  281. package/modules/characters/movers/support.js +8 -8
  282. package/modules/characters/npcAvoid.js +4 -4
  283. package/modules/characters/npcSim.js +23 -17
  284. package/modules/characters/npcView.js +6 -5
  285. package/modules/characters/pathAsync.js +12 -10
  286. package/modules/characters/pathWorker.js +1 -1
  287. package/modules/characters/player.js +108 -0
  288. package/modules/characters/playerStrings.js +2 -2
  289. package/modules/characters/proceduralRig.js +2 -2
  290. package/modules/characters/useModel.js +3 -3
  291. package/modules/characters/walkTo.js +11 -17
  292. package/modules/collision/Collision.js +26 -20
  293. package/modules/collision/contract.js +15 -0
  294. package/modules/content/explain.js +1 -2
  295. package/modules/content/fields.js +24 -3
  296. package/modules/content/ids.js +2 -2
  297. package/modules/content/index.js +61 -99
  298. package/modules/content/loader.js +14 -17
  299. package/modules/content/markers.js +25 -0
  300. package/modules/content/models.js +10 -7
  301. package/modules/content/packs.js +3 -3
  302. package/modules/content/parts.js +2 -2
  303. package/modules/content/places.js +35 -0
  304. package/modules/content/props.js +17 -14
  305. package/modules/content/rules.js +25 -21
  306. package/modules/content/stages.js +7 -7
  307. package/modules/content/templates.js +20 -20
  308. package/modules/content/words.js +34 -0
  309. package/modules/debug/DebugPanel.js +10 -43
  310. package/modules/flow/contract.js +1 -1
  311. package/modules/flow/index.js +11 -7
  312. package/modules/gameplay/Container.js +12 -11
  313. package/modules/gameplay/Containers.js +14 -5
  314. package/modules/gameplay/Dialogue.js +13 -11
  315. package/modules/gameplay/Interactions.js +37 -24
  316. package/modules/gameplay/Inventory.js +8 -9
  317. package/modules/gameplay/Quests.js +16 -9
  318. package/modules/gameplay/boxOps.js +1 -1
  319. package/modules/gameplay/dialogueBubbles.js +3 -4
  320. package/modules/gameplay/inventoryOps.js +0 -1
  321. package/modules/gameplay/pickups.js +22 -23
  322. package/modules/gameplay/questSave.js +3 -3
  323. package/modules/grid/Grid.js +1 -1
  324. package/modules/grid/Layer.js +4 -4
  325. package/modules/grid/index.js +7 -8
  326. package/modules/grid/preview.js +7 -7
  327. package/modules/grid/tiles.js +6 -6
  328. package/modules/hlod/index.js +37 -55
  329. package/modules/hud/index.js +17 -11
  330. package/modules/hud/parts.js +4 -4
  331. package/modules/level/contract.js +16 -0
  332. package/modules/level/heightfield.js +12 -10
  333. package/modules/level/index.js +47 -152
  334. package/modules/level/load.js +79 -0
  335. package/modules/level/meshes.js +65 -0
  336. package/modules/level/nodes.js +6 -7
  337. package/modules/lights/index.js +28 -181
  338. package/modules/lights/slots.js +93 -0
  339. package/modules/lights/sources.js +88 -0
  340. package/modules/music/Music.js +30 -26
  341. package/modules/music/rules.js +1 -1
  342. package/modules/nav/contract.js +14 -0
  343. package/modules/nav/index.js +11 -10
  344. package/modules/net/Client.js +7 -7
  345. package/modules/net/Host.js +7 -7
  346. package/modules/net/Net.js +1 -1
  347. package/modules/net/index.js +5 -4
  348. package/modules/net/sync.js +2 -2
  349. package/modules/net/transports.js +2 -2
  350. package/modules/particles/Particles.js +11 -8
  351. package/modules/particles/effect.js +7 -5
  352. package/modules/particles/shaders.js +2 -1
  353. package/modules/photo/Photo.js +15 -17
  354. package/modules/rigid/RigidBodies.js +66 -43
  355. package/modules/rigid/Vehicles.js +2 -3
  356. package/modules/rigid/ragdoll.js +287 -0
  357. package/modules/rigid/ragdollBones.js +159 -0
  358. package/modules/rigid/sync.js +6 -6
  359. package/modules/settings/Settings.js +108 -39
  360. package/modules/settings/apply.js +6 -6
  361. package/modules/settings/sections.js +16 -14
  362. package/modules/settings/view.js +3 -3
  363. package/modules/sky/Sky.js +29 -22
  364. package/modules/sky/clouds.js +7 -7
  365. package/modules/sky/dome.js +33 -20
  366. package/modules/sky/domeLayers.js +9 -9
  367. package/modules/sky/environment.js +6 -6
  368. package/modules/sky/frame.js +19 -10
  369. package/modules/sky/season.js +7 -1
  370. package/modules/sky/shader.js +24 -25
  371. package/modules/sky/skyModule.js +14 -27
  372. package/modules/sky/tint.js +1 -1
  373. package/modules/swarm/Swarm.js +346 -0
  374. package/modules/swarm/draw.js +68 -0
  375. package/modules/swarm/grid.js +63 -0
  376. package/modules/terrain/ChunkManager.js +70 -52
  377. package/modules/terrain/chunkQueries.js +7 -24
  378. package/modules/terrain/chunkWorker.js +1 -1
  379. package/modules/terrain/draw.js +14 -11
  380. package/modules/terrain/index.js +28 -34
  381. package/modules/terrain/terrainColorMap.js +6 -3
  382. package/modules/terrain/terrainDefaults.js +2 -1
  383. package/modules/terrain/terrainEdit.js +32 -27
  384. package/modules/terrain/terrainGen.js +17 -12
  385. package/modules/terrain/terrainIsland.js +2 -2
  386. package/modules/terrain/terrainMesh.js +7 -6
  387. package/modules/terrain/terrainShape.js +8 -10
  388. package/modules/terrain/terrainShapeMain.js +3 -3
  389. package/modules/timeline/Timeline.js +27 -19
  390. package/modules/timeline/Tween.js +6 -6
  391. package/modules/timeline/shots.js +5 -7
  392. package/modules/triggers/index.js +9 -9
  393. package/modules/vegetation/Vegetation.js +30 -23
  394. package/modules/vegetation/densityMap.js +4 -7
  395. package/modules/vegetation/draw.js +23 -18
  396. package/modules/vegetation/groundChunks.js +11 -31
  397. package/modules/vegetation/index.js +8 -6
  398. package/modules/vegetation/modelGeometry.js +3 -6
  399. package/modules/vegetation/nearFade.js +1 -1
  400. package/modules/water/Water.js +16 -16
  401. package/modules/water/surface.js +3 -3
  402. package/modules/weather/Weather.js +41 -30
  403. package/modules/weather/particles.js +8 -8
  404. package/modules/weather/weatherDraw.js +22 -18
  405. package/modules/world/World.js +8 -8
  406. package/modules/world/explain.js +1 -1
  407. package/modules/world/index.js +18 -12
  408. package/modules/world/persist.js +73 -25
  409. package/modules/world/pos.js +4 -4
  410. package/modules/world/records.js +28 -8
  411. package/modules/world/sim.js +4 -4
  412. package/modules/world/state.js +12 -5
  413. package/modules/world/thingSource.js +4 -2
  414. package/modules/world/views.js +11 -9
  415. package/package.json +42 -7
  416. package/presets.js +1 -3
  417. package/render/PostFX.js +39 -27
  418. package/render/backend.js +26 -32
  419. package/render/cascades.js +17 -12
  420. package/render/cascades.tsl.js +5 -8
  421. package/render/daylight.js +20 -3
  422. package/render/detail.js +8 -7
  423. package/render/effects.js +28 -25
  424. package/render/fuse.js +3 -3
  425. package/render/fx/cloudShadow.tsl.js +3 -3
  426. package/render/fx/detail.tsl.js +1 -1
  427. package/render/fx/index.js +5 -10
  428. package/render/fx/library.tsl.js +11 -0
  429. package/render/fx/lighting.tsl.js +2 -1
  430. package/render/fx/nodeErrors.tsl.js +2 -2
  431. package/render/fx/objectOrigin.tsl.js +1 -2
  432. package/render/fx/patchNodes.tsl.js +5 -15
  433. package/render/fx/postWebGPU.tsl.js +27 -23
  434. package/render/fx/sky.tsl.js +15 -17
  435. package/render/fx/uniforms.tsl.js +4 -4
  436. package/render/fx/wind.tsl.js +1 -1
  437. package/render/fxNumbers.js +3 -0
  438. package/render/layers.js +1 -1
  439. package/render/lighting.js +5 -3
  440. package/render/lightmap.js +20 -20
  441. package/render/lights.js +6 -6
  442. package/render/lit.js +24 -0
  443. package/render/materials.js +8 -7
  444. package/render/mergeCommon.js +22 -0
  445. package/render/modeling.js +2 -2
  446. package/render/occlusion.js +20 -4
  447. package/render/ownFrame.js +4 -4
  448. package/render/patches.js +13 -13
  449. package/render/postWebGL.js +12 -10
  450. package/render/probes.js +16 -19
  451. package/render/recordSweep.js +117 -0
  452. package/render/shaderErrors.js +10 -9
  453. package/render/shadowCache.tsl.js +107 -0
  454. package/render/shadowTypes.js +9 -0
  455. package/{core → render}/shadows.js +57 -11
  456. package/render/slots.js +7 -7
  457. package/render/terms.js +22 -24
  458. package/render/uniformDecl.js +1 -1
  459. package/types/core.d.ts +200 -153
  460. package/types/gameplay.d.ts +163 -91
  461. package/types/generated/core/{Audio.d.ts → audio/Audio.d.ts} +22 -7
  462. package/types/generated/core/{audioVoice.d.ts → audio/audioVoice.d.ts} +2 -2
  463. package/types/generated/core/{Events.d.ts → base/Events.d.ts} +4 -4
  464. package/types/generated/core/{I18n.d.ts → base/I18n.d.ts} +7 -15
  465. package/types/generated/core/{Random.d.ts → base/Random.d.ts} +4 -3
  466. package/types/generated/core/{page.d.ts → engine/page.d.ts} +8 -9
  467. package/types/generated/core/{Input.d.ts → input/Input.d.ts} +12 -8
  468. package/types/generated/core/{Budget.d.ts → inspect/Budget.d.ts} +36 -26
  469. package/types/generated/core/{DebugOverrides.d.ts → inspect/DebugOverrides.d.ts} +2 -2
  470. package/types/generated/core/{Ops.d.ts → ops/Ops.d.ts} +4 -3
  471. package/types/generated/core/{control.d.ts → ops/control.d.ts} +4 -10
  472. package/types/generated/core/{Saves.d.ts → saves/Saves.d.ts} +37 -13
  473. package/types/generated/core/{session.d.ts → saves/session.d.ts} +2 -1
  474. package/types/generated/core/{Rays.d.ts → scene/Rays.d.ts} +8 -27
  475. package/types/generated/core/{Views.d.ts → scene/Views.d.ts} +1 -1
  476. package/types/generated/core/{Batching.d.ts → stream/Batching.d.ts} +7 -7
  477. package/types/generated/core/{Stream.d.ts → stream/Stream.d.ts} +18 -16
  478. package/types/generated/core/{Commits.d.ts → threads/Commits.d.ts} +1 -1
  479. package/types/generated/core/{Jobs.d.ts → threads/Jobs.d.ts} +6 -6
  480. package/types/generated/core/{Threads.d.ts → threads/Threads.d.ts} +4 -4
  481. package/types/generated/modules/calendar/Calendar.d.ts +10 -11
  482. package/types/generated/modules/debug/DebugPanel.d.ts +1 -9
  483. package/types/generated/modules/grid/Layer.d.ts +1 -1
  484. package/types/generated/modules/grid/index.d.ts +3 -3
  485. package/types/generated/modules/music/Music.d.ts +7 -5
  486. package/types/generated/modules/particles/Particles.d.ts +1 -1
  487. package/types/generated/modules/sky/Sky.d.ts +21 -10
  488. package/types/generated/modules/swarm/Swarm.d.ts +80 -0
  489. package/types/generated/modules/timeline/Timeline.d.ts +2 -1
  490. package/types/generated/modules/water/Water.d.ts +1 -0
  491. package/types/generated/modules/weather/Weather.d.ts +16 -12
  492. package/types/generated/modules/weather/weatherDraw.d.ts +3 -3
  493. package/types/generated/modules/world/World.d.ts +5 -3
  494. package/types/generated/render/PostFX.d.ts +17 -11
  495. package/types/generated/render/materials.d.ts +1 -0
  496. package/types/generated/render/occlusion.d.ts +9 -0
  497. package/types/generated/render/patches.d.ts +1 -0
  498. package/types/generated/ui/Focus.d.ts +1 -0
  499. package/types/generated/ui/UI.d.ts +1 -0
  500. package/types/nav.d.ts +11 -11
  501. package/types/physics.d.ts +99 -70
  502. package/types/tsl.d.ts +37 -4
  503. package/types/world.d.ts +38 -71
  504. package/ui/Focus.js +10 -9
  505. package/ui/Parts.js +4 -3
  506. package/ui/UI.js +7 -7
  507. package/ui/defaults.js +3 -2
  508. package/ui/theme.js +5 -3
  509. package/core/assetEntry.js +0 -109
  510. package/core/holds.js +0 -134
  511. package/core/shadowTypes.js +0 -16
  512. package/core/util.js +0 -17
  513. package/docs/MIGRATING-0.3.md +0 -248
  514. package/docs/MIGRATING-0.4.md +0 -320
  515. package/docs/MIGRATING-0.5.md +0 -68
  516. package/docs/MIGRATING-0.6.md +0 -126
  517. package/docs/PERF.md +0 -245
  518. package/docs/recipes/36-sky-ground-plants.md +0 -158
  519. package/docs/recipes/37-terrain-hooks.md +0 -115
  520. package/docs/recipes/38-environment-hooks.md +0 -67
  521. package/docs/recipes/42-terrain-shape.md +0 -64
  522. package/docs/recipes/47-island-snow-backdrop.md +0 -43
  523. package/docs/recipes/54-three-idioms.md +0 -88
  524. package/examples/plain-picture/FINDINGS.md +0 -53
  525. /package/core/{Vars.js → base/Vars.js} +0 -0
  526. /package/core/{mulberry32.js → base/mulberry32.js} +0 -0
  527. /package/core/{inputDefaults.js → input/inputDefaults.js} +0 -0
  528. /package/core/{textureBytes.js → inspect/textureBytes.js} +0 -0
  529. /package/core/{actor.js → ops/actor.js} +0 -0
  530. /package/core/{opsFail.js → ops/opsFail.js} +0 -0
  531. /package/core/{opsHistory.js → ops/opsHistory.js} +0 -0
  532. /package/core/{saveIds.js → saves/saveIds.js} +0 -0
  533. /package/core/{screenToGround.js → scene/screenToGround.js} +0 -0
  534. /package/core/{tier.js → scene/tier.js} +0 -0
  535. /package/core/{cells.js → stream/cells.js} +0 -0
  536. /package/core/{streamCells.js → stream/streamCells.js} +0 -0
  537. /package/core/{pureWorker.js → threads/pureWorker.js} +0 -0
  538. /package/examples/{sheepisland → perf-island}/content/index.js +0 -0
  539. /package/examples/{sheepisland → perf-island}/content/props.js +0 -0
  540. /package/examples/{sheepisland → perf-island}/content/templates.js +0 -0
  541. /package/examples/{sheepisland → perf-island}/content/vegetation.js +0 -0
  542. /package/examples/{sheepisland → perf-island}/picture/lights.js +0 -0
  543. /package/examples/{sheepisland → perf-island}/picture/materials.js +0 -0
  544. /package/examples/{sheepisland → perf-island}/picture/sky.js +0 -0
@@ -2,30 +2,20 @@
2
2
  // timers and saves are the calendar's (modules/calendar); the sky reads engine.calendar each frame to draw.
3
3
  // Usage and the engine.sky API are documented in Sky.js.
4
4
  import { Sky } from './Sky.js';
5
- import { dropOwned } from '../../core/owned.js';
6
- import { readParams, keysSchema } from '../../core/params.js';
7
- import { parseClock } from '../../core/dayTime.js';
8
- import { codedError } from '../../core/errorHints.js';
9
- import { DEV } from '../../core/validate.js';
5
+ import { dropOwned } from '../../core/ops/owned.js';
6
+ import { readParams, keysSchema } from '../../core/base/params.js';
7
+ import { parseClock } from '../../core/time/dayTime.js';
8
+ import { coded } from '../../core/base/errorHints.js';
9
+ import { warnOnce } from '../../core/base/validate.js';
10
10
  /** @import { ModuleDef } from '../../types/core' */
11
11
  /** @import { SkyOptions } from '../../types/world' */
12
12
 
13
13
  // Options sky() accepts: the time drawn without a calendar, and the dome's
14
14
  // start values. After install the numbers are engine.uniforms values (shader.js), the rest plain fields or calls on engine.sky
15
- const SKY_OPTIONS = ['time', 'clouds', 'backdrop', 'keyframes', 'sunSize', 'sunGlow', 'sunBrightness', 'moonSize', 'moonColor', 'moonBrightness',
16
- 'starDensity', 'starScale', 'gradientCurve', 'orbitTilt', 'orbitSway', 'dim'];
17
- // the sky no longer writes lights or fog, so there is nothing to switch off: say what to write instead of the generic unknown-key error
18
- const REMOVED = { shadow: 'shadows are engine.shadows (box, budget, cascades on engine.lights.sun) and three.js (light.shadow.*, renderer.shadowMap.type)',
19
- sun: "lights are the game's: delete the option; createEngine({ lights: false }) drops the placeholder lights, and your picture/ code reads engine.uniforms.uSunDir / uDaylight",
20
- hemisphere: "lights are the game's: delete the option; createEngine({ lights: false }) drops the placeholder lights, and your picture/ code reads engine.uniforms.uDaylight / uSkyTop",
21
- environment: 'the sky builds no map on its own: delete the option and call engine.sky.environment({ into: engine.scene }); an asset map is plain three.js (recipes/34)',
22
- fog: "fog is the game's: delete the option and write scene.fog = new THREE.Fog(color, near, far) in your picture/ code (engine.uniforms.uSkyHorizon is the horizon color)" };
23
- const MOVED = { layers: 'engine.sky.layer(name, layer) per layer', skybox: 'engine.sky.replace(skybox)' };
15
+ const SKY_OPTIONS = ['time', 'clouds', 'backdrop', 'keyframes', 'sunSize', 'sunGlow', 'sunBrightness', 'moonColor', 'moonBrightness',
16
+ 'starDensity', 'dim'];
24
17
  const SKY_PARAMS = keysSchema(SKY_OPTIONS); // keys only: the values take several shapes (time: 'HH:MM' | 0-1), Sky checks them
25
- const CAL_KEYS = ['dayLength', 'day', 'daysPerSeason', 'seasons', 'hoursPerDay'];
26
18
  const STRINGS = {
27
- calendarKey: 'sky({ {key} }): day length, days, seasons and hours per day belong to the calendar module: engine.use(calendar({ {key}: ... }), sky()) ' +
28
- '(the sky only draws the calendar time)',
29
19
  timeTwice: "sky({ time }) is the fixed time drawn without a calendar, but calendar() is installed, so the sky draws the calendar's time; " +
30
20
  'start the day with calendar({ time }) and drop sky({ time })',
31
21
  noSeason: "applyState({ season }): seasons are the calendar's; install calendar({ seasons: [...] }) (sky alone draws one fixed time)",
@@ -37,11 +27,6 @@ const STRINGS = {
37
27
  * @returns {ModuleDef<Sky>}
38
28
  */
39
29
  export function sky(opts = {}) {
40
- // the old calendar keys: say where they went instead of the generic unknown-key error (the calendar moved out of the sky)
41
- const moved = CAL_KEYS.find(k => k in opts);
42
- if (moved) throw codedError('sky-option', STRINGS.calendarKey.replaceAll('{key}', moved));
43
- for (const k in REMOVED) if (k in opts) throw codedError('sky-option', `sky({ ${k} }) was removed: ${REMOVED[k]}`);
44
- if (DEV) for (const k in MOVED) if (k in opts) throw codedError('sky-option', `sky({ ${k} }) moved: ${MOVED[k]} after engine.use(sky()) (one entry per picture value)`);
45
30
  readParams('sky', SKY_PARAMS, opts);
46
31
  let s = null, own = () => {};
47
32
  return {
@@ -51,23 +36,25 @@ export function sky(opts = {}) {
51
36
  // weather: only its name for the picture context; calendar: the time drawn (without it one fixed time, sky({ time }))
52
37
  optional: ['weather', 'calendar'],
53
38
  install(e, ctx) { e.i18n.add({ 'zh-CN': { 'module.sky': '天空' }, en: { 'module.sky': 'sky' } });
54
- // a time given while a calendar draws would sit silently unused (calendar() installed after sky checks the same: modules/calendar/index.js)
55
- if (opts.time != null && e.calendar) throw codedError('sky-option', STRINGS.timeTwice);
39
+ // a time given while a calendar draws sits unused: say so, the game still runs and the calendar's time is drawn
40
+ if (opts.time != null && e.calendar) warnOnce(coded('sky-option', STRINGS.timeTwice), 'sky-time-calendar');
56
41
  s = new Sky(e, opts);
57
42
  // without a calendar the drawn sun tells day from night (night glow reads the measure); a calendar installed later registers its own over it
58
- own = () => { for (const [n, f] of [['daylight', () => s.daylight], ['timeOfDay', () => s.drawnTime]]) if (!e.audio.measures.has(n)) ctx.track(e.audio.measure(n, f)); };
43
+ const measures = [['daylight', () => s.daylight], ['timeOfDay', () => s.drawnTime]];
44
+ own = () => { for (const [n, f] of measures) if (!e.audio.measures.has(n)) ctx.track(e.audio.measure(n, f)); };
59
45
  own();
60
46
  return s;
61
47
  },
62
48
  // a calendar removed mid-game takes its measures with it: the sky takes the signals back at once, or uDaylight / uTimeOfDay would freeze
63
49
  frame(dt) { own(); s.update(); s._envFrame(dt); },
64
50
  // the dome goes too: a sky swapped with replaces must not leave the old dome drawn behind the new one
65
- dispose() { s._shadowOff(); s._swap.remove(); s._envOff(); dropOwned(s.engine, s._owned); s.dome.removeFromParent(); s.dome.geometry.dispose(); s.dome.material.dispose(); },
51
+ dispose() { s._shadowOff(); s._swap.remove(); s._envOff(); s._entries.dispose(); dropOwned(s.engine, s._owned); s.dome.removeFromParent(); s.dome.geometry.dispose(); s.dome.material.dispose(); },
66
52
  // scenario params time / season go to the calendar when there is one (its own applyState); without it time sets the fixed time drawn
53
+ stateKeys: ['time', 'season'],
67
54
  applyState(e, { time, season }) {
68
55
  if (e.calendar) return;
69
56
  if (time != null) s.fixedTime = parseClock(time) % 1;
70
- if (season != null) throw codedError('sky-option', STRINGS.noSeason);
57
+ if (season != null) return { refused: { season: STRINGS.noSeason } }; // the rest of applyState has already run: a throw here would leave it half done
71
58
  },
72
59
  // describe().time is the calendar's; without one the sky reports the fixed time it draws
73
60
  describe(e, ctx) { if (!e.calendar) Object.assign(ctx.out.time, { timeOfDay: Math.round(s.fixedTime * 1000) / 1000, fixed: true }); },
@@ -47,7 +47,7 @@ export function applyCover(sky, U) {
47
47
  if (k > 0) { acc.add(tmp.set(c).multiplyScalar(k)); a += k; keep *= 1 - k; }
48
48
  }
49
49
  if (!calendar && (a > 0 || sky._covered)) { T.value.setRGB(1, 1, 1); mix.value = 0; }
50
- U.uCover.value.setComponent(part === 'ground' ? 1 : 0, 1 - keep); // the amount alone, for a game's own tint (engine.terms.season)
50
+ U.uGroundCover.value.setComponent(part === 'ground' ? 1 : 0, 1 - keep); // the amount alone, for a game's own tint (engine.shaderTerms.season)
51
51
  if (a <= 0) continue;
52
52
  on = true;
53
53
  const amt = 1 - keep, m1 = mix.value, m = 1 - (1 - m1) * (1 - amt);
@@ -0,0 +1,346 @@
1
+ // Swarm module: many same-kind gameplay objects (bullets, enemy crowds, pickups, debris) that spawn, die, move, collide and get queried.
2
+ // Data lives in typed arrays, one array per field; nothing is allocated per object on spawn, update, free or near. One swarm = one plain THREE.InstancedMesh.
3
+ //
4
+ // engine.use(swarm());
5
+ // const bullets = engine.swarm({ name: 'bullets', capacity: 4096, geometry, material, fields: ['vx', 'vz', 'life'] });
6
+ // const h = bullets.spawn({ x, y, z, vx, vz, life: 2 });
7
+ // bullets.onStep((d, i, dt) => { d.x[i] += d.vx[i] * dt; d.z[i] += d.vz[i] * dt; return (d.life[i] -= dt) > 0; }); // set once; runs every fixed step
8
+ // enemies.near(x, z, 1.5, (d, i) => { enemies.free(d.id[i]); });
9
+ //
10
+ // The id rule. Two numbers, never mixed up:
11
+ // a handle (what spawn returns, d.id[i]) names one object for as long as it lives and never names another afterwards; handles kept in a save stay good after loading it;
12
+ // a row i (what onStep and near pass, what d.x[i] reads) is where that object sits now. Rows are valid inside one callback or one plain loop:
13
+ // removing an object moves the last row into the gap. Keep handles (in a variable, or in one of the swarm's own fields); turn one into a row with swarm.row(h) (-1 = gone).
14
+ //
15
+ // Time: onStep's function runs in the fixed step on the swarm's channel (default 'world'); not at all while frozen, or while that channel stands still.
16
+ // Reserved field names drawn by the engine when listed in fields: yaw, pitch, roll (radians, three's order 'YXZ'), scale. Details: recipes/65-swarm.md.
17
+ import * as THREE from 'three';
18
+ import { codedError, coded } from '../../core/base/errorHints.js';
19
+ import { DEV, warnOnce, closest } from '../../core/base/validate.js';
20
+ import { readParams } from '../../core/base/params.js';
21
+ import { refuseSave } from '../../core/saves/saveValues.js';
22
+ import { SwarmGrid } from './grid.js';
23
+ import { makeMesh, writeMesh } from './draw.js';
24
+ /** @import { SwarmData, SwarmOptions, SwarmRowFn } from '../../types/gameplay' */
25
+
26
+ // handle = serial * SLOT + slot. serial counts this swarm's births and is saved, so an old handle never names a new object.
27
+ // A fixed SLOT and not capacity: after a game update raises capacity, a saved handle still gives the same slot.
28
+ // serial starts at 1, so a handle is always >= SLOT and a row always < SLOT: a row passed to free is caught at once and never removes the wrong object.
29
+ // A handle passes 2^24 after 16 births, past what a Float32 holds exactly, so every column a game names is Float64: a stored target must still resolve. Only x, y, z and colour stay Float32.
30
+ const SLOT = 2 ** 20;
31
+ const FIXED = ['x', 'y', 'z'], COLOR = ['r', 'g', 'b'], NOT_FIELDS = ['id', 'color'];
32
+ const OPTIONS = {
33
+ name: { type: 'string', desc: 'unique name: shown in describe(), the key in a save' },
34
+ capacity: { type: 'number', min: 1, max: SLOT, desc: 'most objects alive at once; all memory is taken up front' },
35
+ geometry: { type: 'any', optional: true, desc: 'plain three.js geometry; leave out with material for a swarm that draws nothing' },
36
+ material: { type: 'any', optional: true, desc: 'plain three.js material; it stays the game\'s to dispose' },
37
+ fields: { type: 'any', optional: true, desc: 'names of the number columns beside x, y, z' },
38
+ color: { type: 'bool', default: false, desc: 'per-object colour: columns r, g, b (linear), spawn({ color: 0xff8800 })' },
39
+ channel: { type: 'string', default: 'world', desc: 'time channel of the onStep dt' },
40
+ cell: { type: 'number', default: 2, desc: 'grid cell for near, in meters: about the usual query radius' },
41
+ save: { type: 'bool', default: false, desc: 'keep this swarm in saves; otherwise it is empty after a load or new game' },
42
+ };
43
+
44
+ /** One swarm: what engine.swarm(options) returns. See the top of modules/swarm/Swarm.js for the handle / row rule */
45
+ export class Swarm {
46
+ /**
47
+ * @internal
48
+ * @param {any} engine
49
+ * @param {any} owner the module's table of swarms
50
+ * @param {SwarmOptions} opts
51
+ */
52
+ constructor(engine, owner, opts) {
53
+ const { name, capacity, geometry = null, material = null, fields = [], color, channel, cell, save } = opts;
54
+ /** @internal */ this._owner = owner;
55
+ /** Name given to engine.swarm @type {string} */ this.name = name;
56
+ /** Most objects alive at once @type {number} */ this.capacity = capacity;
57
+ /** Time channel of the onStep dt @type {string} */ this.channel = channel;
58
+ /** Whether this swarm is kept in saves @type {boolean} */ this.saved = save;
59
+ /** Spawns refused because the swarm was full, since it was made @type {number} */ this.dropped = 0;
60
+ const names = [...FIXED, ...fields, ...(color ? COLOR : [])];
61
+ /**
62
+ * The columns: data.x[row], data.y[row], data.z[row] (Float32Array), one Float64Array per field, so a field can hold a handle, and data.id[row], the handle of that row (Float64Array).
63
+ * Rows 0 to count - 1 are live. The same object onStep and near pass as d
64
+ * @type {SwarmData}
65
+ */
66
+ this.data = /** @type {any} */ ({ id: new Float64Array(capacity) });
67
+ /** @internal the columns swap-remove moves together */ this._cols = names.map(n => (this.data[n] = FIXED.includes(n) || (color && COLOR.includes(n)) ? new Float32Array(capacity) : new Float64Array(capacity)));
68
+ /** @internal */ this._names = names;
69
+ // scale defaults to 1, colour to white: a reused row goes back to defaults, so nothing leaks from the object that had it before
70
+ /** @internal */ this._defaults = names.map(n => (n === 'scale' || (color && COLOR.includes(n)) ? 1 : 0));
71
+ /** @internal positions at the end of the step before the last, where interpolation starts; they move with the row */ this._px = new Float32Array(capacity); this._py = new Float32Array(capacity); this._pz = new Float32Array(capacity);
72
+ /** @internal positions at the end of the last step: the next step's _px */ this._ex = new Float32Array(capacity); this._ey = new Float32Array(capacity); this._ez = new Float32Array(capacity);
73
+ /** @internal row -> slot */ this._slot = new Int32Array(capacity);
74
+ /** @internal slot -> row, -1 = free */ this._at = new Int32Array(capacity).fill(-1);
75
+ /** @internal slot -> current handle */ this._handle = new Float64Array(capacity);
76
+ /** @internal rows marked dead, removed when the walk ends */ this._gone = new Uint8Array(capacity);
77
+ /** @internal slots waiting for removal */ this._kill = new Int32Array(capacity); this._killN = 0;
78
+ /** @internal free slots, a stack */ this._free = new Int32Array(capacity); this._freeN = 0;
79
+ this._resetSlots();
80
+ /** @internal next spawn's serial */ this._serial = 1;
81
+ /** @internal live rows, including those waiting in _kill */ this._n = 0;
82
+ /** @internal >0 while onStep or near walks the rows */ this._busy = 0;
83
+ /** @internal */ this._fn = null;
84
+ /** @internal made on the first near: a swarm that never queries pays nothing */ this._grid = null;
85
+ /** @internal */ this._cell = cell;
86
+ /** @internal */ this._tint = color ? new THREE.Color() : null;
87
+ /** @internal */ this._disposed = false;
88
+ /** The swarm's plain THREE.InstancedMesh (null when made without geometry and material); instance index = row. castShadow, layers and the rest are yours @type {THREE.InstancedMesh | null} */
89
+ this.mesh = geometry ? makeMesh(engine, this, geometry, material, color) : null;
90
+ }
91
+
92
+ /** Objects alive now @type {number} */
93
+ get count() { return this._n - this._killN; }
94
+
95
+ /** @internal every slot free, lowest first */
96
+ _resetSlots() {
97
+ const f = this._free, cap = this.capacity;
98
+ for (let k = 0; k < cap; k++) f[k] = cap - 1 - k;
99
+ this._freeN = cap;
100
+ }
101
+
102
+ /**
103
+ * Add one object. Fields left out start at 0 (scale at 1, colour at white). Returns its handle, or -1 when the swarm is full: the object is not added,
104
+ * dropped goes up, and one [swarm-full] warning is printed. May be called from onStep and near callbacks; an object spawned there first moves in the next step
105
+ * @example const h = bullets.spawn({ x: 0, y: 1, z: 0, vx: 8, life: 2 });
106
+ * @param {Record<string, number>} [o] x, y, z, the fields, and color (a hex colour, with { color: true })
107
+ * @returns {number}
108
+ */
109
+ spawn(o) {
110
+ // a late callback (a timer, a bullet's onStep after a level change) may call spawn after dispose: nothing to add to, so say so once and return -1 like a full swarm
111
+ if (this._disposed) { warnOnce(coded('swarm-disposed', `swarm '${this.name}': spawn() after dispose(), nothing was added`), `swarm-disposed-${this.name}`); return -1; }
112
+ if (DEV && o) this._checkSpawn(o);
113
+ if (this._n >= this.capacity) {
114
+ this.dropped++;
115
+ warnOnce(coded('swarm-full', `swarm '${this.name}' is full (capacity ${this.capacity}): spawn returned -1 and the object was not added`), `swarm-full-${this.name}`);
116
+ return -1;
117
+ }
118
+ const row = this._n++, slot = this._free[--this._freeN], h = this._serial++ * SLOT + slot, cols = this._cols, names = this._names, def = this._defaults, d = this.data;
119
+ this._slot[row] = slot; this._at[slot] = row; this._handle[slot] = h; d.id[row] = h;
120
+ for (let k = 0; k < cols.length; k++) { const v = o ? o[names[k]] : undefined; cols[k][row] = v === undefined ? def[k] : v; }
121
+ if (o?.color !== undefined) { const c = this._tint.setHex(o.color); d.r[row] = c.r; d.g[row] = c.g; d.b[row] = c.b; }
122
+ // last position = birth position: otherwise interpolation draws a line from where the row's previous object was
123
+ this._rest(row);
124
+ if (this._grid?.ok) this._grid.insert(slot, row);
125
+ return h;
126
+ }
127
+ /** @internal dev only: a misspelt field would be dropped without a word */
128
+ _checkSpawn(o) {
129
+ for (const k in o) {
130
+ if (k === 'color' ? this._tint : this._names.includes(k)) continue;
131
+ const hint = closest(k, this._names), fix = k === 'color' ? 'add color: true to engine.swarm({ ... })' : `declare it in fields${hint ? ` (did you mean ${hint}?)` : ''}; columns: ${this._names.join(', ')}`;
132
+ throw codedError('swarm-field', `swarm '${this.name}': spawn({ ${k} }) is not a column. Fix: ${fix}`);
133
+ }
134
+ }
135
+
136
+ /**
137
+ * Where a handle's object sits now, or -1 if it is gone. A row is good until the next removal outside a callback: read it, use it, drop it
138
+ * @example const i = enemies.row(target); if (i >= 0) aim(enemies.data.x[i], enemies.data.z[i]);
139
+ * @param {number} handle
140
+ * @returns {number}
141
+ */
142
+ row(handle) {
143
+ const slot = handle % SLOT;
144
+ if (!(slot >= 0 && slot < this.capacity)) return -1;
145
+ const row = this._at[slot];
146
+ return row >= 0 && this._handle[slot] === handle && !this._gone[row] ? row : -1;
147
+ }
148
+
149
+ /**
150
+ * Remove an object by handle: d.id[i] inside a callback. False if it was already gone (safe to call twice; -1 from a full spawn too). A row passed
151
+ * by mistake throws [swarm-handle]. Inside onStep and near the object counts as gone at once (near and row skip it) and rows only move when the walk ends
152
+ * @example enemies.near(x, z, 2, (d, i) => { enemies.free(d.id[i]); });
153
+ * @param {number} handle
154
+ * @returns {boolean}
155
+ */
156
+ free(handle) {
157
+ if (handle >= 0 && handle < SLOT) throw codedError('swarm-handle', `swarm '${this.name}': free(${handle}) got a row, not a handle. Fix: free(d.id[i]), or return false from onStep`);
158
+ const row = this.row(handle);
159
+ if (row < 0) return false;
160
+ if (this._busy) this._mark(row); else this._remove(row);
161
+ return true;
162
+ }
163
+ /** @internal rows must not move during a walk: the onStep loop and the near cell chains are still running */
164
+ _mark(row) { this._gone[row] = 1; this._kill[this._killN++] = this._slot[row]; }
165
+ /** @internal swap-remove */
166
+ _remove(row) {
167
+ const slot = this._slot[row], last = --this._n, g = this._grid;
168
+ if (g?.ok) g.unlink(slot);
169
+ this._at[slot] = -1; this._free[this._freeN++] = slot;
170
+ if (row !== last) {
171
+ const cols = this._cols, d = this.data, moved = this._slot[last];
172
+ for (let k = 0; k < cols.length; k++) cols[k][row] = cols[k][last];
173
+ this._px[row] = this._px[last]; this._py[row] = this._py[last]; this._pz[row] = this._pz[last];
174
+ this._ex[row] = this._ex[last]; this._ey[row] = this._ey[last]; this._ez[row] = this._ez[last];
175
+ d.id[row] = d.id[last]; this._slot[row] = moved; this._at[moved] = row; this._gone[row] = this._gone[last];
176
+ }
177
+ this._gone[last] = 0;
178
+ }
179
+ /** @internal apply what was marked during a walk */
180
+ _flush() {
181
+ const k = this._kill, at = this._at, n = this._killN;
182
+ this._killN = 0;
183
+ for (let j = 0; j < n; j++) this._remove(at[k[j]]);
184
+ }
185
+
186
+ /**
187
+ * Set the one function that moves this swarm: fn(d, i, dt) for each live row, every fixed step, dt on the swarm's channel. Return false to remove the object;
188
+ * anything else keeps it. Returns a handle: h.remove() takes it off. Set it once at setup, not every step (a second one while one is set throws [swarm-step])
189
+ * @example bullets.onStep((d, i, dt) => { d.x[i] += d.vx[i] * dt; return (d.life[i] -= dt) > 0; });
190
+ * @param {SwarmRowFn} fn
191
+ * @returns {{ remove(): void }}
192
+ */
193
+ onStep(fn) {
194
+ if (typeof fn !== 'function') throw codedError('swarm-step', `swarm '${this.name}': onStep(fn): fn must be a function, got ${typeof fn}`);
195
+ if (this._fn) throw codedError('swarm-step', `swarm '${this.name}': onStep(fn) was called while a function is already set`);
196
+ this._fn = fn;
197
+ return { remove: () => { if (this._fn === fn) this._fn = null; } };
198
+ }
199
+ /** @internal a row with no movement to draw: both interpolation ends at its position */
200
+ _rest(row) {
201
+ const d = this.data;
202
+ this._px[row] = this._ex[row] = d.x[row]; this._py[row] = this._ey[row] = d.y[row]; this._pz[row] = this._ez[row] = d.z[row];
203
+ }
204
+ /**
205
+ * @internal time.onMove, after everything in the step, so it needs no place among the game's onFixed: the last end becomes the start, and a game's own
206
+ * change to d.x in onFixed counts as this step's movement and gets interpolated
207
+ */
208
+ _end() {
209
+ if (this._grid) this._grid.ok = false;
210
+ [this._px, this._ex] = [this._ex, this._px]; [this._py, this._ey] = [this._ey, this._py]; [this._pz, this._ez] = [this._ez, this._pz];
211
+ if (!this._n) return;
212
+ const d = this.data;
213
+ const n = this._n; // live rows only: capacity is sized for the peak
214
+ this._ex.set(d.x.subarray(0, n)); this._ey.set(d.y.subarray(0, n)); this._ez.set(d.z.subarray(0, n));
215
+ }
216
+ /** @internal one fixed step */
217
+ _step(dt) {
218
+ const fn = this._fn, d = this.data, n = this._n, gone = this._gone;
219
+ if (!fn || !n || dt === 0) return; // a stopped channel stops the swarm, rather than running 50,000 calls with dt 0
220
+ this._busy++;
221
+ try {
222
+ for (let i = 0; i < n; i++) if (!gone[i] && fn(d, i, dt) === false && !gone[i]) this._mark(i);
223
+ } finally {
224
+ if (--this._busy === 0) this._flush();
225
+ if (this._grid) this._grid.ok = false; // queries after this step must see the new positions
226
+ }
227
+ }
228
+
229
+ /**
230
+ * Visit the live objects within r meters of (x, z), height ignored: cb(d, i, dist2) with the row and the squared distance; cb returning false stops early. Returns
231
+ * how many were visited. The grid is built on the first query after things moved, so a swarm nobody queries pays nothing. Order is the same every run. Inside onStep it stays the
232
+ * grid of that step's first query: distances are exact, but a row that crossed a cell line since then can be missed for one step
233
+ * @example const hit = enemies.near(px, pz, 0.5, (d, i) => { enemies.free(d.id[i]); return false; });
234
+ * @param {number} x
235
+ * @param {number} z
236
+ * @param {number} r
237
+ * @param {(d: SwarmData, i: number, dist2: number) => (boolean | void)} cb
238
+ * @returns {number}
239
+ */
240
+ near(x, z, r, cb) {
241
+ if (!(r >= 0)) throw codedError('module-params', `swarm '${this.name}': near(x, z, r, cb): r must be a number >= 0, got ${r}`);
242
+ if (!this.count) return 0;
243
+ const g = this._grid ??= new SwarmGrid(this, this._cell);
244
+ if (!g.ok) g.build();
245
+ this._busy++;
246
+ try { return g.query(x, z, r, cb); } finally { if (--this._busy === 0) this._flush(); }
247
+ }
248
+
249
+ /** Remove every object (their handles die for good). Inside a callback it applies when the walk ends */
250
+ clear() {
251
+ if (this._busy) { for (let i = 0; i < this._n; i++) if (!this._gone[i]) this._mark(i); return; }
252
+ if (this._grid) this._grid.ok = false;
253
+ for (let i = this._n - 1; i >= 0; i--) this._remove(i);
254
+ }
255
+
256
+ /** Remove this swarm: its mesh leaves the scene and its GPU buffers go. Geometry and material stay, they are the game's. The name is free again */
257
+ dispose() {
258
+ if (this._disposed) return;
259
+ this._disposed = true;
260
+ this.mesh?.removeFromParent();
261
+ this.mesh?.dispose();
262
+ this._owner.drop(this);
263
+ }
264
+
265
+ /** @internal save part entry */
266
+ _save() {
267
+ const n = this._n, cols = {};
268
+ for (let k = 0; k < this._cols.length; k++) cols[this._names[k]] = Array.from(this._cols[k].subarray(0, n));
269
+ return { serial: this._serial, id: Array.from(this.data.id.subarray(0, n)), cols };
270
+ }
271
+ /** @internal */
272
+ _load(v) {
273
+ if (!Array.isArray(v?.id) || !v.cols) refuseSave(`swarm '${this.name}'`, 'the part', 'must be { id, cols }', v);
274
+ this.clear();
275
+ const at = this._at, d = this.data, ids = v.id;
276
+ let lost = 0;
277
+ for (let i = 0; i < ids.length; i++) {
278
+ const h = ids[i], slot = h % SLOT, row = this._n;
279
+ if (!(slot >= 0 && slot < this.capacity) || at[slot] >= 0) { lost++; continue; } // capacity shrank in a game update (or a damaged id)
280
+ this._n++;
281
+ this._slot[row] = slot; at[slot] = row; this._handle[slot] = h; d.id[row] = h;
282
+ for (let k = 0; k < this._cols.length; k++) { const x = v.cols[this._names[k]]?.[i]; this._cols[k][row] = Number.isFinite(x) ? x : this._defaults[k]; } // a column added after the save takes its default
283
+ this._rest(row);
284
+ }
285
+ this._freeN = 0;
286
+ for (let s = this.capacity - 1; s >= 0; s--) if (at[s] < 0) this._free[this._freeN++] = s;
287
+ // restored as saved and not as a maximum: loading one save twice must give the same handles (determinism); every saved handle is smaller, so none collide
288
+ if (Number.isFinite(v.serial)) this._serial = v.serial;
289
+ if (lost) warnOnce(coded('swarm-full', `swarm '${this.name}': ${lost} saved objects did not fit capacity ${this.capacity} and were left out`), `swarm-load-${this.name}`);
290
+ }
291
+ }
292
+
293
+ /**
294
+ * Module: many same-kind gameplay objects in typed arrays, drawn as one InstancedMesh each. After engine.use(swarm()), engine.swarm(options) makes one and returns a Swarm.
295
+ * Bullets, enemy crowds, pickups, debris. See recipes/65-swarm.md
296
+ * @example engine.use(swarm());
297
+ * const coins = engine.swarm({ name: 'coins', capacity: 500, geometry, material, fields: ['yaw'], save: true });
298
+ * @returns {import('../../types/core').ModuleDef}
299
+ * @experimental
300
+ */
301
+ export function swarm() {
302
+ /** @type {Swarm[]} */ let list = [];
303
+ let pending = {}; // a swarm not made yet at load: kept here and filled in when it is made
304
+ const stats = s => ({ count: s.count, capacity: s.capacity, dropped: s.dropped, ...(s.saved ? { saved: true } : {}) });
305
+ return { name: 'swarm', type: 'rules', provides: ['swarm'], label: 'Swarm', stage: 'gameplay',
306
+ install(e, ctx) {
307
+ e.i18n.add({ 'zh-CN': { 'module.swarm': '成群对象' }, en: { 'module.swarm': 'swarm' } });
308
+ const owner = { drop: s => { list = list.filter(o => o !== s); } };
309
+ let firstLoad = false; // set by the first load or new game: swarms spawned before it are warned about when it empties them
310
+ ctx.track(e.time.onMove(() => { for (const s of list) s._end(); }));
311
+ // onRender and not frame: step(render: false) skips the matrices, only drawn frames write them
312
+ ctx.track(e.onRender(() => { for (const s of list) if (s.mesh) writeMesh(s, e.stepBlend); }));
313
+ // one save part for all swarms: a load or new game also empties swarms not in saves, or last round's bullets stay on the field
314
+ e.saves.register('swarm', { version: 1,
315
+ save: () => Object.fromEntries(list.filter(s => s.saved).map(s => [s.name, s._save()])),
316
+ load: d => {
317
+ pending = { ...d };
318
+ for (const s of list) {
319
+ if (s.saved && d?.[s.name]) { s._load(d[s.name]); delete pending[s.name]; continue; }
320
+ // objects spawned before the first load / new game (at startup) are emptied with the rest: allowed, but it looks like a spawn that did not work
321
+ if (!firstLoad && s.count) warnOnce(`engine.swarm('${s.name}'): ${s.count} objects spawned before the first new game / load were cleared by it. Spawn after the game starts (on the start event), or pass save: true`);
322
+ s.clear();
323
+ }
324
+ firstLoad = true;
325
+ } });
326
+ return /** @param {SwarmOptions} opts */ opts => {
327
+ const o = readParams('engine.swarm', OPTIONS, opts), { name, geometry, material, fields = [], color, channel, cell } = o;
328
+ if (list.some(s => s.name === name)) throw codedError('swarm-name', `engine.swarm: a swarm named '${name}' already exists`);
329
+ if (!geometry !== !material) throw codedError('module-params', `engine.swarm('${name}'): give geometry and material together, or neither for a swarm that draws nothing`);
330
+ e.time.dt(channel); // a misspelt channel fails here, with time's own message
331
+ if (!(cell > 0)) throw codedError('module-params', `engine.swarm('${name}'): cell must be > 0 meters, got ${cell}`);
332
+ const taken = [...FIXED, ...(color ? COLOR : []), ...NOT_FIELDS];
333
+ if (!Array.isArray(fields) || fields.some((f, i) => typeof f !== 'string' || taken.includes(f) || fields.indexOf(f) !== i))
334
+ throw codedError('module-params', `engine.swarm('${name}'): fields is a list of new column names; ${taken.join(', ')} are taken and a name may appear once. Got ${JSON.stringify(fields)}`);
335
+ const s = new Swarm(e, owner, o);
336
+ list.push(s);
337
+ if (s.saved && pending[name]) { s._load(pending[name]); delete pending[name]; }
338
+ return s;
339
+ };
340
+ },
341
+ fixed(dt, e) { for (const s of list) s._step(e.time.dt(s.channel)); },
342
+ counts() { let alive = 0; for (const s of list) alive += s.count; return { alive, swarms: list.length }; }, // engine.counts().swarm
343
+ describe() { return Object.fromEntries(list.map(s => [s.name, stats(s)])); },
344
+ explain: { swarm: (e, name) => { const s = list.find(o => o.name === name); return s ? { ...stats(s), channel: s.channel, fields: s._names, moves: !!s._fn, drawn: !!s.mesh } : { error: `no swarm '${name}'; swarms: ${list.map(o => o.name).join(', ') || 'none'}` }; } },
345
+ dispose() { for (const s of [...list]) s.dispose(); list = []; } };
346
+ }
@@ -0,0 +1,68 @@
1
+ // Drawing side of a swarm (helper of Swarm.js): one plain THREE.InstancedMesh, its matrices written once per rendered frame from the data columns.
2
+ import * as THREE from 'three';
3
+ import { engineOwned } from '../../core/scene/things.js';
4
+
5
+ /** The InstancedMesh of a swarm, in the scene, drawing nothing yet */
6
+ export function makeMesh(e, s, geometry, material, color) {
7
+ const cap = s.capacity, mesh = new THREE.InstancedMesh(geometry, material, cap), m = mesh.instanceMatrix.array;
8
+ mesh.name = `swarm:${s.name}`;
9
+ mesh.count = 0;
10
+ mesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
11
+ // with no turn or scale fields a frame writes only the three translation numbers; the other 13 stay as this identity
12
+ for (let o = 0; o < cap * 16; o += 16) m[o] = m[o + 5] = m[o + 10] = m[o + 15] = 1;
13
+ if (color) mesh.instanceColor = new THREE.InstancedBufferAttribute(new Float32Array(cap * 3), 3).setUsage(THREE.DynamicDrawUsage);
14
+ // three computes the bounds once at the first cull and they go stale as objects fly off, wrongly hiding the swarm; so they are made here and updated in the matrix loop
15
+ if (!geometry.boundingSphere) geometry.computeBoundingSphere();
16
+ mesh.boundingSphere = new THREE.Sphere();
17
+ e.scene.add(engineOwned('swarm', mesh));
18
+ return mesh;
19
+ }
20
+
21
+ /**
22
+ * Write instance matrices (and colours) of the live rows, a of the way from the last fixed step to the latest, and the bounds. A frame pays for what changed: a row whose
23
+ * yaw / pitch / roll / scale are the numbers its matrix was built from keeps those nine values (no sin or cos: most traffic drives straight), and matrices or colours
24
+ * that did not change are not uploaded (parked cars, coins, a crowd's colours). The numbers are kept per row, not per object: after a swap-remove equal numbers still mean an equal block.
25
+ */
26
+ export function writeMesh(s, a) {
27
+ const mesh = s.mesh, n = s._n, d = s.data, m = mesh.instanceMatrix.array, X = d.x, Y = d.y, Z = d.z, PX = s._px, PY = s._py, PZ = s._pz;
28
+ const yaw = d.yaw, pitch = d.pitch, roll = d.roll, sc = d.scale, turns = !!(yaw || pitch || roll);
29
+ const built = turns || sc ? s._built ??= new Float64Array(s.capacity * 4).fill(NaN) : null;
30
+ let x0 = Infinity, y0 = Infinity, z0 = Infinity, x1 = -Infinity, y1 = -Infinity, z1 = -Infinity, big = sc ? 0 : 1, dirty = false;
31
+ for (let i = 0, o = 0, t = 0; i < n; i++, o += 16, t += 4) {
32
+ const x = PX[i] + (X[i] - PX[i]) * a, y = PY[i] + (Y[i] - PY[i]) * a, z = PZ[i] + (Z[i] - PZ[i]) * a, k = sc ? sc[i] : 1;
33
+ if (x < x0) x0 = x; if (x > x1) x1 = x;
34
+ if (y < y0) y0 = y; if (y > y1) y1 = y;
35
+ if (z < z0) z0 = z; if (z > z1) z1 = z;
36
+ if (k > big) big = k;
37
+ if (built) {
38
+ const px = pitch ? pitch[i] : 0, py = yaw ? yaw[i] : 0, pz = roll ? roll[i] : 0;
39
+ if (built[t] !== py || built[t + 1] !== px || built[t + 2] !== pz || built[t + 3] !== k) {
40
+ built[t] = py; built[t + 1] = px; built[t + 2] = pz; built[t + 3] = k; dirty = true;
41
+ if (turns) {
42
+ // the formula of three's Euler 'YXZ' (the spec compares it with Matrix4.compose); no Object3D, 50,000 objects cannot allocate each frame
43
+ const ca = Math.cos(px), b = Math.sin(px), c = Math.cos(py), dd = Math.sin(py), e = Math.cos(pz), f = Math.sin(pz);
44
+ const ce = c * e, cf = c * f, de = dd * e, df = dd * f;
45
+ m[o] = (ce + df * b) * k; m[o + 1] = ca * f * k; m[o + 2] = (cf * b - de) * k;
46
+ m[o + 4] = (de * b - cf) * k; m[o + 5] = ca * e * k; m[o + 6] = (df + ce * b) * k;
47
+ m[o + 8] = ca * dd * k; m[o + 9] = -b * k; m[o + 10] = ca * c * k;
48
+ } else { m[o] = k; m[o + 5] = k; m[o + 10] = k; }
49
+ }
50
+ }
51
+ if (m[o + 12] !== x || m[o + 13] !== y || m[o + 14] !== z) { m[o + 12] = x; m[o + 13] = y; m[o + 14] = z; dirty = true; }
52
+ }
53
+ mesh.count = n;
54
+ if (!n) return;
55
+ // upload the live part only: capacity is sized for the peak and most frames use far less
56
+ const im = mesh.instanceMatrix;
57
+ if (dirty) { im.clearUpdateRanges(); im.addUpdateRange(0, n * 16); im.needsUpdate = true; }
58
+ const col = mesh.instanceColor;
59
+ if (col) {
60
+ const c = col.array, R = d.r, G = d.g, B = d.b;
61
+ let tinted = false;
62
+ for (let i = 0, o = 0; i < n; i++, o += 3) if (c[o] !== R[i] || c[o + 1] !== G[i] || c[o + 2] !== B[i]) { c[o] = R[i]; c[o + 1] = G[i]; c[o + 2] = B[i]; tinted = true; }
63
+ if (tinted) { col.clearUpdateRanges(); col.addUpdateRange(0, n * 3); col.needsUpdate = true; }
64
+ }
65
+ const g = mesh.geometry.boundingSphere, bs = mesh.boundingSphere, hx = (x1 - x0) / 2, hy = (y1 - y0) / 2, hz = (z1 - z0) / 2;
66
+ bs.center.set(x0 + hx, y0 + hy, z0 + hz);
67
+ bs.radius = Math.hypot(hx, hy, hz) + (g.radius + g.center.length()) * big;
68
+ }
@@ -0,0 +1,63 @@
1
+ // Spatial grid behind swarm.near (helper of Swarm.js): a hashed uniform grid over x and z, built on the first query after things moved.
2
+ // Why hashed and not an array over the world: a game world has no declared bounds and a bullet may leave the map; the table size depends only on capacity.
3
+ // Why the lists hang on slots and not rows: swap-remove moves rows, slots stay, so free and spawn keep the cells in O(1) with no rebuild.
4
+ // Why cx / cz are kept: two cells can share a bucket; comparing them shows each object once, in its own cell, so a query needs no dedupe.
5
+ export class SwarmGrid {
6
+ /** @param {any} s the swarm @param {number} cell cell size in meters */
7
+ constructor(s, cell) {
8
+ this.s = s; this.cell = cell;
9
+ let size = 64;
10
+ while (size < s.capacity * 2) size *= 2;
11
+ this.mask = size - 1;
12
+ this.head = new Int32Array(size);
13
+ this.next = new Int32Array(s.capacity); this.prev = new Int32Array(s.capacity);
14
+ this.cx = new Int32Array(s.capacity); this.cz = new Int32Array(s.capacity);
15
+ /** false: things moved since the last build */ this.ok = false;
16
+ }
17
+ bucket(cx, cz) { return (Math.imul(cx, 73856093) ^ Math.imul(cz, 19349663)) & this.mask; }
18
+ /** Put a slot into the cell of its row */
19
+ insert(slot, row) {
20
+ const { head, next, prev, s } = this, cx = Math.floor(s.data.x[row] / this.cell), cz = Math.floor(s.data.z[row] / this.cell), b = this.bucket(cx, cz), first = head[b];
21
+ this.cx[slot] = cx; this.cz[slot] = cz;
22
+ next[slot] = first; prev[slot] = -1 - b; // negative = head of a bucket, keeping its number so unlink need not hash again
23
+ if (first >= 0) prev[first] = slot;
24
+ head[b] = slot;
25
+ }
26
+ /** Take a slot out of its cell */
27
+ unlink(slot) {
28
+ const { head, next, prev } = this, p = prev[slot], n = next[slot];
29
+ if (p < 0) head[-1 - p] = n; else next[p] = n;
30
+ if (n >= 0) prev[n] = p;
31
+ }
32
+ build() {
33
+ const { s } = this, slots = s._slot, gone = s._gone;
34
+ this.head.fill(-1);
35
+ for (let i = 0, n = s._n; i < n; i++) if (!gone[i]) this.insert(slots[i], i);
36
+ this.ok = true;
37
+ }
38
+ /** Calls cb(data, row, dist2) for each live object within r of (x, z); cb returning false stops. Returns how many were visited */
39
+ query(x, z, r, cb) {
40
+ const { s, cell, head, next } = this, d = s.data, X = d.x, Z = d.z, at = s._at, gone = s._gone, r2 = r * r;
41
+ const x0 = Math.floor((x - r) / cell), x1 = Math.floor((x + r) / cell), z0 = Math.floor((z - r) / cell), z1 = Math.floor((z + r) / cell);
42
+ let hits = 0;
43
+ // with more cells than objects a row scan is faster; otherwise a wide query would cost by area and not by object count
44
+ if ((x1 - x0 + 1) * (z1 - z0 + 1) > s._n) {
45
+ for (let i = 0, n = s._n; i < n; i++) {
46
+ if (gone[i]) continue;
47
+ const dx = X[i] - x, dz = Z[i] - z, d2 = dx * dx + dz * dz;
48
+ if (d2 <= r2) { hits++; if (cb(d, i, d2) === false) return hits; }
49
+ }
50
+ return hits;
51
+ }
52
+ for (let cz = z0; cz <= z1; cz++) for (let cx = x0; cx <= x1; cx++) {
53
+ for (let k = head[this.bucket(cx, cz)]; k >= 0; k = next[k]) {
54
+ if (this.cx[k] !== cx || this.cz[k] !== cz) continue;
55
+ const i = at[k];
56
+ if (gone[i]) continue;
57
+ const dx = X[i] - x, dz = Z[i] - z, d2 = dx * dx + dz * dz;
58
+ if (d2 <= r2) { hits++; if (cb(d, i, d2) === false) return hits; }
59
+ }
60
+ }
61
+ return hits;
62
+ }
63
+ }