@needle-tools/engine 4.7.2-alpha → 4.7.2-next.6f2cd71

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 (1067) hide show
  1. package/CHANGELOG.md +3782 -3782
  2. package/LICENSE.md +10 -10
  3. package/README.md +64 -64
  4. package/components.needle.json +1 -1
  5. package/dist/generateMeshBVH.worker-BaNp_Xtp.js +25 -0
  6. package/dist/{gltf-progressive-zdhlW609.umd.cjs → gltf-progressive-B9o1T8Vr.umd.cjs} +1 -1
  7. package/dist/{gltf-progressive-YjtQYFa9.js → gltf-progressive-DO0SisAM.js} +2 -2
  8. package/dist/{gltf-progressive-yOP1mp5W.min.js → gltf-progressive-DQF10PJE.min.js} +1 -1
  9. package/dist/{needle-engine.bundle-BhDF-YSv.min.js → needle-engine.bundle-B-NoV0t_.min.js} +64 -64
  10. package/dist/{needle-engine.bundle-D2myV4E4.umd.cjs → needle-engine.bundle-BMnlxDfi.umd.cjs} +59 -59
  11. package/dist/{needle-engine.bundle-gp00DTS4.js → needle-engine.bundle-CFi0ugBx.js} +638 -638
  12. package/dist/needle-engine.d.ts +130 -129
  13. package/dist/needle-engine.js +4 -4
  14. package/dist/needle-engine.min.js +1 -1
  15. package/dist/needle-engine.umd.cjs +1 -1
  16. package/dist/{postprocessing-8AQTeZsr.umd.cjs → postprocessing-CjW23fio.umd.cjs} +2 -2
  17. package/dist/{postprocessing-BkxN_08g.js → postprocessing-DYLNOL3W.js} +3 -3
  18. package/dist/{postprocessing-BDScN9yu.min.js → postprocessing-xYQWCHFu.min.js} +2 -2
  19. package/dist/{three-DMrv-4ar.umd.cjs → three-B_hneGZr.umd.cjs} +4 -4
  20. package/dist/{three-Bz6X1mrw.js → three-DrqIzZTH.js} +4198 -4198
  21. package/dist/{three-Boa-jOq-.min.js → three-DuDKwKB8.min.js} +33 -33
  22. package/dist/{three-examples-GggCDHv0.js → three-examples-B50TT3Iu.js} +5 -5
  23. package/dist/{three-examples-DuVhxqft.min.js → three-examples-DaDLBuy6.min.js} +14 -14
  24. package/dist/{three-examples-C7ryg8vN.umd.cjs → three-examples-X3OadjXB.umd.cjs} +3 -3
  25. package/dist/{three-mesh-ui-CY6Izc7C.min.js → three-mesh-ui-B3p3gyUz.min.js} +1 -1
  26. package/dist/{three-mesh-ui-CwlN0FUC.umd.cjs → three-mesh-ui-CQiIQIlA.umd.cjs} +1 -1
  27. package/dist/{three-mesh-ui-CLNOfsWn.js → three-mesh-ui-CxuWt7m-.js} +1 -1
  28. package/dist/{vendor-zxXa3Dmr.min.js → vendor-BlSxe9JJ.min.js} +3 -3
  29. package/dist/{vendor-BSD1RQIh.js → vendor-BmYIgaS1.js} +3 -3
  30. package/dist/{vendor-DHr4aqIZ.umd.cjs → vendor-Cavtu3CP.umd.cjs} +3 -3
  31. package/lib/asap/needle-asap.d.ts +1 -1
  32. package/lib/asap/needle-asap.js +95 -95
  33. package/lib/asap/sessiongranted.d.ts +3 -3
  34. package/lib/asap/sessiongranted.js +65 -65
  35. package/lib/asap/utils.d.ts +1 -1
  36. package/lib/asap/utils.js +3 -3
  37. package/lib/engine/analytics/index.d.ts +6 -6
  38. package/lib/engine/analytics/index.js +12 -12
  39. package/lib/engine/analytics/lcp.d.ts +3 -3
  40. package/lib/engine/analytics/lcp.js +34 -34
  41. package/lib/engine/api.d.ts +82 -82
  42. package/lib/engine/api.js +81 -81
  43. package/lib/engine/assets/index.d.ts +11 -11
  44. package/lib/engine/assets/index.js +47 -47
  45. package/lib/engine/assets/static.d.ts +1 -1
  46. package/lib/engine/assets/static.js +4 -4
  47. package/lib/engine/codegen/register_types.d.ts +1 -1
  48. package/lib/engine/codegen/register_types.js +300 -300
  49. package/lib/engine/debug/debug.d.ts +15 -15
  50. package/lib/engine/debug/debug.js +44 -44
  51. package/lib/engine/debug/debug_console.d.ts +2 -2
  52. package/lib/engine/debug/debug_console.js +307 -307
  53. package/lib/engine/debug/debug_overlay.d.ts +22 -22
  54. package/lib/engine/debug/debug_overlay.js +316 -316
  55. package/lib/engine/debug/debug_spatial_console.d.ts +2 -2
  56. package/lib/engine/debug/debug_spatial_console.js +390 -390
  57. package/lib/engine/debug/index.d.ts +2 -2
  58. package/lib/engine/debug/index.js +2 -2
  59. package/lib/engine/engine_addressables.d.ts +164 -164
  60. package/lib/engine/engine_addressables.js +601 -601
  61. package/lib/engine/engine_animation.d.ts +43 -43
  62. package/lib/engine/engine_animation.js +133 -133
  63. package/lib/engine/engine_application.d.ts +45 -45
  64. package/lib/engine/engine_application.js +104 -104
  65. package/lib/engine/engine_assetdatabase.d.ts +25 -25
  66. package/lib/engine/engine_assetdatabase.js +346 -346
  67. package/lib/engine/engine_audio.d.ts +4 -4
  68. package/lib/engine/engine_audio.js +23 -23
  69. package/lib/engine/engine_camera.d.ts +13 -13
  70. package/lib/engine/engine_camera.js +30 -30
  71. package/lib/engine/engine_components.d.ts +110 -110
  72. package/lib/engine/engine_components.js +374 -374
  73. package/lib/engine/engine_components_internal.d.ts +9 -9
  74. package/lib/engine/engine_components_internal.js +36 -36
  75. package/lib/engine/engine_constants.d.ts +10 -10
  76. package/lib/engine/engine_constants.js +41 -41
  77. package/lib/engine/engine_context.d.ts +475 -475
  78. package/lib/engine/engine_context.js +1673 -1673
  79. package/lib/engine/engine_context_registry.d.ts +71 -71
  80. package/lib/engine/engine_context_registry.js +117 -117
  81. package/lib/engine/engine_coroutine.d.ts +35 -35
  82. package/lib/engine/engine_coroutine.js +52 -52
  83. package/lib/engine/engine_create_objects.d.ts +119 -119
  84. package/lib/engine/engine_create_objects.js +320 -320
  85. package/lib/engine/engine_default_parameters.d.ts +2 -2
  86. package/lib/engine/engine_default_parameters.js +3 -3
  87. package/lib/engine/engine_editor-sync.d.ts +21 -21
  88. package/lib/engine/engine_editor-sync.js +4 -4
  89. package/lib/engine/engine_fileloader.d.ts +2 -2
  90. package/lib/engine/engine_fileloader.js +8 -8
  91. package/lib/engine/engine_gameobject.d.ts +68 -68
  92. package/lib/engine/engine_gameobject.js +619 -619
  93. package/lib/engine/engine_generic_utils.d.ts +1 -1
  94. package/lib/engine/engine_generic_utils.js +13 -13
  95. package/lib/engine/engine_gizmos.d.ts +149 -149
  96. package/lib/engine/engine_gizmos.js +530 -530
  97. package/lib/engine/engine_gltf.d.ts +12 -12
  98. package/lib/engine/engine_gltf.js +15 -15
  99. package/lib/engine/engine_gltf_builtin_components.d.ts +11 -11
  100. package/lib/engine/engine_gltf_builtin_components.js +341 -341
  101. package/lib/engine/engine_hot_reload.d.ts +8 -8
  102. package/lib/engine/engine_hot_reload.js +197 -197
  103. package/lib/engine/engine_input.d.ts +362 -362
  104. package/lib/engine/engine_input.js +1294 -1294
  105. package/lib/engine/engine_input_utils.d.ts +2 -2
  106. package/lib/engine/engine_input_utils.js +22 -22
  107. package/lib/engine/engine_instancing.d.ts +19 -19
  108. package/lib/engine/engine_instancing.js +39 -39
  109. package/lib/engine/engine_license.d.ts +11 -11
  110. package/lib/engine/engine_license.js +369 -369
  111. package/lib/engine/engine_lifecycle_api.d.ts +83 -83
  112. package/lib/engine/engine_lifecycle_api.js +106 -106
  113. package/lib/engine/engine_lifecycle_functions_internal.d.ts +32 -32
  114. package/lib/engine/engine_lifecycle_functions_internal.js +146 -146
  115. package/lib/engine/engine_lightdata.d.ts +23 -23
  116. package/lib/engine/engine_lightdata.js +101 -101
  117. package/lib/engine/engine_loaders.callbacks.d.ts +97 -97
  118. package/lib/engine/engine_loaders.callbacks.js +86 -86
  119. package/lib/engine/engine_loaders.d.ts +48 -48
  120. package/lib/engine/engine_loaders.gltf.d.ts +13 -13
  121. package/lib/engine/engine_loaders.gltf.js +62 -62
  122. package/lib/engine/engine_loaders.js +337 -337
  123. package/lib/engine/engine_lods.d.ts +35 -35
  124. package/lib/engine/engine_lods.js +160 -160
  125. package/lib/engine/engine_mainloop_utils.d.ts +32 -32
  126. package/lib/engine/engine_mainloop_utils.js +466 -466
  127. package/lib/engine/engine_math.d.ts +114 -114
  128. package/lib/engine/engine_math.js +247 -247
  129. package/lib/engine/engine_modules.d.ts +36 -36
  130. package/lib/engine/engine_modules.js +85 -85
  131. package/lib/engine/engine_networking.d.ts +260 -260
  132. package/lib/engine/engine_networking.js +764 -764
  133. package/lib/engine/engine_networking_auto.d.ts +24 -24
  134. package/lib/engine/engine_networking_auto.js +310 -310
  135. package/lib/engine/engine_networking_blob.d.ts +48 -48
  136. package/lib/engine/engine_networking_blob.js +228 -228
  137. package/lib/engine/engine_networking_files.d.ts +35 -35
  138. package/lib/engine/engine_networking_files.js +172 -172
  139. package/lib/engine/engine_networking_files_default_components.d.ts +6 -6
  140. package/lib/engine/engine_networking_files_default_components.js +42 -42
  141. package/lib/engine/engine_networking_instantiate.d.ts +100 -100
  142. package/lib/engine/engine_networking_instantiate.js +345 -345
  143. package/lib/engine/engine_networking_peer.d.ts +15 -15
  144. package/lib/engine/engine_networking_peer.js +132 -132
  145. package/lib/engine/engine_networking_streams.d.ts +123 -123
  146. package/lib/engine/engine_networking_streams.js +645 -645
  147. package/lib/engine/engine_networking_types.d.ts +22 -22
  148. package/lib/engine/engine_networking_types.js +7 -7
  149. package/lib/engine/engine_networking_utils.d.ts +2 -2
  150. package/lib/engine/engine_networking_utils.js +20 -20
  151. package/lib/engine/engine_networking_websocket.d.ts +1 -1
  152. package/lib/engine/engine_networking_websocket.js +2 -2
  153. package/lib/engine/engine_patcher.d.ts +10 -10
  154. package/lib/engine/engine_patcher.js +142 -142
  155. package/lib/engine/engine_physics.d.ts +152 -152
  156. package/lib/engine/engine_physics.js +645 -645
  157. package/lib/engine/engine_physics.types.d.ts +40 -40
  158. package/lib/engine/engine_physics.types.js +33 -33
  159. package/lib/engine/engine_physics_rapier.d.ts +147 -147
  160. package/lib/engine/engine_physics_rapier.js +1433 -1433
  161. package/lib/engine/engine_playerview.d.ts +26 -26
  162. package/lib/engine/engine_playerview.js +64 -64
  163. package/lib/engine/engine_scenelighting.d.ts +71 -71
  164. package/lib/engine/engine_scenelighting.js +226 -226
  165. package/lib/engine/engine_serialization.d.ts +3 -3
  166. package/lib/engine/engine_serialization.js +3 -3
  167. package/lib/engine/engine_serialization_builtin_serializer.d.ts +72 -72
  168. package/lib/engine/engine_serialization_builtin_serializer.js +403 -403
  169. package/lib/engine/engine_serialization_core.d.ts +94 -94
  170. package/lib/engine/engine_serialization_core.js +607 -607
  171. package/lib/engine/engine_serialization_decorator.d.ts +23 -23
  172. package/lib/engine/engine_serialization_decorator.js +66 -66
  173. package/lib/engine/engine_setup.d.ts +1 -1
  174. package/lib/engine/engine_setup.js +2 -2
  175. package/lib/engine/engine_shaders.d.ts +53 -53
  176. package/lib/engine/engine_shaders.js +252 -252
  177. package/lib/engine/engine_shims.d.ts +4 -4
  178. package/lib/engine/engine_shims.js +24 -24
  179. package/lib/engine/engine_test_utils.d.ts +39 -39
  180. package/lib/engine/engine_test_utils.js +83 -83
  181. package/lib/engine/engine_texture.d.ts +28 -28
  182. package/lib/engine/engine_texture.js +64 -64
  183. package/lib/engine/engine_three_utils.d.ts +204 -204
  184. package/lib/engine/engine_three_utils.js +788 -788
  185. package/lib/engine/engine_time.d.ts +51 -51
  186. package/lib/engine/engine_time.js +82 -82
  187. package/lib/engine/engine_time_utils.d.ts +88 -88
  188. package/lib/engine/engine_time_utils.js +215 -215
  189. package/lib/engine/engine_tonemapping.d.ts +6 -6
  190. package/lib/engine/engine_tonemapping.js +197 -197
  191. package/lib/engine/engine_types.d.ts +578 -578
  192. package/lib/engine/engine_types.js +95 -95
  193. package/lib/engine/engine_typestore.d.ts +28 -28
  194. package/lib/engine/engine_typestore.js +55 -55
  195. package/lib/engine/engine_util_decorator.d.ts +13 -13
  196. package/lib/engine/engine_util_decorator.js +116 -116
  197. package/lib/engine/engine_utils.d.ts +248 -248
  198. package/lib/engine/engine_utils.js +1012 -1012
  199. package/lib/engine/engine_utils_format.d.ts +24 -24
  200. package/lib/engine/engine_utils_format.js +239 -239
  201. package/lib/engine/engine_utils_screenshot.d.ts +159 -159
  202. package/lib/engine/engine_utils_screenshot.js +522 -522
  203. package/lib/engine/engine_utils_screenshot.xr.d.ts +5 -5
  204. package/lib/engine/engine_utils_screenshot.xr.js +90 -90
  205. package/lib/engine/engine_xr.d.ts +1 -1
  206. package/lib/engine/engine_xr.js +1 -1
  207. package/lib/engine/export/gltf/Writers.d.ts +19 -19
  208. package/lib/engine/export/gltf/Writers.js +24 -24
  209. package/lib/engine/export/gltf/index.d.ts +11 -11
  210. package/lib/engine/export/gltf/index.js +123 -123
  211. package/lib/engine/export/index.d.ts +2 -2
  212. package/lib/engine/export/index.js +2 -2
  213. package/lib/engine/export/state.d.ts +7 -7
  214. package/lib/engine/export/state.js +17 -17
  215. package/lib/engine/export/utils.d.ts +2 -2
  216. package/lib/engine/export/utils.js +7 -7
  217. package/lib/engine/extensions/EXT_texture_exr.d.ts +8 -8
  218. package/lib/engine/extensions/EXT_texture_exr.js +32 -32
  219. package/lib/engine/extensions/NEEDLE_animator_controller_model.d.ts +122 -122
  220. package/lib/engine/extensions/NEEDLE_animator_controller_model.js +95 -95
  221. package/lib/engine/extensions/NEEDLE_components.d.ts +35 -35
  222. package/lib/engine/extensions/NEEDLE_components.js +220 -220
  223. package/lib/engine/extensions/NEEDLE_gameobject_data.d.ts +10 -10
  224. package/lib/engine/extensions/NEEDLE_gameobject_data.js +57 -57
  225. package/lib/engine/extensions/NEEDLE_lighting_settings.d.ts +37 -37
  226. package/lib/engine/extensions/NEEDLE_lighting_settings.js +157 -157
  227. package/lib/engine/extensions/NEEDLE_lightmaps.d.ts +18 -18
  228. package/lib/engine/extensions/NEEDLE_lightmaps.js +99 -99
  229. package/lib/engine/extensions/NEEDLE_persistent_assets.d.ts +11 -11
  230. package/lib/engine/extensions/NEEDLE_persistent_assets.js +63 -63
  231. package/lib/engine/extensions/NEEDLE_progressive.d.ts +1 -1
  232. package/lib/engine/extensions/NEEDLE_progressive.js +1 -1
  233. package/lib/engine/extensions/NEEDLE_render_objects.d.ts +13 -13
  234. package/lib/engine/extensions/NEEDLE_render_objects.js +159 -159
  235. package/lib/engine/extensions/NEEDLE_techniques_webgl.d.ts +38 -38
  236. package/lib/engine/extensions/NEEDLE_techniques_webgl.js +564 -564
  237. package/lib/engine/extensions/extension_resolver.d.ts +4 -4
  238. package/lib/engine/extensions/extension_resolver.js +1 -1
  239. package/lib/engine/extensions/extension_utils.d.ts +12 -12
  240. package/lib/engine/extensions/extension_utils.js +152 -152
  241. package/lib/engine/extensions/extensions.d.ts +32 -32
  242. package/lib/engine/extensions/extensions.js +107 -107
  243. package/lib/engine/extensions/index.d.ts +6 -6
  244. package/lib/engine/extensions/index.js +6 -6
  245. package/lib/engine/extensions/usage_tracker.d.ts +13 -13
  246. package/lib/engine/extensions/usage_tracker.js +65 -65
  247. package/lib/engine/js-extensions/Camera.d.ts +1 -1
  248. package/lib/engine/js-extensions/Camera.js +39 -39
  249. package/lib/engine/js-extensions/ExtensionUtils.d.ts +9 -9
  250. package/lib/engine/js-extensions/ExtensionUtils.js +67 -67
  251. package/lib/engine/js-extensions/Layers.d.ts +6 -6
  252. package/lib/engine/js-extensions/Layers.js +22 -22
  253. package/lib/engine/js-extensions/Object3D.d.ts +120 -120
  254. package/lib/engine/js-extensions/Object3D.js +136 -136
  255. package/lib/engine/js-extensions/RGBAColor.d.ts +23 -23
  256. package/lib/engine/js-extensions/RGBAColor.js +111 -111
  257. package/lib/engine/js-extensions/Vector.d.ts +3 -3
  258. package/lib/engine/js-extensions/Vector.js +13 -13
  259. package/lib/engine/js-extensions/index.d.ts +5 -5
  260. package/lib/engine/js-extensions/index.js +5 -5
  261. package/lib/engine/physics/workers/mesh-bvh/GenerateMeshBVHWorker.d.ts +4 -4
  262. package/lib/engine/physics/workers/mesh-bvh/GenerateMeshBVHWorker.js +79 -79
  263. package/lib/engine/shaders/shaderData.d.ts +55 -55
  264. package/lib/engine/shaders/shaderData.js +58 -58
  265. package/lib/engine/tests/test_utils.d.ts +2 -2
  266. package/lib/engine/tests/test_utils.js +53 -53
  267. package/lib/engine/webcomponents/WebXRButtons.d.ts +56 -56
  268. package/lib/engine/webcomponents/WebXRButtons.js +230 -230
  269. package/lib/engine/webcomponents/api.d.ts +5 -5
  270. package/lib/engine/webcomponents/api.js +4 -4
  271. package/lib/engine/webcomponents/buttons.d.ts +51 -51
  272. package/lib/engine/webcomponents/buttons.js +264 -264
  273. package/lib/engine/webcomponents/fonts.d.ts +9 -9
  274. package/lib/engine/webcomponents/fonts.js +32 -32
  275. package/lib/engine/webcomponents/icons.d.ts +9 -9
  276. package/lib/engine/webcomponents/icons.js +52 -52
  277. package/lib/engine/webcomponents/index.d.ts +1 -1
  278. package/lib/engine/webcomponents/index.js +1 -1
  279. package/lib/engine/webcomponents/logo-element.d.ts +10 -10
  280. package/lib/engine/webcomponents/logo-element.js +67 -67
  281. package/lib/engine/webcomponents/needle menu/needle-menu-spatial.d.ts +37 -37
  282. package/lib/engine/webcomponents/needle menu/needle-menu-spatial.js +513 -513
  283. package/lib/engine/webcomponents/needle menu/needle-menu.d.ts +155 -155
  284. package/lib/engine/webcomponents/needle menu/needle-menu.js +1029 -1029
  285. package/lib/engine/webcomponents/needle-button.d.ts +34 -34
  286. package/lib/engine/webcomponents/needle-button.js +161 -161
  287. package/lib/engine/webcomponents/needle-engine.ar-overlay.d.ts +21 -21
  288. package/lib/engine/webcomponents/needle-engine.ar-overlay.js +166 -166
  289. package/lib/engine/webcomponents/needle-engine.attributes.d.ts +69 -69
  290. package/lib/engine/webcomponents/needle-engine.attributes.js +1 -1
  291. package/lib/engine/webcomponents/needle-engine.d.ts +116 -116
  292. package/lib/engine/webcomponents/needle-engine.extras.d.ts +6 -6
  293. package/lib/engine/webcomponents/needle-engine.extras.js +13 -13
  294. package/lib/engine/webcomponents/needle-engine.js +821 -821
  295. package/lib/engine/webcomponents/needle-engine.loading.d.ts +44 -44
  296. package/lib/engine/webcomponents/needle-engine.loading.js +341 -341
  297. package/lib/engine/xr/NeedleXRController.d.ts +313 -313
  298. package/lib/engine/xr/NeedleXRController.js +1007 -1007
  299. package/lib/engine/xr/NeedleXRSession.d.ts +340 -340
  300. package/lib/engine/xr/NeedleXRSession.js +1463 -1463
  301. package/lib/engine/xr/NeedleXRSync.d.ts +22 -22
  302. package/lib/engine/xr/NeedleXRSync.js +188 -188
  303. package/lib/engine/xr/SceneTransition.d.ts +18 -18
  304. package/lib/engine/xr/SceneTransition.js +69 -69
  305. package/lib/engine/xr/TempXRContext.d.ts +34 -34
  306. package/lib/engine/xr/TempXRContext.js +187 -187
  307. package/lib/engine/xr/XRRig.d.ts +7 -7
  308. package/lib/engine/xr/XRRig.js +1 -1
  309. package/lib/engine/xr/api.d.ts +6 -6
  310. package/lib/engine/xr/api.js +6 -6
  311. package/lib/engine/xr/events.d.ts +66 -66
  312. package/lib/engine/xr/events.js +93 -93
  313. package/lib/engine/xr/internal.d.ts +12 -12
  314. package/lib/engine/xr/internal.js +25 -25
  315. package/lib/engine/xr/usdz.d.ts +12 -12
  316. package/lib/engine/xr/usdz.js +29 -29
  317. package/lib/engine/xr/utils.d.ts +11 -11
  318. package/lib/engine/xr/utils.js +34 -34
  319. package/lib/engine-components/AlignmentConstraint.d.ts +10 -10
  320. package/lib/engine-components/AlignmentConstraint.js +39 -39
  321. package/lib/engine-components/Animation.d.ts +156 -156
  322. package/lib/engine-components/Animation.js +508 -508
  323. package/lib/engine-components/AnimationCurve.d.ts +40 -40
  324. package/lib/engine-components/AnimationCurve.js +159 -159
  325. package/lib/engine-components/AnimationUtils.d.ts +8 -8
  326. package/lib/engine-components/AnimationUtils.js +27 -27
  327. package/lib/engine-components/AnimationUtilsAutoplay.d.ts +1 -1
  328. package/lib/engine-components/AnimationUtilsAutoplay.js +39 -39
  329. package/lib/engine-components/Animator.d.ts +217 -217
  330. package/lib/engine-components/Animator.js +354 -354
  331. package/lib/engine-components/AnimatorController.d.ts +227 -227
  332. package/lib/engine-components/AnimatorController.js +1152 -1152
  333. package/lib/engine-components/AudioListener.d.ts +33 -33
  334. package/lib/engine-components/AudioListener.js +86 -86
  335. package/lib/engine-components/AudioSource.d.ts +217 -217
  336. package/lib/engine-components/AudioSource.js +635 -635
  337. package/lib/engine-components/AvatarLoader.d.ts +80 -80
  338. package/lib/engine-components/AvatarLoader.js +231 -231
  339. package/lib/engine-components/AxesHelper.d.ts +32 -32
  340. package/lib/engine-components/AxesHelper.js +67 -67
  341. package/lib/engine-components/BasicIKConstraint.d.ts +9 -9
  342. package/lib/engine-components/BasicIKConstraint.js +43 -43
  343. package/lib/engine-components/BoxCollider.d.ts +2 -2
  344. package/lib/engine-components/BoxCollider.js +2 -2
  345. package/lib/engine-components/BoxHelperComponent.d.ts +47 -47
  346. package/lib/engine-components/BoxHelperComponent.js +102 -102
  347. package/lib/engine-components/Camera.d.ts +231 -231
  348. package/lib/engine-components/Camera.js +700 -700
  349. package/lib/engine-components/CameraUtils.d.ts +1 -1
  350. package/lib/engine-components/CameraUtils.js +123 -123
  351. package/lib/engine-components/CharacterController.d.ts +55 -55
  352. package/lib/engine-components/CharacterController.js +236 -236
  353. package/lib/engine-components/Collider.d.ts +188 -188
  354. package/lib/engine-components/Collider.js +369 -369
  355. package/lib/engine-components/Component.d.ts +792 -792
  356. package/lib/engine-components/Component.js +920 -920
  357. package/lib/engine-components/ContactShadows.d.ts +94 -94
  358. package/lib/engine-components/ContactShadows.js +453 -453
  359. package/lib/engine-components/DeleteBox.d.ts +19 -19
  360. package/lib/engine-components/DeleteBox.js +58 -58
  361. package/lib/engine-components/DeviceFlag.d.ts +16 -16
  362. package/lib/engine-components/DeviceFlag.js +47 -47
  363. package/lib/engine-components/DragControls.d.ts +170 -170
  364. package/lib/engine-components/DragControls.js +1421 -1421
  365. package/lib/engine-components/DropListener.d.ts +215 -215
  366. package/lib/engine-components/DropListener.js +642 -642
  367. package/lib/engine-components/Duplicatable.d.ts +35 -35
  368. package/lib/engine-components/Duplicatable.js +202 -202
  369. package/lib/engine-components/EventList.d.ts +54 -54
  370. package/lib/engine-components/EventList.js +232 -232
  371. package/lib/engine-components/EventTrigger.d.ts +33 -33
  372. package/lib/engine-components/EventTrigger.js +75 -75
  373. package/lib/engine-components/EventType.d.ts +22 -22
  374. package/lib/engine-components/EventType.js +23 -23
  375. package/lib/engine-components/Fog.d.ts +22 -22
  376. package/lib/engine-components/Fog.js +61 -61
  377. package/lib/engine-components/Gizmos.d.ts +17 -17
  378. package/lib/engine-components/Gizmos.js +64 -64
  379. package/lib/engine-components/GridHelper.d.ts +20 -20
  380. package/lib/engine-components/GridHelper.js +54 -54
  381. package/lib/engine-components/GroundProjection.d.ts +67 -67
  382. package/lib/engine-components/GroundProjection.js +343 -343
  383. package/lib/engine-components/Interactable.d.ts +12 -12
  384. package/lib/engine-components/Interactable.js +12 -12
  385. package/lib/engine-components/Joints.d.ts +19 -19
  386. package/lib/engine-components/Joints.js +51 -51
  387. package/lib/engine-components/LODGroup.d.ts +35 -35
  388. package/lib/engine-components/LODGroup.js +152 -152
  389. package/lib/engine-components/Light.d.ts +180 -180
  390. package/lib/engine-components/Light.js +535 -535
  391. package/lib/engine-components/LookAtConstraint.d.ts +19 -19
  392. package/lib/engine-components/LookAtConstraint.js +35 -35
  393. package/lib/engine-components/NeedleMenu.d.ts +50 -50
  394. package/lib/engine-components/NeedleMenu.js +92 -92
  395. package/lib/engine-components/NestedGltf.d.ts +25 -25
  396. package/lib/engine-components/NestedGltf.js +88 -88
  397. package/lib/engine-components/Networking.d.ts +54 -54
  398. package/lib/engine-components/Networking.js +112 -112
  399. package/lib/engine-components/OffsetConstraint.d.ts +14 -14
  400. package/lib/engine-components/OffsetConstraint.js +65 -65
  401. package/lib/engine-components/OrbitControls.d.ts +268 -268
  402. package/lib/engine-components/OrbitControls.js +1015 -1015
  403. package/lib/engine-components/PlayerColor.d.ts +19 -19
  404. package/lib/engine-components/PlayerColor.js +94 -94
  405. package/lib/engine-components/ReflectionProbe.d.ts +28 -28
  406. package/lib/engine-components/ReflectionProbe.js +204 -204
  407. package/lib/engine-components/Renderer.d.ts +153 -153
  408. package/lib/engine-components/Renderer.js +834 -834
  409. package/lib/engine-components/RendererInstancing.d.ts +140 -140
  410. package/lib/engine-components/RendererInstancing.js +744 -744
  411. package/lib/engine-components/RendererLightmap.d.ts +24 -24
  412. package/lib/engine-components/RendererLightmap.js +182 -182
  413. package/lib/engine-components/RigidBody.d.ts +155 -155
  414. package/lib/engine-components/RigidBody.js +517 -517
  415. package/lib/engine-components/SceneSwitcher.d.ts +263 -263
  416. package/lib/engine-components/SceneSwitcher.js +971 -971
  417. package/lib/engine-components/ScreenCapture.d.ts +144 -144
  418. package/lib/engine-components/ScreenCapture.js +547 -547
  419. package/lib/engine-components/ShadowCatcher.d.ts +33 -33
  420. package/lib/engine-components/ShadowCatcher.js +166 -166
  421. package/lib/engine-components/Skybox.d.ts +88 -88
  422. package/lib/engine-components/Skybox.js +469 -469
  423. package/lib/engine-components/SmoothFollow.d.ts +34 -34
  424. package/lib/engine-components/SmoothFollow.js +82 -82
  425. package/lib/engine-components/SpatialTrigger.d.ts +102 -102
  426. package/lib/engine-components/SpatialTrigger.js +225 -225
  427. package/lib/engine-components/SpectatorCamera.d.ts +111 -111
  428. package/lib/engine-components/SpectatorCamera.js +715 -715
  429. package/lib/engine-components/SphereCollider.d.ts +2 -2
  430. package/lib/engine-components/SphereCollider.js +2 -2
  431. package/lib/engine-components/SpriteRenderer.d.ts +132 -132
  432. package/lib/engine-components/SpriteRenderer.js +472 -472
  433. package/lib/engine-components/SyncedCamera.d.ts +41 -41
  434. package/lib/engine-components/SyncedCamera.js +199 -199
  435. package/lib/engine-components/SyncedRoom.d.ts +106 -106
  436. package/lib/engine-components/SyncedRoom.js +371 -371
  437. package/lib/engine-components/SyncedTransform.d.ts +94 -94
  438. package/lib/engine-components/SyncedTransform.js +331 -331
  439. package/lib/engine-components/TestRunner.d.ts +16 -16
  440. package/lib/engine-components/TestRunner.js +102 -102
  441. package/lib/engine-components/TransformGizmo.d.ts +75 -75
  442. package/lib/engine-components/TransformGizmo.js +209 -209
  443. package/lib/engine-components/VideoPlayer.d.ts +184 -184
  444. package/lib/engine-components/VideoPlayer.js +978 -978
  445. package/lib/engine-components/Voip.d.ts +67 -67
  446. package/lib/engine-components/Voip.js +360 -360
  447. package/lib/engine-components/api.d.ts +51 -51
  448. package/lib/engine-components/api.js +50 -50
  449. package/lib/engine-components/avatar/AvatarBlink_Simple.d.ts +11 -11
  450. package/lib/engine-components/avatar/AvatarBlink_Simple.js +76 -76
  451. package/lib/engine-components/avatar/AvatarEyeLook_Rotation.d.ts +14 -14
  452. package/lib/engine-components/avatar/AvatarEyeLook_Rotation.js +68 -68
  453. package/lib/engine-components/avatar/Avatar_Brain_LookAt.d.ts +29 -29
  454. package/lib/engine-components/avatar/Avatar_Brain_LookAt.js +121 -121
  455. package/lib/engine-components/avatar/Avatar_MouthShapes.d.ts +15 -15
  456. package/lib/engine-components/avatar/Avatar_MouthShapes.js +79 -79
  457. package/lib/engine-components/avatar/Avatar_MustacheShake.d.ts +9 -9
  458. package/lib/engine-components/avatar/Avatar_MustacheShake.js +29 -29
  459. package/lib/engine-components/codegen/components.d.ts +216 -216
  460. package/lib/engine-components/codegen/components.js +218 -218
  461. package/lib/engine-components/debug/LogStats.d.ts +5 -5
  462. package/lib/engine-components/debug/LogStats.js +18 -18
  463. package/lib/engine-components/export/gltf/GltfExport.d.ts +30 -30
  464. package/lib/engine-components/export/gltf/GltfExport.js +246 -246
  465. package/lib/engine-components/export/gltf/index.d.ts +1 -1
  466. package/lib/engine-components/export/gltf/index.js +1 -1
  467. package/lib/engine-components/export/index.d.ts +1 -1
  468. package/lib/engine-components/export/index.js +1 -1
  469. package/lib/engine-components/export/usdz/Extension.d.ts +22 -22
  470. package/lib/engine-components/export/usdz/Extension.js +1 -1
  471. package/lib/engine-components/export/usdz/ThreeUSDZExporter.d.ts +162 -162
  472. package/lib/engine-components/export/usdz/ThreeUSDZExporter.js +1789 -1789
  473. package/lib/engine-components/export/usdz/USDZExporter.d.ts +130 -130
  474. package/lib/engine-components/export/usdz/USDZExporter.js +663 -663
  475. package/lib/engine-components/export/usdz/extensions/Animation.d.ts +106 -106
  476. package/lib/engine-components/export/usdz/extensions/Animation.js +1071 -1071
  477. package/lib/engine-components/export/usdz/extensions/DocumentExtension.d.ts +5 -5
  478. package/lib/engine-components/export/usdz/extensions/DocumentExtension.js +6 -6
  479. package/lib/engine-components/export/usdz/extensions/NodeMaterialConverter.d.ts +10 -10
  480. package/lib/engine-components/export/usdz/extensions/NodeMaterialConverter.js +451 -451
  481. package/lib/engine-components/export/usdz/extensions/USDZText.d.ts +54 -54
  482. package/lib/engine-components/export/usdz/extensions/USDZText.js +203 -203
  483. package/lib/engine-components/export/usdz/extensions/USDZUI.d.ts +8 -8
  484. package/lib/engine-components/export/usdz/extensions/USDZUI.js +158 -158
  485. package/lib/engine-components/export/usdz/extensions/behavior/Actions.d.ts +30 -30
  486. package/lib/engine-components/export/usdz/extensions/behavior/Actions.js +88 -88
  487. package/lib/engine-components/export/usdz/extensions/behavior/AudioExtension.d.ts +10 -10
  488. package/lib/engine-components/export/usdz/extensions/behavior/AudioExtension.js +86 -86
  489. package/lib/engine-components/export/usdz/extensions/behavior/Behaviour.d.ts +28 -28
  490. package/lib/engine-components/export/usdz/extensions/behavior/Behaviour.js +290 -290
  491. package/lib/engine-components/export/usdz/extensions/behavior/BehaviourComponents.d.ts +190 -190
  492. package/lib/engine-components/export/usdz/extensions/behavior/BehaviourComponents.js +1060 -1060
  493. package/lib/engine-components/export/usdz/extensions/behavior/BehavioursBuilder.d.ts +135 -135
  494. package/lib/engine-components/export/usdz/extensions/behavior/BehavioursBuilder.js +548 -548
  495. package/lib/engine-components/export/usdz/extensions/behavior/PhysicsExtension.d.ts +7 -7
  496. package/lib/engine-components/export/usdz/extensions/behavior/PhysicsExtension.js +115 -115
  497. package/lib/engine-components/export/usdz/index.d.ts +3 -3
  498. package/lib/engine-components/export/usdz/index.js +2 -2
  499. package/lib/engine-components/export/usdz/utils/animationutils.d.ts +7 -7
  500. package/lib/engine-components/export/usdz/utils/animationutils.js +163 -163
  501. package/lib/engine-components/export/usdz/utils/quicklook.d.ts +2 -2
  502. package/lib/engine-components/export/usdz/utils/quicklook.js +43 -43
  503. package/lib/engine-components/particlesystem/ParticleSystem.d.ts +177 -177
  504. package/lib/engine-components/particlesystem/ParticleSystem.js +1176 -1176
  505. package/lib/engine-components/particlesystem/ParticleSystemModules.d.ts +526 -526
  506. package/lib/engine-components/particlesystem/ParticleSystemModules.js +1930 -1930
  507. package/lib/engine-components/particlesystem/ParticleSystemSubEmitter.d.ts +25 -25
  508. package/lib/engine-components/particlesystem/ParticleSystemSubEmitter.js +87 -87
  509. package/lib/engine-components/particlesystem/api.d.ts +2 -2
  510. package/lib/engine-components/particlesystem/api.js +2 -2
  511. package/lib/engine-components/postprocessing/Effects/Antialiasing.d.ts +17 -17
  512. package/lib/engine-components/postprocessing/Effects/Antialiasing.js +59 -59
  513. package/lib/engine-components/postprocessing/Effects/BloomEffect.d.ts +46 -46
  514. package/lib/engine-components/postprocessing/Effects/BloomEffect.js +113 -113
  515. package/lib/engine-components/postprocessing/Effects/ChromaticAberration.d.ts +11 -11
  516. package/lib/engine-components/postprocessing/Effects/ChromaticAberration.js +39 -39
  517. package/lib/engine-components/postprocessing/Effects/ColorAdjustments.d.ts +23 -23
  518. package/lib/engine-components/postprocessing/Effects/ColorAdjustments.js +111 -111
  519. package/lib/engine-components/postprocessing/Effects/DepthOfField.d.ts +25 -25
  520. package/lib/engine-components/postprocessing/Effects/DepthOfField.js +104 -104
  521. package/lib/engine-components/postprocessing/Effects/EffectWrapper.d.ts +12 -12
  522. package/lib/engine-components/postprocessing/Effects/EffectWrapper.js +18 -18
  523. package/lib/engine-components/postprocessing/Effects/Pixelation.d.ts +11 -11
  524. package/lib/engine-components/postprocessing/Effects/Pixelation.js +32 -32
  525. package/lib/engine-components/postprocessing/Effects/ScreenspaceAmbientOcclusion.d.ts +18 -18
  526. package/lib/engine-components/postprocessing/Effects/ScreenspaceAmbientOcclusion.js +91 -91
  527. package/lib/engine-components/postprocessing/Effects/ScreenspaceAmbientOcclusionN8.d.ts +70 -70
  528. package/lib/engine-components/postprocessing/Effects/ScreenspaceAmbientOcclusionN8.js +176 -176
  529. package/lib/engine-components/postprocessing/Effects/Sharpening.d.ts +18 -18
  530. package/lib/engine-components/postprocessing/Effects/Sharpening.js +127 -127
  531. package/lib/engine-components/postprocessing/Effects/TiltShiftEffect.d.ts +17 -17
  532. package/lib/engine-components/postprocessing/Effects/TiltShiftEffect.js +70 -70
  533. package/lib/engine-components/postprocessing/Effects/Tonemapping.d.ts +19 -19
  534. package/lib/engine-components/postprocessing/Effects/Tonemapping.js +94 -94
  535. package/lib/engine-components/postprocessing/Effects/Tonemapping.utils.d.ts +13 -13
  536. package/lib/engine-components/postprocessing/Effects/Tonemapping.utils.js +51 -51
  537. package/lib/engine-components/postprocessing/Effects/Vignette.d.ts +15 -15
  538. package/lib/engine-components/postprocessing/Effects/Vignette.js +60 -60
  539. package/lib/engine-components/postprocessing/PostProcessingEffect.d.ts +90 -90
  540. package/lib/engine-components/postprocessing/PostProcessingEffect.js +168 -168
  541. package/lib/engine-components/postprocessing/PostProcessingHandler.d.ts +42 -42
  542. package/lib/engine-components/postprocessing/PostProcessingHandler.js +494 -494
  543. package/lib/engine-components/postprocessing/Volume.d.ts +90 -90
  544. package/lib/engine-components/postprocessing/Volume.js +385 -385
  545. package/lib/engine-components/postprocessing/VolumeParameter.d.ts +26 -26
  546. package/lib/engine-components/postprocessing/VolumeParameter.js +136 -136
  547. package/lib/engine-components/postprocessing/VolumeProfile.d.ts +15 -15
  548. package/lib/engine-components/postprocessing/VolumeProfile.js +60 -60
  549. package/lib/engine-components/postprocessing/index.d.ts +6 -6
  550. package/lib/engine-components/postprocessing/index.js +6 -6
  551. package/lib/engine-components/postprocessing/utils.d.ts +55 -55
  552. package/lib/engine-components/postprocessing/utils.js +119 -119
  553. package/lib/engine-components/timeline/PlayableDirector.d.ts +163 -163
  554. package/lib/engine-components/timeline/PlayableDirector.js +686 -686
  555. package/lib/engine-components/timeline/SignalAsset.d.ts +24 -24
  556. package/lib/engine-components/timeline/SignalAsset.js +130 -130
  557. package/lib/engine-components/timeline/TimelineModels.d.ts +89 -89
  558. package/lib/engine-components/timeline/TimelineModels.js +22 -22
  559. package/lib/engine-components/timeline/TimelineTracks.d.ts +110 -110
  560. package/lib/engine-components/timeline/TimelineTracks.js +879 -879
  561. package/lib/engine-components/timeline/index.d.ts +4 -4
  562. package/lib/engine-components/timeline/index.js +3 -3
  563. package/lib/engine-components/ui/BaseUIComponent.d.ts +48 -48
  564. package/lib/engine-components/ui/BaseUIComponent.js +170 -170
  565. package/lib/engine-components/ui/Button.d.ts +64 -64
  566. package/lib/engine-components/ui/Button.js +315 -315
  567. package/lib/engine-components/ui/Canvas.d.ts +74 -74
  568. package/lib/engine-components/ui/Canvas.js +407 -407
  569. package/lib/engine-components/ui/CanvasGroup.d.ts +19 -19
  570. package/lib/engine-components/ui/CanvasGroup.js +58 -58
  571. package/lib/engine-components/ui/EventSystem.d.ts +125 -125
  572. package/lib/engine-components/ui/EventSystem.js +765 -765
  573. package/lib/engine-components/ui/Graphic.d.ts +55 -55
  574. package/lib/engine-components/ui/Graphic.js +255 -255
  575. package/lib/engine-components/ui/Image.d.ts +35 -35
  576. package/lib/engine-components/ui/Image.js +116 -116
  577. package/lib/engine-components/ui/InputField.d.ts +42 -42
  578. package/lib/engine-components/ui/InputField.js +268 -268
  579. package/lib/engine-components/ui/Interfaces.d.ts +38 -38
  580. package/lib/engine-components/ui/Interfaces.js +12 -12
  581. package/lib/engine-components/ui/Layout.d.ts +84 -84
  582. package/lib/engine-components/ui/Layout.js +330 -330
  583. package/lib/engine-components/ui/Outline.d.ts +7 -7
  584. package/lib/engine-components/ui/Outline.js +20 -20
  585. package/lib/engine-components/ui/PointerEvents.d.ts +115 -115
  586. package/lib/engine-components/ui/PointerEvents.js +145 -145
  587. package/lib/engine-components/ui/RaycastUtils.d.ts +11 -11
  588. package/lib/engine-components/ui/RaycastUtils.js +67 -67
  589. package/lib/engine-components/ui/Raycaster.d.ts +30 -30
  590. package/lib/engine-components/ui/Raycaster.js +95 -95
  591. package/lib/engine-components/ui/RectTransform.d.ts +61 -61
  592. package/lib/engine-components/ui/RectTransform.js +356 -356
  593. package/lib/engine-components/ui/SpatialHtml.d.ts +8 -8
  594. package/lib/engine-components/ui/SpatialHtml.js +79 -79
  595. package/lib/engine-components/ui/Symbols.d.ts +1 -1
  596. package/lib/engine-components/ui/Symbols.js +1 -1
  597. package/lib/engine-components/ui/Text.d.ts +78 -78
  598. package/lib/engine-components/ui/Text.js +539 -539
  599. package/lib/engine-components/ui/Utils.d.ts +24 -24
  600. package/lib/engine-components/ui/Utils.js +90 -90
  601. package/lib/engine-components/ui/index.d.ts +1 -1
  602. package/lib/engine-components/ui/index.js +1 -1
  603. package/lib/engine-components/utils/EnvironmentScene.d.ts +5 -5
  604. package/lib/engine-components/utils/EnvironmentScene.js +205 -205
  605. package/lib/engine-components/utils/LookAt.d.ts +31 -31
  606. package/lib/engine-components/utils/LookAt.js +82 -82
  607. package/lib/engine-components/utils/OpenURL.d.ts +42 -42
  608. package/lib/engine-components/utils/OpenURL.js +119 -119
  609. package/lib/engine-components/webxr/Avatar.d.ts +25 -25
  610. package/lib/engine-components/webxr/Avatar.js +255 -255
  611. package/lib/engine-components/webxr/TeleportTarget.d.ts +7 -7
  612. package/lib/engine-components/webxr/TeleportTarget.js +7 -7
  613. package/lib/engine-components/webxr/WebARCameraBackground.d.ts +30 -30
  614. package/lib/engine-components/webxr/WebARCameraBackground.js +155 -155
  615. package/lib/engine-components/webxr/WebARSessionRoot.d.ts +98 -98
  616. package/lib/engine-components/webxr/WebARSessionRoot.js +770 -770
  617. package/lib/engine-components/webxr/WebXR.d.ts +232 -232
  618. package/lib/engine-components/webxr/WebXR.js +561 -561
  619. package/lib/engine-components/webxr/WebXRAvatar.d.ts +27 -27
  620. package/lib/engine-components/webxr/WebXRAvatar.js +44 -44
  621. package/lib/engine-components/webxr/WebXRImageTracking.d.ts +86 -86
  622. package/lib/engine-components/webxr/WebXRImageTracking.js +471 -471
  623. package/lib/engine-components/webxr/WebXRPlaneTracking.d.ts +92 -92
  624. package/lib/engine-components/webxr/WebXRPlaneTracking.js +500 -500
  625. package/lib/engine-components/webxr/WebXRRig.d.ts +32 -32
  626. package/lib/engine-components/webxr/WebXRRig.js +72 -72
  627. package/lib/engine-components/webxr/XRFlag.d.ts +38 -38
  628. package/lib/engine-components/webxr/XRFlag.js +139 -139
  629. package/lib/engine-components/webxr/controllers/XRControllerFollow.d.ts +47 -47
  630. package/lib/engine-components/webxr/controllers/XRControllerFollow.js +120 -120
  631. package/lib/engine-components/webxr/controllers/XRControllerModel.d.ts +43 -43
  632. package/lib/engine-components/webxr/controllers/XRControllerModel.js +352 -352
  633. package/lib/engine-components/webxr/controllers/XRControllerMovement.d.ts +78 -78
  634. package/lib/engine-components/webxr/controllers/XRControllerMovement.js +506 -506
  635. package/lib/engine-components/webxr/index.d.ts +3 -3
  636. package/lib/engine-components/webxr/index.js +3 -3
  637. package/lib/engine-components/webxr/types.d.ts +3 -3
  638. package/lib/engine-components/webxr/types.js +1 -1
  639. package/lib/engine-components-experimental/Presentation.d.ts +6 -6
  640. package/lib/engine-components-experimental/Presentation.js +9 -9
  641. package/lib/engine-components-experimental/api.d.ts +4 -4
  642. package/lib/engine-components-experimental/api.js +4 -4
  643. package/lib/engine-components-experimental/networking/PlayerSync.d.ts +156 -156
  644. package/lib/engine-components-experimental/networking/PlayerSync.js +377 -377
  645. package/lib/engine-schemes/api.d.ts +12 -12
  646. package/lib/engine-schemes/api.js +12 -12
  647. package/lib/engine-schemes/schemes.d.ts +7 -7
  648. package/lib/engine-schemes/schemes.js +19 -19
  649. package/lib/engine-schemes/synced-camera-model.d.ts +25 -25
  650. package/lib/engine-schemes/synced-camera-model.js +67 -67
  651. package/lib/engine-schemes/synced-transform-model.d.ts +31 -31
  652. package/lib/engine-schemes/synced-transform-model.js +66 -66
  653. package/lib/engine-schemes/transform.d.ts +12 -12
  654. package/lib/engine-schemes/transform.js +39 -39
  655. package/lib/engine-schemes/vec2.d.ts +10 -10
  656. package/lib/engine-schemes/vec2.js +25 -25
  657. package/lib/engine-schemes/vec3.d.ts +11 -11
  658. package/lib/engine-schemes/vec3.js +29 -29
  659. package/lib/engine-schemes/vec4.d.ts +12 -12
  660. package/lib/engine-schemes/vec4.js +33 -33
  661. package/lib/engine-schemes/vr-user-state-buffer.d.ts +37 -37
  662. package/lib/engine-schemes/vr-user-state-buffer.js +110 -110
  663. package/lib/include/three/EXT_mesh_gpu_instancing_exporter.d.ts +6 -6
  664. package/lib/include/three/EXT_mesh_gpu_instancing_exporter.js +45 -45
  665. package/lib/needle-engine.d.ts +7 -7
  666. package/lib/needle-engine.js +64 -64
  667. package/package.json +3 -3
  668. package/plugins/common/buildinfo.js +64 -64
  669. package/plugins/common/cloud.js +1 -1
  670. package/plugins/common/config.cjs +31 -31
  671. package/plugins/common/config.js +35 -35
  672. package/plugins/common/files.js +31 -31
  673. package/plugins/common/generator.js +10 -10
  674. package/plugins/common/license.js +452 -452
  675. package/plugins/common/logger.js +327 -327
  676. package/plugins/common/npm.js +15 -15
  677. package/plugins/common/timers.js +7 -7
  678. package/plugins/common/version.js +37 -37
  679. package/plugins/gltf-packer.mjs +1 -1
  680. package/plugins/next/alias.cjs +39 -39
  681. package/plugins/next/license.cjs +24 -24
  682. package/plugins/next/meshbvhworker.cjs +18 -18
  683. package/plugins/next/next.js +141 -141
  684. package/plugins/types/index.d.ts +2 -2
  685. package/plugins/types/license.d.ts +24 -24
  686. package/plugins/types/needleConfig.d.ts +27 -27
  687. package/plugins/types/next.d.ts +2 -2
  688. package/plugins/types/userconfig.d.ts +124 -124
  689. package/plugins/types/vite.d.ts +13 -13
  690. package/plugins/types/webmanifest.d.ts +32 -32
  691. package/plugins/vite/alias.js +189 -189
  692. package/plugins/vite/asap.js +251 -251
  693. package/plugins/vite/build-pipeline.js +371 -371
  694. package/plugins/vite/build.js +19 -19
  695. package/plugins/vite/buildinfo.js +41 -41
  696. package/plugins/vite/config.js +106 -106
  697. package/plugins/vite/copyfiles.js +138 -138
  698. package/plugins/vite/defines.js +70 -70
  699. package/plugins/vite/dependencies.js +232 -232
  700. package/plugins/vite/dependency-watcher.js +237 -237
  701. package/plugins/vite/drop-client.js +76 -76
  702. package/plugins/vite/drop.js +87 -87
  703. package/plugins/vite/editor-connection.js +124 -124
  704. package/plugins/vite/facebook-instant-games.js +102 -102
  705. package/plugins/vite/gzip.js +5 -5
  706. package/plugins/vite/imports-logger.js +143 -143
  707. package/plugins/vite/index.js +147 -147
  708. package/plugins/vite/license.js +56 -56
  709. package/plugins/vite/local-files.js +440 -440
  710. package/plugins/vite/logger.client.js +272 -272
  711. package/plugins/vite/logger.js +100 -100
  712. package/plugins/vite/materialx.js +31 -31
  713. package/plugins/vite/meta.js +163 -163
  714. package/plugins/vite/npm.js +7 -7
  715. package/plugins/vite/peer.js +29 -29
  716. package/plugins/vite/poster-client.js +73 -73
  717. package/plugins/vite/poster.js +79 -79
  718. package/plugins/vite/pwa.js +604 -604
  719. package/plugins/vite/reload-client.js +15 -15
  720. package/plugins/vite/reload.js +351 -351
  721. package/plugins/vite/server.js +66 -66
  722. package/plugins/vite/transform-codegen.js +55 -55
  723. package/plugins/vite/transform.js +32 -32
  724. package/plugins/vite/vite-4.4-hack.js +31 -31
  725. package/src/asap/needle-asap.ts +111 -111
  726. package/src/asap/sessiongranted.ts +75 -75
  727. package/src/asap/utils.ts +4 -4
  728. package/src/engine/analytics/index.ts +10 -10
  729. package/src/engine/analytics/lcp.ts +35 -35
  730. package/src/engine/api.ts +82 -82
  731. package/src/engine/assets/index.ts +59 -59
  732. package/src/engine/assets/static.js +5 -5
  733. package/src/engine/codegen/register_types.ts +300 -300
  734. package/src/engine/debug/debug.ts +51 -51
  735. package/src/engine/debug/debug_console.ts +333 -333
  736. package/src/engine/debug/debug_overlay.ts +332 -332
  737. package/src/engine/debug/debug_spatial_console.ts +429 -429
  738. package/src/engine/debug/index.ts +1 -1
  739. package/src/engine/engine_addressables.ts +671 -671
  740. package/src/engine/engine_animation.ts +145 -145
  741. package/src/engine/engine_application.ts +113 -113
  742. package/src/engine/engine_assetdatabase.ts +389 -389
  743. package/src/engine/engine_audio.ts +24 -24
  744. package/src/engine/engine_camera.ts +39 -39
  745. package/src/engine/engine_components.ts +366 -366
  746. package/src/engine/engine_components_internal.ts +40 -40
  747. package/src/engine/engine_constants.ts +52 -52
  748. package/src/engine/engine_context.ts +1824 -1824
  749. package/src/engine/engine_context_registry.ts +129 -129
  750. package/src/engine/engine_coroutine.ts +54 -54
  751. package/src/engine/engine_create_objects.ts +411 -411
  752. package/src/engine/engine_default_parameters.ts +3 -3
  753. package/src/engine/engine_editor-sync.ts +28 -28
  754. package/src/engine/engine_fileloader.js +9 -9
  755. package/src/engine/engine_gameobject.ts +712 -712
  756. package/src/engine/engine_generic_utils.js +13 -13
  757. package/src/engine/engine_gizmos.ts +577 -577
  758. package/src/engine/engine_gltf.ts +29 -29
  759. package/src/engine/engine_gltf_builtin_components.ts +403 -403
  760. package/src/engine/engine_hot_reload.ts +210 -210
  761. package/src/engine/engine_input.ts +1500 -1500
  762. package/src/engine/engine_input_utils.ts +23 -23
  763. package/src/engine/engine_instancing.ts +45 -45
  764. package/src/engine/engine_license.ts +386 -386
  765. package/src/engine/engine_lifecycle_api.ts +113 -113
  766. package/src/engine/engine_lifecycle_functions_internal.ts +193 -193
  767. package/src/engine/engine_lightdata.ts +125 -125
  768. package/src/engine/engine_loaders.callbacks.ts +136 -136
  769. package/src/engine/engine_loaders.gltf.ts +82 -82
  770. package/src/engine/engine_loaders.ts +378 -378
  771. package/src/engine/engine_lods.ts +186 -186
  772. package/src/engine/engine_mainloop_utils.ts +472 -472
  773. package/src/engine/engine_math.ts +282 -282
  774. package/src/engine/engine_modules.ts +83 -83
  775. package/src/engine/engine_networking.ts +862 -862
  776. package/src/engine/engine_networking_auto.ts +352 -352
  777. package/src/engine/engine_networking_blob.ts +275 -275
  778. package/src/engine/engine_networking_files.ts +217 -217
  779. package/src/engine/engine_networking_files_default_components.ts +58 -58
  780. package/src/engine/engine_networking_instantiate.ts +419 -419
  781. package/src/engine/engine_networking_peer.ts +159 -159
  782. package/src/engine/engine_networking_streams.ts +713 -713
  783. package/src/engine/engine_networking_types.ts +24 -24
  784. package/src/engine/engine_networking_utils.ts +23 -23
  785. package/src/engine/engine_networking_websocket.ts +2 -2
  786. package/src/engine/engine_patcher.ts +199 -199
  787. package/src/engine/engine_physics.ts +783 -783
  788. package/src/engine/engine_physics.types.ts +46 -46
  789. package/src/engine/engine_physics_rapier.ts +1577 -1577
  790. package/src/engine/engine_playerview.ts +80 -80
  791. package/src/engine/engine_scenelighting.ts +294 -294
  792. package/src/engine/engine_serialization.ts +2 -2
  793. package/src/engine/engine_serialization_builtin_serializer.ts +473 -473
  794. package/src/engine/engine_serialization_core.ts +720 -720
  795. package/src/engine/engine_serialization_decorator.ts +80 -80
  796. package/src/engine/engine_setup.ts +1 -1
  797. package/src/engine/engine_shaders.ts +267 -267
  798. package/src/engine/engine_shims.ts +32 -32
  799. package/src/engine/engine_test_utils.ts +109 -109
  800. package/src/engine/engine_texture.ts +82 -82
  801. package/src/engine/engine_three_utils.ts +928 -928
  802. package/src/engine/engine_time.ts +94 -94
  803. package/src/engine/engine_time_utils.ts +237 -237
  804. package/src/engine/engine_tonemapping.ts +208 -208
  805. package/src/engine/engine_types.ts +730 -730
  806. package/src/engine/engine_typestore.ts +63 -63
  807. package/src/engine/engine_util_decorator.ts +136 -136
  808. package/src/engine/engine_utils.ts +1115 -1115
  809. package/src/engine/engine_utils_format.ts +273 -273
  810. package/src/engine/engine_utils_screenshot.ts +708 -708
  811. package/src/engine/engine_utils_screenshot.xr.ts +103 -103
  812. package/src/engine/export/gltf/Writers.ts +34 -34
  813. package/src/engine/export/gltf/index.ts +158 -158
  814. package/src/engine/export/index.ts +2 -2
  815. package/src/engine/export/state.ts +19 -19
  816. package/src/engine/export/utils.ts +9 -9
  817. package/src/engine/extensions/EXT_texture_exr.ts +50 -50
  818. package/src/engine/extensions/NEEDLE_animator_controller_model.ts +195 -195
  819. package/src/engine/extensions/NEEDLE_components.ts +268 -268
  820. package/src/engine/extensions/NEEDLE_gameobject_data.ts +81 -81
  821. package/src/engine/extensions/NEEDLE_lighting_settings.ts +185 -185
  822. package/src/engine/extensions/NEEDLE_lightmaps.ts +119 -119
  823. package/src/engine/extensions/NEEDLE_persistent_assets.ts +76 -76
  824. package/src/engine/extensions/NEEDLE_render_objects.ts +209 -209
  825. package/src/engine/extensions/NEEDLE_techniques_webgl.ts +640 -640
  826. package/src/engine/extensions/extension_resolver.ts +4 -4
  827. package/src/engine/extensions/extension_utils.ts +166 -166
  828. package/src/engine/extensions/extensions.ts +140 -140
  829. package/src/engine/extensions/index.ts +5 -5
  830. package/src/engine/extensions/usage_tracker.ts +100 -100
  831. package/src/engine/js-extensions/Camera.ts +37 -37
  832. package/src/engine/js-extensions/ExtensionUtils.ts +85 -85
  833. package/src/engine/js-extensions/Layers.ts +23 -23
  834. package/src/engine/js-extensions/Object3D.ts +296 -296
  835. package/src/engine/js-extensions/RGBAColor.ts +126 -126
  836. package/src/engine/js-extensions/Vector.ts +18 -18
  837. package/src/engine/js-extensions/index.ts +4 -4
  838. package/src/engine/physics/workers/mesh-bvh/GenerateMeshBVHWorker.js +125 -125
  839. package/src/engine/shaders/shaderData.ts +67 -67
  840. package/src/engine/tests/test_utils.ts +63 -63
  841. package/src/engine/webcomponents/WebXRButtons.ts +260 -260
  842. package/src/engine/webcomponents/api.ts +6 -6
  843. package/src/engine/webcomponents/buttons.ts +292 -292
  844. package/src/engine/webcomponents/fonts.ts +41 -41
  845. package/src/engine/webcomponents/icons.ts +57 -57
  846. package/src/engine/webcomponents/index.ts +1 -1
  847. package/src/engine/webcomponents/logo-element.ts +78 -78
  848. package/src/engine/webcomponents/needle menu/needle-menu-spatial.ts +573 -573
  849. package/src/engine/webcomponents/needle menu/needle-menu.ts +1118 -1118
  850. package/src/engine/webcomponents/needle-button.ts +181 -181
  851. package/src/engine/webcomponents/needle-engine.ar-overlay.ts +186 -186
  852. package/src/engine/webcomponents/needle-engine.attributes.ts +82 -82
  853. package/src/engine/webcomponents/needle-engine.extras.ts +16 -16
  854. package/src/engine/webcomponents/needle-engine.loading.ts +373 -373
  855. package/src/engine/webcomponents/needle-engine.ts +860 -860
  856. package/src/engine/xr/NeedleXRController.ts +1125 -1125
  857. package/src/engine/xr/NeedleXRSession.ts +1624 -1624
  858. package/src/engine/xr/NeedleXRSync.ts +220 -220
  859. package/src/engine/xr/SceneTransition.ts +78 -78
  860. package/src/engine/xr/TempXRContext.ts +216 -216
  861. package/src/engine/xr/XRRig.ts +9 -9
  862. package/src/engine/xr/api.ts +5 -5
  863. package/src/engine/xr/events.ts +102 -102
  864. package/src/engine/xr/internal.ts +34 -34
  865. package/src/engine/xr/usdz.ts +30 -30
  866. package/src/engine/xr/utils.ts +39 -39
  867. package/src/engine-components/AlignmentConstraint.ts +36 -36
  868. package/src/engine-components/Animation.ts +557 -557
  869. package/src/engine-components/AnimationCurve.ts +150 -150
  870. package/src/engine-components/AnimationUtils.ts +28 -28
  871. package/src/engine-components/AnimationUtilsAutoplay.ts +43 -43
  872. package/src/engine-components/Animator.ts +397 -397
  873. package/src/engine-components/AnimatorController.ts +1293 -1293
  874. package/src/engine-components/AudioListener.ts +92 -92
  875. package/src/engine-components/AudioSource.ts +644 -644
  876. package/src/engine-components/AvatarLoader.ts +263 -263
  877. package/src/engine-components/AxesHelper.ts +59 -59
  878. package/src/engine-components/BasicIKConstraint.ts +54 -54
  879. package/src/engine-components/BoxCollider.ts +1 -1
  880. package/src/engine-components/BoxHelperComponent.ts +114 -114
  881. package/src/engine-components/Camera.ts +719 -719
  882. package/src/engine-components/CameraUtils.ts +138 -138
  883. package/src/engine-components/CharacterController.ts +253 -253
  884. package/src/engine-components/Collider.ts +374 -374
  885. package/src/engine-components/Component.ts +1297 -1297
  886. package/src/engine-components/ContactShadows.ts +506 -506
  887. package/src/engine-components/DeleteBox.ts +62 -62
  888. package/src/engine-components/DeviceFlag.ts +46 -46
  889. package/src/engine-components/DragControls.ts +1623 -1623
  890. package/src/engine-components/DropListener.ts +713 -713
  891. package/src/engine-components/Duplicatable.ts +198 -198
  892. package/src/engine-components/EventList.ts +266 -266
  893. package/src/engine-components/EventTrigger.ts +74 -74
  894. package/src/engine-components/EventType.ts +22 -22
  895. package/src/engine-components/Fog.ts +60 -60
  896. package/src/engine-components/Gizmos.ts +56 -56
  897. package/src/engine-components/GridHelper.ts +48 -48
  898. package/src/engine-components/GroundProjection.ts +356 -356
  899. package/src/engine-components/Interactable.ts +14 -14
  900. package/src/engine-components/Joints.ts +52 -52
  901. package/src/engine-components/LODGroup.ts +153 -153
  902. package/src/engine-components/Light.ts +558 -558
  903. package/src/engine-components/LookAtConstraint.ts +25 -25
  904. package/src/engine-components/NeedleMenu.ts +84 -84
  905. package/src/engine-components/NestedGltf.ts +86 -86
  906. package/src/engine-components/Networking.ts +114 -114
  907. package/src/engine-components/OffsetConstraint.ts +60 -60
  908. package/src/engine-components/OrbitControls.ts +1074 -1074
  909. package/src/engine-components/PlayerColor.ts +103 -103
  910. package/src/engine-components/ReflectionProbe.ts +220 -220
  911. package/src/engine-components/Renderer.ts +903 -903
  912. package/src/engine-components/RendererInstancing.ts +855 -855
  913. package/src/engine-components/RendererLightmap.ts +198 -198
  914. package/src/engine-components/RigidBody.ts +526 -526
  915. package/src/engine-components/SceneSwitcher.ts +1030 -1030
  916. package/src/engine-components/ScreenCapture.ts +592 -592
  917. package/src/engine-components/ShadowCatcher.ts +172 -172
  918. package/src/engine-components/Skybox.ts +475 -475
  919. package/src/engine-components/SmoothFollow.ts +76 -76
  920. package/src/engine-components/SpatialTrigger.ts +229 -229
  921. package/src/engine-components/SpectatorCamera.ts +787 -787
  922. package/src/engine-components/SphereCollider.ts +1 -1
  923. package/src/engine-components/SpriteRenderer.ts +468 -468
  924. package/src/engine-components/SyncedCamera.ts +220 -220
  925. package/src/engine-components/SyncedRoom.ts +380 -380
  926. package/src/engine-components/SyncedTransform.ts +383 -383
  927. package/src/engine-components/TestRunner.ts +118 -118
  928. package/src/engine-components/TransformGizmo.ts +219 -219
  929. package/src/engine-components/VideoPlayer.ts +1025 -1025
  930. package/src/engine-components/Voip.ts +363 -363
  931. package/src/engine-components/api.ts +60 -60
  932. package/src/engine-components/avatar/AvatarBlink_Simple.ts +69 -69
  933. package/src/engine-components/avatar/AvatarEyeLook_Rotation.ts +63 -63
  934. package/src/engine-components/avatar/Avatar_Brain_LookAt.ts +139 -139
  935. package/src/engine-components/avatar/Avatar_MouthShapes.ts +83 -83
  936. package/src/engine-components/avatar/Avatar_MustacheShake.ts +31 -31
  937. package/src/engine-components/codegen/components.ts +217 -217
  938. package/src/engine-components/debug/LogStats.ts +21 -21
  939. package/src/engine-components/export/gltf/GltfExport.ts +265 -265
  940. package/src/engine-components/export/usdz/Extension.ts +24 -24
  941. package/src/engine-components/export/usdz/ThreeUSDZExporter.ts +2426 -2426
  942. package/src/engine-components/export/usdz/USDZExporter.ts +705 -705
  943. package/src/engine-components/export/usdz/extensions/Animation.ts +1204 -1204
  944. package/src/engine-components/export/usdz/extensions/DocumentExtension.ts +9 -9
  945. package/src/engine-components/export/usdz/extensions/NodeMaterialConverter.ts +532 -532
  946. package/src/engine-components/export/usdz/extensions/USDZText.ts +240 -240
  947. package/src/engine-components/export/usdz/extensions/USDZUI.ts +189 -189
  948. package/src/engine-components/export/usdz/extensions/behavior/Actions.ts +99 -99
  949. package/src/engine-components/export/usdz/extensions/behavior/AudioExtension.ts +102 -102
  950. package/src/engine-components/export/usdz/extensions/behavior/Behaviour.ts +320 -320
  951. package/src/engine-components/export/usdz/extensions/behavior/BehaviourComponents.ts +1225 -1225
  952. package/src/engine-components/export/usdz/extensions/behavior/BehavioursBuilder.ts +646 -646
  953. package/src/engine-components/export/usdz/extensions/behavior/PhysicsExtension.ts +132 -132
  954. package/src/engine-components/export/usdz/index.ts +2 -2
  955. package/src/engine-components/export/usdz/utils/animationutils.ts +191 -191
  956. package/src/engine-components/export/usdz/utils/quicklook.ts +50 -50
  957. package/src/engine-components/particlesystem/ParticleSystem.ts +1287 -1287
  958. package/src/engine-components/particlesystem/ParticleSystemModules.ts +1765 -1765
  959. package/src/engine-components/particlesystem/ParticleSystemSubEmitter.ts +111 -111
  960. package/src/engine-components/particlesystem/api.ts +1 -1
  961. package/src/engine-components/postprocessing/Effects/Antialiasing.ts +64 -64
  962. package/src/engine-components/postprocessing/Effects/BloomEffect.ts +116 -116
  963. package/src/engine-components/postprocessing/Effects/ChromaticAberration.ts +37 -37
  964. package/src/engine-components/postprocessing/Effects/ColorAdjustments.ts +106 -106
  965. package/src/engine-components/postprocessing/Effects/DepthOfField.ts +103 -103
  966. package/src/engine-components/postprocessing/Effects/EffectWrapper.ts +25 -25
  967. package/src/engine-components/postprocessing/Effects/Pixelation.ts +32 -32
  968. package/src/engine-components/postprocessing/Effects/ScreenspaceAmbientOcclusion.ts +90 -90
  969. package/src/engine-components/postprocessing/Effects/ScreenspaceAmbientOcclusionN8.ts +192 -192
  970. package/src/engine-components/postprocessing/Effects/Sharpening.ts +143 -143
  971. package/src/engine-components/postprocessing/Effects/TiltShiftEffect.ts +61 -61
  972. package/src/engine-components/postprocessing/Effects/Tonemapping.ts +103 -103
  973. package/src/engine-components/postprocessing/Effects/Tonemapping.utils.ts +60 -60
  974. package/src/engine-components/postprocessing/Effects/Vignette.ts +59 -59
  975. package/src/engine-components/postprocessing/PostProcessingEffect.ts +192 -192
  976. package/src/engine-components/postprocessing/PostProcessingHandler.ts +572 -572
  977. package/src/engine-components/postprocessing/Volume.ts +426 -426
  978. package/src/engine-components/postprocessing/VolumeParameter.ts +158 -158
  979. package/src/engine-components/postprocessing/VolumeProfile.ts +61 -61
  980. package/src/engine-components/postprocessing/index.ts +5 -5
  981. package/src/engine-components/postprocessing/utils.ts +154 -154
  982. package/src/engine-components/timeline/PlayableDirector.ts +722 -722
  983. package/src/engine-components/timeline/SignalAsset.ts +144 -144
  984. package/src/engine-components/timeline/TimelineModels.ts +92 -92
  985. package/src/engine-components/timeline/TimelineTracks.ts +967 -967
  986. package/src/engine-components/timeline/index.ts +3 -3
  987. package/src/engine-components/ui/BaseUIComponent.ts +203 -203
  988. package/src/engine-components/ui/Button.ts +307 -307
  989. package/src/engine-components/ui/Canvas.ts +419 -419
  990. package/src/engine-components/ui/CanvasGroup.ts +54 -54
  991. package/src/engine-components/ui/EventSystem.ts +854 -854
  992. package/src/engine-components/ui/Graphic.ts +275 -275
  993. package/src/engine-components/ui/Image.ts +112 -112
  994. package/src/engine-components/ui/InputField.ts +321 -321
  995. package/src/engine-components/ui/Interfaces.ts +57 -57
  996. package/src/engine-components/ui/Layout.ts +334 -334
  997. package/src/engine-components/ui/Outline.ts +13 -13
  998. package/src/engine-components/ui/PointerEvents.ts +206 -206
  999. package/src/engine-components/ui/RaycastUtils.ts +69 -69
  1000. package/src/engine-components/ui/Raycaster.ts +102 -102
  1001. package/src/engine-components/ui/RectTransform.ts +375 -375
  1002. package/src/engine-components/ui/SpatialHtml.ts +79 -79
  1003. package/src/engine-components/ui/Symbols.ts +1 -1
  1004. package/src/engine-components/ui/Text.ts +578 -578
  1005. package/src/engine-components/ui/Utils.ts +113 -113
  1006. package/src/engine-components/utils/EnvironmentScene.ts +245 -245
  1007. package/src/engine-components/utils/LookAt.ts +88 -88
  1008. package/src/engine-components/utils/OpenURL.ts +114 -114
  1009. package/src/engine-components/webxr/Avatar.ts +265 -265
  1010. package/src/engine-components/webxr/TeleportTarget.ts +9 -9
  1011. package/src/engine-components/webxr/WebARCameraBackground.ts +175 -175
  1012. package/src/engine-components/webxr/WebARSessionRoot.ts +880 -880
  1013. package/src/engine-components/webxr/WebXR.ts +585 -585
  1014. package/src/engine-components/webxr/WebXRAvatar.ts +66 -66
  1015. package/src/engine-components/webxr/WebXRImageTracking.ts +519 -519
  1016. package/src/engine-components/webxr/WebXRPlaneTracking.ts +570 -570
  1017. package/src/engine-components/webxr/WebXRRig.ts +77 -77
  1018. package/src/engine-components/webxr/XRFlag.ts +147 -147
  1019. package/src/engine-components/webxr/controllers/XRControllerFollow.ts +118 -118
  1020. package/src/engine-components/webxr/controllers/XRControllerModel.ts +373 -373
  1021. package/src/engine-components/webxr/controllers/XRControllerMovement.ts +550 -550
  1022. package/src/engine-components/webxr/index.ts +2 -2
  1023. package/src/engine-components/webxr/types.ts +3 -3
  1024. package/src/engine-components-experimental/Presentation.ts +12 -12
  1025. package/src/engine-components-experimental/api.ts +4 -4
  1026. package/src/engine-components-experimental/networking/PlayerSync.ts +401 -401
  1027. package/src/engine-schemes/COMPILE_SCHEMES.bat +3 -3
  1028. package/src/engine-schemes/COMPILE_TS.bat +11 -11
  1029. package/src/engine-schemes/README.md +1 -1
  1030. package/src/engine-schemes/api.ts +12 -12
  1031. package/src/engine-schemes/schemes.ts +28 -28
  1032. package/src/engine-schemes/synced-camera-model.ts +92 -92
  1033. package/src/engine-schemes/synced-transform-model.ts +90 -90
  1034. package/src/engine-schemes/syncedCamera.fbs +10 -10
  1035. package/src/engine-schemes/transform.ts +50 -50
  1036. package/src/engine-schemes/transforms.fbs +25 -25
  1037. package/src/engine-schemes/vec.fbs +19 -19
  1038. package/src/engine-schemes/vec2.ts +33 -33
  1039. package/src/engine-schemes/vec3.ts +38 -38
  1040. package/src/engine-schemes/vec4.ts +43 -43
  1041. package/src/engine-schemes/vr-user-state-buffer.ts +145 -145
  1042. package/src/engine-schemes/vrUserStateBuffer.fbs +17 -17
  1043. package/src/include/draco/draco_decoder.js +34 -34
  1044. package/src/include/ktx2/basis_transcoder.js +21 -21
  1045. package/src/include/needle/arial-msdf.json +1471 -1471
  1046. package/src/include/three/DragControls.js +231 -231
  1047. package/src/include/three/EXT_mesh_gpu_instancing_exporter.js +66 -66
  1048. package/src/needle-engine.ts +70 -70
  1049. package/dist/generateMeshBVH.worker-Cdfpaq5W.js +0 -25
  1050. package/src/engine-schemes/dist/api.js +0 -17
  1051. package/src/engine-schemes/dist/api.js.meta +0 -7
  1052. package/src/engine-schemes/dist/schemes.js +0 -25
  1053. package/src/engine-schemes/dist/schemes.js.meta +0 -7
  1054. package/src/engine-schemes/dist/synced-camera-model.js +0 -74
  1055. package/src/engine-schemes/dist/synced-camera-model.js.meta +0 -7
  1056. package/src/engine-schemes/dist/synced-transform-model.js +0 -73
  1057. package/src/engine-schemes/dist/synced-transform-model.js.meta +0 -7
  1058. package/src/engine-schemes/dist/transform.js +0 -46
  1059. package/src/engine-schemes/dist/transform.js.meta +0 -7
  1060. package/src/engine-schemes/dist/vec2.js +0 -32
  1061. package/src/engine-schemes/dist/vec2.js.meta +0 -7
  1062. package/src/engine-schemes/dist/vec3.js +0 -36
  1063. package/src/engine-schemes/dist/vec3.js.meta +0 -7
  1064. package/src/engine-schemes/dist/vec4.js +0 -40
  1065. package/src/engine-schemes/dist/vec4.js.meta +0 -7
  1066. package/src/engine-schemes/dist/vr-user-state-buffer.js +0 -110
  1067. package/src/engine-schemes/dist/vr-user-state-buffer.js.meta +0 -7
