wallhammer-web 0.0.0-stage → 0.4.1

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 (408) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +92 -2
  3. package/dist/base/data.d.ts +67 -0
  4. package/dist/base/data.js +10 -0
  5. package/dist/base/destructible.d.ts +167 -0
  6. package/dist/base/destructible.js +47 -0
  7. package/dist/base/env-slot.d.ts +101 -0
  8. package/dist/base/env-slot.js +8 -0
  9. package/dist/base/frames.d.ts +138 -0
  10. package/dist/base/frames.js +459 -0
  11. package/dist/base/index.d.ts +21 -0
  12. package/dist/base/index.js +11 -0
  13. package/dist/base/mat34.d.ts +46 -0
  14. package/dist/base/mat34.js +173 -0
  15. package/dist/base/material.d.ts +87 -0
  16. package/dist/base/material.js +6 -0
  17. package/dist/base/math.d.ts +27 -0
  18. package/dist/base/math.js +60 -0
  19. package/dist/base/progress.d.ts +38 -0
  20. package/dist/base/progress.js +81 -0
  21. package/dist/base/rig.d.ts +177 -0
  22. package/dist/base/rig.js +97 -0
  23. package/dist/base/trig.d.ts +29 -0
  24. package/dist/base/trig.js +169 -0
  25. package/dist/base/up.d.ts +26 -0
  26. package/dist/base/up.js +40 -0
  27. package/dist/base/view.d.ts +128 -0
  28. package/dist/base/view.js +136 -0
  29. package/dist/camera/camera.d.ts +99 -0
  30. package/dist/camera/camera.js +228 -0
  31. package/dist/camera/follow.d.ts +120 -0
  32. package/dist/camera/follow.js +320 -0
  33. package/dist/camera/free.d.ts +153 -0
  34. package/dist/camera/free.js +359 -0
  35. package/dist/camera/index.d.ts +10 -0
  36. package/dist/camera/index.js +6 -0
  37. package/dist/camera/orbit.d.ts +93 -0
  38. package/dist/camera/orbit.js +261 -0
  39. package/dist/camera/path.d.ts +48 -0
  40. package/dist/camera/path.js +179 -0
  41. package/dist/core/ballistic.d.ts +66 -0
  42. package/dist/core/ballistic.js +104 -0
  43. package/dist/core/bodies.d.ts +77 -0
  44. package/dist/core/bodies.js +125 -0
  45. package/dist/core/clock.d.ts +37 -0
  46. package/dist/core/clock.js +87 -0
  47. package/dist/core/cover-fade.d.ts +14 -0
  48. package/dist/core/cover-fade.js +38 -0
  49. package/dist/core/index.d.ts +13 -0
  50. package/dist/core/index.js +8 -0
  51. package/dist/core/kepler.d.ts +74 -0
  52. package/dist/core/kepler.js +108 -0
  53. package/dist/core/level-fade.d.ts +66 -0
  54. package/dist/core/level-fade.js +123 -0
  55. package/dist/core/palette.d.ts +15 -0
  56. package/dist/core/palette.js +47 -0
  57. package/dist/env/atmosphere.d.ts +129 -0
  58. package/dist/env/atmosphere.js +707 -0
  59. package/dist/env/cloud-field.d.ts +44 -0
  60. package/dist/env/cloud-field.js +111 -0
  61. package/dist/env/environment.d.ts +217 -0
  62. package/dist/env/environment.js +441 -0
  63. package/dist/env/frame-block.d.ts +29 -0
  64. package/dist/env/frame-block.js +152 -0
  65. package/dist/env/glsl.d.ts +35 -0
  66. package/dist/env/glsl.js +246 -0
  67. package/dist/env/index.d.ts +13 -0
  68. package/dist/env/index.js +9 -0
  69. package/dist/env/sky.d.ts +48 -0
  70. package/dist/env/sky.js +227 -0
  71. package/dist/env/sun.d.ts +31 -0
  72. package/dist/env/sun.js +42 -0
  73. package/dist/gen-arch/build.d.ts +17 -0
  74. package/dist/gen-arch/build.js +414 -0
  75. package/dist/gen-arch/damage/damaged.d.ts +44 -0
  76. package/dist/gen-arch/damage/damaged.js +1119 -0
  77. package/dist/gen-arch/damage/fall-material.d.ts +10 -0
  78. package/dist/gen-arch/damage/fall-material.js +47 -0
  79. package/dist/gen-arch/damage/fall.d.ts +78 -0
  80. package/dist/gen-arch/damage/fall.js +797 -0
  81. package/dist/gen-arch/damage/rubble.d.ts +22 -0
  82. package/dist/gen-arch/damage/rubble.js +188 -0
  83. package/dist/gen-arch/index.d.ts +25 -0
  84. package/dist/gen-arch/index.js +16 -0
  85. package/dist/gen-arch/interior/interior-plan.d.ts +114 -0
  86. package/dist/gen-arch/interior/interior-plan.js +615 -0
  87. package/dist/gen-arch/interior/interior.d.ts +97 -0
  88. package/dist/gen-arch/interior/interior.js +966 -0
  89. package/dist/gen-arch/structure/building-shader.d.ts +25 -0
  90. package/dist/gen-arch/structure/building-shader.js +946 -0
  91. package/dist/gen-arch/structure/buildings.d.ts +248 -0
  92. package/dist/gen-arch/structure/buildings.js +294 -0
  93. package/dist/gen-arch/structure/dims.d.ts +77 -0
  94. package/dist/gen-arch/structure/dims.js +39 -0
  95. package/dist/gen-arch/structure/distant.d.ts +62 -0
  96. package/dist/gen-arch/structure/distant.js +316 -0
  97. package/dist/gen-arch/structure/env-slots.d.ts +18 -0
  98. package/dist/gen-arch/structure/env-slots.js +47 -0
  99. package/dist/gen-arch/structure/facade.d.ts +193 -0
  100. package/dist/gen-arch/structure/facade.js +159 -0
  101. package/dist/gen-arch/structure/parts.d.ts +31 -0
  102. package/dist/gen-arch/structure/parts.js +69 -0
  103. package/dist/gen-arch/structure/roof.d.ts +76 -0
  104. package/dist/gen-arch/structure/roof.js +568 -0
  105. package/dist/gen-arch/structure/structure-material.d.ts +23 -0
  106. package/dist/gen-arch/structure/structure-material.js +55 -0
  107. package/dist/gen-arch/structure/writer.d.ts +94 -0
  108. package/dist/gen-arch/structure/writer.js +195 -0
  109. package/dist/gen-core/cell.d.ts +138 -0
  110. package/dist/gen-core/cell.js +150 -0
  111. package/dist/gen-core/cube-sphere.d.ts +57 -0
  112. package/dist/gen-core/cube-sphere.js +159 -0
  113. package/dist/gen-core/field.d.ts +55 -0
  114. package/dist/gen-core/field.js +154 -0
  115. package/dist/gen-core/geometry.d.ts +31 -0
  116. package/dist/gen-core/geometry.js +231 -0
  117. package/dist/gen-core/hash.d.ts +18 -0
  118. package/dist/gen-core/hash.js +58 -0
  119. package/dist/gen-core/height-field.d.ts +33 -0
  120. package/dist/gen-core/height-field.js +137 -0
  121. package/dist/gen-core/index.d.ts +22 -0
  122. package/dist/gen-core/index.js +17 -0
  123. package/dist/gen-core/instance-cells.d.ts +37 -0
  124. package/dist/gen-core/instance-cells.js +72 -0
  125. package/dist/gen-core/near-scatter.d.ts +56 -0
  126. package/dist/gen-core/near-scatter.js +120 -0
  127. package/dist/gen-core/noise.d.ts +23 -0
  128. package/dist/gen-core/noise.js +72 -0
  129. package/dist/gen-core/occupancy.d.ts +21 -0
  130. package/dist/gen-core/occupancy.js +104 -0
  131. package/dist/gen-core/sphere-patch.d.ts +138 -0
  132. package/dist/gen-core/sphere-patch.js +544 -0
  133. package/dist/gen-core/strip-surface.d.ts +34 -0
  134. package/dist/gen-core/strip-surface.js +246 -0
  135. package/dist/gen-core/strip.d.ts +102 -0
  136. package/dist/gen-core/strip.js +817 -0
  137. package/dist/gen-ground/env-slots.d.ts +48 -0
  138. package/dist/gen-ground/env-slots.js +78 -0
  139. package/dist/gen-ground/ground.d.ts +78 -0
  140. package/dist/gen-ground/ground.js +208 -0
  141. package/dist/gen-ground/index.d.ts +9 -0
  142. package/dist/gen-ground/index.js +7 -0
  143. package/dist/gen-ground/markings.d.ts +46 -0
  144. package/dist/gen-ground/markings.js +124 -0
  145. package/dist/gen-ground/materials.d.ts +18 -0
  146. package/dist/gen-ground/materials.js +22 -0
  147. package/dist/gen-ground/terrain-shader.d.ts +5 -0
  148. package/dist/gen-ground/terrain-shader.js +151 -0
  149. package/dist/gen-mesh/bare-shapes.d.ts +194 -0
  150. package/dist/gen-mesh/bare-shapes.js +596 -0
  151. package/dist/gen-mesh/bisect-surface.d.ts +47 -0
  152. package/dist/gen-mesh/bisect-surface.js +261 -0
  153. package/dist/gen-mesh/box.d.ts +18 -0
  154. package/dist/gen-mesh/box.js +2 -0
  155. package/dist/gen-mesh/cell-morph-mesh.d.ts +52 -0
  156. package/dist/gen-mesh/cell-morph-mesh.js +258 -0
  157. package/dist/gen-mesh/cell-surface-mesh.d.ts +32 -0
  158. package/dist/gen-mesh/cell-surface-mesh.js +140 -0
  159. package/dist/gen-mesh/chunk-mesh.d.ts +25 -0
  160. package/dist/gen-mesh/chunk-mesh.js +112 -0
  161. package/dist/gen-mesh/drape-mesh.d.ts +36 -0
  162. package/dist/gen-mesh/drape-mesh.js +98 -0
  163. package/dist/gen-mesh/height-field-mesh.d.ts +14 -0
  164. package/dist/gen-mesh/height-field-mesh.js +98 -0
  165. package/dist/gen-mesh/index.d.ts +26 -0
  166. package/dist/gen-mesh/index.js +15 -0
  167. package/dist/gen-mesh/line-mesh.d.ts +25 -0
  168. package/dist/gen-mesh/line-mesh.js +62 -0
  169. package/dist/gen-mesh/mesh-builder.d.ts +115 -0
  170. package/dist/gen-mesh/mesh-builder.js +315 -0
  171. package/dist/gen-mesh/packed-mesh.d.ts +53 -0
  172. package/dist/gen-mesh/packed-mesh.js +205 -0
  173. package/dist/gen-mesh/prism-mesh.d.ts +33 -0
  174. package/dist/gen-mesh/prism-mesh.js +176 -0
  175. package/dist/gen-mesh/rig-mesh.d.ts +9 -0
  176. package/dist/gen-mesh/rig-mesh.js +135 -0
  177. package/dist/gen-mesh/strip-mesh.d.ts +45 -0
  178. package/dist/gen-mesh/strip-mesh.js +258 -0
  179. package/dist/gen-plan/drain.d.ts +58 -0
  180. package/dist/gen-plan/drain.js +270 -0
  181. package/dist/gen-plan/grid.d.ts +37 -0
  182. package/dist/gen-plan/grid.js +182 -0
  183. package/dist/gen-plan/horizon.d.ts +50 -0
  184. package/dist/gen-plan/horizon.js +185 -0
  185. package/dist/gen-plan/index.d.ts +15 -0
  186. package/dist/gen-plan/index.js +13 -0
  187. package/dist/gen-plan/line-tiles.d.ts +35 -0
  188. package/dist/gen-plan/line-tiles.js +190 -0
  189. package/dist/gen-plan/lines.d.ts +31 -0
  190. package/dist/gen-plan/lines.js +183 -0
  191. package/dist/gen-plan/plots.d.ts +40 -0
  192. package/dist/gen-plan/plots.js +282 -0
  193. package/dist/gen-plan/route.d.ts +55 -0
  194. package/dist/gen-plan/route.js +297 -0
  195. package/dist/gen-plan/sites.d.ts +32 -0
  196. package/dist/gen-plan/sites.js +209 -0
  197. package/dist/gen-tex/code-stamp.d.ts +31 -0
  198. package/dist/gen-tex/code-stamp.js +137 -0
  199. package/dist/gen-tex/index.d.ts +7 -0
  200. package/dist/gen-tex/index.js +5 -0
  201. package/dist/gen-tex/light-horizon.d.ts +47 -0
  202. package/dist/gen-tex/light-horizon.js +180 -0
  203. package/dist/gen-tex/textures.d.ts +8 -0
  204. package/dist/gen-tex/textures.js +49 -0
  205. package/dist/gen-tex/value-textures.d.ts +46 -0
  206. package/dist/gen-tex/value-textures.js +102 -0
  207. package/dist/gen-vegetation/env-slots.d.ts +20 -0
  208. package/dist/gen-vegetation/env-slots.js +29 -0
  209. package/dist/gen-vegetation/index.d.ts +8 -0
  210. package/dist/gen-vegetation/index.js +7 -0
  211. package/dist/gen-vegetation/materials.d.ts +7 -0
  212. package/dist/gen-vegetation/materials.js +17 -0
  213. package/dist/gen-vegetation/planting.d.ts +170 -0
  214. package/dist/gen-vegetation/planting.js +363 -0
  215. package/dist/gen-vegetation/tree-shader.d.ts +23 -0
  216. package/dist/gen-vegetation/tree-shader.js +229 -0
  217. package/dist/gen-vegetation/trees.d.ts +59 -0
  218. package/dist/gen-vegetation/trees.js +329 -0
  219. package/dist/gpu/device.d.ts +286 -0
  220. package/dist/gpu/device.js +1157 -0
  221. package/dist/gpu/gl.d.ts +134 -0
  222. package/dist/gpu/gl.js +276 -0
  223. package/dist/gpu/index.d.ts +4 -0
  224. package/dist/gpu/index.js +3 -0
  225. package/dist/index.d.ts +11 -0
  226. package/dist/index.js +13 -0
  227. package/dist/motion/graph.d.ts +244 -0
  228. package/dist/motion/graph.js +739 -0
  229. package/dist/motion/index.d.ts +8 -0
  230. package/dist/motion/index.js +8 -0
  231. package/dist/motion/pose-ops.d.ts +30 -0
  232. package/dist/motion/pose-ops.js +232 -0
  233. package/dist/motion/reach.d.ts +45 -0
  234. package/dist/motion/reach.js +264 -0
  235. package/dist/motion/skeleton.d.ts +49 -0
  236. package/dist/motion/skeleton.js +99 -0
  237. package/dist/platform/byte-store.d.ts +21 -0
  238. package/dist/platform/byte-store.js +137 -0
  239. package/dist/platform/canvas.d.ts +29 -0
  240. package/dist/platform/canvas.js +76 -0
  241. package/dist/platform/context-loss.d.ts +8 -0
  242. package/dist/platform/context-loss.js +17 -0
  243. package/dist/platform/free-input.d.ts +51 -0
  244. package/dist/platform/free-input.js +100 -0
  245. package/dist/platform/index.d.ts +18 -0
  246. package/dist/platform/index.js +10 -0
  247. package/dist/platform/input.d.ts +48 -0
  248. package/dist/platform/input.js +117 -0
  249. package/dist/platform/keys.d.ts +12 -0
  250. package/dist/platform/keys.js +29 -0
  251. package/dist/platform/loop.d.ts +41 -0
  252. package/dist/platform/loop.js +84 -0
  253. package/dist/platform/walk-input.d.ts +74 -0
  254. package/dist/platform/walk-input.js +226 -0
  255. package/dist/platform/worker.d.ts +51 -0
  256. package/dist/platform/worker.js +170 -0
  257. package/dist/render/bone-instances.d.ts +24 -0
  258. package/dist/render/bone-instances.js +74 -0
  259. package/dist/render/cells.d.ts +70 -0
  260. package/dist/render/cells.js +144 -0
  261. package/dist/render/glsl.d.ts +66 -0
  262. package/dist/render/glsl.js +173 -0
  263. package/dist/render/index.d.ts +26 -0
  264. package/dist/render/index.js +16 -0
  265. package/dist/render/instance-sets.d.ts +97 -0
  266. package/dist/render/instance-sets.js +241 -0
  267. package/dist/render/near-instances.d.ts +75 -0
  268. package/dist/render/near-instances.js +219 -0
  269. package/dist/render/particles.d.ts +63 -0
  270. package/dist/render/particles.js +215 -0
  271. package/dist/render/pieces.d.ts +57 -0
  272. package/dist/render/pieces.js +151 -0
  273. package/dist/render/point-lights.d.ts +97 -0
  274. package/dist/render/point-lights.js +243 -0
  275. package/dist/render/renderer.d.ts +447 -0
  276. package/dist/render/renderer.js +1100 -0
  277. package/dist/render/rig.d.ts +74 -0
  278. package/dist/render/rig.js +576 -0
  279. package/dist/render/shadow-areas.d.ts +49 -0
  280. package/dist/render/shadow-areas.js +125 -0
  281. package/dist/render/shadow-glsl.d.ts +12 -0
  282. package/dist/render/shadow-glsl.js +146 -0
  283. package/dist/render/transient.d.ts +61 -0
  284. package/dist/render/transient.js +213 -0
  285. package/dist/render/value-glsl.d.ts +17 -0
  286. package/dist/render/value-glsl.js +208 -0
  287. package/dist/render/value-layers.d.ts +180 -0
  288. package/dist/render/value-layers.js +333 -0
  289. package/dist/runtime/atmosphere.d.ts +37 -0
  290. package/dist/runtime/atmosphere.js +304 -0
  291. package/dist/runtime/cloud-shell.d.ts +29 -0
  292. package/dist/runtime/cloud-shell.js +158 -0
  293. package/dist/runtime/engine.d.ts +155 -0
  294. package/dist/runtime/engine.js +305 -0
  295. package/dist/runtime/environment-link.d.ts +22 -0
  296. package/dist/runtime/environment-link.js +49 -0
  297. package/dist/runtime/index.d.ts +13 -0
  298. package/dist/runtime/index.js +12 -0
  299. package/dist/runtime/precipitation-glsl.d.ts +2 -0
  300. package/dist/runtime/precipitation-glsl.js +70 -0
  301. package/dist/runtime/precipitation.d.ts +11 -0
  302. package/dist/runtime/precipitation.js +78 -0
  303. package/dist/runtime/sky.d.ts +30 -0
  304. package/dist/runtime/sky.js +114 -0
  305. package/dist/runtime/streaming.d.ts +245 -0
  306. package/dist/runtime/streaming.js +602 -0
  307. package/dist/sim/agenda.d.ts +167 -0
  308. package/dist/sim/agenda.js +425 -0
  309. package/dist/sim/bytes.d.ts +34 -0
  310. package/dist/sim/bytes.js +125 -0
  311. package/dist/sim/destruction/apply.d.ts +59 -0
  312. package/dist/sim/destruction/apply.js +243 -0
  313. package/dist/sim/destruction/cell-states.d.ts +54 -0
  314. package/dist/sim/destruction/cell-states.js +198 -0
  315. package/dist/sim/destruction/index.d.ts +11 -0
  316. package/dist/sim/destruction/index.js +10 -0
  317. package/dist/sim/destruction/int-geometry.d.ts +17 -0
  318. package/dist/sim/destruction/int-geometry.js +131 -0
  319. package/dist/sim/destruction/pick.d.ts +13 -0
  320. package/dist/sim/destruction/pick.js +59 -0
  321. package/dist/sim/destruction/rubble.d.ts +8 -0
  322. package/dist/sim/destruction/rubble.js +159 -0
  323. package/dist/sim/destruction/state.d.ts +15 -0
  324. package/dist/sim/destruction/state.js +83 -0
  325. package/dist/sim/destruction/structure.d.ts +30 -0
  326. package/dist/sim/destruction/structure.js +139 -0
  327. package/dist/sim/events.d.ts +37 -0
  328. package/dist/sim/events.js +106 -0
  329. package/dist/sim/fixed.d.ts +21 -0
  330. package/dist/sim/fixed.js +64 -0
  331. package/dist/sim/flow-probe.d.ts +58 -0
  332. package/dist/sim/flow-probe.js +158 -0
  333. package/dist/sim/flow.d.ts +257 -0
  334. package/dist/sim/flow.js +967 -0
  335. package/dist/sim/index.d.ts +28 -0
  336. package/dist/sim/index.js +20 -0
  337. package/dist/sim/interlock.d.ts +47 -0
  338. package/dist/sim/interlock.js +252 -0
  339. package/dist/sim/movers.d.ts +228 -0
  340. package/dist/sim/movers.js +1083 -0
  341. package/dist/sim/nav.d.ts +72 -0
  342. package/dist/sim/nav.js +292 -0
  343. package/dist/sim/paths.d.ts +80 -0
  344. package/dist/sim/paths.js +197 -0
  345. package/dist/sim/regions.d.ts +87 -0
  346. package/dist/sim/regions.js +517 -0
  347. package/dist/sim/simulation.d.ts +114 -0
  348. package/dist/sim/simulation.js +291 -0
  349. package/dist/sim/states.d.ts +23 -0
  350. package/dist/sim/states.js +54 -0
  351. package/dist/sim/table.d.ts +49 -0
  352. package/dist/sim/table.js +126 -0
  353. package/dist/sim/zones.d.ts +11 -0
  354. package/dist/sim/zones.js +196 -0
  355. package/dist/tools/collision-lines.d.ts +12 -0
  356. package/dist/tools/collision-lines.js +50 -0
  357. package/dist/tools/data-view-glsl.d.ts +3 -0
  358. package/dist/tools/data-view-glsl.js +63 -0
  359. package/dist/tools/data-view-layers.d.ts +20 -0
  360. package/dist/tools/data-view-layers.js +60 -0
  361. package/dist/tools/debug-view.d.ts +30 -0
  362. package/dist/tools/debug-view.js +4 -0
  363. package/dist/tools/index.d.ts +10 -0
  364. package/dist/tools/index.js +7 -0
  365. package/dist/tools/mesh-checks.d.ts +67 -0
  366. package/dist/tools/mesh-checks.js +188 -0
  367. package/dist/tools/profile.d.ts +85 -0
  368. package/dist/tools/profile.js +173 -0
  369. package/dist/world/cell-cache.d.ts +32 -0
  370. package/dist/world/cell-cache.js +60 -0
  371. package/dist/world/cell-format.d.ts +25 -0
  372. package/dist/world/cell-format.js +232 -0
  373. package/dist/world/collide.d.ts +192 -0
  374. package/dist/world/collide.js +822 -0
  375. package/dist/world/index.d.ts +16 -0
  376. package/dist/world/index.js +12 -0
  377. package/dist/world/mesh-solids.d.ts +48 -0
  378. package/dist/world/mesh-solids.js +169 -0
  379. package/dist/world/pick.d.ts +34 -0
  380. package/dist/world/pick.js +177 -0
  381. package/dist/world/providers.d.ts +66 -0
  382. package/dist/world/providers.js +83 -0
  383. package/dist/world/sphere.d.ts +69 -0
  384. package/dist/world/sphere.js +271 -0
  385. package/dist/world/streaming.d.ts +288 -0
  386. package/dist/world/streaming.js +801 -0
  387. package/dist/world/walker.d.ts +145 -0
  388. package/dist/world/walker.js +502 -0
  389. package/docs/architecture.md +111 -0
  390. package/docs/cameras.md +302 -0
  391. package/docs/concepts.md +123 -0
  392. package/docs/destruction.md +127 -0
  393. package/docs/frames.md +199 -0
  394. package/docs/generators.md +575 -0
  395. package/docs/getting-started.md +123 -0
  396. package/docs/headless.md +50 -0
  397. package/docs/motion.md +160 -0
  398. package/docs/planet.md +152 -0
  399. package/docs/recipes.md +521 -0
  400. package/docs/reference.md +364 -0
  401. package/docs/rendering.md +823 -0
  402. package/docs/rigs.md +203 -0
  403. package/docs/simulation.md +235 -0
  404. package/docs/streaming.md +590 -0
  405. package/docs/system.md +166 -0
  406. package/docs/tools.md +175 -0
  407. package/docs/walking.md +262 -0
  408. package/package.json +131 -3
