babylon.scene.ts 69 KB

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