threedog 0.8.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (372) hide show
  1. package/CHANGELOG.md +219 -4
  2. package/README.md +6 -6
  3. package/core/assets/Animator.js +2 -0
  4. package/core/assets/Assets.js +44 -13
  5. package/core/assets/assetEntry.js +87 -22
  6. package/core/assets/assetHot.js +2 -1
  7. package/core/assets/assetReport.js +1 -2
  8. package/core/audio/Audio.js +24 -5
  9. package/core/base/I18n.js +6 -3
  10. package/core/base/Random.js +3 -1
  11. package/core/base/Vars.js +14 -4
  12. package/core/base/errorCodes.js +54 -16
  13. package/core/base/errorHints.js +12 -1
  14. package/core/base/errors.js +6 -4
  15. package/core/base/events.generated.js +10 -0
  16. package/core/base/follows.js +26 -0
  17. package/core/base/math.js +15 -8
  18. package/core/base/params.js +2 -2
  19. package/core/{saves → base}/saveValues.js +24 -6
  20. package/core/base/sections.js +97 -0
  21. package/core/base/spelling.js +32 -0
  22. package/core/base/validate.js +8 -29
  23. package/core/engine/Engine.js +61 -18
  24. package/core/engine/Loading.js +30 -3
  25. package/core/engine/copies.js +1 -1
  26. package/core/engine/headlessLoad.js +30 -13
  27. package/core/engine/lifecycle.js +30 -25
  28. package/core/engine/loop.js +22 -4
  29. package/core/engine/moduleSlots.js +91 -15
  30. package/core/engine/moduleTypes.js +13 -0
  31. package/core/engine/modules.js +248 -62
  32. package/core/engine/page.js +25 -8
  33. package/core/engine/plugins.js +15 -3
  34. package/core/engine/services.js +3 -0
  35. package/core/engine/startup.js +46 -36
  36. package/core/input/Input.js +39 -19
  37. package/core/input/inputKeyboard.js +39 -0
  38. package/core/input/inputPad.js +23 -2
  39. package/core/input/inputPointer.js +3 -1
  40. package/core/input/inputSeat.js +66 -0
  41. package/core/input/inputTouch.js +23 -6
  42. package/core/inspect/DebugOverrides.js +13 -2
  43. package/core/inspect/Describe.js +10 -6
  44. package/core/inspect/Inspect.js +31 -4
  45. package/core/inspect/UrlState.js +14 -10
  46. package/core/inspect/catalog.js +12 -5
  47. package/core/inspect/describeRender.js +3 -2
  48. package/core/inspect/describeText.js +6 -2
  49. package/core/inspect/metadata.generated.js +4140 -0
  50. package/core/inspect/pictureWriters.js +117 -33
  51. package/core/inspect/toolDoor.js +21 -0
  52. package/core/inspect/valueHistory.js +35 -0
  53. package/core/ops/Ops.js +32 -7
  54. package/core/ops/control.js +48 -23
  55. package/core/ops/holds.js +4 -3
  56. package/core/ops/opsAtomic.js +18 -6
  57. package/core/ops/opsCheck.js +7 -5
  58. package/core/ops/opsFail.js +5 -7
  59. package/core/ops/opsRun.js +2 -2
  60. package/core/ops/owned.js +20 -3
  61. package/core/ops/sharedPoint.js +7 -10
  62. package/core/ops/stacks.js +22 -1
  63. package/core/saves/SaveStore.js +52 -26
  64. package/core/saves/Saves.js +122 -27
  65. package/core/saves/saveApply.js +159 -61
  66. package/core/saves/saveFiles.js +30 -25
  67. package/core/saves/saveVersions.js +20 -6
  68. package/core/saves/session.js +76 -33
  69. package/core/saves/stateReplace.js +184 -0
  70. package/core/scene/Rays.js +21 -5
  71. package/core/scene/Views.js +6 -6
  72. package/core/scene/adaptive.js +13 -10
  73. package/core/scene/canvasBox.js +2 -0
  74. package/core/scene/compositeGround.js +72 -0
  75. package/core/scene/floor.js +17 -0
  76. package/core/scene/grid.js +2 -0
  77. package/core/scene/ground.contract.js +14 -0
  78. package/core/scene/ground.js +52 -17
  79. package/core/scene/pixel.js +154 -0
  80. package/core/scene/pixelRatio.js +167 -0
  81. package/core/scene/sceneDelta.js +3 -3
  82. package/core/scene/sceneMethods.js +11 -6
  83. package/core/scene/stepPoses.js +6 -1
  84. package/core/scene/thingExplain.js +1 -1
  85. package/core/scene/thingOps.js +22 -14
  86. package/core/scene/things.js +1 -1
  87. package/core/scene/tier.js +10 -0
  88. package/core/scene/view.js +126 -9
  89. package/core/stream/Batching.js +0 -1
  90. package/core/stream/Stream.js +24 -12
  91. package/core/stream/batchGroups.js +1 -0
  92. package/core/stream/scatter.js +5 -2
  93. package/core/stream/streamSources.js +2 -1
  94. package/core/threads/Commits.js +12 -7
  95. package/core/threads/Jobs.js +15 -5
  96. package/core/threads/Threads.js +5 -2
  97. package/core/time/Clock.js +3 -1
  98. package/core/time/skip.js +10 -4
  99. package/core/time/time.js +16 -10
  100. package/docs/AI.md +89 -72
  101. package/docs/API.md +18 -14
  102. package/docs/CODEMAP.md +68 -40
  103. package/docs/COMMANDS.md +22 -23
  104. package/docs/CONVENTIONS.md +120 -17
  105. package/docs/MIGRATING-0.8.md +2 -0
  106. package/docs/MIGRATING-1.0.md +101 -0
  107. package/docs/THREE.md +65 -12
  108. package/docs/api/cameraRig.md +3 -0
  109. package/docs/api/characters.md +13 -7
  110. package/docs/api/collider3d.md +9 -0
  111. package/docs/api/content.md +16 -15
  112. package/docs/api/dialogue.md +2 -1
  113. package/docs/api/engine.md +18 -16
  114. package/docs/api/events.md +14 -4
  115. package/docs/api/ground.md +2 -2
  116. package/docs/api/i18n.md +1 -1
  117. package/docs/api/input.md +2 -1
  118. package/docs/api/interactions.md +1 -1
  119. package/docs/api/inventory.md +1 -1
  120. package/docs/api/level.md +3 -2
  121. package/docs/api/nav.md +4 -2
  122. package/docs/api/particles.md +8 -5
  123. package/docs/api/pickups.md +1 -1
  124. package/docs/api/post.md +3 -4
  125. package/docs/api/quests.md +4 -2
  126. package/docs/api/rays.md +2 -0
  127. package/docs/api/rigid.md +3 -2
  128. package/docs/api/saves.md +8 -7
  129. package/docs/api/stream.md +4 -5
  130. package/docs/api/terrain.md +3 -4
  131. package/docs/api/terrainDraw.md +1 -1
  132. package/docs/api/timeline.md +2 -2
  133. package/docs/api/tools.md +3 -1
  134. package/docs/api/triggers.md +2 -0
  135. package/docs/api/vegetationDraw.md +1 -1
  136. package/docs/api/water.md +6 -2
  137. package/docs/api/weather.md +19 -4
  138. package/docs/api/weatherDraw.md +1 -1
  139. package/docs/api/world.md +1 -1
  140. package/docs/recipes/01-new-game.md +3 -3
  141. package/docs/recipes/02-npc.md +3 -4
  142. package/docs/recipes/03-items-pickups.md +11 -11
  143. package/docs/recipes/04-quests.md +2 -0
  144. package/docs/recipes/05-props-bake.md +9 -9
  145. package/docs/recipes/06-clock-events.md +6 -6
  146. package/docs/recipes/07-flow-scenes-pause.md +18 -15
  147. package/docs/recipes/08-weather-sky.md +5 -5
  148. package/docs/recipes/09-materials-lights-models.md +3 -3
  149. package/docs/recipes/10-blender-level.md +16 -4
  150. package/docs/recipes/11-vehicles.md +18 -6
  151. package/docs/recipes/12-navmesh.md +52 -8
  152. package/docs/recipes/13-animation.md +34 -8
  153. package/docs/recipes/14-custom-module.md +20 -8
  154. package/docs/recipes/15-perf.md +4 -4
  155. package/docs/recipes/16-dev-bridge.md +9 -8
  156. package/docs/recipes/18-world.md +13 -5
  157. package/docs/recipes/19-shooting-picking.md +3 -2
  158. package/docs/recipes/20-content-actions-save.md +26 -6
  159. package/docs/recipes/21-camera.md +17 -23
  160. package/docs/recipes/22-shop-gold.md +21 -12
  161. package/docs/recipes/23-ops.md +19 -15
  162. package/docs/recipes/26-ui-parts.md +3 -2
  163. package/docs/recipes/27-net.md +3 -3
  164. package/docs/recipes/28-terrain.md +3 -3
  165. package/docs/recipes/29-grid.md +1 -1
  166. package/docs/recipes/30-templates.md +10 -13
  167. package/docs/recipes/31-audio.md +2 -2
  168. package/docs/recipes/32-action-game.md +6 -5
  169. package/docs/recipes/33-stream-sources.md +4 -1
  170. package/docs/recipes/34-environment-lighting.md +7 -8
  171. package/docs/recipes/35-picture-from-reference.md +13 -9
  172. package/docs/recipes/36-ground-plants.md +3 -2
  173. package/docs/recipes/40-scene.md +11 -10
  174. package/docs/recipes/43-shader-patches-surfaces.md +7 -7
  175. package/docs/recipes/44-water-weather-hooks.md +9 -8
  176. package/docs/recipes/45-cascaded-shadows.md +3 -4
  177. package/docs/recipes/46-blender-art-route.md +3 -3
  178. package/docs/recipes/49-game-module-contract.md +2 -1
  179. package/docs/recipes/50-own-renderer.md +1 -0
  180. package/docs/recipes/51-capability-catalog.md +14 -8
  181. package/docs/recipes/52-around-the-picture.md +4 -4
  182. package/docs/recipes/55-mods-time-wrap.md +5 -4
  183. package/docs/recipes/56-webgpu-tsl.md +12 -1
  184. package/docs/recipes/57-control.md +30 -10
  185. package/docs/recipes/58-input.md +13 -0
  186. package/docs/recipes/60-judge-the-picture.md +1 -1
  187. package/docs/recipes/62-picture-code.md +106 -48
  188. package/docs/recipes/63-third-person-start.md +2 -1
  189. package/docs/recipes/64-particles.md +53 -4
  190. package/docs/recipes/65-swarm.md +2 -2
  191. package/docs/recipes/66-common-tasks.md +313 -0
  192. package/examples/action/.threedog/content-index.json +1 -1
  193. package/examples/action/GAMEMAP.md +3 -3
  194. package/examples/perf-island/.threedog/content-index.json +1 -1
  195. package/examples/perf-island/GAMEMAP.md +3 -3
  196. package/examples/perf-island/main.js +2 -2
  197. package/examples/plain-picture/GAMEMAP.md +3 -1
  198. package/examples/rc2d/GAMEMAP.md +1 -1
  199. package/examples/rc2d/rc2d.js +1 -1
  200. package/examples/styletest/.threedog/content-index.json +1 -1
  201. package/examples/styletest/GAMEMAP.md +3 -3
  202. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  203. package/examples/world/.threedog/content-index.json +1 -1
  204. package/examples/world/GAMEMAP.md +5 -4
  205. package/examples/world/main.js +3 -3
  206. package/index.d.ts +8 -5
  207. package/index.js +22 -1
  208. package/llms.txt +2 -1
  209. package/modules/ambience/Ambience.js +5 -3
  210. package/modules/calendar/index.js +7 -5
  211. package/modules/camera/FirstPersonCamera.js +3 -3
  212. package/modules/camera/FixedCamera.js +34 -20
  213. package/modules/camera/FollowCamera.js +20 -11
  214. package/modules/camera/RtsCamera.js +1 -0
  215. package/modules/camera/common.js +33 -22
  216. package/modules/camera/pixelSnap.js +62 -0
  217. package/modules/characters/Character.js +136 -43
  218. package/modules/characters/NPC.js +60 -28
  219. package/modules/characters/assetModel.js +2 -2
  220. package/modules/characters/astar.js +47 -28
  221. package/modules/characters/character.contract.js +21 -0
  222. package/modules/characters/contract.js +17 -3
  223. package/modules/characters/index.js +94 -34
  224. package/modules/characters/moveHelpers.js +80 -15
  225. package/modules/characters/mover.contract.js +14 -0
  226. package/modules/characters/movers/common.js +6 -4
  227. package/modules/characters/movers/rapier.js +12 -5
  228. package/modules/characters/movers/simple.js +25 -12
  229. package/modules/characters/movers/support.js +18 -7
  230. package/modules/characters/npcAvoid.js +15 -12
  231. package/modules/characters/npcSim.js +75 -25
  232. package/modules/characters/npcView.js +13 -6
  233. package/modules/characters/pathAsync.js +74 -24
  234. package/modules/characters/pathJob.js +38 -21
  235. package/modules/characters/player.js +59 -47
  236. package/modules/characters/seat.js +56 -0
  237. package/modules/characters/vehicle.contract.js +8 -5
  238. package/modules/characters/walkTo.js +31 -18
  239. package/modules/collision/Collision.js +44 -26
  240. package/modules/collision/contract.js +2 -2
  241. package/modules/collision/grid.js +6 -1
  242. package/modules/content/explain.js +1 -1
  243. package/modules/content/fields.js +3 -3
  244. package/modules/content/ids.js +3 -1
  245. package/modules/content/index.js +83 -27
  246. package/modules/content/loader.js +110 -130
  247. package/modules/content/markers.js +1 -1
  248. package/modules/content/models.js +48 -14
  249. package/modules/content/packs.js +2 -1
  250. package/modules/content/places.js +5 -4
  251. package/modules/content/props.js +8 -6
  252. package/modules/content/rules.js +29 -47
  253. package/modules/content/templates.js +66 -35
  254. package/modules/content/words.js +19 -6
  255. package/modules/debug/DebugPanel.js +4 -2
  256. package/modules/flow/contract.js +1 -0
  257. package/modules/flow/index.js +24 -14
  258. package/modules/gameplay/Container.js +5 -2
  259. package/modules/gameplay/Containers.js +9 -1
  260. package/modules/gameplay/Dialogue.js +82 -25
  261. package/modules/gameplay/Interactions.js +61 -32
  262. package/modules/gameplay/Inventory.js +56 -13
  263. package/modules/gameplay/Quests.js +133 -24
  264. package/modules/gameplay/boxOps.js +7 -0
  265. package/modules/gameplay/dialogueBubbles.js +14 -9
  266. package/modules/gameplay/inventoryOps.js +11 -7
  267. package/modules/gameplay/pickups.js +43 -16
  268. package/modules/gameplay/questLog.js +4 -2
  269. package/modules/gameplay/questSave.js +6 -1
  270. package/modules/gameplay/quests.contract.js +1 -1
  271. package/modules/grid/Grid.js +1 -1
  272. package/modules/grid/Layer.js +8 -4
  273. package/modules/grid/index.js +21 -15
  274. package/modules/grid/ops.js +43 -46
  275. package/modules/grid/tiles.js +1 -1
  276. package/modules/hlod/index.js +6 -3
  277. package/modules/hud/index.js +6 -4
  278. package/modules/hud/parts.js +4 -4
  279. package/modules/level/contract.js +2 -2
  280. package/modules/level/heightfield.js +17 -21
  281. package/modules/level/index.js +83 -26
  282. package/modules/level/load.js +165 -48
  283. package/modules/level/nodes.js +34 -16
  284. package/modules/lights/index.js +6 -3
  285. package/modules/lights/sources.js +3 -1
  286. package/modules/music/Music.js +4 -2
  287. package/modules/nav/contract.js +7 -5
  288. package/modules/nav/index.js +174 -44
  289. package/modules/nav/navPath.js +45 -10
  290. package/modules/net/index.js +1 -1
  291. package/modules/particles/Particles.js +85 -22
  292. package/modules/particles/effect.js +80 -28
  293. package/modules/particles/shaders.js +17 -0
  294. package/modules/photo/Photo.js +12 -10
  295. package/modules/rigid/RigidBodies.js +200 -57
  296. package/modules/rigid/Vehicles.js +15 -5
  297. package/modules/rigid/collider3d.contract.js +26 -0
  298. package/modules/rigid/ragdoll.js +55 -44
  299. package/modules/rigid/ragdollBones.js +83 -33
  300. package/modules/rigid/refresh.js +10 -0
  301. package/modules/rigid/sync.js +46 -15
  302. package/modules/settings/Settings.js +84 -37
  303. package/modules/settings/apply.js +15 -8
  304. package/modules/settings/sections.js +7 -4
  305. package/modules/settings/strings.js +2 -2
  306. package/modules/sky/skyModule.js +3 -1
  307. package/modules/swarm/Swarm.js +16 -6
  308. package/modules/terrain/ChunkManager.js +10 -16
  309. package/modules/terrain/index.js +17 -11
  310. package/modules/terrain/terrainEdit.js +13 -2
  311. package/modules/terrain/terrainGen.js +5 -3
  312. package/modules/terrain/terrainShape.js +1 -1
  313. package/modules/timeline/Timeline.js +58 -26
  314. package/modules/timeline/Tween.js +19 -13
  315. package/modules/timeline/shots.js +19 -10
  316. package/modules/triggers/index.js +87 -20
  317. package/modules/vegetation/Vegetation.js +4 -3
  318. package/modules/vegetation/draw.js +16 -0
  319. package/modules/vegetation/groundChunks.js +10 -7
  320. package/modules/vegetation/index.js +30 -7
  321. package/modules/water/Water.js +6 -2
  322. package/modules/weather/Weather.js +16 -15
  323. package/modules/weather/weatherDraw.js +7 -6
  324. package/modules/world/World.js +20 -7
  325. package/modules/world/explain.js +1 -1
  326. package/modules/world/index.js +13 -6
  327. package/modules/world/persist.js +23 -8
  328. package/modules/world/pos.js +4 -4
  329. package/modules/world/records.js +13 -7
  330. package/modules/world/sim.js +74 -23
  331. package/modules/world/simFar.js +2 -2
  332. package/modules/world/state.js +31 -6
  333. package/modules/world/thingSource.js +16 -3
  334. package/modules/world/views.js +19 -8
  335. package/package.json +7 -1
  336. package/render/PostFX.js +47 -29
  337. package/render/backend.js +5 -1
  338. package/render/fx/particles.tsl.js +8 -6
  339. package/render/fx/postWebGPU.tsl.js +3 -3
  340. package/render/layers.js +1 -1
  341. package/render/lightmap.js +23 -3
  342. package/render/occlusion.js +43 -12
  343. package/render/patches.js +2 -2
  344. package/render/postWebGL.js +4 -3
  345. package/render/probes.js +25 -0
  346. package/render/shadows.js +2 -2
  347. package/types/core.d.ts +142 -55
  348. package/types/gameplay.d.ts +92 -40
  349. package/types/generated/core/base/I18n.d.ts +2 -2
  350. package/types/generated/core/input/Input.d.ts +16 -2
  351. package/types/generated/core/input/inputSeat.d.ts +26 -0
  352. package/types/generated/core/inspect/DebugOverrides.d.ts +15 -1
  353. package/types/generated/core/ops/Ops.d.ts +2 -1
  354. package/types/generated/core/ops/control.d.ts +12 -2
  355. package/types/generated/core/saves/Saves.d.ts +26 -6
  356. package/types/generated/core/saves/session.d.ts +1 -1
  357. package/types/generated/core/scene/Views.d.ts +1 -1
  358. package/types/generated/core/stream/Stream.d.ts +6 -4
  359. package/types/generated/modules/grid/Grid.d.ts +1 -0
  360. package/types/generated/modules/particles/Particles.d.ts +4 -3
  361. package/types/generated/modules/timeline/Timeline.d.ts +5 -4
  362. package/types/generated/modules/weather/Weather.d.ts +1 -7
  363. package/types/generated/modules/world/World.d.ts +6 -4
  364. package/types/generated/render/PostFX.d.ts +6 -14
  365. package/types/nav.d.ts +36 -4
  366. package/types/physics.d.ts +55 -7
  367. package/types/pixel.d.ts +75 -0
  368. package/types/world.d.ts +14 -8
  369. package/ui/Parts.js +9 -2
  370. package/ui/theme.js +2 -2
  371. package/core/scene/engineCamera.js +0 -32
  372. package/modules/camera/projection.js +0 -21
