threedog 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (506) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/LICENSE +21 -0
  3. package/README.md +39 -2
  4. package/core/Animator.js +268 -0
  5. package/core/Assets.js +256 -0
  6. package/core/Audio.js +267 -0
  7. package/core/Baked.js +72 -0
  8. package/core/Batching.js +247 -0
  9. package/core/Budget.js +221 -0
  10. package/core/Clock.js +94 -0
  11. package/core/Commits.js +77 -0
  12. package/core/DebugOverrides.js +143 -0
  13. package/core/Describe.js +145 -0
  14. package/core/Engine.js +184 -0
  15. package/core/Events.js +153 -0
  16. package/core/I18n.js +94 -0
  17. package/core/Input.js +245 -0
  18. package/core/Inspect.js +77 -0
  19. package/core/InspectScene.js +191 -0
  20. package/core/Jobs.js +146 -0
  21. package/core/Loading.js +149 -0
  22. package/core/MaterialInfo.js +32 -0
  23. package/core/Ops.js +256 -0
  24. package/core/Random.js +52 -0
  25. package/core/Rays.js +160 -0
  26. package/core/SaveStore.js +85 -0
  27. package/core/Saves.js +254 -0
  28. package/core/Stream.js +279 -0
  29. package/core/Threads.js +158 -0
  30. package/core/UrlState.js +94 -0
  31. package/core/Vars.js +35 -0
  32. package/core/Views.js +49 -0
  33. package/core/actor.js +23 -0
  34. package/core/assetEntry.js +89 -0
  35. package/core/assetLoad.js +190 -0
  36. package/core/assetManifest.js +35 -0
  37. package/core/assetReport.js +83 -0
  38. package/core/audioRules.js +121 -0
  39. package/core/audioVoice.js +225 -0
  40. package/core/batchGroups.js +116 -0
  41. package/core/canvasBox.js +63 -0
  42. package/core/catalog.js +169 -0
  43. package/core/checks.js +67 -0
  44. package/core/claims.js +51 -0
  45. package/core/dayTime.js +15 -0
  46. package/core/debugView.js +76 -0
  47. package/core/describeRender.js +45 -0
  48. package/core/describeText.js +143 -0
  49. package/core/easing.js +34 -0
  50. package/core/errorCodes.js +205 -0
  51. package/core/errorHints.js +208 -0
  52. package/core/errors.js +40 -0
  53. package/core/events.generated.js +84 -0
  54. package/core/ground.js +102 -0
  55. package/core/holds.js +106 -0
  56. package/core/inputContext.js +69 -0
  57. package/core/inputDefaults.js +22 -0
  58. package/core/inputPad.js +35 -0
  59. package/core/inputPointer.js +48 -0
  60. package/core/inputTouch.js +48 -0
  61. package/core/lifecycle.js +69 -0
  62. package/core/lightWatch.js +56 -0
  63. package/core/look/coreParts.js +112 -0
  64. package/core/look/layers.js +136 -0
  65. package/core/look/part.js +173 -0
  66. package/core/look/report.js +79 -0
  67. package/core/look/write.js +86 -0
  68. package/core/loop.js +200 -0
  69. package/core/math.js +33 -0
  70. package/core/modules.js +196 -0
  71. package/core/movement.js +19 -0
  72. package/core/mulberry32.js +14 -0
  73. package/core/opsAtomic.js +31 -0
  74. package/core/opsCheck.js +97 -0
  75. package/core/opsFail.js +20 -0
  76. package/core/opsGuard.js +26 -0
  77. package/core/opsHistory.js +27 -0
  78. package/core/opsRun.js +77 -0
  79. package/core/page.js +78 -0
  80. package/core/params.js +132 -0
  81. package/core/pureWorker.js +5 -0
  82. package/core/renamed.js +21 -0
  83. package/core/saveApply.js +128 -0
  84. package/core/saveFiles.js +139 -0
  85. package/core/saveIds.js +53 -0
  86. package/core/saveVersions.js +97 -0
  87. package/core/scatter.js +92 -0
  88. package/core/sceneMethods.js +100 -0
  89. package/core/screenToGround.js +39 -0
  90. package/core/services.js +73 -0
  91. package/core/session.js +171 -0
  92. package/core/shadowTypes.js +15 -0
  93. package/core/skip.js +104 -0
  94. package/core/startup.js +135 -0
  95. package/core/streamCells.js +24 -0
  96. package/core/streamSources.js +73 -0
  97. package/core/styleParts.js +96 -0
  98. package/core/targeting.js +64 -0
  99. package/core/thingExplain.js +68 -0
  100. package/core/thingOps.js +168 -0
  101. package/core/things.js +212 -0
  102. package/core/threadPure.js +120 -0
  103. package/core/threadServe.js +25 -0
  104. package/core/tier.js +11 -0
  105. package/core/util.js +11 -0
  106. package/core/validate.js +204 -0
  107. package/docs/AI.md +123 -0
  108. package/docs/API.md +83 -0
  109. package/docs/CODEMAP.md +347 -0
  110. package/docs/COMMANDS.md +108 -0
  111. package/docs/CONVENTIONS.md +145 -0
  112. package/docs/PERF.md +217 -0
  113. package/docs/THREE.md +86 -0
  114. package/docs/api/ambience.md +15 -0
  115. package/docs/api/assets.md +62 -0
  116. package/docs/api/audio.md +53 -0
  117. package/docs/api/budget.md +40 -0
  118. package/docs/api/cameraRig.md +120 -0
  119. package/docs/api/characters.md +144 -0
  120. package/docs/api/clock.md +7 -0
  121. package/docs/api/collision.md +39 -0
  122. package/docs/api/content.md +64 -0
  123. package/docs/api/dialogue.md +39 -0
  124. package/docs/api/engine.md +199 -0
  125. package/docs/api/entities.md +61 -0
  126. package/docs/api/events.md +95 -0
  127. package/docs/api/flow.md +27 -0
  128. package/docs/api/grids.md +11 -0
  129. package/docs/api/ground.md +16 -0
  130. package/docs/api/hlod.md +34 -0
  131. package/docs/api/hud.md +31 -0
  132. package/docs/api/i18n.md +10 -0
  133. package/docs/api/input.md +24 -0
  134. package/docs/api/interactions.md +31 -0
  135. package/docs/api/inventory.md +66 -0
  136. package/docs/api/jobs.md +10 -0
  137. package/docs/api/level.md +41 -0
  138. package/docs/api/lightPool.md +56 -0
  139. package/docs/api/music.md +34 -0
  140. package/docs/api/nav.md +26 -0
  141. package/docs/api/net.md +14 -0
  142. package/docs/api/openWorld.md +24 -0
  143. package/docs/api/particles.md +41 -0
  144. package/docs/api/photo.md +15 -0
  145. package/docs/api/post.md +10 -0
  146. package/docs/api/quests.md +36 -0
  147. package/docs/api/rays.md +26 -0
  148. package/docs/api/rigid.md +84 -0
  149. package/docs/api/saves.md +32 -0
  150. package/docs/api/settings.md +36 -0
  151. package/docs/api/sky.md +58 -0
  152. package/docs/api/stream.md +31 -0
  153. package/docs/api/style.md +134 -0
  154. package/docs/api/terrain.md +34 -0
  155. package/docs/api/timeline.md +39 -0
  156. package/docs/api/tools.md +57 -0
  157. package/docs/api/triggers.md +56 -0
  158. package/docs/api/vars.md +9 -0
  159. package/docs/api/vegetation.md +52 -0
  160. package/docs/api/water.md +48 -0
  161. package/docs/api/weather.md +29 -0
  162. package/docs/api/world.md +30 -0
  163. package/docs/recipes/01-new-game.md +148 -0
  164. package/docs/recipes/02-npc.md +167 -0
  165. package/docs/recipes/03-items-pickups.md +158 -0
  166. package/docs/recipes/04-quests.md +83 -0
  167. package/docs/recipes/05-props-bake.md +159 -0
  168. package/docs/recipes/06-clock-events.md +117 -0
  169. package/docs/recipes/07-flow-scenes-pause.md +132 -0
  170. package/docs/recipes/08-weather-sky.md +74 -0
  171. package/docs/recipes/09-style-pack.md +234 -0
  172. package/docs/recipes/10-blender-level.md +67 -0
  173. package/docs/recipes/11-vehicles.md +55 -0
  174. package/docs/recipes/12-navmesh.md +79 -0
  175. package/docs/recipes/13-animation.md +149 -0
  176. package/docs/recipes/14-custom-module.md +91 -0
  177. package/docs/recipes/15-perf.md +78 -0
  178. package/docs/recipes/16-dev-bridge.md +180 -0
  179. package/docs/recipes/18-world.md +185 -0
  180. package/docs/recipes/19-shooting-picking.md +76 -0
  181. package/docs/recipes/20-content-actions-save.md +176 -0
  182. package/docs/recipes/21-camera.md +153 -0
  183. package/docs/recipes/22-shop-gold.md +107 -0
  184. package/docs/recipes/23-ops.md +175 -0
  185. package/docs/recipes/26-ui-parts.md +138 -0
  186. package/docs/recipes/27-net.md +96 -0
  187. package/docs/recipes/28-terrain.md +80 -0
  188. package/docs/recipes/29-grid.md +87 -0
  189. package/docs/recipes/30-templates.md +131 -0
  190. package/docs/recipes/31-audio.md +126 -0
  191. package/docs/recipes/32-action-game.md +33 -0
  192. package/docs/recipes/33-stream-sources.md +37 -0
  193. package/docs/recipes/34-environment-lighting.md +36 -0
  194. package/docs/recipes/35-style-from-reference.md +89 -0
  195. package/docs/recipes/36-sky-ground-plant-looks.md +116 -0
  196. package/docs/recipes/37-terrain-look-hooks.md +97 -0
  197. package/docs/recipes/38-environment-look-hooks.md +83 -0
  198. package/docs/recipes/40-scene.md +108 -0
  199. package/docs/recipes/41-thing-registry.md +93 -0
  200. package/docs/recipes/42-terrain-shape.md +64 -0
  201. package/docs/recipes/43-shader-patches-surface-looks.md +120 -0
  202. package/docs/recipes/44-water-weather-look-hooks.md +135 -0
  203. package/docs/recipes/45-cascaded-shadows.md +51 -0
  204. package/docs/recipes/46-blender-art-route.md +114 -0
  205. package/docs/recipes/47-island-snow-backdrop.md +44 -0
  206. package/docs/recipes/48-make-material.md +70 -0
  207. package/docs/recipes/49-game-module-contract.md +71 -0
  208. package/docs/recipes/50-own-renderer.md +12 -0
  209. package/docs/recipes/51-capability-catalog.md +63 -0
  210. package/docs/recipes/52-look.md +108 -0
  211. package/examples/action/DESIGN.md +3 -0
  212. package/examples/action/GAMEMAP.md +127 -0
  213. package/examples/action/content/actions.js +8 -0
  214. package/examples/action/content/audio.js +9 -0
  215. package/examples/action/content/index.js +10 -0
  216. package/examples/action/content/items.js +4 -0
  217. package/examples/action/content/places.js +4 -0
  218. package/examples/action/content/props.js +11 -0
  219. package/examples/action/content/templates.js +10 -0
  220. package/examples/action/content/views.js +6 -0
  221. package/examples/action/look.js +5 -0
  222. package/examples/action/main.js +137 -0
  223. package/examples/action/models.js +25 -0
  224. package/examples/sheepisland/GAMEMAP.md +107 -0
  225. package/examples/sheepisland/content/index.js +6 -0
  226. package/examples/sheepisland/content/props.js +19 -0
  227. package/examples/sheepisland/content/templates.js +5 -0
  228. package/examples/sheepisland/content/vegetation.js +8 -0
  229. package/examples/sheepisland/main.js +71 -0
  230. package/examples/sheepisland/params.js +25 -0
  231. package/examples/sheepisland/style/index.js +79 -0
  232. package/examples/sheepisland/style/models.js +59 -0
  233. package/examples/sheepisland/views.js +9 -0
  234. package/examples/styletest/GAMEMAP.md +135 -0
  235. package/examples/styletest/content/index.js +9 -0
  236. package/examples/styletest/content/items.js +8 -0
  237. package/examples/styletest/content/npcs.js +8 -0
  238. package/examples/styletest/content/places.js +5 -0
  239. package/examples/styletest/content/props.js +16 -0
  240. package/examples/styletest/content/templates.js +9 -0
  241. package/examples/styletest/content/vegetation.js +31 -0
  242. package/examples/styletest/look.js +11 -0
  243. package/examples/styletest/main.js +95 -0
  244. package/examples/styletest/models.js +87 -0
  245. package/examples/styletest/overrides.js +33 -0
  246. package/examples/styletest/panel.js +135 -0
  247. package/examples/styletest/params.js +32 -0
  248. package/examples/styletest/views.js +31 -0
  249. package/examples/world/DESIGN.md +5 -0
  250. package/examples/world/GAMEMAP.md +171 -0
  251. package/examples/world/content/actions.js +8 -0
  252. package/examples/world/content/audio.js +25 -0
  253. package/examples/world/content/bodies.js +12 -0
  254. package/examples/world/content/containers.js +4 -0
  255. package/examples/world/content/dialogues.js +33 -0
  256. package/examples/world/content/index.js +17 -0
  257. package/examples/world/content/items.js +10 -0
  258. package/examples/world/content/npcs.js +14 -0
  259. package/examples/world/content/pickups.js +11 -0
  260. package/examples/world/content/places.js +6 -0
  261. package/examples/world/content/props.js +12 -0
  262. package/examples/world/content/quests.js +15 -0
  263. package/examples/world/content/rules.js +23 -0
  264. package/examples/world/content/templates.js +5 -0
  265. package/examples/world/content/vegetation.js +32 -0
  266. package/examples/world/main.js +168 -0
  267. package/examples/world/models.js +28 -0
  268. package/index.d.ts +306 -0
  269. package/index.js +122 -0
  270. package/llms.txt +61 -0
  271. package/modules/ambience/Ambience.js +186 -0
  272. package/modules/camera/FirstPersonCamera.js +131 -0
  273. package/modules/camera/FixedCamera.js +162 -0
  274. package/modules/camera/FollowCamera.js +91 -0
  275. package/modules/camera/RtsCamera.js +132 -0
  276. package/modules/camera/common.js +182 -0
  277. package/modules/camera/index.js +11 -0
  278. package/modules/camera/projection.js +34 -0
  279. package/modules/characters/Character.js +235 -0
  280. package/modules/characters/NPC.js +242 -0
  281. package/modules/characters/assetModel.js +42 -0
  282. package/modules/characters/astar.js +66 -0
  283. package/modules/characters/behaviors.js +72 -0
  284. package/modules/characters/footsteps.js +13 -0
  285. package/modules/characters/index.js +215 -0
  286. package/modules/characters/moveHelpers.js +29 -0
  287. package/modules/characters/movers/common.js +62 -0
  288. package/modules/characters/movers/rapier.js +74 -0
  289. package/modules/characters/movers/simple.js +43 -0
  290. package/modules/characters/npcAvoid.js +129 -0
  291. package/modules/characters/npcSim.js +150 -0
  292. package/modules/characters/npcView.js +42 -0
  293. package/modules/characters/pathAsync.js +113 -0
  294. package/modules/characters/pathJob.js +62 -0
  295. package/modules/characters/pathWorker.js +7 -0
  296. package/modules/characters/playerStrings.js +12 -0
  297. package/modules/characters/proceduralRig.js +58 -0
  298. package/modules/characters/useModel.js +22 -0
  299. package/modules/characters/walkTo.js +58 -0
  300. package/modules/collision/Collision.js +274 -0
  301. package/modules/collision/grid.js +63 -0
  302. package/modules/content/explain.js +13 -0
  303. package/modules/content/ids.js +95 -0
  304. package/modules/content/index.js +154 -0
  305. package/modules/content/loader.js +190 -0
  306. package/modules/content/models.js +69 -0
  307. package/modules/content/packs.js +69 -0
  308. package/modules/content/props.js +89 -0
  309. package/modules/content/rules.js +134 -0
  310. package/modules/content/templates.js +189 -0
  311. package/modules/debug/DebugPanel.js +174 -0
  312. package/modules/entities/Entities.js +243 -0
  313. package/modules/entities/build.js +25 -0
  314. package/modules/entities/index.js +4 -0
  315. package/modules/flow/index.js +101 -0
  316. package/modules/gameplay/Container.js +227 -0
  317. package/modules/gameplay/Containers.js +89 -0
  318. package/modules/gameplay/Dialogue.js +219 -0
  319. package/modules/gameplay/Interactions.js +253 -0
  320. package/modules/gameplay/Inventory.js +224 -0
  321. package/modules/gameplay/Quests.js +205 -0
  322. package/modules/gameplay/boxOps.js +60 -0
  323. package/modules/gameplay/dialogueBox.js +48 -0
  324. package/modules/gameplay/interactionPrompt.js +28 -0
  325. package/modules/gameplay/inventoryOps.js +137 -0
  326. package/modules/gameplay/pickups.js +115 -0
  327. package/modules/gameplay/questLog.js +54 -0
  328. package/modules/gameplay/questSave.js +71 -0
  329. package/modules/grid/Grid.js +184 -0
  330. package/modules/grid/Layer.js +142 -0
  331. package/modules/grid/index.js +236 -0
  332. package/modules/grid/ops.js +73 -0
  333. package/modules/grid/preview.js +85 -0
  334. package/modules/grid/tiles.js +79 -0
  335. package/modules/hlod/index.js +167 -0
  336. package/modules/hud/index.js +167 -0
  337. package/modules/hud/parts.js +80 -0
  338. package/modules/level/geometry.js +46 -0
  339. package/modules/level/heightfield.js +160 -0
  340. package/modules/level/index.js +233 -0
  341. package/modules/level/nodes.js +84 -0
  342. package/modules/lights/index.js +227 -0
  343. package/modules/music/Music.js +294 -0
  344. package/modules/music/index.js +2 -0
  345. package/modules/music/rules.js +28 -0
  346. package/modules/nav/index.js +156 -0
  347. package/modules/nav/navPath.js +17 -0
  348. package/modules/net/Client.js +137 -0
  349. package/modules/net/Host.js +117 -0
  350. package/modules/net/Net.js +49 -0
  351. package/modules/net/index.js +77 -0
  352. package/modules/net/sync.js +114 -0
  353. package/modules/net/transports.js +118 -0
  354. package/modules/particles/Particles.js +179 -0
  355. package/modules/particles/effect.js +112 -0
  356. package/modules/particles/shaders.js +28 -0
  357. package/modules/photo/Photo.js +146 -0
  358. package/modules/rigid/RigidBodies.js +265 -0
  359. package/modules/rigid/Vehicles.js +97 -0
  360. package/modules/rigid/sync.js +158 -0
  361. package/modules/settings/Settings.js +297 -0
  362. package/modules/settings/apply.js +21 -0
  363. package/modules/settings/index.js +3 -0
  364. package/modules/settings/sections.js +156 -0
  365. package/modules/settings/strings.js +53 -0
  366. package/modules/settings/view.js +65 -0
  367. package/modules/sky/Sky.js +259 -0
  368. package/modules/sky/calendar.js +80 -0
  369. package/modules/sky/cascades.js +125 -0
  370. package/modules/sky/clouds.js +79 -0
  371. package/modules/sky/domeLayers.js +33 -0
  372. package/modules/sky/environment.js +141 -0
  373. package/modules/sky/fog.js +139 -0
  374. package/modules/sky/frame.js +77 -0
  375. package/modules/sky/layers.js +69 -0
  376. package/modules/sky/look.js +51 -0
  377. package/modules/sky/lookFog.js +80 -0
  378. package/modules/sky/lookShadow.js +50 -0
  379. package/modules/sky/lookSky.js +108 -0
  380. package/modules/sky/schedule.js +80 -0
  381. package/modules/sky/shader.js +96 -0
  382. package/modules/sky/shadow.js +74 -0
  383. package/modules/sky/skyModule.js +60 -0
  384. package/modules/terrain/ChunkManager.js +260 -0
  385. package/modules/terrain/chunkJob.js +19 -0
  386. package/modules/terrain/chunkLevels.js +40 -0
  387. package/modules/terrain/chunkQueries.js +42 -0
  388. package/modules/terrain/chunkWorker.js +5 -0
  389. package/modules/terrain/index.js +118 -0
  390. package/modules/terrain/lookGround.js +61 -0
  391. package/modules/terrain/mountTerrain.js +32 -0
  392. package/modules/terrain/terrainColorMap.js +41 -0
  393. package/modules/terrain/terrainDefaults.js +39 -0
  394. package/modules/terrain/terrainEdit.js +139 -0
  395. package/modules/terrain/terrainGen.js +155 -0
  396. package/modules/terrain/terrainIsland.js +131 -0
  397. package/modules/terrain/terrainMesh.js +92 -0
  398. package/modules/terrain/terrainShape.js +108 -0
  399. package/modules/terrain/terrainShapeMain.js +41 -0
  400. package/modules/terrain/terrainTexture.js +44 -0
  401. package/modules/timeline/Timeline.js +253 -0
  402. package/modules/timeline/Tween.js +114 -0
  403. package/modules/timeline/letterbox.js +24 -0
  404. package/modules/timeline/shots.js +90 -0
  405. package/modules/triggers/index.js +268 -0
  406. package/modules/vegetation/Vegetation.js +256 -0
  407. package/modules/vegetation/groundChunks.js +177 -0
  408. package/modules/vegetation/index.js +43 -0
  409. package/modules/vegetation/lookWind.js +37 -0
  410. package/modules/vegetation/modelGeometry.js +21 -0
  411. package/modules/water/Water.js +160 -0
  412. package/modules/water/look.js +80 -0
  413. package/modules/water/surface.js +88 -0
  414. package/modules/weather/Weather.js +242 -0
  415. package/modules/weather/look.js +75 -0
  416. package/modules/weather/particles.js +92 -0
  417. package/modules/weather/shaders.js +49 -0
  418. package/modules/weather/strings.js +15 -0
  419. package/modules/world/World.js +231 -0
  420. package/modules/world/cells.js +42 -0
  421. package/modules/world/explain.js +11 -0
  422. package/modules/world/index.js +71 -0
  423. package/modules/world/persist.js +107 -0
  424. package/modules/world/pos.js +20 -0
  425. package/modules/world/records.js +89 -0
  426. package/modules/world/sim.js +175 -0
  427. package/modules/world/simFar.js +82 -0
  428. package/modules/world/state.js +115 -0
  429. package/modules/world/thingSource.js +44 -0
  430. package/modules/world/views.js +182 -0
  431. package/package.json +66 -4
  432. package/presets.js +96 -0
  433. package/render/PostFX.js +240 -0
  434. package/render/detail.js +105 -0
  435. package/render/effects.js +144 -0
  436. package/render/engineUniforms.js +23 -0
  437. package/render/fuse.js +84 -0
  438. package/render/lighting.js +100 -0
  439. package/render/lights.js +18 -0
  440. package/render/lookSurface.js +161 -0
  441. package/render/materials.js +220 -0
  442. package/render/patches.js +252 -0
  443. package/render/postLook.js +86 -0
  444. package/render/surface.js +69 -0
  445. package/render/uniformDecl.js +29 -0
  446. package/types/common.d.ts +34 -0
  447. package/types/core.d.ts +1965 -0
  448. package/types/gameplay.d.ts +1822 -0
  449. package/types/generated/core/Audio.d.ts +200 -0
  450. package/types/generated/core/Batching.d.ts +47 -0
  451. package/types/generated/core/Budget.d.ts +90 -0
  452. package/types/generated/core/Commits.d.ts +31 -0
  453. package/types/generated/core/DebugOverrides.d.ts +52 -0
  454. package/types/generated/core/Events.d.ts +89 -0
  455. package/types/generated/core/I18n.d.ts +30 -0
  456. package/types/generated/core/Input.d.ts +118 -0
  457. package/types/generated/core/Jobs.d.ts +41 -0
  458. package/types/generated/core/Ops.d.ts +203 -0
  459. package/types/generated/core/Random.d.ts +49 -0
  460. package/types/generated/core/Rays.d.ts +49 -0
  461. package/types/generated/core/Saves.d.ts +162 -0
  462. package/types/generated/core/Stream.d.ts +93 -0
  463. package/types/generated/core/Threads.d.ts +82 -0
  464. package/types/generated/core/Views.d.ts +33 -0
  465. package/types/generated/core/audioVoice.d.ts +47 -0
  466. package/types/generated/core/page.d.ts +18 -0
  467. package/types/generated/core/session.d.ts +48 -0
  468. package/types/generated/modules/ambience/Ambience.d.ts +48 -0
  469. package/types/generated/modules/debug/DebugPanel.d.ts +24 -0
  470. package/types/generated/modules/flow/index.d.ts +10 -0
  471. package/types/generated/modules/grid/Grid.d.ts +151 -0
  472. package/types/generated/modules/grid/Layer.d.ts +65 -0
  473. package/types/generated/modules/grid/index.d.ts +86 -0
  474. package/types/generated/modules/hlod/index.d.ts +11 -0
  475. package/types/generated/modules/hud/index.d.ts +10 -0
  476. package/types/generated/modules/lights/index.d.ts +13 -0
  477. package/types/generated/modules/music/Music.d.ts +111 -0
  478. package/types/generated/modules/net/Net.d.ts +34 -0
  479. package/types/generated/modules/net/index.d.ts +53 -0
  480. package/types/generated/modules/net/transports.d.ts +58 -0
  481. package/types/generated/modules/particles/Particles.d.ts +69 -0
  482. package/types/generated/modules/sky/Sky.d.ts +145 -0
  483. package/types/generated/modules/sky/skyModule.d.ts +10 -0
  484. package/types/generated/modules/timeline/Timeline.d.ts +51 -0
  485. package/types/generated/modules/water/Water.d.ts +29 -0
  486. package/types/generated/modules/weather/Weather.d.ts +62 -0
  487. package/types/generated/modules/world/World.d.ts +242 -0
  488. package/types/generated/modules/world/index.d.ts +15 -0
  489. package/types/generated/render/PostFX.d.ts +125 -0
  490. package/types/generated/render/materials.d.ts +100 -0
  491. package/types/generated/render/patches.d.ts +41 -0
  492. package/types/generated/ui/Focus.d.ts +11 -0
  493. package/types/generated/ui/LoadingScreen.d.ts +2 -0
  494. package/types/generated/ui/UI.d.ts +57 -0
  495. package/types/nav.d.ts +52 -0
  496. package/types/physics.d.ts +592 -0
  497. package/types/style.d.ts +638 -0
  498. package/types/worker.d.ts +11 -0
  499. package/types/world.d.ts +772 -0
  500. package/ui/Focus.js +51 -0
  501. package/ui/LoadingScreen.js +42 -0
  502. package/ui/Parts.js +199 -0
  503. package/ui/UI.js +167 -0
  504. package/ui/defaults.js +85 -0
  505. package/ui/theme.js +124 -0
  506. package/ui/touchPart.js +49 -0
