threedog 0.7.0 → 1.0.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 (593) hide show
  1. package/CHANGELOG.md +411 -1
  2. package/README.md +8 -11
  3. package/core/{Animator.js → assets/Animator.js} +30 -18
  4. package/core/{Assets.js → assets/Assets.js} +131 -56
  5. package/core/{Baked.js → assets/Baked.js} +4 -4
  6. package/core/assets/assetEntry.js +302 -0
  7. package/core/{assetHot.js → assets/assetHot.js} +9 -7
  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} +7 -14
  12. package/core/{namedModel.js → assets/namedModel.js} +17 -13
  13. package/core/{Audio.js → audio/Audio.js} +47 -25
  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} +15 -12
  18. package/core/{Random.js → base/Random.js} +7 -4
  19. package/core/{Vars.js → base/Vars.js} +14 -4
  20. package/core/{easing.js → base/easing.js} +1 -1
  21. package/core/{errorCodes.js → base/errorCodes.js} +151 -125
  22. package/core/{errorHints.js → base/errorHints.js} +17 -10
  23. package/core/{errors.js → base/errors.js} +12 -10
  24. package/core/{events.generated.js → base/events.generated.js} +11 -0
  25. package/core/base/follows.js +26 -0
  26. package/core/base/math.js +66 -0
  27. package/core/{params.js → base/params.js} +5 -6
  28. package/core/base/saveValues.js +81 -0
  29. package/core/base/sections.js +97 -0
  30. package/core/base/spelling.js +32 -0
  31. package/core/base/util.js +32 -0
  32. package/core/{validate.js → base/validate.js} +34 -34
  33. package/core/{Engine.js → engine/Engine.js} +137 -91
  34. package/core/{Loading.js → engine/Loading.js} +34 -5
  35. package/core/{copies.js → engine/copies.js} +4 -4
  36. package/core/{headlessLoad.js → engine/headlessLoad.js} +32 -15
  37. package/core/{lifecycle.js → engine/lifecycle.js} +41 -34
  38. package/core/{loop.js → engine/loop.js} +88 -49
  39. package/core/engine/moduleSlots.js +176 -0
  40. package/core/{moduleTypes.js → engine/moduleTypes.js} +26 -14
  41. package/core/engine/modules.js +503 -0
  42. package/core/{page.js → engine/page.js} +59 -29
  43. package/core/{plugins.js → engine/plugins.js} +21 -12
  44. package/core/{services.js → engine/services.js} +50 -40
  45. package/core/{startup.js → engine/startup.js} +66 -54
  46. package/core/{Input.js → input/Input.js} +67 -39
  47. package/core/{inputContext.js → input/inputContext.js} +14 -5
  48. package/core/input/inputKeyboard.js +39 -0
  49. package/core/{inputPad.js → input/inputPad.js} +24 -3
  50. package/core/{inputPointer.js → input/inputPointer.js} +11 -3
  51. package/core/input/inputSeat.js +66 -0
  52. package/core/{inputTouch.js → input/inputTouch.js} +24 -7
  53. package/core/{Budget.js → inspect/Budget.js} +21 -20
  54. package/core/{DebugOverrides.js → inspect/DebugOverrides.js} +43 -18
  55. package/core/{Describe.js → inspect/Describe.js} +34 -26
  56. package/core/{Inspect.js → inspect/Inspect.js} +39 -10
  57. package/core/{InspectMaterials.js → inspect/InspectMaterials.js} +7 -8
  58. package/core/{InspectPerf.js → inspect/InspectPerf.js} +19 -13
  59. package/core/{InspectScene.js → inspect/InspectScene.js} +8 -5
  60. package/core/{MaterialInfo.js → inspect/MaterialInfo.js} +3 -2
  61. package/core/{UrlState.js → inspect/UrlState.js} +60 -24
  62. package/core/{catalog.js → inspect/catalog.js} +15 -8
  63. package/core/{checks.js → inspect/checks.js} +7 -5
  64. package/core/{debugView.js → inspect/debugView.js} +4 -4
  65. package/core/{describeRender.js → inspect/describeRender.js} +24 -22
  66. package/core/{describeText.js → inspect/describeText.js} +17 -8
  67. package/core/inspect/geometryWatch.js +38 -0
  68. package/core/{lightWatch.js → inspect/lightWatch.js} +8 -8
  69. package/core/inspect/metadata.generated.js +4140 -0
  70. package/core/{pictureWriters.js → inspect/pictureWriters.js} +130 -47
  71. package/core/{shaderCost.js → inspect/shaderCost.js} +1 -1
  72. package/core/inspect/toolDoor.js +21 -0
  73. package/core/inspect/valueHistory.js +35 -0
  74. package/core/{Ops.js → ops/Ops.js} +44 -14
  75. package/core/{control.js → ops/control.js} +57 -31
  76. package/core/ops/holds.js +140 -0
  77. package/core/{opsAtomic.js → ops/opsAtomic.js} +18 -5
  78. package/core/{opsCheck.js → ops/opsCheck.js} +11 -10
  79. package/core/{opsFail.js → ops/opsFail.js} +5 -7
  80. package/core/{opsGuard.js → ops/opsGuard.js} +3 -3
  81. package/core/{opsRun.js → ops/opsRun.js} +9 -6
  82. package/core/{owned.js → ops/owned.js} +33 -19
  83. package/core/{sharedPoint.js → ops/sharedPoint.js} +13 -16
  84. package/core/{stackFrames.js → ops/stackFrames.js} +2 -2
  85. package/core/{stacks.js → ops/stacks.js} +34 -15
  86. package/core/{wrap.js → ops/wrap.js} +8 -6
  87. package/core/{SaveStore.js → saves/SaveStore.js} +53 -27
  88. package/core/{Saves.js → saves/Saves.js} +171 -54
  89. package/core/saves/saveApply.js +312 -0
  90. package/core/{saveFiles.js → saves/saveFiles.js} +45 -38
  91. package/core/{saveVersions.js → saves/saveVersions.js} +24 -23
  92. package/core/saves/session.js +231 -0
  93. package/core/saves/stateReplace.js +184 -0
  94. package/core/{Rays.js → scene/Rays.js} +44 -30
  95. package/core/{Views.js → scene/Views.js} +16 -8
  96. package/core/{adaptive.js → scene/adaptive.js} +19 -9
  97. package/core/{canvasBox.js → scene/canvasBox.js} +4 -3
  98. package/core/scene/compositeGround.js +72 -0
  99. package/core/scene/floor.js +17 -0
  100. package/core/{gameLights.js → scene/gameLights.js} +17 -7
  101. package/core/{grayMap.js → scene/grayMap.js} +8 -2
  102. package/core/{grid.js → scene/grid.js} +6 -4
  103. package/core/{gridLoad.js → scene/gridLoad.js} +1 -1
  104. package/core/scene/ground.contract.js +14 -0
  105. package/core/scene/ground.js +139 -0
  106. package/core/{movement.js → scene/movement.js} +3 -3
  107. package/core/{pictureSlots.js → scene/pictureSlots.js} +2 -2
  108. package/core/scene/pixel.js +154 -0
  109. package/core/scene/pixelRatio.js +167 -0
  110. package/core/{sceneDelta.js → scene/sceneDelta.js} +5 -5
  111. package/core/{sceneMethods.js → scene/sceneMethods.js} +43 -15
  112. package/core/scene/stepPoses.js +60 -0
  113. package/core/{targeting.js → scene/targeting.js} +4 -5
  114. package/core/{thingExplain.js → scene/thingExplain.js} +7 -6
  115. package/core/{thingOps.js → scene/thingOps.js} +25 -16
  116. package/core/{things.js → scene/things.js} +18 -5
  117. package/core/{threePatches.js → scene/threePatches.js} +1 -1
  118. package/core/{tier.js → scene/tier.js} +10 -0
  119. package/core/scene/view.js +161 -0
  120. package/core/{Batching.js → stream/Batching.js} +85 -28
  121. package/core/{Stream.js → stream/Stream.js} +80 -38
  122. package/core/{batchGroups.js → stream/batchGroups.js} +11 -9
  123. package/core/{chunkStream.js → stream/chunkStream.js} +40 -0
  124. package/core/{scatter.js → stream/scatter.js} +7 -4
  125. package/core/{streamSources.js → stream/streamSources.js} +14 -8
  126. package/core/{Commits.js → threads/Commits.js} +17 -11
  127. package/core/{Jobs.js → threads/Jobs.js} +25 -13
  128. package/core/{Threads.js → threads/Threads.js} +21 -18
  129. package/core/{threadPure.js → threads/threadPure.js} +7 -5
  130. package/core/{threadServe.js → threads/threadServe.js} +3 -3
  131. package/core/{Clock.js → time/Clock.js} +20 -11
  132. package/core/{dayTime.js → time/dayTime.js} +5 -1
  133. package/core/{skip.js → time/skip.js} +28 -21
  134. package/core/{time.js → time/time.js} +32 -20
  135. package/core/{uiClock.js → time/uiClock.js} +4 -4
  136. package/docs/AI.md +92 -72
  137. package/docs/API.md +33 -28
  138. package/docs/CODEMAP.md +121 -200
  139. package/docs/COMMANDS.md +77 -70
  140. package/docs/CONVENTIONS.md +167 -24
  141. package/docs/MIGRATING-0.8.md +171 -0
  142. package/docs/MIGRATING-1.0.md +101 -0
  143. package/docs/THREE.md +140 -38
  144. package/docs/api/assets.md +12 -13
  145. package/docs/api/audio.md +6 -5
  146. package/docs/api/budget.md +4 -4
  147. package/docs/api/calendar.md +10 -11
  148. package/docs/api/cameraRig.md +32 -29
  149. package/docs/api/characters.md +35 -24
  150. package/docs/api/clock.md +1 -1
  151. package/docs/api/collider3d.md +9 -0
  152. package/docs/api/collision.md +12 -9
  153. package/docs/api/content.md +18 -17
  154. package/docs/api/dialogue.md +5 -4
  155. package/docs/api/engine.md +58 -54
  156. package/docs/api/events.md +17 -6
  157. package/docs/api/flow.md +1 -1
  158. package/docs/api/grids.md +1 -1
  159. package/docs/api/ground.md +6 -7
  160. package/docs/api/hud.md +2 -2
  161. package/docs/api/i18n.md +6 -6
  162. package/docs/api/input.md +9 -8
  163. package/docs/api/interactions.md +5 -5
  164. package/docs/api/inventory.md +10 -10
  165. package/docs/api/jobs.md +5 -5
  166. package/docs/api/level.md +10 -9
  167. package/docs/api/lightPool.md +1 -6
  168. package/docs/api/music.md +3 -3
  169. package/docs/api/nav.md +14 -12
  170. package/docs/api/openWorld.md +1 -1
  171. package/docs/api/particles.md +10 -7
  172. package/docs/api/photo.md +4 -2
  173. package/docs/api/pickups.md +3 -3
  174. package/docs/api/post.md +21 -5
  175. package/docs/api/quests.md +7 -5
  176. package/docs/api/rays.md +7 -7
  177. package/docs/api/rigid.md +29 -19
  178. package/docs/api/saves.md +13 -11
  179. package/docs/api/settings.md +9 -8
  180. package/docs/api/sky.md +8 -7
  181. package/docs/api/stream.md +8 -9
  182. package/docs/api/swarm.md +34 -0
  183. package/docs/api/terrain.md +6 -8
  184. package/docs/api/terrainDraw.md +2 -2
  185. package/docs/api/timeline.md +4 -4
  186. package/docs/api/tools.md +27 -22
  187. package/docs/api/triggers.md +2 -0
  188. package/docs/api/vars.md +1 -1
  189. package/docs/api/vegetation.md +4 -3
  190. package/docs/api/vegetationDraw.md +2 -2
  191. package/docs/api/water.md +7 -3
  192. package/docs/api/weather.md +27 -12
  193. package/docs/api/weatherDraw.md +4 -4
  194. package/docs/api/world.md +6 -6
  195. package/docs/recipes/01-new-game.md +28 -43
  196. package/docs/recipes/02-npc.md +21 -23
  197. package/docs/recipes/03-items-pickups.md +37 -53
  198. package/docs/recipes/04-quests.md +5 -4
  199. package/docs/recipes/05-props-bake.md +34 -44
  200. package/docs/recipes/06-clock-events.md +31 -22
  201. package/docs/recipes/07-flow-scenes-pause.md +30 -32
  202. package/docs/recipes/08-weather-sky.md +91 -37
  203. package/docs/recipes/09-materials-lights-models.md +25 -39
  204. package/docs/recipes/10-blender-level.md +22 -11
  205. package/docs/recipes/11-vehicles.md +44 -24
  206. package/docs/recipes/12-navmesh.md +60 -15
  207. package/docs/recipes/13-animation.md +70 -22
  208. package/docs/recipes/14-custom-module.md +33 -20
  209. package/docs/recipes/15-perf.md +51 -28
  210. package/docs/recipes/16-dev-bridge.md +39 -58
  211. package/docs/recipes/18-world.md +49 -28
  212. package/docs/recipes/19-shooting-picking.md +7 -4
  213. package/docs/recipes/20-content-actions-save.md +55 -40
  214. package/docs/recipes/21-camera.md +47 -25
  215. package/docs/recipes/22-shop-gold.md +21 -16
  216. package/docs/recipes/23-ops.md +28 -24
  217. package/docs/recipes/26-ui-parts.md +25 -14
  218. package/docs/recipes/27-net.md +3 -5
  219. package/docs/recipes/28-terrain.md +119 -23
  220. package/docs/recipes/29-grid.md +3 -3
  221. package/docs/recipes/30-templates.md +63 -30
  222. package/docs/recipes/31-audio.md +7 -7
  223. package/docs/recipes/32-action-game.md +21 -11
  224. package/docs/recipes/33-stream-sources.md +6 -3
  225. package/docs/recipes/34-environment-lighting.md +72 -25
  226. package/docs/recipes/35-picture-from-reference.md +20 -23
  227. package/docs/recipes/36-ground-plants.md +106 -0
  228. package/docs/recipes/40-scene.md +18 -21
  229. package/docs/recipes/43-shader-patches-surfaces.md +27 -48
  230. package/docs/recipes/44-water-weather-hooks.md +56 -50
  231. package/docs/recipes/45-cascaded-shadows.md +41 -20
  232. package/docs/recipes/46-blender-art-route.md +9 -10
  233. package/docs/recipes/49-game-module-contract.md +7 -6
  234. package/docs/recipes/50-own-renderer.md +3 -2
  235. package/docs/recipes/51-capability-catalog.md +14 -8
  236. package/docs/recipes/52-around-the-picture.md +56 -100
  237. package/docs/recipes/53-ground-up-close.md +61 -24
  238. package/docs/recipes/55-mods-time-wrap.md +17 -20
  239. package/docs/recipes/56-webgpu-tsl.md +28 -15
  240. package/docs/recipes/57-control.md +39 -12
  241. package/docs/recipes/58-input.md +15 -2
  242. package/docs/recipes/59-depth-post-effects.md +1 -1
  243. package/docs/recipes/60-judge-the-picture.md +30 -25
  244. package/docs/recipes/62-picture-code.md +129 -39
  245. package/docs/recipes/63-third-person-start.md +19 -5
  246. package/docs/recipes/64-particles.md +54 -5
  247. package/docs/recipes/65-swarm.md +140 -0
  248. package/docs/recipes/66-common-tasks.md +313 -0
  249. package/examples/action/.threedog/content-index.json +1 -1
  250. package/examples/action/GAMEMAP.md +5 -5
  251. package/examples/perf-island/.threedog/content-index.json +1 -0
  252. package/examples/{sheepisland → perf-island}/GAMEMAP.md +15 -14
  253. package/examples/{sheepisland → perf-island}/assets.js +1 -1
  254. package/examples/{sheepisland → perf-island}/main.js +8 -8
  255. package/examples/{sheepisland → perf-island}/models.js +1 -1
  256. package/examples/{sheepisland → perf-island}/params.js +1 -1
  257. package/examples/{sheepisland → perf-island}/picture/index.js +1 -1
  258. package/examples/{sheepisland → perf-island}/picture/palette.js +2 -2
  259. package/examples/{sheepisland → perf-island}/views.js +1 -1
  260. package/examples/plain-picture/GAMEMAP.md +4 -1
  261. package/examples/rc2d/GAMEMAP.md +4 -3
  262. package/examples/rc2d/main.js +1 -3
  263. package/examples/rc2d/rc2d.js +1 -1
  264. package/examples/styletest/.threedog/content-index.json +1 -1
  265. package/examples/styletest/GAMEMAP.md +6 -5
  266. package/examples/techniques/contact-shadows/contactShadows.js +1 -1
  267. package/examples/techniques/contact-shadows/main.js +1 -1
  268. package/examples/techniques/interior-light/main.js +1 -1
  269. package/examples/techniques/modular-building/README.md +7 -6
  270. package/examples/techniques/outlines-and-rim/picture/post.js +1 -1
  271. package/examples/techniques/procedural-animation/README.md +1 -1
  272. package/examples/webgpu-tsl/GAMEMAP.md +2 -1
  273. package/examples/world/.threedog/content-index.json +1 -1
  274. package/examples/world/GAMEMAP.md +9 -7
  275. package/examples/world/main.js +3 -3
  276. package/examples/world/picture/sky.js +1 -1
  277. package/index.d.ts +16 -12
  278. package/index.js +53 -32
  279. package/llms.txt +11 -14
  280. package/modules/ambience/Ambience.js +16 -11
  281. package/modules/calendar/Calendar.js +19 -19
  282. package/modules/calendar/index.js +18 -16
  283. package/modules/calendar/schedule.js +11 -6
  284. package/modules/calendar/seasons.js +7 -7
  285. package/modules/camera/FirstPersonCamera.js +5 -5
  286. package/modules/camera/FixedCamera.js +43 -30
  287. package/modules/camera/FollowCamera.js +24 -15
  288. package/modules/camera/RtsCamera.js +12 -11
  289. package/modules/camera/common.js +72 -37
  290. package/modules/camera/contract.js +1 -0
  291. package/modules/camera/pixelSnap.js +62 -0
  292. package/modules/characters/Character.js +166 -70
  293. package/modules/characters/NPC.js +84 -44
  294. package/modules/characters/assetModel.js +16 -12
  295. package/modules/characters/astar.js +48 -27
  296. package/modules/characters/behaviors.js +4 -5
  297. package/modules/characters/character.contract.js +21 -0
  298. package/modules/characters/contract.js +17 -3
  299. package/modules/characters/index.js +240 -226
  300. package/modules/characters/moveHelpers.js +88 -12
  301. package/modules/characters/mover.contract.js +14 -0
  302. package/modules/characters/movers/common.js +22 -18
  303. package/modules/characters/movers/manual.js +1 -1
  304. package/modules/characters/movers/rapier.js +18 -10
  305. package/modules/characters/movers/simple.js +26 -13
  306. package/modules/characters/movers/support.js +24 -13
  307. package/modules/characters/npcAvoid.js +19 -16
  308. package/modules/characters/npcSim.js +88 -32
  309. package/modules/characters/npcView.js +19 -11
  310. package/modules/characters/pathAsync.js +81 -29
  311. package/modules/characters/pathJob.js +38 -21
  312. package/modules/characters/pathWorker.js +1 -1
  313. package/modules/characters/player.js +120 -0
  314. package/modules/characters/playerStrings.js +2 -2
  315. package/modules/characters/proceduralRig.js +2 -2
  316. package/modules/characters/seat.js +56 -0
  317. package/modules/characters/useModel.js +3 -3
  318. package/modules/characters/vehicle.contract.js +8 -5
  319. package/modules/characters/walkTo.js +40 -33
  320. package/modules/collision/Collision.js +69 -45
  321. package/modules/collision/contract.js +15 -0
  322. package/modules/collision/grid.js +6 -1
  323. package/modules/content/explain.js +2 -3
  324. package/modules/content/fields.js +24 -3
  325. package/modules/content/ids.js +5 -3
  326. package/modules/content/index.js +132 -114
  327. package/modules/content/loader.js +117 -140
  328. package/modules/content/markers.js +25 -0
  329. package/modules/content/models.js +54 -17
  330. package/modules/content/packs.js +5 -4
  331. package/modules/content/parts.js +2 -2
  332. package/modules/content/places.js +36 -0
  333. package/modules/content/props.js +22 -17
  334. package/modules/content/rules.js +47 -61
  335. package/modules/content/stages.js +7 -7
  336. package/modules/content/templates.js +80 -49
  337. package/modules/content/words.js +47 -0
  338. package/modules/debug/DebugPanel.js +14 -45
  339. package/modules/flow/contract.js +2 -1
  340. package/modules/flow/index.js +30 -16
  341. package/modules/gameplay/Container.js +17 -13
  342. package/modules/gameplay/Containers.js +23 -6
  343. package/modules/gameplay/Dialogue.js +93 -34
  344. package/modules/gameplay/Interactions.js +93 -51
  345. package/modules/gameplay/Inventory.js +64 -22
  346. package/modules/gameplay/Quests.js +146 -30
  347. package/modules/gameplay/boxOps.js +8 -1
  348. package/modules/gameplay/dialogueBubbles.js +16 -12
  349. package/modules/gameplay/inventoryOps.js +11 -8
  350. package/modules/gameplay/pickups.js +63 -37
  351. package/modules/gameplay/questLog.js +4 -2
  352. package/modules/gameplay/questSave.js +9 -4
  353. package/modules/gameplay/quests.contract.js +1 -1
  354. package/modules/grid/Grid.js +2 -2
  355. package/modules/grid/Layer.js +12 -8
  356. package/modules/grid/index.js +28 -23
  357. package/modules/grid/ops.js +43 -46
  358. package/modules/grid/preview.js +7 -7
  359. package/modules/grid/tiles.js +6 -6
  360. package/modules/hlod/index.js +42 -57
  361. package/modules/hud/index.js +22 -14
  362. package/modules/hud/parts.js +8 -8
  363. package/modules/level/contract.js +16 -0
  364. package/modules/level/heightfield.js +29 -31
  365. package/modules/level/index.js +113 -161
  366. package/modules/level/load.js +196 -0
  367. package/modules/level/meshes.js +65 -0
  368. package/modules/level/nodes.js +40 -23
  369. package/modules/lights/index.js +33 -183
  370. package/modules/lights/slots.js +93 -0
  371. package/modules/lights/sources.js +90 -0
  372. package/modules/music/Music.js +34 -28
  373. package/modules/music/rules.js +1 -1
  374. package/modules/nav/contract.js +16 -0
  375. package/modules/nav/index.js +180 -49
  376. package/modules/nav/navPath.js +45 -10
  377. package/modules/net/Client.js +7 -7
  378. package/modules/net/Host.js +7 -7
  379. package/modules/net/Net.js +1 -1
  380. package/modules/net/index.js +6 -5
  381. package/modules/net/sync.js +2 -2
  382. package/modules/net/transports.js +2 -2
  383. package/modules/particles/Particles.js +95 -29
  384. package/modules/particles/effect.js +86 -32
  385. package/modules/particles/shaders.js +19 -1
  386. package/modules/photo/Photo.js +23 -23
  387. package/modules/rigid/RigidBodies.js +255 -89
  388. package/modules/rigid/Vehicles.js +17 -8
  389. package/modules/rigid/collider3d.contract.js +26 -0
  390. package/modules/rigid/ragdoll.js +298 -0
  391. package/modules/rigid/ragdollBones.js +209 -0
  392. package/modules/rigid/refresh.js +10 -0
  393. package/modules/rigid/sync.js +51 -20
  394. package/modules/settings/Settings.js +177 -61
  395. package/modules/settings/apply.js +20 -13
  396. package/modules/settings/sections.js +19 -14
  397. package/modules/settings/strings.js +2 -2
  398. package/modules/settings/view.js +3 -3
  399. package/modules/sky/Sky.js +29 -22
  400. package/modules/sky/clouds.js +7 -7
  401. package/modules/sky/dome.js +33 -20
  402. package/modules/sky/domeLayers.js +9 -9
  403. package/modules/sky/environment.js +6 -6
  404. package/modules/sky/frame.js +19 -10
  405. package/modules/sky/season.js +7 -1
  406. package/modules/sky/shader.js +24 -25
  407. package/modules/sky/skyModule.js +17 -28
  408. package/modules/sky/tint.js +1 -1
  409. package/modules/swarm/Swarm.js +356 -0
  410. package/modules/swarm/draw.js +68 -0
  411. package/modules/swarm/grid.js +63 -0
  412. package/modules/terrain/ChunkManager.js +71 -59
  413. package/modules/terrain/chunkQueries.js +7 -24
  414. package/modules/terrain/chunkWorker.js +1 -1
  415. package/modules/terrain/draw.js +14 -11
  416. package/modules/terrain/index.js +42 -42
  417. package/modules/terrain/terrainColorMap.js +6 -3
  418. package/modules/terrain/terrainDefaults.js +2 -1
  419. package/modules/terrain/terrainEdit.js +45 -29
  420. package/modules/terrain/terrainGen.js +19 -12
  421. package/modules/terrain/terrainIsland.js +2 -2
  422. package/modules/terrain/terrainMesh.js +7 -6
  423. package/modules/terrain/terrainShape.js +8 -10
  424. package/modules/terrain/terrainShapeMain.js +3 -3
  425. package/modules/timeline/Timeline.js +83 -43
  426. package/modules/timeline/Tween.js +25 -19
  427. package/modules/timeline/shots.js +24 -17
  428. package/modules/triggers/index.js +95 -28
  429. package/modules/vegetation/Vegetation.js +34 -26
  430. package/modules/vegetation/densityMap.js +4 -7
  431. package/modules/vegetation/draw.js +39 -18
  432. package/modules/vegetation/groundChunks.js +21 -38
  433. package/modules/vegetation/index.js +37 -12
  434. package/modules/vegetation/modelGeometry.js +3 -6
  435. package/modules/vegetation/nearFade.js +1 -1
  436. package/modules/water/Water.js +20 -16
  437. package/modules/water/surface.js +3 -3
  438. package/modules/weather/Weather.js +52 -40
  439. package/modules/weather/particles.js +8 -8
  440. package/modules/weather/weatherDraw.js +28 -23
  441. package/modules/world/World.js +28 -15
  442. package/modules/world/explain.js +1 -1
  443. package/modules/world/index.js +30 -17
  444. package/modules/world/persist.js +90 -27
  445. package/modules/world/pos.js +5 -5
  446. package/modules/world/records.js +37 -11
  447. package/modules/world/sim.js +78 -27
  448. package/modules/world/simFar.js +2 -2
  449. package/modules/world/state.js +43 -11
  450. package/modules/world/thingSource.js +20 -5
  451. package/modules/world/views.js +27 -14
  452. package/package.json +48 -7
  453. package/presets.js +1 -3
  454. package/render/PostFX.js +83 -53
  455. package/render/backend.js +31 -33
  456. package/render/cascades.js +17 -12
  457. package/render/cascades.tsl.js +5 -8
  458. package/render/daylight.js +20 -3
  459. package/render/detail.js +8 -7
  460. package/render/effects.js +28 -25
  461. package/render/fuse.js +3 -3
  462. package/render/fx/cloudShadow.tsl.js +3 -3
  463. package/render/fx/detail.tsl.js +1 -1
  464. package/render/fx/index.js +5 -10
  465. package/render/fx/library.tsl.js +11 -0
  466. package/render/fx/lighting.tsl.js +2 -1
  467. package/render/fx/nodeErrors.tsl.js +2 -2
  468. package/render/fx/objectOrigin.tsl.js +1 -2
  469. package/render/fx/particles.tsl.js +8 -6
  470. package/render/fx/patchNodes.tsl.js +5 -15
  471. package/render/fx/postWebGPU.tsl.js +30 -26
  472. package/render/fx/sky.tsl.js +15 -17
  473. package/render/fx/uniforms.tsl.js +4 -4
  474. package/render/fx/wind.tsl.js +1 -1
  475. package/render/fxNumbers.js +3 -0
  476. package/render/layers.js +2 -2
  477. package/render/lighting.js +5 -3
  478. package/render/lightmap.js +41 -21
  479. package/render/lights.js +6 -6
  480. package/render/lit.js +24 -0
  481. package/render/materials.js +8 -7
  482. package/render/mergeCommon.js +22 -0
  483. package/render/modeling.js +2 -2
  484. package/render/occlusion.js +62 -15
  485. package/render/ownFrame.js +4 -4
  486. package/render/patches.js +15 -15
  487. package/render/postWebGL.js +15 -12
  488. package/render/probes.js +41 -19
  489. package/render/recordSweep.js +117 -0
  490. package/render/shaderErrors.js +10 -9
  491. package/render/shadowCache.tsl.js +107 -0
  492. package/render/shadowTypes.js +9 -0
  493. package/{core → render}/shadows.js +59 -13
  494. package/render/slots.js +7 -7
  495. package/render/terms.js +22 -24
  496. package/render/uniformDecl.js +1 -1
  497. package/types/core.d.ts +336 -202
  498. package/types/gameplay.d.ts +254 -130
  499. package/types/generated/core/{Audio.d.ts → audio/Audio.d.ts} +22 -7
  500. package/types/generated/core/{audioVoice.d.ts → audio/audioVoice.d.ts} +2 -2
  501. package/types/generated/core/{Events.d.ts → base/Events.d.ts} +4 -4
  502. package/types/generated/core/{I18n.d.ts → base/I18n.d.ts} +8 -16
  503. package/types/generated/core/{Random.d.ts → base/Random.d.ts} +4 -3
  504. package/types/generated/core/{page.d.ts → engine/page.d.ts} +8 -9
  505. package/types/generated/core/{Input.d.ts → input/Input.d.ts} +28 -10
  506. package/types/generated/core/input/inputSeat.d.ts +26 -0
  507. package/types/generated/core/{Budget.d.ts → inspect/Budget.d.ts} +36 -26
  508. package/types/generated/core/{DebugOverrides.d.ts → inspect/DebugOverrides.d.ts} +17 -3
  509. package/types/generated/core/{Ops.d.ts → ops/Ops.d.ts} +6 -4
  510. package/types/generated/core/{control.d.ts → ops/control.d.ts} +14 -10
  511. package/types/generated/core/{Saves.d.ts → saves/Saves.d.ts} +62 -18
  512. package/types/generated/core/{session.d.ts → saves/session.d.ts} +3 -2
  513. package/types/generated/core/{Rays.d.ts → scene/Rays.d.ts} +8 -27
  514. package/types/generated/core/{Views.d.ts → scene/Views.d.ts} +2 -2
  515. package/types/generated/core/{Batching.d.ts → stream/Batching.d.ts} +7 -7
  516. package/types/generated/core/{Stream.d.ts → stream/Stream.d.ts} +22 -18
  517. package/types/generated/core/{Commits.d.ts → threads/Commits.d.ts} +1 -1
  518. package/types/generated/core/{Jobs.d.ts → threads/Jobs.d.ts} +6 -6
  519. package/types/generated/core/{Threads.d.ts → threads/Threads.d.ts} +4 -4
  520. package/types/generated/modules/calendar/Calendar.d.ts +10 -11
  521. package/types/generated/modules/debug/DebugPanel.d.ts +1 -9
  522. package/types/generated/modules/grid/Grid.d.ts +1 -0
  523. package/types/generated/modules/grid/Layer.d.ts +1 -1
  524. package/types/generated/modules/grid/index.d.ts +3 -3
  525. package/types/generated/modules/music/Music.d.ts +7 -5
  526. package/types/generated/modules/particles/Particles.d.ts +5 -4
  527. package/types/generated/modules/sky/Sky.d.ts +21 -10
  528. package/types/generated/modules/swarm/Swarm.d.ts +80 -0
  529. package/types/generated/modules/timeline/Timeline.d.ts +7 -5
  530. package/types/generated/modules/water/Water.d.ts +1 -0
  531. package/types/generated/modules/weather/Weather.d.ts +14 -16
  532. package/types/generated/modules/weather/weatherDraw.d.ts +3 -3
  533. package/types/generated/modules/world/World.d.ts +11 -7
  534. package/types/generated/render/PostFX.d.ts +21 -23
  535. package/types/generated/render/materials.d.ts +1 -0
  536. package/types/generated/render/occlusion.d.ts +9 -0
  537. package/types/generated/render/patches.d.ts +1 -0
  538. package/types/generated/ui/Focus.d.ts +1 -0
  539. package/types/generated/ui/UI.d.ts +1 -0
  540. package/types/nav.d.ts +47 -15
  541. package/types/physics.d.ts +150 -73
  542. package/types/pixel.d.ts +75 -0
  543. package/types/tsl.d.ts +37 -4
  544. package/types/world.d.ts +48 -75
  545. package/ui/Focus.js +10 -9
  546. package/ui/Parts.js +13 -5
  547. package/ui/UI.js +7 -7
  548. package/ui/defaults.js +3 -2
  549. package/ui/theme.js +7 -5
  550. package/core/assetEntry.js +0 -109
  551. package/core/engineCamera.js +0 -32
  552. package/core/ground.js +0 -104
  553. package/core/holds.js +0 -134
  554. package/core/math.js +0 -48
  555. package/core/moduleSlots.js +0 -100
  556. package/core/modules.js +0 -314
  557. package/core/saveApply.js +0 -210
  558. package/core/saveValues.js +0 -46
  559. package/core/session.js +0 -174
  560. package/core/shadowTypes.js +0 -16
  561. package/core/util.js +0 -17
  562. package/core/view.js +0 -43
  563. package/docs/MIGRATING-0.3.md +0 -248
  564. package/docs/MIGRATING-0.4.md +0 -320
  565. package/docs/MIGRATING-0.5.md +0 -68
  566. package/docs/MIGRATING-0.6.md +0 -126
  567. package/docs/PERF.md +0 -245
  568. package/docs/recipes/36-sky-ground-plants.md +0 -158
  569. package/docs/recipes/37-terrain-hooks.md +0 -115
  570. package/docs/recipes/38-environment-hooks.md +0 -67
  571. package/docs/recipes/42-terrain-shape.md +0 -64
  572. package/docs/recipes/47-island-snow-backdrop.md +0 -43
  573. package/docs/recipes/54-three-idioms.md +0 -88
  574. package/examples/plain-picture/FINDINGS.md +0 -53
  575. package/examples/sheepisland/.threedog/content-index.json +0 -1
  576. package/modules/camera/projection.js +0 -21
  577. /package/core/{mulberry32.js → base/mulberry32.js} +0 -0
  578. /package/core/{inputDefaults.js → input/inputDefaults.js} +0 -0
  579. /package/core/{textureBytes.js → inspect/textureBytes.js} +0 -0
  580. /package/core/{actor.js → ops/actor.js} +0 -0
  581. /package/core/{opsHistory.js → ops/opsHistory.js} +0 -0
  582. /package/core/{saveIds.js → saves/saveIds.js} +0 -0
  583. /package/core/{screenToGround.js → scene/screenToGround.js} +0 -0
  584. /package/core/{cells.js → stream/cells.js} +0 -0
  585. /package/core/{streamCells.js → stream/streamCells.js} +0 -0
  586. /package/core/{pureWorker.js → threads/pureWorker.js} +0 -0
  587. /package/examples/{sheepisland → perf-island}/content/index.js +0 -0
  588. /package/examples/{sheepisland → perf-island}/content/props.js +0 -0
  589. /package/examples/{sheepisland → perf-island}/content/templates.js +0 -0
  590. /package/examples/{sheepisland → perf-island}/content/vegetation.js +0 -0
  591. /package/examples/{sheepisland → perf-island}/picture/lights.js +0 -0
  592. /package/examples/{sheepisland → perf-island}/picture/materials.js +0 -0
  593. /package/examples/{sheepisland → perf-island}/picture/sky.js +0 -0