@@ -0,0 +1,72 @@
1
+ // compositeGround({ parts }): one module that holds the exclusive 'ground' slot and answers each query from the part whose region contains the point,
2
+ // so a terrain island and a hand-made level (or several levels) coexist without a second ground path. Parts are modules installed with { part: true }
3
+ // (terrain({ part: true }), level({ part: true })): they give their provider as module.ground instead of taking the slot.
4
+ // parts: [{ of: 'terrain' | 'level', region?, priority? }] (or { ground: provider } for a provider object you made)
5
+ // region: omitted = everywhere | (x, z) => boolean | { volume } (the plain volume water and triggers take, asked at y 0: a region has no height). Higher priority wins where regions overlap (default 0, then list order)
6
+ import { flatGround } from './ground.js';
7
+ import { codedError } from '../base/errorHints.js';
8
+ import { keysSchema } from '../base/params.js';
9
+
10
+ const PARAMS = keysSchema(['parts']);
11
+ const bad = msg => codedError('module-params', 'compositeGround: ' + msg);
12
+ const inRegion = r => {
13
+ if (r == null) return () => true;
14
+ if (typeof r === 'function') return r;
15
+ if (typeof r.volume?.contains === 'function') { const p = { x: 0, y: 0, z: 0 }; return (x, z) => { p.x = x; p.z = z; return r.volume.contains(p); }; }
16
+ throw bad('region must be a function (x, z) => boolean or { volume: { contains({ x, y, z }) } }');
17
+ };
18
+
19
+ export function compositeGround(opts = {}) {
20
+ const list = opts.parts;
21
+ if (!Array.isArray(list) || !list.length) throw bad('pass { parts }: a non-empty list of { of: "terrain" | "level", region?, priority? }');
22
+ for (const p of list) if (!p.of && !p.ground) throw bad('every part needs of: "terrain" | "level" (a module installed with { part: true }) or ground: provider');
23
+ const requires = [...new Set(list.map(p => p.of).filter(Boolean))];
24
+ return {
25
+ name: 'compositeGround', type: 'world', provides: ['ground'], requires, stage: 'ground', label: 'Composite ground', options: opts, params: PARAMS,
26
+ install(engine, ctx) {
27
+ const parts = list.map((p, i) => {
28
+ const g = p.ground ?? engine[p.of]?.ground;
29
+ if (!g) throw bad(`engine.${p.of} gave no ground; install it with ${p.of}({ part: true })`);
30
+ return { g: { ...flatGround, ...g }, in: inRegion(p.region), priority: p.priority ?? 0, i };
31
+ }).sort((a, b) => b.priority - a.priority || a.i - b.i);
32
+ // the part answering at a point: first (by priority) whose region has it and that has ground there; else the last part, so a query always answers
33
+ const at = (x, z) => { for (const p of parts) if (p.in(x, z) && p.g.has(x, z)) return p.g; return parts[parts.length - 1].g; };
34
+ const first = k => parts.find(p => p.g[k] != null)?.g[k];
35
+ const out = {
36
+ height: (x, z, refY) => at(x, z).height(x, z, refY),
37
+ slope: (x, z, refY) => at(x, z).slope(x, z, refY),
38
+ type: (x, z, refY) => at(x, z).type(x, z, refY),
39
+ water: (x, z, refY) => { const g = at(x, z); return g.water ? g.water(x, z, refY) : g.waterLevel; },
40
+ waterLevel: Math.max(...parts.map(p => p.g.waterLevel)),
41
+ has: (x, z) => parts.some(p => p.in(x, z) && p.g.has(x, z)),
42
+ // a part with no void (a level, -Infinity) must not hide the part that has one
43
+ voidY: () => { const ys = parts.map(p => p.g.voidY()).filter(Number.isFinite); return ys.length ? Math.min(...ys) : -Infinity; },
44
+ forEachCollider: (x, z, range, fn) => { for (const p of parts) p.g.forEachCollider?.(x, z, range, fn); },
45
+ };
46
+ for (const k of ['chunkSize', 'viewRange']) if (first(k) != null) out[k] = first(k);
47
+ // physics asks like every other query: a part gives triangles only where it answers, or a terrain's hills stand invisible and solid inside a level's region.
48
+ // A triangle stays when any corner is the part's own, so no hole opens along a region's edge. Worked out once per chunk version and level version.
49
+ const solid = parts.find(p => p.g.chunkCollision)?.g, cut = new WeakMap();
50
+ const own = ({ positions: p, ox, oz }) => {
51
+ const kept = new Float32Array(p.length); let n = 0;
52
+ for (let i = 0; i < p.length; i += 9) {
53
+ if (at(ox + p[i], oz + p[i + 2]) !== solid && at(ox + p[i + 3], oz + p[i + 5]) !== solid && at(ox + p[i + 6], oz + p[i + 8]) !== solid) continue;
54
+ kept.set(p.subarray(i, i + 9), n); n += 9;
55
+ }
56
+ return n === p.length ? p : kept.subarray(0, n);
57
+ };
58
+ if (solid) out.chunkCollision = (cx, cz) => {
59
+ const data = solid.chunkCollision(cx, cz); if (!data) return data;
60
+ const version = out.staticVersion?.() ?? 0;
61
+ let c = cut.get(data.token);
62
+ if (c?.version !== version) cut.set(data.token, c = { version, token: {}, positions: own(data) });
63
+ return { ...data, token: c.token, positions: c.positions };
64
+ };
65
+ if (parts.some(p => p.g.staticTrimeshes)) {
66
+ out.staticTrimeshes = () => parts.flatMap(p => p.g.staticTrimeshes?.() ?? []);
67
+ out.staticVersion = () => parts.reduce((n, p) => n + (p.g.staticVersion?.() ?? 0), 0);
68
+ }
69
+ ctx.ground.provide(out);
70
+ },
71
+ };
72
+ }
@@ -0,0 +1,17 @@
1
+ // The one height tolerance of walking. Everything that asks "is this the same floor" uses it (nav.point, arrival, passing path points, A*, NPC avoidance), so a floor
2
+ // can't count as near for one system and far for another. Its own file with no imports because the path worker needs it, and movement.js brings in the option checks.
3
+
4
+ /** Two heights are one floor when a body standing at one would reach the other. body: engine.movement.height */
5
+ export const sameFloor = (a, b, body) => Math.abs(a - b) <= body;
6
+
7
+ /**
8
+ * Which of a spot's layers below its top a walker comes to: the highest not above lim (its height plus a step), else the lowest, so a cave with only a ceiling overhead still has a floor.
9
+ * The ground (level heightfield) and the path worker's snapshot of it both choose with this, so a floor can't be one height to the search and another to the walker.
10
+ * @param {{ y: number }[]} layers
11
+ * @param {number} lim
12
+ */
13
+ export function layerUnder(layers, lim) {
14
+ let best = null, low = layers[0];
15
+ for (const l of layers) { if (l.y <= lim && !(best?.y >= l.y)) best = l; if (l.y < low.y) low = l; }
16
+ return best ?? low;
17
+ }
@@ -126,3 +126,5 @@ export async function decodePng(input) {
126
126
  if (bitDepth === 16) { samples = new Uint16Array(width * height * channels); for (let i = 0; i < samples.length; i++) samples[i] = (out[i * 2] << 8) | out[i * 2 + 1]; }
127
127
  return { samples, width, height, channels, bitDepth };
128
128
  }
