@egret/engine 0.0.0-stage → 7.0.2

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 (601) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +21 -0
  3. package/README.md +101 -2
  4. package/README.zh-CN.md +102 -0
  5. package/dist/Engine.d.ts +77 -0
  6. package/dist/Engine.js +469 -0
  7. package/dist/animation/index.d.ts +6 -0
  8. package/dist/animation/index.js +5 -0
  9. package/dist/animation/sequenceController.d.ts +22 -0
  10. package/dist/animation/sequenceController.js +618 -0
  11. package/dist/animation/sequenceCoordinator.d.ts +26 -0
  12. package/dist/animation/sequenceCoordinator.js +161 -0
  13. package/dist/animation/sequenceInput.d.ts +25 -0
  14. package/dist/animation/sequenceInput.js +108 -0
  15. package/dist/animation/sequenceMath.d.ts +35 -0
  16. package/dist/animation/sequenceMath.js +164 -0
  17. package/dist/animation/sequenceResetSlot.d.ts +7 -0
  18. package/dist/animation/sequenceResetSlot.js +367 -0
  19. package/dist/animation/sequenceResetTypes.d.ts +48 -0
  20. package/dist/animation/sequenceResetTypes.js +2 -0
  21. package/dist/animation/types.d.ts +75 -0
  22. package/dist/animation/types.js +2 -0
  23. package/dist/assetBundle.d.ts +54 -0
  24. package/dist/assetBundle.js +173 -0
  25. package/dist/assetGroup.d.ts +17 -0
  26. package/dist/assetGroup.js +332 -0
  27. package/dist/assetGroupTypes.d.ts +17 -0
  28. package/dist/assetGroupTypes.js +2 -0
  29. package/dist/audio.d.ts +4 -0
  30. package/dist/audio.js +4 -0
  31. package/dist/audioCues.d.ts +47 -0
  32. package/dist/audioCues.js +127 -0
  33. package/dist/audioMixer.d.ts +7 -0
  34. package/dist/audioMixer.js +785 -0
  35. package/dist/audioTypes.d.ts +246 -0
  36. package/dist/audioTypes.js +3 -0
  37. package/dist/bitmapBindingTicket.d.ts +24 -0
  38. package/dist/bitmapBindingTicket.js +215 -0
  39. package/dist/bitmapButton.d.ts +4 -0
  40. package/dist/bitmapButton.js +407 -0
  41. package/dist/bitmapButtonTypes.d.ts +31 -0
  42. package/dist/bitmapButtonTypes.js +2 -0
  43. package/dist/bitmapFontParse.d.ts +10 -0
  44. package/dist/bitmapFontParse.js +246 -0
  45. package/dist/bitmapFontTypes.d.ts +112 -0
  46. package/dist/bitmapFontTypes.js +2 -0
  47. package/dist/bitmapResourceSlot.d.ts +26 -0
  48. package/dist/bitmapResourceSlot.js +340 -0
  49. package/dist/bitmapText.d.ts +6 -0
  50. package/dist/bitmapText.js +320 -0
  51. package/dist/bitmapfont.d.ts +5 -0
  52. package/dist/bitmapfont.js +5 -0
  53. package/dist/camera.d.ts +4 -0
  54. package/dist/camera.js +4 -0
  55. package/dist/camera2d.d.ts +7 -0
  56. package/dist/camera2d.js +419 -0
  57. package/dist/cameraTypes.d.ts +126 -0
  58. package/dist/cameraTypes.js +2 -0
  59. package/dist/closeHost.d.ts +4 -0
  60. package/dist/closeHost.js +66 -0
  61. package/dist/contentArtifacts.d.ts +12 -0
  62. package/dist/contentArtifacts.js +153 -0
  63. package/dist/contentAtlasPages.d.ts +13 -0
  64. package/dist/contentAtlasPages.js +117 -0
  65. package/dist/contentLoader.d.ts +6 -0
  66. package/dist/contentLoader.js +327 -0
  67. package/dist/contentTypes.d.ts +35 -0
  68. package/dist/contentTypes.js +2 -0
  69. package/dist/createEngine.d.ts +7 -0
  70. package/dist/createEngine.js +25 -0
  71. package/dist/createEngineForProfile.d.ts +5 -0
  72. package/dist/createEngineForProfile.js +45 -0
  73. package/dist/displaySubtreeTicket.d.ts +25 -0
  74. package/dist/displaySubtreeTicket.js +76 -0
  75. package/dist/fontContentLoader.d.ts +6 -0
  76. package/dist/fontContentLoader.js +298 -0
  77. package/dist/fontContentTypes.d.ts +39 -0
  78. package/dist/fontContentTypes.js +2 -0
  79. package/dist/gameClock.d.ts +24 -0
  80. package/dist/gameClock.js +246 -0
  81. package/dist/gameClockTypes.d.ts +37 -0
  82. package/dist/gameClockTypes.js +2 -0
  83. package/dist/gameRun.d.ts +53 -0
  84. package/dist/gameRun.js +97 -0
  85. package/dist/gamepad.d.ts +5 -0
  86. package/dist/gamepad.js +5 -0
  87. package/dist/gamepadInput.d.ts +4 -0
  88. package/dist/gamepadInput.js +281 -0
  89. package/dist/gamepadKeys.d.ts +4 -0
  90. package/dist/gamepadKeys.js +205 -0
  91. package/dist/gamepadTypes.d.ts +142 -0
  92. package/dist/gamepadTypes.js +3 -0
  93. package/dist/hover.d.ts +4 -0
  94. package/dist/hover.js +4 -0
  95. package/dist/hoverInput.d.ts +8 -0
  96. package/dist/hoverInput.js +503 -0
  97. package/dist/hoverInputTypes.d.ts +129 -0
  98. package/dist/hoverInputTypes.js +2 -0
  99. package/dist/index.d.ts +52 -0
  100. package/dist/index.js +21 -0
  101. package/dist/input.d.ts +6 -0
  102. package/dist/input.js +5 -0
  103. package/dist/inputActions.d.ts +86 -0
  104. package/dist/inputActions.js +330 -0
  105. package/dist/internal/contentFactoryState.d.ts +19 -0
  106. package/dist/internal/contentFactoryState.js +42 -0
  107. package/dist/internal/mouseInputFactoryState.d.ts +57 -0
  108. package/dist/internal/mouseInputFactoryState.js +125 -0
  109. package/dist/internal/sequenceControllerFactoryState.d.ts +42 -0
  110. package/dist/internal/sequenceControllerFactoryState.js +98 -0
  111. package/dist/internal/textFieldFactoryState.d.ts +11 -0
  112. package/dist/internal/textFieldFactoryState.js +32 -0
  113. package/dist/internal/texturedFrameState.d.ts +4 -0
  114. package/dist/internal/texturedFrameState.js +12 -0
  115. package/dist/internal/uiFactoryState.d.ts +68 -0
  116. package/dist/internal/uiFactoryState.js +173 -0
  117. package/dist/internal/uiRootState.d.ts +67 -0
  118. package/dist/internal/uiRootState.js +103 -0
  119. package/dist/keyboardInput.d.ts +13 -0
  120. package/dist/keyboardInput.js +579 -0
  121. package/dist/keyboardInputTypes.d.ts +93 -0
  122. package/dist/keyboardInputTypes.js +2 -0
  123. package/dist/kit.d.ts +16 -0
  124. package/dist/kit.js +10 -0
  125. package/dist/layout.d.ts +5 -0
  126. package/dist/layout.js +132 -0
  127. package/dist/layoutTypes.d.ts +28 -0
  128. package/dist/layoutTypes.js +2 -0
  129. package/dist/manifestAssetGroup.d.ts +10 -0
  130. package/dist/manifestAssetGroup.js +477 -0
  131. package/dist/manifestResourceState.d.ts +17 -0
  132. package/dist/manifestResourceState.js +58 -0
  133. package/dist/manifestResourceTypes.d.ts +26 -0
  134. package/dist/manifestResourceTypes.js +2 -0
  135. package/dist/motion.d.ts +35 -0
  136. package/dist/motion.js +206 -0
  137. package/dist/mouseInput.d.ts +102 -0
  138. package/dist/mouseInput.js +562 -0
  139. package/dist/mouseInputTypes.d.ts +41 -0
  140. package/dist/mouseInputTypes.js +2 -0
  141. package/dist/paragraph.d.ts +8 -0
  142. package/dist/paragraph.js +7 -0
  143. package/dist/particleEmitter.d.ts +4 -0
  144. package/dist/particleEmitter.js +300 -0
  145. package/dist/particleTypes.d.ts +115 -0
  146. package/dist/particleTypes.js +2 -0
  147. package/dist/particles.d.ts +4 -0
  148. package/dist/particles.js +4 -0
  149. package/dist/physics2d.d.ts +4 -0
  150. package/dist/physics2d.js +4 -0
  151. package/dist/physics2dGeometry.d.ts +39 -0
  152. package/dist/physics2dGeometry.js +230 -0
  153. package/dist/physics2dTypes.d.ts +221 -0
  154. package/dist/physics2dTypes.js +2 -0
  155. package/dist/physics2dWorld.d.ts +4 -0
  156. package/dist/physics2dWorld.js +823 -0
  157. package/dist/pointerInput.d.ts +12 -0
  158. package/dist/pointerInput.js +300 -0
  159. package/dist/pointerInputTypes.d.ts +41 -0
  160. package/dist/pointerInputTypes.js +2 -0
  161. package/dist/random.d.ts +30 -0
  162. package/dist/random.js +131 -0
  163. package/dist/rendering/ownedPreparationFailure2D.d.ts +5 -0
  164. package/dist/rendering/ownedPreparationFailure2D.js +33 -0
  165. package/dist/rendering/packSharedDraws2D.d.ts +50 -0
  166. package/dist/rendering/packSharedDraws2D.js +379 -0
  167. package/dist/rendering/packedOrientation.d.ts +4 -0
  168. package/dist/rendering/packedOrientation.js +7 -0
  169. package/dist/rendering/prepareRectangles2D.d.ts +92 -0
  170. package/dist/rendering/prepareRectangles2D.js +481 -0
  171. package/dist/rendering/prepareSharedDraws2D.d.ts +90 -0
  172. package/dist/rendering/prepareSharedDraws2D.js +663 -0
  173. package/dist/rendering/preparedBatches2D.d.ts +17 -0
  174. package/dist/rendering/preparedBatches2D.js +30 -0
  175. package/dist/rendering/preparedSharedBatches2D.d.ts +44 -0
  176. package/dist/rendering/preparedSharedBatches2D.js +247 -0
  177. package/dist/rendering/sharedColor2D.d.ts +52 -0
  178. package/dist/rendering/sharedColor2D.js +191 -0
  179. package/dist/rendering/sharedEffects2D.d.ts +23 -0
  180. package/dist/rendering/sharedEffects2D.js +126 -0
  181. package/dist/rendering/sharedPreparationRetention2D.d.ts +120 -0
  182. package/dist/rendering/sharedPreparationRetention2D.js +357 -0
  183. package/dist/rendering/srgbBytes.d.ts +3 -0
  184. package/dist/rendering/srgbBytes.js +64 -0
  185. package/dist/rendering/texturedPreparationBudget2D.d.ts +31 -0
  186. package/dist/rendering/texturedPreparationBudget2D.js +81 -0
  187. package/dist/rendering/world3d/Animation3D.d.ts +104 -0
  188. package/dist/rendering/world3d/Animation3D.js +384 -0
  189. package/dist/rendering/world3d/AnimationTexture3D.d.ts +163 -0
  190. package/dist/rendering/world3d/AnimationTexture3D.js +603 -0
  191. package/dist/rendering/world3d/Batch3D.d.ts +75 -0
  192. package/dist/rendering/world3d/Batch3D.js +332 -0
  193. package/dist/rendering/world3d/Camera3D.d.ts +62 -0
  194. package/dist/rendering/world3d/Camera3D.js +132 -0
  195. package/dist/rendering/world3d/Character3D.d.ts +127 -0
  196. package/dist/rendering/world3d/Character3D.js +305 -0
  197. package/dist/rendering/world3d/Cloth3D.d.ts +130 -0
  198. package/dist/rendering/world3d/Cloth3D.js +503 -0
  199. package/dist/rendering/world3d/Compression3D.d.ts +22 -0
  200. package/dist/rendering/world3d/Compression3D.js +703 -0
  201. package/dist/rendering/world3d/Curves3D.d.ts +119 -0
  202. package/dist/rendering/world3d/Curves3D.js +460 -0
  203. package/dist/rendering/world3d/Decal3D.d.ts +43 -0
  204. package/dist/rendering/world3d/Decal3D.js +242 -0
  205. package/dist/rendering/world3d/Export3D.d.ts +13 -0
  206. package/dist/rendering/world3d/Export3D.js +263 -0
  207. package/dist/rendering/world3d/Geometry3D.d.ts +95 -0
  208. package/dist/rendering/world3d/Geometry3D.js +335 -0
  209. package/dist/rendering/world3d/GeometryBuilder3D.d.ts +53 -0
  210. package/dist/rendering/world3d/GeometryBuilder3D.js +196 -0
  211. package/dist/rendering/world3d/Gizmo3D.d.ts +80 -0
  212. package/dist/rendering/world3d/Gizmo3D.js +514 -0
  213. package/dist/rendering/world3d/Gltf3D.d.ts +73 -0
  214. package/dist/rendering/world3d/Gltf3D.js +996 -0
  215. package/dist/rendering/world3d/GpuParticles3D.d.ts +109 -0
  216. package/dist/rendering/world3d/GpuParticles3D.js +401 -0
  217. package/dist/rendering/world3d/Hdr3D.d.ts +35 -0
  218. package/dist/rendering/world3d/Hdr3D.js +191 -0
  219. package/dist/rendering/world3d/Jelly3D.d.ts +77 -0
  220. package/dist/rendering/world3d/Jelly3D.js +267 -0
  221. package/dist/rendering/world3d/Ktx23D.d.ts +30 -0
  222. package/dist/rendering/world3d/Ktx23D.js +112 -0
  223. package/dist/rendering/world3d/Light3D.d.ts +84 -0
  224. package/dist/rendering/world3d/Light3D.js +97 -0
  225. package/dist/rendering/world3d/Material3D.d.ts +253 -0
  226. package/dist/rendering/world3d/Material3D.js +269 -0
  227. package/dist/rendering/world3d/Mesh3D.d.ts +112 -0
  228. package/dist/rendering/world3d/Mesh3D.js +337 -0
  229. package/dist/rendering/world3d/Meshopt3D.d.ts +15 -0
  230. package/dist/rendering/world3d/Meshopt3D.js +276 -0
  231. package/dist/rendering/world3d/Navigation3D.d.ts +213 -0
  232. package/dist/rendering/world3d/Navigation3D.js +1043 -0
  233. package/dist/rendering/world3d/Object3D.d.ts +118 -0
  234. package/dist/rendering/world3d/Object3D.js +315 -0
  235. package/dist/rendering/world3d/Particles3D.d.ts +90 -0
  236. package/dist/rendering/world3d/Particles3D.js +277 -0
  237. package/dist/rendering/world3d/Physics3D.d.ts +430 -0
  238. package/dist/rendering/world3d/Physics3D.js +2840 -0
  239. package/dist/rendering/world3d/PhysicsHull3D.d.ts +37 -0
  240. package/dist/rendering/world3d/PhysicsHull3D.js +229 -0
  241. package/dist/rendering/world3d/PhysicsMesh3D.d.ts +41 -0
  242. package/dist/rendering/world3d/PhysicsMesh3D.js +340 -0
  243. package/dist/rendering/world3d/PhysicsQueries3D.d.ts +24 -0
  244. package/dist/rendering/world3d/PhysicsQueries3D.js +323 -0
  245. package/dist/rendering/world3d/PhysicsRemote3D.d.ts +179 -0
  246. package/dist/rendering/world3d/PhysicsRemote3D.js +536 -0
  247. package/dist/rendering/world3d/Ragdoll3D.d.ts +74 -0
  248. package/dist/rendering/world3d/Ragdoll3D.js +202 -0
  249. package/dist/rendering/world3d/Raycast3D.d.ts +40 -0
  250. package/dist/rendering/world3d/Raycast3D.js +247 -0
  251. package/dist/rendering/world3d/RenderList3D.d.ts +91 -0
  252. package/dist/rendering/world3d/RenderList3D.js +502 -0
  253. package/dist/rendering/world3d/Retarget3D.d.ts +21 -0
  254. package/dist/rendering/world3d/Retarget3D.js +185 -0
  255. package/dist/rendering/world3d/Rig3D.d.ts +57 -0
  256. package/dist/rendering/world3d/Rig3D.js +219 -0
  257. package/dist/rendering/world3d/Sdf3D.d.ts +181 -0
  258. package/dist/rendering/world3d/Sdf3D.js +1136 -0
  259. package/dist/rendering/world3d/SdfLod3D.d.ts +17 -0
  260. package/dist/rendering/world3d/SdfLod3D.js +56 -0
  261. package/dist/rendering/world3d/Serialize3D.d.ts +66 -0
  262. package/dist/rendering/world3d/Serialize3D.js +629 -0
  263. package/dist/rendering/world3d/Simplify3D.d.ts +29 -0
  264. package/dist/rendering/world3d/Simplify3D.js +426 -0
  265. package/dist/rendering/world3d/StateMachine3D.d.ts +87 -0
  266. package/dist/rendering/world3d/StateMachine3D.js +280 -0
  267. package/dist/rendering/world3d/SurfaceMaterial3D.d.ts +26 -0
  268. package/dist/rendering/world3d/SurfaceMaterial3D.js +138 -0
  269. package/dist/rendering/world3d/Terrain3D.d.ts +248 -0
  270. package/dist/rendering/world3d/Terrain3D.js +827 -0
  271. package/dist/rendering/world3d/Text3D.d.ts +95 -0
  272. package/dist/rendering/world3d/Text3D.js +560 -0
  273. package/dist/rendering/world3d/Texture3D.d.ts +148 -0
  274. package/dist/rendering/world3d/Texture3D.js +270 -0
  275. package/dist/rendering/world3d/Trail3D.d.ts +62 -0
  276. package/dist/rendering/world3d/Trail3D.js +195 -0
  277. package/dist/rendering/world3d/Vehicle3D.d.ts +102 -0
  278. package/dist/rendering/world3d/Vehicle3D.js +228 -0
  279. package/dist/rendering/world3d/VolumetricFog3D.d.ts +57 -0
  280. package/dist/rendering/world3d/VolumetricFog3D.js +230 -0
  281. package/dist/rendering/world3d/Water3D.d.ts +165 -0
  282. package/dist/rendering/world3d/Water3D.js +607 -0
  283. package/dist/rendering/world3d/core3D.d.ts +36 -0
  284. package/dist/rendering/world3d/core3D.js +99 -0
  285. package/dist/rendering/world3d/debug3D.d.ts +69 -0
  286. package/dist/rendering/world3d/debug3D.js +262 -0
  287. package/dist/rendering/world3d/decoders3D.d.ts +42 -0
  288. package/dist/rendering/world3d/decoders3D.js +133 -0
  289. package/dist/rendering/world3d/geometries3D.d.ts +111 -0
  290. package/dist/rendering/world3d/geometries3D.js +610 -0
  291. package/dist/rendering/world3d/helpers3D.d.ts +67 -0
  292. package/dist/rendering/world3d/helpers3D.js +178 -0
  293. package/dist/rendering/world3d/index.d.ts +103 -0
  294. package/dist/rendering/world3d/index.js +62 -0
  295. package/dist/rendering/world3d/math3D.d.ts +114 -0
  296. package/dist/rendering/world3d/math3D.js +675 -0
  297. package/dist/rendering/world3d/primitives3D.d.ts +67 -0
  298. package/dist/rendering/world3d/primitives3D.js +197 -0
  299. package/dist/resources.d.ts +8 -0
  300. package/dist/resources.js +6 -0
  301. package/dist/saveStore.d.ts +71 -0
  302. package/dist/saveStore.js +182 -0
  303. package/dist/semanticList.d.ts +126 -0
  304. package/dist/semanticList.js +175 -0
  305. package/dist/semanticTree.d.ts +10 -0
  306. package/dist/semanticTree.js +539 -0
  307. package/dist/semanticTypes.d.ts +175 -0
  308. package/dist/semanticTypes.js +2 -0
  309. package/dist/semantics.d.ts +6 -0
  310. package/dist/semantics.js +5 -0
  311. package/dist/sequencePlayback.d.ts +19 -0
  312. package/dist/sequencePlayback.js +391 -0
  313. package/dist/sequencePlaybackTypes.d.ts +24 -0
  314. package/dist/sequencePlaybackTypes.js +2 -0
  315. package/dist/sequenceTargetClaims.d.ts +10 -0
  316. package/dist/sequenceTargetClaims.js +31 -0
  317. package/dist/srgbBytes.d.ts +3 -0
  318. package/dist/srgbBytes.js +64 -0
  319. package/dist/startEngine.d.ts +5 -0
  320. package/dist/startEngine.js +31 -0
  321. package/dist/surfaceOwnership.d.ts +3 -0
  322. package/dist/surfaceOwnership.js +15 -0
  323. package/dist/text.d.ts +24 -0
  324. package/dist/text.js +4 -0
  325. package/dist/textField.d.ts +6 -0
  326. package/dist/textField.js +6 -0
  327. package/dist/textTable.d.ts +41 -0
  328. package/dist/textTable.js +114 -0
  329. package/dist/tileMapDraw.d.ts +7 -0
  330. package/dist/tileMapDraw.js +310 -0
  331. package/dist/tiledImport.d.ts +9 -0
  332. package/dist/tiledImport.js +357 -0
  333. package/dist/tilemap.d.ts +5 -0
  334. package/dist/tilemap.js +5 -0
  335. package/dist/tilemapTypes.d.ts +182 -0
  336. package/dist/tilemapTypes.js +2 -0
  337. package/dist/timer.d.ts +34 -0
  338. package/dist/timer.js +119 -0
  339. package/dist/tween.d.ts +15 -0
  340. package/dist/tween.js +329 -0
  341. package/dist/tweenTypes.d.ts +31 -0
  342. package/dist/tweenTypes.js +2 -0
  343. package/dist/ui/controlKeys.d.ts +113 -0
  344. package/dist/ui/controlKeys.js +250 -0
  345. package/dist/ui/controls.d.ts +58 -0
  346. package/dist/ui/controls.js +290 -0
  347. package/dist/ui/editing.d.ts +3 -0
  348. package/dist/ui/editing.js +3 -0
  349. package/dist/ui/index.d.ts +19 -0
  350. package/dist/ui/index.js +11 -0
  351. package/dist/ui/keyboardFocus.d.ts +32 -0
  352. package/dist/ui/keyboardFocus.js +146 -0
  353. package/dist/ui/layerTypes.d.ts +98 -0
  354. package/dist/ui/layerTypes.js +2 -0
  355. package/dist/ui/layers.d.ts +4 -0
  356. package/dist/ui/layers.js +586 -0
  357. package/dist/ui/leafContent.d.ts +21 -0
  358. package/dist/ui/leafContent.js +136 -0
  359. package/dist/ui/rangeControl.d.ts +53 -0
  360. package/dist/ui/rangeControl.js +168 -0
  361. package/dist/ui/scrollControl.d.ts +84 -0
  362. package/dist/ui/scrollControl.js +222 -0
  363. package/dist/ui/stateControls.d.ts +90 -0
  364. package/dist/ui/stateControls.js +331 -0
  365. package/dist/ui/textEditor.d.ts +54 -0
  366. package/dist/ui/textEditor.js +371 -0
  367. package/dist/ui/textEditorTypes.d.ts +85 -0
  368. package/dist/ui/textEditorTypes.js +2 -0
  369. package/dist/ui/textFieldControl.d.ts +100 -0
  370. package/dist/ui/textFieldControl.js +260 -0
  371. package/dist/ui/theme.d.ts +64 -0
  372. package/dist/ui/theme.js +166 -0
  373. package/dist/ui/types.d.ts +285 -0
  374. package/dist/ui/types.js +2 -0
  375. package/dist/ui/uiRoot.d.ts +4 -0
  376. package/dist/ui/uiRoot.js +1526 -0
  377. package/dist/ui/uiRootDisplay.d.ts +46 -0
  378. package/dist/ui/uiRootDisplay.js +148 -0
  379. package/dist/ui/uiRootModel.d.ts +114 -0
  380. package/dist/ui/uiRootModel.js +66 -0
  381. package/dist/ui/virtualList.d.ts +20 -0
  382. package/dist/ui/virtualList.js +105 -0
  383. package/dist/video.d.ts +4 -0
  384. package/dist/video.js +4 -0
  385. package/dist/videoPlayer.d.ts +4 -0
  386. package/dist/videoPlayer.js +215 -0
  387. package/dist/videoTypes.d.ts +77 -0
  388. package/dist/videoTypes.js +2 -0
  389. package/dist/web/BrowserAssetBundle.d.ts +41 -0
  390. package/dist/web/BrowserAssetBundle.js +136 -0
  391. package/dist/web/BrowserAudio.d.ts +74 -0
  392. package/dist/web/BrowserAudio.js +503 -0
  393. package/dist/web/BrowserFrameLoop.d.ts +69 -0
  394. package/dist/web/BrowserFrameLoop.js +125 -0
  395. package/dist/web/BrowserGame.d.ts +174 -0
  396. package/dist/web/BrowserGame.js +473 -0
  397. package/dist/web/BrowserGamepadInput.d.ts +38 -0
  398. package/dist/web/BrowserGamepadInput.js +134 -0
  399. package/dist/web/BrowserHoverInput.d.ts +25 -0
  400. package/dist/web/BrowserHoverInput.js +266 -0
  401. package/dist/web/BrowserImageTextures.d.ts +72 -0
  402. package/dist/web/BrowserImageTextures.js +169 -0
  403. package/dist/web/BrowserInputActions.d.ts +63 -0
  404. package/dist/web/BrowserInputActions.js +345 -0
  405. package/dist/web/BrowserKeyboardInput.d.ts +4 -0
  406. package/dist/web/BrowserKeyboardInput.js +223 -0
  407. package/dist/web/BrowserPlay.d.ts +417 -0
  408. package/dist/web/BrowserPlay.js +1648 -0
  409. package/dist/web/BrowserPointerInput.d.ts +4 -0
  410. package/dist/web/BrowserPointerInput.js +511 -0
  411. package/dist/web/BrowserPreferences.d.ts +10 -0
  412. package/dist/web/BrowserPreferences.js +39 -0
  413. package/dist/web/BrowserSemantics.d.ts +36 -0
  414. package/dist/web/BrowserSemantics.js +418 -0
  415. package/dist/web/BrowserStatsPanel.d.ts +56 -0
  416. package/dist/web/BrowserStatsPanel.js +143 -0
  417. package/dist/web/BrowserStorage.d.ts +35 -0
  418. package/dist/web/BrowserStorage.js +132 -0
  419. package/dist/web/BrowserTextEditor.d.ts +52 -0
  420. package/dist/web/BrowserTextEditor.js +839 -0
  421. package/dist/web/BrowserTextInput.d.ts +89 -0
  422. package/dist/web/BrowserTextInput.js +524 -0
  423. package/dist/web/BrowserTextureProvider.d.ts +58 -0
  424. package/dist/web/BrowserTextureProvider.js +935 -0
  425. package/dist/web/BrowserVideo.d.ts +40 -0
  426. package/dist/web/BrowserVideo.js +237 -0
  427. package/dist/web/CanvasKitFontSetProvider.d.ts +32 -0
  428. package/dist/web/CanvasKitFontSetProvider.js +215 -0
  429. package/dist/web/CanvasKitParagraphProvider.d.ts +173 -0
  430. package/dist/web/CanvasKitParagraphProvider.js +692 -0
  431. package/dist/web/CanvasTextRasterProvider.d.ts +4 -0
  432. package/dist/web/CanvasTextRasterProvider.js +312 -0
  433. package/dist/web/ManifestByteSource.d.ts +151 -0
  434. package/dist/web/ManifestByteSource.js +975 -0
  435. package/dist/web/ManifestFontContentLoader.d.ts +13 -0
  436. package/dist/web/ManifestFontContentLoader.js +30 -0
  437. package/dist/web/MouseInput.d.ts +4 -0
  438. package/dist/web/MouseInput.js +218 -0
  439. package/dist/web/WebGL2Host.d.ts +5 -0
  440. package/dist/web/WebGL2Host.js +2711 -0
  441. package/dist/web/WebGPUHost.d.ts +100 -0
  442. package/dist/web/WebGPUHost.js +3430 -0
  443. package/dist/web/audio.d.ts +3 -0
  444. package/dist/web/audio.js +4 -0
  445. package/dist/web/canvasKitParagraphGeometry.d.ts +27 -0
  446. package/dist/web/canvasKitParagraphGeometry.js +83 -0
  447. package/dist/web/editing.d.ts +5 -0
  448. package/dist/web/editing.js +4 -0
  449. package/dist/web/editorFonts.d.ts +54 -0
  450. package/dist/web/editorFonts.js +297 -0
  451. package/dist/web/game.d.ts +5 -0
  452. package/dist/web/game.js +6 -0
  453. package/dist/web/gamepad.d.ts +3 -0
  454. package/dist/web/gamepad.js +4 -0
  455. package/dist/web/hover.d.ts +3 -0
  456. package/dist/web/hover.js +4 -0
  457. package/dist/web/image.d.ts +4 -0
  458. package/dist/web/image.js +4 -0
  459. package/dist/web/imageProjections2D.d.ts +16 -0
  460. package/dist/web/imageProjections2D.js +2 -0
  461. package/dist/web/input.d.ts +6 -0
  462. package/dist/web/input.js +4 -0
  463. package/dist/web/keyboard.d.ts +3 -0
  464. package/dist/web/keyboard.js +3 -0
  465. package/dist/web/kit.d.ts +11 -0
  466. package/dist/web/kit.js +8 -0
  467. package/dist/web/loop.d.ts +3 -0
  468. package/dist/web/loop.js +4 -0
  469. package/dist/web/paragraph.d.ts +6 -0
  470. package/dist/web/paragraph.js +4 -0
  471. package/dist/web/play.d.ts +10 -0
  472. package/dist/web/play.js +9 -0
  473. package/dist/web/playMusic.d.ts +33 -0
  474. package/dist/web/playMusic.js +194 -0
  475. package/dist/web/playSfx.d.ts +36 -0
  476. package/dist/web/playSfx.js +112 -0
  477. package/dist/web/playTouch.d.ts +45 -0
  478. package/dist/web/playTouch.js +141 -0
  479. package/dist/web/playWidgets.d.ts +71 -0
  480. package/dist/web/playWidgets.js +431 -0
  481. package/dist/web/pointer.d.ts +3 -0
  482. package/dist/web/pointer.js +3 -0
  483. package/dist/web/prepareSharedSubmission2D.d.ts +27 -0
  484. package/dist/web/prepareSharedSubmission2D.js +63 -0
  485. package/dist/web/resources.d.ts +29 -0
  486. package/dist/web/resources.js +96 -0
  487. package/dist/web/semantics.d.ts +3 -0
  488. package/dist/web/semantics.js +4 -0
  489. package/dist/web/sharedDeviceSession.d.ts +64 -0
  490. package/dist/web/sharedDeviceSession.js +2 -0
  491. package/dist/web/sharedEffectShaders.d.ts +13 -0
  492. package/dist/web/sharedEffectShaders.js +181 -0
  493. package/dist/web/sharedFrameUpload.d.ts +25 -0
  494. package/dist/web/sharedFrameUpload.js +2 -0
  495. package/dist/web/sharedHostDeferred.d.ts +7 -0
  496. package/dist/web/sharedHostDeferred.js +12 -0
  497. package/dist/web/sharedRetentionLedger.d.ts +85 -0
  498. package/dist/web/sharedRetentionLedger.js +391 -0
  499. package/dist/web/sharedSubmissionStorage2D.d.ts +56 -0
  500. package/dist/web/sharedSubmissionStorage2D.js +73 -0
  501. package/dist/web/sharedWebGL2Arena.d.ts +40 -0
  502. package/dist/web/sharedWebGL2Arena.js +77 -0
  503. package/dist/web/sharedWebGL2Options.d.ts +33 -0
  504. package/dist/web/sharedWebGL2Options.js +102 -0
  505. package/dist/web/sharedWebGL2Shaders.d.ts +33 -0
  506. package/dist/web/sharedWebGL2Shaders.js +408 -0
  507. package/dist/web/sharedWebGPUOptions.d.ts +41 -0
  508. package/dist/web/sharedWebGPUOptions.js +130 -0
  509. package/dist/web/text.d.ts +3 -0
  510. package/dist/web/text.js +3 -0
  511. package/dist/web/textInput.d.ts +3 -0
  512. package/dist/web/textInput.js +3 -0
  513. package/dist/web/video.d.ts +3 -0
  514. package/dist/web/video.js +4 -0
  515. package/dist/web/webgl2.d.ts +7 -0
  516. package/dist/web/webgl2.js +4 -0
  517. package/dist/web/webgl2LayerState.d.ts +50 -0
  518. package/dist/web/webgl2LayerState.js +102 -0
  519. package/dist/web/webgl2Native.d.ts +72 -0
  520. package/dist/web/webgl2Native.js +572 -0
  521. package/dist/web/webgl2Types.d.ts +150 -0
  522. package/dist/web/webgl2Types.js +2 -0
  523. package/dist/web/webgpu.d.ts +6 -0
  524. package/dist/web/webgpu.js +2 -0
  525. package/dist/web/webgpuBindingCache.d.ts +26 -0
  526. package/dist/web/webgpuBindingCache.js +223 -0
  527. package/dist/web/webgpuBufferPool.d.ts +51 -0
  528. package/dist/web/webgpuBufferPool.js +58 -0
  529. package/dist/web/webgpuImageResidency.d.ts +56 -0
  530. package/dist/web/webgpuImageResidency.js +65 -0
  531. package/dist/web/webgpuLifetime.d.ts +45 -0
  532. package/dist/web/webgpuLifetime.js +64 -0
  533. package/dist/web/webgpuRetentionPool.d.ts +66 -0
  534. package/dist/web/webgpuRetentionPool.js +85 -0
  535. package/dist/web/webgpuSharedPass.d.ts +7 -0
  536. package/dist/web/webgpuSharedPass.js +293 -0
  537. package/dist/web/webgpuSharedResolvePass.d.ts +3 -0
  538. package/dist/web/webgpuSharedResolvePass.js +34 -0
  539. package/dist/web/world3d/Audio3D.d.ts +85 -0
  540. package/dist/web/world3d/Audio3D.js +271 -0
  541. package/dist/web/world3d/BrowserPlay3D.d.ts +295 -0
  542. package/dist/web/world3d/BrowserPlay3D.js +1256 -0
  543. package/dist/web/world3d/FlyControls3D.d.ts +59 -0
  544. package/dist/web/world3d/FlyControls3D.js +162 -0
  545. package/dist/web/world3d/FollowControls3D.d.ts +31 -0
  546. package/dist/web/world3d/FollowControls3D.js +119 -0
  547. package/dist/web/world3d/OrbitControls3D.d.ts +58 -0
  548. package/dist/web/world3d/OrbitControls3D.js +189 -0
  549. package/dist/web/world3d/TransformControls3D.d.ts +37 -0
  550. package/dist/web/world3d/TransformControls3D.js +128 -0
  551. package/dist/web/world3d/WebGL2Renderer3D.d.ts +136 -0
  552. package/dist/web/world3d/WebGL2Renderer3D.js +1175 -0
  553. package/dist/web/world3d/WebGPURenderer3D.d.ts +112 -0
  554. package/dist/web/world3d/WebGPURenderer3D.js +1916 -0
  555. package/dist/web/world3d/World3DView.d.ts +54 -0
  556. package/dist/web/world3d/World3DView.js +79 -0
  557. package/dist/web/world3d/app3D.d.ts +143 -0
  558. package/dist/web/world3d/app3D.js +305 -0
  559. package/dist/web/world3d/assets3D.d.ts +39 -0
  560. package/dist/web/world3d/assets3D.js +112 -0
  561. package/dist/web/world3d/atmosphere3D.d.ts +56 -0
  562. package/dist/web/world3d/atmosphere3D.js +193 -0
  563. package/dist/web/world3d/canvasFont3D.d.ts +21 -0
  564. package/dist/web/world3d/canvasFont3D.js +165 -0
  565. package/dist/web/world3d/frame3D.d.ts +144 -0
  566. package/dist/web/world3d/frame3D.js +388 -0
  567. package/dist/web/world3d/gpuResources3D.d.ts +98 -0
  568. package/dist/web/world3d/gpuResources3D.js +901 -0
  569. package/dist/web/world3d/host3D.d.ts +24 -0
  570. package/dist/web/world3d/host3D.js +61 -0
  571. package/dist/web/world3d/index.d.ts +40 -0
  572. package/dist/web/world3d/index.js +24 -0
  573. package/dist/web/world3d/loaders3D.d.ts +27 -0
  574. package/dist/web/world3d/loaders3D.js +138 -0
  575. package/dist/web/world3d/markers3D.d.ts +53 -0
  576. package/dist/web/world3d/markers3D.js +130 -0
  577. package/dist/web/world3d/materialWebGL23D.d.ts +34 -0
  578. package/dist/web/world3d/materialWebGL23D.js +218 -0
  579. package/dist/web/world3d/overlay3D.d.ts +47 -0
  580. package/dist/web/world3d/overlay3D.js +187 -0
  581. package/dist/web/world3d/post3D.d.ts +116 -0
  582. package/dist/web/world3d/post3D.js +462 -0
  583. package/dist/web/world3d/postWebGL23D.d.ts +24 -0
  584. package/dist/web/world3d/postWebGL23D.js +237 -0
  585. package/dist/web/world3d/postWebGPU3D.d.ts +23 -0
  586. package/dist/web/world3d/postWebGPU3D.js +255 -0
  587. package/dist/web/world3d/probe3D.d.ts +15 -0
  588. package/dist/web/world3d/probe3D.js +66 -0
  589. package/dist/web/world3d/shaders3D.d.ts +43 -0
  590. package/dist/web/world3d/shaders3D.js +851 -0
  591. package/dist/web/world3d/stats3D.d.ts +34 -0
  592. package/dist/web/world3d/stats3D.js +81 -0
  593. package/dist/web/world3d/webGL2FrameMetrics3D.d.ts +71 -0
  594. package/dist/web/world3d/webGL2FrameMetrics3D.js +185 -0
  595. package/dist/web/world3d/webgpu.d.ts +37 -0
  596. package/dist/web/world3d/webgpu.js +23 -0
  597. package/dist/web/world3d/webgpuPacking3D.d.ts +13 -0
  598. package/dist/web/world3d/webgpuPacking3D.js +85 -0
  599. package/dist/web/world3d/wgsl3D.d.ts +68 -0
  600. package/dist/web/world3d/wgsl3D.js +781 -0
  601. package/package.json +220 -4
