babylonFileLoader.ts 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  1. import { Logger } from "../../Misc/logger";
  2. import { Nullable } from "../../types";
  3. import { Camera } from "../../Cameras/camera";
  4. import { Scene } from "../../scene";
  5. import { Vector3 } from "../../Maths/math.vector";
  6. import { Color3, Color4 } from "../../Maths/math.color";
  7. import { Mesh } from "../../Meshes/mesh";
  8. import { AbstractMesh } from "../../Meshes/abstractMesh";
  9. import { Geometry } from "../../Meshes/geometry";
  10. import { TransformNode } from "../../Meshes/transformNode";
  11. import { Material } from "../../Materials/material";
  12. import { MultiMaterial } from "../../Materials/multiMaterial";
  13. import { CubeTexture } from "../../Materials/Textures/cubeTexture";
  14. import { HDRCubeTexture } from "../../Materials/Textures/hdrCubeTexture";
  15. import { AnimationGroup } from "../../Animations/animationGroup";
  16. import { Light } from "../../Lights/light";
  17. import { SceneComponentConstants } from "../../sceneComponent";
  18. import { SceneLoader } from "../../Loading/sceneLoader";
  19. import { AbstractScene } from "../../abstractScene";
  20. import { AssetContainer } from "../../assetContainer";
  21. import { ActionManager } from "../../Actions/actionManager";
  22. import { IParticleSystem } from "../../Particles/IParticleSystem";
  23. import { Skeleton } from "../../Bones/skeleton";
  24. import { MorphTargetManager } from "../../Morph/morphTargetManager";
  25. import { CannonJSPlugin } from "../../Physics/Plugins/cannonJSPlugin";
  26. import { OimoJSPlugin } from "../../Physics/Plugins/oimoJSPlugin";
  27. import { AmmoJSPlugin } from "../../Physics/Plugins/ammoJSPlugin";
  28. import { ReflectionProbe } from "../../Probes/reflectionProbe";
  29. import { _TypeStore } from '../../Misc/typeStore';
  30. import { Tools } from '../../Misc/tools';
  31. import { StringTools } from '../../Misc/stringTools';
  32. /** @hidden */
  33. export var _BabylonLoaderRegistered = true;
  34. /**
  35. * Helps setting up some configuration for the babylon file loader.
  36. */
  37. export class BabylonFileLoaderConfiguration {
  38. /**
  39. * The loader does not allow injecting custom physix engine into the plugins.
  40. * Unfortunately in ES6, we need to manually inject them into the plugin.
  41. * So you could set this variable to your engine import to make it work.
  42. */
  43. public static LoaderInjectedPhysicsEngine: any = undefined;
  44. }
  45. var parseMaterialById = (id: string, parsedData: any, scene: Scene, rootUrl: string) => {
  46. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  47. var parsedMaterial = parsedData.materials[index];
  48. if (parsedMaterial.id === id) {
  49. return Material.Parse(parsedMaterial, scene, rootUrl);
  50. }
  51. }
  52. return null;
  53. };
  54. var isDescendantOf = (mesh: any, names: Array<any>, hierarchyIds: Array<number>) => {
  55. for (var i in names) {
  56. if (mesh.name === names[i]) {
  57. hierarchyIds.push(mesh.id);
  58. return true;
  59. }
  60. }
  61. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  62. hierarchyIds.push(mesh.id);
  63. return true;
  64. }
  65. return false;
  66. };
  67. var logOperation = (operation: string, producer: { file: string, name: string, version: string, exporter_version: string }) => {
  68. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  69. };
  70. var loadDetailLevels = (scene: Scene, mesh: AbstractMesh) => {
  71. const mastermesh: Mesh = mesh as Mesh;
  72. // Every value specified in the ids array of the lod data points to another mesh which should be used as the lower LOD level.
  73. // The distances (or coverages) array values specified are used along with the lod mesh ids as a hint to determine the switching threshold for the various LODs.
  74. if (mesh._waitingData.lods) {
  75. if (mesh._waitingData.lods.ids && mesh._waitingData.lods.ids.length > 0) {
  76. const lodmeshes: string[] = mesh._waitingData.lods.ids;
  77. const wasenabled: boolean = mastermesh.isEnabled(false);
  78. if (mesh._waitingData.lods.distances) {
  79. const distances: number[] = mesh._waitingData.lods.distances;
  80. if (distances.length >= lodmeshes.length) {
  81. const culling: number = (distances.length > lodmeshes.length) ? distances[distances.length - 1] : 0;
  82. mastermesh.setEnabled(false);
  83. for (let index = 0; index < lodmeshes.length; index++) {
  84. const lodid: string = lodmeshes[index];
  85. const lodmesh: Mesh = scene.getMeshByID(lodid) as Mesh;
  86. if (lodmesh != null) {
  87. mastermesh.addLODLevel(distances[index], lodmesh);
  88. }
  89. }
  90. if (culling > 0) {
  91. mastermesh.addLODLevel(culling, null);
  92. }
  93. if (wasenabled === true) {
  94. mastermesh.setEnabled(true);
  95. }
  96. } else {
  97. Tools.Warn("Invalid level of detail distances for " + mesh.name);
  98. }
  99. }
  100. }
  101. mesh._waitingData.lods = null;
  102. }
  103. };
  104. var loadAssetContainer = (scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void, addToScene = false): AssetContainer => {
  105. var container = new AssetContainer(scene);
  106. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  107. // when SceneLoader.debugLogging = true (default), or exception encountered.
  108. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  109. // and avoid problems with multiple concurrent .babylon loads.
  110. var log = "importScene has failed JSON parse";
  111. try {
  112. var parsedData = JSON.parse(data);
  113. log = "";
  114. var fullDetails = SceneLoader.loggingLevel === SceneLoader.DETAILED_LOGGING;
  115. var index: number;
  116. var cache: number;
  117. // Environment texture
  118. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  119. // PBR needed for both HDR texture (gamma space) & a sky box
  120. var isPBR = parsedData.isPBR !== undefined ? parsedData.isPBR : true;
  121. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  122. var hdrSize: number = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  123. var hdrTexture = new HDRCubeTexture((parsedData.environmentTexture.match(/https?:\/\//g) ? "" : rootUrl) + parsedData.environmentTexture, scene, hdrSize, true, !isPBR);
  124. if (parsedData.environmentTextureRotationY) {
  125. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  126. }
  127. scene.environmentTexture = hdrTexture;
  128. } else {
  129. if (StringTools.EndsWith(parsedData.environmentTexture, ".env")) {
  130. var compressedTexture = new CubeTexture((parsedData.environmentTexture.match(/https?:\/\//g) ? "" : rootUrl) + parsedData.environmentTexture, scene);
  131. if (parsedData.environmentTextureRotationY) {
  132. compressedTexture.rotationY = parsedData.environmentTextureRotationY;
  133. }
  134. scene.environmentTexture = compressedTexture;
  135. } else {
  136. var cubeTexture = CubeTexture.CreateFromPrefilteredData((parsedData.environmentTexture.match(/https?:\/\//g) ? "" : rootUrl) + parsedData.environmentTexture, scene);
  137. if (parsedData.environmentTextureRotationY) {
  138. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  139. }
  140. scene.environmentTexture = cubeTexture;
  141. }
  142. }
  143. if (parsedData.createDefaultSkybox === true) {
  144. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  145. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  146. scene.createDefaultSkybox(scene.environmentTexture, isPBR, skyboxScale, skyboxBlurLevel);
  147. }
  148. container.environmentTexture = scene.environmentTexture;
  149. }
  150. // Environment Intensity
  151. if (parsedData.environmentIntensity !== undefined && parsedData.environmentIntensity !== null) {
  152. scene.environmentIntensity = parsedData.environmentIntensity;
  153. }
  154. // Lights
  155. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  156. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  157. var parsedLight = parsedData.lights[index];
  158. var light = Light.Parse(parsedLight, scene);
  159. if (light) {
  160. container.lights.push(light);
  161. log += (index === 0 ? "\n\tLights:" : "");
  162. log += "\n\t\t" + light.toString(fullDetails);
  163. }
  164. }
  165. }
  166. // Reflection probes
  167. if (parsedData.reflectionProbes !== undefined && parsedData.reflectionProbes !== null) {
  168. for (index = 0, cache = parsedData.reflectionProbes.length; index < cache; index++) {
  169. var parsedReflectionProbe = parsedData.reflectionProbes[index];
  170. var reflectionProbe = ReflectionProbe.Parse(parsedReflectionProbe, scene, rootUrl);
  171. if (reflectionProbe) {
  172. container.reflectionProbes.push(reflectionProbe);
  173. log += (index === 0 ? "\n\tReflection Probes:" : "");
  174. log += "\n\t\t" + reflectionProbe.toString(fullDetails);
  175. }
  176. }
  177. }
  178. // Animations
  179. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  180. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  181. var parsedAnimation = parsedData.animations[index];
  182. const internalClass = _TypeStore.GetClass("BABYLON.Animation");
  183. if (internalClass) {
  184. let animation = internalClass.Parse(parsedAnimation);
  185. scene.animations.push(animation);
  186. container.animations.push(animation);
  187. log += (index === 0 ? "\n\tAnimations:" : "");
  188. log += "\n\t\t" + animation.toString(fullDetails);
  189. }
  190. }
  191. }
  192. // Materials
  193. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  194. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  195. var parsedMaterial = parsedData.materials[index];
  196. var mat = Material.Parse(parsedMaterial, scene, rootUrl);
  197. if (mat) {
  198. container.materials.push(mat);
  199. log += (index === 0 ? "\n\tMaterials:" : "");
  200. log += "\n\t\t" + mat.toString(fullDetails);
  201. // Textures
  202. var textures = mat.getActiveTextures();
  203. textures.forEach((t) => {
  204. if (container.textures.indexOf(t) == -1) {
  205. container.textures.push(t);
  206. }
  207. });
  208. }
  209. }
  210. }
  211. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  212. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  213. var parsedMultiMaterial = parsedData.multiMaterials[index];
  214. var mmat = MultiMaterial.ParseMultiMaterial(parsedMultiMaterial, scene);
  215. container.multiMaterials.push(mmat);
  216. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  217. log += "\n\t\t" + mmat.toString(fullDetails);
  218. // Textures
  219. var textures = mmat.getActiveTextures();
  220. textures.forEach((t) => {
  221. if (container.textures.indexOf(t) == -1) {
  222. container.textures.push(t);
  223. }
  224. });
  225. }
  226. }
  227. // Morph targets
  228. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  229. for (var managerData of parsedData.morphTargetManagers) {
  230. container.morphTargetManagers.push(MorphTargetManager.Parse(managerData, scene));
  231. }
  232. }
  233. // Skeletons
  234. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  235. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  236. var parsedSkeleton = parsedData.skeletons[index];
  237. var skeleton = Skeleton.Parse(parsedSkeleton, scene);
  238. container.skeletons.push(skeleton);
  239. log += (index === 0 ? "\n\tSkeletons:" : "");
  240. log += "\n\t\t" + skeleton.toString(fullDetails);
  241. }
  242. }
  243. // Geometries
  244. var geometries = parsedData.geometries;
  245. if (geometries !== undefined && geometries !== null) {
  246. var addedGeometry = new Array<Nullable<Geometry>>();
  247. // VertexData
  248. var vertexData = geometries.vertexData;
  249. if (vertexData !== undefined && vertexData !== null) {
  250. for (index = 0, cache = vertexData.length; index < cache; index++) {
  251. var parsedVertexData = vertexData[index];
  252. addedGeometry.push(Geometry.Parse(parsedVertexData, scene, rootUrl));
  253. }
  254. }
  255. addedGeometry.forEach((g) => {
  256. if (g) {
  257. container.geometries.push(g);
  258. }
  259. });
  260. }
  261. // Transform nodes
  262. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  263. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  264. var parsedTransformNode = parsedData.transformNodes[index];
  265. var node = TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  266. container.transformNodes.push(node);
  267. }
  268. }
  269. // Meshes
  270. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  271. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  272. var parsedMesh = parsedData.meshes[index];
  273. var mesh = <AbstractMesh>Mesh.Parse(parsedMesh, scene, rootUrl);
  274. container.meshes.push(mesh);
  275. log += (index === 0 ? "\n\tMeshes:" : "");
  276. log += "\n\t\t" + mesh.toString(fullDetails);
  277. }
  278. }
  279. // Cameras
  280. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  281. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  282. var parsedCamera = parsedData.cameras[index];
  283. var camera = Camera.Parse(parsedCamera, scene);
  284. container.cameras.push(camera);
  285. log += (index === 0 ? "\n\tCameras:" : "");
  286. log += "\n\t\t" + camera.toString(fullDetails);
  287. }
  288. }
  289. // Animation Groups
  290. if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {
  291. for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {
  292. var parsedAnimationGroup = parsedData.animationGroups[index];
  293. var animationGroup = AnimationGroup.Parse(parsedAnimationGroup, scene);
  294. container.animationGroups.push(animationGroup);
  295. log += (index === 0 ? "\n\tAnimationGroups:" : "");
  296. log += "\n\t\t" + animationGroup.toString(fullDetails);
  297. }
  298. }
  299. // Browsing all the graph to connect the dots
  300. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  301. var camera = scene.cameras[index];
  302. if (camera._waitingParentId) {
  303. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  304. camera._waitingParentId = null;
  305. }
  306. }
  307. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  308. let light = scene.lights[index];
  309. if (light && light._waitingParentId) {
  310. light.parent = scene.getLastEntryByID(light._waitingParentId);
  311. light._waitingParentId = null;
  312. }
  313. }
  314. // Connect parents & children and parse actions and lods
  315. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  316. var transformNode = scene.transformNodes[index];
  317. if (transformNode._waitingParentId) {
  318. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  319. transformNode._waitingParentId = null;
  320. }
  321. }
  322. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  323. var mesh = scene.meshes[index];
  324. if (mesh._waitingParentId) {
  325. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  326. mesh._waitingParentId = null;
  327. }
  328. if (mesh._waitingData.lods) {
  329. loadDetailLevels(scene, mesh);
  330. }
  331. }
  332. // link skeleton transform nodes
  333. for (index = 0, cache = scene.skeletons.length; index < cache; index++) {
  334. var skeleton = scene.skeletons[index];
  335. if (skeleton._hasWaitingData) {
  336. if (skeleton.bones != null) {
  337. skeleton.bones.forEach((bone) => {
  338. if (bone._waitingTransformNodeId) {
  339. var linkTransformNode = scene.getLastEntryByID(bone._waitingTransformNodeId) as TransformNode;
  340. if (linkTransformNode) {
  341. bone.linkTransformNode(linkTransformNode);
  342. }
  343. bone._waitingTransformNodeId = null;
  344. }
  345. });
  346. }
  347. skeleton._hasWaitingData = null;
  348. }
  349. }
  350. // freeze world matrix application
  351. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  352. var currentMesh = scene.meshes[index];
  353. if (currentMesh._waitingData.freezeWorldMatrix) {
  354. currentMesh.freezeWorldMatrix();
  355. currentMesh._waitingData.freezeWorldMatrix = null;
  356. } else {
  357. currentMesh.computeWorldMatrix(true);
  358. }
  359. }
  360. // Lights exclusions / inclusions
  361. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  362. let light = scene.lights[index];
  363. // Excluded check
  364. if (light._excludedMeshesIds.length > 0) {
  365. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  366. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  367. if (excludedMesh) {
  368. light.excludedMeshes.push(excludedMesh);
  369. }
  370. }
  371. light._excludedMeshesIds = [];
  372. }
  373. // Included check
  374. if (light._includedOnlyMeshesIds.length > 0) {
  375. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  376. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  377. if (includedOnlyMesh) {
  378. light.includedOnlyMeshes.push(includedOnlyMesh);
  379. }
  380. }
  381. light._includedOnlyMeshesIds = [];
  382. }
  383. }
  384. AbstractScene.Parse(parsedData, scene, container, rootUrl);
  385. // Actions (scene) Done last as it can access other objects.
  386. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  387. var mesh = scene.meshes[index];
  388. if (mesh._waitingData.actions) {
  389. ActionManager.Parse(mesh._waitingData.actions, mesh, scene);
  390. mesh._waitingData.actions = null;
  391. }
  392. }
  393. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  394. ActionManager.Parse(parsedData.actions, null, scene);
  395. }
  396. } catch (err) {
  397. let msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  398. if (onError) {
  399. onError(msg, err);
  400. } else {
  401. Logger.Log(msg);
  402. throw err;
  403. }
  404. } finally {
  405. if (!addToScene) {
  406. container.removeAllFromScene();
  407. }
  408. if (log !== null && SceneLoader.loggingLevel !== SceneLoader.NO_LOGGING) {
  409. Logger.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (SceneLoader.loggingLevel !== SceneLoader.MINIMAL_LOGGING ? log : ""));
  410. }
  411. }
  412. return container;
  413. };
  414. SceneLoader.RegisterPlugin({
  415. name: "babylon.js",
  416. extensions: ".babylon",
  417. canDirectLoad: (data: string) => {
  418. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  419. return true;
  420. }
  421. return false;
  422. },
  423. importMesh: (meshesNames: any, scene: Scene, data: any, rootUrl: string, meshes: AbstractMesh[], particleSystems: IParticleSystem[], skeletons: Skeleton[], onError?: (message: string, exception?: any) => void): boolean => {
  424. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  425. // when SceneLoader.debugLogging = true (default), or exception encountered.
  426. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  427. // and avoid problems with multiple concurrent .babylon loads.
  428. var log = "importMesh has failed JSON parse";
  429. try {
  430. var parsedData = JSON.parse(data);
  431. log = "";
  432. var fullDetails = SceneLoader.loggingLevel === SceneLoader.DETAILED_LOGGING;
  433. if (!meshesNames) {
  434. meshesNames = null;
  435. } else if (!Array.isArray(meshesNames)) {
  436. meshesNames = [meshesNames];
  437. }
  438. var hierarchyIds = new Array<number>();
  439. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  440. var loadedSkeletonsIds = [];
  441. var loadedMaterialsIds = [];
  442. var index: number;
  443. var cache: number;
  444. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  445. var parsedMesh = parsedData.meshes[index];
  446. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  447. if (meshesNames !== null) {
  448. // Remove found mesh name from list.
  449. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  450. }
  451. //Geometry?
  452. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  453. //does the file contain geometries?
  454. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  455. //find the correct geometry and add it to the scene
  456. var found: boolean = false;
  457. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach((geometryType: string) => {
  458. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  459. return;
  460. } else {
  461. parsedData.geometries[geometryType].forEach((parsedGeometryData: any) => {
  462. if (parsedGeometryData.id === parsedMesh.geometryId) {
  463. switch (geometryType) {
  464. case "vertexData":
  465. Geometry.Parse(parsedGeometryData, scene, rootUrl);
  466. break;
  467. }
  468. found = true;
  469. }
  470. });
  471. }
  472. });
  473. if (found === false) {
  474. Logger.Warn("Geometry not found for mesh " + parsedMesh.id);
  475. }
  476. }
  477. }
  478. // Material ?
  479. if (parsedMesh.materialId) {
  480. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  481. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  482. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  483. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  484. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  485. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  486. var subMatId = parsedMultiMaterial.materials[matIndex];
  487. loadedMaterialsIds.push(subMatId);
  488. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  489. if (mat) {
  490. log += "\n\tMaterial " + mat.toString(fullDetails);
  491. }
  492. }
  493. loadedMaterialsIds.push(parsedMultiMaterial.id);
  494. var mmat = MultiMaterial.ParseMultiMaterial(parsedMultiMaterial, scene);
  495. if (mmat) {
  496. materialFound = true;
  497. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  498. }
  499. break;
  500. }
  501. }
  502. }
  503. if (materialFound === false) {
  504. loadedMaterialsIds.push(parsedMesh.materialId);
  505. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  506. if (!mat) {
  507. Logger.Warn("Material not found for mesh " + parsedMesh.id);
  508. } else {
  509. log += "\n\tMaterial " + mat.toString(fullDetails);
  510. }
  511. }
  512. }
  513. // Skeleton ?
  514. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  515. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  516. if (skeletonAlreadyLoaded === false) {
  517. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  518. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  519. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  520. var skeleton = Skeleton.Parse(parsedSkeleton, scene);
  521. skeletons.push(skeleton);
  522. loadedSkeletonsIds.push(parsedSkeleton.id);
  523. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  524. }
  525. }
  526. }
  527. }
  528. // Morph targets ?
  529. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  530. for (var managerData of parsedData.morphTargetManagers) {
  531. MorphTargetManager.Parse(managerData, scene);
  532. }
  533. }
  534. var mesh = Mesh.Parse(parsedMesh, scene, rootUrl);
  535. meshes.push(mesh);
  536. log += "\n\tMesh " + mesh.toString(fullDetails);
  537. }
  538. }
  539. // Connecting parents and lods
  540. var currentMesh: AbstractMesh;
  541. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  542. currentMesh = scene.meshes[index];
  543. if (currentMesh._waitingParentId) {
  544. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  545. currentMesh._waitingParentId = null;
  546. }
  547. if (currentMesh._waitingData.lods) {
  548. loadDetailLevels(scene, currentMesh);
  549. }
  550. }
  551. // link skeleton transform nodes
  552. for (index = 0, cache = scene.skeletons.length; index < cache; index++) {
  553. var skeleton = scene.skeletons[index];
  554. if (skeleton._hasWaitingData) {
  555. if (skeleton.bones != null) {
  556. skeleton.bones.forEach((bone) => {
  557. if (bone._waitingTransformNodeId) {
  558. var linkTransformNode = scene.getLastEntryByID(bone._waitingTransformNodeId) as TransformNode;
  559. if (linkTransformNode) {
  560. bone.linkTransformNode(linkTransformNode);
  561. }
  562. bone._waitingTransformNodeId = null;
  563. }
  564. });
  565. }
  566. skeleton._hasWaitingData = null;
  567. }
  568. }
  569. // freeze and compute world matrix application
  570. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  571. currentMesh = scene.meshes[index];
  572. if (currentMesh._waitingData.freezeWorldMatrix) {
  573. currentMesh.freezeWorldMatrix();
  574. currentMesh._waitingData.freezeWorldMatrix = null;
  575. } else {
  576. currentMesh.computeWorldMatrix(true);
  577. }
  578. }
  579. }
  580. // Particles
  581. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  582. let parser = AbstractScene.GetIndividualParser(SceneComponentConstants.NAME_PARTICLESYSTEM);
  583. if (parser) {
  584. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  585. var parsedParticleSystem = parsedData.particleSystems[index];
  586. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  587. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  588. }
  589. }
  590. }
  591. }
  592. return true;
  593. } catch (err) {
  594. let msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  595. if (onError) {
  596. onError(msg, err);
  597. } else {
  598. Logger.Log(msg);
  599. throw err;
  600. }
  601. } finally {
  602. if (log !== null && SceneLoader.loggingLevel !== SceneLoader.NO_LOGGING) {
  603. Logger.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (SceneLoader.loggingLevel !== SceneLoader.MINIMAL_LOGGING ? log : ""));
  604. }
  605. }
  606. return false;
  607. },
  608. load: (scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void): boolean => {
  609. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  610. // when SceneLoader.debugLogging = true (default), or exception encountered.
  611. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  612. // and avoid problems with multiple concurrent .babylon loads.
  613. var log = "importScene has failed JSON parse";
  614. try {
  615. var parsedData = JSON.parse(data);
  616. log = "";
  617. // Scene
  618. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  619. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !SceneLoader.ForceFullSceneLoadingForIncremental;
  620. }
  621. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  622. scene.autoClear = parsedData.autoClear;
  623. }
  624. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  625. scene.clearColor = Color4.FromArray(parsedData.clearColor);
  626. }
  627. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  628. scene.ambientColor = Color3.FromArray(parsedData.ambientColor);
  629. }
  630. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  631. scene.gravity = Vector3.FromArray(parsedData.gravity);
  632. }
  633. // Fog
  634. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  635. scene.fogMode = parsedData.fogMode;
  636. scene.fogColor = Color3.FromArray(parsedData.fogColor);
  637. scene.fogStart = parsedData.fogStart;
  638. scene.fogEnd = parsedData.fogEnd;
  639. scene.fogDensity = parsedData.fogDensity;
  640. log += "\tFog mode for scene: ";
  641. switch (scene.fogMode) {
  642. // getters not compiling, so using hardcoded
  643. case 1: log += "exp\n"; break;
  644. case 2: log += "exp2\n"; break;
  645. case 3: log += "linear\n"; break;
  646. }
  647. }
  648. //Physics
  649. if (parsedData.physicsEnabled) {
  650. var physicsPlugin;
  651. if (parsedData.physicsEngine === "cannon") {
  652. physicsPlugin = new CannonJSPlugin(undefined, undefined, BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine);
  653. } else if (parsedData.physicsEngine === "oimo") {
  654. physicsPlugin = new OimoJSPlugin(undefined, BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine);
  655. } else if (parsedData.physicsEngine === "ammo") {
  656. physicsPlugin = new AmmoJSPlugin(undefined, BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine, undefined);
  657. }
  658. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  659. //else - default engine, which is currently oimo
  660. var physicsGravity = parsedData.physicsGravity ? Vector3.FromArray(parsedData.physicsGravity) : null;
  661. scene.enablePhysics(physicsGravity, physicsPlugin);
  662. }
  663. // Metadata
  664. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  665. scene.metadata = parsedData.metadata;
  666. }
  667. //collisions, if defined. otherwise, default is true
  668. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  669. scene.collisionsEnabled = parsedData.collisionsEnabled;
  670. }
  671. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  672. if (!container) {
  673. return false;
  674. }
  675. if (parsedData.autoAnimate) {
  676. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  677. }
  678. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  679. scene.setActiveCameraByID(parsedData.activeCameraID);
  680. }
  681. // Environment texture
  682. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  683. // PBR needed for both HDR texture (gamma space) & a sky box
  684. var isPBR = parsedData.isPBR !== undefined ? parsedData.isPBR : true;
  685. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  686. var hdrSize: number = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  687. var hdrTexture = new HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize, true, !isPBR);
  688. if (parsedData.environmentTextureRotationY) {
  689. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  690. }
  691. scene.environmentTexture = hdrTexture;
  692. } else {
  693. if (StringTools.EndsWith(parsedData.environmentTexture, ".env")) {
  694. var compressedTexture = new CubeTexture(rootUrl + parsedData.environmentTexture, scene);
  695. if (parsedData.environmentTextureRotationY) {
  696. compressedTexture.rotationY = parsedData.environmentTextureRotationY;
  697. }
  698. scene.environmentTexture = compressedTexture;
  699. } else {
  700. var cubeTexture = CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  701. if (parsedData.environmentTextureRotationY) {
  702. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  703. }
  704. scene.environmentTexture = cubeTexture;
  705. }
  706. }
  707. if (parsedData.createDefaultSkybox === true) {
  708. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  709. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  710. scene.createDefaultSkybox(scene.environmentTexture, isPBR, skyboxScale, skyboxBlurLevel);
  711. }
  712. }
  713. // Finish
  714. return true;
  715. } catch (err) {
  716. let msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  717. if (onError) {
  718. onError(msg, err);
  719. } else {
  720. Logger.Log(msg);
  721. throw err;
  722. }
  723. } finally {
  724. if (log !== null && SceneLoader.loggingLevel !== SceneLoader.NO_LOGGING) {
  725. Logger.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (SceneLoader.loggingLevel !== SceneLoader.MINIMAL_LOGGING ? log : ""));
  726. }
  727. }
  728. return false;
  729. },
  730. loadAssetContainer: (scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void): AssetContainer => {
  731. var container = loadAssetContainer(scene, data, rootUrl, onError);
  732. return container;
  733. }
  734. });