129
+
130
+ export const handRolled = [{ kind: 'grid', seen: 'blending over a height / field array by hand', use: 'sampleGrid(data, { width, height, size, interp }) -> (x, z) => value; engine.assets.gridFromImage reads one from a PNG', quiet: /\bsampleGrid\b/, code: /\b(heights?|heightmap|hm|elevation|terrainData|heightData|field)\w*\s*\[/i, near: [{ re: /Math\.floor\(/, lines: 6 }, { re: /\(\s*1\s*-\s*\w+\s*\)|\blerp\s*\(|\bmix\s*\(/, lines: 6 }], tags: false }];
@@ -0,0 +1,14 @@
1
+ // What any ground provider must give (an object contract, shared check @threedog/tools/contract): the plain flat ground, a terrain, a level and compositeGround's
2
+ // answer all pass it, and so must a game's own (engine.setGround(g) or ctx.ground.provide(g) in a module holding provides: ['ground']).
3
+ // height(x, z, refY?) ground height in meters; -Infinity where there is no ground. refY picks the layer on multi-layer ground (the highest not above refY + one step)
4
+ // slope(x, z, refY?) slope; type(x, z, refY?) ground type name ('void' where there is no ground)
5
+ // waterLevel global water surface height (-Infinity = none); water that differs per point is engine.addWaterBody({ query })
6
+ // has? / voidY? / forEachCollider? / chunkSize? ... optional; missing ones are filled from the flat ground
7
+ // engine.surface / slope / groundType / waterAt(x, z, refY) read these. compositeGround({ parts }) is the way to run more than one provider.
8
+ export default {
9
+ name: 'ground',
10
+ kind: 'object',
11
+ api: ['height', 'slope', 'type'],
12
+ fields: ['waterLevel'],
13
+ calls: [['height', 0, 0, 0], ['slope', 0, 0, 0], ['type', 0, 0, 0]],
14
+ };
@@ -1,9 +1,9 @@
1
1
  // Ground API (part of Engine, mixed into Engine.prototype): whoever provides ground height is the "terrain" -- a procedural terrain module, a hand-made level, or a flat plane.
2
2
  // The queries below take (x, z), or a Vector3 / Object3D directly: engine.surface(mesh.position)
3
3
  import { xzOf } from '../base/math.js';
4
- import { warnOnce, fmt } from '../base/validate.js';
4
+ import { warnOnce, fmt, DEV } from '../base/validate.js';
5
5
  import { readParams, keysSchema } from '../base/params.js';
6
- import { coded } from '../base/errorHints.js';
6
+ import { coded, codedError } from '../base/errorHints.js';
7
7
 
8
8
  // Default ground: an infinite flat plane at y = 0. A terrain or level module replaces it
9
9
  export const flatGround = {
@@ -13,6 +13,7 @@ export const flatGround = {
13
13
  // height below which something has fallen out of the world (terrain:void); only an outline sets a finite one
14
14
  voidY: () => -Infinity,
15
15
  };
16
+ const OVER_HOLDER = "engine.setGround: module {holder} holds the ground and this call covers it until the next provider. A module gives the ground with provides: ['ground'] and ctx.ground.provide";
16
17
  const NO_GROUND = '{who}: there is no ground at ({x}, {z}) (outside terrain({ shape })){left}; check engine.ground.has(x, z) first';
17
18
  const noGround = (who, x, z, left = '') => fmt(NO_GROUND, { who, x: x.toFixed(1), z: z.toFixed(1), left });
18
19
 
@@ -31,7 +32,9 @@ export function surfaceOr(e, x, z, refY, fallback = 0) {
31
32
  const y = e.surface(x, z, refY);
32
33
  return y === -Infinity ? fallback : y;
33
34
  }
34
- const WATER_KEYS = ['position', 'radius', 'halfWidth', 'halfDepth', 'level'];
35
+ /** Below this height something has left the world, on any ground: the rule 'fall' is asked about a body here, and a dev build tells of a player here */
36
+ export const FALL_Y = -200;
37
+ const WATER_KEYS = ['position', 'radius', 'halfWidth', 'halfDepth', 'level', 'query', 'bounds', 'mesh', 'volume'];
35
38
 
36
39
  // engine.ground.forEachCollider = the provider's own followed by every added source; absent when there is none
37
40
  function joinColliders(e) {
@@ -43,8 +46,22 @@ function joinColliders(e) {
43
46
  e.ground = g;
44
47
  }
45
48
 
49
+ function writeGround(e, g) { e._groundOwn = g.forEachCollider ?? null; e.ground = { ...flatGround, ...g }; joinColliders(e); }
50
+
46
51
  export const groundMethods = {
47
- setGround(g) { this._groundOwn = g.forEachCollider ?? null; this.ground = { ...flatGround, ...g }; joinColliders(this); },
52
+ // the game's own door: it wins over a module's ground until the next provider. A module writes through ctx.ground.provide, which holds the 'ground' slot
53
+ setGround(g) {
54
+ const holder = this.stacks?.has('ground') ? this.stacks.get('ground').value() : null;
55
+ if (DEV && holder && this._curModule?.name !== holder) warnOnce(coded('shared-taken', fmt(OVER_HOLDER, { holder })));
56
+ this._groundBy = null;
57
+ writeGround(this, g);
58
+ },
59
+ /** @internal ctx.ground.provide: the handle hands back the flat ground, unless the game wrote its own since */
60
+ _provideGround(g) {
61
+ const by = this._groundBy = {};
62
+ writeGround(this, g);
63
+ return { remove: () => { if (this._groundBy === by) { this._groundBy = null; writeGround(this, {}); } } };
64
+ },
48
65
  /**
49
66
  * @internal module plumbing: add a source of static circle colliders (x, z, r) to engine.ground.forEachCollider, which collision and path
50
67
  * planning read. It survives a later setGround (a level installed after the module), so a module streaming its own colliders
@@ -61,10 +78,10 @@ export const groundMethods = {
61
78
  if (typeof x === 'object') { refY = z; [x, z] = xzOf(x); }
62
79
  return this.ground.height(x, z, refY);
63
80
  },
64
- /** Slope */
65
- slope(x, z) { if (typeof x === 'object') [x, z] = xzOf(x); return this.ground.slope(x, z); },
66
- /** Ground type (grass, sand...), used by footsteps and particles */
67
- groundType(x, z) { if (typeof x === 'object') [x, z] = xzOf(x); return this.ground.type(x, z); },
81
+ /** Slope; refY picks the layer on multi-layer ground, as in surface() */
82
+ slope(x, z, refY) { if (typeof x === 'object') { refY = z; [x, z] = xzOf(x); } return this.ground.slope(x, z, refY); },
83
+ /** Ground type (grass, sand...), used by footsteps and particles; refY picks the layer as in surface() */
84
+ groundType(x, z, refY) { if (typeof x === 'object') { refY = z; [x, z] = xzOf(x); } return this.ground.type(x, z, refY); },
68
85
  /** Put an object on the ground beneath it (y = ground height + offset); returns the object. With multi-layer ground the object's current y is the reference height: things under a bridge stay on the ground, things on it land on the deck */
69
86
  snapToGround(obj, offset = 0) {
70
87
  const p = obj.position, y = this.surface(p.x, p.z, p.y);
@@ -74,25 +91,43 @@ export const groundMethods = {
74
91
  }
75
92
  p.y = y + offset; return obj;
76
93
  },
77
- /** Water surface height at a point: the highest of the global water level and the water bodies (lake, pond, river segment) there; -Infinity if there is no water */
78
- waterAt(x, z) {
79
- if (typeof x === 'object') [x, z] = xzOf(x);
80
- let lv = this.ground.waterLevel;
94
+ /** Water surface height at a point: the highest of the global water level and the water bodies (lake, pond, river segment) there; -Infinity if there is no water. refY (a height at the point) matters only to bodies with their own query (a second floor's pool) */
95
+ waterAt(x, z, refY) {
96
+ if (typeof x === 'object') { refY = z; [x, z] = xzOf(x); }
97
+ let lv = this.ground.water ? this.ground.water(x, z, refY) : this.ground.waterLevel;
81
98
  const bodies = this.waterBodies;
82
99
  for (let i = 0; i < bodies.length; i++) { // indexed: runs per sample, no iterator
83
100
  const b = bodies[i];
84
- const inside = b.radius != null ? (x - b.x) ** 2 + (z - b.z) ** 2 < b.radius * b.radius
85
- : Math.abs(x - b.x) < b.hw && Math.abs(z - b.z) < b.hd;
86
- if (inside && b.level > lv) lv = b.level;
101
+ let v;
102
+ if (b.query) { // the game's own water: a query, bounds only skip the call
103
+ const bb = b.bounds;
104
+ if (bb && (x < bb.min.x || x > bb.max.x || z < bb.min.z || z > bb.max.z || (refY != null && (refY < bb.min.y || refY > bb.max.y)))) continue;
105
+ v = b.query(x, z, refY); if (v == null) continue;
106
+ } else {
107
+ const inside = b.radius != null ? (x - b.x) ** 2 + (z - b.z) ** 2 < b.radius * b.radius
108
+ : Math.abs(x - b.x) < b.hw && Math.abs(z - b.z) < b.hd;
109
+ if (!inside) continue;
110
+ v = b.level;
111
+ }
112
+ if (v > lv) lv = v;
87
113
  }
88
114
  return lv;
89
115
  },
90
- /** Add a water body: a circle { position, radius, level } or a rectangle { position, halfWidth, halfDepth, level } (meters). Returns a handle { body, remove() }. The water module draws it */
116
+ /** Add a water body: a circle { position, radius, level } or a rectangle { position, halfWidth, halfDepth, level } (meters); the water module draws it.
117
+ * Your own water (a river, a pool on a floor): { query(x, z, y) -> level | null, bounds?: Box3-like { min, max }, mesh? } or { volume: { contains({x,y,z}), bounds }, level }; the engine draws nothing for these, you add the mesh. Returns { body, remove() } */
91
118
  addWaterBody(opts) {
92
119
  readParams('engine.addWaterBody()', keysSchema(WATER_KEYS), opts);
120
+ let b;
121
+ if (opts.query || opts.volume) {
122
+ const v = opts.volume, level = opts.level;
123
+ if (!opts.query && !(v && typeof v.contains === 'function' && Number.isFinite(level))) throw codedError('module-params', 'engine.addWaterBody(): { volume } needs volume.contains(point) and a numeric level');
124
+ if (opts.query && typeof opts.query !== 'function') throw codedError('module-params', 'engine.addWaterBody({ query }): query must be (x, z, y) => level | null');
125
+ b = { query: opts.query ?? ((x, z, y) => v.contains({ x, y: y ?? level, z }) ? level : null), bounds: opts.bounds ?? v?.bounds ?? null, mesh: opts.mesh ?? null, level: level ?? null };
126
+ } else {
93
127
  const [x, z] = xzOf(opts.position);
94
- const b = opts.radius != null ? { x, z, radius: opts.radius, level: opts.level }
128
+ b = opts.radius != null ? { x, z, radius: opts.radius, level: opts.level }
95
129
  : { x, z, hw: opts.halfWidth ?? 1, hd: opts.halfDepth ?? 1, level: opts.level };
130
+ }
96
131
  this.waterBodies.push(b); this.events.emit('water:add', b);
97
132
  const remove = () => {
98
133
  if (!this.waterBodies.includes(b)) return;
@@ -0,0 +1,154 @@
1
+ // Pixel-game math and the one object built on it (threedog/pixel). One art pixel on screen is `cell` = 1 / pixelsPerMeter world units along the camera's right and up
2
+ // axes. This file is the only place that derives those axes: the cameras' pixelSnap (modules/camera/pixelSnap.js) and pixelSprite call pixelGrid, so the camera and
3
+ // what it shows cannot round on two different grids. No default look: materials come from the game.
4
+ //
5
+ // Why rounding happens on screen axes and not world axes: a camera turned 45 degrees moves diagonally across world x and z, so world-axis rounding (or a world-axis
6
+ // clamp rounded afterwards) lands between art pixels. Why the view's corner goes on the lattice and not its center: with an odd number of art pixels the center sits on half
7
+ // a pixel, and every sprite edge would then fall exactly on a pixel center, where nearest sampling picks either side from frame to frame. The grid has no anchor to
8
+ // keep: its lattice runs through the world origin and the axes are read fresh on each call, so a zoom or a turn needs no reset.
9
+ import * as THREE from 'three';
10
+ import { codedError } from '../base/errorHints.js';
11
+
12
+ const _q = new THREE.Quaternion(), _pq = new THREE.Quaternion(), _p = new THREE.Vector3(), _s = new THREE.Vector3(), _y = new THREE.Vector3(0, 1, 0);
13
+ // a view looking almost straight down would stretch a vertical sprite without limit; a sprite that tall is already unreadable
14
+ const MIN_COS_PITCH = 0.05;
15
+ const TIE = 1e-4;
16
+
17
+ /**
18
+ * The art pixel grid of an orthographic camera. Pure math on the camera's current orientation.
19
+ * @param {{ camera: THREE.Camera, pixelsPerMeter: number }} o
20
+ */
21
+ export function pixelGrid({ camera, pixelsPerMeter } = /** @type {any} */ ({})) {
22
+ if (!camera?.isCamera) throw codedError('camera-option', 'pixelGrid({ camera, pixelsPerMeter }): camera is the camera that draws the picture, usually engine.camera');
23
+ if (!(pixelsPerMeter > 0)) throw codedError('camera-option', `pixelGrid({ pixelsPerMeter }): how many art pixels one world unit covers, above 0; got ${JSON.stringify(pixelsPerMeter)}`);
24
+ const t = 1 / pixelsPerMeter, right = new THREE.Vector3(), up = new THREE.Vector3(), forward = new THREE.Vector3(), axes = { right, up, forward };
25
+ const placed = { position: new THREE.Vector3(), error: { x: 0, y: 0 } }, shift = { x: 0, y: 0 }, _t = new THREE.Vector3();
26
+ const round = v => Math.round(v / t) * t;
27
+ const grid = {
28
+ camera, pixelsPerMeter, cell: t,
29
+ /** The camera's unit right, up and forward axes now. Throws on a perspective camera: its screen axes change across the picture, so no grid fits */
30
+ axes() {
31
+ if (!grid.camera.isOrthographicCamera) throw codedError('camera-option', "pixelGrid and pixelSnap work on an orthographic camera only: a perspective view has no single art pixel size. Set projection: 'orthographic' on the camera, or drop pixelSnap");
32
+ grid.camera.getWorldQuaternion(_q);
33
+ right.set(1, 0, 0).applyQuaternion(_q); up.set(0, 1, 0).applyQuaternion(_q); forward.set(0, 0, -1).applyQuaternion(_q);
34
+ return axes;
35
+ },
36
+ /** World point -> meters along the screen axes: x right, y up, z forward */
37
+ toScreen(world, out = new THREE.Vector3()) {
38
+ grid.axes();
39
+ return out.set(right.dot(world), up.dot(world), forward.dot(world));
40
+ },
41
+ /** Meters along the screen axes -> world point */
42
+ toWorld(screen, out = new THREE.Vector3()) {
43
+ grid.axes();
44
+ const { x, y, z } = screen;
45
+ return out.copy(right).multiplyScalar(x).addScaledVector(up, y).addScaledVector(forward, z);
46
+ },
47
+ /** The world point rounded to the art grid on the two screen axes; depth stays, so what is in front stays in front */
48
+ snap(world, out = new THREE.Vector3()) {
49
+ const s = grid.toScreen(world, _s);
50
+ return grid.toWorld(s.set(round(s.x), round(s.y), s.z), out);
51
+ },
52
+ /** How far snap moves this point, in art pixels on each screen axis (-0.5 to 0.5). Handed over for a game that wants to use the leftover */
53
+ error(world) {
54
+ const s = grid.toScreen(world, _s);
55
+ return { x: (round(s.x) - s.x) / t, y: (round(s.y) - s.y) / t };
56
+ },
57
+ /**
58
+ * snap for what the camera follows. Its offset from the camera's exact position is what must stay steady on screen, so it takes the rounding the camera got in
59
+ * place(). snap() would round the two on their own, and they would step on different frames: a one-pixel shake. Use it for that one object: a thing standing
60
+ * still would creep against the ground as the leftover changes.
61
+ */
62
+ snapFollowed(world, out = new THREE.Vector3()) {
63
+ const s = grid.toScreen(world, _s);
64
+ // the small bias: with an odd buffer a follower at the view's center is exactly half a pixel off the grid, and float noise would flip that tie every frame
65
+ return grid.toWorld(s.set(round(s.x + shift.x + t * TIE), round(s.y + shift.y + t * TIE), s.z), out);
66
+ },
67
+ /** World units of view height a picture of `rows` art pixels needs */
68
+ viewHeight(rows) { return rows * t; },
69
+ /** Does the camera really show rows / pixelsPerMeter of the world? If not, the grid and the picture disagree. Read from the projection, so camera.zoom counts */
70
+ agrees(rows) { return Math.abs(2 / grid.camera.projectionMatrix.elements[5] - rows * t) <= rows * t * 1e-6; },
71
+ /**
72
+ * Where a camera wanting `position` goes: clamp, then round. Bounds { minX, maxX, minZ, maxZ, minY?, maxY? } are projected on the screen axes and rounded inward, and
73
+ * the view's corner is clamped to them, so the rounding after it cannot cross a bound. A level smaller than the view is centered on that axis. Result: { position,
74
+ * error } (both reused between calls), error in art pixels from the clamped position.
75
+ * @param {THREE.Vector3} position @param {{ columns: number, rows: number, bounds?: any }} view
76
+ */
77
+ place(position, { columns, rows, bounds }) {
78
+ const fit = (v, size, key, axis) => {
79
+ let corner = v - size / 2;
80
+ if (bounds) {
81
+ let lo = Infinity, hi = -Infinity;
82
+ for (const x of [bounds.minX, bounds.maxX]) for (const y of [bounds.minY ?? 0, bounds.maxY ?? 0]) for (const z of [bounds.minZ, bounds.maxZ]) {
83
+ const d = x * axis.x + y * axis.y + z * axis.z;
84
+ if (d < lo) lo = d;
85
+ if (d > hi) hi = d;
86
+ }
87
+ const a = Math.ceil(lo / t) * t, b = Math.floor((hi - size) / t) * t;
88
+ corner = a > b ? (lo + hi - size) / 2 : Math.min(b, Math.max(a, corner));
89
+ }
90
+ const rounded = round(corner);
91
+ placed.error[key] = (rounded - corner) / t; shift[key] = rounded - corner;
92
+ return rounded + size / 2;
93
+ };
94
+ const s = grid.toScreen(position, _t);
95
+ s.x = fit(s.x, columns * t, 'x', right); s.y = fit(s.y, rows * t, 'y', up);
96
+ grid.toWorld(s, placed.position);
97
+ return placed;
98
+ },
99
+ };
100
+ return grid;
101
+ }
102
+
103
+ /**
104
+ * Write a sheet frame into a sprite's UVs. Frames count left to right, top to bottom. flip mirrors it on the UVs, not with a negative scale, so the triangle's winding and
105
+ * its shadow stay right.
106
+ * @param {THREE.Mesh} mesh @param {number} frame @param {boolean} [flip] left out: as it was
107
+ */
108
+ export function spriteFrame(mesh, frame, flip) {
109
+ const d = mesh.userData.pixelSprite;
110
+ if (!d) throw codedError('engine-misuse', 'spriteFrame(mesh, frame): the mesh must come from pixelSprite()');
111
+ if (!(Number.isInteger(frame) && frame >= 0 && frame < d.columns * d.rows)) throw codedError('engine-misuse', `spriteFrame: frame ${JSON.stringify(frame)} is outside the sheet, which has ${d.columns * d.rows} frames`);
112
+ d.frame = frame; d.flip = flip ?? d.flip;
113
+ const c = frame % d.columns, r = Math.floor(frame / d.columns), u0 = c / d.columns, u1 = (c + 1) / d.columns, v1 = 1 - r / d.rows, v0 = 1 - (r + 1) / d.rows;
114
+ const [l, h] = d.flip ? [u1, u0] : [u0, u1], uv = mesh.geometry.attributes.uv;
115
+ uv.setXY(0, l, v1); uv.setXY(1, h, v1); uv.setXY(2, l, v0); uv.setXY(3, h, v0); // PlaneGeometry's order: top left, top right, bottom left, bottom right
116
+ uv.needsUpdate = true;
117
+ return mesh;
118
+ }
119
+
120
+ /**
121
+ * A sprite for an orthographic view of a 3D scene: a plain THREE.Mesh, a vertical plane. Standing upright is what keeps a head out of the wall behind it: the whole figure
122
+ * has the depth of its feet. A plane tilted toward the camera would lean its head back through that wall. The height is stretched by 1 / cos(pitch), which the view's
123
+ * tilt takes back, so one texel is one art pixel.
124
+ * Facing comes from the camera's forward direction, not its position: under an orthographic camera, aiming at the position would give every sprite a different angle.
125
+ * It is applied just before drawing, because a character's root turns with its facing and the sprite must not. mesh.position stays exact (physics, saves, gameplay read it);
126
+ * only the drawn matrix is rounded.
127
+ * @param {{ grid: ReturnType<typeof pixelGrid>, material: THREE.Material, width: number, height: number, columns?: number, rows?: number, frame?: number, flip?: boolean,
128
+ * anchor?: [number, number], snap?: 'world' | 'followed' | false }} o width / height: one frame in texels; anchor: the point on the frame at the mesh's origin, 0 to 1 from the
129
+ * bottom left, feet by default; snap: 'followed' for the one object the camera follows (grid.snapFollowed)
130
+ * @returns {THREE.Mesh}
131
+ */
132
+ export function pixelSprite({ grid, material, width, height, columns = 1, rows = 1, frame = 0, flip = false, anchor = [0.5, 0], snap = 'world' } = /** @type {any} */ ({})) {
133
+ if (!grid?.axes) throw codedError('engine-misuse', 'pixelSprite({ grid }): grid comes from pixelGrid() or engine.cameraRig.pixelSnap.grid');
134
+ if (!material?.isMaterial) throw codedError('engine-misuse', 'pixelSprite({ material }): a three.js material of your own; the engine brings no look');
135
+ if (!(width > 0 && height > 0)) throw codedError('engine-misuse', `pixelSprite({ width, height }): one frame's size in texels; got ${width} x ${height}`);
136
+ if (![false, 'world', 'followed'].includes(snap)) throw codedError('engine-misuse', `pixelSprite({ snap: ${JSON.stringify(snap)} }): use 'world', 'followed' or false`);
137
+ const t = grid.cell, w = width * t, h = height * t;
138
+ // the anchor rounds to a whole texel: otherwise the frame's edges fall between art pixels once the anchor is on the grid
139
+ const geometry = new THREE.PlaneGeometry(w, h).translate(w / 2 - Math.round(anchor[0] * width) * t, h / 2 - Math.round(anchor[1] * height) * t, 0);
140
+ const mesh = new THREE.Mesh(geometry, material);
141
+ mesh.userData.pixelSprite = { columns, rows, frame, flip };
142
+ spriteFrame(mesh, frame);
143
+ mesh.onBeforeRender = () => {
144
+ const f = grid.axes().forward, flat = Math.max(MIN_COS_PITCH, Math.hypot(f.x, f.z)), parent = mesh.parent;
145
+ const turn = _pq.setFromAxisAngle(_y, Math.atan2(-f.x, -f.z));
146
+ mesh.quaternion.copy(turn);
147
+ if (parent) mesh.quaternion.premultiply(parent.getWorldQuaternion(_pq).invert());
148
+ mesh.scale.y = 1 / flat;
149
+ mesh.updateMatrix();
150
+ if (parent) mesh.matrixWorld.multiplyMatrices(parent.matrixWorld, mesh.matrix); else mesh.matrixWorld.copy(mesh.matrix);
151
+ if (snap) mesh.matrixWorld.setPosition(grid[snap === 'followed' ? 'snapFollowed' : 'snap'](_p.setFromMatrixPosition(mesh.matrixWorld), _p));
152
+ };
153
+ return mesh;
154
+ }
@@ -0,0 +1,167 @@
1
+ // The renderer's pixel ratio has one owner, this file: every engine write goes through it, and it decides which request wins, so no two entries fight
2
+ // by "who wrote last". Two modes:
3
+ // ratio (the default) writeRatio: the game's and settings' engine.setPixelRatio (askRatio), adaptive resolution under it, the tier's default, a photo's
4
+ // borrowed ratio.
5
+ // pixelSize (createEngine({ pixelSize }), engine.setPixelSize) one art pixel is k real screen pixels: the ratio is devicePixelRatio / k and fitPixelSize
6
+ // alone sets the drawing buffer. Everything else asking for a ratio is held off, refused or kept for later: adaptive stops (engine.adaptive.on
7
+ // reads false), the tier only updates what comes back when pixelSize ends, a photo keeps the art pixels, engine.setPixelRatio throws.
8
+ // A direct renderer.setPixelRatio by the game is not refused (hard rule 4): the engine yields in both modes (view.pixelRatio in core/ops/owned.js).
9
+ // tests/specs/pixel-size.mjs guards that no other file calls renderer.setPixelRatio.
10
+ import { DEV, warnOnce } from '../base/validate.js';
11
+ import { coded, codedError } from '../base/errorHints.js';
12
+ import { ownMsaa } from '../../render/backend.js';
13
+ import { defaultPixelRatio } from './tier.js';
14
+
15
+ const dpr = () => devicePixelRatio || 1;
16
+
17
+ /** Does pixelSize decide the ratio now: for modules whose rows or tools would otherwise ask for one @param {any} e */
18
+ export const pixelSizeOn = e => e._pixelSize != null;
19
+
20
+ /** The ratio a renderer starts with, before the engine's owned rows exist @param {any} r @param {string} tier @param {number} [pixelRatio] */
21
+ export function firstRatio(r, tier, pixelRatio) { r.setPixelRatio(pixelRatio ?? defaultPixelRatio(dpr(), tier)); }
22
+
23
+ /**
24
+ * The one write in ratio mode; re-reading it after keeps this from counting as an outside write. Skips an equal value because three's setPixelRatio resizes
25
+ * the canvas, which clears the drawing buffer. Does nothing under pixelSize, so a caller that missed the mode still cannot move the art pixels.
26
+ * @param {any} e @param {number} p
27
+ */
28
+ export function writeRatio(e, p) {
29
+ if (e._pixelSize != null) return;
30
+ if (Math.abs(e.renderer.getPixelRatio() - p) > 0.001) e.renderer.setPixelRatio(p);
31
+ e._oPixelRatio.mark();
32
+ }
33
+
34
+ /**
35
+ * engine.setPixelRatio. It is the game's (or settings') request: written even when the game took the ratio. It is also the new ceiling, or adaptive
36
+ * resolution would climb back to the old one and undo the engine's own named entry where the raw three.js call stays. Adaptive writes through writeRatio.
37
+ * @param {any} e @param {number} p
38
+ */
39
+ export function askRatio(e, p) {
40
+ if (e._pixelSize != null) throw codedError('pixel-conflict', `engine.setPixelRatio(${p}): pixelSize ${e._pixelSize} decides the ratio now. Keep pixelSize and drop this call, or call engine.setPixelSize(null) first`);
41
+ writeRatio(e, p);
42
+ Object.assign(e.adaptive, { max: p, lowered: false, from: null, good: 0 });
43
+ }
44
+
45
+ /**
46
+ * The real device became known in start(): the tier's default ratio, unless the game chose one or does not leave the renderer to the engine. Under pixelSize
47
+ * it is kept for when pixelSize ends.
48
+ * @param {any} e @param {string} tier
49
+ */
50
+ export function tierRatio(e, tier) {
51
+ if (!e._ownsRenderer || e._createParams.pixelRatio != null) return;
52
+ const p = e.adaptive.base = defaultPixelRatio(dpr(), tier);
53
+ if (e._pixelSize != null) e.adaptive.max = p; else askRatio(e, p);
54
+ }
55
+
56
+ /**
57
+ * Hand the size and ratio to a renderer that replaces this one, exactly as they were: a recomputed size would move the art pixels.
58
+ * @param {any} from @param {any} to @param {any} size a THREE.Vector2 to read into
59
+ */
60
+ export function carryRatio(from, to, size) { from.getSize(size); to.setDrawingBufferSize(size.x, size.y, from.getPixelRatio()); }
61
+
62
+ /**
63
+ * A ratio for one synchronous draw (a photo at a higher resolution). Returns the call that puts the ratio back. check() first: an outside write not noticed
64
+ * yet would otherwise be marked as the engine's on the way back. Under pixelSize the ratio stays, because a finer buffer draws a picture without the art
65
+ * pixels the game chose.
66
+ * @param {any} e @param {number} p @returns {() => void}
67
+ */
68
+ export function borrowRatio(e, p) {
69
+ if (e._pixelSize != null) return () => {};
70
+ e._oPixelRatio.check();
71
+ const back = e.renderer.getPixelRatio();
72
+ writeRatio(e, p);
73
+ return () => writeRatio(e, back);
74
+ }
75
+
76
+ /** Note the canvas's size in real screen pixels from a ResizeObserver entry; browsers without devicePixelContentBoxSize leave it unknown @param {any} e @param {ResizeObserverEntry} entry */
77
+ export function noteDeviceBox(e, entry) {
78
+ const s = entry.devicePixelContentBoxSize?.[0];
79
+ if (s) e._deviceBox = { w: s.inlineSize, h: s.blockSize };
80
+ }
81
+
82
+ /**
83
+ * The canvas's box in real screen pixels, measured by the browser. CSS size times the ratio is only the fallback: at 150% the CSS size is already rounded, and
84
+ * that error is what makes art pixels uneven. The measured box excludes the padding fitPixelSize added, so it is put back here. Device emulation (DevTools, Playwright's
85
+ * deviceScaleFactor) reports the box unscaled, so a measure far from the CSS size is not used.
86
+ * @param {any} e @param {number} w CSS width @param {number} h CSS height @param {number} s device pixel ratio
87
+ */
88
+ function deviceBox(e, w, h, s) {
89
+ const b = e._deviceBox, st = e.renderer.domElement.style;
90
+ const dw = b && b.w + Math.round((parseFloat(st.paddingRight) || 0) * s), dh = b && b.h + Math.round((parseFloat(st.paddingBottom) || 0) * s);
91
+ if (b && Math.abs(dw - w * s) <= s + 1 && Math.abs(dh - h * s) <= s + 1) return { w: dw, h: dh };
92
+ return { w: Math.round(w * s), h: Math.round(h * s) };
93
+ }
94
+
95
+ const padCanvas = (st, right, bottom) => { st.paddingRight = right ? right + 'px' : ''; st.paddingBottom = bottom ? bottom + 'px' : ''; };
96
+ /** Take off what pixelSize put on the canvas: setPixelSize(null), and dispose, because the page may hand the same canvas to the next engine @param {any} e @param {any} st */
97
+ const plainCanvas = (e, st) => { padCanvas(st, 0, 0); Object.assign(st, e._pixelCss); };
98
+
99
+ /**
100
+ * Resize under pixelSize. A whole number of art pixels rarely fills the canvas: stretching the buffer over the rest would make some art pixels wider, so the
101
+ * last few real pixels (fewer than k) stay padding instead; the box the page laid out does not change. The renderer's size is the buffer in CSS units and the
102
+ * small addition keeps three's floor(size * ratio) on the buffer size when the division comes out just under it.
103
+ * @param {any} e @param {number} w CSS width @param {number} h CSS height @returns {boolean} false: not this mode, the plain resize applies
104
+ */
105
+ export function fitPixelSize(e, w, h) {
106
+ const k = e._pixelSize, r = e.renderer, c = r.domElement, o = e._oPixelRatio;
107
+ if (k == null) return false;
108
+ o.check();
109
+ if (!o.on) { padCanvas(c.style, 0, 0); return false; } // the game took the ratio (core/ops/owned.js): the canvas is a plain one again
110
+ const s = dpr(), dev = deviceBox(e, w, h, s), bw = Math.max(1, Math.floor(dev.w / k)), bh = Math.max(1, Math.floor(dev.h / k)), pr = s / k;
111
+ padCanvas(c.style, (dev.w - bw * k) / s, (dev.h - bh * k) / s);
112
+ if (e._autoSize) { c.style.width = w + 'px'; c.style.height = h + 'px'; }
113
+ if (c.width !== bw || c.height !== bh || r.getPixelRatio() !== pr) {
114
+ r.setDrawingBufferSize((bw + 1e-7) / pr, (bh + 1e-7) / pr, pr); // the post chain follows the renderer on its next draw (postWebGL.js follow)
115
+ e._oAspect.drive(bw / bh);
116
+ }
117
+ o.mark();
118
+ return true;
119
+ }
120
+
121
+ /**
122
+ * A window moved to another display or a page zoom changes devicePixelRatio. A resolution query matches one value only, so each change registers the next
123
+ * one. Armed once: a watch left from before setPixelSize(null) keeps its query, which is still the current value.
124
+ * @param {any} e
125
+ */
126
+ function watchDisplay(e) {
127
+ if (e._displayWatch || typeof matchMedia !== 'function') return;
128
+ e._displayWatch = true;
129
+ matchMedia(`(resolution: ${dpr()}dppx)`).addEventListener('change', () => {
130
+ e._displayWatch = false;
131
+ if (e._pixelSize == null) return;
132
+ watchDisplay(e);
133
+ e._resize();
134
+ }, { once: true, signal: e.signal });
135
+ }
136
+
137
+ /**
138
+ * engine.setPixelSize. A direct renderer.setPixelRatio before this call is over: the call is the newer, named request. autoView.manual('pixelRatio') is a claim
139
+ * on purpose, so it conflicts.
140
+ * @param {any} e @param {number | null} k
141
+ */
142
+ export function askPixelSize(e, k) {
143
+ if (k !== null && !(Number.isInteger(k) && k > 0)) throw codedError('engine-misuse', `engine.setPixelSize(k): k is how many real screen pixels make one art pixel, a whole number from 1 up (null turns it off); got ${JSON.stringify(k)}`);
144
+ const o = e._oPixelRatio, was = e._pixelSize, st = e.renderer.domElement.style;
145
+ o.check();
146
+ if (k === null) {
147
+ if (was == null) return;
148
+ e._pixelSize = null;
149
+ plainCanvas(e, st);
150
+ if (o.on) writeRatio(e, e.adaptive.max); // a ratio the game took stays the game's, as in fitPixelSize
151
+ e._resize();
152
+ return;
153
+ }
154
+ if (o.mode === 'manual') throw codedError('pixel-conflict', `engine.setPixelSize(${k}): the game took the pixel ratio with engine.autoView.manual('pixelRatio'). Keep one: hand it back with engine.autoView.manual('pixelRatio', false), or drop this call`);
155
+ if (o.mode === 'yielded') o.manual(false);
156
+ if (was == null) {
157
+ if (!e._pixelCss) e.signal.addEventListener('abort', () => plainCanvas(e, st), { once: true });
158
+ e._pixelCss = { imageRendering: st.imageRendering, boxSizing: st.boxSizing };
159
+ Object.assign(st, { imageRendering: 'pixelated', boxSizing: 'border-box' }); // border-box: the padding comes out of the box the page gave the canvas
160
+ Object.assign(e.adaptive, { lowered: false, from: null, good: 0 });
161
+ }
162
+ e._pixelSize = k;
163
+ // the canvas's MSAA is fixed when its context is made, so nothing here can switch it off
164
+ if (DEV && (e.post.antialias || ownMsaa(e.renderer))) warnOnce(coded('pixel-conflict', `pixelSize ${k} with antialias on: the edges of art pixels come out blended. It can only be set at creation: createEngine({ antialias: false })`));
165
+ watchDisplay(e);
166
+ e._resize();
167
+ }
@@ -1,4 +1,4 @@
1
- // What entered and left a scene since the last frame, so systems that must reach every object in the scene (the cascades and fog patching
1
+ // What entered and left a scene since the last frame, so systems that must reach every object in the scene (the cascades patching
2
2
  // materials, night glow finding its materials, the room map waiting for a material that reads it) visit only the new subtrees instead of
3
3
  // each walking the whole scene after any change. While streaming, something is added almost every frame; four full walks of a 1000+
4
4
  // object scene per such frame cost more than the frame's game code.
@@ -65,10 +65,10 @@ notePatch('scene-add-hook', 'Object3D.prototype.add / remove: wrapped once per p
65
65
  if (P.remove === o.ours.remove) P.remove = o.remove;
66
66
  if (P.add === o.add && P.remove === o.remove) { delete P[KEY]; delete P[ORIG]; }
67
67
  },
68
- { lost: 'plain scene.add is no longer adopted like engine.add, and fog, cascades, night glow and light counts miss objects added later' });
68
+ { lost: 'plain scene.add is no longer adopted like engine.add, and cascades, night glow and light counts miss objects added later' });
69
69
  notePatch('mesh-material-accessor', 'mesh.material on each object with a material that enters a watched scene: an own get / set on that object (the class accessor still runs) so a material swap is seen',
70
70
  () => {}, // off: objects entering from now on keep a plain material (_walk asks patchOn)
71
- { scope: 'objects in the scene', lost: 'mesh.material = other on objects entering from now on is not seen: the new material misses fog and cascades until the object re-enters' });
71
+ { scope: 'objects in the scene', lost: 'mesh.material = other on objects entering from now on is not seen: the new material misses cascades until the object re-enters' });
72
72
 
73
73
  /** The accessor (get / set) `material` resolves to on this object or up its prototype chain, or null when it is a plain value */
74
74
  function materialAccessor(o) {
@@ -2,7 +2,7 @@
2
2
  // add registers each root in the thing registry (things.js) so engine.thing / hit.thing can say what it is and what a save keeps. A plain
3
3
  // engine.scene.add(obj) is registered the same way (things.js adopts roots added under the scene), so both ways in give the same answer.
4
4
  import { DEV } from '../base/validate.js';
5
- import { writeRatio } from './adaptive.js';
5
+ import { askRatio, askPixelSize } from './pixelRatio.js';
6
6
  import { codedError } from '../base/errorHints.js';
7
7
  import { thing } from './thingOps.js';
8
8
  import { isUnder } from '../base/util.js';
@@ -69,8 +69,6 @@ export const sceneMethods = {
69
69
  thing(idOrObj) { return thing(this, idOrObj); },
70
70
  /** @internal Dev: a module found two systems managing one object; listed in describe().scene.conflicts and warned once (code thing-owned) */
71
71
  thingConflict(text) { this._things.conflict(text); },
72
- /** Detach from the parent only (no GPU release; use when you will add it back). Use remove for objects you are done with */
73
- detach(...objs) { for (const o of objs) o.removeFromParent(); },
74
72
  /**
75
73
  * Delete an object for good: detach it, unregister its rays and dispose the geometries and materials nothing else in the scene uses (textures are kept).
76
74
  * One still used by another object stays, and goes with its last user. Geometry and materials shared by assets model clones are only decremented in use count (see Assets.js)
@@ -82,6 +80,7 @@ export const sceneMethods = {
82
80
  this._things.forget(o);
83
81
  this.rays.forget(o);
84
82
  this.assets.forget(o);
83
+ this._poses.forget(o);
85
84
  const shared = this.assets.shared, held = this.batching.held; // a batch still drawing the same geometry / material keeps it alive
86
85
  if (counted) o.traverse(c => { for (const x of parts(c)) this._users.set(x, (this._users.get(x) ?? 0) - 1); });
87
86
  // The whole-scene count only for a part nothing else keeps: unloading a streamed block whose kit is all held by batches walked every object of the district for nothing (7 ms in one frame of the city run)
@@ -110,9 +109,15 @@ export const sceneMethods = {
110
109
  drawOnce(this.renderer, this.scene, camera, target);
111
110
  } finally { if (own) own.inside--; }
112
111
  },
113
- // an engine.setPixelRatio call is the game's (or settings') request: written even when the game took the ratio. It is also the new ceiling, or adaptive
114
- // resolution would climb back to the old one and undo the engine's own named entry where the raw three.js call stays. Adaptive writes through writeRatio
115
- setPixelRatio(p) { writeRatio(this, p); Object.assign(this.adaptive, { max: p, lowered: false, from: null, good: 0 }); },
112
+ /** Render resolution, and the top adaptive resolution climbs back to. Throws while pixelSize is on (core/scene/pixelRatio.js) @param {number} p */
113
+ setPixelRatio(p) { askRatio(this, p); },
114
+ /**
115
+ * One art pixel becomes k real screen pixels, every one the same width at any display scale, and it stays so through a page zoom or a move to another display.
116
+ * While on, adaptive resolution stops and engine.setPixelRatio throws; a photo keeps the art pixels. null turns it off.
117
+ * @example engine.setPixelSize(3);
118
+ * @param {number | null} k a whole number from 1 up, or null
119
+ */
120
+ setPixelSize(k) { askPixelSize(this, k); },
116
121
  /** Raise camera.far to at least far (terrain view range). Goes through ownership: a game that owns camera.far (engine.autoView.manual('far')) keeps its value. @param {number} far */
117
122
  viewFar(far) {
118
123
  if (this.camera.far >= far) return;