threedog 1.0.1 → 1.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 (364) hide show
  1. package/CHANGELOG.md +90 -0
  2. package/README.md +1 -1
  3. package/core/assets/Animator.js +41 -3
  4. package/core/assets/Assets.js +100 -24
  5. package/core/assets/assetEntry.js +73 -20
  6. package/core/assets/assetHot.js +68 -16
  7. package/core/assets/assetLoad.js +6 -6
  8. package/core/assets/assetLod.js +9 -2
  9. package/core/assets/assetManifest.js +12 -2
  10. package/core/assets/assetPart.js +54 -0
  11. package/core/assets/ik.js +271 -0
  12. package/core/assets/modelNeeds.js +37 -0
  13. package/core/assets/namedModel.js +102 -29
  14. package/core/assets/nodeVisibility.js +15 -0
  15. package/core/audio/Audio.js +36 -4
  16. package/core/audio/audioReverb.js +99 -0
  17. package/core/audio/audioRules.js +1 -1
  18. package/core/audio/audioVoice.js +1 -1
  19. package/core/base/Events.js +14 -4
  20. package/core/base/Random.js +1 -1
  21. package/core/base/Vars.js +1 -1
  22. package/core/base/docRef.js +51 -0
  23. package/core/base/errorCodes.js +178 -126
  24. package/core/base/errorHints.js +9 -7
  25. package/core/base/errors.js +25 -10
  26. package/core/base/events.generated.js +2 -0
  27. package/core/base/freeParts.js +76 -0
  28. package/core/base/math.js +28 -0
  29. package/core/base/sections.js +5 -5
  30. package/core/base/validate.js +31 -3
  31. package/core/engine/Engine.js +16 -6
  32. package/core/engine/Loading.js +5 -3
  33. package/core/engine/copies.js +1 -1
  34. package/core/engine/headlessLoad.js +4 -1
  35. package/core/engine/lifecycle.js +32 -16
  36. package/core/engine/loop.js +71 -27
  37. package/core/engine/moduleSlots.js +2 -2
  38. package/core/engine/moduleTypes.js +3 -3
  39. package/core/engine/modules.js +65 -39
  40. package/core/engine/page.js +6 -3
  41. package/core/engine/services.js +6 -5
  42. package/core/engine/startup.js +5 -5
  43. package/core/input/Input.js +28 -14
  44. package/core/input/inputContext.js +28 -16
  45. package/core/input/inputKeyboard.js +31 -3
  46. package/core/input/inputPad.js +4 -0
  47. package/core/input/inputPointer.js +2 -1
  48. package/core/input/inputSeat.js +1 -1
  49. package/core/inspect/Budget.js +109 -19
  50. package/core/inspect/DebugOverrides.js +28 -4
  51. package/core/inspect/Describe.js +17 -9
  52. package/core/inspect/Inspect.js +4 -2
  53. package/core/inspect/InspectMaterials.js +3 -1
  54. package/core/inspect/InspectPerf.js +19 -9
  55. package/core/inspect/InspectScene.js +32 -7
  56. package/core/inspect/MaterialInfo.js +19 -2
  57. package/core/inspect/UrlState.js +46 -27
  58. package/core/inspect/catalog.js +28 -9
  59. package/core/inspect/debugView.js +2 -1
  60. package/core/inspect/describeRender.js +25 -13
  61. package/core/inspect/describeText.js +14 -6
  62. package/core/inspect/lightWatch.js +1 -1
  63. package/core/inspect/metadata.generated.js +35 -17
  64. package/core/inspect/pictureChecks.js +148 -0
  65. package/core/inspect/pictureMenu.js +84 -0
  66. package/core/inspect/pictureWriters.js +26 -6
  67. package/core/inspect/textureBytes.js +12 -2
  68. package/core/inspect/toolDoor.js +2 -4
  69. package/core/ops/Ops.js +11 -4
  70. package/core/ops/holds.js +27 -10
  71. package/core/ops/opsAtomic.js +15 -7
  72. package/core/ops/opsGuard.js +2 -2
  73. package/core/ops/opsRun.js +8 -7
  74. package/core/ops/sharedPoint.js +72 -21
  75. package/core/ops/stacks.js +56 -16
  76. package/core/saves/SaveStore.js +9 -3
  77. package/core/saves/Saves.js +32 -23
  78. package/core/saves/saveApply.js +96 -44
  79. package/core/saves/saveIds.js +1 -1
  80. package/core/saves/saveVersions.js +7 -5
  81. package/core/saves/session.js +17 -8
  82. package/core/saves/stateReplace.js +34 -15
  83. package/core/scene/Rays.js +52 -10
  84. package/core/scene/Views.js +13 -7
  85. package/core/scene/adaptive.js +144 -21
  86. package/core/scene/drawOnly.js +17 -0
  87. package/core/scene/gameLights.js +44 -3
  88. package/core/scene/sceneMethods.js +13 -11
  89. package/core/scene/stepPoses.js +11 -3
  90. package/core/scene/targeting.js +5 -3
  91. package/core/scene/thingOps.js +1 -1
  92. package/core/scene/tier.js +15 -0
  93. package/core/stream/Batching.js +30 -7
  94. package/core/stream/Stream.js +26 -7
  95. package/core/stream/batchGroups.js +2 -2
  96. package/core/stream/chunkStream.js +7 -5
  97. package/core/stream/prepare.js +77 -0
  98. package/core/time/skip.js +3 -1
  99. package/core/time/time.js +4 -2
  100. package/docs/AI.md +82 -83
  101. package/docs/API.md +16 -16
  102. package/docs/CODEMAP.md +16 -11
  103. package/docs/COMMANDS.md +31 -33
  104. package/docs/CONVENTIONS.md +37 -49
  105. package/docs/MIGRATING-0.8.md +2 -2
  106. package/docs/MIGRATING-1.0.md +2 -2
  107. package/docs/THREE.md +28 -35
  108. package/docs/api/assets.md +3 -1
  109. package/docs/api/audio.md +4 -2
  110. package/docs/api/budget.md +5 -0
  111. package/docs/api/cameraRig.md +2 -2
  112. package/docs/api/characters.md +10 -8
  113. package/docs/api/collision.md +6 -4
  114. package/docs/api/engine.md +16 -16
  115. package/docs/api/events.md +3 -2
  116. package/docs/api/ground.md +6 -5
  117. package/docs/api/hud.md +4 -2
  118. package/docs/api/input.md +5 -5
  119. package/docs/api/particles.md +2 -1
  120. package/docs/api/photo.md +3 -0
  121. package/docs/api/post.md +7 -4
  122. package/docs/api/quests.md +2 -2
  123. package/docs/api/rays.md +1 -2
  124. package/docs/api/saves.md +7 -7
  125. package/docs/api/settings.md +2 -2
  126. package/docs/api/tools.md +3 -1
  127. package/docs/api/vars.md +1 -1
  128. package/docs/api/vegetation.md +4 -2
  129. package/docs/api/world.md +1 -1
  130. package/docs/recipes/01-new-game.md +16 -17
  131. package/docs/recipes/02-npc.md +22 -18
  132. package/docs/recipes/03-items-pickups.md +37 -35
  133. package/docs/recipes/04-quests.md +15 -10
  134. package/docs/recipes/05-props-bake.md +101 -95
  135. package/docs/recipes/06-clock-events.md +28 -28
  136. package/docs/recipes/07-flow-scenes-pause.md +29 -26
  137. package/docs/recipes/08-weather-sky.md +52 -64
  138. package/docs/recipes/09-materials-lights-models.md +26 -17
  139. package/docs/recipes/10-blender-level.md +15 -10
  140. package/docs/recipes/11-vehicles.md +12 -7
  141. package/docs/recipes/12-navmesh.md +44 -26
  142. package/docs/recipes/13-animation.md +56 -45
  143. package/docs/recipes/14-custom-module.md +21 -18
  144. package/docs/recipes/15-perf.md +61 -55
  145. package/docs/recipes/16-dev-bridge.md +23 -33
  146. package/docs/recipes/18-world.md +36 -42
  147. package/docs/recipes/19-shooting-picking.md +20 -15
  148. package/docs/recipes/20-content-actions-save.md +48 -56
  149. package/docs/recipes/21-camera.md +45 -54
  150. package/docs/recipes/22-shop-gold.md +12 -7
  151. package/docs/recipes/23-ops.md +25 -23
  152. package/docs/recipes/26-ui-parts.md +67 -47
  153. package/docs/recipes/27-net.md +12 -7
  154. package/docs/recipes/28-terrain.md +24 -21
  155. package/docs/recipes/29-grid.md +32 -27
  156. package/docs/recipes/30-templates.md +21 -20
  157. package/docs/recipes/31-audio.md +39 -22
  158. package/docs/recipes/32-action-game.md +19 -14
  159. package/docs/recipes/33-stream-sources.md +15 -11
  160. package/docs/recipes/34-environment-lighting.md +126 -70
  161. package/docs/recipes/35-picture-from-reference.md +8 -8
  162. package/docs/recipes/36-ground-plants.md +27 -21
  163. package/docs/recipes/40-scene.md +19 -28
  164. package/docs/recipes/43-shader-patches-surfaces.md +15 -12
  165. package/docs/recipes/44-water-weather-hooks.md +34 -31
  166. package/docs/recipes/45-cascaded-shadows.md +35 -26
  167. package/docs/recipes/46-blender-art-route.md +6 -1
  168. package/docs/recipes/49-game-module-contract.md +13 -8
  169. package/docs/recipes/50-own-renderer.md +6 -2
  170. package/docs/recipes/51-capability-catalog.md +15 -8
  171. package/docs/recipes/52-around-the-picture.md +34 -32
  172. package/docs/recipes/53-ground-up-close.md +6 -1
  173. package/docs/recipes/55-mods-time-wrap.md +27 -19
  174. package/docs/recipes/56-webgpu-tsl.md +74 -43
  175. package/docs/recipes/57-control.md +18 -13
  176. package/docs/recipes/58-input.md +26 -16
  177. package/docs/recipes/59-depth-post-effects.md +8 -3
  178. package/docs/recipes/60-judge-the-picture.md +9 -8
  179. package/docs/recipes/61-deploy.md +5 -0
  180. package/docs/recipes/62-picture-code.md +70 -79
  181. package/docs/recipes/63-third-person-start.md +47 -45
  182. package/docs/recipes/64-particles.md +22 -10
  183. package/docs/recipes/65-swarm.md +18 -13
  184. package/docs/recipes/66-common-tasks.md +38 -35
  185. package/examples/action/GAMEMAP.md +2 -3
  186. package/examples/action/main.js +3 -3
  187. package/examples/action/picture/lights.js +3 -1
  188. package/examples/perf-island/GAMEMAP.md +3 -3
  189. package/examples/perf-island/picture/lights.js +2 -1
  190. package/examples/plain-picture/GAMEMAP.md +1 -1
  191. package/examples/rc2d/GAMEMAP.md +1 -1
  192. package/examples/styletest/GAMEMAP.md +2 -2
  193. package/examples/styletest/main.js +1 -1
  194. package/examples/techniques/interior-light/README.md +3 -3
  195. package/examples/techniques/interior-light/interiorLight.js +2 -4
  196. package/examples/techniques/interior-light/picture/lights.js +2 -1
  197. package/examples/techniques/modular-building/picture/lights.js +3 -1
  198. package/examples/techniques/outlines-and-rim/picture/lights.js +3 -1
  199. package/examples/techniques/procedural-animation/README.md +1 -1
  200. package/examples/techniques/procedural-animation/main.js +1 -1
  201. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  202. package/examples/world/GAMEMAP.md +2 -3
  203. package/examples/world/art/humanoid.js +1 -1
  204. package/examples/world/main.js +6 -3
  205. package/index.d.ts +2 -2
  206. package/llms.txt +101 -0
  207. package/modules/ambience/Ambience.js +21 -5
  208. package/modules/calendar/index.js +9 -5
  209. package/modules/calendar/schedule.js +23 -8
  210. package/modules/camera/FirstPersonCamera.js +3 -1
  211. package/modules/camera/FollowCamera.js +10 -5
  212. package/modules/camera/RtsCamera.js +4 -3
  213. package/modules/camera/common.js +70 -8
  214. package/modules/camera/contract.js +1 -1
  215. package/modules/characters/Character.js +16 -10
  216. package/modules/characters/NPC.js +31 -19
  217. package/modules/characters/assetModel.js +14 -9
  218. package/modules/characters/astar.js +6 -1
  219. package/modules/characters/contract.js +2 -2
  220. package/modules/characters/index.js +34 -22
  221. package/modules/characters/movers/manual.js +1 -1
  222. package/modules/characters/movers/rapier.js +17 -2
  223. package/modules/characters/movers/simple.js +1 -1
  224. package/modules/characters/movers/support.js +16 -7
  225. package/modules/characters/npcAvoid.js +2 -2
  226. package/modules/characters/npcSim.js +3 -2
  227. package/modules/characters/pathAsync.js +24 -8
  228. package/modules/characters/pathJob.js +1 -1
  229. package/modules/characters/player.js +10 -9
  230. package/modules/characters/playerStrings.js +5 -5
  231. package/modules/characters/proceduralRig.js +5 -5
  232. package/modules/characters/useModel.js +6 -0
  233. package/modules/characters/walkTo.js +1 -1
  234. package/modules/collision/Collision.js +29 -18
  235. package/modules/collision/grid.js +22 -4
  236. package/modules/content/index.js +3 -1
  237. package/modules/content/loader.js +1 -1
  238. package/modules/content/models.js +82 -33
  239. package/modules/content/props.js +2 -1
  240. package/modules/content/rules.js +11 -5
  241. package/modules/content/templates.js +3 -3
  242. package/modules/content/words.js +2 -2
  243. package/modules/debug/DebugPanel.js +9 -9
  244. package/modules/flow/index.js +9 -6
  245. package/modules/gameplay/Dialogue.js +34 -20
  246. package/modules/gameplay/Interactions.js +19 -15
  247. package/modules/gameplay/Inventory.js +9 -4
  248. package/modules/gameplay/Quests.js +12 -10
  249. package/modules/gameplay/pickups.js +23 -11
  250. package/modules/grid/index.js +1 -1
  251. package/modules/grid/preview.js +2 -2
  252. package/modules/grid/tiles.js +1 -1
  253. package/modules/hlod/index.js +4 -1
  254. package/modules/hud/index.js +47 -10
  255. package/modules/hud/parts.js +28 -9
  256. package/modules/level/geometry.js +8 -3
  257. package/modules/level/index.js +10 -5
  258. package/modules/level/load.js +4 -2
  259. package/modules/lights/sources.js +1 -1
  260. package/modules/music/Music.js +22 -4
  261. package/modules/nav/index.js +20 -10
  262. package/modules/particles/Particles.js +31 -14
  263. package/modules/particles/effect.js +20 -5
  264. package/modules/particles/lit.js +72 -0
  265. package/modules/photo/Photo.js +72 -28
  266. package/modules/photo/pathTrace.js +106 -0
  267. package/modules/rigid/RigidBodies.js +23 -14
  268. package/modules/rigid/Vehicles.js +3 -13
  269. package/modules/rigid/sync.js +2 -1
  270. package/modules/settings/Settings.js +52 -20
  271. package/modules/settings/apply.js +23 -9
  272. package/modules/settings/sections.js +39 -6
  273. package/modules/settings/strings.js +2 -0
  274. package/modules/settings/view.js +19 -3
  275. package/modules/sky/dome.js +15 -3
  276. package/modules/sky/environment.js +28 -12
  277. package/modules/sky/fog.js +1 -1
  278. package/modules/sky/frame.js +6 -1
  279. package/modules/sky/shader.js +4 -3
  280. package/modules/sky/skyModule.js +8 -4
  281. package/modules/swarm/Swarm.js +1 -1
  282. package/modules/terrain/ChunkManager.js +61 -15
  283. package/modules/terrain/chunkJob.js +2 -2
  284. package/modules/terrain/index.js +20 -5
  285. package/modules/terrain/terrainEdit.js +8 -4
  286. package/modules/terrain/terrainTexture.js +4 -2
  287. package/modules/timeline/Timeline.js +4 -3
  288. package/modules/timeline/Tween.js +3 -0
  289. package/modules/timeline/letterbox.js +1 -0
  290. package/modules/triggers/index.js +36 -17
  291. package/modules/vegetation/Vegetation.js +81 -19
  292. package/modules/vegetation/densityMap.js +13 -8
  293. package/modules/vegetation/draw.js +147 -24
  294. package/modules/vegetation/groundChunks.js +20 -5
  295. package/modules/vegetation/index.js +3 -3
  296. package/modules/vegetation/modelGeometry.js +9 -4
  297. package/modules/water/Water.js +11 -8
  298. package/modules/weather/Weather.js +7 -2
  299. package/modules/weather/shaders.js +25 -5
  300. package/modules/weather/weatherDraw.js +20 -6
  301. package/modules/world/World.js +2 -1
  302. package/modules/world/index.js +2 -2
  303. package/modules/world/persist.js +6 -2
  304. package/modules/world/views.js +15 -2
  305. package/package.json +4 -1
  306. package/presets.js +5 -5
  307. package/render/PostFX.js +84 -41
  308. package/render/backend.js +137 -16
  309. package/render/cascades.js +3 -1
  310. package/render/cascades.tsl.js +2 -0
  311. package/render/daylight.js +7 -1
  312. package/render/detail.js +7 -4
  313. package/render/effects.js +27 -8
  314. package/render/fogLook.js +24 -0
  315. package/render/fuse.js +5 -2
  316. package/render/fx/detail.tsl.js +9 -7
  317. package/render/fx/index.js +7 -2
  318. package/render/fx/library.tsl.js +1 -0
  319. package/render/fx/lightShaft.tsl.js +114 -0
  320. package/render/fx/noise.tsl.js +25 -8
  321. package/render/fx/objectOrigin.tsl.js +39 -10
  322. package/render/fx/particles.tsl.js +23 -6
  323. package/render/fx/patchNodes.tsl.js +17 -12
  324. package/render/fx/pcss.tsl.js +51 -0
  325. package/render/fx/postWebGPU.tsl.js +89 -29
  326. package/render/fx/sky.tsl.js +3 -9
  327. package/render/fxNumbers.js +10 -4
  328. package/render/impostor.tsl.js +107 -0
  329. package/render/lighting.js +33 -1
  330. package/render/lightmap.js +42 -28
  331. package/render/lights.js +19 -3
  332. package/render/materials.js +6 -4
  333. package/render/mergeCommon.js +4 -1
  334. package/render/occlusion.js +14 -4
  335. package/render/patches.js +79 -41
  336. package/render/postRuns.js +32 -0
  337. package/render/postWebGL.js +97 -10
  338. package/render/probes.js +10 -14
  339. package/render/shaderErrors.js +2 -1
  340. package/render/shadowCache.tsl.js +33 -5
  341. package/render/shadows.js +42 -16
  342. package/render/slots.js +8 -5
  343. package/render/vertexInputs.js +52 -0
  344. package/types/core.d.ts +114 -46
  345. package/types/gameplay.d.ts +56 -23
  346. package/types/generated/core/audio/Audio.d.ts +27 -1
  347. package/types/generated/core/base/Random.d.ts +1 -1
  348. package/types/generated/core/input/Input.d.ts +6 -8
  349. package/types/generated/core/input/inputSeat.d.ts +1 -1
  350. package/types/generated/core/inspect/Budget.d.ts +26 -0
  351. package/types/generated/core/inspect/DebugOverrides.d.ts +0 -2
  352. package/types/generated/core/saves/Saves.d.ts +10 -7
  353. package/types/generated/core/saves/session.d.ts +8 -2
  354. package/types/generated/core/scene/Rays.d.ts +1 -3
  355. package/types/generated/modules/particles/Particles.d.ts +1 -1
  356. package/types/generated/modules/world/World.d.ts +2 -1
  357. package/types/generated/render/PostFX.d.ts +35 -9
  358. package/types/physics.d.ts +43 -11
  359. package/types/pixel.d.ts +1 -1
  360. package/types/tsl.d.ts +62 -1
  361. package/types/world.d.ts +12 -3
  362. package/ui/Focus.js +7 -5
  363. package/ui/Parts.js +1 -1
  364. package/ui/touchPart.js +6 -3
