babylon.scene.js 59 KB

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