babylon.scene.ts 66 KB

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