castle-web-cli 0.4.232 → 0.4.233

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 (355) hide show
  1. package/dist/agent-failures.d.ts +8 -0
  2. package/dist/agent-failures.js +19 -2
  3. package/dist/agent-prompts.d.ts +1 -1
  4. package/dist/agent-prompts.js +10 -3
  5. package/dist/agent.d.ts +64 -3
  6. package/dist/agent.js +170 -81
  7. package/dist/castle-host/host.d.ts +1 -0
  8. package/dist/castle-host/host.js +51 -3
  9. package/dist/castleJson.d.ts +4 -2
  10. package/dist/castleJson.js +2 -0
  11. package/dist/check.d.ts +3 -1
  12. package/dist/check.js +11 -1
  13. package/dist/devSessionStorage.js +47 -1
  14. package/dist/importPinMismatch.d.ts +22 -0
  15. package/dist/importPinMismatch.js +77 -0
  16. package/dist/importRegression.js +3 -15
  17. package/dist/imports.d.ts +10 -3
  18. package/dist/imports.js +88 -20
  19. package/dist/index.js +5 -4
  20. package/dist/init.js +1 -1
  21. package/dist/platformDoc.js +22 -0
  22. package/dist/routerFences.d.ts +5 -0
  23. package/dist/routerFences.js +12 -2
  24. package/dist/save-deck.d.ts +5 -0
  25. package/dist/save-deck.js +37 -4
  26. package/dist/serve.js +3 -0
  27. package/dist/shell/assets/{index-D2tWM896.js → index-BjOxR-lW.js} +4 -4
  28. package/dist/shell/assets/index-MVLfNYd9.css +1 -0
  29. package/dist/shell/index.html +2 -2
  30. package/dist/taskSteer.d.ts +13 -0
  31. package/dist/taskSteer.js +22 -2
  32. package/kits/base/castle.json +1 -1
  33. package/kits/base/package-lock.json +1 -1
  34. package/kits/base/sdk/README.md +79 -2
  35. package/kits/base/sdk/avatar.d.ts +6 -2
  36. package/kits/base/sdk/avatar.js +12 -4
  37. package/kits/base/sdk/castle.d.ts +1 -1
  38. package/kits/base/sdk/commands.d.ts +14 -0
  39. package/kits/base/sdk/hub.d.ts +6 -2
  40. package/kits/base/sdk/hub.js +13 -0
  41. package/kits/base/sdk/multiplayer.js +17 -1
  42. package/kits/base/sdk/save.js +2 -1
  43. package/kits/base/sdk/server/hub.d.ts +87 -0
  44. package/kits/base/sdk/server/hub.js +70 -0
  45. package/kits/base/sdk/server/platformHandle.d.ts +31 -1
  46. package/kits/base/sdk/server/storage.d.ts +13 -0
  47. package/kits/base/sdk/server/storage.js +46 -0
  48. package/kits/base/sdk/server/wrapper.d.ts +36 -5
  49. package/kits/base/sdk/server/wrapper.js +83 -8
  50. package/kits/hub-game/CLAUDE.md +329 -11
  51. package/kits/hub-game/blueprints/avatar-10.scene +28 -0
  52. package/kits/hub-game/blueprints/avatar-11.scene +28 -0
  53. package/kits/hub-game/blueprints/avatar-12.scene +28 -0
  54. package/kits/hub-game/blueprints/avatar-13.scene +28 -0
  55. package/kits/hub-game/blueprints/avatar-14.scene +28 -0
  56. package/kits/hub-game/blueprints/avatar-15.scene +28 -0
  57. package/kits/hub-game/blueprints/avatar-4.scene +28 -0
  58. package/kits/hub-game/blueprints/avatar-5.scene +28 -0
  59. package/kits/hub-game/blueprints/avatar-6.scene +28 -0
  60. package/kits/hub-game/blueprints/avatar-7.scene +28 -0
  61. package/kits/hub-game/blueprints/avatar-8.scene +28 -0
  62. package/kits/hub-game/blueprints/avatar-9.scene +28 -0
  63. package/kits/hub-game/code/client/actorBudget.js +47 -0
  64. package/kits/hub-game/code/client/attention.js +11 -2
  65. package/kits/hub-game/code/client/avatar.js +309 -35
  66. package/kits/hub-game/code/client/avatarCap.js +228 -0
  67. package/kits/hub-game/code/client/avatarColors.js +70 -0
  68. package/kits/hub-game/code/client/avatarFaces.js +21 -0
  69. package/kits/hub-game/code/client/avatarShare.js +251 -0
  70. package/kits/hub-game/code/client/ballot.js +467 -0
  71. package/kits/hub-game/code/client/build.js +22 -0
  72. package/kits/hub-game/code/client/chrome.js +1144 -50
  73. package/kits/hub-game/code/client/companion.js +716 -0
  74. package/kits/hub-game/code/client/companionDress.js +99 -0
  75. package/kits/hub-game/code/client/decor.js +509 -0
  76. package/kits/hub-game/code/client/earned.js +131 -0
  77. package/kits/hub-game/code/client/emoteBubble.js +75 -0
  78. package/kits/hub-game/code/client/grab.js +339 -20
  79. package/kits/hub-game/code/client/hookLayer.js +299 -13
  80. package/kits/hub-game/code/client/idle.js +163 -22
  81. package/kits/hub-game/code/client/interestCap.js +81 -0
  82. package/kits/hub-game/code/client/keys.js +36 -0
  83. package/kits/hub-game/code/client/labelsNear.js +205 -0
  84. package/kits/hub-game/code/client/menuIcons.js +34 -0
  85. package/kits/hub-game/code/client/pack.js +6 -2
  86. package/kits/hub-game/code/client/packFormat.js +3 -3
  87. package/kits/hub-game/code/client/rehello.js +167 -0
  88. package/kits/hub-game/code/client/shot.js +92 -0
  89. package/kits/hub-game/code/client/sound.js +63 -8
  90. package/kits/hub-game/code/client/soundscape.js +1151 -0
  91. package/kits/hub-game/code/client/soundscapeActions.js +99 -0
  92. package/kits/hub-game/code/client/soundscapeAmbience.js +453 -0
  93. package/kits/hub-game/code/client/soundscapeBaked.js +143 -0
  94. package/kits/hub-game/code/client/soundscapeBusker.js +217 -0
  95. package/kits/hub-game/code/client/soundscapeCourt.js +200 -0
  96. package/kits/hub-game/code/client/soundscapeCrowd.js +331 -0
  97. package/kits/hub-game/code/client/soundscapeCues.js +362 -0
  98. package/kits/hub-game/code/client/soundscapeMap.js +181 -0
  99. package/kits/hub-game/code/client/soundscapeMarket.js +176 -0
  100. package/kits/hub-game/code/client/soundscapeMusic.js +126 -0
  101. package/kits/hub-game/code/client/soundscapeMusicEngine.js +460 -0
  102. package/kits/hub-game/code/client/soundscapeSimlish.js +737 -0
  103. package/kits/hub-game/code/client/soundscapeSongs.js +127 -0
  104. package/kits/hub-game/code/client/soundscapeSongsRound3.js +63 -0
  105. package/kits/hub-game/code/client/soundscapeSynthesis.js +168 -0
  106. package/kits/hub-game/code/client/soundscapeUi.js +211 -0
  107. package/kits/hub-game/code/client/soundscapeVoice.js +1209 -0
  108. package/kits/hub-game/code/client/soundscapeWaves.js +206 -0
  109. package/kits/hub-game/code/client/spin.js +101 -0
  110. package/kits/hub-game/code/client/state.js +109 -1
  111. package/kits/hub-game/code/client/stuck.js +259 -0
  112. package/kits/hub-game/code/client/talk.js +538 -47
  113. package/kits/hub-game/code/client/tiers.js +516 -27
  114. package/kits/hub-game/code/client/toastBand.js +37 -0
  115. package/kits/hub-game/code/client/together.js +32 -0
  116. package/kits/hub-game/code/client/visibility.js +43 -0
  117. package/kits/hub-game/code/client/wear.js +461 -170
  118. package/kits/hub-game/code/client/yours.js +199 -0
  119. package/kits/hub-game/code/companionSpec.js +45 -0
  120. package/kits/hub-game/code/privateText.js +7 -0
  121. package/kits/hub-game/code/server/actions.js +133 -0
  122. package/kits/hub-game/code/server/actors.js +9 -1
  123. package/kits/hub-game/code/server/ask.js +155 -0
  124. package/kits/hub-game/code/server/ballot.js +539 -0
  125. package/kits/hub-game/code/server/cells.js +100 -0
  126. package/kits/hub-game/code/server/companion.js +82 -0
  127. package/kits/hub-game/code/server/cues.js +70 -0
  128. package/kits/hub-game/code/server/decor.js +269 -0
  129. package/kits/hub-game/code/server/earned.js +461 -0
  130. package/kits/hub-game/code/server/friendBests.js +166 -0
  131. package/kits/hub-game/code/server/friendsAmong.js +232 -0
  132. package/kits/hub-game/code/server/history.js +5 -0
  133. package/kits/hub-game/code/server/hub.js +1254 -50
  134. package/kits/hub-game/code/server/idle.js +30 -11
  135. package/kits/hub-game/code/server/index.js +2 -2
  136. package/kits/hub-game/code/server/labels.js +28 -2
  137. package/kits/hub-game/code/server/manifest.js +378 -7
  138. package/kits/hub-game/code/server/menu.js +133 -0
  139. package/kits/hub-game/code/server/npcs.js +830 -80
  140. package/kits/hub-game/code/server/party.js +2 -2
  141. package/kits/hub-game/code/server/players.js +22 -0
  142. package/kits/hub-game/code/server/shot.js +110 -0
  143. package/kits/hub-game/code/server/standing.js +124 -0
  144. package/kits/hub-game/code/server/vis.js +113 -0
  145. package/kits/hub-game/code/server/wear.js +12 -0
  146. package/kits/hub-game/code/server/yours.js +59 -0
  147. package/kits/hub-game/code/shared/cues.js +9 -0
  148. package/kits/hub-game/code/shared/decor.js +41 -0
  149. package/kits/hub-game/code/shared/shot.js +19 -0
  150. package/kits/hub-game/code/shared/spin.js +57 -0
  151. package/kits/hub-game/code/systems/hub.js +845 -95
  152. package/kits/hub-game/docs/content-pack.md +1 -1
  153. package/kits/hub-game/docs/contract.md +2244 -61
  154. package/kits/hub-game/docs/home-pieces.md +64 -0
  155. package/kits/hub-game/models/avatar-10.pxmodel +28 -0
  156. package/kits/hub-game/models/avatar-11.pxmodel +28 -0
  157. package/kits/hub-game/models/avatar-12.pxmodel +27 -0
  158. package/kits/hub-game/models/avatar-13.pxmodel +24 -0
  159. package/kits/hub-game/models/avatar-14.pxmodel +29 -0
  160. package/kits/hub-game/models/avatar-15.pxmodel +24 -0
  161. package/kits/hub-game/models/avatar-4.pxmodel +29 -0
  162. package/kits/hub-game/models/avatar-5.pxmodel +27 -0
  163. package/kits/hub-game/models/avatar-6.pxmodel +26 -0
  164. package/kits/hub-game/models/avatar-7.pxmodel +25 -0
  165. package/kits/hub-game/models/avatar-8.pxmodel +24 -0
  166. package/kits/hub-game/models/avatar-9.pxmodel +30 -0
  167. package/kits/hub-game/models/earned/badge-round.pxmodel +100 -0
  168. package/kits/hub-game/models/earned/badge-shield.pxmodel +117 -0
  169. package/kits/hub-game/models/earned/badge-star.pxmodel +87 -0
  170. package/kits/hub-game/models/earned/belt-plain.pxmodel +72 -0
  171. package/kits/hub-game/models/earned/held-ball.pxmodel +43 -0
  172. package/kits/hub-game/models/earned/held-lantern.pxmodel +85 -0
  173. package/kits/hub-game/models/earned/held-net.pxmodel +57 -0
  174. package/kits/hub-game/models/earned/held-trophy.pxmodel +109 -0
  175. package/kits/hub-game/models/earned/pin-round.pxmodel +62 -0
  176. package/kits/hub-game/models/earned/sash-plain.pxmodel +66 -0
  177. package/kits/hub-game/models/earned/square/belt-plain.pxmodel +104 -0
  178. package/kits/hub-game/models/earned/square/sash-plain.pxmodel +98 -0
  179. package/kits/hub-game/models/hats/bat-clip.pxmodel +206 -0
  180. package/kits/hub-game/models/hats/beekeeper.pxmodel +149 -0
  181. package/kits/hub-game/models/hats/cap.pxmodel +162 -0
  182. package/kits/hub-game/models/hats/captain.pxmodel +178 -0
  183. package/kits/hub-game/models/hats/crooked-top.pxmodel +172 -0
  184. package/kits/hub-game/models/hats/flower-crown.pxmodel +451 -0
  185. package/kits/hub-game/models/hats/foam-crown.pxmodel +179 -0
  186. package/kits/hub-game/models/hats/lantern.pxmodel +230 -0
  187. package/kits/hub-game/models/hats/laurel.pxmodel +533 -0
  188. package/kits/hub-game/models/hats/lighthouse.pxmodel +96 -0
  189. package/kits/hub-game/models/hats/sailor.pxmodel +141 -0
  190. package/kits/hub-game/models/hats/souwester.pxmodel +131 -0
  191. package/kits/hub-game/models/hats/straw.pxmodel +139 -0
  192. package/kits/hub-game/models/hats/sunflower.pxmodel +406 -0
  193. package/kits/hub-game/models/hats/sweatband.pxmodel +112 -0
  194. package/kits/hub-game/models/hats/witch.pxmodel +147 -0
  195. package/kits/hub-game/package-lock.json +2 -0
  196. package/kits/hub-game/package.json +2 -1
  197. package/kits/hub-game/scripts/check.mjs +78 -11
  198. package/kits/hub-game/scripts/companion-follower-wire.json +1 -0
  199. package/kits/hub-game/scripts/fixtures/decor-keyless-draw.json +121 -0
  200. package/kits/hub-game/scripts/fixtures/decor-keyless.json +293 -0
  201. package/kits/hub-game/scripts/fixtures/engine-models-stub.mjs +23 -0
  202. package/kits/hub-game/scripts/fixtures/fake-dom.mjs +107 -0
  203. package/kits/hub-game/scripts/fixtures/interest-legacy.json +385 -0
  204. package/kits/hub-game/scripts/fixtures/npc-notes-v1.77.jsonl +4 -0
  205. package/kits/hub-game/scripts/fixtures/vis-shared-wire.json +1 -0
  206. package/kits/hub-game/scripts/gen-avatars.mjs +933 -16
  207. package/kits/hub-game/scripts/gen-earned.mjs +285 -0
  208. package/kits/hub-game/scripts/gen-hats.mjs +827 -0
  209. package/kits/hub-game/scripts/grab.before-orbit.mjs +400 -0
  210. package/kits/hub-game/scripts/soundscape-wave-analysis.mjs +125 -0
  211. package/kits/hub-game/scripts/test-actions-client.mjs +488 -0
  212. package/kits/hub-game/scripts/test-actions.mjs +298 -0
  213. package/kits/hub-game/scripts/test-actor-budget.mjs +44 -0
  214. package/kits/hub-game/scripts/test-actors.mjs +19 -17
  215. package/kits/hub-game/scripts/test-ask-client.mjs +358 -0
  216. package/kits/hub-game/scripts/test-ask.mjs +269 -0
  217. package/kits/hub-game/scripts/test-attention.mjs +10 -1
  218. package/kits/hub-game/scripts/test-avatar-cap.mjs +379 -0
  219. package/kits/hub-game/scripts/test-avatar-colors.mjs +72 -0
  220. package/kits/hub-game/scripts/test-avatar-models.mjs +181 -0
  221. package/kits/hub-game/scripts/test-avatar-share.mjs +318 -0
  222. package/kits/hub-game/scripts/test-avatar-wire.mjs +753 -0
  223. package/kits/hub-game/scripts/test-avatar.mjs +540 -7
  224. package/kits/hub-game/scripts/test-ballot.mjs +1001 -0
  225. package/kits/hub-game/scripts/test-build.mjs +31 -0
  226. package/kits/hub-game/scripts/test-cells.mjs +71 -0
  227. package/kits/hub-game/scripts/test-chat.mjs +662 -0
  228. package/kits/hub-game/scripts/test-classic.mjs +2 -0
  229. package/kits/hub-game/scripts/test-companion-chat.mjs +198 -0
  230. package/kits/hub-game/scripts/test-companion-client.mjs +1167 -0
  231. package/kits/hub-game/scripts/test-companion.mjs +259 -0
  232. package/kits/hub-game/scripts/test-decor-client.mjs +303 -0
  233. package/kits/hub-game/scripts/test-decor.mjs +457 -0
  234. package/kits/hub-game/scripts/test-earned-client.mjs +459 -0
  235. package/kits/hub-game/scripts/test-earned.mjs +1194 -0
  236. package/kits/hub-game/scripts/test-emote-bubble.mjs +110 -0
  237. package/kits/hub-game/scripts/test-friend-bests.mjs +435 -0
  238. package/kits/hub-game/scripts/test-grab-orbit.mjs +918 -0
  239. package/kits/hub-game/scripts/test-grab.mjs +7 -0
  240. package/kits/hub-game/scripts/test-hats.mjs +422 -168
  241. package/kits/hub-game/scripts/test-hub-leaving.mjs +203 -0
  242. package/kits/hub-game/scripts/test-hub-ops.mjs +439 -2
  243. package/kits/hub-game/scripts/test-hub-trip.mjs +716 -2
  244. package/kits/hub-game/scripts/test-hud-clear.mjs +328 -4
  245. package/kits/hub-game/scripts/test-idle.mjs +361 -1
  246. package/kits/hub-game/scripts/test-interest-cap.mjs +36 -0
  247. package/kits/hub-game/scripts/test-interest-cells.mjs +493 -0
  248. package/kits/hub-game/scripts/test-interest-client.mjs +118 -0
  249. package/kits/hub-game/scripts/test-keys.mjs +46 -1
  250. package/kits/hub-game/scripts/test-labels.mjs +596 -0
  251. package/kits/hub-game/scripts/test-manifest.mjs +207 -0
  252. package/kits/hub-game/scripts/test-menu-client.mjs +480 -0
  253. package/kits/hub-game/scripts/test-menu.mjs +296 -0
  254. package/kits/hub-game/scripts/test-npcs.mjs +1718 -12
  255. package/kits/hub-game/scripts/test-object-entry.mjs +76 -0
  256. package/kits/hub-game/scripts/test-pack.mjs +7 -0
  257. package/kits/hub-game/scripts/test-picker.mjs +314 -0
  258. package/kits/hub-game/scripts/test-rehello.mjs +1039 -0
  259. package/kits/hub-game/scripts/test-relations-among.mjs +222 -0
  260. package/kits/hub-game/scripts/test-relations-refresh.mjs +188 -0
  261. package/kits/hub-game/scripts/test-shot.mjs +756 -0
  262. package/kits/hub-game/scripts/test-soundscape.mjs +5432 -0
  263. package/kits/hub-game/scripts/test-spin.mjs +314 -0
  264. package/kits/hub-game/scripts/test-standing.mjs +416 -0
  265. package/kits/hub-game/scripts/test-stuck.mjs +1903 -0
  266. package/kits/hub-game/scripts/test-tier-cells.mjs +706 -0
  267. package/kits/hub-game/scripts/test-tiers-render.mjs +339 -0
  268. package/kits/hub-game/scripts/test-tiers.mjs +477 -2
  269. package/kits/hub-game/scripts/test-toast-band.mjs +61 -0
  270. package/kits/hub-game/scripts/test-try-on.mjs +22 -22
  271. package/kits/hub-game/scripts/test-vis.mjs +343 -0
  272. package/kits/hub-game/scripts/test-visibility.mjs +134 -0
  273. package/kits/hub-game/scripts/test-yours-chrome.mjs +166 -0
  274. package/kits/hub-game/scripts/test-yours.mjs +372 -0
  275. package/kits/multiplayer-3d/CLAUDE.md +50 -0
  276. package/kits/multiplayer-3d/castle.json +5 -5
  277. package/kits/multiplayer-3d/code/client/avatars.js +7 -0
  278. package/kits/multiplayer-3d/code/client/gait.js +65 -0
  279. package/kits/multiplayer-3d/code/client/nameTags.js +59 -4
  280. package/kits/multiplayer-3d/code/options.js +5 -0
  281. package/kits/multiplayer-3d/code/server/ownership.js +10 -2
  282. package/kits/multiplayer-3d/code/server/sceneBodies.js +12 -0
  283. package/kits/multiplayer-3d/code/server/world.js +7 -0
  284. package/kits/multiplayer-3d/code/systems/multiplayer.js +74 -4
  285. package/kits/multiplayer-3d/package.json +2 -1
  286. package/kits/multiplayer-3d/scripts/fixtures/README.md +11 -0
  287. package/kits/multiplayer-3d/scripts/fixtures/ownership-legacy.json +2 -0
  288. package/kits/multiplayer-3d/scripts/ownership-harness.mjs +102 -0
  289. package/kits/multiplayer-3d/scripts/ownership-loader.mjs +46 -0
  290. package/kits/multiplayer-3d/scripts/ownership-worker.mjs +15 -0
  291. package/kits/multiplayer-3d/scripts/record-ownership-session.mjs +98 -0
  292. package/kits/multiplayer-3d/scripts/test-eligible-claims.mjs +167 -0
  293. package/kits/multiplayer-3d/scripts/test-own-name-tag.mjs +247 -0
  294. package/kits/physics-2d/CLAUDE.md +9 -0
  295. package/kits/physics-2d/castle.json +2 -2
  296. package/kits/physics-2d/engine/scene.js +253 -1
  297. package/kits/physics-2d/engine/skyKey.js +129 -0
  298. package/kits/physics-2d/engine/stillClock.js +106 -0
  299. package/kits/physics-2d/engine/updateBudget.js +21 -0
  300. package/kits/physics-2d/scripts/test-skip-unchanged.mjs +326 -1
  301. package/kits/physics-3d/CLAUDE.md +1169 -30
  302. package/kits/physics-3d/behaviors/Player.jsx +629 -72
  303. package/kits/physics-3d/castle.json +3 -3
  304. package/kits/physics-3d/docs/pxmodel-format.md +8 -0
  305. package/kits/physics-3d/engine3d/Scene3DPlayer.jsx +69 -13
  306. package/kits/physics-3d/engine3d/actornode.js +86 -0
  307. package/kits/physics-3d/engine3d/animationBudget.js +23 -0
  308. package/kits/physics-3d/engine3d/editorWorld.js +6 -0
  309. package/kits/physics-3d/engine3d/emptynodes.js +232 -0
  310. package/kits/physics-3d/engine3d/framecap.js +96 -0
  311. package/kits/physics-3d/engine3d/gait.js +118 -0
  312. package/kits/physics-3d/engine3d/kithooks.js +47 -0
  313. package/kits/physics-3d/engine3d/look.js +507 -48
  314. package/kits/physics-3d/engine3d/lookbake.js +208 -0
  315. package/kits/physics-3d/engine3d/materialpresets.js +2 -0
  316. package/kits/physics-3d/engine3d/motion.js +39 -10
  317. package/kits/physics-3d/engine3d/nearshadows.js +37 -19
  318. package/kits/physics-3d/engine3d/optimize.js +9 -5
  319. package/kits/physics-3d/engine3d/orbitinput.js +487 -9
  320. package/kits/physics-3d/engine3d/orbitlens.js +48 -0
  321. package/kits/physics-3d/engine3d/ownmodel.js +213 -0
  322. package/kits/physics-3d/engine3d/pxmodel.js +42 -11
  323. package/kits/physics-3d/engine3d/shadowfade.js +882 -0
  324. package/kits/physics-3d/engine3d/sky.js +547 -0
  325. package/kits/physics-3d/engine3d/skylife.js +306 -0
  326. package/kits/physics-3d/engine3d/unchanged.js +11 -0
  327. package/kits/physics-3d/engine3d/viewrange.js +52 -0
  328. package/kits/physics-3d/engine3d/world3d.js +796 -69
  329. package/kits/physics-3d/main.jsx +5 -0
  330. package/kits/physics-3d/package.json +1 -1
  331. package/kits/physics-3d/scripts/look-baseline.mjs +155 -0
  332. package/kits/physics-3d/scripts/test-camera-orbit.mjs +2563 -80
  333. package/kits/physics-3d/scripts/test-drop-empty-parts.mjs +1 -1
  334. package/kits/physics-3d/scripts/test-frame-cap-bob.mjs +435 -0
  335. package/kits/physics-3d/scripts/test-frame-cap.mjs +452 -0
  336. package/kits/physics-3d/scripts/test-gait.mjs +387 -0
  337. package/kits/physics-3d/scripts/test-look-bake.mjs +1056 -0
  338. package/kits/physics-3d/scripts/test-model-parse-cache.mjs +92 -0
  339. package/kits/physics-3d/scripts/test-near-shadows.mjs +3 -0
  340. package/kits/physics-3d/scripts/test-orbit-shadow-fade.mjs +1920 -0
  341. package/kits/physics-3d/scripts/test-orbit-shift-lock.mjs +545 -0
  342. package/kits/physics-3d/scripts/test-orbit-shot.mjs +583 -0
  343. package/kits/physics-3d/scripts/test-orbit-view.mjs +230 -0
  344. package/kits/physics-3d/scripts/test-skip-empty-nodes.mjs +845 -0
  345. package/kits/physics-3d/scripts/test-sky.mjs +2470 -0
  346. package/kits/physics-3d/scripts/test-static-actors.mjs +8 -1
  347. package/kits/physics-3d/scripts/test-static-scenery.mjs +2171 -0
  348. package/kits/physics-3d/scripts/test-steady-hover.mjs +2 -0
  349. package/kits/physics-3d/scripts/test-view-range.mjs +260 -0
  350. package/kits/physics-3d/systems/physics3d.js +383 -6
  351. package/kits/real-time/castle.json +2 -2
  352. package/kits/real-time/code/server/gameHooks.js +7 -0
  353. package/kits/real-time/code/server/session.js +97 -19
  354. package/package.json +2 -2
  355. package/dist/shell/assets/index-Cf61cNfT.css +0 -1
@@ -1,6 +1,7 @@
1
1
  // The camera the player controls: `"engine": { "camera": { "follow": "rigid",
2
2
  // "control": "orbit" } }` (behaviors/Player.jsx from `updateOrbiting` on,
3
- // engine3d/orbitinput.js, `castRayFixed` in systems/physics3d.js).
3
+ // engine3d/orbitinput.js, `castBallFixed`, `nearFixed` and `castRayFixedNormal`
4
+ // in systems/physics3d.js).
4
5
  //
