babylon.scene.ts 86 KB

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