babylon.scene.ts 45 KB

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