@@ -1,13 +1,13 @@
1
1
  // Photo mode: a sharper shot, then restore. Resolution and the shadow maps of every casting DirectionalLight in the scene rise for the one frame, so normal
2
2
  // frame rate is unaffected. Why every one: the sun is usually the game's own light.
3
- // Bloom follows the game's post by default (bloom: null): a photo looks like the game; bloom: true / false forces it for the shot only.
3
+ // Bloom follows the game's post by default (bloom: null): a photo looks like the game; bloom: true / false forces it for the shot only. The bloom effect is found by its role (about.acts "glow"), not its name; every effect with that role follows the option and the settings bloom row.
4
4
  //
5
5
  // Taking a photo is the op photo.take (recipes/23-ops.md): the photo key, a game's shutter button, the dev bridge and tests all run it, and
6
6
  // photo.canTake (true or a reason) is its can. engine.photo.take() is the low-level capture the op calls (no checks).
7
7
  // const r = engine.ops.run('photo.take'); // r.value = { url, time, position, subject } or r.code (e.g. 'noFilm')
8
8
  // When the photo key's op is refused the module emits photo:denied { reason } (the game shows it; a button reads r.code itself).
9
9
  // subject is what is in the middle of the frame { name, kind, distance }: NPC (kind 'npc'), named object ('object'),
