@xeokit/xeokit-sdk 2.4.0-alpha-81 → 2.4.0-alpha-82

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 (384) hide show
  1. package/package.json +2 -1
  2. package/src/extras/ContextMenu/ContextMenu.js +907 -0
  3. package/src/extras/ContextMenu/index.js +1 -0
  4. package/src/extras/index.js +1 -0
  5. package/src/index.js +3 -0
  6. package/src/plugins/AngleMeasurementsPlugin/AngleMeasurement.js +658 -0
  7. package/src/plugins/AngleMeasurementsPlugin/AngleMeasurementsControl.js +418 -0
  8. package/src/plugins/AngleMeasurementsPlugin/AngleMeasurementsPlugin.js +400 -0
  9. package/src/plugins/AngleMeasurementsPlugin/index.js +1 -0
  10. package/src/plugins/AnnotationsPlugin/Annotation.js +368 -0
  11. package/src/plugins/AnnotationsPlugin/AnnotationsPlugin.js +583 -0
  12. package/src/plugins/AnnotationsPlugin/index.js +1 -0
  13. package/src/plugins/AxisGizmoPlugin/AxisGizmoPlugin.js +333 -0
  14. package/src/plugins/AxisGizmoPlugin/index.js +1 -0
  15. package/src/plugins/BCFViewpointsPlugin/BCFViewpointsPlugin.js +955 -0
  16. package/src/plugins/BCFViewpointsPlugin/index.js +1 -0
  17. package/src/plugins/CityJSONLoaderPlugin/CityJSONDefaultDataSource.js +29 -0
  18. package/src/plugins/CityJSONLoaderPlugin/CityJSONLoaderPlugin.js +751 -0
  19. package/src/plugins/CityJSONLoaderPlugin/index.js +1 -0
  20. package/src/plugins/DistanceMeasurementsPlugin/DistanceMeasurement.js +870 -0
  21. package/src/plugins/DistanceMeasurementsPlugin/DistanceMeasurementsControl.js +376 -0
  22. package/src/plugins/DistanceMeasurementsPlugin/DistanceMeasurementsPlugin.js +454 -0
  23. package/src/plugins/DistanceMeasurementsPlugin/index.js +1 -0
  24. package/src/plugins/FaceAlignedSectionPlanesPlugin/FaceAlignedSectionPlanesControl.js +639 -0
  25. package/src/plugins/FaceAlignedSectionPlanesPlugin/FaceAlignedSectionPlanesPlugin.js +436 -0
  26. package/src/plugins/FaceAlignedSectionPlanesPlugin/Overview.js +247 -0
  27. package/src/plugins/FaceAlignedSectionPlanesPlugin/Plane.js +167 -0
  28. package/src/plugins/FaceAlignedSectionPlanesPlugin/index.js +1 -0
  29. package/src/plugins/FastNavPlugin/FastNavPlugin.js +429 -0
  30. package/src/plugins/FastNavPlugin/index.js +1 -0
  31. package/src/plugins/GLTFLoaderPlugin/GLTFDefaultDataSource.js +139 -0
  32. package/src/plugins/GLTFLoaderPlugin/GLTFLoaderPlugin.js +421 -0
  33. package/src/plugins/GLTFLoaderPlugin/GLTFSceneModelLoader.js +669 -0
  34. package/src/plugins/GLTFLoaderPlugin/index.js +2 -0
  35. package/src/plugins/LASLoaderPlugin/LASDefaultDataSource.js +58 -0
  36. package/src/plugins/LASLoaderPlugin/LASLoaderPlugin.js +518 -0
  37. package/src/plugins/LASLoaderPlugin/index.js +1 -0
  38. package/src/plugins/LASLoaderPlugin/loadLASHeader.js +183 -0
  39. package/src/plugins/NavCubePlugin/CubeTextureCanvas.js +289 -0
  40. package/src/plugins/NavCubePlugin/NavCubePlugin.js +752 -0
  41. package/src/plugins/NavCubePlugin/index.js +1 -0
  42. package/src/plugins/OBJLoaderPlugin/OBJLoaderPlugin.js +145 -0
  43. package/src/plugins/OBJLoaderPlugin/OBJSceneGraphLoader.js +777 -0
  44. package/src/plugins/OBJLoaderPlugin/index.js +1 -0
  45. package/src/plugins/STLLoaderPlugin/STLDefaultDataSource.js +33 -0
  46. package/src/plugins/STLLoaderPlugin/STLLoaderPlugin.js +274 -0
  47. package/src/plugins/STLLoaderPlugin/STLSceneGraphLoader.js +313 -0
  48. package/src/plugins/STLLoaderPlugin/index.js +2 -0
  49. package/src/plugins/SectionPlanesPlugin/Control.js +1328 -0
  50. package/src/plugins/SectionPlanesPlugin/Overview.js +249 -0
  51. package/src/plugins/SectionPlanesPlugin/Plane.js +169 -0
  52. package/src/plugins/SectionPlanesPlugin/SectionPlanesPlugin.js +404 -0
  53. package/src/plugins/SectionPlanesPlugin/index.js +1 -0
  54. package/src/plugins/SkyboxesPlugin/SkyboxesPlugin.js +134 -0
  55. package/src/plugins/SkyboxesPlugin/index.js +1 -0
  56. package/src/plugins/StoreyViewsPlugin/IFCStoreyPlanObjectStates.js +77 -0
  57. package/src/plugins/StoreyViewsPlugin/Storey.js +61 -0
  58. package/src/plugins/StoreyViewsPlugin/StoreyMap.js +57 -0
  59. package/src/plugins/StoreyViewsPlugin/StoreyViewsPlugin.js +825 -0
  60. package/src/plugins/StoreyViewsPlugin/index.js +1 -0
  61. package/src/plugins/TreeViewPlugin/TreeViewNode.js +97 -0
  62. package/src/plugins/TreeViewPlugin/TreeViewPlugin.js +1424 -0
  63. package/src/plugins/TreeViewPlugin/index.js +1 -0
  64. package/src/plugins/ViewCullPlugin/ViewCullPlugin.js +295 -0
  65. package/src/plugins/ViewCullPlugin/index.js +1 -0
  66. package/src/plugins/WebIFCLoaderPlugin/WebIFCDefaultDataSource.js +58 -0
  67. package/src/plugins/WebIFCLoaderPlugin/WebIFCLoaderPlugin.js +942 -0
  68. package/src/plugins/WebIFCLoaderPlugin/index.js +1 -0
  69. package/src/plugins/XKTLoaderPlugin/XKTDefaultDataSource.js +95 -0
  70. package/src/plugins/XKTLoaderPlugin/XKTLoaderPlugin.js +1107 -0
  71. package/src/plugins/XKTLoaderPlugin/index.js +2 -0
  72. package/src/plugins/XKTLoaderPlugin/parsers/ParserV1.js +169 -0
  73. package/src/plugins/XKTLoaderPlugin/parsers/ParserV10.js +656 -0
  74. package/src/plugins/XKTLoaderPlugin/parsers/ParserV2.js +230 -0
  75. package/src/plugins/XKTLoaderPlugin/parsers/ParserV3.js +223 -0
  76. package/src/plugins/XKTLoaderPlugin/parsers/ParserV4.js +283 -0
  77. package/src/plugins/XKTLoaderPlugin/parsers/ParserV5.js +246 -0
  78. package/src/plugins/XKTLoaderPlugin/parsers/ParserV6.js +301 -0
  79. package/src/plugins/XKTLoaderPlugin/parsers/ParserV7.js +439 -0
  80. package/src/plugins/XKTLoaderPlugin/parsers/ParserV8.js +563 -0
  81. package/src/plugins/XKTLoaderPlugin/parsers/ParserV9.js +514 -0
  82. package/src/plugins/XKTLoaderPlugin/parsers/lib/pako.js +2 -0
  83. package/src/plugins/XML3DLoaderPlugin/XML3DLoaderPlugin.js +238 -0
  84. package/src/plugins/XML3DLoaderPlugin/XML3DSceneGraphLoader.js +1279 -0
  85. package/src/plugins/XML3DLoaderPlugin/index.js +1 -0
  86. package/src/plugins/XML3DLoaderPlugin/zipjs/.jshintrc +11 -0
  87. package/src/plugins/XML3DLoaderPlugin/zipjs/deflate.js +2060 -0
  88. package/src/plugins/XML3DLoaderPlugin/zipjs/inflate.js +2155 -0
  89. package/src/plugins/XML3DLoaderPlugin/zipjs/mime-types.js +1002 -0
  90. package/src/plugins/XML3DLoaderPlugin/zipjs/pako/codecs.js +64 -0
  91. package/src/plugins/XML3DLoaderPlugin/zipjs/z-worker.js +153 -0
  92. package/src/plugins/XML3DLoaderPlugin/zipjs/zip-ext.js +267 -0
  93. package/src/plugins/XML3DLoaderPlugin/zipjs/zip-fs.js +553 -0
  94. package/src/plugins/XML3DLoaderPlugin/zipjs/zip.js +991 -0
  95. package/src/plugins/XML3DLoaderPlugin/zipjs/zlib-asm/codecs.js +49 -0
  96. package/src/plugins/index.js +21 -0
  97. package/src/plugins/lib/culling/ObjectCullStates.js +208 -0
  98. package/src/plugins/lib/earcut.js +677 -0
  99. package/src/plugins/lib/html/Dot.js +145 -0
  100. package/src/plugins/lib/html/Label.js +156 -0
  101. package/src/plugins/lib/html/Wire.js +191 -0
  102. package/src/viewer/Configs.js +79 -0
  103. package/src/viewer/Plugin.js +224 -0
  104. package/src/viewer/Viewer.js +535 -0
  105. package/src/viewer/index.js +5 -0
  106. package/src/viewer/localization/LocaleService.js +475 -0
  107. package/src/viewer/metadata/IFCObjectDefaultColors.js +162 -0
  108. package/src/viewer/metadata/IFCObjectDefaults.js +17 -0
  109. package/src/viewer/metadata/MetaModel.js +389 -0
  110. package/src/viewer/metadata/MetaObject.js +218 -0
  111. package/src/viewer/metadata/MetaScene.js +336 -0
  112. package/src/viewer/metadata/Property.js +55 -0
  113. package/src/viewer/metadata/PropertySet.js +77 -0
  114. package/src/viewer/scene/Bitmap/Bitmap.js +470 -0
  115. package/src/viewer/scene/Bitmap/index.js +1 -0
  116. package/src/viewer/scene/CameraControl/CameraControl.js +1737 -0
  117. package/src/viewer/scene/CameraControl/lib/CameraUpdater.js +312 -0
  118. package/src/viewer/scene/CameraControl/lib/controllers/PanController.js +112 -0
  119. package/src/viewer/scene/CameraControl/lib/controllers/PickController.js +264 -0
  120. package/src/viewer/scene/CameraControl/lib/controllers/PivotController.js +384 -0
  121. package/src/viewer/scene/CameraControl/lib/handlers/KeyboardAxisViewHandler.js +122 -0
  122. package/src/viewer/scene/CameraControl/lib/handlers/KeyboardPanRotateDollyHandler.js +183 -0
  123. package/src/viewer/scene/CameraControl/lib/handlers/MouseMiscHandler.js +68 -0
  124. package/src/viewer/scene/CameraControl/lib/handlers/MousePanRotateDollyHandler.js +345 -0
  125. package/src/viewer/scene/CameraControl/lib/handlers/MousePickHandler.js +372 -0
  126. package/src/viewer/scene/CameraControl/lib/handlers/TouchPanRotateAndDollyHandler.js +269 -0
  127. package/src/viewer/scene/CameraControl/lib/handlers/TouchPickHandler.js +235 -0
  128. package/src/viewer/scene/Component.js +907 -0
  129. package/src/viewer/scene/Entity.js +502 -0
  130. package/src/viewer/scene/ImagePlane/ImagePlane.js +570 -0
  131. package/src/viewer/scene/ImagePlane/index.js +1 -0
  132. package/src/viewer/scene/LineSet/LineSet.js +164 -0
  133. package/src/viewer/scene/LineSet/index.js +1 -0
  134. package/src/viewer/scene/camera/Camera.js +912 -0
  135. package/src/viewer/scene/camera/CameraFlightAnimation.js +669 -0
  136. package/src/viewer/scene/camera/CameraPath.js +194 -0
  137. package/src/viewer/scene/camera/CameraPathAnimation.js +326 -0
  138. package/src/viewer/scene/camera/CustomProjection.js +149 -0
  139. package/src/viewer/scene/camera/Frustum.js +316 -0
  140. package/src/viewer/scene/camera/Ortho.js +286 -0
  141. package/src/viewer/scene/camera/Perspective.js +304 -0
  142. package/src/viewer/scene/camera/index.js +2 -0
  143. package/src/viewer/scene/canvas/Canvas.js +492 -0
  144. package/src/viewer/scene/canvas/Spinner.js +323 -0
  145. package/src/viewer/scene/constants/constants.js +371 -0
  146. package/src/viewer/scene/core.js +233 -0
  147. package/src/viewer/scene/geometry/Geometry.js +33 -0
  148. package/src/viewer/scene/geometry/ReadableGeometry.js +682 -0
  149. package/src/viewer/scene/geometry/VBOGeometry.js +319 -0
  150. package/src/viewer/scene/geometry/builders/buildBoxGeometry.js +238 -0
  151. package/src/viewer/scene/geometry/builders/buildBoxLinesGeometry.js +106 -0
  152. package/src/viewer/scene/geometry/builders/buildCylinderGeometry.js +271 -0
  153. package/src/viewer/scene/geometry/builders/buildGridGeometry.js +102 -0
  154. package/src/viewer/scene/geometry/builders/buildPlaneGeometry.js +168 -0
  155. package/src/viewer/scene/geometry/builders/buildSphereGeometry.js +161 -0
  156. package/src/viewer/scene/geometry/builders/buildTorusGeometry.js +172 -0
  157. package/src/viewer/scene/geometry/builders/buildVectorTextGeometry.js +1721 -0
  158. package/src/viewer/scene/geometry/builders/index.js +8 -0
  159. package/src/viewer/scene/geometry/index.js +4 -0
  160. package/src/viewer/scene/geometry/loaders/index.js +2 -0
  161. package/src/viewer/scene/geometry/loaders/load3DSGeometry.js +103 -0
  162. package/src/viewer/scene/geometry/loaders/loadOBJGeometry.js +130 -0
  163. package/src/viewer/scene/index.js +23 -0
  164. package/src/viewer/scene/input/Input.js +1325 -0
  165. package/src/viewer/scene/libs/k3d.js +1032 -0
  166. package/src/viewer/scene/lights/AmbientLight.js +175 -0
  167. package/src/viewer/scene/lights/CubeTexture.js +156 -0
  168. package/src/viewer/scene/lights/DirLight.js +314 -0
  169. package/src/viewer/scene/lights/Light.js +29 -0
  170. package/src/viewer/scene/lights/LightMap.js +77 -0
  171. package/src/viewer/scene/lights/PointLight.js +395 -0
  172. package/src/viewer/scene/lights/ReflectionMap.js +79 -0
  173. package/src/viewer/scene/lights/Shadow.js +138 -0
  174. package/src/viewer/scene/lights/index.js +5 -0
  175. package/src/viewer/scene/lod/LOD.js +162 -0
  176. package/src/viewer/scene/lod/LODCullingManager.js +83 -0
  177. package/src/viewer/scene/lod/LODState.js +125 -0
  178. package/src/viewer/scene/lod/index.js +1 -0
  179. package/src/viewer/scene/marker/Marker.js +383 -0
  180. package/src/viewer/scene/marker/SpriteMarker.js +356 -0
  181. package/src/viewer/scene/marker/index.js +2 -0
  182. package/src/viewer/scene/materials/EdgeMaterial.js +359 -0
  183. package/src/viewer/scene/materials/EmphasisMaterial.js +613 -0
  184. package/src/viewer/scene/materials/Fresnel.js +222 -0
  185. package/src/viewer/scene/materials/LambertMaterial.js +378 -0
  186. package/src/viewer/scene/materials/LinesMaterial.js +169 -0
  187. package/src/viewer/scene/materials/Material.js +39 -0
  188. package/src/viewer/scene/materials/MetallicMaterial.js +820 -0
  189. package/src/viewer/scene/materials/PhongMaterial.js +860 -0
  190. package/src/viewer/scene/materials/PointsMaterial.js +409 -0
  191. package/src/viewer/scene/materials/SpecularMaterial.js +807 -0
  192. package/src/viewer/scene/materials/Texture.js +513 -0
  193. package/src/viewer/scene/materials/index.js +8 -0
  194. package/src/viewer/scene/math/Frustum.js +118 -0
  195. package/src/viewer/scene/math/buildEdgeIndices.js +162 -0
  196. package/src/viewer/scene/math/geometryCompressionUtils.js +365 -0
  197. package/src/viewer/scene/math/index.js +3 -0
  198. package/src/viewer/scene/math/math.js +5363 -0
  199. package/src/viewer/scene/math/rtcCoords.js +139 -0
  200. package/src/viewer/scene/mementos/CameraMemento.js +200 -0
  201. package/src/viewer/scene/mementos/ModelMemento.js +263 -0
  202. package/src/viewer/scene/mementos/ObjectsMemento.js +259 -0
  203. package/src/viewer/scene/mementos/index.js +3 -0
  204. package/src/viewer/scene/mesh/Mesh.js +2202 -0
  205. package/src/viewer/scene/mesh/draw/DrawRenderer.js +986 -0
  206. package/src/viewer/scene/mesh/draw/DrawShaderSource.js +1570 -0
  207. package/src/viewer/scene/mesh/emphasis/EmphasisEdgesRenderer.js +249 -0
  208. package/src/viewer/scene/mesh/emphasis/EmphasisEdgesShaderSource.js +158 -0
  209. package/src/viewer/scene/mesh/emphasis/EmphasisFillRenderer.js +276 -0
  210. package/src/viewer/scene/mesh/emphasis/EmphasisFillShaderSource.js +261 -0
  211. package/src/viewer/scene/mesh/index.js +1 -0
  212. package/src/viewer/scene/mesh/occlusion/OcclusionRenderer.js +207 -0
  213. package/src/viewer/scene/mesh/occlusion/OcclusionShaderSource.js +156 -0
  214. package/src/viewer/scene/mesh/pick/PickMeshRenderer.js +210 -0
  215. package/src/viewer/scene/mesh/pick/PickMeshShaderSource.js +142 -0
  216. package/src/viewer/scene/mesh/pick/PickTriangleRenderer.js +186 -0
  217. package/src/viewer/scene/mesh/pick/PickTriangleShaderSource.js +116 -0
  218. package/src/viewer/scene/mesh/shadow/ShadowRenderer.js +214 -0
  219. package/src/viewer/scene/mesh/shadow/ShadowShaderSource.js +98 -0
  220. package/src/viewer/scene/metriqs/Metriqs.js +259 -0
  221. package/src/viewer/scene/model/ENTITY_FLAGS.js +21 -0
  222. package/src/viewer/scene/model/PerformanceModel.js +26 -0
  223. package/src/viewer/scene/model/RENDER_PASSES.js +34 -0
  224. package/src/viewer/scene/model/SceneModel.js +3817 -0
  225. package/src/viewer/scene/model/SceneModelEntity.js +478 -0
  226. package/src/viewer/scene/model/SceneModelMesh.js +160 -0
  227. package/src/viewer/scene/model/SceneModelTexture.js +17 -0
  228. package/src/viewer/scene/model/SceneModelTextureSet.js +17 -0
  229. package/src/viewer/scene/model/VBOSceneModel.js +26 -0
  230. package/src/viewer/scene/model/compression.js +227 -0
  231. package/src/viewer/scene/model/dtx/triangles/BindableDataTexture.js +31 -0
  232. package/src/viewer/scene/model/dtx/triangles/DataTextureGenerator.js +631 -0
  233. package/src/viewer/scene/model/dtx/triangles/DataTextureState.js +288 -0
  234. package/src/viewer/scene/model/dtx/triangles/TrianglesDataTextureBuffer.js +31 -0
  235. package/src/viewer/scene/model/dtx/triangles/TrianglesDataTextureLayer.js +1329 -0
  236. package/src/viewer/scene/model/dtx/triangles/TrianglesDataTextureRenderers.js +278 -0
  237. package/src/viewer/scene/model/dtx/triangles/calculateUniquePositions.js +126 -0
  238. package/src/viewer/scene/model/dtx/triangles/dataTextureRamStats.js +54 -0
  239. package/src/viewer/scene/model/dtx/triangles/rebucketPositions.js +347 -0
  240. package/src/viewer/scene/model/dtx/triangles/renderers/TrianglesDataTextureColorRenderer.js +633 -0
  241. package/src/viewer/scene/model/dtx/triangles/renderers/TrianglesDataTextureDepthRenderer.js +475 -0
  242. package/src/viewer/scene/model/dtx/triangles/renderers/TrianglesDataTextureEdgesColorRenderer.js +426 -0
  243. package/src/viewer/scene/model/dtx/triangles/renderers/TrianglesDataTextureEdgesRenderer.js +430 -0
  244. package/src/viewer/scene/model/dtx/triangles/renderers/TrianglesDataTextureNormalsRenderer.js +341 -0
  245. package/src/viewer/scene/model/dtx/triangles/renderers/TrianglesDataTextureOcclusionRenderer.js +442 -0
  246. package/src/viewer/scene/model/dtx/triangles/renderers/TrianglesDataTexturePickDepthRenderer.js +451 -0
  247. package/src/viewer/scene/model/dtx/triangles/renderers/TrianglesDataTexturePickMeshRenderer.js +436 -0
  248. package/src/viewer/scene/model/dtx/triangles/renderers/TrianglesDataTexturePickNormalsFlatRenderer.js +502 -0
  249. package/src/viewer/scene/model/dtx/triangles/renderers/TrianglesDataTexturePickNormalsRenderer.js +430 -0
  250. package/src/viewer/scene/model/dtx/triangles/renderers/TrianglesDataTextureSilhouetteRenderer.js +469 -0
  251. package/src/viewer/scene/model/dtx/triangles/renderers/TrianglesDataTextureSnapDepthBufInitRenderer.js +451 -0
  252. package/src/viewer/scene/model/dtx/triangles/renderers/TrianglesDataTextureSnapDepthRenderer.js +424 -0
  253. package/src/viewer/scene/model/index.js +3 -0
  254. package/src/viewer/scene/model/vbo/ScratchMemory.js +63 -0
  255. package/src/viewer/scene/model/vbo/VBOSceneModelRenderers.js +805 -0
  256. package/src/viewer/scene/model/vbo/float16.js +760 -0
  257. package/src/viewer/scene/model/vbo/linesBatching/LinesBatchingBuffer.js +21 -0
  258. package/src/viewer/scene/model/vbo/linesBatching/LinesBatchingLayer.js +744 -0
  259. package/src/viewer/scene/model/vbo/linesBatching/LinesBatchingRenderers.js +71 -0
  260. package/src/viewer/scene/model/vbo/linesBatching/renderers/LinesBatchingColorRenderer.js +116 -0
  261. package/src/viewer/scene/model/vbo/linesBatching/renderers/LinesBatchingSilhouetteRenderer.js +126 -0
  262. package/src/viewer/scene/model/vbo/linesInstancing/LinesInstancingLayer.js +653 -0
  263. package/src/viewer/scene/model/vbo/linesInstancing/LinesInstancingRenderers.js +71 -0
  264. package/src/viewer/scene/model/vbo/linesInstancing/renderers/LinesInstancingColorRenderer.js +150 -0
  265. package/src/viewer/scene/model/vbo/linesInstancing/renderers/LinesInstancingSilhouetteRenderer.js +128 -0
  266. package/src/viewer/scene/model/vbo/pointsBatching/PointsBatchingBuffer.js +22 -0
  267. package/src/viewer/scene/model/vbo/pointsBatching/PointsBatchingLayer.js +753 -0
  268. package/src/viewer/scene/model/vbo/pointsBatching/PointsBatchingRenderers.js +116 -0
  269. package/src/viewer/scene/model/vbo/pointsBatching/renderers/PointsBatchingColorRenderer.js +167 -0
  270. package/src/viewer/scene/model/vbo/pointsBatching/renderers/PointsBatchingOcclusionRenderer.js +135 -0
  271. package/src/viewer/scene/model/vbo/pointsBatching/renderers/PointsBatchingPickDepthRenderer.js +154 -0
  272. package/src/viewer/scene/model/vbo/pointsBatching/renderers/PointsBatchingPickMeshRenderer.js +146 -0
  273. package/src/viewer/scene/model/vbo/pointsBatching/renderers/PointsBatchingShadowRenderer.js +108 -0
  274. package/src/viewer/scene/model/vbo/pointsBatching/renderers/PointsBatchingSilhouetteRenderer.js +147 -0
  275. package/src/viewer/scene/model/vbo/pointsInstancing/PointsInstancingLayer.js +684 -0
  276. package/src/viewer/scene/model/vbo/pointsInstancing/PointsInstancingRenderers.js +146 -0
  277. package/src/viewer/scene/model/vbo/pointsInstancing/renderers/PointsInstancingColorRenderer.js +174 -0
  278. package/src/viewer/scene/model/vbo/pointsInstancing/renderers/PointsInstancingDepthRenderer.js +156 -0
  279. package/src/viewer/scene/model/vbo/pointsInstancing/renderers/PointsInstancingOcclusionRenderer.js +151 -0
  280. package/src/viewer/scene/model/vbo/pointsInstancing/renderers/PointsInstancingPickDepthRenderer.js +167 -0
  281. package/src/viewer/scene/model/vbo/pointsInstancing/renderers/PointsInstancingPickMeshRenderer.js +151 -0
  282. package/src/viewer/scene/model/vbo/pointsInstancing/renderers/PointsInstancingShadowRenderer.js +121 -0
  283. package/src/viewer/scene/model/vbo/pointsInstancing/renderers/PointsInstancingSilhouetteRenderer.js +156 -0
  284. package/src/viewer/scene/model/vbo/snapBatching/SnapBatchingDepthBufInitRenderer.js +351 -0
  285. package/src/viewer/scene/model/vbo/snapBatching/SnapBatchingDepthRenderer.js +365 -0
  286. package/src/viewer/scene/model/vbo/snapBatching/SnapBatchingRenderers.js +71 -0
  287. package/src/viewer/scene/model/vbo/snapInstancing/SnapInstancingDepthBufInitRenderer.js +381 -0
  288. package/src/viewer/scene/model/vbo/snapInstancing/SnapInstancingDepthRenderer.js +374 -0
  289. package/src/viewer/scene/model/vbo/snapInstancing/SnapInstancingRenderers.js +71 -0
  290. package/src/viewer/scene/model/vbo/trianglesBatching/TrianglesBatchingBuffer.js +26 -0
  291. package/src/viewer/scene/model/vbo/trianglesBatching/TrianglesBatchingLayer.js +1322 -0
  292. package/src/viewer/scene/model/vbo/trianglesBatching/TrianglesBatchingRenderers.js +322 -0
  293. package/src/viewer/scene/model/vbo/trianglesBatching/renderers/TrianglesBatchingColorRenderer.js +240 -0
  294. package/src/viewer/scene/model/vbo/trianglesBatching/renderers/TrianglesBatchingColorTextureRenderer.js +271 -0
  295. package/src/viewer/scene/model/vbo/trianglesBatching/renderers/TrianglesBatchingDepthRenderer.js +127 -0
  296. package/src/viewer/scene/model/vbo/trianglesBatching/renderers/TrianglesBatchingEdgesColorRenderer.js +129 -0
  297. package/src/viewer/scene/model/vbo/trianglesBatching/renderers/TrianglesBatchingEdgesRenderer.js +134 -0
  298. package/src/viewer/scene/model/vbo/trianglesBatching/renderers/TrianglesBatchingFlatColorRenderer.js +237 -0
  299. package/src/viewer/scene/model/vbo/trianglesBatching/renderers/TrianglesBatchingNormalsRenderer.js +139 -0
  300. package/src/viewer/scene/model/vbo/trianglesBatching/renderers/TrianglesBatchingOcclusionRenderer.js +127 -0
  301. package/src/viewer/scene/model/vbo/trianglesBatching/renderers/TrianglesBatchingPBRRenderer.js +563 -0
  302. package/src/viewer/scene/model/vbo/trianglesBatching/renderers/TrianglesBatchingPickDepthRenderer.js +143 -0
  303. package/src/viewer/scene/model/vbo/trianglesBatching/renderers/TrianglesBatchingPickMeshRenderer.js +130 -0
  304. package/src/viewer/scene/model/vbo/trianglesBatching/renderers/TrianglesBatchingPickNormalsFlatRenderer.js +119 -0
  305. package/src/viewer/scene/model/vbo/trianglesBatching/renderers/TrianglesBatchingPickNormalsRenderer.js +129 -0
  306. package/src/viewer/scene/model/vbo/trianglesBatching/renderers/TrianglesBatchingShadowRenderer.js +108 -0
  307. package/src/viewer/scene/model/vbo/trianglesBatching/renderers/TrianglesBatchingSilhouetteRenderer.js +137 -0
  308. package/src/viewer/scene/model/vbo/trianglesInstancing/TrianglesInstancingLayer.js +1167 -0
  309. package/src/viewer/scene/model/vbo/trianglesInstancing/TrianglesInstancingRenderers.js +322 -0
  310. package/src/viewer/scene/model/vbo/trianglesInstancing/renderers/TrianglesInstancingColorRenderer.js +253 -0
  311. package/src/viewer/scene/model/vbo/trianglesInstancing/renderers/TrianglesInstancingColorTextureRenderer.js +278 -0
  312. package/src/viewer/scene/model/vbo/trianglesInstancing/renderers/TrianglesInstancingDepthRenderer.js +125 -0
  313. package/src/viewer/scene/model/vbo/trianglesInstancing/renderers/TrianglesInstancingEdgesColorRenderer.js +131 -0
  314. package/src/viewer/scene/model/vbo/trianglesInstancing/renderers/TrianglesInstancingEdgesRenderer.js +134 -0
  315. package/src/viewer/scene/model/vbo/trianglesInstancing/renderers/TrianglesInstancingFlatColorRenderer.js +244 -0
  316. package/src/viewer/scene/model/vbo/trianglesInstancing/renderers/TrianglesInstancingFlatNormalsRenderer.js +130 -0
  317. package/src/viewer/scene/model/vbo/trianglesInstancing/renderers/TrianglesInstancingNormalsRenderer.js +140 -0
  318. package/src/viewer/scene/model/vbo/trianglesInstancing/renderers/TrianglesInstancingOcclusionRenderer.js +130 -0
  319. package/src/viewer/scene/model/vbo/trianglesInstancing/renderers/TrianglesInstancingPBRRenderer.js +563 -0
  320. package/src/viewer/scene/model/vbo/trianglesInstancing/renderers/TrianglesInstancingPickDepthRenderer.js +148 -0
  321. package/src/viewer/scene/model/vbo/trianglesInstancing/renderers/TrianglesInstancingPickMeshRenderer.js +135 -0
  322. package/src/viewer/scene/model/vbo/trianglesInstancing/renderers/TrianglesInstancingPickNormalsFlatRenderer.js +130 -0
  323. package/src/viewer/scene/model/vbo/trianglesInstancing/renderers/TrianglesInstancingPickNormalsRenderer.js +144 -0
  324. package/src/viewer/scene/model/vbo/trianglesInstancing/renderers/TrianglesInstancingShadowRenderer.js +113 -0
  325. package/src/viewer/scene/model/vbo/trianglesInstancing/renderers/TrianglesInstancingSilhouetteRenderer.js +141 -0
  326. package/src/viewer/scene/nodes/Node.js +1383 -0
  327. package/src/viewer/scene/nodes/index.js +1 -0
  328. package/src/viewer/scene/paths/CubicBezierCurve.js +194 -0
  329. package/src/viewer/scene/paths/Curve.js +183 -0
  330. package/src/viewer/scene/paths/Path.js +239 -0
  331. package/src/viewer/scene/paths/QuadraticBezierCurve.js +161 -0
  332. package/src/viewer/scene/paths/SplineCurve.js +133 -0
  333. package/src/viewer/scene/paths/index.js +5 -0
  334. package/src/viewer/scene/postfx/SAO.js +543 -0
  335. package/src/viewer/scene/scene/Scene.js +2627 -0
  336. package/src/viewer/scene/sectionPlane/SectionPlane.js +194 -0
  337. package/src/viewer/scene/sectionPlane/index.js +1 -0
  338. package/src/viewer/scene/skybox/Skybox.js +123 -0
  339. package/src/viewer/scene/skybox/index.js +1 -0
  340. package/src/viewer/scene/stats.js +44 -0
  341. package/src/viewer/scene/utils/Cache.js +29 -0
  342. package/src/viewer/scene/utils/FileLoader.js +160 -0
  343. package/src/viewer/scene/utils/Loader.js +55 -0
  344. package/src/viewer/scene/utils/LoadingManager.js +86 -0
  345. package/src/viewer/scene/utils/Map.js +45 -0
  346. package/src/viewer/scene/utils/Queue.js +56 -0
  347. package/src/viewer/scene/utils/WorkerPool.js +73 -0
  348. package/src/viewer/scene/utils/index.js +6 -0
  349. package/src/viewer/scene/utils/textureTranscoders/KTX2TextureTranscoder/KTX2TextureTranscoder.js +650 -0
  350. package/src/viewer/scene/utils/textureTranscoders/KTX2TextureTranscoder/index.js +1 -0
  351. package/src/viewer/scene/utils/textureTranscoders/TextureTranscoder.js +31 -0
  352. package/src/viewer/scene/utils/textureTranscoders/index.js +2 -0
  353. package/src/viewer/scene/utils.js +452 -0
  354. package/src/viewer/scene/vfc/VFC.js +82 -0
  355. package/src/viewer/scene/vfc/VFCManager.js +54 -0
  356. package/src/viewer/scene/vfc/VFCState.js +391 -0
  357. package/src/viewer/scene/vfc/cluster-helper.js +134 -0
  358. package/src/viewer/scene/vfc/index.js +1 -0
  359. package/src/viewer/scene/vfc/rbush3d.js +848 -0
  360. package/src/viewer/scene/vfc/xeokit-cluster.js +418 -0
  361. package/src/viewer/scene/viewport/Viewport.js +212 -0
  362. package/src/viewer/scene/webgl/ArrayBuf.js +121 -0
  363. package/src/viewer/scene/webgl/Attribute.js +23 -0
  364. package/src/viewer/scene/webgl/Drawable.js +270 -0
  365. package/src/viewer/scene/webgl/FrameContext.js +313 -0
  366. package/src/viewer/scene/webgl/PickResult.js +339 -0
  367. package/src/viewer/scene/webgl/Pickable.js +69 -0
  368. package/src/viewer/scene/webgl/Program.js +181 -0
  369. package/src/viewer/scene/webgl/RenderBuffer.js +350 -0
  370. package/src/viewer/scene/webgl/RenderBufferManager.js +34 -0
  371. package/src/viewer/scene/webgl/RenderFlags.js +203 -0
  372. package/src/viewer/scene/webgl/RenderState.js +40 -0
  373. package/src/viewer/scene/webgl/Renderer.js +1654 -0
  374. package/src/viewer/scene/webgl/Sampler.js +18 -0
  375. package/src/viewer/scene/webgl/Shader.js +49 -0
  376. package/src/viewer/scene/webgl/Texture2D.js +442 -0
  377. package/src/viewer/scene/webgl/convertConstant.js +244 -0
  378. package/src/viewer/scene/webgl/getExtension.js +32 -0
  379. package/src/viewer/scene/webgl/occlusion/OcclusionLayer.js +214 -0
  380. package/src/viewer/scene/webgl/occlusion/OcclusionTester.js +426 -0
  381. package/src/viewer/scene/webgl/sao/SAODepthLimitedBlurRenderer.js +324 -0
  382. package/src/viewer/scene/webgl/sao/SAOOcclusionRenderer.js +376 -0
  383. package/src/viewer/scene/webgl/webglEnums.js +61 -0
  384. package/src/viewer/scene/webglInfo.js +47 -0