@@ -0,0 +1,233 @@
1
+ // Level module: load a hand-built scene (glTF/GLB from Blender, or THREE objects assembled in code) and make it playable:
2
+ // - ground: walkable meshes become ground height (provides engine.surface/slope/groundType; mutually exclusive with the terrain module)
3
+ // - collision: meshes named col_* (or userData.collider) become walls the character cannot cross; col_ meshes themselves are hidden
4
+ // - markers: objects named spawn, spawn_*, npc_*, trigger_*, marker_* (usually Blender empties) have their positions recorded
5
+ //
6
+ // engine.use(collision(), rigid(), followCamera(), characters(), level({ url: '/models/town.glb' }), triggers());
7
+ // engine.events.on('level:loaded', ({ markers }) => {
8
+ // const s = engine.level.spawn; // spawn point { x, y, z }
9
+ // engine.characters.createPlayer({ spawn: { x: s.x, z: s.z } });
10
+ // engine.triggers.fromMarkers({ onEnter: t => console.log('entered', t.tag) });
11
+ // });
12
+ // engine.start();
13
+ //
14
+ // Files are optional: level({ scene: a THREE.Group }) is usable immediately on install (spawn point and ground are queryable at once).
15
+ //
16
+ // Naming conventions in Blender:
17
+ // walkable name contains ground / floor / road / terrain / stair(s) / ramp, or custom property walkable = true
18
+ // (if none match, all meshes are walkable). Ground type = custom property groundType, else the material name
19
+ // walls/obstacles col_xxx (hidden collision box, only blocks movement), or custom property collider = true (a visible object that blocks)
20
+ // markers spawn, spawn_2, npc_shopkeeper, trigger_door, marker_chest -- custom properties go into userData as-is
21
+ // records custom property template = 'door' (an instance of a content template; its other custom properties fill the template's state) or id = true
22
+ // (the node itself becomes a world record, kind 'levelNode', its custom properties are record fields): id `<level file name>/<node name>`,
23
+ // e.g. town/door_front; saved as a diff like content entries (opened, removed, moved). Untagged meshes stay static scenery
24
+ //
25
+ // Options:
26
+ // url / scene pick one: glTF path (or name in the assets manifest) / THREE.Object3D built in code
27
+ // walkable mesh => true/false, decide which meshes are walkable (default: the naming conventions above)
28
+ // colliders 'named' (default, only col_ and userData.collider) | 'auto' (also treat every non-walkable mesh taller than 0.5 m as a wall) | false
29
+ // cellSize heightfield cell size in meters, default 0.5. Smaller is more precise but uses more memory
30
+ // sharpEdge neighboring-point height difference (m) above which it is a step edge, no smoothing, default 0.6
31
+ // outside ground height outside the level, default 0
32
+ // waterLevel water surface height, default -Infinity (no water)
33
+ // colliderPad extra outward padding of collision boxes, default 0
34
+ // colliderHeight minimum collision box height (a too-low col_ box still blocks this high), default 0
35
+ // hideMarkers hide a marker if it is a mesh (e.g. a placeholder cube), default true
36
+ // addToScene add the scene to engine.scene, default true
37
+ //
38
+ // After install, engine.level:
39
+ // root / object scene root node (THREE.Object3D)
40
+ // markers { name: { name, position, quaternion, scale, userData, object } } (world space; position is a Vector3, object is the original)
41
+ // spawn spawn position (spawn, else the first spawn_*, else the origin)
42
+ // marker(name) / markersWith(prefix) get one / get a group (e.g. markersWith('npc_'))
43
+ // ready whether loading is done (boolean)
44
+ // heightfield heightfield data (for debugging)
45
+ // staticTrimeshes() walkable-mesh triangles (world space), for building Rapier static colliders
46
+ // load(path/asset name or THREE object) switch level (unload current, load new, emit level:loaded when done); returns a Promise
47
+ // unload() unload (also removes everything registered via track)
48
+ // track(handle) register things that belong to the current level and need no keeping (handles with remove(): trigger zones...); auto-removed on level switch /
49
+ // unload.
50
+ // World data that must keep state (NPCs, pickups, props) is not tracked: records carry zone (= level name), a level switch only tears down models.
51
+ // triggers.fromMarkers and content (when positions use level markers) are tracked automatically
52
+ // Rays: all meshes are registered in engine.rays (builds BVH); col_ meshes and non-walkable meshes (buildings, walls) also occlude the camera (collision's
53
+ // cameraOcclusion).
54
+ // Save: the current level (path or asset name) goes into the save; on load, switch back first and wait for it before loading the rest (save key level comes
55
+ // first, load returns a Promise);
56
+ // scenes built in code (scene) cannot be saved, loading does not switch level -- to support cross-level loading, register the builder in the assets manifest
57
+ // and use level({ url: name }).
58
+ // Event: level:loaded { root, markers, spawn }
59
+ // Look: the level module draws nothing itself, the scene looks entirely like your model, so it does not read the style pack.
60
+ import * as THREE from 'three';
61
+ import { buildHeightfield } from './heightfield.js';
62
+ import { toast } from '../../ui/UI.js';
63
+ import { readParams, keysSchema } from '../../core/params.js';
64
+ import { MARKER_RE, levelNodes } from './nodes.js';
65
+ import { worldTrimeshes, colliderBoxes } from './geometry.js';
66
+
67
+ const STRINGS = {
68
+ 'zh-CN': { 'level.loadFailed': '关卡加载失败:{url}', 'level.noScene': '关卡模块需要 url 或 scene 参数' },
69
+ en: { 'level.loadFailed': 'Failed to load level: {url}', 'level.noScene': 'The level module needs a url or scene option' },
70
+ };
71
+
72
+ const WALK_RE = /ground|floor|road|terrain|stairs?|ramp/i;
73
+ const COL_RE = /^col_/i;
74
+
75
+ // a name or userData on the node itself or any ancestor counts (in glTF meshes often hang under a same-named empty)
76
+ function chainHas(o, root, test) {
77
+ for (let p = o; p; p = p.parent) { if (test(p)) return true; if (p === root) break; }
78
+ return false;
79
+ }
80
+ function chainValue(o, root, key) {
81
+ for (let p = o; p; p = p.parent) { if (p.userData?.[key] != null) return p.userData[key]; if (p === root) break; }
82
+ return undefined;
83
+ }
84
+
85
+ const LEVEL_PARAMS = keysSchema(['url', 'scene', 'walkable', 'colliders', 'cellSize', 'outside', 'waterLevel', 'colliderPad', 'colliderHeight', 'sharpEdge', 'hideMarkers', 'addToScene']);
86
+
87
+ export function level(opts = {}) {
88
+ readParams('level', LEVEL_PARAMS, opts);
89
+ const { url = null, scene = null, walkable = null, colliders = 'named', cellSize = 0.5, outside = 0, waterLevel = -Infinity,
90
+ colliderPad = 0, colliderHeight = 0, sharpEdge = 0.6, hideMarkers = true, addToScene = true } = opts;
91
+ let e = null, hf = null, done = false, version = 0, trimeshCache = null, pendingColliders = null;
92
+ let current = typeof url === 'string' && !scene ? url : null; // current level path/asset name (for saving)
93
+ const walkMeshes = [], removers = [];
94
+ let nodeSet = null; // level nodes that become world records (nodes.js), created at install
95
+
96
+ const api = {
97
+ root: null, markers: {}, spawn: new THREE.Vector3(), heightfield: null,
98
+ get object() { return api.root; }, // same as root (consistent with player.object, ent.object)
99
+ get ready() { return done; },
100
+ /** Register things belonging to the current level ({ remove() } handles); auto-removed on level switch / unload; returns the same handle */
101
+ track(h) { if (h) removers.push(h); return h; },
102
+ marker: name => api.markers[name] || null,
103
+ markersWith: prefix => Object.values(api.markers).filter(m => m.name.startsWith(prefix)),
104
+ /** @internal Triangles of walkable meshes (world space), [{ positions: Float32Array, indices: Uint32Array }], cached */
105
+ staticTrimeshes() {
106
+ if (trimeshCache) return trimeshCache;
107
+ trimeshCache = worldTrimeshes(walkMeshes);
108
+ return trimeshCache;
109
+ },
110
+ /** Unload the level: remove from scene, delete colliders, ground reverts to the outside height */
111
+ unload() {
112
+ for (const h of removers.splice(0)) h.remove();
113
+ if (api.root && addToScene) e.remove(api.root); // full removal (geometries and materials shared by assets are not disposed)
114
+ walkMeshes.length = 0; hf = null; trimeshCache = null; api.markers = {}; api.root = null; current = null; version++;
115
+ },
116
+ /** Switch level: unload the current one, load a new one (glTF path/asset name, or THREE object), emit level:loaded when done */
117
+ async load(urlOrScene) {
118
+ api.unload(); done = false;
119
+ e.commits.invalidate(); // background results requested for the old level must not land on the new one
120
+ // world-data zone = level name: other levels' NPCs etc. only lose models, data stays and is rebuilt on return (code-built scenes have no name, record
121
+ // null, no zoning)
122
+ if (e.world) e.world.zone = typeof urlOrScene === 'string' ? urlOrScene : null;
123
+ if (typeof urlOrScene === 'string') {
124
+ current = urlOrScene;
125
+ try { process(await e.assets.model(urlOrScene)); }
126
+ catch (err) { console.error(err); toast(e, e.t('level.loadFailed', { url: urlOrScene }), { kind: 'error' }); }
127
+ } else process(urlOrScene);
128
+ loaded();
129
+ },
130
+ };
131
+
132
+ function loaded() {
133
+ addColliders(); // if the collision module is installed after level, add colliders here
134
+ // nodes tagged template / id become world records (loading is setup, not a gameplay action) before anyone (hlod...) sees level:loaded
135
+ e.ops.allow(nodeSet.place);
136
+ done = true;
137
+ e.assets.trim(); // old level's models have no copies in use: return GPU memory
138
+ e.events.emit('level:loaded', { root: api.root, markers: api.markers, spawn: api.spawn });
139
+ }
140
+
141
+ /** Process a scene: classify meshes, build the heightfield, record markers. Colliders wait for the collision module (may not be installed at install time) */
142
+ function process(root) {
143
+ api.root = root;
144
+ root.userData.budgetTag ??= 'level';
145
+ if (addToScene && !root.parent) e.add(root, { owner: 'level' });
146
+ root.updateMatrixWorld(true);
147
+ nodeSet.take(root); // record nodes leave the level root first: no ground, collision or ray registration for them, and hlod never bakes them
148
+ const meshes = [], cols = [], markerObjs = [];
149
+ root.traverse(o => {
150
+ if (MARKER_RE.test(o.name)) { markerObjs.push(o); return; }
151
+ if (!o.isMesh) return;
152
+ // placeholder models under a marker
153
+ if (o.parent && chainHas(o.parent, root, p => MARKER_RE.test(p.name))) { if (hideMarkers) o.visible = false; return; }
154
+ if (chainHas(o, root, p => COL_RE.test(p.name))) { cols.push(o); o.visible = false; return; }
155
+ meshes.push(o);
156
+ });
157
+ // walkable meshes
158
+ const isWalk = walkable || (m => chainHas(m, root, p => p.userData?.walkable === true || WALK_RE.test(p.name)));
159
+ let walk = meshes.filter(m => chainValue(m, root, 'walkable') !== false && isWalk(m));
160
+ if (!walkable && !walk.length) walk = meshes.filter(m => chainValue(m, root, 'walkable') !== false);
161
+ walkMeshes.push(...walk);
162
+ const walkSet = new Set(walk);
163
+ for (const m of meshes) {
164
+ if (walkSet.has(m)) continue;
165
+ if (chainValue(m, root, 'collider')) cols.push(m);
166
+ else if (colliders === 'auto') { const b = new THREE.Box3().setFromObject(m); if (b.max.y - b.min.y > 0.5) cols.push(m); }
167
+ }
168
+ // heightfield
169
+ const typeOf = (m, mi) => {
170
+ const t = chainValue(m, root, 'groundType'); if (t != null) return String(t);
171
+ const mat = Array.isArray(m.material) ? m.material[mi] : m.material;
172
+ return mat?.name || 'default';
173
+ };
174
+ const t0 = performance.now(); // measure
175
+ hf = api.heightfield = buildHeightfield(walk, { cellSize, outside, typeOf, sharpEdge, stepUp: e.movement.stepHeight, layerGap: e.movement.height });
176
+ api.buildMs = performance.now() - t0; // measure: heightfield build time (shown in the debug panel)
177
+ // markers
178
+ const markers = api.markers = {};
179
+ for (const o of markerObjs) {
180
+ const position = new THREE.Vector3(), quaternion = new THREE.Quaternion(), scale = new THREE.Vector3();
181
+ o.matrixWorld.decompose(position, quaternion, scale);
182
+ markers[o.name] = { name: o.name, position, quaternion, scale, userData: { ...o.userData }, object: o };
183
+ if (hideMarkers && o.isMesh) o.visible = false;
184
+ }
185
+ const sp = markers.spawn || Object.values(markers).find(m => /^spawn_/i.test(m.name));
186
+ api.spawn = sp ? sp.position.clone() : new THREE.Vector3(0, hf.height(0, 0), 0);
187
+ pendingColliders = colliders === false ? cols.filter(m => COL_RE.test(m.name) || chainValue(m, root, 'collider')) : cols;
188
+ // rays: all meshes; collision meshes and non-walkable meshes also occlude the camera
189
+ removers.push(e.rays.addStatic(root), e.rays.addStatic([...cols, ...meshes.filter(m => !walkSet.has(m))], { occluder: true }));
190
+ trimeshCache = null; version++;
191
+ addColliders();
192
+ }
193
+
194
+ /** Turn collision meshes into rotated boxes in the collision module (best-fit box by the mesh's world orientation) */
195
+ function addColliders() {
196
+ const ph = e.collision;
197
+ if (!ph || !pendingColliders) return;
198
+ for (const b of colliderBoxes(pendingColliders, { colliderHeight, colliderPad })) removers.push(ph.addBox(b.at, b.opts));
199
+ pendingColliders = null;
200
+ }
201
+
202
+ return {
203
+ name: 'level', params: LEVEL_PARAMS, options: opts, label: 'Level', stage: 'world', after: ['terrain'], optional: ['world', 'content'],
204
+ install(engine) {
205
+ e = engine;
206
+ nodeSet = levelNodes(e, () => api.root, () => current);
207
+ e.i18n.add(STRINGS);
208
+ // ground API: before the heightfield is built, return the outside height
209
+ e.setGround({
210
+ height: (x, z, refY) => hf ? hf.height(x, z, refY) : outside,
211
+ slope: (x, z) => hf ? hf.slope(x, z) : 0,
212
+ type: (x, z) => hf ? hf.type(x, z) : 'default',
213
+ waterLevel,
214
+ staticTrimeshes: () => api.staticTrimeshes(),
215
+ staticVersion: () => version, // +1 on level change; the physics module rebuilds static colliders on it
216
+ });
217
+ if (scene) process(scene);
218
+ // on load, switch back to the saved level (code-built scenes have no name, record null, no switch)
219
+ // load returns a Promise: the save system waits for the new level (old level's trigger zones are already removed by unload) before reading player
220
+ // position etc.
221
+ e.saves.register('level', { first: true, save: () => current, load: d => { if (typeof d === 'string' && d !== current) return api.load(d); } });
222
+ return api;
223
+ },
224
+ critical: true, // the level file is the game's world: a failed load stops start() with the reason
225
+ async init(engine) {
226
+ if (scene) return loaded();
227
+ if (url) return api.load(url);
228
+ console.warn(engine.t('level.noScene'));
229
+ loaded();
230
+ },
231
+ isReady() { return done; },
232
+ };
233
+ }
@@ -0,0 +1,84 @@
1
+ // Level nodes that become world records: nodes tagged with the custom property template or id (Blender -> glTF extras -> userData) leave the level root
2
+ // and are placed as authored records `<level>/<node>` once the level is processed. Created per level module by levelNodes(e, getRoot, getCurrent).
3
+ import * as THREE from 'three';
4
+ import { warnOnce } from '../../core/validate.js';
5
+
6
+ const STRINGS_DEV = {
7
+ noWorld: '[level] nodes with the custom property template or id become world records: install world() (the openWorld() preset has it); until then they stay in the level as plain scenery (ground, collision, rays like any node)',
8
+ noContent: 'level node {id} has the custom property template: install content() and define the template in content/templates.js',
9
+ clash: 'level node id "{id}" is already used by other data (kind {kind}): rename the node in Blender',
10
+ notLoaded: 'level node {id}: its level is not loaded (a record of another level is built only on that level)',
11
+ };
12
+
13
+ export const MARKER_RE = /^(spawn|spawn_.*|npc_.*|trigger_.*|marker_.*)$/i;
14
+
15
+ /** @param {any} e engine @param {() => any} getRoot current level root @param {() => string | null} getCurrent current level path / name */
16
+ export function levelNodes(e, getRoot, getCurrent) {
17
+ const taken = [], nodes = new Map(); // record nodes waiting to be placed; record id -> node object (levelNode records)
18
+ let presented = null;
19
+ /**
20
+ * Nodes tagged with the custom property template or id (Blender custom property -> glTF extras -> userData): taken out of the level root, world transform
21
+ * kept
22
+ */
23
+ function take(root) {
24
+ taken.length = 0;
25
+ const walk = o => {
26
+ for (const c of [...o.children]) {
27
+ if ((c.userData?.template == null && c.userData?.id == null) || MARKER_RE.test(c.name)) { walk(c); continue; }
28
+ // without world() there is nowhere to put the record: leave the node as part of the level (a game that never uses records still sees its
29
+ // whole scene) and say how to turn it into a record, instead of removing it and dropping it later
30
+ if (!e.world) { warnOnce(STRINGS_DEV.noWorld); continue; }
31
+ const p = new THREE.Vector3(), q = new THREE.Quaternion(), s = new THREE.Vector3();
32
+ c.matrixWorld.decompose(p, q, s);
33
+ c.removeFromParent(); c.position.copy(p); c.quaternion.copy(q); c.scale.copy(s);
34
+ c.userData.hlod = false; // its model comes and goes with the record: never part of a merged far proxy
35
+ taken.push(c);
36
+ }
37
+ };
38
+ walk(root);
39
+ }
40
+ /** The name in node ids `<level>/<node>`: the level file name without folders and extension; a code-built scene uses its root name */
41
+ const levelName = () => {
42
+ const current = getCurrent();
43
+ if (!current) return getRoot()?.name || 'level';
44
+ const f = String(current), base = f.slice(Math.max(f.lastIndexOf('/'), f.lastIndexOf('\\')) + 1), dot = base.lastIndexOf('.');
45
+ return dot > 0 ? base.slice(0, dot) : base;
46
+ };
47
+ const OWN = ['template', 'id', 'name', 'hlod']; // userData keys that are not record fields (three's glTF loader keeps the node name in userData.name)
48
+ /** Taken nodes -> authored world records, id `<level>/<node>`: a template instance (custom property template) or the node itself (custom property id) */
49
+ function place() {
50
+ if (!taken.length) return;
51
+ if (!e.world) return; // takeNodes took nothing then (the nodes stayed in the level)
52
+ const level = levelName(), zone = e.world.zone;
53
+ for (const o of taken.splice(0)) {
54
+ const id = `${level}/${o.name}`, ud = o.userData, node = o.name, { x, y, z } = o.position;
55
+ const fields = Object.fromEntries(Object.entries(ud).filter(([k, v]) => !OWN.includes(k) && (v == null || typeof v !== 'object' || Array.isArray(v) || v.constructor === Object)));
56
+ if (ud.template != null) {
57
+ if (!e.content) throw new Error(STRINGS_DEV.noContent.replace('{id}', id));
58
+ const yaw = new THREE.Euler().setFromQuaternion(o.quaternion, 'YXZ').y, state = Object.keys(e.content.template(ud.template).state ?? {});
59
+ const own = Object.fromEntries(Object.entries(fields).filter(([k]) => state.includes(k)));
60
+ e.content.placeNode({ template: ud.template, id, x, z, floor: y, ...(yaw && { rot: yaw }), ...(o.scale.x !== 1 && { scale: o.scale.x }), ...own }, zone, { level, node });
61
+ } else {
62
+ presentNodes();
63
+ nodes.set(id, o);
64
+ const rec = e.world.add({ ...fields, id, kind: 'levelNode', position: { x, y, z }, ...(zone != null && { zone }), level, node }, { initial: true });
65
+ if (rec && rec.kind !== 'levelNode') throw new Error(STRINGS_DEV.clash.replace('{id}', id).replace('{kind}', rec.kind));
66
+ }
67
+ e.world.setOrigin(id, { level, node });
68
+ }
69
+ }
70
+ /** How a level node record looks: the node itself (detached while far or on another level, rebuilt from the same object) */
71
+ function presentNodes() {
72
+ if (presented) return;
73
+ presented = e.world.present('levelNode', {
74
+ build(rec) {
75
+ const o = nodes.get(rec.id);
76
+ if (!o) throw new Error(STRINGS_DEV.notLoaded.replace('{id}', rec.id));
77
+ o.userData.unstatic = e.rays.addStatic(o);
78
+ return o;
79
+ },
80
+ dispose(rec, o) { o.userData.unstatic?.remove(); e.detach(o); },
81
+ });
82
+ }
83
+ return { take, place };
84
+ }
@@ -0,0 +1,227 @@
1
+ // Light pool: many light sources (torches, street lamps, campfires, muzzle flashes, neon signs) lit by a fixed handful of real three.js lights.
2
+ // engine.use(lightPool({ point: 8 })); // 8 real PointLights, created now, never added / removed / hidden
3
+ // const torch = engine.lightPool.add(torchMesh, { color: 0xffa040, intensity: 4, distance: 8 });
4
+ // torch.set({ intensity: 0 }); torch.remove();
5
+ // Why: three.js builds one shader program per material for each light setup (how many point / spot / directional... lights the scene has).
6
+ // Adding, removing or hiding a light mid-play changes the setup and compiles new programs, so one frame freezes for hundreds of milliseconds
7
+ // (seen in a first-person dungeon: torches switched lights by distance, programs 27 -> 30, a 450 ms frame). The pool's lights exist from install,
8
+ // so engine.start() compiles every material for them behind the loading screen; afterwards they only move to the sources that matter most
9
+ // and fade with intensity (0 = dark but still counted: no recompile). core/lightWatch.js warns in dev when a game changes its lights anyway.
10
+ // Choosing: every `every` seconds each source scores priority x intensity / (1 + (d / range)^2), d = distance to the focus (default the camera);
11
+ // a source that already holds a light gets a small bonus so two equal torches do not swap back and forth. A slot fades its old source out
12
+ // before taking the next one, so lights never pop. Sources without a light can drive a stand-in (`glow`: a halo sprite or emissive material).
13
+ // Shadows: none by default; lightPool({ shadows: k }) makes k of the point lights cast, used by sources added with castShadow: true.
14
+ // An idle shadow light (no source, or faded to 0) stops re-rendering its cube shadow map (shadow.autoUpdate = false): six shadow passes a frame for a dark light.
15
+ // When every point light casts (shadows >= point) there are no plain ones, so sources without castShadow also take the shadow lights (they cast then) instead of never lighting.
16
+ import * as THREE from 'three';
17
+ import { checkOptions, warnOnce } from '../../core/validate.js';
18
+ import { readParams, keysSchema } from '../../core/params.js';
19
+ import { vec3 } from '../../core/math.js';
20
+ /** @import { ModuleDef } from '../../types/core' */
21
+ /** @import { LightPool, LightPoolOptions } from '../../types/world' */
22
+
23
+ const OPT_KEYS = ['point', 'spot', 'shadows', 'every', 'fade', 'focus'];
24
+ const ADD_KEYS = ['name', 'type', 'color', 'intensity', 'distance', 'decay', 'priority', 'castShadow', 'angle', 'penumbra', 'target', 'flicker', 'glow'];
25
+ const SET_KEYS = ['position', ...ADD_KEYS.filter(k => k !== 'type' && k !== 'castShadow')]; // the kind of light a source needs is fixed when it is added
26
+ const BONUS = 1.25; // score bonus for a source that already holds a light (hysteresis)
27
+ const STRINGS = {
28
+ late: 'lightPool() was installed after engine.start(): its lights were added to a running scene, so every material compiles once more (one long frame). Install it with the other modules, before engine.start() [light-recompile]',
29
+ type: "lightPool.add(): type must be 'point' or 'spot', got ",
30
+ allShadow: 'lightPool({ point: {n}, shadows: {k} }): every point light casts shadows, so sources added without castShadow use shadow lights too (and cast). For plain lights next to the shadow ones give point more than shadows, e.g. lightPool({ point: {m}, shadows: {k} })',
31
+ noSlot: "lightPool.add(): a '{type}' source but lightPool({ {type}: 0 }) has no {type} lights; give lightPool() a count, e.g. lightPool({ {type}: 2 })",
32
+ };
33
+
34
+ /** The material a glow stand-in drives, and which of its numbers: emissiveIntensity when it has one (emissive mesh), else opacity (halo sprite) */
35
+ function glowOf(g) {
36
+ if (!g) return null;
37
+ let m = g.isMaterial ? g : null;
38
+ if (!m) g.traverse?.(o => { if (!m && o.material && !Array.isArray(o.material)) m = o.material; });
39
+ if (!m) return null;
40
+ const key = 'emissiveIntensity' in m ? 'emissiveIntensity' : 'opacity';
41
+ return { m, key, base: m[key], k: -1 };
42
+ }
43
+
44
+ const LIGHT_POOL_PARAMS = keysSchema(OPT_KEYS);
45
+
46
+ /**
47
+ * Light pool (many light sources, a fixed number of real lights) -> engine.lightPool
48
+ * @param {LightPoolOptions} [opts]
49
+ * @returns {ModuleDef<LightPool>}
50
+ * @example
51
+ * engine.use(lightPool({ point: 8 })); // before engine.start(), so the startup compile covers these lights
52
+ * for (const t of torchMeshes) engine.lightPool.add(t, { color: 0xffa040, intensity: 4, distance: 8, flicker: (time, i) => 0.85 + 0.15 * Math.sin(time * 13 + i) });
53
+ */
54
+ export function lightPool(opts = {}) {
55
+ readParams('lightPool', LIGHT_POOL_PARAMS, opts);
56
+ const { point = 8, spot = 0, shadows = 0, every = 0.1, fade = 0.3 } = opts;
57
+ let e = null, timer = Infinity, time = 0, seq = 0;
58
+ const sources = [], groups = [], tmp = new THREE.Vector3(), at = new THREE.Vector3();
59
+
60
+ const worldPos = (src, out) => src.follow ? out.setFromMatrixPosition(src.follow.matrixWorld) : out.copy(src.pos);
61
+ const setGlow = (src, k) => {
62
+ const g = src.glow;
63
+ if (!g || g.k === k) return;
64
+ g.k = k; g.m[g.key] = g.base * k;
65
+ };
66
+ function score(src, focus) {
67
+ if (!(src.intensity > 0) || !(src.priority > 0)) return 0;
68
+ const r = src.distance > 0 ? src.distance : 10;
69
+ const s = src.priority * src.intensity / (1 + worldPos(src, tmp).distanceToSquared(focus) / (r * r));
70
+ return src.slot && src.slot.w > 0 ? s * BONUS : s;
71
+ }
72
+ // a slot that has faded its source out lets it go: the source is free for any group again and its stand-in shows fully
73
+ function release(slot) {
74
+ const src = slot.src;
75
+ slot.src = null; slot.want = 0; slot.light.intensity = 0;
76
+ if (slot.group.shadow) slot.light.shadow.autoUpdate = false; // dark: its shadow map is not rendered again until a source takes it
77
+ if (src) { src.slot = null; if (!src.removed) setGlow(src, 1); }
78
+ }
79
+
80
+ /** Pick the best sources for each group (shadow points first, then plain points, then spots) and hand free slots to the winners */
81
+ function assign() {
82
+ const f = api.focus ?? e.camera;
83
+ if (f.isObject3D) f.getWorldPosition(at); else vec3(f, at); // fresh (not last frame's matrix): the camera may have just moved
84
+ for (const s of sources) s.score = score(s, at);
85
+ const taken = new Set();
86
+ for (const g of groups) {
87
+ // a source fading out of another group's slot waits until it is released, so it never holds two lights
88
+ const pick = sources.filter(s => s.score > 0 && !taken.has(s) && g.fits(s) && (!s.slot || s.slot.group === g))
89
+ .sort((a, b) => b.score - a.score).slice(0, g.slots.length);
90
+ const chosen = new Set(pick);
91
+ for (const s of pick) taken.add(s);
92
+ for (const slot of g.slots) slot.want = slot.src && chosen.has(slot.src) ? 1 : 0;
93
+ const waiting = pick.filter(s => !s.slot);
94
+ for (const slot of g.slots) {
95
+ if (!waiting.length) break;
96
+ if (slot.src && (slot.want || slot.w > 0)) continue; // kept by its source, or still fading the old one out: next time
97
+ if (slot.src) release(slot);
98
+ const s = waiting.shift();
99
+ slot.src = s; slot.want = 1; s.slot = slot;
100
+ if (g.shadow) { slot.light.shadow.autoUpdate = true; slot.light.shadow.needsUpdate = true; } // lit again: render its shadow map every frame
101
+ }
102
+ }
103
+ }
104
+
105
+ /** Per frame, only for the N slots: fade, follow, flicker, drive the stand-in */
106
+ function update(dt) {
107
+ const step = fade > 0 ? dt / fade : 1;
108
+ for (const g of groups) for (const slot of g.slots) {
109
+ const src = slot.src;
110
+ if (!src) continue;
111
+ slot.w = slot.want ? Math.min(1, slot.w + step) : Math.max(0, slot.w - step);
112
+ if (slot.w === 0 && !slot.want) { release(slot); continue; }
113
+ const L = slot.light;
114
+ if (src.follow) src.follow.getWorldPosition(L.position); else L.position.copy(src.pos); // fresh for the few lit ones: a muzzle flash must not lag a frame
115
+ L.color.copy(src.color); L.distance = src.distance; L.decay = src.decay;
116
+ const fl = src.flicker ? src.flicker(time, src.index) : 1;
117
+ L.intensity = src.intensity * slot.w * fl;
118
+ if (L.isSpotLight) {
119
+ L.angle = src.angle; L.penumbra = src.penumbra;
120
+ if (src.target?.isObject3D) L.target.position.setFromMatrixPosition(src.target.matrixWorld);
121
+ else if (src.target) vec3(src.target, L.target.position);
122
+ else L.target.position.copy(L.position).y -= 1; // no target: straight down (a ceiling lamp)
123
+ L.target.updateMatrixWorld();
124
+ }
125
+ if (!src.removed) setGlow(src, slot.w === 1 ? 0 : 1 - slot.w); // a removed source's stand-in was put back by remove()
126
+ }
127
+ }
128
+
129
+ function apply(src, o) {
130
+ if ('color' in o) src.color.set(o.color);
131
+ for (const k of ['intensity', 'distance', 'decay', 'priority', 'angle', 'penumbra', 'flicker', 'target', 'name']) if (k in o) src[k] = o[k];
132
+ if ('glow' in o) { if (src.glow) setGlow(src, 1); src.glow = glowOf(o.glow); setGlow(src, src.slot ? 1 - src.slot.w : 1); }
133
+ timer = Infinity; // a changed source is reconsidered on the next frame, not after `every`
134
+ }
135
+
136
+ const api = {
137
+ /** The real lights, created once at install: plain three.js lights in the scene (read them; the pool sets their position, color and intensity) */
138
+ lights: /** @type {any[]} */ ([]),
139
+ /** Distance is measured from this Object3D / position; null (default) = the camera */
140
+ focus: opts.focus ?? null,
141
+ /** Register a light source at a position (Object3D: it follows that object) and return its handle { set(patch), remove(), light, weight } */
142
+ add(position, o = {}) {
143
+ checkOptions('lightPool.add()', o, ADD_KEYS);
144
+ const type = o.type ?? 'point';
145
+ if (type !== 'point' && type !== 'spot') throw new TypeError(STRINGS.type + JSON.stringify(type));
146
+ if (!groups.some(g => g.type === type)) throw new TypeError(STRINGS.noSlot.replaceAll('{type}', type));
147
+ const src = { index: seq++, type, castShadow: !!o.castShadow, follow: position?.isObject3D ? position : null, pos: position?.isObject3D ? null : vec3(position),
148
+ color: new THREE.Color(0xffffff), intensity: 1, distance: 10, decay: 2, priority: 1, angle: Math.PI / 4, penumbra: 0.3, target: null, flicker: null, name: null,
149
+ glow: null, slot: null, score: 0, removed: false };
150
+ apply(src, o);
151
+ sources.push(src);
152
+ const h = {
153
+ /** The real light lighting this source now (null while it has none) */
154
+ get light() { return src.slot?.light ?? null; },
155
+ /** How much of its light it has, 0-1 (fades when lights move between sources) */
156
+ get weight() { return src.slot?.w ?? 0; },
157
+ /** Change the source: { position, color, intensity, distance, decay, priority, angle, penumbra, target, flicker, glow, name } */
158
+ set(patch) {
159
+ checkOptions('lightPool.add().set()', patch, SET_KEYS);
160
+ if ('position' in patch) { const p = patch.position; src.follow = p?.isObject3D ? p : null; src.pos = p?.isObject3D ? null : vec3(p); }
161
+ apply(src, patch);
162
+ return h;
163
+ },
164
+ /** Unregister: its light fades out and goes to another source; the stand-in is put back as it was (safe to call twice) */
165
+ remove() {
166
+ if (src.removed) return;
167
+ src.removed = true;
168
+ const i = sources.indexOf(src); if (i >= 0) sources.splice(i, 1);
169
+ if (src.slot) src.slot.want = 0;
170
+ if (src.glow) { src.glow.m[src.glow.key] = src.glow.base; src.glow.k = -1; }
171
+ timer = Infinity;
172
+ },
173
+ };
174
+ return h;
175
+ },
176
+ /** How the pool is used now: lights per kind, how many are lighting something, and which source each holds */
177
+ usage() {
178
+ const out = { sources: sources.length, lit: 0, slots: [] };
179
+ for (const g of groups) for (const s of g.slots) {
180
+ if (s.src && s.w > 0) out.lit++;
181
+ out.slots.push({ type: g.type, shadow: g.shadow, source: s.src ? (s.src.name ?? s.src.index) : null, weight: Math.round(s.w * 100) / 100 });
182
+ }
183
+ return out;
184
+ },
185
+ };
186
+
187
+ function makeGroup(type, shadow, n) {
188
+ if (n <= 0) return;
189
+ const allShadow = shadow && n >= point; // no plain point lights: the shadow ones also take non-casting sources, so those never stay dark
190
+ const g = { type, shadow, slots: [], fits: type === 'spot' ? s => s.type === 'spot' : shadow && !allShadow ? s => s.type === 'point' && s.castShadow : s => s.type === 'point' };
191
+ for (let i = 0; i < n; i++) {
192
+ const L = type === 'spot' ? new THREE.SpotLight(0xffffff, 0) : new THREE.PointLight(0xffffff, 0);
193
+ L.name = `lightPool_${type}${shadow ? '_shadow' : ''}_${i}`;
194
+ L.castShadow = shadow; // fixed at creation: a shadow count that changes recompiles too
195
+ if (shadow) L.shadow.autoUpdate = false; // no source yet: no shadow passes
196
+ e.scene.add(L);
197
+ if (L.isSpotLight) e.scene.add(L.target);
198
+ api.lights.push(L);
199
+ g.slots.push({ light: L, group: g, src: null, w: 0, want: 0 });
200
+ }
201
+ groups.push(g);
202
+ }
203
+
204
+ return {
205
+ name: 'lightPool', params: LIGHT_POOL_PARAMS, options: opts, label: 'Light pool', stage: 'late', presentation: true,
206
+ install(engine) {
207
+ e = engine;
208
+ const k = Math.max(0, Math.min(shadows, point));
209
+ if (k > 0 && k >= point) warnOnce(STRINGS.allShadow.replace('{n}', String(point)).replace('{m}', String(k + 2)).replaceAll('{k}', String(k)));
210
+ makeGroup('point', true, k);
211
+ makeGroup('point', false, point - k);
212
+ makeGroup('spot', false, spot);
213
+ if (e.ready) warnOnce(STRINGS.late);
214
+ return api;
215
+ },
216
+ frame(dt) {
217
+ time += dt; // presentation seconds for flicker: keeps running while gameplay is frozen, like the picture
218
+ if ((timer += dt) >= every) { timer = 0; assign(); }
219
+ update(dt);
220
+ },
221
+ dispose() { for (const L of api.lights) { L.removeFromParent(); L.target?.removeFromParent(); L.dispose(); } },
222
+ describe() {
223
+ const u = api.usage();
224
+ return { lights: api.lights.length, lit: u.lit, sources: u.sources, shadows: Math.max(0, Math.min(shadows, point)) };
225
+ },
226
+ };
227
+ }