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,144 @@
1
+ // Built-in shader effects (used by render/materials.js): the engine uniforms they read, the GLSL chunks (also registered as
2
+ // THREE.ShaderChunk.threedog_*), the named patches world / clouds / wind / season, and placeholder textures.
3
+ import * as THREE from 'three';
4
+ import { engineUniform } from './engineUniforms.js';
5
+
6
+ // ---------- engine uniforms ----------
7
+ // Each engine has its own uniforms (engine.uniforms) and style pack. Built-in effects name engine uniforms, which patches.js swaps
8
+ // for the compiling renderer's engine (bindUniforms), so two engines on one page never share time, wind or cloud cover.
9
+ const UNIFORM_DEFAULTS = {
10
+ uTime: 0, // fixed seconds (engine.elapsed), written by the engine every fixed step
11
+ uWind: 1, // wind multiplier (driven by weather)
12
+ uCloud: 0.25, // cloud cover 0-1 (driven by weather)
13
+ uCloudShadow: 0, // darkest cloud shadow (style.clouds.shadow; 0 = no cloud shadows)
14
+ uCloudScale: 0.006, // cloud size (smaller = bigger clouds)
15
+ uCloudSpeed: () => new THREE.Vector2(0.012, 0.006), // cloud drift direction and speed
16
+ uWindFreq: 1, // sway frequency multiplier
17
+ uWindAmp: 1, // sway amplitude multiplier (look.wind.amplitude); every wind patch's amplitude is scaled by it
18
+ uFoliageTint: () => new THREE.Color(1, 1, 1), // season: foliage tint (driven by the sky module's calendar)
19
+ uGroundTint: () => new THREE.Color(1, 1, 1), // season: ground tint
20
+ uFoliageMix: 0, uGroundMix: 0, // season mode 'mix': how far the surface moves to the tint (0 = multiply, the default)
21
+ };
22
+ /**
23
+ * A fresh set of engine uniforms with the style pack's cloud and wind values (each engine owns one: engine.uniforms)
24
+ * @internal
25
+ * @param {any} [style]
26
+ * @returns {import('../types/core').EngineUniforms}
27
+ */
28
+ export function createUniforms(style = {}) {
29
+ const u = /** @type {any} */ ({});
30
+ for (const [k, v] of Object.entries(UNIFORM_DEFAULTS)) u[k] = engineUniform(k, typeof v === 'function' ? v() : v);
31
+ const c = style.clouds || {}, w = style.wind || {};
32
+ if (c.shadow != null) u.uCloudShadow.value = c.shadow;
33
+ if (c.scale != null) u.uCloudScale.value = c.scale;
34
+ if (c.speed) u.uCloudSpeed.value.set(c.speed[0], c.speed[1]);
35
+ if (w.frequency != null) u.uWindFreq.value = w.frequency;
36
+ return u;
37
+ }
38
+ const TEMPLATE = createUniforms(); // what built-in patches name; resolved to the compiling engine's uniforms
39
+
40
+ // ---------- GLSL ----------
41
+ /**
42
+ * Shared GLSL value noise: threedogHash(vec2), threedogNoise(vec2) (used by sky clouds and cloud shadows)
43
+ * @internal
44
+ */
45
+ export const NOISE_GLSL = `float threedogHash(vec2 p){ return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }
46
+ float threedogNoise(vec2 p){ vec2 i = floor(p), f = fract(p); f = f*f*(3.0-2.0*f);
47
+ return mix(mix(threedogHash(i), threedogHash(i+vec2(1,0)), f.x), mix(threedogHash(i+vec2(0,1)), threedogHash(i+vec2(1,1)), f.x), f.y); }`;
48
+
49
+ // GLSL pieces, also registered as THREE.ShaderChunk.threedog_* so a hand-written ShaderMaterial can #include them
50
+ // (put the matching engine.uniforms on it; threedog_wind_vertex needs `transformed`, `position` and #define THREEDOG_WIND_AMP;
51
+ // threedog_clouds_pars_fragment reads vThreedogWorld, declared by threedog_world_pars_fragment)
52
+ const CHUNKS = {
53
+ threedog_world_pars_vertex: 'varying vec3 vThreedogWorld;',
54
+ threedog_world_pars_fragment: 'varying vec3 vThreedogWorld;',
55
+ // same order as three's project_vertex: batching, then instancing, then the model matrix (InstancedMesh and BatchedMesh both work)
56
+ threedog_world_vertex: `
57
+ {
58
+ vec4 threedogP = vec4(transformed, 1.0);
59
+ #ifdef USE_BATCHING
60
+ threedogP = batchingMatrix * threedogP;
61
+ #endif
62
+ #ifdef USE_INSTANCING
63
+ threedogP = instanceMatrix * threedogP;
64
+ #endif
65
+ vThreedogWorld = (modelMatrix * threedogP).xyz;
66
+ }`,
67
+ threedog_clouds_pars_fragment: `
68
+ uniform float uTime; uniform float uCloud; uniform float uCloudShadow; uniform float uCloudScale; uniform vec2 uCloudSpeed;
69
+ ${NOISE_GLSL}
70
+ float threedogCloudLight(vec2 xz){
71
+ vec2 p = xz * uCloudScale + uCloudSpeed * uTime;
72
+ float n = threedogNoise(p) * 0.65 + threedogNoise(p * 2.3) * 0.35;
73
+ float c = smoothstep(1.0 - uCloud, 1.0 - uCloud + 0.25, n);
74
+ return 1.0 - c * uCloudShadow;
75
+ }`,
76
+ threedog_wind_pars_vertex: 'uniform float uTime; uniform float uWind; uniform float uWindFreq;',
77
+ // Higher vertices sway more; each tree / grass clump / batched object has its own phase from its own origin
78
+ threedog_wind_vertex: `
79
+ {
80
+ vec4 ipo = vec4(0.0, 0.0, 0.0, 1.0);
81
+ #ifdef USE_BATCHING
82
+ ipo = batchingMatrix * ipo;
83
+ #endif
84
+ #ifdef USE_INSTANCING
85
+ ipo = instanceMatrix * ipo;
86
+ #endif
87
+ vec3 ip = (modelMatrix * ipo).xyz;
88
+ #ifdef THREEDOG_WIND_CUSTOM
89
+ threedogWind(transformed, ip, position);
90
+ #else
91
+ float wt = uTime * uWindFreq;
92
+ float sw = sin(wt * (1.2 + 0.6 * uWind) + ip.x * 0.31 + ip.z * 0.23) * 0.6 + sin(wt * 2.9 + ip.x * 0.77 - ip.z * 0.4) * 0.4;
93
+ float k = max(position.y, 0.0) * THREEDOG_WIND_AMP * uWind;
94
+ transformed.x += sw * k + k * 0.4 * (uWind - 1.0); transformed.z += sw * k * 0.6;
95
+ #endif
96
+ }`,
97
+ };
98
+ Object.assign(THREE.ShaderChunk, CHUNKS);
99
+ /** Short text hash for cacheKeys @internal */
100
+ export const hashText = t => { let h = 7; for (let i = 0; i < t.length; i++) h = (Math.imul(h, 31) + t.charCodeAt(i)) | 0; return (h >>> 0).toString(36); };
101
+ const pick = (...keys) => Object.fromEntries(keys.map(k => [k, TEMPLATE[k]]));
102
+
103
+ // The engine's built-in effects as named patches (also readable as GLSL examples for your own patches)
104
+ /** @internal */
105
+ export const EFFECTS = {
106
+ // world-space position varying vThreedogWorld; clouds, the terrain detail texture and your own patches build on it (needs: ['world'])
107
+ world: () => ({ name: 'world', glsl: {
108
+ vertex: { pars: '#include <threedog_world_pars_vertex>', project_vertex: '#include <threedog_world_vertex>' },
109
+ fragment: { pars: '#include <threedog_world_pars_fragment>' } } }),
110
+ clouds: () => ({ name: 'clouds', needs: { patches: ['world'] }, uniforms: pick('uTime', 'uCloud', 'uCloudShadow', 'uCloudScale', 'uCloudSpeed'), glsl: {
111
+ fragment: { pars: '#include <threedog_clouds_pars_fragment>', lights_fragment_end:
112
+ 'reflectedLight.directDiffuse *= threedogCloudLight(vThreedogWorld.xz);\n reflectedLight.directSpecular *= threedogCloudLight(vThreedogWorld.xz);' } } }),
113
+ // wind(amplitude) or wind(amplitude, { glsl, uniforms, decl }): a style's own sway function replaces the default one (see StyleWind in types/style.d.ts)
114
+ wind: (amplitude, custom) => ({ name: 'wind', cacheKey: custom ? `${amplitude}|${hashText(custom.glsl)}` : amplitude, shadow: true,
115
+ uniforms: { ...pick('uTime', 'uWind', 'uWindFreq', 'uWindAmp'), ...custom?.uniforms }, glsl: {
116
+ vertex: { pars: `uniform float uWindAmp;
117
+ #define THREEDOG_WIND_AMP (${(+amplitude).toFixed(4)} * uWindAmp)
118
+ #include <threedog_wind_pars_vertex>` + (custom
119
+ ? `
120
+ #define THREEDOG_WIND_CUSTOM
121
+ ${custom.decl}
122
+ ${custom.glsl}` : ''), begin_vertex: '#include <threedog_wind_vertex>' } } }),
123
+ season: kind => {
124
+ const u = kind === 'ground' ? 'uGroundTint' : 'uFoliageTint', k = kind === 'ground' ? 'uGroundMix' : 'uFoliageMix';
125
+ // mix is 0 in the default 'multiply' mode (exactly the old `*=`); style.seasons.mode 'mix' sets it so the tint is blended in instead
126
+ return { name: 'season', cacheKey: kind, uniforms: pick(u, k), glsl: { fragment: { pars: `uniform vec3 ${u}; uniform float ${k};`,
127
+ color_fragment: `diffuseColor.rgb = ${k} > 0.0 ? mix(diffuseColor.rgb, ${u}, ${k}) : diffuseColor.rgb * ${u};` } } };
128
+ },
129
+ };
130
+
131
+ // Until the image loads, a 1x1 linear mid-gray placeholder (x2 in the shader = 1) leaves the ground unchanged instead of darkening it.
132
+ /**
133
+ * Neutral 1x1 linear stand-in for a texture that is still loading: 'detail' (0.5 gray, which the detail shader doubles to 1) or
134
+ * 'normal' (a flat normal). A plain Texture (not DataTexture), so the loaded image's source can replace it in place.
135
+ * @internal
136
+ * @param {'detail' | 'normal'} kind
137
+ * @returns {any}
138
+ */
139
+ export function placeholderTexture(kind) {
140
+ const c = document.createElement('canvas'); c.width = c.height = 1;
141
+ const g = c.getContext('2d'); g.fillStyle = kind === 'normal' ? 'rgb(128,128,255)' : 'rgb(128,128,128)'; g.fillRect(0, 0, 1, 1);
142
+ const t = new THREE.Texture(c); t.needsUpdate = true;
143
+ return t;
144
+ }
@@ -0,0 +1,23 @@
1
+ // Engine uniforms (helper of patches.js): a patch uniform that is the engine's own (time, cloud cover...), resolved per renderer when a program compiles.
2
+ // An engine uniform carries its name under this key; at compile time it is swapped for the same-named uniform of the engine
3
+ // that owns the renderer (bindUniforms), and a renderer without an engine keeps the object it was given.
4
+ const ENGINE_UNIFORM = Symbol.for('threedog.engineUniform');
5
+ const BOUND = new WeakMap(); // renderer -> its engine's uniforms
6
+ /**
7
+ * A uniform object { value } tagged as the engine uniform `name` (resolved per renderer at compile time)
8
+ * @internal
9
+ * @param {string} name
10
+ * @param {any} value
11
+ * @returns {{ value: any }}
12
+ */
13
+ export function engineUniform(name, value) { return /** @type {any} */ ({ value, [ENGINE_UNIFORM]: name }); }
14
+ /**
15
+ * Programs this renderer compiles from now on read these engine uniforms (called once per engine)
16
+ * @internal
17
+ * @param {any} renderer
18
+ * @param {Record<string, { value: any }>} uniforms
19
+ * @returns {void}
20
+ */
21
+ export function bindUniforms(renderer, uniforms) { BOUND.set(renderer, uniforms); }
22
+ export const sameUniform = (a, b) => a === b || (!!a[ENGINE_UNIFORM] && a[ENGINE_UNIFORM] === b[ENGINE_UNIFORM]);
23
+ export const resolveUniform = (u, renderer) => (u?.[ENGINE_UNIFORM] && renderer && BOUND.get(renderer)?.[u[ENGINE_UNIFORM]]) || u;
package/render/fuse.js ADDED
@@ -0,0 +1,84 @@
1
+ // Fused post pass: several effects that each carry a small GLSL snippet (PostEffect.fuse) run as ONE fullscreen pass, so a chain of
2
+ // light color effects (LUT, grain, vignette...) costs one read and one write of the screen instead of one per effect.
3
+ // Why in the engine: only the engine knows which effects are neighbors in a slot; the effects themselves stay plain data + GLSL.
4
+ import * as THREE from 'three';
5
+ import { Pass, FullScreenQuad } from 'three/addons/postprocessing/Pass.js';
6
+ /** @import { PostFuse } from './PostFX' */
7
+
8
+ const VERT = 'varying vec2 vUv; void main(){ vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }';
9
+ // Helpers every snippet may call
10
+ const HELPERS = 'float fxHash(vec2 p){ vec3 q = fract(vec3(p.xyx) * 0.1031); q += dot(q, q.yzx + 33.33); return fract((q.x + q.y) * q.z); }';
11
+ const EMPTY = { float: () => 0, int: () => 0, vec2: () => new THREE.Vector2(), vec3: () => new THREE.Vector3(), vec4: () => new THREE.Vector4() };
12
+
13
+ export class FusedPass extends Pass {
14
+ /**
15
+ * @param {{ name: string, params: Record<string, any>, _def: { fuse: PostFuse } }[]} items effect handles, in run order; their
16
+ * params are read live, so refresh() after a params change is enough
17
+ */
18
+ constructor(items) {
19
+ super();
20
+ this.items = items;
21
+ this.time = 0;
22
+ const uniforms = { tDiffuse: { value: null }, uTime: { value: 0 }, uResolution: { value: new THREE.Vector2() } }, decl = [], body = [], owner = {};
23
+ for (const e of items) {
24
+ const f = e._def.fuse;
25
+ for (const [u, type] of Object.entries(f.uniforms ?? {})) {
26
+ if (u in uniforms) throw new Error(`post effect '${e.name}': fuse uniform '${u}' is already taken by ${owner[u] ?? 'the engine'}; prefix your uniform names with the effect name`);
27
+ uniforms[u] = { value: EMPTY[type]?.() ?? null }; owner[u] = `'${e.name}'`;
28
+ decl.push(`uniform ${type} ${u};`);
29
+ }
30
+ body.push(` { // ${e.name}\n${f.glsl}\n }`);
31
+ }
32
+ this.material = new THREE.ShaderMaterial({ uniforms, vertexShader: VERT,
33
+ fragmentShader: `uniform sampler2D tDiffuse; uniform float uTime; uniform vec2 uResolution; ${decl.join(' ')}\nvarying vec2 vUv;\n${HELPERS}\n` +
34
+ `void main(){\n vec4 color = texture2D(tDiffuse, vUv);\n${body.join('\n')}\n gl_FragColor = color;\n}` });
35
+ this.quad = new FullScreenQuad(this.material);
36
+ this.refresh();
37
+ }
38
+ /** Copy every effect's current values into the uniforms */
39
+ refresh() {
40
+ const u = this.material.uniforms;
41
+ for (const e of this.items) for (const [k, v] of Object.entries(e._def.fuse.values?.(e.params) ?? {})) {
42
+ if (!(k in u)) throw new Error(`post effect '${e.name}': fuse.values() returned '${k}', which fuse.uniforms does not declare`);
43
+ u[k].value = v;
44
+ }
45
+ }
46
+ setSize() {}
47
+ render(renderer, writeBuffer, readBuffer, deltaTime) {
48
+ const u = this.material.uniforms;
49
+ this.time = (this.time + deltaTime) % 64; // wrapped so grain keeps its precision in a long session
50
+ u.tDiffuse.value = readBuffer.texture; u.uTime.value = this.time; u.uResolution.value.set(readBuffer.width, readBuffer.height);
51
+ renderer.setRenderTarget(this.renderToScreen ? null : writeBuffer);
52
+ this.quad.render(renderer);
53
+ }
54
+ dispose() { this.material.dispose(); this.quad.dispose(); }
55
+ }
56
+
57
+ /**
58
+ * Split an ordered, enabled effect list into entries for the chain: runs of consecutive fuse effects in one slot become one group
59
+ * (an array); an effect whose fuse has reads: true starts a new group because it samples the pass input, which earlier snippets
60
+ * of the same group have not yet changed. Everything else stays as it is.
61
+ * @param {any[]} on
62
+ * @returns {(any | any[])[]}
63
+ */
64
+ export function groupFuse(on) {
65
+ const out = [];
66
+ for (const e of on) {
67
+ const f = e._def.fuse, last = out[out.length - 1];
68
+ if (f && Array.isArray(last) && last[0].slot === e.slot && !f.reads) last.push(e);
69
+ else out.push(f ? [e] : e);
70
+ }
71
+ return out;
72
+ }
73
+
74
+ // Only the buffer the scene render wrote holds scene depth: after a pass that swaps buffers, readBuffer.depthTexture is another
75
+ // target's (a fullscreen quad's, or stale). A depth reader behind such a pass would silently find nothing, so the chain refuses it.
76
+ export function checkDepthOrder(chain) {
77
+ let swapped = null;
78
+ for (const e of chain) {
79
+ if (e._def?.needsDepth && swapped)
80
+ throw new Error(`post effect '${e.name}' reads scene depth (needsDepth) but runs after '${swapped}', which swaps buffers, so the depth it would read is not the scene's; ` +
81
+ `give '${e.name}' a lower order or an earlier slot than '${swapped}', or turn one of them off`);
82
+ if (e._impl.needsSwap && !e._impl.keepsDepth) swapped ??= e.name;
83
+ }
84
+ }
@@ -0,0 +1,100 @@
1
+ // The `lighting` surface patch and the toon ramp: extra, optional light shaping on three's lit materials (lambert, phong, standard, toon).
2
+ // three has no "shadow color": a shadow just removes the sun's light. The patch therefore works after the lights are summed (lights_fragment_end):
3
+ // it re-reads the first directional light (three sorts shadow-casting lights first, so that is the sun) and its shadow-map value for this
4
+ // pixel, and shapes the result from them. Limits: one directional light is considered (point / spot lights are untouched); wrap does not
5
+ // follow a toon ramp (a toon ramp is the better tool there); cloud shadows are not "shadow" for shadowTint.
6
+ // All values are uniforms: materials differing only in numbers or colors share one program (the cacheKey holds which features are on).
7
+ import * as THREE from 'three';
8
+ import { checkOptions } from '../core/validate.js';
9
+ import { hashText } from './effects.js';
10
+ import { declareUniforms } from './uniformDecl.js';
11
+
12
+ const KEYS = ['wrap', 'shadowTint', 'rim', 'glsl', 'uniforms'];
13
+ const lum = 'vec3(0.2126, 0.7152, 0.0722)';
14
+
15
+ // Functions need getShadow and the light uniforms, which exist only after these includes: they go after shadowmap_pars_fragment
16
+ const SUN = `float threedogSunShadow(){
17
+ #if NUM_DIR_LIGHTS > 0 && defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
18
+ return receiveShadow ? getShadow( directionalShadowMap[ 0 ], directionalLightShadows[ 0 ].shadowMapSize, directionalLightShadows[ 0 ].shadowIntensity,
19
+ directionalLightShadows[ 0 ].shadowBias, directionalLightShadows[ 0 ].shadowRadius, vDirectionalShadowCoord[ 0 ] ) : 1.0;
20
+ #else
21
+ return 1.0;
22
+ #endif
23
+ }`;
24
+
25
+ /**
26
+ * @typedef {{ wrap?: number, shadowTint?: { color: import('../types/common').ColorLike, strength?: number, soft?: number },
27
+ * rim?: { color: import('../types/common').ColorLike, strength?: number, power?: number, shadowSide?: number }, glsl?: string, uniforms?: Record<string, any> }} LightingOptions
28
+ */
29
+
30
+ /**
31
+ * The `lighting` patch (see MaterialLighting in types/style.d.ts). With `glsl` your function replaces the built-in shaping.
32
+ * @internal use materialSpec.lighting, style.lighting or applyEffects(mat, { patches: [lightingPatch(opts)] })
33
+ * @param {LightingOptions} o
34
+ * @param {string} [label]
35
+ * @returns {import('./patches.js').ShaderPatch}
36
+ */
37
+ export function lightingPatch(o, label = 'lighting') {
38
+ checkOptions(label, o, KEYS);
39
+ const { wrap, shadowTint: st, rim } = o;
40
+ if (o.glsl && !/void\s+threedogLighting\s*\(/.test(o.glsl)) throw new Error(`${label}.glsl must define \`void threedogLighting(inout ReflectedLight light, vec3 normal, vec3 viewDir, vec3 sunDir, float sunShadow, vec3 albedo)\`: normal and viewDir are in view space, sunDir points to the sun, sunShadow is 1 lit / 0 in shadow (1 without shadows); change light.directDiffuse / indirectDiffuse (the lights are already summed)`);
41
+ if (st && st.color === undefined) throw new Error(`${label}.shadowTint needs a color: { color: shadowColor, strength: 0.6 }`);
42
+ if (rim && rim.color === undefined) throw new Error(`${label}.rim needs a color: { color: rimColor, strength: 0.4, power: 3 }`);
43
+ const own = declareUniforms(label + '.uniforms', o.uniforms);
44
+ const u = { ...own.uniforms };
45
+ let pars = `uniform float uLitWrap; uniform vec3 uLitShadowColor; uniform vec2 uLitShadow; uniform vec3 uLitRimColor; uniform vec3 uLitRim;\n${own.decl}`;
46
+ let code = '#if NUM_DIR_LIGHTS > 0\n float tdSun = threedogSunShadow(); vec3 tdL = directionalLights[ 0 ].direction; float tdNL = dot( normal, tdL );\n';
47
+ if (o.glsl) code += ' threedogLighting( reflectedLight, normal, normalize( vViewPosition ), tdL, tdSun, diffuseColor.rgb );\n';
48
+ else {
49
+ if (wrap !== undefined) {
50
+ // half-lambert: the diffuse term (n.l + w) / (1 + w); only the part beyond plain Lambert is added, with the sun's color and shadow
51
+ code += ' reflectedLight.directDiffuse += ( max( ( tdNL + uLitWrap ) / ( 1.0 + uLitWrap ), 0.0 ) - max( tdNL, 0.0 ) ) * directionalLights[ 0 ].color * tdSun * RECIPROCAL_PI * diffuseColor.rgb;\n';
52
+ u.uLitWrap = { value: wrap };
53
+ }
54
+ if (st) {
55
+ // 1 - lit: in the shadow map, or turned away from the sun (soft = how wide the terminator is, in n.l). The hue moves, the brightness stays.
56
+ const c = new THREE.Color(st.color);
57
+ code += ` { float tdK = ( 1.0 - tdSun * smoothstep( 0.0, uLitShadow.y, tdNL ) ) * uLitShadow.x;
58
+ vec3 tdHue = uLitShadowColor / max( dot( uLitShadowColor, ${lum} ), 0.001 );
59
+ reflectedLight.indirectDiffuse = mix( reflectedLight.indirectDiffuse, reflectedLight.indirectDiffuse * tdHue, tdK ); }\n`;
60
+ u.uLitShadowColor = { value: c }; u.uLitShadow = { value: new THREE.Vector2(st.strength ?? 0.5, Math.max(st.soft ?? 0.3, 0.001)) };
61
+ }
62
+ if (rim) {
63
+ // fresnel-like edge light, added to the ambient part; shadowSide 1 = only on the side facing away from the sun
64
+ code += ' reflectedLight.indirectDiffuse += uLitRimColor * ( pow( 1.0 - clamp( dot( normal, normalize( vViewPosition ) ), 0.0, 1.0 ), uLitRim.y ) * mix( 1.0, 1.0 - clamp( tdNL, 0.0, 1.0 ), uLitRim.z ) * uLitRim.x );\n';
65
+ u.uLitRimColor = { value: new THREE.Color(rim.color) }; u.uLitRim = { value: new THREE.Vector3(rim.strength ?? 0.4, rim.power ?? 3, rim.shadowSide ?? 0) };
66
+ }
67
+ }
68
+ code += '#endif';
69
+ for (const n of ['uLitWrap', 'uLitShadowColor', 'uLitShadow', 'uLitRimColor', 'uLitRim']) u[n] ??= { value: n === 'uLitWrap' ? 0 : n === 'uLitShadow' ? new THREE.Vector2() : n === 'uLitRim' ? new THREE.Vector3() : new THREE.Color() };
70
+ const key = o.glsl ? 'g' + hashText(o.glsl) : `${wrap !== undefined ? 'w' : ''}${st ? 's' : ''}${rim ? 'r' : ''}`;
71
+ return { name: 'lighting', cacheKey: key, uniforms: u, glsl: { fragment: { pars, shadowmap_pars_fragment: (o.glsl ? o.glsl + '\n' : '') + SUN, lights_fragment_end: code } } };
72
+ }
73
+
74
+ // ---------- toon ramp ----------
75
+ const rampCache = new Map();
76
+ /**
77
+ * The gradientMap of a toon material from `ramp` (grays or colors, dark to light) and `soften` (0 = hard bands, 1 = bands melt into each other).
78
+ * Color entries tint the light of that band (a cool band in the shade); a gray number n is the light's strength there.
79
+ * @internal
80
+ * @param {(number | import('../types/common').ColorLike)[]} ramp
81
+ * @param {number} [soften]
82
+ * @returns {THREE.DataTexture}
83
+ */
84
+ export function rampTexture(ramp, soften = 0) {
85
+ if (!Array.isArray(ramp) || ramp.length < 2) throw new Error('toon ramp must be an array of at least 2 grays or colors, dark to light, e.g. ramp: [0.35, 0.7, 1] or three colors');
86
+ const key = JSON.stringify([ramp, soften]);
87
+ if (rampCache.has(key)) return rampCache.get(key);
88
+ const cols = ramp.map(v => typeof v === 'number' && v <= 1 ? new THREE.Color(v, v, v) : new THREE.Color(v));
89
+ const soft = Math.max(0, Math.min(1, soften)), W = soft > 0 ? 128 : cols.length, N = cols.length, data = new Uint16Array(W * 4), c = new THREE.Color();
90
+ for (let i = 0; i < W; i++) {
91
+ const x = (i + 0.5) / W * N, b = Math.round(x), d = x - b; // b = nearest band border
92
+ if (soft > 0 && b > 0 && b < N && Math.abs(d) < soft / 2) c.copy(cols[b - 1]).lerp(cols[b], THREE.MathUtils.smoothstep(d, -soft / 2, soft / 2));
93
+ else c.copy(cols[Math.min(N - 1, Math.floor(x))]);
94
+ data.set([THREE.DataUtils.toHalfFloat(c.r), THREE.DataUtils.toHalfFloat(c.g), THREE.DataUtils.toHalfFloat(c.b), THREE.DataUtils.toHalfFloat(1)], i * 4);
95
+ }
96
+ const t = new THREE.DataTexture(data, W, 1, THREE.RGBAFormat, THREE.HalfFloatType);
97
+ t.minFilter = t.magFilter = soft > 0 ? THREE.LinearFilter : THREE.NearestFilter; t.needsUpdate = true;
98
+ rampCache.set(key, t);
99
+ return t;
100
+ }
@@ -0,0 +1,18 @@
1
+ // Default lights every engine has (engine.lights, the mechanism): a directional "sun" + hemisphere ambient, plain white / neutral gray, no
2
+ // shadows. They exist only so a scene (and the gray placeholders) is never black; they are not a tuned look: sun color and intensity curves,
3
+ // sky colors, fog, shadows and exposure come from the style pack through the sky module, which drives these same two lights instead of
4
+ // adding its own. A game that wants different lighting edits or hides them (engine.lights.sun.visible = false) and adds its own three.js lights,
5
+ // before engine.start(): a light count that changes during play recompiles shaders (recipes/09 "Lights and stalls", lightPool() for many lights).
6
+ import * as THREE from 'three';
7
+
8
+ /** @param {any} engine @returns {{ sun: THREE.DirectionalLight, hemi: THREE.HemisphereLight }} */
9
+ export function createDefaultLights(engine, { add = true } = {}) {
10
+ const hemi = new THREE.HemisphereLight(0xffffff, 0x555555, 1.2);
11
+ const sun = new THREE.DirectionalLight(0xffffff, 2);
12
+ sun.position.set(40, 80, 30); // above and to the side, so faces read with some shading
13
+ sun.castShadow = false; // placeholder lighting casts no shadows; an installed sky module turns them on (sizes from style.sky.shadow)
14
+ // add: false (createEngine({ lights: false })): the objects still exist so engine.lights.sun / hemi and the sky module never hit undefined, but they
15
+ // are not in the scene, so nothing is lit by them and they cost no shader light slots; the game brings all its own lights
16
+ if (add) engine.scene.add(hemi, sun, sun.target);
17
+ return { sun, hemi };
18
+ }
@@ -0,0 +1,161 @@
1
+ // look.materials and look.surface (render/materials.js reads them when it makes a material).
2
+ // Why a file of its own: materials.js is near the size cap, and the two parts share one rule: a verb changes what makeMaterial does NEXT time
3
+ // (a Material already handed out is not touched, catalog / describe say appliesTo; rebuilding made materials from the spec costs a recompile each, so it is not done).
4
+ // Exception: plain numeric / color properties (LIVE_KEYS below) are written to the already-made materials of that role at once; they need no recompile.
5
+ // look.materials set({ wool: { roughness: 0.4 } }) merge into the role's spec (style.materials[role] stays below as the style layer)
6
+ // patch(name, shaderPatch, { roles }) add a named ShaderPatch (render/patches.js) to materials made for those roles
7
+ // replace(role, Material | fn) a role is this Material (cloned) / this (params, purpose, engine) => Material
8
+ // look.surface set({ lighting: { wrap, shadowTint, rim }, detail: {...}, ramp: [...], soften }) defaults for every spec-made material
9
+ // patch('lighting' | 'detail', glsl) the shared threedogLighting / threedogDetailSample function
10
+ import { defineLookPart } from '../core/look/part.js';
11
+ import * as THREE from 'three';
12
+ import { codedError } from '../core/errorHints.js';
13
+ import { isPlainObject as isPlain } from '../core/util.js';
14
+ import { rampTexture } from './lighting.js';
15
+
16
+ const asGlsl = v => (typeof v === 'string' ? { glsl: v } : v); // a hook value is a GLSL string or { glsl, uniforms }
17
+
18
+ /** A material spec key makeMaterial understands: its own keys (materials.js SPEC_KEYS + type) or a property of one of the three.js types it makes */
19
+ const probes = []; // one probe Material per three.js type, made on first use; page-wide on purpose (they are never rendered)
20
+ function knownSpecKey(k) {
21
+ if (['type', 'steps', 'ramp', 'soften', 'repeat', 'wrap', 'detail', 'lighting'].includes(k)) return true;
22
+ if (!probes.length) probes.push(...[THREE.MeshPhysicalMaterial, THREE.MeshLambertMaterial, THREE.MeshPhongMaterial, THREE.MeshToonMaterial, THREE.MeshBasicMaterial].map(C => new C()));
23
+ return probes.some(m => k in m);
24
+ }
25
+ /** Plain material properties that change at once on materials already made for the role (no shader change, so no recompile); every other key is for new materials only */
26
+ export const LIVE_KEYS = ['color', 'emissive', 'emissiveIntensity', 'roughness', 'metalness', 'opacity', 'envMapIntensity', 'shininess', 'specular'];
27
+ const COLOR_KEYS = new Set(['color', 'emissive', 'specular']);
28
+ /** Every Material made per role, per engine, as weak refs (a disposed material that nobody holds drops out) */
29
+ const LIVE = new WeakMap();
30
+ const liveOf = e => LIVE.get(e) ?? LIVE.set(e, new Map()).get(e);
31
+ /** The last Material made per role, per engine (look.materials.object(role)); kept here so materials.js never touches the part's fields */
32
+ const MADE = new WeakMap();
33
+ const madeOf = e => MADE.get(e) ?? MADE.set(e, new Map()).get(e);
34
+
35
+ /** Materials: role names are open, so the part grows `<role>.<specKey>` params as the style or a game mentions them */
36
+ export function defineMaterialsLook(e, purposes) {
37
+ const M = e.style.materials ?? {};
38
+ const params = {}, style = {};
39
+ const grow = (into, key) => { into[key] = { type: 'any', default: null, neutral: true, desc: 'a spec key of this role (type, color, roughness, steps, ramp, detail, lighting ...); null = not overridden' }; };
40
+ for (const [role, spec] of Object.entries(M)) if (isPlain(spec)) for (const [k, v] of Object.entries(spec)) { grow(params, `${role}.${k}`); style[`${role}.${k}`] = v; }
41
+ const made = madeOf(e);
42
+ const part = defineLookPart(e, {
43
+ id: 'materials', group: 'surface', module: 'core', docs: ['recipes/52-look.md'], params, style: () => style, appliesTo: `materials made after the change, except the live keys (${LIVE_KEYS.join(', ')}), which also change the materials already made for that role; type, steps, ramp, soften, repeat, wrap, detail, lighting, patch and replace are for new materials only`,
44
+ applyAtStart: false,
45
+ apply(v, changed) { // live keys: write them to the already-made materials of the role (a cleared key goes back to the style value, or stays when the style gave none)
46
+ for (const k of changed) {
47
+ const i = k.indexOf('.'), role = k.slice(0, i), prop = k.slice(i + 1);
48
+ if (i < 0 || !LIVE_KEYS.includes(prop)) continue;
49
+ const val = v[k] ?? style[k];
50
+ if (val == null) continue;
51
+ for (const ref of liveOf(e).get(role) ?? []) {
52
+ const m = ref.deref();
53
+ if (!m) { liveOf(e).get(role).delete(ref); continue; }
54
+ if (!(prop in m)) continue;
55
+ if (COLOR_KEYS.has(prop)) m[prop].set(val); else m[prop] = val;
56
+ }
57
+ }
58
+ },
59
+ // a function, not a map: look.materials.object('wool') is the last Material made for that role, object() all of them
60
+ object: () => role => (role === undefined ? Object.fromEntries(made) : made.get(role)),
61
+ // set({ wool: { roughnes: 1 } }) used to add the typo as a new key; now a role key must be one makeMaterial reads (review M7).
62
+ // normalize runs for set() and engine.debug.override alike, before the values are checked
63
+ normalize(p) {
64
+ const grown = {};
65
+ for (const [role, spec] of Object.entries(p)) if (isPlain(spec)) for (const k of Object.keys(spec)) if (!part.has(`${role}.${k}`)) {
66
+ if (!knownSpecKey(k)) throw codedError('look-param', `look.materials.set(): ${role}.${k} is not a material spec key (type, color, roughness, steps, ramp, detail, lighting or a three.js material property)`);
67
+ grow(grown, `${role}.${k}`);
68
+ }
69
+ if (Object.keys(grown).length) part.extend(grown);
70
+ return p;
71
+ },
72
+ hooks: { '<name>': { signature: 'a ShaderPatch { name, glsl, uniforms, needs } (render/patches.js); patch(name, spec, { roles: ["wool"] }) adds it to materials made for those roles (none = all)', scope: ['fragment', 'vertex'] } },
73
+ replace: { accepts: "replace('wool', Material | (params, purpose, engine) => Material); replace('wool', null) gives the role back to the style", loses: ['the role spec: type, steps, ramp, detail, lighting ... and look.materials.set keys for that role'] },
74
+ verbs: {
75
+ patch: { signature: 'patch(name, shaderPatch | null, { roles, owner })',
76
+ take(bad, name, spec, { roles, owner } = {}) {
77
+ if (typeof name !== 'string' || !name) bad("name is the patch's name, e.g. patch('snap', { glsl: {...} }, { roles: ['wool'] })");
78
+ if (spec != null && !isPlain(spec)) bad(`the patch is a ShaderPatch object { glsl: { vertex|fragment: {...} }, uniforms, needs } (render/patches.js); got ${typeof spec}`);
79
+ return [{ [`hook:${name}`]: spec == null ? null : { patch: { name, ...spec }, roles: roles ?? null } }, owner];
80
+ } },
81
+ replace: { signature: 'replace(role, Material | (params, purpose, engine) => Material | null, { owner })',
82
+ take(bad, role, impl, { owner } = {}) {
83
+ if (typeof role !== 'string') bad("the first argument is the role name, e.g. replace('wool', new THREE.MeshMatcapMaterial(...))");
84
+ if (impl != null && !impl.isMaterial && typeof impl !== 'function') bad(`give a three.js Material or a function (params, purpose, engine) => Material; got ${typeof impl}`);
85
+ return [{ [`replace:${role}`]: impl ?? null }, owner];
86
+ } },
87
+ },
88
+ });
89
+ return part;
90
+ }
91
+
92
+ /** What the games and debug layers changed for a role: { key: value } to lay over the role's spec (makeMaterial) */
93
+ export function materialOverrides(eng, role) {
94
+ const p = eng?.look?.materials, out = {};
95
+ if (!p) return out;
96
+ for (const [k] of p.resolved(role + '.')) { const v = p.top(k); if (v != null) out[k.slice(role.length + 1)] = v; }
97
+ return out;
98
+ }
99
+ /** replace(role, ...) from a game / debug layer, else undefined */
100
+ export const materialReplace = (eng, role) => eng?.look?.materials?.top(`replace:${role}`) ?? undefined;
101
+ /** Patches added with look.materials.patch for this role */
102
+ export function materialPatches(eng, role) {
103
+ const p = eng?.look?.materials, out = [];
104
+ if (p) for (const [, v] of p.resolved('hook:')) if (v && (!v.roles || v.roles.includes(role))) out.push(v.patch);
105
+ return out;
106
+ }
107
+ /** Remember the last Material made for a role (look.materials.object(role)) */
108
+ export function materialMade(eng, role, m) {
109
+ if (!eng) return;
110
+ madeOf(eng).set(role, m);
111
+ (liveOf(eng).get(role) ?? liveOf(eng).set(role, new Set()).get(role)).add(new WeakRef(m));
112
+ }
113
+
114
+ const needColor = name => v => (isPlain(v) && v.color !== undefined ? null : `needs a color, e.g. { color: '#334', strength: 0.5 } (${name})`);
115
+ /** Surface: the pack-wide lighting / detail / toon ramp every spec-made material starts from */
116
+ export function defineSurfaceLook(e) {
117
+ const L = e.style.lighting ?? {};
118
+ const keep = o => Object.fromEntries(Object.entries(o).filter(([, v]) => v != null));
119
+ const num = v => (typeof v === 'number' ? null : 'must be a number');
120
+ defineLookPart(e, {
121
+ id: 'surface', appliesTo: 'materials made after the change', group: 'surface', module: 'core', docs: ['recipes/52-look.md'],
122
+ params: {
123
+ 'lighting.wrap': { type: 'any', default: null, neutral: true, check: num, desc: 'half-lambert wrap 0-1: how far light bends past the terminator (softer shade edge); null = off' },
124
+ 'lighting.shadowTint': { type: 'any', default: null, neutral: true, check: needColor('shadowTint'), desc: '{ color, strength?, soft? } hue of the shaded side; null = off' },
125
+ 'lighting.rim': { type: 'any', default: null, neutral: true, check: needColor('rim'), desc: '{ color, strength?, power?, shadowSide? } edge light; null = off' },
126
+ detail: { type: 'any', default: null, neutral: true, check: v => (isPlain(v) ? null : 'must be a detail object, e.g. { noise: "grain", strength: 0.2 } (render/detail.js)'), desc: 'detail layer added to every spec-made material (a spec\'s own detail wins; detail: false in a spec opts out); null = none' },
127
+ ramp: { type: 'any', default: null, neutral: true, check: v => { try { rampTexture(v); return null; } catch (err) { return err.message; } }, desc: 'toon ramp for every toon material, grays or colors dark to light; null = each spec\'s own steps / ramp' },
128
+ soften: { type: 'any', default: null, neutral: true, check: num, desc: 'how much the toon bands melt into each other 0-1; used with ramp' },
129
+ },
130
+ style: () => keep({ 'lighting.wrap': L.wrap, 'lighting.shadowTint': L.shadowTint, 'lighting.rim': L.rim, 'hook:lighting': L.glsl ? { glsl: L.glsl, uniforms: L.uniforms } : null }),
131
+ hooks: {
132
+ lighting: { signature: 'void threedogLighting(inout ReflectedLight light, vec3 normal, vec3 viewDir, vec3 sunDir, float sunShadow, vec3 albedo)', scope: ['fragment'], example: 'engine.look.surface.patch("lighting", glslString)' },
133
+ detail: { signature: 'vec4 threedogDetailSample(vec2 p) // rgb + height 0-1', scope: ['fragment'], example: 'engine.look.surface.patch("detail", glslString)' },
134
+ },
135
+ noReplace: 'to swap a whole material, use engine.look.materials.replace(role, ...)',
136
+ });
137
+ }
138
+
139
+ /** The pack-wide lighting options for makeMaterial: style.lighting under any look.surface change (undefined without the part) */
140
+ export function surfaceLighting(eng) {
141
+ const p = eng?.look?.surface;
142
+ if (!p) return eng?.style?.lighting;
143
+ const o = keep3({ wrap: p.value('lighting.wrap'), shadowTint: p.value('lighting.shadowTint'), rim: p.value('lighting.rim'), ...asGlsl(p.value('hook:lighting')) });
144
+ return Object.keys(o).length ? o : undefined;
145
+ }
146
+ /** The pack-wide detail options (with the detail hook's glsl), or undefined */
147
+ export function surfaceDetail(eng) {
148
+ const p = eng?.look?.surface, d = p?.value('detail');
149
+ return d ? { ...asGlsl(p.value('hook:detail')), ...d } : undefined;
150
+ }
151
+ /** The pack-wide toon ramp { ramp, soften }, or undefined */
152
+ export function surfaceRamp(eng) {
153
+ const p = eng?.look?.surface, r = p?.value('ramp');
154
+ return r ? { ramp: r, soften: p.value('soften') ?? 0 } : undefined;
155
+ }
156
+ function keep3(o) { return Object.fromEntries(Object.entries(o).filter(([, v]) => v != null)); }
157
+ /** The ground's detail options: look.ground (style.terrain.detail under any change, plus its detail glsl hook), or style.terrain.detail without the part */
158
+ export function groundDetail(eng) {
159
+ const p = eng?.look?.ground, d = p ? p.value('detail') : eng?.style?.terrain?.detail;
160
+ return d ? { ...asGlsl(p?.value('hook:detail')), ...d } : undefined;
161
+ }