5
6
  // - Without the key, and with `"follow": "rigid"` alone, the Player is the
6
7
  // Player it was: every drawn frame of a scripted run (keys, stick, taps, a
@@ -26,7 +27,8 @@
26
27
  // where it was left.
27
28
  // - The pointers' roles (stick, look, pinch, tap), the wheel, the lock, and
28
29
  // the listeners that are only there under the key.
29
- // - `castRayFixed` on rapier itself, when it is installed here.
30
+ // - `castRayFixed`, `castRayFixedNormal`, `castBallFixed` and `nearFixed`
31
+ // on rapier itself, when it is installed here.
30
32
  //
31
33
  // test-static-actors.mjs runs it (`npm run check`).
32
34
  // node scripts/test-camera-orbit.mjs
@@ -36,6 +38,8 @@ import { register } from 'node:module';
36
38
  import { dirname, join } from 'node:path';
37
39
  import { fileURLToPath, pathToFileURL } from 'node:url';
38
40
  import * as THREE from 'three';
41
+ import { runShiftLockChecks } from './test-orbit-shift-lock.mjs';
42
+ import { runOrbitShotChecks } from './test-orbit-shot.mjs';
39
43
 
40
44
  const stub = `
41
45
  const any = () => new Proxy(function () {}, {
@@ -121,6 +125,8 @@ const { Player: PlayerBefore } = await import('./Player.before-orbit.mjs');
121
125
  const { placeFollowCamera, Physics3DSystem } = await import('../systems/physics3d.js');
122
126
  const { makeLookGestures, attachOrbitInput, stickFrom, LOOK_RAD_PER_PX, WHEEL_ZOOM_PER_NOTCH } = await import('../engine3d/orbitinput.js');
123
127
  const { SceneRuntime } = await import('../../physics-2d/engine/scene.js');
128
+ const { renderHidingOwnModel, HIDE_WITHIN, SHOW_PAST } = await import('../engine3d/ownmodel.js');
129
+ const { fitOrbitLens } = await import('../engine3d/orbitlens.js');
124
130
 
125
131
  const DEG = Math.PI / 180;
126
132
  const FIXED = 1 / 60;
@@ -128,9 +134,97 @@ const PROPS = { ...Player.defaultProps };
128
134
  const FLOOR = 0.7;
129
135
  const TUNING = { stickRadius: 56, tapSlop: 12, tapMs: 300 };
130
136
  // The Player's own numbers, restated: a change there is a change here.
131
- const LOOK_HEIGHT = 0.8;
132
- const RANGE0 = Math.hypot(PROPS.camDistance, PROPS.camHeight - LOOK_HEIGHT);
133
- const PITCH0 = Math.atan2(PROPS.camHeight - LOOK_HEIGHT, PROPS.camDistance);
137
+ // Roblox's default camera at our scale: its character is 5 studs tall, the
138
+ // kit's avatar 1.46 m, so a stud is 0.292 m.
139
+ const STUD = 1.46 / 5;
140
+ // The look point: Roblox's root part plus 1.5 studs, 0.438 m above the
141
+ // Transform (the capsule's middle, the torso's).
142
+ const LOOK_HEIGHT = 1.5 * STUD;
143
+ // Where the camera starts: 12.5 studs, 3.65 m, whatever camDistance and
144
+ // camHeight are, 15 degrees down.
145
+ const RANGE0 = 12.5 * STUD;
146
+ const PITCH0 = 15 * DEG;
147
+ // The zoom: 1.5 m in (Roblox's 0.5 studs would be first person), 128 studs
148
+ // (37.4 m) out. The tilt: 80 degrees either way of the horizontal.
149
+ const NEAREST = 1.5;
150
+ const FARTHEST = 128 * STUD;
151
+ const PITCH_LEAST = -80 * DEG;
152
+ const PITCH_MOST = 80 * DEG;
153
+
154
+ // A query the camera asks of physics (`nearFixed`, `castBallFixed`,
155
+ // `castRayFixedNormal`): counted, and the frame's first sweep (the one toward
156
+ // where the camera wants to be; a blend's comes after) kept as `lastCast`.
157
+ function noteQuery(world) {
158
+ world.casts += 1;
159
+ }
160
+ function noteCast(world, from, dir, max, radius) {
161
+ noteQuery(world);
162
+ world.sweeps = (world.sweeps ?? 0) + 1;
163
+ if (world.castAt === world.scene.time) return;
164
+ world.castAt = world.scene.time;
165
+ world.lastCast = { from: { ...from }, dir: { ...dir }, max, radius };
166
+ }
167
+
168
+ // Stand-in fixed solids for the camera's queries: half-spaces `{ n, d }`,
169
+ // each the unit normal out of the solid and its face's offset along it
170
+ // (n . p = d on the face, less inside). A ball is never swept from a place
171
+ // that already touches one: the Player starts it clear (rapier does not
172
+ // answer such a sweep reliably).
173
+ function halfSpaces(world, planes) {
174
+ const sideOf = (p, { n, d }) => n.x * p.x + n.y * p.y + n.z * p.z - d;
175
+ const sweep = (from, dir, max, radius) => {
176
+ let best = null;
177
+ for (const plane of planes) {
178
+ const s = sideOf(from, plane);
179
+ if (radius > 0) assert.ok(s >= radius - 1e-9, `the ball starts clear (${s} off a face, radius ${radius})`);
180
+ else if (s < 0) return { distance: 0, actorId: plane.actorId ?? null, normal: { ...plane.n } };
181
+ const closing = -(plane.n.x * dir.x + plane.n.y * dir.y + plane.n.z * dir.z);
182
+ if (!(closing > 0)) continue;
183
+ const distance = (s - radius) / closing;
184
+ if (distance <= max && (!best || distance < best.distance)) best = { distance, actorId: plane.actorId ?? null, normal: { ...plane.n } };
185
+ }
186
+ return best;
187
+ };
188
+ Object.assign(world.scene.physics3d, {
189
+ castRayFixedNormal: (from, dir, max) => {
190
+ noteQuery(world);
191
+ return sweep(from, dir, max, 0);
192
+ },
193
+ castBallFixed: (from, dir, max, radius) => {
194
+ noteCast(world, from, dir, max, radius);
195
+ return sweep(from, dir, max, radius);
196
+ },
197
+ nearFixed: (p, within) => {
198
+ noteQuery(world);
199
+ const found = [];
200
+ for (const plane of planes) {
201
+ const s = sideOf(p, plane);
202
+ const point = { x: p.x - plane.n.x * s, y: p.y - plane.n.y * s, z: p.z - plane.n.z * s };
203
+ if (s < 0) found.push({ distance: 0, inside: true, normal: null, point, actorId: plane.actorId ?? null });
204
+ else if (s <= within) found.push({ distance: s, inside: false, normal: { ...plane.n }, point, actorId: plane.actorId ?? null });
205
+ }
206
+ return found;
207
+ },
208
+ });
209
+ return world;
210
+ }
211
+
212
+ // The camera's queries delegated to a physics api (rapier's own), counted:
213
+ // whichever of them it has.
214
+ const CAMERA_QUERIES = ['castRayFixed', 'castRayFixedNormal', 'castBallFixed', 'nearFixed', 'nearestFixed'];
215
+ function queriesOf(world, api) {
216
+ for (const name of CAMERA_QUERIES) {
217
+ if (!api[name]) continue;
218
+ world.scene.physics3d[name] = (...args) => {
219
+ if (name === 'castBallFixed') noteCast(world, ...args);
220
+ else noteQuery(world);
221
+ const hit = api[name](...args);
222
+ if (name === 'castBallFixed') world.lastHit = hit;
223
+ return hit;
224
+ };
225
+ }
226
+ return world;
227
+ }
134
228
 
135
229
  // A world of one capsule on flat ground, stepped as systems/physics3d.js
136
230
  // steps (test-camera-follow.mjs's, with the scene's latched keys settable
@@ -161,13 +255,22 @@ function makeWorld(mode, PlayerClass = Player) {
161
255
  resetForces: logged('resetForces', () => {
162
256
  body.force = 0;
163
257
  }),
164
- // What stands between the camera and the player: `world.wall` metres
165
- // from the point the camera looks at, or nothing.
166
- castRayFixed: (from, dir, max) => {
167
- world.casts += 1;
168
- world.lastCast = { from: { ...from }, dir: { ...dir }, max };
258
+ // What stands between the camera and the player: a shell `world.wall`
259
+ // metres round the point the camera looks at, or nothing; the look
260
+ // point is never near it.
261
+ castRayFixedNormal: (from, dir, max) => {
262
+ noteQuery(world);
169
263
  return world.wall !== null && world.wall <= max ? { distance: world.wall, actorId: 'wall' } : null;
170
264
  },
265
+ castBallFixed: (from, dir, max, radius) => {
266
+ noteCast(world, from, dir, max, radius);
267
+ const distance = world.wall === null ? Infinity : Math.max(0, world.wall - radius);
268
+ return distance <= max ? { distance, actorId: 'wall' } : null;
269
+ },
270
+ nearFixed: () => {
271
+ noteQuery(world);
272
+ return [];
273
+ },
171
274
  };
172
275
  const stick = {
173
276
  x: 0,
@@ -329,6 +432,11 @@ function unkeyedIsUnchanged() {
329
432
  for (const mode of ['off', 'rigid']) {
330
433
  const now = makeWorld(mode, Player);
331
434
  const before = makeWorld(mode, PlayerBefore);
435
+ // These keys must never even be read without the orbit key.
436
+ now.scene.data = { engine: { camera: {
437
+ get distance() { return assert.fail(`${mode}: read engine.camera.distance`); },
438
+ get pitch() { return assert.fail(`${mode}: read engine.camera.pitch`); },
439
+ } } };
332
440
  const stepNow = scripted(now);
333
441
  const stepBefore = scripted(before);
334
442
  for (let i = 0; i < 720; i += 1) {
@@ -337,7 +445,7 @@ function unkeyedIsUnchanged() {
337
445
  }
338
446
  same(now, before, `${mode}: the Player is the one before the key`);
339
447
  assert.ok(now.frames.some((f) => f.calls.includes(mode === 'rigid' ? 'addForce' : 'applyImpulse')), 'and the run did something');
340
- assert.equal(now.casts, 0, `${mode}: nothing is asked of castRayFixed`);
448
+ assert.equal(now.casts, 0, `${mode}: nothing is asked of castRayFixedNormal, castBallFixed or nearFixed`);
341
449
  assert.deepEqual(now.lookCalls(), { listens: 0, consumes: 0 }, `${mode}: the camera's input is not touched`);
342
450
  assert.equal(now.scene.cameraOrbit, undefined, `${mode}: nothing is kept on the runtime`);
343
451
  assert.equal(now.actor.runtime.orbit, undefined, `${mode}: nor on the actor`);
@@ -457,6 +565,18 @@ function makeRuntime(mode, PlayerClass = Player, attachSource = PlayerClass ===
457
565
  harness.casts += 1;
458
566
  return null;
459
567
  },
568
+ castRayFixedNormal: () => {
569
+ harness.casts += 1;
570
+ return null;
571
+ },
572
+ castBallFixed: () => {
573
+ harness.casts += 1;
574
+ return null;
575
+ },
576
+ nearFixed: () => {
577
+ harness.casts += 1;
578
+ return [];
579
+ },
460
580
  };
461
581
  const physics = new Physics3DSystem();
