babylon.scene.ts 78 KB

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