babylon.scene.ts 78 KB

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