babylon.scene.ts 75 KB

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