babylon.scene.js 45 KB

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