@@ -0,0 +1,1916 @@
1
+ import { World3DError } from '../../rendering/world3d/core3D.js';
2
+ import { linearToSrgb, mat3NormalFromMat4, mat4Invert } from '../../rendering/world3d/math3D.js';
3
+ import { instanceStreamRevisions3D } from '../../rendering/world3d/Mesh3D.js';
4
+ import { SkinnedInstancedMesh3D } from '../../rendering/world3d/AnimationTexture3D.js';
5
+ import { GpuParticles3D } from '../../rendering/world3d/GpuParticles3D.js';
6
+ import { RenderList3D } from '../../rendering/world3d/RenderList3D.js';
7
+ import { COMPRESSED_BLOCK_BYTES_3D, CubeTexture3D, RenderTarget3D, isCompressedPixels3D, isTexturePixels3D } from '../../rendering/world3d/Texture3D.js';
8
+ import { FRAME_BLOCK_FLOATS_3D, FRAME_OFFSETS_3D, TILED_LIGHTS_3D, writeTiledLights3D, outputToneMapping3D, planShadows3D, writeFrameBlock3D } from './frame3D.js';
9
+ import { createPostProcessSettings3D, outlineActive3D, postViewFromCamera3D } from './post3D.js';
10
+ import { PostChainWebGPU3D } from './postWebGPU3D.js';
11
+ import { MATERIAL_BLOCK_BYTES_3D, MIPMAP_WGSL_3D, OBJECT_BLOCK_BYTES_3D, SKYBOX_WGSL_3D, buildMaterialWgsl3D, shaderFeatureKey3D } from './wgsl3D.js';
12
+ import { convertVertexAttribute3D, packMorphStorage3D, packWireIndices3D, writeObjectMorph3D } from './webgpuPacking3D.js';
13
+ // WebGPU flag values, spelled out so this module needs no global constant namespaces.
14
+ const SHADER_STAGE = Object.freeze({ VERTEX: 1, FRAGMENT: 2 });
15
+ const BUFFER_USAGE = Object.freeze({
16
+ MAP_READ: 1,
17
+ COPY_DST: 8,
18
+ INDEX: 16,
19
+ VERTEX: 32,
20
+ UNIFORM: 64,
21
+ STORAGE: 128
22
+ });
23
+ const TEXTURE_USAGE = Object.freeze({ COPY_SRC: 1, COPY_DST: 2, TEXTURE_BINDING: 4, RENDER_ATTACHMENT: 16 });
24
+ const MAP_MODE_READ = 1;
25
+ const ATTRIBUTE_SLOTS = ['position', 'normal', 'uv', 'tangent', 'color', 'joints', 'weights', 'uv1'];
26
+ const TARGET_FORMAT = 'rgba8unorm-srgb', HDR_FORMAT = 'rgba16float';
27
+ const SHADOW_FORMAT = 'depth32float';
28
+ const DEPTH_FORMAT = 'depth24plus';
29
+ const IDENTITY4 = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
30
+ const PRUNE_INTERVAL = 600;
31
+ function hostSize(source) {
32
+ const size = source;
33
+ return [Math.max(1, size.videoWidth ?? size.width ?? 1), Math.max(1, size.videoHeight ?? size.height ?? 1)];
34
+ }
35
+ // The device loss promise can outlive a renderer that borrows the device.
36
+ function observeDeviceLoss(device, listener) {
37
+ void device.lost.then(info => {
38
+ const callback = listener;
39
+ listener = undefined;
40
+ callback?.(info);
41
+ });
42
+ return () => {
43
+ listener = undefined;
44
+ };
45
+ }
46
+ /** Draws 3D scenes with WebGPU: set its size, render a scene from a camera, and read what it drew. */
47
+ export class WebGPURenderer3D {
48
+ canvas;
49
+ device;
50
+ toneMapping;
51
+ exposure;
52
+ shadowsEnabled;
53
+ /** Bloom, color grading and FXAA; set `enabled` to turn the chain on. */
54
+ postProcess = createPostProcessSettings3D();
55
+ viewport;
56
+ autoClear = true;
57
+ #post;
58
+ #inPost = false;
59
+ #frameToneMapping = 'none';
60
+ info = {
61
+ frame: 0,
62
+ drawCalls: 0,
63
+ triangles: 0,
64
+ visited: 0,
65
+ culled: 0,
66
+ lightsDropped: 0,
67
+ lightsTiled: 0,
68
+ shadowMaps: 0,
69
+ programs: 0,
70
+ geometries: 0,
71
+ textures: 0
72
+ };
73
+ #context;
74
+ #format;
75
+ #sampleCount;
76
+ #alpha;
77
+ #ownsDevice;
78
+ #list = new RenderList3D();
79
+ #frameData = new Float32Array(FRAME_BLOCK_FLOATS_3D);
80
+ #frameBuffer;
81
+ #tiledTable = new Float32Array(TILED_LIGHTS_3D.width * TILED_LIGHTS_3D.rows * 4);
82
+ #tiledBuffer;
83
+ #frameLayout;
84
+ #depthFrameLayout;
85
+ #materialLayout;
86
+ #objectLayout;
87
+ #skinLayout;
88
+ #pipelineLayout;
89
+ #depthPipelineLayout;
90
+ #modules = new Map();
91
+ #pipelines = new Map();
92
+ #geometries = new Map();
93
+ #instances = new Map();
94
+ #textures = new Map();
95
+ #targets = new Map();
96
+ #materials = new Map();
97
+ #bones = new Map();
98
+ #animations = new Map();
99
+ #sceneDepth;
100
+ /** True while the frame being drawn has a depth image of its solid geometry. */
101
+ #softDepth = false;
102
+ #sceneDepthSerial = 0;
103
+ #skins = new WeakMap();
104
+ #samplers = new Map();
105
+ #mipPipelines = new Map();
106
+ #shadowSlots = new Map();
107
+ #depthFrames = [];
108
+ #whiteTexture;
109
+ #whiteCubeTexture;
110
+ #white;
111
+ #whiteCube;
112
+ #unsubscribeDeviceLoss;
113
+ #defaultSampler;
114
+ #shadowSampler;
115
+ #dummyBones;
116
+ #dummyMorph;
117
+ #dummySkin;
118
+ #shadowAtlasSize;
119
+ #shadowTexture;
120
+ #shadowView;
121
+ #frameGroup;
122
+ #grabSampler;
123
+ /** Copies of the output for see-through surfaces, one per kind of output. */
124
+ #grabs = new Map();
125
+ #frameGroupKey = '';
126
+ #objectBuffer;
127
+ #objectGroup;
128
+ #objectCapacity = 256;
129
+ #objectStaging = new ArrayBuffer(256 * OBJECT_BLOCK_BYTES_3D);
130
+ #objectFloats = new Float32Array(this.#objectStaging);
131
+ #objectInts = new Int32Array(this.#objectStaging);
132
+ #objectCount = 0;
133
+ #canvasDepth;
134
+ #canvasColor;
135
+ #canvasKey = '';
136
+ #skyBuffer;
137
+ #skyGroup;
138
+ #skyLayout;
139
+ #serial = 0;
140
+ #shadowCount = 0;
141
+ #lost = false;
142
+ #disposed = false;
143
+ #scratch16 = new Float32Array(16);
144
+ #scratch9 = new Float32Array(9);
145
+ #materialData = new Float32Array(MATERIAL_BLOCK_BYTES_3D / 4);
146
+ /** Use createWebGPURenderer3D(); the constructor needs an acquired device. */
147
+ constructor(options, device, ownsDevice) {
148
+ const canvas = options.canvas;
149
+ const context = canvas.getContext('webgpu');
150
+ if (!context)
151
+ throw new World3DError('WORLD3D_CONTEXT_UNAVAILABLE', 'webgpu canvas context');
152
+ this.canvas = canvas;
153
+ this.device = device;
154
+ this.#ownsDevice = ownsDevice;
155
+ this.#context = context;
156
+ this.#format = navigator.gpu.getPreferredCanvasFormat();
157
+ this.#alpha = options.alpha ?? false;
158
+ this.#sampleCount = (options.antialias ?? true) ? 4 : 1;
159
+ this.toneMapping = options.toneMapping ?? 'aces';
160
+ this.exposure = options.exposure ?? 1;
161
+ this.shadowsEnabled = options.shadows ?? true;
162
+ this.#shadowAtlasSize = Math.min(options.shadowAtlasSize ?? 2048, device.limits.maxTextureDimension2D);
163
+ // The canvas image is copied when see-through surfaces need what lies behind them.
164
+ context.configure({
165
+ device,
166
+ format: this.#format,
167
+ alphaMode: this.#alpha ? 'premultiplied' : 'opaque',
168
+ usage: TEXTURE_USAGE.RENDER_ATTACHMENT | TEXTURE_USAGE.COPY_SRC
169
+ });
170
+ const filtering = [];
171
+ for (let i = 0; i < 7; i++) {
172
+ filtering.push({ binding: 1 + i * 2, visibility: SHADER_STAGE.FRAGMENT, texture: {} });
173
+ filtering.push({ binding: 2 + i * 2, visibility: SHADER_STAGE.FRAGMENT, sampler: {} });
174
+ }
175
+ const both = SHADER_STAGE.VERTEX | SHADER_STAGE.FRAGMENT;
176
+ this.#frameLayout = device.createBindGroupLayout({
177
+ entries: [
178
+ { binding: 0, visibility: both, buffer: {} },
179
+ { binding: 1, visibility: SHADER_STAGE.FRAGMENT, texture: { sampleType: 'depth' } },
180
+ { binding: 2, visibility: SHADER_STAGE.FRAGMENT, sampler: { type: 'comparison' } },
181
+ { binding: 3, visibility: SHADER_STAGE.FRAGMENT, texture: { viewDimension: 'cube' } },
182
+ { binding: 4, visibility: SHADER_STAGE.FRAGMENT, sampler: {} },
183
+ { binding: 5, visibility: SHADER_STAGE.FRAGMENT, texture: {} },
184
+ { binding: 6, visibility: SHADER_STAGE.FRAGMENT, sampler: {} },
185
+ { binding: 7, visibility: SHADER_STAGE.FRAGMENT, texture: { sampleType: 'depth' } },
186
+ { binding: 8, visibility: SHADER_STAGE.FRAGMENT, buffer: { type: 'read-only-storage' } }
187
+ ]
188
+ });
189
+ this.#depthFrameLayout = device.createBindGroupLayout({ entries: [{ binding: 0, visibility: both, buffer: {} }] });
190
+ this.#materialLayout = device.createBindGroupLayout({
191
+ entries: [{ binding: 0, visibility: both, buffer: {} }, ...filtering]
192
+ });
193
+ this.#objectLayout = device.createBindGroupLayout({
194
+ entries: [
195
+ { binding: 0, visibility: both, buffer: { hasDynamicOffset: true, minBindingSize: OBJECT_BLOCK_BYTES_3D } }
196
+ ]
197
+ });
198
+ this.#skinLayout = device.createBindGroupLayout({
199
+ entries: [
200
+ { binding: 0, visibility: SHADER_STAGE.VERTEX, buffer: { type: 'read-only-storage' } },
201
+ { binding: 1, visibility: SHADER_STAGE.VERTEX, buffer: { type: 'read-only-storage' } }
202
+ ]
203
+ });
204
+ this.#pipelineLayout = device.createPipelineLayout({
205
+ bindGroupLayouts: [this.#frameLayout, this.#materialLayout, this.#objectLayout, this.#skinLayout]
206
+ });
207
+ this.#depthPipelineLayout = device.createPipelineLayout({
208
+ bindGroupLayouts: [this.#depthFrameLayout, this.#materialLayout, this.#objectLayout, this.#skinLayout]
209
+ });
210
+ this.#frameBuffer = device.createBuffer({
211
+ size: FRAME_BLOCK_FLOATS_3D * 4,
212
+ usage: BUFFER_USAGE.UNIFORM | BUFFER_USAGE.COPY_DST
213
+ });
214
+ this.#tiledBuffer = device.createBuffer({
215
+ size: this.#tiledTable.byteLength,
216
+ usage: BUFFER_USAGE.STORAGE | BUFFER_USAGE.COPY_DST
217
+ });
218
+ this.#objectBuffer = this.createObjectBuffer();
219
+ this.#objectGroup = this.createObjectGroup();
220
+ const white = (this.#whiteTexture = device.createTexture({
221
+ size: [1, 1],
222
+ format: 'rgba8unorm',
223
+ usage: TEXTURE_USAGE.TEXTURE_BINDING | TEXTURE_USAGE.COPY_DST
224
+ }));
225
+ device.queue.writeTexture({ texture: white }, new Uint8Array([255, 255, 255, 255]), {}, [1, 1]);
226
+ this.#white = white.createView();
227
+ const whiteCube = (this.#whiteCubeTexture = device.createTexture({
228
+ size: [1, 1, 6],
229
+ format: 'rgba8unorm',
230
+ usage: TEXTURE_USAGE.TEXTURE_BINDING | TEXTURE_USAGE.COPY_DST
231
+ }));
232
+ for (let face = 0; face < 6; face++)
233
+ device.queue.writeTexture({ texture: whiteCube, origin: [0, 0, face] }, new Uint8Array([255, 255, 255, 255]), {}, [1, 1]);
234
+ this.#whiteCube = whiteCube.createView({ dimension: 'cube' });
235
+ this.#defaultSampler = device.createSampler({ magFilter: 'linear', minFilter: 'linear', mipmapFilter: 'linear' });
236
+ this.#shadowSampler = device.createSampler({ compare: 'less-equal', magFilter: 'linear', minFilter: 'linear' });
237
+ this.#grabSampler = device.createSampler({
238
+ magFilter: 'linear',
239
+ minFilter: 'linear',
240
+ addressModeU: 'clamp-to-edge',
241
+ addressModeV: 'clamp-to-edge'
242
+ });
243
+ this.#dummyBones = device.createBuffer({ size: 64, usage: BUFFER_USAGE.STORAGE });
244
+ this.#dummyMorph = device.createBuffer({ size: 16, usage: BUFFER_USAGE.STORAGE });
245
+ this.#dummySkin = this.createSkinGroup(this.#dummyBones, this.#dummyMorph);
246
+ this.#unsubscribeDeviceLoss = observeDeviceLoss(device, info => {
247
+ this.#lost = true;
248
+ options.onDeviceLost?.(info.message);
249
+ });
250
+ }
251
+ get isDeviceLost() {
252
+ return this.#lost;
253
+ }
254
+ setSize(width, height, pixelRatio = 1) {
255
+ const w = Math.max(1, Math.floor(width * pixelRatio)), h = Math.max(1, Math.floor(height * pixelRatio));
256
+ if (!Number.isFinite(w) || !Number.isFinite(h))
257
+ throw new World3DError('WORLD3D_INPUT_INVALID', 'size');
258
+ if (this.canvas.width !== w)
259
+ this.canvas.width = w;
260
+ if (this.canvas.height !== h)
261
+ this.canvas.height = h;
262
+ }
263
+ resizeToDisplaySize(pixelRatio = 1) {
264
+ const element = this.canvas;
265
+ if (typeof element.clientWidth !== 'number')
266
+ return false;
267
+ const w = Math.max(1, Math.floor(element.clientWidth * pixelRatio)), h = Math.max(1, Math.floor(element.clientHeight * pixelRatio));
268
+ if (element.width === w && element.height === h)
269
+ return false;
270
+ element.width = w;
271
+ element.height = h;
272
+ return true;
273
+ }
274
+ // ---- small GPU helpers -----------------------------------------------------
275
+ createObjectBuffer() {
276
+ return this.device.createBuffer({
277
+ size: this.#objectCapacity * OBJECT_BLOCK_BYTES_3D,
278
+ usage: BUFFER_USAGE.UNIFORM | BUFFER_USAGE.COPY_DST
279
+ });
280
+ }
281
+ createObjectGroup() {
282
+ return this.device.createBindGroup({
283
+ layout: this.#objectLayout,
284
+ entries: [{ binding: 0, resource: { buffer: this.#objectBuffer, size: OBJECT_BLOCK_BYTES_3D } }]
285
+ });
286
+ }
287
+ createSkinGroup(bones, morph) {
288
+ return this.device.createBindGroup({
289
+ layout: this.#skinLayout,
290
+ entries: [
291
+ { binding: 0, resource: { buffer: bones } },
292
+ { binding: 1, resource: { buffer: morph } }
293
+ ]
294
+ });
295
+ }
296
+ /** Write `data` into a buffer of at least its size, recreating the buffer when it must grow. */
297
+ writeBuffer(entry, data, usage, length = data.length) {
298
+ const bytes = Math.max(4, Math.ceil((length * data.BYTES_PER_ELEMENT) / 4) * 4);
299
+ let target = entry;
300
+ if (!target || target.bytes < bytes) {
301
+ target?.buffer.destroy();
302
+ target = {
303
+ buffer: this.device.createBuffer({ size: bytes, usage: usage | BUFFER_USAGE.COPY_DST }),
304
+ version: -1,
305
+ bytes
306
+ };
307
+ }
308
+ // Uint16 index data may end on a 2-byte boundary; pad the final write to 4 bytes.
309
+ if ((length * data.BYTES_PER_ELEMENT) % 4 === 0)
310
+ this.device.queue.writeBuffer(target.buffer, 0, data.buffer, data.byteOffset, length * data.BYTES_PER_ELEMENT);
311
+ else {
312
+ const padded = new Uint16Array(length + 1);
313
+ padded.set(data.subarray(0, length));
314
+ this.device.queue.writeBuffer(target.buffer, 0, padded);
315
+ }
316
+ return target;
317
+ }
318
+ sampler(texture) {
319
+ const anisotropy = texture.magFilter === 'linear' && texture.minFilter === 'linear' && texture.mipmaps
320
+ ? Math.min(Math.max(Math.floor(texture.anisotropy), 1), 16)
321
+ : 1;
322
+ const key = texture.wrapS + texture.wrapT + texture.magFilter + texture.minFilter + texture.mipmaps + anisotropy;
323
+ let sampler = this.#samplers.get(key);
324
+ if (!sampler) {
325
+ const wrap = (mode) => mode === 'clamp' ? 'clamp-to-edge' : mode === 'mirror' ? 'mirror-repeat' : 'repeat';
326
+ sampler = this.device.createSampler({
327
+ addressModeU: wrap(texture.wrapS),
328
+ addressModeV: wrap(texture.wrapT),
329
+ addressModeW: 'clamp-to-edge',
330
+ magFilter: texture.magFilter,
331
+ minFilter: texture.minFilter,
332
+ mipmapFilter: texture.mipmaps ? 'linear' : 'nearest',
333
+ maxAnisotropy: anisotropy
334
+ });
335
+ this.#samplers.set(key, sampler);
336
+ }
337
+ return sampler;
338
+ }
339
+ // ---- textures ---------------------------------------------------------------
340
+ uploadSource(texture, source, layer, flipY) {
341
+ const queue = this.device.queue;
342
+ if (isTexturePixels3D(source)) {
343
+ let data = source.data;
344
+ if (flipY) {
345
+ const row = source.width * 4, flipped = new Uint8Array(data.length);
346
+ for (let y = 0; y < source.height; y++)
347
+ flipped.set(data.subarray(y * row, y * row + row), (source.height - 1 - y) * row);
348
+ data = flipped;
349
+ }
350
+ queue.writeTexture({ texture, origin: [0, 0, layer] }, data.buffer, { offset: data.byteOffset, bytesPerRow: source.width * 4, rowsPerImage: source.height }, [source.width, source.height]);
351
+ return;
352
+ }
353
+ const [width, height] = hostSize(source);
354
+ queue.copyExternalImageToTexture({ source: source, flipY }, { texture, origin: [0, 0, layer] }, [width, height]);
355
+ }
356
+ generateMipmaps(texture, layers) {
357
+ const device = this.device, format = texture.format;
358
+ let pipeline = this.#mipPipelines.get(format);
359
+ if (!pipeline) {
360
+ const module = device.createShaderModule({ code: MIPMAP_WGSL_3D });
361
+ pipeline = device.createRenderPipeline({
362
+ layout: 'auto',
363
+ vertex: { module, entryPoint: 'vertexMain' },
364
+ fragment: { module, entryPoint: 'fragmentMain', targets: [{ format }] },
365
+ primitive: { topology: 'triangle-list' }
366
+ });
367
+ this.#mipPipelines.set(format, pipeline);
368
+ }
369
+ const encoder = device.createCommandEncoder();
370
+ for (let layer = 0; layer < layers; layer++) {
371
+ for (let level = 1; level < texture.mipLevelCount; level++) {
372
+ const source = texture.createView({
373
+ dimension: '2d',
374
+ baseMipLevel: level - 1,
375
+ mipLevelCount: 1,
376
+ baseArrayLayer: layer,
377
+ arrayLayerCount: 1
378
+ });
379
+ const pass = encoder.beginRenderPass({
380
+ colorAttachments: [
381
+ {
382
+ view: texture.createView({
383
+ dimension: '2d',
384
+ baseMipLevel: level,
385
+ mipLevelCount: 1,
386
+ baseArrayLayer: layer,
387
+ arrayLayerCount: 1
388
+ }),
389
+ loadOp: 'clear',
390
+ storeOp: 'store'
391
+ }
392
+ ]
393
+ });
394
+ pass.setPipeline(pipeline);
395
+ pass.setBindGroup(0, device.createBindGroup({
396
+ layout: pipeline.getBindGroupLayout(0),
397
+ entries: [
398
+ { binding: 0, resource: source },
399
+ { binding: 1, resource: this.#defaultSampler }
400
+ ]
401
+ }));
402
+ pass.draw(3);
403
+ pass.end();
404
+ }
405
+ }
406
+ device.queue.submit([encoder.finish()]);
407
+ }
408
+ createColorTexture(width, height, layers, texture) {
409
+ const limit = this.device.limits.maxTextureDimension2D;
410
+ if (width > limit || height > limit)
411
+ throw new World3DError('WORLD3D_BUDGET', 'texture size');
412
+ return this.device.createTexture({
413
+ size: [width, height, layers],
414
+ format: texture.colorSpace === 'srgb' ? 'rgba8unorm-srgb' : 'rgba8unorm',
415
+ mipLevelCount: texture.mipmaps ? Math.floor(Math.log2(Math.max(width, height))) + 1 : 1,
416
+ usage: TEXTURE_USAGE.TEXTURE_BINDING | TEXTURE_USAGE.COPY_DST | TEXTURE_USAGE.RENDER_ATTACHMENT
417
+ });
418
+ }
419
+ textureEntry(texture, create) {
420
+ let entry = this.#textures.get(texture);
421
+ if (entry && entry.version === texture.version)
422
+ return entry;
423
+ const { texture: gpu, view } = create();
424
+ const previous = entry?.texture;
425
+ if (entry) {
426
+ entry.texture = gpu;
427
+ entry.view = view;
428
+ }
429
+ else {
430
+ const created = {
431
+ texture: gpu,
432
+ view,
433
+ sampler: this.#defaultSampler,
434
+ version: -1,
435
+ maxMip: 0,
436
+ unsubscribe: texture.onDispose(() => {
437
+ const current = this.#textures.get(texture);
438
+ if (current && this.#textures.delete(texture))
439
+ current.texture.destroy();
440
+ })
441
+ };
442
+ this.#textures.set(texture, (entry = created));
443
+ }
444
+ previous?.destroy();
445
+ entry.sampler = this.sampler(texture);
446
+ entry.maxMip = gpu.mipLevelCount - 1;
447
+ entry.version = texture.version;
448
+ return entry;
449
+ }
450
+ /** GPU view and sampler for a 2D texture, uploading when its version changed. */
451
+ texture2d(texture) {
452
+ const source = texture.source;
453
+ if (source instanceof RenderTarget3D) {
454
+ // A target's texture samples the color attachment directly.
455
+ const target = this.target(source);
456
+ return { view: target.colorView, sampler: this.sampler(texture), key: 't' + source.id + ':' + source.version };
457
+ }
458
+ const entry = this.textureEntry(texture, () => {
459
+ if (isCompressedPixels3D(source)) {
460
+ const format = this.compressedFormat(source.format, texture.colorSpace === 'srgb');
461
+ if (!format)
462
+ throw new World3DError('WORLD3D_RESOURCE_FAILED', 'compressed format ' + source.format + ' is not supported by this device');
463
+ const block = COMPRESSED_BLOCK_BYTES_3D[source.format];
464
+ // The base size must be block-aligned; smaller mips are padded to whole blocks on upload.
465
+ const gpu = this.device.createTexture({
466
+ size: [Math.ceil(source.width / 4) * 4, Math.ceil(source.height / 4) * 4],
467
+ format,
468
+ mipLevelCount: source.levels.length,
469
+ usage: TEXTURE_USAGE.TEXTURE_BINDING | TEXTURE_USAGE.COPY_DST
470
+ });
471
+ let width = gpu.width, height = gpu.height;
472
+ source.levels.forEach((level, mipLevel) => {
473
+ const columns = Math.ceil(width / 4), rows = Math.ceil(height / 4);
474
+ this.device.queue.writeTexture({ texture: gpu, mipLevel }, level.buffer, { offset: level.byteOffset, bytesPerRow: columns * block, rowsPerImage: rows }, [columns * 4, rows * 4]);
475
+ width = Math.max(1, width >> 1);
476
+ height = Math.max(1, height >> 1);
477
+ });
478
+ return { texture: gpu, view: gpu.createView() };
479
+ }
480
+ const [width, height] = isTexturePixels3D(source) ? [source.width, source.height] : hostSize(source);
481
+ const gpu = this.createColorTexture(width, height, 1, texture);
482
+ this.uploadSource(gpu, source, 0, texture.flipY);
483
+ if (gpu.mipLevelCount > 1)
484
+ this.generateMipmaps(gpu, 1);
485
+ return { texture: gpu, view: gpu.createView() };
486
+ });
487
+ return { view: entry.view, sampler: entry.sampler, key: texture.id + ':' + texture.version };
488
+ }
489
+ compressedFormat(format, srgb) {
490
+ const table = {
491
+ 'bc1': ['texture-compression-bc', 'bc1-rgba-unorm'],
492
+ 'bc3': ['texture-compression-bc', 'bc3-rgba-unorm'],
493
+ 'bc7': ['texture-compression-bc', 'bc7-rgba-unorm'],
494
+ 'etc2-rgb8': ['texture-compression-etc2', 'etc2-rgb8unorm'],
495
+ 'etc2-rgba8': ['texture-compression-etc2', 'etc2-rgba8unorm'],
496
+ 'astc-4x4': ['texture-compression-astc', 'astc-4x4-unorm']
497
+ };
498
+ const entry = table[format];
499
+ if (!entry || !this.device.features.has(entry[0]))
500
+ return undefined;
501
+ return (entry[1] + (srgb ? '-srgb' : ''));
502
+ }
503
+ /** True when textures in this compressed format can be used on this device. */
504
+ supportsCompressedFormat(format) {
505
+ return this.compressedFormat(format, false) !== undefined;
506
+ }
507
+ textureCube(texture) {
508
+ return this.textureEntry(texture, () => {
509
+ const first = texture.faces[0], size = isTexturePixels3D(first) ? first.width : hostSize(first)[0];
510
+ const gpu = this.createColorTexture(size, size, 6, texture);
511
+ texture.faces.forEach((face, layer) => this.uploadSource(gpu, face, layer, false));
512
+ if (gpu.mipLevelCount > 1)
513
+ this.generateMipmaps(gpu, 6);
514
+ return { texture: gpu, view: gpu.createView({ dimension: 'cube' }) };
515
+ });
516
+ }
517
+ target(target) {
518
+ if (target.isDisposed)
519
+ throw new World3DError('WORLD3D_DISPOSED', 'render target');
520
+ let entry = this.#targets.get(target);
521
+ if (entry && entry.version === target.version)
522
+ return entry;
523
+ const limit = this.device.limits.maxTextureDimension2D;
524
+ if (target.width > limit || target.height > limit)
525
+ throw new World3DError('WORLD3D_BUDGET', 'render target size');
526
+ const color = this.device.createTexture({
527
+ size: [target.width, target.height],
528
+ format: target.format === 'rgba16f' ? HDR_FORMAT : TARGET_FORMAT,
529
+ usage: TEXTURE_USAGE.RENDER_ATTACHMENT | TEXTURE_USAGE.TEXTURE_BINDING | TEXTURE_USAGE.COPY_SRC
530
+ });
531
+ const depth = target.depth
532
+ ? this.device.createTexture({
533
+ size: [target.width, target.height],
534
+ format: DEPTH_FORMAT,
535
+ usage: target.depthTexture
536
+ ? TEXTURE_USAGE.RENDER_ATTACHMENT | TEXTURE_USAGE.TEXTURE_BINDING
537
+ : TEXTURE_USAGE.RENDER_ATTACHMENT
538
+ })
539
+ : undefined;
540
+ if (entry) {
541
+ entry.color.destroy();
542
+ entry.depth?.destroy();
543
+ entry.color = color;
544
+ entry.colorView = color.createView();
545
+ entry.depth = depth;
546
+ entry.depthView = depth?.createView();
547
+ }
548
+ else {
549
+ const created = {
550
+ color,
551
+ colorView: color.createView(),
552
+ depth,
553
+ depthView: depth?.createView(),
554
+ version: -1,
555
+ unsubscribe: target.onDispose(() => {
556
+ const current = this.#targets.get(target);
557
+ if (current && this.#targets.delete(target)) {
558
+ current.color.destroy();
559
+ current.depth?.destroy();
560
+ }
561
+ })
562
+ };
563
+ this.#targets.set(target, (entry = created));
564
+ }
565
+ entry.version = target.version;
566
+ return entry;
567
+ }
568
+ // ---- geometry ---------------------------------------------------------------
569
+ convert(name, attribute) {
570
+ return convertVertexAttribute3D(name, attribute);
571
+ }
572
+ geometry(geometry) {
573
+ let entry = this.#geometries.get(geometry);
574
+ // Buffers are checked against the CPU versions once per render call.
575
+ if (entry && entry.serial === this.#serial)
576
+ return entry;
577
+ if (!entry) {
578
+ const created = {
579
+ buffers: new Map(),
580
+ index: undefined,
581
+ wire: undefined,
582
+ morph: undefined,
583
+ layoutVersion: -1,
584
+ serial: -1,
585
+ unsubscribe: geometry.onDispose(() => this.releaseGeometry(geometry))
586
+ };
587
+ this.#geometries.set(geometry, (entry = created));
588
+ }
589
+ for (const name of ATTRIBUTE_SLOTS) {
590
+ const attribute = geometry.getAttribute(name), current = entry.buffers.get(name);
591
+ if (!attribute) {
592
+ if (current) {
593
+ current.buffer.destroy();
594
+ entry.buffers.delete(name);
595
+ }
596
+ continue;
597
+ }
598
+ if (current && current.version === attribute.version)
599
+ continue;
600
+ const next = this.writeBuffer(current, this.convert(name, attribute), BUFFER_USAGE.VERTEX);
601
+ next.version = attribute.version;
602
+ entry.buffers.set(name, next);
603
+ }
604
+ const index = geometry.index;
605
+ if (index) {
606
+ if (!entry.index || entry.index.version !== index.version) {
607
+ const data = index.data instanceof Uint32Array || index.data instanceof Uint16Array
608
+ ? index.data
609
+ : Uint16Array.from(index.data);
610
+ const next = this.writeBuffer(entry.index, data, BUFFER_USAGE.INDEX);
611
+ entry.index = {
612
+ buffer: next.buffer,
613
+ bytes: next.bytes,
614
+ version: index.version,
615
+ format: data instanceof Uint32Array ? 'uint32' : 'uint16'
616
+ };
617
+ }
618
+ }
619
+ else if (entry.index) {
620
+ entry.index.buffer.destroy();
621
+ entry.index = undefined;
622
+ }
623
+ if (entry.layoutVersion !== geometry.layoutVersion) {
624
+ entry.morph?.buffer.destroy();
625
+ entry.morph = undefined;
626
+ const targets = geometry.morphTargets;
627
+ if (targets.length > 0) {
628
+ const vertexCount = geometry.vertexCount, channels = targets.some(target => target.normal) ? 2 : 1;
629
+ const data = packMorphStorage3D(targets, channels, vertexCount);
630
+ if (data.byteLength > this.device.limits.maxStorageBufferBindingSize)
631
+ throw new World3DError('WORLD3D_BUDGET', 'morph target data');
632
+ entry.morph = { buffer: this.writeBuffer(undefined, data, BUFFER_USAGE.STORAGE).buffer, channels, vertexCount };
633
+ }
634
+ entry.wire?.buffer.destroy();
635
+ entry.wire = undefined;
636
+ entry.layoutVersion = geometry.layoutVersion;
637
+ }
638
+ entry.serial = this.#serial;
639
+ return entry;
640
+ }
641
+ wireframe(geometry, entry) {
642
+ if (entry.wire && entry.wire.version === geometry.version)
643
+ return entry.wire;
644
+ const lines = packWireIndices3D(geometry);
645
+ entry.wire?.buffer.destroy();
646
+ const wire = {
647
+ buffer: this.writeBuffer(undefined, lines, BUFFER_USAGE.INDEX).buffer,
648
+ count: lines.length,
649
+ version: geometry.version
650
+ };
651
+ entry.wire = wire;
652
+ return wire;
653
+ }
654
+ releaseGeometry(geometry) {
655
+ const entry = this.#geometries.get(geometry);
656
+ if (!entry)
657
+ return;
658
+ this.#geometries.delete(geometry);
659
+ for (const buffer of entry.buffers.values())
660
+ buffer.buffer.destroy();
661
+ entry.index?.buffer.destroy();
662
+ entry.wire?.buffer.destroy();
663
+ entry.morph?.buffer.destroy();
664
+ }
665
+ uploadInstances(entry, source, version) {
666
+ if (entry?.source === source && entry.version === version)
667
+ return entry;
668
+ const buffer = this.writeBuffer(entry, source, BUFFER_USAGE.VERTEX);
669
+ buffer.source = source;
670
+ buffer.version = version;
671
+ return buffer;
672
+ }
673
+ instances(mesh, frame) {
674
+ const crowd = mesh instanceof SkinnedInstancedMesh3D ? mesh : undefined;
675
+ const revisions = crowd ? undefined : instanceStreamRevisions3D(mesh);
676
+ const matrices = crowd?.drawMatrices ?? mesh.instanceMatrices;
677
+ const matrixVersion = revisions?.matrices ?? mesh.instanceVersion;
678
+ let entry = this.#instances.get(mesh);
679
+ const resident = this.uploadInstances(entry?.matrices, matrices, matrixVersion);
680
+ if (!entry) {
681
+ entry = { matrices: resident, colors: undefined, lastFrame: frame };
682
+ this.#instances.set(mesh, entry);
683
+ }
684
+ else
685
+ entry.matrices = resident;
686
+ entry.lastFrame = frame;
687
+ const colors = crowd ? crowd.drawColors : mesh.instanceColors;
688
+ if (colors)
689
+ entry.colors = this.uploadInstances(entry.colors, colors, revisions?.colors ?? mesh.instanceVersion);
690
+ else if (entry.colors)
691
+ entry.colors.source = undefined;
692
+ if (crowd)
693
+ entry.animation = this.uploadInstances(entry.animation, crowd.drawAnimation, mesh.instanceVersion);
694
+ return entry;
695
+ }
696
+ /** Bind group holding the bone matrices and morph deltas for a mesh. */
697
+ skin(mesh, gpu, skinned, frame) {
698
+ const crowd = !skinned && mesh instanceof SkinnedInstancedMesh3D ? mesh.animations : undefined;
699
+ if (!skinned && !gpu.morph && !crowd)
700
+ return this.#dummySkin;
701
+ let bonesBuffer = this.#dummyBones;
702
+ if (crowd) {
703
+ // Baked poses are uploaded once and stay until the table is disposed.
704
+ let table = this.#animations.get(crowd);
705
+ if (!table) {
706
+ table = this.device.createBuffer({
707
+ size: crowd.data.byteLength,
708
+ usage: BUFFER_USAGE.STORAGE | BUFFER_USAGE.COPY_DST
709
+ });
710
+ this.device.queue.writeBuffer(table, 0, crowd.data.buffer, crowd.data.byteOffset, crowd.data.byteLength);
711
+ this.#animations.set(crowd, table);
712
+ const created = table;
713
+ crowd.onDispose(() => {
714
+ if (this.#animations.get(crowd) === created) {
715
+ created.destroy();
716
+ this.#animations.delete(crowd);
717
+ }
718
+ });
719
+ }
720
+ bonesBuffer = table;
721
+ }
722
+ if (skinned) {
723
+ const skeleton = mesh.skeleton, count = skeleton.bones.length;
724
+ let bones = this.#bones.get(skeleton);
725
+ if (!bones || bones.count !== count) {
726
+ bones?.buffer.destroy();
727
+ bones = {
728
+ buffer: this.device.createBuffer({
729
+ size: Math.max(count, 1) * 64,
730
+ usage: BUFFER_USAGE.STORAGE | BUFFER_USAGE.COPY_DST
731
+ }),
732
+ version: -1,
733
+ count,
734
+ lastFrame: frame
735
+ };
736
+ this.#bones.set(skeleton, bones);
737
+ }
738
+ bones.lastFrame = frame;
739
+ if (bones.version !== skeleton.version && count > 0) {
740
+ this.device.queue.writeBuffer(bones.buffer, 0, skeleton.boneMatrices.buffer, skeleton.boneMatrices.byteOffset, skeleton.boneMatrices.byteLength);
741
+ bones.version = skeleton.version;
742
+ }
743
+ bonesBuffer = bones.buffer;
744
+ }
745
+ const morphBuffer = gpu.morph?.buffer ?? this.#dummyMorph;
746
+ let entry = this.#skins.get(mesh);
747
+ if (!entry || entry.bones !== bonesBuffer || entry.morph !== morphBuffer) {
748
+ entry = { group: this.createSkinGroup(bonesBuffer, morphBuffer), bones: bonesBuffer, morph: morphBuffer };
749
+ this.#skins.set(mesh, entry);
750
+ }
751
+ return entry.group;
752
+ }
753
+ // ---- materials and pipelines ---------------------------------------------------
754
+ material(material) {
755
+ let entry = this.#materials.get(material);
756
+ if (!entry) {
757
+ const buffer = this.device.createBuffer({
758
+ size: MATERIAL_BLOCK_BYTES_3D,
759
+ usage: BUFFER_USAGE.UNIFORM | BUFFER_USAGE.COPY_DST
760
+ });
761
+ const created = {
762
+ buffer,
763
+ group: undefined,
764
+ key: '',
765
+ serial: -1,
766
+ unsubscribe: material.onDispose(() => {
767
+ if (this.#materials.delete(material))
768
+ buffer.destroy();
769
+ })
770
+ };
771
+ this.#materials.set(material, (entry = created));
772
+ }
773
+ if (entry.serial === this.#serial && entry.group)
774
+ return entry.group;
775
+ entry.serial = this.#serial;
776
+ // Scalars are rewritten once per frame so plain field edits need no touch().
777
+ const data = this.#materialData, e = material.emissiveIntensity, map = material.map;
778
+ data[0] = material.color[0];
779
+ data[1] = material.color[1];
780
+ data[2] = material.color[2];
781
+ data[3] = material.opacity;
782
+ data[4] = material.emissive[0] * e;
783
+ data[5] = material.emissive[1] * e;
784
+ data[6] = material.emissive[2] * e;
785
+ data[7] = material.softness;
786
+ data[8] = material.metallic;
787
+ data[9] = material.roughness;
788
+ data[10] = material.normalScale;
789
+ data[11] = material.occlusionStrength;
790
+ data[12] = material.specular[0];
791
+ data[13] = material.specular[1];
792
+ data[14] = material.specular[2];
793
+ data[15] = material.shading === 'toon' ? material.toonSteps : material.shininess;
794
+ data[16] = material.alphaCutoff;
795
+ data[17] = material.environmentIntensity;
796
+ data[18] = material.clearcoat;
797
+ data[19] = material.clearcoatRoughness;
798
+ let ax = 1, bx = 0, tx = 0, ay = 0, by = 1, ty = 0;
799
+ if (map?.hasTransform) {
800
+ const c = Math.cos(map.rotation), s = Math.sin(map.rotation);
801
+ ax = c * map.repeat[0];
802
+ bx = -s * map.repeat[1];
803
+ tx = map.offset[0];
804
+ ay = s * map.repeat[0];
805
+ by = c * map.repeat[1];
806
+ ty = map.offset[1];
807
+ }
808
+ // WebGPU stores rendered images top row first, so target textures are read with V flipped.
809
+ if (map?.source instanceof RenderTarget3D) {
810
+ ay = -ay;
811
+ by = -by;
812
+ ty = 1 - ty;
813
+ }
814
+ data[20] = ax;
815
+ data[21] = bx;
816
+ data[22] = tx;
817
+ data[23] = 0;
818
+ data[24] = ay;
819
+ data[25] = by;
820
+ data[26] = ty;
821
+ data[27] = 0;
822
+ data[28] = material.rotation;
823
+ data[29] = material.sizeAttenuation ? 1 : 0;
824
+ data[30] = material.reflectionDistortion;
825
+ data[31] = material.reflectionStrength;
826
+ if (material.shader)
827
+ data.set(material.shader.uniforms, 32);
828
+ else
829
+ data.fill(0, 32, 48);
830
+ data[48] = material.sheenColor[0] * material.sheen;
831
+ data[49] = material.sheenColor[1] * material.sheen;
832
+ data[50] = material.sheenColor[2] * material.sheen;
833
+ data[51] = material.sheenRoughness;
834
+ data[52] = material.lightMapIntensity;
835
+ data[53] = material.transmission;
836
+ data[54] = material.ior;
837
+ data[55] = material.thickness;
838
+ data[56] = material.attenuationColor[0];
839
+ data[57] = material.attenuationColor[1];
840
+ data[58] = material.attenuationColor[2];
841
+ data[59] = Number.isFinite(material.attenuationDistance) ? material.attenuationDistance : 0;
842
+ const splat = material.splat;
843
+ data[60] = splat?.repeat[0] ?? 1;
844
+ data[61] = splat?.repeat[1] ?? 1;
845
+ data[62] = splat?.repeat[2] ?? 1;
846
+ data[63] = splat?.repeat[3] ?? 1;
847
+ this.device.queue.writeBuffer(entry.buffer, 0, data);
848
+ const entries = [{ binding: 0, resource: { buffer: entry.buffer } }];
849
+ let key = '';
850
+ // Ground layers borrow the slots of the maps they stand in for; a missing layer reads the first.
851
+ (splat
852
+ ? [
853
+ splat.layers[0],
854
+ material.normalMap,
855
+ splat.layers[3] ?? splat.layers[0],
856
+ splat.layers[2] ?? splat.layers[0],
857
+ splat.layers[1] ?? splat.layers[0],
858
+ splat.weights,
859
+ material.reflectionMap
860
+ ]
861
+ : [
862
+ material.map,
863
+ material.normalMap,
864
+ material.metallicRoughnessMap,
865
+ material.occlusionMap,
866
+ material.emissiveMap,
867
+ material.lightMap,
868
+ material.reflectionMap
869
+ ]).forEach((texture, i) => {
870
+ const gpu = texture && !texture.isDisposed ? this.texture2d(texture) : undefined;
871
+ entries.push({ binding: 1 + i * 2, resource: gpu?.view ?? this.#white }, { binding: 2 + i * 2, resource: gpu?.sampler ?? this.#defaultSampler });
872
+ key += (gpu?.key ?? '-') + '|';
873
+ });
874
+ if (!entry.group || entry.key !== key) {
875
+ entry.group = this.device.createBindGroup({ layout: this.#materialLayout, entries });
876
+ entry.key = key;
877
+ }
878
+ return entry.group;
879
+ }
880
+ features(item, gpu, kind, frameFlags) {
881
+ const { mesh, material } = item, depthOnly = kind === 'depth' || kind === 'scene-depth';
882
+ const lit = material.shading !== 'unlit' && material.shading !== 'matcap' && !depthOnly;
883
+ const uv = gpu.buffers.has('uv'), instanced = mesh.isInstanced;
884
+ // A map on the second coordinate set needs only that set; it falls back to the first when the geometry lacks it.
885
+ const second = gpu.buffers.has('uv1') && !depthOnly, occlusionUv1 = second && lit && material.occlusionMap?.channel === 1;
886
+ const emissiveUv1 = second && material.shading !== 'matcap' && material.emissiveMap?.channel === 1;
887
+ const lightUv1 = second && lit && material.lightMap?.channel === 1, lightMap = lit && material.lightMap !== undefined && (uv || lightUv1);
888
+ const skinning = mesh.skeleton !== undefined && gpu.buffers.has('joints') && gpu.buffers.has('weights');
889
+ // A draw may bind eight vertex buffers. Baked instances use them up, so they do without tangents, vertex colors and second coordinates.
890
+ const baked = instanced && !skinning && mesh instanceof SkinnedInstancedMesh3D;
891
+ return {
892
+ shading: material.shading,
893
+ depthOnly,
894
+ normal: gpu.buffers.has('normal') && (!depthOnly || material.shader?.wgslVertex !== undefined),
895
+ uv: uv &&
896
+ (!depthOnly ||
897
+ (material.map !== undefined && material.alphaMode !== 'opaque') ||
898
+ material.shader?.wgslVertex !== undefined),
899
+ tangent: lit && uv && material.normalMap !== undefined && gpu.buffers.has('tangent') && !baked,
900
+ vertexColor: material.vertexColors && gpu.buffers.has('color') && !baked,
901
+ skinning,
902
+ morph: gpu.morph !== undefined,
903
+ morphNormals: gpu.morph?.channels === 2,
904
+ skinInstancing: instanced &&
905
+ !skinning &&
906
+ mesh instanceof SkinnedInstancedMesh3D &&
907
+ gpu.buffers.has('joints') &&
908
+ gpu.buffers.has('weights'),
909
+ splat: !depthOnly && uv && material.splat !== undefined,
910
+ gpuParticles: instanced && !depthOnly && mesh instanceof GpuParticles3D,
911
+ softDepth: !depthOnly && material.softness > 0 && this.#softDepth,
912
+ instancing: instanced,
913
+ instanceColor: instanced && !depthOnly && mesh.instanceColors !== undefined,
914
+ billboard: material.billboard && !material.screenSpace,
915
+ screenSpace: material.screenSpace,
916
+ map: uv && material.map !== undefined && (!depthOnly || material.alphaMode !== 'opaque'),
917
+ mapFromTarget: !depthOnly && uv && material.map?.source instanceof RenderTarget3D,
918
+ normalMap: lit && uv && material.normalMap !== undefined,
919
+ metallicRoughnessMap: lit && uv && material.metallicRoughnessMap !== undefined && material.shading === 'standard',
920
+ occlusionMap: lit && (uv || occlusionUv1) && material.occlusionMap !== undefined,
921
+ uv1: (occlusionUv1 || emissiveUv1 || lightUv1) && !baked,
922
+ occlusionUv1: occlusionUv1 && !baked,
923
+ emissiveUv1: emissiveUv1 && !baked,
924
+ lightMap,
925
+ lightUv1: lightUv1 && !baked,
926
+ transmission: !depthOnly && this.#grabbed && material.shading === 'standard' && material.transmission > 0,
927
+ emissiveMap: !depthOnly && (uv || emissiveUv1) && material.emissiveMap !== undefined && material.shading !== 'matcap',
928
+ alphaMask: material.alphaMode === 'mask',
929
+ alphaBlend: material.alphaMode === 'blend',
930
+ premultipliedAlpha: !depthOnly && material.alphaMode === 'blend' && material.blending === 'premultiplied',
931
+ flatShading: material.flatShading,
932
+ doubleSided: material.side === 'double',
933
+ receiveShadow: lit && mesh.receiveShadow && this.#shadowCount > 0,
934
+ environment: lit && frameFlags.environment,
935
+ fog: !depthOnly && frameFlags.fog && material.fog,
936
+ ...(!depthOnly && material.shader?.wgsl !== undefined
937
+ ? { customKey: material.shader.key, customWgsl: material.shader.wgsl }
938
+ : {}),
939
+ ...(material.shader?.wgslVertex !== undefined
940
+ ? { customKey: material.shader.key, customVertexWgsl: material.shader.wgslVertex }
941
+ : {}),
942
+ ...(lit && material.shader?.wgslNormal !== undefined
943
+ ? { customKey: material.shader.key, customNormalWgsl: material.shader.wgslNormal }
944
+ : {}),
945
+ reflectionMap: lit && material.shading === 'standard' && material.reflectionMap !== undefined,
946
+ toneMapped: !depthOnly && this.#frameToneMapping !== 'none' && material.toneMapped,
947
+ linearOutput: kind === 'target' || kind === 'hdr'
948
+ };
949
+ }
950
+ pipeline(features, item, gpu, kind, mirrored, wire) {
951
+ const { geometry, material, mesh } = item, shadow = kind === 'depth', depthOnly = shadow || kind === 'scene-depth';
952
+ const featureKey = shaderFeatureKey3D(features);
953
+ const topology = wire
954
+ ? 'line-list'
955
+ : geometry.topology === 'triangles'
956
+ ? 'triangle-list'
957
+ : geometry.topology === 'lines'
958
+ ? 'line-list'
959
+ : geometry.topology === 'line-strip'
960
+ ? 'line-strip'
961
+ : 'point-list';
962
+ // Shadow maps draw both faces: closed and open meshes then cast alike.
963
+ const cull = shadow || material.side === 'double' || material.billboard ? 'none' : material.side === 'back' ? 'front' : 'back';
964
+ const blend = !depthOnly && material.alphaMode === 'blend' ? material.blending : 'off';
965
+ const depthWrite = shadow || material.depthWrite, offset = shadow ? '1.5,2' : material.polygonOffset ? material.polygonOffset.join(',') : '';
966
+ const colorSize = geometry.getAttribute('color')?.itemSize ?? 4, instanceColorSize = mesh.isInstanced ? mesh.instanceColorSize : 4;
967
+ const strip = topology === 'line-strip' && gpu.index ? gpu.index.format : '';
968
+ const key = [
969
+ featureKey,
970
+ kind,
971
+ topology,
972
+ cull,
973
+ mirrored ? 'cw' : 'ccw',
974
+ blend,
975
+ depthWrite,
976
+ material.depthTest,
977
+ offset,
978
+ colorSize,
979
+ instanceColorSize,
980
+ strip
981
+ ].join('/');
982
+ let pipeline = this.#pipelines.get(key);
983
+ if (pipeline)
984
+ return pipeline;
985
+ let module = this.#modules.get(featureKey);
986
+ if (!module) {
987
+ module = this.device.createShaderModule({ code: buildMaterialWgsl3D(features), label: featureKey });
988
+ this.#modules.set(featureKey, module);
989
+ }
990
+ const buffers = [];
991
+ const add = (enabled, location, format, stride) => {
992
+ if (enabled)
993
+ buffers.push({ arrayStride: stride, attributes: [{ shaderLocation: location, offset: 0, format }] });
994
+ };
995
+ add(true, 0, 'float32x3', 12);
996
+ add(features.normal, 1, 'float32x3', 12);
997
+ add(features.uv, 2, 'float32x2', 8);
998
+ add(features.tangent, 3, 'float32x4', 16);
999
+ add(features.vertexColor, 4, colorSize === 3 ? 'float32x3' : 'float32x4', colorSize * 4);
1000
+ add(features.skinning || features.skinInstancing === true, 5, 'uint32x4', 16);
1001
+ add(features.skinning || features.skinInstancing === true, 6, 'float32x4', 16);
1002
+ add(features.uv1, 7, 'float32x2', 8);
1003
+ if (features.instancing) {
1004
+ buffers.push({
1005
+ arrayStride: 64,
1006
+ stepMode: 'instance',
1007
+ attributes: [0, 1, 2, 3].map(column => ({
1008
+ shaderLocation: 8 + column,
1009
+ offset: column * 16,
1010
+ format: 'float32x4'
1011
+ }))
1012
+ });
1013
+ }
1014
+ if (features.instanceColor) {
1015
+ buffers.push({
1016
+ arrayStride: instanceColorSize * 4,
1017
+ stepMode: 'instance',
1018
+ attributes: [{ shaderLocation: 12, offset: 0, format: instanceColorSize === 3 ? 'float32x3' : 'float32x4' }]
1019
+ });
1020
+ }
1021
+ if (features.skinInstancing)
1022
+ buffers.push({
1023
+ arrayStride: 48,
1024
+ stepMode: 'instance',
1025
+ attributes: [0, 1, 2].map(part => ({
1026
+ shaderLocation: 13 + part,
1027
+ offset: part * 16,
1028
+ format: 'float32x4'
1029
+ }))
1030
+ });
1031
+ const blendState = blend === 'off'
1032
+ ? undefined
1033
+ : blend === 'additive'
1034
+ ? { color: { srcFactor: 'src-alpha', dstFactor: 'one' }, alpha: { srcFactor: 'zero', dstFactor: 'one' } }
1035
+ : blend === 'multiply'
1036
+ ? { color: { srcFactor: 'dst', dstFactor: 'zero' }, alpha: { srcFactor: 'zero', dstFactor: 'one' } }
1037
+ : blend === 'premultiplied'
1038
+ ? {
1039
+ color: { srcFactor: 'one', dstFactor: 'one-minus-src-alpha' },
1040
+ alpha: { srcFactor: 'one', dstFactor: 'one-minus-src-alpha' }
1041
+ }
1042
+ : {
1043
+ color: { srcFactor: 'src-alpha', dstFactor: 'one-minus-src-alpha' },
1044
+ alpha: { srcFactor: 'one', dstFactor: 'one-minus-src-alpha' }
1045
+ };
1046
+ const needsFragment = !depthOnly || features.alphaMask || features.alphaBlend;
1047
+ const filled = topology === 'triangle-list';
1048
+ const descriptor = {
1049
+ label: key,
1050
+ layout: depthOnly ? this.#depthPipelineLayout : this.#pipelineLayout,
1051
+ vertex: { module, entryPoint: 'vertexMain', buffers },
1052
+ primitive: {
1053
+ topology,
1054
+ cullMode: cull,
1055
+ frontFace: mirrored ? 'cw' : 'ccw',
1056
+ ...(strip ? { stripIndexFormat: strip } : {})
1057
+ },
1058
+ depthStencil: {
1059
+ format: depthOnly ? SHADOW_FORMAT : DEPTH_FORMAT,
1060
+ depthWriteEnabled: depthWrite,
1061
+ depthCompare: material.depthTest || shadow ? 'less-equal' : 'always',
1062
+ // Depth bias applies to filled triangles only.
1063
+ ...(filled && shadow ? { depthBias: 2, depthBiasSlopeScale: 1.5 } : {}),
1064
+ ...(filled && !shadow && material.polygonOffset
1065
+ ? { depthBias: Math.round(material.polygonOffset[1]), depthBiasSlopeScale: material.polygonOffset[0] }
1066
+ : {})
1067
+ },
1068
+ multisample: { count: kind === 'canvas' ? this.#sampleCount : 1 },
1069
+ ...(needsFragment
1070
+ ? {
1071
+ fragment: {
1072
+ module,
1073
+ entryPoint: 'fragmentMain',
1074
+ targets: depthOnly
1075
+ ? []
1076
+ : [{ format: this.colorFormat(kind), ...(blendState ? { blend: blendState } : {}) }]
1077
+ }
1078
+ }
1079
+ : {})
1080
+ };
1081
+ pipeline = this.device.createRenderPipeline(descriptor);
1082
+ this.#pipelines.set(key, pipeline);
1083
+ return pipeline;
1084
+ }
1085
+ // ---- drawing -----------------------------------------------------------------
1086
+ writeObject(mesh, gpu, skinned) {
1087
+ const index = this.#objectCount++, o = index * (OBJECT_BLOCK_BYTES_3D / 4), floats = this.#objectFloats, ints = this.#objectInts;
1088
+ if (skinned) {
1089
+ floats.set(IDENTITY4, o);
1090
+ floats.set(mesh.bindMatrix, o + 28);
1091
+ }
1092
+ else {
1093
+ floats.set(mesh.matrixWorld, o);
1094
+ const normal = mat3NormalFromMat4(this.#scratch9, mesh.matrixWorld);
1095
+ for (let column = 0; column < 3; column++) {
1096
+ floats[o + 16 + column * 4] = normal[column * 3];
1097
+ floats[o + 17 + column * 4] = normal[column * 3 + 1];
1098
+ floats[o + 18 + column * 4] = normal[column * 3 + 2];
1099
+ }
1100
+ }
1101
+ if (gpu.morph) {
1102
+ writeObjectMorph3D(mesh, gpu, floats, ints, o);
1103
+ }
1104
+ else
1105
+ ints[o + 46] = 0;
1106
+ return index * OBJECT_BLOCK_BYTES_3D;
1107
+ }
1108
+ // Pass-local memo of the last bound state; consecutive draws that share it skip the redundant calls.
1109
+ #boundPipeline;
1110
+ #boundMaterial;
1111
+ #boundSkin;
1112
+ #boundVertices;
1113
+ #boundIndex;
1114
+ #drawVariants = new WeakMap();
1115
+ #grabbed = false;
1116
+ resetPassState() {
1117
+ this.#boundPipeline = undefined;
1118
+ this.#boundMaterial = undefined;
1119
+ this.#boundSkin = undefined;
1120
+ this.#boundVertices = undefined;
1121
+ this.#boundIndex = undefined;
1122
+ }
1123
+ draw(pass, item, kind, frameFlags) {
1124
+ const { mesh, geometry, material } = item, frame = this.#list.frame;
1125
+ const gpu = this.geometry(geometry);
1126
+ if (!gpu.buffers.has('position'))
1127
+ return;
1128
+ const instanced = mesh.isInstanced;
1129
+ const instances = mesh instanceof SkinnedInstancedMesh3D ? mesh.drawCount : instanced ? mesh.count : 1;
1130
+ if (instances <= 0 || this.#objectCount >= this.#objectCapacity)
1131
+ return;
1132
+ const world = mesh.matrixWorld;
1133
+ const determinant = world[0] * (world[5] * world[10] - world[6] * world[9]) -
1134
+ world[4] * (world[1] * world[10] - world[2] * world[9]) +
1135
+ world[8] * (world[1] * world[6] - world[2] * world[5]);
1136
+ const wire = material.wireframe && kind !== 'depth' && geometry.topology === 'triangles';
1137
+ // Everything that selects a pipeline besides the material and geometry themselves,
1138
+ // packed into one number so the common case is a single map lookup.
1139
+ const bits = (kind === 'canvas' ? 0 : kind === 'target' ? 1 : kind === 'depth' ? 2 : kind === 'hdr' ? 3 : 65536) |
1140
+ (wire ? 4 : 0) |
1141
+ (determinant < 0 ? 8 : 0) |
1142
+ (instanced ? 16 : 0) |
1143
+ (instanced && mesh.instanceColors ? 32 : 0) |
1144
+ (mesh.skeleton ? 64 : 0) |
1145
+ (mesh.receiveShadow && this.#shadowCount > 0 ? 128 : 0) |
1146
+ (frameFlags.fog ? 256 : 0) |
1147
+ (frameFlags.environment ? 512 : 0) |
1148
+ (this.#frameToneMapping !== 'none' ? 1024 : 0) |
1149
+ (instanced && mesh.instanceColorSize === 4 ? 2048 : 0) |
1150
+ (material.side === 'double' ? 4096 : material.side === 'back' ? 8192 : 0) |
1151
+ (mesh instanceof SkinnedInstancedMesh3D ? 16384 : 0) |
1152
+ (mesh instanceof GpuParticles3D ? 32768 : 0);
1153
+ let cache = this.#drawVariants.get(material);
1154
+ if (!cache || cache.version !== material.version)
1155
+ this.#drawVariants.set(material, (cache = { version: material.version, variants: new Map() }));
1156
+ // Material fields that select shader features or pipeline state. They are read every
1157
+ // draw so plain assignments (a new map, another blend mode) need no touch().
1158
+ const map = material.map;
1159
+ const surface = (map ? 1 : 0) |
1160
+ (map?.source instanceof RenderTarget3D ? 2 : 0) |
1161
+ (material.normalMap ? 4 : 0) |
1162
+ (material.metallicRoughnessMap ? 8 : 0) |
1163
+ (material.occlusionMap ? 16 : 0) |
1164
+ (material.emissiveMap ? 32 : 0) |
1165
+ (material.alphaMode === 'mask' ? 64 : material.alphaMode === 'blend' ? 128 : 0) |
1166
+ (material.blending === 'premultiplied'
1167
+ ? 256
1168
+ : material.blending === 'additive'
1169
+ ? 32768
1170
+ : material.blending === 'multiply'
1171
+ ? 65536
1172
+ : 0) |
1173
+ (material.flatShading ? 512 : 0) |
1174
+ (material.vertexColors ? 1024 : 0) |
1175
+ (material.billboard ? 2048 : 0) |
1176
+ (material.screenSpace ? 4096 : 0) |
1177
+ (material.depthTest ? 8192 : 0) |
1178
+ (material.depthWrite ? 16384 : 0) |
1179
+ (material.fog ? 131072 : 0) |
1180
+ (material.toneMapped ? 262144 : 0) |
1181
+ (material.polygonOffset ? 524288 : 0) |
1182
+ (material.occlusionMap?.channel === 1 ? 1048576 : 0) |
1183
+ (material.emissiveMap?.channel === 1 ? 2097152 : 0) |
1184
+ (material.lightMap ? 4194304 : 0) |
1185
+ (material.lightMap?.channel === 1 ? 8388608 : 0) |
1186
+ (material.reflectionMap ? 16777216 : 0) |
1187
+ (material.softness > 0 && this.#softDepth ? 33554432 : 0) |
1188
+ (material.splat ? 67108864 : 0);
1189
+ const variantKey = surface * 131072 + bits;
1190
+ let byGeometry = cache.variants.get(geometry.id);
1191
+ if (!byGeometry)
1192
+ cache.variants.set(geometry.id, (byGeometry = new Map()));
1193
+ let variant = byGeometry.get(variantKey);
1194
+ if (!variant || variant.layoutVersion !== gpu.layoutVersion) {
1195
+ const built = this.features(item, gpu, kind, frameFlags);
1196
+ variant = {
1197
+ features: built,
1198
+ pipeline: this.pipeline(built, item, gpu, kind, determinant < 0 && !built.skinning, wire),
1199
+ layoutVersion: gpu.layoutVersion
1200
+ };
1201
+ byGeometry.set(variantKey, variant);
1202
+ }
1203
+ const features = variant.features;
1204
+ if (variant.pipeline !== this.#boundPipeline) {
1205
+ pass.setPipeline(variant.pipeline);
1206
+ this.#boundPipeline = variant.pipeline;
1207
+ }
1208
+ const materialGroup = this.material(material);
1209
+ if (materialGroup !== this.#boundMaterial) {
1210
+ pass.setBindGroup(1, materialGroup);
1211
+ this.#boundMaterial = materialGroup;
1212
+ }
1213
+ pass.setBindGroup(2, this.#objectGroup, [this.writeObject(mesh, gpu, features.skinning)]);
1214
+ const skinGroup = this.skin(mesh, gpu, features.skinning, frame);
1215
+ if (skinGroup !== this.#boundSkin) {
1216
+ pass.setBindGroup(3, skinGroup);
1217
+ this.#boundSkin = skinGroup;
1218
+ }
1219
+ // Vertex bindings depend on the geometry and on which attributes this variant reads.
1220
+ if (instanced || this.#boundVertices !== variant || this.#boundPipeline !== variant.pipeline) {
1221
+ let slot = 0;
1222
+ const bind = (enabled, name) => {
1223
+ if (enabled)
1224
+ pass.setVertexBuffer(slot++, gpu.buffers.get(name).buffer);
1225
+ };
1226
+ bind(true, 'position');
1227
+ bind(features.normal, 'normal');
1228
+ bind(features.uv, 'uv');
1229
+ bind(features.tangent, 'tangent');
1230
+ bind(features.vertexColor, 'color');
1231
+ bind(features.skinning || features.skinInstancing === true, 'joints');
1232
+ bind(features.skinning || features.skinInstancing === true, 'weights');
1233
+ bind(features.uv1, 'uv1');
1234
+ if (instanced) {
1235
+ const instance = this.instances(mesh, frame);
1236
+ pass.setVertexBuffer(slot++, instance.matrices.buffer);
1237
+ if (features.instanceColor)
1238
+ pass.setVertexBuffer(slot++, instance.colors.buffer);
1239
+ if (features.skinInstancing)
1240
+ pass.setVertexBuffer(slot++, instance.animation.buffer);
1241
+ }
1242
+ this.#boundVertices = instanced ? undefined : variant;
1243
+ this.#boundIndex = undefined;
1244
+ }
1245
+ if (wire) {
1246
+ // Wireframe draws the whole geometry: its edge list is not split by groups.
1247
+ const lines = this.wireframe(geometry, gpu);
1248
+ pass.setIndexBuffer(lines.buffer, 'uint32');
1249
+ pass.drawIndexed(lines.count, instances);
1250
+ this.#boundIndex = undefined;
1251
+ }
1252
+ else if (gpu.index) {
1253
+ if (gpu.index.buffer !== this.#boundIndex) {
1254
+ pass.setIndexBuffer(gpu.index.buffer, gpu.index.format);
1255
+ this.#boundIndex = gpu.index.buffer;
1256
+ }
1257
+ pass.drawIndexed(item.count, instances, item.start);
1258
+ }
1259
+ else
1260
+ pass.draw(item.count, instances, item.start);
1261
+ if (kind !== 'depth' && kind !== 'scene-depth') {
1262
+ this.info.drawCalls++;
1263
+ if (!wire && geometry.topology === 'triangles')
1264
+ this.info.triangles += (item.count / 3) * instances;
1265
+ }
1266
+ }
1267
+ depthItem = {
1268
+ mesh: undefined,
1269
+ geometry: undefined,
1270
+ material: undefined,
1271
+ start: 0,
1272
+ count: 0,
1273
+ depth: 0
1274
+ };
1275
+ drawDepth(pass, mesh) {
1276
+ const geometry = mesh.geometry, item = this.depthItem, groups = geometry.groups, flags = { fog: false, environment: false };
1277
+ if (geometry.topology !== 'triangles')
1278
+ return;
1279
+ item.mesh = mesh;
1280
+ item.geometry = geometry;
1281
+ if (Array.isArray(mesh.material) && groups.length > 0) {
1282
+ for (const group of groups) {
1283
+ item.material = mesh.materialAt(group.materialIndex);
1284
+ item.start = group.start;
1285
+ item.count = group.count;
1286
+ if (item.material.visible && !item.material.isDisposed && !item.material.billboard)
1287
+ this.draw(pass, item, 'depth', flags);
1288
+ }
1289
+ }
1290
+ else {
1291
+ item.material = mesh.materialAt(0);
1292
+ item.start = 0;
1293
+ item.count = geometry.drawCount;
1294
+ if (item.material.visible && !item.material.isDisposed && !item.material.billboard)
1295
+ this.draw(pass, item, 'depth', flags);
1296
+ }
1297
+ }
1298
+ ensureShadowAtlas() {
1299
+ if (!this.#shadowTexture) {
1300
+ const size = this.#shadowAtlasSize;
1301
+ this.#shadowTexture = this.device.createTexture({
1302
+ size: [size, size],
1303
+ format: SHADOW_FORMAT,
1304
+ usage: TEXTURE_USAGE.RENDER_ATTACHMENT | TEXTURE_USAGE.TEXTURE_BINDING
1305
+ });
1306
+ this.#shadowView = this.#shadowTexture.createView();
1307
+ }
1308
+ return this.#shadowView;
1309
+ }
1310
+ canvasAttachments(texture) {
1311
+ const key = texture.width + 'x' + texture.height;
1312
+ if (key !== this.#canvasKey || !this.#canvasDepth) {
1313
+ this.#canvasDepth?.destroy();
1314
+ this.#canvasColor?.destroy();
1315
+ const size = [texture.width, texture.height];
1316
+ this.#canvasDepth = this.device.createTexture({
1317
+ size,
1318
+ format: DEPTH_FORMAT,
1319
+ sampleCount: this.#sampleCount,
1320
+ usage: TEXTURE_USAGE.RENDER_ATTACHMENT
1321
+ });
1322
+ this.#canvasColor =
1323
+ this.#sampleCount > 1
1324
+ ? this.device.createTexture({
1325
+ size,
1326
+ format: this.#format,
1327
+ sampleCount: this.#sampleCount,
1328
+ usage: TEXTURE_USAGE.RENDER_ATTACHMENT
1329
+ })
1330
+ : undefined;
1331
+ this.#canvasKey = key;
1332
+ }
1333
+ return { color: this.#canvasColor?.createView(), depth: this.#canvasDepth.createView() };
1334
+ }
1335
+ colorFormat(kind) {
1336
+ return kind === 'target' ? TARGET_FORMAT : kind === 'hdr' ? HDR_FORMAT : this.#format;
1337
+ }
1338
+ drawSkybox(pass, texture, intensity, camera, kind) {
1339
+ const device = this.device, key = 'skybox/' + kind;
1340
+ if (!mat4Invert(this.#scratch16, camera.viewProjectionMatrix))
1341
+ return;
1342
+ let pipeline = this.#pipelines.get(key);
1343
+ if (!pipeline) {
1344
+ this.#skyLayout ??= device.createBindGroupLayout({
1345
+ entries: [
1346
+ { binding: 0, visibility: SHADER_STAGE.VERTEX | SHADER_STAGE.FRAGMENT, buffer: {} },
1347
+ { binding: 1, visibility: SHADER_STAGE.FRAGMENT, texture: { viewDimension: 'cube' } },
1348
+ { binding: 2, visibility: SHADER_STAGE.FRAGMENT, sampler: {} }
1349
+ ]
1350
+ });
1351
+ const module = device.createShaderModule({ code: SKYBOX_WGSL_3D, label: 'skybox' });
1352
+ pipeline = device.createRenderPipeline({
1353
+ label: key,
1354
+ layout: device.createPipelineLayout({ bindGroupLayouts: [this.#skyLayout] }),
1355
+ vertex: { module, entryPoint: 'vertexMain' },
1356
+ fragment: { module, entryPoint: 'fragmentMain', targets: [{ format: this.colorFormat(kind) }] },
1357
+ primitive: { topology: 'triangle-list' },
1358
+ depthStencil: { format: DEPTH_FORMAT, depthWriteEnabled: false, depthCompare: 'less-equal' },
1359
+ multisample: { count: kind === 'canvas' ? this.#sampleCount : 1 }
1360
+ });
1361
+ this.#pipelines.set(key, pipeline);
1362
+ }
1363
+ this.#skyBuffer ??= device.createBuffer({ size: 80, usage: BUFFER_USAGE.UNIFORM | BUFFER_USAGE.COPY_DST });
1364
+ const data = new Float32Array(20);
1365
+ data.set(this.#scratch16);
1366
+ data[16] = intensity;
1367
+ data[17] = kind === 'canvas' ? 0 : 1;
1368
+ data[18] = this.exposure;
1369
+ data[19] = this.#frameToneMapping === 'aces' ? 2 : this.#frameToneMapping === 'reinhard' ? 1 : 0;
1370
+ device.queue.writeBuffer(this.#skyBuffer, 0, data);
1371
+ const cube = this.textureCube(texture), groupKey = texture.id + ':' + texture.version;
1372
+ if (!this.#skyGroup || this.#skyGroup.key !== groupKey) {
1373
+ this.#skyGroup = {
1374
+ key: groupKey,
1375
+ group: device.createBindGroup({
1376
+ layout: this.#skyLayout,
1377
+ entries: [
1378
+ { binding: 0, resource: { buffer: this.#skyBuffer } },
1379
+ { binding: 1, resource: cube.view },
1380
+ { binding: 2, resource: cube.sampler }
1381
+ ]
1382
+ })
1383
+ };
1384
+ }
1385
+ pass.setPipeline(pipeline);
1386
+ pass.setBindGroup(0, this.#skyGroup.group);
1387
+ pass.draw(3);
1388
+ this.info.drawCalls++;
1389
+ }
1390
+ /**
1391
+ * Draw one frame to the canvas, or into `target` when given. Returns false
1392
+ * when the device is lost and nothing was drawn.
1393
+ */
1394
+ /**
1395
+ * Draw runs of plain meshes that share a geometry and a material as one
1396
+ * instanced draw each, in the main view and in shadow maps. On by default;
1397
+ * the meshes themselves are untouched.
1398
+ */
1399
+ /** Point lights past the eight nearest are lit by screen tile, up to 256; false drops them instead. */
1400
+ get tiledLights() {
1401
+ return this.#list.tiledLights;
1402
+ }
1403
+ set tiledLights(value) {
1404
+ this.#list.tiledLights = Boolean(value);
1405
+ }
1406
+ get autoInstancing() {
1407
+ return this.#list.autoInstanceThreshold > 1;
1408
+ }
1409
+ set autoInstancing(value) {
1410
+ this.#list.autoInstanceThreshold = value ? 8 : 0;
1411
+ }
1412
+ render(scene, camera, target) {
1413
+ return this.renderView(scene, camera, target);
1414
+ }
1415
+ /** Draw the mirror directly with its own output, shadows and object selection. */
1416
+ renderReflectionPass(scene, camera, pass) {
1417
+ return this.renderView(scene, camera, pass.target, pass);
1418
+ }
1419
+ /** The retained mirror image must still belong to the live WebGPU device. */
1420
+ reuseReflection(target) {
1421
+ return !this.#disposed && !this.#lost && this.#targets.get(target)?.version === target.version;
1422
+ }
1423
+ renderView(scene, camera, target, reflection) {
1424
+ if (this.#disposed)
1425
+ throw new World3DError('WORLD3D_DISPOSED', 'renderer');
1426
+ if (this.#lost)
1427
+ return false;
1428
+ if (!reflection && this.postProcess.enabled && !this.#inPost)
1429
+ return this.renderPost(scene, camera, target);
1430
+ const device = this.device, list = this.#list, info = this.info, kind = target ? (target.format === 'rgba16f' ? 'hdr' : 'target') : 'canvas';
1431
+ if (target?.isDisposed)
1432
+ throw new World3DError('WORLD3D_DISPOSED', 'render target');
1433
+ this.#frameToneMapping = outputToneMapping3D(reflection?.toneMapping ?? this.toneMapping, target);
1434
+ list.build(scene, camera, reflection);
1435
+ this.#serial++;
1436
+ this.#objectCount = 0;
1437
+ info.frame = list.frame;
1438
+ info.drawCalls = info.triangles = 0;
1439
+ info.visited = list.stats.visited;
1440
+ info.culled = list.stats.culled;
1441
+ info.lightsDropped = list.stats.lightsDropped;
1442
+ const atlas = this.ensureShadowAtlas();
1443
+ const plans = planShadows3D(this.#frameData, list, this.#shadowAtlasSize, this.shadowsEnabled && (reflection?.shadows ?? true), true, this.#shadowSlots, camera);
1444
+ this.#shadowCount = plans.length;
1445
+ const environment = scene.environment && !scene.environment.isDisposed ? this.textureCube(scene.environment) : undefined;
1446
+ writeFrameBlock3D(this.#frameData, scene, camera, list, this.#shadowSlots, {
1447
+ exposure: this.exposure,
1448
+ toneMapping: this.#frameToneMapping,
1449
+ environmentMaxMip: environment?.maxMip ?? 0
1450
+ });
1451
+ this.#frameData[FRAME_OFFSETS_3D.clipInfo + 2] = this.viewport ? this.viewport[2] : 1;
1452
+ this.#frameData[FRAME_OFFSETS_3D.clipInfo + 3] = this.viewport ? this.viewport[3] : 1;
1453
+ {
1454
+ // Lights past the eight in the frame block go to the tiled list, read by screen tile.
1455
+ const fullWidth = target ? target.width : this.#context.getCurrentTexture().width, fullHeight = target ? target.height : this.#context.getCurrentTexture().height;
1456
+ const rect = this.viewport;
1457
+ const tileWidth = rect ? Math.max(Math.round(rect[2] * fullWidth), 1) : fullWidth, tileHeight = rect ? Math.max(Math.round(rect[3] * fullHeight), 1) : fullHeight;
1458
+ const originX = rect ? Math.round(rect[0] * fullWidth) : 0, originY = rect ? Math.max(fullHeight - Math.round(rect[1] * fullHeight) - tileHeight, 0) : 0;
1459
+ const tiled = writeTiledLights3D(this.#frameData, this.#tiledTable, list.tiledPointLights, camera.viewProjectionMatrix, tileWidth, tileHeight, true, originX, originY);
1460
+ if (tiled > 0)
1461
+ device.queue.writeBuffer(this.#tiledBuffer, 0, this.#tiledTable);
1462
+ this.info.lightsTiled = tiled;
1463
+ }
1464
+ device.queue.writeBuffer(this.#frameBuffer, 0, this.#frameData);
1465
+ // Surfaces that fade near solid geometry read its depth, drawn once before the frame.
1466
+ const soft = list.transparent.some(item => item.material.softness > 0);
1467
+ const softWidth = target ? target.width : this.#context.getCurrentTexture().width, softHeight = target ? target.height : this.#context.getCurrentTexture().height;
1468
+ if (soft &&
1469
+ (!this.#sceneDepth ||
1470
+ this.#sceneDepth.texture.width !== softWidth ||
1471
+ this.#sceneDepth.texture.height !== softHeight)) {
1472
+ this.#sceneDepth?.texture.destroy();
1473
+ this.#sceneDepth?.buffer.destroy();
1474
+ const texture = device.createTexture({
1475
+ size: [softWidth, softHeight],
1476
+ format: SHADOW_FORMAT,
1477
+ usage: TEXTURE_USAGE.RENDER_ATTACHMENT | TEXTURE_USAGE.TEXTURE_BINDING
1478
+ });
1479
+ const buffer = device.createBuffer({ size: 128, usage: BUFFER_USAGE.UNIFORM | BUFFER_USAGE.COPY_DST });
1480
+ this.#sceneDepth = {
1481
+ texture,
1482
+ view: texture.createView(),
1483
+ buffer,
1484
+ group: device.createBindGroup({
1485
+ layout: this.#depthFrameLayout,
1486
+ entries: [{ binding: 0, resource: { buffer } }]
1487
+ })
1488
+ };
1489
+ this.#sceneDepthSerial++;
1490
+ }
1491
+ this.#softDepth = soft;
1492
+ const sceneDepthView = soft ? this.#sceneDepth.view : atlas;
1493
+ const frameKey = (environment ? scene.environment.id + ':' + scene.environment.version : '-') +
1494
+ (soft ? '|d' + this.#sceneDepthSerial : '');
1495
+ if (!this.#frameGroup || this.#frameGroupKey !== frameKey) {
1496
+ this.#frameGroup = device.createBindGroup({
1497
+ layout: this.#frameLayout,
1498
+ entries: [
1499
+ { binding: 0, resource: { buffer: this.#frameBuffer } },
1500
+ { binding: 1, resource: atlas },
1501
+ { binding: 2, resource: this.#shadowSampler },
1502
+ { binding: 3, resource: environment?.view ?? this.#whiteCube },
1503
+ { binding: 4, resource: environment?.sampler ?? this.#defaultSampler },
1504
+ { binding: 5, resource: this.#white },
1505
+ { binding: 6, resource: this.#grabSampler },
1506
+ { binding: 7, resource: sceneDepthView },
1507
+ { binding: 8, resource: { buffer: this.#tiledBuffer } }
1508
+ ]
1509
+ });
1510
+ this.#frameGroupKey = frameKey;
1511
+ }
1512
+ // Size the per-draw uniform buffer before any pass references its bind group.
1513
+ let needed = list.opaque.length * (soft ? 2 : 1) + list.transparent.length;
1514
+ for (const plan of plans)
1515
+ for (const mesh of plan.casters)
1516
+ needed += Array.isArray(mesh.material) ? Math.max(mesh.geometry.groups.length, 1) : 1;
1517
+ if (needed > this.#objectCapacity) {
1518
+ while (this.#objectCapacity < needed)
1519
+ this.#objectCapacity *= 2;
1520
+ this.#objectBuffer.destroy();
1521
+ this.#objectBuffer = this.createObjectBuffer();
1522
+ this.#objectGroup = this.createObjectGroup();
1523
+ this.#objectStaging = new ArrayBuffer(this.#objectCapacity * OBJECT_BLOCK_BYTES_3D);
1524
+ this.#objectFloats = new Float32Array(this.#objectStaging);
1525
+ this.#objectInts = new Int32Array(this.#objectStaging);
1526
+ }
1527
+ const encoder = device.createCommandEncoder();
1528
+ if (plans.length > 0) {
1529
+ this.resetPassState();
1530
+ const pass = encoder.beginRenderPass({
1531
+ colorAttachments: [],
1532
+ depthStencilAttachment: { view: atlas, depthClearValue: 1, depthLoadOp: 'clear', depthStoreOp: 'store' }
1533
+ });
1534
+ for (const plan of plans) {
1535
+ let slot = this.#depthFrames[plan.slot];
1536
+ if (!slot) {
1537
+ const buffer = device.createBuffer({ size: 128, usage: BUFFER_USAGE.UNIFORM | BUFFER_USAGE.COPY_DST });
1538
+ slot = this.#depthFrames[plan.slot] = {
1539
+ buffer,
1540
+ group: device.createBindGroup({
1541
+ layout: this.#depthFrameLayout,
1542
+ entries: [{ binding: 0, resource: { buffer } }]
1543
+ })
1544
+ };
1545
+ }
1546
+ device.queue.writeBuffer(slot.buffer, 0, plan.matrix);
1547
+ pass.setViewport(plan.x, plan.y, plan.tile, plan.tile, 0, 1);
1548
+ pass.setScissorRect(plan.x, plan.y, plan.tile, plan.tile);
1549
+ pass.setBindGroup(0, slot.group);
1550
+ for (const mesh of plan.casters)
1551
+ this.drawDepth(pass, mesh);
1552
+ }
1553
+ pass.end();
1554
+ }
1555
+ if (soft) {
1556
+ const depth = this.#sceneDepth;
1557
+ // The depth-only frame block holds a view-projection matrix followed by the view matrix.
1558
+ device.queue.writeBuffer(depth.buffer, 0, camera.viewProjectionMatrix);
1559
+ device.queue.writeBuffer(depth.buffer, 64, camera.viewMatrix);
1560
+ this.resetPassState();
1561
+ const pass = encoder.beginRenderPass({
1562
+ colorAttachments: [],
1563
+ depthStencilAttachment: { view: depth.view, depthClearValue: 1, depthLoadOp: 'clear', depthStoreOp: 'store' }
1564
+ });
1565
+ const rect = this.viewport;
1566
+ if (rect) {
1567
+ const w = Math.max(Math.round(rect[2] * softWidth), 1), h = Math.max(Math.round(rect[3] * softHeight), 1);
1568
+ const x = Math.min(Math.max(Math.round(rect[0] * softWidth), 0), softWidth - 1), y = Math.min(Math.max(softHeight - Math.round(rect[1] * softHeight) - h, 0), softHeight - 1);
1569
+ pass.setViewport(x, y, Math.min(w, softWidth - x), Math.min(h, softHeight - y), 0, 1);
1570
+ }
1571
+ pass.setBindGroup(0, depth.group);
1572
+ const none = { fog: false, environment: false };
1573
+ // Scene depth follows the main view's culling and material offset.
1574
+ for (const item of list.opaque) {
1575
+ if (item.geometry.topology === 'triangles' &&
1576
+ item.material.depthWrite &&
1577
+ !item.material.billboard &&
1578
+ !item.material.screenSpace)
1579
+ this.draw(pass, item, 'scene-depth', none);
1580
+ }
1581
+ pass.end();
1582
+ }
1583
+ const background = scene.background;
1584
+ // sRGB targets encode on write, so they are cleared with linear values.
1585
+ const encode = target ? (value) => value : linearToSrgb;
1586
+ const clearValue = Array.isArray(background)
1587
+ ? [encode(background[0]), encode(background[1]), encode(background[2]), 1]
1588
+ : [0, 0, 0, (target || this.#alpha) && !background ? 0 : 1];
1589
+ let colorAttachment, depthView, outputWidth, outputHeight, outputTexture;
1590
+ // See-through surfaces read a copy of everything drawn before them, which splits the pass in two.
1591
+ const grab = list.transparent.some(item => item.material.transmission > 0 && item.material.shading === 'standard');
1592
+ const loadOp = this.autoClear ? 'clear' : 'load';
1593
+ if (target) {
1594
+ const entry = this.target(target);
1595
+ colorAttachment = { view: entry.colorView, clearValue, loadOp, storeOp: 'store' };
1596
+ depthView = entry.depthView;
1597
+ outputTexture = entry.color;
1598
+ outputWidth = target.width;
1599
+ outputHeight = target.height;
1600
+ if (!depthView)
1601
+ throw new World3DError('WORLD3D_INPUT_INVALID', 'the WebGPU backend requires render targets with depth');
1602
+ }
1603
+ else {
1604
+ const current = this.#context.getCurrentTexture(), attachments = this.canvasAttachments(current), view = current.createView();
1605
+ // The multisampled color is kept so a later view of the same frame can load it.
1606
+ colorAttachment = attachments.color
1607
+ ? { view: attachments.color, resolveTarget: view, clearValue, loadOp, storeOp: 'store' }
1608
+ : { view, clearValue, loadOp, storeOp: 'store' };
1609
+ depthView = attachments.depth;
1610
+ outputTexture = current;
1611
+ outputWidth = current.width;
1612
+ outputHeight = current.height;
1613
+ }
1614
+ this.resetPassState();
1615
+ const depthStoreOp = target?.depthTexture || grab ? 'store' : 'discard';
1616
+ let pass = encoder.beginRenderPass({
1617
+ colorAttachments: [colorAttachment],
1618
+ depthStencilAttachment: { view: depthView, depthClearValue: 1, depthLoadOp: 'clear', depthStoreOp }
1619
+ });
1620
+ const view = this.viewport;
1621
+ const frame = () => {
1622
+ if (!view)
1623
+ return;
1624
+ // The public rectangle has its origin at the bottom left; WebGPU's is at the top left.
1625
+ const w = Math.max(Math.round(view[2] * outputWidth), 1), h = Math.max(Math.round(view[3] * outputHeight), 1);
1626
+ const x = Math.min(Math.max(Math.round(view[0] * outputWidth), 0), outputWidth - 1), y = Math.min(Math.max(outputHeight - Math.round(view[1] * outputHeight) - h, 0), outputHeight - 1);
1627
+ const cw = Math.min(w, outputWidth - x), ch = Math.min(h, outputHeight - y);
1628
+ pass.setViewport(x, y, cw, ch, 0, 1);
1629
+ pass.setScissorRect(x, y, cw, ch);
1630
+ };
1631
+ frame();
1632
+ const flags = { fog: scene.fog !== undefined, environment: environment !== undefined };
1633
+ pass.setBindGroup(0, this.#frameGroup);
1634
+ for (const item of list.opaque)
1635
+ this.draw(pass, item, kind, flags);
1636
+ if (background instanceof CubeTexture3D && !background.isDisposed) {
1637
+ this.drawSkybox(pass, background, scene.backgroundIntensity, camera, kind);
1638
+ this.resetPassState();
1639
+ pass.setBindGroup(0, this.#frameGroup);
1640
+ }
1641
+ if (grab) {
1642
+ pass.end();
1643
+ const format = this.colorFormat(kind);
1644
+ let entry = this.#grabs.get(kind);
1645
+ if (!entry ||
1646
+ entry.texture.width !== outputWidth ||
1647
+ entry.texture.height !== outputHeight ||
1648
+ entry.texture.format !== format) {
1649
+ entry?.texture.destroy();
1650
+ const texture = device.createTexture({
1651
+ size: [outputWidth, outputHeight],
1652
+ format,
1653
+ usage: TEXTURE_USAGE.TEXTURE_BINDING | TEXTURE_USAGE.COPY_DST
1654
+ });
1655
+ this.#grabs.set(kind, (entry = { texture, view: texture.createView(), group: undefined, key: '' }));
1656
+ }
1657
+ if (!entry.group || entry.key !== frameKey) {
1658
+ entry.group = device.createBindGroup({
1659
+ layout: this.#frameLayout,
1660
+ entries: [
1661
+ { binding: 0, resource: { buffer: this.#frameBuffer } },
1662
+ { binding: 1, resource: atlas },
1663
+ { binding: 2, resource: this.#shadowSampler },
1664
+ { binding: 3, resource: environment?.view ?? this.#whiteCube },
1665
+ { binding: 4, resource: environment?.sampler ?? this.#defaultSampler },
1666
+ { binding: 5, resource: entry.view },
1667
+ { binding: 6, resource: this.#grabSampler },
1668
+ { binding: 7, resource: sceneDepthView },
1669
+ { binding: 8, resource: { buffer: this.#tiledBuffer } }
1670
+ ]
1671
+ });
1672
+ entry.key = frameKey;
1673
+ }
1674
+ encoder.copyTextureToTexture({ texture: outputTexture }, { texture: entry.texture }, [outputWidth, outputHeight]);
1675
+ pass = encoder.beginRenderPass({
1676
+ colorAttachments: [{ ...colorAttachment, loadOp: 'load' }],
1677
+ depthStencilAttachment: {
1678
+ view: depthView,
1679
+ depthLoadOp: 'load',
1680
+ depthStoreOp: target?.depthTexture ? 'store' : 'discard'
1681
+ }
1682
+ });
1683
+ frame();
1684
+ this.resetPassState();
1685
+ pass.setBindGroup(0, entry.group);
1686
+ this.#grabbed = true;
1687
+ }
1688
+ for (const item of list.transparent)
1689
+ this.draw(pass, item, kind, flags);
1690
+ this.#grabbed = false;
1691
+ pass.end();
1692
+ if (this.#objectCount > 0)
1693
+ device.queue.writeBuffer(this.#objectBuffer, 0, this.#objectStaging, 0, this.#objectCount * OBJECT_BLOCK_BYTES_3D);
1694
+ device.queue.submit([encoder.finish()]);
1695
+ this.prune(list.frame);
1696
+ info.programs = this.#pipelines.size;
1697
+ info.geometries = this.#geometries.size;
1698
+ info.textures = this.#textures.size;
1699
+ info.shadowMaps = plans.length;
1700
+ return true;
1701
+ }
1702
+ /** Draw the scene into the half-float chain target, then post-process into the output. */
1703
+ renderPost(scene, camera, target) {
1704
+ if (target?.isDisposed)
1705
+ throw new World3DError('WORLD3D_DISPOSED', 'render target');
1706
+ const current = target ? undefined : this.#context.getCurrentTexture();
1707
+ const width = target ? target.width : current.width, height = target ? target.height : current.height;
1708
+ const post = (this.#post ??= new PostChainWebGPU3D(this.device));
1709
+ post.scene.setSize(Math.max(width, 1), Math.max(height, 1));
1710
+ this.#inPost = true;
1711
+ try {
1712
+ if (!this.render(scene, camera, post.scene))
1713
+ return false;
1714
+ }
1715
+ finally {
1716
+ this.#inPost = false;
1717
+ }
1718
+ const encoder = this.device.createCommandEncoder();
1719
+ const output = target ? this.target(target).colorView : current.createView();
1720
+ const format = target ? (target.format === 'rgba16f' ? HDR_FORMAT : TARGET_FORMAT) : this.#format;
1721
+ // 8-bit targets encode sRGB on write and half-float targets store linear light; only the canvas needs encoded values.
1722
+ // Outlined objects are drawn once more, flat white, into a mask the composite traces.
1723
+ let maskView;
1724
+ if (outlineActive3D(this.postProcess)) {
1725
+ post.mask.setSize(Math.max(width, 1), Math.max(height, 1));
1726
+ const saved = {
1727
+ layerMask: camera.layerMask,
1728
+ override: scene.overrideMaterial,
1729
+ background: scene.background,
1730
+ shadows: this.shadowsEnabled,
1731
+ planes: scene.clippingPlanes
1732
+ };
1733
+ camera.layerMask = this.postProcess.outlineLayers;
1734
+ scene.overrideMaterial = post.maskMaterial;
1735
+ scene.background = [0, 0, 0];
1736
+ this.shadowsEnabled = false;
1737
+ this.#inPost = true;
1738
+ // The counters describe the scene, not this helper pass.
1739
+ const counted = { ...this.info };
1740
+ try {
1741
+ if (this.render(scene, camera, post.mask))
1742
+ maskView = this.target(post.mask).colorView;
1743
+ }
1744
+ finally {
1745
+ this.#inPost = false;
1746
+ camera.layerMask = saved.layerMask;
1747
+ scene.overrideMaterial = saved.override;
1748
+ scene.background = saved.background;
1749
+ this.shadowsEnabled = saved.shadows;
1750
+ Object.assign(this.info, counted);
1751
+ }
1752
+ }
1753
+ const sceneEntry = this.target(post.scene);
1754
+ this.info.drawCalls += post.run(encoder, sceneEntry.colorView, sceneEntry.depthView, maskView, postViewFromCamera3D(camera), width, height, output, format, target !== undefined, this.postProcess, target?.format === 'rgba16f' ? 'none' : this.toneMapping);
1755
+ this.device.queue.submit([encoder.finish()]);
1756
+ return true;
1757
+ }
1758
+ /** Retire per-mesh and per-skeleton buffers that have not been drawn recently. */
1759
+ prune(frame) {
1760
+ if (frame % PRUNE_INTERVAL !== 0)
1761
+ return;
1762
+ for (const [mesh, entry] of this.#instances) {
1763
+ if (frame - entry.lastFrame < PRUNE_INTERVAL)
1764
+ continue;
1765
+ entry.matrices.buffer.destroy();
1766
+ entry.colors?.buffer.destroy();
1767
+ entry.animation?.buffer.destroy();
1768
+ this.#instances.delete(mesh);
1769
+ }
1770
+ for (const [skeleton, entry] of this.#bones) {
1771
+ if (frame - entry.lastFrame < PRUNE_INTERVAL)
1772
+ continue;
1773
+ entry.buffer.destroy();
1774
+ this.#bones.delete(skeleton);
1775
+ }
1776
+ }
1777
+ /** RGBA8 pixels of a render target, top row first. */
1778
+ async readRenderTargetPixels(target) {
1779
+ if (target.format === 'rgba16f')
1780
+ throw new World3DError('WORLD3D_INPUT_INVALID', 'half-float targets cannot be read back as bytes');
1781
+ if (this.#disposed)
1782
+ throw new World3DError('WORLD3D_DISPOSED', 'renderer');
1783
+ if (this.#lost)
1784
+ throw new World3DError('WORLD3D_CONTEXT_LOST', 'readback');
1785
+ const device = this.device, entry = this.target(target), width = target.width, height = target.height;
1786
+ // Buffer rows must be padded to a multiple of 256 bytes.
1787
+ const bytesPerRow = Math.ceil((width * 4) / 256) * 256;
1788
+ const buffer = device.createBuffer({
1789
+ size: bytesPerRow * height,
1790
+ usage: BUFFER_USAGE.COPY_DST | BUFFER_USAGE.MAP_READ
1791
+ });
1792
+ try {
1793
+ const encoder = device.createCommandEncoder();
1794
+ encoder.copyTextureToBuffer({ texture: entry.color }, { buffer, bytesPerRow, rowsPerImage: height }, [
1795
+ width,
1796
+ height
1797
+ ]);
1798
+ device.queue.submit([encoder.finish()]);
1799
+ await buffer.mapAsync(MAP_MODE_READ);
1800
+ const mapped = new Uint8Array(buffer.getMappedRange()), out = new Uint8Array(width * height * 4);
1801
+ for (let y = 0; y < height; y++)
1802
+ out.set(mapped.subarray(y * bytesPerRow, y * bytesPerRow + width * 4), y * width * 4);
1803
+ buffer.unmap();
1804
+ return out;
1805
+ }
1806
+ catch (cause) {
1807
+ throw new World3DError('WORLD3D_RESOURCE_FAILED', 'render target readback', cause);
1808
+ }
1809
+ finally {
1810
+ buffer.destroy();
1811
+ }
1812
+ }
1813
+ /** Release every GPU object and unconfigure the canvas. Idempotent. */
1814
+ dispose() {
1815
+ if (this.#disposed)
1816
+ return;
1817
+ this.#disposed = true;
1818
+ this.#unsubscribeDeviceLoss();
1819
+ this.#list.clear();
1820
+ this.#post?.dispose();
1821
+ this.#post = undefined;
1822
+ for (const geometry of [...this.#geometries.keys()]) {
1823
+ this.#geometries.get(geometry).unsubscribe();
1824
+ this.releaseGeometry(geometry);
1825
+ }
1826
+ for (const entry of this.#textures.values()) {
1827
+ entry.unsubscribe();
1828
+ entry.texture.destroy();
1829
+ }
1830
+ for (const entry of this.#targets.values()) {
1831
+ entry.unsubscribe();
1832
+ entry.color.destroy();
1833
+ entry.depth?.destroy();
1834
+ }
1835
+ for (const entry of this.#materials.values()) {
1836
+ entry.unsubscribe();
1837
+ entry.buffer.destroy();
1838
+ }
1839
+ for (const entry of this.#instances.values()) {
1840
+ entry.matrices.buffer.destroy();
1841
+ entry.colors?.buffer.destroy();
1842
+ entry.animation?.buffer.destroy();
1843
+ }
1844
+ for (const entry of this.#bones.values())
1845
+ entry.buffer.destroy();
1846
+ for (const table of this.#animations.values())
1847
+ table.destroy();
1848
+ this.#animations.clear();
1849
+ for (const slot of this.#depthFrames)
1850
+ slot?.buffer.destroy();
1851
+ this.#textures.clear();
1852
+ this.#targets.clear();
1853
+ this.#materials.clear();
1854
+ this.#instances.clear();
1855
+ this.#bones.clear();
1856
+ this.#pipelines.clear();
1857
+ this.#modules.clear();
1858
+ this.#frameBuffer.destroy();
1859
+ this.#tiledBuffer.destroy();
1860
+ this.#objectBuffer.destroy();
1861
+ this.#skyBuffer?.destroy();
1862
+ this.#dummyBones.destroy();
1863
+ this.#dummyMorph.destroy();
1864
+ this.#whiteTexture.destroy();
1865
+ this.#whiteCubeTexture.destroy();
1866
+ for (const entry of this.#grabs.values())
1867
+ entry.texture.destroy();
1868
+ this.#grabs.clear();
1869
+ this.#shadowTexture?.destroy();
1870
+ this.#canvasDepth?.destroy();
1871
+ this.#canvasColor?.destroy();
1872
+ this.#sceneDepth?.texture.destroy();
1873
+ this.#sceneDepth?.buffer.destroy();
1874
+ this.#sceneDepth = undefined;
1875
+ try {
1876
+ this.#context.unconfigure();
1877
+ }
1878
+ catch {
1879
+ /* The canvas may already be detached. */
1880
+ }
1881
+ if (this.#ownsDevice)
1882
+ this.device.destroy();
1883
+ }
1884
+ }
1885
+ /** Acquire a device (unless one is borrowed) and create the WebGPU renderer. */
1886
+ export async function createWebGPURenderer3D(options) {
1887
+ const canvas = options?.canvas;
1888
+ if (!canvas || typeof canvas.getContext !== 'function')
1889
+ throw new World3DError('WORLD3D_INPUT_INVALID', 'canvas');
1890
+ if (options.device)
1891
+ return new WebGPURenderer3D(options, options.device, false);
1892
+ if (typeof navigator === 'undefined' || !navigator.gpu)
1893
+ throw new World3DError('WORLD3D_CONTEXT_UNAVAILABLE', 'webgpu');
1894
+ const adapter = await navigator.gpu.requestAdapter({
1895
+ powerPreference: options.powerPreference ?? 'high-performance'
1896
+ });
1897
+ if (!adapter)
1898
+ throw new World3DError('WORLD3D_CONTEXT_UNAVAILABLE', 'webgpu adapter');
1899
+ let device;
1900
+ // Enable every block-compression family the adapter offers so compressed textures can be uploaded.
1901
+ const requiredFeatures = ['texture-compression-bc', 'texture-compression-etc2', 'texture-compression-astc'].filter(feature => adapter.features.has(feature));
1902
+ try {
1903
+ device = await adapter.requestDevice({ requiredFeatures });
1904
+ }
1905
+ catch (cause) {
1906
+ throw new World3DError('WORLD3D_CONTEXT_UNAVAILABLE', 'webgpu device', cause);
1907
+ }
1908
+ try {
1909
+ return new WebGPURenderer3D(options, device, true);
1910
+ }
1911
+ catch (cause) {
1912
+ device.destroy();
1913
+ throw cause;
1914
+ }
1915
+ }
1916
+ //# sourceMappingURL=WebGPURenderer3D.js.map