10
- // vegetation ('vegetation'; after hitting an instanced mesh, vegetation.instanceAt looks up the kind); null when it hits the sky or an unnamed ground.
10
+ // vegetation ('vegetation'; after hitting an instanced mesh, vegetation.plantOf reads the kind from the hit); null when it hits the sky or an unnamed ground.
11
11
  // The photo key (action 'photo') is the game's: engine.input.bind('photo', ['KeyC', 'PadX']), presets.bindings.photo (P / gamepad RB) or [] for no key
12
12
  // Shutter sound: the game's createEngine({ audio: { sounds: { shutter } } }) supplies a file, otherwise a synthesized fallback
13
13
  import { warnOnce } from '../../core/base/validate.js';
@@ -15,45 +15,71 @@ import { builtInSounds } from '../../core/assets/assetManifest.js';
15
15
  import { readParams, keysSchema } from '../../core/base/params.js';
16
16
  import { toast } from '../../ui/UI.js';
17
17
  import { coded } from '../../core/base/errorHints.js';
18
+ import { reportError } from '../../core/base/errors.js';
18
19
  import { setShadowUpdate, shadowsOn } from '../../render/backend.js';
19
20
  import { borrowRatio } from '../../core/scene/pixelRatio.js';
21
+ import { traceFrame, refusal, REFUSALS, traceError } from './pathTrace.js';
20
22
  const GROUP = 'photo'; // attachment group in engine.saves
21
23
  const TAKE_KEYS = ['scale', 'shadowMapSize', 'bloom', 'quality', 'format'];
24
+ const TRACE_PARAMS = keysSchema([...TAKE_KEYS, 'samples', 'seconds'], null, { samples: { type: 'int', optional: true, min: 1 }, seconds: { type: 'number', optional: true, min: 1 } });
22
25
 
