babylon.scene.js 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609
  1. var BABYLON;
  2. (function (BABYLON) {
  3. /**
  4. * Represents a scene to be rendered by the engine.
  5. * @see http://doc.babylonjs.com/page.php?p=21911
  6. */
  7. var Scene = (function () {
  8. /**
  9. * @constructor
  10. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  11. */
  12. function Scene(engine) {
  13. // Members
  14. this.autoClear = true;
  15. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  17. this.forceWireframe = false;
  18. this.forcePointsCloud = false;
  19. this.forceShowBoundingBoxes = false;
  20. this.animationsEnabled = true;
  21. this.cameraToUseForPointers = null; // Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position
  22. // Fog
  23. /**
  24. * is fog enabled on this scene.
  25. * @type {boolean}
  26. */
  27. this.fogEnabled = true;
  28. this.fogMode = Scene.FOGMODE_NONE;
  29. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  30. this.fogDensity = 0.1;
  31. this.fogStart = 0;
  32. this.fogEnd = 1000.0;
  33. // Lights
  34. /**
  35. * is shadow enabled on this scene.
  36. * @type {boolean}
  37. */
  38. this.shadowsEnabled = true;
  39. /**
  40. * is light enabled on this scene.
  41. * @type {boolean}
  42. */
  43. this.lightsEnabled = true;
  44. /**
  45. * All of the lights added to this scene.
  46. * @see BABYLON.Light
  47. * @type {BABYLON.Light[]}
  48. */
  49. this.lights = new Array();
  50. // Cameras
  51. /**
  52. * All of the cameras added to this scene.
  53. * @see BABYLON.Camera
  54. * @type {BABYLON.Camera[]}
  55. */
  56. this.cameras = new Array();
  57. this.activeCameras = new Array();
  58. // Meshes
  59. /**
  60. * All of the (abstract) meshes added to this scene.
  61. * @see BABYLON.AbstractMesh
  62. * @type {BABYLON.AbstractMesh[]}
  63. */
  64. this.meshes = new Array();
  65. // Geometries
  66. this._geometries = new Array();
  67. this.materials = new Array();
  68. this.multiMaterials = new Array();
  69. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  70. // Textures
  71. this.texturesEnabled = true;
  72. this.textures = new Array();
  73. // Particles
  74. this.particlesEnabled = true;
  75. this.particleSystems = new Array();
  76. // Sprites
  77. this.spritesEnabled = true;
  78. this.spriteManagers = new Array();
  79. // Layers
  80. this.layers = new Array();
  81. // Skeletons
  82. this.skeletonsEnabled = true;
  83. this.skeletons = new Array();
  84. // Lens flares
  85. this.lensFlaresEnabled = true;
  86. this.lensFlareSystems = new Array();
  87. // Collisions
  88. this.collisionsEnabled = true;
  89. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  90. // Postprocesses
  91. this.postProcessesEnabled = true;
  92. // Customs render targets
  93. this.renderTargetsEnabled = true;
  94. this.dumpNextRenderTargets = false;
  95. this.customRenderTargets = new Array();
  96. // Imported meshes
  97. this.importedMeshesFiles = new Array();
  98. this._actionManagers = new Array();
  99. this._meshesForIntersections = new BABYLON.SmartArray(256);
  100. // Procedural textures
  101. this.proceduralTexturesEnabled = true;
  102. this._proceduralTextures = new Array();
  103. this.soundTracks = new Array();
  104. this._audioEnabled = true;
  105. this._headphone = false;
  106. this._totalVertices = 0;
  107. this._activeVertices = 0;
  108. this._activeParticles = 0;
  109. this._lastFrameDuration = 0;
  110. this._evaluateActiveMeshesDuration = 0;
  111. this._renderTargetsDuration = 0;
  112. this._particlesDuration = 0;
  113. this._renderDuration = 0;
  114. this._spritesDuration = 0;
  115. this._animationRatio = 0;
  116. this._renderId = 0;
  117. this._executeWhenReadyTimeoutId = -1;
  118. this._toBeDisposed = new BABYLON.SmartArray(256);
  119. this._onReadyCallbacks = new Array();
  120. this._pendingData = []; //ANY
  121. this._onBeforeRenderCallbacks = new Array();
  122. this._onAfterRenderCallbacks = new Array();
  123. this._activeMeshes = new BABYLON.SmartArray(256);
  124. this._processedMaterials = new BABYLON.SmartArray(256);
  125. this._renderTargets = new BABYLON.SmartArray(256);
  126. this._activeParticleSystems = new BABYLON.SmartArray(256);
  127. this._activeSkeletons = new BABYLON.SmartArray(32);
  128. this._activeBones = 0;
  129. this._activeAnimatables = new Array();
  130. this._transformMatrix = BABYLON.Matrix.Zero();
  131. this._scaledPosition = BABYLON.Vector3.Zero();
  132. this._scaledVelocity = BABYLON.Vector3.Zero();
  133. this._engine = engine;
  134. engine.scenes.push(this);
  135. this._renderingManager = new BABYLON.RenderingManager(this);
  136. this.postProcessManager = new BABYLON.PostProcessManager(this);
  137. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  138. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  139. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  140. this.attachControl();
  141. this._debugLayer = new BABYLON.DebugLayer(this);
  142. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  143. //simplification queue
  144. this.simplificationQueue = new BABYLON.SimplificationQueue();
  145. }
  146. Object.defineProperty(Scene, "FOGMODE_NONE", {
  147. get: function () {
  148. return Scene._FOGMODE_NONE;
  149. },
  150. enumerable: true,
  151. configurable: true
  152. });
  153. Object.defineProperty(Scene, "FOGMODE_EXP", {
  154. get: function () {
  155. return Scene._FOGMODE_EXP;
  156. },
  157. enumerable: true,
  158. configurable: true
  159. });
  160. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  161. get: function () {
  162. return Scene._FOGMODE_EXP2;
  163. },
  164. enumerable: true,
  165. configurable: true
  166. });
  167. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  168. get: function () {
  169. return Scene._FOGMODE_LINEAR;
  170. },
  171. enumerable: true,
  172. configurable: true
  173. });
  174. Object.defineProperty(Scene.prototype, "debugLayer", {
  175. // Properties
  176. get: function () {
  177. return this._debugLayer;
  178. },
  179. enumerable: true,
  180. configurable: true
  181. });
  182. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  183. /**
  184. * The mesh that is currently under the pointer.
  185. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  186. */
  187. get: function () {
  188. return this._meshUnderPointer;
  189. },
  190. enumerable: true,
  191. configurable: true
  192. });
  193. Object.defineProperty(Scene.prototype, "pointerX", {
  194. /**
  195. * Current on-screen X position of the pointer
  196. * @return {number} X position of the pointer
  197. */
  198. get: function () {
  199. return this._pointerX;
  200. },
  201. enumerable: true,
  202. configurable: true
  203. });
  204. Object.defineProperty(Scene.prototype, "pointerY", {
  205. /**
  206. * Current on-screen Y position of the pointer
  207. * @return {number} Y position of the pointer
  208. */
  209. get: function () {
  210. return this._pointerY;
  211. },
  212. enumerable: true,
  213. configurable: true
  214. });
  215. Scene.prototype.getCachedMaterial = function () {
  216. return this._cachedMaterial;
  217. };
  218. Scene.prototype.getBoundingBoxRenderer = function () {
  219. return this._boundingBoxRenderer;
  220. };
  221. Scene.prototype.getOutlineRenderer = function () {
  222. return this._outlineRenderer;
  223. };
  224. Scene.prototype.getEngine = function () {
  225. return this._engine;
  226. };
  227. Scene.prototype.getTotalVertices = function () {
  228. return this._totalVertices;
  229. };
  230. Scene.prototype.getActiveVertices = function () {
  231. return this._activeVertices;
  232. };
  233. Scene.prototype.getActiveParticles = function () {
  234. return this._activeParticles;
  235. };
  236. Scene.prototype.getActiveBones = function () {
  237. return this._activeBones;
  238. };
  239. // Stats
  240. Scene.prototype.getLastFrameDuration = function () {
  241. return this._lastFrameDuration;
  242. };
  243. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  244. return this._evaluateActiveMeshesDuration;
  245. };
  246. Scene.prototype.getActiveMeshes = function () {
  247. return this._activeMeshes;
  248. };
  249. Scene.prototype.getRenderTargetsDuration = function () {
  250. return this._renderTargetsDuration;
  251. };
  252. Scene.prototype.getRenderDuration = function () {
  253. return this._renderDuration;
  254. };
  255. Scene.prototype.getParticlesDuration = function () {
  256. return this._particlesDuration;
  257. };
  258. Scene.prototype.getSpritesDuration = function () {
  259. return this._spritesDuration;
  260. };
  261. Scene.prototype.getAnimationRatio = function () {
  262. return this._animationRatio;
  263. };
  264. Scene.prototype.getRenderId = function () {
  265. return this._renderId;
  266. };
  267. Scene.prototype.incrementRenderId = function () {
  268. this._renderId++;
  269. };
  270. Scene.prototype._updatePointerPosition = function (evt) {
  271. var canvasRect = this._engine.getRenderingCanvasClientRect();
  272. this._pointerX = evt.clientX - canvasRect.left;
  273. this._pointerY = evt.clientY - canvasRect.top;
  274. if (this.cameraToUseForPointers) {
  275. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  276. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  277. }
  278. };
  279. // Pointers handling
  280. Scene.prototype.attachControl = function () {
  281. var _this = this;
  282. this._onPointerMove = function (evt) {
  283. var canvas = _this._engine.getRenderingCanvas();
  284. _this._updatePointerPosition(evt);
  285. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers; }, false, _this.cameraToUseForPointers);
  286. if (pickResult.hit) {
  287. _this._meshUnderPointer = pickResult.pickedMesh;
  288. _this.setPointerOverMesh(pickResult.pickedMesh);
  289. canvas.style.cursor = "pointer";
  290. }
  291. else {
  292. _this.setPointerOverMesh(null);
  293. canvas.style.cursor = "";
  294. _this._meshUnderPointer = null;
  295. }
  296. };
  297. this._onPointerDown = function (evt) {
  298. var predicate = null;
  299. if (!_this.onPointerDown) {
  300. predicate = function (mesh) {
  301. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  302. };
  303. }
  304. _this._updatePointerPosition(evt);
  305. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  306. if (pickResult.hit) {
  307. if (pickResult.pickedMesh.actionManager) {
  308. switch (evt.button) {
  309. case 0:
  310. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  311. break;
  312. case 1:
  313. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  314. break;
  315. case 2:
  316. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  317. break;
  318. }
  319. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  320. }
  321. }
  322. if (_this.onPointerDown) {
  323. _this.onPointerDown(evt, pickResult);
  324. }
  325. };
  326. this._onKeyDown = function (evt) {
  327. if (_this.actionManager) {
  328. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  329. }
  330. };
  331. this._onKeyUp = function (evt) {
  332. if (_this.actionManager) {
  333. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  334. }
  335. };
  336. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  337. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  338. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  339. BABYLON.Tools.RegisterTopRootEvents([
  340. { name: "keydown", handler: this._onKeyDown },
  341. { name: "keyup", handler: this._onKeyUp }
  342. ]);
  343. };
  344. Scene.prototype.detachControl = function () {
  345. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  346. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  347. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  348. BABYLON.Tools.UnregisterTopRootEvents([
  349. { name: "keydown", handler: this._onKeyDown },
  350. { name: "keyup", handler: this._onKeyUp }
  351. ]);
  352. };
  353. // Ready
  354. Scene.prototype.isReady = function () {
  355. if (this._pendingData.length > 0) {
  356. return false;
  357. }
  358. for (var index = 0; index < this._geometries.length; index++) {
  359. var geometry = this._geometries[index];
  360. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  361. return false;
  362. }
  363. }
  364. for (index = 0; index < this.meshes.length; index++) {
  365. var mesh = this.meshes[index];
  366. if (!mesh.isReady()) {
  367. return false;
  368. }
  369. var mat = mesh.material;
  370. if (mat) {
  371. if (!mat.isReady(mesh)) {
  372. return false;
  373. }
  374. }
  375. }
  376. return true;
  377. };
  378. Scene.prototype.resetCachedMaterial = function () {
  379. this._cachedMaterial = null;
  380. };
  381. Scene.prototype.registerBeforeRender = function (func) {
  382. this._onBeforeRenderCallbacks.push(func);
  383. };
  384. Scene.prototype.unregisterBeforeRender = function (func) {
  385. var index = this._onBeforeRenderCallbacks.indexOf(func);
  386. if (index > -1) {
  387. this._onBeforeRenderCallbacks.splice(index, 1);
  388. }
  389. };
  390. Scene.prototype.registerAfterRender = function (func) {
  391. this._onAfterRenderCallbacks.push(func);
  392. };
  393. Scene.prototype.unregisterAfterRender = function (func) {
  394. var index = this._onAfterRenderCallbacks.indexOf(func);
  395. if (index > -1) {
  396. this._onAfterRenderCallbacks.splice(index, 1);
  397. }
  398. };
  399. Scene.prototype._addPendingData = function (data) {
  400. this._pendingData.push(data);
  401. };
  402. Scene.prototype._removePendingData = function (data) {
  403. var index = this._pendingData.indexOf(data);
  404. if (index !== -1) {
  405. this._pendingData.splice(index, 1);
  406. }
  407. };
  408. Scene.prototype.getWaitingItemsCount = function () {
  409. return this._pendingData.length;
  410. };
  411. /**
  412. * Registers a function to be executed when the scene is ready.
  413. * @param {Function} func - the function to be executed.
  414. */
  415. Scene.prototype.executeWhenReady = function (func) {
  416. var _this = this;
  417. this._onReadyCallbacks.push(func);
  418. if (this._executeWhenReadyTimeoutId !== -1) {
  419. return;
  420. }
  421. this._executeWhenReadyTimeoutId = setTimeout(function () {
  422. _this._checkIsReady();
  423. }, 150);
  424. };
  425. Scene.prototype._checkIsReady = function () {
  426. var _this = this;
  427. if (this.isReady()) {
  428. this._onReadyCallbacks.forEach(function (func) {
  429. func();
  430. });
  431. this._onReadyCallbacks = [];
  432. this._executeWhenReadyTimeoutId = -1;
  433. return;
  434. }
  435. this._executeWhenReadyTimeoutId = setTimeout(function () {
  436. _this._checkIsReady();
  437. }, 150);
  438. };
  439. // Animations
  440. /**
  441. * Will start the animation sequence of a given target
  442. * @param target - the target
  443. * @param {number} from - from which frame should animation start
  444. * @param {number} to - till which frame should animation run.
  445. * @param {boolean} [loop] - should the animation loop
  446. * @param {number} [speedRatio] - the speed in which to run the animation
  447. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  448. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  449. * @return {BABYLON.Animatable} the animatable object created for this animation
  450. * @see BABYLON.Animatable
  451. * @see http://doc.babylonjs.com/page.php?p=22081
  452. */
  453. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  454. if (speedRatio === undefined) {
  455. speedRatio = 1.0;
  456. }
  457. this.stopAnimation(target);
  458. if (!animatable) {
  459. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  460. }
  461. // Local animations
  462. if (target.animations) {
  463. animatable.appendAnimations(target, target.animations);
  464. }
  465. // Children animations
  466. if (target.getAnimatables) {
  467. var animatables = target.getAnimatables();
  468. for (var index = 0; index < animatables.length; index++) {
  469. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  470. }
  471. }
  472. return animatable;
  473. };
  474. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  475. if (speedRatio === undefined) {
  476. speedRatio = 1.0;
  477. }
  478. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  479. return animatable;
  480. };
  481. Scene.prototype.getAnimatableByTarget = function (target) {
  482. for (var index = 0; index < this._activeAnimatables.length; index++) {
  483. if (this._activeAnimatables[index].target === target) {
  484. return this._activeAnimatables[index];
  485. }
  486. }
  487. return null;
  488. };
  489. /**
  490. * Will stop the animation of the given target
  491. * @param target - the target
  492. * @see beginAnimation
  493. */
  494. Scene.prototype.stopAnimation = function (target) {
  495. var animatable = this.getAnimatableByTarget(target);
  496. if (animatable) {
  497. animatable.stop();
  498. }
  499. };
  500. Scene.prototype._animate = function () {
  501. if (!this.animationsEnabled) {
  502. return;
  503. }
  504. if (!this._animationStartDate) {
  505. this._animationStartDate = BABYLON.Tools.Now;
  506. }
  507. // Getting time
  508. var now = BABYLON.Tools.Now;
  509. var delay = now - this._animationStartDate;
  510. for (var index = 0; index < this._activeAnimatables.length; index++) {
  511. if (!this._activeAnimatables[index]._animate(delay)) {
  512. this._activeAnimatables.splice(index, 1);
  513. index--;
  514. }
  515. }
  516. };
  517. // Matrix
  518. Scene.prototype.getViewMatrix = function () {
  519. return this._viewMatrix;
  520. };
  521. Scene.prototype.getProjectionMatrix = function () {
  522. return this._projectionMatrix;
  523. };
  524. Scene.prototype.getTransformMatrix = function () {
  525. return this._transformMatrix;
  526. };
  527. Scene.prototype.setTransformMatrix = function (view, projection) {
  528. this._viewMatrix = view;
  529. this._projectionMatrix = projection;
  530. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  531. };
  532. // Methods
  533. /**
  534. * sets the active camera of the scene using its ID
  535. * @param {string} id - the camera's ID
  536. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  537. * @see activeCamera
  538. */
  539. Scene.prototype.setActiveCameraByID = function (id) {
  540. var camera = this.getCameraByID(id);
  541. if (camera) {
  542. this.activeCamera = camera;
  543. return camera;
  544. }
  545. return null;
  546. };
  547. /**
  548. * sets the active camera of the scene using its name
  549. * @param {string} name - the camera's name
  550. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  551. * @see activeCamera
  552. */
  553. Scene.prototype.setActiveCameraByName = function (name) {
  554. var camera = this.getCameraByName(name);
  555. if (camera) {
  556. this.activeCamera = camera;
  557. return camera;
  558. }
  559. return null;
  560. };
  561. /**
  562. * get a material using its id
  563. * @param {string} the material's ID
  564. * @return {BABYLON.Material|null} the material or null if none found.
  565. */
  566. Scene.prototype.getMaterialByID = function (id) {
  567. for (var index = 0; index < this.materials.length; index++) {
  568. if (this.materials[index].id === id) {
  569. return this.materials[index];
  570. }
  571. }
  572. return null;
  573. };
  574. /**
  575. * get a material using its name
  576. * @param {string} the material's name
  577. * @return {BABYLON.Material|null} the material or null if none found.
  578. */
  579. Scene.prototype.getMaterialByName = function (name) {
  580. for (var index = 0; index < this.materials.length; index++) {
  581. if (this.materials[index].name === name) {
  582. return this.materials[index];
  583. }
  584. }
  585. return null;
  586. };
  587. Scene.prototype.getCameraByID = function (id) {
  588. for (var index = 0; index < this.cameras.length; index++) {
  589. if (this.cameras[index].id === id) {
  590. return this.cameras[index];
  591. }
  592. }
  593. return null;
  594. };
  595. /**
  596. * get a camera using its name
  597. * @param {string} the camera's name
  598. * @return {BABYLON.Camera|null} the camera or null if none found.
  599. */
  600. Scene.prototype.getCameraByName = function (name) {
  601. for (var index = 0; index < this.cameras.length; index++) {
  602. if (this.cameras[index].name === name) {
  603. return this.cameras[index];
  604. }
  605. }
  606. return null;
  607. };
  608. /**
  609. * get a light node using its name
  610. * @param {string} the light's name
  611. * @return {BABYLON.Light|null} the light or null if none found.
  612. */
  613. Scene.prototype.getLightByName = function (name) {
  614. for (var index = 0; index < this.lights.length; index++) {
  615. if (this.lights[index].name === name) {
  616. return this.lights[index];
  617. }
  618. }
  619. return null;
  620. };
  621. /**
  622. * get a light node using its ID
  623. * @param {string} the light's id
  624. * @return {BABYLON.Light|null} the light or null if none found.
  625. */
  626. Scene.prototype.getLightByID = function (id) {
  627. for (var index = 0; index < this.lights.length; index++) {
  628. if (this.lights[index].id === id) {
  629. return this.lights[index];
  630. }
  631. }
  632. return null;
  633. };
  634. /**
  635. * get a geometry using its ID
  636. * @param {string} the geometry's id
  637. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  638. */
  639. Scene.prototype.getGeometryByID = function (id) {
  640. for (var index = 0; index < this._geometries.length; index++) {
  641. if (this._geometries[index].id === id) {
  642. return this._geometries[index];
  643. }
  644. }
  645. return null;
  646. };
  647. /**
  648. * add a new geometry to this scene.
  649. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  650. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  651. * @return {boolean} was the geometry added or not
  652. */
  653. Scene.prototype.pushGeometry = function (geometry, force) {
  654. if (!force && this.getGeometryByID(geometry.id)) {
  655. return false;
  656. }
  657. this._geometries.push(geometry);
  658. return true;
  659. };
  660. Scene.prototype.getGeometries = function () {
  661. return this._geometries;
  662. };
  663. /**
  664. * Get a the first added mesh found of a given ID
  665. * @param {string} id - the id to search for
  666. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  667. */
  668. Scene.prototype.getMeshByID = function (id) {
  669. for (var index = 0; index < this.meshes.length; index++) {
  670. if (this.meshes[index].id === id) {
  671. return this.meshes[index];
  672. }
  673. }
  674. return null;
  675. };
  676. /**
  677. * Get a the last added mesh found of a given ID
  678. * @param {string} id - the id to search for
  679. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  680. */
  681. Scene.prototype.getLastMeshByID = function (id) {
  682. for (var index = this.meshes.length - 1; index >= 0; index--) {
  683. if (this.meshes[index].id === id) {
  684. return this.meshes[index];
  685. }
  686. }
  687. return null;
  688. };
  689. /**
  690. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  691. * @param {string} id - the id to search for
  692. * @return {BABYLON.Node|null} the node found or null if not found at all.
  693. */
  694. Scene.prototype.getLastEntryByID = function (id) {
  695. for (var index = this.meshes.length - 1; index >= 0; index--) {
  696. if (this.meshes[index].id === id) {
  697. return this.meshes[index];
  698. }
  699. }
  700. for (index = this.cameras.length - 1; index >= 0; index--) {
  701. if (this.cameras[index].id === id) {
  702. return this.cameras[index];
  703. }
  704. }
  705. for (index = this.lights.length - 1; index >= 0; index--) {
  706. if (this.lights[index].id === id) {
  707. return this.lights[index];
  708. }
  709. }
  710. return null;
  711. };
  712. Scene.prototype.getNodeByName = function (name) {
  713. var mesh = this.getMeshByName(name);
  714. if (mesh) {
  715. return mesh;
  716. }
  717. var light = this.getLightByName(name);
  718. if (light) {
  719. return light;
  720. }
  721. return this.getCameraByName(name);
  722. };
  723. Scene.prototype.getMeshByName = function (name) {
  724. for (var index = 0; index < this.meshes.length; index++) {
  725. if (this.meshes[index].name === name) {
  726. return this.meshes[index];
  727. }
  728. }
  729. return null;
  730. };
  731. Scene.prototype.getSoundByName = function (name) {
  732. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  733. if (this.mainSoundTrack.soundCollection[index].name === name) {
  734. return this.mainSoundTrack.soundCollection[index];
  735. }
  736. }
  737. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  738. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  739. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  740. return this.soundTracks[sdIndex].soundCollection[index];
  741. }
  742. }
  743. }
  744. return null;
  745. };
  746. Scene.prototype.getLastSkeletonByID = function (id) {
  747. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  748. if (this.skeletons[index].id === id) {
  749. return this.skeletons[index];
  750. }
  751. }
  752. return null;
  753. };
  754. Scene.prototype.getSkeletonById = function (id) {
  755. for (var index = 0; index < this.skeletons.length; index++) {
  756. if (this.skeletons[index].id === id) {
  757. return this.skeletons[index];
  758. }
  759. }
  760. return null;
  761. };
  762. Scene.prototype.getSkeletonByName = function (name) {
  763. for (var index = 0; index < this.skeletons.length; index++) {
  764. if (this.skeletons[index].name === name) {
  765. return this.skeletons[index];
  766. }
  767. }
  768. return null;
  769. };
  770. Scene.prototype.isActiveMesh = function (mesh) {
  771. return (this._activeMeshes.indexOf(mesh) !== -1);
  772. };
  773. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  774. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  775. var material = subMesh.getMaterial();
  776. if (mesh.showSubMeshesBoundingBox) {
  777. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  778. }
  779. if (material) {
  780. // Render targets
  781. if (material.getRenderTargetTextures) {
  782. if (this._processedMaterials.indexOf(material) === -1) {
  783. this._processedMaterials.push(material);
  784. this._renderTargets.concat(material.getRenderTargetTextures());
  785. }
  786. }
  787. // Dispatch
  788. this._activeVertices += subMesh.indexCount;
  789. this._renderingManager.dispatch(subMesh);
  790. }
  791. }
  792. };
  793. Scene.prototype._evaluateActiveMeshes = function () {
  794. this.activeCamera._activeMeshes.reset();
  795. this._activeMeshes.reset();
  796. this._renderingManager.reset();
  797. this._processedMaterials.reset();
  798. this._activeParticleSystems.reset();
  799. this._activeSkeletons.reset();
  800. this._boundingBoxRenderer.reset();
  801. if (!this._frustumPlanes) {
  802. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  803. }
  804. else {
  805. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  806. }
  807. // Meshes
  808. var meshes;
  809. var len;
  810. if (this._selectionOctree) {
  811. var selection = this._selectionOctree.select(this._frustumPlanes);
  812. meshes = selection.data;
  813. len = selection.length;
  814. }
  815. else {
  816. len = this.meshes.length;
  817. meshes = this.meshes;
  818. }
  819. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  820. var mesh = meshes[meshIndex];
  821. if (mesh.isBlocked) {
  822. continue;
  823. }
  824. this._totalVertices += mesh.getTotalVertices();
  825. if (!mesh.isReady()) {
  826. continue;
  827. }
  828. mesh.computeWorldMatrix();
  829. // Intersections
  830. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  831. this._meshesForIntersections.pushNoDuplicate(mesh);
  832. }
  833. // Switch to current LOD
  834. var meshLOD = mesh.getLOD(this.activeCamera);
  835. if (!meshLOD) {
  836. continue;
  837. }
  838. mesh._preActivate();
  839. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  840. this._activeMeshes.push(mesh);
  841. this.activeCamera._activeMeshes.push(mesh);
  842. mesh._activate(this._renderId);
  843. this._activeMesh(meshLOD);
  844. }
  845. }
  846. // Particle systems
  847. var beforeParticlesDate = BABYLON.Tools.Now;
  848. if (this.particlesEnabled) {
  849. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  850. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  851. var particleSystem = this.particleSystems[particleIndex];
  852. if (!particleSystem.isStarted()) {
  853. continue;
  854. }
  855. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  856. this._activeParticleSystems.push(particleSystem);
  857. particleSystem.animate();
  858. }
  859. }
  860. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  861. }
  862. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  863. };
  864. Scene.prototype._activeMesh = function (mesh) {
  865. if (mesh.skeleton && this.skeletonsEnabled) {
  866. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  867. }
  868. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  869. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  870. }
  871. if (mesh && mesh.subMeshes) {
  872. // Submeshes Octrees
  873. var len;
  874. var subMeshes;
  875. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  876. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  877. len = intersections.length;
  878. subMeshes = intersections.data;
  879. }
  880. else {
  881. subMeshes = mesh.subMeshes;
  882. len = subMeshes.length;
  883. }
  884. for (var subIndex = 0; subIndex < len; subIndex++) {
  885. var subMesh = subMeshes[subIndex];
  886. this._evaluateSubMesh(subMesh, mesh);
  887. }
  888. }
  889. };
  890. Scene.prototype.updateTransformMatrix = function (force) {
  891. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  892. };
  893. Scene.prototype._renderForCamera = function (camera) {
  894. var engine = this._engine;
  895. this.activeCamera = camera;
  896. if (!this.activeCamera)
  897. throw new Error("Active camera not set");
  898. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  899. // Viewport
  900. engine.setViewport(this.activeCamera.viewport);
  901. // Camera
  902. this._renderId++;
  903. this.updateTransformMatrix();
  904. if (this.beforeCameraRender) {
  905. this.beforeCameraRender(this.activeCamera);
  906. }
  907. // Meshes
  908. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  909. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  910. this._evaluateActiveMeshes();
  911. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  912. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  913. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  914. var skeleton = this._activeSkeletons.data[skeletonIndex];
  915. skeleton.prepare();
  916. }
  917. // Render targets
  918. var beforeRenderTargetDate = BABYLON.Tools.Now;
  919. if (this.renderTargetsEnabled) {
  920. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  921. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  922. var renderTarget = this._renderTargets.data[renderIndex];
  923. if (renderTarget._shouldRender()) {
  924. this._renderId++;
  925. renderTarget.render(false, this.dumpNextRenderTargets);
  926. }
  927. }
  928. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  929. this._renderId++;
  930. }
  931. if (this._renderTargets.length > 0) {
  932. engine.restoreDefaultFramebuffer();
  933. }
  934. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  935. // Prepare Frame
  936. this.postProcessManager._prepareFrame();
  937. var beforeRenderDate = BABYLON.Tools.Now;
  938. // Backgrounds
  939. if (this.layers.length) {
  940. engine.setDepthBuffer(false);
  941. var layerIndex;
  942. var layer;
  943. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  944. layer = this.layers[layerIndex];
  945. if (layer.isBackground) {
  946. layer.render();
  947. }
  948. }
  949. engine.setDepthBuffer(true);
  950. }
  951. // Render
  952. BABYLON.Tools.StartPerformanceCounter("Main render");
  953. this._renderingManager.render(null, null, true, true);
  954. BABYLON.Tools.EndPerformanceCounter("Main render");
  955. // Bounding boxes
  956. this._boundingBoxRenderer.render();
  957. // Lens flares
  958. if (this.lensFlaresEnabled) {
  959. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  960. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  961. this.lensFlareSystems[lensFlareSystemIndex].render();
  962. }
  963. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  964. }
  965. // Foregrounds
  966. if (this.layers.length) {
  967. engine.setDepthBuffer(false);
  968. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  969. layer = this.layers[layerIndex];
  970. if (!layer.isBackground) {
  971. layer.render();
  972. }
  973. }
  974. engine.setDepthBuffer(true);
  975. }
  976. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  977. // Finalize frame
  978. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  979. // Update camera
  980. this.activeCamera._updateFromScene();
  981. // Reset some special arrays
  982. this._renderTargets.reset();
  983. if (this.afterCameraRender) {
  984. this.afterCameraRender(this.activeCamera);
  985. }
  986. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  987. };
  988. Scene.prototype._processSubCameras = function (camera) {
  989. if (camera.subCameras.length === 0) {
  990. this._renderForCamera(camera);
  991. return;
  992. }
  993. for (var index = 0; index < camera.subCameras.length; index++) {
  994. this._renderForCamera(camera.subCameras[index]);
  995. }
  996. this.activeCamera = camera;
  997. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  998. // Update camera
  999. this.activeCamera._updateFromScene();
  1000. };
  1001. Scene.prototype._checkIntersections = function () {
  1002. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  1003. var sourceMesh = this._meshesForIntersections.data[index];
  1004. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  1005. var action = sourceMesh.actionManager.actions[actionIndex];
  1006. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  1007. var parameters = action.getTriggerParameter();
  1008. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  1009. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  1010. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  1011. if (areIntersecting && currentIntersectionInProgress === -1) {
  1012. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  1013. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  1014. sourceMesh._intersectionsInProgress.push(otherMesh);
  1015. }
  1016. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  1017. sourceMesh._intersectionsInProgress.push(otherMesh);
  1018. }
  1019. }
  1020. else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  1021. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  1022. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  1023. if (indexOfOther > -1) {
  1024. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  1025. }
  1026. }
  1027. }
  1028. }
  1029. }
  1030. };
  1031. Scene.prototype.render = function () {
  1032. var startDate = BABYLON.Tools.Now;
  1033. this._particlesDuration = 0;
  1034. this._spritesDuration = 0;
  1035. this._activeParticles = 0;
  1036. this._renderDuration = 0;
  1037. this._renderTargetsDuration = 0;
  1038. this._evaluateActiveMeshesDuration = 0;
  1039. this._totalVertices = 0;
  1040. this._activeVertices = 0;
  1041. this._activeBones = 0;
  1042. this.getEngine().resetDrawCalls();
  1043. this._meshesForIntersections.reset();
  1044. this.resetCachedMaterial();
  1045. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  1046. // Actions
  1047. if (this.actionManager) {
  1048. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  1049. }
  1050. //Simplification Queue
  1051. if (!this.simplificationQueue.running) {
  1052. this.simplificationQueue.executeNext();
  1053. }
  1054. // Before render
  1055. if (this.beforeRender) {
  1056. this.beforeRender();
  1057. }
  1058. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  1059. this._onBeforeRenderCallbacks[callbackIndex]();
  1060. }
  1061. // Animations
  1062. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  1063. this._animationRatio = deltaTime * (60.0 / 1000.0);
  1064. this._animate();
  1065. // Physics
  1066. if (this._physicsEngine) {
  1067. BABYLON.Tools.StartPerformanceCounter("Physics");
  1068. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  1069. BABYLON.Tools.EndPerformanceCounter("Physics");
  1070. }
  1071. // Customs render targets
  1072. var beforeRenderTargetDate = BABYLON.Tools.Now;
  1073. var engine = this.getEngine();
  1074. var currentActiveCamera = this.activeCamera;
  1075. if (this.renderTargetsEnabled) {
  1076. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  1077. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  1078. var renderTarget = this.customRenderTargets[customIndex];
  1079. if (renderTarget._shouldRender()) {
  1080. this._renderId++;
  1081. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  1082. if (!this.activeCamera)
  1083. throw new Error("Active camera not set");
  1084. // Viewport
  1085. engine.setViewport(this.activeCamera.viewport);
  1086. // Camera
  1087. this.updateTransformMatrix();
  1088. renderTarget.render(false, this.dumpNextRenderTargets);
  1089. }
  1090. }
  1091. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  1092. this._renderId++;
  1093. }
  1094. if (this.customRenderTargets.length > 0) {
  1095. engine.restoreDefaultFramebuffer();
  1096. }
  1097. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  1098. this.activeCamera = currentActiveCamera;
  1099. // Procedural textures
  1100. if (this.proceduralTexturesEnabled) {
  1101. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  1102. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  1103. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  1104. if (proceduralTexture._shouldRender()) {
  1105. proceduralTexture.render();
  1106. }
  1107. }
  1108. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  1109. }
  1110. // Clear
  1111. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  1112. // Shadows
  1113. if (this.shadowsEnabled) {
  1114. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  1115. var light = this.lights[lightIndex];
  1116. var shadowGenerator = light.getShadowGenerator();
  1117. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  1118. this._renderTargets.push(shadowGenerator.getShadowMap());
  1119. }
  1120. }
  1121. }
  1122. // Depth renderer
  1123. if (this._depthRenderer) {
  1124. this._renderTargets.push(this._depthRenderer.getDepthMap());
  1125. }
  1126. // RenderPipeline
  1127. this.postProcessRenderPipelineManager.update();
  1128. // Multi-cameras?
  1129. if (this.activeCameras.length > 0) {
  1130. var currentRenderId = this._renderId;
  1131. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  1132. this._renderId = currentRenderId;
  1133. this._processSubCameras(this.activeCameras[cameraIndex]);
  1134. }
  1135. }
  1136. else {
  1137. if (!this.activeCamera) {
  1138. throw new Error("No camera defined");
  1139. }
  1140. this._processSubCameras(this.activeCamera);
  1141. }
  1142. // Intersection checks
  1143. this._checkIntersections();
  1144. // Update the audio listener attached to the camera
  1145. this._updateAudioParameters();
  1146. // After render
  1147. if (this.afterRender) {
  1148. this.afterRender();
  1149. }
  1150. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  1151. this._onAfterRenderCallbacks[callbackIndex]();
  1152. }
  1153. for (var index = 0; index < this._toBeDisposed.length; index++) {
  1154. this._toBeDisposed.data[index].dispose();
  1155. this._toBeDisposed[index] = null;
  1156. }
  1157. this._toBeDisposed.reset();
  1158. if (this.dumpNextRenderTargets) {
  1159. this.dumpNextRenderTargets = false;
  1160. }
  1161. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  1162. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  1163. };
  1164. Scene.prototype._updateAudioParameters = function () {
  1165. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  1166. return;
  1167. }
  1168. var listeningCamera;
  1169. var audioEngine = BABYLON.Engine.audioEngine;
  1170. if (this.activeCameras.length > 0) {
  1171. listeningCamera = this.activeCameras[0];
  1172. }
  1173. else {
  1174. listeningCamera = this.activeCamera;
  1175. }
  1176. if (listeningCamera && audioEngine.canUseWebAudio) {
  1177. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  1178. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  1179. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  1180. cameraDirection.normalize();
  1181. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  1182. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  1183. var sound = this.mainSoundTrack.soundCollection[i];
  1184. if (sound.useCustomAttenuation) {
  1185. sound.updateDistanceFromListener();
  1186. }
  1187. }
  1188. for (i = 0; i < this.soundTracks.length; i++) {
  1189. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  1190. sound = this.soundTracks[i].soundCollection[j];
  1191. if (sound.useCustomAttenuation) {
  1192. sound.updateDistanceFromListener();
  1193. }
  1194. }
  1195. }
  1196. }
  1197. };
  1198. Object.defineProperty(Scene.prototype, "audioEnabled", {
  1199. // Audio
  1200. get: function () {
  1201. return this._audioEnabled;
  1202. },
  1203. set: function (value) {
  1204. this._audioEnabled = value;
  1205. if (this._audioEnabled) {
  1206. this._enableAudio();
  1207. }
  1208. else {
  1209. this._disableAudio();
  1210. }
  1211. },
  1212. enumerable: true,
  1213. configurable: true
  1214. });
  1215. Scene.prototype._disableAudio = function () {
  1216. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  1217. this.mainSoundTrack.soundCollection[i].pause();
  1218. }
  1219. for (i = 0; i < this.soundTracks.length; i++) {
  1220. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  1221. this.soundTracks[i].soundCollection[j].pause();
  1222. }
  1223. }
  1224. };
  1225. Scene.prototype._enableAudio = function () {
  1226. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  1227. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  1228. this.mainSoundTrack.soundCollection[i].play();
  1229. }
  1230. }
  1231. for (i = 0; i < this.soundTracks.length; i++) {
  1232. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  1233. if (this.soundTracks[i].soundCollection[j].isPaused) {
  1234. this.soundTracks[i].soundCollection[j].play();
  1235. }
  1236. }
  1237. }
  1238. };
  1239. Object.defineProperty(Scene.prototype, "headphone", {
  1240. get: function () {
  1241. return this._headphone;
  1242. },
  1243. set: function (value) {
  1244. this._headphone = value;
  1245. if (this._headphone) {
  1246. this._switchAudioModeForHeadphones();
  1247. }
  1248. else {
  1249. this._switchAudioModeForNormalSpeakers();
  1250. }
  1251. },
  1252. enumerable: true,
  1253. configurable: true
  1254. });
  1255. Scene.prototype._switchAudioModeForHeadphones = function () {
  1256. this.mainSoundTrack.switchPanningModelToHRTF();
  1257. for (var i = 0; i < this.soundTracks.length; i++) {
  1258. this.soundTracks[i].switchPanningModelToHRTF();
  1259. }
  1260. };
  1261. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  1262. this.mainSoundTrack.switchPanningModelToEqualPower();
  1263. for (var i = 0; i < this.soundTracks.length; i++) {
  1264. this.soundTracks[i].switchPanningModelToEqualPower();
  1265. }
  1266. };
  1267. Scene.prototype.enableDepthRenderer = function () {
  1268. if (this._depthRenderer) {
  1269. return this._depthRenderer;
  1270. }
  1271. this._depthRenderer = new BABYLON.DepthRenderer(this);
  1272. return this._depthRenderer;
  1273. };
  1274. Scene.prototype.disableDepthRenderer = function () {
  1275. if (!this._depthRenderer) {
  1276. return;
  1277. }
  1278. this._depthRenderer.dispose();
  1279. this._depthRenderer = null;
  1280. };
  1281. Scene.prototype.dispose = function () {
  1282. this.beforeRender = null;
  1283. this.afterRender = null;
  1284. this.skeletons = [];
  1285. this._boundingBoxRenderer.dispose();
  1286. if (this._depthRenderer) {
  1287. this._depthRenderer.dispose();
  1288. }
  1289. // Debug layer
  1290. this.debugLayer.hide();
  1291. // Events
  1292. if (this.onDispose) {
  1293. this.onDispose();
  1294. }
  1295. this._onBeforeRenderCallbacks = [];
  1296. this._onAfterRenderCallbacks = [];
  1297. this.detachControl();
  1298. // Release sounds & sounds tracks
  1299. this.disposeSounds();
  1300. // Detach cameras
  1301. var canvas = this._engine.getRenderingCanvas();
  1302. var index;
  1303. for (index = 0; index < this.cameras.length; index++) {
  1304. this.cameras[index].detachControl(canvas);
  1305. }
  1306. while (this.lights.length) {
  1307. this.lights[0].dispose();
  1308. }
  1309. while (this.meshes.length) {
  1310. this.meshes[0].dispose(true);
  1311. }
  1312. while (this.cameras.length) {
  1313. this.cameras[0].dispose();
  1314. }
  1315. while (this.materials.length) {
  1316. this.materials[0].dispose();
  1317. }
  1318. while (this.particleSystems.length) {
  1319. this.particleSystems[0].dispose();
  1320. }
  1321. while (this.spriteManagers.length) {
  1322. this.spriteManagers[0].dispose();
  1323. }
  1324. while (this.layers.length) {
  1325. this.layers[0].dispose();
  1326. }
  1327. while (this.textures.length) {
  1328. this.textures[0].dispose();
  1329. }
  1330. // Post-processes
  1331. this.postProcessManager.dispose();
  1332. // Physics
  1333. if (this._physicsEngine) {
  1334. this.disablePhysicsEngine();
  1335. }
  1336. // Remove from engine
  1337. index = this._engine.scenes.indexOf(this);
  1338. if (index > -1) {
  1339. this._engine.scenes.splice(index, 1);
  1340. }
  1341. this._engine.wipeCaches();
  1342. };
  1343. // Release sounds & sounds tracks
  1344. Scene.prototype.disposeSounds = function () {
  1345. this.mainSoundTrack.dispose();
  1346. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  1347. this.soundTracks[scIndex].dispose();
  1348. }
  1349. };
  1350. // Collisions
  1351. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  1352. if (excludedMesh === void 0) { excludedMesh = null; }
  1353. position.divideToRef(collider.radius, this._scaledPosition);
  1354. velocity.divideToRef(collider.radius, this._scaledVelocity);
  1355. collider.retry = 0;
  1356. collider.initialVelocity = this._scaledVelocity;
  1357. collider.initialPosition = this._scaledPosition;
  1358. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  1359. finalPosition.multiplyInPlace(collider.radius);
  1360. };
  1361. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  1362. if (excludedMesh === void 0) { excludedMesh = null; }
  1363. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  1364. if (collider.retry >= maximumRetry) {
  1365. finalPosition.copyFrom(position);
  1366. return;
  1367. }
  1368. collider._initialize(position, velocity, closeDistance);
  1369. for (var index = 0; index < this.meshes.length; index++) {
  1370. var mesh = this.meshes[index];
  1371. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  1372. mesh._checkCollision(collider);
  1373. }
  1374. }
  1375. if (!collider.collisionFound) {
  1376. position.addToRef(velocity, finalPosition);
  1377. return;
  1378. }
  1379. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  1380. collider._getResponse(position, velocity);
  1381. }
  1382. if (velocity.length() <= closeDistance) {
  1383. finalPosition.copyFrom(position);
  1384. return;
  1385. }
  1386. collider.retry++;
  1387. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  1388. };
  1389. // Octrees
  1390. Scene.prototype.getWorldExtends = function () {
  1391. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1392. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1393. for (var index = 0; index < this.meshes.length; index++) {
  1394. var mesh = this.meshes[index];
  1395. mesh.computeWorldMatrix(true);
  1396. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  1397. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  1398. BABYLON.Tools.CheckExtends(minBox, min, max);
  1399. BABYLON.Tools.CheckExtends(maxBox, min, max);
  1400. }
  1401. return {
  1402. min: min,
  1403. max: max
  1404. };
  1405. };
  1406. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  1407. if (maxCapacity === void 0) { maxCapacity = 64; }
  1408. if (maxDepth === void 0) { maxDepth = 2; }
  1409. if (!this._selectionOctree) {
  1410. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  1411. }
  1412. var worldExtends = this.getWorldExtends();
  1413. // Update octree
  1414. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  1415. return this._selectionOctree;
  1416. };
  1417. // Picking
  1418. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  1419. var engine = this._engine;
  1420. if (!camera) {
  1421. if (!this.activeCamera)
  1422. throw new Error("Active camera not set");
  1423. camera = this.activeCamera;
  1424. }
  1425. var cameraViewport = camera.viewport;
  1426. var viewport = cameraViewport.toGlobal(engine);
  1427. // Moving coordinates to local viewport world
  1428. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  1429. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  1430. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  1431. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  1432. };
  1433. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  1434. var pickingInfo = null;
  1435. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  1436. var mesh = this.meshes[meshIndex];
  1437. if (predicate) {
  1438. if (!predicate(mesh)) {
  1439. continue;
  1440. }
  1441. }
  1442. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  1443. continue;
  1444. }
  1445. var world = mesh.getWorldMatrix();
  1446. var ray = rayFunction(world);
  1447. var result = mesh.intersects(ray, fastCheck);
  1448. if (!result || !result.hit)
  1449. continue;
  1450. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  1451. continue;
  1452. pickingInfo = result;
  1453. if (fastCheck) {
  1454. break;
  1455. }
  1456. }
  1457. return pickingInfo || new BABYLON.PickingInfo();
  1458. };
  1459. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  1460. var _this = this;
  1461. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  1462. /// <param name="x">X position on screen</param>
  1463. /// <param name="y">Y position on screen</param>
  1464. /// <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>
  1465. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  1466. /// <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>
  1467. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  1468. };
  1469. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  1470. var _this = this;
  1471. return this._internalPick(function (world) {
  1472. if (!_this._pickWithRayInverseMatrix) {
  1473. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  1474. }
  1475. world.invertToRef(_this._pickWithRayInverseMatrix);
  1476. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  1477. }, predicate, fastCheck);
  1478. };
  1479. Scene.prototype.setPointerOverMesh = function (mesh) {
  1480. if (this._pointerOverMesh === mesh) {
  1481. return;
  1482. }
  1483. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  1484. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  1485. }
  1486. this._pointerOverMesh = mesh;
  1487. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  1488. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  1489. }
  1490. };
  1491. Scene.prototype.getPointerOverMesh = function () {
  1492. return this._pointerOverMesh;
  1493. };
  1494. // Physics
  1495. Scene.prototype.getPhysicsEngine = function () {
  1496. return this._physicsEngine;
  1497. };
  1498. Scene.prototype.enablePhysics = function (gravity, plugin) {
  1499. if (this._physicsEngine) {
  1500. return true;
  1501. }
  1502. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  1503. if (!this._physicsEngine.isSupported()) {
  1504. this._physicsEngine = null;
  1505. return false;
  1506. }
  1507. this._physicsEngine._initialize(gravity);
  1508. return true;
  1509. };
  1510. Scene.prototype.disablePhysicsEngine = function () {
  1511. if (!this._physicsEngine) {
  1512. return;
  1513. }
  1514. this._physicsEngine.dispose();
  1515. this._physicsEngine = undefined;
  1516. };
  1517. Scene.prototype.isPhysicsEnabled = function () {
  1518. return this._physicsEngine !== undefined;
  1519. };
  1520. Scene.prototype.setGravity = function (gravity) {
  1521. if (!this._physicsEngine) {
  1522. return;
  1523. }
  1524. this._physicsEngine._setGravity(gravity);
  1525. };
  1526. Scene.prototype.createCompoundImpostor = function (parts, options) {
  1527. if (parts.parts) {
  1528. options = parts;
  1529. parts = parts.parts;
  1530. }
  1531. if (!this._physicsEngine) {
  1532. return null;
  1533. }
  1534. for (var index = 0; index < parts.length; index++) {
  1535. var mesh = parts[index].mesh;
  1536. mesh._physicImpostor = parts[index].impostor;
  1537. mesh._physicsMass = options.mass / parts.length;
  1538. mesh._physicsFriction = options.friction;
  1539. mesh._physicRestitution = options.restitution;
  1540. }
  1541. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  1542. };
  1543. Scene.prototype.deleteCompoundImpostor = function (compound) {
  1544. for (var index = 0; index < compound.parts.length; index++) {
  1545. var mesh = compound.parts[index].mesh;
  1546. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  1547. this._physicsEngine._unregisterMesh(mesh);
  1548. }
  1549. };
  1550. // Misc.
  1551. Scene.prototype.createDefaultCameraOrLight = function () {
  1552. // Light
  1553. if (this.lights.length === 0) {
  1554. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  1555. }
  1556. // Camera
  1557. if (!this.activeCamera) {
  1558. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  1559. // Compute position
  1560. var worldExtends = this.getWorldExtends();
  1561. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  1562. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  1563. camera.setTarget(worldCenter);
  1564. this.activeCamera = camera;
  1565. }
  1566. };
  1567. // Tags
  1568. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  1569. if (tagsQuery === undefined) {
  1570. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  1571. return list;
  1572. }
  1573. var listByTags = [];
  1574. forEach = forEach || (function (item) {
  1575. return;
  1576. });
  1577. for (var i in list) {
  1578. var item = list[i];
  1579. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  1580. listByTags.push(item);
  1581. forEach(item);
  1582. }
  1583. }
  1584. return listByTags;
  1585. };
  1586. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  1587. return this._getByTags(this.meshes, tagsQuery, forEach);
  1588. };
  1589. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  1590. return this._getByTags(this.cameras, tagsQuery, forEach);
  1591. };
  1592. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  1593. return this._getByTags(this.lights, tagsQuery, forEach);
  1594. };
  1595. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  1596. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  1597. };
  1598. // Statics
  1599. Scene._FOGMODE_NONE = 0;
  1600. Scene._FOGMODE_EXP = 1;
  1601. Scene._FOGMODE_EXP2 = 2;
  1602. Scene._FOGMODE_LINEAR = 3;
  1603. Scene.MinDeltaTime = 1.0;
  1604. Scene.MaxDeltaTime = 1000.0;
  1605. return Scene;
  1606. })();
  1607. BABYLON.Scene = Scene;
  1608. })(BABYLON || (BABYLON = {}));
  1609. //# sourceMappingURL=babylon.scene.js.map