threedog 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (506) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/LICENSE +21 -0
  3. package/README.md +39 -2
  4. package/core/Animator.js +268 -0
  5. package/core/Assets.js +256 -0
  6. package/core/Audio.js +267 -0
  7. package/core/Baked.js +72 -0
  8. package/core/Batching.js +247 -0
  9. package/core/Budget.js +221 -0
  10. package/core/Clock.js +94 -0
  11. package/core/Commits.js +77 -0
  12. package/core/DebugOverrides.js +143 -0
  13. package/core/Describe.js +145 -0
  14. package/core/Engine.js +184 -0
  15. package/core/Events.js +153 -0
  16. package/core/I18n.js +94 -0
  17. package/core/Input.js +245 -0
  18. package/core/Inspect.js +77 -0
  19. package/core/InspectScene.js +191 -0
  20. package/core/Jobs.js +146 -0
  21. package/core/Loading.js +149 -0
  22. package/core/MaterialInfo.js +32 -0
  23. package/core/Ops.js +256 -0
  24. package/core/Random.js +52 -0
  25. package/core/Rays.js +160 -0
  26. package/core/SaveStore.js +85 -0
  27. package/core/Saves.js +254 -0
  28. package/core/Stream.js +279 -0
  29. package/core/Threads.js +158 -0
  30. package/core/UrlState.js +94 -0
  31. package/core/Vars.js +35 -0
  32. package/core/Views.js +49 -0
  33. package/core/actor.js +23 -0
  34. package/core/assetEntry.js +89 -0
  35. package/core/assetLoad.js +190 -0
  36. package/core/assetManifest.js +35 -0
  37. package/core/assetReport.js +83 -0
  38. package/core/audioRules.js +121 -0
  39. package/core/audioVoice.js +225 -0
  40. package/core/batchGroups.js +116 -0
  41. package/core/canvasBox.js +63 -0
  42. package/core/catalog.js +169 -0
  43. package/core/checks.js +67 -0
  44. package/core/claims.js +51 -0
  45. package/core/dayTime.js +15 -0
  46. package/core/debugView.js +76 -0
  47. package/core/describeRender.js +45 -0
  48. package/core/describeText.js +143 -0
  49. package/core/easing.js +34 -0
  50. package/core/errorCodes.js +205 -0
  51. package/core/errorHints.js +208 -0
  52. package/core/errors.js +40 -0
  53. package/core/events.generated.js +84 -0
  54. package/core/ground.js +102 -0
  55. package/core/holds.js +106 -0
  56. package/core/inputContext.js +69 -0
  57. package/core/inputDefaults.js +22 -0
  58. package/core/inputPad.js +35 -0
  59. package/core/inputPointer.js +48 -0
  60. package/core/inputTouch.js +48 -0
  61. package/core/lifecycle.js +69 -0
  62. package/core/lightWatch.js +56 -0
  63. package/core/look/coreParts.js +112 -0
  64. package/core/look/layers.js +136 -0
  65. package/core/look/part.js +173 -0
  66. package/core/look/report.js +79 -0
  67. package/core/look/write.js +86 -0
  68. package/core/loop.js +200 -0
  69. package/core/math.js +33 -0
  70. package/core/modules.js +196 -0
  71. package/core/movement.js +19 -0
  72. package/core/mulberry32.js +14 -0
  73. package/core/opsAtomic.js +31 -0
  74. package/core/opsCheck.js +97 -0
  75. package/core/opsFail.js +20 -0
  76. package/core/opsGuard.js +26 -0
  77. package/core/opsHistory.js +27 -0
  78. package/core/opsRun.js +77 -0
  79. package/core/page.js +78 -0
  80. package/core/params.js +132 -0
  81. package/core/pureWorker.js +5 -0
  82. package/core/renamed.js +21 -0
  83. package/core/saveApply.js +128 -0
  84. package/core/saveFiles.js +139 -0
  85. package/core/saveIds.js +53 -0
  86. package/core/saveVersions.js +97 -0
  87. package/core/scatter.js +92 -0
  88. package/core/sceneMethods.js +100 -0
  89. package/core/screenToGround.js +39 -0
  90. package/core/services.js +73 -0
  91. package/core/session.js +171 -0
  92. package/core/shadowTypes.js +15 -0
  93. package/core/skip.js +104 -0
  94. package/core/startup.js +135 -0
  95. package/core/streamCells.js +24 -0
  96. package/core/streamSources.js +73 -0
  97. package/core/styleParts.js +96 -0
  98. package/core/targeting.js +64 -0
  99. package/core/thingExplain.js +68 -0
  100. package/core/thingOps.js +168 -0
  101. package/core/things.js +212 -0
  102. package/core/threadPure.js +120 -0
  103. package/core/threadServe.js +25 -0
  104. package/core/tier.js +11 -0
  105. package/core/util.js +11 -0
  106. package/core/validate.js +204 -0
  107. package/docs/AI.md +123 -0
  108. package/docs/API.md +83 -0
  109. package/docs/CODEMAP.md +347 -0
  110. package/docs/COMMANDS.md +108 -0
  111. package/docs/CONVENTIONS.md +145 -0
  112. package/docs/PERF.md +217 -0
  113. package/docs/THREE.md +86 -0
  114. package/docs/api/ambience.md +15 -0
  115. package/docs/api/assets.md +62 -0
  116. package/docs/api/audio.md +53 -0
  117. package/docs/api/budget.md +40 -0
  118. package/docs/api/cameraRig.md +120 -0
  119. package/docs/api/characters.md +144 -0
  120. package/docs/api/clock.md +7 -0
  121. package/docs/api/collision.md +39 -0
  122. package/docs/api/content.md +64 -0
  123. package/docs/api/dialogue.md +39 -0
  124. package/docs/api/engine.md +199 -0
  125. package/docs/api/entities.md +61 -0
  126. package/docs/api/events.md +95 -0
  127. package/docs/api/flow.md +27 -0
  128. package/docs/api/grids.md +11 -0
  129. package/docs/api/ground.md +16 -0
  130. package/docs/api/hlod.md +34 -0
  131. package/docs/api/hud.md +31 -0
  132. package/docs/api/i18n.md +10 -0
  133. package/docs/api/input.md +24 -0
  134. package/docs/api/interactions.md +31 -0
  135. package/docs/api/inventory.md +66 -0
  136. package/docs/api/jobs.md +10 -0
  137. package/docs/api/level.md +41 -0
  138. package/docs/api/lightPool.md +56 -0
  139. package/docs/api/music.md +34 -0
  140. package/docs/api/nav.md +26 -0
  141. package/docs/api/net.md +14 -0
  142. package/docs/api/openWorld.md +24 -0
  143. package/docs/api/particles.md +41 -0
  144. package/docs/api/photo.md +15 -0
  145. package/docs/api/post.md +10 -0
  146. package/docs/api/quests.md +36 -0
  147. package/docs/api/rays.md +26 -0
  148. package/docs/api/rigid.md +84 -0
  149. package/docs/api/saves.md +32 -0
  150. package/docs/api/settings.md +36 -0
  151. package/docs/api/sky.md +58 -0
  152. package/docs/api/stream.md +31 -0
  153. package/docs/api/style.md +134 -0
  154. package/docs/api/terrain.md +34 -0
  155. package/docs/api/timeline.md +39 -0
  156. package/docs/api/tools.md +57 -0
  157. package/docs/api/triggers.md +56 -0
  158. package/docs/api/vars.md +9 -0
  159. package/docs/api/vegetation.md +52 -0
  160. package/docs/api/water.md +48 -0
  161. package/docs/api/weather.md +29 -0
  162. package/docs/api/world.md +30 -0
  163. package/docs/recipes/01-new-game.md +148 -0
  164. package/docs/recipes/02-npc.md +167 -0
  165. package/docs/recipes/03-items-pickups.md +158 -0
  166. package/docs/recipes/04-quests.md +83 -0
  167. package/docs/recipes/05-props-bake.md +159 -0
  168. package/docs/recipes/06-clock-events.md +117 -0
  169. package/docs/recipes/07-flow-scenes-pause.md +132 -0
  170. package/docs/recipes/08-weather-sky.md +74 -0
  171. package/docs/recipes/09-style-pack.md +234 -0
  172. package/docs/recipes/10-blender-level.md +67 -0
  173. package/docs/recipes/11-vehicles.md +55 -0
  174. package/docs/recipes/12-navmesh.md +79 -0
  175. package/docs/recipes/13-animation.md +149 -0
  176. package/docs/recipes/14-custom-module.md +91 -0
  177. package/docs/recipes/15-perf.md +78 -0
  178. package/docs/recipes/16-dev-bridge.md +180 -0
  179. package/docs/recipes/18-world.md +185 -0
  180. package/docs/recipes/19-shooting-picking.md +76 -0
  181. package/docs/recipes/20-content-actions-save.md +176 -0
  182. package/docs/recipes/21-camera.md +153 -0
  183. package/docs/recipes/22-shop-gold.md +107 -0
  184. package/docs/recipes/23-ops.md +175 -0
  185. package/docs/recipes/26-ui-parts.md +138 -0
  186. package/docs/recipes/27-net.md +96 -0
  187. package/docs/recipes/28-terrain.md +80 -0
  188. package/docs/recipes/29-grid.md +87 -0
  189. package/docs/recipes/30-templates.md +131 -0
  190. package/docs/recipes/31-audio.md +126 -0
  191. package/docs/recipes/32-action-game.md +33 -0
  192. package/docs/recipes/33-stream-sources.md +37 -0
  193. package/docs/recipes/34-environment-lighting.md +36 -0
  194. package/docs/recipes/35-style-from-reference.md +89 -0
  195. package/docs/recipes/36-sky-ground-plant-looks.md +116 -0
  196. package/docs/recipes/37-terrain-look-hooks.md +97 -0
  197. package/docs/recipes/38-environment-look-hooks.md +83 -0
  198. package/docs/recipes/40-scene.md +108 -0
  199. package/docs/recipes/41-thing-registry.md +93 -0
  200. package/docs/recipes/42-terrain-shape.md +64 -0
  201. package/docs/recipes/43-shader-patches-surface-looks.md +120 -0
  202. package/docs/recipes/44-water-weather-look-hooks.md +135 -0
  203. package/docs/recipes/45-cascaded-shadows.md +51 -0
  204. package/docs/recipes/46-blender-art-route.md +114 -0
  205. package/docs/recipes/47-island-snow-backdrop.md +44 -0
  206. package/docs/recipes/48-make-material.md +70 -0
  207. package/docs/recipes/49-game-module-contract.md +71 -0
  208. package/docs/recipes/50-own-renderer.md +12 -0
  209. package/docs/recipes/51-capability-catalog.md +63 -0
  210. package/docs/recipes/52-look.md +108 -0
  211. package/examples/action/DESIGN.md +3 -0
  212. package/examples/action/GAMEMAP.md +127 -0
  213. package/examples/action/content/actions.js +8 -0
  214. package/examples/action/content/audio.js +9 -0
  215. package/examples/action/content/index.js +10 -0
  216. package/examples/action/content/items.js +4 -0
  217. package/examples/action/content/places.js +4 -0
  218. package/examples/action/content/props.js +11 -0
  219. package/examples/action/content/templates.js +10 -0
  220. package/examples/action/content/views.js +6 -0
  221. package/examples/action/look.js +5 -0
  222. package/examples/action/main.js +137 -0
  223. package/examples/action/models.js +25 -0
  224. package/examples/sheepisland/GAMEMAP.md +107 -0
  225. package/examples/sheepisland/content/index.js +6 -0
  226. package/examples/sheepisland/content/props.js +19 -0
  227. package/examples/sheepisland/content/templates.js +5 -0
  228. package/examples/sheepisland/content/vegetation.js +8 -0
  229. package/examples/sheepisland/main.js +71 -0
  230. package/examples/sheepisland/params.js +25 -0
  231. package/examples/sheepisland/style/index.js +79 -0
  232. package/examples/sheepisland/style/models.js +59 -0
  233. package/examples/sheepisland/views.js +9 -0
  234. package/examples/styletest/GAMEMAP.md +135 -0
  235. package/examples/styletest/content/index.js +9 -0
  236. package/examples/styletest/content/items.js +8 -0
  237. package/examples/styletest/content/npcs.js +8 -0
  238. package/examples/styletest/content/places.js +5 -0
  239. package/examples/styletest/content/props.js +16 -0
  240. package/examples/styletest/content/templates.js +9 -0
  241. package/examples/styletest/content/vegetation.js +31 -0
  242. package/examples/styletest/look.js +11 -0
  243. package/examples/styletest/main.js +95 -0
  244. package/examples/styletest/models.js +87 -0
  245. package/examples/styletest/overrides.js +33 -0
  246. package/examples/styletest/panel.js +135 -0
  247. package/examples/styletest/params.js +32 -0
  248. package/examples/styletest/views.js +31 -0
  249. package/examples/world/DESIGN.md +5 -0
  250. package/examples/world/GAMEMAP.md +171 -0
  251. package/examples/world/content/actions.js +8 -0
  252. package/examples/world/content/audio.js +25 -0
  253. package/examples/world/content/bodies.js +12 -0
  254. package/examples/world/content/containers.js +4 -0
  255. package/examples/world/content/dialogues.js +33 -0
  256. package/examples/world/content/index.js +17 -0
  257. package/examples/world/content/items.js +10 -0
  258. package/examples/world/content/npcs.js +14 -0
  259. package/examples/world/content/pickups.js +11 -0
  260. package/examples/world/content/places.js +6 -0
  261. package/examples/world/content/props.js +12 -0
  262. package/examples/world/content/quests.js +15 -0
  263. package/examples/world/content/rules.js +23 -0
  264. package/examples/world/content/templates.js +5 -0
  265. package/examples/world/content/vegetation.js +32 -0
  266. package/examples/world/main.js +168 -0
  267. package/examples/world/models.js +28 -0
  268. package/index.d.ts +306 -0
  269. package/index.js +122 -0
  270. package/llms.txt +61 -0
  271. package/modules/ambience/Ambience.js +186 -0
  272. package/modules/camera/FirstPersonCamera.js +131 -0
  273. package/modules/camera/FixedCamera.js +162 -0
  274. package/modules/camera/FollowCamera.js +91 -0
  275. package/modules/camera/RtsCamera.js +132 -0
  276. package/modules/camera/common.js +182 -0
  277. package/modules/camera/index.js +11 -0
  278. package/modules/camera/projection.js +34 -0
  279. package/modules/characters/Character.js +235 -0
  280. package/modules/characters/NPC.js +242 -0
  281. package/modules/characters/assetModel.js +42 -0
  282. package/modules/characters/astar.js +66 -0
  283. package/modules/characters/behaviors.js +72 -0
  284. package/modules/characters/footsteps.js +13 -0
  285. package/modules/characters/index.js +215 -0
  286. package/modules/characters/moveHelpers.js +29 -0
  287. package/modules/characters/movers/common.js +62 -0
  288. package/modules/characters/movers/rapier.js +74 -0
  289. package/modules/characters/movers/simple.js +43 -0
  290. package/modules/characters/npcAvoid.js +129 -0
  291. package/modules/characters/npcSim.js +150 -0
  292. package/modules/characters/npcView.js +42 -0
  293. package/modules/characters/pathAsync.js +113 -0
  294. package/modules/characters/pathJob.js +62 -0
  295. package/modules/characters/pathWorker.js +7 -0
  296. package/modules/characters/playerStrings.js +12 -0
  297. package/modules/characters/proceduralRig.js +58 -0
  298. package/modules/characters/useModel.js +22 -0
  299. package/modules/characters/walkTo.js +58 -0
  300. package/modules/collision/Collision.js +274 -0
  301. package/modules/collision/grid.js +63 -0
  302. package/modules/content/explain.js +13 -0
  303. package/modules/content/ids.js +95 -0
  304. package/modules/content/index.js +154 -0
  305. package/modules/content/loader.js +190 -0
  306. package/modules/content/models.js +69 -0
  307. package/modules/content/packs.js +69 -0
  308. package/modules/content/props.js +89 -0
  309. package/modules/content/rules.js +134 -0
  310. package/modules/content/templates.js +189 -0
  311. package/modules/debug/DebugPanel.js +174 -0
  312. package/modules/entities/Entities.js +243 -0
  313. package/modules/entities/build.js +25 -0
  314. package/modules/entities/index.js +4 -0
  315. package/modules/flow/index.js +101 -0
  316. package/modules/gameplay/Container.js +227 -0
  317. package/modules/gameplay/Containers.js +89 -0
  318. package/modules/gameplay/Dialogue.js +219 -0
  319. package/modules/gameplay/Interactions.js +253 -0
  320. package/modules/gameplay/Inventory.js +224 -0
  321. package/modules/gameplay/Quests.js +205 -0
  322. package/modules/gameplay/boxOps.js +60 -0
  323. package/modules/gameplay/dialogueBox.js +48 -0
  324. package/modules/gameplay/interactionPrompt.js +28 -0
  325. package/modules/gameplay/inventoryOps.js +137 -0
  326. package/modules/gameplay/pickups.js +115 -0
  327. package/modules/gameplay/questLog.js +54 -0
  328. package/modules/gameplay/questSave.js +71 -0
  329. package/modules/grid/Grid.js +184 -0
  330. package/modules/grid/Layer.js +142 -0
  331. package/modules/grid/index.js +236 -0
  332. package/modules/grid/ops.js +73 -0
  333. package/modules/grid/preview.js +85 -0
  334. package/modules/grid/tiles.js +79 -0
  335. package/modules/hlod/index.js +167 -0
  336. package/modules/hud/index.js +167 -0
  337. package/modules/hud/parts.js +80 -0
  338. package/modules/level/geometry.js +46 -0
  339. package/modules/level/heightfield.js +160 -0
  340. package/modules/level/index.js +233 -0
  341. package/modules/level/nodes.js +84 -0
  342. package/modules/lights/index.js +227 -0
  343. package/modules/music/Music.js +294 -0
  344. package/modules/music/index.js +2 -0
  345. package/modules/music/rules.js +28 -0
  346. package/modules/nav/index.js +156 -0
  347. package/modules/nav/navPath.js +17 -0
  348. package/modules/net/Client.js +137 -0
  349. package/modules/net/Host.js +117 -0
  350. package/modules/net/Net.js +49 -0
  351. package/modules/net/index.js +77 -0
  352. package/modules/net/sync.js +114 -0
  353. package/modules/net/transports.js +118 -0
  354. package/modules/particles/Particles.js +179 -0
  355. package/modules/particles/effect.js +112 -0
  356. package/modules/particles/shaders.js +28 -0
  357. package/modules/photo/Photo.js +146 -0
  358. package/modules/rigid/RigidBodies.js +265 -0
  359. package/modules/rigid/Vehicles.js +97 -0
  360. package/modules/rigid/sync.js +158 -0
  361. package/modules/settings/Settings.js +297 -0
  362. package/modules/settings/apply.js +21 -0
  363. package/modules/settings/index.js +3 -0
  364. package/modules/settings/sections.js +156 -0
  365. package/modules/settings/strings.js +53 -0
  366. package/modules/settings/view.js +65 -0
  367. package/modules/sky/Sky.js +259 -0
  368. package/modules/sky/calendar.js +80 -0
  369. package/modules/sky/cascades.js +125 -0
  370. package/modules/sky/clouds.js +79 -0
  371. package/modules/sky/domeLayers.js +33 -0
  372. package/modules/sky/environment.js +141 -0
  373. package/modules/sky/fog.js +139 -0
  374. package/modules/sky/frame.js +77 -0
  375. package/modules/sky/layers.js +69 -0
  376. package/modules/sky/look.js +51 -0
  377. package/modules/sky/lookFog.js +80 -0
  378. package/modules/sky/lookShadow.js +50 -0
  379. package/modules/sky/lookSky.js +108 -0
  380. package/modules/sky/schedule.js +80 -0
  381. package/modules/sky/shader.js +96 -0
  382. package/modules/sky/shadow.js +74 -0
  383. package/modules/sky/skyModule.js +60 -0
  384. package/modules/terrain/ChunkManager.js +260 -0
  385. package/modules/terrain/chunkJob.js +19 -0
  386. package/modules/terrain/chunkLevels.js +40 -0
  387. package/modules/terrain/chunkQueries.js +42 -0
  388. package/modules/terrain/chunkWorker.js +5 -0
  389. package/modules/terrain/index.js +118 -0
  390. package/modules/terrain/lookGround.js +61 -0
  391. package/modules/terrain/mountTerrain.js +32 -0
  392. package/modules/terrain/terrainColorMap.js +41 -0
  393. package/modules/terrain/terrainDefaults.js +39 -0
  394. package/modules/terrain/terrainEdit.js +139 -0
  395. package/modules/terrain/terrainGen.js +155 -0
  396. package/modules/terrain/terrainIsland.js +131 -0
  397. package/modules/terrain/terrainMesh.js +92 -0
  398. package/modules/terrain/terrainShape.js +108 -0
  399. package/modules/terrain/terrainShapeMain.js +41 -0
  400. package/modules/terrain/terrainTexture.js +44 -0
  401. package/modules/timeline/Timeline.js +253 -0
  402. package/modules/timeline/Tween.js +114 -0
  403. package/modules/timeline/letterbox.js +24 -0
  404. package/modules/timeline/shots.js +90 -0
  405. package/modules/triggers/index.js +268 -0
  406. package/modules/vegetation/Vegetation.js +256 -0
  407. package/modules/vegetation/groundChunks.js +177 -0
  408. package/modules/vegetation/index.js +43 -0
  409. package/modules/vegetation/lookWind.js +37 -0
  410. package/modules/vegetation/modelGeometry.js +21 -0
  411. package/modules/water/Water.js +160 -0
  412. package/modules/water/look.js +80 -0
  413. package/modules/water/surface.js +88 -0
  414. package/modules/weather/Weather.js +242 -0
  415. package/modules/weather/look.js +75 -0
  416. package/modules/weather/particles.js +92 -0
  417. package/modules/weather/shaders.js +49 -0
  418. package/modules/weather/strings.js +15 -0
  419. package/modules/world/World.js +231 -0
  420. package/modules/world/cells.js +42 -0
  421. package/modules/world/explain.js +11 -0
  422. package/modules/world/index.js +71 -0
  423. package/modules/world/persist.js +107 -0
  424. package/modules/world/pos.js +20 -0
  425. package/modules/world/records.js +89 -0
  426. package/modules/world/sim.js +175 -0
  427. package/modules/world/simFar.js +82 -0
  428. package/modules/world/state.js +115 -0
  429. package/modules/world/thingSource.js +44 -0
  430. package/modules/world/views.js +182 -0
  431. package/package.json +66 -4
  432. package/presets.js +96 -0
  433. package/render/PostFX.js +240 -0
  434. package/render/detail.js +105 -0
  435. package/render/effects.js +144 -0
  436. package/render/engineUniforms.js +23 -0
  437. package/render/fuse.js +84 -0
  438. package/render/lighting.js +100 -0
  439. package/render/lights.js +18 -0
  440. package/render/lookSurface.js +161 -0
  441. package/render/materials.js +220 -0
  442. package/render/patches.js +252 -0
  443. package/render/postLook.js +86 -0
  444. package/render/surface.js +69 -0
  445. package/render/uniformDecl.js +29 -0
  446. package/types/common.d.ts +34 -0
  447. package/types/core.d.ts +1965 -0
  448. package/types/gameplay.d.ts +1822 -0
  449. package/types/generated/core/Audio.d.ts +200 -0
  450. package/types/generated/core/Batching.d.ts +47 -0
  451. package/types/generated/core/Budget.d.ts +90 -0
  452. package/types/generated/core/Commits.d.ts +31 -0
  453. package/types/generated/core/DebugOverrides.d.ts +52 -0
  454. package/types/generated/core/Events.d.ts +89 -0
  455. package/types/generated/core/I18n.d.ts +30 -0
  456. package/types/generated/core/Input.d.ts +118 -0
  457. package/types/generated/core/Jobs.d.ts +41 -0
  458. package/types/generated/core/Ops.d.ts +203 -0
  459. package/types/generated/core/Random.d.ts +49 -0
  460. package/types/generated/core/Rays.d.ts +49 -0
  461. package/types/generated/core/Saves.d.ts +162 -0
  462. package/types/generated/core/Stream.d.ts +93 -0
  463. package/types/generated/core/Threads.d.ts +82 -0
  464. package/types/generated/core/Views.d.ts +33 -0
  465. package/types/generated/core/audioVoice.d.ts +47 -0
  466. package/types/generated/core/page.d.ts +18 -0
  467. package/types/generated/core/session.d.ts +48 -0
  468. package/types/generated/modules/ambience/Ambience.d.ts +48 -0
  469. package/types/generated/modules/debug/DebugPanel.d.ts +24 -0
  470. package/types/generated/modules/flow/index.d.ts +10 -0
  471. package/types/generated/modules/grid/Grid.d.ts +151 -0
  472. package/types/generated/modules/grid/Layer.d.ts +65 -0
  473. package/types/generated/modules/grid/index.d.ts +86 -0
  474. package/types/generated/modules/hlod/index.d.ts +11 -0
  475. package/types/generated/modules/hud/index.d.ts +10 -0
  476. package/types/generated/modules/lights/index.d.ts +13 -0
  477. package/types/generated/modules/music/Music.d.ts +111 -0
  478. package/types/generated/modules/net/Net.d.ts +34 -0
  479. package/types/generated/modules/net/index.d.ts +53 -0
  480. package/types/generated/modules/net/transports.d.ts +58 -0
  481. package/types/generated/modules/particles/Particles.d.ts +69 -0
  482. package/types/generated/modules/sky/Sky.d.ts +145 -0
  483. package/types/generated/modules/sky/skyModule.d.ts +10 -0
  484. package/types/generated/modules/timeline/Timeline.d.ts +51 -0
  485. package/types/generated/modules/water/Water.d.ts +29 -0
  486. package/types/generated/modules/weather/Weather.d.ts +62 -0
  487. package/types/generated/modules/world/World.d.ts +242 -0
  488. package/types/generated/modules/world/index.d.ts +15 -0
  489. package/types/generated/render/PostFX.d.ts +125 -0
  490. package/types/generated/render/materials.d.ts +100 -0
  491. package/types/generated/render/patches.d.ts +41 -0
  492. package/types/generated/ui/Focus.d.ts +11 -0
  493. package/types/generated/ui/LoadingScreen.d.ts +2 -0
  494. package/types/generated/ui/UI.d.ts +57 -0
  495. package/types/nav.d.ts +52 -0
  496. package/types/physics.d.ts +592 -0
  497. package/types/style.d.ts +638 -0
  498. package/types/worker.d.ts +11 -0
  499. package/types/world.d.ts +772 -0
  500. package/ui/Focus.js +51 -0
  501. package/ui/LoadingScreen.js +42 -0
  502. package/ui/Parts.js +199 -0
  503. package/ui/UI.js +167 -0
  504. package/ui/defaults.js +85 -0
  505. package/ui/theme.js +124 -0
  506. package/ui/touchPart.js +49 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ # Changelog (threedog)
