threedog 0.0.0-stage → 0.1.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 (459) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/LICENSE +21 -0
  3. package/README.md +39 -2
  4. package/core/Animator.js +267 -0
  5. package/core/Assets.js +240 -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/Describe.js +134 -0
  13. package/core/Engine.js +221 -0
  14. package/core/Events.js +95 -0
  15. package/core/I18n.js +94 -0
  16. package/core/Input.js +245 -0
  17. package/core/Inspect.js +97 -0
  18. package/core/InspectScene.js +187 -0
  19. package/core/Jobs.js +146 -0
  20. package/core/Loading.js +149 -0
  21. package/core/Ops.js +272 -0
  22. package/core/Random.js +52 -0
  23. package/core/Rays.js +160 -0
  24. package/core/SaveStore.js +85 -0
  25. package/core/Saves.js +253 -0
  26. package/core/Stream.js +279 -0
  27. package/core/Threads.js +158 -0
  28. package/core/UrlState.js +93 -0
  29. package/core/Vars.js +34 -0
  30. package/core/actor.js +23 -0
  31. package/core/assetEntry.js +89 -0
  32. package/core/assetLoad.js +190 -0
  33. package/core/assetManifest.js +35 -0
  34. package/core/audioRules.js +121 -0
  35. package/core/audioVoice.js +225 -0
  36. package/core/batchGroups.js +116 -0
  37. package/core/canvasBox.js +63 -0
  38. package/core/dayTime.js +15 -0
  39. package/core/describeText.js +136 -0
  40. package/core/easing.js +34 -0
  41. package/core/errorCodes.js +172 -0
  42. package/core/errorHints.js +203 -0
  43. package/core/errors.js +40 -0
  44. package/core/events.generated.js +84 -0
  45. package/core/ground.js +102 -0
  46. package/core/inputContext.js +69 -0
  47. package/core/inputDefaults.js +22 -0
  48. package/core/inputPad.js +35 -0
  49. package/core/inputPointer.js +48 -0
  50. package/core/inputTouch.js +48 -0
  51. package/core/lifecycle.js +68 -0
  52. package/core/lightWatch.js +36 -0
  53. package/core/loop.js +199 -0
  54. package/core/math.js +33 -0
  55. package/core/modules.js +182 -0
  56. package/core/movement.js +19 -0
  57. package/core/mulberry32.js +14 -0
  58. package/core/opsCheck.js +86 -0
  59. package/core/opsGuard.js +26 -0
  60. package/core/opsHistory.js +27 -0
  61. package/core/page.js +78 -0
  62. package/core/pureWorker.js +5 -0
  63. package/core/saveApply.js +128 -0
  64. package/core/saveFiles.js +139 -0
  65. package/core/saveIds.js +53 -0
  66. package/core/saveVersions.js +97 -0
  67. package/core/scatter.js +92 -0
  68. package/core/sceneMethods.js +125 -0
  69. package/core/screenToGround.js +39 -0
  70. package/core/session.js +171 -0
  71. package/core/shadowTypes.js +15 -0
  72. package/core/skip.js +104 -0
  73. package/core/startup.js +133 -0
  74. package/core/streamCells.js +24 -0
  75. package/core/streamSources.js +73 -0
  76. package/core/styleParts.js +96 -0
  77. package/core/targeting.js +64 -0
  78. package/core/thingOps.js +157 -0
  79. package/core/things.js +198 -0
  80. package/core/threadPure.js +120 -0
  81. package/core/threadServe.js +25 -0
  82. package/core/tier.js +11 -0
  83. package/core/validate.js +188 -0
  84. package/docs/AI.md +149 -0
  85. package/docs/API.md +84 -0
  86. package/docs/CODEMAP.md +335 -0
  87. package/docs/COMMANDS.md +96 -0
  88. package/docs/CONVENTIONS.md +134 -0
  89. package/docs/PERF.md +217 -0
  90. package/docs/THREE.md +86 -0
  91. package/docs/api/ambience.md +15 -0
  92. package/docs/api/assets.md +60 -0
  93. package/docs/api/audio.md +53 -0
  94. package/docs/api/budget.md +40 -0
  95. package/docs/api/cameraRig.md +120 -0
  96. package/docs/api/characters.md +142 -0
  97. package/docs/api/clock.md +7 -0
  98. package/docs/api/collision.md +35 -0
  99. package/docs/api/content.md +63 -0
  100. package/docs/api/debug.md +10 -0
  101. package/docs/api/dialogue.md +39 -0
  102. package/docs/api/engine.md +190 -0
  103. package/docs/api/entities.md +61 -0
  104. package/docs/api/events.md +91 -0
  105. package/docs/api/flow.md +27 -0
  106. package/docs/api/grids.md +11 -0
  107. package/docs/api/ground.md +16 -0
  108. package/docs/api/hlod.md +34 -0
  109. package/docs/api/hud.md +31 -0
  110. package/docs/api/i18n.md +10 -0
  111. package/docs/api/input.md +24 -0
  112. package/docs/api/interactions.md +31 -0
  113. package/docs/api/inventory.md +66 -0
  114. package/docs/api/jobs.md +10 -0
  115. package/docs/api/level.md +41 -0
  116. package/docs/api/lightPool.md +56 -0
  117. package/docs/api/music.md +34 -0
  118. package/docs/api/nav.md +26 -0
  119. package/docs/api/net.md +14 -0
  120. package/docs/api/openWorld.md +24 -0
  121. package/docs/api/particles.md +41 -0
  122. package/docs/api/photo.md +15 -0
  123. package/docs/api/post.md +9 -0
  124. package/docs/api/quests.md +36 -0
  125. package/docs/api/rays.md +26 -0
  126. package/docs/api/rigid.md +84 -0
  127. package/docs/api/saves.md +31 -0
  128. package/docs/api/settings.md +36 -0
  129. package/docs/api/sky.md +58 -0
  130. package/docs/api/stream.md +31 -0
  131. package/docs/api/style.md +134 -0
  132. package/docs/api/terrain.md +34 -0
  133. package/docs/api/timeline.md +39 -0
  134. package/docs/api/tools.md +55 -0
  135. package/docs/api/triggers.md +56 -0
  136. package/docs/api/vars.md +9 -0
  137. package/docs/api/vegetation.md +52 -0
  138. package/docs/api/water.md +48 -0
  139. package/docs/api/weather.md +29 -0
  140. package/docs/api/world.md +30 -0
  141. package/docs/recipes/01-new-game.md +148 -0
  142. package/docs/recipes/02-npc.md +151 -0
  143. package/docs/recipes/03-items-pickups.md +158 -0
  144. package/docs/recipes/04-quests.md +83 -0
  145. package/docs/recipes/05-props-bake.md +159 -0
  146. package/docs/recipes/06-clock-events.md +104 -0
  147. package/docs/recipes/07-flow-scenes-pause.md +128 -0
  148. package/docs/recipes/08-weather-sky.md +74 -0
  149. package/docs/recipes/09-style-pack.md +234 -0
  150. package/docs/recipes/10-blender-level.md +67 -0
  151. package/docs/recipes/11-vehicles.md +55 -0
  152. package/docs/recipes/12-navmesh.md +57 -0
  153. package/docs/recipes/13-animation.md +146 -0
  154. package/docs/recipes/14-custom-module.md +91 -0
  155. package/docs/recipes/15-perf.md +78 -0
  156. package/docs/recipes/16-dev-bridge.md +146 -0
  157. package/docs/recipes/18-world.md +185 -0
  158. package/docs/recipes/19-shooting-picking.md +76 -0
  159. package/docs/recipes/20-content-actions-save.md +176 -0
  160. package/docs/recipes/21-camera.md +104 -0
  161. package/docs/recipes/22-shop-gold.md +107 -0
  162. package/docs/recipes/23-ops.md +139 -0
  163. package/docs/recipes/26-ui-parts.md +138 -0
  164. package/docs/recipes/27-net.md +96 -0
  165. package/docs/recipes/28-terrain.md +80 -0
  166. package/docs/recipes/29-grid.md +87 -0
  167. package/docs/recipes/30-templates.md +131 -0
  168. package/docs/recipes/31-audio.md +126 -0
  169. package/docs/recipes/32-action-game.md +33 -0
  170. package/docs/recipes/33-stream-sources.md +37 -0
  171. package/docs/recipes/34-environment-lighting.md +35 -0
  172. package/docs/recipes/35-style-from-reference.md +89 -0
  173. package/docs/recipes/36-sky-ground-plant-looks.md +116 -0
  174. package/docs/recipes/37-terrain-look-hooks.md +97 -0
  175. package/docs/recipes/38-environment-look-hooks.md +81 -0
  176. package/docs/recipes/40-scene.md +79 -0
  177. package/docs/recipes/41-thing-registry.md +64 -0
  178. package/docs/recipes/42-terrain-shape.md +64 -0
  179. package/docs/recipes/43-shader-patches-surface-looks.md +118 -0
  180. package/docs/recipes/44-water-weather-look-hooks.md +133 -0
  181. package/docs/recipes/45-cascaded-shadows.md +51 -0
  182. package/docs/recipes/46-blender-art-route.md +92 -0
  183. package/docs/recipes/47-island-snow-backdrop.md +44 -0
  184. package/examples/action/DESIGN.md +3 -0
  185. package/examples/action/GAMEMAP.md +127 -0
  186. package/examples/action/content/actions.js +8 -0
  187. package/examples/action/content/audio.js +9 -0
  188. package/examples/action/content/index.js +9 -0
  189. package/examples/action/content/items.js +4 -0
  190. package/examples/action/content/places.js +4 -0
  191. package/examples/action/content/props.js +11 -0
  192. package/examples/action/content/templates.js +10 -0
  193. package/examples/action/look.js +5 -0
  194. package/examples/action/main.js +137 -0
  195. package/examples/action/models.js +25 -0
  196. package/examples/sheepisland/GAMEMAP.md +108 -0
  197. package/examples/sheepisland/content/index.js +6 -0
  198. package/examples/sheepisland/content/props.js +19 -0
  199. package/examples/sheepisland/content/templates.js +5 -0
  200. package/examples/sheepisland/content/vegetation.js +8 -0
  201. package/examples/sheepisland/main.js +71 -0
  202. package/examples/sheepisland/params.js +25 -0
  203. package/examples/sheepisland/style/index.js +79 -0
  204. package/examples/sheepisland/style/models.js +59 -0
  205. package/examples/sheepisland/views.js +9 -0
  206. package/examples/styletest/GAMEMAP.md +135 -0
  207. package/examples/styletest/content/index.js +9 -0
  208. package/examples/styletest/content/items.js +8 -0
  209. package/examples/styletest/content/npcs.js +8 -0
  210. package/examples/styletest/content/places.js +5 -0
  211. package/examples/styletest/content/props.js +16 -0
  212. package/examples/styletest/content/templates.js +9 -0
  213. package/examples/styletest/content/vegetation.js +31 -0
  214. package/examples/styletest/look.js +11 -0
  215. package/examples/styletest/main.js +95 -0
  216. package/examples/styletest/models.js +87 -0
  217. package/examples/styletest/overrides.js +33 -0
  218. package/examples/styletest/panel.js +135 -0
  219. package/examples/styletest/params.js +32 -0
  220. package/examples/styletest/views.js +31 -0
  221. package/examples/world/DESIGN.md +5 -0
  222. package/examples/world/GAMEMAP.md +171 -0
  223. package/examples/world/content/actions.js +8 -0
  224. package/examples/world/content/audio.js +25 -0
  225. package/examples/world/content/bodies.js +12 -0
  226. package/examples/world/content/containers.js +4 -0
  227. package/examples/world/content/dialogues.js +33 -0
  228. package/examples/world/content/index.js +17 -0
  229. package/examples/world/content/items.js +10 -0
  230. package/examples/world/content/npcs.js +14 -0
  231. package/examples/world/content/pickups.js +11 -0
  232. package/examples/world/content/places.js +6 -0
  233. package/examples/world/content/props.js +12 -0
  234. package/examples/world/content/quests.js +15 -0
  235. package/examples/world/content/rules.js +23 -0
  236. package/examples/world/content/templates.js +5 -0
  237. package/examples/world/content/vegetation.js +32 -0
  238. package/examples/world/main.js +168 -0
  239. package/examples/world/models.js +28 -0
  240. package/index.d.ts +279 -0
  241. package/index.js +120 -0
  242. package/llms.txt +56 -0
  243. package/modules/ambience/Ambience.js +183 -0
  244. package/modules/camera/FirstPersonCamera.js +133 -0
  245. package/modules/camera/FixedCamera.js +155 -0
  246. package/modules/camera/FollowCamera.js +85 -0
  247. package/modules/camera/RtsCamera.js +134 -0
  248. package/modules/camera/common.js +152 -0
  249. package/modules/camera/index.js +11 -0
  250. package/modules/characters/Character.js +223 -0
  251. package/modules/characters/NPC.js +242 -0
  252. package/modules/characters/assetModel.js +42 -0
  253. package/modules/characters/astar.js +59 -0
  254. package/modules/characters/behaviors.js +72 -0
  255. package/modules/characters/footsteps.js +13 -0
  256. package/modules/characters/index.js +212 -0
  257. package/modules/characters/moveHelpers.js +29 -0
  258. package/modules/characters/movers/common.js +62 -0
  259. package/modules/characters/movers/rapier.js +74 -0
  260. package/modules/characters/movers/simple.js +38 -0
  261. package/modules/characters/npcAvoid.js +129 -0
  262. package/modules/characters/npcSim.js +144 -0
  263. package/modules/characters/npcView.js +42 -0
  264. package/modules/characters/pathAsync.js +107 -0
  265. package/modules/characters/pathJob.js +61 -0
  266. package/modules/characters/pathWorker.js +7 -0
  267. package/modules/characters/playerStrings.js +12 -0
  268. package/modules/characters/proceduralRig.js +54 -0
  269. package/modules/collision/Collision.js +176 -0
  270. package/modules/collision/grid.js +63 -0
  271. package/modules/content/ids.js +95 -0
  272. package/modules/content/index.js +152 -0
  273. package/modules/content/loader.js +187 -0
  274. package/modules/content/models.js +69 -0
  275. package/modules/content/packs.js +69 -0
  276. package/modules/content/props.js +89 -0
  277. package/modules/content/rules.js +133 -0
  278. package/modules/content/templates.js +189 -0
  279. package/modules/debug/DebugPanel.js +168 -0
  280. package/modules/entities/Entities.js +239 -0
  281. package/modules/entities/build.js +25 -0
  282. package/modules/entities/index.js +4 -0
  283. package/modules/flow/index.js +98 -0
  284. package/modules/gameplay/Container.js +227 -0
  285. package/modules/gameplay/Containers.js +89 -0
  286. package/modules/gameplay/Dialogue.js +216 -0
  287. package/modules/gameplay/Interactions.js +243 -0
  288. package/modules/gameplay/Inventory.js +214 -0
  289. package/modules/gameplay/Quests.js +195 -0
  290. package/modules/gameplay/boxOps.js +60 -0
  291. package/modules/gameplay/dialogueBox.js +48 -0
  292. package/modules/gameplay/interactionPrompt.js +28 -0
  293. package/modules/gameplay/inventoryOps.js +137 -0
  294. package/modules/gameplay/pickups.js +113 -0
  295. package/modules/gameplay/questLog.js +54 -0
  296. package/modules/gameplay/questSave.js +71 -0
  297. package/modules/grid/Grid.js +184 -0
  298. package/modules/grid/Layer.js +142 -0
  299. package/modules/grid/index.js +236 -0
  300. package/modules/grid/ops.js +73 -0
  301. package/modules/grid/preview.js +85 -0
  302. package/modules/grid/tiles.js +75 -0
  303. package/modules/hlod/index.js +164 -0
  304. package/modules/hud/index.js +164 -0
  305. package/modules/hud/parts.js +80 -0
  306. package/modules/level/geometry.js +46 -0
  307. package/modules/level/heightfield.js +160 -0
  308. package/modules/level/index.js +231 -0
  309. package/modules/level/nodes.js +84 -0
  310. package/modules/lights/index.js +224 -0
  311. package/modules/music/Music.js +290 -0
  312. package/modules/music/index.js +2 -0
  313. package/modules/music/rules.js +28 -0
  314. package/modules/nav/index.js +154 -0
  315. package/modules/nav/navPath.js +17 -0
  316. package/modules/net/Client.js +136 -0
  317. package/modules/net/Host.js +117 -0
  318. package/modules/net/Net.js +49 -0
  319. package/modules/net/index.js +75 -0
  320. package/modules/net/sync.js +114 -0
  321. package/modules/net/transports.js +118 -0
  322. package/modules/particles/Particles.js +179 -0
  323. package/modules/particles/effect.js +112 -0
  324. package/modules/particles/shaders.js +28 -0
  325. package/modules/photo/Photo.js +143 -0
  326. package/modules/rigid/RigidBodies.js +262 -0
  327. package/modules/rigid/Vehicles.js +97 -0
  328. package/modules/rigid/sync.js +158 -0
  329. package/modules/settings/Settings.js +294 -0
  330. package/modules/settings/apply.js +20 -0
  331. package/modules/settings/index.js +3 -0
  332. package/modules/settings/sections.js +156 -0
  333. package/modules/settings/strings.js +53 -0
  334. package/modules/settings/view.js +65 -0
  335. package/modules/sky/Sky.js +257 -0
  336. package/modules/sky/calendar.js +80 -0
  337. package/modules/sky/cascades.js +125 -0
  338. package/modules/sky/clouds.js +79 -0
  339. package/modules/sky/domeLayers.js +33 -0
  340. package/modules/sky/environment.js +115 -0
  341. package/modules/sky/fog.js +136 -0
  342. package/modules/sky/frame.js +76 -0
  343. package/modules/sky/layers.js +69 -0
  344. package/modules/sky/look.js +50 -0
  345. package/modules/sky/schedule.js +80 -0
  346. package/modules/sky/shader.js +96 -0
  347. package/modules/sky/shadow.js +80 -0
  348. package/modules/sky/skyModule.js +59 -0
  349. package/modules/terrain/ChunkManager.js +291 -0
  350. package/modules/terrain/chunkJob.js +19 -0
  351. package/modules/terrain/chunkQueries.js +42 -0
  352. package/modules/terrain/chunkWorker.js +5 -0
  353. package/modules/terrain/index.js +110 -0
  354. package/modules/terrain/mountTerrain.js +32 -0
  355. package/modules/terrain/terrainColorMap.js +41 -0
  356. package/modules/terrain/terrainDefaults.js +39 -0
  357. package/modules/terrain/terrainEdit.js +139 -0
  358. package/modules/terrain/terrainGen.js +155 -0
  359. package/modules/terrain/terrainIsland.js +131 -0
  360. package/modules/terrain/terrainMesh.js +92 -0
  361. package/modules/terrain/terrainShape.js +108 -0
  362. package/modules/terrain/terrainShapeMain.js +41 -0
  363. package/modules/terrain/terrainTexture.js +44 -0
  364. package/modules/timeline/Timeline.js +249 -0
  365. package/modules/timeline/Tween.js +118 -0
  366. package/modules/timeline/letterbox.js +24 -0
  367. package/modules/timeline/shots.js +88 -0
  368. package/modules/triggers/index.js +261 -0
  369. package/modules/vegetation/Vegetation.js +255 -0
  370. package/modules/vegetation/groundChunks.js +177 -0
  371. package/modules/vegetation/index.js +40 -0
  372. package/modules/vegetation/modelGeometry.js +21 -0
  373. package/modules/water/Water.js +144 -0
  374. package/modules/water/surface.js +88 -0
  375. package/modules/weather/Weather.js +251 -0
  376. package/modules/weather/particles.js +92 -0
  377. package/modules/weather/shaders.js +49 -0
  378. package/modules/world/World.js +231 -0
  379. package/modules/world/cells.js +42 -0
  380. package/modules/world/index.js +64 -0
  381. package/modules/world/persist.js +107 -0
  382. package/modules/world/pos.js +20 -0
  383. package/modules/world/records.js +89 -0
  384. package/modules/world/sim.js +175 -0
  385. package/modules/world/simFar.js +82 -0
  386. package/modules/world/state.js +115 -0
  387. package/modules/world/views.js +182 -0
  388. package/package.json +66 -4
  389. package/presets.js +96 -0
  390. package/render/PostFX.js +243 -0
  391. package/render/detail.js +105 -0
  392. package/render/effects.js +142 -0
  393. package/render/engineUniforms.js +23 -0
  394. package/render/fuse.js +72 -0
  395. package/render/lighting.js +100 -0
  396. package/render/lights.js +16 -0
  397. package/render/materials.js +203 -0
  398. package/render/patches.js +252 -0
  399. package/render/surface.js +67 -0
  400. package/render/uniformDecl.js +29 -0
  401. package/types/common.d.ts +34 -0
  402. package/types/core.d.ts +1773 -0
  403. package/types/gameplay.d.ts +1812 -0
  404. package/types/generated/core/Audio.d.ts +200 -0
  405. package/types/generated/core/Batching.d.ts +47 -0
  406. package/types/generated/core/Budget.d.ts +90 -0
  407. package/types/generated/core/Commits.d.ts +31 -0
  408. package/types/generated/core/Events.d.ts +46 -0
  409. package/types/generated/core/I18n.d.ts +30 -0
  410. package/types/generated/core/Input.d.ts +118 -0
  411. package/types/generated/core/Jobs.d.ts +41 -0
  412. package/types/generated/core/Ops.d.ts +162 -0
  413. package/types/generated/core/Random.d.ts +49 -0
  414. package/types/generated/core/Rays.d.ts +49 -0
  415. package/types/generated/core/Saves.d.ts +161 -0
  416. package/types/generated/core/Stream.d.ts +93 -0
  417. package/types/generated/core/Threads.d.ts +82 -0
  418. package/types/generated/core/audioVoice.d.ts +47 -0
  419. package/types/generated/core/page.d.ts +18 -0
  420. package/types/generated/core/session.d.ts +48 -0
  421. package/types/generated/modules/ambience/Ambience.d.ts +48 -0
  422. package/types/generated/modules/debug/DebugPanel.d.ts +24 -0
  423. package/types/generated/modules/flow/index.d.ts +10 -0
  424. package/types/generated/modules/grid/Grid.d.ts +151 -0
  425. package/types/generated/modules/grid/Layer.d.ts +64 -0
  426. package/types/generated/modules/grid/index.d.ts +86 -0
  427. package/types/generated/modules/hlod/index.d.ts +11 -0
  428. package/types/generated/modules/hud/index.d.ts +10 -0
  429. package/types/generated/modules/lights/index.d.ts +13 -0
  430. package/types/generated/modules/music/Music.d.ts +111 -0
  431. package/types/generated/modules/net/Net.d.ts +34 -0
  432. package/types/generated/modules/net/index.d.ts +53 -0
  433. package/types/generated/modules/net/transports.d.ts +58 -0
  434. package/types/generated/modules/particles/Particles.d.ts +69 -0
  435. package/types/generated/modules/sky/Sky.d.ts +152 -0
  436. package/types/generated/modules/sky/skyModule.d.ts +10 -0
  437. package/types/generated/modules/timeline/Timeline.d.ts +51 -0
  438. package/types/generated/modules/water/Water.d.ts +29 -0
  439. package/types/generated/modules/weather/Weather.d.ts +72 -0
  440. package/types/generated/modules/world/World.d.ts +242 -0
  441. package/types/generated/modules/world/index.d.ts +15 -0
  442. package/types/generated/render/PostFX.d.ts +128 -0
  443. package/types/generated/render/materials.d.ts +90 -0
  444. package/types/generated/render/patches.d.ts +41 -0
  445. package/types/generated/ui/Focus.d.ts +11 -0
  446. package/types/generated/ui/LoadingScreen.d.ts +2 -0
  447. package/types/generated/ui/UI.d.ts +57 -0
  448. package/types/nav.d.ts +52 -0
  449. package/types/physics.d.ts +584 -0
  450. package/types/style.d.ts +628 -0
  451. package/types/worker.d.ts +11 -0
  452. package/types/world.d.ts +772 -0
  453. package/ui/Focus.js +51 -0
  454. package/ui/LoadingScreen.js +42 -0
  455. package/ui/Parts.js +195 -0
  456. package/ui/UI.js +167 -0
  457. package/ui/defaults.js +85 -0
  458. package/ui/theme.js +124 -0
  459. package/ui/touchPart.js +49 -0