@@ -4,10 +4,12 @@
4
4
  // For a record the ops turn into world.set / world.move / world.remove (the model follows the record); for a plain object they write the transform and,
5
5
  // when the object has a stable id and is rebuilt by code at setup, record it as an override in the 'scene' save part (things.js).
6
6
  import { Things, snap, write, moduleOwnerOf } from './things.js';
7
- import { closest, DEV } from './validate.js';
7
+ import { closest, DEV, goodPos } from '../base/validate.js';
8
8
  import { onSceneRoot } from './sceneDelta.js';
9
- import { codedError } from './errorHints.js';
10
- import { explainThing } from './thingExplain.js';
9
+ import { codedError } from '../base/errorHints.js';
10
+
11
+ // ops.undo of a run that failed has no value to reverse: an answer, not a crash
12
+ const NOTHING_TO_UNDO = { code: 'nothingToUndo' };
11
13
 
12
14
  const SAY = {
13
15
  record: { keeps: ['record fields and position (world save part)'], loses: ['the built model itself: it is rebuilt from its template / present after a load'] },
@@ -27,16 +29,13 @@ function editText(en, tier, rec) {
27
29
  return `made during play${en.op ? ` by op ${en.op}` : ''}${at}: to keep it, make it a template and create it inside the op with engine.content.spawn(name, at)`;
28
30
  }
29
31
 
30
- /** thing.explain(): the whole story of the id in one object (thingExplain.js); a method, not a field, so the thing stays small */
31
- const withExplain = (e, t) => Object.defineProperty(t, 'explain', { value: () => explainThing(e, t), enumerable: false });
32
-
33
32
  /** A registered plain object as a thing (same shape as hit.thing); `object` is a non-enumerable getter so the result stays JSON-able */
34
33
  function nativeThing(e, en, root) {
35
34
  const tier = e._things.tier(en), say = SAY[tier];
36
35
  const out = { id: en.id, kind: root.type, owner: en.owner, at: en.at, phase: en.phase, ...(en.op && { op: en.op, tick: en.tick }), saved: tier,
37
36
  keeps: say.keeps, loses: say.loses, edit: editText(en, tier), removed: e._things.gone.has(en.id),
38
37
  template: null, definedAt: null, model: null, fields: {} };
39
- return withExplain(e, Object.defineProperty(out, 'object', { get: () => root, enumerable: false }));
38
+ return Object.defineProperty(out, 'object', { get: () => root, enumerable: false });
40
39
  }
41
40
 
42
41
  /**
@@ -60,7 +59,7 @@ const native = (e, hit) => hit && hit[0].owner !== 'world' ? nativeThing(e, hit[
60
59
  function recordAsThing(e, id) {
61
60
  const src = e._things.source(id), r = src.explain(id);
62
61
  const out = { ...r, owner: 'world', at: r.definedAt ?? null, phase: r.spawned ? 'play' : 'setup', saved: 'record', ...SAY.record, edit: editText(null, 'record', r.edit) };
63
- return withExplain(e, Object.defineProperty(out, 'object', { get: () => src.view(id), enumerable: false }));
62
+ return Object.defineProperty(out, 'object', { get: () => src.view(id), enumerable: false });
64
63
  }
65
64
  /** Every id engine.thing knows (for "did you mean") */
66
65
  function thingIds(e) { return [...e._things.recordIds(), ...e._things.byId.keys()]; }
@@ -76,8 +75,8 @@ function patchOf(o, a) {
76
75
  return p;
77
76
  }
78
77
  const xyz = p => Array.isArray(p) ? { x: p[0], y: p[1], z: p[2] } : p;
79
- const yaw = r => typeof r === 'number' ? r : r[1];
80
- const uni = s => typeof s === 'number' ? s : s[0];
78
+ /** thing.set args as a record patch. rotation and scale pass as given, a number or [x, y, z], as the record's rot and scale read them */
79
+ const recordPatch = a => ({ ...(a.position && { position: xyz(a.position) }), ...(a.rotation != null && { rot: a.rotation }), ...(a.scale != null && { scale: a.scale }) });
81
80
 
82
81
  /** Register the registry, engine.thing's ops, the 'scene' save part and the session:start setup window (called once by the Engine constructor) */
83
82
  export function installThings(e) {
@@ -108,28 +107,36 @@ export function installThings(e) {
108
107
  for (const o of e.scene.children) { const owner = moduleOwnerOf(o); if (owner && !T.byObj.has(o)) T.add(o, { owner }, null); }
109
108
  T.explainers = []; // explain contributions from modules (see thingExplain.js)
110
109
  /**
111
- * Add a contribution to engine.thing(id).explain(): fn(engine, thing, out) may fill out.state / out.rules (or add keys) for the things its module owns.
110
+ * Add a contribution to engine.explain({ thing: id }): fn(engine, thing, out) may fill out.state / out.rules (or add keys) for the things its module owns.
112
111
  * For module authors: core never reads another module's record or template shape, the module hands it over here. A throwing fn is skipped.
113
112
  * @param {(e: any, t: any, out: any) => void} fn
114
113
  * @example engine.explainWith((e, t, out) => { const r = e.myRecords.get(t.id); if (r) out.state = { ...r }; });
115
114
  */
116
- e.explainWith = fn => { T.explainers.push(fn); };
115
+ e.explainWith = fn => { T.explainers.push(fn); return { remove: () => { T.explainers = T.explainers.filter(x => x !== fn); } }; };
117
116
  e.saves.register('scene', { atomic: true, save: () => T.save(), load: d => T.load(d) });
118
117
  const kindOf = id => T.source(id) ? 'record' : T.live(id) ? T.tier(T.byObj.get(T.live(id))) : null;
119
118
  const reasons = {
120
119
  noThing: 'no world record or engine.add object has this id (engine.thing(id) suggests the closest one)',
121
120
  engineOwned: 'an engine module manages this object (water, particles, physics…); change it through that module',
122
121
  recordVisible: 'a world record has no visible flag: hide its model with present({ show: rec => … }) and a field set by world.set',
122
+ badPosition: 'position takes [x, y, z] or { x, y, z } with finite numbers (y may be left out of the object)',
123
+ ownerRefuses: 'what owns this record cannot apply the change (facts.why says why and what to do instead)',
123
124
  };
124
125
  e.ops.define('thing.set', {
125
126
  targets: '*',
126
- desc: 'Move / turn / scale / show or hide a thing: a world record (via world.set / move) or an engine.add object (saved as an override when it has an id)',
127
+ desc: 'Move / turn / scale / show or hide a thing: a world record (via world.set / move; a live character or a body gets it through its owner) or an engine.add object (saved as an override when it has an id)',
127
128
  args: { id: 'string', position: 'any?', rotation: 'any?', scale: 'any?', visible: 'bool?' },
128
- can: (_, a) => { const k = kindOf(a.id); return !k ? 'noThing' : k === 'engine' ? 'engineOwned' : k === 'record' && a.visible != null ? 'recordVisible' : true; },
129
+ can: (_, a) => {
130
+ const k = kindOf(a.id);
131
+ if (!k || k === 'engine') return k ? 'engineOwned' : 'noThing';
132
+ if (k === 'record' && a.visible != null) return 'recordVisible';
133
+ if (a.position != null && !goodPos(a.position)) return 'badPosition';
134
+ const why = k === 'record' && T.source(a.id).refuses(a.id, recordPatch(a));
135
+ return why ? { code: 'ownerRefuses', facts: { why } } : true;
136
+ },
129
137
  run(eng, a) {
130
138
  if (kindOf(a.id) === 'record') {
131
- const patch = { ...(a.position && { position: xyz(a.position) }), ...(a.rotation != null && { rot: yaw(a.rotation) }), ...(a.scale != null && { scale: uni(a.scale) }) };
132
- return { record: true, before: T.source(a.id).set(a.id, patch) };
139
+ return { record: true, before: T.source(a.id).set(a.id, recordPatch(a)) };
133
140
  }
134
141
  const obj = T.live(a.id), p = patchOf(obj, a);
135
142
  if (T.tier(T.byObj.get(obj)) === 'code') return T.override(a.id, obj, p);
@@ -137,6 +144,7 @@ export function installThings(e) {
137
144
  write(obj, p);
138
145
  return before;
139
146
  },
147
+ canUndo(_, a, v) { if (!v) return NOTHING_TO_UNDO; const why = v.record && T.source(a.id)?.refusesUndo(a.id, v.before); return why ? { code: 'ownerRefuses', facts: { why } } : true; },
140
148
  undo(eng, a, v) {
141
149
  if (v.record) { T.source(a.id).set(a.id, v.before); return; }
142
150
  const obj = T.live(a.id); if (!obj) return;
@@ -159,6 +167,7 @@ export function installThings(e) {
159
167
  T.hide(a.id, T.live(a.id), T.tier(T.byObj.get(T.live(a.id))) === 'code');
160
168
  return {};
161
169
  },
170
+ canUndo: (_, a, v) => v ? true : NOTHING_TO_UNDO,
162
171
  undo(eng, a, v) {
163
172
  if (!v.record) { T.unhide(a.id); return; }
164
173
  v.src.restore(v.record);
@@ -4,9 +4,21 @@
4
4
  // The WeakMap does not keep objects alive and the id map holds only WeakRefs, so a game that drops an object without engine.remove leaks nothing.
5
5
  // Overrides (thing.set / thing.remove on objects the game's code rebuilds each start) live here too and are the 'scene' save part (version 1):
6
6
  // { set: { id: { position?, rotation?, scale?, visible? } }, removed: [id] }; ids a save names before the object exists wait in pending.
7
- import { DEV, warnOnce } from './validate.js';
8
- import { codedError, coded } from './errorHints.js';
9
- import { stackFrames, frameText } from './stackFrames.js';
7
+ import { DEV, warnOnce } from '../base/validate.js';
8
+ import { codedError, coded } from '../base/errorHints.js';
9
+ import { stackFrames, frameText } from '../ops/stackFrames.js';
10
+ import { isPlainObject } from '../base/util.js';
11
+ import { refuseSave } from '../base/saveValues.js';
12
+
13
+ /** Throw save-bad-record when the 'scene' part is not { set: { id: { prop: value } }, removed: [id] } (same refusal as the world part, world/persist.js) */
14
+ function checkSceneSave(d) {
15
+ const bad = (path, want, got) => refuseSave('scene', path, `must be ${want}`, got);
16
+ if (d == null) return;
17
+ if (!isPlainObject(d)) bad('the scene part', 'a plain object', d);
18
+ if (d.set !== undefined && !isPlainObject(d.set)) bad('set', 'a plain object of id -> properties', d.set);
19
+ for (const [id, p] of Object.entries(d.set ?? {})) if (!isPlainObject(p)) bad(`set.${id}`, 'a plain object of properties', p);
20
+ if (d.removed !== undefined && !(Array.isArray(d.removed) && d.removed.every(id => typeof id === 'string'))) bad('removed', 'an array of ids', d.removed);
21
+ }
10
22
 
11
23
  /** Stacks taken per session in dev: bullets or debris added every frame must not slow dev builds down for a file:line nobody reads */
12
24
  const STACK_CAP = 2000;
@@ -123,7 +135,7 @@ export class Things {
123
135
  if (stable && owner !== 'world') claimId(this.e, id, obj);
124
136
  if (!stable) id = `obj#${++this.n}`;
125
137
  const e = this.e, play = e.ready && !this.setup;
126
- const en = new Entry(id, stable, owner, play ? 'play' : 'setup', play ? e.ops.running : null, play ? e.tick : null, opts?.save, stack);
138
+ const en = new Entry(id, stable, owner, play ? 'play' : 'setup', play ? e.ops.running : null, play ? e.time.tick : null, opts?.save, stack);
127
139
  this.byObj.set(obj, en); this.byId.set(id, new WeakRef(obj));
128
140
  if (owner === 'game') this.adopt(obj, en);
129
141
  return en;
@@ -139,7 +151,7 @@ export class Things {
139
151
  adopt(obj, en) {
140
152
  const tier = this.tier(en);
141
153
  if (tier === 'session' && (en.save === true || en.op)) {
142
- this.unsaved.add(new WeakRef(obj));
154
+ if (DEV) this.unsaved.add(new WeakRef(obj)); // only the dev reports read it, and they alone prune it
143
155
  if (DEV && en.save === true) warnOnce(coded('thing-unsaved', `engine.add(obj, { save: true })${en.at ? ` at ${en.at}` : ''}: this object cannot be saved (${en.stable ? 'it was made during play' : 'it has no stable id'}), so it will not come back after a load. Give it an id and add it at setup (engine.add(obj, { id: 'name' })), or make it a template and create it inside an op with engine.content.spawn(name, at)`));
144
156
  }
145
157
  if (tier === 'code') this.applySaved(obj, en.id);
@@ -184,6 +196,7 @@ export class Things {
184
196
  }
185
197
  /** Replace overrides with the save's: undo the current ones first (newGame applies an empty part), then apply to live objects, keep the rest pending */
186
198
  load(d) {
199
+ checkSceneSave(d); // before anything is touched: a damaged save is refused (save-bad-record) like a damaged world part, not a code error that freezes the game
187
200
  for (const [id, o] of this.over) { const obj = this.live(id); if (obj) write(obj, pick(o.orig, Object.keys(o.cur))); }
188
201
  this.over.clear();
189
202
  for (const id of [...this.removed]) this.unhide(id);
@@ -7,7 +7,7 @@
7
7
  // threePatches.list() // [{ id, what, scope, on, offable, lost }]
8
8
  // threePatches.off('shadow-accessors') // three's own behavior again (moving patches then cast still shadows)
9
9
  // Page-wide on purpose: a prototype is shared by every engine on the page, so the switch is too.
10
- import { codedError } from './errorHints.js';
10
+ import { codedError } from '../base/errorHints.js';
11
11
 
12
12
  const KEY = Symbol.for('threedog.threePatches'); // global: a second copy of a file (hot reload) re-registers the same id instead of a second entry
13
13
  /** @typedef {{ id: string, what: string, scope: string, on: boolean, offable: boolean, lost: string, off: (() => void) | null }} PatchEntry */
@@ -11,6 +11,16 @@ export function forcedTier(search = typeof location === 'undefined' ? '' : locat
11
11
  return TIERS.includes(t) ? t : null;
12
12
  }
13
13
 
14
+ /** The name under engine.saves.storageKey of a player's MSAA choice */
15
+ export const MSAA_KEY = 'msaa';
16
+ /**
17
+ * The player's MSAA choice for this game, or null. Read in createEngine before the renderer, and so before saves exist: the key is storageKey(MSAA_KEY) spelled from saveKey.
18
+ * @param {string} saveKey @returns {boolean | null}
19
+ */
20
+ export function storedMsaa(saveKey) {
21
+ try { const v = localStorage.getItem(`${saveKey}-${MSAA_KEY}`); return v == null ? null : v === '1'; } catch { return null; }
22
+ }
23
+
14
24
  /**
15
25
  * Default render scale. High tier: the display scale up to 1.5. Low tier: at least 0.75 x display scale (1.5 on a 2x screen; a fixed 1 there
16
26
  * would be an upscaled blurry picture), never above 1.5 or the display scale.
@@ -0,0 +1,161 @@
1
+ // engine.autoView: the camera and drawing-buffer values the engine changes on its own (camera.far for the view range, camera.fov for the settings slider and camera
2
+ // modules, the pixel ratio for adaptive resolution). Each is an owned property (core/ops/owned.js): a game's direct write wins, manual() takes one on purpose.
3
+ import * as THREE from 'three';
4
+ import { codedError } from '../base/errorHints.js';
5
+ import { defineOwned, manualVerb } from '../ops/owned.js';
6
+
7
+ /**
8
+ * What engine.camera accepts: exactly THREE.PerspectiveCamera or THREE.OrthographicCamera. Exactly, because a subclass (ArrayCamera, a game's own) may draw by rules the engine's
9
+ * cameras, shadows and post chain never read.
10
+ * @param {any} cam
11
+ */
12
+ export function checkCamera(cam) {
13
+ if (cam?.constructor === THREE.PerspectiveCamera || cam?.constructor === THREE.OrthographicCamera) return;
14
+ throw codedError('camera-option', `engine.camera takes a THREE.PerspectiveCamera or THREE.OrthographicCamera, got ${cam?.constructor?.name ?? cam}. Make one of those two, or keep a `
15
+ + `subclass of your own out of engine.camera: render with it into a target in engine.onRender(({ renderer, scene }) => ...)`);
16
+ }
17
+
18
+ /**
19
+ * Give a real orthographic camera a view height and shape around its own center, before camera.zoom.
20
+ * @param {THREE.OrthographicCamera} c @param {number} height world units @param {number} [aspect] width / height, left out: as it is
21
+ */
22
+ export function fitOrtho(c, height, aspect = (c.right - c.left) / (c.top - c.bottom)) {
23
+ const x = (c.left + c.right) / 2, y = (c.top + c.bottom) / 2, w = height * aspect;
24
+ c.left = x - w / 2; c.right = x + w / 2; c.top = y + height / 2; c.bottom = y - height / 2;
25
+ c.updateProjectionMatrix();
26
+ }
27
+
28
+ /** The one place that writes camera.fov. A real orthographic camera has none @param {any} e @param {number} v */
29
+ function writeLens(e, v) { const c = e.camera; if ('fov' in c && c.fov !== v) { c.fov = v; c.updateProjectionMatrix(); } }
30
+
31
+ /**
32
+ * Every engine write of camera.fov that is the base view (settings menu slider, camera modules) goes through here: it yields to a fov the game set itself.
33
+ * While someone holds the camera the value is what the view goes back to, not what it shows now (viewHold).
34
+ * @param {any} e @param {number} v
35
+ */
36
+ export function setFov(e, v) {
37
+ if (v == null) return;
38
+ const h = e._viewHold, o = e._oFov;
39
+ if (!h) { o.drive(v); return; }
40
+ o.check();
41
+ if (o.on) h.fov = v;
42
+ }
43
+
44
+ /**
45
+ * The fov a holder of the camera shows (a shot, a named view): a layer on the base view, gone when the last holder leaves. It goes on even over a fov the game owns, because the
46
+ * game asked for this shot; the game's value is what the hold recorded, so it comes back with the rest.
47
+ * @param {any} e @param {number} v only with the camera held
48
+ */
49
+ export function holdFov(e, v) {
50
+ e._oFov.check();
51
+ writeLens(e, v);
52
+ e._oFov.mark();
53
+ e._viewHold.shown = e.camera.fov;
54
+ }
55
+
56
+ /**
57
+ * The fov of a rig's shot. A shot with one is a layer on the base view like a holder's, so the slider's value waits under it; null, a shot without one, lets the base view show.
58
+ * It yields to a fov the game took, as setFov does. Why not setFov: a rig writes every frame, and what it writes there is the base, so nothing else could ever change it.
59
+ * @param {any} e @param {number | null} v
60
+ */
61
+ export function shotFov(e, v) {
62
+ e._oFov.check();
63
+ e._shotLens = v != null && e._oFov.on;
64
+ viewHold(e);
65
+ if (e._shotLens) holdFov(e, v);
66
+ }
67
+
68
+ /**
69
+ * The 'camera' stack changed. Why here and not in each holder: every holder used to record the fov it found and write it back when it left, so two overlapping shots handed back
70
+ * each other's half-way value and a slider moved meanwhile was lost. The first holder records the view it took, whatever asks for the view during the hold changes that record, and
71
+ * the last one out lands it. A fov someone else wrote during the hold differs from what the holders showed, and stays.
72
+ * @param {any} e
73
+ */
74
+ export function viewHold(e) {
75
+ const held = e.stacks.get('camera').size() > 0 || !!e._shotLens, h = e._viewHold;
76
+ if (held === !!h) return;
77
+ if (held) { e._viewHold = { fov: e.camera.fov, shown: e.camera.fov, projection: null }; return; }
78
+ e._viewHold = null;
79
+ if (h.projection) setProjection(e, ...h.projection);
80
+ if (e.camera.fov !== h.shown || h.fov === undefined) return;
81
+ writeLens(e, h.fov);
82
+ e._oFov.mark(); // the record is the engine's own write; a fov that differed above stays for check() to see
83
+ }
84
+
85
+ /** The fov of the perspective view: while a rig's orthographic camera stands in, that is the camera it stands in for @param {any} e @returns {number | undefined} */
86
+ export const lensFov = e => (e._ortho?.home ?? e.camera).fov;
87
+
88
+ /** The base view's fov, what a shot with none blends to @param {any} e @returns {number | undefined} */
89
+ export const baseFov = e => e._viewHold?.fov ?? lensFov(e);
90
+
91
+ /** Hand everything a camera carries that its class does not decide to the next one, and make it engine.camera @param {any} e @param {any} to */
92
+ function swapCamera(e, to) {
93
+ const from = e.camera;
94
+ to.near = from.near; to.far = from.far; to.zoom = from.zoom; to.layers.mask = from.layers.mask;
95
+ to.position.copy(from.position); to.quaternion.copy(from.quaternion); to.up.copy(from.up);
96
+ if (from.parent) { from.parent.add(to); from.removeFromParent(); }
97
+ if (from.children.length) to.add(...from.children); // what a game hung on the camera stays on the view
98
+ e.camera = to;
99
+ }
100
+
101
+ /**
102
+ * A rig's projection option, as a thin call into the one way to an orthographic view: a real THREE.OrthographicCamera in engine.camera (the setter in core/engine/Engine.js, where
103
+ * everything that draws, picks or owns a camera value already follows). The option stays because a view is not only a camera: a shot, a rig switch and a new playthrough each ask
104
+ * for theirs, and going back needs someone who remembers what was there. That memory is engine._ortho: the one orthographic camera the rigs share, and the camera it stands in for.
105
+ * A camera the game assigned is never overruled: 'perspective' is the rigs' "back to the default" and leaves a real orthographic camera as it is, and 'orthographic' on one only
106
+ * sets its height.
107
+ * @param {any} e the engine
108
+ * @param {'perspective' | 'orthographic'} [projection]
109
+ * @param {number} [size] orthographic only: world units covered by the view height (before camera.zoom)
110
+ */
111
+ export function setProjection(e, projection = 'perspective', size = 20) {
112
+ if (projection !== 'perspective' && projection !== 'orthographic') throw codedError('camera-option', `projection must be 'perspective' or 'orthographic', got '${projection}'`);
113
+ if (e._viewHold) { e._viewHold.projection = [projection, size]; return; } // a swap would pull the camera out from under the holder: it lands with the rest of the view
114
+ const cam = e.camera;
115
+ if (projection === 'perspective') { if (cam === e._ortho?.camera) swapCamera(e, e._ortho.home); return; }
116
+ if (!(size > 0)) throw codedError('camera-option', `orthographic projection needs size > 0 (world units of view height), got ${size}`);
117
+ if (cam.isOrthographicCamera) { if (cam.top - cam.bottom !== size) fitOrtho(cam, size); return; }
118
+ e._ortho ??= { camera: new THREE.OrthographicCamera(), home: null };
119
+ e._ortho.home = cam;
120
+ fitOrtho(e._ortho.camera, size, cam.aspect);
121
+ swapCamera(e, e._ortho.camera);
122
+ }
123
+
124
+ /** @param {any} e */
125
+ export function defineView(e) {
126
+ const cam = () => e.camera;
127
+ // A real THREE.OrthographicCamera has no fov and no aspect, and its depth range is the game's: the engine leaves its far and fov alone, and its aspect is the frustum's shape.
128
+ // The one a rig's projection made (setProjection) stands in for the perspective camera, so its far stays the view range's and goes back with the swap.
129
+ // Rounded because a new view height writes the frustum again, and float noise there is not a game's write
130
+ const lens = () => 'fov' in cam(), shape = c => Math.round((c.right - c.left) / (c.top - c.bottom) * 1e6) / 1e6;
131
+ e._oFar = defineOwned(e, { id: 'view.far', part: 'view', key: 'far', read: () => cam().far, objects: [e.camera],
132
+ write: v => { if (lens() || cam() === e._ortho?.camera) { cam().far = v; cam().updateProjectionMatrix(); } }, levels: { manual: "engine.autoView.manual('far')" } });
133
+ e._oPixelRatio = defineOwned(e, { id: 'view.pixelRatio', part: 'view', key: 'pixelRatio', read: () => e.renderer.getPixelRatio(), objects: [e.renderer],
134
+ levels: { manual: "engine.autoView.manual('pixelRatio')", set: 'engine.setPixelRatio(1.5)' } });
135
+ // fov: the settings menu slider and camera modules (first person / rts / fixed shots, and restoring the fov at uninstall) go through setFov, and a holder's shot through holdFov,
136
+ // so a game that sets camera.fov itself (a zoom) is not undone by the next camera switch.
137
+ e._oFov = defineOwned(e, { id: 'view.fov', part: 'view', key: 'fov', read: () => cam().fov, objects: [e.camera],
138
+ write: v => writeLens(e, v), levels: { manual: "engine.autoView.manual('fov')" } });
139
+ // aspect: the engine writes it on every resize and when engine.camera is assigned. A game's own (letterbox, split view) stays, the same as far and fov.
140
+ // A real orthographic camera keeps its view height and its width follows; left / right the game wrote itself count as its own aspect
141
+ e._oAspect = defineOwned(e, { id: 'view.aspect', part: 'view', key: 'aspect', read: () => (lens() ? cam().aspect : shape(cam())), objects: [e.camera],
142
+ write: v => { const c = cam(); if (lens()) { c.aspect = v; c.updateProjectionMatrix(); } else fitOrtho(c, c.top - c.bottom, v); }, levels: { manual: "engine.autoView.manual('aspect')" } });
143
+ e._oFar.mark(); e._oPixelRatio.mark(); e._oFov.mark(); e._oAspect.mark();
144
+ e.autoView = {
145
+ /**
146
+ * Stop the engine changing a camera or drawing-buffer value: the value is yours until you hand it back. A direct write takes it too; this says so on purpose,
147
+ * with no warning. 'camera' hands the pose back after a direct write (take it with engine.takeCamera(owner)).
148
+ * @example
149
+ * const mine = engine.autoView.manual('far');
150
+ * engine.camera.far = 5000;
151
+ * mine.remove();
152
+ * @param {'far' | 'fov' | 'aspect' | 'pixelRatio' | 'sunDir' | 'camera'} key
153
+ * @param {boolean} [on] false hands it back
154
+ * @returns {{ remove(): void }} remove() hands it back
155
+ */
156
+ manual(key, on = true) {
157
+ if (typeof key !== 'string') throw codedError('owned-misuse', `engine.autoView.manual(key): key must be 'far', 'fov', 'aspect', 'pixelRatio', 'sunDir' or 'camera'; got ${JSON.stringify(key)}`);
158
+ return manualVerb(e, 'view', key, on);
159
+ },
160
+ };
161
+ }
@@ -5,12 +5,13 @@
5
5
  // writable without surprises (your own Raycaster, scene walks, material swaps see exactly the meshes you made). Opt in per object with
6
6
  // obj.userData.batch = true on the root you add to the scene. Dev: when many identical game meshes draw one by one, stats.hint (describe().perf.batching)
7
7
  // and one console line say so with that opt-in.
8
- // Rule: once at least minCount meshes with the same geometry, material and shadow flags sit in one cell (cell meters, default engine.stream.cellSize),
8
+ // Rule: once at least minCount meshes with the same geometry, material and shadow flags sit in one cell (cell meters, default four engine.stream cells),
9
9
  // they become instances of one InstancedMesh; below that they stay plain meshes. A batch dissolves when it drops under half of minCount.
10
10
  // The placed object stays in the scene as it was (its userData, record, colliders, interactions are untouched): only its meshes are hidden and marked
11
11
  // moved to layer 31 (BATCH_LAYER: not drawn, not in shadows; visible stays the game's). engine.raycast / pick / photo still hit the original and
12
12
  // return it, never an instance index (engine.rays tests layer 31 too). Your own THREE.Raycaster: batching.item(hit.object, hit.instanceId).
13
13
  // Moving / hiding / removing the object updates its instance next frame (checked each frame on the object's own transform); recolor with tint().
14
+ // Ownership with BundleGroup: a mesh under a three BundleGroup is the bundle's. Batching leaves it alone, so each mesh has one owner; userData.batch = true on such a root warns once.
14
15
  // Never batched: skinned / instanced / morphing meshes, objects with animations, multi-material, transparent, ShaderMaterial, custom renderOrder /
15
16
  // layers / onBeforeRender, meshes with children, anything hlod registered (userData.hlod), and anything marked userData.batch = false (itself or a
16
17
  // parent; a world record says batch: false).
@@ -19,11 +20,14 @@
19
20
  // Ownership with hlod: batching owns repeated things that are near enough to be built (props, views, stream entries); hlod owns the level geometry it was
20
21
  // given and swaps it for merged proxies far away. A mesh belongs to whichever took it first, so they never fight over visibility.
21
22
  // createEngine({ batching: false }) turns it off (nothing is watched, zero cost); engine.batching.enabled = false at runtime dissolves every batch.
22
- /** @import { BatchingOptions, BatchingStats, BatchInfo } from '../types/core' */
23
+ /** @import { BatchingOptions, BatchingStats, BatchInfo } from '../../types/core' */
23
24
  import * as THREE from 'three';
24
- import { warnOnce, DEV, note } from './validate.js';
25
- import { BATCH_LAYER, build, join, leave, dissolve, color, localTint, bounds, snap, same, stored, under } from './batchGroups.js';
26
- import { codedError } from './errorHints.js';
25
+ import { warnOnce, DEV, note, fmt } from '../base/validate.js';
26
+ import { BATCH_LAYER, build, join, leave, dissolve, color, localTint, bounds, snap, same, stored, inBundle } from './batchGroups.js';
27
+ import { isUnder } from '../base/util.js';
28
+ import { codedError } from '../base/errorHints.js';
29
+ import { notePatch, patchOn } from '../scene/threePatches.js';
30
+ import { engineOwned } from '../scene/things.js';
27
31
 
28
32
  const OPTS = ['minCount', 'cell'];
29
33
  // Thing-registry owners whose roots are engine-placed content (things.js add). Engine modules' own helpers ('engine:grid' tiles, 'engine:rigid'
@@ -31,6 +35,14 @@ const OPTS = ['minCount', 'cell'];
31
35
  const CONTENT = new Set(['world', 'stream', 'level']);
32
36
  // Round-robin visits in a row that found an unbatched root moved: it is moving, not placed, and stops being a batch candidate until it rests
33
37
  const MOVING = 3;
38
+ // Default batch cell, in stream cells. Why wider than one stream cell: a root lands in one batch cell, so a cell no wider than a streamed block batches nothing across
39
+ // blocks. A model used a few times per block (six facades over 16 buildings) never reached minCount and every copy drew alone. Measured on the city run: 64 m 18.9 ms a frame,
40
+ // 256 m 9.9 ms. The price is coarser culling, about 13-25% more triangles drawn there; a game with heavy props and little CPU load can set a smaller cell.
41
+ const CELL_SPAN = 4;
42
+ const VERIFY_MESHES = 256; // meshes the round robin looks at per frame; one root is always finished, so a single huge root goes over once per lap
43
+ const PATCH = 'batching-draw-walk';
44
+ notePatch(PATCH, "children of a parent holding batched meshes: those meshes are out of the array during the engine's own draw, back right after (core/stream/Batching.js)", () => {},
45
+ { scope: 'objects in the scene', lost: 'three walks every batched original twice a frame again; a district of blocks pays about a third of its frame for meshes that do not draw' });
34
46
  const STRINGS = {
35
47
  evicted: '[batching] a batched copy of "{name}" changed after batching ({why}); it is drawn on its own from now on. Mark models that animate parts or swap materials with batch: false on the record (userData.batch = false on the object)',
36
48
  opts: 'createEngine({ batching }) takes false or { minCount, cell }; unknown key "{key}"',
@@ -39,6 +51,7 @@ const STRINGS = {
39
51
  note: 'repeated static meshes the engine placed (world records, stream builds, level files) are drawn as InstancedMesh batches (originals stay in the ' +
40
52
  'scene on layer 31; your own scene.add meshes only with userData.batch = true). Your own THREE.Raycaster: engine.batching.item(hit.object, hit.instanceId); ' +
41
53
  'keep a model as plain meshes: batch: false on its record (userData.batch = false on the object); off: createEngine({ batching: false })',
54
+ bundled: '[batching] userData.batch = true on "{name}" has no effect: it is a BundleGroup, which draws its own meshes. Keep one: a BundleGroup, or a plain Group with batching',
42
55
  // Game meshes are not batched by default (see the header); when that costs many draw calls the game should hear the one-line way in.
43
56
  hint: '{n} copies of "{name}" added by the game draw one by one (engine.batching only batches what the engine places). If they stay static, set ' +
44
57
  'obj.userData.batch = true on each before adding it to batch them as one InstancedMesh per cell',
@@ -46,13 +59,13 @@ const STRINGS = {
46
59
  const PROTO_BEFORE = THREE.Object3D.prototype.onBeforeRender;
47
60
  const HIDDEN = (1 << BATCH_LAYER) >>> 0; // three keeps layer masks unsigned
48
61
 
49
- /** engine.batching: draws repeated static models as InstancedMesh batches (see the top of core/Batching.js). */
62
+ /** engine.batching: draws repeated static models as InstancedMesh batches (see the top of core/stream/Batching.js). */
50
63
  export class Batching {
51
64
  /** @internal @param {any} engine @param {BatchingOptions | false} [opts] */
52
65
  constructor(engine, opts = {}) {
53
- for (const k of Object.keys(opts || {})) if (!OPTS.includes(k)) throw codedError('batching-option', STRINGS.opts.replace('{key}', k));
66
+ for (const k of Object.keys(opts || {})) if (!OPTS.includes(k)) throw codedError('batching-option', fmt(STRINGS.opts, { key: k }));
54
67
  /** @internal */ this.engine = engine;
55
- /** Same model at least this many times in one cell becomes a batch (default 8) @type {number} */
68
+ /** Same model at least this many times in one cell becomes a batch (default 8) @type {number} @experimental */
56
69
  this.minCount = (opts && opts.minCount) || 8;
57
70
  /** @internal */ this._cell = (opts && opts.cell) || null;
58
71
  /** @internal key -> group */ this.groups = new Map();
@@ -61,17 +74,20 @@ export class Batching {
61
74
  /** @internal */ this.list = [];
62
75
  /** @internal */ this.cursor = 0;
63
76
  /** @internal roots added since the last update */ this.incoming = new Set();
64
- /** @internal mesh -> its original material while a local tint clone is on it */ this.orig = new Map();
77
+ /** @internal mesh -> its original material while a local tint clone is on it (weak: a tinted mesh that left for good must not stay here) */ this.orig = new WeakMap();
65
78
  /** @internal mesh -> tint color */ this.tints = new WeakMap();
66
79
  /** @internal geometries evicted once (never batched again) */ this.banned = new WeakSet();
67
80
  /** @internal batch InstancedMesh -> group */ this.byMesh = new WeakMap();
68
- /** Geometries and materials a live batch draws (engine.remove does not dispose these) @type {Map<any, number>} */ this.held = new Map();
81
+ /** Geometries and materials a live batch draws (engine.remove does not dispose these) @type {Map<any, number>} @experimental */ this.held = new Map();
69
82
  /** Parent of every batch InstancedMesh (in the scene) @type {THREE.Group} */
70
- this.root = new THREE.Group();
83
+ this.root = engineOwned('batching', new THREE.Group()); // the registry is up by now: unmarked, scene.add would adopt it as a game object
71
84
  this.root.name = 'batching'; this.root.matrixAutoUpdate = false; this.root.userData.batch = false;
72
85
  /** @internal dev: 'geometry.id|material.id' -> how many unbatched game meshes draw it (the opt-in hint) */ this.plain = new Map();
73
86
  /** @internal dev: game root -> the plain keys it counted (taken back when it leaves the scene) */ this.counted = new Map();
74
87
  /** @internal dev: the key the hint is about (null until some key reached minCount) */ this._hintKey = null; /** @internal the hint console line was printed */ this._hinted = false;
88
+ /** @internal parent -> { parent, all, count, last, drawn }: parents whose batched children skip the draw walk */ this.skips = new Map();
89
+ /** @internal parents with a join, leave or child change since skips was listed */ this.skipsStale = new Set();
90
+ /** @internal the children are swapped right now */ this.skipping = false;
75
91
  /** @internal */ this._on = false;
76
92
  /** @internal */ this._add = ev => { if (ev.child !== this.root) this.incoming.add(ev.child); };
77
93
  /** @internal */ this._rem = ev => { this.incoming.delete(ev.child); this._untrack(ev.child); this._uncount(ev.child); };
@@ -86,17 +102,17 @@ export class Batching {
86
102
  this._on = on;
87
103
  if (on) {
88
104
  s.addEventListener('childadded', this._add); s.addEventListener('childremoved', this._rem);
89
- s.add(this.root);
90
105
  for (const c of s.children) if (c !== this.root) this.incoming.add(c);
91
106
  } else {
92
107
  s.removeEventListener('childadded', this._add); s.removeEventListener('childremoved', this._rem);
93
108
  for (const r of [...this.roots.keys()]) this._untrack(r);
109
+ this._listSkips(); // lets go of the parents
94
110
  this.incoming.clear(); this.root.removeFromParent();
95
111
  this.plain.clear(); this.counted.clear(); this._hintKey = null; // switching on again recounts every root
96
112
  }
97
113
  }
98
- /** Cell edge in meters (default engine.stream.cellSize) @type {number} */
99
- get cell() { return this._cell ?? this.engine.stream.cellSize; }
114
+ /** Cell edge in meters (default four engine.stream cells, 256 m) @type {number} */
115
+ get cell() { return this._cell ?? this.engine.stream.cellSize * CELL_SPAN; }
100
116
  set cell(v) { this._cell = v; this._rescan(); }
101
117
 
102
118
  /** Every batch: { mesh: InstancedMesh, cell, count, items } (items[i] is the placed object drawn by instance i) @returns {BatchInfo[]} */
@@ -125,7 +141,7 @@ export class Batching {
125
141
  /** @internal dev: the opt-in line while the most repeated unbatched game mesh still has at least minCount copies in the scene */
126
142
  _hint() {
127
143
  const k = this._hintKey, n = k ? this.plain.get(k)?.n ?? 0 : 0;
128
- return n >= this.minCount ? STRINGS.hint.replace('{n}', n).replace('{name}', this.plain.get(k).name) : null;
144
+ return n >= this.minCount ? fmt(STRINGS.hint, { n, name: this.plain.get(k).name }) : null;
129
145
  }
130
146
  /**
131
147
  * Where an object is drawn: [{ mesh, index }] for each of its meshes that is batched ([] when drawn on its own).
@@ -160,9 +176,10 @@ export class Batching {
160
176
  }
161
177
  /** Re-check one object now (after you changed its parts by hand, or set userData.batch on a root already in the scene); normally automatic @param {THREE.Object3D} obj */
162
178
  refresh(obj) {
163
- const info = this._infoOf(obj); if (info) { this._detach(info); this._untrack(info.root); }
164
- this._uncount(obj);
165
- if (obj.parent === this.engine.scene) this.incoming.add(obj);
179
+ const info = this._infoOf(obj), root = info?.root ?? obj; // a part of a placed object: the object is what goes round again
180
+ if (info) this._untrack(root);
181
+ this._uncount(root);
182
+ if (root.parent === this.engine.scene) this.incoming.add(root);
166
183
  }
167
184
 
168
185
  /** @internal Called by the engine each frame after frame hooks / stream / jobs, before rendering */
@@ -170,11 +187,49 @@ export class Batching {
170
187
  if (!this._on) return;
171
188
  if (this.incoming.size) { for (const r of this.incoming) if (r.parent === this.engine.scene) this._track(r); this.incoming.clear(); }
172
189
  for (const info of this.live) this._check(info);
173
- // round robin: look for parts changed behind our back (bounded per frame)
174
- const L = this.list, n = Math.min(L.length, 256);
175
- for (let i = 0; i < n; i++) { if (this.cursor >= L.length) this.cursor = 0; this._verify(L[this.cursor++]); }
190
+ // round robin: look for parts changed behind our back. Bounded in meshes, not roots: a streamed city block is one root with hundreds of meshes,
191
+ // and 256 roots a frame checked every mesh of a district every frame (a quarter of the frame in the city stress run)
192
+ const L = this.list;
193
+ for (let seen = 0, left = VERIFY_MESHES; seen < L.length && left > 0; seen++) {
194
+ if (this.cursor >= L.length) this.cursor = 0;
195
+ const info = L[this.cursor++]; left -= info.entries.length; this._verify(info);
196
+ }
176
197
  for (const g of this.groups.values()) if (g.dirty) { g.dirty = false; bounds(g); }
177
198
  }
199
+ /**
200
+ * @internal Called right before the frame's draw: batched originals leave their parent's children until unskip(), so three's two whole-scene walks
201
+ * (updateMatrixWorld, the draw list) do not visit meshes that never draw. They cost more than the draws themselves in a district of blocks. Only this
202
+ * window: game code, raycasts and scene.traverse always see the scene as it was built. Scene changes made during a render are lost here (three itself
203
+ * walks these arrays then, so that was never safe). A root that is itself the batched mesh stays: it sits in the scene's own children.
204
+ */
205
+ skip() {
206
+ if (!this._on || !patchOn(PATCH)) return;
207
+ // three appends on add, so count and last child together see every add and remove, also a swap that keeps the count
208
+ for (const s of this.skips.values()) { const c = s.parent.children; if (c.length !== s.count || c[c.length - 1] !== s.last) this.skipsStale.add(s.parent); }
209
+ if (this.skipsStale.size) this._listSkips();
210
+ for (const s of this.skips.values()) { s.all = s.parent.children; s.parent.children = s.drawn; }
211
+ this.skipping = true;
212
+ }
213
+ /** @internal Right after the draw: every parent gets its real children back */
214
+ unskip() {
215
+ if (!this.skipping) return;
216
+ this.skipping = false;
217
+ for (const s of this.skips.values()) s.parent.children = s.all;
218
+ }
219
+ /** @internal A mesh joined or left a batch: its parent is listed again before the next draw. A root that is itself the mesh sits in the scene's children, which are never skipped */
220
+ _skipChanged(e) { if (e.mesh !== e.info.root && e.mesh.parent) this.skipsStale.add(e.mesh.parent); }
221
+ /**
222
+ * @internal What is left of the changed parents' children without their batched meshes. Only those parents: listing every parent went through every batched mesh of the district
223
+ * each time a block came or went. A child hung on a batched mesh still draws until the round robin evicts it, so a mesh with children is not skipped.
224
+ */
225
+ _listSkips() {
226
+ for (const parent of this.skipsStale) {
227
+ const drawn = parent.children.filter(c => !c.userData.batched || c.children.length);
228
+ if (drawn.length === parent.children.length) this.skips.delete(parent);
229
+ else this.skips.set(parent, { parent, all: null, count: parent.children.length, last: parent.children.at(-1), drawn });
230
+ }
231
+ this.skipsStale.clear();
232
+ }
178
233
  /** @internal */
179
234
  dispose() { this.enabled = false; this.groups.clear(); }
180
235
 
@@ -186,8 +241,10 @@ export class Batching {
186
241
  const u = root.userData, owner = this.engine._things?.byObj.get(root)?.owner, mine = u.batch === true || CONTENT.has(owner);
187
242
  // the opt-in hint counts only the game's own roots: an engine module's helpers ('engine:grid' tiles, 'engine:rigid' bodies) are not the game's to mark
188
243
  if (!mine || u.batch === false || root.animations?.length) { this._plain(root, !mine && u.batch !== false && (owner == null || owner === 'game')); return; }
244
+ if (u.batch === true && root.isBundleGroup) warnOnce(fmt(STRINGS.bundled, { name: root.name || 'a group' }));
189
245
  const meshes = [];
190
246
  let ok = true;
247
+ root.updateMatrixWorld(true); // _eligible reads the world matrix
191
248
  const walk = (o, top) => {
192
249
  if (!ok) return;
193
250
  if (o.isSkinnedMesh || o.isInstancedMesh || o.isBatchedMesh) { ok = false; return; }
@@ -199,7 +256,7 @@ export class Batching {
199
256
  };
200
257
  walk(root, true);
201
258
  if (!ok || !meshes.length) return;
202
- const info = { root, entries: [], snap: [], cell: null, shown: false, idx: this.list.length, moves: 0, moving: false };
259
+ const info = { root, entries: [], snap: [], cell: null, idx: this.list.length, moves: 0, moving: false };
203
260
  for (const mesh of meshes) info.entries.push({ mesh, info, group: null, slot: -1 });
204
261
  this.roots.set(root, info); this.list.push(info);
205
262
  snap(root, info.snap);
@@ -210,7 +267,8 @@ export class Batching {
210
267
  const mat = this.orig.get(m) ?? m.material;
211
268
  return !m.children.length && !Array.isArray(mat) && mat && !mat.transparent && !mat.isShaderMaterial && m.geometry?.attributes.position
212
269
  && !m.morphTargetInfluences && !Object.keys(m.geometry.morphAttributes).length && !m.userData.hlod && !this.banned.has(m.geometry)
213
- && m.renderOrder === 0 && m.layers.mask === 1 && m.frustumCulled && m.onBeforeRender === PROTO_BEFORE;
270
+ && m.renderOrder === 0 && m.layers.mask === 1 && m.frustumCulled && m.onBeforeRender === PROTO_BEFORE && !inBundle(m)
271
+ && m.matrixWorld.determinant() >= 0; // mirrored: three picks the winding from the object's matrix, and a batch's is identity, so it would draw inside out
214
272
  }
215
273
  /** @internal */
216
274
  _untrack(root) {
@@ -262,7 +320,7 @@ export class Batching {
262
320
  /** @internal put a root's meshes into the groups of its cell */
263
321
  _attach(info) {
264
322
  const p = info.root.position, cs = this.cell;
265
- info.cell = Math.floor(p.x / cs) + ',' + Math.floor(p.z / cs); info.shown = true;
323
+ info.cell = Math.floor(p.x / cs) + ',' + Math.floor(p.z / cs);
266
324
  info.root.updateMatrixWorld(true);
267
325
  for (const e of info.entries) {
268
326
  const m = e.mesh, mat = this.orig.get(m) ?? m.material;
@@ -276,7 +334,6 @@ export class Batching {
276
334
  }
277
335
  /** @internal take a root's meshes out of their groups (they draw on their own again) */
278
336
  _detach(info) {
279
- info.shown = false;
280
337
  for (const e of info.entries) {
281
338
  const g = e.group; if (!g) continue;
282
339
  e.group = null; g.members.delete(e);
@@ -295,7 +352,7 @@ export class Batching {
295
352
  snap(r, info.snap);
296
353
  if (!r.visible) { this._detach(info); return; }
297
354
  const cs = this.cell, cell = Math.floor(r.position.x / cs) + ',' + Math.floor(r.position.z / cs);
298
- if (cell !== info.cell || !info.shown) { this._detach(info); this._attach(info); return; }
355
+ if (cell !== info.cell) { this._detach(info); this._attach(info); return; }
299
356
  r.updateMatrixWorld(true);
300
357
  for (const e of info.entries) if (e.slot >= 0) { e.group.mesh.setMatrixAt(e.slot, e.mesh.matrixWorld); e.group.mesh.instanceMatrix.needsUpdate = true; e.group.dirty = true; }
301
358
  }
@@ -317,7 +374,7 @@ export class Batching {
317
374
  if (e.slot < 0) continue;
318
375
  const m = e.mesh, g = e.group;
319
376
  let why = m.layers.mask !== HIDDEN ? 'layers' : !m.visible ? 'hidden' : m.material !== g.material ? 'material' : m.geometry !== g.geometry ? 'geometry' : m.children.length ? 'children'
320
- : m.castShadow !== g.cast || m.receiveShadow !== g.receive ? 'shadow flags' : !under(m, r) ? 're-parented' : '';
377
+ : m.castShadow !== g.cast || m.receiveShadow !== g.receive ? 'shadow flags' : !isUnder(m, r) ? 're-parented' : '';
321
378
  if (!why) {
322
379
  m.updateWorldMatrix(true, false);
323
380
  if (!stored(g.mesh.instanceMatrix.array, e.slot, m.matrixWorld) && same(r, info.snap)) why = 'a part moved';
@@ -327,7 +384,7 @@ export class Batching {
327
384
  }
328
385
  /** @internal */
329
386
  _evict(info, why) {
330
- warnOnce(STRINGS.evicted.replace('{name}', info.root.name || info.entries[0].mesh.name || 'model').replace('{why}', why));
387
+ warnOnce(fmt(STRINGS.evicted, { name: info.root.name || info.entries[0].mesh.name || 'model', why }));
331
388
  for (const e of info.entries) this.banned.add(e.mesh.geometry);
332
389
  this._untrack(info.root);
333
390
  }