2
+
3
+ The engine has not been released yet, so this log is not maintained before release. At release time it is written in one pass from git history and `docs/API.md`: "what changed, how a game upgrades", placed under the version heading.
4
+
5
+ ## 0.1.0 (unreleased)
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 penstic
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,40 @@
1
- # Temporary Holding Version
1
+ # threedog
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A web 3D game engine on three.js 0.187: **core** (rendering, main loop, input, audio, saving, UI) -> **modules** (terrain, sky and weather, physics, characters, dialogue, inventory, quests... installed on demand) -> **style pack** (all art).
4
+
5
+ ## Install
6
+ ```sh
7
+ npm install threedog three@~0.187.0
8
+ npm install @threedog/style-lowpoly # optional: the low-poly style pack (the engine ships no art)
9
+ npm install @threedog/terrain-noise # optional: the noise terrain generator terrainPreset() (without one the ground is flat)
10
+ npm install -D vite @threedog/tools # optional: the vite preset and the threedog command line
11
+ ```
12
+ `three` is a peer dependency: your game and the engine share one copy. Types for three come with the engine (`@types/three`, same version), so `// @ts-check` JS and TypeScript both see real three.js types.
13
+
14
+ ## Minimal usage
15
+ ```js
16
+ import { createEngine, presets, openWorld } from 'threedog';
17
+ import lowpoly from '@threedog/style-lowpoly'; // optional style pack (npm install @threedog/style-lowpoly)
18
+ import { terrainPreset } from '@threedog/terrain-noise'; // optional terrain generator (npm install @threedog/terrain-noise)
19
+
20
+ const engine = createEngine({ canvas: document.getElementById('view'), style: lowpoly });
21
+ engine.use(openWorld({ camera: 'follow', seed: 7, terrain: terrainPreset() }));
22
+ engine.characters.createPlayer({ ...presets.player.thirdPerson });
23
+ engine.start();
24
+ ```
25
+ `vite.config.js` with the preset: `import { gameConfig } from '@threedog/tools/vite'; export default gameConfig(import.meta.dirname);`
26
+
27
+ ## Entry points
28
+ - `threedog`: the whole public API (`THREE` is re-exported, so `import { THREE } from 'threedog'` is the same three instance).
29
+ - Style packs are separate packages: the engine ships no art. `npm install @threedog/style-lowpoly` for the optional low-poly one (visuals only; the noise terrain generator `terrainPreset()` is `@threedog/terrain-noise`); without a style pack everything is a neutral gray placeholder.
30
+ - `threedog/error-hints`: the developer error hint table (used by `@threedog/tools`).
31
+
32
+ Nothing else is a public path; files under `core/`, `modules/` etc. may move between versions.
33
+
34
+ ## Global changes to three.js
35
+ Importing the engine changes two defaults on `THREE.Mesh.prototype`, for every mesh in the page:
36
+ - `Mesh.prototype.raycast` is replaced by three-mesh-bvh's accelerated raycast (`BufferGeometry.prototype.computeBoundsTree` / `disposeBoundsTree` are added). Results are the same as three's own raycast; meshes without a bounds tree fall back to it.
37
+ - `Mesh.prototype.customDepthMaterial` and `customDistanceMaterial` become accessors: when nothing was assigned, a mesh whose material has engine vertex patches (wind sway) returns a matching depth material, so its shadow moves with it. Assigning a value (including in your own code) still wins; assigning `undefined` restores the default. The value is stored under a symbol, so `Object.hasOwn(mesh, 'customDepthMaterial')` is false.
38
+
39
+ ## Docs
40
+ Shipped in the package: `docs/AI.md` (how to use the engine, written for AI assistants), `docs/API.md` + `docs/api/` (per module), `docs/recipes/` (task guides), `docs/THREE.md` (using three.js directly).
@@ -0,0 +1,268 @@
1
+ // Animation state machine: assets.animate(model, config) returns it. Native objects below.
2
+ // const anim = engine.assets.animate(model, {
3
+ // states: { idle: { clip: 'Idle' }, move: { blend: [{ clip: 'Walk', at: 1.5 }, { clip: 'Run', at: 6 }], param: 'speed' },
4
+ // wave: { clip: 'Wave', loop: false, then: 'idle', lock: true },
5
+ // attack: { clip: 'Sword_Slash', loop: false, timing: [[0, 0], [0.16, 0.35], [0.28, 0.6], [0.62, 1]] } },
6
+ // transitions: { '*>idle': 0.3 },
7
+ // });
8
+ // anim.set('speed', 3); anim.go('move'); anim.action('wave');
9
+ // anim.sync('attack', fighter.t); ... anim.sync(null); // gameplay time drives the pose; null hands control back
10
+ // States are the mapping: game names (idle / attack / hurt) on the left, whatever the asset calls the clip on the right.
11
+ // The mapping belongs to the model file, so it can live as data in the asset manifest (models: { hero: { url, animation: { states } } }): Assets.animate
12
+ // merges it under the code's config, and swapping the model then never touches game code. anim.check([...actions]) lists what the game would miss.
13
+ // A clip name also matches the part after the last '|' ('Idle' finds 'CharacterArmature|Idle', as Blender exports name them).
14
+ // Weights are managed here: each state has a fading weight, blend trees split it by parameter; all action weights sum to 1.
15
+ // A one-shot action emits anim:end { root, state } when done, then moves to its `then`. Native objects: mixer, actions (clip name -> AnimationAction).
16
+ // Rule: animation is presentation; gameplay timing must not read it. The mixer advances per frame (dropped frames, step's frameEvery or a disposed model all skew it),
17
+ // so hit windows, stun and cooldowns count in fixed steps, and sync(state, t) is how that gameplay time reaches the pose: the clip never runs ahead or ends by itself.
18
+ import * as THREE from 'three';
19
+ import { warnOnce, warnMissing, missingText, checkOptions } from './validate.js';
20
+
21
+ // Config keys: a typo (loops: false, state: {...}) would silently play the wrong thing, so both levels are checked like any other options
22
+ const CONFIG_KEYS = ['fade', 'states', 'transitions', 'params'];
23
+ const STATE_KEYS = ['clip', 'blend', 'param', 'sync', 'loop', 'then', 'lock', 'timing'];
24
+
25
+ /**
26
+ * Find a clip by exact name, else by the part after the last '|' ('Idle' finds 'CharacterArmature|Idle').
27
+ * @example findClip(model.userData.animations, 'Sword_Slash')
28
+ */
29
+ export function findClip(clips, name) {
30
+ return THREE.AnimationClip.findByName(clips, name) ?? clips.find(c => c.name.slice(c.name.lastIndexOf('|') + 1) === name) ?? null;
31
+ }
32
+ const short = n => n.slice(n.lastIndexOf('|') + 1);
33
+ const r3 = v => Math.round(v * 1000) / 1000;
34
+
35
+ export class Animator {
36
+ /** mappedIn (from Assets.animate): { label, states } when part of the mapping came from the manifest, so fix texts point at the data, not at code */
37
+ constructor(engine, root, config = {}, mappedIn = null) {
38
+ // config is the code's options merged over the manifest mapping, so name both places a typo can be in
39
+ checkOptions(mappedIn ? `assets.animate() / ${mappedIn.label}` : 'assets.animate()', config, CONFIG_KEYS);
40
+ const { fade = 0.25, states = {}, transitions = {}, params = {} } = config;
41
+ this.engine = engine;
42
+ this._mappedIn = mappedIn;
43
+ this.root = root;
44
+ this.fade = fade;
45
+ this.states = states;
46
+ this.transitions = transitions;
47
+ this.params = { speed: 0, ...params };
48
+ this.mixer = new THREE.AnimationMixer(root);
49
+ this.clips = root.userData.animations || [];
50
+ this.actions = new Map(); // clip name (as written in the state) -> three.js AnimationAction
51
+ this.state = null;
52
+ this._layers = []; // states being shown: { name, def, w, target, rate, actions: [{ a, clip }], driven }
53
+ this._return = null; // state to return to when an action() one-shot ends
54
+ this._driven = null; // state currently posed by sync(); go() and action() leave it alone
55
+ this._t = 0; // last gameplay time passed to sync (describe)
56
+ // A static model (a procedural prop, a model exported without clips) has nothing to play: no dev warnings, no per-frame hook; go() / action() just return null.
57
+ this.hasClips = this.clips.length > 0;
58
+ this._hook = null;
59
+ if (this.hasClips) {
60
+ this._check();
61
+ this.mixer.addEventListener('finished', ev => this._finished(ev.action));
62
+ this._hook = engine.onFrame(dt => this.update(dt));
63
+ }
64
+ }
65
+ /** Dev check at build time: the same problems check() returns, minus the game's action list (the Animator does not know it). */
66
+ _check() {
67
+ for (const [st, def] of Object.entries(this.states)) checkOptions(`assets.animate() ${this._where(st)}`, def, STATE_KEYS);
68
+ for (const p of this._problems()) warnOnce(p);
69
+ }
70
+ /** Where a state is written: the manifest entry when the mapping came from there (data), else the code's states. */
71
+ _where(st) {
72
+ const m = this._mappedIn;
73
+ return m && (m.states.includes(st) || !this.states[st]) ? `${m.label}.states.${st}` : `states.${st}`;
74
+ }
75
+ _problems() {
76
+ const names = [...new Set(this.clips.map(c => short(c.name)))], out = [];
77
+ for (const [st, def] of Object.entries(this.states)) {
78
+ for (const clip of def.blend ? def.blend.map(b => b.clip) : [def.clip]) {
79
+ if (!findClip(this.clips, clip)) out.push(`assets.animate(): state "${st}" maps to a missing clip. ${missingText('clip', clip, names)}. Fix the clip name in ${this._where(st)}, or remove the state`);
80
+ }
81
+ if (def.then && !this.states[def.then]) out.push(`assets.animate(): ${this._where(st)}.then. ${missingText('animState', def.then, Object.keys(this.states))}`);
82
+ }
83
+ return out;
84
+ }
85
+ /**
86
+ * Check the mapping against the action names the game plays: every problem as text with its fix, [] when all of them will play.
87
+ * Covers an action without a state, a state whose clip is not in the model, a `then` that is not a state, and a model without clips.
88
+ * Call it once after building (a test, the dev console): a bad name in go() / sync() only warns at the moment it is played.
89
+ * @example anim.check(['idle', 'walk', 'attack', 'hurt']) // [] or ['action "hurt" has no state. Add it to ... states.hurt: { clip: ... } (clips in the model: Death, Idle, ...)']
90
+ * @param {string[]} [actions] @returns {string[]}
91
+ */
92
+ check(actions = []) {
93
+ if (!this.hasClips) return actions.length ? [`assets.animate(): the model has no animation clips, so ${actions.join(', ')} cannot play. Export the glTF with its animations (Blender: Animation > include all actions), or play them procedurally`] : [];
94
+ const names = [...new Set(this.clips.map(c => short(c.name)))];
95
+ const missing = actions.filter(n => !this.states[n]).map(n => `assets.animate(): action "${n}" has no state. Add it to ${this._where(n)}: { clip: '<name>' } (clips in the model: ${names.join(', ')})`);
96
+ return missing.concat(this._problems());
97
+ }
98
+ /** Get the action for a clip (null if there is no such clip). */
99
+ _action(name) {
100
+ if (!this.actions.has(name)) {
101
+ const c = findClip(this.clips, name);
102
+ if (!c) return null;
103
+ this.actions.set(name, this.mixer.clipAction(c));
104
+ }
105
+ return this.actions.get(name);
106
+ }
107
+ _fadeFor(from, to, fade) {
108
+ const t = this.transitions;
109
+ return fade ?? t[`${from}>${to}`] ?? t[`*>${to}`] ?? t[`${from}>*`] ?? this.fade;
110
+ }
111
+
112
+ /** Set a parameter for blend trees (e.g. speed). */
113
+ set(param, v) { this.params[param] = v; return this; }
114
+
115
+ /**
116
+ * Switch to a state (fade = transition seconds). Returns the action, or null (with a dev warning) if the state or its clip does not exist.
117
+ * Does not switch while the current state is locked and unfinished, or while sync() drives a state.
118
+ * @example anim.go('idle'); anim.go('run', 0.1)
119
+ */
120
+ go(state, fade) {
121
+ if (this._driven) return this._layers.find(l => l.name === this._driven).actions[0].a;
122
+ const cur = this._layers.find(l => l.name === this.state && l.target === 1);
123
+ if (cur && state === this.state && !cur.done) return cur.actions[0].a; // already in this state (a finished one-shot may replay)
124
+ if ((cur?.def.lock || cur?.once) && !cur.done) return cur.actions[0].a;
125
+ return this._enter(state, fade);
126
+ }
127
+ /** Switch unconditionally (go after its guards, and sync). */
128
+ _enter(state, fade) {
129
+ if (!this.hasClips) return null; // static model: nothing to play, nothing to warn about
130
+ const def = this.states[state];
131
+ if (!def) { warnMissing('animState', state, Object.keys(this.states)); return null; }
132
+ const actions = (def.blend ? def.blend.map(b => b.clip) : [def.clip]).map(clip => ({ a: this._action(clip), clip }));
133
+ if (actions.some(x => !x.a)) return null; // missing clip: already reported by _check
134
+ const f = this._fadeFor(this.state, state, fade), rate = f > 0 ? 1 / f : Infinity;
135
+ for (const l of this._layers) { l.target = 0; l.rate = rate; }
136
+ let layer = this._layers.find(l => l.name === state);
137
+ if (!layer) {
138
+ layer = { name: state, def, w: this._layers.some(l => l.w > 0) ? 0 : 1, actions }; // the first state shows immediately
139
+ this._layers.push(layer);
140
+ for (const { a } of actions) {
141
+ a.reset().setEffectiveWeight(0);
142
+ if (def.loop === false) { a.setLoop(THREE.LoopOnce, 1); a.clampWhenFinished = true; } else a.setLoop(THREE.LoopRepeat, Infinity);
143
+ a.play();
144
+ }
145
+ } else if (def.loop === false) for (const { a } of actions) a.reset().play();
146
+ Object.assign(layer, { target: 1, rate, done: false, once: false, driven: false });
147
+ for (const { a } of actions) a.paused = false;
148
+ this.state = state;
149
+ this._weights();
150
+ return actions[0].a;
151
+ }
152
+ /** Play a one-shot action: when done, go to the state's `then`; without `then` (or given a bare clip name) return to the previous state. */
153
+ action(name, fade) {
154
+ const prev = this.state, def = this.states[name];
155
+ if (!def) {
156
+ if (!findClip(this.clips, name)) { if (this.hasClips) warnMissing('clip', name, this.clips.map(c => short(c.name))); return null; }
157
+ this.states[name] = { clip: name, loop: false, lock: true };
158
+ }
159
+ const a = this.go(name, fade);
160
+ if (a && this.state === name) {
161
+ this._layers.find(l => l.name === name).once = true; // not interrupted by the character's per-frame go() until it ends
162
+ if (!this.states[name].then) this._return = prev;
163
+ }
164
+ return a;
165
+ }
166
+
167
+ /**
168
+ * Gameplay drives the clock: show `state` at gameplay time `t` (seconds since the gameplay action started, counted in fixed steps).
169
+ * While synced the clip does not advance or end by itself, and go() / action() leave it alone (a character's per-frame locomotion cannot override it).
170
+ * The state's `timing` maps gameplay seconds to clip seconds: a number = the gameplay length the whole clip is stretched over,
171
+ * or [[gameT, clipT], ...] pairs (piecewise linear) to land the swing on the hit phase. Without timing, clip seconds = t.
172
+ * sync(null) hands control back (the next go() switches as usual). Call it every frame or fixed step; cheap when nothing changes.
173
+ * @example
174
+ * // states: { slash: { clip: 'Sword_Slash', loop: false, timing: [[0, 0], [0.16, 0.4], [0.28, 0.6], [0.62, 1]] } }
175
+ * engine.onFrame(() => fighter.act ? anim.sync('slash', fighter.act.t) : anim.sync(null));
176
+ * @param {string | null} state @param {number} [t] @returns {import('three').AnimationAction | null}
177
+ */
178
+ sync(state, t = 0) {
179
+ if (state == null) {
180
+ const l = this._driven && this._layers.find(x => x.name === this._driven);
181
+ if (l) { l.driven = false; l.done = true; for (const { a } of l.actions) a.paused = false; }
182
+ this._driven = null;
183
+ return null;
184
+ }
185
+ if (this._driven !== state || !this._layers.some(l => l.name === state && l.target === 1)) {
186
+ this._driven = null;
187
+ if (!this._enter(state)) return null;
188
+ const l = this._layers.find(x => x.name === state);
189
+ l.driven = true; this._driven = state;
190
+ for (const { a } of l.actions) { a.paused = true; a.enabled = true; }
191
+ }
192
+ this._t = t;
193
+ const def = this.states[state], l = this._layers.find(x => x.name === state);
194
+ for (const { a } of l.actions) a.time = this._clipTime(def, a.getClip().duration, t);
195
+ return l.actions[0].a;
196
+ }
197
+ /** Gameplay seconds -> clip seconds through the state's timing; looping states wrap, one-shots clamp to the clip. */
198
+ _clipTime(def, dur, t) {
199
+ const k = def.timing;
200
+ let c = t;
201
+ if (typeof k === 'number') c = k > 0 ? t / k * dur : 0;
202
+ else if (Array.isArray(k) && k.length) {
203
+ c = k[k.length - 1][1];
204
+ if (t <= k[0][0]) c = k[0][1];
205
+ else for (let i = 1; i < k.length; i++) if (t < k[i][0]) { const [t0, c0] = k[i - 1], [t1, c1] = k[i]; c = c0 + (c1 - c0) * (t - t0) / (t1 - t0); break; }
206
+ }
207
+ return def.loop === false ? Math.min(Math.max(c, 0), dur) : ((c % dur) + dur) % dur;
208
+ }
209
+
210
+ _finished(action) {
211
+ const layer = this._layers.find(l => l.name === this.state);
212
+ if (!layer || layer.driven || !layer.actions.some(x => x.a === action)) return;
213
+ layer.done = true;
214
+ this.engine.events.emit('anim:end', { root: this.root, state: layer.name });
215
+ const next = layer.def.then ?? this._return;
216
+ this._return = null;
217
+ if (next) this.go(next);
218
+ }
219
+
220
+ /** @internal Per frame: advance fades, split blend-tree weights by parameter, sync stride, then advance the mixer (the engine calls it). */
221
+ update(dt) {
222
+ let j = 0; // fade, stop faded-out layers and compact in place (no arrays per frame)
223
+ for (const l of this._layers) {
224
+ l.w = l.target > l.w ? Math.min(1, l.w + dt * l.rate) : Math.max(0, l.w - dt * l.rate);
225
+ if (l.w === 0 && l.target === 0) { for (const { a } of l.actions) a.setEffectiveWeight(0).stop(); continue; }
226
+ this._layers[j++] = l;
227
+ }
228
+ this._layers.length = j;
229
+ this._weights();
230
+ this.mixer.update(dt);
231
+ this.afterPose?.(dt); // Character.onPose callbacks (the pose is final here)
232
+ }
233
+ _weights() {
234
+ let total = 0;
235
+ for (const l of this._layers) total += l.w;
236
+ for (const l of this._layers) {
237
+ const lw = total > 0 ? l.w / total : 0, bw = l.def.blend ? this._blend(l.def) : [1];
238
+ let dur = 0;
239
+ l.actions.forEach((x, i) => { dur += bw[i] * x.a.getClip().duration; });
240
+ l.actions.forEach((x, i) => {
241
+ x.a.setEffectiveWeight(lw * bw[i]);
242
+ // blended actions share one beat (walk and run footfalls land together)
243
+ if (l.def.blend && l.def.sync !== false && dur > 0) x.a.setEffectiveTimeScale(x.a.getClip().duration / dur);
244
+ });
245
+ }
246
+ }
247
+ /** Blend-tree weights: a parameter between two `at` values splits proportionally across the two neighbours. */
248
+ _blend(def) {
249
+ const v = this.params[def.param ?? 'speed'] ?? 0, b = def.blend, w = b.map(() => 0);
250
+ if (v <= b[0].at) w[0] = 1;
251
+ else if (v >= b[b.length - 1].at) w[b.length - 1] = 1;
252
+ else for (let i = 0; i < b.length - 1; i++) if (v >= b[i].at && v < b[i + 1].at) { const t = (v - b[i].at) / (b[i + 1].at - b[i].at); w[i] = 1 - t; w[i + 1] = t; }
253
+ return w;
254
+ }
255
+ /**
256
+ * What is showing, as plain data (describe, dev bridge, tests): state, its clip and clip time, progress 0-1 through the clip,
257
+ * whether gameplay drives it (and the last gameplay t), and every fading state's weight.
258
+ * @example engine.player.anim.describe() // { state: 'attack', clip: 'Sword_Slash', time: 0.42, progress: 0.42, driven: true, t: 0.2, weights: { attack: 0.8, idle: 0.2 } }
259
+ */
260
+ describe() {
261
+ const l = this._layers.find(x => x.name === this.state), a = l?.actions[0].a, dur = a?.getClip().duration || 0;
262
+ const total = this._layers.reduce((s, x) => s + x.w, 0) || 1; // shown as shares, like the mixer weights (they sum to 1)
263
+ return { state: this.state, clip: l?.actions[0].clip ?? null, time: a ? r3(a.time) : 0, progress: dur ? r3(a.time / dur) : 0,
264
+ driven: !!l?.driven, ...(l?.driven && { t: r3(this._t) }), weights: Object.fromEntries(this._layers.map(x => [x.name, r3(x.w / total)])) };
265
+ }
266
+ /** Call when no longer needed to stop per-frame updates. */
267
+ dispose() { this._hook?.remove(); this.mixer.stopAllAction(); }
268
+ }
package/core/Assets.js ADDED
@@ -0,0 +1,256 @@
1
+ // Asset management:
2
+ // 1. Asset manifest: register every model, texture and sound under a name; code uses names only, so swapping a file means editing the manifest.
3
+ // 2. Preload: load everything marked preload once at startup; the loading screen shows progress.
4
+ // 3. Cache and reuse: one file downloads once; models return independent copies (geometry and materials shared), so you can place many.
5
+ // 4. Release: models count usage per copy; release(name) frees only when the last copy is removed, trim() frees every model with no copy in use (see their docs
6
+ // below).
7
+ // 5. Compression: Draco / Meshopt models and .ktx2 textures load as-is; the decoder downloads on first use (npm run assets produces compressed files).
8
+ // 6. Code-generated models: write a function (or { build, params }) in the manifest; it is built on demand and cached automatically, see cached() below.
9
+ // 7. Observable: every load is a task in engine.loading. A registered file that fails falls back (gray placeholder / silence / the entry's fallback)
10
+ // unless it is critical: true, which stops start() instead (assetEntry.js).
11
+ // 8. Asset packs: a manifest is a plain object, so a folder or an npm package can ship one and a game registers it with one call (recipes/05-props-bake.md
12
+ // "Asset packs").
13
+ //
14
+ // Put files under public/: public/models/house.glb -> write the path as '/models/house.glb'
15
+ //
16
+ // engine.assets.manifest({
17
+ // name: 'main', // shown as the source manifest in engine.loading
18
+ // models: { house: '/models/house.glb', hero: { url: '/models/hero.glb', critical: true }, block: buildBlock },
19
+ // textures: { paper: { url: '/textures/paper.jpg', color: true }, ground: '/textures/ground.ktx2' },
20
+ // sounds: { bgm: '/sounds/morning.mp3' },
21
+ // fonts: { pixel: '/fonts/pixel.woff2', pixelBold: { url: '/fonts/pixel-bold.woff2', family: 'pixel', weight: 700 } }, // style.ui.fonts names them
22
+ // });
23
+ // engine.assets.manifest({ name: 'forest', base: '/packs/forest/', models: { oak: 'oak.glb' } }); // -> /packs/forest/oak.glb
24
+ // await engine.assets.preload(p => console.log(p)); // p: 0-1 (code-generated models are built ahead only if marked preload)
25
+ // const house = await engine.assets.model('house'); // get by name
26
+ import { reportGltf, reportText } from './assetReport.js';
27
+ import * as THREE from 'three';
28
+ import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
29
+ import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js';
30
+ import { clone as skeletonClone } from 'three/addons/utils/SkeletonUtils.js';
31
+ import { warnMissing, warnOnce, fmt } from './validate.js';
32
+ import { codedError, coded } from './errorHints.js';
33
+ import { Animator } from './Animator.js';
34
+ import { fetchEntry, freeEntry, preloadEntries } from './assetEntry.js';
35
+ import { registerManifest } from './assetManifest.js';
36
+
37
+ const STRINGS = {
38
+ noFont: 'assets.font(\'{name}\'): no font named {name}{known}. Register the file in an asset pack: engine.assets.manifest({ fonts: { {name}: \'/fonts/{name}.woff2\' } })',
39
+ sameName: 'assets.cached(\'{name}\'): the same name was used with two different generator functions, so the cache would mix them (keyed by name + params). Use a different name per model; if the result depends on outer variables, put them in params',
40
+ };
41
+ /** Short hash of the source (cache key; tells apart same-name, different-function cases) */
42
+ const srcHash = s => { let h = 0; for (let i = 0; i < s.length; i++) h = (Math.imul(h, 31) + s.charCodeAt(i)) | 0; return (h >>> 0).toString(36); };
43
+
44
+ export class Assets {
45
+ constructor(engine) {
46
+ this.engine = engine;
47
+ this.entries = new Map(); // name -> { type, url, opts, promise, value }
48
+ this.gltf = new GLTFLoader();
49
+ this.gltf.setMeshoptDecoder(MeshoptDecoder);
50
+ this.draco = null; // DRACOLoader / KTX2Loader:created on the first compressed data
51
+ this.ktx2 = null;
52
+ this.tex = new THREE.TextureLoader();
53
+ this.shared = new WeakSet(); // geometry and materials shared by model copies (engine.remove does not dispose them)
54
+ this._instances = new WeakMap(); // model copy root -> asset entry (counts usage)
55
+ this._animators = new WeakMap(); // model root -> Animator from animate(): engine.remove disposes it with the model
56
+ this.cacheMinMs = 20; // builds faster than this are not cached (reading the file would be slower)
57
+ this._loaders = {};
58
+ }
59
+
60
+ /**
61
+ * Register an asset manifest or asset pack (may be called repeatedly; a later entry with the same name replaces the earlier one). A model may be a generator
62
+ * function or { build, params, preload }.
63
+ * Per entry: critical: true = start() stops if it fails (otherwise it falls back and the game continues); fallback: 'otherName' replaces the gray
64
+ * placeholder.
65
+ * name labels the manifest in engine.loading (default 'manifest#1', '#2'...), so a failure says which list it came from.
66
+ * base (a pack's folder: '/packs/forest/', a CDN URL, or new URL('./files/', import.meta.url)) resolves the relative paths of this manifest; '/x' and full
67
+ * URLs stay as written.
68
+ * @example engine.assets.manifest({ name: 'level-1', models: { hero: { url: '/models/hero.glb', critical: true }, bush: { url: '/models/bush.glb', fallback:
69
+ * 'rock' } } });
70
+ * @example import forest from 'my-forest-assets'; engine.assets.manifest(forest); // { name: 'forest', base, models: { oak: 'oak.glb' } }
71
+ */
72
+ manifest(pack = {}) { return registerManifest(this, pack); }
73
+
74
+ /**
75
+ * The generator function registered under a model name (manifest models: { pine: fn } or { build }), null for a file model or an unknown name.
76
+ * Content uses it to build parametrized procedural models ([name, ...params]) through cached(); code rarely needs it
77
+ * @example const fn = engine.assets.builder('flower'); if (fn) engine.assets.cached('flower', fn, 0xff0000);
78
+ * @param {string} name
79
+ * @returns {((...args: any[]) => any) | null}
80
+ */
81
+ builder(name) {
82
+ const e = this.entries.get(name);
83
+ return e?.named && e.type === 'model' && e.opts.build || null;
84
+ }
85
+
86
+ _resolve(nameOrUrl, type) {
87
+ let e = this.entries.get(nameOrUrl);
88
+ // not path-like (no / or .) and not registered: most likely a misspelled name
89
+ if (!e && !/[/.]/.test(nameOrUrl)) warnMissing('asset', nameOrUrl, [...this.entries].filter(([, x]) => x.type === type && x.named).map(([n]) => n));
90
+ if (!e) { e = { type, name: nameOrUrl, url: nameOrUrl, opts: {}, promise: null }; this.entries.set(nameOrUrl, e); }
91
+ return e;
92
+ }
93
+ /** @internal Load an entry as a task in engine.loading (assetEntry.js) */
94
+ _fetch(e) { return fetchEntry(this, e); }
95
+
96
+ /**
97
+ * Preload manifest assets (all by default; onlyMarked=true loads only those marked preload). Code-generated models and fonts are loaded ahead only if marked
98
+ * preload (style.ui.fonts loads its own at start()). onProgress(0-1, current name).
99
+ * Finishing is not succeeding: failed lists every entry that failed, including those now showing their fallback (details in engine.loading).
100
+ */
101
+ async preload(onProgress, { onlyMarked = false } = {}) {
102
+ return preloadEntries(this, onProgress, onlyMarked);
103
+ }
104
+
105
+ /**
106
+ * A font from an asset pack, by name: downloads it once, adds it to document.fonts and resolves to the FontFace (null when the file
107
+ * failed and the entry is not critical: text then shows the next family of style.ui.font). Only registered names work, because a font
108
+ * needs its CSS family and descriptors; style.ui.fonts calls this for you at start().
109
+ * @example engine.assets.manifest({ name: 'ui', fonts: { pixel: '/fonts/pixel.woff2' } }); await engine.assets.font('pixel');
110
+ * @param {string} name
111
+ * @returns {Promise<FontFace | null>}
112
+ */
113
+ async font(name) {
114
+ const e = this.entries.get(name);
115
+ if (e?.type !== 'font') {
116
+ const known = [...this.entries.values()].filter(x => x.type === 'font' && x.named).map(x => x.name);
117
+ throw codedError('unknown-name', fmt(STRINGS.noFont, { name, known: known.length ? ` (fonts: ${known.join(', ')})` : '' }));
118
+ }
119
+ return this._fetch(e);
120
+ }
121
+
122
+ /** Get a model copy (name or path); skinned characters clone correctly. static: true registers it with engine.rays (builds ray acceleration) */
123
+ async model(nameOrUrl, opts = {}) {
124
+ const e = this._resolve(nameOrUrl, 'model'), gltf = await this._fetch(e);
125
+ return this._copy(e, gltf, opts);
126
+ }
127
+ /**
128
+ * A model copy right now if that model has already loaded, else null (never starts a load, never waits). For code that rebuilds often,
129
+ * such as a character coming back into view, so it skips the frame of placeholder an await would cost. Same options as model()
130
+ * @example const m = engine.assets.modelNow('villager') ?? await engine.assets.model('villager');
131
+ */
132
+ modelNow(nameOrUrl, opts = {}) {
133
+ const e = this.entries.get(nameOrUrl);
134
+ return e?.type === 'model' && e.value ? this._copy(e, e.value, opts) : null;
135
+ }
136
+ /** @internal one counted copy of a loaded model */
137
+ _copy(e, gltf, { castShadow, receiveShadow, static: isStatic = false } = {}) {
138
+ const root = skeletonClone(gltf.scene);
139
+ e.users = (e.users || 0) + 1; e.releasePending = false; this._instances.set(root, e);
140
+ // code-generated models keep their own shadow settings; file models cast and receive shadows by default
141
+ const cast = castShadow ?? (e.opts.build ? null : true), recv = receiveShadow ?? (e.opts.build ? null : true);
142
+ root.traverse(o => { if (o.isMesh) { if (cast != null) o.castShadow = cast; if (recv != null) o.receiveShadow = recv; } });
143
+ root.userData.animations = gltf.animations;
144
+ if (isStatic) this.engine.rays.addStatic(root);
145
+ return root;
146
+ }
147
+ /**
148
+ * Import report of a loaded model: materials, textures with their colorSpace, normal maps, clips, nodes, template / id nodes and col_ colliders,
149
+ * with issues for what the file has but the scene lost (normal map, material replaced by a style role, clip not loaded, clip mapping that names
150
+ * no clip) and for wrong color spaces. Pass a name (the loaded template) or a copy from model() (what the game shows). Text: assets.reportText(name)
151
+ * @example console.table(engine.assets.report('hero').issues);
152
+ * @param {string | any} nameOrRoot
153
+ */
154
+ report(nameOrRoot) {
155
+ const root = typeof nameOrRoot === 'string' ? null : nameOrRoot, e = root ? this._instances.get(root) : this.entries.get(nameOrRoot);
156
+ const gltf = e?.value;
157
+ if (!gltf?.scene) throw new Error(`assets.report: ${root ? 'that object is not a model copy from assets.model()' : `model "${nameOrRoot}" is not loaded yet (await engine.assets.model(...) first)`}`);
158
+ return reportGltf(gltf, e, root ?? gltf.scene, this.engine.renderer);
159
+ }
160
+ /** assets.report as text for the console / describe */
161
+ reportText(nameOrRoot) { return reportText(this.report(nameOrRoot)); }
162
+ /** Get the geometry of the first mesh in a model (for vegetation and bulk placement) */
163
+ async geometry(nameOrUrl) {
164
+ const e = this._resolve(nameOrUrl, 'model'), gltf = await this._fetch(e);
165
+ e.pinned = true; // the geometry was handed out and we cannot know who still uses it: trim does not free it
166
+ let g = null; gltf.scene.traverse(o => { if (!g && o.isMesh) g = o.geometry; });
167
+ return g;
168
+ }
169
+ /**
170
+ * Get a texture (name or path; .ktx2 works too). Color textures default to sRGB; pass { color: false } for normal/roughness maps.
171
+ * opts is part of the cache key: the same image fetched with different opts gives two separately configured textures (never silently reuses the first one's
172
+ * settings)
173
+ */
174
+ async texture(nameOrUrl, opts = {}) {
175
+ const base = this._resolve(nameOrUrl, 'texture');
176
+ const diff = Object.keys(opts).filter(k => k !== 'url' && JSON.stringify(opts[k]) !== JSON.stringify(base.opts[k]));
177
+ if (!diff.length) return this._fetch(base);
178
+ const key = nameOrUrl + '#' + JSON.stringify(Object.fromEntries(diff.sort().map(k => [k, opts[k]])));
179
+ let v = this.entries.get(key);
180
+ if (!v) this.entries.set(key, v = { type: 'texture', url: base.url, opts: { ...base.opts, ...opts }, promise: null, variantOf: nameOrUrl });
181
+ return this._fetch(v);
182
+ }
183
+
184
+ /**
185
+ * Release an asset and return its GPU memory (reloaded on next use). A texture is released together with all its opts variants.
186
+ * A model with copies still in the scene is not released yet; it is freed when the last copy is engine.remove'd (copies in use are never broken)
187
+ */
188
+ release(name) {
189
+ for (const [k, v] of this.entries) if (v.variantOf === name) { this.release(k); this.entries.delete(k); }
190
+ const e = this.entries.get(name); if (e) freeEntry(e);
191
+ }
192
+ /** Release every model with no copy in use (call after a level change; level calls it). Returns the names released */
193
+ trim() {
194
+ const freed = [];
195
+ for (const [k, e] of this.entries) if (e.type === 'model' && e.value && !e.users && !e.pinned) { freeEntry(e); freed.push(k); }
196
+ return freed;
197
+ }
198
+ /** How many copies of this model are in use (taken by model() and not yet engine.remove'd) */
199
+ users(name) { return this.entries.get(name)?.users ?? 0; }
200
+ /** Called when an object is fully removed (engine.remove calls it): decrements the usage count of model copies beneath it and stops their animators */
201
+ forget(obj) {
202
+ obj.traverse(o => {
203
+ const anim = this._animators.get(o); if (anim) { this._animators.delete(o); anim.dispose(); }
204
+ const e = this._instances.get(o); if (!e) return;
205
+ this._instances.delete(o);
206
+ if (--e.users <= 0 && e.releasePending) freeEntry(e);
207
+ });
208
+ }
209
+ /** Release all loaded assets and decoders (engine.dispose calls it) */
210
+ dispose() {
211
+ for (const e of this.entries.values()) { e.users = 0; freeEntry(e); }
212
+ this.draco?.dispose(); this.ktx2?.dispose();
213
+ }
214
+
215
+ /**
216
+ * Code-generated model (build returns an Object3D or BufferGeometry): built once per name + params, returns a copy (geometry returns the same instance).
217
+ * A generator written with `function` (not an arrow) can read this.palette = style.palette (the key includes it, so a new palette rebuilds).
218
+ * Cache key = name + generator source + params: outer variables build uses (colors, sizes, seeds in the closure...) must go in params,
219
+ * otherwise changing a variable still reads the stale cache. In dev, one name paired with different source warns once.
220
+ * Lookup order: files baked by npm run bake (public/models/baked/) -> the dev auto-cache (.threedog/cache, invalidated when code changes) -> build now.
221
+ * In dev, if the generator code is newer than the baked file, it builds now and warns once.
222
+ */
223
+ async cached(name, build, params) {
224
+ const src = String(build), seen = (this._cachedSrc ||= new Map()).get(name);
225
+ if (seen != null && seen !== src) warnOnce(coded('asset-name-clash', fmt(STRINGS.sameName, { name })));
226
+ else this._cachedSrc.set(name, src);
227
+ const key = 'cached:' + name + ':' + JSON.stringify(params ?? null) + ':' + JSON.stringify(this.engine.style.palette ?? null) + ':' + srcHash(src);
228
+ const e = this.entries.get(key) || this.entries.set(key, { type: 'model', url: name, opts: { build, params }, promise: null }).get(key);
229
+ const g = await this._fetch(e);
230
+ e.pinned = true; // neither copies nor geometry are counted: trim does not free it
231
+ return g.geometry ?? skeletonClone(g.scene);
232
+ }
233
+ /** Current usage: number of geometries and textures in GPU memory */
234
+ get memory() { return { ...this.engine.renderer.info.memory }; }
235
+
236
+ /**
237
+ * Skeletal animation: returns the state machine (Animator.js); it runs per frame, so gameplay timing must not read it.
238
+ * A manifest model entry's `animation` (clip names mapped to game action names, plain data) is the base; config wins per state.
239
+ * @example engine.assets.manifest({ models: { hero: { url: '/models/hero.glb', animation: { states: { attack: { clip: 'Slash', loop: false } } } } } });
240
+ * engine.assets.animate(await engine.assets.model('hero')).go('attack');
241
+ */
242
+ animate(root, config = {}) {
243
+ const m = this.mapping(root), src = this._instances.get(root);
244
+ const cfg = m ? { ...m, ...config, states: { ...m.states, ...config.states }, transitions: { ...m.transitions, ...config.transitions } } : config;
245
+ const a = new Animator(this.engine, root, cfg, m && { label: `manifest "${src.manifest}" models.${src.name}.animation`, states: Object.keys(m.states || {}).filter(k => !config.states?.[k]) });
246
+ this._animators.get(root)?.dispose(); // one animator per model: a new one replaces the old
247
+ this._animators.set(root, a);
248
+ return a;
249
+ }
250
+ /**
251
+ * A model copy's manifest animation mapping ({ states, transitions, fade }), or null. Characters read it so default clip names never shadow it.
252
+ * @example engine.assets.mapping(model)?.states.attack // { clip: 'Slash', loop: false }
253
+ * @param {import('three').Object3D} root @returns {{ states?: object, transitions?: object, fade?: number } | null}
254
+ */
255
+ mapping(root) { return this._instances.get(root)?.opts.animation ?? null; }
256
+ }