@@ -0,0 +1,42 @@
1
+ // Spatial index for world: the xz plane is cut into fixed-size cells (default 32 m) and each record is filed under its cell. Distance queries and focus-based model building both pre-filter by cell.
2
+ // Cell keys are numbers and cells hold record objects directly: there are hundreds to thousands of moves and neighbor queries per step, and string keys plus id lookups would only add garbage and cost.
3
+
4
+ const OFF = 2 ** 20, SPAN = 2 ** 21; // ±1 million cells in each direction (±30,000 km at 32 m per cell); keys stay safe integers
5
+
6
+ /** @internal */
7
+ export class Cells {
8
+ /** @param {number} size cell edge length (meters) */
9
+ constructor(size) {
10
+ this.size = size;
11
+ this.map = new Map(); // cell key → Set<record> (deleted when empty, so walked-through areas leave no empty cells)
12
+ this.of = new Map(); // id → cell key
13
+ }
14
+ key(x, z) { return (Math.floor(x / this.size) + OFF) * SPAN + Math.floor(z / this.size) + OFF; }
15
+ /** Put into / move to the cell containing the position; returns true if the cell changed */
16
+ put(rec) {
17
+ const k = this.key(rec.position.x, rec.position.z), old = this.of.get(rec.id);
18
+ if (old === k) return false;
19
+ if (old !== undefined) this.out(old, rec);
20
+ let set = this.map.get(k); if (!set) this.map.set(k, set = new Set());
21
+ set.add(rec); this.of.set(rec.id, k);
22
+ return true;
23
+ }
24
+ delete(rec) { const k = this.of.get(rec.id); if (k !== undefined) this.out(k, rec); this.of.delete(rec.id); }
25
+ out(k, rec) { const set = this.map.get(k); set.delete(rec); if (!set.size) this.map.delete(k); }
26
+ clear() { this.map.clear(); this.of.clear(); }
27
+ /** Call fn(rec, squared distance) for each record within radius of c. No allocation, no sorting.
28
+ * When the circle covers more cells than exist (huge radius, even Infinity) scan all cells instead, so it cannot hang */
29
+ forEach(c, radius, fn) {
30
+ const s = this.size, r2 = radius * radius, cx = c.x, cz = c.z;
31
+ const x0 = Math.floor((cx - radius) / s), x1 = Math.floor((cx + radius) / s), z0 = Math.floor((cz - radius) / s), z1 = Math.floor((cz + radius) / s);
32
+ if ((x1 - x0 + 1) * (z1 - z0 + 1) > this.map.size) { for (const set of this.map.values()) visit(set, cx, cz, r2, fn); return; }
33
+ for (let x = x0; x <= x1; x++) for (let z = z0; z <= z1; z++) {
34
+ const set = this.map.get((x + OFF) * SPAN + z + OFF);
35
+ if (set) visit(set, cx, cz, r2, fn);
36
+ }
37
+ }
38
+ }
39
+
40
+ function visit(set, cx, cz, r2, fn) {
41
+ for (const rec of set) { const dx = rec.position.x - cx, dz = rec.position.z - cz, d2 = dx * dx + dz * dz; if (d2 <= r2) fn(rec, d2); }
42
+ }
@@ -0,0 +1,64 @@
1
+ // world() module: installed as engine.world (world data, see World.js). Models load around engine.stream sources; records stay when models unload. Independent of game type: slow-life NPCs, shooter enemies, survival zombies and containers all use it.
2
+ // engine.use(world()) // the openWorld() preset installs it by default
3
+ // engine.use(world({ radius: 80 })) // distance (meters) for building models and counting as near, default 60
4
+ // Save key world (runtime records whole, initial records only changes and removals, see the top of World.js); emits world:load after loading. The loading screen waits for world.ready (nearby models all built). describe() reports world.total / byKind / presented, and nearby records with a name go into nearby.
5
+ import { World } from './World.js';
6
+ import { WORLD_MIGRATE } from './persist.js';
7
+ import { checkOptions, closest, warnOnce, DEV } from '../../core/validate.js';
8
+
9
+ const ORPHAN = '[world] the save has changes for {n} id(s) that the content no longer defines: {list}. They are kept in the save (restoring the entry brings them back); '
10
+ + "if an entry was renamed, add the pair to content/renames.js (export default { 'oldId': 'newId' }) and the saved state follows it; 'oldId': null drops it";
11
+ const RENAME_TARGET = '[world] content/renames.js moves saved state to {list}, which no content entry defines: fix the new id (did you mean {near}?)';
12
+
13
+ /**
14
+ * World data module: installed as engine.world. Put things here that must be saved, survive level changes and keep changing while far away; models are only built while nearby
15
+ * @example engine.use(world())
16
+ * @param {{ cellSize?: number, radius?: number, farEvery?: number, farMaxPerTick?: number, buildPerFrame?: number }} [opts]
17
+ * @returns {import('../../types/core').ModuleDef<World>}
18
+ */
19
+ export function world(opts = {}) {
20
+ checkOptions('world()', opts, ['cellSize', 'radius', 'farEvery', 'farMaxPerTick', 'buildPerFrame']);
21
+ let w = null;
22
+ return {
23
+ name: 'world', label: 'World data', stage: 'world',
24
+ install(e) {
25
+ w = new World(e, opts);
26
+ e.stream.player.at(() => w.center); // the default stream source sits where gameplay is simulated (world.anchor, else the player)
27
+ e.stream.readyCheck('world', s => s.detail !== 'full' || w.ready);
28
+ e.saves.register('world', { version: 3, migrate: WORLD_MIGRATE, save: () => w.toJSON(), load: d => w.fromJSON(d) });
29
+ e.budget.metric('worldRecords', () => w.records.size);
30
+ if (DEV) { // orphans are known once content loaded (engine:ready), after a load, and per level for `<level>/<node>` ids
31
+ const warn = () => {
32
+ targets();
33
+ const o = w.orphans(); if (!o.length) return;
34
+ const ids = [...w._base.keys()];
35
+ // a near id the save has no data for is the likely new name: suggest the exact renames.js pair
36
+ const list = o.slice(0, 8).map(id => { const c = closest(id, ids); return c ? `${id} (did you mean ${c}? renames: { '${id}': '${c}' })` : id; });
37
+ warnOnce(ORPHAN.replace('{n}', String(o.length)).replace('{list}', list.join(', ') + (o.length > 8 ? ', …' : '')));
38
+ };
39
+ const targets = () => { // a rename target nothing defines moves the player's state into a void: name it (level-node targets once that level loaded)
40
+ const due = id => { const i = id.indexOf('/'); return i < 0 || w._levels.has(id.slice(0, i)); };
41
+ const bad = [...w._renames].filter(([, b]) => b != null && !w._base.has(b) && due(b));
42
+ if (bad.length) warnOnce(RENAME_TARGET.replace('{list}', bad.map(([a, b]) => `${b} (from ${a})`).join(', ')).replace('{near}', closest(bad[0][1], [...w._base.keys()]) ?? '-'));
43
+ };
44
+ for (const ev of ['engine:ready', 'save:loaded', 'level:loaded']) e.events.on(ev, () => { if (e.ready) warn(); });
45
+ }
46
+ return w;
47
+ },
48
+ isReady() { return w.ready; },
49
+ afterLoad(e) { if (e.paused) w.refresh(); return w.whenReady; }, // a paused engine has no frames to build in: build now
50
+ counts() { let views = 0; for (const id of w.records.keys()) if (w.view(id)) views++; return { records: w.records.size, views }; }, // engine.counts().world
51
+ fixed(dt) { w.fixed(dt); },
52
+ skip(dt, e, done) { w._s.skip(dt, done); },
53
+ frame(dt) { w.frame(dt); },
54
+ describe(e, ctx) {
55
+ const byKind = {};
56
+ for (const r of w.records.values()) byKind[r.kind] = (byKind[r.kind] || 0) + 1;
57
+ // with a model, report by the model (merged with the interaction and other modules' reports on the same object into one entry); skip records of another zone (level)
58
+ for (const r of w.query({ near: ctx.center, radius: ctx.radius })) if (r.name != null && w._inZone(r)) ctx.near(w.view(r.id) ?? r.position, { id: r.id, name: r.name, kind: r.kind }, true);
59
+ const orphans = w.orphans();
60
+ return { total: w.records.size, byKind, presented: w._v.map.size, zone: w.zone, ...(orphans.length && { orphans: orphans.slice(0, 20) }) };
61
+ },
62
+ dispose() { w.dispose(); },
63
+ };
64
+ }
@@ -0,0 +1,107 @@
1
+ // World saves and initial records. Rules (independent of the order of content.load):
2
+ // Things written in content (props, pickups, NPCs…) are initial records: add(def, { initial: true }), which needs a stable id.
3
+ // A save only keeps "which fields changed" and "which were removed" (tombstones) for them; runtime-created ones (a tree the player planted, a spawned monster) are saved whole.
4
+ // Load: runtime records are replaced wholesale by the save's; initial records first go back to their original content, then the save's changes are applied; records removed in the save do not reappear.
5
+ // Orphans: a change or removal in the save whose id the content no longer produces (renamed / deleted entry) is kept in _pending / _removed and
6
+ // written back by the next save, never dropped, so reverting the content change gets the player's data back; dev warns once (world.orphans()).
7
+ // Loading before content is loaded works too: changes and removals are remembered and applied / skipped when content is added. Things newly added to content after a game update still show up with an old save.
8
+ // Temporary things (data for effects, one-off spawns): add(def, { save: false }) — not saved, cleared on load.
9
+ // Changes are found by comparing JSON against the original content, not by events: fields changed directly inside simulate are saved too.
10
+ // Save format (part 'world', version 3): every record is keyed by its stable id, and only what play changed is stored:
11
+ // { seq, step, time, records: { id: whole runtime record without id }, changed: { id: { set?: changed fields, del?: [removed fields] } },
12
+ // removed: [ids of removed initial records], owed: { id: simulation seconds owed, only for kinds simulated with far } }
13
+ // Version 1 kept records as an array: migrate step 1 (WORLD_MIGRATE) turns it into the id-keyed object.
14
+ // Version 2 numbered runtime records `<kind>-<n>`; version 3 uses `<kind>#<n>`, so a runtime id can never equal an authored one (authored ids may not
15
+ // contain `#`, content/ids.js). Step 2 renames them (legacyRuntimeIds says which), and the containers part follows with the same map (a template
16
+ // instance's container is keyed by the record id).
17
+ // Removed fields are recorded separately (not saved as null): after loading it is "no such field", same as in a live run; a field that was null stays null.
18
+ // step / time are the simulation step count and accumulated seconds: far simulation takes turns by step-count buckets, so one save advances the same way every time (see sim.js).
19
+
20
+ import { legacyRuntimeIds, renameIdKeys, renameIdValues } from '../../core/saveIds.js';
21
+
22
+ const PLAIN_STRINGS = {
23
+ msg: 'world data must be plain values (number, string, boolean, array, plain object): {path} is {what}. Put models in world.present() and logic in world.simulate()',
24
+ fn: 'a function', obj: 'a three.js object', asset: 'a three.js asset', dom: 'a DOM element',
25
+ };
26
+ /** Dev-time check: data must not contain three.js objects, functions or DOM elements (saves can only store plain values) @internal */
27
+ export function checkPlain(v, path, depth = 0) {
28
+ const fail = what => { throw new Error(PLAIN_STRINGS.msg.replace('{path}', path).replace('{what}', what)); };
29
+ if (v == null || typeof v !== 'object') { if (typeof v === 'function') fail(PLAIN_STRINGS.fn); return; }
30
+ const what = v.isObject3D ? PLAIN_STRINGS.obj : v.isMaterial || v.isBufferGeometry || v.isTexture ? PLAIN_STRINGS.asset : typeof Element !== 'undefined' && v instanceof Element ? PLAIN_STRINGS.dom : null;
31
+ if (what) fail(what);
32
+ if (depth > 6) return;
33
+ for (const k in v) checkPlain(v[k], `${path}.${k}`, depth + 1);
34
+ }
35
+
36
+ /** Compare an initial record with its original: which top-level fields changed, which were removed (null if neither) */
37
+ function diff(rec, base) {
38
+ let set = null, del = null;
39
+ for (const k in rec) {
40
+ if (rec[k] === undefined) { if (k in base) (del ||= []).push(k); continue; } // set to undefined = removed
41
+ if (JSON.stringify(rec[k]) !== JSON.stringify(base[k])) (set ||= {})[k] = rec[k];
42
+ }
43
+ for (const k in base) if (!(k in rec)) (del ||= []).push(k);
44
+ return set || del ? { set: set ?? undefined, del: del ?? undefined } : null;
45
+ }
46
+
47
+ /** Upgrade steps of the world save part (saves.register version 3) @internal */
48
+ export const WORLD_MIGRATE = {
49
+ 1: d => ({ ...d, records: Object.fromEntries((d?.records || []).map(({ id, ...r }) => [id, r])) }), // array of records -> keyed by id
50
+ 2: d => { // runtime ids `<kind>-<n>` -> `<kind>#<n>`: record keys, owed keys, and field values that name a renamed record
51
+ const map = legacyRuntimeIds(d);
52
+ if (!map.size) return d;
53
+ return { ...d, records: renameIdValues(renameIdKeys(d.records, map), map), changed: renameIdValues(d.changed, map), owed: renameIdKeys(d.owed, map) };
54
+ },
55
+ };
56
+
57
+
58
+
59
+ /** @param {import('./World.js').World} w @internal */
60
+ export function saveWorld(w) {
61
+ const records = {}, changed = {};
62
+ for (const rec of w.records.values()) {
63
+ if (w._unsaved.has(rec.id)) continue;
64
+ const base = w._base.get(rec.id);
65
+ if (!base) { const { id, ...r } = rec; records[id] = r; continue; }
66
+ const d = diff(rec, base);
67
+ if (d) changed[rec.id] = d;
68
+ }
69
+ for (const [id, d] of w._pending) changed[id] = d; // from a save, content not loaded yet this time (e.g. another level): keep as is
70
+ return { seq: w._seq, ...w._s.toJSON(), records, changed, removed: [...w._removed] };
71
+ }
72
+
73
+ /** Load: replace runtime records wholesale; loaded initial records go back to the original then get the save's changes; unloaded content waits for its add. Independent of the order of content.load @internal */
74
+ export function loadWorld(w, d) {
75
+ w._v.clear();
76
+ w.records.clear(); w._cells.clear(); w._unsaved.clear();
77
+ for (const id of [...w._origin.keys()]) if (!w._base.has(id)) w._origin.delete(id); // runtime records come from the save now (no op to name)
78
+ w._seq = d?.seq ?? 0;
79
+ w._removed = new Set(d?.removed);
80
+ w._pending = new Map(Object.entries(d?.changed || {}));
81
+ w._s.fromJSON(d);
82
+ renamePending(w); // content/renames.js, before initial records take their diffs
83
+ for (const [id, base] of w._base) if (!w._removed.has(id)) w._insert(w._fromBase(id, base));
84
+ for (const [id, r] of Object.entries(d?.records || {})) w._insert({ id, ...r });
85
+ w.engine.events.emit('world:load', { count: w.records.size });
86
+ }
87
+
88
+ /**
89
+ * Apply content/renames.js to the save data waiting for content: changed fields (_pending), removals (_removed) and owed simulation time move from the old
90
+ * id to the new one; a null target drops them (deleted on purpose, so they are no orphans). Skipped, and returned as 'old (why)', when the old id is still
91
+ * authored (the rename would steal its data) or the new id already has saved data (two saves' worth of state cannot merge): those stay orphans. @internal
92
+ * @param {import('./World.js').World} w
93
+ * @returns {string[]}
94
+ */
95
+ export function renamePending(w) {
96
+ const stuck = [], owed = w._s.owed;
97
+ for (const [a, b] of w._renames) {
98
+ const has = w._pending.has(a) || w._removed.has(a) || owed.has(a);
99
+ if (!has) continue;
100
+ if (w._base.has(a)) { stuck.push(`${a} (still defined by content)`); continue; }
101
+ if (b != null && (w._pending.has(b) || w._removed.has(b) || owed.has(b))) { stuck.push(`${a} (${b} already has saved changes)`); continue; }
102
+ if (w._pending.has(a)) { if (b != null) w._pending.set(b, w._pending.get(a)); w._pending.delete(a); }
103
+ if (w._removed.delete(a) && b != null) w._removed.add(b);
104
+ if (owed.has(a)) { if (b != null) owed.set(b, owed.get(a)); owed.delete(a); }
105
+ }
106
+ return stuck;
107
+ }
@@ -0,0 +1,20 @@
1
+ // Position read / write for world: shared by add / move / query. A wrong position (a Vector3 used as an array, [x, z] with only two numbers) silently becomes NaN and null in the save,
2
+ // so dev builds throw on the spot and say how to fix it.
3
+ import { DEV } from '../../core/validate.js';
4
+
5
+ const STRINGS = {
6
+ arr: '{fn}: an array position must be [x, y, z] (three numbers); for a horizontal position only, write { x, z }',
7
+ nan: '{fn}: position is not a valid number (got {got}). Common cause: a Vector3 used as an array (v[0] is undefined); write v.x / v.z, or pass the Vector3 itself',
8
+ };
9
+
10
+ /** Write position v (Vector3 / object / [x, y, z] / { x, z }) into p; y stays unchanged if omitted @internal */
11
+ export function putPos(fn, v, p) {
12
+ const arr = Array.isArray(v), o = v.isObject3D ? v.position : v;
13
+ if (DEV && arr && v.length !== 3) throw new Error(STRINGS.arr.replace('{fn}', fn));
14
+ const x = arr ? v[0] : o.x, y = arr ? v[1] : o.y ?? p.y, z = arr ? v[2] : o.z;
15
+ // check before writing: a bad position leaves no half-written NaN in the data
16
+ if (DEV && !(Number.isFinite(x) && Number.isFinite(y) && Number.isFinite(z))) throw new Error(STRINGS.nan.replace('{fn}', fn).replace('{got}', JSON.stringify(v)));
17
+ p.x = x; p.y = y; p.z = z;
18
+ }
19
+ /** Query center: objects use position, arrays are [x, y, z], others (Vector3 / { x, z }) are used as is, no allocation @internal */
20
+ export const centerOf = c => c.isObject3D ? c.position : Array.isArray(c) ? { x: c[0], z: c[2] } : c;
@@ -0,0 +1,89 @@
1
+ // World record mutations (add / rest / orphans / set / remove): the bodies behind the World methods of the same names. World.js keeps the public
2
+ // JSDoc and signatures; these functions take the world as `w` and reach its internals the same way sim.js / views.js / persist.js do.
3
+ import { DEV, checkOptionsArg, fmt } from '../../core/validate.js';
4
+ import { checkPlain } from './persist.js';
5
+ import { putPos, centerOf } from './pos.js';
6
+ import { claimId } from '../../core/things.js';
7
+
8
+ export const STRINGS = {
9
+ noKind: 'world.add() needs a kind (what sort of thing this is), e.g. world.add({ kind: "crate", position: [0, 0, 0] })',
10
+ dupId: 'world.add(): id "{id}" already exists. Omit id to auto-number; to change an existing record use world.set("{id}", { … })',
11
+ initialId: 'world.add(def, { initial: true }) needs a stable id (saves match content by id), e.g. world.add({ id: "chest_1", kind: "{kind}", … }, { initial: true })',
12
+ noId: 'world.{fn}(): no record with id "{id}" (world.query({ kind }) lists what exists)',
13
+ setKey: 'world.set("{id}", patch): patch must not contain id / kind (they are the identity of the record). To change the kind, remove then add',
14
+ };
15
+
16
+ export function addRecord(w, def, opts) {
17
+ DEV && w.engine.ops.guard('world.add');
18
+ if (!def?.kind) throw new Error(STRINGS.noKind);
19
+ if (DEV) { checkOptionsArg('world.add(def, opts)', opts, ['initial', 'save']); checkPlain({ ...def, position: undefined }, def.kind); }
20
+ const { id: given, kind, position, ...rest } = def, initial = !!opts?.initial;
21
+ if (initial && given == null) throw new Error(fmt(STRINGS.initialId, { kind }));
22
+ const id = given ?? `${kind}#${++w._seq}`, have = w.records.get(id), p = { x: 0, y: 0, z: 0 };
23
+ if (position) putPos('world.add()', position, p);
24
+ const rec = { id, kind, position: p, ...rest };
25
+ if (initial) {
26
+ if (!w._base.has(id)) w._base.set(id, structuredClone(rec));
27
+ if (have) return have;
28
+ claimId(w.engine, id);
29
+ if (w._removed.has(id)) return null;
30
+ return w._insert(w._fromBase(id, w._base.get(id)), true);
31
+ }
32
+ if (have) throw new Error(fmt(STRINGS.dupId, { id }));
33
+ claimId(w.engine, id);
34
+ if (opts?.save === false) w._unsaved.add(id);
35
+ if (DEV) w._origin.set(id, { spawned: { op: w.engine.ops.running, tick: w.engine.tick } }); // who made it (inspect / pick)
36
+ return w._insert(rec, true);
37
+ }
38
+
39
+ export function restRecord(w, id, position, tolerance) {
40
+ const rec = w.records.get(id), base = w._base.get(id); if (!rec) return;
41
+ const a = rec.position, b = base?.position;
42
+ const same = !!b && Math.abs(a.x - b.x) <= tolerance && Math.abs(a.y - b.y) <= tolerance && Math.abs(a.z - b.z) <= tolerance;
43
+ putPos(`world.rest("${id}")`, position, rec.position); w._index(rec);
44
+ if (same) base.position = { ...rec.position };
45
+ }
46
+
47
+ export function orphanIds(w) {
48
+ const out = [], known = id => w._base.has(id) || w.records.has(id);
49
+ const due = id => { const i = id.indexOf('/'); return i < 0 || w._levels.has(id.slice(0, i)); };
50
+ for (const id of w._pending.keys()) if (!known(id) && due(id)) out.push(id);
51
+ for (const id of w._removed) if (!known(id) && !w._base.has(id) && due(id)) out.push(id);
52
+ return out;
53
+ }
54
+
55
+ export function setRecord(w, id, patch) {
56
+ DEV && w.engine.ops.guard('world.set');
57
+ const rec = w._need(id, 'set');
58
+ if (DEV) { if ('id' in patch || 'kind' in patch) throw new Error(fmt(STRINGS.setKey, { id })); checkPlain({ ...patch, position: undefined }, id); }
59
+ const { position, ...rest } = patch;
60
+ Object.assign(rec, rest);
61
+ if (position) w.move(id, position);
62
+ if (w._v.presenters.get(rec.kind)?.show) w._v.dirty = true;
63
+ w.engine.events.emit('world:change', { id, kind: rec.kind, keys: Object.keys(patch) });
64
+ return rec;
65
+ }
66
+
67
+ export function removeRecord(w, id) {
68
+ DEV && w.engine.ops.guard('world.remove');
69
+ const rec = w.records.get(id); if (!rec) return;
70
+ w._v.unview(id);
71
+ w._cells.delete(rec);
72
+ w.records.delete(id);
73
+ w._s.removed(id);
74
+ w._unsaved.delete(id);
75
+ if (w._base.has(id)) w._removed.add(id); else w._origin.delete(id);
76
+ w.engine.events.emit('world:remove', { id, kind: rec.kind });
77
+ }
78
+
79
+ export function queryRecords(w, opts) {
80
+ const { kind, near, radius = 30, where, zone } = opts, out = [];
81
+ const ok = r => (!kind || r.kind === kind) && (zone === undefined || (r.zone ?? null) === zone) && (!where || where(r));
82
+ if (near) {
83
+ w._cells.forEach(centerOf(near), radius, (r, d2) => { if (ok(r)) out.push([d2, r]); });
84
+ return out.sort((a, b) => a[0] - b[0]).map(a => a[1]);
85
+ }
86
+ if (!kind) return [...w.records.values()].filter(ok);
87
+ for (const e of w._s.kinds.get(kind)?.set ?? []) if (ok(e.rec)) out.push(e.rec); // table grouped by kind: no full scan
88
+ return out;
89
+ }
@@ -0,0 +1,175 @@
1
+ // Simulation layer of world: near records every fixed step, far records in id buckets taking turns under a per-step cap. The public API is in World.js
2
+ // (simulate / anchor); this is the implementation.
3
+ // Time: the dt of both near and far is "accumulated fixed-step seconds" (same ruler as every engine hook's dt, not multiplied by clock.timeScale).
4
+ // For one record going near, far, near again, the dts add up to the elapsed time:
5
+ // far dt = seconds accumulated since the last simulation; on the far → near step, far first pays back the owed time, then near runs.
6
+ // A kind with only far (crops) does not split near / far and always advances at far's pace; a kind with only near is not simulated while far and its owed time
7
+ // is not made up.
8
+ // Owed time is saved: it is paid back after loading, so simulate code never tracks time itself.
9
+ // Determinism: near / far is split by the gameplay anchor (world.anchor), far work is capped by count with the rest queued first for the next step, and buckets
10
+ // follow the step count (saved) —
11
+ // so the result depends only on data and step count, not on machine speed, frame rate or whether models are built.
12
+ // Far with worker: true goes through simFar.js (batched to engine.threads, written back on a fixed later step through commits).
13
+ // Near order: at the start of each step collect records inside the radius, then simulate them sorted by id — order inside a cell depends on insertion order and
14
+ // changes after loading;
15
+ // when near records affect each other (avoiding each other, fighting over the same thing), sorting by id keeps "kept running" and "saved then loaded"
16
+ // bit-identical.
17
+
18
+ import { DEV, checkOptionsArg } from '../../core/validate.js';
19
+ import { FarFlights } from './simFar.js';
20
+
21
+ /** Near simulation order: by id (independent of insertion order and loading) */
22
+ const byId = (a, b) => a.rec.id < b.rec.id ? -1 : 1;
23
+ /** Simple hash of id: far simulation uses it to pick a bucket (computed once per record, stored on ent) */
24
+ const hashOf = s => { let h = 0; for (let i = 0; i < s.length; i++) h = (Math.imul(h, 31) + s.charCodeAt(i)) | 0; return h >>> 0; };
25
+
26
+ /** @internal */
27
+ export class Sim {
28
+ /** @param {import('./World.js').World} w */
29
+ constructor(w) {
30
+ this.w = w;
31
+ this.sims = new Map(); // kind → { near, far, farEvery, radius }
32
+ this.ents = new Map(); // id → { rec, h, last, near, queued, dead }: last = time of the last simulation, near = step number of the last near simulation
33
+ this.kinds = new Map(); // kind → { set: Set<ent>, P, buckets }: P is the far period (steps), buckets[step % P] is this step's turn
34
+ this.owed = new Map(); // from a save, content not added yet: id → time of the last simulation (used when added)
35
+ this.backlog = []; // far simulations left undone by the previous step's cap (FIFO, done first next step)
36
+ this.time = 0; // accumulated simulation seconds (saved)
37
+ this.n = 0; // simulation step count (saved: buckets follow it, so after loading the same batch is up as in a live run)
38
+ this.at = { x: 0, z: 0 }; // this step's simulation center (taken from world.anchor at the start of each step)
39
+ this.dt = 0;
40
+ this.list = []; // records to simulate near this step (reused, not allocated each step)
41
+ this.flights = new FarFlights(this); // far with worker: true (simFar.js)
42
+ // created once, no closure per step
43
+ this._pick = (rec, d2) => { const s = this.sims.get(rec.kind); if (s && d2 <= s.r2 && this.w._inZone(rec)) this.list.push(this.ents.get(rec.id)); };
44
+ }
45
+
46
+ simulate(kind, opts) {
47
+ if (DEV) checkOptionsArg(`world.simulate('${kind}', opts)`, opts, ['near', 'far', 'farEvery', 'radius', 'worker']);
48
+ const s = { ...opts };
49
+ if (s.worker && s.far) this.flights.register(kind, s);
50
+ this.sims.set(kind, s);
51
+ return { remove: () => { if (this.sims.get(kind) === s) this.sims.delete(kind); } };
52
+ }
53
+ /** A new record starts counting time from the moment it is added (owed time from a save carries on) */
54
+ added(rec) {
55
+ const id = rec.id, o = this.owed.get(id);
56
+ if (o !== undefined) this.owed.delete(id);
57
+ const e = { rec, h: hashOf(id), last: o ?? this.time, near: -1, queued: false, dead: false, flight: null };
58
+ this.ents.set(id, e);
59
+ let K = this.kinds.get(rec.kind); if (!K) this.kinds.set(rec.kind, K = { set: new Set(), P: 0, buckets: null });
60
+ K.set.add(e); if (K.P) K.buckets[e.h % K.P].add(e);
61
+ }
62
+ removed(id) {
63
+ const e = this.ents.get(id); if (!e) return;
64
+ this.ents.delete(id); e.dead = true; // queued entries are skipped when seen dead
65
+ const K = this.kinds.get(e.rec.kind); K.set.delete(e); if (K.P) K.buckets[e.h % K.P].delete(e);
66
+ }
67
+ /** This record was simulated near in the latest step (the presentation layer uses it to keep positionFrom 'view' models) */
68
+ isNear(id) { return this.ents.get(id)?.near === this.n; }
69
+
70
+ /** Near radius: the written one, else the presentation radius. Models that move themselves (positionFrom 'view') widen to the teardown distance (1.25×) —
71
+ * why: the model may still exist within that distance, and one with a model must run near, otherwise far changes to the data get copied back over by world from the model position */
72
+ radius(kind, s) {
73
+ const W = this.w, V = W._v, p = V.presenters.get(kind);
74
+ if (s.radius != null) return typeof s.radius === 'function' ? s.radius() : s.radius;
75
+ if (!p) return W.radius;
76
+ return V.radius(p) * (p.positionFrom === 'view' ? 1.25 : 1);
77
+ }
78
+
79
+ fixed(dt, anchor) {
80
+ const W = this.w, now = this.time += dt, n = ++this.n;
81
+ this.at.x = anchor.x; this.at.z = anchor.z; this.dt = dt;
82
+ if (!this.sims.size) return;
83
+ let maxR2 = -1;
84
+ // radius may be a function: asked once per kind per step
85
+ for (const [kind, s] of this.sims) { s.r2 = s.near ? this.radius(kind, s) ** 2 : -1; if (s.r2 > maxR2) maxR2 = s.r2; }
86
+ if (maxR2 >= 0) {
87
+ const L = this.list; L.length = 0;
88
+ W._cells.forEach(this.at, Math.sqrt(maxR2), this._pick);
89
+ L.sort(byId);
90
+ for (const e of L) e.near = n; // mark first: isNear in simulate and skipping far both follow what was picked at the start of this step
91
+ for (const e of L) if (!e.dead) this.nearOne(e);
92
+ }
93
+ // far: first the ones queued by the previous step, then this step's bucket; at most farMaxPerTick per step, the rest queue (dt accumulates, no time lost)
94
+ const max = W.farMaxPerTick, q = this.backlog;
95
+ let done = 0, i = 0;
96
+ for (; i < q.length && done < max; i++) {
97
+ const e = q[i]; e.queued = false;
98
+ const s = !e.dead && this.sims.get(e.rec.kind);
99
+ if (s?.far && !e.flight) done += this.farOne(e, s, now);
100
+ }
101
+ if (i) q.splice(0, i);
102
+ for (const [kind, s] of this.sims) {
103
+ const K = s.far && this.kinds.get(kind); if (!K?.set.size) continue;
104
+ const P = Math.max(1, Math.round((s.farEvery ?? W.farEvery) / dt));
105
+ if (K.P !== P) this.rebucket(K, P);
106
+ for (const e of K.buckets[n % P]) {
107
+ if (e.near === n || e.queued || e.flight) continue;
108
+ if (done >= max) { e.queued = true; q.push(e); continue; }
109
+ done += this.farOne(e, s, now);
110
+ }
111
+ }
112
+ this.flights.flush();
113
+ }
114
+ nearOne(e) {
115
+ const rec = e.rec, s = this.sims.get(rec.kind), now = this.time, dt = this.dt;
116
+ if (!s?.near) return; // earlier simulation in this step replaced the registration of this kind
117
+ // For records whose model drives the position (positionFrom 'view'): near simulation needs the model, so build it right now instead of next frame —
118
+ // otherwise the steps before the model is built and the first step after loading would differ from a live run (the result would depend on frame boundaries)
119
+ const V = this.w._v, p = V.presenters.get(rec.kind);
120
+ if (p?.positionFrom === 'view' && !V.map.has(rec.id) && (!p.show || p.show(rec))) V.build(rec, p);
121
+ if (e.flight) this.flights.land(e);
122
+ const owed = now - dt - e.last; // just came in from far: first make up the stretch far has not simulated
123
+ e.last = now;
124
+ if (owed > 1e-9 && s.far) s.far(rec, owed);
125
+ s.near(rec, dt, this.w.view(rec.id));
126
+ }
127
+ farOne(e, s, now) {
128
+ const dt = now - e.last;
129
+ e.last = now;
130
+ if (dt <= 0) return 0; // added during this step
131
+ if (s.pure) this.flights.add(e, s, dt); else s.far(e.rec, dt);
132
+ return 1;
133
+ }
134
+ /** engine.skip: move simulation time without stepping; on the last segment (done) every record with far catches up what it owes in one far(rec, dt), in id order.
135
+ * Same rule as a far turn: kinds with only near are not made up. Worker kinds run here synchronously (the skip result must exist when skip returns) */
136
+ skip(dt, done) {
137
+ const now = this.time += dt;
138
+ if (!done) return;
139
+ for (const e of [...this.ents.values()].sort(byId)) {
140
+ const s = !e.dead && this.sims.get(e.rec.kind);
141
+ if (!s?.far) continue;
142
+ if (e.flight) this.flights.land(e);
143
+ const owed = now - e.last;
144
+ e.last = now;
145
+ if (owed <= 0) continue;
146
+ if (s.pure) this.flights.now(e, s, owed); else s.far(e.rec, owed);
147
+ }
148
+ }
149
+ rebucket(K, P) {
150
+ K.P = P; K.buckets = Array.from({ length: P }, () => new Set());
151
+ for (const e of K.set) K.buckets[e.h % P].add(e);
152
+ }
153
+
154
+ /** Save: step count, accumulated seconds, and how many seconds each far-simulated record still owes (near ones simulate every step, owe nothing, are not written).
155
+ * Step count and seconds are saved too: after loading buckets take turns in the same batch and dt has the same float error, so one save advances the same way every time */
156
+ toJSON() {
157
+ const owed = {}, W = this.w, t = this.time;
158
+ // in flight (worker far not landed): the record does not have that stretch yet, so it is still owed
159
+ // only kinds simulated with far owe time: a prop, pickup or near-only kind never makes it up, so it writes nothing (saves stay small)
160
+ for (const [id, e] of this.ents) {
161
+ if (!this.sims.get(e.rec.kind)?.far) continue;
162
+ const last = e.flight ? e.flight.from : e.last;
163
+ if (t - last > 1e-6 && !W._unsaved.has(id)) owed[id] = t - last;
164
+ }
165
+ for (const [id, last] of this.owed) owed[id] = t - last; // those whose content is not added back yet are written too (used on the next add)
166
+ return { step: this.n, time: t, owed };
167
+ }
168
+ /** Load: work back the last simulation time from "seconds owed"; records are re-added later by loadWorld */
169
+ fromJSON(d) {
170
+ for (const e of this.ents.values()) e.dead = true; // results still in flight belong to the old records: dropped
171
+ this.ents.clear(); this.kinds.clear(); this.backlog.length = 0;
172
+ this.n = d?.step ?? 0; this.time = d?.time ?? 0;
173
+ this.owed = new Map(Object.entries(d?.owed || {}).map(([id, s]) => [id, this.time - s]));
174
+ }
175
+ }
@@ -0,0 +1,82 @@
1
+ // Far simulation in workers: world.simulate(kind, { far, worker: true }). Part of sim.js.
2
+ // Each step, the far records picked for this step (buckets and cap work exactly as without workers) are copied as one batch per kind,
3
+ // sent to engine.threads, and the results are written back FAR_LAG steps later through engine.commits:
4
+ // arrived in time -> worker result; not yet -> the same function runs on the main thread on the same copies.
5
+ // So threads on, off, slow or crashed all give bit-identical records at every step (same V8, same recompiled source, same input).
6
+ // Write-back is a field diff against the copy: only fields far changed are written, so gameplay changing other fields during the flight is kept;
7
+ // a field both changed is won by far (it lands later). A record that turns near while in flight lands its result first (same value), then near runs.
8
+ // A record in flight is skipped by far scheduling until it lands; its time keeps accumulating and is simulated on its next turn, so no time is lost.
9
+
10
+ /** Steps between sending a batch and writing it back (4 = 67 ms): enough for a worker round trip, short enough that far records barely lag */
11
+ const FAR_LAG = 4;
12
+
13
+ /** Deep equality of plain data (records hold only plain values) */
14
+ function same(a, b) {
15
+ if (a === b) return true;
16
+ if (!a || !b || typeof a !== 'object' || typeof b !== 'object') return Number.isNaN(a) && Number.isNaN(b);
17
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
18
+ const ka = Object.keys(a);
19
+ if (ka.length !== Object.keys(b).length) return false;
20
+ for (const k of ka) if (!same(a[k], b[k])) return false;
21
+ return true;
22
+ }
23
+
24
+ /** @internal */
25
+ export class FarFlights {
26
+ /** @param {import('./sim.js').Sim} sim */
27
+ constructor(sim) {
28
+ this.sim = sim;
29
+ this.open = new Map(); // simulate registration -> [[ent, dt], ...] picked this step
30
+ this.defs = 0;
31
+ }
32
+ /** simulate(kind, { worker: true }): recompile far so it runs the same in a worker and here; the original closure is never called */
33
+ register(kind, s) {
34
+ const T = this.sim.w.engine.threads, label = `world.simulate('${kind}') far`;
35
+ s.pure = T.pure(s.far, label);
36
+ s.far = s.pure.call;
37
+ s.key = kind + '#' + ++this.defs;
38
+ if (T.size) T.pureLane().broadcast({ def: s.key, src: s.pure.src, label }, 'def:' + s.key);
39
+ }
40
+ add(e, s, dt) {
41
+ let b = this.open.get(s); if (!b) this.open.set(s, b = []);
42
+ b.push([e, dt]);
43
+ }
44
+ /** End of the far pass: send each kind's batch */
45
+ flush() {
46
+ for (const [s, items] of this.open) this.send(s, items);
47
+ this.open.clear();
48
+ }
49
+ send(s, items) {
50
+ const engine = this.sim.w.engine, T = engine.threads;
51
+ // copies taken now: what far sees is the record as of this step, whatever happens to it during the flight
52
+ const f = { s, items, snaps: items.map(([e, dt]) => [structuredClone(e.rec), dt]), results: null };
53
+ for (const [e, dt] of items) e.flight = { f, from: e.last - dt };
54
+ const t = engine.commits.request({ lag: FAR_LAG, apply: r => this.apply(f, r), fallback: () => f.snaps.map((_, i) => this.compute(f, i)) });
55
+ // a failed worker run is ignored: the fallback runs the same code here at the due step and throws the same (clear) error
56
+ if (T.size) T.pureLane().run({ call: s.key, items: f.snaps }).then(r => { f.results = r.map(x => x.args[0]); t.resolve(f.results); }, () => {});
57
+ }
58
+ /** Run one worker kind's far here and now (engine.skip), written back the same way as a landed result */
59
+ now(e, s, dt) {
60
+ const f = { s, snaps: [[structuredClone(e.rec), dt]] };
61
+ this.write(e, f, this.compute(f, 0), 0);
62
+ }
63
+ compute(f, i) { const [rec, dt] = f.snaps[i], c = structuredClone(rec); f.s.pure.call(c, dt); return c; }
64
+ apply(f, results) {
65
+ f.items.forEach(([e], i) => { if (e.flight?.f === f) this.write(e, f, results[i], i); });
66
+ }
67
+ /** Near needs this record now: land its result early (worker result if it arrived, else computed here; the value is the same) */
68
+ land(e) {
69
+ const f = e.flight.f, i = f.items.findIndex(x => x[0] === e);
70
+ this.write(e, f, f.results ? f.results[i] : this.compute(f, i), i);
71
+ }
72
+ write(e, f, res, i) {
73
+ e.flight = null;
74
+ if (e.dead) return;
75
+ const rec = e.rec, snap = f.snaps[i][0];
76
+ for (const k in res) {
77
+ if (k === 'id' || k === 'kind' || same(res[k], snap[k])) continue;
78
+ if (k === 'position') this.sim.w.move(rec.id, res.position); else rec[k] = res[k];
79
+ }
80
+ for (const k in snap) if (!(k in res)) delete rec[k];
81
+ }
82
+ }