babylon.scene.js 113 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457
  1. var __extends = (this && this.__extends) || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  5. };
  6. var BABYLON;
  7. (function (BABYLON) {
  8. var PointerEventTypes = (function () {
  9. function PointerEventTypes() {
  10. }
  11. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  12. get: function () {
  13. return PointerEventTypes._POINTERDOWN;
  14. },
  15. enumerable: true,
  16. configurable: true
  17. });
  18. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  19. get: function () {
  20. return PointerEventTypes._POINTERUP;
  21. },
  22. enumerable: true,
  23. configurable: true
  24. });
  25. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  26. get: function () {
  27. return PointerEventTypes._POINTERMOVE;
  28. },
  29. enumerable: true,
  30. configurable: true
  31. });
  32. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  33. get: function () {
  34. return PointerEventTypes._POINTERWHEEL;
  35. },
  36. enumerable: true,
  37. configurable: true
  38. });
  39. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  40. get: function () {
  41. return PointerEventTypes._POINTERPICK;
  42. },
  43. enumerable: true,
  44. configurable: true
  45. });
  46. PointerEventTypes._POINTERDOWN = 0x01;
  47. PointerEventTypes._POINTERUP = 0x02;
  48. PointerEventTypes._POINTERMOVE = 0x04;
  49. PointerEventTypes._POINTERWHEEL = 0x08;
  50. PointerEventTypes._POINTERPICK = 0x10;
  51. return PointerEventTypes;
  52. }());
  53. BABYLON.PointerEventTypes = PointerEventTypes;
  54. var PointerInfoBase = (function () {
  55. function PointerInfoBase(type, event) {
  56. this.type = type;
  57. this.event = event;
  58. }
  59. return PointerInfoBase;
  60. }());
  61. BABYLON.PointerInfoBase = PointerInfoBase;
  62. /**
  63. * This class is used to store pointer related info for the onPrePointerObservable event.
  64. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  65. */
  66. var PointerInfoPre = (function (_super) {
  67. __extends(PointerInfoPre, _super);
  68. function PointerInfoPre(type, event, localX, localY) {
  69. _super.call(this, type, event);
  70. this.skipOnPointerObservable = false;
  71. this.localPosition = new BABYLON.Vector2(localX, localY);
  72. }
  73. return PointerInfoPre;
  74. }(PointerInfoBase));
  75. BABYLON.PointerInfoPre = PointerInfoPre;
  76. /**
  77. * This type contains all the data related to a pointer event in Babylon.js.
  78. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  79. */
  80. var PointerInfo = (function (_super) {
  81. __extends(PointerInfo, _super);
  82. function PointerInfo(type, event, pickInfo) {
  83. _super.call(this, type, event);
  84. this.pickInfo = pickInfo;
  85. }
  86. return PointerInfo;
  87. }(PointerInfoBase));
  88. BABYLON.PointerInfo = PointerInfo;
  89. /**
  90. * Represents a scene to be rendered by the engine.
  91. * @see http://doc.babylonjs.com/page.php?p=21911
  92. */
  93. var Scene = (function () {
  94. /**
  95. * @constructor
  96. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  97. */
  98. function Scene(engine) {
  99. // Members
  100. this.autoClear = true;
  101. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  102. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  103. this.forceWireframe = false;
  104. this.forcePointsCloud = false;
  105. this.forceShowBoundingBoxes = false;
  106. this.animationsEnabled = true;
  107. this.constantlyUpdateMeshUnderPointer = false;
  108. this.hoverCursor = "pointer";
  109. // Events
  110. /**
  111. * An event triggered when the scene is disposed.
  112. * @type {BABYLON.Observable}
  113. */
  114. this.onDisposeObservable = new BABYLON.Observable();
  115. /**
  116. * An event triggered before rendering the scene
  117. * @type {BABYLON.Observable}
  118. */
  119. this.onBeforeRenderObservable = new BABYLON.Observable();
  120. /**
  121. * An event triggered after rendering the scene
  122. * @type {BABYLON.Observable}
  123. */
  124. this.onAfterRenderObservable = new BABYLON.Observable();
  125. /**
  126. * An event triggered when the scene is ready
  127. * @type {BABYLON.Observable}
  128. */
  129. this.onReadyObservable = new BABYLON.Observable();
  130. /**
  131. * An event triggered before rendering a camera
  132. * @type {BABYLON.Observable}
  133. */
  134. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  135. /**
  136. * An event triggered after rendering a camera
  137. * @type {BABYLON.Observable}
  138. */
  139. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  140. /**
  141. * An event triggered when a camera is created
  142. * @type {BABYLON.Observable}
  143. */
  144. this.onNewCameraAddedObservable = new BABYLON.Observable();
  145. /**
  146. * An event triggered when a camera is removed
  147. * @type {BABYLON.Observable}
  148. */
  149. this.onCameraRemovedObservable = new BABYLON.Observable();
  150. /**
  151. * An event triggered when a light is created
  152. * @type {BABYLON.Observable}
  153. */
  154. this.onNewLightAddedObservable = new BABYLON.Observable();
  155. /**
  156. * An event triggered when a light is removed
  157. * @type {BABYLON.Observable}
  158. */
  159. this.onLightRemovedObservable = new BABYLON.Observable();
  160. /**
  161. * An event triggered when a geometry is created
  162. * @type {BABYLON.Observable}
  163. */
  164. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  165. /**
  166. * An event triggered when a geometry is removed
  167. * @type {BABYLON.Observable}
  168. */
  169. this.onGeometryRemovedObservable = new BABYLON.Observable();
  170. /**
  171. * An event triggered when a mesh is created
  172. * @type {BABYLON.Observable}
  173. */
  174. this.onNewMeshAddedObservable = new BABYLON.Observable();
  175. /**
  176. * An event triggered when a mesh is removed
  177. * @type {BABYLON.Observable}
  178. */
  179. this.onMeshRemovedObservable = new BABYLON.Observable();
  180. // Animations
  181. this.animations = [];
  182. /**
  183. * This observable event is triggered when any mouse event registered during Scene.attach() is called BEFORE the 3D engine to process anything (mesh/sprite picking for instance).
  184. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  185. */
  186. this.onPrePointerObservable = new BABYLON.Observable();
  187. /**
  188. * Observable event triggered each time an input event is received from the rendering canvas
  189. */
  190. this.onPointerObservable = new BABYLON.Observable();
  191. this.cameraToUseForPointers = null; // Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position
  192. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  193. this._startingPointerTime = 0;
  194. // Fog
  195. /**
  196. * is fog enabled on this scene.
  197. * @type {boolean}
  198. */
  199. this.fogEnabled = true;
  200. this.fogMode = Scene.FOGMODE_NONE;
  201. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  202. this.fogDensity = 0.1;
  203. this.fogStart = 0;
  204. this.fogEnd = 1000.0;
  205. // Lights
  206. /**
  207. * is shadow enabled on this scene.
  208. * @type {boolean}
  209. */
  210. this.shadowsEnabled = true;
  211. /**
  212. * is light enabled on this scene.
  213. * @type {boolean}
  214. */
  215. this.lightsEnabled = true;
  216. /**
  217. * All of the lights added to this scene.
  218. * @see BABYLON.Light
  219. * @type {BABYLON.Light[]}
  220. */
  221. this.lights = new Array();
  222. // Cameras
  223. /**
  224. * All of the cameras added to this scene.
  225. * @see BABYLON.Camera
  226. * @type {BABYLON.Camera[]}
  227. */
  228. this.cameras = new Array();
  229. this.activeCameras = new Array();
  230. // Meshes
  231. /**
  232. * All of the (abstract) meshes added to this scene.
  233. * @see BABYLON.AbstractMesh
  234. * @type {BABYLON.AbstractMesh[]}
  235. */
  236. this.meshes = new Array();
  237. // Geometries
  238. this._geometries = new Array();
  239. this.materials = new Array();
  240. this.multiMaterials = new Array();
  241. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  242. // Textures
  243. this.texturesEnabled = true;
  244. this.textures = new Array();
  245. // Particles
  246. this.particlesEnabled = true;
  247. this.particleSystems = new Array();
  248. // Sprites
  249. this.spritesEnabled = true;
  250. this.spriteManagers = new Array();
  251. // Layers
  252. this.layers = new Array();
  253. // Skeletons
  254. this.skeletonsEnabled = true;
  255. this.skeletons = new Array();
  256. // Lens flares
  257. this.lensFlaresEnabled = true;
  258. this.lensFlareSystems = new Array();
  259. // Collisions
  260. this.collisionsEnabled = true;
  261. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  262. // Postprocesses
  263. this.postProcessesEnabled = true;
  264. // Customs render targets
  265. this.renderTargetsEnabled = true;
  266. this.dumpNextRenderTargets = false;
  267. this.customRenderTargets = new Array();
  268. // Imported meshes
  269. this.importedMeshesFiles = new Array();
  270. // Probes
  271. this.probesEnabled = true;
  272. this.reflectionProbes = new Array();
  273. this._actionManagers = new Array();
  274. this._meshesForIntersections = new BABYLON.SmartArray(256);
  275. // Procedural textures
  276. this.proceduralTexturesEnabled = true;
  277. this._proceduralTextures = new Array();
  278. this.soundTracks = new Array();
  279. this._audioEnabled = true;
  280. this._headphone = false;
  281. // Performance counters
  282. this._totalMeshesCounter = new BABYLON.PerfCounter();
  283. this._totalLightsCounter = new BABYLON.PerfCounter();
  284. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  285. this._totalTexturesCounter = new BABYLON.PerfCounter();
  286. this._totalVertices = new BABYLON.PerfCounter();
  287. this._activeIndices = new BABYLON.PerfCounter();
  288. this._activeParticles = new BABYLON.PerfCounter();
  289. this._lastFrameDuration = new BABYLON.PerfCounter();
  290. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  291. this._renderTargetsDuration = new BABYLON.PerfCounter();
  292. this._particlesDuration = new BABYLON.PerfCounter();
  293. this._renderDuration = new BABYLON.PerfCounter();
  294. this._spritesDuration = new BABYLON.PerfCounter();
  295. this._activeBones = new BABYLON.PerfCounter();
  296. this._renderId = 0;
  297. this._executeWhenReadyTimeoutId = -1;
  298. this._intermediateRendering = false;
  299. this._toBeDisposed = new BABYLON.SmartArray(256);
  300. this._pendingData = []; //ANY
  301. this._activeMeshes = new BABYLON.SmartArray(256);
  302. this._processedMaterials = new BABYLON.SmartArray(256);
  303. this._renderTargets = new BABYLON.SmartArray(256);
  304. this._activeParticleSystems = new BABYLON.SmartArray(256);
  305. this._activeSkeletons = new BABYLON.SmartArray(32);
  306. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  307. this._activeAnimatables = new Array();
  308. this._transformMatrix = BABYLON.Matrix.Zero();
  309. this._edgesRenderers = new BABYLON.SmartArray(16);
  310. this._uniqueIdCounter = 0;
  311. this._engine = engine;
  312. engine.scenes.push(this);
  313. this._renderingManager = new BABYLON.RenderingManager(this);
  314. this.postProcessManager = new BABYLON.PostProcessManager(this);
  315. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  316. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  317. if (BABYLON.OutlineRenderer) {
  318. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  319. }
  320. this.attachControl();
  321. if (BABYLON.SoundTrack) {
  322. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  323. }
  324. //simplification queue
  325. if (BABYLON.SimplificationQueue) {
  326. this.simplificationQueue = new BABYLON.SimplificationQueue();
  327. }
  328. //collision coordinator initialization. For now legacy per default.
  329. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  330. }
  331. Object.defineProperty(Scene, "FOGMODE_NONE", {
  332. get: function () {
  333. return Scene._FOGMODE_NONE;
  334. },
  335. enumerable: true,
  336. configurable: true
  337. });
  338. Object.defineProperty(Scene, "FOGMODE_EXP", {
  339. get: function () {
  340. return Scene._FOGMODE_EXP;
  341. },
  342. enumerable: true,
  343. configurable: true
  344. });
  345. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  346. get: function () {
  347. return Scene._FOGMODE_EXP2;
  348. },
  349. enumerable: true,
  350. configurable: true
  351. });
  352. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  353. get: function () {
  354. return Scene._FOGMODE_LINEAR;
  355. },
  356. enumerable: true,
  357. configurable: true
  358. });
  359. Object.defineProperty(Scene.prototype, "onDispose", {
  360. set: function (callback) {
  361. if (this._onDisposeObserver) {
  362. this.onDisposeObservable.remove(this._onDisposeObserver);
  363. }
  364. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  365. },
  366. enumerable: true,
  367. configurable: true
  368. });
  369. Object.defineProperty(Scene.prototype, "beforeRender", {
  370. set: function (callback) {
  371. if (this._onBeforeRenderObserver) {
  372. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  373. }
  374. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  375. },
  376. enumerable: true,
  377. configurable: true
  378. });
  379. Object.defineProperty(Scene.prototype, "afterRender", {
  380. set: function (callback) {
  381. if (this._onAfterRenderObserver) {
  382. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  383. }
  384. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  385. },
  386. enumerable: true,
  387. configurable: true
  388. });
  389. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  390. set: function (callback) {
  391. if (this._onBeforeCameraRenderObserver) {
  392. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  393. }
  394. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  395. },
  396. enumerable: true,
  397. configurable: true
  398. });
  399. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  400. set: function (callback) {
  401. if (this._onAfterCameraRenderObserver) {
  402. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  403. }
  404. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  405. },
  406. enumerable: true,
  407. configurable: true
  408. });
  409. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  410. get: function () {
  411. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  412. },
  413. enumerable: true,
  414. configurable: true
  415. });
  416. Object.defineProperty(Scene.prototype, "debugLayer", {
  417. // Properties
  418. get: function () {
  419. if (!this._debugLayer) {
  420. this._debugLayer = new BABYLON.DebugLayer(this);
  421. }
  422. return this._debugLayer;
  423. },
  424. enumerable: true,
  425. configurable: true
  426. });
  427. Object.defineProperty(Scene.prototype, "workerCollisions", {
  428. get: function () {
  429. return this._workerCollisions;
  430. },
  431. set: function (enabled) {
  432. enabled = (enabled && !!Worker);
  433. this._workerCollisions = enabled;
  434. if (this.collisionCoordinator) {
  435. this.collisionCoordinator.destroy();
  436. }
  437. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  438. this.collisionCoordinator.init(this);
  439. },
  440. enumerable: true,
  441. configurable: true
  442. });
  443. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  444. get: function () {
  445. return this._selectionOctree;
  446. },
  447. enumerable: true,
  448. configurable: true
  449. });
  450. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  451. /**
  452. * The mesh that is currently under the pointer.
  453. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  454. */
  455. get: function () {
  456. return this._pointerOverMesh;
  457. },
  458. enumerable: true,
  459. configurable: true
  460. });
  461. Object.defineProperty(Scene.prototype, "pointerX", {
  462. /**
  463. * Current on-screen X position of the pointer
  464. * @return {number} X position of the pointer
  465. */
  466. get: function () {
  467. return this._pointerX;
  468. },
  469. enumerable: true,
  470. configurable: true
  471. });
  472. Object.defineProperty(Scene.prototype, "pointerY", {
  473. /**
  474. * Current on-screen Y position of the pointer
  475. * @return {number} Y position of the pointer
  476. */
  477. get: function () {
  478. return this._pointerY;
  479. },
  480. enumerable: true,
  481. configurable: true
  482. });
  483. Scene.prototype.getCachedMaterial = function () {
  484. return this._cachedMaterial;
  485. };
  486. Scene.prototype.getBoundingBoxRenderer = function () {
  487. return this._boundingBoxRenderer;
  488. };
  489. Scene.prototype.getOutlineRenderer = function () {
  490. return this._outlineRenderer;
  491. };
  492. Scene.prototype.getEngine = function () {
  493. return this._engine;
  494. };
  495. Scene.prototype.getTotalVertices = function () {
  496. return this._totalVertices.current;
  497. };
  498. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  499. get: function () {
  500. return this._totalVertices;
  501. },
  502. enumerable: true,
  503. configurable: true
  504. });
  505. Scene.prototype.getActiveIndices = function () {
  506. return this._activeIndices.current;
  507. };
  508. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  509. get: function () {
  510. return this._activeIndices;
  511. },
  512. enumerable: true,
  513. configurable: true
  514. });
  515. Scene.prototype.getActiveParticles = function () {
  516. return this._activeParticles.current;
  517. };
  518. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  519. get: function () {
  520. return this._activeParticles;
  521. },
  522. enumerable: true,
  523. configurable: true
  524. });
  525. Scene.prototype.getActiveBones = function () {
  526. return this._activeBones.current;
  527. };
  528. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  529. get: function () {
  530. return this._activeBones;
  531. },
  532. enumerable: true,
  533. configurable: true
  534. });
  535. // Stats
  536. Scene.prototype.getLastFrameDuration = function () {
  537. return this._lastFrameDuration.current;
  538. };
  539. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  540. get: function () {
  541. return this._lastFrameDuration;
  542. },
  543. enumerable: true,
  544. configurable: true
  545. });
  546. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  547. return this._evaluateActiveMeshesDuration.current;
  548. };
  549. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  550. get: function () {
  551. return this._evaluateActiveMeshesDuration;
  552. },
  553. enumerable: true,
  554. configurable: true
  555. });
  556. Scene.prototype.getActiveMeshes = function () {
  557. return this._activeMeshes;
  558. };
  559. Scene.prototype.getRenderTargetsDuration = function () {
  560. return this._renderTargetsDuration.current;
  561. };
  562. Scene.prototype.getRenderDuration = function () {
  563. return this._renderDuration.current;
  564. };
  565. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  566. get: function () {
  567. return this._renderDuration;
  568. },
  569. enumerable: true,
  570. configurable: true
  571. });
  572. Scene.prototype.getParticlesDuration = function () {
  573. return this._particlesDuration.current;
  574. };
  575. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  576. get: function () {
  577. return this._particlesDuration;
  578. },
  579. enumerable: true,
  580. configurable: true
  581. });
  582. Scene.prototype.getSpritesDuration = function () {
  583. return this._spritesDuration.current;
  584. };
  585. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  586. get: function () {
  587. return this._spritesDuration;
  588. },
  589. enumerable: true,
  590. configurable: true
  591. });
  592. Scene.prototype.getAnimationRatio = function () {
  593. return this._animationRatio;
  594. };
  595. Scene.prototype.getRenderId = function () {
  596. return this._renderId;
  597. };
  598. Scene.prototype.incrementRenderId = function () {
  599. this._renderId++;
  600. };
  601. Scene.prototype._updatePointerPosition = function (evt) {
  602. var canvasRect = this._engine.getRenderingCanvasClientRect();
  603. this._pointerX = evt.clientX - canvasRect.left;
  604. this._pointerY = evt.clientY - canvasRect.top;
  605. this._unTranslatedPointerX = this._pointerX;
  606. this._unTranslatedPointerY = this._pointerY;
  607. if (this.cameraToUseForPointers) {
  608. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  609. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  610. }
  611. };
  612. // Pointers handling
  613. /**
  614. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  615. * @param attachUp defines if you want to attach events to pointerup
  616. * @param attachDown defines if you want to attach events to pointerdown
  617. * @param attachMove defines if you want to attach events to pointermove
  618. */
  619. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  620. var _this = this;
  621. if (attachUp === void 0) { attachUp = true; }
  622. if (attachDown === void 0) { attachDown = true; }
  623. if (attachMove === void 0) { attachMove = true; }
  624. var spritePredicate = function (sprite) {
  625. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  626. };
  627. this._onPointerMove = function (evt) {
  628. _this._updatePointerPosition(evt);
  629. // PreObservable support
  630. if (_this.onPrePointerObservable.hasObservers()) {
  631. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  632. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  633. _this.onPrePointerObservable.notifyObservers(pi, type);
  634. if (pi.skipOnPointerObservable) {
  635. return;
  636. }
  637. }
  638. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  639. return;
  640. }
  641. var canvas = _this._engine.getRenderingCanvas();
  642. if (!_this.pointerMovePredicate) {
  643. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  644. }
  645. // Meshes
  646. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  647. if (pickResult.hit && pickResult.pickedMesh) {
  648. _this.setPointerOverSprite(null);
  649. _this.setPointerOverMesh(pickResult.pickedMesh);
  650. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  651. canvas.style.cursor = _this.hoverCursor;
  652. }
  653. else {
  654. canvas.style.cursor = "";
  655. }
  656. }
  657. else {
  658. _this.setPointerOverMesh(null);
  659. // Sprites
  660. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  661. if (pickResult.hit && pickResult.pickedSprite) {
  662. canvas.style.cursor = _this.hoverCursor;
  663. _this.setPointerOverSprite(pickResult.pickedSprite);
  664. }
  665. else {
  666. _this.setPointerOverSprite(null);
  667. // Restore pointer
  668. canvas.style.cursor = "";
  669. }
  670. }
  671. if (_this.onPointerMove) {
  672. _this.onPointerMove(evt, pickResult);
  673. }
  674. if (_this.onPointerObservable.hasObservers()) {
  675. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  676. var pi = new PointerInfo(type, evt, pickResult);
  677. _this.onPointerObservable.notifyObservers(pi, type);
  678. }
  679. };
  680. this._onPointerDown = function (evt) {
  681. _this._updatePointerPosition(evt);
  682. // PreObservable support
  683. if (_this.onPrePointerObservable.hasObservers()) {
  684. var type = PointerEventTypes.POINTERDOWN;
  685. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  686. _this.onPrePointerObservable.notifyObservers(pi, type);
  687. if (pi.skipOnPointerObservable) {
  688. return;
  689. }
  690. }
  691. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  692. return;
  693. }
  694. _this._startingPointerPosition.x = _this._pointerX;
  695. _this._startingPointerPosition.y = _this._pointerY;
  696. _this._startingPointerTime = new Date().getTime();
  697. if (!_this.pointerDownPredicate) {
  698. _this.pointerDownPredicate = function (mesh) {
  699. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  700. };
  701. }
  702. // Meshes
  703. _this._pickedDownMesh = null;
  704. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  705. if (pickResult.hit && pickResult.pickedMesh) {
  706. if (pickResult.pickedMesh.actionManager) {
  707. _this._pickedDownMesh = pickResult.pickedMesh;
  708. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  709. switch (evt.button) {
  710. case 0:
  711. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  712. break;
  713. case 1:
  714. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  715. break;
  716. case 2:
  717. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  718. break;
  719. }
  720. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  721. }
  722. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  723. var that = _this;
  724. window.setTimeout(function () {
  725. var pickResult = that.pick(that._unTranslatedPointerX, that._unTranslatedPointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger); }, false, that.cameraToUseForPointers);
  726. if (pickResult.hit && pickResult.pickedMesh) {
  727. if (pickResult.pickedMesh.actionManager) {
  728. if (that._startingPointerTime !== 0 && ((new Date().getTime() - that._startingPointerTime) > BABYLON.ActionManager.LongPressDelay) && (Math.abs(that._startingPointerPosition.x - that._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(that._startingPointerPosition.y - that._pointerY) < BABYLON.ActionManager.DragMovementThreshold)) {
  729. that._startingPointerTime = 0;
  730. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  731. }
  732. }
  733. }
  734. }, BABYLON.ActionManager.LongPressDelay);
  735. }
  736. }
  737. }
  738. if (_this.onPointerDown) {
  739. _this.onPointerDown(evt, pickResult);
  740. }
  741. if (_this.onPointerObservable.hasObservers()) {
  742. var type = PointerEventTypes.POINTERDOWN;
  743. var pi = new PointerInfo(type, evt, pickResult);
  744. _this.onPointerObservable.notifyObservers(pi, type);
  745. }
  746. // Sprites
  747. _this._pickedDownSprite = null;
  748. if (_this.spriteManagers.length > 0) {
  749. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  750. if (pickResult.hit && pickResult.pickedSprite) {
  751. if (pickResult.pickedSprite.actionManager) {
  752. _this._pickedDownSprite = pickResult.pickedSprite;
  753. switch (evt.button) {
  754. case 0:
  755. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  756. break;
  757. case 1:
  758. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  759. break;
  760. case 2:
  761. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  762. break;
  763. }
  764. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  765. }
  766. }
  767. }
  768. };
  769. this._onPointerUp = function (evt) {
  770. _this._updatePointerPosition(evt);
  771. // PreObservable support
  772. if (_this.onPrePointerObservable.hasObservers()) {
  773. var type = PointerEventTypes.POINTERUP;
  774. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  775. _this.onPrePointerObservable.notifyObservers(pi, type);
  776. if (pi.skipOnPointerObservable) {
  777. return;
  778. }
  779. }
  780. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  781. return;
  782. }
  783. if (!_this.pointerUpPredicate) {
  784. _this.pointerUpPredicate = function (mesh) {
  785. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  786. };
  787. }
  788. // Meshes
  789. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  790. if (pickResult.hit && pickResult.pickedMesh) {
  791. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  792. if (_this.onPointerPick) {
  793. _this.onPointerPick(evt, pickResult);
  794. }
  795. if (_this.onPointerObservable.hasObservers()) {
  796. var type = PointerEventTypes.POINTERPICK;
  797. var pi = new PointerInfo(type, evt, pickResult);
  798. _this.onPointerObservable.notifyObservers(pi, type);
  799. }
  800. }
  801. if (pickResult.pickedMesh.actionManager) {
  802. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  803. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  804. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  805. }
  806. }
  807. }
  808. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  809. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  810. }
  811. if (_this.onPointerUp) {
  812. _this.onPointerUp(evt, pickResult);
  813. }
  814. if (_this.onPointerObservable.hasObservers()) {
  815. var type = PointerEventTypes.POINTERUP;
  816. var pi = new PointerInfo(type, evt, pickResult);
  817. _this.onPointerObservable.notifyObservers(pi, type);
  818. }
  819. _this._startingPointerTime = 0;
  820. // Sprites
  821. if (_this.spriteManagers.length > 0) {
  822. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  823. if (pickResult.hit && pickResult.pickedSprite) {
  824. if (pickResult.pickedSprite.actionManager) {
  825. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  826. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  827. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  828. }
  829. }
  830. }
  831. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  832. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  833. }
  834. }
  835. };
  836. this._onKeyDown = function (evt) {
  837. if (_this.actionManager) {
  838. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  839. }
  840. };
  841. this._onKeyUp = function (evt) {
  842. if (_this.actionManager) {
  843. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  844. }
  845. };
  846. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  847. var canvas = this._engine.getRenderingCanvas();
  848. if (attachMove) {
  849. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  850. // Wheel
  851. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  852. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  853. }
  854. if (attachDown) {
  855. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  856. }
  857. if (attachUp) {
  858. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  859. }
  860. canvas.tabIndex = 1;
  861. canvas.addEventListener("keydown", this._onKeyDown, false);
  862. canvas.addEventListener("keyup", this._onKeyUp, false);
  863. };
  864. Scene.prototype.detachControl = function () {
  865. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  866. var canvas = this._engine.getRenderingCanvas();
  867. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  868. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  869. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  870. // Wheel
  871. canvas.removeEventListener('mousewheel', this._onPointerMove);
  872. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  873. canvas.removeEventListener("keydown", this._onKeyDown);
  874. canvas.removeEventListener("keyup", this._onKeyUp);
  875. };
  876. // Ready
  877. Scene.prototype.isReady = function () {
  878. if (this._pendingData.length > 0) {
  879. return false;
  880. }
  881. var index;
  882. for (index = 0; index < this._geometries.length; index++) {
  883. var geometry = this._geometries[index];
  884. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  885. return false;
  886. }
  887. }
  888. for (index = 0; index < this.meshes.length; index++) {
  889. var mesh = this.meshes[index];
  890. if (!mesh.isReady()) {
  891. return false;
  892. }
  893. var mat = mesh.material;
  894. if (mat) {
  895. if (!mat.isReady(mesh)) {
  896. return false;
  897. }
  898. }
  899. }
  900. return true;
  901. };
  902. Scene.prototype.resetCachedMaterial = function () {
  903. this._cachedMaterial = null;
  904. };
  905. Scene.prototype.registerBeforeRender = function (func) {
  906. this.onBeforeRenderObservable.add(func);
  907. };
  908. Scene.prototype.unregisterBeforeRender = function (func) {
  909. this.onBeforeRenderObservable.removeCallback(func);
  910. };
  911. Scene.prototype.registerAfterRender = function (func) {
  912. this.onAfterRenderObservable.add(func);
  913. };
  914. Scene.prototype.unregisterAfterRender = function (func) {
  915. this.onAfterRenderObservable.removeCallback(func);
  916. };
  917. Scene.prototype._addPendingData = function (data) {
  918. this._pendingData.push(data);
  919. };
  920. Scene.prototype._removePendingData = function (data) {
  921. var index = this._pendingData.indexOf(data);
  922. if (index !== -1) {
  923. this._pendingData.splice(index, 1);
  924. }
  925. };
  926. Scene.prototype.getWaitingItemsCount = function () {
  927. return this._pendingData.length;
  928. };
  929. /**
  930. * Registers a function to be executed when the scene is ready.
  931. * @param {Function} func - the function to be executed.
  932. */
  933. Scene.prototype.executeWhenReady = function (func) {
  934. var _this = this;
  935. this.onReadyObservable.add(func);
  936. if (this._executeWhenReadyTimeoutId !== -1) {
  937. return;
  938. }
  939. this._executeWhenReadyTimeoutId = setTimeout(function () {
  940. _this._checkIsReady();
  941. }, 150);
  942. };
  943. Scene.prototype._checkIsReady = function () {
  944. var _this = this;
  945. if (this.isReady()) {
  946. this.onReadyObservable.notifyObservers(this);
  947. this.onReadyObservable.clear();
  948. this._executeWhenReadyTimeoutId = -1;
  949. return;
  950. }
  951. this._executeWhenReadyTimeoutId = setTimeout(function () {
  952. _this._checkIsReady();
  953. }, 150);
  954. };
  955. // Animations
  956. /**
  957. * Will start the animation sequence of a given target
  958. * @param target - the target
  959. * @param {number} from - from which frame should animation start
  960. * @param {number} to - till which frame should animation run.
  961. * @param {boolean} [loop] - should the animation loop
  962. * @param {number} [speedRatio] - the speed in which to run the animation
  963. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  964. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  965. * @return {BABYLON.Animatable} the animatable object created for this animation
  966. * @see BABYLON.Animatable
  967. * @see http://doc.babylonjs.com/page.php?p=22081
  968. */
  969. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  970. if (speedRatio === void 0) { speedRatio = 1.0; }
  971. this.stopAnimation(target);
  972. if (!animatable) {
  973. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  974. }
  975. // Local animations
  976. if (target.animations) {
  977. animatable.appendAnimations(target, target.animations);
  978. }
  979. // Children animations
  980. if (target.getAnimatables) {
  981. var animatables = target.getAnimatables();
  982. for (var index = 0; index < animatables.length; index++) {
  983. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  984. }
  985. }
  986. animatable.reset();
  987. return animatable;
  988. };
  989. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  990. if (speedRatio === undefined) {
  991. speedRatio = 1.0;
  992. }
  993. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  994. return animatable;
  995. };
  996. Scene.prototype.getAnimatableByTarget = function (target) {
  997. for (var index = 0; index < this._activeAnimatables.length; index++) {
  998. if (this._activeAnimatables[index].target === target) {
  999. return this._activeAnimatables[index];
  1000. }
  1001. }
  1002. return null;
  1003. };
  1004. Object.defineProperty(Scene.prototype, "Animatables", {
  1005. get: function () {
  1006. return this._activeAnimatables;
  1007. },
  1008. enumerable: true,
  1009. configurable: true
  1010. });
  1011. /**
  1012. * Will stop the animation of the given target
  1013. * @param target - the target
  1014. * @see beginAnimation
  1015. */
  1016. Scene.prototype.stopAnimation = function (target) {
  1017. var animatable = this.getAnimatableByTarget(target);
  1018. if (animatable) {
  1019. animatable.stop();
  1020. }
  1021. };
  1022. Scene.prototype._animate = function () {
  1023. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  1024. return;
  1025. }
  1026. if (!this._animationStartDate) {
  1027. if (this._pendingData.length > 0) {
  1028. return;
  1029. }
  1030. this._animationStartDate = BABYLON.Tools.Now;
  1031. }
  1032. // Getting time
  1033. var now = BABYLON.Tools.Now;
  1034. var delay = now - this._animationStartDate;
  1035. for (var index = 0; index < this._activeAnimatables.length; index++) {
  1036. this._activeAnimatables[index]._animate(delay);
  1037. }
  1038. };
  1039. // Matrix
  1040. Scene.prototype.getViewMatrix = function () {
  1041. return this._viewMatrix;
  1042. };
  1043. Scene.prototype.getProjectionMatrix = function () {
  1044. return this._projectionMatrix;
  1045. };
  1046. Scene.prototype.getTransformMatrix = function () {
  1047. return this._transformMatrix;
  1048. };
  1049. Scene.prototype.setTransformMatrix = function (view, projection) {
  1050. this._viewMatrix = view;
  1051. this._projectionMatrix = projection;
  1052. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  1053. // Update frustum
  1054. if (!this._frustumPlanes) {
  1055. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  1056. }
  1057. else {
  1058. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  1059. }
  1060. };
  1061. // Methods
  1062. Scene.prototype.addMesh = function (newMesh) {
  1063. newMesh.uniqueId = this._uniqueIdCounter++;
  1064. var position = this.meshes.push(newMesh);
  1065. //notify the collision coordinator
  1066. this.collisionCoordinator.onMeshAdded(newMesh);
  1067. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  1068. };
  1069. Scene.prototype.removeMesh = function (toRemove) {
  1070. var index = this.meshes.indexOf(toRemove);
  1071. if (index !== -1) {
  1072. // Remove from the scene if mesh found
  1073. this.meshes.splice(index, 1);
  1074. }
  1075. //notify the collision coordinator
  1076. this.collisionCoordinator.onMeshRemoved(toRemove);
  1077. this.onMeshRemovedObservable.notifyObservers(toRemove);
  1078. return index;
  1079. };
  1080. Scene.prototype.removeSkeleton = function (toRemove) {
  1081. var index = this.skeletons.indexOf(toRemove);
  1082. if (index !== -1) {
  1083. // Remove from the scene if mesh found
  1084. this.skeletons.splice(index, 1);
  1085. }
  1086. return index;
  1087. };
  1088. Scene.prototype.removeLight = function (toRemove) {
  1089. var index = this.lights.indexOf(toRemove);
  1090. if (index !== -1) {
  1091. // Remove from the scene if mesh found
  1092. this.lights.splice(index, 1);
  1093. }
  1094. this.onLightRemovedObservable.notifyObservers(toRemove);
  1095. return index;
  1096. };
  1097. Scene.prototype.removeCamera = function (toRemove) {
  1098. var index = this.cameras.indexOf(toRemove);
  1099. if (index !== -1) {
  1100. // Remove from the scene if mesh found
  1101. this.cameras.splice(index, 1);
  1102. }
  1103. // Remove from activeCameras
  1104. var index2 = this.activeCameras.indexOf(toRemove);
  1105. if (index2 !== -1) {
  1106. // Remove from the scene if mesh found
  1107. this.activeCameras.splice(index2, 1);
  1108. }
  1109. // Reset the activeCamera
  1110. if (this.activeCamera === toRemove) {
  1111. if (this.cameras.length > 0) {
  1112. this.activeCamera = this.cameras[0];
  1113. }
  1114. else {
  1115. this.activeCamera = null;
  1116. }
  1117. }
  1118. this.onCameraRemovedObservable.notifyObservers(toRemove);
  1119. return index;
  1120. };
  1121. Scene.prototype.addLight = function (newLight) {
  1122. newLight.uniqueId = this._uniqueIdCounter++;
  1123. var position = this.lights.push(newLight);
  1124. this.onNewLightAddedObservable.notifyObservers(newLight);
  1125. };
  1126. Scene.prototype.addCamera = function (newCamera) {
  1127. newCamera.uniqueId = this._uniqueIdCounter++;
  1128. var position = this.cameras.push(newCamera);
  1129. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  1130. };
  1131. /**
  1132. * Switch active camera
  1133. * @param {Camera} newCamera - new active camera
  1134. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  1135. */
  1136. Scene.prototype.swithActiveCamera = function (newCamera, attachControl) {
  1137. if (attachControl === void 0) { attachControl = true; }
  1138. var canvas = this._engine.getRenderingCanvas();
  1139. this.activeCamera.detachControl(canvas);
  1140. this.activeCamera = newCamera;
  1141. if (attachControl) {
  1142. newCamera.attachControl(canvas);
  1143. }
  1144. };
  1145. /**
  1146. * sets the active camera of the scene using its ID
  1147. * @param {string} id - the camera's ID
  1148. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  1149. * @see activeCamera
  1150. */
  1151. Scene.prototype.setActiveCameraByID = function (id) {
  1152. var camera = this.getCameraByID(id);
  1153. if (camera) {
  1154. this.activeCamera = camera;
  1155. return camera;
  1156. }
  1157. return null;
  1158. };
  1159. /**
  1160. * sets the active camera of the scene using its name
  1161. * @param {string} name - the camera's name
  1162. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  1163. * @see activeCamera
  1164. */
  1165. Scene.prototype.setActiveCameraByName = function (name) {
  1166. var camera = this.getCameraByName(name);
  1167. if (camera) {
  1168. this.activeCamera = camera;
  1169. return camera;
  1170. }
  1171. return null;
  1172. };
  1173. /**
  1174. * get a material using its id
  1175. * @param {string} the material's ID
  1176. * @return {BABYLON.Material|null} the material or null if none found.
  1177. */
  1178. Scene.prototype.getMaterialByID = function (id) {
  1179. for (var index = 0; index < this.materials.length; index++) {
  1180. if (this.materials[index].id === id) {
  1181. return this.materials[index];
  1182. }
  1183. }
  1184. return null;
  1185. };
  1186. /**
  1187. * get a material using its name
  1188. * @param {string} the material's name
  1189. * @return {BABYLON.Material|null} the material or null if none found.
  1190. */
  1191. Scene.prototype.getMaterialByName = function (name) {
  1192. for (var index = 0; index < this.materials.length; index++) {
  1193. if (this.materials[index].name === name) {
  1194. return this.materials[index];
  1195. }
  1196. }
  1197. return null;
  1198. };
  1199. Scene.prototype.getLensFlareSystemByName = function (name) {
  1200. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  1201. if (this.lensFlareSystems[index].name === name) {
  1202. return this.lensFlareSystems[index];
  1203. }
  1204. }
  1205. return null;
  1206. };
  1207. Scene.prototype.getLensFlareSystemByID = function (id) {
  1208. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  1209. if (this.lensFlareSystems[index].id === id) {
  1210. return this.lensFlareSystems[index];
  1211. }
  1212. }
  1213. return null;
  1214. };
  1215. Scene.prototype.getCameraByID = function (id) {
  1216. for (var index = 0; index < this.cameras.length; index++) {
  1217. if (this.cameras[index].id === id) {
  1218. return this.cameras[index];
  1219. }
  1220. }
  1221. return null;
  1222. };
  1223. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  1224. for (var index = 0; index < this.cameras.length; index++) {
  1225. if (this.cameras[index].uniqueId === uniqueId) {
  1226. return this.cameras[index];
  1227. }
  1228. }
  1229. return null;
  1230. };
  1231. /**
  1232. * get a camera using its name
  1233. * @param {string} the camera's name
  1234. * @return {BABYLON.Camera|null} the camera or null if none found.
  1235. */
  1236. Scene.prototype.getCameraByName = function (name) {
  1237. for (var index = 0; index < this.cameras.length; index++) {
  1238. if (this.cameras[index].name === name) {
  1239. return this.cameras[index];
  1240. }
  1241. }
  1242. return null;
  1243. };
  1244. /**
  1245. * get a bone using its id
  1246. * @param {string} the bone's id
  1247. * @return {BABYLON.Bone|null} the bone or null if not found
  1248. */
  1249. Scene.prototype.getBoneByID = function (id) {
  1250. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  1251. var skeleton = this.skeletons[skeletonIndex];
  1252. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  1253. if (skeleton.bones[boneIndex].id === id) {
  1254. return skeleton.bones[boneIndex];
  1255. }
  1256. }
  1257. }
  1258. return null;
  1259. };
  1260. /**
  1261. * get a bone using its id
  1262. * @param {string} the bone's name
  1263. * @return {BABYLON.Bone|null} the bone or null if not found
  1264. */
  1265. Scene.prototype.getBoneByName = function (name) {
  1266. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  1267. var skeleton = this.skeletons[skeletonIndex];
  1268. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  1269. if (skeleton.bones[boneIndex].name === name) {
  1270. return skeleton.bones[boneIndex];
  1271. }
  1272. }
  1273. }
  1274. return null;
  1275. };
  1276. /**
  1277. * get a light node using its name
  1278. * @param {string} the light's name
  1279. * @return {BABYLON.Light|null} the light or null if none found.
  1280. */
  1281. Scene.prototype.getLightByName = function (name) {
  1282. for (var index = 0; index < this.lights.length; index++) {
  1283. if (this.lights[index].name === name) {
  1284. return this.lights[index];
  1285. }
  1286. }
  1287. return null;
  1288. };
  1289. /**
  1290. * get a light node using its ID
  1291. * @param {string} the light's id
  1292. * @return {BABYLON.Light|null} the light or null if none found.
  1293. */
  1294. Scene.prototype.getLightByID = function (id) {
  1295. for (var index = 0; index < this.lights.length; index++) {
  1296. if (this.lights[index].id === id) {
  1297. return this.lights[index];
  1298. }
  1299. }
  1300. return null;
  1301. };
  1302. /**
  1303. * get a light node using its scene-generated unique ID
  1304. * @param {number} the light's unique id
  1305. * @return {BABYLON.Light|null} the light or null if none found.
  1306. */
  1307. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  1308. for (var index = 0; index < this.lights.length; index++) {
  1309. if (this.lights[index].uniqueId === uniqueId) {
  1310. return this.lights[index];
  1311. }
  1312. }
  1313. return null;
  1314. };
  1315. /**
  1316. * get a particle system by id
  1317. * @param id {number} the particle system id
  1318. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  1319. */
  1320. Scene.prototype.getParticleSystemByID = function (id) {
  1321. for (var index = 0; index < this.particleSystems.length; index++) {
  1322. if (this.particleSystems[index].id === id) {
  1323. return this.particleSystems[index];
  1324. }
  1325. }
  1326. return null;
  1327. };
  1328. /**
  1329. * get a geometry using its ID
  1330. * @param {string} the geometry's id
  1331. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  1332. */
  1333. Scene.prototype.getGeometryByID = function (id) {
  1334. for (var index = 0; index < this._geometries.length; index++) {
  1335. if (this._geometries[index].id === id) {
  1336. return this._geometries[index];
  1337. }
  1338. }
  1339. return null;
  1340. };
  1341. /**
  1342. * add a new geometry to this scene.
  1343. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  1344. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  1345. * @return {boolean} was the geometry added or not
  1346. */
  1347. Scene.prototype.pushGeometry = function (geometry, force) {
  1348. if (!force && this.getGeometryByID(geometry.id)) {
  1349. return false;
  1350. }
  1351. this._geometries.push(geometry);
  1352. //notify the collision coordinator
  1353. this.collisionCoordinator.onGeometryAdded(geometry);
  1354. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  1355. return true;
  1356. };
  1357. /**
  1358. * Removes an existing geometry
  1359. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  1360. * @return {boolean} was the geometry removed or not
  1361. */
  1362. Scene.prototype.removeGeometry = function (geometry) {
  1363. var index = this._geometries.indexOf(geometry);
  1364. if (index > -1) {
  1365. this._geometries.splice(index, 1);
  1366. //notify the collision coordinator
  1367. this.collisionCoordinator.onGeometryDeleted(geometry);
  1368. this.onGeometryRemovedObservable.notifyObservers(geometry);
  1369. return true;
  1370. }
  1371. return false;
  1372. };
  1373. Scene.prototype.getGeometries = function () {
  1374. return this._geometries;
  1375. };
  1376. /**
  1377. * Get the first added mesh found of a given ID
  1378. * @param {string} id - the id to search for
  1379. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  1380. */
  1381. Scene.prototype.getMeshByID = function (id) {
  1382. for (var index = 0; index < this.meshes.length; index++) {
  1383. if (this.meshes[index].id === id) {
  1384. return this.meshes[index];
  1385. }
  1386. }
  1387. return null;
  1388. };
  1389. Scene.prototype.getMeshesByID = function (id) {
  1390. return this.meshes.filter(function (m) {
  1391. return m.id === id;
  1392. });
  1393. };
  1394. /**
  1395. * Get a mesh with its auto-generated unique id
  1396. * @param {number} uniqueId - the unique id to search for
  1397. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  1398. */
  1399. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  1400. for (var index = 0; index < this.meshes.length; index++) {
  1401. if (this.meshes[index].uniqueId === uniqueId) {
  1402. return this.meshes[index];
  1403. }
  1404. }
  1405. return null;
  1406. };
  1407. /**
  1408. * Get a the last added mesh found of a given ID
  1409. * @param {string} id - the id to search for
  1410. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  1411. */
  1412. Scene.prototype.getLastMeshByID = function (id) {
  1413. for (var index = this.meshes.length - 1; index >= 0; index--) {
  1414. if (this.meshes[index].id === id) {
  1415. return this.meshes[index];
  1416. }
  1417. }
  1418. return null;
  1419. };
  1420. /**
  1421. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  1422. * @param {string} id - the id to search for
  1423. * @return {BABYLON.Node|null} the node found or null if not found at all.
  1424. */
  1425. Scene.prototype.getLastEntryByID = function (id) {
  1426. var index;
  1427. for (index = this.meshes.length - 1; index >= 0; index--) {
  1428. if (this.meshes[index].id === id) {
  1429. return this.meshes[index];
  1430. }
  1431. }
  1432. for (index = this.cameras.length - 1; index >= 0; index--) {
  1433. if (this.cameras[index].id === id) {
  1434. return this.cameras[index];
  1435. }
  1436. }
  1437. for (index = this.lights.length - 1; index >= 0; index--) {
  1438. if (this.lights[index].id === id) {
  1439. return this.lights[index];
  1440. }
  1441. }
  1442. return null;
  1443. };
  1444. Scene.prototype.getNodeByID = function (id) {
  1445. var mesh = this.getMeshByID(id);
  1446. if (mesh) {
  1447. return mesh;
  1448. }
  1449. var light = this.getLightByID(id);
  1450. if (light) {
  1451. return light;
  1452. }
  1453. var camera = this.getCameraByID(id);
  1454. if (camera) {
  1455. return camera;
  1456. }
  1457. var bone = this.getBoneByID(id);
  1458. return bone;
  1459. };
  1460. Scene.prototype.getNodeByName = function (name) {
  1461. var mesh = this.getMeshByName(name);
  1462. if (mesh) {
  1463. return mesh;
  1464. }
  1465. var light = this.getLightByName(name);
  1466. if (light) {
  1467. return light;
  1468. }
  1469. var camera = this.getCameraByName(name);
  1470. if (camera) {
  1471. return camera;
  1472. }
  1473. var bone = this.getBoneByName(name);
  1474. return bone;
  1475. };
  1476. Scene.prototype.getMeshByName = function (name) {
  1477. for (var index = 0; index < this.meshes.length; index++) {
  1478. if (this.meshes[index].name === name) {
  1479. return this.meshes[index];
  1480. }
  1481. }
  1482. return null;
  1483. };
  1484. Scene.prototype.getSoundByName = function (name) {
  1485. var index;
  1486. if (BABYLON.AudioEngine) {
  1487. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  1488. if (this.mainSoundTrack.soundCollection[index].name === name) {
  1489. return this.mainSoundTrack.soundCollection[index];
  1490. }
  1491. }
  1492. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  1493. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  1494. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  1495. return this.soundTracks[sdIndex].soundCollection[index];
  1496. }
  1497. }
  1498. }
  1499. }
  1500. return null;
  1501. };
  1502. Scene.prototype.getLastSkeletonByID = function (id) {
  1503. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  1504. if (this.skeletons[index].id === id) {
  1505. return this.skeletons[index];
  1506. }
  1507. }
  1508. return null;
  1509. };
  1510. Scene.prototype.getSkeletonById = function (id) {
  1511. for (var index = 0; index < this.skeletons.length; index++) {
  1512. if (this.skeletons[index].id === id) {
  1513. return this.skeletons[index];
  1514. }
  1515. }
  1516. return null;
  1517. };
  1518. Scene.prototype.getSkeletonByName = function (name) {
  1519. for (var index = 0; index < this.skeletons.length; index++) {
  1520. if (this.skeletons[index].name === name) {
  1521. return this.skeletons[index];
  1522. }
  1523. }
  1524. return null;
  1525. };
  1526. Scene.prototype.isActiveMesh = function (mesh) {
  1527. return (this._activeMeshes.indexOf(mesh) !== -1);
  1528. };
  1529. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  1530. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  1531. var material = subMesh.getMaterial();
  1532. if (mesh.showSubMeshesBoundingBox) {
  1533. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  1534. }
  1535. if (material) {
  1536. // Render targets
  1537. if (material.getRenderTargetTextures) {
  1538. if (this._processedMaterials.indexOf(material) === -1) {
  1539. this._processedMaterials.push(material);
  1540. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  1541. }
  1542. }
  1543. // Dispatch
  1544. this._activeIndices.addCount(subMesh.indexCount, false);
  1545. this._renderingManager.dispatch(subMesh);
  1546. }
  1547. }
  1548. };
  1549. Scene.prototype._isInIntermediateRendering = function () {
  1550. return this._intermediateRendering;
  1551. };
  1552. Scene.prototype._evaluateActiveMeshes = function () {
  1553. this.activeCamera._activeMeshes.reset();
  1554. this._activeMeshes.reset();
  1555. this._renderingManager.reset();
  1556. this._processedMaterials.reset();
  1557. this._activeParticleSystems.reset();
  1558. this._activeSkeletons.reset();
  1559. this._softwareSkinnedMeshes.reset();
  1560. this._boundingBoxRenderer.reset();
  1561. this._edgesRenderers.reset();
  1562. // Meshes
  1563. var meshes;
  1564. var len;
  1565. if (this._selectionOctree) {
  1566. var selection = this._selectionOctree.select(this._frustumPlanes);
  1567. meshes = selection.data;
  1568. len = selection.length;
  1569. }
  1570. else {
  1571. len = this.meshes.length;
  1572. meshes = this.meshes;
  1573. }
  1574. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  1575. var mesh = meshes[meshIndex];
  1576. if (mesh.isBlocked) {
  1577. continue;
  1578. }
  1579. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  1580. if (!mesh.isReady() || !mesh.isEnabled()) {
  1581. continue;
  1582. }
  1583. mesh.computeWorldMatrix();
  1584. // Intersections
  1585. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  1586. this._meshesForIntersections.pushNoDuplicate(mesh);
  1587. }
  1588. // Switch to current LOD
  1589. var meshLOD = mesh.getLOD(this.activeCamera);
  1590. if (!meshLOD) {
  1591. continue;
  1592. }
  1593. mesh._preActivate();
  1594. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  1595. this._activeMeshes.push(mesh);
  1596. this.activeCamera._activeMeshes.push(mesh);
  1597. mesh._activate(this._renderId);
  1598. this._activeMesh(mesh, meshLOD);
  1599. }
  1600. }
  1601. // Particle systems
  1602. this._particlesDuration.beginMonitoring();
  1603. var beforeParticlesDate = BABYLON.Tools.Now;
  1604. if (this.particlesEnabled) {
  1605. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  1606. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  1607. var particleSystem = this.particleSystems[particleIndex];
  1608. if (!particleSystem.isStarted()) {
  1609. continue;
  1610. }
  1611. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  1612. this._activeParticleSystems.push(particleSystem);
  1613. particleSystem.animate();
  1614. }
  1615. }
  1616. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  1617. }
  1618. this._particlesDuration.endMonitoring(false);
  1619. };
  1620. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  1621. if (mesh.skeleton && this.skeletonsEnabled) {
  1622. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  1623. mesh.skeleton.prepare();
  1624. }
  1625. if (!mesh.computeBonesUsingShaders) {
  1626. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  1627. }
  1628. }
  1629. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  1630. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  1631. }
  1632. if (sourceMesh._edgesRenderer) {
  1633. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  1634. }
  1635. if (mesh && mesh.subMeshes) {
  1636. // Submeshes Octrees
  1637. var len;
  1638. var subMeshes;
  1639. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  1640. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  1641. len = intersections.length;
  1642. subMeshes = intersections.data;
  1643. }
  1644. else {
  1645. subMeshes = mesh.subMeshes;
  1646. len = subMeshes.length;
  1647. }
  1648. for (var subIndex = 0; subIndex < len; subIndex++) {
  1649. var subMesh = subMeshes[subIndex];
  1650. this._evaluateSubMesh(subMesh, mesh);
  1651. }
  1652. }
  1653. };
  1654. Scene.prototype.updateTransformMatrix = function (force) {
  1655. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  1656. };
  1657. Scene.prototype._renderForCamera = function (camera) {
  1658. var engine = this._engine;
  1659. var startTime = BABYLON.Tools.Now;
  1660. this.activeCamera = camera;
  1661. if (!this.activeCamera)
  1662. throw new Error("Active camera not set");
  1663. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  1664. // Viewport
  1665. engine.setViewport(this.activeCamera.viewport);
  1666. // Camera
  1667. this.resetCachedMaterial();
  1668. this._renderId++;
  1669. this.updateTransformMatrix();
  1670. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  1671. // Meshes
  1672. this._evaluateActiveMeshesDuration.beginMonitoring();
  1673. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  1674. this._evaluateActiveMeshes();
  1675. this._evaluateActiveMeshesDuration.endMonitoring(false);
  1676. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  1677. // Software skinning
  1678. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  1679. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  1680. mesh.applySkeleton(mesh.skeleton);
  1681. }
  1682. // Render targets
  1683. this._renderTargetsDuration.beginMonitoring();
  1684. var beforeRenderTargetDate = BABYLON.Tools.Now;
  1685. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  1686. this._intermediateRendering = true;
  1687. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  1688. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  1689. var renderTarget = this._renderTargets.data[renderIndex];
  1690. if (renderTarget._shouldRender()) {
  1691. this._renderId++;
  1692. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  1693. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  1694. }
  1695. }
  1696. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  1697. this._intermediateRendering = false;
  1698. this._renderId++;
  1699. engine.restoreDefaultFramebuffer(); // Restore back buffer
  1700. }
  1701. this._renderTargetsDuration.endMonitoring(false);
  1702. // Prepare Frame
  1703. this.postProcessManager._prepareFrame();
  1704. this._renderDuration.beginMonitoring();
  1705. // Backgrounds
  1706. var layerIndex;
  1707. var layer;
  1708. if (this.layers.length) {
  1709. engine.setDepthBuffer(false);
  1710. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  1711. layer = this.layers[layerIndex];
  1712. if (layer.isBackground) {
  1713. layer.render();
  1714. }
  1715. }
  1716. engine.setDepthBuffer(true);
  1717. }
  1718. // Render
  1719. BABYLON.Tools.StartPerformanceCounter("Main render");
  1720. this._renderingManager.render(null, null, true, true);
  1721. BABYLON.Tools.EndPerformanceCounter("Main render");
  1722. // Bounding boxes
  1723. this._boundingBoxRenderer.render();
  1724. // Edges
  1725. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  1726. this._edgesRenderers.data[edgesRendererIndex].render();
  1727. }
  1728. // Lens flares
  1729. if (this.lensFlaresEnabled) {
  1730. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  1731. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  1732. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  1733. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  1734. lensFlareSystem.render();
  1735. }
  1736. }
  1737. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  1738. }
  1739. // Foregrounds
  1740. if (this.layers.length) {
  1741. engine.setDepthBuffer(false);
  1742. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  1743. layer = this.layers[layerIndex];
  1744. if (!layer.isBackground) {
  1745. layer.render();
  1746. }
  1747. }
  1748. engine.setDepthBuffer(true);
  1749. }
  1750. this._renderDuration.endMonitoring(false);
  1751. // Finalize frame
  1752. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  1753. // Update camera
  1754. this.activeCamera._updateFromScene();
  1755. // Reset some special arrays
  1756. this._renderTargets.reset();
  1757. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  1758. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  1759. };
  1760. Scene.prototype._processSubCameras = function (camera) {
  1761. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  1762. this._renderForCamera(camera);
  1763. return;
  1764. }
  1765. // rig cameras
  1766. for (var index = 0; index < camera._rigCameras.length; index++) {
  1767. this._renderForCamera(camera._rigCameras[index]);
  1768. }
  1769. this.activeCamera = camera;
  1770. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  1771. // Update camera
  1772. this.activeCamera._updateFromScene();
  1773. };
  1774. Scene.prototype._checkIntersections = function () {
  1775. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  1776. var sourceMesh = this._meshesForIntersections.data[index];
  1777. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  1778. var action = sourceMesh.actionManager.actions[actionIndex];
  1779. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  1780. var parameters = action.getTriggerParameter();
  1781. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  1782. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  1783. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  1784. if (areIntersecting && currentIntersectionInProgress === -1) {
  1785. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  1786. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  1787. sourceMesh._intersectionsInProgress.push(otherMesh);
  1788. }
  1789. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  1790. sourceMesh._intersectionsInProgress.push(otherMesh);
  1791. }
  1792. }
  1793. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  1794. //They intersected, and now they don't.
  1795. //is this trigger an exit trigger? execute an event.
  1796. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  1797. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  1798. }
  1799. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  1800. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  1801. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  1802. }
  1803. }
  1804. }
  1805. }
  1806. }
  1807. };
  1808. Scene.prototype.render = function () {
  1809. this._lastFrameDuration.beginMonitoring();
  1810. this._particlesDuration.fetchNewFrame();
  1811. this._spritesDuration.fetchNewFrame();
  1812. this._activeParticles.fetchNewFrame();
  1813. this._renderDuration.fetchNewFrame();
  1814. this._renderTargetsDuration.fetchNewFrame();
  1815. this._evaluateActiveMeshesDuration.fetchNewFrame();
  1816. this._totalVertices.fetchNewFrame();
  1817. this._activeIndices.fetchNewFrame();
  1818. this._activeBones.fetchNewFrame();
  1819. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  1820. this._meshesForIntersections.reset();
  1821. this.resetCachedMaterial();
  1822. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  1823. // Actions
  1824. if (this.actionManager) {
  1825. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  1826. }
  1827. //Simplification Queue
  1828. if (this.simplificationQueue && !this.simplificationQueue.running) {
  1829. this.simplificationQueue.executeNext();
  1830. }
  1831. // Animations
  1832. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  1833. this._animationRatio = deltaTime * (60.0 / 1000.0);
  1834. this._animate();
  1835. // Physics
  1836. if (this._physicsEngine) {
  1837. BABYLON.Tools.StartPerformanceCounter("Physics");
  1838. this._physicsEngine._step(deltaTime / 1000.0);
  1839. BABYLON.Tools.EndPerformanceCounter("Physics");
  1840. }
  1841. // Before render
  1842. this.onBeforeRenderObservable.notifyObservers(this);
  1843. // Customs render targets
  1844. this._renderTargetsDuration.beginMonitoring();
  1845. var beforeRenderTargetDate = BABYLON.Tools.Now;
  1846. var engine = this.getEngine();
  1847. var currentActiveCamera = this.activeCamera;
  1848. if (this.renderTargetsEnabled) {
  1849. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  1850. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  1851. var renderTarget = this.customRenderTargets[customIndex];
  1852. if (renderTarget._shouldRender()) {
  1853. this._renderId++;
  1854. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  1855. if (!this.activeCamera)
  1856. throw new Error("Active camera not set");
  1857. // Viewport
  1858. engine.setViewport(this.activeCamera.viewport);
  1859. // Camera
  1860. this.updateTransformMatrix();
  1861. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  1862. }
  1863. }
  1864. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  1865. this._renderId++;
  1866. }
  1867. if (this.customRenderTargets.length > 0) {
  1868. engine.restoreDefaultFramebuffer();
  1869. }
  1870. this._renderTargetsDuration.endMonitoring();
  1871. this.activeCamera = currentActiveCamera;
  1872. // Procedural textures
  1873. if (this.proceduralTexturesEnabled) {
  1874. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  1875. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  1876. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  1877. if (proceduralTexture._shouldRender()) {
  1878. proceduralTexture.render();
  1879. }
  1880. }
  1881. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  1882. }
  1883. // Clear
  1884. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  1885. // Shadows
  1886. if (this.shadowsEnabled) {
  1887. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  1888. var light = this.lights[lightIndex];
  1889. var shadowGenerator = light.getShadowGenerator();
  1890. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  1891. this._renderTargets.push(shadowGenerator.getShadowMap());
  1892. }
  1893. }
  1894. }
  1895. // Depth renderer
  1896. if (this._depthRenderer) {
  1897. this._renderTargets.push(this._depthRenderer.getDepthMap());
  1898. }
  1899. // RenderPipeline
  1900. this.postProcessRenderPipelineManager.update();
  1901. // Multi-cameras?
  1902. if (this.activeCameras.length > 0) {
  1903. var currentRenderId = this._renderId;
  1904. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  1905. this._renderId = currentRenderId;
  1906. if (cameraIndex > 0) {
  1907. this._engine.clear(0, false, true);
  1908. }
  1909. this._processSubCameras(this.activeCameras[cameraIndex]);
  1910. }
  1911. }
  1912. else {
  1913. if (!this.activeCamera) {
  1914. throw new Error("No camera defined");
  1915. }
  1916. this._processSubCameras(this.activeCamera);
  1917. }
  1918. // Intersection checks
  1919. this._checkIntersections();
  1920. // Update the audio listener attached to the camera
  1921. if (BABYLON.AudioEngine) {
  1922. this._updateAudioParameters();
  1923. }
  1924. // After render
  1925. if (this.afterRender) {
  1926. this.afterRender();
  1927. }
  1928. this.onAfterRenderObservable.notifyObservers(this);
  1929. // Cleaning
  1930. for (var index = 0; index < this._toBeDisposed.length; index++) {
  1931. this._toBeDisposed.data[index].dispose();
  1932. this._toBeDisposed[index] = null;
  1933. }
  1934. this._toBeDisposed.reset();
  1935. if (this.dumpNextRenderTargets) {
  1936. this.dumpNextRenderTargets = false;
  1937. }
  1938. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  1939. this._lastFrameDuration.endMonitoring();
  1940. this._totalMeshesCounter.addCount(this.meshes.length, true);
  1941. this._totalLightsCounter.addCount(this.lights.length, true);
  1942. this._totalMaterialsCounter.addCount(this.materials.length, true);
  1943. this._totalTexturesCounter.addCount(this.textures.length, true);
  1944. this._activeBones.addCount(0, true);
  1945. this._activeIndices.addCount(0, true);
  1946. this._activeParticles.addCount(0, true);
  1947. };
  1948. Scene.prototype._updateAudioParameters = function () {
  1949. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  1950. return;
  1951. }
  1952. var listeningCamera;
  1953. var audioEngine = BABYLON.Engine.audioEngine;
  1954. if (this.activeCameras.length > 0) {
  1955. listeningCamera = this.activeCameras[0];
  1956. }
  1957. else {
  1958. listeningCamera = this.activeCamera;
  1959. }
  1960. if (listeningCamera && audioEngine.canUseWebAudio) {
  1961. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  1962. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  1963. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  1964. cameraDirection.normalize();
  1965. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  1966. var i;
  1967. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  1968. var sound = this.mainSoundTrack.soundCollection[i];
  1969. if (sound.useCustomAttenuation) {
  1970. sound.updateDistanceFromListener();
  1971. }
  1972. }
  1973. for (i = 0; i < this.soundTracks.length; i++) {
  1974. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  1975. sound = this.soundTracks[i].soundCollection[j];
  1976. if (sound.useCustomAttenuation) {
  1977. sound.updateDistanceFromListener();
  1978. }
  1979. }
  1980. }
  1981. }
  1982. };
  1983. Object.defineProperty(Scene.prototype, "audioEnabled", {
  1984. // Audio
  1985. get: function () {
  1986. return this._audioEnabled;
  1987. },
  1988. set: function (value) {
  1989. this._audioEnabled = value;
  1990. if (BABYLON.AudioEngine) {
  1991. if (this._audioEnabled) {
  1992. this._enableAudio();
  1993. }
  1994. else {
  1995. this._disableAudio();
  1996. }
  1997. }
  1998. },
  1999. enumerable: true,
  2000. configurable: true
  2001. });
  2002. Scene.prototype._disableAudio = function () {
  2003. var i;
  2004. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  2005. this.mainSoundTrack.soundCollection[i].pause();
  2006. }
  2007. for (i = 0; i < this.soundTracks.length; i++) {
  2008. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  2009. this.soundTracks[i].soundCollection[j].pause();
  2010. }
  2011. }
  2012. };
  2013. Scene.prototype._enableAudio = function () {
  2014. var i;
  2015. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  2016. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  2017. this.mainSoundTrack.soundCollection[i].play();
  2018. }
  2019. }
  2020. for (i = 0; i < this.soundTracks.length; i++) {
  2021. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  2022. if (this.soundTracks[i].soundCollection[j].isPaused) {
  2023. this.soundTracks[i].soundCollection[j].play();
  2024. }
  2025. }
  2026. }
  2027. };
  2028. Object.defineProperty(Scene.prototype, "headphone", {
  2029. get: function () {
  2030. return this._headphone;
  2031. },
  2032. set: function (value) {
  2033. this._headphone = value;
  2034. if (BABYLON.AudioEngine) {
  2035. if (this._headphone) {
  2036. this._switchAudioModeForHeadphones();
  2037. }
  2038. else {
  2039. this._switchAudioModeForNormalSpeakers();
  2040. }
  2041. }
  2042. },
  2043. enumerable: true,
  2044. configurable: true
  2045. });
  2046. Scene.prototype._switchAudioModeForHeadphones = function () {
  2047. this.mainSoundTrack.switchPanningModelToHRTF();
  2048. for (var i = 0; i < this.soundTracks.length; i++) {
  2049. this.soundTracks[i].switchPanningModelToHRTF();
  2050. }
  2051. };
  2052. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  2053. this.mainSoundTrack.switchPanningModelToEqualPower();
  2054. for (var i = 0; i < this.soundTracks.length; i++) {
  2055. this.soundTracks[i].switchPanningModelToEqualPower();
  2056. }
  2057. };
  2058. Scene.prototype.enableDepthRenderer = function () {
  2059. if (this._depthRenderer) {
  2060. return this._depthRenderer;
  2061. }
  2062. this._depthRenderer = new BABYLON.DepthRenderer(this);
  2063. return this._depthRenderer;
  2064. };
  2065. Scene.prototype.disableDepthRenderer = function () {
  2066. if (!this._depthRenderer) {
  2067. return;
  2068. }
  2069. this._depthRenderer.dispose();
  2070. this._depthRenderer = null;
  2071. };
  2072. Scene.prototype.freezeMaterials = function () {
  2073. for (var i = 0; i < this.materials.length; i++) {
  2074. this.materials[i].freeze();
  2075. }
  2076. };
  2077. Scene.prototype.unfreezeMaterials = function () {
  2078. for (var i = 0; i < this.materials.length; i++) {
  2079. this.materials[i].unfreeze();
  2080. }
  2081. };
  2082. Scene.prototype.dispose = function () {
  2083. this.beforeRender = null;
  2084. this.afterRender = null;
  2085. this.skeletons = [];
  2086. this._boundingBoxRenderer.dispose();
  2087. if (this._depthRenderer) {
  2088. this._depthRenderer.dispose();
  2089. }
  2090. // Debug layer
  2091. if (this._debugLayer) {
  2092. this._debugLayer.hide();
  2093. }
  2094. // Events
  2095. this.onDisposeObservable.notifyObservers(this);
  2096. this.onDisposeObservable.clear();
  2097. this.onBeforeRenderObservable.clear();
  2098. this.onAfterRenderObservable.clear();
  2099. this.detachControl();
  2100. // Release sounds & sounds tracks
  2101. if (BABYLON.AudioEngine) {
  2102. this.disposeSounds();
  2103. }
  2104. // Detach cameras
  2105. var canvas = this._engine.getRenderingCanvas();
  2106. var index;
  2107. for (index = 0; index < this.cameras.length; index++) {
  2108. this.cameras[index].detachControl(canvas);
  2109. }
  2110. // Release lights
  2111. while (this.lights.length) {
  2112. this.lights[0].dispose();
  2113. }
  2114. // Release meshes
  2115. while (this.meshes.length) {
  2116. this.meshes[0].dispose(true);
  2117. }
  2118. // Release cameras
  2119. while (this.cameras.length) {
  2120. this.cameras[0].dispose();
  2121. }
  2122. // Release materials
  2123. while (this.materials.length) {
  2124. this.materials[0].dispose();
  2125. }
  2126. // Release particles
  2127. while (this.particleSystems.length) {
  2128. this.particleSystems[0].dispose();
  2129. }
  2130. // Release sprites
  2131. while (this.spriteManagers.length) {
  2132. this.spriteManagers[0].dispose();
  2133. }
  2134. // Release layers
  2135. while (this.layers.length) {
  2136. this.layers[0].dispose();
  2137. }
  2138. // Release textures
  2139. while (this.textures.length) {
  2140. this.textures[0].dispose();
  2141. }
  2142. // Post-processes
  2143. this.postProcessManager.dispose();
  2144. // Physics
  2145. if (this._physicsEngine) {
  2146. this.disablePhysicsEngine();
  2147. }
  2148. // Remove from engine
  2149. index = this._engine.scenes.indexOf(this);
  2150. if (index > -1) {
  2151. this._engine.scenes.splice(index, 1);
  2152. }
  2153. this._engine.wipeCaches();
  2154. };
  2155. // Release sounds & sounds tracks
  2156. Scene.prototype.disposeSounds = function () {
  2157. this.mainSoundTrack.dispose();
  2158. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  2159. this.soundTracks[scIndex].dispose();
  2160. }
  2161. };
  2162. // Octrees
  2163. Scene.prototype.getWorldExtends = function () {
  2164. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2165. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2166. for (var index = 0; index < this.meshes.length; index++) {
  2167. var mesh = this.meshes[index];
  2168. mesh.computeWorldMatrix(true);
  2169. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  2170. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  2171. BABYLON.Tools.CheckExtends(minBox, min, max);
  2172. BABYLON.Tools.CheckExtends(maxBox, min, max);
  2173. }
  2174. return {
  2175. min: min,
  2176. max: max
  2177. };
  2178. };
  2179. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  2180. if (maxCapacity === void 0) { maxCapacity = 64; }
  2181. if (maxDepth === void 0) { maxDepth = 2; }
  2182. if (!this._selectionOctree) {
  2183. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  2184. }
  2185. var worldExtends = this.getWorldExtends();
  2186. // Update octree
  2187. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  2188. return this._selectionOctree;
  2189. };
  2190. // Picking
  2191. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  2192. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  2193. var engine = this._engine;
  2194. if (!camera) {
  2195. if (!this.activeCamera)
  2196. throw new Error("Active camera not set");
  2197. camera = this.activeCamera;
  2198. }
  2199. var cameraViewport = camera.viewport;
  2200. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  2201. // Moving coordinates to local viewport world
  2202. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  2203. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  2204. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  2205. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  2206. };
  2207. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  2208. var engine = this._engine;
  2209. if (!camera) {
  2210. if (!this.activeCamera)
  2211. throw new Error("Active camera not set");
  2212. camera = this.activeCamera;
  2213. }
  2214. var cameraViewport = camera.viewport;
  2215. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  2216. var identity = BABYLON.Matrix.Identity();
  2217. // Moving coordinates to local viewport world
  2218. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  2219. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  2220. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  2221. };
  2222. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  2223. var pickingInfo = null;
  2224. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  2225. var mesh = this.meshes[meshIndex];
  2226. if (predicate) {
  2227. if (!predicate(mesh)) {
  2228. continue;
  2229. }
  2230. }
  2231. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  2232. continue;
  2233. }
  2234. var world = mesh.getWorldMatrix();
  2235. var ray = rayFunction(world);
  2236. var result = mesh.intersects(ray, fastCheck);
  2237. if (!result || !result.hit)
  2238. continue;
  2239. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  2240. continue;
  2241. pickingInfo = result;
  2242. if (fastCheck) {
  2243. break;
  2244. }
  2245. }
  2246. return pickingInfo || new BABYLON.PickingInfo();
  2247. };
  2248. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  2249. var pickingInfo = null;
  2250. camera = camera || this.activeCamera;
  2251. if (this.spriteManagers.length > 0) {
  2252. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  2253. var spriteManager = this.spriteManagers[spriteIndex];
  2254. if (!spriteManager.isPickable) {
  2255. continue;
  2256. }
  2257. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  2258. if (!result || !result.hit)
  2259. continue;
  2260. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  2261. continue;
  2262. pickingInfo = result;
  2263. if (fastCheck) {
  2264. break;
  2265. }
  2266. }
  2267. }
  2268. return pickingInfo || new BABYLON.PickingInfo();
  2269. };
  2270. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  2271. var _this = this;
  2272. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  2273. /// <param name="x">X position on screen</param>
  2274. /// <param name="y">Y position on screen</param>
  2275. /// <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>
  2276. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  2277. /// <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>
  2278. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  2279. };
  2280. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  2281. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  2282. /// <param name="x">X position on screen</param>
  2283. /// <param name="y">Y position on screen</param>
  2284. /// <param name="predicate">Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true</param>
  2285. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  2286. /// <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>
  2287. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  2288. };
  2289. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  2290. var _this = this;
  2291. return this._internalPick(function (world) {
  2292. if (!_this._pickWithRayInverseMatrix) {
  2293. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  2294. }
  2295. world.invertToRef(_this._pickWithRayInverseMatrix);
  2296. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  2297. }, predicate, fastCheck);
  2298. };
  2299. Scene.prototype.setPointerOverMesh = function (mesh) {
  2300. if (this._pointerOverMesh === mesh) {
  2301. return;
  2302. }
  2303. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  2304. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  2305. }
  2306. this._pointerOverMesh = mesh;
  2307. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  2308. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  2309. }
  2310. };
  2311. Scene.prototype.getPointerOverMesh = function () {
  2312. return this._pointerOverMesh;
  2313. };
  2314. Scene.prototype.setPointerOverSprite = function (sprite) {
  2315. if (this._pointerOverSprite === sprite) {
  2316. return;
  2317. }
  2318. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  2319. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  2320. }
  2321. this._pointerOverSprite = sprite;
  2322. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  2323. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  2324. }
  2325. };
  2326. Scene.prototype.getPointerOverSprite = function () {
  2327. return this._pointerOverSprite;
  2328. };
  2329. // Physics
  2330. Scene.prototype.getPhysicsEngine = function () {
  2331. return this._physicsEngine;
  2332. };
  2333. /**
  2334. * Enables physics to the current scene
  2335. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  2336. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  2337. * @return {boolean} was the physics engine initialized
  2338. */
  2339. Scene.prototype.enablePhysics = function (gravity, plugin) {
  2340. if (this._physicsEngine) {
  2341. return true;
  2342. }
  2343. try {
  2344. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  2345. return true;
  2346. }
  2347. catch (e) {
  2348. BABYLON.Tools.Error(e.message);
  2349. return false;
  2350. }
  2351. };
  2352. Scene.prototype.disablePhysicsEngine = function () {
  2353. if (!this._physicsEngine) {
  2354. return;
  2355. }
  2356. this._physicsEngine.dispose();
  2357. this._physicsEngine = undefined;
  2358. };
  2359. Scene.prototype.isPhysicsEnabled = function () {
  2360. return this._physicsEngine !== undefined;
  2361. };
  2362. /**
  2363. *
  2364. * Sets the gravity of the physics engine (and NOT of the scene)
  2365. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  2366. */
  2367. Scene.prototype.setGravity = function (gravity) {
  2368. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  2369. if (!this._physicsEngine) {
  2370. return;
  2371. }
  2372. this._physicsEngine.setGravity(gravity);
  2373. };
  2374. /**
  2375. * Legacy support, using the new API
  2376. * @Deprecated
  2377. */
  2378. Scene.prototype.createCompoundImpostor = function (parts, options) {
  2379. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  2380. if (parts.parts) {
  2381. options = parts;
  2382. parts = parts.parts;
  2383. }
  2384. var mainMesh = parts[0].mesh;
  2385. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  2386. for (var index = 1; index < parts.length; index++) {
  2387. var mesh = parts[index].mesh;
  2388. if (mesh.parent !== mainMesh) {
  2389. mesh.position = mesh.position.subtract(mainMesh.position);
  2390. mesh.parent = mainMesh;
  2391. }
  2392. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  2393. }
  2394. mainMesh.physicsImpostor.forceUpdate();
  2395. };
  2396. Scene.prototype.deleteCompoundImpostor = function (compound) {
  2397. var mesh = compound.parts[0].mesh;
  2398. mesh.physicsImpostor.dispose();
  2399. mesh.physicsImpostor = null;
  2400. };
  2401. // Misc.
  2402. Scene.prototype.createDefaultCameraOrLight = function () {
  2403. // Light
  2404. if (this.lights.length === 0) {
  2405. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  2406. }
  2407. // Camera
  2408. if (!this.activeCamera) {
  2409. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  2410. // Compute position
  2411. var worldExtends = this.getWorldExtends();
  2412. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  2413. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  2414. camera.setTarget(worldCenter);
  2415. this.activeCamera = camera;
  2416. }
  2417. };
  2418. // Tags
  2419. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  2420. if (tagsQuery === undefined) {
  2421. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  2422. return list;
  2423. }
  2424. var listByTags = [];
  2425. forEach = forEach || (function (item) { return; });
  2426. for (var i in list) {
  2427. var item = list[i];
  2428. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  2429. listByTags.push(item);
  2430. forEach(item);
  2431. }
  2432. }
  2433. return listByTags;
  2434. };
  2435. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  2436. return this._getByTags(this.meshes, tagsQuery, forEach);
  2437. };
  2438. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  2439. return this._getByTags(this.cameras, tagsQuery, forEach);
  2440. };
  2441. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  2442. return this._getByTags(this.lights, tagsQuery, forEach);
  2443. };
  2444. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  2445. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  2446. };
  2447. // Statics
  2448. Scene._FOGMODE_NONE = 0;
  2449. Scene._FOGMODE_EXP = 1;
  2450. Scene._FOGMODE_EXP2 = 2;
  2451. Scene._FOGMODE_LINEAR = 3;
  2452. Scene.MinDeltaTime = 1.0;
  2453. Scene.MaxDeltaTime = 1000.0;
  2454. return Scene;
  2455. }());
  2456. BABYLON.Scene = Scene;
  2457. })(BABYLON || (BABYLON = {}));