462
582
  runtime.registerSystem({
@@ -601,6 +721,46 @@ function coldKeyless() {
601
721
  // the orbit input held is gone at the load, with no event, and from the
602
722
  // first frame the Player is the one before the key, whatever those fingers
603
723
  // go on doing. Then the key again, with no event between.
724
+ // The orbit lens across a load of the runtime itself: physics-2d's
725
+ // SceneRuntime.load resets the physics system before the next scene's data
726
+ // is in, and that reset gives the world camera its lens back
727
+ // (engine3d/orbitlens.js), so a keyless scene's first update already sees
728
+ // it, and what that update sets (70, the key's own number, included) stands.
729
+ // The frames here are the Player's; renderWorld's part is
730
+ // test-orbit-view.mjs's.
731
+ function lensAcrossLoads() {
732
+ let checks = 0;
733
+ for (const own of [70, 85]) {
734
+ const h = makeRuntime('orbit');
735
+ const world = h.runtime.three;
736
+ const before = h.camera.projectionMatrix.toArray();
737
+ for (let i = 0; i < 5; i += 1) {
738
+ h.frame();
739
+ fitOrbitLens(world, h.runtime);
740
+ }
741
+ assert.equal(h.camera.fov, 70, 'the key took the lens');
742
+ h.load('off');
743
+ assert.equal(h.runtime.cameraControl, null);
744
+ assert.equal(h.camera.fov, 50, 'given back by the load, before the keyless scene runs');
745
+ assert.deepEqual(h.camera.projectionMatrix.toArray(), before);
746
+ assert.equal(world.orbitLens, null);
747
+ h.camera.fov = own;
748
+ h.camera.updateProjectionMatrix();
749
+ h.run(30);
750
+ assert.equal(h.camera.fov, own, `the keyless scene's ${own} degrees stand`);
751
+ h.load('rigid');
752
+ assert.equal(h.camera.fov, own, 'and a load of another keyless scene does not touch it');
753
+ h.load('orbit');
754
+ h.frame();
755
+ fitOrbitLens(world, h.runtime);
756
+ assert.equal(h.camera.fov, 70);
757
+ h.load('off');
758
+ assert.equal(h.camera.fov, own, 'and keyless again: the lens it had when the key met it');
759
+ checks += 1;
760
+ }
761
+ return checks;
762
+ }
763
+
604
764
  function acrossLoads() {
605
765
  let checks = 0;
606
766
  for (const mode of ['off', 'rigid']) {
@@ -920,14 +1080,17 @@ function looking() {
920
1080
  world.run(90);
921
1081
  return world;
922
1082
  };
923
- // It starts where the fixed camera sits: camDistance behind, camHeight up.
1083
+ // It starts behind the player 3.65 m from the point it looks at, 15
1084
+ // degrees down, nearer and lower than the fixed camera sits.
924
1085
  {
925
1086
  const world = settled();
926
1087
  const t = world.actor.components.Transform;
927
1088
  const a = world.scene.persistent.camAngle;
928
1089
  const fixed = { x: t.x - PROPS.camDistance * Math.sin(a), y: t.y + PROPS.camHeight, z: t.z + PROPS.camDistance * Math.cos(a) };
929
- assert.ok(world.off(fixed) < 1e-3, `starts where the fixed camera sits (${world.off(fixed)} m off)`);
930
- assert.ok(world.off(world.rest(a, PITCH0, RANGE0)) < 1e-3);
1090
+ assert.ok(world.off(fixed) > 1, `not where the fixed camera sits (${world.off(fixed)} m off)`);
1091
+ assert.ok(world.camera.position.y < fixed.y, 'lower than it');
1092
+ assert.ok(world.off(world.rest(a, PITCH0, RANGE0)) < 1e-3, 'at 15 degrees, 3.65 m away');
1093
+ assert.ok(Math.abs(RANGE0 - 3.65) < 1e-12 && Math.abs(LOOK_HEIGHT - 0.438) < 1e-12, 'the numbers, in metres');
931
1094
  // And looks at the player, LOOK_HEIGHT up.
932
1095
  const look = new THREE.Vector3(0, 0, -1).applyQuaternion(world.camera.quaternion);
933
1096
  const to = new THREE.Vector3(t.x - world.camera.position.x, t.y + LOOK_HEIGHT - world.camera.position.y, t.z - world.camera.position.z).normalize();
@@ -960,7 +1123,8 @@ function looking() {
960
1123
  assert.ok(ahead.x < -0.05, `the view swung right (${ahead.x})`);
961
1124
  checks += 1;
962
1125
  }
963
- // The tilt stays between 5 and 70 degrees, the distance between 3 and 12 m.
1126
+ // The tilt stays within 80 degrees of the horizontal either way, the
1127
+ // distance between 1.5 and 37.376 m.
964
1128
  {
965
1129
  const world = settled();
966
1130
  const drag = (dy) => {
@@ -971,56 +1135,86 @@ function looking() {
971
1135
  world.run(90);
972
1136
  };
973
1137
  drag(2000);
974
- assert.equal(world.scene.cameraOrbit.pitch, 70 * DEG, 'no steeper than 70 degrees');
975
- assert.ok(world.off(world.rest(world.scene.persistent.camAngle, 70 * DEG, RANGE0)) < 1e-4);
1138
+ assert.equal(world.scene.cameraOrbit.pitch, PITCH_MOST, 'no steeper than 80 degrees');
1139
+ assert.equal(PITCH_MOST, 80 * DEG);
1140
+ assert.ok(world.off(world.rest(world.scene.persistent.camAngle, PITCH_MOST, RANGE0)) < 1e-4);
976
1141
  drag(-4000);
977
- assert.equal(world.scene.cameraOrbit.pitch, 5 * DEG, 'no flatter than 5');
978
- assert.ok(world.camera.position.y > world.actor.components.Transform.y + LOOK_HEIGHT, 'and still above the point it looks at');
1142
+ assert.equal(world.scene.cameraOrbit.pitch, PITCH_LEAST, 'no lower than 80 degrees below the horizontal');
1143
+ assert.equal(PITCH_LEAST, -80 * DEG);
1144
+ // Nothing is in the way here (no ground in this stand-in world): below
1145
+ // the point it looks at, looking up at it.
1146
+ assert.ok(world.off(world.rest(world.scene.persistent.camAngle, PITCH_LEAST, RANGE0)) < 1e-4);
1147
+ assert.ok(world.camera.position.y < world.actor.components.Transform.y + LOOK_HEIGHT - 3, 'below the point it looks at');
1148
+ const up = new THREE.Vector3(0, 0, -1).applyQuaternion(world.camera.quaternion);
1149
+ assert.ok(up.y > Math.sin(79 * DEG), `looking up at it (${up.y})`);
979
1150
  for (let i = 0; i < 40; i += 1) world.gestures.wheel(-100, 0, i);
980
1151
  world.run(90);
981
- assert.equal(world.scene.cameraOrbit.range, 3, 'no nearer than 3 m');
982
- assert.ok(world.off(world.rest(world.scene.persistent.camAngle, 5 * DEG, 3)) < 1e-4);
983
- for (let i = 0; i < 40; i += 1) {
1152
+ assert.equal(world.scene.cameraOrbit.range, NEAREST, 'no nearer than 1.5 m');
1153
+ assert.equal(NEAREST, 1.5);
1154
+ assert.ok(world.off(world.rest(world.scene.persistent.camAngle, PITCH_LEAST, NEAREST)) < 1e-4);
1155
+ for (let i = 0; i < 60; i += 1) {
984
1156
  world.gestures.wheel(100, 0, i);
985
1157
  world.frame();
986
1158
  }
987
1159
  world.run(90);
988
- assert.equal(world.scene.cameraOrbit.range, 12, 'no farther than 12 m');
989
- assert.ok(world.off(world.rest(world.scene.persistent.camAngle, 5 * DEG, 12)) < 1e-4);
1160
+ assert.equal(world.scene.cameraOrbit.range, FARTHEST, 'no farther than 128 studs');
1161
+ assert.ok(Math.abs(FARTHEST - 37.376) < 1e-9);
1162
+ assert.ok(world.off(world.rest(world.scene.persistent.camAngle, PITCH_LEAST, FARTHEST)) < 1e-4);
990
1163
  // One notch is a tenth.
991
1164
  world.gestures.wheel(-100, 0, 0);
992
1165
  world.frame();
993
- assert.ok(Math.abs(world.scene.cameraOrbit.range - 12 / WHEEL_ZOOM_PER_NOTCH) < 1e-9, 'a notch of the wheel is a tenth nearer');
1166
+ assert.ok(Math.abs(world.scene.cameraOrbit.range - FARTHEST / WHEEL_ZOOM_PER_NOTCH) < 1e-9, 'a notch of the wheel is a tenth nearer');
994
1167
  // A pinch: fingers twice as far apart, half the distance.
995
1168
  world.gestures.down(5, { x: 500, y: 300, time: 0, left: false });
996
1169
  world.gestures.down(6, { x: 700, y: 300, time: 0, left: false });
997
1170
  world.gestures.move(6, 900, 300, 1);
998
- const from = 12 / WHEEL_ZOOM_PER_NOTCH;
1171
+ const from = FARTHEST / WHEEL_ZOOM_PER_NOTCH;
999
1172
  world.frame();
1000
1173
  assert.ok(Math.abs(world.scene.cameraOrbit.range - from / 2) < 1e-9, 'fingers apart bring it nearer');
1001
1174
  world.gestures.move(5, 880, 300, 2);
1002
1175
  world.frame();
1003
- assert.equal(world.scene.cameraOrbit.range, 12, 'and a pinch stops at the limits too');
1176
+ assert.equal(world.scene.cameraOrbit.range, FARTHEST, 'and a pinch stops at the limits too');
1004
1177
  checks += 1;
1005
1178
  }
1006
- // A Player whose camera starts outside the limits has room to where it
1007
- // starts; one with other numbers starts from its own.
1179
+ // camDistance and camHeight do not move the orbit camera: a Player with
1180
+ // any numbers starts at 3.65 m and 15 degrees, with the same limits; and a
1181
+ // Player with other numbers than the one before starts again from there
1182
+ // (a scene that changes them asks for its own camera).
1008
1183
  {
1009
- const world = makeWorld('orbit');
1010
- world.actor.components.Player = { ...PROPS, camDistance: 20, camHeight: 30 };
1011
- world.run(5);
1012
- const o = world.scene.cameraOrbit;
1013
- assert.equal(o.range, Math.hypot(20, 30 - LOOK_HEIGHT));
1014
- assert.equal(o.farthest, o.range, 'room out to where it starts');
1015
- assert.equal(o.nearest, 3);
1016
- assert.equal(o.pitch, Math.atan2(30 - LOOK_HEIGHT, 20), 'a tilt inside the limits is kept');
1017
- world.actor.components.Player = { ...PROPS, camDistance: 1, camHeight: 1 };
1184
+ assert.equal(PROPS.camDistance, 9);
1185
+ assert.equal(PROPS.camHeight, 7);
1186
+ for (const [camDistance, camHeight] of [[9, 7], [6, 4], [20, 30], [1, 1], [0, 20]]) {
1187
+ const world = makeWorld('orbit');
1188
+ world.actor.components.Player = { ...PROPS, camDistance, camHeight };
1189
+ world.run(90);
1190
+ const o = world.scene.cameraOrbit;
1191
+ assert.equal(o.pitch, PITCH0, `${camDistance}/${camHeight}: starts 15 degrees down`);
1192
+ assert.equal(o.range, RANGE0, `${camDistance}/${camHeight}: 3.65 m away`);
1193
+ assert.equal(o.nearest, NEAREST);
1194
+ assert.equal(o.farthest, FARTHEST);
1195
+ const t = world.actor.components.Transform;
1196
+ const at = world.camera.position;
1197
+ const dist = Math.hypot(at.x - t.x, at.y - (t.y + LOOK_HEIGHT), at.z - t.z);
1198
+ assert.ok(Math.abs(dist - RANGE0) < 1e-3, `${camDistance}/${camHeight}: the camera is ${dist} m from the look point, not ${RANGE0}`);
1199
+ const rise = Math.asin((at.y - (t.y + LOOK_HEIGHT)) / dist);
1200
+ assert.ok(Math.abs(rise - PITCH0) < 1e-3, `${camDistance}/${camHeight}: the camera sits ${rise / DEG} degrees up`);
1201
+ }
1202
+ const world = settled();
1203
+ world.gestures.wheel(-300, 0, 0);
1204
+ world.gestures.down(1, { x: 900, y: 300, time: 0, left: false });
1205
+ world.gestures.move(1, 900, 360, 5);
1206
+ world.run(10);
1207
+ assert.notEqual(world.scene.cameraOrbit.range, RANGE0);
1208
+ assert.notEqual(world.scene.cameraOrbit.pitch, PITCH0);
1209
+ world.run(10);
1210
+ const kept = { ...world.scene.cameraOrbit };
1211
+ world.actor.components.Player = { ...PROPS };
1018
1212
  world.run(5);
1019
- assert.equal(world.scene.cameraOrbit.nearest, Math.hypot(1, 1 - LOOK_HEIGHT), 'and in to it');
1020
- assert.equal(world.scene.cameraOrbit.farthest, 12);
1021
- world.actor.components.Player = { ...PROPS, camDistance: 0, camHeight: 20 };
1213
+ assert.deepEqual(world.scene.cameraOrbit, kept, 'the same numbers keep what was chosen');
1214
+ world.actor.components.Player = { ...PROPS, camDistance: 6 };
1022
1215
  world.run(5);
1023
- assert.equal(world.scene.cameraOrbit.pitch, 70 * DEG, 'a tilt outside them is brought in');
1216
+ assert.equal(world.scene.cameraOrbit.range, RANGE0, 'other numbers start again');
1217
+ assert.equal(world.scene.cameraOrbit.pitch, PITCH0);
1024
1218
  checks += 1;
1025
1219
  }
1026
1220
  // What the player chose is on the runtime and nowhere that is sent.
@@ -1042,6 +1236,68 @@ function looking() {
1042
1236
  return checks;
1043
1237
  }
1044
1238
 
1239
+ function startingValues() {
1240
+ let checks = 0;
1241
+ const cases = [
1242
+ [{}, RANGE0, PITCH0],
1243
+ [{ distance: 8, pitch: 30 }, 8, 30 * DEG],
1244
+ [{ distance: 0, pitch: -100 }, NEAREST, PITCH_LEAST],
1245
+ [{ distance: 100, pitch: 100 }, FARTHEST, PITCH_MOST],
1246
+ [{ distance: Number.MAX_VALUE, pitch: Number.MAX_VALUE }, FARTHEST, PITCH_MOST],
1247
+ [{ distance: 8 }, 8, PITCH0],
1248
+ [{ pitch: -30 }, RANGE0, -30 * DEG],
1249
+ ...[NaN, Infinity, -Infinity, '8', null, {}, true].map((value) => [{ distance: value, pitch: value }, RANGE0, PITCH0]),
1250
+ ];
1251
+ for (const [camera, range, pitch] of cases) {
1252
+ const world = makeWorld('orbit');
1253
+ world.scene.data = { engine: { camera } };
1254
+ world.frame();
1255
+ const chosen = world.scene.cameraOrbit;
1256
+ assert.equal(chosen.range, range, 'starting distance, clamped or default');
1257
+ assert.equal(chosen.pitch, pitch, 'starting pitch, clamped or default');
1258
+ assert.equal(chosen.nearest, NEAREST, 'starting keys do not change zoom limits');
1259
+ assert.equal(chosen.farthest, FARTHEST);
1260
+ world.run(90);
1261
+ assert.ok(world.off(world.rest(world.scene.persistent.camAngle, pitch, range)) < 1e-3, 'the camera uses the start with positive pitch looking down');
1262
+ world.gestures.wheel(-100, 0, 0);
1263
+ world.gestures.down(1, { x: 900, y: 300, time: 0, left: false });
1264
+ world.gestures.move(1, 900, pitch === PITCH_MOST ? 280 : 320, 5);
1265
+ world.frame();
1266
+ assert.notEqual(chosen.pitch, pitch, 'the player can tilt away from the start');
1267
+ const kept = { ...chosen };
1268
+ // A deep copy: an object-valued key is a fresh object, as a reload makes it.
1269
+ world.scene.data = { engine: { camera: structuredClone(camera) } };
1270
+ world.run(30, ['KeyW']);
1271
+ assert.equal(world.scene.cameraOrbit, chosen, 'unchanged values preserve the choice object, including NaN');
1272
+ assert.deepEqual(chosen, kept, 'no reset during play or when equal scene data replaces the object');
1273
+ checks += 1;
1274
+ }
1275
+ {
1276
+ const world = makeWorld('orbit');
1277
+ const camera = { distance: 8, pitch: 30 };
1278
+ world.scene.data = { engine: { camera } };
1279
+ world.run(90);
1280
+ const reset = (change, range, pitch, label) => {
1281
+ world.scene.cameraOrbit.range = 10;
1282
+ world.scene.cameraOrbit.pitch = 0;
1283
+ const before = world.scene.cameraOrbit;
1284
+ change();
1285
+ world.frame();
1286
+ assert.notEqual(world.scene.cameraOrbit, before, label);
1287
+ assert.equal(world.scene.cameraOrbit.range, range, label);
1288
+ assert.equal(world.scene.cameraOrbit.pitch, pitch, label);
1289
+ checks += 1;
1290
+ };
1291
+ reset(() => (camera.distance = 6), 6, 30 * DEG, 'distance edit resets both starts');
1292
+ reset(() => (camera.pitch = -20), 6, -20 * DEG, 'pitch edit resets both starts');
1293
+ reset(() => (world.actor.components.Player = { ...PROPS, camDistance: 6 }), 6, -20 * DEG, 'camDistance still reapplies authored starts');
1294
+ reset(() => (world.actor.components.Player = { ...PROPS, camDistance: 6, camHeight: 4 }), 6, -20 * DEG, 'camHeight still reapplies authored starts');
1295
+ reset(() => (world.scene.data = { engine: { camera: { distance: 12, pitch: 40 } } }), 12, 40 * DEG, 'different scene values reset');
1296
+ reset(() => (world.scene.data = {}), RANGE0, PITCH0, 'removing keys restores defaults');
1297
+ }
1298
+ return checks;
1299
+ }
1300
+
1045
1301
  function blocked() {
1046
1302
  let checks = 0;
1047
1303
  const world = makeWorld('orbit');
@@ -1051,39 +1307,39 @@ function blocked() {
1051
1307
  const t = world.actor.components.Transform;
1052
1308
  return Math.hypot(world.camera.position.x - t.x, world.camera.position.y - (t.y + LOOK_HEIGHT), world.camera.position.z - t.z);
1053
1309
  };
1054
- // While the first frame's takeover blend lasts its drawn point is tested
1055
- // too; settled, one ray a frame.
1056
- assert.ok(world.casts > 90, 'a second ray while a blend lasts');
1310
+ // While the first frame's takeover blend lasts its drawn point is swept
1311
+ // toward too; settled, two queries a frame: whether anything is near the
1312
+ // look point (nothing here) and one sweep toward where the camera wants
1313
+ // to be.
1314
+ assert.ok(world.casts > 2 * 90, 'a second sweep while a blend lasts');
1057
1315
  world.casts = 0;
1058
1316
  world.run(30);
1059
- assert.equal(world.casts, 30, 'one ray a frame');
1060
- // The ray goes from the point the camera is placed from (the player's
1317
+ assert.equal(world.casts, 2 * 30, 'two queries a frame');
1318
+ // The ball goes from the point the camera is placed from (the player's
1061
1319
  // eased height, LOOK_HEIGHT up) toward where the camera wants to be, as
1062
- // far as it wants to be and the margin past that.
1320
+ // far as it wants to be, the margin round.
1063
1321
  const t = world.actor.components.Transform;
1064
1322
  const eye = { x: world.camera.position.x - world.lastCast.dir.x * RANGE0, y: world.camera.position.y - world.lastCast.dir.y * RANGE0, z: world.camera.position.z - world.lastCast.dir.z * RANGE0 };
1065
1323
  for (const k of ['x', 'y', 'z']) assert.ok(Math.abs(world.lastCast.from[k] - eye[k]) < 1e-4, `the ray starts where the camera is placed from (${k})`);
1066
1324
  assert.ok(Math.abs(world.lastCast.from.y - (t.y + LOOK_HEIGHT)) < 1e-3);
1067
- assert.ok(Math.abs(world.lastCast.max - (RANGE0 + 0.25)) < 1e-6);
1325
+ assert.ok(Math.abs(world.lastCast.max - RANGE0) < 1e-6);
1326
+ assert.equal(world.lastCast.radius, 0.25, 'a ball the margin round');
1068
1327
  const want = world.rest(a, PITCH0, 1);
1069
1328
  for (const k of ['x', 'y', 'z']) assert.ok(Math.abs(world.lastCast.dir[k] - (want[k] - world.lastCast.from[k])) < 1e-6, `ray ${k}`);
1070
1329
  assert.ok(Math.abs(Math.hypot(world.lastCast.dir.x, world.lastCast.dir.y, world.lastCast.dir.z) - 1) < 1e-12, 'a unit direction');
1071
1330
  checks += 1;
1072
1331
  // Something in the way: in front of it at once, a margin clear.
1073
- world.wall = 4;
1332
+ world.wall = 3;
1074
1333
  world.frame();
1075
- assert.ok(Math.abs(reach() - 3.75) < 1e-5, `pulled in at once, 0.25 m clear (${reach()})`);
1076
- assert.ok(world.off(world.rest(a, PITCH0, 3.75)) < 1e-5, 'along the same line');
1334
+ assert.ok(Math.abs(reach() - 2.75) < 1e-5, `pulled in at once, 0.25 m clear (${reach()})`);
1335
+ assert.ok(world.off(world.rest(a, PITCH0, 2.75)) < 1e-5, 'along the same line');
1077
1336
  world.wall = 2;
1078
1337
  world.frame();
1079
1338
  assert.ok(Math.abs(reach() - 1.75) < 1e-5, 'and in again at once');
1080
- // Never nearer than 0.6 m.
1339
+ // However near, the margin off it.
1081
1340
  world.wall = 0.3;
1082
1341
  world.frame();
1083
- assert.ok(Math.abs(reach() - 0.6) < 1e-5, `no nearer than 0.6 m (${reach()})`);
1084
- world.wall = 0;
1085
- world.frame();
1086
- assert.ok(Math.abs(reach() - 0.6) < 1e-5);
1342
+ assert.ok(Math.abs(reach() - 0.05) < 1e-5, `the margin off a near wall (${reach()})`);
1087
1343
  checks += 1;
1088
1344
  // Out of the way: back out slowly, never past where it wants to be.
1089
1345
  world.wall = null;
@@ -1098,14 +1354,15 @@ function blocked() {
1098
1354
  assert.ok(Math.abs(reach() - RANGE0) < 1e-3, 'all the way');
1099
1355
  checks += 1;
1100
1356
  // Half way out, something nearer again: in at once.
1101
- world.wall = 3;
1357
+ world.wall = 2;
1102
1358
  world.frame();
1103
1359
  world.wall = null;
1104
1360
  world.run(10);
1105
1361
  const half = reach();
1106
- world.wall = half + 2;
1362
+ assert.ok(half > 2 && half < RANGE0 - 0.3, `half way out (${half})`);
1363
+ world.wall = half + 0.5;
1107
1364
  world.frame();
1108
- assert.ok(reach() > half && reach() <= half + 2 - 0.25 + 1e-9, 'still easing out behind a farther wall, inside it');
1365
+ assert.ok(reach() > half && reach() <= half + 0.5 - 0.25 + 1e-9, 'still easing out behind a farther wall, inside it');
1109
1366
  world.wall = 1.5;
1110
1367
  world.frame();
1111
1368
  assert.ok(Math.abs(reach() - 1.25) < 1e-5);
@@ -1117,7 +1374,7 @@ function blocked() {
1117
1374
  {
1118
1375
  const held = makeWorld('orbit');
1119
1376
  held.run(90);
1120
- held.wall = 4;
1377
+ held.wall = 3;
1121
1378
  held.frame();
1122
1379
  const at = () => {
1123
1380
  const tt = held.actor.components.Transform;
@@ -1127,24 +1384,24 @@ function blocked() {
1127
1384
  // behind the player, where the camera belongs.
1128
1385
  return (c.x - held.lastCast.from.x) * d.x + (c.y - held.lastCast.from.y) * d.y + (c.z - held.lastCast.from.z) * d.z + 0 * tt.x;
1129
1386
  };
1130
- assert.ok(Math.abs(at() - 3.75) < 1e-5);
1387
+ assert.ok(Math.abs(at() - 2.75) < 1e-5);
1131
1388
  let last = at();
1132
1389
  for (let i = 0; i < 90; i += 1) {
1133
1390
  if (i < 20) held.gestures.wheel(-100, 0);
1134
1391
  held.frame();
1135
1392
  const now = at();
1136
1393
  assert.ok(now > 0, `frame ${i}: the camera is not through the player (${now})`);
1137
- assert.ok(now <= 3.75 + 1e-5, `frame ${i}: nor past the wall (${now})`);
1394
+ assert.ok(now <= 2.75 + 1e-5, `frame ${i}: nor past the wall (${now})`);
1138
1395
  assert.ok(now <= last + 1e-5, `frame ${i}: and only comes nearer (${now} after ${last})`);
1139
1396
  assert.ok(now >= Math.min(0.6, held.scene.cameraOrbit.range) - 1e-9, `frame ${i}: no nearer than 0.6 m`);
1140
1397
  last = now;
1141
1398
  }
1142
- assert.equal(held.scene.cameraOrbit.range, 3, 'zoomed all the way in');
1143
- assert.ok(Math.abs(at() - 3) < 1e-3, `at the distance asked, nearer than the wall (${at()})`);
1399
+ assert.equal(held.scene.cameraOrbit.range, NEAREST, 'zoomed all the way in');
1400
+ assert.ok(Math.abs(at() - NEAREST) < 1e-3, `at the distance asked, nearer than the wall (${at()})`);
1144
1401
  // Back out with the wall still there: no farther than in front of it.
1145
1402
  for (let i = 0; i < 20; i += 1) held.gestures.wheel(100, 0);
1146
1403
  held.run(90);
1147
- assert.ok(Math.abs(at() - 3.75) < 1e-5, `held in front of the wall again (${at()})`);
1404
+ assert.ok(Math.abs(at() - 2.75) < 1e-5, `held in front of the wall again (${at()})`);
1148
1405
  checks += 1;
1149
1406
  }
1150
1407
  // With nothing in the way, zooming in and out is at the zoom's own pace,
@@ -1156,13 +1413,16 @@ function blocked() {
1156
1413
  free.run(30);
1157
1414
  const tt = free.actor.components.Transform;
1158
1415
  const dist = () => Math.hypot(free.camera.position.x - tt.x, free.camera.position.y - (tt.y + LOOK_HEIGHT), free.camera.position.z - tt.z);
1159
- assert.ok(Math.abs(dist() - 3) < 1e-2, `zooming in (${dist()})`);
1416
+ assert.ok(Math.abs(dist() - NEAREST) < 1e-2, `zooming in (${dist()})`);
1417
+ // Out in two frames' asking (a frame takes no more than 16 times).
1418
+ for (let i = 0; i < 40; i += 1) free.gestures.wheel(100, 0);
1419
+ free.frame();
1160
1420
  for (let i = 0; i < 40; i += 1) free.gestures.wheel(100, 0);
1161
1421
  free.run(30);
1162
- assert.ok(Math.abs(dist() - 12) < 5e-2, `and out (${dist()})`);
1422
+ assert.ok(Math.abs(dist() - FARTHEST) < 5e-2, `and out (${dist()})`);
1163
1423
  checks += 1;
1164
1424
  }
1165
- // No physics world: no ray, and the camera is placed all the same.
1425
+ // No physics world: no query, and the camera is placed all the same.
1166
1426
  {
1167
1427
  const unready = makeWorld('orbit');
1168
1428
  unready.ready = false;
@@ -1171,21 +1431,158 @@ function blocked() {
1171
1431
  t0.x += 0.05;
1172
1432
  unready.frame();
1173
1433
  }
1174
- assert.equal(unready.casts, 0, 'no ray without a world');
1434
+ assert.equal(unready.casts, 0, 'no query without a world');
1175
1435
  assert.ok(unready.off(unready.rest(Math.PI / 4, PITCH0, RANGE0)) < 1e-2, 'placed before physics is ready');
1176
1436
  checks += 1;
1177
1437
  }
1178
- // An api without castRayFixed (an older physics system): no collision.
1179
- {
1438
+ // An api without the lens's queries (an older physics system): no
1439
+ // collision.
1440
+ for (const missing of ['castBallFixed', 'nearFixed', 'castRayFixedNormal']) {
1180
1441
  const old = makeWorld('orbit');
1181
- delete old.scene.physics3d.castRayFixed;
1442
+ old.wall = 2;
1443
+ delete old.scene.physics3d[missing];
1182
1444
  old.run(90);
1183
- assert.ok(old.off(old.rest(Math.PI / 4, PITCH0, RANGE0)) < 1e-3);
1445
+ assert.ok(old.off(old.rest(Math.PI / 4, PITCH0, RANGE0)) < 1e-3, `without ${missing}`);
1184
1446
  checks += 1;
1185
1447
  }
1186
1448
  return checks;
1187
1449
  }
1188
1450
 
1451
+ // Below the horizontal the ground holds the camera above itself as a wall
1452
+ // holds it in front. On flat ground (a fixed solid whose top is at y = 0, as
1453
+ // the kit's ground is), at every tilt from 80 degrees up to 80 down and at
1454
+ // every zoom, walking and jumping, the camera and the whole of its near plane
1455
+ // (a 70 degree lens on a 20:9 screen) stay above the ground; held by it, the
1456
+ // camera is 0.25 m off it, square to it. The queries are the ground's: a
1457
+ // stand-in plane, or rapier's own (`fixedRay`).
1458
+ const GROUND = [{ n: { x: 0, y: 1, z: 0 }, d: 0 }];
1459
+ function grounded(api = null) {
1460
+ const world = makeWorld('orbit');
1461
+ const camera = world.camera;
1462
+ camera.fov = 70;
1463
+ camera.aspect = 20 / 9;
1464
+ camera.updateProjectionMatrix();
1465
+ if (api) queriesOf(world, api);
1466
+ else halfSpaces(world, GROUND);
1467
+ const corner = new THREE.Vector3();
1468
+ let lowest = Infinity;
1469
+ let frames = 0;
1470
+ const check = () => {
1471
+ camera.updateMatrixWorld();
1472
+ for (const [x, y] of [[-1, -1], [1, -1], [1, 1], [-1, 1], [0, 0]]) {
1473
+ corner.set(x, y, -1).unproject(camera);
1474
+ lowest = Math.min(lowest, corner.y);
1475
+ assert.ok(corner.y > 0, `frame ${frames}: the near plane is above the ground (${corner.y} at ${world.scene.cameraOrbit.pitch / DEG} degrees, ${world.scene.cameraOrbit.range} m)`);
1476
+ }
1477
+ frames += 1;
1478
+ };
1479
+ world.run(90);
1480
+ let pointer = 10;
1481
+ for (const zoom of [FARTHEST, 20, 8, RANGE0, NEAREST]) {
1482
+ world.scene.cameraOrbit.range = zoom;
1483
+ // Up to the top, then down to the bottom in steps of 2.5 degrees, a
1484
+ // drag a frame, walking and jumping.
1485
+ for (const [dy, steps] of [[1, 80], [-1, 80]]) {
1486
+ pointer += 1;
1487
+ world.gestures.down(pointer, { x: 900, y: 400, time: 0, left: false });
1488
+ let y = 400;
1489
+ for (let i = 0; i < steps; i += 1) {
1490
+ y += dy * ((2.5 * DEG) / LOOK_RAD_PER_PX);
1491
+ world.gestures.move(pointer, 900, y, i + 1);
1492
+ world.frame(UNEVEN(i), i % 40 < 20 ? ['KeyW'] : i % 40 === 25 ? ['Space'] : []);
1493
+ check();
1494
+ }
1495
+ world.gestures.up(pointer, 9999, false);
1496
+ world.run(90);
1497
+ check();
1498
+ }
1499
+ assert.equal(world.scene.cameraOrbit.pitch, PITCH_LEAST);
1500
+ // Settled at the bottom: held by the ground, 0.25 m off it.
1501
+ if (zoom >= RANGE0) assert.ok(Math.abs(camera.position.y - 0.25) < 1e-3, `held 0.25 m off the ground (${camera.position.y})`);
1502
+ }
1503
+ // Not held when the ground is not in the way: at the start, the camera
1504
+ // is where it rests.
1505
+ const fresh = makeWorld('orbit');
1506
+ if (api) queriesOf(fresh, api);
1507
+ else halfSpaces(fresh, GROUND);
1508
+ fresh.run(90);
1509
+ assert.ok(fresh.off(fresh.rest(fresh.scene.persistent.camAngle, PITCH0, RANGE0)) < 1e-3, 'the ground does not hold a camera above it');
1510
+ assert.ok(lowest > 0 && frames > 800);
1511
+ return 1;
1512
+ }
1513
+
1514
+ // A wide lens needs a wider stand-off (review 1, finding 5). A wall square
1515
+ // to the x axis 0.8 m from the player, a 120 degree lens: the whole near
1516
+ // plane stays in front of the wall on a 20:9 screen and on a 9:20 one, at
1517
+ // the start's tilt and the reported yaw, and across tilts, yaws and zooms.
1518
+ // The stand-off at 70 degrees on 20:9 is the 0.25 m it was.
1519
+ function wideLens() {
1520
+ let checks = 0;
1521
+ const WALL = 0.8;
1522
+ const corner = new THREE.Vector3();
1523
+ const nearestCorner = (camera) => {
1524
+ camera.updateMatrixWorld();
1525
+ let most = -Infinity;
1526
+ for (const [x, y] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) {
1527
+ corner.set(x, y, -1).unproject(camera);
1528
+ most = Math.max(most, corner.x);
1529
+ }
1530
+ return most;
1531
+ };
1532
+ const lensWorld = (fov, aspect, wall = WALL) => {
1533
+ const world = makeWorld('orbit');
1534
+ world.scene.data = { engine: { camera: { follow: 'rigid', control: 'orbit', fov } } };
1535
+ // As orbitlens.js `fitOrbitLens` sets it at the draw.
1536
+ world.camera.fov = fov;
1537
+ world.camera.aspect = aspect;
1538
+ world.camera.updateProjectionMatrix();
1539
+ return halfSpaces(world, [{ n: { x: -1, y: 0, z: 0 }, d: -wall, actorId: 'wall' }]);
1540
+ };
1541
+ // The report: 120 degrees, 20:9, the start's 15 degree tilt, yaw -20.
1542
+ for (const aspect of [20 / 9, 9 / 20]) {
1543
+ const world = lensWorld(120, aspect);
1544
+ world.scene.persistent.camAngle = -20 * DEG;
1545
+ world.run(120);
1546
+ assert.ok(Math.abs(world.scene.cameraOrbit.pitch - PITCH0) < 1e-12);
1547
+ const x = world.camera.position.x;
1548
+ const reach = nearestCorner(world.camera);
1549
+ assert.ok(reach < WALL, `aspect ${aspect.toFixed(3)}: the near plane stays in front of the wall (a corner at x = ${reach.toFixed(3)}, the camera at ${x.toFixed(3)})`);
1550
+ const half = Math.tan(60 * DEG);
1551
+ const margin = 0.1 * Math.sqrt(1 + half * half + (aspect * half) ** 2) + 0.05;
1552
+ assert.ok(Math.abs(WALL - x - margin) < 1e-3, `held its lens's stand-off off the wall, square to it (${(WALL - x).toFixed(4)} m, want ${margin.toFixed(4)})`);
1553
+ checks += 2;
1554
+ }
1555
+ // Every tilt, yaw and zoom toward the wall, at 120 degrees both ways round
1556
+ // and at 90 degrees on 20:9.
1557
+ for (const [fov, aspect] of [[120, 20 / 9], [120, 9 / 20], [90, 20 / 9]]) {
1558
+ const world = lensWorld(fov, aspect);
1559
+ world.run(30);
1560
+ for (const range of [NEAREST, RANGE0, 12]) {
1561
+ for (let pitch = -60; pitch <= 80; pitch += 20) {
1562
+ for (let yaw = -80; yaw <= 0; yaw += 20) {
1563
+ world.scene.persistent.camAngle = yaw * DEG;
1564
+ world.scene.cameraOrbit.pitch = pitch * DEG;
1565
+ world.scene.cameraOrbit.range = range;
1566
+ world.run(60);
1567
+ const reach = nearestCorner(world.camera);
1568
+ assert.ok(reach < WALL, `${fov} degrees, aspect ${aspect.toFixed(3)}, tilt ${pitch}, yaw ${yaw}, ${range} m: a corner at x = ${reach.toFixed(3)}`);
1569
+ checks += 1;
1570
+ }
1571
+ }
1572
+ }
1573
+ }
1574
+ // The default lens: 0.25 m, as before.
1575
+ const world = lensWorld(70, 20 / 9, 2);
1576
+ world.scene.data = {};
1577
+ world.scene.persistent.camAngle = -90 * DEG;
1578
+ world.scene.cameraOrbit = null;
1579
+ world.run(120);
1580
+ world.scene.cameraOrbit.pitch = 0;
1581
+ world.run(120);
1582
+ assert.ok(Math.abs(2 - world.camera.position.x - 0.25) < 1e-6, `0.25 m off the wall at 70 degrees (${2 - world.camera.position.x})`);
1583
+ return checks + 1;
1584
+ }
1585
+
1189
1586
  // Without the key the character always faces PI - camAngle, so code that
1190
1587
  // turns it sets camAngle. Under the key turning the character is asked for
1191
1588
  // (`scene.faceRequest`, as the hub asks beside its camAngle write); a
@@ -1808,6 +2205,648 @@ function listeners() {
1808
2205
  return checks;
1809
2206
  }
1810
2207
 
2208
+ // Desktop mouse capture under the key: a stand-in document and window
2209
+ // (pointerLockElement, exitPointerLock, the lock's events, blur and
2210
+ // visibilitychange) behind a stand-in canvas that can ask for the lock.
2211
+ // `mode` is how requestPointerLock answers: 'promise' (a promise settled
2212
+ // by `grant`/`deny`), 'none' (returns nothing, as old Safari: the events
2213
+ // only), 'throw', or 'missing' (no requestPointerLock at all).
2214
+ // `exit` is how exitPointerLock ends the lock: 'webkit' clears
2215
+ // pointerLockElement and sends pointerlockchange later (`flush`);
2216
+ // 'chromium' clears it inside the call and sends the event later.
2217
+ function makeLockDom(mode = 'promise', canvas = makeCanvas(), exit = 'webkit') {
2218
+ const doc = makeCanvas();
2219
+ const win = makeCanvas();
2220
+ doc.defaultView = win;
2221
+ doc.pointerLockElement = null;
2222
+ doc.visibilityState = 'visible';
2223
+ doc.exits = 0;
2224
+ doc.exitPointerLock = () => {
2225
+ doc.exits += 1;
2226
+ if (exit === 'chromium') {
2227
+ if (doc.pointerLockElement === null) return;
2228
+ doc.pointerLockElement = null;
2229
+ dom.later.push(() => doc.fire('pointerlockchange'));
2230
+ return;
2231
+ }
2232
+ // The browser exits after the call returns.
2233
+ dom.later.push(() => {
2234
+ if (doc.pointerLockElement === null) return;
2235
+ doc.pointerLockElement = null;
2236
+ doc.fire('pointerlockchange');
2237
+ });
2238
+ };
2239
+ canvas.ownerDocument = doc;
2240
+ canvas.requests = 0;
2241
+ // Which pointers are captured now: a lock that lands takes every capture
2242
+ // away (the Pointer Events spec's implicit release), and a capture cannot
2243
+ // be taken while the lock is on.
2244
+ canvas.holding = new Set();
2245
+ // Pointers that came up beyond the canvas: no longer active.
2246
+ canvas.gone = new Set();
2247
+ canvas.hasPointerCapture = (id) => canvas.holding.has(id);
2248
+ canvas.setPointerCapture = (id) => {
2249
+ if (canvas.gone.has(id)) throw Object.assign(new Error('not active'), { name: 'NotFoundError' });
2250
+ if (doc.pointerLockElement === canvas) throw Object.assign(new Error('locked'), { name: 'InvalidStateError' });
2251
+ canvas.captured.push(id);
2252
+ canvas.holding.add(id);
2253
+ };
2254
+ const dom = { canvas, doc, win, later: [], waiting: [] };
2255
+ if (mode !== 'missing') {
2256
+ canvas.requestPointerLock = () => {
2257
+ canvas.requests += 1;
2258
+ if (mode === 'throw') throw new Error('no lock here');
2259
+ let settle;
2260
+ const promise = new Promise((resolve, reject) => (settle = { resolve, reject }));
2261
+ dom.waiting.push(settle);
2262
+ return mode === 'promise' ? promise : undefined;
2263
+ };
2264
+ }
2265
+ // The lock lands (pointerlockchange, then the promise).
2266
+ dom.grant = async () => {
2267
+ const settle = dom.waiting.shift();
2268
+ doc.pointerLockElement = canvas;
2269
+ canvas.holding.clear();
2270
+ doc.fire('pointerlockchange');
2271
+ settle.resolve();
2272
+ await tick();
2273
+ };
2274
+ // Refused: pointerlockerror and a rejection (a SecurityError in Chrome).
2275
+ dom.deny = async () => {
2276
+ const settle = dom.waiting.shift();
2277
+ doc.fire('pointerlockerror');
2278
+ settle.reject(Object.assign(new Error('refused'), { name: 'SecurityError' }));
2279
+ await tick();
2280
+ };
2281
+ // The browser ends the lock itself (Escape, the host taking focus).
2282
+ dom.escape = () => {
2283
+ doc.pointerLockElement = null;
2284
+ doc.fire('pointerlockchange');
2285
+ };
2286
+ dom.flush = () => {
2287
+ for (const fn of dom.later.splice(0)) fn();
2288
+ };
2289
+ dom.locked = () => doc.pointerLockElement === canvas;
2290
+ dom.watched = () => [...doc.types(), ...win.types().map((t) => `window:${t}`)];
2291
+ return dom;
2292
+ }
2293
+ const tick = () => new Promise((resolve) => setTimeout(resolve, 0));
2294
+
2295
+ async function mouseLock() {
2296
+ let checks = 0;
2297
+ const make = (mode) => {
2298
+ const dom = makeLockDom(mode);
2299
+ const runtime = { cameraControl: 'orbit', taps: 0 };
2300
+ const stick = { x: 0, y: 0, active: false };
2301
+ const orbit = attachOrbitInput(dom.canvas, runtime, stick, () => (runtime.taps += 1), TUNING);
2302
+ runtime.lookInput.listen();
2303
+ const ev = (id, x, y, more = {}) => ({ pointerId: id, clientX: x, clientY: y, pointerType: 'mouse', button: -1, buttons: 1, ...more });
2304
+ const take = () => ({ ...runtime.lookInput.consume() });
2305
+ return { ...dom, dom, runtime, stick, orbit, ev, take };
2306
+ };
2307
+ const near = (a, b) => Math.abs(a - b) < 1e-12;
2308
+
2309
+ // A left drag: no lock at the press or inside the slop; once past it the
2310
+ // lock is asked for, once. Locked, the turn is movementX/Y (the client
2311
+ // position stands still); the pointerup lets go of it and the listeners.
2312
+ {
2313
+ const h = make('promise');
2314
+ h.orbit.down(h.ev(1, 700, 300, { button: 0 }));
2315
+ assert.equal(h.canvas.requests, 0, 'a left press does not ask');
2316
+ assert.deepEqual(h.watched().sort(), ['visibilitychange', 'window:blur'], 'it listens for a blur or the page hidden only, while the button is down');
2317
+ h.orbit.move(h.ev(1, 705, 304));
2318
+ assert.equal(h.canvas.requests, 0, 'nor a move inside the slop');
2319
+ h.orbit.move(h.ev(1, 720, 300));
2320
+ assert.equal(h.canvas.requests, 1, 'past the slop it asks');
2321
+ assert.deepEqual(h.watched().sort(), ['pointercancel', 'pointerlockchange', 'pointerup', 'visibilitychange', 'window:blur'], 'and for the lock coming and going (the promise says how the request went), and for lifts beyond the canvas while it may take captures');
2322
+ assert.ok(near(h.take().yaw, 15 * LOOK_RAD_PER_PX), 'before the lock lands the client position turns');
2323
+ h.orbit.move(h.ev(1, 730, 300));
2324
+ assert.equal(h.canvas.requests, 1, 'once per drag');
2325
+ h.take();
2326
+ await h.grant();
2327
+ assert.equal(h.locked(), true);
2328
+ assert.equal(h.orbit.move(h.ev(1, 730, 300, { movementX: 40, movementY: -10 })), true);
2329
+ let got = h.take();
2330
+ assert.ok(near(got.yaw, 40 * LOOK_RAD_PER_PX) && near(got.pitch, -10 * LOOK_RAD_PER_PX), 'locked: movementX/Y at the same scale');
2331
+ h.orbit.move(h.ev(1, 730, 300, { movementX: -5, movementY: 0 }));
2332
+ h.orbit.move(h.ev(1, 730, 300, { movementX: undefined, movementY: undefined }));
2333
+ got = h.take();
2334
+ assert.ok(near(got.yaw, -5 * LOOK_RAD_PER_PX) && got.pitch === 0, 'and only them');
2335
+ assert.equal(h.orbit.up(h.ev(1, 730, 300, { button: 0, buttons: 0, type: 'pointerup' })), true);
2336
+ assert.equal(h.doc.exits, 1, 'the release lets go of the lock');
2337
+ h.flush();
2338
+ assert.equal(h.locked(), false);
2339
+ assert.deepEqual(h.watched(), [], 'and every listener once it is gone');
2340
+ assert.equal(h.runtime.taps, 0, 'a drag does not jump');
2341
+ assert.equal(h.orbit.busy, false);
2342
+ checks += 1;
2343
+ }
2344
+ // A left tap still jumps, and is never locked, quick clicks one after
2345
+ // another included.
2346
+ {
2347
+ const h = make('promise');
2348
+ for (let i = 0; i < 3; i += 1) {
2349
+ h.orbit.down(h.ev(1, 700, 300, { button: 0 }));
2350
+ h.orbit.move(h.ev(1, 703, 302));
2351
+ h.orbit.up(h.ev(1, 703, 302, { button: 0, buttons: 0, type: 'pointerup' }));
2352
+ }
2353
+ assert.equal(h.runtime.taps, 3, 'every left tap jumps');
2354
+ assert.equal(h.canvas.requests, 0, 'none asks for the lock');
2355
+ assert.deepEqual(h.watched(), []);
2356
+ assert.deepEqual(h.canvas.captured, [1, 1, 1], 'the capture at the press, as before');
2357
+ checks += 1;
2358
+ }
2359
+ // A right drag asks at the press; a right click alone does not jump, and
2360
+ // the context menu is kept off the canvas.
2361
+ {
2362
+ const h = make('promise');
2363
+ h.orbit.down(h.ev(1, 700, 300, { button: 2, buttons: 2 }));
2364
+ assert.equal(h.canvas.requests, 1, 'a right press asks at once');
2365
+ await h.grant();
2366
+ assert.equal(h.canvas.fire('contextmenu'), true, 'the context menu is prevented');
2367
+ h.orbit.move(h.ev(1, 700, 300, { buttons: 2, movementX: 6, movementY: 0 }));
2368
+ assert.deepEqual(h.take(), { yaw: 0, pitch: 0, zoom: 1, locked: false }, 'inside the slop nothing turns');
2369
+ h.orbit.move(h.ev(1, 700, 300, { buttons: 2, movementX: 10, movementY: 0 }));
2370
+ assert.ok(h.take().yaw > 0, 'past it (counted from movement) it does');
2371
+ h.orbit.up(h.ev(1, 700, 300, { button: 2, buttons: 0, type: 'pointerup' }));
2372
+ h.flush();
2373
+ assert.equal(h.locked(), false);
2374
+ h.orbit.down(h.ev(1, 700, 300, { button: 2, buttons: 2 }));
2375
+ h.orbit.up(h.ev(1, 700, 300, { button: 2, buttons: 0, type: 'pointerup' }));
2376
+ assert.equal(h.runtime.taps, 0, 'a right click does not jump');
2377
+ // That click's lock lands after its release: let go of at once.
2378
+ await h.grant();
2379
+ assert.equal(h.doc.exits, 2, 'a lock that lands after the release is let go of');
2380
+ h.flush();
2381
+ assert.equal(h.locked(), false);
2382
+ assert.deepEqual(h.watched(), []);
2383
+ checks += 1;
2384
+ }
2385
+ // A lock arriving after the release, by the events alone (old Safari:
2386
+ // no promise), and one landing while the next press is still a tap.
2387
+ {
2388
+ const h = make('none');
2389
+ h.orbit.down(h.ev(1, 700, 300, { button: 0 }));
2390
+ h.orbit.move(h.ev(1, 740, 300));
2391
+ h.orbit.up(h.ev(1, 740, 300, { button: 0, buttons: 0, type: 'pointerup' }));
2392
+ h.orbit.down(h.ev(1, 700, 300, { button: 0 }));
2393
+ await h.grant();
2394
+ assert.equal(h.doc.exits, 1, 'landing on a tap: let go of');
2395
+ h.flush();
2396
+ h.orbit.up(h.ev(1, 700, 300, { button: 0, buttons: 0, type: 'pointerup' }));
2397
+ assert.equal(h.runtime.taps, 1, 'and the tap still jumps');
2398
+ assert.deepEqual(h.watched(), []);
2399
+ // With the events alone, a refusal is pointerlockerror; it does not say
2400
+ // whose it is, so ours is watched for a while after it.
2401
+ h.take();
2402
+ h.orbit.down(h.ev(1, 700, 300, { button: 2, buttons: 2 }));
2403
+ h.doc.fire('pointerlockerror');
2404
+ h.dom.waiting.shift();
2405
+ h.orbit.move(h.ev(1, 760, 300, { buttons: 2, movementX: 999 }));
2406
+ assert.ok(near(h.take().yaw, 60 * LOOK_RAD_PER_PX), 'refused: the client position turns, not movement');
2407
+ h.orbit.up(h.ev(1, 760, 300, { button: 2, buttons: 0, type: 'pointerup' }));
2408
+ assert.deepEqual(h.watched().sort(), ['pointercancel', 'pointerlockchange', 'pointerlockerror', 'pointerup'], 'the request is still watched');
2409
+ await new Promise((resolve) => setTimeout(resolve, 1100));
2410
+ assert.deepEqual(h.watched(), [], 'and not after a second');
2411
+ checks += 1;
2412
+ }
2413
+ // Another element's pointerlockerror while ours is on its way (old
2414
+ // Safari: no promise, so an error does not say whose it is): our lock,
2415
+ // landing after the release, is still let go of.
2416
+ {
2417
+ const h = make('none');
2418
+ h.orbit.down(h.ev(1, 700, 300, { button: 2, buttons: 2 }));
2419
+ assert.equal(h.canvas.requests, 1);
2420
+ h.doc.fire('pointerlockerror');
2421
+ h.orbit.up(h.ev(1, 700, 300, { button: 2, buttons: 0, type: 'pointerup' }));
2422
+ await h.grant();
2423
+ assert.equal(h.doc.exits, 1, 'a lock of ours landing after a foreign error is let go of');
2424
+ h.flush();
2425
+ assert.equal(h.locked(), false);
2426
+ assert.deepEqual(h.watched(), [], 'and nothing is left listening once it is gone');
2427
+ checks += 1;
2428
+ }
2429
+ // With a promise, a pointerlockerror is never taken for ours: the promise
2430
+ // says how our request went.
2431
+ {
2432
+ const h = make('promise');
2433
+ h.orbit.down(h.ev(1, 700, 300, { button: 2, buttons: 2 }));
2434
+ h.doc.fire('pointerlockerror');
2435
+ await h.grant();
2436
+ h.orbit.move(h.ev(1, 700, 300, { buttons: 2, movementX: 30 }));
2437
+ assert.ok(near(h.take().yaw, 30 * LOOK_RAD_PER_PX), 'a foreign error leaves our lock and its movement');
2438
+ h.orbit.up(h.ev(1, 700, 300, { button: 2, buttons: 0, type: 'pointerup' }));
2439
+ h.flush();
2440
+ assert.equal(h.locked(), false);
2441
+ assert.deepEqual(h.watched(), []);
2442
+ checks += 1;
2443
+ }
2444
+ // A late lock landing during the next left tap takes that tap's capture
2445
+ // (the spec's implicit release); once it is let go of, the capture is
2446
+ // given back, so a release beyond the canvas still ends the tap, a jump.
2447
+ for (const mode of ['promise', 'none']) {
2448
+ const h = make(mode);
2449
+ h.orbit.down(h.ev(1, 700, 300, { button: 2, buttons: 2 }));
2450
+ h.orbit.up(h.ev(1, 700, 300, { button: 2, buttons: 0, type: 'pointerup' }));
2451
+ h.canvas.holding.clear();
2452
+ h.orbit.down(h.ev(1, 995, 300, { button: 0 }));
2453
+ await h.grant();
2454
+ assert.equal(h.canvas.holding.has(1), false, `${mode}: the lock took the capture`);
2455
+ h.flush();
2456
+ assert.equal(h.locked(), false);
2457
+ assert.equal(h.canvas.holding.has(1), true, `${mode}: and it is given back`);
2458
+ assert.equal(h.orbit.move(h.ev(1, 1001, 300)), true);
2459
+ h.orbit.up(h.ev(1, 1001, 300, { button: 0, buttons: 0, type: 'pointerup' }));
2460
+ assert.deepEqual({ busy: h.orbit.busy, taps: h.runtime.taps }, { busy: false, taps: 1 }, `${mode}: the tap ends, a jump`);
2461
+ assert.deepEqual(h.watched(), []);
2462
+ checks += 1;
2463
+ }
2464
+ // A lost pointerup never leaves a mouse pointer held: the next press, a
2465
+ // move with no button down, or a blur ends it.
2466
+ for (const how of ['press', 'buttons0', 'blur']) {
2467
+ const h = make('missing');
2468
+ h.orbit.down(h.ev(1, 700, 300, { button: 0 }));
2469
+ if (how === 'press') {
2470
+ h.orbit.down(h.ev(2, 700, 300, { button: 0 }));
2471
+ h.orbit.up(h.ev(2, 700, 300, { button: 0, buttons: 0, type: 'pointerup' }));
2472
+ }
2473
+ if (how === 'buttons0') h.orbit.move(h.ev(1, 700, 300, { buttons: 0 }));
2474
+ if (how === 'blur') h.win.fire('blur');
2475
+ assert.equal(h.orbit.busy, false, `${how}: nothing is held`);
2476
+ assert.equal(h.runtime.taps, how === 'press' ? 1 : 0, `${how}: only a real tap jumps`);
2477
+ assert.deepEqual(h.watched(), []);
2478
+ checks += 1;
2479
+ }
2480
+ // Each way a held, locked drag is let go of: the drag ends with no tap and
2481
+ // no look or stick left held, the lock is let go of, and so are the
2482
+ // listeners.
2483
+ for (const how of ['blur', 'hidden', 'escape', 'buttons0', 'reset', 'detach', 'cancel']) {
2484
+ const h = make('promise');
2485
+ h.orbit.down(h.ev(1, 700, 300, { button: 0 }));
2486
+ h.orbit.move(h.ev(1, 740, 300));
2487
+ await h.grant();
2488
+ h.take();
2489
+ if (how === 'blur') h.win.fire('blur');
2490
+ if (how === 'hidden') {
2491
+ h.doc.fire('visibilitychange');
2492
+ assert.equal(h.orbit.busy, true, `${how}: a visibilitychange to visible is nothing`);
2493
+ h.doc.visibilityState = 'hidden';
2494
+ h.doc.fire('visibilitychange');
2495
+ }
2496
+ if (how === 'escape') h.escape();
2497
+ if (how === 'buttons0') assert.equal(h.orbit.move(h.ev(1, 740, 300, { buttons: 0, movementX: 50 })), true);
2498
+ if (how === 'reset') h.runtime.lookInput.reset();
2499
+ if (how === 'detach') h.orbit.detach();
2500
+ if (how === 'cancel') h.orbit.up(h.ev(1, 740, 300, { type: 'pointercancel', buttons: 0 }));
2501
+ assert.equal(h.orbit.busy, false, `${how}: the drag is over`);
2502
+ assert.equal(h.doc.exits, how === 'escape' ? 0 : 1, `${how}: the lock is let go of`);
2503
+ h.flush();
2504
+ assert.equal(h.locked(), false, how);
2505
+ assert.deepEqual(h.watched(), [], `${how}: no listener is left`);
2506
+ assert.equal(h.orbit.move(h.ev(1, 900, 300, { movementX: 80 })), false, `${how}: its later moves are not this file's`);
2507
+ assert.deepEqual(h.take(), { yaw: 0, pitch: 0, zoom: 1, locked: false }, `${how}: nothing turns after it`);
2508
+ assert.equal(h.orbit.up(h.ev(1, 900, 300, { button: 0, buttons: 0, type: 'pointerup' })), false);
2509
+ assert.equal(h.runtime.taps, 0, `${how}: no tap`);
2510
+ assert.equal(h.stick.active, false);
2511
+ checks += 1;
2512
+ }
2513
+ // Escape, then a drag at once: Chrome refuses the re-lock (a rejection)
2514
+ // and the drag goes on, on the capture, with nothing thrown.
2515
+ {
2516
+ const h = make('promise');
2517
+ h.orbit.down(h.ev(1, 700, 300, { button: 2, buttons: 2 }));
2518
+ await h.grant();
2519
+ h.escape();
2520
+ h.orbit.down(h.ev(1, 700, 300, { button: 2, buttons: 2 }));
2521
+ assert.equal(h.canvas.requests, 2);
2522
+ await h.deny();
2523
+ // Out of the frame and back: the capture keeps the moves coming.
2524
+ h.orbit.move(h.ev(1, -200, 300, { buttons: 2 }));
2525
+ assert.ok(near(h.take().yaw, -900 * LOOK_RAD_PER_PX), 'refused: the drag turns on the client position, beyond the frame');
2526
+ h.orbit.up(h.ev(1, -200, 300, { button: 2, buttons: 0, type: 'pointerup' }));
2527
+ assert.equal(h.orbit.busy, false, 'and a release outside ends it');
2528
+ assert.deepEqual(h.watched(), []);
2529
+ assert.equal(h.doc.exits, 0);
2530
+ // The next drag asks again.
2531
+ h.orbit.down(h.ev(1, 700, 300, { button: 2, buttons: 2 }));
2532
+ assert.equal(h.canvas.requests, 3);
2533
+ await h.grant();
2534
+ h.orbit.up(h.ev(1, 700, 300, { button: 2, buttons: 0, type: 'pointerup' }));
2535
+ h.flush();
2536
+ assert.deepEqual(h.watched(), []);
2537
+ checks += 1;
2538
+ }
2539
+ // A requestPointerLock that throws, or none at all: the drag as before.
2540
+ for (const mode of ['throw', 'missing']) {
2541
+ const h = make(mode);
2542
+ h.orbit.down(h.ev(1, 700, 300, { button: 2, buttons: 2 }));
2543
+ h.orbit.move(h.ev(1, 740, 300, { buttons: 2 }));
2544
+ assert.ok(near(h.take().yaw, 40 * LOOK_RAD_PER_PX), `${mode}: the drag turns`);
2545
+ h.orbit.up(h.ev(1, 740, 300, { button: 2, buttons: 0, type: 'pointerup' }));
2546
+ assert.equal(h.orbit.busy, false);
2547
+ assert.deepEqual(h.canvas.captured, [1], `${mode}: on the capture`);
2548
+ assert.deepEqual(h.watched(), [], `${mode}: nothing left listening`);
2549
+ assert.equal(h.canvas.requests, mode === 'throw' ? 1 : 0);
2550
+ checks += 1;
2551
+ }
2552
+ // A second button during a drag: pointer events send it as a pointermove.
2553
+ // Pressed during a left tap it makes a look (no jump) and asks; during a
2554
+ // locked drag it changes nothing; the lock ends with the last button.
2555
+ {
2556
+ const h = make('promise');
2557
+ h.orbit.down(h.ev(1, 700, 300, { button: 0 }));
2558
+ h.orbit.move(h.ev(1, 700, 300, { button: 2, buttons: 3 }));
2559
+ assert.equal(h.canvas.requests, 1, 'a chord asks');
2560
+ await h.grant();
2561
+ h.orbit.move(h.ev(1, 700, 300, { button: 0, buttons: 2, movementX: 3 }));
2562
+ assert.equal(h.orbit.busy, true, 'letting go of one button keeps the drag');
2563
+ assert.equal(h.doc.exits, 0);
2564
+ h.orbit.move(h.ev(1, 700, 300, { buttons: 2, movementX: 7 }));
2565
+ assert.ok(near(h.take().yaw, 10 * LOOK_RAD_PER_PX), 'a chord is a look from its press');
2566
+ h.orbit.up(h.ev(1, 700, 300, { button: 2, buttons: 0, type: 'pointerup' }));
2567
+ assert.equal(h.runtime.taps, 0, 'and does not jump');
2568
+ assert.equal(h.doc.exits, 1);
2569
+ h.flush();
2570
+ assert.deepEqual(h.watched(), []);
2571
+ checks += 1;
2572
+ }
2573
+ // Touch and pen are untouched: no lock, no listeners, as before.
2574
+ for (const pointerType of ['touch', 'pen']) {
2575
+ const h = make('promise');
2576
+ h.orbit.down({ pointerId: 1, clientX: 700, clientY: 300, pointerType, button: 0, buttons: 1 });
2577
+ h.orbit.move({ pointerId: 1, clientX: 760, clientY: 300, pointerType, buttons: 1, movementX: 500 });
2578
+ assert.ok(near(h.take().yaw, 60 * LOOK_RAD_PER_PX), `${pointerType}: the client position, as always`);
2579
+ h.orbit.move({ pointerId: 1, clientX: 760, clientY: 300, pointerType, buttons: 0 });
2580
+ assert.equal(h.orbit.busy, true, `${pointerType}: buttons 0 is not a lift`);
2581
+ h.orbit.up({ pointerId: 1, clientX: 760, clientY: 300, pointerType, type: 'pointerup' });
2582
+ h.orbit.down({ pointerId: 2, clientX: 700, clientY: 300, pointerType, button: 0 });
2583
+ h.orbit.up({ pointerId: 2, clientX: 700, clientY: 300, pointerType, type: 'pointerup' });
2584
+ assert.equal(h.runtime.taps, 1, `${pointerType}: a tap jumps`);
2585
+ assert.equal(h.canvas.requests, 0);
2586
+ assert.deepEqual(h.watched(), []);
2587
+ checks += 1;
2588
+ }
2589
+ // A scene without the key loaded while a right press's request is on its
2590
+ // way: at the load the canvas has the keyless listeners only, and with a
2591
+ // promise nothing at all on the document or window (old Safari's
2592
+ // event-only request keeps its two lock listeners until it is answered);
2593
+ // the grant that lands in the keyless scene is let go of at once, after
2594
+ // which nothing is left, and the keyless scene runs as before the key.
2595
+ for (const lockMode of ['promise', 'none']) {
2596
+ for (const mode of ['off', 'rigid']) {
2597
+ const h = makeRuntime('orbit');
2598
+ const dom = makeLockDom(lockMode, h.canvas);
2599
+ h.run(30);
2600
+ h.canvas.fire('pointerdown', { pointerId: 1, clientX: 800, clientY: 300, pointerType: 'mouse', button: 2, buttons: 2 });
2601
+ assert.equal(dom.canvas.requests, 1);
2602
+ h.load(mode);
2603
+ const what = `${lockMode}, orbit then ${mode}`;
2604
+ assert.deepEqual(h.canvas.types(), ['pointercancel', 'pointerdown', 'pointermove', 'pointerup'], `${what}: the keyless listeners only`);
2605
+ // Only lifts beyond the canvas (a grant would take captures) and, with
2606
+ // no promise, the request's own two.
2607
+ assert.deepEqual(dom.watched().sort(), lockMode === 'promise' ? ['pointercancel', 'pointerup'] : ['pointercancel', 'pointerlockchange', 'pointerlockerror', 'pointerup'], `${what}: on the document and window`);
2608
+ await dom.grant();
2609
+ assert.equal(dom.doc.exits, 1, `${what}: the late grant is let go of`);
2610
+ dom.flush();
2611
+ assert.equal(dom.locked(), false);
2612
+ assert.deepEqual(dom.watched(), [], `${what}: and nothing is left listening`);
2613
+ const twin = makeRuntime(mode, PlayerBefore);
2614
+ h.copyTo(twin);
2615
+ twin.load(mode);
2616
+ h.frames.length = 0;
2617
+ h.calls.length = 0;
2618
+ const input = keylessInput(h, twin);
2619
+ for (let i = 1; i < 200; i += 1) {
2620
+ // The right button held from the keyed scene, moved and let go of here only.
2621
+ if (i < 50) h.canvas.fire('pointermove', { pointerId: 1, clientX: 800 + i, clientY: 300, pointerType: 'mouse', button: -1, buttons: 2, movementX: 9 });
2622
+ if (i === 50) h.canvas.fire('pointerup', { pointerId: 1, clientX: 850, clientY: 300, pointerType: 'mouse', button: 2, buttons: 0 });
2623
+ const keys = input(i);
2624
+ h.frame(UNEVEN(i), keys);
2625
+ twin.frame(UNEVEN(i), keys);
2626
+ }
2627
+ sameFrames(h.frames, twin.frames, `${what}: the Player before the key`);
2628
+ assert.equal(dom.canvas.requests, 1, `${what}: no lock asked for in the keyless scene`);
2629
+ assert.deepEqual(dom.watched(), []);
2630
+ checks += 1;
2631
+ }
2632
+ }
2633
+ // Every pointer down on the canvas gets back the capture a lock of ours
2634
+ // took from it (the spec's implicit release), keyless or under the key,
2635
+ // mouse or touch: a release beyond the canvas still reaches it, so the
2636
+ // stick is let go of and a tap jumps.
2637
+ {
2638
+ const fire = (h, type, id, x, y, pointerType, button = 0, buttons = type === 'pointerup' ? 0 : 1) =>
2639
+ h.canvas.fire(type, { pointerId: id, clientX: x, clientY: y, pointerType, button, buttons });
2640
+ // Beyond the canvas, the lift reaches it only through a capture.
2641
+ const outsideUp = (h, id, x, y, pointerType) => {
2642
+ if (h.canvas.holding.has(id)) fire(h, 'pointerup', id, x, y, pointerType);
2643
+ };
2644
+ // A late grant landing in a keyless scene, on a keyless mouse stick and
2645
+ // a keyless touch tap that went down after the load.
2646
+ for (const lockMode of ['promise', 'none']) {
2647
+ for (const mode of ['off', 'rigid']) {
2648
+ const what = `${lockMode}, orbit then ${mode}`;
2649
+ const h = makeRuntime('orbit');
2650
+ const dom = makeLockDom(lockMode, h.canvas);
2651
+ h.run(10);
2652
+ fire(h, 'pointerdown', 1, 800, 300, 'mouse', 2, 2);
2653
+ h.load(mode);
2654
+ fire(h, 'pointerup', 1, 800, 300, 'mouse', 2);
2655
+ fire(h, 'pointerdown', 1, 300, 400, 'mouse');
2656
+ fire(h, 'pointermove', 1, 300, 330, 'mouse');
2657
+ fire(h, 'pointerdown', 6, 700, 300, 'touch');
2658
+ assert.equal(h.stick().active, true);
2659
+ await dom.grant();
2660
+ assert.deepEqual([...h.canvas.holding], [], 'the grant took every capture');
2661
+ assert.equal(dom.doc.exits, 1);
2662
+ dom.flush();
2663
+ assert.deepEqual([...h.canvas.holding].sort(), [1, 6], `${what}: each is given back`);
2664
+ outsideUp(h, 1, -50, 330, 'mouse');
2665
+ assert.equal(h.stick().active, false, `${what}: a release beyond the canvas lets go of the stick`);
2666
+ outsideUp(h, 6, 700, 300, 'touch');
2667
+ assert.equal(h.jumped(), true, `${what}: and a tap jumps`);
2668
+ assert.deepEqual(dom.watched(), [], `${what}: nothing is left listening`);
2669
+ checks += 1;
2670
+ }
2671
+ }
2672
+ // Under the key: a touch stick held while a mouse lock lands and ends;
2673
+ // and a touch put down while the lock is on, which cannot be captured
2674
+ // then (no throw), and is once it ends.
2675
+ for (const when of ['before', 'during']) {
2676
+ const h = makeRuntime('orbit');
2677
+ const dom = makeLockDom('promise', h.canvas);
2678
+ h.run(10);
2679
+ if (when === 'before') {
2680
+ fire(h, 'pointerdown', 7, 300, 400, 'touch');
2681
+ fire(h, 'pointermove', 7, 300, 330, 'touch');
2682
+ }
2683
+ fire(h, 'pointerdown', 1, 800, 300, 'mouse', 2, 2);
2684
+ await dom.grant();
2685
+ if (when === 'during') {
2686
+ fire(h, 'pointerdown', 7, 300, 400, 'touch');
2687
+ fire(h, 'pointermove', 7, 300, 330, 'touch');
2688
+ }
2689
+ assert.equal(h.stick().active, true, `${when}: the touch walks`);
2690
+ assert.equal(h.canvas.holding.has(7), false);
2691
+ fire(h, 'pointerup', 1, 800, 300, 'mouse', 2);
2692
+ dom.flush();
2693
+ assert.equal(h.canvas.holding.has(7), true, `${when}: the touch gets its capture once the lock ends`);
2694
+ outsideUp(h, 7, -10, 330, 'touch');
2695
+ assert.equal(h.stick().active, false, `${when}: and its release beyond the canvas lets go of the stick`);
2696
+ assert.equal(h.runtime.orbitInput().busy, false);
2697
+ assert.deepEqual(dom.watched(), []);
2698
+ checks += 1;
2699
+ }
2700
+ }
2701
+ // A finger lifted beyond the canvas while a lock of ours had its capture:
2702
+ // its pointerup never reaches the canvas, and once the lock ends it is
2703
+ // let go of as a pointercancel would be, as origin/main's capture would
2704
+ // have: the stick idles, nothing is held, the next finger takes the
2705
+ // stick. Under the key, and keyless (a late grant after a scene load).
2706
+ {
2707
+ const fire = (h, type, id, x, y, pointerType, button = 0, buttons = type === 'pointerup' ? 0 : 1) =>
2708
+ h.canvas.fire(type, { pointerId: id, clientX: x, clientY: y, pointerType, button, buttons });
2709
+ for (const scene of ['orbit', 'off', 'rigid']) {
2710
+ const h = makeRuntime('orbit');
2711
+ const dom = makeLockDom('promise', h.canvas);
2712
+ h.run(10);
2713
+ if (scene !== 'orbit') {
2714
+ fire(h, 'pointerdown', 1, 800, 300, 'mouse', 2, 2);
2715
+ h.load(scene);
2716
+ fire(h, 'pointerup', 1, 800, 300, 'mouse', 2);
2717
+ }
2718
+ fire(h, 'pointerdown', 7, 300, 400, 'touch');
2719
+ fire(h, 'pointermove', 7, 300, 330, 'touch');
2720
+ if (scene === 'orbit') fire(h, 'pointerdown', 1, 800, 300, 'mouse', 2, 2);
2721
+ await dom.grant();
2722
+ // The finger lifts beyond the canvas: its pointerup goes elsewhere.
2723
+ h.canvas.gone.add(7);
2724
+ if (scene === 'orbit') fire(h, 'pointerup', 1, 800, 300, 'mouse', 2);
2725
+ assert.equal(h.stick().active, true, `${scene}: walking until the lock ends`);
2726
+ dom.flush();
2727
+ assert.equal(dom.locked(), false);
2728
+ assert.equal(h.stick().active, false, `${scene}: the finger lifted beyond the canvas lets go of the stick`);
2729
+ assert.equal(h.runtime.orbitInput().busy, false, `${scene}: nothing is held`);
2730
+ assert.equal(h.jumped(), false, `${scene}: and it is no tap`);
2731
+ fire(h, 'pointerdown', 8, 300, 400, 'touch');
2732
+ fire(h, 'pointermove', 8, 300, 340, 'touch');
2733
+ assert.equal(h.stick().active, true, `${scene}: the next finger takes the stick`);
2734
+ fire(h, 'pointerup', 8, 300, 340, 'touch');
2735
+ assert.equal(h.stick().active, false);
2736
+ assert.deepEqual(dom.watched(), []);
2737
+ checks += 1;
2738
+ }
2739
+ }
2740
+ // A late grant crossing into a keyless scene, under both unlock timings:
2741
+ // Chromium clears pointerLockElement inside exitPointerLock and sends
2742
+ // pointerlockchange later; WebKit does both later. A touch stick and a
2743
+ // touch tap that went down in the keyless scene lose their captures to
2744
+ // the grant. Lifted beyond the canvas before the unlock event: the
2745
+ // document catches each lift and hands it to the keyless handler, so the
2746
+ // stick stops and the tap jumps. Lifted beyond it after: the capture
2747
+ // given back at the unlock event brings it to the canvas.
2748
+ {
2749
+ const fire = (h, type, id, x, y, pointerType, button = 0, buttons = type === 'pointerup' ? 0 : 1) =>
2750
+ h.canvas.fire(type, { pointerId: id, clientX: x, clientY: y, pointerType, button, buttons });
2751
+ // A lift beyond the canvas: to the canvas if it holds the capture, else
2752
+ // to the document (capture phase), aimed at something else.
2753
+ const liftOutside = (h, dom, id, x, y) => {
2754
+ const event = { pointerId: id, clientX: x, clientY: y, pointerType: 'touch', button: 0, buttons: 0 };
2755
+ if (h.canvas.holding.has(id)) h.canvas.fire('pointerup', event);
2756
+ else {
2757
+ h.canvas.gone.add(id);
2758
+ dom.doc.fire('pointerup', { ...event, target: 'elsewhere' });
2759
+ }
2760
+ };
2761
+ for (const exit of ['chromium', 'webkit']) {
2762
+ for (const lift of ['before', 'after']) {
2763
+ const what = `${exit}, lifted ${lift} the unlock event`;
2764
+ const h = makeRuntime('orbit');
2765
+ const dom = makeLockDom('promise', h.canvas, exit);
2766
+ h.run(10);
2767
+ fire(h, 'pointerdown', 1, 800, 300, 'mouse', 2, 2);
2768
+ h.load('off');
2769
+ fire(h, 'pointerup', 1, 800, 300, 'mouse', 2);
2770
+ fire(h, 'pointerdown', 7, 300, 400, 'touch');
2771
+ fire(h, 'pointermove', 7, 300, 330, 'touch');
2772
+ fire(h, 'pointerdown', 6, 700, 300, 'touch');
2773
+ await dom.grant();
2774
+ assert.equal(dom.doc.exits, 1, `${what}: the late grant is let go of`);
2775
+ assert.equal(h.canvas.holding.size, 0);
2776
+ if (lift === 'before') {
2777
+ liftOutside(h, dom, 7, -10, 330);
2778
+ liftOutside(h, dom, 6, 700, 300);
2779
+ dom.flush();
2780
+ } else {
2781
+ dom.flush();
2782
+ assert.deepEqual([...h.canvas.holding].sort(), [6, 7], `${what}: the captures are given back at the event`);
2783
+ liftOutside(h, dom, 7, -10, 330);
2784
+ liftOutside(h, dom, 6, 700, 300);
2785
+ }
2786
+ assert.equal(h.stick().active, false, `${what}: the stick stops`);
2787
+ assert.equal(h.jumped(), true, `${what}: the tap jumps`);
2788
+ assert.equal(dom.locked(), false);
2789
+ assert.deepEqual(dom.watched(), [], `${what}: nothing is left listening`);
2790
+ // The next finger takes the stick.
2791
+ fire(h, 'pointerdown', 8, 300, 400, 'touch');
2792
+ fire(h, 'pointermove', 8, 300, 340, 'touch');
2793
+ assert.equal(h.stick().active, true, `${what}: the next finger walks`);
2794
+ checks += 1;
2795
+ }
2796
+ }
2797
+ // Under the key, Chromium's timing: a touch stick lifted beyond the
2798
+ // canvas between the exit call and its event.
2799
+ {
2800
+ const h = makeRuntime('orbit');
2801
+ const dom = makeLockDom('promise', h.canvas, 'chromium');
2802
+ h.run(10);
2803
+ fire(h, 'pointerdown', 7, 300, 400, 'touch');
2804
+ fire(h, 'pointermove', 7, 300, 330, 'touch');
2805
+ fire(h, 'pointerdown', 1, 800, 300, 'mouse', 2, 2);
2806
+ await dom.grant();
2807
+ fire(h, 'pointerup', 1, 800, 300, 'mouse', 2);
2808
+ assert.equal(dom.locked(), false, 'chromium: cleared inside the call');
2809
+ liftOutside(h, dom, 7, -10, 330);
2810
+ dom.flush();
2811
+ assert.equal(h.stick().active, false, 'chromium, under the key: the stick stops');
2812
+ assert.equal(h.runtime.orbitInput().busy, false);
2813
+ assert.deepEqual(dom.watched(), []);
2814
+ checks += 1;
2815
+ }
2816
+ }
2817
+ // Keyless, through Scene3DPlayer's attachInput on a canvas that can lock:
2818
+ // mouse drags and clicks of every button are the stick and jumps they
2819
+ // were, frame for frame, with no lock asked for and nothing added to the
2820
+ // document or the window.
2821
+ for (const mode of ['off', 'rigid']) {
2822
+ const now = makeRuntime(mode, Player);
2823
+ const before = makeRuntime(mode, PlayerBefore);
2824
+ const dom = makeLockDom('promise');
2825
+ Object.assign(now.canvas, { ownerDocument: dom.doc, requestPointerLock: dom.canvas.requestPointerLock });
2826
+ const mouse = (h, type, id, x, y, button) => h.canvas.fire(type, { pointerId: id, clientX: x, clientY: y, pointerType: 'mouse', button, buttons: type === 'pointerup' ? 0 : 1 << button, movementX: 30, movementY: 30 });
2827
+ for (let i = 0; i < 300; i += 1) {
2828
+ const phase = i % 50;
2829
+ const button = [0, 2, 1][Math.floor(i / 50) % 3];
2830
+ for (const h of [now, before]) {
2831
+ if (phase === 0) mouse(h, 'pointerdown', 1, 700, 300, button);
2832
+ if (phase > 0 && phase < 20) mouse(h, 'pointermove', 1, 700 + phase * 5, 300 - phase * 3, -1);
2833
+ if (phase === 20) mouse(h, 'pointerup', 1, 800, 240, button);
2834
+ if (phase === 30) mouse(h, 'pointerdown', 1, 600, 300, button);
2835
+ if (phase === 32) mouse(h, 'pointerup', 1, 601, 300, button);
2836
+ h.frame(FIXED);
2837
+ }
2838
+ }
2839
+ sameFrames(now.frames, before.frames, `${mode}: mouse drags on a canvas that can lock, as before the key`);
2840
+ assert.ok(now.frames.some((f) => f.stick.active) && now.frames.some((f) => f.calls.includes('setVelocity')), 'and the mouse walked and jumped');
2841
+ assert.equal(dom.canvas.requests, 0, `${mode}: no lock is asked for`);
2842
+ assert.deepEqual(dom.watched(), [], `${mode}: nothing listens on the document or window`);
2843
+ assert.deepEqual(now.canvas.types(), ['pointercancel', 'pointerdown', 'pointermove', 'pointerup']);
2844
+ assert.equal(now.runtime.lookInput, undefined);
2845
+ checks += 1;
2846
+ }
2847
+ return checks;
2848
+ }
2849
+
1811
2850
  // attachInput before the key and now, keyless and with `"follow": "rigid"`
1812
2851
  // alone: the same pointer and key events, one by one, leave the same stick,
1813
2852
  // the same jumps, the same keys, and the same listeners on the canvas and
@@ -1994,7 +3033,7 @@ function blendHeld() {
1994
3033
  world.frame();
1995
3034
  const from = { ...world.lastCast.from };
1996
3035
  const dir = { ...world.lastCast.dir };
1997
- world.wall = 4;
3036
+ world.wall = 3;
1998
3037
  world.camera.position.set(from.x + dir.x * 8, from.y + dir.y * 8, from.z + dir.z * 8);
1999
3038
  const out = () => {
2000
3039
  const c = world.camera.position;
@@ -2005,22 +3044,501 @@ function blendHeld() {
2005
3044
  for (let i = 0; i < 60; i += 1) {
2006
3045
  world.frame(UNEVEN(i));
2007
3046
  const now = out();
2008
- assert.ok(now <= 3.75 + 1e-9, `frame ${i}: drawn no farther than the wall allows (${now})`);
3047
+ assert.ok(now <= 2.75 + 1e-9, `frame ${i}: drawn no farther than the wall allows (${now})`);
2009
3048
  assert.ok(now <= last + 1e-9, `frame ${i}: and only nearer (${now} after ${last})`);
2010
3049
  last = now;
2011
3050
  }
2012
- assert.ok(Math.abs(out() - 3.75) < 1e-3, 'settled in front of the wall');
3051
+ assert.ok(Math.abs(out() - 2.75) < 1e-3, 'settled in front of the wall');
2013
3052
  // A blend from beside the wall's ray, not along it, is held too.
2014
3053
  world.camera.position.set(from.x + 6, from.y + 3, from.z - 5);
2015
3054
  for (let i = 0; i < 30; i += 1) {
2016
3055
  world.frame();
2017
- assert.ok(out() <= 3.75 + 1e-9, `beside: frame ${i} (${out()})`);
3056
+ assert.ok(out() <= 2.75 + 1e-9, `beside: frame ${i} (${out()})`);
3057
+ }
3058
+ checks += 1;
3059
+ return checks;
3060
+ }
3061
+
3062
+ // A stand-in for an actor's three node: a real Group whose `visible` is an
3063
+ // accessor on its class, so every write to it is counted, the ones made
3064
+ // after ownmodel.js has put the node back included.
3065
+ class CountedGroup extends THREE.Group {
3066
+ constructor() {
3067
+ super();
3068
+ this.writes = 0;
3069
+ }
3070
+ get visible() {
3071
+ return this.shown;
2018
3072
  }
3073
+ set visible(value) {
3074
+ this.writes = (this.writes ?? 0) + 1;
3075
+ this.shown = value;
3076
+ }
3077
+ }
3078
+ function countedNode(x = 0, y = 1, z = 0) {
3079
+ const node = new CountedGroup();
3080
+ node.position.set(x, y, z);
3081
+ return node;
3082
+ }
3083
+
3084
+ // What the play loop draws with (Scene3DPlayer's `startLoop`), its own
3085
+ // line; `render` stands in for world3d.js `renderWorld`, recording what
3086
+ // each draw saw.
3087
+ const DRAW_LINE = 'if (runtime.orbitOwnModel !== undefined) renderHidingOwnModel(world, runtime, renderWorld);\n else renderWorld(world, runtime);';
3088
+ assert.ok(readFileSync(new URL('../engine3d/Scene3DPlayer.jsx', import.meta.url), 'utf8').includes(DRAW_LINE), 'the play loop draws as drawFrame does');
3089
+ function drawFrame(world, runtime, render) {
3090
+ if (runtime.orbitOwnModel !== undefined) renderHidingOwnModel(world, runtime, render);
3091
+ else render(world, runtime);
3092
+ }
3093
+ function makeDraws(nodeOf) {
3094
+ const seen = [];
3095
+ const render = (world, runtime) => seen.push({ world, runtime, visible: nodeOf()?.visible });
3096
+ return { seen, render };
3097
+ }
3098
+
3099
+ // The camera inside or against the player's own model leaves it out of
3100
+ // that one draw and nothing else: within the threshold hidden, beyond it
3101
+ // shown, with a margin between; a node something else hid is not touched;
3102
+ // a node replaced is judged afresh; a throw still gives it back.
3103
+ function ownModel() {
3104
+ let checks = 0;
3105
+ const camera = new THREE.PerspectiveCamera(50, 1.6, 0.1, 1000);
3106
+ let node = countedNode();
3107
+ const scene = new THREE.Scene();
3108
+ scene.add(node);
3109
+ const world = { camera, scene, nodes: new Map([['player', { node }]]) };
3110
+ const runtime = {};
3111
+ const { seen, render } = makeDraws(() => node);
3112
+ const draw = (x, y, z) => {
3113
+ camera.position.set(x, y, z);
3114
+ runtime.orbitOwnModel = 'player';
3115
+ drawFrame(world, runtime, render);
3116
+ assert.equal(runtime.orbitOwnModel, undefined, 'the draw takes the name');
3117
+ assert.equal(node.visible, true, 'and every draw ends with the node shown');
3118
+ return seen.at(-1).visible;
3119
+ };
3120
+ // Over the head, as the orbit camera sits: 0.8 m up is the look point.
3121
+ assert.equal(draw(0, 1.8 + 0.6, 0), false, 'at the 0.6 m floor: hidden');
3122
+ assert.equal(node.writes, 2, 'hidden for the draw (one write) and given back (one)');
3123
+ assert.equal(draw(0, 1.8 + HIDE_WITHIN + 0.1, 0), false, 'between the lines it stays hidden');
3124
+ assert.equal(draw(0, 1.8 + SHOW_PAST + 0.01, 0), true, 'past SHOW_PAST: shown');
3125
+ assert.equal(draw(0, 1.8 + HIDE_WITHIN + 0.1, 0), true, 'between the lines from outside: shown');
3126
+ assert.equal(draw(HIDE_WITHIN - 0.05, 1.3, 0), false, 'level with the chest, within: hidden');
3127
+ assert.equal(draw(9, 8, 0), true, 'at rest far out: shown');
3128
+ const writes = node.writes;
3129
+ draw(30, 30, 30);
3130
+ assert.equal(node.writes, writes, 'a draw that shows it writes nothing');
3131
+ checks += 1;
3132
+ // A deck's own hide is kept, and never set back to true.
3133
+ node.visible = false;
3134
+ const before = node.writes;
3135
+ camera.position.set(0, 2.3, 0);
3136
+ runtime.orbitOwnModel = 'player';
3137
+ drawFrame(world, runtime, render);
3138
+ assert.equal(seen.at(-1).visible, false, 'drawn hidden, as the deck has it');
3139
+ assert.equal(node.visible, false, "the deck's hide is still there after the draw");
3140
+ assert.equal(node.writes, before, 'and the node was not written');
3141
+ node.visible = true;
3142
+ checks += 1;
3143
+ // The node replaced between frames (a new look): the old one is never
3144
+ // touched again, the new one is judged without the old one's margin.
3145
+ draw(0, 2.4, 0);
3146
+ const old = node;
3147
+ const oldWrites = old.writes;
3148
+ node = countedNode();
3149
+ scene.add(node);
3150
+ world.nodes.set('player', { node });
3151
+ assert.equal(draw(0, 1.8 + HIDE_WITHIN + 0.1, 0), true, 'a new node between the lines is shown');
3152
+ assert.equal(draw(0, 2.4, 0), false, 'and hidden within');
3153
+ assert.equal(old.writes, oldWrites, 'the old node is left as it was');
3154
+ checks += 1;
3155
+ // No node, an instanced rig, another actor's name, no name: drawn whole.
3156
+ for (const [what, entry, name] of [
3157
+ ['no node', null, 'player'],
3158
+ ['an instanced rig', { node, instancedRig: new THREE.Group() }, 'player'],
3159
+ ['another actor', { node }, 'other'],
3160
+ ]) {
3161
+ if (entry) world.nodes.set('player', entry);
3162
+ else world.nodes.delete('player');
3163
+ camera.position.set(0, 2.4, 0);
3164
+ runtime.orbitOwnModel = name;
3165
+ const writes = node.writes;
3166
+ drawFrame(world, runtime, render);
3167
+ assert.equal(node.writes, writes, `${what}: nothing hidden`);
3168
+ }
3169
+ world.nodes.set('player', { node });
3170
+ const count = seen.length;
3171
+ const plain = [];
3172
+ drawFrame(world, runtime, (w, r) => plain.push([w, r, node.visible]));
3173
+ assert.deepEqual(plain, [[world, runtime, true]], 'no name: the render, once, with the same arguments');
3174
+ assert.equal(seen.length, count);
2019
3175
  checks += 1;
3176
+ // A render that throws still gives the node back.
3177
+ camera.position.set(0, 2.4, 0);
3178
+ runtime.orbitOwnModel = 'player';
3179
+ assert.throws(() =>
3180
+ drawFrame(world, runtime, () => {
3181
+ assert.equal(node.visible, false);
3182
+ throw new Error('render failed');
3183
+ })
3184
+ );
3185
+ assert.equal(node.visible, true, 'shown after a throw');
3186
+ checks += 1;
3187
+ // Extras follow the same one-render contract, even if detached or removed
3188
+ // from the registration set by the render. Other hides are never undone.
3189
+ {
3190
+ const extra = countedNode();
3191
+ const alreadyHidden = countedNode();
3192
+ const detached = countedNode();
3193
+ const readOnly = new THREE.Group();
3194
+ Object.defineProperty(readOnly, 'visible', { value: true, writable: false });
3195
+ alreadyHidden.visible = false;
3196
+ const hiddenWrites = alreadyHidden.writes;
3197
+ scene.add(extra, alreadyHidden, readOnly);
3198
+ world.ownModelWith = new Set([extra, alreadyHidden, detached, readOnly, node]);
3199
+ const drawExtras = (during) => {
3200
+ camera.position.set(0, 2.4, 0);
3201
+ drawFrame(world, { orbitOwnModel: 'player' }, () => {
3202
+ assert.equal(node.visible, false, 'the own model is hidden');
3203
+ assert.equal(extra.visible, false, 'the registered extra is hidden with it');
3204
+ assert.equal(alreadyHidden.visible, false, 'a preexisting hide stays hidden');
3205
+ assert.equal(detached.visible, true, 'an extra outside the scene stays shown');
3206
+ assert.equal(readOnly.visible, true, 'a read-only extra stays shown');
3207
+ during();
3208
+ });
3209
+ };
3210
+ drawExtras(() => {});
3211
+ assert.equal(extra.visible, true, 'extra restored after a normal render');
3212
+ assert.equal(extra.writes, 2, 'only the hide and restore were written');
3213
+ assert.equal(alreadyHidden.writes, hiddenWrites, 'a preexisting hide was never written');
3214
+ assert.equal(detached.writes, 0, 'a detached extra was never written');
3215
+ const failure = new Error('extra render failed');
3216
+ assert.throws(() => drawExtras(() => {
3217
+ scene.remove(extra, node);
3218
+ world.ownModelWith.delete(extra);
3219
+ throw failure;
3220
+ }), (error) => error === failure);
3221
+ assert.equal(extra.visible, true, 'extra restored after detach, unregister and throw');
3222
+ assert.equal(node.visible, true, 'model restored after detach and throw');
3223
+ scene.add(node, extra);
3224
+ world.ownModelWith.add(extra);
3225
+ const before = extra.writes;
3226
+ drawExtras(() => { extra.visible = true; });
3227
+ assert.equal(extra.writes, before + 2, 'a true written during render is kept without another write');
3228
+ delete world.ownModelWith;
3229
+ checks += 1;
3230
+ }
3231
+ // Throwing restore setters cannot strand later extras or replace the first error.
3232
+ {
3233
+ for (const target of ['model', 'extra']) {
3234
+ const model = countedNode();
3235
+ const extra = new THREE.Group();
3236
+ const later = new THREE.Group();
3237
+ const tag = new THREE.Sprite();
3238
+ const scene = new THREE.Scene();
3239
+ scene.add(model, extra, later, tag);
3240
+ const world = {
3241
+ camera, scene, nodes: new Map([['player', { node: model }]]),
3242
+ ownModelWith: new Set([extra, later, tag]),
3243
+ };
3244
+ const objects = [['model', model], ['extra', extra], ['later', later], ['tag', tag]];
3245
+ const restored = [];
3246
+ const firstError = new Error(`${target} restore failed`);
3247
+ const laterError = new Error('later restore failed');
3248
+ camera.position.set(0, 2.4, 0);
3249
+ assert.throws(() => renderHidingOwnModel(world, { orbitOwnModel: 'player' }, () => {
3250
+ for (const [name, object] of objects) {
3251
+ assert.equal(object.visible, false, `${target}: ${name} hidden during render`);
3252
+ let visible = object.visible;
3253
+ Object.defineProperty(object, 'visible', {
3254
+ configurable: true,
3255
+ get: () => visible,
3256
+ set(value) {
3257
+ visible = value;
3258
+ if (value !== true) return;
3259
+ restored.push(name);
3260
+ if (name === target) throw firstError;
3261
+ if (name === 'later') throw laterError;
3262
+ },
3263
+ });
3264
+ }
3265
+ }), (error) => error === firstError, `${target}: the first restore error propagates`);
3266
+ assert.deepEqual(restored, ['model', 'extra', 'later', 'tag'], `${target}: model restored first, then every extra`);
3267
+ for (const [name, object] of objects) {
3268
+ assert.equal(object.visible, true, `${target}: ${name} restored despite throwing setters`);
3269
+ }
3270
+ renderHidingOwnModel(world, {}, () => {
3271
+ for (const [name, object] of objects) {
3272
+ assert.equal(object.visible, true, `${target}: ${name} visible in a later keyless frame`);
3273
+ }
3274
+ });
3275
+ }
3276
+ checks += 1;
3277
+ }
3278
+ // Keyless draws and keyed draws that show the model never read the set.
3279
+ {
3280
+ Object.defineProperty(world, 'ownModelWith', {
3281
+ configurable: true,
3282
+ get() { throw new Error('ownModelWith must not be read'); },
3283
+ });
3284
+ let renders = 0;
3285
+ drawFrame(world, {}, () => { renders += 1; });
3286
+ camera.position.set(30, 30, 30);
3287
+ drawFrame(world, { orbitOwnModel: 'player' }, () => { renders += 1; });
3288
+ camera.position.set(0, 2.4, 0);
3289
+ node.visible = false;
3290
+ drawFrame(world, { orbitOwnModel: 'player' }, () => { renders += 1; });
3291
+ assert.equal(node.visible, false, 'the model hidden elsewhere remains hidden');
3292
+ node.visible = true;
3293
+ assert.equal(renders, 3, 'all draws render without reading the set');
3294
+ delete world.ownModelWith;
3295
+ checks += 1;
3296
+ }
3297
+ // What is written to `visible` during the render: a `true` is kept; a
3298
+ // pass that saves it and puts it back leaves the node shown (the value it
3299
+ // saved was this file's false); a `false` cannot be told from this file's
3300
+ // and is shown again (the accepted trade-off), a throw or not; reads
3301
+ // during it are false; a plain Group's own data property is as it was.
3302
+ {
3303
+ const plain = new THREE.Group();
3304
+ plain.position.set(0, 1, 0);
3305
+ const plainScene = new THREE.Scene();
3306
+ plainScene.add(plain);
3307
+ const w = { camera, scene: plainScene, nodes: new Map([['player', { node: plain }]]) };
3308
+ const own = () => Object.getOwnPropertyDescriptor(plain, 'visible');
3309
+ const want = own();
3310
+ const drawWith = (during) => {
3311
+ camera.position.set(0, 2.4, 0);
3312
+ const r = { orbitOwnModel: 'player' };
3313
+ drawFrame(w, r, () => during(plain));
3314
+ };
3315
+ drawWith((n) => assert.equal(n.visible, false, 'read as false during the render'));
3316
+ assert.deepEqual(own(), want, 'the own data property as it was');
3317
+ drawWith((n) => {
3318
+ const saved = n.visible;
3319
+ n.visible = false;
3320
+ n.visible = saved;
3321
+ });
3322
+ assert.deepEqual(own(), want, 'a pass that saves and restores visible: shown after it');
3323
+ // And a later keyless scene reusing the node draws it shown.
3324
+ let keyless;
3325
+ drawFrame(w, {}, () => (keyless = plain.visible));
3326
+ assert.equal(keyless, true, 'a keyless frame after it draws the node shown');
3327
+ drawWith((n) => (n.visible = true));
3328
+ assert.equal(plain.visible, true, 'a true written during the render is kept');
3329
+ drawWith((n) => (n.visible = false));
3330
+ assert.equal(plain.visible, true, 'a false written during the render: shown again (accepted)');
3331
+ assert.throws(() =>
3332
+ drawWith(() => {
3333
+ throw new Error('callback threw');
3334
+ })
3335
+ );
3336
+ assert.deepEqual(own(), want, 'shown after a throw');
3337
+ // Accepted: a copy of the node taken during the hidden render (clone,
3338
+ // a parent's clone, toJSON) copies it hidden, as for any node hidden
3339
+ // for a frame; the node itself is shown after the render.
3340
+ const parent = new THREE.Group();
3341
+ plainScene.add(parent);
3342
+ parent.add(plain);
3343
+ const got = {};
3344
+ drawWith((n) => {
3345
+ got.clone = n.clone();
3346
+ got.parentClone = parent.clone();
3347
+ got.json = n.toJSON();
3348
+ });
3349
+ assert.equal(got.clone.visible, false, 'a clone made during the hidden render copies visible: false');
3350
+ assert.equal(got.parentClone.children[0].visible, false, "and one made by a parent's clone");
3351
+ assert.equal(got.json.object.visible, false, 'toJSON during it writes visible: false');
3352
+ assert.deepEqual(own(), want, 'the node itself shown after the render');
3353
+ assert.ok(!Object.hasOwn(plain, 'clone') && !Object.hasOwn(plain, 'toJSON'), 'nothing put on the node');
3354
+ plainScene.add(plain);
3355
+ checks += 1;
3356
+ // A node that cannot be extended (preventExtensions) is hidden for the
3357
+ // render and shown after it, the render run, nothing thrown.
3358
+ {
3359
+ const sealed = new THREE.Group();
3360
+ sealed.position.set(0, 1, 0);
3361
+ const s2 = new THREE.Scene();
3362
+ s2.add(sealed);
3363
+ Object.preventExtensions(sealed);
3364
+ const w2 = { camera, scene: s2, nodes: new Map([['player', { node: sealed }]]) };
3365
+ camera.position.set(0, 2.4, 0);
3366
+ let ran;
3367
+ drawFrame(w2, { orbitOwnModel: 'player' }, () => (ran = sealed.visible));
3368
+ assert.equal(ran, false, 'a non-extensible node: the render ran with it hidden');
3369
+ assert.equal(sealed.visible, true, 'and it is shown after');
3370
+ // A render that throws on it still gives it back.
3371
+ assert.throws(() =>
3372
+ drawFrame(w2, { orbitOwnModel: 'player' }, () => {
3373
+ throw new Error('render failed');
3374
+ })
3375
+ );
3376
+ assert.equal(sealed.visible, true, 'shown after a throwing render');
3377
+ checks += 1;
3378
+ }
3379
+ // A `visible` that cannot be written is left alone.
3380
+ Object.defineProperty(plain, 'visible', { value: true, writable: false, enumerable: true, configurable: true });
3381
+ let saw;
3382
+ drawWith((n) => (saw = n.visible));
3383
+ assert.equal(saw, true, 'a read-only visible: drawn as is');
3384
+ checks += 1;
3385
+ }
3386
+ // Measured in the world: a node a deck keeps under a group of its own.
3387
+ {
3388
+ const root = new THREE.Scene();
3389
+ const group = new THREE.Group();
3390
+ const n = countedNode(0, 1, 0);
3391
+ root.add(group);
3392
+ group.add(n);
3393
+ root.add(camera);
3394
+ const w = { camera, scene: root, nodes: new Map([['player', { node: n }]]) };
3395
+ const drawAt = (gx, cx) => {
3396
+ group.position.set(gx, 0, 0);
3397
+ camera.position.set(cx, 2.4, 0);
3398
+ let saw;
3399
+ drawFrame(w, { orbitOwnModel: 'player' }, () => (saw = n.visible));
3400
+ return saw;
3401
+ };
3402
+ root.updateMatrixWorld();
3403
+ const before = n.matrixWorld.clone();
3404
+ const camBefore = camera.matrixWorld.clone();
3405
+ assert.equal(drawAt(5, 5), false, 'near in the world, 5 m off locally: hidden');
3406
+ assert.ok(before.equals(n.matrixWorld) && camBefore.equals(camera.matrixWorld), 'measuring writes no matrix');
3407
+ assert.equal(drawAt(5, 0), true, 'near locally, 5 m off in the world: shown');
3408
+ assert.equal(drawAt(-3, -3), false, 'the group moved since the last render: still measured where it is');
3409
+ // The scene not updating its matrices (matrixWorldAutoUpdate off): the
3410
+ // render draws the cached ones, and the choice is made on those, which
3411
+ // are not brought up to date.
3412
+ root.matrixWorldAutoUpdate = false;
3413
+ const cache = (gx, cx) => {
3414
+ group.position.set(gx, 0, 0);
3415
+ camera.position.set(cx, 2.4, 0);
3416
+ root.updateMatrixWorld(true);
3417
+ return [n.matrixWorld.clone(), camera.matrixWorld.clone()];
3418
+ };
3419
+ const [cachedNode, cachedCam] = cache(20, 20);
3420
+ assert.equal(drawAt(0, 50), false, 'drawn next to it (cached), 50 m off locally: hidden');
3421
+ assert.ok(n.matrixWorld.equals(cachedNode) && camera.matrixWorld.equals(cachedCam), 'the cached matrices are not updated');
3422
+ cache(20, 0);
3423
+ assert.equal(drawAt(0, 0), true, 'drawn 20 m off (cached), next to it locally: shown');
3424
+ // A camera with no parent is brought up to date by the renderer itself
3425
+ // (its own matrixWorldAutoUpdate), whatever the scene's.
3426
+ root.remove(camera);
3427
+ cache(0, 50);
3428
+ camera.updateMatrixWorld();
3429
+ assert.equal(drawAt(0, 0), false, 'a parentless camera moved next to it: measured where it is now');
3430
+ root.add(camera);
3431
+ root.matrixWorldAutoUpdate = true;
3432
+ checks += 1;
3433
+ root.remove(camera);
3434
+ checks += 1;
3435
+ }
3436
+ // The rendered scene under a parent of its own whose
3437
+ // matrixWorldAutoUpdate is off, the scene's own on: the renderer updates
3438
+ // from the scene (the parent's cached matrixWorld included), so that is
3439
+ // where the node is measured.
3440
+ {
3441
+ const outer = new THREE.Group();
3442
+ outer.matrixWorldAutoUpdate = false;
3443
+ const sc = new THREE.Scene();
3444
+ outer.add(sc);
3445
+ const n = countedNode(0, 1, 0);
3446
+ sc.add(n);
3447
+ outer.updateMatrixWorld(true);
3448
+ const w = { camera, scene: sc, nodes: new Map([['player', { node: n }]]) };
3449
+ camera.position.set(0, 2.4, 0);
3450
+ const drawn = () => {
3451
+ let saw;
3452
+ drawFrame(w, { orbitOwnModel: 'player' }, () => (saw = n.visible));
3453
+ return saw;
3454
+ };
3455
+ sc.position.set(10, 0, 0);
3456
+ assert.equal(drawn(), true, 'the scene moved to x=10 (the node cached at the origin): shown');
3457
+ sc.updateMatrixWorld();
3458
+ assert.ok(Math.abs(n.matrixWorld.elements[12] - 10) < 1e-9, 'the renderer does draw it at x=10');
3459
+ outer.matrixWorld.makeTranslation(-10, 0, 0);
3460
+ assert.equal(drawn(), false, "the scene's parent's cached matrix brings it back to the origin: hidden");
3461
+ sc.updateMatrixWorld();
3462
+ assert.ok(Math.abs(n.matrixWorld.elements[12]) < 1e-9, 'where the renderer draws it');
3463
+ // A node not in the rendered scene is not drawn, so not hidden.
3464
+ const elsewhere = countedNode(0, 1, 0);
3465
+ new THREE.Scene().add(elsewhere);
3466
+ const w2 = { camera, scene: sc, nodes: new Map([['player', { node: elsewhere }]]) };
3467
+ camera.position.set(0, 2.4, 0);
3468
+ let saw;
3469
+ drawFrame(w2, { orbitOwnModel: 'player' }, () => (saw = elsewhere.visible));
3470
+ assert.equal(saw, true, 'a node outside the rendered scene: not hidden');
3471
+ assert.equal(elsewhere.writes, 0, 'and not written');
3472
+ checks += 1;
3473
+ }
3474
+ // Through the runtime: the keyed Player names its actor each frame it
3475
+ // places the camera; a frame it does not (turned off, removed) names
3476
+ // none; a load drops a name not yet drawn. Keyless runtimes never name.
3477
+ const hidden = (mode) => {
3478
+ const h = makeRuntime(mode);
3479
+ const n = countedNode();
3480
+ const scene = new THREE.Scene();
3481
+ scene.add(n);
3482
+ const w = { camera: h.camera, scene, nodes: new Map([['player', { node: n }]]) };
3483
+ // A shell `h.wall` round the look point, as makeWorld's.
3484
+ h.runtime.physics3d.castRayFixedNormal = () => (h.wall ? { distance: h.wall, actorId: 'wall' } : null);
3485
+ h.runtime.physics3d.castBallFixed = (from, dir, max, radius) => (h.wall && h.wall - radius <= max ? { distance: Math.max(0, h.wall - radius), actorId: 'wall' } : null);
3486
+ h.runtime.physics3d.nearFixed = () => [];
3487
+ const d = makeDraws(() => n);
3488
+ h.draw = () => {
3489
+ const t = h.player()?.components.Transform;
3490
+ if (t) n.position.set(t.x, t.y, t.z);
3491
+ drawFrame(w, h.runtime, d.render);
3492
+ return d.seen.at(-1).visible;
3493
+ };
3494
+ h.step = () => {
3495
+ h.frame();
3496
+ return h.draw();
3497
+ };
3498
+ return { h, n };
3499
+ };
3500
+ {
3501
+ const { h, n } = hidden('orbit');
3502
+ for (let i = 0; i < 30; i += 1) assert.equal(h.step(), true, 'far out: shown');
3503
+ h.wall = 1.2;
3504
+ assert.equal(h.step(), false, 'a wall close behind (the camera at 0.95 m): hidden');
3505
+ assert.equal(n.visible, true);
3506
+ h.frame();
3507
+ assert.equal(h.runtime.orbitOwnModel, 'player', 'named by the placement');
3508
+ h.load('orbit');
3509
+ assert.equal(h.runtime.orbitOwnModel, undefined, 'a load drops the name');
3510
+ assert.equal(h.draw(), true, 'and that frame is drawn whole');
3511
+ assert.equal(h.step(), false, 'the next keyed frame names it again');
3512
+ h.player().components.Player.$enabled = false;
3513
+ assert.equal(h.step(), true, 'a Player turned off hides nothing');
3514
+ h.player().components.Player.$enabled = true;
3515
+ assert.equal(h.step(), false);
3516
+ delete h.player().components.Player;
3517
+ assert.equal(h.step(), true, 'a Player removed hides nothing');
3518
+ assert.equal(h.runtime.orbitOwnModel, undefined);
3519
+ h.load('off');
3520
+ h.wall = 0.5;
3521
+ h.camera.position.set(0, 1.5, 0);
3522
+ for (let i = 0; i < 10; i += 1) assert.equal(h.step(), true, 'a keyless scene after it: drawn whole');
3523
+ checks += 1;
3524
+ }
3525
+ for (const mode of ['off', 'rigid']) {
3526
+ const { h, n } = hidden(mode);
3527
+ const step = keylessInput(h);
3528
+ for (let i = 0; i < 240; i += 1) {
3529
+ h.frame(UNEVEN(i), [...step(i), ...(i % 90 < 40 ? ['KeyW'] : [])]);
3530
+ assert.equal(h.runtime.orbitOwnModel, undefined, `${mode}: never named`);
3531
+ h.draw();
3532
+ }
3533
+ assert.ok(!('orbitOwnModel' in h.runtime), `${mode}: the field is never written`);
3534
+ assert.equal(n.writes, 0, `${mode}: the node is never written`);
3535
+ checks += 1;
3536
+ }
2020
3537
  return checks;
2021
3538
  }
2022
3539
 
2023
- // `castRayFixed` on rapier itself: fixed bodies' solid colliders only.
3540
+ // `castRayFixed` on rapier itself: fixed bodies' solid colliders only, and
3541
+ // the orbit camera's own queries beside it.
2024
3542
  async function fixedRay() {
2025
3543
  if (!realRapier) return 0;
2026
3544
  const { Physics3DSystem } = await import('../systems/physics3d.js?orbit-real');
@@ -2064,18 +3582,945 @@ async function fixedRay() {
2064
3582
  // The ground is fixed and solid.
2065
3583
  const down = scene.physics3d.castRayFixed(from, { x: 0, y: -1, z: 0 }, 20);
2066
3584
  assert.ok(down && down.actorId === null && Math.abs(down.distance - 5) < 1e-3, 'the ground blocks');
3585
+ // Its result is what it always was, `{ distance, actorId }` and nothing
3586
+ // else (review 6: the orbit camera's normal is `castRayFixedNormal`'s).
3587
+ assert.deepEqual(Object.keys(hit), ['distance', 'actorId'], 'castRayFixed: distance and actorId only');
3588
+ assert.deepEqual(hit, { distance: hit.distance, actorId: 'wall' });
3589
+ assert.deepEqual(Object.keys(down), ['distance', 'actorId']);
2067
3590
  // From inside a wall: at once.
2068
3591
  assert.equal(scene.physics3d.castRayFixed({ x: 8, y: 5, z: 0 }, dir, 20).distance, 0);
3592
+ // `castRayFixedNormal`: the same hits, with the surface's normal facing
3593
+ // back along the ray.
3594
+ const hitN = scene.physics3d.castRayFixedNormal(from, dir, 20);
3595
+ assert.ok(hitN.actorId === 'wall' && hitN.distance === hit.distance, 'the same hit');
3596
+ const n = hitN.normal;
3597
+ assert.ok(Math.abs(n.x + 1) < 1e-6 && Math.abs(n.y) < 1e-6 && Math.abs(n.z) < 1e-6, `the wall faces the ray (${JSON.stringify(n)})`);
3598
+ assert.deepEqual(scene.physics3d.castRayFixedNormal(from, { x: 0, y: -1, z: 0 }, 20).normal, { x: 0, y: 1, z: 0 }, 'the ground faces up');
3599
+ assert.equal(scene.physics3d.castRayFixedNormal(from, dir, 7), null, 'nothing within reach');
3600
+ // The ball: the same filter, stopped its radius short of the wall's face
3601
+ // (to within 0.1 mm, rapier's own answer taken on to the face), and the
3602
+ // ground under it at a slant.
3603
+ const ball = scene.physics3d.castBallFixed(from, dir, 20, 0.5);
3604
+ assert.equal(ball.actorId, 'wall', 'castBallFixed passes the sensor, the dynamic and the kinematic body');
3605
+ assert.ok(Math.abs(ball.distance - 7) < 1e-4, `the ball's middle its radius off the face (${ball.distance})`);
3606
+ assert.ok(Math.abs(ball.normal.x + 1) < 1e-6, 'the face faces the ball');
3607
+ assert.equal(scene.physics3d.castBallFixed(from, dir, 6.9, 0.5), null, 'nothing within reach');
3608
+ assert.equal(scene.physics3d.castBallFixed(from, { x: -1, y: 0, z: 0 }, 20, 0.5), null, 'nothing that way');
3609
+ for (const pitch of [-80, -45, -20, -5]) {
3610
+ const slant = { x: 0, y: Math.sin(pitch * DEG), z: Math.cos(pitch * DEG) };
3611
+ const down = scene.physics3d.castBallFixed({ x: -5, y: 1.2, z: 0 }, slant, 40, 0.484);
3612
+ const y = 1.2 + slant.y * down.distance;
3613
+ assert.ok(down.actorId === null && Math.abs(y - 0.484) < 1e-4, `the ground at ${pitch} degrees: the ball's middle ${y} m up`);
3614
+ }
3615
+ assert.equal(scene.physics3d.castBallFixed(from, dir, 20, 0), null, 'no ball without a radius');
3616
+ // The fixed solids near a point: within reach or not, the dynamic body
3617
+ // passed, a point inside one, and an edge.
3618
+ const [nearWall, ...more] = scene.physics3d.nearFixed({ x: 7, y: 5, z: 0 }, 1);
3619
+ assert.equal(more.length, 0);
3620
+ assert.ok(nearWall.actorId === 'wall' && Math.abs(nearWall.distance - 0.5) < 1e-6 && Math.abs(nearWall.normal.x + 1) < 1e-6 && Math.abs(nearWall.point.x - 7.5) < 1e-6, `0.5 m off the wall's face (${JSON.stringify(nearWall)})`);
3621
+ assert.deepEqual(scene.physics3d.nearFixed({ x: 7, y: 5, z: 0 }, 0.4), [], 'nothing within 0.4 m');
3622
+ assert.deepEqual(scene.physics3d.nearFixed({ x: 4, y: 5, z: 0 }, 0.4), [], 'the dynamic body is passed');
3623
+ const inside = scene.physics3d.nearFixed({ x: 8, y: 5, z: 0 }, 1).find((f) => f.actorId === 'wall');
3624
+ assert.ok(inside.inside && inside.distance === 0 && inside.normal === null, 'inside the wall');
3625
+ // Below the wall's bottom edge: its nearest point is on the edge, and the
3626
+ // normal points from there to the point.
3627
+ const [edge] = scene.physics3d.nearFixed({ x: 7, y: 2.8, z: 0 }, 0.6);
3628
+ const r = Math.hypot(0.5, 0.2);
3629
+ assert.ok(edge.actorId === 'wall' && Math.abs(edge.distance - r) < 1e-5 && Math.abs(edge.normal.x + 0.5 / r) < 1e-5 && Math.abs(edge.normal.y + 0.2 / r) < 1e-5, `the wall's edge (${JSON.stringify(edge)})`);
3630
+ // The orbit camera on rapier's own ground.
3631
+ grounded(scene.physics3d);
2069
3632
  system.dispose(scene);
2070
3633
  assert.equal(scene.physics3d.castRayFixed(from, dir, 20), null, 'null after the world is gone');
3634
+ assert.equal(scene.physics3d.castBallFixed(from, dir, 20, 0.5), null);
3635
+ assert.deepEqual(scene.physics3d.nearFixed(from, 20), []);
3636
+ assert.equal(scene.physics3d.castRayFixedNormal(from, dir, 20), null);
3637
+ return 1;
3638
+ }
3639
+
3640
+ // Rapier itself with these actors (boxes: a Transform at the middle, a
3641
+ // Shape `width` x `height` x `depth`) and its own ground, top at y = 0.
3642
+ export async function rapierWorld(actors) {
3643
+ const { Physics3DSystem } = await import('../systems/physics3d.js?orbit-real');
3644
+ const scene = { time: 0, data: {}, getActors: () => actors, getActor: (id) => actors.find((a) => a.id === id), forEachBehavior: () => {} };
3645
+ const system = new Physics3DSystem();
3646
+ system.attach(scene);
3647
+ for (let i = 0; i < 200 && !scene.physics3d.ready(); i += 1) {
3648
+ await new Promise((resolve) => setTimeout(resolve, 5));
3649
+ scene.time += FIXED;
3650
+ system.afterBehaviors(scene, FIXED);
3651
+ }
3652
+ assert.ok(scene.physics3d.ready(), 'rapier loaded');
3653
+ for (let i = 0; i < 3; i += 1) system.afterBehaviors(scene, FIXED);
3654
+ return { scene, system };
3655
+ }
3656
+ const wallBox = (id, x, z, width, depth) => ({
3657
+ id,
3658
+ components: {
3659
+ Transform: { x, y: 5, z, rotationX: 0, rotationY: 0, rotationZ: 0 },
3660
+ Shape: { kind: 'box', width, height: 200, depth, solid: true },
3661
+ },
3662
+ runtime: {},
3663
+ });
3664
+
3665
+ // A keyed world with this lens (near 0.1), its queries `api`'s.
3666
+ export function lensOn(api, fov, aspect) {
3667
+ const world = makeWorld('orbit');
3668
+ world.scene.data = { engine: { camera: { follow: 'rigid', control: 'orbit', fov } } };
3669
+ world.camera.fov = fov;
3670
+ world.camera.aspect = aspect;
3671
+ world.camera.near = 0.1;
3672
+ world.camera.updateProjectionMatrix();
3673
+ return queriesOf(world, api);
3674
+ }
3675
+ // The lens's stand-off, as Player.jsx `lensMargin` has it.
3676
+ function marginOf(fov, aspect) {
3677
+ const half = Math.tan((fov * DEG) / 2);
3678
+ return Math.max(0.25, 0.1 * Math.sqrt(1 + half * half + (aspect * half) ** 2) + 0.05);
3679
+ }
3680
+
3681
+ // Grazing lines (review 3): the camera stays its lens's margin off a surface
3682
+ // however flat its line meets it, at every lens and zoom, in a corner of two
3683
+ // walls and where the ground meets a wall, on rapier itself. The near
3684
+ // plane's corners (and middle) never cross a wall's face or the ground.
3685
+ async function grazing() {
3686
+ if (!realRapier) return 0;
3687
+ let checks = 0;
3688
+ const corner = new THREE.Vector3();
3689
+ // The near plane's farthest reach toward +x, +z and -y.
3690
+ const reachOf = (camera) => {
3691
+ camera.updateMatrixWorld();
3692
+ const most = { x: -Infinity, z: -Infinity, y: Infinity };
3693
+ for (const [x, y] of [[-1, -1], [1, -1], [1, 1], [-1, 1], [0, 0]]) {
3694
+ corner.set(x, y, -1).unproject(camera);
3695
+ most.x = Math.max(most.x, corner.x);
3696
+ most.z = Math.max(most.z, corner.z);
3697
+ most.y = Math.min(most.y, corner.y);
3698
+ }
3699
+ return most;
3700
+ };
3701
+ // One wall, its face at x = 0.8, 200 m long.
3702
+ {
3703
+ const { scene, system } = await rapierWorld([wallBox('wall', 1.3, 0, 1, 200)]);
3704
+ // The report: 120 degrees on 20:9, near 0.1, level, yaw -3, the
3705
+ // farthest zoom. It was at x = 0.546819 with a corner at 0.925958.
3706
+ {
3707
+ const world = lensOn(scene.physics3d, 120, 20 / 9);
3708
+ world.run(30);
3709
+ world.scene.persistent.camAngle = -3 * DEG;
3710
+ world.scene.cameraOrbit.pitch = 0;
3711
+ world.scene.cameraOrbit.range = FARTHEST;
3712
+ world.run(600);
3713
+ const reach = reachOf(world.camera);
3714
+ const x = world.camera.position.x;
3715
+ assert.ok(reach.x < 0.8, `the report: the near plane stays in front of the wall (a corner at x = ${reach.x.toFixed(6)}, the camera at ${x.toFixed(6)})`);
3716
+ assert.ok(Math.abs(0.8 - x - marginOf(120, 20 / 9)) < 1e-3, `held its margin off the wall, square to it (${(0.8 - x).toFixed(4)})`);
3717
+ checks += 1;
3718
+ }
3719
+ // Near grazing both ways round (and square on, pressed close), every
3720
+ // tilt, four zooms, two lenses on a wide and a tall screen, with the
3721
+ // player 0.8 m from the wall and with it against the wall (its capsule's
3722
+ // 0.35 m off, nearer than the widest lens's margin): every frame of the
3723
+ // sweep, settling included.
3724
+ const yaws = [...Array.from({ length: 21 }, (_, i) => i - 10), -30, -60, -90];
3725
+ for (const [fov, aspect, x0] of [[70, 20 / 9, 0], [70, 9 / 20, 0], [120, 20 / 9, 0], [120, 9 / 20, 0], [120, 20 / 9, 0.45], [70, 9 / 20, 0.45]]) {
3726
+ const world = lensOn(scene.physics3d, fov, aspect);
3727
+ world.body.pos.x = x0;
3728
+ world.actor.components.Transform.x = x0;
3729
+ world.run(30);
3730
+ for (const range of [NEAREST, RANGE0, 12, FARTHEST]) {
3731
+ for (let pitch = -80; pitch <= 80; pitch += 20) {
3732
+ for (const yaw of yaws) {
3733
+ world.scene.persistent.camAngle = yaw * DEG;
3734
+ world.scene.cameraOrbit.pitch = pitch * DEG;
3735
+ world.scene.cameraOrbit.range = range;
3736
+ for (let i = 0; i < 12; i += 1) {
3737
+ world.frame(UNEVEN(i));
3738
+ const reach = reachOf(world.camera);
3739
+ const where = `${fov} degrees, aspect ${aspect.toFixed(3)}, player at x = ${x0}, tilt ${pitch}, yaw ${yaw}, ${range} m, frame ${i}`;
3740
+ assert.ok(reach.x < 0.8, `${where}: a corner at x = ${reach.x.toFixed(4)}`);
3741
+ assert.ok(reach.y > 0, `${where}: a corner at y = ${reach.y.toFixed(4)}`);
3742
+ }
3743
+ checks += 1;
3744
+ }
3745
+ }
3746
+ }
3747
+ }
3748
+ system.dispose(scene);
3749
+ }
3750
+ // A corner: a second wall with its face at z = 3 across the first one's
3751
+ // end, and the ground under both. Toward the corner at every tilt.
3752
+ {
3753
+ const { scene, system } = await rapierWorld([wallBox('wall', 1.3, 0, 1, 200), wallBox('end', 0, 3.5, 200, 1)]);
3754
+ for (const [fov, aspect] of [[70, 20 / 9], [120, 20 / 9], [120, 9 / 20]]) {
3755
+ const world = lensOn(scene.physics3d, fov, aspect);
3756
+ world.run(30);
3757
+ for (const range of [RANGE0, FARTHEST]) {
3758
+ for (let pitch = -80; pitch <= 80; pitch += 10) {
3759
+ for (let yaw = -88; yaw <= -1; yaw += 3) {
3760
+ world.scene.persistent.camAngle = yaw * DEG;
3761
+ world.scene.cameraOrbit.pitch = pitch * DEG;
3762
+ world.scene.cameraOrbit.range = range;
3763
+ for (let i = 0; i < 12; i += 1) {
3764
+ world.frame(UNEVEN(i));
3765
+ const reach = reachOf(world.camera);
3766
+ const where = `corner: ${fov} degrees, aspect ${aspect.toFixed(3)}, tilt ${pitch}, yaw ${yaw}, ${range} m, frame ${i}`;
3767
+ assert.ok(reach.x < 0.8 && reach.z < 3 && reach.y > 0, `${where}: the near plane reaches ${JSON.stringify(reach)}`);
3768
+ }
3769
+ checks += 1;
3770
+ }
3771
+ }
3772
+ }
3773
+ }
3774
+ system.dispose(scene);
3775
+ }
3776
+ // Review 4: the camera held off the wall must not be behind something
3777
+ // else. The review's case: 120 degrees on 20:9, level, yaw -3, 12 m, the
3778
+ // wall's face at x = 0.8 and a thin post (x 0.1 to 0.22, z 5.75 to 6.25)
3779
+ // beside the camera's line (the axis-ray push of review 3 moved the camera
3780
+ // to x = 0.316 at z = 12, behind it). Settled, for 240 frames, the line
3781
+ // from the look point to the camera meets nothing, and the camera does
3782
+ // not move.
3783
+ {
3784
+ const { scene, system } = await rapierWorld([wallBox('wall', 1.3, 0, 1, 200), wallBox('post', 0.16, 6, 0.12, 0.5)]);
3785
+ const cast = scene.physics3d.castRayFixed;
3786
+ const world = lensOn(scene.physics3d, 120, 20 / 9);
3787
+ world.run(30);
3788
+ world.scene.persistent.camAngle = -3 * DEG;
3789
+ world.scene.cameraOrbit.pitch = 0;
3790
+ world.scene.cameraOrbit.range = 12;
3791
+ world.run(600);
3792
+ const settled = { ...world.camera.position };
3793
+ const dir = { x: 0, y: 0, z: 0 };
3794
+ for (let i = 0; i < 240; i += 1) {
3795
+ world.frame(FIXED);
3796
+ const t = world.actor.components.Transform;
3797
+ const from = { x: t.x, y: t.y + LOOK_HEIGHT, z: t.z };
3798
+ const p = world.camera.position;
3799
+ const length = Math.hypot(p.x - from.x, p.y - from.y, p.z - from.z);
3800
+ dir.x = (p.x - from.x) / length;
3801
+ dir.y = (p.y - from.y) / length;
3802
+ dir.z = (p.z - from.z) / length;
3803
+ const hit = cast(from, dir, length);
3804
+ const where = `the post: frame ${i}, the camera at (${p.x.toFixed(4)}, ${p.y.toFixed(4)}, ${p.z.toFixed(4)})`;
3805
+ assert.ok(!hit, `${where}: its line to the player meets ${hit?.actorId} at ${hit?.distance?.toFixed(4)} m`);
3806
+ const moved = Math.hypot(p.x - settled.x, p.y - settled.y, p.z - settled.z);
3807
+ assert.ok(moved < 1e-9, `${where}: moved ${moved} from where it settled`);
3808
+ assert.ok(reachOf(world.camera).x < 0.8, `${where}: the near plane stays in front of the wall`);
3809
+ }
3810
+ checks += 1;
3811
+ system.dispose(scene);
3812
+ }
3813
+ return checks;
3814
+ }
3815
+
3816
+ // A box `min` to `max`, fixed and solid, and how far a point is from it.
3817
+ const solidBox = ({ id, min, max }) => ({
3818
+ id,
3819
+ components: {
3820
+ Transform: { x: (min.x + max.x) / 2, y: (min.y + max.y) / 2, z: (min.z + max.z) / 2, rotationX: 0, rotationY: 0, rotationZ: 0 },
3821
+ Shape: { kind: 'box', width: max.x - min.x, height: max.y - min.y, depth: max.z - min.z, solid: true },
3822
+ },
3823
+ runtime: {},
3824
+ });
3825
+ const boxGap = (p, { min, max }) =>
3826
+ Math.hypot(Math.max(min.x - p.x, 0, p.x - max.x), Math.max(min.y - p.y, 0, p.y - max.y), Math.max(min.z - p.z, 0, p.z - max.z));
3827
+
3828
+ // Review 5: the camera let back out once what held it is gone. 120 degrees
3829
+ // on 20:9, level, yaw -3, 12 m; two separate boxes beside the camera's line
3830
+ // and a third across it that holds the camera in, settled, then removed.
3831
+ // `popRun` records every frame after the removal: where the camera is, how
3832
+ // far out from the look point, and how far it is from each box and the
3833
+ // ground, measured on the boxes themselves. The first record is the
3834
+ // settled frame before the removal.
3835
+ export const POP_LAYOUT = {
3836
+ boxes: [
3837
+ { id: 'a', min: { x: 0.42, y: 0, z: 4.56 }, max: { x: 1.6, y: 2.43, z: 7.27 } },
3838
+ { id: 'b', min: { x: -1.6, y: 0, z: 5.2 }, max: { x: 0.06, y: 1.33, z: 7.72 } },
3839
+ ],
3840
+ blocker: { id: 'blocker', min: { x: -1, y: 0, z: 2.03 }, max: { x: 1, y: 3, z: 2.43 } },
3841
+ };
3842
+ export async function popRun(layout = POP_LAYOUT, frames = 240) {
3843
+ const actors = [...layout.boxes, layout.blocker].map(solidBox);
3844
+ const { scene, system } = await rapierWorld(actors);
3845
+ const world = lensOn(scene.physics3d, 120, 20 / 9);
3846
+ world.run(30);
3847
+ world.scene.persistent.camAngle = -3 * DEG;
3848
+ world.scene.cameraOrbit.pitch = 0;
3849
+ world.scene.cameraOrbit.range = 12;
3850
+ world.run(600);
3851
+ const t = world.actor.components.Transform;
3852
+ const p = world.camera.position;
3853
+ const note = () => {
3854
+ const out = Math.hypot(p.x - t.x, p.y - (t.y + LOOK_HEIGHT), p.z - t.z);
3855
+ const gaps = Object.fromEntries(layout.boxes.map((box) => [box.id, boxGap(p, box)]));
3856
+ return { p: { x: p.x, y: p.y, z: p.z }, out, gaps: { ...gaps, ground: p.y } };
3857
+ };
3858
+ const seen = [note()];
3859
+ actors.splice(actors.findIndex((a) => a.id === layout.blocker.id), 1);
3860
+ system.afterBehaviors(scene, FIXED);
3861
+ for (let i = 0; i < frames; i += 1) {
3862
+ world.frame(FIXED);
3863
+ seen.push(note());
3864
+ }
3865
+ system.dispose(scene);
3866
+ return seen;
3867
+ }
3868
+ const popAt = (f, i) => `review 5: ${i === 0 ? 'settled, before the removal' : `frame ${i} after the removal`}, the camera at (${f.p.x.toFixed(6)}, ${f.p.y.toFixed(6)}, ${f.p.z.toFixed(6)})`;
3869
+
3870
+ // P1: the camera is its lens's margin off both boxes and the ground on
3871
+ // every frame (the review's case left it 8 mm off one; on 38441228 this
3872
+ // one comes within 34 mm of a box).
3873
+ export async function popClear(seen = null) {
3874
+ if (!realRapier) return 0;
3875
+ const frames = seen ?? (await popRun());
3876
+ const margin = marginOf(120, 20 / 9);
3877
+ let worst = null;
3878
+ frames.forEach((f, i) => {
3879
+ for (const [id, gap] of Object.entries(f.gaps)) if (!worst || gap < worst.gap) worst = { f, i, id, gap };
3880
+ });
3881
+ const { f, i, id, gap } = worst;
3882
+ assert.ok(gap >= margin - 1e-3, `${popAt(f, i)}: ${(gap * 1000).toFixed(2)} mm off ${id}, want the margin, ${(margin * 1000).toFixed(2)} mm`);
3883
+ return 1;
3884
+ }
3885
+
3886
+ // P2: no frame moves the camera farther than easing out at 6/s takes it
3887
+ // from where it was drawn (the review's case jumped 3.985 m in a frame; on
3888
+ // 38441228 this one jumps 2.231 m, 1.6 m more than easing allows, once the
3889
+ // pull that held it stops); a snap in is allowed, and the camera stays on
3890
+ // its line meanwhile.
3891
+ export async function popSteady(seen = null) {
3892
+ if (!realRapier) return 0;
3893
+ const frames = seen ?? (await popRun());
3894
+ let worst = null;
3895
+ for (let i = 1; i < frames.length; i += 1) {
3896
+ const [was, now] = [frames[i - 1], frames[i]];
3897
+ const easing = Math.max(0, 12 - was.out) * (1 - Math.exp(-6 * FIXED));
3898
+ const step = Math.hypot(now.p.x - was.p.x, now.p.y - was.p.y, now.p.z - was.p.z);
3899
+ // Past what easing out allows: outward, or sideways beyond a snap in.
3900
+ const over = Math.max(now.out - was.out - easing, step - easing - Math.max(0, was.out - now.out));
3901
+ if (!worst || over > worst.over) worst = { i, now, step, easing, over };
3902
+ }
3903
+ const { i, now, step, easing, over } = worst;
3904
+ assert.ok(over <= 1e-6, `${popAt(now, i)}: moved ${step.toFixed(6)} m in a frame, ${over.toFixed(6)} m past what easing out at 6/s allows (${easing.toFixed(6)})`);
3905
+ return 1;
3906
+ }
3907
+
3908
+ // Review 6: corners. A slab of rapier (a box `half` its size each way,
3909
+ // turned `turn` degrees about y, its middle at `middle`) and how far a point
3910
+ // is from it, measured on the box itself; `inside` when a point is in it.
3911
+ const slab = (id, middle, half, turn = 0) => {
3912
+ const c = Math.cos(turn * DEG);
3913
+ const s = Math.sin(turn * DEG);
3914
+ const local = (p) => {
3915
+ const x = p.x - middle.x;
3916
+ const z = p.z - middle.z;
3917
+ return { x: x * c - z * s, y: p.y - middle.y, z: x * s + z * c };
3918
+ };
3919
+ return {
3920
+ id,
3921
+ actor: {
3922
+ id,
3923
+ components: {
3924
+ Transform: { ...middle, rotationX: 0, rotationY: turn, rotationZ: 0 },
3925
+ Shape: { kind: 'box', width: 2 * half.x, height: 2 * half.y, depth: 2 * half.z, solid: true },
3926
+ },
3927
+ runtime: {},
3928
+ },
3929
+ gap: (p) => {
3930
+ const l = local(p);
3931
+ return Math.hypot(Math.max(Math.abs(l.x) - half.x, 0), Math.max(Math.abs(l.y) - half.y, 0), Math.max(Math.abs(l.z) - half.z, 0));
3932
+ },
3933
+ inside: (p) => {
3934
+ const l = local(p);
3935
+ return Math.abs(l.x) < half.x && Math.abs(l.y) < half.y && Math.abs(l.z) < half.z;
3936
+ },
3937
+ };
3938
+ };
3939
+ // A wall 1 m thick, 200 m long and high, its face 0.35 m from the player at
3940
+ // the origin (its capsule's radius: the player pressed to it), the face's
3941
+ // outward normal at `angle` degrees round from +x toward +z.
3942
+ const wallFacing = (id, angle) => {
3943
+ const n = { x: Math.cos(angle * DEG), z: Math.sin(angle * DEG) };
3944
+ return slab(id, { x: -0.85 * n.x, y: 5, z: -0.85 * n.z }, { x: 0.5, y: 100, z: 100 }, 180 - angle);
3945
+ };
3946
+ // A ceiling over the player's head, its underside 0.35 m above the look
3947
+ // point.
3948
+ const ceiling = () => slab('ceiling', { x: 0, y: FLOOR + LOOK_HEIGHT + 0.35 + 0.5, z: 0 }, { x: 100, y: 0.5, z: 100 });
3949
+
3950
+ // The player pressed into a corner, the camera turned every way round it,
3951
+ // up and down, near and far, at 120 degrees on 20:9: on every frame the
3952
+ // camera is its lens's margin (less 0.1 mm) off every slab and the ground,
3953
+ // and no corner
3954
+ // of the near plane (nor its middle) is inside a slab or under the ground.
3955
+ // Returns the nearest it came, less the margin, for the report.
3956
+ async function cornered(slabs, label) {
3957
+ const { scene, system } = await rapierWorld(slabs.map((x) => x.actor));
3958
+ const world = lensOn(scene.physics3d, 120, 20 / 9);
3959
+ const margin = marginOf(120, 20 / 9);
3960
+ const camera = world.camera;
3961
+ const near = new THREE.Vector3();
3962
+ world.run(30);
3963
+ let least = Infinity;
3964
+ for (const range of [12, RANGE0]) {
3965
+ for (const pitch of [-30, 0, 40]) {
3966
+ for (let yaw = -150; yaw <= 180; yaw += 30) {
3967
+ world.scene.persistent.camAngle = yaw * DEG;
3968
+ world.scene.cameraOrbit.pitch = pitch * DEG;
3969
+ world.scene.cameraOrbit.range = range;
3970
+ for (let i = 0; i < 20; i += 1) {
3971
+ world.frame(UNEVEN(i));
3972
+ const p = camera.position;
3973
+ const where = `${label}: tilt ${pitch}, yaw ${yaw}, ${range} m, frame ${i}, the camera at (${p.x.toFixed(4)}, ${p.y.toFixed(4)}, ${p.z.toFixed(4)})`;
3974
+ for (const x of slabs) {
3975
+ const gap = x.gap(p);
3976
+ least = Math.min(least, gap - margin);
3977
+ assert.ok(gap >= margin - 1e-4, `${where}: ${(gap * 1000).toFixed(2)} mm off ${x.id}, want ${(margin * 1000).toFixed(2)}`);
3978
+ }
3979
+ least = Math.min(least, p.y - margin);
3980
+ assert.ok(p.y >= margin - 1e-4, `${where}: ${p.y} m off the ground`);
3981
+ camera.updateMatrixWorld();
3982
+ for (const [cx, cy] of [[-1, -1], [1, -1], [1, 1], [-1, 1], [0, 0]]) {
3983
+ near.set(cx, cy, -1).unproject(camera);
3984
+ const into = slabs.find((x) => x.inside(near));
3985
+ assert.ok(!into && near.y > 0, `${where}: the near plane's corner (${cx}, ${cy}) is inside ${into?.id ?? 'the ground'}`);
3986
+ }
3987
+ }
3988
+ }
3989
+ }
3990
+ }
3991
+ system.dispose(scene);
3992
+ return least;
3993
+ }
3994
+
3995
+ // Two walls meeting at every angle from 30 to 150 degrees, the player in the
3996
+ // corner (review 6's case is 60: the moves off each wall undid each other
3997
+ // and the camera was left 8.66 mm off a wall); and three surfaces at once:
3998
+ // two walls square to each other under a ceiling, and the 60 degree corner
3999
+ // under it.
4000
+ export async function corners() {
4001
+ if (!realRapier) return 0;
4002
+ let checks = 0;
4003
+ corners.least = {};
4004
+ for (let wedge = 30; wedge <= 150; wedge += 15) {
4005
+ corners.least[wedge] = await cornered([wallFacing('a', 180), wallFacing('b', 360 - wedge)], `a ${wedge} degree corner`);
4006
+ checks += 1;
4007
+ }
4008
+ corners.least.square = await cornered([wallFacing('a', 180), wallFacing('b', 270), ceiling()], 'two square walls and a ceiling');
4009
+ corners.least.sixty = await cornered([wallFacing('a', 180), wallFacing('b', 300), ceiling()], 'a 60 degree corner and a ceiling');
4010
+ return checks + 2;
4011
+ }
4012
+
4013
+ // A gap narrower than twice the margin (two walls 0.7 m apart, the player
4014
+ // between them, 120 degrees on 20:9). No place there keeps the lens's near
4015
+ // plane out of both walls, and it is accepted that the lens cuts into them
4016
+ // (Roblox's camera clips there too; the near plane is not shrunk). What is
4017
+ // guaranteed, and all this asserts: the camera point itself is never inside
4018
+ // a wall, nothing is NaN, and a settled camera stays where it is.
4019
+ async function narrowGapStable() {
4020
+ if (!realRapier) return 0;
4021
+ const walls = [wallFacing('a', 180), wallFacing('b', 0)];
4022
+ const { scene, system } = await rapierWorld(walls.map((x) => x.actor));
4023
+ const world = lensOn(scene.physics3d, 120, 20 / 9);
4024
+ const p = world.camera.position;
4025
+ world.run(30);
4026
+ for (const pitch of [-30, 0, 40]) {
4027
+ for (let yaw = -150; yaw <= 180; yaw += 30) {
4028
+ world.scene.persistent.camAngle = yaw * DEG;
4029
+ world.scene.cameraOrbit.pitch = pitch * DEG;
4030
+ world.scene.cameraOrbit.range = 12;
4031
+ const where = (i) => `a narrow gap: tilt ${pitch}, yaw ${yaw}, frame ${i}, the camera at (${p.x}, ${p.y}, ${p.z})`;
4032
+ for (let i = 0; i < 120; i += 1) {
4033
+ world.frame(UNEVEN(i));
4034
+ assert.ok([p.x, p.y, p.z, ...world.camera.quaternion.toArray()].every(Number.isFinite), `${where(i)}: not a number`);
4035
+ for (const x of walls) assert.ok(!x.inside(p) && x.gap(p) > 0, `${where(i)}: inside ${x.id}`);
4036
+ }
4037
+ const settled = { x: p.x, y: p.y, z: p.z };
4038
+ for (let i = 0; i < 60; i += 1) {
4039
+ world.frame(FIXED);
4040
+ const moved = Math.hypot(p.x - settled.x, p.y - settled.y, p.z - settled.z);
4041
+ assert.ok(moved < 1e-9, `${where(120 + i)}: moved ${moved} after settling`);
4042
+ }
4043
+ }
4044
+ }
4045
+ system.dispose(scene);
2071
4046
  return 1;
2072
4047
  }
2073
4048
 
4049
+ // Review 7: a wall the player stands near is removed. The camera, held by
4050
+ // it, eases back out measured from the look point: no frame takes it
4051
+ // farther out than easing at 6/s from where it was drawn allows, though the
4052
+ // ball's start moves back to the look point as the wall goes. The review's
4053
+ // case is a wall face 0.5 m off with the camera at -60 degrees (it went out
4054
+ // 1.161 m in the first frame where 1.139 is allowed); also nearer and
4055
+ // farther faces and other angles.
4056
+ export async function releaseEase() {
4057
+ if (!realRapier) return 0;
4058
+ let checks = 0;
4059
+ for (const face of [0.36, 0.42, 0.5, 0.6]) {
4060
+ for (const yaw of [-30, -45, -60, -80]) {
4061
+ const walls = [wallFacing('a', 180)];
4062
+ walls[0].actor.components.Transform.x += face - 0.35;
4063
+ const actors = walls.map((x) => x.actor);
4064
+ const { scene, system } = await rapierWorld(actors);
4065
+ const world = lensOn(scene.physics3d, 120, 20 / 9);
4066
+ world.run(30);
4067
+ world.scene.cameraOrbit.pitch = 0;
4068
+ world.scene.cameraOrbit.range = 12;
4069
+ world.scene.persistent.camAngle = yaw * DEG;
4070
+ world.run(600);
4071
+ const t = world.actor.components.Transform;
4072
+ const p = world.camera.position;
4073
+ const out = () => Math.hypot(p.x - t.x, p.y - (t.y + LOOK_HEIGHT), p.z - t.z);
4074
+ actors.length = 0;
4075
+ system.afterBehaviors(scene, FIXED);
4076
+ let before = out();
4077
+ for (let i = 0; i < 90; i += 1) {
4078
+ world.frame(FIXED);
4079
+ const now = out();
4080
+ const allowed = Math.max(0, 12 - before) * (1 - Math.exp(-6 * FIXED));
4081
+ assert.ok(now - before <= allowed + 1e-9, `review 7: a face ${face} m off, yaw ${yaw}, frame ${i} after the removal: out ${(now - before).toFixed(6)} m, easing at 6/s allows ${allowed.toFixed(6)}`);
4082
+ before = now;
4083
+ }
4084
+ assert.ok(Math.abs(out() - 12) < 0.05, `review 7: a face ${face} m off, yaw ${yaw}: back out (${out()})`);
4085
+ system.dispose(scene);
4086
+ checks += 1;
4087
+ }
4088
+ }
4089
+ return checks;
4090
+ }
4091
+
4092
+ // Review 8, P2: a box beside the look point (its face 0.35 m off, the
4093
+ // camera not held by it but its start moved off it) is removed. The camera,
4094
+ // drawn short of its distance by that move, eases back out at 6/s too (it
4095
+ // went out 0.0616 m in a frame where 0.0059 m is allowed); at a few angles
4096
+ // and with the box nearer and farther.
4097
+ export async function releaseBeside() {
4098
+ if (!realRapier) return 0;
4099
+ let checks = 0;
4100
+ for (const face of [0.35, 0.42, 0.5]) {
4101
+ for (const yaw of [-160, -120, 170, 135]) {
4102
+ const actors = [solidBox({ id: 'box', min: { x: face, y: 0, z: 0 }, max: { x: face + 1, y: 5, z: 2 } })];
4103
+ const { scene, system } = await rapierWorld(actors);
4104
+ const world = lensOn(scene.physics3d, 120, 20 / 9);
4105
+ world.run(30);
4106
+ world.scene.persistent.camAngle = yaw * DEG;
4107
+ world.scene.cameraOrbit.pitch = 0;
4108
+ world.scene.cameraOrbit.range = 12;
4109
+ world.run(600);
4110
+ const t = world.actor.components.Transform;
4111
+ const p = world.camera.position;
4112
+ const out = () => Math.hypot(p.x - t.x, p.y - (t.y + LOOK_HEIGHT), p.z - t.z);
4113
+ actors.length = 0;
4114
+ system.afterBehaviors(scene, FIXED);
4115
+ let before = out();
4116
+ for (let i = 0; i < 90; i += 1) {
4117
+ world.frame(FIXED);
4118
+ const now = out();
4119
+ const allowed = Math.max(0, 12 - before) * (1 - Math.exp(-6 * FIXED));
4120
+ // (The last 0.1 mm is let go at once: CAMERA_OUT_DONE.)
4121
+ assert.ok(now - before <= allowed + 1e-4, `review 8: a box ${face} m off, yaw ${yaw}, frame ${i} after the removal: out ${(now - before).toFixed(6)} m, easing at 6/s allows ${allowed.toFixed(6)}`);
4122
+ before = now;
4123
+ }
4124
+ system.dispose(scene);
4125
+ checks += 1;
4126
+ }
4127
+ }
4128
+ return checks;
4129
+ }
4130
+
4131
+ // A seeded random number source (mulberry32).
4132
+ function seeded(seed) {
4133
+ let state = seed >>> 0;
4134
+ return () => {
4135
+ state = (state + 0x6d2b79f5) | 0;
4136
+ let t = Math.imul(state ^ (state >>> 15), 1 | state);
4137
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
4138
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
4139
+ };
4140
+ }
4141
+
4142
+ // Review 8, P1: rapier's sweep can miss a box outright. Random boxes, one or
4143
+ // two, turned any way about y, around a player whose look point is its
4144
+ // lens's margin clear of them; random yaws (mostly toward a box) and tilts, 70 and 120 degree
4145
+ // lenses on 16:9 and 20:9 screens, every frame as the camera swings round
4146
+ // to them: the camera is the margin (less 1 mm) off every box and the
4147
+ // ground, and no point of a 21 x 21 grid over the near plane is inside a
4148
+ // box. Seeded, so the same cases run every time. The review's case (one box,
4149
+ // yaw 5.0856, tilt 0.5191, 120 degrees on 20:9, 47 frames) is the first.
4150
+ export async function randomBoxes(cases = 120, seed = 8, withReview = true) {
4151
+ if (!realRapier) return 0;
4152
+ const random = seeded(seed);
4153
+ const between = (a, b) => a + (b - a) * random();
4154
+ const grid = new THREE.Vector3();
4155
+ const lookAt = { x: 0, y: FLOOR + LOOK_HEIGHT, z: 0 };
4156
+ const review = {
4157
+ slabs: [slab('box', { x: 2.31591782, y: 1.5, z: 0.14141787 }, { x: 0.12034748, y: 1.5, z: 0.52895252 })],
4158
+ fov: 120,
4159
+ aspect: 20 / 9,
4160
+ yaw: 5.085648783239423,
4161
+ pitch: 0.5191120134075965,
4162
+ };
4163
+ let checks = 0;
4164
+ for (let n = 0; n < cases; n += 1) {
4165
+ let setup = n === 0 && withReview ? review : null;
4166
+ while (!setup) {
4167
+ const fov = random() < 0.5 ? 70 : 120;
4168
+ const aspect = random() < 0.5 ? 16 / 9 : 20 / 9;
4169
+ const slabs = [];
4170
+ const count = random() < 0.5 ? 1 : 2;
4171
+ for (let k = 0; k < count; k += 1) {
4172
+ const away = between(0.8, 5);
4173
+ const angle = between(0, 2 * Math.PI);
4174
+ const half = { x: between(0.05, 0.8), y: between(0.3, 2), z: between(0.05, 0.8) };
4175
+ slabs.push(slab(`box${k}`, { x: away * Math.cos(angle), y: half.y, z: away * Math.sin(angle) }, half, between(-90, 90)));
4176
+ }
4177
+ if (slabs.every((x) => x.gap(lookAt) >= marginOf(fov, aspect) + 0.06)) {
4178
+ // Mostly toward a box, where the sweep passes its edges.
4179
+ const aim = slabs[0].actor.components.Transform;
4180
+ const yaw = random() < 0.75 ? Math.atan2(-aim.x, aim.z) + between(-0.5, 0.5) : between(-Math.PI, Math.PI);
4181
+ setup = { slabs, fov, aspect, yaw, pitch: between(-0.6, 0.9) };
4182
+ }
4183
+ }
4184
+ const { slabs, fov, aspect, yaw, pitch } = setup;
4185
+ const { scene, system } = await rapierWorld(slabs.map((x) => x.actor));
4186
+ const world = lensOn(scene.physics3d, fov, aspect);
4187
+ const margin = marginOf(fov, aspect);
4188
+ const camera = world.camera;
4189
+ const p = camera.position;
4190
+ world.run(30);
4191
+ world.scene.persistent.camAngle = yaw;
4192
+ world.scene.cameraOrbit.pitch = pitch;
4193
+ world.scene.cameraOrbit.range = 12;
4194
+ for (let i = 0; i < 90; i += 1) {
4195
+ world.frame(FIXED);
4196
+ const where = `random boxes, case ${n} (${fov} degrees, aspect ${aspect.toFixed(3)}, yaw ${yaw}, tilt ${pitch}), frame ${i}, the camera at (${p.x.toFixed(4)}, ${p.y.toFixed(4)}, ${p.z.toFixed(4)})`;
4197
+ for (const x of slabs) {
4198
+ const gap = x.gap(p);
4199
+ assert.ok(gap >= margin - 1e-3, `${where}: ${(gap * 1000).toFixed(2)} mm off ${x.id}, want ${(margin * 1000).toFixed(2)}`);
4200
+ }
4201
+ assert.ok(p.y >= margin - 1e-3, `${where}: ${p.y} m off the ground`);
4202
+ camera.updateMatrixWorld();
4203
+ for (let a = 0; a <= 20; a += 1) {
4204
+ for (let b = 0; b <= 20; b += 1) {
4205
+ grid.set(a / 10 - 1, b / 10 - 1, -1).unproject(camera);
4206
+ const into = slabs.find((x) => x.inside(grid));
4207
+ assert.ok(!into, `${where}: the near plane at (${grid.x.toFixed(4)}, ${grid.y.toFixed(4)}, ${grid.z.toFixed(4)}) is inside ${into?.id}`);
4208
+ }
4209
+ }
4210
+ }
4211
+ system.dispose(scene);
4212
+ checks += 1;
4213
+ }
4214
+ return checks;
4215
+ }
4216
+
4217
+ // Rapier's misses, made to happen: a sweep that reports nothing, every
4218
+ // time or only when every solid is asked at once, still stops the ball its
4219
+ // radius off the wall (to within a millimetre, by halving, or by sweeping
4220
+ // against the solid alone), and a ball whose line ends inside a wall is
4221
+ // brought out of it.
4222
+ export async function ballMisses() {
4223
+ if (!realRapier) return 0;
4224
+ const { scene, system } = await rapierWorld([wallBox('wall', 8, 0, 1, 4)]);
4225
+ const world = system.world;
4226
+ const real = world.castShape.bind(world);
4227
+ const from = { x: 0, y: 5, z: 0 };
4228
+ const dir = { x: 1, y: 0, z: 0 };
4229
+ const sure = scene.physics3d.castBallFixed(from, dir, 20, 0.5);
4230
+ assert.ok(Math.abs(sure.distance - 7) < 1e-4, `rapier itself (${sure.distance})`);
4231
+ world.castShape = () => null;
4232
+ const blind = scene.physics3d.castBallFixed(from, dir, 20, 0.5);
4233
+ assert.ok(blind && blind.actorId === 'wall' && blind.distance <= 7 + 1e-4 && blind.distance > 7 - 2e-3, `missed every time: halved to ${blind?.distance}`);
4234
+ assert.ok(Math.abs(blind.normal.x + 1) < 1e-3, `facing the ball (${JSON.stringify(blind.normal)})`);
4235
+ world.castShape = (...args) => (args[11] ? real(...args) : null);
4236
+ const alone = scene.physics3d.castBallFixed(from, dir, 20, 0.5);
4237
+ assert.ok(Math.abs(alone.distance - 7) < 1e-4, `missed with every solid, met alone (${alone.distance})`);
4238
+ // Short of the wall the end is clear: nothing to find, as rapier says.
4239
+ world.castShape = () => null;
4240
+ assert.equal(scene.physics3d.castBallFixed(from, dir, 6.9, 0.5), null);
4241
+ // Beside the wall's line, ending inside it: out of it.
4242
+ const slant = { x: Math.cos(0.2), y: 0, z: Math.sin(0.2) };
4243
+ const side = scene.physics3d.castBallFixed({ x: 0, y: 5, z: -2.2 }, slant, 9, 0.5);
4244
+ const end = { x: side.distance * slant.x, z: -2.2 + side.distance * slant.z };
4245
+ const gap = Math.hypot(Math.max(7.5 - end.x, 0, end.x - 8.5), Math.max(-2 - end.z, 0, end.z - 2));
4246
+ assert.ok(gap >= 0.5 - 1e-3, `a slant missed: the ball ends ${gap} m off the wall`);
4247
+ world.castShape = real;
4248
+ system.dispose(scene);
4249
+ return 1;
4250
+ }
4251
+
4252
+ // Review 9: a takeover blend a wall holds in, the wall then removed. The
4253
+ // blend is let out at the collision pace: no frame takes the camera
4254
+ // farther from the look point than easing at 6/s toward its distance allows
4255
+ // (the blend's own 10/s carried it 0.246 m where 0.179 m is allowed), and
4256
+ // it still ends where the camera rests. The review's case (a wall at x = 1,
4257
+ // 70 degrees on 16:9, the camera handed back at (8, 8, 8)) and others; with
4258
+ // the wall kept the blend ends held by it and stays; with no wall the blend
4259
+ // is never held and ends in about 0.3 s, as before. Review 10: a wall near
4260
+ // the look point (its face 0.4 m off, so the start is moved off it and the
4261
+ // camera rests farther out than its distance) and a corner of two such
4262
+ // walls, at 70 and 120 degrees: the blend held there ends too (it was held
4263
+ // open for good, 0.093 m short, after 20 s). Every blend ends: what is
4264
+ // left of it 0.1 mm or less, no longer held, and one sweep a frame.
4265
+ const nearWall = (id, axis) => solidBox({ id, min: { x: -20, y: 0, z: -20, [axis]: 0.4 }, max: { x: 20, y: 20, z: 20, [axis]: 0.5 } });
4266
+ export async function blendRelease() {
4267
+ if (!realRapier) return 0;
4268
+ let checks = 0;
4269
+ const handBacks = [{ x: 8, y: 8, z: 8 }, { x: 6, y: 3, z: -2 }, { x: 4, y: 6, z: 5 }];
4270
+ const cases = [];
4271
+ for (const wallAt of [1, 1.5, null]) {
4272
+ for (const remove of wallAt === null ? [false] : [true, false]) {
4273
+ const walls = () => (wallAt === null ? [] : [solidBox({ id: 'wall', min: { x: wallAt, y: 0, z: -10 }, max: { x: wallAt + 0.1, y: 20, z: 20 } })]);
4274
+ cases.push({ walls, wallAt, remove, fov: 70, aspect: 16 / 9, label: wallAt === null ? 'no wall' : `a wall at x = ${wallAt}${remove ? ', removed' : ', kept'}` });
4275
+ }
4276
+ }
4277
+ for (const [fov, aspect] of [[70, 16 / 9], [120, 20 / 9]]) {
4278
+ for (const remove of [false, true]) {
4279
+ cases.push({ walls: () => [nearWall('near', 'x')], remove, fov, aspect, label: `a wall 0.4 m off${remove ? ', removed' : ', kept'}, ${fov} degrees` });
4280
+ cases.push({ walls: () => [nearWall('near', 'x'), nearWall('side', 'z')], remove, fov, aspect, label: `a corner 0.4 m off${remove ? ', removed' : ', kept'}, ${fov} degrees` });
4281
+ }
4282
+ }
4283
+ for (const c of cases) {
4284
+ for (const from of handBacks) {
4285
+ const actors = c.walls();
4286
+ const { scene, system } = await rapierWorld(actors);
4287
+ const world = lensOn(scene.physics3d, c.fov, c.aspect);
4288
+ const t = world.actor.components.Transform;
4289
+ const p = world.camera.position;
4290
+ const out = () => Math.hypot(p.x - t.x, p.y - (t.y + LOOK_HEIGHT), p.z - t.z);
4291
+ const label = `blend: ${c.label}, handed back at (${from.x}, ${from.y}, ${from.z})`;
4292
+ world.run(120);
4293
+ const whole = world.off(from);
4294
+ p.set(from.x, from.y, from.z);
4295
+ world.frame();
4296
+ if (c.wallAt) assert.ok(p.x <= c.wallAt - marginOf(c.fov, c.aspect) + 1e-3, `${label}: the wall holds the blend (x = ${p.x})`);
4297
+ if (c.remove) {
4298
+ actors.length = 0;
4299
+ system.afterBehaviors(scene, FIXED);
4300
+ }
4301
+ let before = out();
4302
+ let last = { x: p.x, y: p.y, z: p.z };
4303
+ let moved = Infinity;
4304
+ for (let i = 0; i < 300; i += 1) {
4305
+ world.frame(FIXED);
4306
+ const now = out();
4307
+ const allowed = Math.max(0, RANGE0 - before) * (1 - Math.exp(-6 * FIXED));
4308
+ if (c.remove) assert.ok(now - before <= allowed + 1e-4, `${label}, frame ${i}: out ${(now - before).toFixed(6)} m, easing at 6/s allows ${allowed.toFixed(6)}`);
4309
+ moved = Math.hypot(p.x - last.x, p.y - last.y, p.z - last.z);
4310
+ last = { x: p.x, y: p.y, z: p.z };
4311
+ before = now;
4312
+ if (c.walls().length === 0 && i === 16) assert.ok(world.off(world.rest(world.scene.persistent.camAngle, PITCH0, RANGE0)) < whole * 0.06, `${label}: about there in 0.3 s`);
4313
+ }
4314
+ const state = world.actor.runtime.orbit;
4315
+ assert.ok(Math.hypot(state.off.x, state.off.y, state.off.z) <= 1e-4, `${label}: the blend ended (${Math.hypot(state.off.x, state.off.y, state.off.z)} left)`);
4316
+ assert.ok(state.blendHeld !== true, `${label}: no longer held`);
4317
+ assert.ok(moved < 1e-9, `${label}: and the camera stays (${moved})`);
4318
+ world.sweeps = 0;
4319
+ world.run(60);
4320
+ assert.equal(world.sweeps, 60, `${label}: one sweep a frame once settled`);
4321
+ if (c.walls().length === 0 || c.remove) assert.ok(world.off(world.rest(world.scene.persistent.camAngle, PITCH0, RANGE0)) < 1e-3, `${label}: where it rests`);
4322
+ system.dispose(scene);
4323
+ checks += 1;
4324
+ }
4325
+ }
4326
+ return checks;
4327
+ }
4328
+
4329
+ // Compact copies of the preview world's blockers at the reported seats,
4330
+ // plus bench-8's grazing cylinder. Held Transforms must stay steady even
4331
+ // near blockers; body/hold fighting is checked separately below.
4332
+ // Each box: id, centre x/y/z, width/height/depth, yaw. No models or hub code.
4333
+ const seatedBoxes = [
4334
+ ['bench-8', -5.198, .25, 7.602, 2.4, .5, .6, 180],
4335
+ ['bench-23', 12.6, .25, 67.16, 2.4, .5, .6, 270],
4336
+ ['set-board-S6L', 16.88, 1.7, 66.433, 1.6, 1.1, .14, 270],
4337
+ ['bench-25', 12.6, .25, 78.6, 2.4, .5, .6, 270],
4338
+ ['stall-harbour-2', 12.2, .5, 74.767, 2.4, 1, .9, 270],
4339
+ ['set-S7L', 20.5, 1.8, 78, 8.667, 3.6, 7, 270],
4340
+ ['set-board-S7L', 16.88, 1.7, 75.1, 1.6, 1.1, .14, 270],
4341
+ ['harbour-far-l', 13.1, .7, 83.4, 21.8, 1.4, .8, 0],
4342
+ ['quay-crate-4', 12.3, .45, 79.2, .9, .9, .9, 0],
4343
+ ];
4344
+ function seatedSolids() {
4345
+ const boxes = seatedBoxes.map(([id, x, y, z, width, height, depth, rotationY]) => ({
4346
+ id, components: {
4347
+ Transform: { x, y, z, rotationX: 0, rotationY, rotationZ: 0 },
4348
+ Shape: { kind: 'box', width, height, depth }, Solid: {},
4349
+ }, runtime: {},
4350
+ }));
4351
+ for (const [id, x, y, z, radius, height] of [
4352
+ ['tree-9', -3.896, 1, 9.643, .9, 2],
4353
+ ['quay-barrel-3', 11.5, .45, 78.5, .42, .9],
4354
+ ]) boxes.push({ id, components: {
4355
+ Transform: { x, y, z, rotationX: 0, rotationY: 0, rotationZ: 0 },
4356
+ Shape: { kind: 'cylinder', radius, height }, Solid: {},
4357
+ }, runtime: {} });
4358
+ return boxes;
4359
+ }
4360
+ // Advance the real Player and its camera while holding the Transform, as
4361
+ // a seat does. Unlike makeWorld.frame, this does not simulate stand-in physics.
4362
+ function seatedFrame(world, height, dt = FIXED) {
4363
+ world.actor.components.Transform.y = height;
4364
+ world.scene.time += dt;
4365
+ new Player(world.actor.components.Player).update(world.actor, world.scene, dt);
4366
+ placeFollowCamera(world.scene);
4367
+ }
4368
+
4369
+ export async function seatedJitter() {
4370
+ if (!realRapier) return 0;
4371
+ const actors = seatedSolids();
4372
+ const { scene, system } = await rapierWorld(actors);
4373
+ let checks = 0;
4374
+ try {
4375
+ for (const id of ['bench-8', 'bench-23', 'bench-25']) {
4376
+ const seat = actors.find((a) => a.id === id).components.Transform;
4377
+ for (const yaw of [0, 45, 90, 135, 160, 180, 225, 270, 315, 345]) {
4378
+ for (const pitch of [-20, 0, 15, 35, 60]) {
4379
+ const world = lensOn(scene.physics3d, 70, 1.6);
4380
+ Object.assign(world.actor.components.Transform, seat, { y: 1.35 });
4381
+ world.scene.persistent.camAngle = yaw * DEG;
4382
+ world.scene.data.engine.camera.pitch = pitch;
4383
+ for (let i = 0; i < 240; i += 1) seatedFrame(world, 1.35);
4384
+ const at = world.camera.position.clone();
4385
+ const aim = world.camera.quaternion.toArray();
4386
+ const from = { ...world.lastCast.from };
4387
+ const limit = world.actor.runtime.orbit.limit;
4388
+ const label = `${id}, yaw ${yaw}, pitch ${pitch}`;
4389
+ for (let i = 0; i < 120; i += 1) {
4390
+ seatedFrame(world, 1.35);
4391
+ const p = world.camera.position;
4392
+ assert.ok(p.distanceTo(at) < 1e-8, `${label}, held Transform, frame ${i}: camera moved ${p.distanceTo(at)} m`);
4393
+ assert.ok(world.camera.quaternion.toArray().every((v, j) => Math.abs(v - aim[j]) < 1e-8), `${label}: the aim stays steady`);
4394
+ for (const k of ['x', 'y', 'z']) assert.ok(Math.abs(world.lastCast.from[k] - from[k]) < 1e-8, `${label}: sweep start ${k} stays steady`);
4395
+ const now = world.actor.runtime.orbit.limit;
4396
+ assert.ok(now === limit || Math.abs(now - limit) < 1e-8, `${label}: the pop-in limit stays steady`);
4397
+ assert.deepEqual(scene.physics3d.nearFixed(p, .25 - 2e-4), [], `${label}: the camera ball stays clear of every solid`);
4398
+ }
4399
+ checks += 1;
4400
+ }
4401
+ }
4402
+ }
4403
+ // A still Transform must still take a new blocker in at once and
4404
+ // let it out at 6/s. No camera filtering is justified by these seats.
4405
+ const world = lensOn(scene.physics3d, 70, 1.6);
4406
+ world.scene.persistent.camAngle = 0;
4407
+ for (let i = 0; i < 240; i += 1) seatedFrame(world, 1.35);
4408
+ const wall = wallBox('new-seat-wall', 0, 2, 20, .5);
4409
+ actors.push(wall);
4410
+ system.afterBehaviors(scene, FIXED);
4411
+ seatedFrame(world, 1.35);
4412
+ assert.ok(world.camera.position.z <= 1.5 + 1e-4, 'a new wall snaps the camera in, including its margin');
4413
+ assert.deepEqual(scene.physics3d.nearFixed(world.camera.position, .25 - 2e-4), [], 'stationary camera stays outside the new wall');
4414
+ actors.pop();
4415
+ system.afterBehaviors(scene, FIXED);
4416
+ for (let i = 0; i < 180; i += 1) {
4417
+ const was = world.actor.runtime.orbit.out;
4418
+ seatedFrame(world, 1.35);
4419
+ const out = world.actor.runtime.orbit.out;
4420
+ assert.ok(out - was <= (RANGE0 - was) * (1 - Math.exp(-6 * FIXED)) + 1e-4, 'stationary camera eases out at 6/s (with its 0.1 mm completion tolerance)');
4421
+ }
4422
+ checks += 1;
4423
+ // Keep nearFixed's displaced start stable too (a look point 0.1 m
4424
+ // from a wall), including a wider lens that needs a larger ball.
4425
+ for (const [fov, aspect] of [[70, 1.6], [120, 20 / 9]]) {
4426
+ const w = lensOn(scene.physics3d, fov, aspect);
4427
+ const wall = wallBox('beside-seat', .6, 0, 1, 20);
4428
+ actors.push(wall);
4429
+ system.afterBehaviors(scene, FIXED);
4430
+ w.scene.persistent.camAngle = Math.PI / 2;
4431
+ for (let i = 0; i < 240; i += 1) seatedFrame(w, 1.35);
4432
+ const at = w.camera.position.clone();
4433
+ assert.ok(w.lastCast.from.x < -.1, 'the near wall displaces the sweep start');
4434
+ for (let i = 0; i < 120; i += 1) {
4435
+ seatedFrame(w, 1.35);
4436
+ assert.ok(w.camera.position.distanceTo(at) < 1e-8, 'the displaced start stays steady');
4437
+ assert.deepEqual(scene.physics3d.nearFixed(w.camera.position, marginOf(fov, aspect) - 2e-4), [], 'the wider lens stays clear');
4438
+ }
4439
+ actors.pop();
4440
+ system.afterBehaviors(scene, FIXED);
4441
+ checks += 1;
4442
+ }
4443
+ return checks;
4444
+ } finally {
4445
+ system.dispose(scene);
4446
+ }
4447
+ }
4448
+
4449
+ // Bench-25's held capsule overlaps the adjacent crate. Exercise the real
4450
+ // controller, physics, interpolation and camera with a 50 ms server-style
4451
+ // clamp (5 cm horizontal / 50 cm vertical slack). Keep this as a body-fight
4452
+ // reproducer, not a reason to suppress correct camera motion in Player.
4453
+ async function seatedBodyRun(clearCrate) {
4454
+ const actors = seatedSolids();
4455
+ if (clearCrate) actors.find((a) => a.id === 'quay-crate-4').components.Transform.z = 79.45;
4456
+ const at = { x: 12.6, y: 1.35, z: 78.6 };
4457
+ const player = {
4458
+ id: 'sitter', components: {
4459
+ Transform: { ...at, rotationX: 0, rotationY: 270, rotationZ: 0 },
4460
+ Shape: { kind: 'capsule', height: 1.4, radius: .35 },
4461
+ Body: { type: 'dynamic', gravityScale: 2, lockRotations: true, friction: 0 },
4462
+ Solid: {}, Player: { ...PROPS },
4463
+ }, runtime: {},
4464
+ };
4465
+ actors.push(player);
4466
+ const { scene, system } = await rapierWorld(actors);
4467
+ const world = lensOn(scene.physics3d, 70, 1.6);
4468
+ Object.assign(scene, { cameraFollowsRigidly: true, cameraControl: 'orbit',
4469
+ persistent: { camAngle: Math.PI / 4 }, keys: new Set(), actorsWith: () => [],
4470
+ three: { camera: world.camera }, lookInput: world.gestures.look, moveInput: world.stick });
4471
+ scene.data = { engine: { camera: { follow: 'rigid', control: 'orbit' } } };
4472
+ const body = scene.physics3d.bodyOf(player);
4473
+ body.setTranslation(at, true);
4474
+ body.setLinvel({ x: 0, y: 0, z: 0 }, true);
4475
+ Object.assign(player.components.Transform, at);
4476
+ let last = null;
4477
+ const result = { body: 0, camera: 0, clamps: 0 };
4478
+ try {
4479
+ for (let i = 0; i < 600; i += 1) {
4480
+ scene.time += FIXED;
4481
+ new Player(player.components.Player).update(player, scene, FIXED);
4482
+ system.afterBehaviors(scene, FIXED);
4483
+ // Multiplayer accepts the clamp after physics. The rendered Transform
4484
+ // catches up in the next physics pass; preserve that interpolation.
4485
+ if (i % 3 === 0) {
4486
+ const p = body.translation();
4487
+ if (Math.hypot(p.x - at.x, p.z - at.z) > .05 || Math.abs(p.y - at.y) > .5) {
4488
+ body.setTranslation(at, true);
4489
+ if (i >= 300) result.clamps += 1;
4490
+ }
4491
+ }
4492
+ placeFollowCamera(scene);
4493
+ const p = { ...body.translation() };
4494
+ const cam = world.camera.position.clone();
4495
+ if (i >= 300 && last) {
4496
+ result.body = Math.max(result.body, Math.hypot(p.x - last.p.x, p.y - last.p.y, p.z - last.p.z));
4497
+ result.camera = Math.max(result.camera, cam.distanceTo(last.cam));
4498
+ }
4499
+ last = { p, cam };
4500
+ }
4501
+ return result;
4502
+ } finally {
4503
+ system.dispose(scene);
4504
+ }
4505
+ }
4506
+ async function seatedBodyClamp() {
4507
+ if (!realRapier) return 0;
4508
+ const blocked = await seatedBodyRun(false);
4509
+ assert.equal(blocked.clamps, 100, 'the overlapping seat triggers a clamp every 50 ms over five measured seconds');
4510
+ assert.ok(blocked.body > .05, 'the held body repeatedly depenetrates and is corrected');
4511
+ assert.ok(blocked.camera > .05, 'the camera follows the actual body jitter');
4512
+ const clear = await seatedBodyRun(true);
4513
+ assert.equal(clear.clamps, 0, 'moving the crate in the fixture removes the clamp cycle');
4514
+ assert.ok(clear.body < 1e-8 && clear.camera < 1e-8, 'clear held body and its camera both stay still');
4515
+ return 2;
4516
+ }
4517
+
2074
4518
  export async function run() {
2075
4519
  const parts = {
2076
4520
  unchanged: unkeyedIsUnchanged(),
2077
4521
  cold: coldKeyless(),
2078
4522
  loads: acrossLoads(),
4523
+ lens: lensAcrossLoads(),
2079
4524
  offAndOn: offAndOn(),
2080
4525
  lockedTrip: lockedTrip(),
2081
4526
  locking: locking(),
@@ -2084,21 +4529,59 @@ export async function run() {
2084
4529
  ownInputOnly: ownInputOnly(),
2085
4530
  offByCallback: offByCallback(),
2086
4531
  blendHeld: blendHeld(),
4532
+ ownModel: ownModel(),
2087
4533
  walking: walking(),
2088
4534
  looking: looking(),
4535
+ startingValues: startingValues(),
2089
4536
  blocked: blocked(),
4537
+ grounded: grounded(),
4538
+ wideLens: wideLens(),
2090
4539
  facing: facing(),
2091
4540
  takenOver: takenOver(),
2092
4541
  roles: pointerRoles(),
2093
4542
  listeners: listeners(),
4543
+ mouseLock: await mouseLock(),
4544
+ shiftLock: await runShiftLockChecks(),
4545
+ orbitShot: await runOrbitShotChecks(),
2094
4546
  rapier: await fixedRay(),
4547
+ grazing: await grazing(),
4548
+ popClear: await popClear(),
4549
+ popSteady: await popSteady(),
4550
+ corners: await corners(),
4551
+ narrowGapStable: await narrowGapStable(),
4552
+ releaseEase: await releaseEase(),
4553
+ releaseBeside: await releaseBeside(),
4554
+ randomBoxes: await randomBoxes(),
4555
+ ballMisses: await ballMisses(),
4556
+ blendRelease: await blendRelease(),
4557
+ seatedJitter: await seatedJitter(),
4558
+ seatedBodyClamp: await seatedBodyClamp(),
2095
4559
  };
2096
4560
  const checks = Object.values(parts).reduce((a, b) => a + b, 0);
2097
4561
  return { checks, real: parts.rapier > 0 };
2098
4562
  }
2099
4563
 
2100
4564
  export const summary = ({ checks, real }) =>
2101
- `${checks} orbit-camera checks (${real ? 'castRayFixed on rapier itself' : 'rapier itself is not installed here, so castRayFixed was not run on it'})`;
4565
+ `${checks} orbit-camera checks (${real ? 'castRayFixed, castRayFixedNormal, castBallFixed and nearFixed on rapier itself' : 'rapier itself is not installed here, so the camera\'s queries were not run on it'})`;
4566
+
4567
+ // The world starts keyless; loading orbit creates extras before returning to
4568
+ // scene client code, and later loads preserve the registrations.
4569
+ {
4570
+ const runtime = new SceneRuntime(sceneData('off', { x: 0, y: 1, z: 0 }), [Player], {}, {});
4571
+ runtime.three = {};
4572
+ runtime.load(sceneData('off', { x: 0, y: 1, z: 0 }));
4573
+ assert.equal(runtime.three.ownModelWith, undefined);
4574
+ runtime.load(sceneData('orbit', { x: 0, y: 1, z: 0 }));
4575
+ assert.ok(runtime.three.ownModelWith instanceof Set);
4576
+ const extras = runtime.three.ownModelWith;
4577
+ const tag = new THREE.Object3D();
4578
+ extras.add(tag);
4579
+ for (const mode of ['off', 'orbit']) {
4580
+ runtime.load(sceneData(mode, { x: 0, y: 1, z: 0 }));
4581
+ assert.equal(runtime.three.ownModelWith, extras);
4582
+ assert.ok(extras.has(tag));
4583
+ }
4584
+ }
2102
4585
 
2103
4586
  if (import.meta.url === `file://${process.argv[1]}`) {
2104
4587
  console.log(`camera orbit: ${summary(await run())}`);