babylon.scene.js 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126
  1. "use strict";
  2. var BABYLON = BABYLON || {};
  3. (function () {
  4. BABYLON.Scene = function (engine) {
  5. this._engine = engine;
  6. this.autoClear = true;
  7. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  8. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  9. engine.scenes.push(this);
  10. this._totalVertices = 0;
  11. this._activeVertices = 0;
  12. this._activeParticles = 0;
  13. this._lastFrameDuration = 0;
  14. this._evaluateActiveMeshesDuration = 0;
  15. this._renderTargetsDuration = 0;
  16. this._renderDuration = 0;
  17. this._renderId = 0;
  18. this._executeWhenReadyTimeoutId = -1;
  19. this._toBeDisposed = new BABYLON.Tools.SmartArray(256);
  20. this._onReadyCallbacks = [];
  21. this._pendingData = [];
  22. this._onBeforeRenderCallbacks = [];
  23. // Fog
  24. this.fogMode = BABYLON.Scene.FOGMODE_NONE;
  25. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  26. this.fogDensity = 0.1;
  27. this.fogStart = 0;
  28. this.fogEnd = 1000.0;
  29. // Lights
  30. this.lightsEnabled = true;
  31. this.lights = [];
  32. // Cameras
  33. this.cameras = [];
  34. this.activeCamera = null;
  35. // Meshes
  36. this.meshes = [];
  37. // Internal smart arrays
  38. this._activeMeshes = new BABYLON.Tools.SmartArray(256);
  39. this._processedMaterials = new BABYLON.Tools.SmartArray(256);
  40. this._renderTargets = new BABYLON.Tools.SmartArray(256);
  41. this._activeParticleSystems = new BABYLON.Tools.SmartArray(256);
  42. this._activeSkeletons = new BABYLON.Tools.SmartArray(32);
  43. // Rendering groups
  44. this._renderingManager = new BABYLON.RenderingManager(this);
  45. // Materials
  46. this.materials = [];
  47. this.multiMaterials = [];
  48. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  49. // Textures
  50. this.texturesEnabled = true;
  51. this.textures = [];
  52. // Particles
  53. this.particlesEnabled = true;
  54. this.particleSystems = [];
  55. // Sprites
  56. this.spriteManagers = [];
  57. // Layers
  58. this.layers = [];
  59. // Skeletons
  60. this.skeletons = [];
  61. // Lens flares
  62. this.lensFlareSystems = [];
  63. // Collisions
  64. this.collisionsEnabled = true;
  65. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  66. // Animations
  67. this._activeAnimatables = [];
  68. // Matrices
  69. this._transformMatrix = BABYLON.Matrix.Zero();
  70. // Internals
  71. this._scaledPosition = BABYLON.Vector3.Zero();
  72. this._scaledVelocity = BABYLON.Vector3.Zero();
  73. // Postprocesses
  74. this.postProcessesEnabled = true;
  75. this.postProcessManager = new BABYLON.PostProcessManager(this);
  76. // Customs render targets
  77. this.renderTargetsEnabled = true;
  78. this.customRenderTargets = [];
  79. // Multi-cameras
  80. this.activeCameras = [];
  81. };
  82. // Properties
  83. BABYLON.Scene.prototype.getEngine = function () {
  84. return this._engine;
  85. };
  86. BABYLON.Scene.prototype.getTotalVertices = function () {
  87. return this._totalVertices;
  88. };
  89. BABYLON.Scene.prototype.getActiveVertices = function () {
  90. return this._activeVertices;
  91. };
  92. BABYLON.Scene.prototype.getActiveParticles = function () {
  93. return this._activeParticles;
  94. };
  95. // Stats
  96. BABYLON.Scene.prototype.getLastFrameDuration = function () {
  97. return this._lastFrameDuration;
  98. };
  99. BABYLON.Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  100. return this._evaluateActiveMeshesDuration;
  101. };
  102. BABYLON.Scene.prototype.getActiveMeshes = function () {
  103. return this._activeMeshes;
  104. };
  105. BABYLON.Scene.prototype.getRenderTargetsDuration = function () {
  106. return this._renderTargetsDuration;
  107. };
  108. BABYLON.Scene.prototype.getRenderDuration = function () {
  109. return this._renderDuration;
  110. };
  111. BABYLON.Scene.prototype.getParticlesDuration = function () {
  112. return this._particlesDuration;
  113. };
  114. BABYLON.Scene.prototype.getSpritesDuration = function () {
  115. return this._spritesDuration;
  116. };
  117. BABYLON.Scene.prototype.getAnimationRatio = function () {
  118. return this._animationRatio;
  119. };
  120. BABYLON.Scene.prototype.getRenderId = function () {
  121. return this._renderId;
  122. };
  123. // Ready
  124. BABYLON.Scene.prototype.isReady = function () {
  125. if (this._pendingData.length > 0) {
  126. return false;
  127. }
  128. for (var index = 0; index < this.meshes.length; index++) {
  129. var mesh = this.meshes[index];
  130. var mat = mesh.material;
  131. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  132. return false;
  133. }
  134. if (mat) {
  135. if (!mat.isReady(mesh)) {
  136. return false;
  137. }
  138. }
  139. }
  140. return true;
  141. };
  142. BABYLON.Scene.prototype.registerBeforeRender = function (func) {
  143. this._onBeforeRenderCallbacks.push(func);
  144. };
  145. BABYLON.Scene.prototype.unregisterBeforeRender = function (func) {
  146. var index = this._onBeforeRenderCallbacks.indexOf(func);
  147. if (index > -1) {
  148. this._onBeforeRenderCallbacks.splice(index, 1);
  149. }
  150. };
  151. BABYLON.Scene.prototype._addPendingData = function (data) {
  152. this._pendingData.push(data);
  153. };
  154. BABYLON.Scene.prototype._removePendingData = function (data) {
  155. var index = this._pendingData.indexOf(data);
  156. if (index !== -1) {
  157. this._pendingData.splice(index, 1);
  158. }
  159. };
  160. BABYLON.Scene.prototype.getWaitingItemsCount = function () {
  161. return this._pendingData.length;
  162. };
  163. BABYLON.Scene.prototype.executeWhenReady = function (func) {
  164. this._onReadyCallbacks.push(func);
  165. if (this._executeWhenReadyTimeoutId !== -1) {
  166. return;
  167. }
  168. var that = this;
  169. this._executeWhenReadyTimeoutId = setTimeout(function () {
  170. that._checkIsReady();
  171. }, 150);
  172. };
  173. BABYLON.Scene.prototype._checkIsReady = function () {
  174. if (this.isReady()) {
  175. this._onReadyCallbacks.forEach(function (func) {
  176. func();
  177. });
  178. this._onReadyCallbacks = [];
  179. this._executeWhenReadyTimeoutId = -1;
  180. return;
  181. }
  182. var that = this;
  183. this._executeWhenReadyTimeoutId = setTimeout(function () {
  184. that._checkIsReady();
  185. }, 150);
  186. };
  187. // Animations
  188. BABYLON.Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd) {
  189. if (speedRatio === undefined) {
  190. speedRatio = 1.0;
  191. }
  192. // Local animations
  193. if (target.animations) {
  194. this.stopAnimation(target);
  195. var animatable = new BABYLON._Animatable(target, from, to, loop, speedRatio, onAnimationEnd);
  196. this._activeAnimatables.push(animatable);
  197. }
  198. // Children animations
  199. if (target.getAnimatables) {
  200. var animatables = target.getAnimatables();
  201. for (var index = 0; index < animatables.length; index++) {
  202. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd);
  203. }
  204. }
  205. };
  206. BABYLON.Scene.prototype.stopAnimation = function (target) {
  207. // Local animations
  208. if (target.animations) {
  209. for (var index = 0; index < this._activeAnimatables.length; index++) {
  210. if (this._activeAnimatables[index].target === target) {
  211. this._activeAnimatables.splice(index, 1);
  212. return;
  213. }
  214. }
  215. }
  216. // Children animations
  217. if (target.getAnimatables) {
  218. var animatables = target.getAnimatables();
  219. for (var index = 0; index < animatables.length; index++) {
  220. this.stopAnimation(animatables[index]);
  221. }
  222. }
  223. };
  224. BABYLON.Scene.prototype._animate = function () {
  225. if (!this._animationStartDate) {
  226. this._animationStartDate = new Date();
  227. }
  228. // Getting time
  229. var now = new Date();
  230. var delay = now - this._animationStartDate;
  231. for (var index = 0; index < this._activeAnimatables.length; index++) {
  232. if (!this._activeAnimatables[index]._animate(delay)) {
  233. this._activeAnimatables.splice(index, 1);
  234. index--;
  235. }
  236. }
  237. };
  238. // Matrix
  239. BABYLON.Scene.prototype.getViewMatrix = function () {
  240. return this._viewMatrix;
  241. };
  242. BABYLON.Scene.prototype.getProjectionMatrix = function () {
  243. return this._projectionMatrix;
  244. };
  245. BABYLON.Scene.prototype.getTransformMatrix = function () {
  246. return this._transformMatrix;
  247. };
  248. BABYLON.Scene.prototype.setTransformMatrix = function (view, projection) {
  249. this._viewMatrix = view;
  250. this._projectionMatrix = projection;
  251. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  252. };
  253. // Methods
  254. BABYLON.Scene.prototype.setActiveCameraByID = function (id) {
  255. var camera = this.getCameraByID(id);
  256. if (camera) {
  257. this.activeCamera = camera;
  258. return camera;
  259. }
  260. return null;
  261. };
  262. BABYLON.Scene.prototype.setActiveCameraByName = function (name) {
  263. var camera = this.getCameraByName(name);
  264. if (camera) {
  265. this.activeCamera = camera;
  266. return camera;
  267. }
  268. return null;
  269. };
  270. BABYLON.Scene.prototype.getMaterialByID = function (id) {
  271. for (var index = 0; index < this.materials.length; index++) {
  272. if (this.materials[index].id === id) {
  273. return this.materials[index];
  274. }
  275. }
  276. return null;
  277. };
  278. BABYLON.Scene.prototype.getMaterialByName = function (name) {
  279. for (var index = 0; index < this.materials.length; index++) {
  280. if (this.materials[index].name === name) {
  281. return this.materials[index];
  282. }
  283. }
  284. return null;
  285. };
  286. BABYLON.Scene.prototype.getCameraByID = function (id) {
  287. for (var index = 0; index < this.cameras.length; index++) {
  288. if (this.cameras[index].id === id) {
  289. return this.cameras[index];
  290. }
  291. }
  292. return null;
  293. };
  294. BABYLON.Scene.prototype.getCameraByName = function (name) {
  295. for (var index = 0; index < this.cameras.length; index++) {
  296. if (this.cameras[index].name === name) {
  297. return this.cameras[index];
  298. }
  299. }
  300. return null;
  301. };
  302. BABYLON.Scene.prototype.getLightByID = function (id) {
  303. for (var index = 0; index < this.lights.length; index++) {
  304. if (this.lights[index].id === id) {
  305. return this.lights[index];
  306. }
  307. }
  308. return null;
  309. };
  310. BABYLON.Scene.prototype.getMeshByID = function (id) {
  311. for (var index = 0; index < this.meshes.length; index++) {
  312. if (this.meshes[index].id === id) {
  313. return this.meshes[index];
  314. }
  315. }
  316. return null;
  317. };
  318. BABYLON.Scene.prototype.getLastMeshByID = function (id) {
  319. for (var index = this.meshes.length - 1; index >= 0 ; index--) {
  320. if (this.meshes[index].id === id) {
  321. return this.meshes[index];
  322. }
  323. }
  324. return null;
  325. };
  326. BABYLON.Scene.prototype.getLastEntryByID = function (id) {
  327. for (var index = this.meshes.length - 1; index >= 0 ; index--) {
  328. if (this.meshes[index].id === id) {
  329. return this.meshes[index];
  330. }
  331. }
  332. for (var index = this.cameras.length - 1; index >= 0 ; index--) {
  333. if (this.cameras[index].id === id) {
  334. return this.cameras[index];
  335. }
  336. }
  337. for (var index = this.lights.length - 1; index >= 0 ; index--) {
  338. if (this.lights[index].id === id) {
  339. return this.lights[index];
  340. }
  341. }
  342. return null;
  343. };
  344. BABYLON.Scene.prototype.getMeshByName = function (name) {
  345. for (var index = 0; index < this.meshes.length; index++) {
  346. if (this.meshes[index].name === name) {
  347. return this.meshes[index];
  348. }
  349. }
  350. return null;
  351. };
  352. BABYLON.Scene.prototype.getLastSkeletonByID = function (id) {
  353. for (var index = this.skeletons.length - 1; index >= 0 ; index--) {
  354. if (this.skeletons[index].id === id) {
  355. return this.skeletons[index];
  356. }
  357. }
  358. return null;
  359. };
  360. BABYLON.Scene.prototype.getSkeletonById = function (id) {
  361. for (var index = 0; index < this.skeletons.length; index++) {
  362. if (this.skeletons[index].id === id) {
  363. return this.skeletons[index];
  364. }
  365. }
  366. return null;
  367. };
  368. BABYLON.Scene.prototype.getSkeletonByName = function (name) {
  369. for (var index = 0; index < this.skeleton.length; index++) {
  370. if (this.skeletons[index].name === name) {
  371. return this.skeletons[index];
  372. }
  373. }
  374. return null;
  375. };
  376. BABYLON.Scene.prototype.isActiveMesh = function (mesh) {
  377. return (this._activeMeshes.indexOf(mesh) !== -1);
  378. };
  379. BABYLON.Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  380. if (mesh.subMeshes.length == 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  381. var material = subMesh.getMaterial();
  382. if (material) {
  383. // Render targets
  384. if (material.getRenderTargetTextures) {
  385. if (this._processedMaterials.indexOf(material) === -1) {
  386. this._processedMaterials.push(material);
  387. this._renderTargets.concat(material.getRenderTargetTextures());
  388. }
  389. }
  390. // Dispatch
  391. this._activeVertices += subMesh.verticesCount;
  392. this._renderingManager.dispatch(subMesh);
  393. }
  394. }
  395. };
  396. BABYLON.Scene.prototype._evaluateActiveMeshes = function () {
  397. this._activeMeshes.reset();
  398. this._renderingManager.reset();
  399. this._processedMaterials.reset();
  400. this._activeParticleSystems.reset();
  401. this._activeSkeletons.reset();
  402. if (!this._frustumPlanes) {
  403. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  404. } else {
  405. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  406. }
  407. // Meshes
  408. if (this._selectionOctree) { // Octree
  409. var selection = this._selectionOctree.select(this._frustumPlanes);
  410. for (var blockIndex = 0; blockIndex < selection.length; blockIndex++) {
  411. var block = selection.data[blockIndex];
  412. for (var meshIndex = 0; meshIndex < block.meshes.length; meshIndex++) {
  413. var mesh = block.meshes[meshIndex];
  414. if (Math.abs(mesh._renderId) !== this._renderId) {
  415. this._totalVertices += mesh.getTotalVertices();
  416. if (!mesh.isReady()) {
  417. continue;
  418. }
  419. mesh.computeWorldMatrix();
  420. mesh._renderId = 0;
  421. }
  422. if (mesh._renderId === this._renderId || (mesh._renderId === 0 && mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && mesh.isInFrustum(this._frustumPlanes))) {
  423. if (mesh._renderId === 0) {
  424. this._activeMeshes.push(mesh);
  425. }
  426. mesh._renderId = this._renderId;
  427. if (mesh.skeleton) {
  428. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  429. }
  430. var subMeshes = block.subMeshes[meshIndex];
  431. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  432. var subMesh = subMeshes[subIndex];
  433. if (subMesh._renderId === this._renderId) {
  434. continue;
  435. }
  436. subMesh._renderId = this._renderId;
  437. this._evaluateSubMesh(subMesh, mesh);
  438. }
  439. } else {
  440. mesh._renderId = -this._renderId;
  441. }
  442. }
  443. }
  444. } else { // Full scene traversal
  445. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  446. var mesh = this.meshes[meshIndex];
  447. this._totalVertices += mesh.getTotalVertices();
  448. if (!mesh.isReady()) {
  449. continue;
  450. }
  451. mesh.computeWorldMatrix();
  452. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && mesh.isInFrustum(this._frustumPlanes)) {
  453. this._activeMeshes.push(mesh);
  454. if (mesh.skeleton) {
  455. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  456. }
  457. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  458. var subMesh = mesh.subMeshes[subIndex];
  459. this._evaluateSubMesh(subMesh, mesh);
  460. }
  461. }
  462. }
  463. }
  464. // Particle systems
  465. var beforeParticlesDate = new Date();
  466. if (this.particlesEnabled) {
  467. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  468. var particleSystem = this.particleSystems[particleIndex];
  469. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  470. this._activeParticleSystems.push(particleSystem);
  471. particleSystem.animate();
  472. }
  473. }
  474. }
  475. this._particlesDuration += new Date() - beforeParticlesDate;
  476. };
  477. BABYLON.Scene.prototype._renderForCamera = function (camera) {
  478. var engine = this._engine;
  479. this.activeCamera = camera;
  480. if (!this.activeCamera)
  481. throw new Error("Active camera not set");
  482. // Viewport
  483. engine.setViewport(this.activeCamera.viewport);
  484. // Camera
  485. this._renderId++;
  486. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  487. // Meshes
  488. var beforeEvaluateActiveMeshesDate = new Date();
  489. this._evaluateActiveMeshes();
  490. this._evaluateActiveMeshesDuration += new Date() - beforeEvaluateActiveMeshesDate;
  491. // Skeletons
  492. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  493. var skeleton = this._activeSkeletons.data[skeletonIndex];
  494. skeleton.prepare();
  495. }
  496. // Customs render targets registration
  497. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  498. this._renderTargets.push(this.customRenderTargets[customIndex]);
  499. }
  500. // Render targets
  501. var beforeRenderTargetDate = new Date();
  502. if (this.renderTargetsEnabled) {
  503. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  504. var renderTarget = this._renderTargets.data[renderIndex];
  505. this._renderId++;
  506. renderTarget.render();
  507. }
  508. }
  509. if (this._renderTargets.length > 0) { // Restore back buffer
  510. engine.restoreDefaultFramebuffer();
  511. }
  512. this._renderTargetsDuration = new Date() - beforeRenderTargetDate;
  513. // Prepare Frame
  514. this.postProcessManager._prepareFrame();
  515. var beforeRenderDate = new Date();
  516. // Backgrounds
  517. if (this.layers.length) {
  518. engine.setDepthBuffer(false);
  519. var layerIndex;
  520. var layer;
  521. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  522. layer = this.layers[layerIndex];
  523. if (layer.isBackground) {
  524. layer.render();
  525. }
  526. }
  527. engine.setDepthBuffer(true);
  528. }
  529. // Render
  530. this._renderingManager.render(null, null, true, true);
  531. // Lens flares
  532. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  533. this.lensFlareSystems[lensFlareSystemIndex].render();
  534. }
  535. // Foregrounds
  536. if (this.layers.length) {
  537. engine.setDepthBuffer(false);
  538. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  539. layer = this.layers[layerIndex];
  540. if (!layer.isBackground) {
  541. layer.render();
  542. }
  543. }
  544. engine.setDepthBuffer(true);
  545. }
  546. this._renderDuration += new Date() - beforeRenderDate;
  547. // Finalize frame
  548. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  549. // Update camera
  550. this.activeCamera._updateFromScene();
  551. // Reset some special arrays
  552. this._renderTargets.reset();
  553. };
  554. BABYLON.Scene.prototype._processSubCameras = function (camera) {
  555. if (camera.subCameras.length == 0) {
  556. this._renderForCamera(camera);
  557. return;
  558. }
  559. // Sub-cameras
  560. for (var index = 0; index < camera.subCameras.length; index++) {
  561. this._renderForCamera(camera.subCameras[index]);
  562. }
  563. this.activeCamera = camera;
  564. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  565. // Update camera
  566. this.activeCamera._updateFromScene();
  567. };
  568. BABYLON.Scene.prototype.render = function () {
  569. var startDate = new Date();
  570. this._particlesDuration = 0;
  571. this._spritesDuration = 0;
  572. this._activeParticles = 0;
  573. this._renderDuration = 0;
  574. this._evaluateActiveMeshesDuration = 0;
  575. this._totalVertices = 0;
  576. this._activeVertices = 0;
  577. // Before render
  578. if (this.beforeRender) {
  579. this.beforeRender();
  580. }
  581. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  582. this._onBeforeRenderCallbacks[callbackIndex]();
  583. }
  584. // Animations
  585. var deltaTime = BABYLON.Tools.GetDeltaTime();
  586. this._animationRatio = deltaTime * (60.0 / 1000.0);
  587. this._animate();
  588. // Physics
  589. if (this._physicsEngine) {
  590. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  591. }
  592. // Clear
  593. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe, true);
  594. // Shadows
  595. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  596. var light = this.lights[lightIndex];
  597. var shadowGenerator = light.getShadowGenerator();
  598. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap()._scene.textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  599. this._renderTargets.push(shadowGenerator.getShadowMap());
  600. }
  601. }
  602. // Multi-cameras?
  603. if (this.activeCameras.length > 0) {
  604. var currentRenderId = this._renderId;
  605. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  606. this._renderId = currentRenderId;
  607. this._processSubCameras(this.activeCameras[cameraIndex]);
  608. }
  609. } else {
  610. this._processSubCameras(this.activeCamera);
  611. }
  612. // After render
  613. if (this.afterRender) {
  614. this.afterRender();
  615. }
  616. // Cleaning
  617. for (var index = 0; index < this._toBeDisposed.length; index++) {
  618. this._toBeDisposed.data[index].dispose();
  619. this._toBeDisposed[index] = null;
  620. }
  621. this._toBeDisposed.reset();
  622. this._lastFrameDuration = new Date() - startDate;
  623. };
  624. BABYLON.Scene.prototype.dispose = function () {
  625. this.beforeRender = null;
  626. this.afterRender = null;
  627. this.skeletons = [];
  628. // Detach cameras
  629. var canvas = this._engine.getRenderingCanvas();
  630. var index;
  631. for (index = 0; index < this.cameras.length; index++) {
  632. this.cameras[index].detachControl(canvas);
  633. }
  634. // Release lights
  635. while (this.lights.length) {
  636. this.lights[0].dispose(true);
  637. }
  638. // Release meshes
  639. while (this.meshes.length) {
  640. this.meshes[0].dispose(true);
  641. }
  642. // Release cameras
  643. while (this.cameras.length) {
  644. this.cameras[0].dispose();
  645. }
  646. // Release materials
  647. while (this.materials.length) {
  648. this.materials[0].dispose();
  649. }
  650. // Release particles
  651. while (this.particleSystems.length) {
  652. this.particleSystems[0].dispose();
  653. }
  654. // Release sprites
  655. while (this.spriteManagers.length) {
  656. this.spriteManagers[0].dispose();
  657. }
  658. // Release layers
  659. while (this.layers.length) {
  660. this.layers[0].dispose();
  661. }
  662. // Release textures
  663. while (this.textures.length) {
  664. this.textures[0].dispose();
  665. }
  666. // Post-processes
  667. this.postProcessManager.dispose();
  668. // Physics
  669. if (this._physicsEngine) {
  670. this.disablePhysicsEngine();
  671. }
  672. // Remove from engine
  673. index = this._engine.scenes.indexOf(this);
  674. this._engine.scenes.splice(index, 1);
  675. this._engine.wipeCaches();
  676. };
  677. // Collisions
  678. BABYLON.Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition) {
  679. position.divideToRef(collider.radius, this._scaledPosition);
  680. velocity.divideToRef(collider.radius, this._scaledVelocity);
  681. collider.retry = 0;
  682. collider.initialVelocity = this._scaledVelocity;
  683. collider.initialPosition = this._scaledPosition;
  684. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition);
  685. finalPosition.multiplyInPlace(collider.radius);
  686. };
  687. BABYLON.Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition) {
  688. var closeDistance = BABYLON.Engine.collisionsEpsilon * 10.0;
  689. if (collider.retry >= maximumRetry) {
  690. finalPosition.copyFrom(position);
  691. return;
  692. }
  693. collider._initialize(position, velocity, closeDistance);
  694. // Check all meshes
  695. for (var index = 0; index < this.meshes.length; index++) {
  696. var mesh = this.meshes[index];
  697. if (mesh.isEnabled() && mesh.checkCollisions) {
  698. mesh._checkCollision(collider);
  699. }
  700. }
  701. if (!collider.collisionFound) {
  702. position.addToRef(velocity, finalPosition);
  703. return;
  704. }
  705. if (velocity.x != 0 || velocity.y != 0 || velocity.z != 0) {
  706. collider._getResponse(position, velocity);
  707. }
  708. if (velocity.length() <= closeDistance) {
  709. finalPosition.copyFrom(position);
  710. return;
  711. }
  712. collider.retry++;
  713. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition);
  714. };
  715. // Octrees
  716. BABYLON.Scene.prototype.createOrUpdateSelectionOctree = function () {
  717. if (!this._selectionOctree) {
  718. this._selectionOctree = new BABYLON.Octree();
  719. }
  720. // World limits
  721. var checkExtends = function (v, min, max) {
  722. if (v.x < min.x)
  723. min.x = v.x;
  724. if (v.y < min.y)
  725. min.y = v.y;
  726. if (v.z < min.z)
  727. min.z = v.z;
  728. if (v.x > max.x)
  729. max.x = v.x;
  730. if (v.y > max.y)
  731. max.y = v.y;
  732. if (v.z > max.z)
  733. max.z = v.z;
  734. };
  735. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  736. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  737. for (var index = 0; index < this.meshes.length; index++) {
  738. var mesh = this.meshes[index];
  739. mesh.computeWorldMatrix(true);
  740. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  741. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  742. checkExtends(minBox, min, max);
  743. checkExtends(maxBox, min, max);
  744. }
  745. // Update octree
  746. this._selectionOctree.update(min, max, this.meshes);
  747. };
  748. // Picking
  749. BABYLON.Scene.prototype.createPickingRay = function (x, y, world, camera) {
  750. var engine = this._engine;
  751. if (!camera) {
  752. if (!this.activeCamera)
  753. throw new Error("Active camera not set");
  754. camera = this.activeCamera;
  755. }
  756. var viewport = camera.viewport.toGlobal(engine);
  757. return BABYLON.Ray.CreateNew(x * this._engine.getHardwareScalingLevel(), y * this._engine.getHardwareScalingLevel(), viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  758. };
  759. BABYLON.Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  760. var pickingInfo = null;
  761. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  762. var mesh = this.meshes[meshIndex];
  763. if (predicate) {
  764. if (!predicate(mesh)) {
  765. continue;
  766. }
  767. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  768. continue;
  769. }
  770. var world = mesh.getWorldMatrix();
  771. var ray = rayFunction(world);
  772. var result = mesh.intersects(ray, fastCheck);
  773. if (!result.hit)
  774. continue;
  775. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  776. continue;
  777. pickingInfo = result;
  778. if (fastCheck) {
  779. break;
  780. }
  781. }
  782. return pickingInfo || new BABYLON.PickingInfo();
  783. };
  784. BABYLON.Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  785. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  786. /// <param name="x">X position on screen</param>
  787. /// <param name="y">Y position on screen</param>
  788. /// <param name="predicate">Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true</param>
  789. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  790. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  791. var that = this;
  792. return this._internalPick(function (world) {
  793. return that.createPickingRay(x, y, world, camera);
  794. }, predicate, fastCheck);
  795. };
  796. BABYLON.Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  797. var that = this;
  798. return this._internalPick(function (world) {
  799. if (!that._pickWithRayInverseMatrix) {
  800. that._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  801. }
  802. world.invertToRef(that._pickWithRayInverseMatrix);
  803. return BABYLON.Ray.Transform(ray, that._pickWithRayInverseMatrix);
  804. }, predicate, fastCheck);
  805. };
  806. // Physics
  807. BABYLON.Scene.prototype.enablePhysics = function (gravity, iterations) {
  808. if (this._physicsEngine) {
  809. return true;
  810. }
  811. if (!BABYLON.PhysicsEngine.IsSupported()) {
  812. return false;
  813. }
  814. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, iterations || 10);
  815. return true;
  816. };
  817. BABYLON.Scene.prototype.disablePhysicsEngine = function () {
  818. if (!this._physicsEngine) {
  819. return;
  820. }
  821. this._physicsEngine.dispose();
  822. this._physicsEngine = undefined;
  823. };
  824. BABYLON.Scene.prototype.isPhysicsEnabled = function () {
  825. return this._physicsEngine !== undefined;
  826. };
  827. BABYLON.Scene.prototype.setGravity = function (gravity) {
  828. if (!this._physicsEngine) {
  829. return;
  830. }
  831. this._physicsEngine._setGravity(gravity);
  832. };
  833. BABYLON.Scene.prototype.createCompoundImpostor = function (options) {
  834. if (!this._physicsEngine) {
  835. return null;
  836. }
  837. for (var index = 0; index < options.parts.length; index++) {
  838. var mesh = options.parts[index].mesh;
  839. mesh._physicImpostor = options.parts[index].impostor;
  840. mesh._physicsMass = options.mass / options.parts.length;
  841. mesh._physicsFriction = options.friction;
  842. mesh._physicRestitution = options.restitution;
  843. }
  844. return this._physicsEngine._registerCompound(options);
  845. };
  846. BABYLON.Scene.prototype.deleteCompoundImpostor = function (compound) {
  847. for (var index = 0; index < compound.parts.length; index++) {
  848. var mesh = compound.parts[index].mesh;
  849. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  850. this._scene._physicsEngine._unregisterMesh(mesh);
  851. }
  852. };
  853. // Tags
  854. BABYLON.Scene.prototype._getByTags = function(list, tagsQuery) {
  855. if (tagsQuery === undefined) {
  856. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  857. return list;
  858. }
  859. var listByTags = [];
  860. for (var i in list) {
  861. var item = list[i];
  862. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  863. listByTags.push(item);
  864. }
  865. }
  866. return listByTags;
  867. };
  868. BABYLON.Scene.prototype.getMeshesByTags = function (tagsQuery) {
  869. return this._getByTags(this.meshes, tagsQuery);
  870. };
  871. BABYLON.Scene.prototype.getCamerasByTags = function (tagsQuery) {
  872. return this._getByTags(this.cameras, tagsQuery);
  873. };
  874. BABYLON.Scene.prototype.getLightsByTags = function (tagsQuery) {
  875. return this._getByTags(this.lights, tagsQuery);
  876. };
  877. BABYLON.Scene.prototype.getMaterialByTags = function (tagsQuery) {
  878. return this._getByTags(this.materials, tagsQuery).concat(this._getByTags(this.multiMaterials, tagsQuery));
  879. };
  880. // Statics
  881. BABYLON.Scene.FOGMODE_NONE = 0;
  882. BABYLON.Scene.FOGMODE_EXP = 1;
  883. BABYLON.Scene.FOGMODE_EXP2 = 2;
  884. BABYLON.Scene.FOGMODE_LINEAR = 3;
  885. })();