babylon.scene.js 67 KB

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