@@ -0,0 +1,801 @@
1
+ // World streaming, the decision part (Wallhammer Zero ARCHITECTURE "One frame → Streaming" and the research report
2
+ // "No Man's Sky: generation and streaming", sections on cell states, tickets and epochs). Pure logic: it runs in Node
3
+ // without a GPU, reads no clock and decides only from its inputs, so the same camera path always gives the same
4
+ // sequence of requests. The execution part (workers, uploads, time budgets) lives in `runtime` and only decides *when*
5
+ // work happens, never *what*.
6
+ //
7
+ // - Cells form a quadtree over the world shape. The level of a cell is its level of detail: a coarse parent covers
8
+ // what its four children cover, with the same number of vertices on four times the area.
9
+ // - A ticket is a reason to load (the camera, a predicted point ahead of it, a teleport target, a tool). The ticket
10
+ // level of a cell is `min over tickets (base + distance / cell edge)`. Roots are wanted while it is at most
11
+ // `rootRange`; a cell is split into its children while it is at most `splitLevel`. Because the distance is divided
12
+ // by the edge, every quadtree level gets its own ring around the camera, in proportion to its size.
13
+ // - Cell states follow the design: NONE → MESHED (one job builds layout, content and meshes) → RESIDENT (uploaded).
14
+ // MACRO, LAYOUT and CONTENT pass inside the job; ACTIVE (physics, AI) does not exist in this engine.
15
+ // - Cancelling: every request carries the cell's epoch. When a cell stops being wanted while its job runs, the epoch
16
+ // is raised and the job is aborted; a result with an old epoch is dropped as stale.
17
+ // - A cell keeps its GPU data while its parent's ticket level stays within `splitLevel + hysteresis` (no flicker at a
18
+ // ring edge). Outside it, GPU data are released and the CPU data stay as a cache until the memory budget needs room;
19
+ // then the cells wanted longest ago and farthest away go first.
20
+ // - Drawing: the cover of the wanted quadtree. A split cell is replaced by its children only when all four are
21
+ // RESIDENT, so the parent stays visible until the children arrive: no holes, no overlap, no popping to empty.
22
+ // - The world shape answers every question of place: which coarsest cells lie near a ticket (`cellsNear`), how far a
23
+ // cell is (`distanceM`), where its middle is (`center`) and which way is up at a ticket (`upAt`). Nothing here
24
+ // assumes a plane.
25
+ // - Optional, off by default: selection by screen-space error (`screenError`). The split distance then follows from
26
+ // the viewport and a tolerance in pixels instead of `splitLevel`, a cell is never split before it is loaded, a cell
27
+ // whose measured error is too small to see is not split at all, and a budget of cells lowers the detail as a whole
28
+ // when the plan would not fit. Jobs for cells in front of a ticket's direction start first.
29
+ // - `morphRange` gives, per level, the distances between which cells of that level blend into their parent's shape
30
+ // (see gen-mesh, cell morph mesh). It follows from the split distance alone, so the blend and the choice of levels
31
+ // cannot drift apart.
32
+ // - `refresh` marks the content of cells as out of date (their source changed, for example edits of the content).
33
+ // A job in flight is cancelled and requested again, a cell kept off the GPU is forgotten, and a cell on the GPU
34
+ // stays drawn with its old content while its new content is built ahead of every other request; the execution
35
+ // part swaps the GPU data when it arrives (`complete` leaves such a cell RESIDENT, then `swapped`). Out-of-date
36
+ // content never goes onto the GPU again: a refreshing cell that leaves the GPU first is forgotten. Without a call
37
+ // of `refresh` nothing here behaves differently.
38
+ import { cellKey, compareCells } from '../gen-core/cell.js';
39
+ /** Cell states of the design. MACRO, LAYOUT and CONTENT are passed inside one job here; ACTIVE is not used. */
40
+ export const CELL_STATES = ['NONE', 'MACRO', 'LAYOUT', 'CONTENT', 'MESHED', 'RESIDENT', 'ACTIVE'];
41
+ const RANK = { NONE: 0, MACRO: 1, LAYOUT: 2, CONTENT: 3, MESHED: 4, RESIDENT: 5, ACTIVE: 6 };
42
+ /** Pixels that one radian covers at the middle of a perspective view: `viewportHeightPx / (2 · tan(fovY / 2))`. */
43
+ export function pixelsPerRadian(viewportHeightPx, fovYRad) {
44
+ return viewportHeightPx / (2 * Math.tan(fovYRad / 2));
45
+ }
46
+ export const DEFAULT_STREAMING = {
47
+ rootLevel: 4,
48
+ leafLevel: 8,
49
+ rootRange: 2,
50
+ splitLevel: 1,
51
+ prefetch: 0.5,
52
+ hysteresis: 0.75,
53
+ maxInFlight: 8,
54
+ memoryBudgetBytes: 128 * 1024 * 1024,
55
+ };
56
+ /** Most steps the budget of cells may lower the detail by (each step divides the split distance by 2^¼). */
57
+ const MAX_DETAIL_STEPS = 16;
58
+ /** Detail comes back one step when the finer plan would use at most this share of the budget. */
59
+ const DETAIL_BACK_SHARE = 0.85;
60
+ /** The blend into the parent's shape takes at least this share of the distance at which the parent is split. */
61
+ const MORPH_MIN_SHARE = 0.15;
62
+ export class StreamingManager {
63
+ config;
64
+ cells = new Map();
65
+ tickets = [];
66
+ plan = { wanted: new Map(), prefetch: new Map(), split: new Set(), roots: [], levels: new Map() };
67
+ drawnList = [];
68
+ holes = 0;
69
+ stepNo = 0;
70
+ /** Source of epochs. World-wide and never reused, so a result from before a cell was forgotten can never match. */
71
+ epochSeq = 0;
72
+ totals = { requested: 0, completed: 0, cancelled: 0, stale: 0, failed: 0, evicted: 0 };
73
+ /** Steps the budget of cells has lowered the detail by (selection by screen-space error only). */
74
+ detailStep = 0;
75
+ /** A cell changed state since the last plan and the plan depends on states (selection by screen-space error). */
76
+ planStale = false;
77
+ /** Every request issued, as `step:key`, for determinism checks. Cleared by `clearLog`. */
78
+ log = [];
79
+ /** Cancels and evictions `refresh` decided between steps; handed out with the next `update`. */
80
+ pendingCancels = [];
81
+ pendingEvictions = [];
82
+ refreshTotal = 0;
83
+ constructor(config) {
84
+ if (config.leafLevel < config.rootLevel)
85
+ throw new Error('leafLevel must not be coarser than rootLevel');
86
+ this.config = config;
87
+ }
88
+ /** Ticket level of a cell: the minimum over tickets of base + distance / edge. */
89
+ ticketLevel(cell, tickets = this.tickets) {
90
+ const shape = this.config.shape;
91
+ const edge = shape.edgeM(cell.level);
92
+ let best = Infinity;
93
+ for (const t of tickets) {
94
+ const d = shape.distanceM(cell, t.center);
95
+ const a = t.altitude ?? 0;
96
+ const l = t.base + Math.sqrt(d * d + a * a) / edge;
97
+ if (l < best)
98
+ best = l;
99
+ }
100
+ return best;
101
+ }
102
+ /**
103
+ * The ticket the image is drawn for: the one with the lowest base (the first by id among equals), or null without
104
+ * tickets. A ticket that only preloads counts only when there is no other. The blend between levels is measured
105
+ * from it.
106
+ */
107
+ viewer() {
108
+ let best = null;
109
+ for (const t of this.tickets) {
110
+ if (!best)
111
+ best = t;
112
+ else if (!best.preload !== !t.preload)
113
+ best = best.preload ? t : best;
114
+ else if (t.base < best.base)
115
+ best = t;
116
+ }
117
+ return best;
118
+ }
119
+ /**
120
+ * Split distance of a ticket in cell edges: a cell is replaced by its children while its ticket level is at most
121
+ * this. `splitLevel`, or with selection by screen-space error the distance at which the error covers the tolerance.
122
+ */
123
+ splitDistance(t) {
124
+ const se = this.config.screenError;
125
+ if (!se)
126
+ return this.config.splitLevel;
127
+ return ((se.errorPerEdge * (t.pixelsPerRadian ?? se.pixelsPerRadian)) / se.maxErrorPx) * this.detailScale(this.detailStep);
128
+ }
129
+ /**
130
+ * Distances from the viewer between which a cell of `level` blends from its own shape (at `startM` and nearer) into
131
+ * its parent's (at `endM` and farther), in the metric of the ticket level: distance along the surface combined with
132
+ * the viewer's altitude. `endM` is where the parent stops being split, so a cell that has just replaced its parent
133
+ * shows the parent's shape. Null when there is nothing to blend into (the coarsest level, no viewer).
134
+ *
135
+ * The blend is free of jumps when the split distance is at least 2.02 edges: a cell must be back in its own shape
136
+ * over its whole footprint (√2 edges across) before it is split, and the blend still needs 15 % of the way to run.
137
+ * Below that the blend is squeezed into the last 15 % and small steps remain, which the skirt of the cell covers.
138
+ *
139
+ * The ranges assume a parent that is split at the full split distance. A parent whose measured error is smaller is
140
+ * split nearer (selection by screen-space error), where its children are already in their own shape: they replace
141
+ * it with a step of up to the tolerance on the screen. Content that must not show that step reports the full error.
142
+ */
143
+ morphRange(level) {
144
+ const t = this.viewer();
145
+ if (!t || level <= this.config.rootLevel || level > this.config.leafLevel)
146
+ return null;
147
+ const split = this.splitDistance(t) - t.base;
148
+ if (!(split > 0))
149
+ return null;
150
+ const edge = this.config.shape.edgeM(level);
151
+ const endM = 2 * split * edge;
152
+ const startM = Math.min((split + Math.SQRT2) * edge, (1 - MORPH_MIN_SHARE) * endM);
153
+ return { startM, endM };
154
+ }
155
+ /** Decides what is wanted for the given tickets, then returns the work to do. One call per frame (or step). */
156
+ update(tickets) {
157
+ this.stepNo++;
158
+ this.tickets = [...tickets].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
159
+ const plan = this.config.screenError ? this.planByScreenError(this.config.screenError) : this.planCells();
160
+ this.plan = plan;
161
+ this.planStale = false;
162
+ const cfg = this.config;
163
+ const actions = { requests: [], cancels: [], uploads: [], releases: [], evictions: [] };
164
+ if (this.pendingCancels.length > 0 || this.pendingEvictions.length > 0) {
165
+ actions.cancels.push(...this.pendingCancels);
166
+ actions.evictions.push(...this.pendingEvictions);
167
+ this.pendingCancels = [];
168
+ this.pendingEvictions = [];
169
+ }
170
+ // Records for every wanted or prefetched cell.
171
+ for (const [key, cell] of [...plan.wanted, ...plan.prefetch]) {
172
+ let r = this.cells.get(key);
173
+ if (!r) {
174
+ r = { cell, key, state: 'NONE', want: 'none', epoch: 0, inFlight: false, cpuBytes: 0, gpuBytes: 0, lastWanted: 0, level: 0, failures: 0, retryAt: 0 };
175
+ this.cells.set(key, r);
176
+ }
177
+ }
178
+ // What each tracked cell is wanted for now.
179
+ const records = this.sortedRecords();
180
+ for (const r of records) {
181
+ r.level = plan.levels.get(r.key) ?? this.planLevel(r.cell);
182
+ if (plan.wanted.has(r.key))
183
+ r.want = 'resident';
184
+ else if (plan.prefetch.has(r.key))
185
+ r.want = 'meshed';
186
+ else
187
+ r.want = this.withinKeepBand(r.cell) ? 'keep' : 'none';
188
+ if (r.want === 'resident' || r.want === 'meshed')
189
+ r.lastWanted = this.stepNo;
190
+ // Out-of-date content that is no longer wanted on the screen is forgotten, never kept for later.
191
+ if (r.refresh && r.want !== 'resident')
192
+ this.forgetRefreshing(r, actions.cancels, actions.releases, actions.evictions);
193
+ if (r.want === 'none') {
194
+ if (r.inFlight) {
195
+ // Stale work: raise the epoch, abort the job; its result will not be accepted.
196
+ actions.cancels.push({ cell: r.cell, key: r.key, epoch: r.epoch });
197
+ r.epoch = ++this.epochSeq;
198
+ r.inFlight = false;
199
+ this.totals.cancelled++;
200
+ }
201
+ if (r.state === 'RESIDENT') {
202
+ actions.releases.push(r.cell);
203
+ r.state = 'MESHED';
204
+ r.gpuBytes = 0;
205
+ }
206
+ }
207
+ }
208
+ // New requests, most urgent first, up to the in-flight limit.
209
+ const inFlight = records.filter((r) => r.inFlight).length;
210
+ const candidates = records.filter((r) => (r.want === 'resident' || r.want === 'meshed') && RANK[r.state] < RANK.MESHED && !r.inFlight && r.retryAt <= this.stepNo);
211
+ const keyed = candidates.map((r) => ({ r, k: this.priority(r) }));
212
+ keyed.sort((a, b) => comparePriority(a.k, b.k) || compareCells(a.r.cell, b.r.cell));
213
+ // Cells drawn with out-of-date content go ahead of every other candidate, in cell order.
214
+ const refreshing = records.filter((r) => r.refresh && r.state === 'RESIDENT' && !r.inFlight && r.retryAt <= this.stepNo);
215
+ const order = refreshing.length > 0 ? [...refreshing, ...keyed.map((x) => x.r)] : keyed.map((x) => x.r);
216
+ const free = Math.max(0, cfg.maxInFlight - inFlight);
217
+ for (const r of order.slice(0, free)) {
218
+ r.inFlight = true;
219
+ r.epoch = ++this.epochSeq;
220
+ actions.requests.push({ cell: r.cell, key: r.key, epoch: r.epoch });
221
+ this.log.push(`${this.stepNo}:${r.key}`);
222
+ this.totals.requested++;
223
+ }
224
+ // Uploads: MESHED cells wanted on the GPU, coarse-first like the requests.
225
+ const up = records.filter((r) => r.want === 'resident' && r.state === 'MESHED').map((r) => ({ r, k: this.priority(r) }));
226
+ up.sort((a, b) => comparePriority(a.k, b.k) || compareCells(a.r.cell, b.r.cell));
227
+ actions.uploads = up.map((u) => u.r.cell);
228
+ // Memory budget: forget unwanted cells first, the ones wanted longest ago and farthest away before others.
229
+ this.enforceBudget(actions);
230
+ if (cfg.gpuBudgetBytes !== undefined)
231
+ this.enforceGpuCeiling(actions, cfg.gpuBudgetBytes);
232
+ this.computeCover();
233
+ return actions;
234
+ }
235
+ /**
236
+ * A job finished. Returns false when the result is stale (old epoch) or nobody waits for it any more. `errorM` is
237
+ * the content's measured error (`CellContent.error`), used by selection by screen-space error.
238
+ */
239
+ complete(req, cpuBytes, errorM) {
240
+ const r = this.cells.get(req.key);
241
+ if (!r || r.epoch !== req.epoch || !r.inFlight) {
242
+ this.totals.stale++;
243
+ return false;
244
+ }
245
+ r.inFlight = false;
246
+ // New content for a cell drawn with out-of-date content: it stays RESIDENT, the execution part swaps its GPU data.
247
+ if (r.refresh && r.state === 'RESIDENT')
248
+ r.refresh = false;
249
+ else
250
+ r.state = 'MESHED';
251
+ r.cpuBytes = cpuBytes;
252
+ r.failures = 0;
253
+ if (errorM !== undefined && errorM >= 0)
254
+ r.errorM = errorM;
255
+ else
256
+ delete r.errorM;
257
+ if (this.config.screenError)
258
+ this.planStale = true;
259
+ this.totals.completed++;
260
+ return true;
261
+ }
262
+ /** A job failed or was aborted. A cell that keeps failing is retried no sooner than its next request round. */
263
+ fail(req) {
264
+ const r = this.cells.get(req.key);
265
+ if (!r || r.epoch !== req.epoch)
266
+ return;
267
+ r.inFlight = false;
268
+ r.failures++;
269
+ r.retryAt = this.stepNo + Math.min(600, 30 * 2 ** Math.min(r.failures, 5));
270
+ this.totals.failed++;
271
+ }
272
+ /** The execution part uploaded a MESHED cell. */
273
+ resident(cell, gpuBytes) {
274
+ const r = this.cells.get(cellKey(cell));
275
+ if (!r || r.state !== 'MESHED')
276
+ return;
277
+ r.state = 'RESIDENT';
278
+ r.gpuBytes = gpuBytes;
279
+ this.computeCover();
280
+ }
281
+ /**
282
+ * The execution part swapped the GPU data of a RESIDENT cell for the new content `complete` accepted after a
283
+ * `refresh`. The cell stays RESIDENT and drawn throughout.
284
+ */
285
+ swapped(cell, gpuBytes) {
286
+ const r = this.cells.get(cellKey(cell));
287
+ if (!r || r.state !== 'RESIDENT')
288
+ return;
289
+ r.gpuBytes = gpuBytes;
290
+ }
291
+ /**
292
+ * The content of these cells is out of date. Returns how many tracked cells it touched:
293
+ * - a job in flight is cancelled (its late result is stale) and the cell is requested again by the usual rules;
294
+ * - a MESHED cell is forgotten (state NONE, listed in the next step's `evictions`) and built again when wanted;
295
+ * - a RESIDENT cell stays drawn with its old content; the next step requests it ahead of every other candidate
296
+ * (within `maxInFlight`), and when its new content arrives `complete` leaves it RESIDENT for the swap. A second
297
+ * call during a refresh restarts the job.
298
+ * Cells that are not tracked, or NONE with no job, are left alone.
299
+ */
300
+ refresh(cells) {
301
+ const list = [...cells].sort(compareCells);
302
+ let touched = 0;
303
+ let last = '';
304
+ for (const c of list) {
305
+ const key = cellKey(c);
306
+ if (key === last)
307
+ continue;
308
+ last = key;
309
+ const r = this.cells.get(key);
310
+ if (!r)
311
+ continue;
312
+ const wasInFlight = r.inFlight;
313
+ if (r.inFlight) {
314
+ this.pendingCancels.push({ cell: r.cell, key: r.key, epoch: r.epoch });
315
+ r.epoch = ++this.epochSeq;
316
+ r.inFlight = false;
317
+ this.totals.cancelled++;
318
+ }
319
+ if (r.state === 'RESIDENT') {
320
+ r.refresh = true;
321
+ touched++;
322
+ }
323
+ else if (r.state === 'MESHED') {
324
+ this.pendingEvictions.push(r.cell);
325
+ r.state = 'NONE';
326
+ r.cpuBytes = 0;
327
+ delete r.errorM;
328
+ if (this.config.screenError)
329
+ this.planStale = true;
330
+ touched++;
331
+ }
332
+ else if (wasInFlight)
333
+ touched++;
334
+ }
335
+ this.refreshTotal += touched;
336
+ return touched;
337
+ }
338
+ /** Cells drawn with out-of-date content that wait for their new content, and all cells `refresh` has touched. */
339
+ refreshes() {
340
+ let pending = 0;
341
+ for (const r of this.cells.values())
342
+ if (r.refresh)
343
+ pending++;
344
+ return { pending, total: this.refreshTotal };
345
+ }
346
+ /** State of a cell (NONE when it is not tracked). */
347
+ state(cell) {
348
+ return this.cells.get(cellKey(cell))?.state ?? 'NONE';
349
+ }
350
+ /** Cells to draw this frame: the cover of the wanted quadtree, parents standing in for children not yet resident. */
351
+ drawn() {
352
+ return this.drawnList;
353
+ }
354
+ /** True when every wanted cell is RESIDENT: the image is complete and depends only on the tickets. */
355
+ get settled() {
356
+ if (this.planStale)
357
+ return false;
358
+ for (const key of this.plan.wanted.keys()) {
359
+ const r = this.cells.get(key);
360
+ if (r?.state !== 'RESIDENT' || r.refresh)
361
+ return false;
362
+ }
363
+ return this.plan.wanted.size > 0;
364
+ }
365
+ /**
366
+ * True when a cell was loaded since the last `update` and the next one may therefore want more (selection by
367
+ * screen-space error descends only below loaded cells). The caller should run another step.
368
+ */
369
+ get stale() {
370
+ return this.planStale;
371
+ }
372
+ /** Wanted cells (target RESIDENT), in a deterministic order. */
373
+ wanted() {
374
+ return [...this.plan.wanted.values()].sort(compareCells);
375
+ }
376
+ counters() {
377
+ const states = Object.fromEntries(CELL_STATES.map((s) => [s, 0]));
378
+ let cpu = 0;
379
+ let gpu = 0;
380
+ let inFlight = 0;
381
+ let queued = 0;
382
+ for (const r of this.cells.values()) {
383
+ states[r.state]++;
384
+ cpu += r.cpuBytes;
385
+ gpu += r.gpuBytes;
386
+ if (r.inFlight)
387
+ inFlight++;
388
+ else if ((r.want === 'resident' || r.want === 'meshed') && RANK[r.state] < RANK.MESHED)
389
+ queued++;
390
+ }
391
+ return {
392
+ step: this.stepNo,
393
+ states,
394
+ inFlight,
395
+ queued,
396
+ wanted: this.plan.wanted.size,
397
+ drawn: this.drawnList.length,
398
+ holes: this.holes,
399
+ cpuBytes: cpu,
400
+ gpuBytes: gpu,
401
+ ...this.totals,
402
+ settled: this.settled,
403
+ detail: this.config.screenError ? this.detailScale(this.detailStep) : 1,
404
+ };
405
+ }
406
+ clearLog() {
407
+ this.log.length = 0;
408
+ }
409
+ // --- internals ---------------------------------------------------------------------------------------------------
410
+ sortedRecords() {
411
+ return [...this.cells.values()].sort((a, b) => compareCells(a.cell, b.cell));
412
+ }
413
+ /** The wanted quadtree: roots near the tickets, split while the ticket level allows it. */
414
+ planCells() {
415
+ const cfg = this.config;
416
+ const shape = cfg.shape;
417
+ const plan = { wanted: new Map(), prefetch: new Map(), split: new Set(), roots: [], levels: new Map() };
418
+ plan.roots = this.planRoots();
419
+ const visit = (c, prefetchOnly) => {
420
+ const key = cellKey(c);
421
+ const level = this.ticketLevel(c);
422
+ plan.levels.set(key, level);
423
+ if (prefetchOnly)
424
+ plan.prefetch.set(key, c);
425
+ else
426
+ plan.wanted.set(key, c);
427
+ if (c.level >= cfg.leafLevel)
428
+ return;
429
+ const split = !prefetchOnly && level <= cfg.splitLevel;
430
+ if (split)
431
+ plan.split.add(key);
432
+ if (split || level <= cfg.splitLevel + cfg.prefetch)
433
+ for (const ch of shape.children(c))
434
+ visit(ch, !split);
435
+ };
436
+ for (const r of plan.roots)
437
+ visit(r, false);
438
+ // A cell wanted through one parent is not also a prefetch.
439
+ for (const k of plan.wanted.keys())
440
+ plan.prefetch.delete(k);
441
+ return plan;
442
+ }
443
+ /** The coarsest wanted cells: those the shape reports near a ticket whose ticket level is within `rootRange`. */
444
+ planRoots() {
445
+ const cfg = this.config;
446
+ const shape = cfg.shape;
447
+ const rootEdge = shape.edgeM(cfg.rootLevel);
448
+ const roots = new Map();
449
+ for (const t of this.tickets) {
450
+ const reach = Math.max(0, cfg.rootRange - t.base) * rootEdge;
451
+ for (const c of shape.cellsNear(t.center, reach, cfg.rootLevel)) {
452
+ if (cfg.face !== undefined && c.face !== cfg.face)
453
+ continue;
454
+ const key = cellKey(c);
455
+ if (!roots.has(key) && this.ticketLevel(c) <= cfg.rootRange)
456
+ roots.set(key, c);
457
+ }
458
+ }
459
+ return [...roots.values()].sort(compareCells);
460
+ }
461
+ /** Share of the full split distance after the budget lowered the detail by `step` steps. */
462
+ detailScale(step) {
463
+ return 2 ** (-step / 4);
464
+ }
465
+ /**
466
+ * Ticket level of a cell divided by the ticket's split distance, the minimum over tickets: at most 1 where the cell
467
+ * is close enough to be split. `scale` is the share of the full split distance in use. `preload` picks the tickets:
468
+ * all of them (undefined), only those that load without changing the image (true) or only the others (false).
469
+ */
470
+ relativeLevel(cell, se, scale, preload) {
471
+ const shape = this.config.shape;
472
+ const edge = shape.edgeM(cell.level);
473
+ let best = Infinity;
474
+ for (const t of this.tickets) {
475
+ if (preload !== undefined && (t.preload ?? false) !== preload)
476
+ continue;
477
+ const split = ((se.errorPerEdge * (t.pixelsPerRadian ?? se.pixelsPerRadian)) / se.maxErrorPx) * scale;
478
+ if (!(split > 0))
479
+ continue;
480
+ const d = shape.distanceM(cell, t.center);
481
+ const a = t.altitude ?? 0;
482
+ const l = (t.base + Math.sqrt(d * d + a * a) / edge) / split;
483
+ if (l < best)
484
+ best = l;
485
+ }
486
+ return best;
487
+ }
488
+ /**
489
+ * Share of the split distance at which a loaded cell is really split: 1 without a measured error, less when the
490
+ * measured error is smaller than the assumed one (a flat cell is split later, a cell without error never).
491
+ */
492
+ errorShare(cell, se) {
493
+ const e = this.cells.get(cellKey(cell))?.errorM;
494
+ if (e === undefined)
495
+ return 1;
496
+ const edge = this.config.shape.edgeM(cell.level);
497
+ return Math.min(1, Math.max(e, (se.minErrorPerEdge ?? 0) * edge) / (se.errorPerEdge * edge));
498
+ }
499
+ /** The level a record is ordered by when the plan does not list it. */
500
+ planLevel(cell) {
501
+ const se = this.config.screenError;
502
+ return se ? this.relativeLevel(cell, se, this.detailScale(this.detailStep)) : this.ticketLevel(cell);
503
+ }
504
+ /**
505
+ * The wanted quadtree by screen-space error, within the budget of cells. Lowers the detail step by step while the
506
+ * plan is over the budget and raises it again once the next finer plan fits with room to spare.
507
+ */
508
+ planByScreenError(se) {
509
+ const budget = se.maxCells ?? Infinity;
510
+ let step = this.detailStep;
511
+ let plan = null;
512
+ if (step > 0) {
513
+ const finer = this.planAtDetail(se, step - 1);
514
+ if (finer.wanted.size <= budget * DETAIL_BACK_SHARE) {
515
+ step--;
516
+ plan = finer;
517
+ }
518
+ }
519
+ plan ??= this.planAtDetail(se, step);
520
+ while (plan.wanted.size > budget && step < MAX_DETAIL_STEPS)
521
+ plan = this.planAtDetail(se, ++step);
522
+ this.detailStep = step;
523
+ return plan;
524
+ }
525
+ planAtDetail(se, step) {
526
+ const cfg = this.config;
527
+ const shape = cfg.shape;
528
+ const scale = this.detailScale(step);
529
+ const plan = { wanted: new Map(), prefetch: new Map(), split: new Set(), roots: this.planRoots(), levels: new Map() };
530
+ const ahead = 1 + cfg.prefetch / cfg.splitLevel;
531
+ const preloading = this.tickets.some((t) => t.preload);
532
+ const visit = (c, prefetchOnly) => {
533
+ const key = cellKey(c);
534
+ // What is drawn follows the tickets that are not preloading; a preloading ticket fetches the cells it would split.
535
+ const level = this.relativeLevel(c, se, scale, false);
536
+ const fetch = preloading ? this.relativeLevel(c, se, scale, true) : Infinity;
537
+ plan.levels.set(key, Math.min(level, fetch));
538
+ if (prefetchOnly)
539
+ plan.prefetch.set(key, c);
540
+ else
541
+ plan.wanted.set(key, c);
542
+ if (c.level >= cfg.leafLevel)
543
+ return;
544
+ // Never descend below a cell that is not loaded: until it is, nothing could stand in for its children on the
545
+ // screen, and its measured error is not known.
546
+ const r = this.cells.get(key);
547
+ if (!r || RANK[r.state] < RANK.MESHED)
548
+ return;
549
+ const share = this.errorShare(c, se);
550
+ const split = !prefetchOnly && level <= share;
551
+ if (split)
552
+ plan.split.add(key);
553
+ if (split || level <= share * ahead || fetch <= share)
554
+ for (const ch of shape.children(c))
555
+ visit(ch, !split);
556
+ };
557
+ for (const r of plan.roots)
558
+ visit(r, false);
559
+ for (const k of plan.wanted.keys())
560
+ plan.prefetch.delete(k);
561
+ return plan;
562
+ }
563
+ /** Is the cell still close enough to keep its GPU data (hysteresis)? */
564
+ withinKeepBand(cell) {
565
+ const cfg = this.config;
566
+ if (cell.level <= cfg.rootLevel)
567
+ return this.ticketLevel(cell) <= cfg.rootRange + cfg.hysteresis;
568
+ const p = cfg.shape.parent(cell);
569
+ if (p === null)
570
+ return false;
571
+ const se = cfg.screenError;
572
+ if (se)
573
+ return this.relativeLevel(p, se, this.detailScale(this.detailStep)) <= this.errorShare(p, se) * (1 + cfg.hysteresis / cfg.splitLevel);
574
+ return this.ticketLevel(p) <= cfg.splitLevel + cfg.hysteresis;
575
+ }
576
+ /** Lexicographic priority, smaller first (see the design's job order). */
577
+ priority(r) {
578
+ const cfg = this.config;
579
+ // 1. Missing drawable parent: a cell with nothing resident above it would leave a hole.
580
+ let covered = 1;
581
+ if (r.cell.level > cfg.rootLevel) {
582
+ covered = 0;
583
+ for (let p = cfg.shape.parent(r.cell); p && p.level >= cfg.rootLevel; p = cfg.shape.parent(p)) {
584
+ if (this.cells.get(cellKey(p))?.state === 'RESIDENT') {
585
+ covered = 1;
586
+ break;
587
+ }
588
+ }
589
+ }
590
+ else
591
+ covered = 0;
592
+ // 2. Deficit: wanted on the GPU before prefetch.
593
+ const deficit = r.want === 'resident' ? 0 : 1;
594
+ // 3. Ticket level band, 4. direction of view or travel, 5. exact level.
595
+ const facing = this.facingBucket(r.cell);
596
+ // Selection by screen-space error: what lies in front of a ticket's direction goes first, then the nearest.
597
+ if (cfg.screenError)
598
+ return [covered, deficit, facing, r.level];
599
+ const band = Math.floor(r.level);
600
+ return [covered, deficit, band, facing, r.level];
601
+ }
602
+ /**
603
+ * 0 = straight ahead of a ticket's direction … 3 = behind it. Cells without a directed ticket get 1. Both the
604
+ * direction and the way to the cell's middle are taken across "up" at the ticket, so height plays no part.
605
+ */
606
+ facingBucket(cell) {
607
+ const shape = this.config.shape;
608
+ const c = shape.center(cell);
609
+ const half = shape.edgeM(cell.level) / 2;
610
+ let best = 3;
611
+ let any = false;
612
+ for (const t of this.tickets) {
613
+ if (!t.dir)
614
+ continue;
615
+ any = true;
616
+ const up = shape.upAt(t.center);
617
+ let vx = c[0] - t.center[0];
618
+ let vy = c[1] - t.center[1];
619
+ let vz = c[2] - t.center[2];
620
+ const vu = vx * up[0] + vy * up[1] + vz * up[2];
621
+ vx -= up[0] * vu;
622
+ vy -= up[1] * vu;
623
+ vz -= up[2] * vu;
624
+ let dx = t.dir[0];
625
+ let dy = t.dir.length === 3 ? t.dir[1] : 0;
626
+ let dz = t.dir.length === 3 ? t.dir[2] : t.dir[1];
627
+ const du = dx * up[0] + dy * up[1] + dz * up[2];
628
+ dx -= up[0] * du;
629
+ dy -= up[1] * du;
630
+ dz -= up[2] * du;
631
+ const len = Math.sqrt(vx * vx + vy * vy + vz * vz);
632
+ const dl = Math.sqrt(dx * dx + dy * dy + dz * dz);
633
+ if (len < half * 1.5 || dl === 0)
634
+ return 0;
635
+ const cos = (vx * dx + vy * dy + vz * dz) / (len * dl);
636
+ const b = cos > 0.7 ? 0 : cos > 0 ? 1 : cos > -0.7 ? 2 : 3;
637
+ if (b < best)
638
+ best = b;
639
+ }
640
+ return any ? best : 1;
641
+ }
642
+ enforceBudget(actions) {
643
+ let total = 0;
644
+ for (const r of this.cells.values())
645
+ total += r.cpuBytes + r.gpuBytes;
646
+ const budget = this.config.memoryBudgetBytes;
647
+ // Untouched cells with no data and no job are dropped from bookkeeping at once.
648
+ for (const r of this.sortedRecords()) {
649
+ if (r.want === 'none' && r.state === 'NONE' && !r.inFlight)
650
+ this.cells.delete(r.key);
651
+ }
652
+ if (total <= budget)
653
+ return;
654
+ const order = { none: 0, keep: 1, meshed: 2, resident: 3 };
655
+ const victims = [...this.cells.values()]
656
+ .filter((r) => r.want !== 'resident' && r.state !== 'NONE' && !r.inFlight)
657
+ .sort((a, b) => order[a.want] - order[b.want] || a.lastWanted - b.lastWanted || b.level - a.level || compareCells(a.cell, b.cell));
658
+ for (const r of victims) {
659
+ if (total <= budget)
660
+ break;
661
+ total -= r.cpuBytes + r.gpuBytes;
662
+ if (r.state === 'RESIDENT' && !actions.releases.some((c) => cellKey(c) === r.key))
663
+ actions.releases.push(r.cell);
664
+ actions.evictions.push(r.cell);
665
+ this.cells.delete(r.key);
666
+ this.totals.evicted++;
667
+ }
668
+ }
669
+ /**
670
+ * GPU bytes held by everything that is not a streamed cell (textures, other meshes, targets). The execution part
671
+ * sets it from what the device reports; it only matters with `gpuBudgetBytes`.
672
+ */
673
+ gpuReserveBytes = 0;
674
+ gpuTotals = { released: 0, deferred: 0 };
675
+ /** With `gpuBudgetBytes`: cells taken off the GPU to get under the ceiling, and uploads that had to wait (per step). */
676
+ gpuPressure() {
677
+ return { ...this.gpuTotals };
678
+ }
679
+ /**
680
+ * The execution part lost every GPU object (a lost graphics context): cells on the GPU are MESHED again, so the
681
+ * next step lists them as uploads and they are made again from their CPU data.
682
+ */
683
+ dropResident() {
684
+ for (const r of this.cells.values()) {
685
+ if (r.state !== 'RESIDENT')
686
+ continue;
687
+ if (r.refresh) {
688
+ // Its CPU data are out of date too: forgotten, listed in the next step.
689
+ this.forgetRefreshing(r, this.pendingCancels, null, this.pendingEvictions);
690
+ continue;
691
+ }
692
+ r.state = 'MESHED';
693
+ r.gpuBytes = 0;
694
+ }
695
+ this.computeCover();
696
+ }
697
+ /** A cell with out-of-date content leaves the GPU: its job is cancelled and it is forgotten (state NONE). */
698
+ forgetRefreshing(r, cancels, releases, evictions) {
699
+ if (r.inFlight) {
700
+ cancels.push({ cell: r.cell, key: r.key, epoch: r.epoch });
701
+ r.epoch = ++this.epochSeq;
702
+ r.inFlight = false;
703
+ this.totals.cancelled++;
704
+ }
705
+ if (releases && !releases.some((c) => cellKey(c) === r.key))
706
+ releases.push(r.cell);
707
+ evictions.push(r.cell);
708
+ r.state = 'NONE';
709
+ r.cpuBytes = 0;
710
+ r.gpuBytes = 0;
711
+ r.refresh = false;
712
+ delete r.errorM;
713
+ if (this.config.screenError)
714
+ this.planStale = true;
715
+ }
716
+ enforceGpuCeiling(actions, ceiling) {
717
+ this.gpuTotals = { released: 0, deferred: 0 };
718
+ const room = Math.max(0, ceiling - this.gpuReserveBytes);
719
+ let total = 0;
720
+ for (const r of this.cells.values())
721
+ total += r.gpuBytes;
722
+ // What the uploads of this step would add. Cells nobody wants on the GPU make room for them too; otherwise a
723
+ // cell kept only by hysteresis could hold a wanted one back for as long as the view stands.
724
+ let asked = 0;
725
+ for (const cell of actions.uploads)
726
+ asked += this.cells.get(cellKey(cell))?.cpuBytes ?? 0;
727
+ if (total + asked > room) {
728
+ const victims = [...this.cells.values()].filter((r) => r.state === 'RESIDENT').map((r) => ({ r, k: this.priority(r) }));
729
+ // Not wanted on the GPU first (longest ago first), then wanted ones in reverse order of urgency.
730
+ victims.sort((a, b) => (a.r.want === 'resident' ? 1 : 0) - (b.r.want === 'resident' ? 1 : 0) ||
731
+ (a.r.want === 'resident' ? comparePriority(b.k, a.k) : a.r.lastWanted - b.r.lastWanted) ||
732
+ compareCells(b.r.cell, a.r.cell));
733
+ for (const { r } of victims) {
734
+ // A wanted cell leaves only while the ceiling itself is broken.
735
+ if (total + (r.want === 'resident' ? 0 : asked) <= room)
736
+ break;
737
+ // The coarsest cells are the cover of last resort: they stay.
738
+ if (r.want === 'resident' && r.cell.level <= this.config.rootLevel)
739
+ continue;
740
+ total -= r.gpuBytes;
741
+ this.gpuTotals.released++;
742
+ if (r.refresh) {
743
+ this.forgetRefreshing(r, actions.cancels, actions.releases, actions.evictions);
744
+ continue;
745
+ }
746
+ r.state = 'MESHED';
747
+ r.gpuBytes = 0;
748
+ if (!actions.releases.some((c) => cellKey(c) === r.key))
749
+ actions.releases.push(r.cell);
750
+ }
751
+ }
752
+ // Uploads in their order of urgency while they fit (a cell's GPU bytes are its CPU bytes).
753
+ const fit = [];
754
+ const releasedNow = new Set(actions.releases.map(cellKey));
755
+ for (const cell of actions.uploads) {
756
+ const r = this.cells.get(cellKey(cell));
757
+ if (!r)
758
+ continue;
759
+ const first = r.cell.level <= this.config.rootLevel;
760
+ if (!releasedNow.has(r.key) && (first || total + r.cpuBytes <= room)) {
761
+ fit.push(cell);
762
+ total += r.cpuBytes;
763
+ }
764
+ else
765
+ this.gpuTotals.deferred++;
766
+ }
767
+ actions.uploads = fit;
768
+ }
769
+ /** Drawing cover of the wanted quadtree. */
770
+ computeCover() {
771
+ const plan = this.plan;
772
+ const out = [];
773
+ let holes = 0;
774
+ const resident = (c) => this.cells.get(cellKey(c))?.state === 'RESIDENT';
775
+ const visit = (c) => {
776
+ const kids = c.level < this.config.leafLevel ? this.config.shape.children(c) : [];
777
+ const kidsReady = kids.length > 0 && kids.every(resident);
778
+ if (plan.split.has(cellKey(c)) && kidsReady)
779
+ for (const k of kids)
780
+ visit(k);
781
+ else if (resident(c))
782
+ out.push(c);
783
+ // Only after a jump: the cell itself is missing but finer cells from before still cover it.
784
+ else if (kidsReady)
785
+ for (const k of kids)
786
+ visit(k);
787
+ else
788
+ holes++;
789
+ };
790
+ for (const r of plan.roots)
791
+ visit(r);
792
+ this.drawnList = out;
793
+ this.holes = holes;
794
+ }
795
+ }
796
+ function comparePriority(a, b) {
797
+ for (let i = 0; i < a.length; i++)
798
+ if (a[i] !== b[i])
799
+ return a[i] - b[i];
800
+ return 0;
801
+ }