@@ -0,0 +1,3817 @@
1
+ import {Component} from "../Component.js";
2
+ import {math} from "../math/math.js";
3
+ import {buildEdgeIndices} from '../math/buildEdgeIndices.js';
4
+ import {SceneModelMesh} from './SceneModelMesh.js';
5
+ import {getScratchMemory, putScratchMemory} from "./vbo/ScratchMemory.js";
6
+ import {TrianglesBatchingLayer} from './vbo/trianglesBatching/TrianglesBatchingLayer.js';
7
+ import {TrianglesInstancingLayer} from './vbo/trianglesInstancing/TrianglesInstancingLayer.js';
8
+ import {LinesBatchingLayer} from './vbo/linesBatching/LinesBatchingLayer.js';
9
+ import {LinesInstancingLayer} from './vbo/linesInstancing/LinesInstancingLayer.js';
10
+ import {PointsBatchingLayer} from './vbo/pointsBatching/PointsBatchingLayer.js';
11
+ import {PointsInstancingLayer} from './vbo/pointsInstancing/PointsInstancingLayer.js';
12
+ import {ENTITY_FLAGS} from './ENTITY_FLAGS.js';
13
+ import {RenderFlags} from "../webgl/RenderFlags.js";
14
+ import {worldToRTCPositions} from "../math/rtcCoords.js";
15
+ import {SceneModelTextureSet} from "./SceneModelTextureSet.js";
16
+ import {SceneModelTexture} from "./SceneModelTexture.js";
17
+ import {Texture2D} from "../webgl/Texture2D.js";
18
+ import {utils} from "../utils.js";
19
+ import {getKTX2TextureTranscoder} from "../utils/textureTranscoders/KTX2TextureTranscoder/KTX2TextureTranscoder.js";
20
+ import {
21
+ ClampToEdgeWrapping,
22
+ LinearEncoding,
23
+ LinearFilter,
24
+ LinearMipmapLinearFilter,
25
+ LinearMipMapNearestFilter,
26
+ MirroredRepeatWrapping,
27
+ NearestFilter,
28
+ NearestMipMapLinearFilter,
29
+ NearestMipMapNearestFilter,
30
+ RepeatWrapping,
31
+ sRGBEncoding
32
+ } from "../constants/constants.js";
33
+ import {createPositionsDecodeMatrix, quantizePositions} from "./compression.js";
34
+ import {uniquifyPositions} from "./dtx/triangles/calculateUniquePositions";
35
+ import {rebucketPositions} from "./dtx/triangles/rebucketPositions";
36
+ import {TrianglesDataTextureLayer} from "./dtx/triangles/TrianglesDataTextureLayer";
37
+ import {SceneModelEntity} from "./SceneModelEntity";
38
+ import {geometryCompressionUtils} from "../math/geometryCompressionUtils";
39
+
40
+ const tempVec3a = math.vec3();
41
+ const tempMat4 = math.mat4();
42
+
43
+ const DEFAULT_SCALE = math.vec3([1, 1, 1]);
44
+ const DEFAULT_POSITION = math.vec3([0, 0, 0]);
45
+ const DEFAULT_ROTATION = math.vec3([0, 0, 0]);
46
+ const DEFAULT_QUATERNION = math.identityQuaternion();
47
+ const DEFAULT_MATRIX = math.identityMat4();
48
+
49
+ const DEFAULT_COLOR_TEXTURE_ID = "defaultColorTexture";
50
+ const DEFAULT_METAL_ROUGH_TEXTURE_ID = "defaultMetalRoughTexture";
51
+ const DEFAULT_NORMALS_TEXTURE_ID = "defaultNormalsTexture";
52
+ const DEFAULT_EMISSIVE_TEXTURE_ID = "defaultEmissiveTexture";
53
+ const DEFAULT_OCCLUSION_TEXTURE_ID = "defaultOcclusionTexture";
54
+ const DEFAULT_TEXTURE_SET_ID = "defaultTextureSet";
55
+
56
+ const defaultCompressedColor = new Uint8Array([255, 255, 255]);
57
+
58
+ const VBO_INSTANCED = 0;
59
+ const VBO_BATCHED = 1;
60
+ const DTX = 2;
61
+
62
+ /**
63
+ * @desc A high-performance model representation for efficient rendering and low memory usage.
64
+ *
65
+ * # Examples
66
+ *
67
+ * Internally, SceneModel uses a combination of several different techniques to render and represent
68
+ * the different parts of a typical model. Each of the live examples at these links is designed to "unit test" one of these
69
+ * techniques, in isolation. If some bug occurs in SceneModel, we use these tests to debug, but they also
70
+ * serve to demonstrate how to use the capabilities of SceneModel programmatically.
71
+ *
72
+ * * [Loading building models into SceneModels](/examples/buildings)
73
+ * * [Loading city models into SceneModels](/examples/cities)
74
+ * * [Loading LiDAR scans into SceneModels](/examples/lidar)
75
+ * * [Loading CAD models into SceneModels](/examples/cad)
76
+ * * [SceneModel feature tests](/examples/scenemodel)
77
+ *
78
+ * # Overview
79
+ *
80
+ * While xeokit's standard [scene graph](https://github.com/xeokit/xeokit-sdk/wiki/Scene-Graphs) is great for gizmos and medium-sized models, it doesn't scale up to millions of objects in terms of memory and rendering efficiency.
81
+ *
82
+ * For huge models, we have the ````SceneModel```` representation, which is optimized to pack large amounts of geometry into memory and render it efficiently using WebGL.
83
+ *
84
+ * ````SceneModel```` is the default model representation loaded by (at least) {@link GLTFLoaderPlugin}, {@link XKTLoaderPlugin} and {@link WebIFCLoaderPlugin}.
85
+ *
86
+ * In this tutorial you'll learn how to use ````SceneModel```` to create high-detail content programmatically. Ordinarily you'd be learning about ````SceneModel```` if you were writing your own model loader plugins.
87
+ *
88
+ * # Contents
89
+ *
90
+ * - [SceneModel](#DataTextureSceneModel)
91
+ * - [GPU-Resident Geometry](#gpu-resident-geometry)
92
+ * - [Picking](#picking)
93
+ * - [Example 1: Geometry Instancing](#example-1--geometry-instancing)
94
+ * - [Finalizing a SceneModel](#finalizing-a-DataTextureSceneModel)
95
+ * - [Finding Entities](#finding-entities)
96
+ * - [Example 2: Geometry Batching](#example-2--geometry-batching)
97
+ * - [Classifying with Metadata](#classifying-with-metadata)
98
+ * - [Querying Metadata](#querying-metadata)
99
+ * - [Metadata Structure](#metadata-structure)
100
+ * - [RTC Coordinates](#rtc-coordinates-for-double-precision)
101
+ * - [Example 3: RTC Coordinates with Geometry Instancing](#example-2--rtc-coordinates-with-geometry-instancing)
102
+ * - [Example 4: RTC Coordinates with Geometry Batching](#example-2--rtc-coordinates-with-geometry-batching)
103
+ *
104
+ * ## SceneModel
105
+ *
106
+ * ````SceneModel```` uses two rendering techniques internally:
107
+ *
108
+ * 1. ***Geometry batching*** for unique geometries, combining those into a single WebGL geometry buffer, to render in one draw call, and
109
+ * 2. ***geometry instancing*** for geometries that are shared by multiple meshes, rendering all instances of each shared geometry in one draw call.
110
+ *
111
+ * <br>
112
+ * These techniques come with certain limitations:
113
+ *
114
+ * * Non-realistic rendering - while scene graphs can use xeokit's full set of material workflows, ````SceneModel```` uses simple Lambertian shading without textures.
115
+ * * Static transforms - transforms within a ````SceneModel```` are static and cannot be dynamically translated, rotated and scaled the way {@link Node}s and {@link Mesh}es in scene graphs can.
116
+ * * Immutable model representation - while scene graph {@link Node}s and
117
+ * {@link Mesh}es can be dynamically plugged together, ````SceneModel```` is immutable,
118
+ * since it packs its geometries into buffers and instanced arrays.
119
+ *
120
+ * ````SceneModel````'s API allows us to exploit batching and instancing, while exposing its elements as
121
+ * abstract {@link Entity} types.
122
+ *
123
+ * {@link Entity} is the abstract base class for
124
+ * the various xeokit components that represent models, objects, or anonymous visible elements. An Entity has a unique ID and can be
125
+ * individually shown, hidden, selected, highlighted, ghosted, culled, picked and clipped, and has its own World-space boundary.
126
+ *
127
+ * * A ````SceneModel```` is an {@link Entity} that represents a model.
128
+ * * A ````SceneModel```` represents each of its objects with an {@link Entity}.
129
+ * * Each {@link Entity} has one or more meshes that define its shape.
130
+ * * Each mesh has either its own unique geometry, or shares a geometry with other meshes.
131
+ *
132
+ * ## GPU-Resident Geometry
133
+ *
134
+ * For a low memory footprint, ````SceneModel```` stores its geometries in GPU memory only, compressed (quantized) as integers. Unfortunately, GPU-resident geometry is
135
+ * not readable by JavaScript.
136
+ *
137
+ *
138
+ * ## Example 1: Geometry Instancing
139
+ *
140
+ * In the example below, we'll use a ````SceneModel````
141
+ * to build a simple table model using geometry instancing.
142
+ *
143
+ * We'll start by adding a reusable box-shaped geometry to our ````SceneModel````.
144
+ *
145
+ * Then, for each object in our model we'll add an {@link Entity}
146
+ * that has a mesh that instances our box geometry, transforming and coloring the instance.
147
+ *
148
+ * [![](http://xeokit.io/img/docs/sceneGraph.png)](https://xeokit.github.io/xeokit-sdk/examples/#sceneRepresentation_SceneModel_instancing)
149
+ *
150
+ * ````javascript
151
+ * import {Viewer, SceneModel} from "xeokit-sdk.es.js";
152
+ *
153
+ * const viewer = new Viewer({
154
+ * canvasId: "myCanvas",
155
+ * transparent: true
156
+ * });
157
+ *
158
+ * viewer.scene.camera.eye = [-21.80, 4.01, 6.56];
159
+ * viewer.scene.camera.look = [0, -5.75, 0];
160
+ * viewer.scene.camera.up = [0.37, 0.91, -0.11];
161
+ *
162
+ * // Build a SceneModel representing a table
163
+ * // with four legs, using geometry instancing
164
+ *
165
+ * const sceneModel = new SceneModel(viewer.scene, {
166
+ * id: "table",
167
+ * isModel: true, // <--- Registers SceneModel in viewer.scene.models
168
+ * position: [0, 0, 0],
169
+ * scale: [1, 1, 1],
170
+ * rotation: [0, 0, 0]
171
+ * });
172
+ *
173
+ * // Create a reusable geometry within the SceneModel
174
+ * // We'll instance this geometry by five meshes
175
+ *
176
+ * sceneModel.createGeometry({
177
+ *
178
+ * id: "myBoxGeometry",
179
+ *
180
+ * // The primitive type - allowed values are "points", "lines" and "triangles".
181
+ * // See the OpenGL/WebGL specification docs
182
+ * // for how the coordinate arrays are supposed to be laid out.
183
+ * primitive: "triangles",
184
+ *
185
+ * // The vertices - eight for our cube, each
186
+ * // one spanning three array elements for X,Y and Z
187
+ * positions: [
188
+ * 1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, // v0-v1-v2-v3 front
189
+ * 1, 1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, // v0-v3-v4-v1 right
190
+ * 1, 1, 1, 1, 1, -1, -1, 1, -1, -1, 1, 1, // v0-v1-v6-v1 top
191
+ * -1, 1, 1, -1, 1, -1, -1, -1, -1, -1, -1, 1, // v1-v6-v7-v2 left
192
+ * -1, -1, -1, 1, -1, -1, 1, -1, 1, -1, -1, 1, // v7-v4-v3-v2 bottom
193
+ * 1, -1, -1, -1, -1, -1, -1, 1, -1, 1, 1, -1 // v4-v7-v6-v1 back
194
+ * ],
195
+ *
196
+ * // Normal vectors, one for each vertex
197
+ * normals: [
198
+ * 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, // v0-v1-v2-v3 front
199
+ * 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, // v0-v3-v4-v5 right
200
+ * 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, // v0-v5-v6-v1 top
201
+ * -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, // v1-v6-v7-v2 left
202
+ * 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, // v7-v4-v3-v2 bottom
203
+ * 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1 // v4-v7-v6-v5 back
204
+ * ],
205
+ *
206
+ * // Indices - these organise the positions and and normals
207
+ * // into geometric primitives in accordance with the "primitive" parameter,
208
+ * // in this case a set of three indices for each triangle.
209
+ * //
210
+ * // Note that each triangle is specified in counter-clockwise winding order.
211
+ * //
212
+ * indices: [
213
+ * 0, 1, 2, 0, 2, 3, // front
214
+ * 4, 5, 6, 4, 6, 7, // right
215
+ * 8, 9, 10, 8, 10, 11, // top
216
+ * 12, 13, 14, 12, 14, 15, // left
217
+ * 16, 17, 18, 16, 18, 19, // bottom
218
+ * 20, 21, 22, 20, 22, 23
219
+ * ]
220
+ * });
221
+ *
222
+ * // Red table leg
223
+ *
224
+ * sceneModel.createMesh({
225
+ * id: "redLegMesh",
226
+ * geometryId: "myBoxGeometry",
227
+ * position: [-4, -6, -4],
228
+ * scale: [1, 3, 1],
229
+ * rotation: [0, 0, 0],
230
+ * color: [1, 0.3, 0.3]
231
+ * });
232
+ *
233
+ * sceneModel.createEntity({
234
+ * id: "redLeg",
235
+ * meshIds: ["redLegMesh"],
236
+ * isObject: true // <---- Registers Entity by ID on viewer.scene.objects
237
+ * });
238
+ *
239
+ * // Green table leg
240
+ *
241
+ * sceneModel.createMesh({
242
+ * id: "greenLegMesh",
243
+ * geometryId: "myBoxGeometry",
244
+ * position: [4, -6, -4],
245
+ * scale: [1, 3, 1],
246
+ * rotation: [0, 0, 0],
247
+ * color: [0.3, 1.0, 0.3]
248
+ * });
249
+ *
250
+ * sceneModel.createEntity({
251
+ * id: "greenLeg",
252
+ * meshIds: ["greenLegMesh"],
253
+ * isObject: true // <---- Registers Entity by ID on viewer.scene.objects
254
+ * });
255
+ *
256
+ * // Blue table leg
257
+ *
258
+ * sceneModel.createMesh({
259
+ * id: "blueLegMesh",
260
+ * geometryId: "myBoxGeometry",
261
+ * position: [4, -6, 4],
262
+ * scale: [1, 3, 1],
263
+ * rotation: [0, 0, 0],
264
+ * color: [0.3, 0.3, 1.0]
265
+ * });
266
+ *
267
+ * sceneModel.createEntity({
268
+ * id: "blueLeg",
269
+ * meshIds: ["blueLegMesh"],
270
+ * isObject: true // <---- Registers Entity by ID on viewer.scene.objects
271
+ * });
272
+ *
273
+ * // Yellow table leg
274
+ *
275
+ * sceneModel.createMesh({
276
+ * id: "yellowLegMesh",
277
+ * geometryId: "myBoxGeometry",
278
+ * position: [-4, -6, 4],
279
+ * scale: [1, 3, 1],
280
+ * rotation: [0, 0, 0],
281
+ * color: [1.0, 1.0, 0.0]
282
+ * });
283
+ *
284
+ * sceneModel.createEntity({
285
+ * id: "yellowLeg",
286
+ * meshIds: ["yellowLegMesh"],
287
+ * isObject: true // <---- Registers Entity by ID on viewer.scene.objects
288
+ * });
289
+ *
290
+ * // Purple table top
291
+ *
292
+ * sceneModel.createMesh({
293
+ * id: "purpleTableTopMesh",
294
+ * geometryId: "myBoxGeometry",
295
+ * position: [0, -3, 0],
296
+ * scale: [6, 0.5, 6],
297
+ * rotation: [0, 0, 0],
298
+ * color: [1.0, 0.3, 1.0]
299
+ * });
300
+ *
301
+ * sceneModel.createEntity({
302
+ * id: "purpleTableTop",
303
+ * meshIds: ["purpleTableTopMesh"],
304
+ * isObject: true // <---- Registers Entity by ID on viewer.scene.objects
305
+ * });
306
+ * ````
307
+ *
308
+ * ## Finalizing a SceneModel
309
+ *
310
+ * Before we can view and interact with our ````SceneModel````, we need to **finalize** it. Internally, this causes the ````SceneModel```` to build the
311
+ * vertex buffer objects (VBOs) that support our geometry instances. When using geometry batching (see next example),
312
+ * this causes ````SceneModel```` to build the VBOs that combine the batched geometries. Note that you can do both instancing and
313
+ * batching within the same ````SceneModel````.
314
+ *
315
+ * Once finalized, we can't add anything more to our ````SceneModel````.
316
+ *
317
+ * ```` javascript
318
+ * SceneModel.finalize();
319
+ * ````
320
+ *
321
+ * ## Finding Entities
322
+ *
323
+ * As mentioned earlier, {@link Entity} is
324
+ * the abstract base class for components that represent models, objects, or just
325
+ * anonymous visible elements.
326
+ *
327
+ * Since we created configured our ````SceneModel```` with ````isModel: true````,
328
+ * we're able to find it as an Entity by ID in ````viewer.scene.models````. Likewise, since
329
+ * we configured each of its Entities with ````isObject: true````, we're able to
330
+ * find them in ````viewer.scene.objects````.
331
+ *
332
+ *
333
+ * ````javascript
334
+ * // Get the whole table model Entity
335
+ * const table = viewer.scene.models["table"];
336
+ *
337
+ * // Get some leg object Entities
338
+ * const redLeg = viewer.scene.objects["redLeg"];
339
+ * const greenLeg = viewer.scene.objects["greenLeg"];
340
+ * const blueLeg = viewer.scene.objects["blueLeg"];
341
+ * ````
342
+ *
343
+ * ## Example 2: Geometry Batching
344
+ *
345
+ * Let's once more use a ````SceneModel````
346
+ * to build the simple table model, this time exploiting geometry batching.
347
+ *
348
+ * [![](http://xeokit.io/img/docs/sceneGraph.png)](https://xeokit.github.io/xeokit-sdk/examples/#sceneRepresentation_SceneModel_batching)
349
+ *
350
+ * ````javascript
351
+ * import {Viewer, SceneModel} from "xeokit-sdk.es.js";
352
+ *
353
+ * const viewer = new Viewer({
354
+ * canvasId: "myCanvas",
355
+ * transparent: true
356
+ * });
357
+ *
358
+ * viewer.scene.camera.eye = [-21.80, 4.01, 6.56];
359
+ * viewer.scene.camera.look = [0, -5.75, 0];
360
+ * viewer.scene.camera.up = [0.37, 0.91, -0.11];
361
+ *
362
+ * // Create a SceneModel representing a table with four legs, using geometry batching
363
+ * const sceneModel = new SceneModel(viewer.scene, {
364
+ * id: "table",
365
+ * isModel: true, // <--- Registers SceneModel in viewer.scene.models
366
+ * position: [0, 0, 0],
367
+ * scale: [1, 1, 1],
368
+ * rotation: [0, 0, 0]
369
+ * });
370
+ *
371
+ * // Red table leg
372
+ *
373
+ * sceneModel.createMesh({
374
+ * id: "redLegMesh",
375
+ *
376
+ * // Geometry arrays are same as for the earlier batching example
377
+ * primitive: "triangles",
378
+ * positions: [ 1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1 ... ],
379
+ * normals: [ 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, ... ],
380
+ * indices: [ 0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7, ... ],
381
+ * position: [-4, -6, -4],
382
+ * scale: [1, 3, 1],
383
+ * rotation: [0, 0, 0],
384
+ * color: [1, 0.3, 0.3]
385
+ * });
386
+ *
387
+ * sceneModel.createEntity({
388
+ * id: "redLeg",
389
+ * meshIds: ["redLegMesh"],
390
+ * isObject: true // <---- Registers Entity by ID on viewer.scene.objects
391
+ * });
392
+ *
393
+ * // Green table leg
394
+ *
395
+ * sceneModel.createMesh({
396
+ * id: "greenLegMesh",
397
+ * primitive: "triangles",
398
+ * primitive: "triangles",
399
+ * positions: [ 1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1 ... ],
400
+ * normals: [ 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, ... ],
401
+ * indices: [ 0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7, ... ],
402
+ * position: [4, -6, -4],
403
+ * scale: [1, 3, 1],
404
+ * rotation: [0, 0, 0],
405
+ * color: [0.3, 1.0, 0.3]
406
+ * });
407
+ *
408
+ * sceneModel.createEntity({
409
+ * id: "greenLeg",
410
+ * meshIds: ["greenLegMesh"],
411
+ * isObject: true // <---- Registers Entity by ID on viewer.scene.objects
412
+ * });
413
+ *
414
+ * // Blue table leg
415
+ *
416
+ * sceneModel.createMesh({
417
+ * id: "blueLegMesh",
418
+ * primitive: "triangles",
419
+ * positions: [ 1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1 ... ],
420
+ * normals: [ 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, ... ],
421
+ * indices: [ 0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7, ... ],
422
+ * position: [4, -6, 4],
423
+ * scale: [1, 3, 1],
424
+ * rotation: [0, 0, 0],
425
+ * color: [0.3, 0.3, 1.0]
426
+ * });
427
+ *
428
+ * sceneModel.createEntity({
429
+ * id: "blueLeg",
430
+ * meshIds: ["blueLegMesh"],
431
+ * isObject: true // <---- Registers Entity by ID on viewer.scene.objects
432
+ * });
433
+ *
434
+ * // Yellow table leg object
435
+ *
436
+ * sceneModel.createMesh({
437
+ * id: "yellowLegMesh",
438
+ * positions: [ 1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1 ... ],
439
+ * normals: [ 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, ... ],
440
+ * indices: [ 0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7, ... ],
441
+ * position: [-4, -6, 4],
442
+ * scale: [1, 3, 1],
443
+ * rotation: [0, 0, 0],
444
+ * color: [1.0, 1.0, 0.0]
445
+ * });
446
+ *
447
+ * sceneModel.createEntity({
448
+ * id: "yellowLeg",
449
+ * meshIds: ["yellowLegMesh"],
450
+ * isObject: true // <---- Registers Entity by ID on viewer.scene.objects
451
+ * });
452
+ *
453
+ * // Purple table top
454
+ *
455
+ * sceneModel.createMesh({
456
+ * id: "purpleTableTopMesh",
457
+ * positions: [ 1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1 ... ],
458
+ * normals: [ 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, ... ],
459
+ * indices: [ 0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7, ... ],
460
+ * position: [0, -3, 0],
461
+ * scale: [6, 0.5, 6],
462
+ * rotation: [0, 0, 0],
463
+ * color: [1.0, 0.3, 1.0]
464
+ * });
465
+ *
466
+ * sceneModel.createEntity({
467
+ * id: "purpleTableTop",
468
+ * meshIds: ["purpleTableTopMesh"],
469
+ * isObject: true // <---- Registers Entity by ID on viewer.scene.objects
470
+ * });
471
+ *
472
+ * // Finalize the SceneModel.
473
+ *
474
+ * SceneModel.finalize();
475
+ *
476
+ * // Find BigModelNodes by their model and object IDs
477
+ *
478
+ * // Get the whole table model
479
+ * const table = viewer.scene.models["table"];
480
+ *
481
+ * // Get some leg objects
482
+ * const redLeg = viewer.scene.objects["redLeg"];
483
+ * const greenLeg = viewer.scene.objects["greenLeg"];
484
+ * const blueLeg = viewer.scene.objects["blueLeg"];
485
+ * ````
486
+ *
487
+ * ## Classifying with Metadata
488
+ *
489
+ * In the previous examples, we used ````SceneModel```` to build
490
+ * two versions of the same table model, to demonstrate geometry batching and geometry instancing.
491
+ *
492
+ * We'll now classify our {@link Entity}s with metadata. This metadata
493
+ * will work the same for both our examples, since they create the exact same structure of {@link Entity}s
494
+ * to represent their models and objects. The abstract Entity type is, after all, intended to provide an abstract interface through which differently-implemented scene content can be accessed uniformly.
495
+ *
496
+ * To create the metadata, we'll create a {@link MetaModel} for our model,
497
+ * with a {@link MetaObject} for each of it's objects. The MetaModel and MetaObjects
498
+ * get the same IDs as the {@link Entity}s that represent their model and objects within our scene.
499
+ *
500
+ * ```` javascript
501
+ * const furnitureMetaModel = viewer.metaScene.createMetaModel("furniture", { // Creates a MetaModel in the MetaScene
502
+ *
503
+ * "projectId": "myTableProject",
504
+ * "revisionId": "V1.0",
505
+ *
506
+ * "metaObjects": [
507
+ * { // Creates a MetaObject in the MetaModel
508
+ * "id": "table",
509
+ * "name": "Table", // Same ID as an object Entity
510
+ * "type": "furniture", // Arbitrary type, could be IFC type
511
+ * "properties": { // Arbitrary properties, could be IfcPropertySet
512
+ * "cost": "200"
513
+ * }
514
+ * },
515
+ * {
516
+ * "id": "redLeg",
517
+ * "name": "Red table Leg",
518
+ * "type": "leg",
519
+ * "parent": "table", // References first MetaObject as parent
520
+ * "properties": {
521
+ * "material": "wood"
522
+ * }
523
+ * },
524
+ * {
525
+ * "id": "greenLeg", // Node with corresponding id does not need to exist
526
+ * "name": "Green table leg", // and MetaObject does not need to exist for Node with an id
527
+ * "type": "leg",
528
+ * "parent": "table",
529
+ * "properties": {
530
+ * "material": "wood"
531
+ * }
532
+ * },
533
+ * {
534
+ * "id": "blueLeg",
535
+ * "name": "Blue table leg",
536
+ * "type": "leg",
537
+ * "parent": "table",
538
+ * "properties": {
539
+ * "material": "wood"
540
+ * }
541
+ * },
542
+ * {
543
+ * "id": "yellowLeg",
544
+ * "name": "Yellow table leg",
545
+ * "type": "leg",
546
+ * "parent": "table",
547
+ * "properties": {
548
+ * "material": "wood"
549
+ * }
550
+ * },
551
+ * {
552
+ * "id": "tableTop",
553
+ * "name": "Purple table top",
554
+ * "type": "surface",
555
+ * "parent": "table",
556
+ * "properties": {
557
+ * "material": "formica",
558
+ * "width": "60",
559
+ * "depth": "60",
560
+ * "thickness": "5"
561
+ * }
562
+ * }
563
+ * ]
564
+ * });
565
+ * ````
566
+ *
567
+ * ## Querying Metadata
568
+ *
569
+ * Having created and classified our model (either the instancing or batching example), we can now find the {@link MetaModel}
570
+ * and {@link MetaObject}s using the IDs of their
571
+ * corresponding {@link Entity}s.
572
+ *
573
+ * ````JavaScript
574
+ * const furnitureMetaModel = scene.metaScene.metaModels["furniture"];
575
+ *
576
+ * const redLegMetaObject = scene.metaScene.metaObjects["redLeg"];
577
+ * ````
578
+ *
579
+ * In the snippet below, we'll log metadata on each {@link Entity} we click on:
580
+ *
581
+ * ````JavaScript
582
+ * viewer.scene.input.on("mouseclicked", function (coords) {
583
+ *
584
+ * const hit = viewer.scene.pick({
585
+ * canvasPos: coords
586
+ * });
587
+ *
588
+ * if (hit) {
589
+ * const entity = hit.entity;
590
+ * const metaObject = viewer.metaScene.metaObjects[entity.id];
591
+ * if (metaObject) {
592
+ * console.log(JSON.stringify(metaObject.getJSON(), null, "\t"));
593
+ * }
594
+ * }
595
+ * });
596
+ * ````
597
+ *
598
+ * ## Metadata Structure
599
+ *
600
+ * The {@link MetaModel}
601
+ * organizes its {@link MetaObject}s in
602
+ * a tree that describes their structural composition:
603
+ *
604
+ * ````JavaScript
605
+ * // Get metadata on the root object
606
+ * const tableMetaObject = furnitureMetaModel.rootMetaObject;
607
+ *
608
+ * // Get metadata on the leg objects
609
+ * const redLegMetaObject = tableMetaObject.children[0];
610
+ * const greenLegMetaObject = tableMetaObject.children[1];
611
+ * const blueLegMetaObject = tableMetaObject.children[2];
612
+ * const yellowLegMetaObject = tableMetaObject.children[3];
613
+ * ````
614
+ *
615
+ * Given an {@link Entity}, we can find the object or model of which it is a part, or the objects that comprise it. We can also generate UI
616
+ * components from the metadata, such as the tree view demonstrated in [this demo](https://xeokit.github.io/xeokit-sdk/examples/#BIMOffline_glTF_OTCConferenceCenter).
617
+ *
618
+ * This hierarchy allows us to express the hierarchical structure of a model while representing it in
619
+ * various ways in the 3D scene (such as with ````SceneModel````, which
620
+ * has a non-hierarchical scene representation).
621
+ *
622
+ * Note also that a {@link MetaObject} does not need to have a corresponding
623
+ * {@link Entity} and vice-versa.
624
+ *
625
+ * # RTC Coordinates for Double Precision
626
+ *
627
+ * ````SceneModel```` can emulate 64-bit precision on GPUs using relative-to-center (RTC) coordinates.
628
+ *
629
+ * Consider a model that contains many small objects, but with such large spatial extents that 32 bits of GPU precision (accurate to ~7 digits) will not be sufficient to render all of the the objects without jittering.
630
+ *
631
+ * To prevent jittering, we could spatially subdivide the objects into "tiles". Each tile would have a center position, and the positions of the objects within the tile would be relative to that center ("RTC coordinates").
632
+ *
633
+ * While the center positions of the tiles would be 64-bit values, the object positions only need to be 32-bit.
634
+ *
635
+ * Internally, when rendering an object with RTC coordinates, xeokit first temporarily translates the camera viewing matrix by the object's tile's RTC center, on the CPU, using 64-bit math.
636
+ *
637
+ * Then xeokit loads the viewing matrix into its WebGL shaders, where math happens at 32-bit precision. Within the shaders, the matrix is effectively down-cast to 32-bit precision, and the object's 32-bit vertex positions are transformed by the matrix.
638
+ *
639
+ * We see no jittering, because with RTC a detectable loss of GPU accuracy only starts happening to objects as they become very distant from the camera viewpoint, at which point they are too small to be discernible anyway.
640
+ *
641
+ * ## RTC Coordinates with Geometry Instancing
642
+ *
643
+ * To use RTC with ````SceneModel```` geometry instancing, we specify an RTC center for the geometry via its ````origin```` parameter. Then ````SceneModel```` assumes that all meshes that instance that geometry are within the same RTC coordinate system, ie. the meshes ````position```` and ````rotation```` properties are assumed to be relative to the geometry's ````origin````.
644
+ *
645
+ * For simplicity, our example's meshes all instance the same geometry. Therefore, our example model has only one RTC center.
646
+ *
647
+ * Note that the axis-aligned World-space boundary (AABB) of our model is ````[ -6, -9, -6, 1000000006, -2.5, 1000000006]````.
648
+ *
649
+ * [![](http://xeokit.io/img/docs/sceneGraph.png)](https://xeokit.github.io/xeokit-sdk/examples/#sceneRepresentation_SceneModel_batching)
650
+ *
651
+ * ````javascript
652
+ * const origin = [100000000, 0, 100000000];
653
+ *
654
+ * sceneModel.createGeometry({
655
+ * id: "box",
656
+ * primitive: "triangles",
657
+ * positions: [ 1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1 ... ],
658
+ * normals: [ 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, ... ],
659
+ * indices: [ 0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7, ... ],
660
+ * });
661
+ *
662
+ * sceneModel.createMesh({
663
+ * id: "leg1",
664
+ * geometryId: "box",
665
+ * position: [-4, -6, -4],
666
+ * scale: [1, 3, 1],
667
+ * rotation: [0, 0, 0],
668
+ * color: [1, 0.3, 0.3],
669
+ * origin: origin
670
+ * });
671
+ *
672
+ * sceneModel.createEntity({
673
+ * meshIds: ["leg1"],
674
+ * isObject: true
675
+ * });
676
+ *
677
+ * sceneModel.createMesh({
678
+ * id: "leg2",
679
+ * geometryId: "box",
680
+ * position: [4, -6, -4],
681
+ * scale: [1, 3, 1],
682
+ * rotation: [0, 0, 0],
683
+ * color: [0.3, 1.0, 0.3],
684
+ * origin: origin
685
+ * });
686
+ *
687
+ * sceneModel.createEntity({
688
+ * meshIds: ["leg2"],
689
+ * isObject: true
690
+ * });
691
+ *
692
+ * sceneModel.createMesh({
693
+ * id: "leg3",
694
+ * geometryId: "box",
695
+ * position: [4, -6, 4],
696
+ * scale: [1, 3, 1],
697
+ * rotation: [0, 0, 0],
698
+ * color: [0.3, 0.3, 1.0],
699
+ * origin: origin
700
+ * });
701
+ *
702
+ * sceneModel.createEntity({
703
+ * meshIds: ["leg3"],
704
+ * isObject: true
705
+ * });
706
+ *
707
+ * sceneModel.createMesh({
708
+ * id: "leg4",
709
+ * geometryId: "box",
710
+ * position: [-4, -6, 4],
711
+ * scale: [1, 3, 1],
712
+ * rotation: [0, 0, 0],
713
+ * color: [1.0, 1.0, 0.0],
714
+ * origin: origin
715
+ * });
716
+ *
717
+ * sceneModel.createEntity({
718
+ * meshIds: ["leg4"],
719
+ * isObject: true
720
+ * });
721
+ *
722
+ * sceneModel.createMesh({
723
+ * id: "top",
724
+ * geometryId: "box",
725
+ * position: [0, -3, 0],
726
+ * scale: [6, 0.5, 6],
727
+ * rotation: [0, 0, 0],
728
+ * color: [1.0, 0.3, 1.0],
729
+ * origin: origin
730
+ * });
731
+ *
732
+ * sceneModel.createEntity({
733
+ * meshIds: ["top"],
734
+ * isObject: true
735
+ * });
736
+ * ````
737
+ *
738
+ * ## RTC Coordinates with Geometry Batching
739
+ *
740
+ * To use RTC with ````SceneModel```` geometry batching, we specify an RTC center (````origin````) for each mesh. For performance, we try to have as many meshes share the same value for ````origin```` as possible. Each mesh's ````positions````, ````position```` and ````rotation```` properties are assumed to be relative to ````origin````.
741
+ *
742
+ * For simplicity, the meshes in our example all share the same RTC center.
743
+ *
744
+ * The axis-aligned World-space boundary (AABB) of our model is ````[ -6, -9, -6, 1000000006, -2.5, 1000000006]````.
745
+ *
746
+ * [![](http://xeokit.io/img/docs/sceneGraph.png)](https://xeokit.github.io/xeokit-sdk/examples/#sceneRepresentation_SceneModel_batching)
747
+ *
748
+ * ````javascript
749
+ * const origin = [100000000, 0, 100000000];
750
+ *
751
+ * sceneModel.createMesh({
752
+ * id: "leg1",
753
+ * origin: origin, // This mesh's positions and transforms are relative to the RTC center
754
+ * primitive: "triangles",
755
+ * positions: [ 1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1 ... ],
756
+ * normals: [ 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, ... ],
757
+ * indices: [ 0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7, ... ],
758
+ * position: [-4, -6, -4],
759
+ * scale: [1, 3, 1],
760
+ * rotation: [0, 0, 0],
761
+ * color: [1, 0.3, 0.3]
762
+ * });
763
+ *
764
+ * sceneModel.createEntity({
765
+ * meshIds: ["leg1"],
766
+ * isObject: true
767
+ * });
768
+ *
769
+ * sceneModel.createMesh({
770
+ * id: "leg2",
771
+ * origin: origin, // This mesh's positions and transforms are relative to the RTC center
772
+ * primitive: "triangles",
773
+ * positions: [ 1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1 ... ],
774
+ * normals: [ 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, ... ],
775
+ * indices: [ 0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7, ... ],
776
+ * position: [4, -6, -4],
777
+ * scale: [1, 3, 1],
778
+ * rotation: [0, 0, 0],
779
+ * color: [0.3, 1.0, 0.3]
780
+ * });
781
+ *
782
+ * sceneModel.createEntity({
783
+ * meshIds: ["leg2"],
784
+ * isObject: true
785
+ * });
786
+ *
787
+ * sceneModel.createMesh({
788
+ * id: "leg3",
789
+ * origin: origin, // This mesh's positions and transforms are relative to the RTC center
790
+ * primitive: "triangles",
791
+ * positions: [ 1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1 ... ],
792
+ * normals: [ 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, ... ],
793
+ * indices: [ 0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7, ... ],
794
+ * position: [4, -6, 4],
795
+ * scale: [1, 3, 1],
796
+ * rotation: [0, 0, 0],
797
+ * color: [0.3, 0.3, 1.0]
798
+ * });
799
+ *
800
+ * sceneModel.createEntity({
801
+ * meshIds: ["leg3"],
802
+ * isObject: true
803
+ * });
804
+ *
805
+ * sceneModel.createMesh({
806
+ * id: "leg4",
807
+ * origin: origin, // This mesh's positions and transforms are relative to the RTC center
808
+ * primitive: "triangles",
809
+ * positions: [ 1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1 ... ],
810
+ * normals: [ 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, ... ],
811
+ * indices: [ 0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7, ... ],
812
+ * position: [-4, -6, 4],
813
+ * scale: [1, 3, 1],
814
+ * rotation: [0, 0, 0],
815
+ * color: [1.0, 1.0, 0.0]
816
+ * });
817
+ *
818
+ * sceneModel.createEntity({
819
+ * meshIds: ["leg4"],
820
+ * isObject: true
821
+ * });
822
+ *
823
+ * sceneModel.createMesh({
824
+ * id: "top",
825
+ * origin: origin, // This mesh's positions and transforms are relative to the RTC center
826
+ * primitive: "triangles",
827
+ * positions: [ 1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1 ... ],
828
+ * normals: [ 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, ... ],
829
+ * indices: [ 0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7, ... ],
830
+ * position: [0, -3, 0],
831
+ * scale: [6, 0.5, 6],
832
+ * rotation: [0, 0, 0],
833
+ * color: [1.0, 0.3, 1.0]
834
+ * });
835
+ *
836
+ * sceneModel.createEntity({
837
+ * meshIds: ["top"],
838
+ * isObject: true
839
+ * });
840
+ * ````
841
+ *
842
+ * ## Positioning at World-space coordinates
843
+ *
844
+ * To position a SceneModel at given double-precision World coordinates, we can
845
+ * configure the ````origin```` of the SceneModel itself. The ````origin```` is a double-precision
846
+ * 3D World-space position at which the SceneModel will be located.
847
+ *
848
+ * Note that ````position```` is a single-precision offset relative to ````origin````.
849
+ *
850
+ * ````javascript
851
+ * const origin = [100000000, 0, 100000000];
852
+ *
853
+ * const sceneModel = new SceneModel(viewer.scene, {
854
+ * id: "table",
855
+ * isModel: true,
856
+ * origin: origin, // Everything in this SceneModel is relative to this RTC center
857
+ * position: [0, 0, 0],
858
+ * scale: [1, 1, 1],
859
+ * rotation: [0, 0, 0]
860
+ * });
861
+ *
862
+ * sceneModel.createGeometry({
863
+ * id: "box",
864
+ * primitive: "triangles",
865
+ * positions: [ 1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1 ... ],
866
+ * normals: [ 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, ... ],
867
+ * indices: [ 0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7, ... ],
868
+ * });
869
+ *
870
+ * sceneModel.createMesh({
871
+ * id: "leg1",
872
+ * geometryId: "box",
873
+ * position: [-4, -6, -4],
874
+ * scale: [1, 3, 1],
875
+ * rotation: [0, 0, 0],
876
+ * color: [1, 0.3, 0.3]
877
+ * });
878
+ *
879
+ * sceneModel.createEntity({
880
+ * meshIds: ["leg1"],
881
+ * isObject: true
882
+ * });
883
+ *
884
+ * sceneModel.createMesh({
885
+ * id: "leg2",
886
+ * geometryId: "box",
887
+ * position: [4, -6, -4],
888
+ * scale: [1, 3, 1],
889
+ * rotation: [0, 0, 0],
890
+ * color: [0.3, 1.0, 0.3]
891
+ * });
892
+ *
893
+ * sceneModel.createEntity({
894
+ * meshIds: ["leg2"],
895
+ * isObject: true
896
+ * });
897
+ *
898
+ * sceneModel.createMesh({
899
+ * id: "leg3",
900
+ * geometryId: "box",
901
+ * position: [4, -6, 4],
902
+ * scale: [1, 3, 1],
903
+ * rotation: [0, 0, 0],
904
+ * color: [0.3, 0.3, 1.0]
905
+ * });
906
+ *
907
+ * sceneModel.createEntity({
908
+ * meshIds: ["leg3"],
909
+ * isObject: true
910
+ * });
911
+ *
912
+ * sceneModel.createMesh({
913
+ * id: "leg4",
914
+ * geometryId: "box",
915
+ * position: [-4, -6, 4],
916
+ * scale: [1, 3, 1],
917
+ * rotation: [0, 0, 0],
918
+ * color: [1.0, 1.0, 0.0]
919
+ * });
920
+ *
921
+ * sceneModel.createEntity({
922
+ * meshIds: ["leg4"],
923
+ * isObject: true
924
+ * });
925
+ *
926
+ * sceneModel.createMesh({
927
+ * id: "top",
928
+ * geometryId: "box",
929
+ * position: [0, -3, 0],
930
+ * scale: [6, 0.5, 6],
931
+ * rotation: [0, 0, 0],
932
+ * color: [1.0, 0.3, 1.0]
933
+ * });
934
+ *
935
+ * sceneModel.createEntity({
936
+ * meshIds: ["top"],
937
+ * isObject: true
938
+ * });
939
+ * ````
940
+ *
941
+ * # Textures
942
+ *
943
+ * ## Loading KTX2 Texture Files into a SceneModel
944
+ *
945
+ * A {@link SceneModel} that is configured with a {@link KTX2TextureTranscoder} will
946
+ * allow us to load textures into it from KTX2 buffers or files.
947
+ *
948
+ * In the example below, we'll create a {@link Viewer}, containing a {@link SceneModel} configured with a
949
+ * {@link KTX2TextureTranscoder}. We'll then programmatically create a simple object within the SceneModel, consisting of
950
+ * a single mesh with a texture loaded from a KTX2 file, which our SceneModel internally transcodes, using
951
+ * its {@link KTX2TextureTranscoder}. Note how we configure our {@link KTX2TextureTranscoder} with a path to the Basis Universal
952
+ * transcoder WASM module.
953
+ *
954
+ * ````javascript
955
+ * const viewer = new Viewer({
956
+ * canvasId: "myCanvas",
957
+ * transparent: true
958
+ * });
959
+ *
960
+ * viewer.scene.camera.eye = [-21.80, 4.01, 6.56];
961
+ * viewer.scene.camera.look = [0, -5.75, 0];
962
+ * viewer.scene.camera.up = [0.37, 0.91, -0.11];
963
+ *
964
+ * const textureTranscoder = new KTX2TextureTranscoder({
965
+ * viewer,
966
+ * transcoderPath: "https://cdn.jsdelivr.net/npm/@xeokit/xeokit-sdk/dist/basis/" // <------ Path to BasisU transcoder module
967
+ * });
968
+ *
969
+ * const sceneModel = new SceneModel(viewer.scene, {
970
+ * id: "myModel",
971
+ * textureTranscoder // <<-------------------- Configure model with our transcoder
972
+ * });
973
+ *
974
+ * sceneModel.createTexture({
975
+ * id: "myColorTexture",
976
+ * src: "../assets/textures/compressed/sample_uastc_zstd.ktx2" // <<----- KTX2 texture asset
977
+ * });
978
+ *
979
+ * sceneModel.createTexture({
980
+ * id: "myMetallicRoughnessTexture",
981
+ * src: "../assets/textures/alpha/crosshatchAlphaMap.jpg" // <<----- JPEG texture asset
982
+ * });
983
+ *
984
+ * sceneModel.createTextureSet({
985
+ * id: "myTextureSet",
986
+ * colorTextureId: "myColorTexture",
987
+ * metallicRoughnessTextureId: "myMetallicRoughnessTexture"
988
+ * });
989
+ *
990
+ * sceneModel.createMesh({
991
+ * id: "myMesh",
992
+ * textureSetId: "myTextureSet",
993
+ * primitive: "triangles",
994
+ * positions: [1, 1, 1, ...],
995
+ * normals: [0, 0, 1, 0, ...],
996
+ * uv: [1, 0, 0, ...],
997
+ * indices: [0, 1, 2, ...],
998
+ * });
999
+ *
1000
+ * sceneModel.createEntity({
1001
+ * id: "myEntity",
1002
+ * meshIds: ["myMesh"]
1003
+ * });
1004
+ *
1005
+ * sceneModel.finalize();
1006
+ * ````
1007
+ *
1008
+ * ## Loading KTX2 Textures from ArrayBuffers into a SceneModel
1009
+ *
1010
+ * A SceneModel that is configured with a {@link KTX2TextureTranscoder} will allow us to load textures into
1011
+ * it from KTX2 ArrayBuffers.
1012
+ *
1013
+ * In the example below, we'll create a {@link Viewer}, containing a {@link SceneModel} configured with a
1014
+ * {@link KTX2TextureTranscoder}. We'll then programmatically create a simple object within the SceneModel, consisting of
1015
+ * a single mesh with a texture loaded from a KTX2 ArrayBuffer, which our SceneModel internally transcodes, using
1016
+ * its {@link KTX2TextureTranscoder}.
1017
+ *
1018
+ * ````javascript
1019
+ * const viewer = new Viewer({
1020
+ * canvasId: "myCanvas",
1021
+ * transparent: true
1022
+ * });
1023
+ *
1024
+ * viewer.scene.camera.eye = [-21.80, 4.01, 6.56];
1025
+ * viewer.scene.camera.look = [0, -5.75, 0];
1026
+ * viewer.scene.camera.up = [0.37, 0.91, -0.11];
1027
+ *
1028
+ * const textureTranscoder = new KTX2TextureTranscoder({
1029
+ * viewer,
1030
+ * transcoderPath: "https://cdn.jsdelivr.net/npm/@xeokit/xeokit-sdk/dist/basis/" // <------ Path to BasisU transcoder module
1031
+ * });
1032
+ *
1033
+ * const sceneModel = new SceneModel(viewer.scene, {
1034
+ * id: "myModel",
1035
+ * textureTranscoder // <<-------------------- Configure model with our transcoder
1036
+ * });
1037
+ *
1038
+ * utils.loadArraybuffer("../assets/textures/compressed/sample_uastc_zstd.ktx2",(arrayBuffer) => {
1039
+ *
1040
+ * sceneModel.createTexture({
1041
+ * id: "myColorTexture",
1042
+ * buffers: [arrayBuffer] // <<----- KTX2 texture asset
1043
+ * });
1044
+ *
1045
+ * sceneModel.createTexture({
1046
+ * id: "myMetallicRoughnessTexture",
1047
+ * src: "../assets/textures/alpha/crosshatchAlphaMap.jpg" // <<----- JPEG texture asset
1048
+ * });
1049
+ *
1050
+ * sceneModel.createTextureSet({
1051
+ * id: "myTextureSet",
1052
+ * colorTextureId: "myColorTexture",
1053
+ * metallicRoughnessTextureId: "myMetallicRoughnessTexture"
1054
+ * });
1055
+ *
1056
+ * sceneModel.createMesh({
1057
+ * id: "myMesh",
1058
+ * textureSetId: "myTextureSet",
1059
+ * primitive: "triangles",
1060
+ * positions: [1, 1, 1, ...],
1061
+ * normals: [0, 0, 1, 0, ...],
1062
+ * uv: [1, 0, 0, ...],
1063
+ * indices: [0, 1, 2, ...],
1064
+ * });
1065
+ *
1066
+ * sceneModel.createEntity({
1067
+ * id: "myEntity",
1068
+ * meshIds: ["myMesh"]
1069
+ * });
1070
+ *
1071
+ * sceneModel.finalize();
1072
+ * });
1073
+ * ````
1074
+ *
1075
+ * @implements {Entity}
1076
+ */
1077
+ export class SceneModel extends Component {
1078
+
1079
+ /**
1080
+ * @constructor
1081
+ * @param {Component} owner Owner component. When destroyed, the owner will destroy this component as well.
1082
+ * @param {*} [cfg] Configs
1083
+ * @param {String} [cfg.id] Optional ID, unique among all components in the parent scene, generated automatically when omitted.
1084
+ * @param {Boolean} [cfg.isModel] Specify ````true```` if this SceneModel represents a model, in which case the SceneModel will be registered by {@link SceneModel#id} in {@link Scene#models} and may also have a corresponding {@link MetaModel} with matching {@link MetaModel#id}, registered by that ID in {@link MetaScene#metaModels}.
1085
+ * @param {Number[]} [cfg.origin=[0,0,0]] World-space double-precision 3D origin.
1086
+ * @param {Number[]} [cfg.position=[0,0,0]] Local, single-precision 3D position, relative to the origin parameter.
1087
+ * @param {Number[]} [cfg.scale=[1,1,1]] Local scale.
1088
+ * @param {Number[]} [cfg.rotation=[0,0,0]] Local rotation, as Euler angles given in degrees, for each of the X, Y and Z axis.
1089
+ * @param {Number[]} [cfg.matrix=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1] Local modelling transform matrix. Overrides the position, scale and rotation parameters.
1090
+ * @param {Boolean} [cfg.visible=true] Indicates if the SceneModel is initially visible.
1091
+ * @param {Boolean} [cfg.culled=false] Indicates if the SceneModel is initially culled from view.
1092
+ * @param {Boolean} [cfg.pickable=true] Indicates if the SceneModel is initially pickable.
1093
+ * @param {Boolean} [cfg.clippable=true] Indicates if the SceneModel is initially clippable.
1094
+ * @param {Boolean} [cfg.collidable=true] Indicates if the SceneModel is initially included in boundary calculations.
1095
+ * @param {Boolean} [cfg.xrayed=false] Indicates if the SceneModel is initially xrayed.
1096
+ * @param {Boolean} [cfg.highlighted=false] Indicates if the SceneModel is initially highlighted.
1097
+ * @param {Boolean} [cfg.selected=false] Indicates if the SceneModel is initially selected.
1098
+ * @param {Boolean} [cfg.edges=false] Indicates if the SceneModel's edges are initially emphasized.
1099
+ * @param {Number[]} [cfg.colorize=[1.0,1.0,1.0]] SceneModel's initial RGB colorize color, multiplies by the rendered fragment colors.
1100
+ * @param {Number} [cfg.opacity=1.0] SceneModel's initial opacity factor, multiplies by the rendered fragment alpha.
1101
+ * @param {Number} [cfg.backfaces=false] When we set this ````true````, then we force rendering of backfaces for this SceneModel. When
1102
+ * we leave this ````false````, then we allow the Viewer to decide when to render backfaces. In that case, the
1103
+ * Viewer will hide backfaces on watertight meshes, show backfaces on open meshes, and always show backfaces on meshes when we slice them open with {@link SectionPlane}s.
1104
+ * @param {Boolean} [cfg.saoEnabled=true] Indicates if Scalable Ambient Obscurance (SAO) will apply to this SceneModel. SAO is configured by the Scene's {@link SAO} component.
1105
+ * @param {Boolean} [cfg.pbrEnabled=true] Indicates if physically-based rendering (PBR) will apply to the SceneModel when {@link Scene#pbrEnabled} is ````true````.
1106
+ * @param {Boolean} [cfg.colorTextureEnabled=true] Indicates if base color textures will be rendered for the SceneModel when {@link Scene#colorTextureEnabled} is ````true````.
1107
+ * @param {Number} [cfg.edgeThreshold=10] When xraying, highlighting, selecting or edging, this is the threshold angle between normals of adjacent triangles, below which their shared wireframe edge is not drawn.
1108
+ * @param {Number} [cfg.maxGeometryBatchSize=50000000] Maximum geometry batch size, as number of vertices. This is optionally supplied
1109
+ * to limit the size of the batched geometry arrays that SceneModel internally creates for batched geometries.
1110
+ * A lower value means less heap allocation/de-allocation while creating/loading batched geometries, but more draw calls and
1111
+ * slower rendering speed. A high value means larger heap allocation/de-allocation while creating/loading, but less draw calls
1112
+ * and faster rendering speed. It's recommended to keep this somewhere roughly between ````50000```` and ````50000000```.
1113
+ * @param {TextureTranscoder} [cfg.textureTranscoder] Transcoder that will be used internally by {@link SceneModel#createTexture}
1114
+ * to convert transcoded texture data. Only required when we'll be providing transcoded data
1115
+ * to {@link SceneModel#createTexture}. We assume that all transcoded texture data added to a ````SceneModel````
1116
+ * will then in a format supported by this transcoder.
1117
+ * @param {Boolean} [params.dtxEnabled=true] When ````true```` (default) use data textures (DTX), where appropriate, to
1118
+ * represent the returned model. Set false to always use vertex buffer objects (VBOs). Note that DTX is only applicable
1119
+ * to non-textured triangle meshes, and that VBOs are always used for meshes that have textures, line segments, or point
1120
+ * primitives. Only works while {@link DTX#enabled} is also ````true````.
1121
+ */
1122
+ constructor(owner, cfg = {}) {
1123
+
1124
+ super(owner, cfg);
1125
+
1126
+ this._dtxEnabled = this.scene.dtxEnabled && (cfg.dtxEnabled !== false);
1127
+
1128
+ this._enableVertexWelding = false; // Not needed for most objects, and very expensive, so disabled
1129
+ this._enableIndexBucketing = true;
1130
+
1131
+ this._vboBatchingLayerScratchMemory = getScratchMemory();
1132
+ this._textureTranscoder = cfg.textureTranscoder || getKTX2TextureTranscoder(this.scene.viewer);
1133
+
1134
+ this._maxGeometryBatchSize = cfg.maxGeometryBatchSize;
1135
+
1136
+ this._aabb = math.collapseAABB3();
1137
+ this._aabbDirty = true;
1138
+
1139
+ this._quantizationRanges = {};
1140
+
1141
+ this._vboInstancingLayers = {};
1142
+ this._vboBatchingLayers = {};
1143
+ this._dtxLayers = {};
1144
+
1145
+ this._meshList = [];
1146
+
1147
+ this.layerList = []; // For GL state efficiency when drawing, InstancingLayers are in first part, BatchingLayers are in second
1148
+ this._entityList = [];
1149
+
1150
+ this._geometries = {};
1151
+ this._dtxBuckets = {}; // Geometries with optimizations used for data texture representation
1152
+ this._textures = {};
1153
+ this._textureSets = {};
1154
+ this._meshes = {};
1155
+ this._entities = {};
1156
+
1157
+ this._scheduledMeshes = {}
1158
+
1159
+ /** @private **/
1160
+ this.renderFlags = new RenderFlags();
1161
+
1162
+ /**
1163
+ * @private
1164
+ */
1165
+ this.numGeometries = 0; // Number of geometries created with createGeometry()
1166
+
1167
+ // These counts are used to avoid unnecessary render passes
1168
+ // They are incremented or decremented exclusively by BatchingLayer and InstancingLayer
1169
+
1170
+ /**
1171
+ * @private
1172
+ */
1173
+ this.numPortions = 0;
1174
+
1175
+ /**
1176
+ * @private
1177
+ */
1178
+ this.numVisibleLayerPortions = 0;
1179
+
1180
+ /**
1181
+ * @private
1182
+ */
1183
+ this.numTransparentLayerPortions = 0;
1184
+
1185
+ /**
1186
+ * @private
1187
+ */
1188
+ this.numXRayedLayerPortions = 0;
1189
+
1190
+ /**
1191
+ * @private
1192
+ */
1193
+ this.numHighlightedLayerPortions = 0;
1194
+
1195
+ /**
1196
+ * @private
1197
+ */
1198
+ this.numSelectedLayerPortions = 0;
1199
+
1200
+ /**
1201
+ * @private
1202
+ */
1203
+ this.numEdgesLayerPortions = 0;
1204
+
1205
+ /**
1206
+ * @private
1207
+ */
1208
+ this.numPickableLayerPortions = 0;
1209
+
1210
+ /**
1211
+ * @private
1212
+ */
1213
+ this.numClippableLayerPortions = 0;
1214
+
1215
+ /**
1216
+ * @private
1217
+ */
1218
+ this.numCulledLayerPortions = 0;
1219
+
1220
+ this.numEntities = 0;
1221
+ this._numTriangles = 0;
1222
+ this._numLines = 0;
1223
+ this._numPoints = 0;
1224
+
1225
+ this._edgeThreshold = cfg.edgeThreshold || 10;
1226
+
1227
+ // Build static matrix
1228
+
1229
+ this._origin = math.vec3(cfg.origin || [0, 0, 0]);
1230
+ this._position = math.vec3(cfg.position || [0, 0, 0]);
1231
+ this._rotation = math.vec3(cfg.rotation || [0, 0, 0]);
1232
+ this._quaternion = math.vec4(cfg.quaternion || [0, 0, 0, 1]);
1233
+ this._conjugateQuaternion = math.vec4(cfg.quaternion || [0, 0, 0, 1]);
1234
+
1235
+ if (cfg.rotation) {
1236
+ math.eulerToQuaternion(this._rotation, "XYZ", this._quaternion);
1237
+ }
1238
+ this._scale = math.vec3(cfg.scale || [1, 1, 1]);
1239
+
1240
+ this._worldRotationMatrix = math.mat4();
1241
+ this._worldRotationMatrixConjugate = math.mat4();
1242
+ this._matrix = math.mat4();
1243
+ this._matrixDirty = true;
1244
+
1245
+ this._rebuildMatrices();
1246
+
1247
+ this._worldNormalMatrix = math.mat4();
1248
+ math.inverseMat4(this._matrix, this._worldNormalMatrix);
1249
+ math.transposeMat4(this._worldNormalMatrix);
1250
+
1251
+ if (cfg.matrix || cfg.position || cfg.rotation || cfg.scale || cfg.quaternion) {
1252
+ this._viewMatrix = math.mat4();
1253
+ this._viewNormalMatrix = math.mat4();
1254
+ this._viewMatrixDirty = true;
1255
+ this._matrixNonIdentity = true;
1256
+ }
1257
+
1258
+ this._opacity = 1.0;
1259
+ this._colorize = [1, 1, 1];
1260
+
1261
+ this._saoEnabled = (cfg.saoEnabled !== false);
1262
+ this._pbrEnabled = (cfg.pbrEnabled !== false);
1263
+ this._colorTextureEnabled = (cfg.colorTextureEnabled !== false);
1264
+
1265
+ this._isModel = cfg.isModel;
1266
+ if (this._isModel) {
1267
+ this.scene._registerModel(this);
1268
+ }
1269
+
1270
+ this._onCameraViewMatrix = this.scene.camera.on("matrix", () => {
1271
+ this._viewMatrixDirty = true;
1272
+ });
1273
+
1274
+ if (this.scene.vfc.enabled) {
1275
+ this._vfcManager = this.scene.vfc.getVFCManager(this);
1276
+ }
1277
+
1278
+ this._createDefaultTextureSet();
1279
+
1280
+ this.visible = cfg.visible;
1281
+ this.culled = cfg.culled;
1282
+ this.pickable = cfg.pickable;
1283
+ this.clippable = cfg.clippable;
1284
+ this.collidable = cfg.collidable;
1285
+ this.castsShadow = cfg.castsShadow;
1286
+ this.receivesShadow = cfg.receivesShadow;
1287
+ this.xrayed = cfg.xrayed;
1288
+ this.highlighted = cfg.highlighted;
1289
+ this.selected = cfg.selected;
1290
+ this.edges = cfg.edges;
1291
+ this.colorize = cfg.colorize;
1292
+ this.opacity = cfg.opacity;
1293
+ this.backfaces = cfg.backfaces;
1294
+ }
1295
+
1296
+ _createDefaultTextureSet() {
1297
+ // Every SceneModelMesh gets at least the default TextureSet,
1298
+ // which contains empty default textures filled with color
1299
+ const defaultColorTexture = new SceneModelTexture({
1300
+ id: DEFAULT_COLOR_TEXTURE_ID,
1301
+ texture: new Texture2D({
1302
+ gl: this.scene.canvas.gl,
1303
+ preloadColor: [1, 1, 1, 1] // [r, g, b, a]})
1304
+ })
1305
+ });
1306
+ const defaultMetalRoughTexture = new SceneModelTexture({
1307
+ id: DEFAULT_METAL_ROUGH_TEXTURE_ID,
1308
+ texture: new Texture2D({
1309
+ gl: this.scene.canvas.gl,
1310
+ preloadColor: [0, 1, 1, 1] // [unused, roughness, metalness, unused]
1311
+ })
1312
+ });
1313
+ const defaultNormalsTexture = new SceneModelTexture({
1314
+ id: DEFAULT_NORMALS_TEXTURE_ID,
1315
+ texture: new Texture2D({
1316
+ gl: this.scene.canvas.gl,
1317
+ preloadColor: [0, 0, 0, 0] // [x, y, z, unused] - these must be zeros
1318
+ })
1319
+ });
1320
+ const defaultEmissiveTexture = new SceneModelTexture({
1321
+ id: DEFAULT_EMISSIVE_TEXTURE_ID,
1322
+ texture: new Texture2D({
1323
+ gl: this.scene.canvas.gl,
1324
+ preloadColor: [0, 0, 0, 1] // [x, y, z, unused]
1325
+ })
1326
+ });
1327
+ const defaultOcclusionTexture = new SceneModelTexture({
1328
+ id: DEFAULT_OCCLUSION_TEXTURE_ID,
1329
+ texture: new Texture2D({
1330
+ gl: this.scene.canvas.gl,
1331
+ preloadColor: [1, 1, 1, 1] // [x, y, z, unused]
1332
+ })
1333
+ });
1334
+ this._textures[DEFAULT_COLOR_TEXTURE_ID] = defaultColorTexture;
1335
+ this._textures[DEFAULT_METAL_ROUGH_TEXTURE_ID] = defaultMetalRoughTexture;
1336
+ this._textures[DEFAULT_NORMALS_TEXTURE_ID] = defaultNormalsTexture;
1337
+ this._textures[DEFAULT_EMISSIVE_TEXTURE_ID] = defaultEmissiveTexture;
1338
+ this._textures[DEFAULT_OCCLUSION_TEXTURE_ID] = defaultOcclusionTexture;
1339
+ this._textureSets[DEFAULT_TEXTURE_SET_ID] = new SceneModelTextureSet({
1340
+ id: DEFAULT_TEXTURE_SET_ID,
1341
+ model: this,
1342
+ colorTexture: defaultColorTexture,
1343
+ metallicRoughnessTexture: defaultMetalRoughTexture,
1344
+ normalsTexture: defaultNormalsTexture,
1345
+ emissiveTexture: defaultEmissiveTexture,
1346
+ occlusionTexture: defaultOcclusionTexture
1347
+ });
1348
+ }
1349
+
1350
+ //------------------------------------------------------------------------------------------------------------------
1351
+ // SceneModel members
1352
+ //------------------------------------------------------------------------------------------------------------------
1353
+
1354
+ /**
1355
+ * Returns true to indicate that this Component is a SceneModel.
1356
+ * @type {Boolean}
1357
+ */
1358
+ get isPerformanceModel() {
1359
+ return true;
1360
+ }
1361
+
1362
+ /**
1363
+ * Returns the {@link Entity}s in this SceneModel.
1364
+ * @returns {*|{}}
1365
+ */
1366
+ get objects() {
1367
+ return this._entities;
1368
+ }
1369
+
1370
+ /**
1371
+ * Gets the 3D World-space origin for this SceneModel.
1372
+ *
1373
+ * Each mesh origin, if supplied, is relative to this origin.
1374
+ *
1375
+ * Default value is ````[0,0,0]````.
1376
+ *
1377
+ * @type {Float64Array}
1378
+ */
1379
+ get origin() {
1380
+ return this._origin;
1381
+ }
1382
+
1383
+ /**
1384
+ * Sets the SceneModel's local translation.
1385
+ *
1386
+ * Default value is ````[0,0,0]````.
1387
+ *
1388
+ * @type {Number[]}
1389
+ */
1390
+ set position(value) {
1391
+ this._position.set(value || [0, 0, 0]);
1392
+ this._setWorldMatrixDirty();
1393
+ this._setWorldAABBDirty();
1394
+ this.glRedraw();
1395
+ }
1396
+
1397
+ /**
1398
+ * Gets the SceneModel's local translation.
1399
+ *
1400
+ * Default value is ````[0,0,0]````.
1401
+ *
1402
+ * @type {Number[]}
1403
+ */
1404
+ get position() {
1405
+ return this._position;
1406
+ }
1407
+
1408
+ /**
1409
+ * Sets the SceneModel's local rotation, as Euler angles given in degrees, for each of the X, Y and Z axis.
1410
+ *
1411
+ * Default value is ````[0,0,0]````.
1412
+ *
1413
+ * @type {Number[]}
1414
+ */
1415
+ set rotation(value) {
1416
+ this._rotation.set(value || [0, 0, 0]);
1417
+ math.eulerToQuaternion(this._rotation, "XYZ", this._quaternion);
1418
+ this._setWorldMatrixDirty();
1419
+ this._setWorldAABBDirty();
1420
+ this.glRedraw();
1421
+ }
1422
+
1423
+ /**
1424
+ * Gets the SceneModel's local rotation, as Euler angles given in degrees, for each of the X, Y and Z axis.
1425
+ *
1426
+ * Default value is ````[0,0,0]````.
1427
+ *
1428
+ * @type {Number[]}
1429
+ */
1430
+ get rotation() {
1431
+ return this._rotation;
1432
+ }
1433
+
1434
+ /**
1435
+ * Sets the SceneModel's local rotation quaternion.
1436
+ *
1437
+ * Default value is ````[0,0,0,1]````.
1438
+ *
1439
+ * @type {Number[]}
1440
+ */
1441
+ set quaternion(value) {
1442
+ this._quaternion.set(value || [0, 0, 0, 1]);
1443
+ math.quaternionToEuler(this._quaternion, "XYZ", this._rotation);
1444
+ this._setWorldMatrixDirty();
1445
+ this._setWorldAABBDirty();
1446
+ this.glRedraw();
1447
+ }
1448
+
1449
+ /**
1450
+ * Gets the SceneModel's local rotation quaternion.
1451
+ *
1452
+ * Default value is ````[0,0,0,1]````.
1453
+ *
1454
+ * @type {Number[]}
1455
+ */
1456
+ get quaternion() {
1457
+ return this._quaternion;
1458
+ }
1459
+
1460
+ /**
1461
+ * Sets the SceneModel's local scale.
1462
+ *
1463
+ * Default value is ````[1,1,1]````.
1464
+ *
1465
+ * @type {Number[]}
1466
+ * @deprecated
1467
+ */
1468
+ set scale(value) {
1469
+ // NOP - deprecated
1470
+ }
1471
+
1472
+ /**
1473
+ * Gets the SceneModel's local scale.
1474
+ *
1475
+ * Default value is ````[1,1,1]````.
1476
+ *
1477
+ * @type {Number[]}
1478
+ * @deprecated
1479
+ */
1480
+ get scale() {
1481
+ return this._scale;
1482
+ }
1483
+
1484
+ /**
1485
+ * Sets the SceneModel's local modeling transform matrix.
1486
+ *
1487
+ * Default value is ````[1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]````.
1488
+ *
1489
+ * @type {Number[]}
1490
+ */
1491
+ set matrix(value) {
1492
+ this._matrix.set(value || DEFAULT_MATRIX);
1493
+
1494
+ math.quaternionToRotationMat4(this._quaternion, this._worldRotationMatrix);
1495
+ math.conjugateQuaternion(this._quaternion, this._conjugateQuaternion);
1496
+ math.quaternionToRotationMat4(this._quaternion, this._worldRotationMatrixConjugate);
1497
+ this._matrix.set(this._worldRotationMatrix);
1498
+ math.translateMat4v(this._position, this._matrix);
1499
+
1500
+ this._matrixDirty = false;
1501
+ this._setWorldMatrixDirty();
1502
+ this._setWorldAABBDirty();
1503
+ this.glRedraw();
1504
+ }
1505
+
1506
+ /**
1507
+ * Gets the SceneModel's local modeling transform matrix.
1508
+ *
1509
+ * Default value is ````[1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]````.
1510
+ *
1511
+ * @type {Number[]}
1512
+ */
1513
+ get matrix() {
1514
+ if (this._matrixDirty) {
1515
+ this._rebuildMatrices();
1516
+ }
1517
+ return this._matrix;
1518
+ }
1519
+
1520
+ /**
1521
+ * Gets the SceneModel's local modeling rotation transform matrix.
1522
+ *
1523
+ * @type {Number[]}
1524
+ */
1525
+ get rotationMatrix() {
1526
+ if (this._matrixDirty) {
1527
+ this._rebuildMatrices();
1528
+ }
1529
+ return this._worldRotationMatrix;
1530
+ }
1531
+
1532
+ _rebuildMatrices() {
1533
+ if (this._matrixDirty) {
1534
+ math.quaternionToRotationMat4(this._quaternion, this._worldRotationMatrix);
1535
+ math.conjugateQuaternion(this._quaternion, this._conjugateQuaternion);
1536
+ math.quaternionToRotationMat4(this._quaternion, this._worldRotationMatrixConjugate);
1537
+ this._matrix.set(this._worldRotationMatrix);
1538
+ math.translateMat4v(this._position, this._matrix);
1539
+ this._matrixDirty = false;
1540
+ }
1541
+ }
1542
+
1543
+ /**
1544
+ * Gets the conjugate of the SceneModel's local modeling rotation transform matrix.
1545
+ *
1546
+ * @type {Number[]}
1547
+ */
1548
+ get rotationMatrixConjugate() {
1549
+ if (this._matrixDirty) {
1550
+ this._rebuildMatrices();
1551
+ }
1552
+ return this._worldRotationMatrixConjugate;
1553
+ }
1554
+
1555
+ _setWorldMatrixDirty() {
1556
+ this._matrixDirty = true;
1557
+ }
1558
+
1559
+ _setLocalAABBDirty() {
1560
+ for (let i = 0, len = this._entityList.length; i < len; i++) {
1561
+ this._entityList[i]._setLocalAABBDirty(); // Entities need to rebuild their Local AABBs from their Mesh's local AABBs
1562
+ }
1563
+ }
1564
+
1565
+ _setWorldAABBDirty() {
1566
+ this._aabbDirty = true;
1567
+ this.scene._aabbDirty = true;
1568
+ this._matrixDirty = true;
1569
+ for (let i = 0, len = this._entityList.length; i < len; i++) {
1570
+ this._entityList[i]._setWorldAABBDirty(); // Entities need to retransform their World AABBs by SceneModel's worldMatrix
1571
+ }
1572
+ }
1573
+
1574
+ /**
1575
+ * Gets the SceneModel's World matrix.
1576
+ *
1577
+ * @property worldMatrix
1578
+ * @type {Number[]}
1579
+ */
1580
+ get worldMatrix() {
1581
+ return this.matrix;
1582
+ }
1583
+
1584
+ /**
1585
+ * Gets the SceneModel's World normal matrix.
1586
+ *
1587
+ * @type {Number[]}
1588
+ */
1589
+ get worldNormalMatrix() {
1590
+ return this._worldNormalMatrix;
1591
+ }
1592
+
1593
+ /**
1594
+ * Called by private renderers in ./lib, returns the view matrix with which to
1595
+ * render this SceneModel. The view matrix is the concatenation of the
1596
+ * Camera view matrix with the Performance model's world (modeling) matrix.
1597
+ *
1598
+ * @private
1599
+ */
1600
+ get viewMatrix() {
1601
+ if (!this._viewMatrix) {
1602
+ return this.scene.camera.viewMatrix;
1603
+ }
1604
+ if (this._matrixDirty) {
1605
+ this._rebuildMatrices();
1606
+ this._viewMatrixDirty = true;
1607
+ }
1608
+ if (this._viewMatrixDirty) {
1609
+ math.mulMat4(this.scene.camera.viewMatrix, this._matrix, this._viewMatrix);
1610
+ math.inverseMat4(this._viewMatrix, this._viewNormalMatrix);
1611
+ math.transposeMat4(this._viewNormalMatrix);
1612
+ this._viewMatrixDirty = false;
1613
+ }
1614
+ return this._viewMatrix;
1615
+ }
1616
+
1617
+ /**
1618
+ * Called by private renderers in ./lib, returns the view normal matrix with which to render this SceneModel.
1619
+ *
1620
+ * @private
1621
+ */
1622
+ get viewNormalMatrix() {
1623
+ if (!this._viewNormalMatrix) {
1624
+ return this.scene.camera.viewNormalMatrix;
1625
+ }
1626
+ if (this._matrixDirty) {
1627
+ this._rebuildMatrices();
1628
+ this._viewMatrixDirty = true;
1629
+ }
1630
+ if (this._viewMatrixDirty) {
1631
+ math.mulMat4(this.scene.camera.viewMatrix, this._matrix, this._viewMatrix);
1632
+ math.inverseMat4(this._viewMatrix, this._viewNormalMatrix);
1633
+ math.transposeMat4(this._viewNormalMatrix);
1634
+ this._viewMatrixDirty = false;
1635
+ }
1636
+ math.inverseMat4(this._viewMatrix, this._viewNormalMatrix);
1637
+ math.transposeMat4(this._viewNormalMatrix);
1638
+ return this._viewNormalMatrix;
1639
+ }
1640
+
1641
+ /**
1642
+ * Sets if backfaces are rendered for this SceneModel.
1643
+ *
1644
+ * Default is ````false````.
1645
+ *
1646
+ * @type {Boolean}
1647
+ */
1648
+ get backfaces() {
1649
+ return this._backfaces;
1650
+ }
1651
+
1652
+ /**
1653
+ * Sets if backfaces are rendered for this SceneModel.
1654
+ *
1655
+ * Default is ````false````.
1656
+ *
1657
+ * When we set this ````true````, then backfaces are always rendered for this SceneModel.
1658
+ *
1659
+ * When we set this ````false````, then we allow the Viewer to decide whether to render backfaces. In this case,
1660
+ * the Viewer will:
1661
+ *
1662
+ * * hide backfaces on watertight meshes,
1663
+ * * show backfaces on open meshes, and
1664
+ * * always show backfaces on meshes when we slice them open with {@link SectionPlane}s.
1665
+ *
1666
+ * @type {Boolean}
1667
+ */
1668
+ set backfaces(backfaces) {
1669
+ backfaces = !!backfaces;
1670
+ this._backfaces = backfaces;
1671
+ this.glRedraw();
1672
+ }
1673
+
1674
+ /**
1675
+ * Gets the list of {@link Entity}s within this SceneModel.
1676
+ *
1677
+ * @returns {Entity[]}
1678
+ */
1679
+ get entityList() {
1680
+ return this._entityList;
1681
+ }
1682
+
1683
+ /**
1684
+ * Returns true to indicate that SceneModel is an {@link Entity}.
1685
+ * @type {Boolean}
1686
+ */
1687
+ get isEntity() {
1688
+ return true;
1689
+ }
1690
+
1691
+ /**
1692
+ * Returns ````true```` if this SceneModel represents a model.
1693
+ *
1694
+ * When ````true```` the SceneModel will be registered by {@link SceneModel#id} in
1695
+ * {@link Scene#models} and may also have a {@link MetaObject} with matching {@link MetaObject#id}.
1696
+ *
1697
+ * @type {Boolean}
1698
+ */
1699
+ get isModel() {
1700
+ return this._isModel;
1701
+ }
1702
+
1703
+ //------------------------------------------------------------------------------------------------------------------
1704
+ // SceneModel members
1705
+ //------------------------------------------------------------------------------------------------------------------
1706
+
1707
+ /**
1708
+ * Returns ````false```` to indicate that SceneModel never represents an object.
1709
+ *
1710
+ * @type {Boolean}
1711
+ */
1712
+ get isObject() {
1713
+ return false;
1714
+ }
1715
+
1716
+ /**
1717
+ * Gets the SceneModel's World-space 3D axis-aligned bounding box.
1718
+ *
1719
+ * Represented by a six-element Float64Array containing the min/max extents of the
1720
+ * axis-aligned volume, ie. ````[xmin, ymin,zmin,xmax,ymax, zmax]````.
1721
+ *
1722
+ * @type {Number[]}
1723
+ */
1724
+ get aabb() {
1725
+ if (this._aabbDirty) {
1726
+ math.collapseAABB3(this._aabb);
1727
+ for (let i = 0, len = this._entityList.length; i < len; i++) {
1728
+ math.expandAABB3(this._aabb, this._entityList[i].aabb);
1729
+ }
1730
+ this._aabbDirty = false;
1731
+ }
1732
+ return this._aabb;
1733
+ }
1734
+
1735
+ /**
1736
+ * The approximate number of triangle primitives in this SceneModel.
1737
+ *
1738
+ * @type {Number}
1739
+ */
1740
+ get numTriangles() {
1741
+ return this._numTriangles;
1742
+ }
1743
+
1744
+ //------------------------------------------------------------------------------------------------------------------
1745
+ // Entity members
1746
+ //------------------------------------------------------------------------------------------------------------------
1747
+
1748
+ /**
1749
+ * The approximate number of line primitives in this SceneModel.
1750
+ *
1751
+ * @type {Number}
1752
+ */
1753
+ get numLines() {
1754
+ return this._numLines;
1755
+ }
1756
+
1757
+ /**
1758
+ * The approximate number of point primitives in this SceneModel.
1759
+ *
1760
+ * @type {Number}
1761
+ */
1762
+ get numPoints() {
1763
+ return this._numPoints;
1764
+ }
1765
+
1766
+ /**
1767
+ * Gets if any {@link Entity}s in this SceneModel are visible.
1768
+ *
1769
+ * The SceneModel is only rendered when {@link SceneModel#visible} is ````true```` and {@link SceneModel#culled} is ````false````.
1770
+ *
1771
+ * @type {Boolean}
1772
+ */
1773
+ get visible() {
1774
+ return (this.numVisibleLayerPortions > 0);
1775
+ }
1776
+
1777
+ /**
1778
+ * Sets if this SceneModel is visible.
1779
+ *
1780
+ * The SceneModel is only rendered when {@link SceneModel#visible} is ````true```` and {@link SceneModel#culled} is ````false````.
1781
+ **
1782
+ * @type {Boolean}
1783
+ */
1784
+ set visible(visible) {
1785
+ visible = visible !== false;
1786
+ this._visible = visible;
1787
+ for (let i = 0, len = this._entityList.length; i < len; i++) {
1788
+ this._entityList[i].visible = visible;
1789
+ }
1790
+ this.glRedraw();
1791
+ }
1792
+
1793
+ /**
1794
+ * Gets if any {@link Entity}s in this SceneModel are xrayed.
1795
+ *
1796
+ * @type {Boolean}
1797
+ */
1798
+ get xrayed() {
1799
+ return (this.numXRayedLayerPortions > 0);
1800
+ }
1801
+
1802
+ /**
1803
+ * Sets if all {@link Entity}s in this SceneModel are xrayed.
1804
+ *
1805
+ * @type {Boolean}
1806
+ */
1807
+ set xrayed(xrayed) {
1808
+ xrayed = !!xrayed;
1809
+ this._xrayed = xrayed;
1810
+ for (let i = 0, len = this._entityList.length; i < len; i++) {
1811
+ this._entityList[i].xrayed = xrayed;
1812
+ }
1813
+ this.glRedraw();
1814
+ }
1815
+
1816
+ /**
1817
+ * Gets if any {@link Entity}s in this SceneModel are highlighted.
1818
+ *
1819
+ * @type {Boolean}
1820
+ */
1821
+ get highlighted() {
1822
+ return (this.numHighlightedLayerPortions > 0);
1823
+ }
1824
+
1825
+ /**
1826
+ * Sets if all {@link Entity}s in this SceneModel are highlighted.
1827
+ *
1828
+ * @type {Boolean}
1829
+ */
1830
+ set highlighted(highlighted) {
1831
+ highlighted = !!highlighted;
1832
+ this._highlighted = highlighted;
1833
+ for (let i = 0, len = this._entityList.length; i < len; i++) {
1834
+ this._entityList[i].highlighted = highlighted;
1835
+ }
1836
+ this.glRedraw();
1837
+ }
1838
+
1839
+ /**
1840
+ * Gets if any {@link Entity}s in this SceneModel are selected.
1841
+ *
1842
+ * @type {Boolean}
1843
+ */
1844
+ get selected() {
1845
+ return (this.numSelectedLayerPortions > 0);
1846
+ }
1847
+
1848
+ /**
1849
+ * Sets if all {@link Entity}s in this SceneModel are selected.
1850
+ *
1851
+ * @type {Boolean}
1852
+ */
1853
+ set selected(selected) {
1854
+ selected = !!selected;
1855
+ this._selected = selected;
1856
+ for (let i = 0, len = this._entityList.length; i < len; i++) {
1857
+ this._entityList[i].selected = selected;
1858
+ }
1859
+ this.glRedraw();
1860
+ }
1861
+
1862
+ /**
1863
+ * Gets if any {@link Entity}s in this SceneModel have edges emphasised.
1864
+ *
1865
+ * @type {Boolean}
1866
+ */
1867
+ get edges() {
1868
+ return (this.numEdgesLayerPortions > 0);
1869
+ }
1870
+
1871
+ /**
1872
+ * Sets if all {@link Entity}s in this SceneModel have edges emphasised.
1873
+ *
1874
+ * @type {Boolean}
1875
+ */
1876
+ set edges(edges) {
1877
+ edges = !!edges;
1878
+ this._edges = edges;
1879
+ for (let i = 0, len = this._entityList.length; i < len; i++) {
1880
+ this._entityList[i].edges = edges;
1881
+ }
1882
+ this.glRedraw();
1883
+ }
1884
+
1885
+ /**
1886
+ * Gets if this SceneModel is culled from view.
1887
+ *
1888
+ * The SceneModel is only rendered when {@link SceneModel#visible} is true and {@link SceneModel#culled} is false.
1889
+ *
1890
+ * @type {Boolean}
1891
+ */
1892
+ get culled() {
1893
+ return this._culled;
1894
+ }
1895
+
1896
+ /**
1897
+ * Sets if this SceneModel is culled from view.
1898
+ *
1899
+ * The SceneModel is only rendered when {@link SceneModel#visible} is true and {@link SceneModel#culled} is false.
1900
+ *
1901
+ * @type {Boolean}
1902
+ */
1903
+ set culled(culled) {
1904
+ culled = !!culled;
1905
+ this._culled = culled;
1906
+ for (let i = 0, len = this._entityList.length; i < len; i++) {
1907
+ this._entityList[i].culled = culled;
1908
+ }
1909
+ this.glRedraw();
1910
+ }
1911
+
1912
+ /**
1913
+ * Gets if {@link Entity}s in this SceneModel are clippable.
1914
+ *
1915
+ * Clipping is done by the {@link SectionPlane}s in {@link Scene#sectionPlanes}.
1916
+ *
1917
+ * @type {Boolean}
1918
+ */
1919
+ get clippable() {
1920
+ return this._clippable;
1921
+ }
1922
+
1923
+ /**
1924
+ * Sets if {@link Entity}s in this SceneModel are clippable.
1925
+ *
1926
+ * Clipping is done by the {@link SectionPlane}s in {@link Scene#sectionPlanes}.
1927
+ *
1928
+ * @type {Boolean}
1929
+ */
1930
+ set clippable(clippable) {
1931
+ clippable = clippable !== false;
1932
+ this._clippable = clippable;
1933
+ for (let i = 0, len = this._entityList.length; i < len; i++) {
1934
+ this._entityList[i].clippable = clippable;
1935
+ }
1936
+ this.glRedraw();
1937
+ }
1938
+
1939
+ /**
1940
+ * Gets if this SceneModel is collidable.
1941
+ *
1942
+ * @type {Boolean}
1943
+ */
1944
+ get collidable() {
1945
+ return this._collidable;
1946
+ }
1947
+
1948
+ /**
1949
+ * Sets if {@link Entity}s in this SceneModel are collidable.
1950
+ *
1951
+ * @type {Boolean}
1952
+ */
1953
+ set collidable(collidable) {
1954
+ collidable = collidable !== false;
1955
+ this._collidable = collidable;
1956
+ for (let i = 0, len = this._entityList.length; i < len; i++) {
1957
+ this._entityList[i].collidable = collidable;
1958
+ }
1959
+ }
1960
+
1961
+ /**
1962
+ * Gets if this SceneModel is pickable.
1963
+ *
1964
+ * Picking is done via calls to {@link Scene#pick}.
1965
+ *
1966
+ * @type {Boolean}
1967
+ */
1968
+ get pickable() {
1969
+ return (this.numPickableLayerPortions > 0);
1970
+ }
1971
+
1972
+ /**
1973
+ * Sets if {@link Entity}s in this SceneModel are pickable.
1974
+ *
1975
+ * Picking is done via calls to {@link Scene#pick}.
1976
+ *
1977
+ * @type {Boolean}
1978
+ */
1979
+ set pickable(pickable) {
1980
+ pickable = pickable !== false;
1981
+ this._pickable = pickable;
1982
+ for (let i = 0, len = this._entityList.length; i < len; i++) {
1983
+ this._entityList[i].pickable = pickable;
1984
+ }
1985
+ }
1986
+
1987
+ /**
1988
+ * Gets the RGB colorize color for this SceneModel.
1989
+ *
1990
+ * Each element of the color is in range ````[0..1]````.
1991
+ *
1992
+ * @type {Number[]}
1993
+ */
1994
+ get colorize() {
1995
+ return this._colorize;
1996
+ }
1997
+
1998
+ /**
1999
+ * Sets the RGB colorize color for this SceneModel.
2000
+ *
2001
+ * Multiplies by rendered fragment colors.
2002
+ *
2003
+ * Each element of the color is in range ````[0..1]````.
2004
+ *
2005
+ * @type {Number[]}
2006
+ */
2007
+ set colorize(colorize) {
2008
+ this._colorize = colorize;
2009
+ for (let i = 0, len = this._entityList.length; i < len; i++) {
2010
+ this._entityList[i].colorize = colorize;
2011
+ }
2012
+ }
2013
+
2014
+ /**
2015
+ * Gets this SceneModel's opacity factor.
2016
+ *
2017
+ * This is a factor in range ````[0..1]```` which multiplies by the rendered fragment alphas.
2018
+ *
2019
+ * @type {Number}
2020
+ */
2021
+ get opacity() {
2022
+ return this._opacity;
2023
+ }
2024
+
2025
+ /**
2026
+ * Sets the opacity factor for this SceneModel.
2027
+ *
2028
+ * This is a factor in range ````[0..1]```` which multiplies by the rendered fragment alphas.
2029
+ *
2030
+ * @type {Number}
2031
+ */
2032
+ set opacity(opacity) {
2033
+ this._opacity = opacity;
2034
+ for (let i = 0, len = this._entityList.length; i < len; i++) {
2035
+ this._entityList[i].opacity = opacity;
2036
+ }
2037
+ }
2038
+
2039
+ /**
2040
+ * Gets if this SceneModel casts a shadow.
2041
+ *
2042
+ * @type {Boolean}
2043
+ */
2044
+ get castsShadow() {
2045
+ return this._castsShadow;
2046
+ }
2047
+
2048
+ /**
2049
+ * Sets if this SceneModel casts a shadow.
2050
+ *
2051
+ * @type {Boolean}
2052
+ */
2053
+ set castsShadow(castsShadow) {
2054
+ castsShadow = (castsShadow !== false);
2055
+ if (castsShadow !== this._castsShadow) {
2056
+ this._castsShadow = castsShadow;
2057
+ this.glRedraw();
2058
+ }
2059
+ }
2060
+
2061
+ /**
2062
+ * Sets if this SceneModel can have shadow cast upon it.
2063
+ *
2064
+ * @type {Boolean}
2065
+ */
2066
+ get receivesShadow() {
2067
+ return this._receivesShadow;
2068
+ }
2069
+
2070
+ /**
2071
+ * Sets if this SceneModel can have shadow cast upon it.
2072
+ *
2073
+ * @type {Boolean}
2074
+ */
2075
+ set receivesShadow(receivesShadow) {
2076
+ receivesShadow = (receivesShadow !== false);
2077
+ if (receivesShadow !== this._receivesShadow) {
2078
+ this._receivesShadow = receivesShadow;
2079
+ this.glRedraw();
2080
+ }
2081
+ }
2082
+
2083
+ /**
2084
+ * Gets if Scalable Ambient Obscurance (SAO) will apply to this SceneModel.
2085
+ *
2086
+ * SAO is configured by the Scene's {@link SAO} component.
2087
+ *
2088
+ * Only works when {@link SAO#enabled} is also true.
2089
+ *
2090
+ * @type {Boolean}
2091
+ */
2092
+ get saoEnabled() {
2093
+ return this._saoEnabled;
2094
+ }
2095
+
2096
+ /**
2097
+ * Gets if physically-based rendering (PBR) is enabled for this SceneModel.
2098
+ *
2099
+ * Only works when {@link Scene#pbrEnabled} is also true.
2100
+ *
2101
+ * @type {Boolean}
2102
+ */
2103
+ get pbrEnabled() {
2104
+ return this._pbrEnabled;
2105
+ }
2106
+
2107
+ /**
2108
+ * Gets if color textures are enabled for this SceneModel.
2109
+ *
2110
+ * Only works when {@link Scene#colorTextureEnabled} is also true.
2111
+ *
2112
+ * @type {Boolean}
2113
+ */
2114
+ get colorTextureEnabled() {
2115
+ return this._colorTextureEnabled;
2116
+ }
2117
+
2118
+ /**
2119
+ * Returns true to indicate that SceneModel is implements {@link Drawable}.
2120
+ *
2121
+ * @type {Boolean}
2122
+ */
2123
+ get isDrawable() {
2124
+ return true;
2125
+ }
2126
+
2127
+ /** @private */
2128
+ get isStateSortable() {
2129
+ return false
2130
+ }
2131
+
2132
+ /**
2133
+ * Configures the appearance of xrayed {@link Entity}s within this SceneModel.
2134
+ *
2135
+ * This is the {@link Scene#xrayMaterial}.
2136
+ *
2137
+ * @type {EmphasisMaterial}
2138
+ */
2139
+ get xrayMaterial() {
2140
+ return this.scene.xrayMaterial;
2141
+ }
2142
+
2143
+ /**
2144
+ * Configures the appearance of highlighted {@link Entity}s within this SceneModel.
2145
+ *
2146
+ * This is the {@link Scene#highlightMaterial}.
2147
+ *
2148
+ * @type {EmphasisMaterial}
2149
+ */
2150
+ get highlightMaterial() {
2151
+ return this.scene.highlightMaterial;
2152
+ }
2153
+
2154
+ /**
2155
+ * Configures the appearance of selected {@link Entity}s within this SceneModel.
2156
+ *
2157
+ * This is the {@link Scene#selectedMaterial}.
2158
+ *
2159
+ * @type {EmphasisMaterial}
2160
+ */
2161
+ get selectedMaterial() {
2162
+ return this.scene.selectedMaterial;
2163
+ }
2164
+
2165
+ /**
2166
+ * Configures the appearance of edges of {@link Entity}s within this SceneModel.
2167
+ *
2168
+ * This is the {@link Scene#edgeMaterial}.
2169
+ *
2170
+ * @type {EdgeMaterial}
2171
+ */
2172
+ get edgeMaterial() {
2173
+ return this.scene.edgeMaterial;
2174
+ }
2175
+
2176
+ //------------------------------------------------------------------------------------------------------------------
2177
+ // Drawable members
2178
+ //------------------------------------------------------------------------------------------------------------------
2179
+
2180
+ /**
2181
+ * Called by private renderers in ./lib, returns the picking view matrix with which to
2182
+ * ray-pick on this SceneModel.
2183
+ *
2184
+ * @private
2185
+ */
2186
+ getPickViewMatrix(pickViewMatrix) {
2187
+ if (!this._viewMatrix) {
2188
+ return pickViewMatrix;
2189
+ }
2190
+ return this._viewMatrix;
2191
+ }
2192
+
2193
+ /**
2194
+ *
2195
+ * @param cfg
2196
+ */
2197
+ createQuantizationRange(cfg) {
2198
+ if (cfg.id === undefined || cfg.id === null) {
2199
+ this.error("[createQuantizationRange] Config missing: id");
2200
+ return;
2201
+ }
2202
+ if (cfg.aabb) {
2203
+ this.error("[createQuantizationRange] Config missing: aabb");
2204
+ return;
2205
+ }
2206
+ if (this._quantizationRanges[cfg.id]) {
2207
+ this.error("[createQuantizationRange] QuantizationRange already created: " + cfg.id);
2208
+ return;
2209
+ }
2210
+ this._quantizationRanges[cfg.id] = {
2211
+ id: cfg.id,
2212
+ aabb: cfg.aabb,
2213
+ matrix: createPositionsDecodeMatrix(cfg.aabb, math.mat4())
2214
+ }
2215
+ }
2216
+
2217
+ /**
2218
+ * Creates a reusable geometry within this SceneModel.
2219
+ *
2220
+ * We can then supply the geometry ID to {@link SceneModel#createMesh} when we want to create meshes that
2221
+ * instance the geometry.
2222
+ *
2223
+ * @param {*} cfg Geometry properties.
2224
+ * @param {String|Number} cfg.id Mandatory ID for the geometry, to refer to with {@link SceneModel#createMesh}.
2225
+ * @param {String} cfg.primitive The primitive type. Accepted values are 'points', 'lines', 'triangles', 'solid' and 'surface'.
2226
+ * @param {Number[]} [cfg.positions] Flat array of uncompressed 3D vertex positions positions. Required for all primitive types. Overridden by ````positionsCompressed````.
2227
+ * @param {Number[]} [cfg.positionsCompressed] Flat array of quantized 3D vertex positions. Overrides ````positions````, and must be accompanied by ````positionsDecodeMatrix````.
2228
+ * @param {Number[]} [cfg.positionsDecodeMatrix] A 4x4 matrix for decompressing ````positionsCompressed````. Must be accompanied by ````positionsCompressed````.
2229
+ * @param {Number[]} [cfg.normals] Flat array of normal vectors. Only used with "triangles", "solid" and "surface" primitives. When no normals are given, the geometry will be flat shaded using auto-generated face-aligned normals.
2230
+ * @param {Number[]} [cfg.normalsCompressed] Flat array of oct-encoded normal vectors. Overrides ````normals````. Only used with "triangles", "solid" and "surface" primitives. When no normals are given, the geometry will be flat shaded using auto-generated face-aligned normals.
2231
+ * @param {Number[]} [cfg.colors] Flat array of uncompressed RGBA vertex colors, as float values in range ````[0..1]````. Ignored when ````geometryId```` is given. Overridden by ````color```` and ````colorsCompressed````.
2232
+ * @param {Number[]} [cfg.colorsCompressed] Flat array of compressed RGBA vertex colors, as unsigned short integers in range ````[0..255]````. Ignored when ````geometryId```` is given. Overrides ````colors```` and is overridden by ````color````.
2233
+ * @param {Number[]} [cfg.uv] Flat array of uncompressed vertex UV coordinates. Only used with "triangles", "solid" and "surface" primitives. Required for textured rendering.
2234
+ * @param {Number[]} [cfg.uvCompressed] Flat array of compressed vertex UV coordinates. Only used with "triangles", "solid" and "surface" primitives. Overrides ````uv````. Must be accompanied by ````uvDecodeMatrix````. Only used with "triangles", "solid" and "surface" primitives. Required for textured rendering.
2235
+ * @param {Number[]} [cfg.uvDecodeMatrix] A 3x3 matrix for decompressing ````uvCompressed````.
2236
+ * @param {Number[]} [cfg.indices] Array of primitive connectivity indices. Not required for `points` primitives.
2237
+ * @param {Number[]} [cfg.edgeIndices] Array of edge line indices. Used only with 'triangles', 'solid' and 'surface' primitives. Automatically generated internally if not supplied, using the optional ````edgeThreshold```` given to the ````SceneModel```` constructor.
2238
+ */
2239
+ createGeometry(cfg) {
2240
+ if (cfg.id === undefined || cfg.id === null) {
2241
+ this.error("[createGeometry] Config missing: id");
2242
+ return;
2243
+ }
2244
+ if (this._geometries[cfg.id]) {
2245
+ this.error("[createGeometry] Geometry already created: " + cfg.id);
2246
+ return;
2247
+ }
2248
+ if (cfg.primitive === undefined || cfg.primitive === null) {
2249
+ cfg.primitive = "triangles";
2250
+ }
2251
+ if (cfg.primitive !== "points" && cfg.primitive !== "lines" && cfg.primitive !== "triangles" && cfg.primitive !== "solid" && cfg.primitive !== "surface") {
2252
+ this.error(`[createGeometry] Unsupported value for 'primitive': '${primitive}' - supported values are 'points', 'lines', 'triangles', 'solid' and 'surface'. Defaulting to 'triangles'.`);
2253
+ return;
2254
+ }
2255
+ if (!cfg.positions && !cfg.positionsCompressed && !cfg.buckets) {
2256
+ this.error("[createGeometry] Param expected: `positions`, `positionsCompressed' or 'buckets");
2257
+ return null;
2258
+ }
2259
+ if (cfg.positionsCompressed && !cfg.positionsDecodeMatrix && !cfg.positionsDecodeBoundary) {
2260
+ this.error("[createGeometry] Param expected: `positionsDecodeMatrix` or 'positionsDecodeBoundary' (required for `positionsCompressed')");
2261
+ return null;
2262
+ }
2263
+ if (cfg.positionsDecodeMatrix && cfg.positionsDecodeBoundary) {
2264
+ this.error("[createGeometry] Only one of these params expected: `positionsDecodeMatrix` or 'positionsDecodeBoundary' (required for `positionsCompressed')");
2265
+ return null;
2266
+ }
2267
+ if (cfg.uvCompressed && !cfg.uvDecodeMatrix) {
2268
+ this.error("[createGeometry] Param expected: `uvDecodeMatrix` (required for `uvCompressed')");
2269
+ return null;
2270
+ }
2271
+ if (!cfg.buckets && !cfg.indices && cfg.primitive !== "points") {
2272
+ this.error(`[createGeometry] Param expected: indices (required for '${cfg.primitive}' primitive type)`);
2273
+ return null;
2274
+ }
2275
+ if (cfg.positionsDecodeBoundary) {
2276
+ cfg.positionsDecodeMatrix = createPositionsDecodeMatrix(cfg.positionsDecodeBoundary, math.mat4());
2277
+ }
2278
+ if (cfg.positions) {
2279
+ const aabb = math.collapseAABB3();
2280
+ cfg.positionsDecodeMatrix = math.mat4();
2281
+ math.expandAABB3Points3(aabb, cfg.positions);
2282
+ cfg.positionsCompressed = quantizePositions(cfg.positions, aabb, cfg.positionsDecodeMatrix);
2283
+ } else {
2284
+ cfg.positionsDecodeMatrix = new Float64Array(cfg.positionsDecodeMatrix);
2285
+ cfg.positionsCompressed = new Uint16Array(cfg.positionsCompressed);
2286
+ }
2287
+ if (cfg.colorsCompressed && cfg.colorsCompressed.length > 0) {
2288
+ cfg.colorsCompressed = new Uint8Array(cfg.colorsCompressed);
2289
+ } else if (cfg.colors && cfg.colors.length > 0) {
2290
+ const colors = cfg.colors;
2291
+ const colorsCompressed = new Uint8Array(colors.length);
2292
+ for (let i = 0, len = colors.length; i < len; i++) {
2293
+ colorsCompressed[i] = colors[i] * 255;
2294
+ }
2295
+ cfg.colorsCompressed = colorsCompressed;
2296
+ }
2297
+ if (!cfg.buckets && !cfg.edgeIndices && (cfg.primitive === "triangles" || cfg.primitive === "solid" || cfg.primitive === "surface")) {
2298
+ if (cfg.positions) {
2299
+ cfg.edgeIndices = buildEdgeIndices(cfg.positions, cfg.indices, null, 5.0);
2300
+ } else {
2301
+ cfg.edgeIndices = buildEdgeIndices(cfg.positionsCompressed, cfg.indices, cfg.positionsDecodeMatrix, 2.0);
2302
+ }
2303
+ }
2304
+ if (cfg.buckets) {
2305
+ this._dtxBuckets[cfg.id] = cfg.buckets;
2306
+ }
2307
+ if (cfg.uv) {
2308
+ const bounds = geometryCompressionUtils.getUVBounds(cfg.uv);
2309
+ const result = geometryCompressionUtils.compressUVs(cfg.uv, bounds.min, bounds.max);
2310
+ cfg.uvCompressed = result.quantized;
2311
+ cfg.uvDecodeMatrix = result.decodeMatrix;
2312
+ } else if (cfg.uvCompressed) {
2313
+ cfg.uvCompressed = new Uint16Array(cfg.uvCompressed);
2314
+ cfg.uvDecodeMatrix = new Float64Array(cfg.uvDecodeMatrix);
2315
+ }
2316
+ if (cfg.normals) { // HACK
2317
+ cfg.normals = null;
2318
+ }
2319
+ this._geometries [cfg.id] = cfg;
2320
+ this._numTriangles += (cfg.indices ? Math.round(cfg.indices.length / 3) : 0);
2321
+ this.numGeometries++;
2322
+ }
2323
+
2324
+ /**
2325
+ * Creates a texture within this SceneModel.
2326
+ *
2327
+ * We can then supply the texture ID to {@link SceneModel#createTextureSet} when we want to create texture sets that use the texture.
2328
+ *
2329
+ * @param {*} cfg Texture properties.
2330
+ * @param {String|Number} cfg.id Mandatory ID for the texture, to refer to with {@link SceneModel#createTextureSet}.
2331
+ * @param {String} [cfg.src] Image file for the texture. Assumed to be transcoded if not having a recognized image file
2332
+ * extension (jpg, jpeg, png etc.). If transcoded, then assumes ````SceneModel```` is configured with a {@link TextureTranscoder}.
2333
+ * @param {ArrayBuffer[]} [cfg.buffers] Transcoded texture data. Assumes ````SceneModel```` is
2334
+ * configured with a {@link TextureTranscoder}. This parameter is given as an array of buffers so we can potentially support multi-image textures, such as cube maps.
2335
+ * @param {HTMLImageElement} [cfg.image] HTML Image object to load into this texture. Overrides ````src```` and ````buffers````. Never transcoded.
2336
+ * @param {Number} [cfg.minFilter=LinearMipmapLinearFilter] How the texture is sampled when a texel covers less than one pixel.
2337
+ * Supported values are {@link LinearMipmapLinearFilter}, {@link LinearMipMapNearestFilter}, {@link NearestMipMapNearestFilter}, {@link NearestMipMapLinearFilter} and {@link LinearMipMapLinearFilter}.
2338
+ * @param {Number} [cfg.magFilter=LinearFilter] How the texture is sampled when a texel covers more than one pixel. Supported values are {@link LinearFilter} and {@link NearestFilter}.
2339
+ * @param {Number} [cfg.wrapS=RepeatWrapping] Wrap parameter for texture coordinate *S*. Supported values are {@link ClampToEdgeWrapping}, {@link MirroredRepeatWrapping} and {@link RepeatWrapping}.
2340
+ * @param {Number} [cfg.wrapT=RepeatWrapping] Wrap parameter for texture coordinate *T*. Supported values are {@link ClampToEdgeWrapping}, {@link MirroredRepeatWrapping} and {@link RepeatWrapping}..
2341
+ * @param {Number} [cfg.wrapR=RepeatWrapping] Wrap parameter for texture coordinate *R*. Supported values are {@link ClampToEdgeWrapping}, {@link MirroredRepeatWrapping} and {@link RepeatWrapping}.
2342
+ * @param {Boolean} [cfg.flipY=false] Flips this Texture's source data along its vertical axis when ````true````.
2343
+ * @param {Number} [cfg.encoding=LinearEncoding] Encoding format. Supported values are {@link LinearEncoding} and {@link sRGBEncoding}.
2344
+ */
2345
+ createTexture(cfg) {
2346
+ const textureId = cfg.id;
2347
+ if (textureId === undefined || textureId === null) {
2348
+ this.error("[createTexture] Config missing: id");
2349
+ return;
2350
+ }
2351
+ if (this._textures[textureId]) {
2352
+ this.error("[createTexture] Texture already created: " + textureId);
2353
+ return;
2354
+ }
2355
+ if (!cfg.src && !cfg.image && !cfg.buffers) {
2356
+ this.error("[createTexture] Param expected: `src`, `image' or 'buffers'");
2357
+ return null;
2358
+ }
2359
+ let minFilter = cfg.minFilter || LinearMipmapLinearFilter;
2360
+ if (minFilter !== LinearFilter &&
2361
+ minFilter !== LinearMipMapNearestFilter &&
2362
+ minFilter !== LinearMipmapLinearFilter &&
2363
+ minFilter !== NearestMipMapLinearFilter &&
2364
+ minFilter !== NearestMipMapNearestFilter) {
2365
+ this.error(`[createTexture] Unsupported value for 'minFilter' -
2366
+ supported values are LinearFilter, LinearMipMapNearestFilter, NearestMipMapNearestFilter,
2367
+ NearestMipMapLinearFilter and LinearMipmapLinearFilter. Defaulting to LinearMipmapLinearFilter.`);
2368
+ minFilter = LinearMipmapLinearFilter;
2369
+ }
2370
+ let magFilter = cfg.magFilter || LinearFilter;
2371
+ if (magFilter !== LinearFilter && magFilter !== NearestFilter) {
2372
+ this.error(`[createTexture] Unsupported value for 'magFilter' - supported values are LinearFilter and NearestFilter. Defaulting to LinearFilter.`);
2373
+ magFilter = LinearFilter;
2374
+ }
2375
+ let wrapS = cfg.wrapS || RepeatWrapping;
2376
+ if (wrapS !== ClampToEdgeWrapping && wrapS !== MirroredRepeatWrapping && wrapS !== RepeatWrapping) {
2377
+ this.error(`[createTexture] Unsupported value for 'wrapS' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping.`);
2378
+ wrapS = RepeatWrapping;
2379
+ }
2380
+ let wrapT = cfg.wrapT || RepeatWrapping;
2381
+ if (wrapT !== ClampToEdgeWrapping && wrapT !== MirroredRepeatWrapping && wrapT !== RepeatWrapping) {
2382
+ this.error(`[createTexture] Unsupported value for 'wrapT' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping.`);
2383
+ wrapT = RepeatWrapping;
2384
+ }
2385
+ let wrapR = cfg.wrapR || RepeatWrapping;
2386
+ if (wrapR !== ClampToEdgeWrapping && wrapR !== MirroredRepeatWrapping && wrapR !== RepeatWrapping) {
2387
+ this.error(`[createTexture] Unsupported value for 'wrapR' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping.`);
2388
+ wrapR = RepeatWrapping;
2389
+ }
2390
+ let encoding = cfg.encoding || LinearEncoding;
2391
+ if (encoding !== LinearEncoding && encoding !== sRGBEncoding) {
2392
+ this.error("[createTexture] Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding.");
2393
+ encoding = LinearEncoding;
2394
+ }
2395
+ const texture = new Texture2D({
2396
+ gl: this.scene.canvas.gl,
2397
+ minFilter,
2398
+ magFilter,
2399
+ wrapS,
2400
+ wrapT,
2401
+ wrapR,
2402
+ // flipY: cfg.flipY,
2403
+ encoding
2404
+ });
2405
+ if (cfg.preloadColor) {
2406
+ texture.setPreloadColor(cfg.preloadColor);
2407
+ }
2408
+ if (cfg.image) { // Ignore transcoder for Images
2409
+ const image = cfg.image;
2410
+ image.crossOrigin = "Anonymous";
2411
+ texture.setImage(image, {minFilter, magFilter, wrapS, wrapT, wrapR, flipY: cfg.flipY, encoding});
2412
+ } else if (cfg.src) {
2413
+ const ext = cfg.src.split('.').pop();
2414
+ switch (ext) { // Don't transcode recognized image file types
2415
+ case "jpeg":
2416
+ case "jpg":
2417
+ case "png":
2418
+ case "gif":
2419
+ const image = new Image();
2420
+ image.onload = () => {
2421
+ texture.setImage(image, {
2422
+ minFilter,
2423
+ magFilter,
2424
+ wrapS,
2425
+ wrapT,
2426
+ wrapR,
2427
+ flipY: cfg.flipY,
2428
+ encoding
2429
+ });
2430
+ this.glRedraw();
2431
+ };
2432
+ image.src = cfg.src; // URL or Base64 string
2433
+ break;
2434
+ default: // Assume other file types need transcoding
2435
+ if (!this._textureTranscoder) {
2436
+ this.error(`[createTexture] Can't create texture from 'src' - SceneModel needs to be configured with a TextureTranscoder for this file type ('${ext}')`);
2437
+ } else {
2438
+ utils.loadArraybuffer(cfg.src, (arrayBuffer) => {
2439
+ if (!arrayBuffer.byteLength) {
2440
+ this.error(`[createTexture] Can't create texture from 'src': file data is zero length`);
2441
+ return;
2442
+ }
2443
+ this._textureTranscoder.transcode([arrayBuffer], texture).then(() => {
2444
+ this.glRedraw();
2445
+ });
2446
+ },
2447
+ function (errMsg) {
2448
+ this.error(`[createTexture] Can't create texture from 'src': ${errMsg}`);
2449
+ });
2450
+ }
2451
+ break;
2452
+ }
2453
+ } else if (cfg.buffers) { // Buffers implicitly require transcoding
2454
+ if (!this._textureTranscoder) {
2455
+ this.error(`[createTexture] Can't create texture from 'buffers' - SceneModel needs to be configured with a TextureTranscoder for this option`);
2456
+ } else {
2457
+ this._textureTranscoder.transcode(cfg.buffers, texture).then(() => {
2458
+ this.glRedraw();
2459
+ });
2460
+ }
2461
+ }
2462
+ this._textures[textureId] = new SceneModelTexture({id: textureId, texture});
2463
+ }
2464
+
2465
+ /**
2466
+ * Creates a texture set within this SceneModel.
2467
+ *
2468
+ * A texture set is a collection of textures that can be shared among meshes. We can then supply the texture set
2469
+ * ID to {@link SceneModel#createMesh} when we want to create meshes that use the texture set.
2470
+ *
2471
+ * The textures can work as a texture atlas, where each mesh can have geometry UVs that index
2472
+ * a different part of the textures. This allows us to minimize the number of textures in our models, which
2473
+ * means faster rendering.
2474
+ *
2475
+ * @param {*} cfg Texture set properties.
2476
+ * @param {String|Number} cfg.id Mandatory ID for the texture set, to refer to with {@link SceneModel#createMesh}.
2477
+ * @param {*} [cfg.colorTextureId] ID of *RGBA* base color texture, with color in *RGB* and alpha in *A*.
2478
+ * @param {*} [cfg.metallicRoughnessTextureId] ID of *RGBA* metal-roughness texture, with the metallic factor in *R*, and roughness factor in *G*.
2479
+ * @param {*} [cfg.normalsTextureId] ID of *RGBA* normal map texture, with normal map vectors in *RGB*.
2480
+ * @param {*} [cfg.emissiveTextureId] ID of *RGBA* emissive map texture, with emissive color in *RGB*.
2481
+ * @param {*} [cfg.occlusionTextureId] ID of *RGBA* occlusion map texture, with occlusion factor in *R*.
2482
+ */
2483
+ createTextureSet(cfg) {
2484
+ const textureSetId = cfg.id;
2485
+ if (textureSetId === undefined || textureSetId === null) {
2486
+ this.error("[createTextureSet] Config missing: id");
2487
+ return;
2488
+ }
2489
+ if (this._textureSets[textureSetId]) {
2490
+ this.error(`[createTextureSet] Texture set already created: ${textureSetId}`);
2491
+ return;
2492
+ }
2493
+ let colorTexture;
2494
+ if (cfg.colorTextureId !== undefined && cfg.colorTextureId !== null) {
2495
+ colorTexture = this._textures[cfg.colorTextureId];
2496
+ if (!colorTexture) {
2497
+ this.error(`[createTextureSet] Texture not found: ${cfg.colorTextureId} - ensure that you create it first with createTexture()`);
2498
+ return;
2499
+ }
2500
+ } else {
2501
+ colorTexture = this._textures[DEFAULT_COLOR_TEXTURE_ID];
2502
+ }
2503
+ let metallicRoughnessTexture;
2504
+ if (cfg.metallicRoughnessTextureId !== undefined && cfg.metallicRoughnessTextureId !== null) {
2505
+ metallicRoughnessTexture = this._textures[cfg.metallicRoughnessTextureId];
2506
+ if (!metallicRoughnessTexture) {
2507
+ this.error(`[createTextureSet] Texture not found: ${cfg.metallicRoughnessTextureId} - ensure that you create it first with createTexture()`);
2508
+ return;
2509
+ }
2510
+ } else {
2511
+ metallicRoughnessTexture = this._textures[DEFAULT_METAL_ROUGH_TEXTURE_ID];
2512
+ }
2513
+ let normalsTexture;
2514
+ if (cfg.normalsTextureId !== undefined && cfg.normalsTextureId !== null) {
2515
+ normalsTexture = this._textures[cfg.normalsTextureId];
2516
+ if (!normalsTexture) {
2517
+ this.error(`[createTextureSet] Texture not found: ${cfg.normalsTextureId} - ensure that you create it first with createTexture()`);
2518
+ return;
2519
+ }
2520
+ } else {
2521
+ normalsTexture = this._textures[DEFAULT_NORMALS_TEXTURE_ID];
2522
+ }
2523
+ let emissiveTexture;
2524
+ if (cfg.emissiveTextureId !== undefined && cfg.emissiveTextureId !== null) {
2525
+ emissiveTexture = this._textures[cfg.emissiveTextureId];
2526
+ if (!emissiveTexture) {
2527
+ this.error(`[createTextureSet] Texture not found: ${cfg.emissiveTextureId} - ensure that you create it first with createTexture()`);
2528
+ return;
2529
+ }
2530
+ } else {
2531
+ emissiveTexture = this._textures[DEFAULT_EMISSIVE_TEXTURE_ID];
2532
+ }
2533
+ let occlusionTexture;
2534
+ if (cfg.occlusionTextureId !== undefined && cfg.occlusionTextureId !== null) {
2535
+ occlusionTexture = this._textures[cfg.occlusionTextureId];
2536
+ if (!occlusionTexture) {
2537
+ this.error(`[createTextureSet] Texture not found: ${cfg.occlusionTextureId} - ensure that you create it first with createTexture()`);
2538
+ return;
2539
+ }
2540
+ } else {
2541
+ occlusionTexture = this._textures[DEFAULT_OCCLUSION_TEXTURE_ID];
2542
+ }
2543
+ const textureSet = new SceneModelTextureSet({
2544
+ id: textureSetId,
2545
+ model: this,
2546
+ colorTexture,
2547
+ metallicRoughnessTexture,
2548
+ normalsTexture,
2549
+ emissiveTexture,
2550
+ occlusionTexture
2551
+ });
2552
+ this._textureSets[textureSetId] = textureSet;
2553
+ }
2554
+
2555
+ /**
2556
+ * Creates a mesh within this SceneModel.
2557
+ *
2558
+ * A mesh can either define its own geometry or share it with other meshes. To define own geometry, provide the
2559
+ * various geometry arrays to this method. To share a geometry, provide the ID of a geometry created earlier
2560
+ * with {@link SceneModel#createGeometry}.
2561
+ *
2562
+ * Internally, SceneModel will batch all unique mesh geometries into the same arrays, which improves
2563
+ * rendering performance.
2564
+ *
2565
+ * If you accompany the arrays with an ````origin````, then ````createMesh()```` will assume
2566
+ * that the ````positions```` are in relative-to-center (RTC) coordinates, with ````origin```` being the origin of their
2567
+ * RTC coordinate system.
2568
+ *
2569
+ * @param {object} cfg Object properties.
2570
+ * @param {String} cfg.id Mandatory ID for the new mesh. Must not clash with any existing components within the {@link Scene}.
2571
+ * @param {String|Number} [cfg.textureSetId] ID of a texture set previously created with {@link SceneModel#createTextureSet"}.
2572
+ * @param {String|Number} [cfg.geometryId] ID of a geometry to instance, previously created with {@link SceneModel#createGeometry"}. Overrides all other geometry parameters given to this method.
2573
+ * @param {String} cfg.primitive The primitive type. Accepted values are 'points', 'lines', 'triangles', 'solid' and 'surface'.
2574
+ * @param {Number[]} [cfg.positions] Flat array of uncompressed 3D vertex positions positions. Required for all primitive types. Overridden by ````positionsCompressed````.
2575
+ * @param {Number[]} [cfg.positionsCompressed] Flat array of quantized 3D vertex positions. Overrides ````positions````, and must be accompanied by ````positionsDecodeMatrix````.
2576
+ * @param {Number[]} [cfg.positionsDecodeMatrix] A 4x4 matrix for decompressing ````positionsCompressed````. Must be accompanied by ````positionsCompressed````.
2577
+ * @param {Number[]} [cfg.normals] Flat array of normal vectors. Only used with "triangles", "solid" and "surface" primitives. When no normals are given, the geometry will be flat shaded using auto-generated face-aligned normals.
2578
+ * @param {Number[]} [cfg.normalsCompressed] Flat array of oct-encoded normal vectors. Overrides ````normals````. Only used with "triangles", "solid" and "surface" primitives. When no normals are given, the geometry will be flat shaded using auto-generated face-aligned normals.
2579
+ * @param {Number[]} [cfg.colors] Flat array of uncompressed RGBA vertex colors, as float values in range ````[0..1]````. Ignored when ````geometryId```` is given. Overridden by ````color```` and ````colorsCompressed````.
2580
+ * @param {Number[]} [cfg.colorsCompressed] Flat array of compressed RGBA vertex colors, as unsigned short integers in range ````[0..255]````. Ignored when ````geometryId```` is given. Overrides ````colors```` and is overridden by ````color````.
2581
+ * @param {Number[]} [cfg.uv] Flat array of uncompressed vertex UV coordinates. Only used with "triangles", "solid" and "surface" primitives. Required for textured rendering.
2582
+ * @param {Number[]} [cfg.uvCompressed] Flat array of compressed vertex UV coordinates. Only used with "triangles", "solid" and "surface" primitives. Overrides ````uv````. Must be accompanied by ````uvDecodeMatrix````. Only used with "triangles", "solid" and "surface" primitives. Required for textured rendering.
2583
+ * @param {Number[]} [cfg.uvDecodeMatrix] A 3x3 matrix for decompressing ````uvCompressed````.
2584
+ * @param {Number[]} [cfg.indices] Array of primitive connectivity indices. Not required for `points` primitives.
2585
+ * @param {Number[]} [cfg.edgeIndices] Array of edge line indices. Used only with 'triangles', 'solid' and 'surface' primitives. Automatically generated internally if not supplied, using the optional ````edgeThreshold```` given to the ````SceneModel```` constructor.
2586
+ * @param {Number[]} [cfg.origin] Optional geometry origin, relative to {@link SceneModel#origin}. When this is given, then ````positions```` are assumed to be relative to this.
2587
+ * @param {Number[]} [cfg.position=[0,0,0]] Local 3D position of the mesh.
2588
+ * @param {Number[]} [cfg.scale=[1,1,1]] Scale of the mesh.
2589
+ * @param {Number[]} [cfg.rotation=[0,0,0]] Rotation of the mesh as Euler angles given in degrees, for each of the X, Y and Z axis.
2590
+ * @param {Number[]} [cfg.matrix=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]] Mesh modelling transform matrix. Overrides the ````position````, ````scale```` and ````rotation```` parameters.
2591
+ * @param {Number[]} [cfg.color=[1,1,1]] RGB color in range ````[0..1, 0..1, 0..1]````. Overridden by texture set ````colorTexture````. Overrides ````colors```` and ````colorsCompressed````.
2592
+ * @param {Number} [cfg.opacity=1] Opacity in range ````[0..1]````. Overridden by texture set ````colorTexture````.
2593
+ * @param {Number} [cfg.metallic=0] Metallic factor in range ````[0..1]````. Overridden by texture set ````metallicRoughnessTexture````.
2594
+ * @param {Number} [cfg.roughness=1] Roughness factor in range ````[0..1]````. Overridden by texture set ````metallicRoughnessTexture````.
2595
+ */
2596
+ createMesh(cfg) {
2597
+
2598
+ if (cfg.id === undefined || cfg.id === null) {
2599
+ this.error("[createMesh] SceneModel.createMesh() config missing: id");
2600
+ return;
2601
+ }
2602
+
2603
+ if (this._scheduledMeshes[cfg.id]) {
2604
+ this.error(`[createMesh] SceneModel already has a mesh with this ID: ${cfg.id}`);
2605
+ return;
2606
+ }
2607
+
2608
+ const instancing = (cfg.geometryId !== undefined);
2609
+ const batching = !instancing;
2610
+
2611
+ if (batching) {
2612
+
2613
+ // Batched geometry
2614
+
2615
+ if (cfg.primitive === undefined || cfg.primitive === null) {
2616
+ cfg.primitive = "triangles";
2617
+ }
2618
+ if (cfg.primitive !== "points" && cfg.primitive !== "lines" && cfg.primitive !== "triangles" && cfg.primitive !== "solid" && cfg.primitive !== "surface") {
2619
+ this.error(`Unsupported value for 'primitive': '${primitive}' ('geometryId' is absent) - supported values are 'points', 'lines', 'triangles', 'solid' and 'surface'.`);
2620
+ return;
2621
+ }
2622
+ if (!cfg.positions && !cfg.positionsCompressed && !cfg.buckets) {
2623
+ this.error("Param expected: 'positions', 'positionsCompressed' or `buckets` ('geometryId' is absent)");
2624
+ return null;
2625
+ }
2626
+ if (cfg.positions && (cfg.positionsDecodeMatrix || cfg.positionsDecodeBoundary)) {
2627
+ this.error("Illegal params: 'positions' not expected with 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)");
2628
+ return null;
2629
+ }
2630
+ if (cfg.positionsCompressed && !cfg.positionsDecodeMatrix && !cfg.positionsDecodeBoundary) {
2631
+ this.error("Param expected: 'positionsCompressed' should be accompanied by 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)");
2632
+ return null;
2633
+ }
2634
+ if (cfg.uvCompressed && !cfg.uvDecodeMatrix) {
2635
+ this.error("Param expected: 'uvCompressed' should be accompanied by `uvDecodeMatrix` ('geometryId' is absent)");
2636
+ return null;
2637
+ }
2638
+ if (!cfg.buckets && !cfg.indices && cfg.primitive !== "points") {
2639
+ this.error(`Param expected: indices (required for '${cfg.primitive}' primitive type)`);
2640
+ return null;
2641
+ }
2642
+ if ((cfg.matrix || cfg.position || cfg.rotation || cfg.scale) && (cfg.positionsCompressed || cfg.positionsDecodeBoundary)) {
2643
+ this.error("Unexpected params: 'matrix', 'rotation', 'scale', 'position' not allowed with 'positionsCompressed'");
2644
+ return null;
2645
+ }
2646
+
2647
+ const useDTX = (!!this._dtxEnabled && (cfg.primitive === "triangles" || cfg.primitive === "solid" || cfg.primitive === "surface"));
2648
+
2649
+ cfg.origin = cfg.origin ? math.addVec3(this._origin, cfg.origin, math.vec3()) : this._origin;
2650
+
2651
+ // MATRIX - optional for batching
2652
+
2653
+ if (cfg.matrix) {
2654
+ cfg.meshMatrix = cfg.matrix;
2655
+ } else if (cfg.scale || cfg.rotation || cfg.position) {
2656
+ const scale = cfg.scale || DEFAULT_SCALE;
2657
+ const position = cfg.position || DEFAULT_POSITION;
2658
+ const rotation = cfg.rotation || DEFAULT_ROTATION;
2659
+ math.eulerToQuaternion(rotation, "XYZ", DEFAULT_QUATERNION);
2660
+ cfg.meshMatrix = math.composeMat4(position, DEFAULT_QUATERNION, scale, math.mat4());
2661
+ }
2662
+
2663
+ if (cfg.positionsDecodeBoundary) {
2664
+ cfg.positionsDecodeMatrix = createPositionsDecodeMatrix(cfg.positionsDecodeBoundary, math.mat4());
2665
+ }
2666
+
2667
+ if (useDTX) {
2668
+
2669
+ // DTX
2670
+
2671
+ cfg.type = DTX;
2672
+
2673
+ // NPR
2674
+
2675
+ cfg.color = (cfg.color) ? new Uint8Array([Math.floor(cfg.color[0] * 255), Math.floor(cfg.color[1] * 255), Math.floor(cfg.color[2] * 255)]) : defaultCompressedColor;
2676
+ cfg.opacity = (cfg.opacity !== undefined && cfg.opacity !== null) ? Math.floor(cfg.opacity * 255) : 255;
2677
+
2678
+ // RTC
2679
+
2680
+ if (cfg.positions) {
2681
+ const rtcCenter = math.vec3();
2682
+ const rtcPositions = [];
2683
+ const rtcNeeded = worldToRTCPositions(cfg.positions, rtcPositions, rtcCenter);
2684
+ if (rtcNeeded) {
2685
+ cfg.positions = rtcPositions;
2686
+ cfg.origin = math.addVec3(cfg.origin, rtcCenter, rtcCenter);
2687
+ }
2688
+ }
2689
+
2690
+ // COMPRESSION
2691
+
2692
+ if (cfg.positions) {
2693
+ const aabb = math.collapseAABB3();
2694
+ cfg.positionsDecodeMatrix = math.mat4();
2695
+ math.expandAABB3Points3(aabb, cfg.positions);
2696
+ cfg.positionsCompressed = quantizePositions(cfg.positions, aabb, cfg.positionsDecodeMatrix)
2697
+ }
2698
+
2699
+ // EDGES
2700
+
2701
+ if (!cfg.buckets && !cfg.edgeIndices && (cfg.primitive === "triangles" || cfg.primitive === "solid" || cfg.primitive === "surface")) {
2702
+ if (cfg.positions) { // Faster
2703
+ cfg.edgeIndices = buildEdgeIndices(cfg.positions, cfg.indices, null, 2.0);
2704
+ } else {
2705
+ cfg.edgeIndices = buildEdgeIndices(cfg.positionsCompressed, cfg.indices, cfg.positionsDecodeMatrix, 2.0);
2706
+ }
2707
+ }
2708
+
2709
+ // BUCKETING
2710
+
2711
+ if (!cfg.buckets) {
2712
+ cfg.buckets = createDTXBuckets(cfg, this._enableVertexWelding && this._enableIndexBucketing);
2713
+ }
2714
+
2715
+ } else {
2716
+
2717
+ // VBO
2718
+
2719
+ cfg.type = VBO_BATCHED;
2720
+
2721
+ // PBR
2722
+
2723
+ cfg.color = (cfg.color) ? new Uint8Array([Math.floor(cfg.color[0] * 255), Math.floor(cfg.color[1] * 255), Math.floor(cfg.color[2] * 255)]) : [255, 255, 255];
2724
+ cfg.opacity = (cfg.opacity !== undefined && cfg.opacity !== null) ? Math.floor(cfg.opacity * 255) : 255;
2725
+ cfg.metallic = (cfg.metallic !== undefined && cfg.metallic !== null) ? Math.floor(cfg.metallic * 255) : 0;
2726
+ cfg.roughness = (cfg.roughness !== undefined && cfg.roughness !== null) ? Math.floor(cfg.roughness * 255) : 255;
2727
+
2728
+ // RTC
2729
+
2730
+ if (cfg.positions) {
2731
+ const rtcPositions = [];
2732
+ const rtcNeeded = worldToRTCPositions(cfg.positions, rtcPositions, tempVec3a);
2733
+ if (rtcNeeded) {
2734
+ cfg.positions = rtcPositions;
2735
+ cfg.origin = math.addVec3(cfg.origin, tempVec3a, math.vec3());
2736
+ }
2737
+ }
2738
+
2739
+ // EDGES
2740
+
2741
+ if (!cfg.buckets && !cfg.edgeIndices && (cfg.primitive === "triangles" || cfg.primitive === "solid" || cfg.primitive === "surface")) {
2742
+ if (cfg.positions) {
2743
+ cfg.edgeIndices = buildEdgeIndices(cfg.positions, cfg.indices, null, 2.0);
2744
+ } else {
2745
+ cfg.edgeIndices = buildEdgeIndices(cfg.positionsCompressed, cfg.indices, cfg.positionsDecodeMatrix, 2.0);
2746
+ }
2747
+ }
2748
+
2749
+ // TEXTURE
2750
+
2751
+ // cfg.textureSetId = cfg.textureSetId || DEFAULT_TEXTURE_SET_ID;
2752
+ if (cfg.textureSetId) {
2753
+ cfg.textureSet = this._textureSets[cfg.textureSetId];
2754
+ if (!cfg.textureSet) {
2755
+ this.error(`[createMesh] Texture set not found: ${cfg.textureSetId} - ensure that you create it first with createTextureSet()`);
2756
+ return;
2757
+ }
2758
+ }
2759
+ }
2760
+
2761
+ } else {
2762
+
2763
+ // INSTANCING
2764
+
2765
+ if (cfg.positions || cfg.positionsCompressed || cfg.indices || cfg.edgeIndices || cfg.normals || cfg.normalsCompressed || cfg.uv || cfg.uvCompressed || cfg.positionsDecodeMatrix) {
2766
+ this.error(`Mesh geometry parameters not expected when instancing a geometry (not expected: positions, positionsCompressed, indices, edgeIndices, normals, normalsCompressed, uv, uvCompressed, positionsDecodeMatrix)`);
2767
+ return;
2768
+ }
2769
+
2770
+ cfg.geometry = this._geometries[cfg.geometryId];
2771
+ if (!cfg.geometry) {
2772
+ this.error(`[createMesh] Geometry not found: ${cfg.geometryId} - ensure that you create it first with createGeometry()`);
2773
+ return;
2774
+ }
2775
+
2776
+ cfg.origin = cfg.origin ? math.addVec3(this._origin, cfg.origin, math.vec3()) : this._origin;
2777
+ cfg.positionsDecodeMatrix = cfg.geometry.positionsDecodeMatrix;
2778
+
2779
+ // MATRIX - always have a matrix for instancing
2780
+
2781
+ if (cfg.matrix) {
2782
+ cfg.meshMatrix = cfg.matrix.slice();
2783
+ } else {
2784
+ const scale = cfg.scale || DEFAULT_SCALE;
2785
+ const position = cfg.position || DEFAULT_POSITION;
2786
+ const rotation = cfg.rotation || DEFAULT_ROTATION;
2787
+ math.eulerToQuaternion(rotation, "XYZ", DEFAULT_QUATERNION);
2788
+ cfg.meshMatrix = math.composeMat4(position, DEFAULT_QUATERNION, scale, math.mat4());
2789
+ }
2790
+
2791
+ const useDTX = (!!this._dtxEnabled && (cfg.geometry.primitive === "triangles" || cfg.geometry.primitive === "solid" || cfg.geometry.primitive === "surface"));
2792
+
2793
+ if (useDTX) {
2794
+
2795
+ // DTX
2796
+
2797
+ cfg.type = DTX;
2798
+
2799
+ // NPR
2800
+
2801
+ cfg.color = (cfg.color) ? new Uint8Array([Math.floor(cfg.color[0] * 255), Math.floor(cfg.color[1] * 255), Math.floor(cfg.color[2] * 255)]) : defaultCompressedColor;
2802
+ cfg.opacity = (cfg.opacity !== undefined && cfg.opacity !== null) ? Math.floor(cfg.opacity * 255) : 255;
2803
+
2804
+ // BUCKETING - lazy generated, reused
2805
+
2806
+ let buckets = this._dtxBuckets[cfg.geometryId];
2807
+ if (!buckets) {
2808
+ buckets = createDTXBuckets(cfg.geometry, this._enableVertexWelding, this._enableIndexBucketing);
2809
+ this._dtxBuckets[cfg.geometryId] = buckets;
2810
+ }
2811
+ cfg.buckets = buckets;
2812
+
2813
+ } else {
2814
+
2815
+ // VBO
2816
+
2817
+ cfg.type = VBO_INSTANCED;
2818
+
2819
+ // PBR
2820
+
2821
+ cfg.color = (cfg.color) ? new Uint8Array([Math.floor(cfg.color[0] * 255), Math.floor(cfg.color[1] * 255), Math.floor(cfg.color[2] * 255)]) : defaultCompressedColor;
2822
+ cfg.opacity = (cfg.opacity !== undefined && cfg.opacity !== null) ? Math.floor(cfg.opacity * 255) : 255;
2823
+ cfg.metallic = (cfg.metallic !== undefined && cfg.metallic !== null) ? Math.floor(cfg.metallic * 255) : 0;
2824
+ cfg.roughness = (cfg.roughness !== undefined && cfg.roughness !== null) ? Math.floor(cfg.roughness * 255) : 255;
2825
+
2826
+ // TEXTURE
2827
+
2828
+ if (cfg.textureSetId) {
2829
+ cfg.textureSet = this._textureSets[cfg.textureSetId];
2830
+ // if (!cfg.textureSet) {
2831
+ // this.error(`[createMesh] Texture set not found: ${cfg.textureSetId} - ensure that you create it first with createTextureSet()`);
2832
+ // return;
2833
+ // }
2834
+ }
2835
+
2836
+ // OBB - used for fast AABB calculation
2837
+
2838
+ createGeometryOBB(cfg.geometry)
2839
+ }
2840
+ }
2841
+
2842
+ cfg.numPrimitives = this._getNumPrimitives(cfg);
2843
+
2844
+ if (this._vfcManager && !this._vfcManager.finalized) {
2845
+ this._vfcManager.addMesh(cfg); // Deferred so VFC manager can cluster meshes for GPU cache locality
2846
+ } else {
2847
+ this._createMesh(cfg);
2848
+ }
2849
+ }
2850
+
2851
+ _createMesh(cfg) {
2852
+
2853
+ const mesh = new SceneModelMesh(this, cfg.id, cfg.color, cfg.opacity);
2854
+
2855
+ mesh.pickId = this.scene._renderer.getPickID(mesh);
2856
+
2857
+ const pickId = mesh.pickId;
2858
+ const a = pickId >> 24 & 0xFF;
2859
+ const b = pickId >> 16 & 0xFF;
2860
+ const g = pickId >> 8 & 0xFF;
2861
+ const r = pickId & 0xFF;
2862
+
2863
+ cfg.pickColor = new Uint8Array([r, g, b, a]); // Quantized pick color
2864
+ cfg.worldAABB = math.collapseAABB3();
2865
+ cfg.aabb = cfg.worldAABB; /// Hack for VBOInstancing layer
2866
+ cfg.solid = (cfg.primitive === "solid");
2867
+ mesh.origin = math.vec3(cfg.origin);
2868
+ switch (cfg.type) {
2869
+ case DTX:
2870
+ mesh.layer = this._getDTXLayer(cfg);
2871
+ break;
2872
+ case VBO_BATCHED:
2873
+ mesh.layer = this._getVBOBatchingLayer(cfg);
2874
+ break;
2875
+ case VBO_INSTANCED:
2876
+ mesh.layer = this._getVBOInstancingLayer(cfg);
2877
+ break;
2878
+ }
2879
+ mesh.portionId = mesh.layer.createPortion(cfg);
2880
+ mesh.aabb = cfg.worldAABB;
2881
+ mesh.numPrimitives = cfg.numPrimitives;
2882
+ math.expandAABB3(this._aabb, mesh.aabb);
2883
+ this._meshes[cfg.id] = mesh;
2884
+ this._meshList.push(mesh);
2885
+ }
2886
+
2887
+ _getNumPrimitives(cfg) {
2888
+ let countIndices = 0;
2889
+ const primitive = cfg.geometry ? cfg.geometry.primitive : cfg.primitive;
2890
+ switch (primitive) {
2891
+ case "triangles":
2892
+ case "solid":
2893
+ case "surface":
2894
+ switch (cfg.type) {
2895
+ case DTX:
2896
+ for (let i = 0, len = cfg.buckets.length; i < len; i++) {
2897
+ countIndices += cfg.buckets[i].indices.length;
2898
+ }
2899
+ break;
2900
+ case VBO_BATCHED:
2901
+ countIndices += cfg.indices.length;
2902
+ break;
2903
+ case VBO_INSTANCED:
2904
+ countIndices += cfg.geometry.indices.length;
2905
+ break;
2906
+ }
2907
+ return Math.round(countIndices / 3);
2908
+ case "points":
2909
+ switch (cfg.type) {
2910
+ case DTX:
2911
+ for (let i = 0, len = cfg.buckets.length; i < len; i++) {
2912
+ countIndices += cfg.buckets[i].positionsCompressed.length;
2913
+ }
2914
+ break;
2915
+ case VBO_BATCHED:
2916
+ countIndices += cfg.positions ? cfg.positions.length : cfg.positionsCompressed.length;
2917
+ break;
2918
+ case VBO_INSTANCED:
2919
+ countIndices += cfg.positions ? cfg.positions.length : cfg.positionsCompressed.length;
2920
+ break;
2921
+ }
2922
+ return Math.round(countIndices);
2923
+ case "lines":
2924
+ case "line-strip":
2925
+ switch (cfg.type) {
2926
+ case DTX:
2927
+ for (let i = 0, len = cfg.buckets.length; i < len; i++) {
2928
+ countIndices += cfg.buckets[i].indices.length;
2929
+ }
2930
+ break;
2931
+ case VBO_BATCHED:
2932
+ countIndices += cfg.indices.length;
2933
+ break;
2934
+ case VBO_INSTANCED:
2935
+ countIndices += cfg.geometry.indices.length;
2936
+ break;
2937
+ }
2938
+ return Math.round(countIndices / 2);
2939
+ }
2940
+ return 0;
2941
+ }
2942
+
2943
+ _getDTXLayer(cfg) {
2944
+ const origin = cfg.origin;
2945
+ const layerId = `${Math.round(origin[0])}.${Math.round(origin[1])}.${Math.round(origin[2])}`;
2946
+ let dtxLayer = this._dtxLayers[layerId];
2947
+ if (dtxLayer) {
2948
+ if (!dtxLayer.canCreatePortion(cfg)) {
2949
+ dtxLayer.finalize();
2950
+ delete this._dtxLayers[layerId];
2951
+ dtxLayer = null;
2952
+ } else {
2953
+ return dtxLayer;
2954
+ }
2955
+ }
2956
+ console.log(`[SceneModel ${this.id}]: creating TrianglesDataTextureLayer`);
2957
+ dtxLayer = new TrianglesDataTextureLayer(this, {layerIndex: 0, origin}); // layerIndex is set in #finalize()
2958
+ this._dtxLayers[layerId] = dtxLayer;
2959
+ this.layerList.push(dtxLayer);
2960
+ return dtxLayer;
2961
+ }
2962
+
2963
+ _getVBOBatchingLayer(cfg) {
2964
+ const model = this;
2965
+ const origin = cfg.origin;
2966
+ const positionsDecodeHash = cfg.positionsDecodeMatrix || cfg.positionsDecodeBoundary ?
2967
+ this._createHashStringFromMatrix(cfg.positionsDecodeMatrix || cfg.positionsDecodeBoundary)
2968
+ : "-";
2969
+ const textureSetId = cfg.textureSetId || "-";
2970
+ const layerId = `${Math.round(origin[0])}.${Math.round(origin[1])}.${Math.round(origin[2])}.${cfg.primitive}.${positionsDecodeHash}.${textureSetId}`;
2971
+ let vboBatchingLayer = this._vboBatchingLayers[layerId];
2972
+ if (vboBatchingLayer) {
2973
+ return vboBatchingLayer;
2974
+ }
2975
+ let textureSet = cfg.textureSet;
2976
+ while (!vboBatchingLayer) {
2977
+ switch (cfg.primitive) {
2978
+ case "triangles":
2979
+ console.log(`[SceneModel ${this.id}]: creating TrianglesBatchingLayer`);
2980
+ vboBatchingLayer = new TrianglesBatchingLayer({
2981
+ model,
2982
+ textureSet,
2983
+ layerIndex: 0, // This is set in #finalize()
2984
+ scratchMemory: this._vboBatchingLayerScratchMemory,
2985
+ positionsDecodeMatrix: cfg.positionsDecodeMatrix, // Can be undefined
2986
+ uvDecodeMatrix: cfg.uvDecodeMatrix, // Can be undefined
2987
+ origin,
2988
+ maxGeometryBatchSize: this._maxGeometryBatchSize,
2989
+ solid: (cfg.primitive === "solid"),
2990
+ autoNormals: true
2991
+ });
2992
+ break;
2993
+ case "solid":
2994
+ console.log(`[SceneModel ${this.id}]: creating TrianglesBatchingLayer`);
2995
+ vboBatchingLayer = new TrianglesBatchingLayer({
2996
+ model,
2997
+ textureSet,
2998
+ layerIndex: 0, // This is set in #finalize()
2999
+ scratchMemory: this._vboBatchingLayerScratchMemory,
3000
+ positionsDecodeMatrix: cfg.positionsDecodeMatrix, // Can be undefined
3001
+ uvDecodeMatrix: cfg.uvDecodeMatrix, // Can be undefined
3002
+ origin,
3003
+ maxGeometryBatchSize: this._maxGeometryBatchSize,
3004
+ solid: (cfg.primitive === "solid"),
3005
+ autoNormals: true
3006
+ });
3007
+ break;
3008
+ case "surface":
3009
+ console.log(`[SceneModel ${this.id}]: creating TrianglesBatchingLayer`);
3010
+ vboBatchingLayer = new TrianglesBatchingLayer({
3011
+ model,
3012
+ textureSet,
3013
+ layerIndex: 0, // This is set in #finalize()
3014
+ scratchMemory: this._vboBatchingLayerScratchMemory,
3015
+ positionsDecodeMatrix: cfg.positionsDecodeMatrix, // Can be undefined
3016
+ uvDecodeMatrix: cfg.uvDecodeMatrix, // Can be undefined
3017
+ origin,
3018
+ maxGeometryBatchSize: this._maxGeometryBatchSize,
3019
+ solid: (cfg.primitive === "solid"),
3020
+ autoNormals: true
3021
+ });
3022
+ break;
3023
+ case "lines":
3024
+ console.log(`[SceneModel ${this.id}]: creating LinesBatchingLayer`);
3025
+ vboBatchingLayer = new LinesBatchingLayer({
3026
+ model,
3027
+ layerIndex: 0, // This is set in #finalize()
3028
+ scratchMemory: this._vboBatchingLayerScratchMemory,
3029
+ positionsDecodeMatrix: cfg.positionsDecodeMatrix, // Can be undefined
3030
+ uvDecodeMatrix: cfg.uvDecodeMatrix, // Can be undefined
3031
+ origin,
3032
+ maxGeometryBatchSize: this._maxGeometryBatchSize
3033
+ });
3034
+ break;
3035
+ case "points":
3036
+ console.log(`[SceneModel ${this.id}]: creating PointsBatchingLayer`);
3037
+ vboBatchingLayer = new PointsBatchingLayer({
3038
+ model,
3039
+ layerIndex: 0, // This is set in #finalize()
3040
+ scratchMemory: this._vboBatchingLayerScratchMemory,
3041
+ positionsDecodeMatrix: cfg.positionsDecodeMatrix, // Can be undefined
3042
+ uvDecodeMatrix: cfg.uvDecodeMatrix, // Can be undefined
3043
+ origin,
3044
+ maxGeometryBatchSize: this._maxGeometryBatchSize
3045
+ });
3046
+ break;
3047
+ }
3048
+ const lenPositions = cfg.positionsCompressed ? cfg.positionsCompressed.length : cfg.positions.length;
3049
+ const canCreatePortion = (cfg.primitive === "points")
3050
+ ? vboBatchingLayer.canCreatePortion(lenPositions)
3051
+ : vboBatchingLayer.canCreatePortion(lenPositions, cfg.indices.length);
3052
+ if (!canCreatePortion) {
3053
+ vboBatchingLayer.finalize();
3054
+ delete this._vboBatchingLayers[layerId];
3055
+ vboBatchingLayer = null;
3056
+ }
3057
+ }
3058
+ this._vboBatchingLayers[layerId] = vboBatchingLayer;
3059
+ this.layerList.push(vboBatchingLayer);
3060
+ return vboBatchingLayer;
3061
+ }
3062
+
3063
+ _createHashStringFromMatrix(matrix) {
3064
+ const matrixString = matrix.join('');
3065
+ let hash = 0;
3066
+ for (let i = 0; i < matrixString.length; i++) {
3067
+ const char = matrixString.charCodeAt(i);
3068
+ hash = (hash << 5) - hash + char;
3069
+ hash |= 0; // Convert to 32-bit integer
3070
+ }
3071
+ const hashString = (hash >>> 0).toString(16);
3072
+ return hashString;
3073
+ }
3074
+
3075
+ _getVBOInstancingLayer(cfg) {
3076
+ const model = this;
3077
+ const origin = cfg.origin;
3078
+ const textureSetId = cfg.textureSetId || "-";
3079
+ const geometryId = cfg.geometryId;
3080
+ const layerId = `${Math.round(origin[0])}.${Math.round(origin[1])}.${Math.round(origin[2])}.${textureSetId}.${geometryId}`;
3081
+ let vboInstancingLayer = this._vboInstancingLayers[layerId];
3082
+ if (vboInstancingLayer) {
3083
+ return vboInstancingLayer;
3084
+ }
3085
+ let textureSet = cfg.textureSet;
3086
+ const geometry = cfg.geometry;
3087
+ while (!vboInstancingLayer) {
3088
+ switch (geometry.primitive) {
3089
+ case "triangles":
3090
+ console.log(`[SceneModel ${this.id}]: creating TrianglesInstancingLayer`);
3091
+ vboInstancingLayer = new TrianglesInstancingLayer({
3092
+ model,
3093
+ textureSet,
3094
+ geometry,
3095
+ origin,
3096
+ layerIndex: 0,
3097
+ solid: false
3098
+ });
3099
+ break;
3100
+ case "solid":
3101
+ console.log(`[SceneModel ${this.id}]: creating TrianglesInstancingLayer`);
3102
+ vboInstancingLayer = new TrianglesInstancingLayer({
3103
+ model,
3104
+ textureSet,
3105
+ geometry,
3106
+ origin,
3107
+ layerIndex: 0,
3108
+ solid: true
3109
+ });
3110
+ break;
3111
+ case "surface":
3112
+ console.log(`[SceneModel ${this.id}]: creating TrianglesInstancingLayer`);
3113
+ vboInstancingLayer = new TrianglesInstancingLayer({
3114
+ model,
3115
+ textureSet,
3116
+ geometry,
3117
+ origin,
3118
+ layerIndex: 0,
3119
+ solid: false
3120
+ });
3121
+ break;
3122
+ case "lines":
3123
+ console.log(`[SceneModel ${this.id}]: creating LinesInstancingLayer`);
3124
+ vboInstancingLayer = new LinesInstancingLayer({
3125
+ model,
3126
+ textureSet,
3127
+ geometry,
3128
+ origin,
3129
+ layerIndex: 0
3130
+ });
3131
+ break;
3132
+ case "points":
3133
+ console.log(`[SceneModel ${this.id}]: creating PointsInstancingLayer`);
3134
+ vboInstancingLayer = new PointsInstancingLayer({
3135
+ model,
3136
+ textureSet,
3137
+ geometry,
3138
+ origin,
3139
+ layerIndex: 0
3140
+ });
3141
+ break;
3142
+ }
3143
+ // const lenPositions = geometry.positionsCompressed.length;
3144
+ // if (!vboInstancingLayer.canCreatePortion(lenPositions, geometry.indices.length)) { // FIXME: indices should be optional
3145
+ // vboInstancingLayer.finalize();
3146
+ // delete this._vboInstancingLayers[layerId];
3147
+ // vboInstancingLayer = null;
3148
+ // }
3149
+ }
3150
+ this._vboInstancingLayers[layerId] = vboInstancingLayer;
3151
+ this.layerList.push(vboInstancingLayer);
3152
+ return vboInstancingLayer;
3153
+ }
3154
+
3155
+ /**
3156
+ * Creates an {@link Entity} within this SceneModel, giving it one or more meshes previously created with {@link SceneModel#createMesh}.
3157
+ *
3158
+ * A mesh can only belong to one {@link Entity}, so you'll get an error if you try to reuse a mesh among multiple {@link Entity}s.
3159
+ *
3160
+ * @param {Object} cfg Entity configuration.
3161
+ * @param {String} cfg.id Optional ID for the new Entity. Must not clash with any existing components within the {@link Scene}.
3162
+ * @param {String[]} cfg.meshIds IDs of one or more meshes created previously with {@link SceneModel@createMesh}.
3163
+
3164
+ * @param {Boolean} [cfg.isObject] Set ````true```` if the {@link Entity} represents an object, in which case it will be registered by {@link Entity#id} in {@link Scene#objects} and can also have a corresponding {@link MetaObject} with matching {@link MetaObject#id}, registered by that ID in {@link MetaScene#metaObjects}.
3165
+ * @param {Boolean} [cfg.visible=true] Indicates if the Entity is initially visible.
3166
+ * @param {Boolean} [cfg.culled=false] Indicates if the Entity is initially culled from view.
3167
+ * @param {Boolean} [cfg.pickable=true] Indicates if the Entity is initially pickable.
3168
+ * @param {Boolean} [cfg.clippable=true] Indicates if the Entity is initially clippable.
3169
+ * @param {Boolean} [cfg.collidable=true] Indicates if the Entity is initially included in boundary calculations.
3170
+ * @param {Boolean} [cfg.castsShadow=true] Indicates if the Entity initially casts shadows.
3171
+ * @param {Boolean} [cfg.receivesShadow=true] Indicates if the Entity initially receives shadows.
3172
+ * @param {Boolean} [cfg.xrayed=false] Indicates if the Entity is initially xrayed. XRayed appearance is configured by {@link SceneModel#xrayMaterial}.
3173
+ * @param {Boolean} [cfg.highlighted=false] Indicates if the Entity is initially highlighted. Highlighted appearance is configured by {@link SceneModel#highlightMaterial}.
3174
+ * @param {Boolean} [cfg.selected=false] Indicates if the Entity is initially selected. Selected appearance is configured by {@link SceneModel#selectedMaterial}.
3175
+ * @param {Boolean} [cfg.edges=false] Indicates if the Entity's edges are initially emphasized. Edges appearance is configured by {@link SceneModel#edgeMaterial}.
3176
+ * @param {Boolean} [cfg.lodCullable=true] Indicates if the Entity can be LoD culled. LoD culling isconfigured by {@link LOD}.
3177
+ * @returns {Entity}
3178
+ */
3179
+ createEntity(cfg) {
3180
+ if (cfg.id === undefined) {
3181
+ cfg.id = math.createUUID();
3182
+ } else if (this.scene.components[cfg.id]) {
3183
+ this.error(`Scene already has a Component with this ID: ${cfg.id} - will assign random ID`);
3184
+ cfg.id = math.createUUID();
3185
+ }
3186
+ if (cfg.meshIds === undefined) {
3187
+ this.error("Config missing: meshIds");
3188
+ return;
3189
+ }
3190
+ let flags = 0;
3191
+ if (this._visible && cfg.visible !== false) {
3192
+ flags = flags | ENTITY_FLAGS.VISIBLE;
3193
+ }
3194
+ if (this._pickable && cfg.pickable !== false) {
3195
+ flags = flags | ENTITY_FLAGS.PICKABLE;
3196
+ }
3197
+ if (this._culled && cfg.culled !== false) {
3198
+ flags = flags | ENTITY_FLAGS.CULLED;
3199
+ }
3200
+ if (this._clippable && cfg.clippable !== false) {
3201
+ flags = flags | ENTITY_FLAGS.CLIPPABLE;
3202
+ }
3203
+ if (this._collidable && cfg.collidable !== false) {
3204
+ flags = flags | ENTITY_FLAGS.COLLIDABLE;
3205
+ }
3206
+ if (this._edges && cfg.edges !== false) {
3207
+ flags = flags | ENTITY_FLAGS.EDGES;
3208
+ }
3209
+ if (this._xrayed && cfg.xrayed !== false) {
3210
+ flags = flags | ENTITY_FLAGS.XRAYED;
3211
+ }
3212
+ if (this._highlighted && cfg.highlighted !== false) {
3213
+ flags = flags | ENTITY_FLAGS.HIGHLIGHTED;
3214
+ }
3215
+ if (this._selected && cfg.selected !== false) {
3216
+ flags = flags | ENTITY_FLAGS.SELECTED;
3217
+ }
3218
+ cfg.flags = flags;
3219
+ if (this._vfcManager && !this._vfcManager.finalized) {
3220
+ for (let i = 0, len = cfg.meshIds.length; i < len; i++) {
3221
+ const meshId = cfg.meshIds[i];
3222
+ if (this._scheduledMeshes[meshId]) {
3223
+ this.error(`[createEntity] Mesh not found: ${meshId}`);
3224
+ return;
3225
+ }
3226
+ }
3227
+ this._vfcManager.addEntity(cfg);
3228
+ } else {
3229
+ this._createEntity(cfg);
3230
+ }
3231
+ }
3232
+
3233
+ _createEntity(cfg) {
3234
+ let meshes = [];
3235
+ const aabb = math.collapseAABB3();
3236
+ for (let i = 0, len = cfg.meshIds.length; i < len; i++) {
3237
+ const meshId = cfg.meshIds[i];
3238
+ const mesh = this._meshes[meshId];
3239
+ if (!mesh) {
3240
+ this.error(`Mesh with this ID not found: "${meshId}" - ignoring this mesh`);
3241
+ continue;
3242
+ }
3243
+ if (mesh.parent) {
3244
+ this.error(`Mesh with ID "${meshId}" already belongs to object with ID "${mesh.parent.id}" - ignoring this mesh`);
3245
+ continue;
3246
+ }
3247
+ math.expandAABB3(aabb, mesh.aabb);
3248
+ meshes.push(mesh);
3249
+ }
3250
+ const lodCullable = true;
3251
+ const entity = new SceneModelEntity(
3252
+ this,
3253
+ cfg.isObject,
3254
+ cfg.id,
3255
+ meshes,
3256
+ cfg.flags,
3257
+ aabb,
3258
+ lodCullable); // Internally sets SceneModelEntity#parent to this SceneModel
3259
+ this._entityList.push(entity);
3260
+ this._entities[cfg.id] = entity;
3261
+ this.numEntities++;
3262
+ }
3263
+
3264
+ /**
3265
+ * Finalizes this SceneModel.
3266
+ *
3267
+ * Immediately creates the SceneModel's {@link Entity}s within the {@link Scene}.
3268
+ *
3269
+ * Once finalized, you can't add anything more to this SceneModel.
3270
+ */
3271
+ finalize() {
3272
+ if (this.destroyed) {
3273
+ return;
3274
+ }
3275
+ if (this._vfcManager) {
3276
+ this._vfcManager.finalize(() => {// Makes deferred calls to #_createEntity() and #_createMesh()
3277
+ });
3278
+ }
3279
+ for (let i = 0, len = this.layerList.length; i < len; i++) {
3280
+ const layer = this.layerList[i];
3281
+ layer.finalize();
3282
+ }
3283
+ this._geometries = {};
3284
+ this._dtxBuckets = {};
3285
+ this._textures = {};
3286
+ this._textureSets = {};
3287
+ this._dtxLayers = {};
3288
+ this._vboInstancingLayers = {};
3289
+ this._vboBatchingLayers = {};
3290
+ for (let i = 0, len = this._entityList.length; i < len; i++) {
3291
+ const entity = this._entityList[i];
3292
+ entity._finalize();
3293
+ }
3294
+ for (let i = 0, len = this._entityList.length; i < len; i++) {
3295
+ const entity = this._entityList[i];
3296
+ entity._finalize2();
3297
+ }
3298
+ // Sort layers to reduce WebGL shader switching when rendering them
3299
+ this.layerList.sort((a, b) => {
3300
+ if (a.sortId < b.sortId) {
3301
+ return -1;
3302
+ }
3303
+ if (a.sortId > b.sortId) {
3304
+ return 1;
3305
+ }
3306
+ return 0;
3307
+ });
3308
+ for (let i = 0, len = this.layerList.length; i < len; i++) {
3309
+ const layer = this.layerList[i];
3310
+ layer.layerIndex = i;
3311
+ }
3312
+ this.glRedraw();
3313
+ this.scene._aabbDirty = true;
3314
+ if (this.scene.lod.enabled) {
3315
+ this._lodManager = this.scene.lod.getLODManager(this);
3316
+ }
3317
+
3318
+ this._viewMatrixDirty = true;
3319
+ this._matrixDirty = true;
3320
+ this._aabbDirty = true;
3321
+
3322
+ this._setWorldMatrixDirty();
3323
+ this._setWorldAABBDirty();
3324
+
3325
+ this.position = this._position;
3326
+ }
3327
+
3328
+ /** @private */
3329
+ stateSortCompare(drawable1, drawable2) {
3330
+ }
3331
+
3332
+ /** @private */
3333
+ rebuildRenderFlags() {
3334
+ this.renderFlags.reset();
3335
+ this._updateRenderFlagsVisibleLayers();
3336
+ if (this.renderFlags.numLayers > 0 && this.renderFlags.numVisibleLayers === 0) {
3337
+ this.renderFlags.culled = true;
3338
+ return;
3339
+ }
3340
+ this._updateRenderFlags();
3341
+ }
3342
+
3343
+ /**
3344
+ * @private
3345
+ */
3346
+ _updateRenderFlagsVisibleLayers() {
3347
+ const renderFlags = this.renderFlags;
3348
+ renderFlags.numLayers = this.layerList.length;
3349
+ renderFlags.numVisibleLayers = 0;
3350
+ for (let layerIndex = 0, len = this.layerList.length; layerIndex < len; layerIndex++) {
3351
+ const layer = this.layerList[layerIndex];
3352
+ const layerVisible = this._getActiveSectionPlanesForLayer(layer);
3353
+ if (layerVisible) {
3354
+ renderFlags.visibleLayers[renderFlags.numVisibleLayers++] = layerIndex;
3355
+ }
3356
+ }
3357
+ }
3358
+
3359
+ _getActiveSectionPlanesForLayer(layer) {
3360
+ const renderFlags = this.renderFlags;
3361
+ const sectionPlanes = this.scene._sectionPlanesState.sectionPlanes;
3362
+ const numSectionPlanes = sectionPlanes.length;
3363
+ const baseIndex = layer.layerIndex * numSectionPlanes;
3364
+ if (numSectionPlanes > 0) {
3365
+ for (let i = 0; i < numSectionPlanes; i++) {
3366
+ const sectionPlane = sectionPlanes[i];
3367
+ if (!sectionPlane.active) {
3368
+ renderFlags.sectionPlanesActivePerLayer[baseIndex + i] = false;
3369
+ } else {
3370
+ renderFlags.sectionPlanesActivePerLayer[baseIndex + i] = true;
3371
+ renderFlags.sectioned = true;
3372
+ }
3373
+ }
3374
+ }
3375
+ return true;
3376
+ }
3377
+
3378
+ _updateRenderFlags() {
3379
+ if (this.numVisibleLayerPortions === 0) {
3380
+ return;
3381
+ }
3382
+ if (this.numCulledLayerPortions === this.numPortions) {
3383
+ return;
3384
+ }
3385
+ const renderFlags = this.renderFlags;
3386
+ renderFlags.colorOpaque = (this.numTransparentLayerPortions < this.numPortions);
3387
+ if (this.numTransparentLayerPortions > 0) {
3388
+ renderFlags.colorTransparent = true;
3389
+ }
3390
+ if (this.numXRayedLayerPortions > 0) {
3391
+ const xrayMaterial = this.scene.xrayMaterial._state;
3392
+ if (xrayMaterial.fill) {
3393
+ if (xrayMaterial.fillAlpha < 1.0) {
3394
+ renderFlags.xrayedSilhouetteTransparent = true;
3395
+ } else {
3396
+ renderFlags.xrayedSilhouetteOpaque = true;
3397
+ }
3398
+ }
3399
+ if (xrayMaterial.edges) {
3400
+ if (xrayMaterial.edgeAlpha < 1.0) {
3401
+ renderFlags.xrayedEdgesTransparent = true;
3402
+ } else {
3403
+ renderFlags.xrayedEdgesOpaque = true;
3404
+ }
3405
+ }
3406
+ }
3407
+ if (this.numEdgesLayerPortions > 0) {
3408
+ const edgeMaterial = this.scene.edgeMaterial._state;
3409
+ if (edgeMaterial.edges) {
3410
+ renderFlags.edgesOpaque = (this.numTransparentLayerPortions < this.numPortions);
3411
+ if (this.numTransparentLayerPortions > 0) {
3412
+ renderFlags.edgesTransparent = true;
3413
+ }
3414
+ }
3415
+ }
3416
+ if (this.numSelectedLayerPortions > 0) {
3417
+ const selectedMaterial = this.scene.selectedMaterial._state;
3418
+ if (selectedMaterial.fill) {
3419
+ if (selectedMaterial.fillAlpha < 1.0) {
3420
+ renderFlags.selectedSilhouetteTransparent = true;
3421
+ } else {
3422
+ renderFlags.selectedSilhouetteOpaque = true;
3423
+ }
3424
+ }
3425
+ if (selectedMaterial.edges) {
3426
+ if (selectedMaterial.edgeAlpha < 1.0) {
3427
+ renderFlags.selectedEdgesTransparent = true;
3428
+ } else {
3429
+ renderFlags.selectedEdgesOpaque = true;
3430
+ }
3431
+ }
3432
+ }
3433
+ if (this.numHighlightedLayerPortions > 0) {
3434
+ const highlightMaterial = this.scene.highlightMaterial._state;
3435
+ if (highlightMaterial.fill) {
3436
+ if (highlightMaterial.fillAlpha < 1.0) {
3437
+ renderFlags.highlightedSilhouetteTransparent = true;
3438
+ } else {
3439
+ renderFlags.highlightedSilhouetteOpaque = true;
3440
+ }
3441
+ }
3442
+ if (highlightMaterial.edges) {
3443
+ if (highlightMaterial.edgeAlpha < 1.0) {
3444
+ renderFlags.highlightedEdgesTransparent = true;
3445
+ } else {
3446
+ renderFlags.highlightedEdgesOpaque = true;
3447
+ }
3448
+ }
3449
+ }
3450
+ }
3451
+
3452
+ // -------------- RENDERING ---------------------------------------------------------------------------------------
3453
+
3454
+ /** @private */
3455
+ drawColorOpaque(frameCtx) {
3456
+ const renderFlags = this.renderFlags;
3457
+ for (let i = 0, len = renderFlags.visibleLayers.length; i < len; i++) {
3458
+ const layerIndex = renderFlags.visibleLayers[i];
3459
+ this.layerList[layerIndex].drawColorOpaque(renderFlags, frameCtx);
3460
+ }
3461
+ }
3462
+
3463
+ /** @private */
3464
+ drawColorTransparent(frameCtx) {
3465
+ const renderFlags = this.renderFlags;
3466
+ for (let i = 0, len = renderFlags.visibleLayers.length; i < len; i++) {
3467
+ const layerIndex = renderFlags.visibleLayers[i];
3468
+ this.layerList[layerIndex].drawColorTransparent(renderFlags, frameCtx);
3469
+ }
3470
+ }
3471
+
3472
+ /** @private */
3473
+ drawDepth(frameCtx) { // Dedicated to SAO because it skips transparent objects
3474
+ const renderFlags = this.renderFlags;
3475
+ for (let i = 0, len = renderFlags.visibleLayers.length; i < len; i++) {
3476
+ const layerIndex = renderFlags.visibleLayers[i];
3477
+ this.layerList[layerIndex].drawDepth(renderFlags, frameCtx);
3478
+ }
3479
+ }
3480
+
3481
+ /** @private */
3482
+ drawNormals(frameCtx) { // Dedicated to SAO because it skips transparent objects
3483
+ const renderFlags = this.renderFlags;
3484
+ for (let i = 0, len = renderFlags.visibleLayers.length; i < len; i++) {
3485
+ const layerIndex = renderFlags.visibleLayers[i];
3486
+ this.layerList[layerIndex].drawNormals(renderFlags, frameCtx);
3487
+ }
3488
+ }
3489
+
3490
+ /** @private */
3491
+ drawSilhouetteXRayed(frameCtx) {
3492
+ const renderFlags = this.renderFlags;
3493
+ for (let i = 0, len = renderFlags.visibleLayers.length; i < len; i++) {
3494
+ const layerIndex = renderFlags.visibleLayers[i];
3495
+ this.layerList[layerIndex].drawSilhouetteXRayed(renderFlags, frameCtx);
3496
+ }
3497
+ }
3498
+
3499
+ /** @private */
3500
+ drawSilhouetteHighlighted(frameCtx) {
3501
+ const renderFlags = this.renderFlags;
3502
+ for (let i = 0, len = renderFlags.visibleLayers.length; i < len; i++) {
3503
+ const layerIndex = renderFlags.visibleLayers[i];
3504
+ this.layerList[layerIndex].drawSilhouetteHighlighted(renderFlags, frameCtx);
3505
+ }
3506
+ }
3507
+
3508
+ /** @private */
3509
+ drawSilhouetteSelected(frameCtx) {
3510
+ const renderFlags = this.renderFlags;
3511
+ for (let i = 0, len = renderFlags.visibleLayers.length; i < len; i++) {
3512
+ const layerIndex = renderFlags.visibleLayers[i];
3513
+ this.layerList[layerIndex].drawSilhouetteSelected(renderFlags, frameCtx);
3514
+ }
3515
+ }
3516
+
3517
+ /** @private */
3518
+ drawEdgesColorOpaque(frameCtx) {
3519
+ const renderFlags = this.renderFlags;
3520
+ for (let i = 0, len = renderFlags.visibleLayers.length; i < len; i++) {
3521
+ const layerIndex = renderFlags.visibleLayers[i];
3522
+ this.layerList[layerIndex].drawEdgesColorOpaque(renderFlags, frameCtx);
3523
+ }
3524
+ }
3525
+
3526
+ /** @private */
3527
+ drawEdgesColorTransparent(frameCtx) {
3528
+ const renderFlags = this.renderFlags;
3529
+ for (let i = 0, len = renderFlags.visibleLayers.length; i < len; i++) {
3530
+ const layerIndex = renderFlags.visibleLayers[i];
3531
+ this.layerList[layerIndex].drawEdgesColorTransparent(renderFlags, frameCtx);
3532
+ }
3533
+ }
3534
+
3535
+ /** @private */
3536
+ drawEdgesXRayed(frameCtx) {
3537
+ const renderFlags = this.renderFlags;
3538
+ for (let i = 0, len = renderFlags.visibleLayers.length; i < len; i++) {
3539
+ const layerIndex = renderFlags.visibleLayers[i];
3540
+ this.layerList[layerIndex].drawEdgesXRayed(renderFlags, frameCtx);
3541
+ }
3542
+ }
3543
+
3544
+ /** @private */
3545
+ drawEdgesHighlighted(frameCtx) {
3546
+ const renderFlags = this.renderFlags;
3547
+ for (let i = 0, len = renderFlags.visibleLayers.length; i < len; i++) {
3548
+ const layerIndex = renderFlags.visibleLayers[i];
3549
+ this.layerList[layerIndex].drawEdgesHighlighted(renderFlags, frameCtx);
3550
+ }
3551
+ }
3552
+
3553
+ /** @private */
3554
+ drawEdgesSelected(frameCtx) {
3555
+ const renderFlags = this.renderFlags;
3556
+ for (let i = 0, len = renderFlags.visibleLayers.length; i < len; i++) {
3557
+ const layerIndex = renderFlags.visibleLayers[i];
3558
+ this.layerList[layerIndex].drawEdgesSelected(renderFlags, frameCtx);
3559
+ }
3560
+ }
3561
+
3562
+ /**
3563
+ * @private
3564
+ */
3565
+ drawOcclusion(frameCtx) {
3566
+ if (this.numVisibleLayerPortions === 0) {
3567
+ return;
3568
+ }
3569
+ const renderFlags = this.renderFlags;
3570
+ for (let i = 0, len = renderFlags.visibleLayers.length; i < len; i++) {
3571
+ const layerIndex = renderFlags.visibleLayers[i];
3572
+ this.layerList[layerIndex].drawOcclusion(renderFlags, frameCtx);
3573
+ }
3574
+ }
3575
+
3576
+ /**
3577
+ * @private
3578
+ */
3579
+ drawShadow(frameCtx) {
3580
+ if (this.numVisibleLayerPortions === 0) {
3581
+ return;
3582
+ }
3583
+ const renderFlags = this.renderFlags;
3584
+ for (let i = 0, len = renderFlags.visibleLayers.length; i < len; i++) {
3585
+ const layerIndex = renderFlags.visibleLayers[i];
3586
+ this.layerList[layerIndex].drawShadow(renderFlags, frameCtx);
3587
+ }
3588
+ }
3589
+
3590
+ /** @private */
3591
+ setPickMatrices(pickViewMatrix, pickProjMatrix) {
3592
+ if (this._numVisibleLayerPortions === 0) {
3593
+ return;
3594
+ }
3595
+ const renderFlags = this.renderFlags;
3596
+ for (let i = 0, len = renderFlags.visibleLayers.length; i < len; i++) {
3597
+ const layerIndex = renderFlags.visibleLayers[i];
3598
+ const layer = this.layerList[layerIndex];
3599
+ if (layer.setPickMatrices) {
3600
+ layer.setPickMatrices(pickViewMatrix, pickProjMatrix);
3601
+ }
3602
+ }
3603
+ }
3604
+
3605
+ /** @private */
3606
+ drawPickMesh(frameCtx) {
3607
+ if (this.numVisibleLayerPortions === 0) {
3608
+ return;
3609
+ }
3610
+ const renderFlags = this.renderFlags;
3611
+ for (let i = 0, len = renderFlags.visibleLayers.length; i < len; i++) {
3612
+ const layerIndex = renderFlags.visibleLayers[i];
3613
+ this.layerList[layerIndex].drawPickMesh(renderFlags, frameCtx);
3614
+ }
3615
+ }
3616
+
3617
+ /**
3618
+ * Called by SceneModelMesh.drawPickDepths()
3619
+ * @private
3620
+ */
3621
+ drawPickDepths(frameCtx) {
3622
+ if (this.numVisibleLayerPortions === 0) {
3623
+ return;
3624
+ }
3625
+ const renderFlags = this.renderFlags;
3626
+ for (let i = 0, len = renderFlags.visibleLayers.length; i < len; i++) {
3627
+ const layerIndex = renderFlags.visibleLayers[i];
3628
+ this.layerList[layerIndex].drawPickDepths(renderFlags, frameCtx);
3629
+ }
3630
+ }
3631
+
3632
+ /**
3633
+ * Called by SceneModelMesh.drawPickNormals()
3634
+ * @private
3635
+ */
3636
+ drawPickNormals(frameCtx) {
3637
+ if (this.numVisibleLayerPortions === 0) {
3638
+ return;
3639
+ }
3640
+ const renderFlags = this.renderFlags;
3641
+ for (let i = 0, len = renderFlags.visibleLayers.length; i < len; i++) {
3642
+ const layerIndex = renderFlags.visibleLayers[i];
3643
+ this.layerList[layerIndex].drawPickNormals(renderFlags, frameCtx);
3644
+ }
3645
+ }
3646
+
3647
+ /**
3648
+ * @private
3649
+ */
3650
+ drawSnapInitDepthBuf(frameCtx) {
3651
+ if (this.numVisibleLayerPortions === 0) {
3652
+ return;
3653
+ }
3654
+ const renderFlags = this.renderFlags;
3655
+ for (let i = 0, len = renderFlags.visibleLayers.length; i < len; i++) {
3656
+ const layerIndex = renderFlags.visibleLayers[i];
3657
+ const layer = this.layerList[layerIndex];
3658
+ if (layer.drawSnapInitDepthBuf) {
3659
+ frameCtx.snapPickOrigin = [0, 0, 0];
3660
+ frameCtx.snapPickCoordinateScale = [1, 1, 1];
3661
+ frameCtx.snapPickLayerNumber++;
3662
+ layer.drawSnapInitDepthBuf(renderFlags, frameCtx);
3663
+ frameCtx.snapPickLayerParams[frameCtx.snapPickLayerNumber] = {
3664
+ origin: frameCtx.snapPickOrigin.slice(),
3665
+ coordinateScale: frameCtx.snapPickCoordinateScale.slice(),
3666
+ };
3667
+ }
3668
+ }
3669
+ }
3670
+
3671
+ /**
3672
+ * @private
3673
+ */
3674
+ drawSnapDepths(frameCtx) {
3675
+ if (this.numVisibleLayerPortions === 0) {
3676
+ return;
3677
+ }
3678
+ const renderFlags = this.renderFlags;
3679
+ for (let i = 0, len = renderFlags.visibleLayers.length; i < len; i++) {
3680
+ const layerIndex = renderFlags.visibleLayers[i];
3681
+ const layer = this.layerList[layerIndex];
3682
+ if (layer.drawSnapDepths) {
3683
+ frameCtx.snapPickOrigin = [0, 0, 0];
3684
+ frameCtx.snapPickCoordinateScale = [1, 1, 1];
3685
+ frameCtx.snapPickLayerNumber++;
3686
+ layer.drawSnapDepths(renderFlags, frameCtx);
3687
+ frameCtx.snapPickLayerParams[frameCtx.snapPickLayerNumber] = {
3688
+ origin: frameCtx.snapPickOrigin.slice(),
3689
+ coordinateScale: frameCtx.snapPickCoordinateScale.slice(),
3690
+ };
3691
+ }
3692
+ }
3693
+ }
3694
+
3695
+ /**
3696
+ * Destroys this SceneModel.
3697
+ */
3698
+ destroy() {
3699
+ for (let layerId in this._vboBatchingLayers) {
3700
+ if (this._vboBatchingLayers.hasOwnProperty(layerId)) {
3701
+ this._vboBatchingLayers[layerId].destroy();
3702
+ }
3703
+ }
3704
+ this._vboBatchingLayers = {};
3705
+ for (let layerId in this._vboInstancingLayers) {
3706
+ if (this._vboInstancingLayers.hasOwnProperty(layerId)) {
3707
+ this._vboInstancingLayers[layerId].destroy();
3708
+ }
3709
+ }
3710
+ this._vboInstancingLayers = {};
3711
+ this.scene.camera.off(this._onCameraViewMatrix);
3712
+ for (let i = 0, len = this.layerList.length; i < len; i++) {
3713
+ this.layerList[i].destroy();
3714
+ }
3715
+ this.layerList = [];
3716
+ for (let i = 0, len = this._entityList.length; i < len; i++) {
3717
+ this._entityList[i]._destroy();
3718
+ }
3719
+ // Object.entries(this._geometries).forEach(([id, geometry]) => {
3720
+ // geometry.destroy();
3721
+ // });
3722
+ this._geometries = {};
3723
+ this._dtxBuckets = {};
3724
+ this._textures = {};
3725
+ this._textureSets = {};
3726
+ this._meshes = {};
3727
+ this._entities = {};
3728
+ this.scene._aabbDirty = true;
3729
+ if (this._isModel) {
3730
+ this.scene._deregisterModel(this);
3731
+ }
3732
+ putScratchMemory();
3733
+ if (this._vfcManager) {
3734
+ this.scene.vfc.putVFCManager(this._vfcManager);
3735
+ }
3736
+ if (this._lodManager) {
3737
+ this.scene.lod.putLODManager(this._lodManager);
3738
+ }
3739
+ super.destroy();
3740
+ }
3741
+ }
3742
+
3743
+
3744
+ /**
3745
+ * This function applies two steps to the provided mesh geometry data:
3746
+ *
3747
+ * - 1st, it reduces its `.positions` to unique positions, thus removing duplicate vertices. It will adjust the `.indices` and `.edgeIndices` array accordingly to the unique `.positions`.
3748
+ *
3749
+ * - 2nd, it tries to do an optimization called `index rebucketting`
3750
+ *
3751
+ * _Rebucketting minimizes the amount of RAM usage for a given mesh geometry by trying do demote its needed index bitness._
3752
+ *
3753
+ * - _for 32 bit indices, will try to demote them to 16 bit indices_
3754
+ * - _for 16 bit indices, will try to demote them to 8 bits indices_
3755
+ * - _8 bits indices are kept as-is_
3756
+ *
3757
+ * The fact that 32/16/8 bits are needed for indices, depends on the number of maximumm indexable vertices within the mesh geometry: this is, the number of vertices in the mesh geometry.
3758
+ *
3759
+ * The function returns the same provided input `geometry`, enrichened with the additional key `.preparedBukets`.
3760
+ *
3761
+ * @param {object} geometry The mesh information containing `.positions`, `.indices`, `.edgeIndices` arrays.
3762
+ *
3763
+ * @param enableVertexWelding
3764
+ * @param enableIndexBucketing
3765
+ * @returns {object} The mesh information enrichened with `.buckets` key.
3766
+ */
3767
+ function createDTXBuckets(geometry, enableVertexWelding, enableIndexBucketing) {
3768
+ let uniquePositionsCompressed, uniqueIndices, uniqueEdgeIndices;
3769
+ if (enableVertexWelding) { // Expensive - careful!
3770
+ [
3771
+ uniquePositionsCompressed,
3772
+ uniqueIndices,
3773
+ uniqueEdgeIndices,
3774
+ ] = uniquifyPositions({
3775
+ positionsCompressed: geometry.positionsCompressed,
3776
+ indices: geometry.indices,
3777
+ edgeIndices: geometry.edgeIndices
3778
+ });
3779
+ } else {
3780
+ uniquePositionsCompressed = geometry.positionsCompressed;
3781
+ uniqueIndices = geometry.indices;
3782
+ uniqueEdgeIndices = geometry.edgeIndices;
3783
+ }
3784
+ let buckets;
3785
+ if (enableIndexBucketing) {
3786
+ let numUniquePositions = uniquePositionsCompressed.length / 3;
3787
+ buckets = rebucketPositions({
3788
+ positionsCompressed: uniquePositionsCompressed,
3789
+ indices: uniqueIndices,
3790
+ edgeIndices: uniqueEdgeIndices,
3791
+ },
3792
+ (numUniquePositions > (1 << 16)) ? 16 : 8,
3793
+ // true
3794
+ );
3795
+ } else {
3796
+ buckets = [{
3797
+ positionsCompressed: uniquePositionsCompressed,
3798
+ indices: uniqueIndices,
3799
+ edgeIndices: uniqueEdgeIndices,
3800
+ }];
3801
+ }
3802
+ return buckets;
3803
+ }
3804
+
3805
+ function createGeometryOBB(geometry) {
3806
+ geometry.obb = math.OBB3();
3807
+ if (geometry.positionsCompressed && geometry.positionsCompressed.length > 0) {
3808
+ const localAABB = math.collapseAABB3();
3809
+ math.expandAABB3Points3(localAABB, geometry.positionsCompressed);
3810
+ geometryCompressionUtils.decompressAABB(localAABB, geometry.positionsDecodeMatrix);
3811
+ math.AABB3ToOBB3(localAABB, geometry.obb);
3812
+ } else if (geometry.positions && geometry.positions.length > 0) {
3813
+ const localAABB = math.collapseAABB3();
3814
+ math.expandAABB3Points3(localAABB, geometry.positions);
3815
+ math.AABB3ToOBB3(localAABB, geometry.obb);
3816
+ }
3817
+ }