23
26
  export class Photo {
24
- constructor(engine, { scale = 1.6, shadowMapSize = 4096, bloom = null, quality = 0.92, format = 'image/jpeg', maxAlbum = 50 } = {}) {
25
- Object.assign(this, { engine, scale, shadowMapSize, bloom, quality, format, maxAlbum });
27
+ constructor(engine, { scale = 1.6, shadowMapSize = 4096, bloom = null, quality = 0.92, format = 'image/jpeg', maxAlbum = 50, pathTracer = null } = {}) {
28
+ Object.assign(this, { engine, scale, shadowMapSize, bloom, quality, format, maxAlbum, pathTracer });
26
29
  this.album = [];
27
30
  this._n = 0; // shots taken this run (photo id = shot time + sequence number)
31
+ this.tracing = null; // { samples, of, stop } while a path-traced photo accumulates (describe().tracing)
28
32
  this.canTake = () => true; // the op's can: a game returns false or a reason string (e.g. 'noFilm') to refuse
29
33
  }
30
34
 
31
35
  /** Capture a photo now, without checks (the op photo.take checks canTake and calls this). Returns { url, time, position, subject } */
32
36
  take(opts = {}) {
33
37
  readParams('photo.take()', keysSchema(TAKE_KEYS), opts);
34
- const o = { scale: this.scale, shadowMapSize: this.shadowMapSize, bloom: this.bloom, quality: this.quality, format: this.format, ...opts };
38
+ const o = this._opts(opts);
39
+ return this._keep(this._shoot(o, o.scale, () => this.engine.renderOnce(), true));
40
+ }
41
+ _opts(opts) { return { scale: this.scale, shadowMapSize: this.shadowMapSize, bloom: this.bloom, quality: this.quality, format: this.format, ...opts }; }
42
+ /** A path-traced photo (pathTrace.js): a Promise of the shot plus pathTraced { samples, ms, size, untraced }. Traced at the current ratio unless
43
+ * opts names a scale: every extra pixel costs every sample */
44
+ async trace(opts = {}) {
45
+ readParams('photo.trace()', TRACE_PARAMS, opts);
46
+ const why = this.tracing ? 'tracing' : refusal(this.engine, this.pathTracer);
47
+ if (why) throw traceError(REFUSALS[why]);
48
+ const e = this.engine, state = this.tracing = { samples: 0, of: opts.samples ?? 128, stop: false };
49
+ let t = null;
50
+ try {
51
+ t = await traceFrame(e, this.pathTracer, opts, Math.min(3, e.renderer.getPixelRatio() * (opts.scale ?? 1)), state);
52
+ if (e.disposed || state.stop) throw traceError('stopped: the engine was disposed or the photo module removed');
53
+ return this._keep(this._shoot(this._opts(opts), t.ratio / e.renderer.getPixelRatio(), t.present, false), { pathTraced: t.info });
54
+ } finally { t?.dispose(); if (this.tracing === state) this.tracing = null; }
55
+ }
56
+ /** One frame drawn by draw() at the pixel ratio times scale, read in the same task. real: a rasterized frame, which also gets photo-sized shadows and the bloom choice */
57
+ _shoot(o, scale, draw, real) {
35
58
  const e = this.engine, r = e.renderer;
36
- const prevBloom = e.post.get('bloom')?.enabled, suns = [];
37
- if (shadowsOn(e)) e.scene.traverse(l => { if (l.isDirectionalLight && l.castShadow && l.visible) suns.push([l, l.shadow.mapSize.x, l.shadow.mapSize.y]); });
38
- const forceBloom = typeof o.bloom === 'boolean' && prevBloom !== undefined;
39
- let url, bloomHold = null, ratioBack = null;
59
+ const glows = e.post.byRole('glow', 'bloom'), suns = []; // the option follows every effect that declares the glow role (about.acts), whatever its name
60
+ if (real && shadowsOn(e)) e.scene.traverse(l => { if (l.isDirectionalLight && l.castShadow && l.visible) suns.push([l, l.shadow.mapSize.x, l.shadow.mapSize.y]); });
61
+ const forceBloom = real && typeof o.bloom === 'boolean' && glows.length > 0;
62
+ let bloomHolds = [], ratioBack = null;
40
63
  // restored in finally: a throw mid-shot (a failed WebGPU frame, a tainted canvas in toDataURL) must not leave the game running at the photo's
41
64
  // pixel ratio and shadow map size with photo's bloom hold still on
42
65
  try {
43
- ratioBack = borrowRatio(e, Math.min(3, r.getPixelRatio() * o.scale)); // the post chain follows the renderer on its next draw (postWebGL.js follow)
44
- for (const [l] of suns) e.shadows.mapSize(l, o.shadowMapSize);
66
+ ratioBack = borrowRatio(e, Math.min(3, r.getPixelRatio() * scale)); // the post chain follows the renderer on its next draw (postWebGL.js follow)
67
+ for (const [l, w, h] of suns) e.shadows.mapSize(l, Math.max(w, o.shadowMapSize), Math.max(h, o.shadowMapSize)); // at least the photo size; a larger map the game uses is never lowered
45
68
  // a hold on the system layer, removed after the shot: the game's own choice stays what it was (tests/specs/render-once.mjs); a settings restriction still wins
46
- bloomHold = forceBloom ? e.mod('post.bloom.enabled', { owner: 'photo', set: o.bloom, layer: 'system' }) : null;
47
- setShadowUpdate(r, e.scene, { now: true }); // shadows may update only every few frames (engine.shadows.budget); force an update on the photo frame
48
- e.renderOnce(); // the frame the player sees, post included, read below in the same task; a fresh frame on WebGPU (engine.renderOnce)
49
- url = r.domElement.toDataURL(o.format, o.quality);
69
+ if (forceBloom) bloomHolds = glows.map(h => e.mod(`post.${h.name}.enabled`, { owner: 'photo', set: o.bloom, layer: 'system' }));
70
+ if (real) setShadowUpdate(r, e.scene, { now: true }); // shadows may update only every few frames (engine.shadows.budget); force an update on the photo frame
71
+ draw(); // the frame the player sees, post included (a fresh frame on WebGPU, engine.renderOnce), or the traced picture; read below in the same task
72
+ return r.domElement.toDataURL(o.format, o.quality);
50
73
  } finally {
51
74
  ratioBack?.();
52
75
  for (const [l, w, h] of suns) e.shadows.mapSize(l, w, h);
53
- bloomHold?.remove();
76
+ for (const h of bloomHolds) h.remove();
54
77
  }
78
+ }
79
+ _keep(url, extra = {}) {
80
+ const e = this.engine;
55
81
  const p = e.actorPosition() ?? e.cameraRig?.focusPoint(); // where whoever the user controls stands (engine.actor)
56
- const shot = { url, time: e.calendar?.clock ?? '', position: p ? { x: Math.round(p.x), z: Math.round(p.z) } : null, subject: this.subject() };
82
+ const shot = { url, time: e.calendar?.clock ?? '', position: p ? { x: Math.round(p.x), z: Math.round(p.z) } : null, subject: this.subject(), ...extra };
57
83
  this.album.unshift(shot); if (this.album.length > this.maxAlbum) this._drop(this.album.pop());
58
84
  this._persist(shot);
59
85
  e.events.emit('photo:taken', shot);
@@ -70,7 +96,7 @@ export class Photo {
70
96
  try {
71
97
  await this.engine.saves.putAttachment(GROUP, id, async () => { // a function, so saves.flush() also waits for the bytes of this photo
72
98
  const blob = await (await fetch(shot.url)).blob();
73
- if (this.album.includes(shot)) shot.url = URL.createObjectURL(blob); // still in the album: hold the bytes as a Blob from now on
99
+ if (this.album.includes(shot) && !this._signal?.aborted) shot.url = URL.createObjectURL(blob); // still in the album: hold the bytes as a Blob from now on
74
100
  return blob;
75
101
  }, meta);
76
102
  } catch (err) { this._fail(err); }
@@ -83,13 +109,16 @@ export class Photo {
83
109
  /** At startup / after importing a save file, read the stored photos back into the album (newest first, merged with and de-duplicated against what is already there) */
84
110
  async restore() {
85
111
  let rows; try { rows = await this.engine.saves.attachments(GROUP); } catch (err) { this._fail(err); return; }
112
+ if (this._signal?.aborted) return; // removed while the rows were read: no Blob URLs from here on
86
113
  const have = new Set(this.album.map(s => s.id));
87
114
  for (const r of rows) if (!have.has(r.id)) this.album.push({ ...r.meta, id: r.id, url: URL.createObjectURL(r.blob), at: r.at }); // meta first: an imported file's meta.url must not replace the photo
88
115
  this.album.sort((a, b) => (b.at ?? Infinity) - (a.at ?? Infinity) || 0); // a just-taken shot has no `at`: goes first
89
116
  while (this.album.length > this.maxAlbum) this._drop(this.album.pop());
90
117
  }
91
118
  _fail(err) {
92
- warnOnce(coded('save-write', `[photo] failed to save photo: ${err?.message ?? err}`));
119
+ warnOnce(coded('save-write', `[photo] failed to save photo: ${err?.message ?? err}`), 'photo-save-fail'); // fixed key: the message names the photo id, so it would never dedupe
120
+ if (this._toasted) return; // every photo of a session fails alike (private mode): the player hears it once
121
+ this._toasted = true;
93
122
  toast(this.engine, this.engine.t('saves.failed', { why: err?.message || String(err) }), { kind: 'error', ms: 5000 });
94
123
  }
95
124
 
@@ -99,9 +128,9 @@ export class Photo {
99
128
  const hit = e.pick(0, 0, { targets: [e.scene], filter: h => !h.object.isPoints && !h.object.isSprite && !under(h.object, skip) });
100
129
  if (!hit) return null;
101
130
  const distance = Math.round(hit.distance * 10) / 10;
102
- if (hit.object.isInstancedMesh) { // instanced things (vegetation): ask vegetation which kind it is
103
- const v = e.vegetation?.instanceAt(hit.point, { radius: 3 });
104
- return v ? { name: v.species, kind: 'vegetation', distance } : null;
131
+ if (hit.object.isInstancedMesh) { // instanced things (vegetation): ask vegetation which kind it is; any other instanced mesh falls through to its name below
132
+ const v = e.vegetation?.plantOf(hit); // the plant the ray hit, from the hit itself: a lamp near a tree is not that tree, and a canopy hit far from the trunk still is
133
+ if (v) return { name: v.species, kind: 'vegetation', distance };
105
134
  }
106
135
  // an NPC anywhere up the chain wins over a named part on the way: character bodies name their parts ('torso', 'head'), and a photo of
107
136
  // someone is a photo of that someone, not of their torso. Only without an NPC does the nearest named object count
@@ -116,7 +145,7 @@ function under(o, set) { for (let p = o; p; p = p.parent) if (set.has(p)) return
116
145
 
117
146
  const STRINGS = { 'zh-CN': { 'module.photo': '拍照', 'photo.action': '拍照' }, en: { 'module.photo': 'photo', 'photo.action': 'Take photo' } };
118
147
 
119
- const PHOTO_PARAMS = keysSchema(['maxAlbum', ...TAKE_KEYS]);
148
+ const PHOTO_PARAMS = keysSchema(['maxAlbum', 'pathTracer', ...TAKE_KEYS]);
120
149
 
121
150
  /** Photo module. Once installed: engine.ops.run('photo.take') takes a photo through photo.canTake; engine.photo.take() captures without checks */
122
151
  export function photo(all = {}) {
@@ -128,25 +157,40 @@ export function photo(all = {}) {
128
157
  install(e, ctx) {
129
158
  e.i18n.add(STRINGS);
130
159
  // declared only: the game binds the key (presets.bindings.photo or its own; [] = no key), so every key in a game comes from one bindings table
131
- ctx.input.action('photo', { label: 'photo.action' });
160
+ ctx.input.define('photo', { label: 'photo.action' });
132
161
  if (e.input.keysOf('photo').length) ctx.track(e.input.touchButton('photo', 'photo.action'));
133
162
  builtInSounds(e.assets, { shutter: (audio, p, out) => { // sound asset 'shutter', silent until audio.sounds names it
134
163
  audio.noiseBurst({ dur: 0.03, type: 'highpass', freq: p.freq ?? 3000, vol: p.volume ?? 0.4, out });
135
164
  audio.noiseBurst({ dur: 0.05, type: 'bandpass', freq: 1800, vol: (p.volume ?? 0.4) * 0.75, delay: 0.07, out }); return 0.15;
136
165
  } });
137
166
  ph = new Photo(e, opts);
167
+ ph._signal = ctx.signal; // aborts when the module is removed: async work that finishes later must not create Blob URLs nobody will revoke
138
168
  ph.restore(); // read photos taken last time back from storage
169
+ const allowed = () => { const r = ph.canTake(); return r === true ? true : typeof r === 'string' && r ? r : 'denied'; };
139
170
  ctx.ops.define('photo.take', {
140
171
  desc: 'Take a photo (refused when photo.canTake() returns false or a reason)',
141
- can: () => { const r = ph.canTake(); return r === true ? true : typeof r === 'string' && r ? r : 'denied'; },
172
+ can: allowed,
142
173
  run: () => ph.take(),
143
174
  offers: () => [{}],
144
175
  reasons: { denied: 'photo.canTake() returned false' },
145
176
  });
146
- ctx.track(e.events.on('save:imported', () => ph.restore())); // after restoring from a save file, the attachments in the file (photos) also go into the album
177
+ // what can be known before loading is refused here; a failure after the start (the import, no sample in time) rejects r.value, the op stays a start
178
+ ctx.ops.define('photo.trace', {
179
+ desc: 'Start a path-traced photo: r.value is a Promise of the shot (refused when it cannot start, or by photo.canTake())',
180
+ args: { samples: 'int?', seconds: 'number?' },
181
+ can: () => ph.tracing ? 'tracing' : refusal(e, ph.pathTracer) ?? allowed(),
182
+ run: (_, a) => ph.trace(a),
183
+ offers: () => ph.pathTracer ? [{}] : [],
184
+ reasons: { ...REFUSALS, denied: 'photo.canTake() returned false' },
185
+ });
186
+ ctx.track(e.events.on('save:imported', () => { ph.restore().catch(err => reportError(e, err, 'photo restore after save:imported', { soft: true })); })); // fire and forget on purpose: returning the Promise would fail an unrelated load // after restoring from a save file, the attachments in the file (photos) also go into the album
147
187
  return ph;
148
188
  },
149
- dispose() { for (const s of ph.album) if (s.url.startsWith('blob:')) URL.revokeObjectURL(s.url); }, // a blob: URL holds its bytes until revoked, past the engine's life
189
+ dispose() {
190
+ if (ph.tracing) ph.tracing.stop = true; // a running trace ends at its next frame and rejects; nothing is drawn or kept
191
+ for (const s of ph.album) if (s.url.startsWith('blob:')) URL.revokeObjectURL(s.url); // a blob: URL holds its bytes until revoked, past the engine's life
192
+ ph.album.length = 0; // the album goes with the module (the stored photos stay in storage)
193
+ },
150
194
  frame(dt, e) {
151
195
  if (!e.input.pressed('photo')) return;
152
196
  const r = e.ops.run('photo.take', {}, { source: 'player' });
@@ -155,7 +199,7 @@ export function photo(all = {}) {
155
199
  // "did the shot land and what was in it": album size and the newest shot's subject; whether it can be taken now is describe().actions (photo.take)
156
200
  describe(e) {
157
201
  const s = ph.album[0];
158
- return { album: ph.album.length, maxAlbum: ph.maxAlbum, keyBound: e.input.keysOf('photo').length > 0,
202
+ return { album: ph.album.length, maxAlbum: ph.maxAlbum, keyBound: e.input.keysOf('photo').length > 0, tracing: ph.tracing && { samples: ph.tracing.samples, of: ph.tracing.of },
159
203
  last: s ? { time: s.time, position: s.position, subject: s.subject?.name ?? null } : null };
160
204
  },
161
205
  };
@@ -0,0 +1,106 @@
1
+ // A path-traced still for photo.trace(): three-gpu-pathtracer accumulates samples off screen against a snapshot
2
+ // (setScene captures geometry, transforms, materials and lights; the camera is a clone), so the game may keep running and moving its camera meanwhile.
3
+ // The library is the game's optional dependency and the game writes its import (photo({ pathTracer: () => import('three-gpu-pathtracer/webgpu') }), or 'three-gpu-pathtracer' on WebGL):
4
+ // a bundler fails the build of every game that has not installed a package the engine names, even inside a dynamic import.
5
+ import { Vector2 } from 'three';
6
+ import { backendName } from '../../render/backend.js';
7
+ import { codedError } from '../../core/base/errorHints.js';
8
+ import { isDrawOnly, drawOnlyWhat } from '../../core/scene/drawOnly.js';
9
+
10
+ const INSTALL = "path tracing needs the game's three-gpu-pathtracer: npm i -D three-gpu-pathtracer three-mesh-bvh, then photo({ pathTracer: () => import('three-gpu-pathtracer/webgpu') }) (on WebGL: 'three-gpu-pathtracer')";
11
+ /** The op's refusals, known before anything loads; the text is also the error photo.trace() rejects with */
12
+ export const REFUSALS = { noTracer: INSTALL, webgl2: 'path tracing needs the WebGPU backend or a WebGLRenderer: this page runs WebGPURenderer on its WebGL2 fallback (describe().renderer)', tracing: 'a traced photo is still accumulating (photo.tracing)' };
13
+ export const refusal = (e, load) => typeof load !== 'function' ? 'noTracer' : backendName(e.renderer) === 'webgl2' ? 'webgl2' : null;
14
+ export const traceError = msg => codedError('photo-path-trace', `photo.trace(): ${msg}`);
15
+ const SHOWN = 5; // the untraced list names this many, then "+N more": a line, not a dump
16
+
17
+ /** What the tracer will not draw as the game does: it reads Standard / Physical fields by name (any other model becomes a plain Standard surface),
18
+ * ignores TSL node slots (colorNode, positionNode…) and onBeforeCompile, needs normals, and traces meshes only (on WebGL one instance per InstancedMesh).
19
+ * skip: the drawOnly parts traceSnapshot hides; each one's own words say what the photo lacks */
20
+ export function untracedLine(scene, skip, gpu) {
21
+ const why = new Map(), flat = new Set(); let other = 0, inst = 0;
22
+ scene.traverseVisible(o => {
23
+ if (skip.includes(o)) return;
24
+ if (o.isAmbientLight || o.isHemisphereLight || o.isLightProbe) { flat.add(o.type); return; } // the tracer lights by lights with a position and scene.environment
25
+ if (!o.isMesh) { if (o.isPoints || o.isLine || o.isSprite) other++; return; }
26
+ if (!gpu && o.isInstancedMesh) inst++;
27
+ if (!o.geometry.attributes.normal) why.set(o, `${o.name || 'a mesh'} (no normals)`); // generateMissingAttributes stays off: the game's geometry is never written
28
+ for (const m of [o.material].flat()) {
29
+ if (!m || why.has(m)) continue;
30
+ const slots = [...Object.keys(m).filter(k => k.endsWith('Node') && m[k]?.isNode), ...(Object.hasOwn(m, 'onBeforeCompile') ? ['onBeforeCompile'] : [])];
31
+ const what = m.isMeshStandardMaterial || m.isMeshStandardNodeMaterial ? slots.join(', ') : m.type;
32
+ if (what) why.set(m, `${m.name || m.type} (${what})`);
33
+ }
34
+ });
35
+ const list = [...why.values()], more = list.length > SHOWN ? ` +${list.length - SHOWN} more` : '';
36
+ // the last part always: a --ref comparison would otherwise read the missing bloom or grading as a lighting difference
37
+ return `not traced as drawn: ${[...(list.length ? [list.slice(0, SHOWN).join('; ') + more] : []), ...(inst ? [`${inst} InstancedMesh (traced as one instance)`] : []),
38
+ ...(other ? [`${other} points / lines / sprites (left out)`] : []), ...(flat.size ? [`${[...flat].join(', ')} (left out)`] : []),
39
+ ...new Set(skip.map(drawOnlyWhat).filter(Boolean)), 'no post effects (bloom, grading) in a traced picture'].join('; ')}`;
40
+ }
41
+
42
+ /**
43
+ * Hand the scene to the tracer without the parts the engine draws for something else (core/scene/drawOnly.js: the sky dome, a cascade's
44
+ * copies of the sun, which the tracer would add up to several suns, impostor cards, which outside their shader are one quad at the origin).
45
+ * Hidden for the snapshot only: setScene reads visibility now, and they show again before the next frame. Returns the untraced line.
46
+ * @param {{ setScene(scene: any, camera: any): void }} pt @param {any} scene @param {any} camera @param {boolean} gpu @returns {string}
47
+ */
48
+ export function traceSnapshot(pt, scene, camera, gpu) {
49
+ const parts = [];
50
+ scene.traverseVisible(o => { if (isDrawOnly(o)) parts.push(o); });
51
+ const untraced = untracedLine(scene, parts, gpu);
52
+ try { for (const o of parts) o.visible = false; pt.setScene(scene, camera); } finally { for (const o of parts) o.visible = true; }
53
+ return untraced;
54
+ }
55
+
56
+ /**
57
+ * Accumulate up to `samples` per pixel (or until `seconds` pass). `state` ({ samples, of, stop }) is written as it goes; stop or a disposed engine
58
+ * ends it. Returns { ratio, present(), dispose(), info }: present() draws the result to the canvas, for a read in the same task.
59
+ * @param {any} e @param {() => Promise<any>} load @param {{ samples?: number, seconds?: number }} opts @param {number} ratio @param {any} state
60
+ */
61
+ export async function traceFrame(e, load, { samples = 128, seconds = 60 }, ratio, state) {
62
+ let lib; try { lib = await load(); } catch (err) { throw traceError(`${INSTALL} (the import failed: ${err?.message ?? err})`); }
63
+ const stopped = () => e.disposed || state.stop, STOPPED = 'stopped: the engine was disposed or the photo module removed';
64
+ if (stopped()) throw traceError(STOPPED); // the import took frames: the renderer may be gone
65
+ // two entries, one per renderer: WebGPUPathTracer (compute kernels, needs a device) and WebGLPathTracer (a WebGLRenderer; deprecated upstream)
66
+ const r = e.renderer, drawnBy = backendName(r), gpu = drawnBy === 'webgpu', name = gpu ? 'WebGPUPathTracer' : 'WebGLPathTracer';
67
+ if (!lib?.[name]) throw traceError(`path tracing on ${drawnBy} needs ${name}: photo({ pathTracer: () => import('three-gpu-pathtracer${gpu ? '/webgpu' : ''}') })`);
68
+ const pt = new lib[name](r), css = r.getSize(new Vector2()), w = Math.max(1, Math.floor(css.x * ratio)), h = Math.max(1, Math.floor(css.y * ratio));
69
+ // setScene builds a BVH per geometry (not indirect, and the library takes no BVH options): it adds a boundsTree (on a skinned mesh, the mesh),
70
+ // gives an unindexed geometry an index and reorders an existing index in place, which would move a game's drawRange subsets and faceIndex
71
+ // meanings. Copy each index first; afterwards remove only the objects the tracer made (by identity) and write the original order back.
72
+ // shortcut: a game that edits the contents of its own index during a trace loses that edit; upgrade if one ever needs to
73
+ const held = new Map(); e.scene.traverse(o => { if (o.isMesh) for (const x of [o, o.geometry]) if (!held.has(x)) held.set(x, { bt: x.boundsTree, ix: x.index, copy: x.index?.array.slice() }); });
74
+ const mark = () => { for (const [x, h] of held) { h.madeBt = x.boundsTree !== h.bt ? x.boundsTree : null; h.madeIx = x.index !== h.ix ? x.index : null; } };
75
+ const dispose = () => {
76
+ pt.dispose();
77
+ for (const [x, h] of held) {
78
+ if (h.madeBt && x.boundsTree === h.madeBt) delete x.boundsTree;
79
+ if (h.madeIx && x.index === h.madeIx) x.setIndex(null);
80
+ if (h.copy && x.index === h.ix) { h.ix.array.set(h.copy); h.ix.needsUpdate = true; }
81
+ }
82
+ };
83
+ try {
84
+ // off screen at a size fixed now, no preview, fade or raster stand-in: adaptive resolution, a resize or a take() between frames changes
85
+ // the canvas, never the tracer, so nothing restarts and present() never shows a raster frame
86
+ Object.assign(pt, { renderToCanvas: false, dynamicLowRes: false, rasterizeScene: false, generateMissingAttributes: false, renderDelay: 0, fadeDuration: 0, minSamples: 1, maxSamples: samples });
87
+ if (gpu) { pt.synchronizeRenderSize = false; pt.setSize(w, h); } else pt.renderScale = ratio / r.getPixelRatio(); // the WebGL tracer sizes on its first sample, then stops following
88
+ const info = { samples: 0, ms: 0, size: [w, h], untraced: '' };
89
+ pt.addEventListener?.('progress', ev => { if (ev.samples) state.samples = info.samples = Math.round(ev.samples.avg); });
90
+ const count = () => gpu ? info.samples : state.samples = info.samples = Math.floor(pt.samples), done = () => gpu ? pt.complete : count() >= samples;
91
+ const t0 = performance.now(); // wall-clock: the limit is the player's seconds; accumulation runs off the game clock
92
+ try { info.untraced = traceSnapshot(pt, e.scene, e.camera.clone(), gpu); } finally { mark(); }
93
+ // a frame, or a timer when the tab is hidden (no animation frames there), so `seconds` always ends it
94
+ while (!done() && !stopped() && performance.now() - t0 < seconds * 1000) { pt.renderSample(); pt.synchronizeRenderSize = false; await new Promise(go => { requestAnimationFrame(go); setTimeout(go, 250); }); } // wall-clock
95
+ if (stopped()) throw traceError(STOPPED);
96
+ if (gpu && pt.complete) state.samples = info.samples = samples;
97
+ // nothing to present (the kernels were still compiling, or no count came back): a black picture must not pass for a traced one
98
+ if (!count()) throw traceError(`no sample arrived in ${seconds} s (kernels still compiling?): raise seconds`);
99
+ info.ms = Math.round(performance.now() - t0); // wall-clock
100
+ const present = () => {
101
+ Object.assign(pt, { renderToCanvas: true, pause: true, pausePathTracing: true }); pt.renderSample();
102
+ if (!count()) throw traceError('the traced picture lost its samples before it was drawn: nothing was kept');
103
+ };
104
+ return { ratio, info, present, dispose };
105
+ } catch (err) { dispose(); throw err; }
106
+ }
@@ -52,19 +52,23 @@ function setLocalPose(mesh, t, r) {
52
52
  const _I = new THREE.Matrix4(), _eu = new THREE.Euler(), _box = new THREE.Box3(), _part = new THREE.Box3(), _inv = new THREE.Matrix4(), _rel = new THREE.Matrix4();
53
53
  /**
54
54
  * The size a body gets from its model, as [x, y, z]: measured in the mesh's own axes, since the body takes its rotation, and at its world scale, parents included.
55
- * The box around it in the world grew with the turn, so a turned crate got a larger body turned on top of that
55
+ * The box around it in the world grew with the turn, so a turned crate got a larger body turned on top of that.
56
+ * skip(o): parts left out (a vehicle's wheels). The mesh is not moved: a parent's transform is in matrixWorld and in its inverse alike, so it cancels
56
57
  */
57
- function ownSize(mesh) {
58
+ export function ownBox(mesh, skip) {
58
59
  mesh.updateWorldMatrix(true, true);
59
60
  mesh.matrixWorld.decompose(_p, _q, _s);
60
61
  _inv.copy(mesh.matrixWorld).invert(); _box.makeEmpty();
61
62
  mesh.traverse(o => {
62
- const g = o.geometry; if (!g) return;
63
+ const g = o.geometry; if (!g || skip?.(o)) return;
63
64
  if (!g.boundingBox) g.computeBoundingBox();
64
65
  _box.union(_part.copy(g.boundingBox).applyMatrix4(_rel.multiplyMatrices(_inv, o.matrixWorld)));
65
66
  });
66
- return _box.getSize(_p).multiply(_s).toArray();
67
+ const box = _box.clone(), k = _s.set(Math.abs(_s.x), Math.abs(_s.y), Math.abs(_s.z)); // a mirrored model (scale -1) has the size of its picture, not min above max
68
+ box.min.multiply(k); box.max.multiply(k);
69
+ return box;
67
70
  }
71
+ const ownSize = mesh => ownBox(mesh).getSize(_p).toArray();
68
72
  const NO_TURN = { x: 0, y: 0, z: 0, w: 1 };
69
73
 
70
74
  const PHYSICS = { physics: true }; // stream source filter (shared, not rebuilt every step)
@@ -111,6 +115,7 @@ export class RigidBodies {
111
115
  constructor(engine, { gravity = -9.81, terrainRing = 1, buoyancy = true, buoyancyForce = 1.6, waterDrag = 2.5, floatLine = 0.3, floatDepth = 0.8,
112
116
  treeColliderHeight = 6, treeRadius = 16, playerCapsule, fallbackFloor = true } = {}) {
113
117
  const mv = engine.movement; // default capsule uses the shared character radius / height: total height = 2 * halfHeight + 2 * radius
118
+ this._capsuleRadiusGiven = playerCapsule?.radius != null; // the mover follows the character's radius only when the game did not set one here
114
119
  playerCapsule ??= { halfHeight: Math.max(0.05, (mv.height - 2 * mv.radius) / 2), radius: mv.radius };
115
120
  this.engine = engine;
116
121
  this.gravity = gravity;
@@ -126,7 +131,7 @@ export class RigidBodies {
126
131
  this.trees = new Map(); // chunk key -> { token, colliders }: trunk cylinders of the chunks near the player / bodies (see sync.js)
127
132
  this._anchors = []; this._treeMemo = [];
128
133
  this.groundTrees = new Map(); // 'x,z,r' -> cylinder collider: circles from ground.forEachCollider when the ground has no chunked collision
129
- /** @internal houses / pillars of the collision module as colliders (engine.collision.mirror, built on the first step: sync.js syncStatics) */ this._statics = null; /** @internal mirror data -> collider, for those standing on the ground */ this._onGround = new Map();
134
+ /** @internal houses / pillars of the collision module as colliders (engine.collision.mirror, built on the first step: sync.js syncStatics) */ this._statics = null; /** @internal mirror data -> collider, for those standing on the ground */ this._onGround = new Map(); /** @internal collider -> mirror data, for those with a layer: the rapier mover lets a body that passes it through */ this._layered = new Map();
130
135
  /** @internal the sources of the copies above, checked on every read (_current) */ this._collision = follows(() => engine.collision); this._level = follows(() => engine.ground.staticTrimeshes ?? null, () => engine.ground.staticVersion?.() ?? 0); this._standOn = follows(() => engine.ground, G => G.staticVersion?.() ?? 0); this._floor = follows(() => wantsFloor(this));
131
136
  /** @internal the world changed since Rapier last built its query structures, which it does only in a step */ this._behind = false;
132
137
  /** @internal fixed solids of the collider3d contract: what they are, so every new world (init, _fresh) builds them; a collider only lives as long as its world */ this._solids = new Set();
@@ -143,9 +148,10 @@ export class RigidBodies {
143
148
  _wasm() { return (this._rapier ??= import('@dimforge/rapier3d-compat').then(async mod => { const R = mod.default ?? mod; await R.init(); return R; })); }
144
149
 
145
150
  /** @internal module hook */
146
- async init() {
151
+ async init(signal) {
147
152
  if (this.ready) return;
148
153
  this.rapier = await this._wasm();
154
+ if (signal?.aborted) return; // unloaded while the WASM loaded: dispose ran with no world to free, so none may be made now (ctx.signal)
149
155
  this._newWorld();
150
156
  this.ready = true;
151
157
  }
@@ -195,7 +201,7 @@ export class RigidBodies {
195
201
  }
196
202
  const old = this.world, R = this.rapier, hadJoints = old.impulseJoints.len();
197
203
  this._newWorld();
198
- this.terrain.clear(); this.trees.clear(); this.groundTrees.clear(); this._statics?.clear(); this._onGround.clear();
204
+ this.terrain.clear(); this.trees.clear(); this.groundTrees.clear(); this._statics?.clear(); this._onGround.clear(); this._layered.clear();
199
205
  this._level.reset(); this._levelColliders = [];
200
206
  this._srcMemo = null; this._srcPending = false; this._syncT = 0; this._anchors = []; this._treeMemo = [];
201
207
  for (const b of this.bodies) {
@@ -233,6 +239,9 @@ export class RigidBodies {
233
239
  // id names the body in the save part 'rigid': two live bodies with one id would load into each other
234
240
  if (id != null && this.bodies.some(b => b.id === id)) throw codedError('rigid-misuse', `rigid: id '${id}' is already used by another body or vehicle; ids name the body in saves, pick a unique one (e.g. the world record id)`);
235
241
  const R = this.rapier, { p, q } = worldPose(mesh, 'rigid');
242
+ // the pose registration comes first: a mesh another body or a character already owns throws here, before any Rapier body exists to leak
243
+ let entry;
244
+ const pose = this.engine._poses.add(mesh, at => { if (this.world) this.setPosition(entry, entry.place?.(at) ?? at); }, () => entry.remove(), () => id != null ? `rigid body '${id}'` : 'a rigid body');
236
245
  const bd = (fixed ? R.RigidBodyDesc.fixed() : R.RigidBodyDesc.dynamic())
237
246
  .setTranslation(p.x, p.y, p.z).setRotation({ x: q.x, y: q.y, z: q.z, w: q.w })
238
247
  .setLinearDamping(damping).setAngularDamping(angularDamping).setCanSleep(true);
@@ -240,13 +249,13 @@ export class RigidBodies {
240
249
  desc.setFriction(friction).setRestitution(restitution).setMass(mass);
241
250
  const collider = this.world.createCollider(desc, body); // desc is kept on the entry (_desc): _fresh rebuilds the collider from it
242
251
  if (!mesh.parent) this.engine.add(mesh, { owner: 'engine:rigid' }); // shadow casting/receiving follows the model's own settings (not forced)
243
- const entry = { id, body, collider, mesh, object: mesh, enabled: true, volume: 0, damping, angularDamping, fixed, _x: p.x, _z: p.z, _desc: desc }; // _x / _z: where sync.js looks for trunks to give it
252
+ entry = { id, body, collider, mesh, object: mesh, enabled: true, volume: 0, damping, angularDamping, fixed, _x: p.x, _z: p.z, _desc: desc }; // _x / _z: where sync.js looks for trunks to give it
244
253
  entry.remove = () => this._remove(entry);
245
254
  recordLocks(entry, body);
246
255
  this.bodies.push(entry); this._byHandle = null; this._behind = true;
247
256
  // a write to the record of this model lands here (world/views.js placed); with rigid gone first at dispose the model is on its own
248
257
  // entry.place: a template's copy says what a written place means for it (content/templates.js)
249
- this.engine._poses.add(mesh, at => { if (this.world) this.setPosition(entry, entry.place?.(at) ?? at); }, () => entry.remove());
258
+ entry._pose = pose;
250
259
  // a loaded save holds this body's state (it is built after the load, e.g. by a world presenter): it continues from there, not from the record's pose
251
260
  this._claim(entry);
252
261
  return entry;
@@ -269,7 +278,7 @@ export class RigidBodies {
269
278
  addHull(mesh, o = {}) {
270
279
  readParams('rigid.addHull()', keysSchema(BODY_KEYS), o);
271
280
  if (!this._ready('addHull')) return null;
272
- const g = mesh.geometry, pts = new Float32Array(g.attributes.position.array.length);
281
+ const g = mesh.geometry, pts = new Float32Array(g.attributes.position.count * 3); // count, not array.length: an interleaved attribute's array is the whole buffer
273
282
  const v = new THREE.Vector3();
274
283
  mesh.updateWorldMatrix(true, false); mesh.matrixWorld.decompose(_p, _q, _s); // the world scale: a parent's counts as much as the mesh's own
275
284
  const scale = _s.clone();
@@ -332,7 +341,7 @@ export class RigidBodies {
332
341
  const i = this.bodies.indexOf(entry); if (i < 0) return;
333
342
  this.world?.removeRigidBody(entry.body); // no world: rigid left first at dispose and freed its bodies with it
334
343
  this.bodies.splice(i, 1); this._byHandle = null; this._behind = true;
335
- this.engine._poses.remove(entry.mesh);
344
+ entry._pose.remove();
336
345
  }
337
346
  /** Push: impulse vector v (Vector3 / [x, y, z] / { x, y, z }) */
338
347
  impulse(entry, v) { const { x, y, z } = vec3(v); entry.body.wakeUp(); entry.body.applyImpulse({ x, y, z }, true); }
@@ -572,11 +581,11 @@ export function rigid(opts = {}) {
572
581
  ctx.track(e.events.on('session:end', () => { r._freshDue = true; }));
573
582
  ctx.track(e.events.on('session:failed', () => { r._freshDue = false; r._claimSaved(); }));
574
583
  ctx.track(e.events.on('world:load', () => r._fresh()));
575
- ctx.saves.register('rigid', { notAtomic: 'the physics world is stepped, not written: a load cannot rewind what the bodies did', save: () => r._saveState(), load: d => r._loadState(d) });
584
+ ctx.saves.define('rigid', { notAtomic: 'the physics world is stepped, not written: a load cannot rewind what the bodies did', save: () => r._saveState(), load: d => r._loadState(d) });
576
585
  return r;
577
586
  },
578
587
  afterLoad() { if (r._freshDue) r._fresh(); r._claimSaved(); }, // after every part loaded and _fresh rebuilt the world (world:load is emitted inside the world part's load)
579
- async init(e, ctx) { await r.init(); ctx.whileCompiling(() => warmRapier(r.rapier)); },
588
+ async init(e, ctx) { await r.init(ctx.signal); ctx.whileCompiling(() => warmRapier(r.rapier)); },
580
589
  counts() { return r.bodies.length; }, // engine.counts().rigid
581
590
  // bodies by type and what they are doing: sleeping = at rest (normal), frozen = disabled because no terrain collider is under them yet (they wait, not fall)
582
591
  describe() {
@@ -586,7 +595,7 @@ export function rigid(opts = {}) {
586
595
  },
587
596
  fixed(dt) { r.step(dt); },
588
597
  // a vehicle lives in this world: its riders get out while the seat and the exit can still be read, or they would read a freed solver every step
589
- dispose() { for (const v of [...r.vehicles]) r._removeVehicle(v); r._ragdolls?.dispose(); r.world?.free(); r.world = null; },
598
+ dispose() { for (const v of [...r.vehicles]) r._removeVehicle(v); r._ragdolls?.dispose(); for (const b of [...r.bodies]) r._remove(b); r.world?.free(); r.world = null; }, // every body lets go of its mesh's pose, or a new rigid could not take the same mesh
590
599
  };
591
600
  }
592
601
 
@@ -9,23 +9,13 @@
9
9
  // Native objects: car.body (rigid body), car.controller (vehicle controller).
10
10
  import * as THREE from 'three';
11
11
  import { vec3 } from '../../core/base/math.js';
12
+ import { ownBox } from './RigidBodies.js';
12
13
 
13
14
  export const VEHICLE_KEYS = ['id', 'wheels', 'mass', 'engineForce', 'brakeForce', 'maxSteer', 'suspension', 'seats', 'hideDriver', 'camera', 'size', 'friction', 'exitOffset'];
14
15
  export const STRINGS = { 'zh-CN': { 'vehicle.enter': '上车', 'vehicle.exit': '下车' }, en: { 'vehicle.enter': 'Get in', 'vehicle.exit': 'Get out' } };
15
16
 
16
- /** Chassis size: model bounding box (wheels excluded), in local coordinates */
17
- function bodyBox(mesh, wheelObjs) {
18
- const box = new THREE.Box3(), q = mesh.quaternion.clone(), p = mesh.position.clone();
19
- mesh.quaternion.identity(); mesh.position.set(0, 0, 0); mesh.updateMatrixWorld(true);
20
- const skip = o => { for (let x = o; x; x = x.parent) if (wheelObjs.has(x)) return true; return false; };
21
- mesh.traverse(o => {
22
- if (!o.isMesh || skip(o)) return;
23
- if (!o.geometry.boundingBox) o.geometry.computeBoundingBox();
24
- box.union(o.geometry.boundingBox.clone().applyMatrix4(o.matrixWorld));
25
- });
26
- mesh.quaternion.copy(q); mesh.position.copy(p); mesh.updateMatrixWorld(true);
27
- return box;
28
- }
17
+ /** Chassis box, wheels excluded and meshes only (a sprite, points or line on the car, like a name tag or glow, is no chassis): the box of a body from its model (ownBox, RigidBodies.js), so a vehicle and a plain body measure alike */
18
+ const bodyBox = (mesh, wheelObjs) => ownBox(mesh, o => { if (!o.isMesh) return true; for (let x = o; x; x = x.parent) if (wheelObjs.has(x)) return true; return false; });
29
19
 
30
20
  /** Create a vehicle (called by RigidBodies.addWheeled) */
31
21
  export function createVehicle(rigid, mesh, { wheels, mass = 800, engineForce = 800, brakeForce = 20, maxSteer = 0.5, suspension = {}, seats, hideDriver = true, camera, size, friction = 1.5, exitOffset = 0.8 }, id) {
@@ -149,9 +149,10 @@ export function syncStatics(r) {
149
149
  const shape = type === 'box' ? R.ColliderDesc.cuboid(o.hw, o.h / 2, o.hd).setRotation({ x: Q.x, y: Q.y, z: Q.z, w: Q.w }) : R.ColliderDesc.cylinder(o.h / 2, o.r);
150
150
  const c = r.world.createCollider(shape.setTranslation(o.x, g + o.h / 2, o.z));
151
151
  if (o.y == null) r._onGround.set(o, c);
152
+ if (o.ly !== undefined) r._layered.set(c, o);
152
153
  return c;
153
154
  },
154
- remove(c, o) { r._onGround.delete(o); r.world.removeCollider(c, false); },
155
+ remove(c, o) { r._onGround.delete(o); r._layered.delete(c); r.world.removeCollider(c, false); },
155
156
  }) ?? null;
156
157
  return !!r._statics?.sync();
157
158
  }