@@ -1,1824 +1,1824 @@
1
- import 'three/examples/jsm/renderers/webgl-legacy/nodes/WebGLNodes.js';
2
-
3
- import type { EffectComposer } from "postprocessing";
4
- import {
5
- BufferGeometry, Camera, Color, DepthTexture, Group,
6
- Material, NearestFilter, NoToneMapping, Object3D, OrthographicCamera, PCFSoftShadowMap,
7
- PerspectiveCamera, RGBAFormat, Scene, SRGBColorSpace,
8
- Texture, WebGLRenderer, type WebGLRendererParameters, WebGLRenderTarget, type WebXRArrayCamera
9
- } from 'three';
10
- /** @ts-ignore (not yet in types?) */
11
- import { BasicNodeLibrary } from "three";
12
- import * as Stats from 'three/examples/jsm/libs/stats.module.js';
13
- import type { EffectComposer as ThreeEffectComposer } from "three/examples/jsm/postprocessing/EffectComposer.js";
14
- import { nodeFrame } from "three/examples/jsm/renderers/webgl-legacy/nodes/WebGLNodeBuilder.js";
15
-
16
- import { isDevEnvironment, LogType, showBalloonError, showBalloonMessage } from './debug/index.js';
17
- import { Addressables } from './engine_addressables.js';
18
- import { AnimationsRegistry } from './engine_animation.js';
19
- import { Application } from './engine_application.js';
20
- import { AssetDatabase } from './engine_assetdatabase.js';
21
- import { VERSION } from './engine_constants.js';
22
- import { ContextEvent, ContextRegistry } from './engine_context_registry.js';
23
- import { WaitForPromise } from './engine_coroutine.js';
24
- import { ObjectUtils } from "./engine_create_objects.js";
25
- import { destroy, foreachComponent } from './engine_gameobject.js';
26
- import { getLoader } from './engine_gltf.js';
27
- import { Input } from './engine_input.js';
28
- import { invokeLifecycleFunctions } from './engine_lifecycle_functions_internal.js';
29
- import { type ILightDataRegistry, LightDataRegistry } from './engine_lightdata.js';
30
- import { LODsManager } from "./engine_lods.js";
31
- import * as looputils from './engine_mainloop_utils.js';
32
- import { NetworkConnection } from './engine_networking.js';
33
- import { Physics } from './engine_physics.js';
34
- import { PlayerViewManager } from './engine_playerview.js';
35
- import { RendererData as SceneLighting } from './engine_scenelighting.js';
36
- import { getTempColor, logHierarchy } from './engine_three_utils.js';
37
- import { Time } from './engine_time.js';
38
- import { patchTonemapping } from './engine_tonemapping.js';
39
- import type { CoroutineData, ICamera, IComponent, IContext, ILight, LoadedModel, Model, Vec2 } from "./engine_types.js";
40
- import { deepClone, delay, DeviceUtilities, getParam } from './engine_utils.js';
41
- import type { INeedleXRSessionEventReceiver, NeedleXRSession } from './engine_xr.js';
42
- import { NeedleMenu } from './webcomponents/needle menu/needle-menu.js';
43
- import type { NeedleEngineWebComponent } from './webcomponents/needle-engine.js';
44
-
45
- const debug = getParam("debugcontext");
46
- const stats = getParam("stats");
47
- const debugActive = getParam("debugactive");
48
- const debugframerate = getParam("debugframerate");
49
- const debugCoroutine = getParam("debugcoroutine");
50
-
51
- // this is where functions that setup unity scenes will be pushed into
52
- // those will be accessed from our custom html element to load them into their context
53
- export const build_scene_functions: { [name: string]: (context: Context) => Promise<void> } = {};
54
-
55
-
56
- export declare class LoadingProgressArgs {
57
- /** the name or URL of the loaded file */
58
- name: string;
59
- /** the loading progress event from the loader */
60
- progress: ProgressEvent;
61
- /** the index of the loaded file */
62
- index: number;
63
- /** the total number of files to load */
64
- count: number;
65
- }
66
- export declare class ContextCreateArgs {
67
- /** list of glTF or GLB files to load */
68
- files: Array<string>;
69
- abortSignal?: AbortSignal;
70
- /** called when loading a provided glTF file started */
71
- onLoadingStart?: (index: number, file: string) => void;
72
- /** called on update for each loaded glTF file */
73
- onLoadingProgress?: (args: LoadingProgressArgs) => void;
74
- /** Called after a gLTF file has finished loading */
75
- onLoadingFinished?: (index: number, file: string, glTF: Model | null) => void;
76
- }
77
-
78
- export class ContextArgs {
79
- name?: string;
80
- /** for debugging only */
81
- alias?: string;
82
- /** the hash is used as a seed when initially loading the scene files */
83
- hash?: string;
84
-
85
- /** when true the context will not check if it's visible in the viewport and always update and render */
86
- runInBackground?: boolean;
87
- /** the DOM element the context belongs to or is inside of (this does not have to be the canvas. use renderer.domElement if you want to access the dom canvas) */
88
- domElement?: HTMLElement | null;
89
- /** externally owned renderer */
90
- renderer?: WebGLRenderer;
91
- /** externally owned camera */
92
- camera?: Camera;
93
- /** externally owned scene */
94
- scene?: Scene;
95
- }
96
-
97
- export enum FrameEvent {
98
- Start = -1,
99
- EarlyUpdate = 0,
100
- Update = 1,
101
- LateUpdate = 2,
102
- OnBeforeRender = 3,
103
- OnAfterRender = 4,
104
- PrePhysicsStep = 9,
105
- PostPhysicsStep = 10,
106
- Undefined = -1,
107
- }
108
-
109
- /** threejs callback event signature */
110
- export declare type OnRenderCallback = (renderer: WebGLRenderer, scene: Scene, camera: Camera, geometry: BufferGeometry, material: Material, group: Group) => void
111
-
112
-
113
- export function registerComponent(script: IComponent, context?: Context) {
114
- if (!script) return;
115
- if (!script.isComponent) {
116
- if (isDevEnvironment() || debug)
117
- console.error("Registered script is not a Needle Engine component. \nThe script will be ignored. Please make sure your component extends \"Behaviour\" imported from \"@needle-tools/engine\"\n", script);
118
- return;
119
- }
120
- if (!context) {
121
- context = Context.Current;
122
- if (debug) console.warn("> Registering component without context");
123
- }
124
- const new_scripts = context?.new_scripts;
125
- if (!new_scripts.includes(script)) {
126
- new_scripts.push(script);
127
- }
128
- }
129
-
130
- /**
131
- * The context is the main object that holds all the data and state of the Needle Engine.
132
- * It can be used to access the scene, renderer, camera, input, physics, networking, and more.
133
- * @example
134
- * ```typescript
135
- * import { Behaviour } from "@needle-tools/engine";
136
- * import { Mesh, BoxGeometry, MeshBasicMaterial } from "three";
137
- * export class MyScript extends Behaviour {
138
- * start() {
139
- * console.log("Hello from MyScript");
140
- * this.context.scene.add(new Mesh(new BoxGeometry(), new MeshBasicMaterial()));
141
- * }
142
- * }
143
- * ```
144
- */
145
- export class Context implements IContext {
146
-
147
- private static _defaultTargetFramerate: { value?: number, toString?() } = { value: 90, toString() { return this.value; } }
148
- /** When a new context is created this is the framerate that will be used by default */
149
- static get DefaultTargetFrameRate(): number | undefined {
150
- return Context._defaultTargetFramerate.value;
151
- }
152
- /** When a new context is created this is the framerate that will be used by default */
153
- static set DefaultTargetFrameRate(val: number | undefined) {
154
- Context._defaultTargetFramerate.value = val;
155
- }
156
-
157
- private static _defaultWebglRendererParameters: WebGLRendererParameters = {
158
- antialias: true,
159
- alpha: false,
160
- // Note: this is due to a bug on OSX devices. See NE-5370
161
- powerPreference: (DeviceUtilities.isiOS() || DeviceUtilities.isMacOS()) ? "default" : "high-performance",
162
- stencil: true,
163
- // logarithmicDepthBuffer: true,
164
- // reverseDepthBuffer: true, // https://github.com/mrdoob/three.js/issues/29770
165
- };
166
- /** The default parameters that will be used when creating a new WebGLRenderer.
167
- * Modify in global context to change the default parameters for all new contexts.
168
- * @example
169
- * ```typescript
170
- * import { Context } from "@needle-tools/engine";
171
- * Context.DefaultWebGLRendererParameters.antialias = false;
172
- * ```
173
- */
174
- static get DefaultWebGLRendererParameters(): WebGLRendererParameters {
175
- return Context._defaultWebglRendererParameters;
176
- }
177
-
178
- /** The needle engine version */
179
- get version() {
180
- return VERSION;
181
- }
182
-
183
- /** The currently active context. Only set during the update loops */
184
- static get Current(): Context {
185
- return ContextRegistry.Current as Context;
186
- }
187
-
188
- /** @internal this property should not be set by user code */
189
- static set Current(context: Context) {
190
- ContextRegistry.Current = context;
191
- }
192
-
193
- static get All(): Context[] {
194
- return ContextRegistry.All as Context[];
195
- }
196
-
197
- /** The name of the context */
198
- name: string;
199
- /** An alias for the context */
200
- alias: string | undefined | null;
201
- /** When the renderer or camera are managed by an external process (e.g. when running in r3f context).
202
- * When this is false you are responsible to call update(timestamp, xframe.
203
- * It is also currently assumed that rendering is handled performed by an external process
204
- * */
205
- isManagedExternally: boolean = false;
206
- /** set to true to pause the update loop. You can receive an event for it in your components.
207
- * Note that script updates will not be called when paused */
208
- isPaused: boolean = false;
209
- /** When enabled the application will run while not visible on the page */
210
- runInBackground: boolean = false;
211
- /**
212
- * Set to the target framerate you want your application to run in (you can use ?stats to check the fps)
213
- * Set to undefined if you want to run at the maximum framerate
214
- */
215
- targetFrameRate?: number | { value?: number };
216
-
217
- /** Use a higher number for more accurate physics simulation.
218
- * When undefined physics steps will be 1 for mobile devices and 5 for desktop devices
219
- * Set to 0 to disable physics updates
220
- * TODO: changing physics steps is currently not supported because then forces that we get from the character controller and rigidbody et al are not correct anymore - this needs to be properly tested before making this configureable
221
- */
222
- private physicsSteps?: number = 1;
223
-
224
- /** used to append to loaded assets */
225
- hash?: string;
226
-
227
- /** The `<needle-engine>` web component */
228
- domElement: NeedleEngineWebComponent | HTMLElement;
229
-
230
- appendHTMLElement(element: HTMLElement) {
231
- if (this.domElement.shadowRoot)
232
- return this.domElement.shadowRoot.appendChild(element);
233
- else return this.domElement.appendChild(element);
234
- }
235
-
236
- get resolutionScaleFactor() { return this._resolutionScaleFactor; }
237
- /** use to scale the resolution up or down of the renderer. default is 1 */
238
- set resolutionScaleFactor(val: number) {
239
- if (val === this._resolutionScaleFactor) return;
240
- if (typeof val !== "number") return;
241
- if (val <= 0) {
242
- console.error("Invalid resolution scale factor", val);
243
- return;
244
- }
245
- this._resolutionScaleFactor = val;
246
- this.updateSize();
247
- }
248
- private _resolutionScaleFactor: number = 1;
249
-
250
- // domElement.clientLeft etc doesnt return absolute position
251
- private _boundingClientRectFrame: number = -1;
252
- private _boundingClientRect: DOMRect | null = null;
253
- private _domX; private _domY;
254
- /** update bounding rects + domX, domY */
255
- private calculateBoundingClientRect() {
256
- // workaround for mozilla webXR viewer
257
- if (this.xr) {
258
- this._domX = 0;
259
- this._domY = 0;
260
- return;
261
- }
262
- // TODO: cache this
263
- if (this._boundingClientRectFrame === this.time.frame) return;
264
- this._boundingClientRectFrame = this.time.frame;
265
- this._boundingClientRect = this.domElement.getBoundingClientRect();
266
- this._domX = this._boundingClientRect.x;
267
- this._domY = this._boundingClientRect.y;
268
- }
269
-
270
- /** The width of the `<needle-engine>` element on the website */
271
- get domWidth(): number {
272
- // for mozilla XR
273
- if (this.isInAR) return window.innerWidth;
274
- return this.domElement.clientWidth;
275
- }
276
- /** The height of the `<needle-engine>` element on the website */
277
- get domHeight(): number {
278
- // for mozilla XR
279
- if (this.isInAR) return window.innerHeight;
280
- return this.domElement.clientHeight;
281
- }
282
- /** the X position of the `<needle-engine>` element on the website */
283
- get domX(): number {
284
- this.calculateBoundingClientRect();
285
- return this._domX;
286
- }
287
- /** the Y position of the `<needle-engine>` element on the website */
288
- get domY(): number {
289
- this.calculateBoundingClientRect();
290
- return this._domY;
291
- }
292
- /**
293
- * Is a XR session currently active and presenting?
294
- * @returns true if the xr renderer is currently presenting
295
- */
296
- get isInXR() { return this.renderer?.xr?.isPresenting || false; }
297
- /** shorthand for `NeedleXRSession.active`
298
- * Automatically set by NeedleXRSession when a XR session is active
299
- * @returns the active XR session or null if no session is active
300
- * */
301
- xr: NeedleXRSession | null = null;
302
- /**
303
- * Shorthand for `this.xr?.mode`. AR or VR
304
- * @returns the current XR session mode (immersive-vr or immersive-ar)
305
- */
306
- get xrSessionMode() { return this.xr?.mode; }
307
- /** Shorthand for `this.xrSessionMode === "immersive-vr"`
308
- * @returns true if a webxr VR session is currently active.
309
- */
310
- get isInVR() { return this.xrSessionMode === "immersive-vr"; }
311
- /**
312
- * Shorthand for `this.xrSessionMode === "immersive-ar"`
313
- * @returns true if a webxr AR session is currently active.
314
- */
315
- get isInAR() { return this.xrSessionMode === "immersive-ar"; }
316
- /** If a XR session is active and in pass through mode (immersive-ar on e.g. Quest)
317
- * @returns true if the XR session is in pass through mode
318
- */
319
- get isInPassThrough() { return this.xr ? this.xr.isPassThrough : false; }
320
- /** access the raw `XRSession` object (shorthand for `context.renderer.xr.getSession()`). For more control use `NeedleXRSession.active` */
321
- get xrSession() { return this.renderer?.xr?.getSession(); }
322
- /** @returns the latest XRFrame (if a XRSession is currently active)
323
- * @link https://developer.mozilla.org/en-US/docs/Web/API/XRFrame
324
- */
325
- get xrFrame() { return this._xrFrame }
326
- /** @returns the current WebXR camera while the WebXRManager is active (shorthand for `context.renderer.xr.getCamera()`) */
327
- get xrCamera(): WebXRArrayCamera | undefined { return this.renderer.xr.isPresenting ? this.renderer?.xr?.getCamera() : undefined }
328
- private _xrFrame: XRFrame | null = null;
329
- /**
330
- * The AR overlay element is used to display 2D HTML elements while a AR session is active.
331
- */
332
- get arOverlayElement(): HTMLElement {
333
- const el = this.domElement as any;
334
- if (typeof el.getAROverlayContainer === "function")
335
- return el.getAROverlayContainer();
336
- return this.domElement;
337
- }
338
- /**
339
- * Current event of the update cycle (e.g. `FrameEvent.EarlyUpdate` or `FrameEvent.OnBeforeRender`)
340
- */
341
- get currentFrameEvent(): FrameEvent {
342
- return this._currentFrameEvent;
343
- }
344
- private _currentFrameEvent: FrameEvent = FrameEvent.Undefined;
345
-
346
- /**
347
- * The scene contains all objects in the hierarchy and is automatically rendered by the context every frane.
348
- */
349
- scene: Scene;
350
- /**
351
- * The renderer is used to render the scene. It is automatically created when the context is created.
352
- */
353
- renderer!: WebGLRenderer;
354
- /**
355
- * The effect composer can be used to render postprocessing effects. If assigned then it will automatically render the scene every frame.
356
- */
357
- composer: EffectComposer | ThreeEffectComposer | null = null;
358
-
359
- /**
360
- * @internal All known components. Don't use directly
361
- */
362
- readonly scripts: IComponent[] = [];
363
- /**
364
- * @internal All paused components. Don't use directly
365
- */
366
- readonly scripts_pausedChanged: IComponent[] = [];
367
- /**
368
- * @internal All components that have a early update event. Don't use directly
369
- */
370
- readonly scripts_earlyUpdate: IComponent[] = [];
371
- /**
372
- * @internal All components that have a update event. Don't use directly
373
- */
374
- readonly scripts_update: IComponent[] = [];
375
- /**
376
- * @internal All components that have a late update event. Don't use directly
377
- */
378
- readonly scripts_lateUpdate: IComponent[] = [];
379
- /**
380
- * @internal All components that have a onBeforeRender event. Don't use directly
381
- */
382
- readonly scripts_onBeforeRender: IComponent[] = [];
383
- /**
384
- * @internal All components that have a onAfterRender event. Don't use directly
385
- */
386
- readonly scripts_onAfterRender: IComponent[] = [];
387
- /**
388
- * @internal All components that have coroutines. Don't use directly
389
- */
390
- readonly scripts_WithCorroutines: IComponent[] = [];
391
- /**
392
- * @internal Components with immersive-vr event methods. Don't use directly
393
- */
394
- readonly scripts_immersive_vr: INeedleXRSessionEventReceiver[] = [];
395
- /**
396
- * @internal Components with immersive-ar event methods. Don't use directly
397
- */
398
- readonly scripts_immersive_ar: INeedleXRSessionEventReceiver[] = [];
399
- /**
400
- * @internal Coroutine data
401
- */
402
- readonly coroutines: { [FrameEvent: number]: Array<CoroutineData> } = {}
403
-
404
- /** callbacks called once after the context has been created */
405
- readonly post_setup_callbacks: Function[] = [];
406
- /** called every frame at the beginning of the frame (after component start events and before earlyUpdate) */
407
- readonly pre_update_callbacks: Function[] = [];
408
- /** called every frame before rendering (after all component events) */
409
- readonly pre_render_callbacks: Array<(frame: XRFrame | null) => void> = [];
410
- /** called every frame after rendering (after all component events) */
411
- readonly post_render_callbacks: Function[] = [];
412
- /** called every frame befroe update (this list is emptied every frame) */
413
- readonly pre_update_oneshot_callbacks: Function[] = [];
414
-
415
- /** @internal */
416
- readonly new_scripts: IComponent[] = [];
417
- /** @internal */
418
- readonly new_script_start: IComponent[] = [];
419
- /** @internal */
420
- readonly new_scripts_pre_setup_callbacks: Function[] = [];
421
- /** @internal */
422
- readonly new_scripts_post_setup_callbacks: Function[] = [];
423
- /** @internal */
424
- readonly new_scripts_xr: INeedleXRSessionEventReceiver[] = [];
425
-
426
- /**
427
- * The **main camera component** of the scene - this camera is used for rendering.
428
- * Use `setCurrentCamera` for updating the main camera.
429
- */
430
- mainCameraComponent: ICamera | undefined = undefined;
431
-
432
- /**
433
- * The main camera of the scene - this camera is used for rendering
434
- * Use `setCurrentCamera` for updating the main camera.
435
- */
436
- get mainCamera(): Camera {
437
- if (this._mainCamera) {
438
- return this._mainCamera;
439
- }
440
- if (this.mainCameraComponent) {
441
- const cam = this.mainCameraComponent as ICamera;
442
- if (!cam.threeCamera)
443
- cam.buildCamera();
444
- return cam.threeCamera;
445
- }
446
- if (!this._fallbackCamera) {
447
- this._fallbackCamera = new PerspectiveCamera(75, this.domWidth / this.domHeight, 0.1, 1000);
448
- }
449
- return this._fallbackCamera;
450
- }
451
- /** Set the main camera of the scene. If set to null the camera of the {@link mainCameraComponent} will be used - this camera is used for rendering */
452
- set mainCamera(cam: Camera | null) {
453
- this._mainCamera = cam;
454
- }
455
- private _mainCamera: Camera | null = null;
456
- private _fallbackCamera: PerspectiveCamera | null = null;
457
-
458
- /** access application state (e.g. if all audio should be muted) */
459
- application: Application;
460
- /** access animation mixer used by components in the scene */
461
- animations: AnimationsRegistry;
462
- /** access timings (current frame number, deltaTime, timeScale, ...) */
463
- time: Time;
464
- /** access input data (e.g. click or touch events) */
465
- input: Input;
466
- /** access physics related methods (e.g. raycasting). To access the phyiscs engine use `context.physics.engine` */
467
- physics: Physics;
468
- /** access networking methods (use it to send or listen to messages or join a networking backend) */
469
- connection: NetworkConnection;
470
- /**
471
- * @deprecated AssetDataBase is deprecated
472
- */
473
- assets: AssetDatabase;
474
- /** The main light in the scene */
475
- mainLight: ILight | null = null;
476
- /** @deprecated Use sceneLighting */
477
- get rendererData() { return this.sceneLighting }
478
- sceneLighting: SceneLighting;
479
- addressables: Addressables;
480
- lightmaps: ILightDataRegistry;
481
- players: PlayerViewManager;
482
- readonly lodsManager: LODsManager;
483
- /** Access the needle menu to add or remove buttons to the menu element */
484
- readonly menu: NeedleMenu;
485
-
486
- /** @returns true if the context is fully created and ready */
487
- get isCreated() { return this._isCreated; }
488
-
489
- private _needsUpdateSize: boolean = false;
490
- private _isCreated: boolean = false;
491
- private _isCreating: boolean = false;
492
- private _isVisible: boolean = false;
493
-
494
- private _stats = stats ? new Stats.default() : null;
495
-
496
- constructor(args?: ContextArgs) {
497
- this.name = args?.name || "";
498
- this.alias = args?.alias;
499
- this.domElement = args?.domElement || document.body;
500
- this.hash = args?.hash;
501
-
502
- if (args?.renderer) {
503
- this.renderer = args.renderer;
504
- this.isManagedExternally = true;
505
- }
506
- if (args?.runInBackground !== undefined) this.runInBackground = args.runInBackground;
507
- if (args?.scene) this.scene = args.scene;
508
- else this.scene = new Scene();
509
- if (args?.camera) this._mainCamera = args.camera;
510
-
511
- this.application = new Application(this);
512
- this.time = new Time();
513
- this.input = new Input(this);
514
- this.physics = new Physics(this);
515
- this.connection = new NetworkConnection(this);
516
- // eslint-disable-next-line deprecation/deprecation
517
- this.assets = new AssetDatabase();
518
- this.sceneLighting = new SceneLighting(this);
519
- this.addressables = new Addressables(this);
520
- this.lightmaps = new LightDataRegistry(this);
521
- this.players = new PlayerViewManager(this);
522
- this.menu = new NeedleMenu(this);
523
- this.lodsManager = new LODsManager(this);
524
- this.animations = new AnimationsRegistry(this);
525
-
526
-
527
- const resizeCallback = () => this._needsUpdateSize = true;
528
- window.addEventListener('resize', resizeCallback);
529
- this._disposeCallbacks.push(() => window.removeEventListener('resize', resizeCallback));
530
-
531
- const resizeObserver = new ResizeObserver(_ => this._needsUpdateSize = true);
532
- resizeObserver.observe(this.domElement);
533
- this._disposeCallbacks.push(() => resizeObserver.disconnect());
534
-
535
- this._intersectionObserver = new IntersectionObserver(entries => {
536
- this._isVisible = entries[0].isIntersecting;
537
- });
538
- this._disposeCallbacks.push(() => this._intersectionObserver?.disconnect());
539
-
540
- ContextRegistry.register(this);
541
- }
542
-
543
- /**
544
- * Calling this function will dispose the current renderer and create a new one which will then be assigned to the context. It can be used to create a new renderer with custom WebGLRendererParameters.
545
- * **Note**: Instead you can also modify the static `Context.DefaultWebGlRendererParameters` before the context is created.
546
- * **Note**: This method is recommended because it re-uses an potentially already existing canvas element. This is necessary to keep input event handlers from working (e.g. components like OrbitControls subscribe to input events on the canvas)
547
- * @returns {WebGLRenderer} the newly created renderer
548
- */
549
- createNewRenderer(params?: WebGLRendererParameters) {
550
- this.renderer?.dispose();
551
-
552
- params = { ...Context.DefaultWebGLRendererParameters, ...params };
553
- if (!params.canvas) {
554
- // get canvas already configured in the Needle Engine Web Component
555
- const canvas = this.domElement?.shadowRoot?.querySelector("canvas");
556
- if (canvas) {
557
- params.canvas = canvas;
558
- if (debug) {
559
- console.log("Using canvas from shadow root", canvas);
560
- }
561
- }
562
- }
563
- if (debug) console.log("Using Renderer Parameters:", params, this.domElement)
564
-
565
- this.renderer = new WebGLRenderer(params);
566
-
567
- this.renderer.debug.checkShaderErrors = isDevEnvironment() || getParam("checkshadererrors") === true;
568
-
569
- // some tonemapping other than "NONE" is required for adjusting exposure with EXR environments
570
- this.renderer.toneMappingExposure = 1; // range [0...inf] instead of the usual -15..15
571
- this.renderer.toneMapping = NoToneMapping; // could also set to LinearToneMapping, ACESFilmicToneMapping
572
-
573
- this.renderer.setClearColor(new Color('lightgrey'), 0);
574
- // // @ts-ignore
575
- // this.renderer.alpha = false;
576
- this.renderer.shadowMap.enabled = true;
577
- this.renderer.shadowMap.type = PCFSoftShadowMap;
578
- this.renderer.setSize(this.domWidth, this.domHeight);
579
- this.renderer.outputColorSpace = SRGBColorSpace;
580
-
581
- // Injecting the core nodes library here, like WebGPURenderer backends do
582
- //@ts-ignore
583
- this.renderer.nodes = {
584
- library: new BasicNodeLibrary(),
585
- modelViewMatrix: null,
586
- modelNormalViewMatrix: null,
587
- };
588
- // this.renderer.toneMapping = AgXToneMapping;
589
- this.lodsManager.setRenderer(this.renderer);
590
-
591
- this.input.bindEvents();
592
-
593
- return this.renderer;
594
- }
595
-
596
-
597
- private _intersectionObserver: IntersectionObserver | null = null;
598
- private internalOnUpdateVisible() {
599
- this._intersectionObserver?.disconnect();
600
- this._intersectionObserver?.observe(this.domElement);
601
- }
602
-
603
- private _disposeCallbacks: Function[] = [];
604
-
605
-
606
- /** will request a renderer size update the next render call (will call updateSize the next update) */
607
- requestSizeUpdate() { this._needsUpdateSize = true; }
608
-
609
- /** Clamps the renderer max resolution. If undefined the max resolution is not clamped. Default is undefined */
610
- maxRenderResolution?: Vec2;
611
-
612
- /** Control the renderer devicePixelRatio.
613
- * **Options**
614
- * - `auto` - Needle Engine automatically sets the pixel ratio to the current window.devicePixelRatio.
615
- * - `manual` - Needle Engine will not change the renderer pixel ratio. You can set it manually.
616
- * - `number` - Needle Engine will set the pixel ratio to the given number. The change will be applied to the renderer and the composer (if used) at the end of the current frame.
617
- */
618
- get devicePixelRatio() { return this._devicePixelRatio; }
619
- set devicePixelRatio(val: "auto" | "manual" | number) {
620
- if (val !== this._devicePixelRatio) {
621
- this._devicePixelRatio = val;
622
- this._needsUpdateSize = true;
623
- }
624
- }
625
- private _devicePixelRatio: "auto" | "manual" | number = "auto";
626
-
627
- /**
628
- * Update the renderer and canvas size. This is also automatically called when a DOM size change is detected.
629
- */
630
- updateSize(force: boolean = false) {
631
- if (force || (!this.isManagedExternally && this.renderer.xr?.isPresenting === false)) {
632
- this._needsUpdateSize = false;
633
- const scaleFactor = this.resolutionScaleFactor;
634
- let width = this.domWidth * scaleFactor;
635
- let height = this.domHeight * scaleFactor;
636
- if (this.maxRenderResolution) {
637
- this.maxRenderResolution.x = Math.max(1, this.maxRenderResolution.x);
638
- width = Math.min(this.maxRenderResolution.x, width);
639
- this.maxRenderResolution.y = Math.max(1, this.maxRenderResolution.y);
640
- height = Math.min(this.maxRenderResolution.y, height);
641
- }
642
- const camera = this.mainCamera as PerspectiveCamera;
643
- this.updateAspect(camera);
644
- this.renderer.setSize(width, height, true);
645
- // avoid setting pixel values here since this can cause pingpong updates
646
- // e.g. when system scale is set to 125%
647
- // https://github.com/needle-tools/needle-engine-support/issues/69
648
- this.renderer.domElement.style.width = "100%";
649
- this.renderer.domElement.style.height = "100%";
650
-
651
- const devicePixelRatio = typeof this.devicePixelRatio === "number"
652
- ? this.devicePixelRatio
653
- : this.devicePixelRatio === "auto"
654
- ? window.devicePixelRatio
655
- : undefined;
656
- if (devicePixelRatio !== undefined) {
657
- this.renderer.setPixelRatio(devicePixelRatio);
658
- }
659
-
660
- if (this.composer) {
661
- this.composer.setSize?.call(this.composer, width, height);
662
- if (devicePixelRatio !== undefined && "setPixelRatio" in this.composer && typeof this.composer.setPixelRatio === "function")
663
- this.composer.setPixelRatio?.call(this.composer, window.devicePixelRatio);
664
- }
665
- }
666
- }
667
-
668
- /**
669
- * Update the camera aspect ratio or orthorgraphic camera size. This is automatically called when a DOM size change is detected.
670
- */
671
- updateAspect(camera: PerspectiveCamera | OrthographicCamera, width?: number, height?: number) {
672
- if (!camera) return;
673
- if (width === undefined)
674
- width = this.domWidth;
675
- if (height === undefined)
676
- height = this.domHeight;
677
- const aspectRatio = width / height;
678
- if ((camera as PerspectiveCamera).isPerspectiveCamera) {
679
- const cam = camera as PerspectiveCamera;
680
- const pa = cam.aspect;
681
- cam.aspect = aspectRatio;
682
- if (pa !== cam.aspect)
683
- camera.updateProjectionMatrix();
684
- }
685
- else if ((camera as OrthographicCamera).isOrthographicCamera) {
686
- const cam = camera as OrthographicCamera;
687
- // Maintain the camera's current vertical size (top - bottom)
688
- const verticalSize = cam.top - cam.bottom;
689
- // Calculate new horizontal size based on aspect ratio
690
- const horizontalSize = verticalSize * aspectRatio;
691
- // Update camera bounds while maintaining center position
692
- const halfWidth = horizontalSize / 2;
693
- const halfHeight = verticalSize / 2;
694
- if (cam.left != -halfWidth || cam.top != halfHeight) {
695
- cam.left = -halfWidth;
696
- cam.right = halfWidth;
697
- cam.top = halfHeight;
698
- cam.bottom = -halfHeight;
699
- camera.updateProjectionMatrix();
700
- }
701
- }
702
- }
703
-
704
- /** This will recreate the whole needle engine context and dispose the whole scene content
705
- * All content will be reloaded (loading times might be faster due to browser caches)
706
- * All scripts will be recreated */
707
- recreate() {
708
- this.clear();
709
- this.create(this._originalCreationArgs);
710
- }
711
-
712
- private _originalCreationArgs?: ContextCreateArgs;
713
-
714
- /** @deprecated use create. This method will be removed in a future version */
715
- async onCreate(opts?: ContextCreateArgs) {
716
- return this.create(opts);
717
- }
718
- /** @internal */
719
- async create(opts?: ContextCreateArgs) {
720
- try {
721
- this._isCreating = true;
722
- if (opts !== this._originalCreationArgs)
723
- this._originalCreationArgs = deepClone(opts);
724
- window.addEventListener("unhandledrejection", this.onUnhandledRejection)
725
- const res = await this.internalOnCreate(opts);
726
- this._isCreated = res;
727
- return res;
728
- }
729
- finally {
730
- window.removeEventListener("unhandledrejection", this.onUnhandledRejection)
731
- this._isCreating = false;
732
- }
733
- }
734
-
735
- private onUnhandledRejection = (event: PromiseRejectionEvent) => {
736
- this.onError(event.reason);
737
- };
738
-
739
- /** Dispatches an error */
740
- private onError(error: string) {
741
- this.domElement.dispatchEvent(new CustomEvent("error", { detail: error }));
742
- }
743
-
744
- /**
745
- * Clears the context and destroys all scenes and objects in the scene.
746
- * The ContextCleared event is called at the end.
747
- * This is automatically called when e.g. the `src` attribute changes on `<needle-engine>`
748
- * or when the web component is removed from the DOM
749
- */
750
- clear() {
751
- ContextRegistry.dispatchCallback(ContextEvent.ContextClearing, this);
752
- invokeLifecycleFunctions(this, ContextEvent.ContextClearing);
753
- // NOTE: this does dispose the environment/background image too
754
- // which is probably not desired if it is set via the background-image attribute
755
- destroy(this.scene, true, true);
756
- this.scene = new Scene();
757
- this.addressables?.dispose();
758
- this.lightmaps?.clear();
759
- this.physics?.engine?.clearCaches();
760
- this.lodsManager.disable();
761
-
762
- this._onBeforeRenderListeners.clear();
763
- this._onAfterRenderListeners.clear();
764
-
765
- if (!this.isManagedExternally) {
766
- if (this.renderer) {
767
- this.renderer.renderLists.dispose();
768
- this.renderer.state.reset();
769
- this.renderer.resetState();
770
- }
771
- }
772
- // We do not want to clear the renderer here because when switching src we want to keep the last rendered frame in case the loading screen is not visible
773
- // if a user wants to see the background they can still call setClearAlpha(0) and clear manually
774
- ContextRegistry.dispatchCallback(ContextEvent.ContextCleared, this);
775
- }
776
-
777
- /**
778
- * Dispose all allocated resources and clears the scene. This is automatically called e.g. when the `<needle-engine>` component is removed from the DOM.
779
- */
780
- dispose() {
781
- this.internalOnDestroy();
782
- }
783
-
784
- /**@deprecated use dispose() */
785
- onDestroy() { this.internalOnDestroy(); }
786
-
787
- private internalOnDestroy() {
788
- Context.Current = this;
789
- ContextRegistry.dispatchCallback(ContextEvent.ContextDestroying, this);
790
- invokeLifecycleFunctions(this, ContextEvent.ContextDestroying);
791
- this.clear();
792
- this.renderer?.setAnimationLoop(null);
793
- if (this.renderer) {
794
- this.renderer.setClearAlpha(0);
795
- this.renderer.clear();
796
- if (!this.isManagedExternally) {
797
- if (debug) console.log("Disposing renderer");
798
- this.renderer.dispose();
799
- }
800
- }
801
- this.scene = null!;
802
- this.renderer = null!;
803
- this.input.dispose();
804
- this.menu.onDestroy();
805
- this.animations.onDestroy();
806
- for (const cb of this._disposeCallbacks) {
807
- try {
808
- cb();
809
- }
810
- catch (e) {
811
- console.error("Error in on dispose callback:", e, cb);
812
- }
813
- }
814
- if (this.domElement?.parentElement) {
815
- this.domElement.parentElement.removeChild(this.domElement);
816
- }
817
- this._isCreated = false;
818
- ContextRegistry.dispatchCallback(ContextEvent.ContextDestroyed, this);
819
- invokeLifecycleFunctions(this, ContextEvent.ContextDestroyed);
820
- ContextRegistry.unregister(this);
821
- if (Context.Current === this) {
822
- //@ts-ignore
823
- Context.Current = null;
824
- }
825
- }
826
-
827
- /** @internal Automatically called by components when you call `startCoroutine`. Use `startCoroutine` instead */
828
- registerCoroutineUpdate(script: IComponent, coroutine: Generator, evt: FrameEvent): Generator {
829
- if (typeof coroutine?.next !== "function") {
830
- console.error("Registered invalid coroutine function from " + script.name + "\nCoroutine functions must be generators: \"*myCoroutine() {...}\"\nStart a coroutine from a component by calling \"this.startCoroutine(myCoroutine())\"")
831
- return coroutine;
832
- }
833
- if (!this.coroutines[evt]) this.coroutines[evt] = [];
834
- this.coroutines[evt].push({ comp: script, main: coroutine });
835
- return coroutine;
836
- }
837
-
838
- /** @internal Automatically called by components. */
839
- unregisterCoroutineUpdate(coroutine: Generator, evt: FrameEvent): void {
840
- if (!this.coroutines[evt]) return;
841
- const idx = this.coroutines[evt].findIndex(c => c.main === coroutine);
842
- if (idx >= 0) this.coroutines[evt].splice(idx, 1);
843
- }
844
-
845
- /** @internal Automatically called */
846
- stopAllCoroutinesFrom(script: IComponent) {
847
- for (const evt in this.coroutines) {
848
- const rout: CoroutineData[] = this.coroutines[evt];
849
- for (let i = rout.length - 1; i >= 0; i--) {
850
- const r = rout[i];
851
- if (r.comp === script) {
852
- rout.splice(i, 1);
853
- }
854
- }
855
- }
856
- }
857
-
858
- private _cameraStack: ICamera[] = [];
859
-
860
- /** Change the main camera */
861
- setCurrentCamera(cam: ICamera) {
862
- if (!cam) return;
863
- if (!cam.threeCamera) cam.buildCamera(); // < to build camera
864
- if (!cam.threeCamera) {
865
- console.warn("Camera component is missing camera", cam)
866
- return;
867
- }
868
- const index = this._cameraStack.indexOf(cam);
869
- if (index >= 0) this._cameraStack.splice(index, 1);
870
- this._cameraStack.push(cam);
871
- this.mainCameraComponent = cam;
872
- const camera = cam.threeCamera as PerspectiveCamera;
873
- if (camera.isPerspectiveCamera)
874
- this.updateAspect(camera);
875
- (this.mainCameraComponent as ICamera)?.applyClearFlagsIfIsActiveCamera();
876
- }
877
-
878
- /**
879
- * Remove the camera from the mainCamera stack (if it has been set before with `setCurrentCamera`)
880
- */
881
- removeCamera(cam?: ICamera | null) {
882
- if (!cam) return;
883
- const index = this._cameraStack.indexOf(cam);
884
- if (index >= 0) this._cameraStack.splice(index, 1);
885
-
886
- if (this.mainCameraComponent === cam) {
887
- this.mainCameraComponent = undefined;
888
-
889
- if (this._cameraStack.length > 0) {
890
- const last = this._cameraStack[this._cameraStack.length - 1];
891
- this.setCurrentCamera(last);
892
- }
893
- }
894
- }
895
-
896
- private readonly _onBeforeRenderListeners = new Map<string, OnRenderCallback[]>();
897
- private readonly _onAfterRenderListeners = new Map<string, OnRenderCallback[]>();
898
-
899
- /** Use to subscribe to onBeforeRender events on threejs objects.
900
- * @link https://threejs.org/docs/#api/en/core/Object3D.onBeforeRender
901
- */
902
- addBeforeRenderListener(target: Object3D, callback: OnRenderCallback) {
903
- if (!this._onBeforeRenderListeners.has(target.uuid)) {
904
- const arr: OnRenderCallback[] = [];
905
- this._onBeforeRenderListeners.set(target.uuid, arr);
906
- target.onBeforeRender = this._createRenderCallbackWrapper(arr);
907
- }
908
- this._onBeforeRenderListeners.get(target.uuid)!.push(callback);
909
- }
910
- /** Remove callback from three `onBeforeRender` event (if it has been added with `addBeforeRenderListener(...)`)
911
- * @link https://threejs.org/docs/#api/en/core/Object3D.onBeforeRender
912
- */
913
- removeBeforeRenderListener(target: Object3D, callback: OnRenderCallback) {
914
- if (this._onBeforeRenderListeners.has(target.uuid)) {
915
- const arr = this._onBeforeRenderListeners.get(target.uuid)!;
916
- const idx = arr.indexOf(callback);
917
- if (idx >= 0) arr.splice(idx, 1);
918
- }
919
- }
920
-
921
- /**
922
- * Subscribe to onAfterRender events on threejs objects
923
- * @link https://threejs.org/docs/#api/en/core/Object3D.onAfterRender
924
- */
925
- addAfterRenderListener(target: Object3D, callback: OnRenderCallback) {
926
- if (!this._onAfterRenderListeners.has(target.uuid)) {
927
- const arr = [];
928
- this._onAfterRenderListeners.set(target.uuid, arr);
929
- target.onAfterRender = this._createRenderCallbackWrapper(arr);
930
- }
931
- this._onAfterRenderListeners.get(target.uuid)?.push(callback);
932
- }
933
- /**
934
- * Remove from onAfterRender events on threejs objects
935
- * @link https://threejs.org/docs/#api/en/core/Object3D.onAfterRender
936
- */
937
- removeAfterRenderListener(target: Object3D, callback: OnRenderCallback) {
938
- if (this._onAfterRenderListeners.has(target.uuid)) {
939
- const arr = this._onAfterRenderListeners.get(target.uuid)!;
940
- const idx = arr.indexOf(callback);
941
- if (idx >= 0) arr.splice(idx, 1);
942
- }
943
- }
944
-
945
-
946
- private _createRenderCallbackWrapper(array: OnRenderCallback[]): OnRenderCallback {
947
- return (renderer, scene, camera, geometry, material, group) => {
948
- for (let i = 0; i < array.length; i++) {
949
- const fn = array[i];
950
- fn(renderer, scene, camera, geometry, material, group);
951
- }
952
- }
953
- }
954
-
955
-
956
-
957
- private _requireDepthTexture: boolean = false;
958
- private _requireColorTexture: boolean = false;
959
- private _renderTarget?: WebGLRenderTarget;
960
- private _isRendering: boolean = false;
961
-
962
- /** @returns true while the WebGL renderer is rendering (between onBeforeRender and onAfterRender events) */
963
- get isRendering() { return this._isRendering; }
964
-
965
- setRequireDepth(val: boolean) {
966
- this._requireDepthTexture = val;
967
- }
968
- setRequireColor(val: boolean) {
969
- this._requireColorTexture = val;
970
- }
971
- get depthTexture(): DepthTexture | null {
972
- return this._renderTarget?.depthTexture || null;
973
- }
974
- get opaqueColorTexture(): Texture | null {
975
- return this._renderTarget?.texture || null;
976
- }
977
-
978
- /** @returns true if the `<needle-engine>` DOM element is visible on screen (`context.domElement`) */
979
- get isVisibleToUser() {
980
- if (this.isInXR) return true;
981
- if (!this._isVisible) return false;
982
- const style = getComputedStyle(this.domElement);
983
- return style.visibility !== "hidden" && style.display !== "none" && style.opacity !== "0";
984
- }
985
-
986
- private _createId: number = 0;
987
- private async internalOnCreate(opts?: ContextCreateArgs): Promise<boolean> {
988
- const createId = ++this._createId;
989
-
990
- if (debug) console.log("Creating context", this.name, opts);
991
-
992
- // wait for async imported dependencies to be loaded
993
- // see https://linear.app/needle/issue/NE-4445
994
- const dependenciesReady = globalThis["needle:dependencies:ready"];
995
- if (dependenciesReady instanceof Promise) {
996
- if (debug) console.log("Waiting for dependencies to be ready");
997
- await dependenciesReady
998
- .catch(err => {
999
- if (debug || isDevEnvironment()) {
1000
- showBalloonError("Needle Engine dependencies failed to load. Please check the console for more details");
1001
- const printedError = false;
1002
- if (err instanceof ReferenceError) {
1003
- let offendingComponentName = "YourComponentName";
1004
- const offendingComponentStartIndex = err.message.indexOf("'");
1005
- if (offendingComponentStartIndex > 0) {
1006
- const offendingComponentEndIndex = err.message.indexOf("'", offendingComponentStartIndex + 1);
1007
- if (offendingComponentEndIndex > 0) {
1008
- const name = err.message.substring(offendingComponentStartIndex + 1, offendingComponentEndIndex);
1009
- if (name.length > 3) offendingComponentName = name;
1010
- }
1011
- }
1012
- console.error(`Needle Engine dependencies failed to load:\n\n# Make sure you don't have circular imports in your scripts!\n\nPossible solutions: \n→ Replace @serializable(${offendingComponentName}) in your script with @serializable(Behaviour)\n→ If you only need type information try importing the type only, e.g: import { type ${offendingComponentName} }\n\n---`, err)
1013
- return;
1014
- }
1015
- if (!printedError) {
1016
- console.error("Needle Engine dependencies failed to load", err);
1017
- }
1018
- }
1019
- })
1020
- .then(() => {
1021
- if (debug) console.log("Needle Engine dependencies are ready");
1022
- });
1023
- }
1024
-
1025
- this.clear();
1026
-
1027
- const oldRenderer = this.renderer;
1028
- // We only need to create a new renderer if we don't have one yet
1029
- // We do prevent creating a new renderer here to avoid flickering when the context is created while the content is still being loaded. This can be the case where CSS transformations update the layout (e.g. scale() while loading + old canvas disposed but in the DOM layout.)
1030
- const needsNewRenderer = !oldRenderer || oldRenderer["isDisposed"] === true;
1031
-
1032
- // stop the animation loop if its running during creation
1033
- // since we do not want to start enabling scripts etc before they are deserialized
1034
- if (this.isManagedExternally === false && (needsNewRenderer)) {
1035
- this.createNewRenderer();
1036
- }
1037
- else {
1038
- this.lodsManager.setRenderer(this.renderer);
1039
- }
1040
- this.renderer?.setAnimationLoop(null);
1041
-
1042
- await delay(1);
1043
-
1044
- Context.Current = this;
1045
- await ContextRegistry.dispatchCallback(ContextEvent.ContextCreationStart, this);
1046
-
1047
- // load and create scene
1048
- let prepare_succeeded = true;
1049
- let loadedFiles!: Array<LoadedModel | null>;
1050
- try {
1051
- Context.Current = this;
1052
- if (opts) {
1053
- loadedFiles = await this.internalLoadInitialContent(createId, opts);
1054
- }
1055
- else loadedFiles = [];
1056
- }
1057
- catch (err) {
1058
- console.error(err);
1059
- prepare_succeeded = false;
1060
- }
1061
- if (!prepare_succeeded) {
1062
- this.onError("Failed to load initial content");
1063
- return false;
1064
- }
1065
- if (createId !== this._createId || opts?.abortSignal?.aborted) {
1066
- return false;
1067
- }
1068
-
1069
- this.internalOnUpdateVisible();
1070
-
1071
- if (!this.renderer) {
1072
- if (debug) console.warn("Context has no renderer (perhaps it was disconnected?", this.domElement.isConnected);
1073
- return false;
1074
- }
1075
-
1076
- if (!this.isManagedExternally && !this.domElement.shadowRoot) {
1077
- this.domElement.prepend(this.renderer.domElement);
1078
- }
1079
-
1080
- Context.Current = this;
1081
-
1082
- // TODO: we could configure if we need physics
1083
- // await this.physics.engine?.initialize();
1084
-
1085
- // Setup
1086
- Context.Current = this;
1087
- for (let i = 0; i < this.new_scripts.length; i++) {
1088
- const script = this.new_scripts[i];
1089
- if (script.gameObject !== undefined && script.gameObject !== null) {
1090
- if (script.gameObject.userData === undefined) script.gameObject.userData = {};
1091
- if (script.gameObject.userData.components === undefined) script.gameObject.userData.components = [];
1092
- const arr = script.gameObject.userData.components;
1093
- if (!arr.includes(script)) arr.push(script);
1094
- }
1095
- // if (script.gameObject && !this.raycastTargets.includes(script.gameObject)) {
1096
- // this.raycastTargets.push(script.gameObject);
1097
- // }
1098
- }
1099
-
1100
- // const context = new SerializationContext(this.scene);
1101
- // for (let i = 0; i < this.new_scripts.length; i++) {
1102
- // const script = this.new_scripts[i];
1103
- // const ser = script as unknown as ISerializable;
1104
- // if (ser.$serializedTypes === undefined) continue;
1105
- // context.context = this;
1106
- // context.object = script.gameObject;
1107
- // deserializeObject(ser, script, context);
1108
- // }
1109
-
1110
- // resolve post setup callbacks (things that rely on threejs objects having references to components)
1111
- if (this.post_setup_callbacks) {
1112
- for (let i = 0; i < this.post_setup_callbacks.length; i++) {
1113
- Context.Current = this;
1114
- await this.post_setup_callbacks[i](this);
1115
- }
1116
- }
1117
-
1118
- if (!this._mainCamera) {
1119
- Context.Current = this;
1120
- let camera: ICamera | null = null;
1121
- foreachComponent(this.scene, comp => {
1122
- const cam = comp as ICamera;
1123
- if (cam?.isCamera) {
1124
- looputils.updateActiveInHierarchyWithoutEventCall(cam.gameObject);
1125
- if (!cam.activeAndEnabled) return undefined;
1126
- if (cam.tag === "MainCamera") {
1127
- camera = cam;
1128
- return true;
1129
- }
1130
- else camera = cam;
1131
- }
1132
- return undefined;
1133
- });
1134
- if (camera) {
1135
- this.setCurrentCamera(camera);
1136
- }
1137
- else {
1138
- const res = ContextRegistry.dispatchCallback(ContextEvent.MissingCamera, this, { files: loadedFiles });
1139
- if (!res && !this.mainCamera && !this.isManagedExternally)
1140
- console.warn("Missing camera in main scene", this);
1141
- }
1142
- }
1143
-
1144
- this.input.bindEvents();
1145
-
1146
- Context.Current = this;
1147
- looputils.processNewScripts(this);
1148
-
1149
- // We have to step once so that colliders that have been created in onEnable can be raycasted in start
1150
- if (this.physics.engine) {
1151
- this.physics.engine?.step(0);
1152
- this.physics.engine?.postStep();
1153
- }
1154
-
1155
- // const mainCam = this.mainCameraComponent as Camera;
1156
- // if (mainCam) {
1157
- // mainCam.applyClearFlagsIfIsActiveCamera();
1158
- // }
1159
-
1160
- if (!this.isManagedExternally && this.composer && this.mainCamera) {
1161
- // TODO: import postprocessing async
1162
- // const renderPass = new RenderPass(this.scene, this.mainCamera);
1163
- // this.renderer.setSize(this.domWidth, this.domHeight);
1164
- // this.composer.addPass(renderPass);
1165
- // this.composer.setSize(this.domWidth, this.domHeight);
1166
- }
1167
-
1168
- this._needsUpdateSize = true;
1169
-
1170
- if (this._stats) {
1171
- this._stats.showPanel(0);
1172
- this._stats.dom.style.position = "absolute"; // (default is fixed)
1173
- this.domElement.shadowRoot?.appendChild(this._stats.dom);
1174
- }
1175
-
1176
- if (debug)
1177
- logHierarchy(this.scene, true);
1178
-
1179
- // If no target framerate was set we use the default
1180
- if (this.targetFrameRate === undefined) {
1181
- if (debug) console.warn("No target framerate set, using default", Context.DefaultTargetFrameRate);
1182
- // the _defaultTargetFramerate is intentionally an object so it can be changed at any time if not explictly set by the user
1183
- this.targetFrameRate = Context._defaultTargetFramerate;
1184
- }
1185
- else if (debug) console.log("Target framerate set to", this.targetFrameRate);
1186
-
1187
- this._dispatchReadyAfterFrame = true;
1188
- const res = ContextRegistry.dispatchCallback(ContextEvent.ContextCreated, this, { files: loadedFiles });
1189
- if (res) {
1190
- const domElement = this.domElement as HTMLElement;
1191
- if ("internalSetLoadingMessage" in domElement && typeof domElement.internalSetLoadingMessage === "function")
1192
- domElement?.internalSetLoadingMessage("finish loading");
1193
- await res;
1194
- }
1195
- if (opts?.abortSignal?.aborted) {
1196
- return false;
1197
- }
1198
- invokeLifecycleFunctions(this, ContextEvent.ContextCreated);
1199
- if (debug) console.log("Context Created...", this.renderer, this.renderer.domElement)
1200
-
1201
- this._isCreating = false;
1202
- if (!this.isManagedExternally && !opts?.abortSignal?.aborted)
1203
- this.restartRenderLoop();
1204
- return true;
1205
- }
1206
-
1207
- private async internalLoadInitialContent(createId: number, args: ContextCreateArgs): Promise<Array<LoadedModel>> {
1208
- const results = new Array<LoadedModel>();
1209
- // early out if we dont have any files to load
1210
- if (args.files.length === 0) return results;
1211
-
1212
-
1213
- const files = [...args.files];
1214
- const progressArg: LoadingProgressArgs = {
1215
- name: "",
1216
- progress: null!,
1217
- index: 0,
1218
- count: files.length
1219
- }
1220
-
1221
- const loader = getLoader();
1222
- // this hash should be constant since it is used to initialize the UIDProvider per initially loaded scene
1223
- const loadingHash = 0;
1224
- for (let i = 0; i < files.length; i++) {
1225
- if (args.abortSignal?.aborted) {
1226
- if (debug) console.log("Aborting loading because of abort signal");
1227
- break;
1228
- }
1229
- // abort loading if the create id has changed
1230
- if (createId !== this._createId) {
1231
- if (debug) console.log("Aborting loading because create id changed", createId, this._createId);
1232
- break;
1233
- }
1234
- const file = files[i];
1235
- args?.onLoadingStart?.call(this, i, file);
1236
- if (debug) console.log("Context Load " + file);
1237
- const res = await loader.loadSync(this, file, file, loadingHash, prog => {
1238
- if (args.abortSignal?.aborted) return;
1239
- progressArg.name = file;
1240
- progressArg.progress = prog;
1241
- progressArg.index = i;
1242
- progressArg.count = files.length;
1243
- args.onLoadingProgress?.call(this, progressArg);
1244
- });
1245
- args?.onLoadingFinished?.call(this, i, file, res ?? null);
1246
- if (res) {
1247
- results.push({
1248
- src: file,
1249
- file: res
1250
- });
1251
- }
1252
- else {
1253
- // a file could not be loaded
1254
- console.warn("Could not load file: " + file);
1255
- }
1256
- }
1257
-
1258
- // if the id was changed while still loading
1259
- // then we want to cleanup/destroy previously loaded files
1260
- if (createId !== this._createId || args.abortSignal?.aborted) {
1261
- if (debug) console.log("Aborting loading because create id changed or abort signal was set", createId, this._createId);
1262
- for (const res of results) {
1263
- if (res && res.file) {
1264
- for (const scene of res.file.scenes)
1265
- destroy(scene, true, true);
1266
- }
1267
- }
1268
- }
1269
- // otherwise we want to add the loaded files to the current scene
1270
- else {
1271
- let anyModelFound = false;
1272
- for (const res of results) {
1273
- if (res && res.file) {
1274
- // TODO: should we load all scenes in a glTF here?
1275
- if (res.file.scene) {
1276
- anyModelFound = true;
1277
- this.scene.add(res.file.scene);
1278
- }
1279
- else {
1280
- console.warn("No scene found in loaded file");
1281
- }
1282
- }
1283
- }
1284
- // If the loaded files do not contain ANY model
1285
- // We then attempt to create a mesh from each material in the loaded files to visualize it
1286
- // It's ok to do this at this point because we know the context has been cleared because the whole `src` attribute has been set
1287
- if (!anyModelFound) {
1288
- for (const res of results) {
1289
- if (res && res.file && "parser" in res.file) {
1290
- let y = 0;
1291
- if (!Array.isArray(res.file.parser.json.materials)) continue;
1292
- for (let i = 0; i < res.file.parser.json.materials.length; i++) {
1293
- const mat = await res.file.parser.getDependency("material", i);
1294
- const parent = new Object3D();
1295
- parent.position.x = i * 1.1;
1296
- parent.position.y = y;
1297
- this.scene.add(parent);
1298
- ObjectUtils.createPrimitive("ShaderBall", {
1299
- parent,
1300
- material: mat
1301
- });
1302
- }
1303
- y += 1;
1304
- }
1305
- }
1306
- }
1307
- }
1308
-
1309
- return results;
1310
- }
1311
-
1312
-
1313
- /** Sets the animation loop.
1314
- * Can not be done while creating the context or when disposed
1315
- **/
1316
- public restartRenderLoop(): boolean {
1317
- if (!this.renderer) {
1318
- console.error("Can not start render loop without renderer");
1319
- return false;
1320
- }
1321
- if (this._isCreating) {
1322
- console.warn("Can not start render loop while creating context");
1323
- return false;
1324
- }
1325
- this.renderer.setAnimationLoop((timestamp, frame: XRFrame | null) => {
1326
- if (this.isManagedExternally) return;
1327
- this.update(timestamp, frame)
1328
- });
1329
- return true;
1330
- }
1331
-
1332
- private _renderlooperrors = 0;
1333
-
1334
- /** Performs a full update step including script callbacks, rendering (unless isManagedExternally is set to false) and post render callbacks */
1335
- public update(timestamp: DOMHighResTimeStamp, frame?: XRFrame | null) {
1336
- if (frame === undefined) frame = null;
1337
- if (isDevEnvironment() || debug || looputils.hasNewScripts()) {
1338
- try {
1339
- //performance.mark('update.start');
1340
- this.internalStep(timestamp, frame);
1341
- this._renderlooperrors = 0;
1342
- //performance.mark('update.end');
1343
- //performance.measure('NE Frame', 'update.start', 'update.end');
1344
- }
1345
- catch (err) {
1346
- this._renderlooperrors += 1;
1347
- if ((isDevEnvironment() || debug) && (err instanceof Error || err instanceof TypeError))
1348
- showBalloonMessage(`Caught unhandled exception during render-loop - see console for details.`, LogType.Error);
1349
- console.error("Frame #" + this.time.frame + "\n", err);
1350
- if (this._renderlooperrors >= 3) {
1351
- console.warn("Stopping render loop due to error")
1352
- this.renderer.setAnimationLoop(null);
1353
- }
1354
- this.domElement.dispatchEvent(new CustomEvent("error", { detail: err }));
1355
- }
1356
- }
1357
- else {
1358
- this.internalStep(timestamp, frame);
1359
- }
1360
- }
1361
-
1362
- /** Call to **manually** perform physics steps.
1363
- * By default the context uses the `physicsSteps` property to perform steps during the update loop
1364
- * If you just want to increase the accuracy of physics you can instead set the `physicsSteps` property to a higher value
1365
- * */
1366
- public updatePhysics(steps: number) {
1367
- this.internalUpdatePhysics(steps);
1368
- }
1369
-
1370
- private _lastTimestamp = 0;
1371
- private _accumulatedTime = 0;
1372
- private _dispatchReadyAfterFrame = false;
1373
-
1374
- // TODO: we need to skip after render callbacks if the render loop is managed externally. When changing this we also need to to update the r3f sample
1375
- private internalStep(timestamp: DOMHighResTimeStamp, frame: XRFrame | null) {
1376
- if (this.internalOnBeforeRender(timestamp, frame) === false) return;
1377
- this.internalOnRender();
1378
- this.internalOnAfterRender();
1379
- }
1380
-
1381
- private internalOnBeforeRender(timestamp: DOMHighResTimeStamp, frame: XRFrame | null) {
1382
-
1383
- // If we don't auto reset we get wrong stats in WebXR. AutoReset was turned off to support custom blits and count them too
1384
- // But when we're using postprocessing we need to reset manually: https://discourse.threejs.org/t/accessing-draw-calls-when-using-effectcomposer
1385
- this.renderer.info.autoReset = frame ? true : false;
1386
- if (this.renderer.info.autoReset === false) {
1387
- this.renderer.info.reset();
1388
- }
1389
-
1390
-
1391
- const sessionStarted = frame !== null && this._xrFrame === null;
1392
- this._xrFrame = frame;
1393
- if (sessionStarted) {
1394
- this.domElement.dispatchEvent(new CustomEvent("xr-session-started", { detail: { context: this, session: this.xrSession, frame: frame } }));
1395
- }
1396
-
1397
- this._currentFrameEvent = FrameEvent.Undefined;
1398
-
1399
- if (this.isManagedExternally === false && this.isInXR === false && this.targetFrameRate !== undefined) {
1400
- if (this._lastTimestamp === 0) this._lastTimestamp = timestamp;
1401
- this._accumulatedTime += (timestamp - this._lastTimestamp) / 1000;
1402
- this._lastTimestamp = timestamp;
1403
- let targetFrameRate = this.targetFrameRate;
1404
- if (typeof targetFrameRate === "object") targetFrameRate = targetFrameRate.value!;
1405
- // if(debug) console.log(this._accumulatedTime, (1 / (targetFrameRate)))
1406
- if (this._accumulatedTime < (1 / (targetFrameRate + 1))) {
1407
- return false;
1408
- }
1409
- this._accumulatedTime = 0;
1410
- }
1411
-
1412
- this._stats?.begin();
1413
-
1414
- Context.Current = this;
1415
- if (this.onHandlePaused()) return false;
1416
-
1417
- Context.Current = this;
1418
- this.time.update();
1419
- if (debugframerate)
1420
- console.log("FPS", (this.time.smoothedFps).toFixed(0));
1421
-
1422
-
1423
- looputils.processNewScripts(this);
1424
- looputils.updateIsActive(this.scene);
1425
- looputils.processStart(this);
1426
- invokeLifecycleFunctions(this, FrameEvent.Start);
1427
-
1428
- while (this._cameraStack.length > 0 && (!this.mainCameraComponent || this.mainCameraComponent.destroyed)) {
1429
- this._cameraStack.splice(this._cameraStack.length - 1, 1);
1430
- const last = this._cameraStack[this._cameraStack.length - 1];
1431
- this.setCurrentCamera(last);
1432
- }
1433
-
1434
- if (this.pre_update_oneshot_callbacks) {
1435
- for (const i in this.pre_update_oneshot_callbacks) {
1436
- this.pre_update_oneshot_callbacks[i]();
1437
- }
1438
- this.pre_update_oneshot_callbacks.length = 0;
1439
- }
1440
-
1441
- if (this.pre_update_callbacks) {
1442
- for (const i in this.pre_update_callbacks) {
1443
- this.pre_update_callbacks[i]();
1444
- }
1445
- }
1446
-
1447
- this._currentFrameEvent = FrameEvent.EarlyUpdate;
1448
-
1449
- for (let i = 0; i < this.scripts_earlyUpdate.length; i++) {
1450
- const script = this.scripts_earlyUpdate[i];
1451
- if (!script.activeAndEnabled) continue;
1452
- if (script.earlyUpdate !== undefined) {
1453
- Context.Current = this;
1454
- script.earlyUpdate();
1455
- }
1456
- }
1457
- this.executeCoroutines(FrameEvent.EarlyUpdate);
1458
- invokeLifecycleFunctions(this, FrameEvent.EarlyUpdate);
1459
- if (this.onHandlePaused()) return false;
1460
-
1461
- this._currentFrameEvent = FrameEvent.Update;
1462
-
1463
- for (let i = 0; i < this.scripts_update.length; i++) {
1464
- const script = this.scripts_update[i];
1465
- if (!script.activeAndEnabled) continue;
1466
- if (script.update !== undefined) {
1467
- Context.Current = this;
1468
- script.update();
1469
- }
1470
- }
1471
- this.executeCoroutines(FrameEvent.Update);
1472
- invokeLifecycleFunctions(this, FrameEvent.Update);
1473
- if (this.onHandlePaused()) return false;
1474
-
1475
- this._currentFrameEvent = FrameEvent.LateUpdate;
1476
-
1477
- for (let i = 0; i < this.scripts_lateUpdate.length; i++) {
1478
- const script = this.scripts_lateUpdate[i];
1479
- if (!script.activeAndEnabled) continue;
1480
- if (script.lateUpdate !== undefined) {
1481
- Context.Current = this;
1482
- script.lateUpdate();
1483
- }
1484
- }
1485
-
1486
- // this.mainLight = null;
1487
- this.executeCoroutines(FrameEvent.LateUpdate);
1488
- invokeLifecycleFunctions(this, FrameEvent.LateUpdate);
1489
- if (this.onHandlePaused()) return false;
1490
-
1491
- if (this.physicsSteps === undefined) {
1492
- this.physicsSteps = 1;
1493
- }
1494
- if (this.physics.engine && this.physicsSteps > 0) {
1495
- this.internalUpdatePhysics(this.physicsSteps);
1496
- }
1497
-
1498
- if (this.onHandlePaused()) return false;
1499
-
1500
- if (this.isVisibleToUser || this.runInBackground) {
1501
-
1502
- this._currentFrameEvent = FrameEvent.OnBeforeRender;
1503
-
1504
- // should we move these callbacks in the regular three onBeforeRender events?
1505
- for (let i = 0; i < this.scripts_onBeforeRender.length; i++) {
1506
- const script = this.scripts_onBeforeRender[i];
1507
- if (!script.activeAndEnabled) continue;
1508
- // if(script.isActiveAndEnabled === false) continue;
1509
- if (script.onBeforeRender !== undefined) {
1510
- Context.Current = this;
1511
- script.onBeforeRender(frame);
1512
- }
1513
- }
1514
-
1515
- this.executeCoroutines(FrameEvent.OnBeforeRender);
1516
- invokeLifecycleFunctions(this, FrameEvent.OnBeforeRender);
1517
-
1518
- if (this._needsUpdateSize)
1519
- this.updateSize();
1520
-
1521
- if (this.pre_render_callbacks) {
1522
- for (const i in this.pre_render_callbacks) {
1523
- this.pre_render_callbacks[i](frame);
1524
- }
1525
- }
1526
-
1527
- }
1528
-
1529
- return true;
1530
- }
1531
-
1532
- private internalUpdatePhysics(steps: number) {
1533
- if (!this.physics.engine) return false;
1534
- const physicsSteps = steps;
1535
- const dt = this.time.deltaTime / physicsSteps;
1536
- for (let i = 0; i < physicsSteps; i++) {
1537
- this._currentFrameEvent = FrameEvent.PrePhysicsStep;
1538
- this.executeCoroutines(FrameEvent.PrePhysicsStep);
1539
- this.physics.engine.step(dt);
1540
- this._currentFrameEvent = FrameEvent.PostPhysicsStep;
1541
- this.executeCoroutines(FrameEvent.PostPhysicsStep);
1542
- }
1543
- this.physics.engine.postStep();
1544
- return true;
1545
- }
1546
-
1547
- private internalOnRender() {
1548
- if (!this.isManagedExternally) {
1549
- // when loading assets we compile them async after GLTFLoader is done
1550
- // but as a fallback we still register them (if e.g. there's no camera for compile async)
1551
- looputils.runPrewarm(this);
1552
- this._currentFrameEvent = FrameEvent.Undefined;
1553
- nodeFrame.update();
1554
- this.renderNow();
1555
- this._currentFrameEvent = FrameEvent.OnAfterRender;
1556
- }
1557
- }
1558
-
1559
- private internalOnAfterRender() {
1560
- if (this.isVisibleToUser || this.runInBackground) {
1561
- for (let i = 0; i < this.scripts_onAfterRender.length; i++) {
1562
- const script = this.scripts_onAfterRender[i];
1563
- if (!script.activeAndEnabled) continue;
1564
- if (script.onAfterRender !== undefined) {
1565
- Context.Current = this;
1566
- script.onAfterRender();
1567
- }
1568
- }
1569
-
1570
- this.executeCoroutines(FrameEvent.OnAfterRender);
1571
- invokeLifecycleFunctions(this, FrameEvent.OnAfterRender);
1572
-
1573
- if (this.post_render_callbacks) {
1574
- for (const i in this.post_render_callbacks) {
1575
- this.post_render_callbacks[i]();
1576
- }
1577
- }
1578
- }
1579
-
1580
- this._currentFrameEvent = -1;
1581
-
1582
- this.connection.sendBufferedMessagesNow();
1583
-
1584
- if (this._stats) {
1585
- this._stats.end();
1586
- if (this.time.frameCount % 150 === 0)
1587
- console.log(this.renderer.info.render.calls + " DrawCalls", "\nRender:", { ...this.renderer.info.render }, "\nMemory:", { ...this.renderer.info.memory }, "\nTarget Framerate: " + this.targetFrameRate);
1588
- }
1589
-
1590
- if (this._dispatchReadyAfterFrame) {
1591
- this._dispatchReadyAfterFrame = false;
1592
- this.domElement.dispatchEvent(new CustomEvent("ready"));
1593
- ContextRegistry.dispatchCallback(ContextEvent.ContextFirstFrameRendered, this);
1594
- }
1595
- }
1596
-
1597
- private readonly _tempClearColor = new Color();
1598
- private readonly _tempClearColor2 = new Color();
1599
- renderNow(camera?: Camera) {
1600
- if (!camera) {
1601
- camera = this.mainCamera as Camera;
1602
- if (!camera) return false;
1603
- }
1604
- this.handleRendererContextLost();
1605
-
1606
- this._isRendering = true;
1607
- this.renderRequiredTextures();
1608
-
1609
- if (this.renderer.toneMapping !== NoToneMapping)
1610
- patchTonemapping(this);
1611
-
1612
- if (this.composer && !this.isInXR) {
1613
- // if a camera is passed in we need to check if we need to update the composer's camera
1614
- if (camera && "setMainCamera" in this.composer) {
1615
- const currentPassesCamera = this.composer.passes[0]?.mainCamera;
1616
- if (currentPassesCamera != camera)
1617
- this.composer.setMainCamera(camera);
1618
- }
1619
-
1620
- const backgroundColor = this.renderer.getClearColor(this._tempClearColor);
1621
- const clearAlpha = this.renderer.getClearAlpha();
1622
- this._tempClearColor2.copy(backgroundColor);
1623
- this.renderer.setClearColor(backgroundColor.convertSRGBToLinear(), this.renderer.getClearAlpha());
1624
- this.composer.render(this.time.deltaTime);
1625
- this.renderer.setClearColor(this._tempClearColor2, clearAlpha); // restore clear color
1626
- }
1627
- else if (camera) {
1628
- // Workaround for issue on Vision Pro –
1629
- // depth buffer is not cleared between eye draws, despite the spec...
1630
- if (this.isInXR && DeviceUtilities.isMacOS())
1631
- this.renderer.clearDepth();
1632
- this.renderer.render(this.scene, camera);
1633
- }
1634
- this._isRendering = false;
1635
- return true;
1636
- }
1637
-
1638
- private _contextRestoreTries = 0;
1639
- private handleRendererContextLost() {
1640
- // Try to restore the context every x frames
1641
- if (this.time.frame % 10 && this.renderer.getContext().isContextLost()) {
1642
- if (this._contextRestoreTries++ < 100) {
1643
- console.warn("Attempting to recover WebGL context...");
1644
- this.renderer.forceContextRestore();
1645
- }
1646
- }
1647
- }
1648
-
1649
- /** returns true if we should return out of the frame loop */
1650
- private _wasPaused: boolean = false;
1651
- private onHandlePaused(): boolean {
1652
- const paused = this.evaluatePaused();
1653
- if (this._wasPaused !== paused) {
1654
- if (debugActive) console.log("Paused?", paused, "context:" + this.alias);
1655
- for (let i = 0; i < this.scripts_pausedChanged.length; i++) {
1656
- const script = this.scripts_pausedChanged[i];
1657
- if (!script.activeAndEnabled) continue;
1658
- if (script.onPausedChanged !== undefined) {
1659
- Context.Current = this;
1660
- script.onPausedChanged(paused, this._wasPaused);
1661
- }
1662
- }
1663
- }
1664
- this._wasPaused = paused;
1665
- return paused;
1666
- }
1667
-
1668
- private evaluatePaused(): boolean {
1669
- if (this.isInXR) return false;
1670
- if (this.isPaused) return true;
1671
- // if the element is not visible use the runInBackground flag to determine if we should continue
1672
- if (this.runInBackground) {
1673
- return false;
1674
- }
1675
- const paused = !this.isVisibleToUser;
1676
- return paused;
1677
- }
1678
-
1679
- private renderRequiredTextures() {
1680
- if (!this.mainCamera) return;
1681
- if (!this._requireDepthTexture && !this._requireColorTexture) return;
1682
- if (!this._renderTarget) {
1683
- this._renderTarget = new WebGLRenderTarget(this.domWidth, this.domHeight);
1684
- if (this._requireDepthTexture) {
1685
- const dt = new DepthTexture(this.domWidth, this.domHeight);;
1686
- this._renderTarget.depthTexture = dt;
1687
- }
1688
- if (this._requireColorTexture) {
1689
- this._renderTarget.texture = new Texture();
1690
- this._renderTarget.texture.generateMipmaps = false;
1691
- this._renderTarget.texture.minFilter = NearestFilter;
1692
- this._renderTarget.texture.magFilter = NearestFilter;
1693
- this._renderTarget.texture.format = RGBAFormat;
1694
- }
1695
- }
1696
- const rt = this._renderTarget;
1697
- if (rt.texture) {
1698
- rt.texture.colorSpace = this.renderer.outputColorSpace;
1699
- }
1700
- const prevTarget = this.renderer.getRenderTarget();
1701
- this.renderer.setRenderTarget(rt);
1702
- this.renderer.render(this.scene, this.mainCamera);
1703
- this.renderer.setRenderTarget(prevTarget);
1704
- }
1705
-
1706
- private executeCoroutines(evt: FrameEvent) {
1707
- if (this.coroutines[evt]) {
1708
- const evts = this.coroutines[evt];
1709
- for (let i = 0; i < evts.length; i++) {
1710
- try {
1711
- const evt = evts[i];
1712
- // TODO we might want to keep coroutines playing even if the component is disabled or inactive
1713
- const remove = !evt.comp || evt.comp.destroyed || !evt.main || evt.comp["enabled"] === false;
1714
- if (remove) {
1715
- if (debugCoroutine) console.log("Removing coroutine", evt.comp, evt.comp["enabled"])
1716
- evts.splice(i, 1);
1717
- --i;
1718
- continue;
1719
- }
1720
- const iter = evt.chained;
1721
- if (iter && iter.length > 0) {
1722
- const last: Generator = iter[iter.length - 1];
1723
- const res = last.next();
1724
- if (res.done) {
1725
- iter.pop();
1726
- }
1727
- if (isGenerator(res)) {
1728
- if (!evt.chained) evt.chained = [];
1729
- evt.chained.push(res.value);
1730
- }
1731
- if (!res.done) continue;
1732
- }
1733
-
1734
- const res = evt.main.next();
1735
- if (res.done === true) {
1736
- evts.splice(i, 1);
1737
- --i;
1738
- continue;
1739
- }
1740
- const val = res.value;
1741
- if (isGenerator(val)) {
1742
- // invoke once if its a generator
1743
- // this means e.g. WaitForFrame(1) works and will capture
1744
- // the frame it was created
1745
- const gen = val as Generator;
1746
- const res = gen.next();
1747
- if (res.done) continue;
1748
- if (!evt.chained) evt.chained = [];
1749
- evt.chained.push(val as Generator);
1750
- }
1751
- else if (val instanceof Promise) {
1752
- // If its a promise we want to wait for it to resolve
1753
- const prom = val as Promise<any>;
1754
- if (!evt.chained) evt.chained = [];
1755
- const nested = WaitForPromise(prom);
1756
- evt.chained?.push(nested);
1757
- continue;
1758
- }
1759
- }
1760
- catch (e) {
1761
- console.error(e);
1762
- }
1763
- }
1764
- }
1765
-
1766
- function isGenerator(val: any): boolean {
1767
- if (val) {
1768
- if (val.next && val.return) {
1769
- return true;
1770
- }
1771
- }
1772
- return false;
1773
- }
1774
- }
1775
-
1776
- }
1777
-
1778
-
1779
- // const scene = new Scene();
1780
- // const useComposer = utils.getParam("postfx");
1781
- // const renderer = new WebGLRenderer({ antialias: true });
1782
- // const composer = useComposer ? new EffectComposer(renderer) : undefined;
1783
-
1784
- // renderer.setClearColor(new Color('lightgrey'), 0)
1785
- // renderer.antialias = true;
1786
- // renderer.alpha = false;
1787
- // renderer.shadowMap.enabled = true;
1788
- // renderer.shadowMap.type = PCFSoftShadowMap;
1789
- // renderer.setSize(window.innerWidth, window.innerHeight);
1790
- // renderer.outputEncoding = sRGBEncoding;
1791
- // renderer.physicallyCorrectLights = true;
1792
- // document.body.appendChild(renderer.domElement);
1793
-
1794
- // // generation pushes loading requests in this array
1795
- // const sceneData: {
1796
- // mainCamera: Camera | undefined
1797
- // } = {
1798
- // preparing: [],
1799
- // resolving: [],
1800
- // scripts: [],
1801
- // raycastTargets: [],
1802
- // mainCamera: undefined,
1803
- // mainCameraComponent: undefined,
1804
- // };
1805
-
1806
- // // contains a list of functions to be called after loading is done
1807
- // const post_setup_callbacks = [];
1808
-
1809
- // const pre_render_Callbacks = [];
1810
- // const post_render_callbacks = [];
1811
-
1812
- // const new_scripts = [];
1813
- // const new_scripts_post_setup_callbacks = [];
1814
- // const new_scripts_pre_setup_callbacks = [];
1815
-
1816
- // export {
1817
- // scene, renderer, composer,
1818
- // new_scripts,
1819
- // new_scripts_post_setup_callbacks, new_scripts_pre_setup_callbacks,
1820
- // sceneData,
1821
- // post_setup_callbacks,
1822
- // pre_render_Callbacks,
1823
- // post_render_callbacks
1824
- // }
1
+ import 'three/examples/jsm/renderers/webgl-legacy/nodes/WebGLNodes.js';
2
+
3
+ import type { EffectComposer } from "postprocessing";
4
+ import {
5
+ BufferGeometry, Camera, Color, DepthTexture, Group,
6
+ Material, NearestFilter, NoToneMapping, Object3D, OrthographicCamera, PCFSoftShadowMap,
7
+ PerspectiveCamera, RGBAFormat, Scene, SRGBColorSpace,
8
+ Texture, WebGLRenderer, type WebGLRendererParameters, WebGLRenderTarget, type WebXRArrayCamera
9
+ } from 'three';
10
+ /** @ts-ignore (not yet in types?) */
11
+ import { BasicNodeLibrary } from "three";
12
+ import * as Stats from 'three/examples/jsm/libs/stats.module.js';
13
+ import type { EffectComposer as ThreeEffectComposer } from "three/examples/jsm/postprocessing/EffectComposer.js";
14
+ import { nodeFrame } from "three/examples/jsm/renderers/webgl-legacy/nodes/WebGLNodeBuilder.js";
15
+
16
+ import { isDevEnvironment, LogType, showBalloonError, showBalloonMessage } from './debug/index.js';
17
+ import { Addressables } from './engine_addressables.js';
18
+ import { AnimationsRegistry } from './engine_animation.js';
19
+ import { Application } from './engine_application.js';
20
+ import { AssetDatabase } from './engine_assetdatabase.js';
21
+ import { VERSION } from './engine_constants.js';
22
+ import { ContextEvent, ContextRegistry } from './engine_context_registry.js';
23
+ import { WaitForPromise } from './engine_coroutine.js';
24
+ import { ObjectUtils } from "./engine_create_objects.js";
25
+ import { destroy, foreachComponent } from './engine_gameobject.js';
26
+ import { getLoader } from './engine_gltf.js';
27
+ import { Input } from './engine_input.js';
28
+ import { invokeLifecycleFunctions } from './engine_lifecycle_functions_internal.js';
29
+ import { type ILightDataRegistry, LightDataRegistry } from './engine_lightdata.js';
30
+ import { LODsManager } from "./engine_lods.js";
31
+ import * as looputils from './engine_mainloop_utils.js';
32
+ import { NetworkConnection } from './engine_networking.js';
33
+ import { Physics } from './engine_physics.js';
34
+ import { PlayerViewManager } from './engine_playerview.js';
35
+ import { RendererData as SceneLighting } from './engine_scenelighting.js';
36
+ import { getTempColor, logHierarchy } from './engine_three_utils.js';
37
+ import { Time } from './engine_time.js';
38
+ import { patchTonemapping } from './engine_tonemapping.js';
39
+ import type { CoroutineData, ICamera, IComponent, IContext, ILight, LoadedModel, Model, Vec2 } from "./engine_types.js";
40
+ import { deepClone, delay, DeviceUtilities, getParam } from './engine_utils.js';
41
+ import type { INeedleXRSessionEventReceiver, NeedleXRSession } from './engine_xr.js';
42
+ import { NeedleMenu } from './webcomponents/needle menu/needle-menu.js';
43
+ import type { NeedleEngineWebComponent } from './webcomponents/needle-engine.js';
44
+
45
+ const debug = getParam("debugcontext");
46
+ const stats = getParam("stats");
47
+ const debugActive = getParam("debugactive");
48
+ const debugframerate = getParam("debugframerate");
49
+ const debugCoroutine = getParam("debugcoroutine");
50
+
51
+ // this is where functions that setup unity scenes will be pushed into
52
+ // those will be accessed from our custom html element to load them into their context
53
+ export const build_scene_functions: { [name: string]: (context: Context) => Promise<void> } = {};
54
+
55
+
56
+ export declare class LoadingProgressArgs {
57
+ /** the name or URL of the loaded file */
58
+ name: string;
59
+ /** the loading progress event from the loader */
60
+ progress: ProgressEvent;
61
+ /** the index of the loaded file */
62
+ index: number;
63
+ /** the total number of files to load */
64
+ count: number;
65
+ }
66
+ export declare class ContextCreateArgs {
67
+ /** list of glTF or GLB files to load */
68
+ files: Array<string>;
69
+ abortSignal?: AbortSignal;
70
+ /** called when loading a provided glTF file started */
71
+ onLoadingStart?: (index: number, file: string) => void;
72
+ /** called on update for each loaded glTF file */
73
+ onLoadingProgress?: (args: LoadingProgressArgs) => void;
74
+ /** Called after a gLTF file has finished loading */
75
+ onLoadingFinished?: (index: number, file: string, glTF: Model | null) => void;
76
+ }
77
+
78
+ export class ContextArgs {
79
+ name?: string;
80
+ /** for debugging only */
81
+ alias?: string;
82
+ /** the hash is used as a seed when initially loading the scene files */
83
+ hash?: string;
84
+
85
+ /** when true the context will not check if it's visible in the viewport and always update and render */
86
+ runInBackground?: boolean;
87
+ /** the DOM element the context belongs to or is inside of (this does not have to be the canvas. use renderer.domElement if you want to access the dom canvas) */
88
+ domElement?: HTMLElement | null;
89
+ /** externally owned renderer */
90
+ renderer?: WebGLRenderer;
91
+ /** externally owned camera */
92
+ camera?: Camera;
93
+ /** externally owned scene */
94
+ scene?: Scene;
95
+ }
96
+
97
+ export enum FrameEvent {
98
+ Start = -1,
99
+ EarlyUpdate = 0,
100
+ Update = 1,
101
+ LateUpdate = 2,
102
+ OnBeforeRender = 3,
103
+ OnAfterRender = 4,
104
+ PrePhysicsStep = 9,
105
+ PostPhysicsStep = 10,
106
+ Undefined = -1,
107
+ }
108
+
109
+ /** threejs callback event signature */
110
+ export declare type OnRenderCallback = (renderer: WebGLRenderer, scene: Scene, camera: Camera, geometry: BufferGeometry, material: Material, group: Group) => void
111
+
112
+
113
+ export function registerComponent(script: IComponent, context?: Context) {
114
+ if (!script) return;
115
+ if (!script.isComponent) {
116
+ if (isDevEnvironment() || debug)
117
+ console.error("Registered script is not a Needle Engine component. \nThe script will be ignored. Please make sure your component extends \"Behaviour\" imported from \"@needle-tools/engine\"\n", script);
118
+ return;
119
+ }
120
+ if (!context) {
121
+ context = Context.Current;
122
+ if (debug) console.warn("> Registering component without context");
123
+ }
124
+ const new_scripts = context?.new_scripts;
125
+ if (!new_scripts.includes(script)) {
126
+ new_scripts.push(script);
127
+ }
128
+ }
129
+
130
+ /**
131
+ * The context is the main object that holds all the data and state of the Needle Engine.
132
+ * It can be used to access the scene, renderer, camera, input, physics, networking, and more.
133
+ * @example
134
+ * ```typescript
135
+ * import { Behaviour } from "@needle-tools/engine";
136
+ * import { Mesh, BoxGeometry, MeshBasicMaterial } from "three";
137
+ * export class MyScript extends Behaviour {
138
+ * start() {
139
+ * console.log("Hello from MyScript");
140
+ * this.context.scene.add(new Mesh(new BoxGeometry(), new MeshBasicMaterial()));
141
+ * }
142
+ * }
143
+ * ```
144
+ */
145
+ export class Context implements IContext {
146
+
147
+ private static _defaultTargetFramerate: { value?: number, toString?() } = { value: 90, toString() { return this.value; } }
148
+ /** When a new context is created this is the framerate that will be used by default */
149
+ static get DefaultTargetFrameRate(): number | undefined {
150
+ return Context._defaultTargetFramerate.value;
151
+ }
152
+ /** When a new context is created this is the framerate that will be used by default */
153
+ static set DefaultTargetFrameRate(val: number | undefined) {
154
+ Context._defaultTargetFramerate.value = val;
155
+ }
156
+
157
+ private static _defaultWebglRendererParameters: WebGLRendererParameters = {
158
+ antialias: true,
159
+ alpha: false,
160
+ // Note: this is due to a bug on OSX devices. See NE-5370
161
+ powerPreference: (DeviceUtilities.isiOS() || DeviceUtilities.isMacOS()) ? "default" : "high-performance",
162
+ stencil: true,
163
+ // logarithmicDepthBuffer: true,
164
+ // reverseDepthBuffer: true, // https://github.com/mrdoob/three.js/issues/29770
165
+ };
166
+ /** The default parameters that will be used when creating a new WebGLRenderer.
167
+ * Modify in global context to change the default parameters for all new contexts.
168
+ * @example
169
+ * ```typescript
170
+ * import { Context } from "@needle-tools/engine";
171
+ * Context.DefaultWebGLRendererParameters.antialias = false;
172
+ * ```
173
+ */
174
+ static get DefaultWebGLRendererParameters(): WebGLRendererParameters {
175
+ return Context._defaultWebglRendererParameters;
176
+ }
177
+
178
+ /** The needle engine version */
179
+ get version() {
180
+ return VERSION;
181
+ }
182
+
183
+ /** The currently active context. Only set during the update loops */
184
+ static get Current(): Context {
185
+ return ContextRegistry.Current as Context;
186
+ }
187
+
188
+ /** @internal this property should not be set by user code */
189
+ static set Current(context: Context) {
190
+ ContextRegistry.Current = context;
191
+ }
192
+
193
+ static get All(): Context[] {
194
+ return ContextRegistry.All as Context[];
195
+ }
196
+
197
+ /** The name of the context */
198
+ name: string;
199
+ /** An alias for the context */
200
+ alias: string | undefined | null;
201
+ /** When the renderer or camera are managed by an external process (e.g. when running in r3f context).
202
+ * When this is false you are responsible to call update(timestamp, xframe.
203
+ * It is also currently assumed that rendering is handled performed by an external process
204
+ * */
205
+ isManagedExternally: boolean = false;
206
+ /** set to true to pause the update loop. You can receive an event for it in your components.
207
+ * Note that script updates will not be called when paused */
208
+ isPaused: boolean = false;
209
+ /** When enabled the application will run while not visible on the page */
210
+ runInBackground: boolean = false;
211
+ /**
212
+ * Set to the target framerate you want your application to run in (you can use ?stats to check the fps)
213
+ * Set to undefined if you want to run at the maximum framerate
214
+ */
215
+ targetFrameRate?: number | { value?: number };
216
+
217
+ /** Use a higher number for more accurate physics simulation.
218
+ * When undefined physics steps will be 1 for mobile devices and 5 for desktop devices
219
+ * Set to 0 to disable physics updates
220
+ * TODO: changing physics steps is currently not supported because then forces that we get from the character controller and rigidbody et al are not correct anymore - this needs to be properly tested before making this configureable
221
+ */
222
+ private physicsSteps?: number = 1;
223
+
224
+ /** used to append to loaded assets */
225
+ hash?: string;
226
+
227
+ /** The `<needle-engine>` web component */
228
+ domElement: NeedleEngineWebComponent | HTMLElement;
229
+
230
+ appendHTMLElement(element: HTMLElement) {
231
+ if (this.domElement.shadowRoot)
232
+ return this.domElement.shadowRoot.appendChild(element);
233
+ else return this.domElement.appendChild(element);
234
+ }
235
+
236
+ get resolutionScaleFactor() { return this._resolutionScaleFactor; }
237
+ /** use to scale the resolution up or down of the renderer. default is 1 */
238
+ set resolutionScaleFactor(val: number) {
239
+ if (val === this._resolutionScaleFactor) return;
240
+ if (typeof val !== "number") return;
241
+ if (val <= 0) {
242
+ console.error("Invalid resolution scale factor", val);
243
+ return;
244
+ }
245
+ this._resolutionScaleFactor = val;
246
+ this.updateSize();
247
+ }
248
+ private _resolutionScaleFactor: number = 1;
249
+
250
+ // domElement.clientLeft etc doesnt return absolute position
251
+ private _boundingClientRectFrame: number = -1;
252
+ private _boundingClientRect: DOMRect | null = null;
253
+ private _domX; private _domY;
254
+ /** update bounding rects + domX, domY */
255
+ private calculateBoundingClientRect() {
256
+ // workaround for mozilla webXR viewer
257
+ if (this.xr) {
258
+ this._domX = 0;
259
+ this._domY = 0;
260
+ return;
261
+ }
262
+ // TODO: cache this
263
+ if (this._boundingClientRectFrame === this.time.frame) return;
264
+ this._boundingClientRectFrame = this.time.frame;
265
+ this._boundingClientRect = this.domElement.getBoundingClientRect();
266
+ this._domX = this._boundingClientRect.x;
267
+ this._domY = this._boundingClientRect.y;
268
+ }
269
+
270
+ /** The width of the `<needle-engine>` element on the website */
271
+ get domWidth(): number {
272
+ // for mozilla XR
273
+ if (this.isInAR) return window.innerWidth;
274
+ return this.domElement.clientWidth;
275
+ }
276
+ /** The height of the `<needle-engine>` element on the website */
277
+ get domHeight(): number {
278
+ // for mozilla XR
279
+ if (this.isInAR) return window.innerHeight;
280
+ return this.domElement.clientHeight;
281
+ }
282
+ /** the X position of the `<needle-engine>` element on the website */
283
+ get domX(): number {
284
+ this.calculateBoundingClientRect();
285
+ return this._domX;
286
+ }
287
+ /** the Y position of the `<needle-engine>` element on the website */
288
+ get domY(): number {
289
+ this.calculateBoundingClientRect();
290
+ return this._domY;
291
+ }
292
+ /**
293
+ * Is a XR session currently active and presenting?
294
+ * @returns true if the xr renderer is currently presenting
295
+ */
296
+ get isInXR() { return this.renderer?.xr?.isPresenting || false; }
297
+ /** shorthand for `NeedleXRSession.active`
298
+ * Automatically set by NeedleXRSession when a XR session is active
299
+ * @returns the active XR session or null if no session is active
300
+ * */
301
+ xr: NeedleXRSession | null = null;
302
+ /**
303
+ * Shorthand for `this.xr?.mode`. AR or VR
304
+ * @returns the current XR session mode (immersive-vr or immersive-ar)
305
+ */
306
+ get xrSessionMode() { return this.xr?.mode; }
307
+ /** Shorthand for `this.xrSessionMode === "immersive-vr"`
308
+ * @returns true if a webxr VR session is currently active.
309
+ */
310
+ get isInVR() { return this.xrSessionMode === "immersive-vr"; }
311
+ /**
312
+ * Shorthand for `this.xrSessionMode === "immersive-ar"`
313
+ * @returns true if a webxr AR session is currently active.
314
+ */
315
+ get isInAR() { return this.xrSessionMode === "immersive-ar"; }
316
+ /** If a XR session is active and in pass through mode (immersive-ar on e.g. Quest)
317
+ * @returns true if the XR session is in pass through mode
318
+ */
319
+ get isInPassThrough() { return this.xr ? this.xr.isPassThrough : false; }
320
+ /** access the raw `XRSession` object (shorthand for `context.renderer.xr.getSession()`). For more control use `NeedleXRSession.active` */
321
+ get xrSession() { return this.renderer?.xr?.getSession(); }
322
+ /** @returns the latest XRFrame (if a XRSession is currently active)
323
+ * @link https://developer.mozilla.org/en-US/docs/Web/API/XRFrame
324
+ */
325
+ get xrFrame() { return this._xrFrame }
326
+ /** @returns the current WebXR camera while the WebXRManager is active (shorthand for `context.renderer.xr.getCamera()`) */
327
+ get xrCamera(): WebXRArrayCamera | undefined { return this.renderer.xr.isPresenting ? this.renderer?.xr?.getCamera() : undefined }
328
+ private _xrFrame: XRFrame | null = null;
329
+ /**
330
+ * The AR overlay element is used to display 2D HTML elements while a AR session is active.
331
+ */
332
+ get arOverlayElement(): HTMLElement {
333
+ const el = this.domElement as any;
334
+ if (typeof el.getAROverlayContainer === "function")
335
+ return el.getAROverlayContainer();
336
+ return this.domElement;
337
+ }
338
+ /**
339
+ * Current event of the update cycle (e.g. `FrameEvent.EarlyUpdate` or `FrameEvent.OnBeforeRender`)
340
+ */
341
+ get currentFrameEvent(): FrameEvent {
342
+ return this._currentFrameEvent;
343
+ }
344
+ private _currentFrameEvent: FrameEvent = FrameEvent.Undefined;
345
+
346
+ /**
347
+ * The scene contains all objects in the hierarchy and is automatically rendered by the context every frane.
348
+ */
349
+ scene: Scene;
350
+ /**
351
+ * The renderer is used to render the scene. It is automatically created when the context is created.
352
+ */
353
+ renderer!: WebGLRenderer;
354
+ /**
355
+ * The effect composer can be used to render postprocessing effects. If assigned then it will automatically render the scene every frame.
356
+ */
357
+ composer: EffectComposer | ThreeEffectComposer | null = null;
358
+
359
+ /**
360
+ * @internal All known components. Don't use directly
361
+ */
362
+ readonly scripts: IComponent[] = [];
363
+ /**
364
+ * @internal All paused components. Don't use directly
365
+ */
366
+ readonly scripts_pausedChanged: IComponent[] = [];
367
+ /**
368
+ * @internal All components that have a early update event. Don't use directly
369
+ */
370
+ readonly scripts_earlyUpdate: IComponent[] = [];
371
+ /**
372
+ * @internal All components that have a update event. Don't use directly
373
+ */
374
+ readonly scripts_update: IComponent[] = [];
375
+ /**
376
+ * @internal All components that have a late update event. Don't use directly
377
+ */
378
+ readonly scripts_lateUpdate: IComponent[] = [];
379
+ /**
380
+ * @internal All components that have a onBeforeRender event. Don't use directly
381
+ */
382
+ readonly scripts_onBeforeRender: IComponent[] = [];
383
+ /**
384
+ * @internal All components that have a onAfterRender event. Don't use directly
385
+ */
386
+ readonly scripts_onAfterRender: IComponent[] = [];
387
+ /**
388
+ * @internal All components that have coroutines. Don't use directly
389
+ */
390
+ readonly scripts_WithCorroutines: IComponent[] = [];
391
+ /**
392
+ * @internal Components with immersive-vr event methods. Don't use directly
393
+ */
394
+ readonly scripts_immersive_vr: INeedleXRSessionEventReceiver[] = [];
395
+ /**
396
+ * @internal Components with immersive-ar event methods. Don't use directly
397
+ */
398
+ readonly scripts_immersive_ar: INeedleXRSessionEventReceiver[] = [];
399
+ /**
400
+ * @internal Coroutine data
401
+ */
402
+ readonly coroutines: { [FrameEvent: number]: Array<CoroutineData> } = {}
403
+
404
+ /** callbacks called once after the context has been created */
405
+ readonly post_setup_callbacks: Function[] = [];
406
+ /** called every frame at the beginning of the frame (after component start events and before earlyUpdate) */
407
+ readonly pre_update_callbacks: Function[] = [];
408
+ /** called every frame before rendering (after all component events) */
409
+ readonly pre_render_callbacks: Array<(frame: XRFrame | null) => void> = [];
410
+ /** called every frame after rendering (after all component events) */
411
+ readonly post_render_callbacks: Function[] = [];
412
+ /** called every frame befroe update (this list is emptied every frame) */
413
+ readonly pre_update_oneshot_callbacks: Function[] = [];
414
+
415
+ /** @internal */
416
+ readonly new_scripts: IComponent[] = [];
417
+ /** @internal */
418
+ readonly new_script_start: IComponent[] = [];
419
+ /** @internal */
420
+ readonly new_scripts_pre_setup_callbacks: Function[] = [];
421
+ /** @internal */
422
+ readonly new_scripts_post_setup_callbacks: Function[] = [];
423
+ /** @internal */
424
+ readonly new_scripts_xr: INeedleXRSessionEventReceiver[] = [];
425
+
426
+ /**
427
+ * The **main camera component** of the scene - this camera is used for rendering.
428
+ * Use `setCurrentCamera` for updating the main camera.
429
+ */
430
+ mainCameraComponent: ICamera | undefined = undefined;
431
+
432
+ /**
433
+ * The main camera of the scene - this camera is used for rendering
434
+ * Use `setCurrentCamera` for updating the main camera.
435
+ */
436
+ get mainCamera(): Camera {
437
+ if (this._mainCamera) {
438
+ return this._mainCamera;
439
+ }
440
+ if (this.mainCameraComponent) {
441
+ const cam = this.mainCameraComponent as ICamera;
442
+ if (!cam.threeCamera)
443
+ cam.buildCamera();
444
+ return cam.threeCamera;
445
+ }
446
+ if (!this._fallbackCamera) {
447
+ this._fallbackCamera = new PerspectiveCamera(75, this.domWidth / this.domHeight, 0.1, 1000);
448
+ }
449
+ return this._fallbackCamera;
450
+ }
451
+ /** Set the main camera of the scene. If set to null the camera of the {@link mainCameraComponent} will be used - this camera is used for rendering */
452
+ set mainCamera(cam: Camera | null) {
453
+ this._mainCamera = cam;
454
+ }
455
+ private _mainCamera: Camera | null = null;
456
+ private _fallbackCamera: PerspectiveCamera | null = null;
457
+
458
+ /** access application state (e.g. if all audio should be muted) */
459
+ application: Application;
460
+ /** access animation mixer used by components in the scene */
461
+ animations: AnimationsRegistry;
462
+ /** access timings (current frame number, deltaTime, timeScale, ...) */
463
+ time: Time;
464
+ /** access input data (e.g. click or touch events) */
465
+ input: Input;
466
+ /** access physics related methods (e.g. raycasting). To access the phyiscs engine use `context.physics.engine` */
467
+ physics: Physics;
468
+ /** access networking methods (use it to send or listen to messages or join a networking backend) */
469
+ connection: NetworkConnection;
470
+ /**
471
+ * @deprecated AssetDataBase is deprecated
472
+ */
473
+ assets: AssetDatabase;
474
+ /** The main light in the scene */
475
+ mainLight: ILight | null = null;
476
+ /** @deprecated Use sceneLighting */
477
+ get rendererData() { return this.sceneLighting }
478
+ sceneLighting: SceneLighting;
479
+ addressables: Addressables;
480
+ lightmaps: ILightDataRegistry;
481
+ players: PlayerViewManager;
482
+ readonly lodsManager: LODsManager;
483
+ /** Access the needle menu to add or remove buttons to the menu element */
484
+ readonly menu: NeedleMenu;
485
+
486
+ /** @returns true if the context is fully created and ready */
487
+ get isCreated() { return this._isCreated; }
488
+
489
+ private _needsUpdateSize: boolean = false;
490
+ private _isCreated: boolean = false;
491
+ private _isCreating: boolean = false;
492
+ private _isVisible: boolean = false;
493
+
494
+ private _stats = stats ? new Stats.default() : null;
495
+
496
+ constructor(args?: ContextArgs) {
497
+ this.name = args?.name || "";
498
+ this.alias = args?.alias;
499
+ this.domElement = args?.domElement || document.body;
500
+ this.hash = args?.hash;
501
+
502
+ if (args?.renderer) {
503
+ this.renderer = args.renderer;
504
+ this.isManagedExternally = true;
505
+ }
506
+ if (args?.runInBackground !== undefined) this.runInBackground = args.runInBackground;
507
+ if (args?.scene) this.scene = args.scene;
508
+ else this.scene = new Scene();
509
+ if (args?.camera) this._mainCamera = args.camera;
510
+
511
+ this.application = new Application(this);
512
+ this.time = new Time();
513
+ this.input = new Input(this);
514
+ this.physics = new Physics(this);
515
+ this.connection = new NetworkConnection(this);
516
+ // eslint-disable-next-line deprecation/deprecation
517
+ this.assets = new AssetDatabase();
518
+ this.sceneLighting = new SceneLighting(this);
519
+ this.addressables = new Addressables(this);
520
+ this.lightmaps = new LightDataRegistry(this);
521
+ this.players = new PlayerViewManager(this);
522
+ this.menu = new NeedleMenu(this);
523
+ this.lodsManager = new LODsManager(this);
524
+ this.animations = new AnimationsRegistry(this);
525
+
526
+
527
+ const resizeCallback = () => this._needsUpdateSize = true;
528
+ window.addEventListener('resize', resizeCallback);
529
+ this._disposeCallbacks.push(() => window.removeEventListener('resize', resizeCallback));
530
+
531
+ const resizeObserver = new ResizeObserver(_ => this._needsUpdateSize = true);
532
+ resizeObserver.observe(this.domElement);
533
+ this._disposeCallbacks.push(() => resizeObserver.disconnect());
534
+
535
+ this._intersectionObserver = new IntersectionObserver(entries => {
536
+ this._isVisible = entries[0].isIntersecting;
537
+ });
538
+ this._disposeCallbacks.push(() => this._intersectionObserver?.disconnect());
539
+
540
+ ContextRegistry.register(this);
541
+ }
542
+
543
+ /**
544
+ * Calling this function will dispose the current renderer and create a new one which will then be assigned to the context. It can be used to create a new renderer with custom WebGLRendererParameters.
545
+ * **Note**: Instead you can also modify the static `Context.DefaultWebGlRendererParameters` before the context is created.
546
+ * **Note**: This method is recommended because it re-uses an potentially already existing canvas element. This is necessary to keep input event handlers from working (e.g. components like OrbitControls subscribe to input events on the canvas)
547
+ * @returns {WebGLRenderer} the newly created renderer
548
+ */
549
+ createNewRenderer(params?: WebGLRendererParameters) {
550
+ this.renderer?.dispose();
551
+
552
+ params = { ...Context.DefaultWebGLRendererParameters, ...params };
553
+ if (!params.canvas) {
554
+ // get canvas already configured in the Needle Engine Web Component
555
+ const canvas = this.domElement?.shadowRoot?.querySelector("canvas");
556
+ if (canvas) {
557
+ params.canvas = canvas;
558
+ if (debug) {
559
+ console.log("Using canvas from shadow root", canvas);
560
+ }
561
+ }
562
+ }
563
+ if (debug) console.log("Using Renderer Parameters:", params, this.domElement)
564
+
565
+ this.renderer = new WebGLRenderer(params);
566
+
567
+ this.renderer.debug.checkShaderErrors = isDevEnvironment() || getParam("checkshadererrors") === true;
568
+
569
+ // some tonemapping other than "NONE" is required for adjusting exposure with EXR environments
570
+ this.renderer.toneMappingExposure = 1; // range [0...inf] instead of the usual -15..15
571
+ this.renderer.toneMapping = NoToneMapping; // could also set to LinearToneMapping, ACESFilmicToneMapping
572
+
573
+ this.renderer.setClearColor(new Color('lightgrey'), 0);
574
+ // // @ts-ignore
575
+ // this.renderer.alpha = false;
576
+ this.renderer.shadowMap.enabled = true;
577
+ this.renderer.shadowMap.type = PCFSoftShadowMap;
578
+ this.renderer.setSize(this.domWidth, this.domHeight);
579
+ this.renderer.outputColorSpace = SRGBColorSpace;
580
+
581
+ // Injecting the core nodes library here, like WebGPURenderer backends do
582
+ //@ts-ignore
583
+ this.renderer.nodes = {
584
+ library: new BasicNodeLibrary(),
585
+ modelViewMatrix: null,
586
+ modelNormalViewMatrix: null,
587
+ };
588
+ // this.renderer.toneMapping = AgXToneMapping;
589
+ this.lodsManager.setRenderer(this.renderer);
590
+
591
+ this.input.bindEvents();
592
+
593
+ return this.renderer;
594
+ }
595
+
596
+
597
+ private _intersectionObserver: IntersectionObserver | null = null;
598
+ private internalOnUpdateVisible() {
599
+ this._intersectionObserver?.disconnect();
600
+ this._intersectionObserver?.observe(this.domElement);
601
+ }
602
+
603
+ private _disposeCallbacks: Function[] = [];
604
+
605
+
606
+ /** will request a renderer size update the next render call (will call updateSize the next update) */
607
+ requestSizeUpdate() { this._needsUpdateSize = true; }
608
+
609
+ /** Clamps the renderer max resolution. If undefined the max resolution is not clamped. Default is undefined */
610
+ maxRenderResolution?: Vec2;
611
+
612
+ /** Control the renderer devicePixelRatio.
613
+ * **Options**
614
+ * - `auto` - Needle Engine automatically sets the pixel ratio to the current window.devicePixelRatio.
615
+ * - `manual` - Needle Engine will not change the renderer pixel ratio. You can set it manually.
616
+ * - `number` - Needle Engine will set the pixel ratio to the given number. The change will be applied to the renderer and the composer (if used) at the end of the current frame.
617
+ */
618
+ get devicePixelRatio() { return this._devicePixelRatio; }
619
+ set devicePixelRatio(val: "auto" | "manual" | number) {
620
+ if (val !== this._devicePixelRatio) {
621
+ this._devicePixelRatio = val;
622
+ this._needsUpdateSize = true;
623
+ }
624
+ }
625
+ private _devicePixelRatio: "auto" | "manual" | number = "auto";
626
+
627
+ /**
628
+ * Update the renderer and canvas size. This is also automatically called when a DOM size change is detected.
629
+ */
630
+ updateSize(force: boolean = false) {
631
+ if (force || (!this.isManagedExternally && this.renderer.xr?.isPresenting === false)) {
632
+ this._needsUpdateSize = false;
633
+ const scaleFactor = this.resolutionScaleFactor;
634
+ let width = this.domWidth * scaleFactor;
635
+ let height = this.domHeight * scaleFactor;
636
+ if (this.maxRenderResolution) {
637
+ this.maxRenderResolution.x = Math.max(1, this.maxRenderResolution.x);
638
+ width = Math.min(this.maxRenderResolution.x, width);
639
+ this.maxRenderResolution.y = Math.max(1, this.maxRenderResolution.y);
640
+ height = Math.min(this.maxRenderResolution.y, height);
641
+ }
642
+ const camera = this.mainCamera as PerspectiveCamera;
643
+ this.updateAspect(camera);
644
+ this.renderer.setSize(width, height, true);
645
+ // avoid setting pixel values here since this can cause pingpong updates
646
+ // e.g. when system scale is set to 125%
647
+ // https://github.com/needle-tools/needle-engine-support/issues/69
648
+ this.renderer.domElement.style.width = "100%";
649
+ this.renderer.domElement.style.height = "100%";
650
+
651
+ const devicePixelRatio = typeof this.devicePixelRatio === "number"
652
+ ? this.devicePixelRatio
653
+ : this.devicePixelRatio === "auto"
654
+ ? window.devicePixelRatio
655
+ : undefined;
656
+ if (devicePixelRatio !== undefined) {
657
+ this.renderer.setPixelRatio(devicePixelRatio);
658
+ }
659
+
660
+ if (this.composer) {
661
+ this.composer.setSize?.call(this.composer, width, height);
662
+ if (devicePixelRatio !== undefined && "setPixelRatio" in this.composer && typeof this.composer.setPixelRatio === "function")
663
+ this.composer.setPixelRatio?.call(this.composer, window.devicePixelRatio);
664
+ }
665
+ }
666
+ }
667
+
668
+ /**
669
+ * Update the camera aspect ratio or orthorgraphic camera size. This is automatically called when a DOM size change is detected.
670
+ */
671
+ updateAspect(camera: PerspectiveCamera | OrthographicCamera, width?: number, height?: number) {
672
+ if (!camera) return;
673
+ if (width === undefined)
674
+ width = this.domWidth;
675
+ if (height === undefined)
676
+ height = this.domHeight;
677
+ const aspectRatio = width / height;
678
+ if ((camera as PerspectiveCamera).isPerspectiveCamera) {
679
+ const cam = camera as PerspectiveCamera;
680
+ const pa = cam.aspect;
681
+ cam.aspect = aspectRatio;
682
+ if (pa !== cam.aspect)
683
+ camera.updateProjectionMatrix();
684
+ }
685
+ else if ((camera as OrthographicCamera).isOrthographicCamera) {
686
+ const cam = camera as OrthographicCamera;
687
+ // Maintain the camera's current vertical size (top - bottom)
688
+ const verticalSize = cam.top - cam.bottom;
689
+ // Calculate new horizontal size based on aspect ratio
690
+ const horizontalSize = verticalSize * aspectRatio;
691
+ // Update camera bounds while maintaining center position
692
+ const halfWidth = horizontalSize / 2;
693
+ const halfHeight = verticalSize / 2;
694
+ if (cam.left != -halfWidth || cam.top != halfHeight) {
695
+ cam.left = -halfWidth;
696
+ cam.right = halfWidth;
697
+ cam.top = halfHeight;
698
+ cam.bottom = -halfHeight;
699
+ camera.updateProjectionMatrix();
700
+ }
701
+ }
702
+ }
703
+
704
+ /** This will recreate the whole needle engine context and dispose the whole scene content
705
+ * All content will be reloaded (loading times might be faster due to browser caches)
706
+ * All scripts will be recreated */
707
+ recreate() {
708
+ this.clear();
709
+ this.create(this._originalCreationArgs);
710
+ }
711
+
712
+ private _originalCreationArgs?: ContextCreateArgs;
713
+
714
+ /** @deprecated use create. This method will be removed in a future version */
715
+ async onCreate(opts?: ContextCreateArgs) {
716
+ return this.create(opts);
717
+ }
718
+ /** @internal */
719
+ async create(opts?: ContextCreateArgs) {
720
+ try {
721
+ this._isCreating = true;
722
+ if (opts !== this._originalCreationArgs)
723
+ this._originalCreationArgs = deepClone(opts);
724
+ window.addEventListener("unhandledrejection", this.onUnhandledRejection)
725
+ const res = await this.internalOnCreate(opts);
726
+ this._isCreated = res;
727
+ return res;
728
+ }
729
+ finally {
730
+ window.removeEventListener("unhandledrejection", this.onUnhandledRejection)
731
+ this._isCreating = false;
732
+ }
733
+ }
734
+
735
+ private onUnhandledRejection = (event: PromiseRejectionEvent) => {
736
+ this.onError(event.reason);
737
+ };
738
+
739
+ /** Dispatches an error */
740
+ private onError(error: string) {
741
+ this.domElement.dispatchEvent(new CustomEvent("error", { detail: error }));
742
+ }
743
+
744
+ /**
745
+ * Clears the context and destroys all scenes and objects in the scene.
746
+ * The ContextCleared event is called at the end.
747
+ * This is automatically called when e.g. the `src` attribute changes on `<needle-engine>`
748
+ * or when the web component is removed from the DOM
749
+ */
750
+ clear() {
751
+ ContextRegistry.dispatchCallback(ContextEvent.ContextClearing, this);
752
+ invokeLifecycleFunctions(this, ContextEvent.ContextClearing);
753
+ // NOTE: this does dispose the environment/background image too
754
+ // which is probably not desired if it is set via the background-image attribute
755
+ destroy(this.scene, true, true);
756
+ this.scene = new Scene();
757
+ this.addressables?.dispose();
758
+ this.lightmaps?.clear();
759
+ this.physics?.engine?.clearCaches();
760
+ this.lodsManager.disable();
761
+
762
+ this._onBeforeRenderListeners.clear();
763
+ this._onAfterRenderListeners.clear();
764
+
765
+ if (!this.isManagedExternally) {
766
+ if (this.renderer) {
767
+ this.renderer.renderLists.dispose();
768
+ this.renderer.state.reset();
769
+ this.renderer.resetState();
770
+ }
771
+ }
772
+ // We do not want to clear the renderer here because when switching src we want to keep the last rendered frame in case the loading screen is not visible
773
+ // if a user wants to see the background they can still call setClearAlpha(0) and clear manually
774
+ ContextRegistry.dispatchCallback(ContextEvent.ContextCleared, this);
775
+ }
776
+
777
+ /**
778
+ * Dispose all allocated resources and clears the scene. This is automatically called e.g. when the `<needle-engine>` component is removed from the DOM.
779
+ */
780
+ dispose() {
781
+ this.internalOnDestroy();
782
+ }
783
+
784
+ /**@deprecated use dispose() */
785
+ onDestroy() { this.internalOnDestroy(); }
786
+
787
+ private internalOnDestroy() {
788
+ Context.Current = this;
789
+ ContextRegistry.dispatchCallback(ContextEvent.ContextDestroying, this);
790
+ invokeLifecycleFunctions(this, ContextEvent.ContextDestroying);
791
+ this.clear();
792
+ this.renderer?.setAnimationLoop(null);
793
+ if (this.renderer) {
794
+ this.renderer.setClearAlpha(0);
795
+ this.renderer.clear();
796
+ if (!this.isManagedExternally) {
797
+ if (debug) console.log("Disposing renderer");
798
+ this.renderer.dispose();
799
+ }
800
+ }
801
+ this.scene = null!;
802
+ this.renderer = null!;
803
+ this.input.dispose();
804
+ this.menu.onDestroy();
805
+ this.animations.onDestroy();
806
+ for (const cb of this._disposeCallbacks) {
807
+ try {
808
+ cb();
809
+ }
810
+ catch (e) {
811
+ console.error("Error in on dispose callback:", e, cb);
812
+ }
813
+ }
814
+ if (this.domElement?.parentElement) {
815
+ this.domElement.parentElement.removeChild(this.domElement);
816
+ }
817
+ this._isCreated = false;
818
+ ContextRegistry.dispatchCallback(ContextEvent.ContextDestroyed, this);
819
+ invokeLifecycleFunctions(this, ContextEvent.ContextDestroyed);
820
+ ContextRegistry.unregister(this);
821
+ if (Context.Current === this) {
822
+ //@ts-ignore
823
+ Context.Current = null;
824
+ }
825
+ }
826
+
827
+ /** @internal Automatically called by components when you call `startCoroutine`. Use `startCoroutine` instead */
828
+ registerCoroutineUpdate(script: IComponent, coroutine: Generator, evt: FrameEvent): Generator {
829
+ if (typeof coroutine?.next !== "function") {
830
+ console.error("Registered invalid coroutine function from " + script.name + "\nCoroutine functions must be generators: \"*myCoroutine() {...}\"\nStart a coroutine from a component by calling \"this.startCoroutine(myCoroutine())\"")
831
+ return coroutine;
832
+ }
833
+ if (!this.coroutines[evt]) this.coroutines[evt] = [];
834
+ this.coroutines[evt].push({ comp: script, main: coroutine });
835
+ return coroutine;
836
+ }
837
+
838
+ /** @internal Automatically called by components. */
839
+ unregisterCoroutineUpdate(coroutine: Generator, evt: FrameEvent): void {
840
+ if (!this.coroutines[evt]) return;
841
+ const idx = this.coroutines[evt].findIndex(c => c.main === coroutine);
842
+ if (idx >= 0) this.coroutines[evt].splice(idx, 1);
843
+ }
844
+
845
+ /** @internal Automatically called */
846
+ stopAllCoroutinesFrom(script: IComponent) {
847
+ for (const evt in this.coroutines) {
848
+ const rout: CoroutineData[] = this.coroutines[evt];
849
+ for (let i = rout.length - 1; i >= 0; i--) {
850
+ const r = rout[i];
851
+ if (r.comp === script) {
852
+ rout.splice(i, 1);
853
+ }
854
+ }
855
+ }
856
+ }
857
+
858
+ private _cameraStack: ICamera[] = [];
859
+
860
+ /** Change the main camera */
861
+ setCurrentCamera(cam: ICamera) {
862
+ if (!cam) return;
863
+ if (!cam.threeCamera) cam.buildCamera(); // < to build camera
864
+ if (!cam.threeCamera) {
865
+ console.warn("Camera component is missing camera", cam)
866
+ return;
867
+ }
868
+ const index = this._cameraStack.indexOf(cam);
869
+ if (index >= 0) this._cameraStack.splice(index, 1);
870
+ this._cameraStack.push(cam);
871
+ this.mainCameraComponent = cam;
872
+ const camera = cam.threeCamera as PerspectiveCamera;
873
+ if (camera.isPerspectiveCamera)
874
+ this.updateAspect(camera);
875
+ (this.mainCameraComponent as ICamera)?.applyClearFlagsIfIsActiveCamera();
876
+ }
877
+
878
+ /**
879
+ * Remove the camera from the mainCamera stack (if it has been set before with `setCurrentCamera`)
880
+ */
881
+ removeCamera(cam?: ICamera | null) {
882
+ if (!cam) return;
883
+ const index = this._cameraStack.indexOf(cam);
884
+ if (index >= 0) this._cameraStack.splice(index, 1);
885
+
886
+ if (this.mainCameraComponent === cam) {
887
+ this.mainCameraComponent = undefined;
888
+
889
+ if (this._cameraStack.length > 0) {
890
+ const last = this._cameraStack[this._cameraStack.length - 1];
891
+ this.setCurrentCamera(last);
892
+ }
893
+ }
894
+ }
895
+
896
+ private readonly _onBeforeRenderListeners = new Map<string, OnRenderCallback[]>();
897
+ private readonly _onAfterRenderListeners = new Map<string, OnRenderCallback[]>();
898
+
899
+ /** Use to subscribe to onBeforeRender events on threejs objects.
900
+ * @link https://threejs.org/docs/#api/en/core/Object3D.onBeforeRender
901
+ */
902
+ addBeforeRenderListener(target: Object3D, callback: OnRenderCallback) {
903
+ if (!this._onBeforeRenderListeners.has(target.uuid)) {
904
+ const arr: OnRenderCallback[] = [];
905
+ this._onBeforeRenderListeners.set(target.uuid, arr);
906
+ target.onBeforeRender = this._createRenderCallbackWrapper(arr);
907
+ }
908
+ this._onBeforeRenderListeners.get(target.uuid)!.push(callback);
909
+ }
910
+ /** Remove callback from three `onBeforeRender` event (if it has been added with `addBeforeRenderListener(...)`)
911
+ * @link https://threejs.org/docs/#api/en/core/Object3D.onBeforeRender
912
+ */
913
+ removeBeforeRenderListener(target: Object3D, callback: OnRenderCallback) {
914
+ if (this._onBeforeRenderListeners.has(target.uuid)) {
915
+ const arr = this._onBeforeRenderListeners.get(target.uuid)!;
916
+ const idx = arr.indexOf(callback);
917
+ if (idx >= 0) arr.splice(idx, 1);
918
+ }
919
+ }
920
+
921
+ /**
922
+ * Subscribe to onAfterRender events on threejs objects
923
+ * @link https://threejs.org/docs/#api/en/core/Object3D.onAfterRender
924
+ */
925
+ addAfterRenderListener(target: Object3D, callback: OnRenderCallback) {
926
+ if (!this._onAfterRenderListeners.has(target.uuid)) {
927
+ const arr = [];
928
+ this._onAfterRenderListeners.set(target.uuid, arr);
929
+ target.onAfterRender = this._createRenderCallbackWrapper(arr);
930
+ }
931
+ this._onAfterRenderListeners.get(target.uuid)?.push(callback);
932
+ }
933
+ /**
934
+ * Remove from onAfterRender events on threejs objects
935
+ * @link https://threejs.org/docs/#api/en/core/Object3D.onAfterRender
936
+ */
937
+ removeAfterRenderListener(target: Object3D, callback: OnRenderCallback) {
938
+ if (this._onAfterRenderListeners.has(target.uuid)) {
939
+ const arr = this._onAfterRenderListeners.get(target.uuid)!;
940
+ const idx = arr.indexOf(callback);
941
+ if (idx >= 0) arr.splice(idx, 1);
942
+ }
943
+ }
944
+
945
+
946
+ private _createRenderCallbackWrapper(array: OnRenderCallback[]): OnRenderCallback {
947
+ return (renderer, scene, camera, geometry, material, group) => {
948
+ for (let i = 0; i < array.length; i++) {
949
+ const fn = array[i];
950
+ fn(renderer, scene, camera, geometry, material, group);
951
+ }
952
+ }
953
+ }
954
+
955
+
956
+
957
+ private _requireDepthTexture: boolean = false;
958
+ private _requireColorTexture: boolean = false;
959
+ private _renderTarget?: WebGLRenderTarget;
960
+ private _isRendering: boolean = false;
961
+
962
+ /** @returns true while the WebGL renderer is rendering (between onBeforeRender and onAfterRender events) */
963
+ get isRendering() { return this._isRendering; }
964
+
965
+ setRequireDepth(val: boolean) {
966
+ this._requireDepthTexture = val;
967
+ }
968
+ setRequireColor(val: boolean) {
969
+ this._requireColorTexture = val;
970
+ }
971
+ get depthTexture(): DepthTexture | null {
972
+ return this._renderTarget?.depthTexture || null;
973
+ }
974
+ get opaqueColorTexture(): Texture | null {
975
+ return this._renderTarget?.texture || null;
976
+ }
977
+
978
+ /** @returns true if the `<needle-engine>` DOM element is visible on screen (`context.domElement`) */
979
+ get isVisibleToUser() {
980
+ if (this.isInXR) return true;
981
+ if (!this._isVisible) return false;
982
+ const style = getComputedStyle(this.domElement);
983
+ return style.visibility !== "hidden" && style.display !== "none" && style.opacity !== "0";
984
+ }
985
+
986
+ private _createId: number = 0;
987
+ private async internalOnCreate(opts?: ContextCreateArgs): Promise<boolean> {
988
+ const createId = ++this._createId;
989
+
990
+ if (debug) console.log("Creating context", this.name, opts);
991
+
992
+ // wait for async imported dependencies to be loaded
993
+ // see https://linear.app/needle/issue/NE-4445
994
+ const dependenciesReady = globalThis["needle:dependencies:ready"];
995
+ if (dependenciesReady instanceof Promise) {
996
+ if (debug) console.log("Waiting for dependencies to be ready");
997
+ await dependenciesReady
998
+ .catch(err => {
999
+ if (debug || isDevEnvironment()) {
1000
+ showBalloonError("Needle Engine dependencies failed to load. Please check the console for more details");
1001
+ const printedError = false;
1002
+ if (err instanceof ReferenceError) {
1003
+ let offendingComponentName = "YourComponentName";
1004
+ const offendingComponentStartIndex = err.message.indexOf("'");
1005
+ if (offendingComponentStartIndex > 0) {
1006
+ const offendingComponentEndIndex = err.message.indexOf("'", offendingComponentStartIndex + 1);
1007
+ if (offendingComponentEndIndex > 0) {
1008
+ const name = err.message.substring(offendingComponentStartIndex + 1, offendingComponentEndIndex);
1009
+ if (name.length > 3) offendingComponentName = name;
1010
+ }
1011
+ }
1012
+ console.error(`Needle Engine dependencies failed to load:\n\n# Make sure you don't have circular imports in your scripts!\n\nPossible solutions: \n→ Replace @serializable(${offendingComponentName}) in your script with @serializable(Behaviour)\n→ If you only need type information try importing the type only, e.g: import { type ${offendingComponentName} }\n\n---`, err)
1013
+ return;
1014
+ }
1015
+ if (!printedError) {
1016
+ console.error("Needle Engine dependencies failed to load", err);
1017
+ }
1018
+ }
1019
+ })
1020
+ .then(() => {
1021
+ if (debug) console.log("Needle Engine dependencies are ready");
1022
+ });
1023
+ }
1024
+
1025
+ this.clear();
1026
+
1027
+ const oldRenderer = this.renderer;
1028
+ // We only need to create a new renderer if we don't have one yet
1029
+ // We do prevent creating a new renderer here to avoid flickering when the context is created while the content is still being loaded. This can be the case where CSS transformations update the layout (e.g. scale() while loading + old canvas disposed but in the DOM layout.)
1030
+ const needsNewRenderer = !oldRenderer || oldRenderer["isDisposed"] === true;
1031
+
1032
+ // stop the animation loop if its running during creation
1033
+ // since we do not want to start enabling scripts etc before they are deserialized
1034
+ if (this.isManagedExternally === false && (needsNewRenderer)) {
1035
+ this.createNewRenderer();
1036
+ }
1037
+ else {
1038
+ this.lodsManager.setRenderer(this.renderer);
1039
+ }
1040
+ this.renderer?.setAnimationLoop(null);
1041
+
1042
+ await delay(1);
1043
+
1044
+ Context.Current = this;
1045
+ await ContextRegistry.dispatchCallback(ContextEvent.ContextCreationStart, this);
1046
+
1047
+ // load and create scene
1048
+ let prepare_succeeded = true;
1049
+ let loadedFiles!: Array<LoadedModel | null>;
1050
+ try {
1051
+ Context.Current = this;
1052
+ if (opts) {
1053
+ loadedFiles = await this.internalLoadInitialContent(createId, opts);
1054
+ }
1055
+ else loadedFiles = [];
1056
+ }
1057
+ catch (err) {
1058
+ console.error(err);
1059
+ prepare_succeeded = false;
1060
+ }
1061
+ if (!prepare_succeeded) {
1062
+ this.onError("Failed to load initial content");
1063
+ return false;
1064
+ }
1065
+ if (createId !== this._createId || opts?.abortSignal?.aborted) {
1066
+ return false;
1067
+ }
1068
+
1069
+ this.internalOnUpdateVisible();
1070
+
1071
+ if (!this.renderer) {
1072
+ if (debug) console.warn("Context has no renderer (perhaps it was disconnected?", this.domElement.isConnected);
1073
+ return false;
1074
+ }
1075
+
1076
+ if (!this.isManagedExternally && !this.domElement.shadowRoot) {
1077
+ this.domElement.prepend(this.renderer.domElement);
1078
+ }
1079
+
1080
+ Context.Current = this;
1081
+
1082
+ // TODO: we could configure if we need physics
1083
+ // await this.physics.engine?.initialize();
1084
+
1085
+ // Setup
1086
+ Context.Current = this;
1087
+ for (let i = 0; i < this.new_scripts.length; i++) {
1088
+ const script = this.new_scripts[i];
1089
+ if (script.gameObject !== undefined && script.gameObject !== null) {
1090
+ if (script.gameObject.userData === undefined) script.gameObject.userData = {};
1091
+ if (script.gameObject.userData.components === undefined) script.gameObject.userData.components = [];
1092
+ const arr = script.gameObject.userData.components;
1093
+ if (!arr.includes(script)) arr.push(script);
1094
+ }
1095
+ // if (script.gameObject && !this.raycastTargets.includes(script.gameObject)) {
1096
+ // this.raycastTargets.push(script.gameObject);
1097
+ // }
1098
+ }
1099
+
1100
+ // const context = new SerializationContext(this.scene);
1101
+ // for (let i = 0; i < this.new_scripts.length; i++) {
1102
+ // const script = this.new_scripts[i];
1103
+ // const ser = script as unknown as ISerializable;
1104
+ // if (ser.$serializedTypes === undefined) continue;
1105
+ // context.context = this;
1106
+ // context.object = script.gameObject;
1107
+ // deserializeObject(ser, script, context);
1108
+ // }
1109
+
1110
+ // resolve post setup callbacks (things that rely on threejs objects having references to components)
1111
+ if (this.post_setup_callbacks) {
1112
+ for (let i = 0; i < this.post_setup_callbacks.length; i++) {
1113
+ Context.Current = this;
1114
+ await this.post_setup_callbacks[i](this);
1115
+ }
1116
+ }
1117
+
1118
+ if (!this._mainCamera) {
1119
+ Context.Current = this;
1120
+ let camera: ICamera | null = null;
1121
+ foreachComponent(this.scene, comp => {
1122
+ const cam = comp as ICamera;
1123
+ if (cam?.isCamera) {
1124
+ looputils.updateActiveInHierarchyWithoutEventCall(cam.gameObject);
1125
+ if (!cam.activeAndEnabled) return undefined;
1126
+ if (cam.tag === "MainCamera") {
1127
+ camera = cam;
1128
+ return true;
1129
+ }
1130
+ else camera = cam;
1131
+ }
1132
+ return undefined;
1133
+ });
1134
+ if (camera) {
1135
+ this.setCurrentCamera(camera);
1136
+ }
1137
+ else {
1138
+ const res = ContextRegistry.dispatchCallback(ContextEvent.MissingCamera, this, { files: loadedFiles });
1139
+ if (!res && !this.mainCamera && !this.isManagedExternally)
1140
+ console.warn("Missing camera in main scene", this);
1141
+ }
1142
+ }
1143
+
1144
+ this.input.bindEvents();
1145
+
1146
+ Context.Current = this;
1147
+ looputils.processNewScripts(this);
1148
+
1149
+ // We have to step once so that colliders that have been created in onEnable can be raycasted in start
1150
+ if (this.physics.engine) {
1151
+ this.physics.engine?.step(0);
1152
+ this.physics.engine?.postStep();
1153
+ }
1154
+
1155
+ // const mainCam = this.mainCameraComponent as Camera;
1156
+ // if (mainCam) {
1157
+ // mainCam.applyClearFlagsIfIsActiveCamera();
1158
+ // }
1159
+
1160
+ if (!this.isManagedExternally && this.composer && this.mainCamera) {
1161
+ // TODO: import postprocessing async
1162
+ // const renderPass = new RenderPass(this.scene, this.mainCamera);
1163
+ // this.renderer.setSize(this.domWidth, this.domHeight);
1164
+ // this.composer.addPass(renderPass);
1165
+ // this.composer.setSize(this.domWidth, this.domHeight);
1166
+ }
1167
+
1168
+ this._needsUpdateSize = true;
1169
+
1170
+ if (this._stats) {
1171
+ this._stats.showPanel(0);
1172
+ this._stats.dom.style.position = "absolute"; // (default is fixed)
1173
+ this.domElement.shadowRoot?.appendChild(this._stats.dom);
1174
+ }
1175
+
1176
+ if (debug)
1177
+ logHierarchy(this.scene, true);
1178
+
1179
+ // If no target framerate was set we use the default
1180
+ if (this.targetFrameRate === undefined) {
1181
+ if (debug) console.warn("No target framerate set, using default", Context.DefaultTargetFrameRate);
1182
+ // the _defaultTargetFramerate is intentionally an object so it can be changed at any time if not explictly set by the user
1183
+ this.targetFrameRate = Context._defaultTargetFramerate;
1184
+ }
1185
+ else if (debug) console.log("Target framerate set to", this.targetFrameRate);
1186
+
1187
+ this._dispatchReadyAfterFrame = true;
1188
+ const res = ContextRegistry.dispatchCallback(ContextEvent.ContextCreated, this, { files: loadedFiles });
1189
+ if (res) {
1190
+ const domElement = this.domElement as HTMLElement;
1191
+ if ("internalSetLoadingMessage" in domElement && typeof domElement.internalSetLoadingMessage === "function")
1192
+ domElement?.internalSetLoadingMessage("finish loading");
1193
+ await res;
1194
+ }
1195
+ if (opts?.abortSignal?.aborted) {
1196
+ return false;
1197
+ }
1198
+ invokeLifecycleFunctions(this, ContextEvent.ContextCreated);
1199
+ if (debug) console.log("Context Created...", this.renderer, this.renderer.domElement)
1200
+
1201
+ this._isCreating = false;
1202
+ if (!this.isManagedExternally && !opts?.abortSignal?.aborted)
1203
+ this.restartRenderLoop();
1204
+ return true;
1205
+ }
1206
+
1207
+ private async internalLoadInitialContent(createId: number, args: ContextCreateArgs): Promise<Array<LoadedModel>> {
1208
+ const results = new Array<LoadedModel>();
1209
+ // early out if we dont have any files to load
1210
+ if (args.files.length === 0) return results;
1211
+
1212
+
1213
+ const files = [...args.files];
1214
+ const progressArg: LoadingProgressArgs = {
1215
+ name: "",
1216
+ progress: null!,
1217
+ index: 0,
1218
+ count: files.length
1219
+ }
1220
+
1221
+ const loader = getLoader();
1222
+ // this hash should be constant since it is used to initialize the UIDProvider per initially loaded scene
1223
+ const loadingHash = 0;
1224
+ for (let i = 0; i < files.length; i++) {
1225
+ if (args.abortSignal?.aborted) {
1226
+ if (debug) console.log("Aborting loading because of abort signal");
1227
+ break;
1228
+ }
1229
+ // abort loading if the create id has changed
1230
+ if (createId !== this._createId) {
1231
+ if (debug) console.log("Aborting loading because create id changed", createId, this._createId);
1232
+ break;
1233
+ }
1234
+ const file = files[i];
1235
+ args?.onLoadingStart?.call(this, i, file);
1236
+ if (debug) console.log("Context Load " + file);
1237
+ const res = await loader.loadSync(this, file, file, loadingHash, prog => {
1238
+ if (args.abortSignal?.aborted) return;
1239
+ progressArg.name = file;
1240
+ progressArg.progress = prog;
1241
+ progressArg.index = i;
1242
+ progressArg.count = files.length;
1243
+ args.onLoadingProgress?.call(this, progressArg);
1244
+ });
1245
+ args?.onLoadingFinished?.call(this, i, file, res ?? null);
1246
+ if (res) {
1247
+ results.push({
1248
+ src: file,
1249
+ file: res
1250
+ });
1251
+ }
1252
+ else {
1253
+ // a file could not be loaded
1254
+ console.warn("Could not load file: " + file);
1255
+ }
1256
+ }
1257
+
1258
+ // if the id was changed while still loading
1259
+ // then we want to cleanup/destroy previously loaded files
1260
+ if (createId !== this._createId || args.abortSignal?.aborted) {
1261
+ if (debug) console.log("Aborting loading because create id changed or abort signal was set", createId, this._createId);
1262
+ for (const res of results) {
1263
+ if (res && res.file) {
1264
+ for (const scene of res.file.scenes)
1265
+ destroy(scene, true, true);
1266
+ }
1267
+ }
1268
+ }
1269
+ // otherwise we want to add the loaded files to the current scene
1270
+ else {
1271
+ let anyModelFound = false;
1272
+ for (const res of results) {
1273
+ if (res && res.file) {
1274
+ // TODO: should we load all scenes in a glTF here?
1275
+ if (res.file.scene) {
1276
+ anyModelFound = true;
1277
+ this.scene.add(res.file.scene);
1278
+ }
1279
+ else {
1280
+ console.warn("No scene found in loaded file");
1281
+ }
1282
+ }
1283
+ }
1284
+ // If the loaded files do not contain ANY model
1285
+ // We then attempt to create a mesh from each material in the loaded files to visualize it
1286
+ // It's ok to do this at this point because we know the context has been cleared because the whole `src` attribute has been set
1287
+ if (!anyModelFound) {
1288
+ for (const res of results) {
1289
+ if (res && res.file && "parser" in res.file) {
1290
+ let y = 0;
1291
+ if (!Array.isArray(res.file.parser.json.materials)) continue;
1292
+ for (let i = 0; i < res.file.parser.json.materials.length; i++) {
1293
+ const mat = await res.file.parser.getDependency("material", i);
1294
+ const parent = new Object3D();
1295
+ parent.position.x = i * 1.1;
1296
+ parent.position.y = y;
1297
+ this.scene.add(parent);
1298
+ ObjectUtils.createPrimitive("ShaderBall", {
1299
+ parent,
1300
+ material: mat
1301
+ });
1302
+ }
1303
+ y += 1;
1304
+ }
1305
+ }
1306
+ }
1307
+ }
1308
+
1309
+ return results;
1310
+ }
1311
+
1312
+
1313
+ /** Sets the animation loop.
1314
+ * Can not be done while creating the context or when disposed
1315
+ **/
1316
+ public restartRenderLoop(): boolean {
1317
+ if (!this.renderer) {
1318
+ console.error("Can not start render loop without renderer");
1319
+ return false;
1320
+ }
1321
+ if (this._isCreating) {
1322
+ console.warn("Can not start render loop while creating context");
1323
+ return false;
1324
+ }
1325
+ this.renderer.setAnimationLoop((timestamp, frame: XRFrame | null) => {
1326
+ if (this.isManagedExternally) return;
1327
+ this.update(timestamp, frame)
1328
+ });
1329
+ return true;
1330
+ }
1331
+
1332
+ private _renderlooperrors = 0;
1333
+
1334
+ /** Performs a full update step including script callbacks, rendering (unless isManagedExternally is set to false) and post render callbacks */
1335
+ public update(timestamp: DOMHighResTimeStamp, frame?: XRFrame | null) {
1336
+ if (frame === undefined) frame = null;
1337
+ if (isDevEnvironment() || debug || looputils.hasNewScripts()) {
1338
+ try {
1339
+ //performance.mark('update.start');
1340
+ this.internalStep(timestamp, frame);
1341
+ this._renderlooperrors = 0;
1342
+ //performance.mark('update.end');
1343
+ //performance.measure('NE Frame', 'update.start', 'update.end');
1344
+ }
1345
+ catch (err) {
1346
+ this._renderlooperrors += 1;
1347
+ if ((isDevEnvironment() || debug) && (err instanceof Error || err instanceof TypeError))
1348
+ showBalloonMessage(`Caught unhandled exception during render-loop - see console for details.`, LogType.Error);
1349
+ console.error("Frame #" + this.time.frame + "\n", err);
1350
+ if (this._renderlooperrors >= 3) {
1351
+ console.warn("Stopping render loop due to error")
1352
+ this.renderer.setAnimationLoop(null);
1353
+ }
1354
+ this.domElement.dispatchEvent(new CustomEvent("error", { detail: err }));
1355
+ }
1356
+ }
1357
+ else {
1358
+ this.internalStep(timestamp, frame);
1359
+ }
1360
+ }
1361
+
1362
+ /** Call to **manually** perform physics steps.
1363
+ * By default the context uses the `physicsSteps` property to perform steps during the update loop
1364
+ * If you just want to increase the accuracy of physics you can instead set the `physicsSteps` property to a higher value
1365
+ * */
1366
+ public updatePhysics(steps: number) {
1367
+ this.internalUpdatePhysics(steps);
1368
+ }
1369
+
1370
+ private _lastTimestamp = 0;
1371
+ private _accumulatedTime = 0;
1372
+ private _dispatchReadyAfterFrame = false;
1373
+
1374
+ // TODO: we need to skip after render callbacks if the render loop is managed externally. When changing this we also need to to update the r3f sample
1375
+ private internalStep(timestamp: DOMHighResTimeStamp, frame: XRFrame | null) {
1376
+ if (this.internalOnBeforeRender(timestamp, frame) === false) return;
1377
+ this.internalOnRender();
1378
+ this.internalOnAfterRender();
1379
+ }
1380
+
1381
+ private internalOnBeforeRender(timestamp: DOMHighResTimeStamp, frame: XRFrame | null) {
1382
+
1383
+ // If we don't auto reset we get wrong stats in WebXR. AutoReset was turned off to support custom blits and count them too
1384
+ // But when we're using postprocessing we need to reset manually: https://discourse.threejs.org/t/accessing-draw-calls-when-using-effectcomposer
1385
+ this.renderer.info.autoReset = frame ? true : false;
1386
+ if (this.renderer.info.autoReset === false) {
1387
+ this.renderer.info.reset();
1388
+ }
1389
+
1390
+
1391
+ const sessionStarted = frame !== null && this._xrFrame === null;
1392
+ this._xrFrame = frame;
1393
+ if (sessionStarted) {
1394
+ this.domElement.dispatchEvent(new CustomEvent("xr-session-started", { detail: { context: this, session: this.xrSession, frame: frame } }));
1395
+ }
1396
+
1397
+ this._currentFrameEvent = FrameEvent.Undefined;
1398
+
1399
+ if (this.isManagedExternally === false && this.isInXR === false && this.targetFrameRate !== undefined) {
1400
+ if (this._lastTimestamp === 0) this._lastTimestamp = timestamp;
1401
+ this._accumulatedTime += (timestamp - this._lastTimestamp) / 1000;
1402
+ this._lastTimestamp = timestamp;
1403
+ let targetFrameRate = this.targetFrameRate;
1404
+ if (typeof targetFrameRate === "object") targetFrameRate = targetFrameRate.value!;
1405
+ // if(debug) console.log(this._accumulatedTime, (1 / (targetFrameRate)))
1406
+ if (this._accumulatedTime < (1 / (targetFrameRate + 1))) {
1407
+ return false;
1408
+ }
1409
+ this._accumulatedTime = 0;
1410
+ }
1411
+
1412
+ this._stats?.begin();
1413
+
1414
+ Context.Current = this;
1415
+ if (this.onHandlePaused()) return false;
1416
+
1417
+ Context.Current = this;
1418
+ this.time.update();
1419
+ if (debugframerate)
1420
+ console.log("FPS", (this.time.smoothedFps).toFixed(0));
1421
+
1422
+
1423
+ looputils.processNewScripts(this);
1424
+ looputils.updateIsActive(this.scene);
1425
+ looputils.processStart(this);
1426
+ invokeLifecycleFunctions(this, FrameEvent.Start);
1427
+
1428
+ while (this._cameraStack.length > 0 && (!this.mainCameraComponent || this.mainCameraComponent.destroyed)) {
1429
+ this._cameraStack.splice(this._cameraStack.length - 1, 1);
1430
+ const last = this._cameraStack[this._cameraStack.length - 1];
1431
+ this.setCurrentCamera(last);
1432
+ }
1433
+
1434
+ if (this.pre_update_oneshot_callbacks) {
1435
+ for (const i in this.pre_update_oneshot_callbacks) {
1436
+ this.pre_update_oneshot_callbacks[i]();
1437
+ }
1438
+ this.pre_update_oneshot_callbacks.length = 0;
1439
+ }
1440
+
1441
+ if (this.pre_update_callbacks) {
1442
+ for (const i in this.pre_update_callbacks) {
1443
+ this.pre_update_callbacks[i]();
1444
+ }
1445
+ }
1446
+
1447
+ this._currentFrameEvent = FrameEvent.EarlyUpdate;
1448
+
1449
+ for (let i = 0; i < this.scripts_earlyUpdate.length; i++) {
1450
+ const script = this.scripts_earlyUpdate[i];
1451
+ if (!script.activeAndEnabled) continue;
1452
+ if (script.earlyUpdate !== undefined) {
1453
+ Context.Current = this;
1454
+ script.earlyUpdate();
1455
+ }
1456
+ }
1457
+ this.executeCoroutines(FrameEvent.EarlyUpdate);
1458
+ invokeLifecycleFunctions(this, FrameEvent.EarlyUpdate);
1459
+ if (this.onHandlePaused()) return false;
1460
+
1461
+ this._currentFrameEvent = FrameEvent.Update;
1462
+
1463
+ for (let i = 0; i < this.scripts_update.length; i++) {
1464
+ const script = this.scripts_update[i];
1465
+ if (!script.activeAndEnabled) continue;
1466
+ if (script.update !== undefined) {
1467
+ Context.Current = this;
1468
+ script.update();
1469
+ }
1470
+ }
1471
+ this.executeCoroutines(FrameEvent.Update);
1472
+ invokeLifecycleFunctions(this, FrameEvent.Update);
1473
+ if (this.onHandlePaused()) return false;
1474
+
1475
+ this._currentFrameEvent = FrameEvent.LateUpdate;
1476
+
1477
+ for (let i = 0; i < this.scripts_lateUpdate.length; i++) {
1478
+ const script = this.scripts_lateUpdate[i];
1479
+ if (!script.activeAndEnabled) continue;
1480
+ if (script.lateUpdate !== undefined) {
1481
+ Context.Current = this;
1482
+ script.lateUpdate();
1483
+ }
1484
+ }
1485
+
1486
+ // this.mainLight = null;
1487
+ this.executeCoroutines(FrameEvent.LateUpdate);
1488
+ invokeLifecycleFunctions(this, FrameEvent.LateUpdate);
1489
+ if (this.onHandlePaused()) return false;
1490
+
1491
+ if (this.physicsSteps === undefined) {
1492
+ this.physicsSteps = 1;
1493
+ }
1494
+ if (this.physics.engine && this.physicsSteps > 0) {
1495
+ this.internalUpdatePhysics(this.physicsSteps);
1496
+ }
1497
+
1498
+ if (this.onHandlePaused()) return false;
1499
+
1500
+ if (this.isVisibleToUser || this.runInBackground) {
1501
+
1502
+ this._currentFrameEvent = FrameEvent.OnBeforeRender;
1503
+
1504
+ // should we move these callbacks in the regular three onBeforeRender events?
1505
+ for (let i = 0; i < this.scripts_onBeforeRender.length; i++) {
1506
+ const script = this.scripts_onBeforeRender[i];
1507
+ if (!script.activeAndEnabled) continue;
1508
+ // if(script.isActiveAndEnabled === false) continue;
1509
+ if (script.onBeforeRender !== undefined) {
1510
+ Context.Current = this;
1511
+ script.onBeforeRender(frame);
1512
+ }
1513
+ }
1514
+
1515
+ this.executeCoroutines(FrameEvent.OnBeforeRender);
1516
+ invokeLifecycleFunctions(this, FrameEvent.OnBeforeRender);
1517
+
1518
+ if (this._needsUpdateSize)
1519
+ this.updateSize();
1520
+
1521
+ if (this.pre_render_callbacks) {
1522
+ for (const i in this.pre_render_callbacks) {
1523
+ this.pre_render_callbacks[i](frame);
1524
+ }
1525
+ }
1526
+
1527
+ }
1528
+
1529
+ return true;
1530
+ }
1531
+
1532
+ private internalUpdatePhysics(steps: number) {
1533
+ if (!this.physics.engine) return false;
1534
+ const physicsSteps = steps;
1535
+ const dt = this.time.deltaTime / physicsSteps;
1536
+ for (let i = 0; i < physicsSteps; i++) {
1537
+ this._currentFrameEvent = FrameEvent.PrePhysicsStep;
1538
+ this.executeCoroutines(FrameEvent.PrePhysicsStep);
1539
+ this.physics.engine.step(dt);
1540
+ this._currentFrameEvent = FrameEvent.PostPhysicsStep;
1541
+ this.executeCoroutines(FrameEvent.PostPhysicsStep);
1542
+ }
1543
+ this.physics.engine.postStep();
1544
+ return true;
1545
+ }
1546
+
1547
+ private internalOnRender() {
1548
+ if (!this.isManagedExternally) {
1549
+ // when loading assets we compile them async after GLTFLoader is done
1550
+ // but as a fallback we still register them (if e.g. there's no camera for compile async)
1551
+ looputils.runPrewarm(this);
1552
+ this._currentFrameEvent = FrameEvent.Undefined;
1553
+ nodeFrame.update();
1554
+ this.renderNow();
1555
+ this._currentFrameEvent = FrameEvent.OnAfterRender;
1556
+ }
1557
+ }
1558
+
1559
+ private internalOnAfterRender() {
1560
+ if (this.isVisibleToUser || this.runInBackground) {
1561
+ for (let i = 0; i < this.scripts_onAfterRender.length; i++) {
1562
+ const script = this.scripts_onAfterRender[i];
1563
+ if (!script.activeAndEnabled) continue;
1564
+ if (script.onAfterRender !== undefined) {
1565
+ Context.Current = this;
1566
+ script.onAfterRender();
1567
+ }
1568
+ }
1569
+
1570
+ this.executeCoroutines(FrameEvent.OnAfterRender);
1571
+ invokeLifecycleFunctions(this, FrameEvent.OnAfterRender);
1572
+
1573
+ if (this.post_render_callbacks) {
1574
+ for (const i in this.post_render_callbacks) {
1575
+ this.post_render_callbacks[i]();
1576
+ }
1577
+ }
1578
+ }
1579
+
1580
+ this._currentFrameEvent = -1;
1581
+
1582
+ this.connection.sendBufferedMessagesNow();
1583
+
1584
+ if (this._stats) {
1585
+ this._stats.end();
1586
+ if (this.time.frameCount % 150 === 0)
1587
+ console.log(this.renderer.info.render.calls + " DrawCalls", "\nRender:", { ...this.renderer.info.render }, "\nMemory:", { ...this.renderer.info.memory }, "\nTarget Framerate: " + this.targetFrameRate);
1588
+ }
1589
+
1590
+ if (this._dispatchReadyAfterFrame) {
1591
+ this._dispatchReadyAfterFrame = false;
1592
+ this.domElement.dispatchEvent(new CustomEvent("ready"));
1593
+ ContextRegistry.dispatchCallback(ContextEvent.ContextFirstFrameRendered, this);
1594
+ }
1595
+ }
1596
+
1597
+ private readonly _tempClearColor = new Color();
1598
+ private readonly _tempClearColor2 = new Color();
1599
+ renderNow(camera?: Camera) {
1600
+ if (!camera) {
1601
+ camera = this.mainCamera as Camera;
1602
+ if (!camera) return false;
1603
+ }
1604
+ this.handleRendererContextLost();
1605
+
1606
+ this._isRendering = true;
1607
+ this.renderRequiredTextures();
1608
+
1609
+ if (this.renderer.toneMapping !== NoToneMapping)
1610
+ patchTonemapping(this);
1611
+
1612
+ if (this.composer && !this.isInXR) {
1613
+ // if a camera is passed in we need to check if we need to update the composer's camera
1614
+ if (camera && "setMainCamera" in this.composer) {
1615
+ const currentPassesCamera = this.composer.passes[0]?.mainCamera;
1616
+ if (currentPassesCamera != camera)
1617
+ this.composer.setMainCamera(camera);
1618
+ }
1619
+
1620
+ const backgroundColor = this.renderer.getClearColor(this._tempClearColor);
1621
+ const clearAlpha = this.renderer.getClearAlpha();
1622
+ this._tempClearColor2.copy(backgroundColor);
1623
+ this.renderer.setClearColor(backgroundColor.convertSRGBToLinear(), this.renderer.getClearAlpha());
1624
+ this.composer.render(this.time.deltaTime);
1625
+ this.renderer.setClearColor(this._tempClearColor2, clearAlpha); // restore clear color
1626
+ }
1627
+ else if (camera) {
1628
+ // Workaround for issue on Vision Pro –
1629
+ // depth buffer is not cleared between eye draws, despite the spec...
1630
+ if (this.isInXR && DeviceUtilities.isMacOS())
1631
+ this.renderer.clearDepth();
1632
+ this.renderer.render(this.scene, camera);
1633
+ }
1634
+ this._isRendering = false;
1635
+ return true;
1636
+ }
1637
+
1638
+ private _contextRestoreTries = 0;
1639
+ private handleRendererContextLost() {
1640
+ // Try to restore the context every x frames
1641
+ if (this.time.frame % 10 && this.renderer.getContext().isContextLost()) {
1642
+ if (this._contextRestoreTries++ < 100) {
1643
+ console.warn("Attempting to recover WebGL context...");
1644
+ this.renderer.forceContextRestore();
1645
+ }
1646
+ }
1647
+ }
1648
+
1649
+ /** returns true if we should return out of the frame loop */
1650
+ private _wasPaused: boolean = false;
1651
+ private onHandlePaused(): boolean {
1652
+ const paused = this.evaluatePaused();
1653
+ if (this._wasPaused !== paused) {
1654
+ if (debugActive) console.log("Paused?", paused, "context:" + this.alias);
1655
+ for (let i = 0; i < this.scripts_pausedChanged.length; i++) {
1656
+ const script = this.scripts_pausedChanged[i];
1657
+ if (!script.activeAndEnabled) continue;
1658
+ if (script.onPausedChanged !== undefined) {
1659
+ Context.Current = this;
1660
+ script.onPausedChanged(paused, this._wasPaused);
1661
+ }
1662
+ }
1663
+ }
1664
+ this._wasPaused = paused;
1665
+ return paused;
1666
+ }
1667
+
1668
+ private evaluatePaused(): boolean {
1669
+ if (this.isInXR) return false;
1670
+ if (this.isPaused) return true;
1671
+ // if the element is not visible use the runInBackground flag to determine if we should continue
1672
+ if (this.runInBackground) {
1673
+ return false;
1674
+ }
1675
+ const paused = !this.isVisibleToUser;
1676
+ return paused;
1677
+ }
1678
+
1679
+ private renderRequiredTextures() {
1680
+ if (!this.mainCamera) return;
1681
+ if (!this._requireDepthTexture && !this._requireColorTexture) return;
1682
+ if (!this._renderTarget) {
1683
+ this._renderTarget = new WebGLRenderTarget(this.domWidth, this.domHeight);
1684
+ if (this._requireDepthTexture) {
1685
+ const dt = new DepthTexture(this.domWidth, this.domHeight);;
1686
+ this._renderTarget.depthTexture = dt;
1687
+ }
1688
+ if (this._requireColorTexture) {
1689
+ this._renderTarget.texture = new Texture();
1690
+ this._renderTarget.texture.generateMipmaps = false;
1691
+ this._renderTarget.texture.minFilter = NearestFilter;
1692
+ this._renderTarget.texture.magFilter = NearestFilter;
1693
+ this._renderTarget.texture.format = RGBAFormat;
1694
+ }
1695
+ }
1696
+ const rt = this._renderTarget;
1697
+ if (rt.texture) {
1698
+ rt.texture.colorSpace = this.renderer.outputColorSpace;
1699
+ }
1700
+ const prevTarget = this.renderer.getRenderTarget();
1701
+ this.renderer.setRenderTarget(rt);
1702
+ this.renderer.render(this.scene, this.mainCamera);
1703
+ this.renderer.setRenderTarget(prevTarget);
1704
+ }
1705
+
1706
+ private executeCoroutines(evt: FrameEvent) {
1707
+ if (this.coroutines[evt]) {
1708
+ const evts = this.coroutines[evt];
1709
+ for (let i = 0; i < evts.length; i++) {
1710
+ try {
1711
+ const evt = evts[i];
1712
+ // TODO we might want to keep coroutines playing even if the component is disabled or inactive
1713
+ const remove = !evt.comp || evt.comp.destroyed || !evt.main || evt.comp["enabled"] === false;
1714
+ if (remove) {
1715
+ if (debugCoroutine) console.log("Removing coroutine", evt.comp, evt.comp["enabled"])
1716
+ evts.splice(i, 1);
1717
+ --i;
1718
+ continue;
1719
+ }
1720
+ const iter = evt.chained;
1721
+ if (iter && iter.length > 0) {
1722
+ const last: Generator = iter[iter.length - 1];
1723
+ const res = last.next();
1724
+ if (res.done) {
1725
+ iter.pop();
1726
+ }
1727
+ if (isGenerator(res)) {
1728
+ if (!evt.chained) evt.chained = [];
1729
+ evt.chained.push(res.value);
1730
+ }
1731
+ if (!res.done) continue;
1732
+ }
1733
+
1734
+ const res = evt.main.next();
1735
+ if (res.done === true) {
1736
+ evts.splice(i, 1);
1737
+ --i;
1738
+ continue;
1739
+ }
1740
+ const val = res.value;
1741
+ if (isGenerator(val)) {
1742
+ // invoke once if its a generator
1743
+ // this means e.g. WaitForFrame(1) works and will capture
1744
+ // the frame it was created
1745
+ const gen = val as Generator;
1746
+ const res = gen.next();
1747
+ if (res.done) continue;
1748
+ if (!evt.chained) evt.chained = [];
1749
+ evt.chained.push(val as Generator);
1750
+ }
1751
+ else if (val instanceof Promise) {
1752
+ // If its a promise we want to wait for it to resolve
1753
+ const prom = val as Promise<any>;
1754
+ if (!evt.chained) evt.chained = [];
1755
+ const nested = WaitForPromise(prom);
1756
+ evt.chained?.push(nested);
1757
+ continue;
1758
+ }
1759
+ }
1760
+ catch (e) {
1761
+ console.error(e);
1762
+ }
1763
+ }
1764
+ }
1765
+
1766
+ function isGenerator(val: any): boolean {
1767
+ if (val) {
1768
+ if (val.next && val.return) {
1769
+ return true;
1770
+ }
1771
+ }
1772
+ return false;
1773
+ }
1774
+ }
1775
+
1776
+ }
1777
+
1778
+
1779
+ // const scene = new Scene();
1780
+ // const useComposer = utils.getParam("postfx");
1781
+ // const renderer = new WebGLRenderer({ antialias: true });
1782
+ // const composer = useComposer ? new EffectComposer(renderer) : undefined;
1783
+
1784
+ // renderer.setClearColor(new Color('lightgrey'), 0)
1785
+ // renderer.antialias = true;
1786
+ // renderer.alpha = false;
1787
+ // renderer.shadowMap.enabled = true;
1788
+ // renderer.shadowMap.type = PCFSoftShadowMap;
1789
+ // renderer.setSize(window.innerWidth, window.innerHeight);
1790
+ // renderer.outputEncoding = sRGBEncoding;
1791
+ // renderer.physicallyCorrectLights = true;
1792
+ // document.body.appendChild(renderer.domElement);
1793
+
1794
+ // // generation pushes loading requests in this array
1795
+ // const sceneData: {
1796
+ // mainCamera: Camera | undefined
1797
+ // } = {
1798
+ // preparing: [],
1799
+ // resolving: [],
1800
+ // scripts: [],
1801
+ // raycastTargets: [],
1802
+ // mainCamera: undefined,
1803
+ // mainCameraComponent: undefined,
1804
+ // };
1805
+
1806
+ // // contains a list of functions to be called after loading is done
1807
+ // const post_setup_callbacks = [];
1808
+
1809
+ // const pre_render_Callbacks = [];
1810
+ // const post_render_callbacks = [];
1811
+
1812
+ // const new_scripts = [];
1813
+ // const new_scripts_post_setup_callbacks = [];
1814
+ // const new_scripts_pre_setup_callbacks = [];
1815
+
1816
+ // export {
1817
+ // scene, renderer, composer,
1818
+ // new_scripts,
1819
+ // new_scripts_post_setup_callbacks, new_scripts_pre_setup_callbacks,
1820
+ // sceneData,
1821
+ // post_setup_callbacks,
1822
+ // pre_render_Callbacks,
1823
+ // post_render_callbacks
1824
+ // }