babylon.scene.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. var BABYLON = BABYLON || {};
  2. (function () {
  3. BABYLON.Scene = function (engine) {
  4. this._engine = engine;
  5. this.autoClear = true;
  6. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  8. engine.scenes.push(this);
  9. this._totalVertices = 0;
  10. this._activeVertices = 0;
  11. this._activeParticles = 0;
  12. this._lastFrameDuration = 0;
  13. this._evaluateActiveMeshesDuration = 0;
  14. this._renderTargetsDuration = 0;
  15. this._renderDuration = 0;
  16. this._toBeDisposed = [];
  17. this._onReadyCallbacks = [];
  18. this._pendingData = [];
  19. // Lights
  20. this.lights = [];
  21. // Cameras
  22. this.cameras = [];
  23. this.activeCamera = null;
  24. // Meshes
  25. this.meshes = [];
  26. this._activeMeshes = [];
  27. // Materials
  28. this.materials = [];
  29. this.multiMaterials = [];
  30. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  31. // Textures
  32. this.textures = [];
  33. // Particles
  34. this.particleSystems = [];
  35. // Sprites
  36. this.spriteManagers = [];
  37. // Layers
  38. this.layers = [];
  39. // Collisions
  40. this.collisionsEnabled = true;
  41. this.gravity = new BABYLON.Vector3(0, 0, -9);
  42. // Animations
  43. this._activeAnimatables = [];
  44. };
  45. // Properties
  46. BABYLON.Scene.prototype.getEngine = function () {
  47. return this._engine;
  48. };
  49. BABYLON.Scene.prototype.getTotalVertices = function () {
  50. return this._totalVertices;
  51. };
  52. BABYLON.Scene.prototype.getActiveVertices = function () {
  53. return this._activeVertices;
  54. };
  55. BABYLON.Scene.prototype.getTotalVertices = function () {
  56. return this._totalVertices;
  57. };
  58. BABYLON.Scene.prototype.getActiveParticles = function () {
  59. return this._activeParticles;
  60. };
  61. // Stats
  62. BABYLON.Scene.prototype.getLastFrameDuration = function () {
  63. return this._lastFrameDuration;
  64. };
  65. BABYLON.Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  66. return this._evaluateActiveMeshesDuration;
  67. };
  68. BABYLON.Scene.prototype.getRenderTargetsDuration = function () {
  69. return this._renderTargetsDuration;
  70. };
  71. BABYLON.Scene.prototype.getRenderDuration = function () {
  72. return this._renderDuration;
  73. };
  74. BABYLON.Scene.prototype.getParticlesDuration = function () {
  75. return this._particlesDuration;
  76. };
  77. BABYLON.Scene.prototype.getSpritesDuration = function () {
  78. return this._spritesDuration;
  79. };
  80. BABYLON.Scene.prototype.getAnimationRatio = function () {
  81. return this._animationRatio;
  82. };
  83. // Ready
  84. BABYLON.Scene.prototype.isReady = function () {
  85. for (var index = 0; index < this.materials.length; index++) {
  86. if (!this.materials[index].isReady()) {
  87. return false;
  88. }
  89. }
  90. return true;
  91. };
  92. BABYLON.Scene.prototype.executeWhenReady = function (func) {
  93. if (this.isReady()) {
  94. func();
  95. return;
  96. }
  97. if (this._pendingData.length === 0) {
  98. func();
  99. return;
  100. }
  101. this._onReadyCallbacks.push(func);
  102. };
  103. BABYLON.Scene.prototype._addPendingData = function (data) {
  104. this._pendingData.push(data);
  105. };
  106. BABYLON.Scene.prototype._removePendingData = function (data) {
  107. var index = this._pendingData.indexOf(data);
  108. if (index !== -1) {
  109. this._pendingData.splice(index, 1);
  110. if (this._pendingData.length === 0) {
  111. this._onReadyCallbacks.forEach(function (func) {
  112. func();
  113. });
  114. this._onReadyCallbacks = [];
  115. }
  116. }
  117. };
  118. // Animations
  119. BABYLON.Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio) {
  120. if (speedRatio === undefined) {
  121. speedRatio = 1.0;
  122. }
  123. // Local animations
  124. if (target.animations) {
  125. this.stopAnimation(target);
  126. var animatable = new BABYLON._Animatable(target, from, to, loop, speedRatio);
  127. this._activeAnimatables.push(animatable);
  128. }
  129. // Children animations
  130. if (target.getAnimatables) {
  131. var animatables = target.getAnimatables();
  132. for (var index = 0; index < animatables.length; index++) {
  133. this.beginAnimation(animatables[index], from, to, loop, speedRatio);
  134. }
  135. }
  136. };
  137. BABYLON.Scene.prototype.stopAnimation = function (target) {
  138. for (var index = 0; index < this._activeAnimatables.length; index++) {
  139. if (this._activeAnimatables[index].target === target) {
  140. this._activeAnimatables.splice(index, 1);
  141. return;
  142. }
  143. }
  144. };
  145. BABYLON.Scene.prototype._animate = function () {
  146. for (var index = 0; index < this._activeAnimatables.length; index++) {
  147. if (!this._activeAnimatables[index]._animate()) {
  148. this._activeAnimatables.splice(index, 1);
  149. index--;
  150. }
  151. }
  152. };
  153. // Matrix
  154. BABYLON.Scene.prototype.getViewMatrix = function () {
  155. return this._viewMatrix;
  156. };
  157. BABYLON.Scene.prototype.getProjectionMatrix = function () {
  158. return this._projectionMatrix;
  159. };
  160. BABYLON.Scene.prototype.getTransformMatrix = function () {
  161. return this._transformMatrix;
  162. };
  163. BABYLON.Scene.prototype.setTransformMatrix = function (view, projection) {
  164. this._viewMatrix = view;
  165. this._projectionMatrix = projection;
  166. this._transformMatrix = this._viewMatrix.multiply(this._projectionMatrix);
  167. };
  168. // Methods
  169. BABYLON.Scene.prototype.activeCameraByID = function (id) {
  170. for (var index = 0; index < this.cameras.length; index++) {
  171. if (this.cameras[index].id == id) {
  172. this.activeCamera = this.cameras[index];
  173. return;
  174. }
  175. }
  176. };
  177. BABYLON.Scene.prototype.getMaterialByID = function (id) {
  178. for (var index = 0; index < this.materials.length; index++) {
  179. if (this.materials[index].id == id) {
  180. return this.materials[index];
  181. }
  182. }
  183. return null;
  184. };
  185. BABYLON.Scene.prototype.getMeshByID = function (id) {
  186. for (var index = 0; index < this.meshes.length; index++) {
  187. if (this.meshes[index].id == id) {
  188. return this.meshes[index];
  189. }
  190. }
  191. return null;
  192. };
  193. BABYLON.Scene.prototype.getLastMeshByID = function (id) {
  194. var result = null;
  195. for (var index = 0; index < this.meshes.length; index++) {
  196. if (this.meshes[index].id == id) {
  197. result = this.meshes[index];
  198. }
  199. }
  200. return result;
  201. };
  202. BABYLON.Scene.prototype.getMeshByName = function (name) {
  203. for (var index = 0; index < this.meshes.length; index++) {
  204. if (this.meshes[index].name == name) {
  205. return this.meshes[index];
  206. }
  207. }
  208. return null;
  209. };
  210. BABYLON.Scene.prototype.isActiveMesh = function (mesh) {
  211. return (this._activeMeshes.indexOf(mesh) !== -1);
  212. };
  213. BABYLON.Scene.prototype._evaluateActiveMeshes = function () {
  214. this._activeMeshes = [];
  215. this._opaqueSubMeshes = [];
  216. this._transparentSubMeshes = [];
  217. this._alphaTestSubMeshes = [];
  218. this._processedMaterials = [];
  219. this._renderTargets = [];
  220. this._activeParticleSystems = [];
  221. var frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  222. this._totalVertices = 0;
  223. this._activeVertices = 0;
  224. // meshes
  225. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  226. var mesh = this.meshes[meshIndex];
  227. this._totalVertices += mesh.getTotalVertices();
  228. mesh.computeWorldMatrix();
  229. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && mesh.isInFrustrum(frustumPlanes)) {
  230. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  231. var subMesh = mesh.subMeshes[subIndex];
  232. if (mesh.subMeshes.length == 1 || subMesh.isInFrustrum(frustumPlanes)) {
  233. var material = subMesh.getMaterial();
  234. if (this._activeMeshes.indexOf(mesh) === -1) {
  235. this._activeMeshes.push(mesh);
  236. }
  237. if (material) {
  238. // Render targets
  239. if (material.getRenderTargetTextures) {
  240. if (this._processedMaterials.indexOf(material) === -1) {
  241. this._processedMaterials.push(material);
  242. this._renderTargets = this._renderTargets.concat(material.getRenderTargetTextures());
  243. }
  244. }
  245. // Dispatch
  246. if (material.needAlphaBlending() || mesh.visibility < 1.0) { // Transparent
  247. if (material.alpha > 0 || mesh.visibility < 1.0) {
  248. this._transparentSubMeshes.push(subMesh); // Opaque
  249. }
  250. } else if (material.needAlphaTesting()) { // Alpha test
  251. this._alphaTestSubMeshes.push(subMesh);
  252. } else {
  253. this._opaqueSubMeshes.push(subMesh);
  254. }
  255. }
  256. }
  257. }
  258. }
  259. }
  260. // Particle systems
  261. var beforeParticlesDate = new Date();
  262. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  263. var particleSystem = this.particleSystems[particleIndex];
  264. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  265. this._activeParticleSystems.push(particleSystem);
  266. particleSystem.animate();
  267. }
  268. }
  269. this._particlesDuration += new Date() - beforeParticlesDate;
  270. };
  271. BABYLON.Scene.prototype._localRender = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, activeMeshes) {
  272. var engine = this._engine;
  273. // Opaque
  274. for (var subIndex = 0; subIndex < opaqueSubMeshes.length; subIndex++) {
  275. var submesh = opaqueSubMeshes[subIndex];
  276. this._activeVertices += submesh.verticesCount;
  277. submesh.render();
  278. }
  279. // Alpha test
  280. engine.setAlphaTesting(true);
  281. for (var subIndex = 0; subIndex < alphaTestSubMeshes.length; subIndex++) {
  282. var submesh = alphaTestSubMeshes[subIndex];
  283. this._activeVertices += submesh.verticesCount;
  284. submesh.render();
  285. }
  286. engine.setAlphaTesting(false);
  287. if (!activeMeshes) {
  288. // Sprites
  289. var beforeSpritessDate = new Date();
  290. for (var index = 0; index < this.spriteManagers.length; index++) {
  291. var spriteManager = this.spriteManagers[index];
  292. spriteManager.render();
  293. }
  294. this._spritesDuration = new Date() - beforeSpritessDate;
  295. }
  296. // Transparent
  297. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  298. for (var subIndex = 0; subIndex < transparentSubMeshes.length; subIndex++) {
  299. var submesh = transparentSubMeshes[subIndex];
  300. this._activeVertices += submesh.verticesCount;
  301. submesh.render();
  302. }
  303. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  304. // Particles
  305. var beforeParticlesDate = new Date();
  306. for (var particleIndex = 0; particleIndex < this._activeParticleSystems.length; particleIndex++) {
  307. var particleSystem = this._activeParticleSystems[particleIndex];
  308. if (!activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  309. this._activeParticles += particleSystem.render();
  310. }
  311. }
  312. this._particlesDuration += new Date() - beforeParticlesDate;
  313. };
  314. BABYLON.Scene.prototype.render = function () {
  315. var startDate = new Date();
  316. this._particlesDuration = 0;
  317. this._activeParticles = 0;
  318. var engine = this._engine;
  319. // Before render
  320. if (this.beforeRender) {
  321. this.beforeRender();
  322. }
  323. // Camera
  324. if (!this.activeCamera)
  325. throw new Error("Active camera not set");
  326. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  327. // Animations
  328. this._animationRatio = BABYLON.Tools.GetDeltaTime() * (60.0 / 1000.0);
  329. this._animate();
  330. // Meshes
  331. var beforeEvaluateActiveMeshesDate = new Date();
  332. this._evaluateActiveMeshes();
  333. this._evaluateActiveMeshesDuration = new Date() - beforeEvaluateActiveMeshesDate;
  334. // Render targets
  335. var beforeRenderTargetDate = new Date();
  336. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  337. var renderTarget = this._renderTargets[renderIndex];
  338. renderTarget.render();
  339. }
  340. if (this._renderTargets.length > 0) { // Restore back buffer
  341. engine.restoreDefaultFramebuffer();
  342. }
  343. this._renderTargetsDuration = new Date() - beforeRenderTargetDate;
  344. // Clear
  345. var beforeRenderDate = new Date();
  346. engine.clear(this.clearColor, this.autoClear, true);
  347. // Backgrounds
  348. engine.setDepthBuffer(false);
  349. for (var layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  350. var layer = this.layers[layerIndex];
  351. if (layer.isBackground) {
  352. layer.render();
  353. }
  354. }
  355. engine.setDepthBuffer(true);
  356. // Render
  357. this._localRender(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  358. // Foregrounds
  359. engine.setDepthBuffer(false);
  360. for (var layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  361. var layer = this.layers[layerIndex];
  362. if (!layer.isBackground) {
  363. layer.render();
  364. }
  365. }
  366. engine.setDepthBuffer(true);
  367. this._renderDuration = new Date() - beforeRenderDate;
  368. // Update camera
  369. this.activeCamera._update();
  370. // After render
  371. if (this.afterRender) {
  372. this.afterRender();
  373. }
  374. // Cleaning
  375. for (var index = 0; index < this._toBeDisposed.length; index++) {
  376. this._toBeDisposed[index].dispose();
  377. }
  378. this._toBeDisposed = [];
  379. this._lastFrameDuration = new Date() - startDate;
  380. };
  381. BABYLON.Scene.prototype.dispose = function () {
  382. this.beforeRender = null;
  383. this.afterRender = null;
  384. // Detach cameras
  385. var canvas = this._engine.getRenderingCanvas();
  386. for (var index = 0; index < this.cameras.length; index++) {
  387. this.cameras[index].detachControl(canvas);
  388. }
  389. // Release meshes
  390. while (this.meshes.length) {
  391. this.meshes[0].dispose(true);
  392. }
  393. // Release materials
  394. while (this.materials.length) {
  395. this.materials[0].dispose();
  396. }
  397. // Release particles
  398. while (this.particleSystems.length) {
  399. this.particleSystems[0].dispose();
  400. }
  401. // Release sprites
  402. while (this.spriteManagers.length) {
  403. this.spriteManagers[0].dispose();
  404. }
  405. // Release layers
  406. while (this.layers.length) {
  407. this.layers[0].dispose();
  408. }
  409. // Release textures
  410. while (this.textures.length) {
  411. this.textures[index].dispose();
  412. }
  413. // Remove from engine
  414. var index = this._engine.scenes.indexOf(this);
  415. this._engine.scenes.splice(index, 1);
  416. this._engine.wipeCaches();
  417. };
  418. // Collisions
  419. BABYLON.Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry) {
  420. var scaledPosition = position.divide(collider.radius);
  421. var scaledVelocity = velocity.divide(collider.radius);
  422. collider.retry = 0;
  423. collider.initialVelocity = scaledVelocity;
  424. collider.initialPosition = scaledPosition;
  425. var finalPosition = this._collideWithWorld(scaledPosition, scaledVelocity, collider, maximumRetry);
  426. finalPosition = finalPosition.multiply(collider.radius);
  427. return finalPosition;
  428. };
  429. BABYLON.Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry) {
  430. var closeDistance = BABYLON.Engine.collisionsEpsilon * 10.0;
  431. if (collider.retry >= maximumRetry) {
  432. return position;
  433. }
  434. collider._initialize(position, velocity, closeDistance);
  435. // Check all meshes
  436. for (var index = 0; index < this.meshes.length; index++) {
  437. var mesh = this.meshes[index];
  438. if (mesh.isEnabled() && mesh.checkCollisions) {
  439. mesh._checkCollision(collider);
  440. }
  441. }
  442. if (!collider.collisionFound) {
  443. return position.add(velocity);
  444. }
  445. if (velocity.x != 0 || velocity.y != 0 || velocity.z != 0) {
  446. var response = collider._getResponse(position, velocity);
  447. position = response.position;
  448. velocity = response.velocity;
  449. }
  450. if (velocity.length() <= closeDistance) {
  451. return position;
  452. }
  453. collider.retry++;
  454. return this._collideWithWorld(position, velocity, collider, maximumRetry);
  455. };
  456. // Picking
  457. BABYLON.Scene.prototype.createPickingRay = function (x, y, world) {
  458. var engine = this._engine;
  459. if (!this._viewMatrix) {
  460. if (!this.activeCamera)
  461. throw new Error("Active camera not set");
  462. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  463. }
  464. return BABYLON.Ray.CreateNew(x, y, engine.getRenderWidth(), engine.getRenderHeight(), world ? world : BABYLON.Matrix.Identity(), this._viewMatrix, this._projectionMatrix);
  465. };
  466. BABYLON.Scene.prototype.pick = function (x, y) {
  467. var distance = Number.MAX_VALUE;
  468. var pickedPoint = null;
  469. var pickedMesh = null;
  470. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  471. var mesh = this.meshes[meshIndex];
  472. if (!mesh.isEnabled() || !mesh.isVisible) {
  473. continue;
  474. }
  475. var world = mesh.getWorldMatrix();
  476. var ray = this.createPickingRay(x, y, world);
  477. var result = mesh.intersects(ray);
  478. if (!result.hit)
  479. continue;
  480. if (result.distance >= distance)
  481. continue;
  482. distance = result.distance;
  483. pickedMesh = mesh;
  484. // Get picked point
  485. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  486. var direction = ray.direction.clone();
  487. direction.normalize();
  488. direction = direction.scale(result.distance);
  489. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  490. pickedPoint = worldOrigin.add(worldDirection);
  491. }
  492. return { hit: distance != Number.MAX_VALUE, distance: distance, pickedMesh: pickedMesh, pickedPoint: pickedPoint };
  493. };
  494. })();